(()=>{"use strict";var __webpack_modules__={3233(e,t,a){a.d(t,{A:()=>r});const{__:n,sprintf:l}=wp.i18n,o={};o.COMMON={GENERAL:n("General","ai-engine"),MODULES:n("Modules","ai-engine"),CLIENT_MODULES:n("Client Modules","ai-engine"),BACKEND_MODULES:n("Admin Modules","ai-engine"),SERVER_MODULES:n("Server Modules","ai-engine"),ADVISOR:n("Advisor","ai-engine"),SETTINGS:n("Settings","ai-engine"),CHATBOT:n("Chatbot","ai-engine"),CHATBOTS:n("Chatbots","ai-engine"),CHATBOT_HELP:n("Customizable chatbots your visitors can talk to. Popup, inline, or fullscreen.","ai-engine"),INSIGHTS:n("Insights","ai-engine"),STYLE:n("Style","ai-engine"),ENABLE:n("Enable","ai-engine"),NAME:n("Name","ai-engine"),SUBMIT:n("Submit","ai-engine"),MODEL:n("Model","ai-engine"),AI_MODEL:n("AI Model","ai-engine"),TEMPERATURE:n("Temperature","ai-engine"),MAX_TOKENS:n("Max Tokens","ai-engine"),CONTEXT_MAX_LENGTH:n("Context Max Length","ai-engine"),STOP_SEQUENCE:n("Stop Sequence","ai-engine"),MODE:n("Mode","ai-engine"),CONTEXT:n("Knowledge & Context","ai-engine"),IMAGES_NUMBER:n("Number of Images","ai-engine"),AVATAR:n("Avatar","ai-engine"),AI_NAME:n("AI Name","ai-engine"),GUEST_NAME:n("Guest Name","ai-engine"),USER_NAME:n("User Name","ai-engine"),PLACEHOLDER:n("Placeholder","ai-engine"),START_SENTENCE:n("Start Sentence","ai-engine"),SEND:n("Send","ai-engine"),CLEAR:n("Clear","ai-engine"),CLOSE:n("Close","ai-engine"),VIEW:n("View","ai-engine"),EDIT:n("Edit","ai-engine"),SYSTEM_NAME:n("System Name","ai-engine"),ID:n("ID","ai-engine"),SCOPE:n("Scope","ai-engine"),POPUP:n("Popup","ai-engine"),POSITION:n("Position","ai-engine"),CENTER:n("Center","ai-engine"),OPEN_DELAY:n("Open Delay","ai-engine"),ENV_MOVES_BELOW_USAGE:n("Once everything is set up, this panel moves below Usage automatically.","ai-engine"),WINDOW_ANIMATION:n("Window Animation","ai-engine"),ZOOM:n("Zoom","ai-engine"),SLIDE:n("Slide","ai-engine"),FADE:n("Fade","ai-engine"),VOICE:n("Voice","ai-engine"),TALK_MODE:n("Talk Mode","ai-engine"),HANDS_FREE:n("Hands-Free","ai-engine"),HOLD_TO_TALK:n("Hold to Talk","ai-engine"),ICON:n("Icon","ai-engine"),ICON_TEXT:n("Icon Text","ai-engine"),ICON_TEXT_DELAY:n("Icon Text Delay","ai-engine"),ICON_SIZE:n("Icon Size","ai-engine"),FULL_SCREEN:n("Full Screen","ai-engine"),CASUALLY_FINE_TUNED:n("Casually Fine-Tuned","ai-engine"),CONTENT_AWARE:n("Content Aware","ai-engine"),TITLE:n("Title","ai-engine"),TOPIC:n("Topic","ai-engine"),TOPICS:n("Topics","ai-engine"),SPACING:n("Spacing","ai-engine"),BORDER_RADIUS:n("Border Radius","ai-engine"),FONT_SIZE:n("Font Size","ai-engine"),FONT_COLOR:n("Font Color","ai-engine"),BORDER_COLOR:n("Border Color","ai-engine"),BACK_PRIMARY_COLOR:n("Back Primary Color","ai-engine"),BACK_SECONDARY_COLOR:n("Back 2nd Color","ai-engine"),HEADER_COLOR:n("Header Color","ai-engine"),HEADER_BACKGROUND_COLOR:n("Header Back Color","ai-engine"),HEADER_SUBTITLE:n("Header Subtitle","ai-engine"),BUBBLE_COLOR:n("Bubble Color","ai-engine"),BACK_USER_COLOR:n("Back User Color","ai-engine"),BACK_AI_COLOR:n("Back AI Color","ai-engine"),BACK_AI_SECONDARY_COLOR:n("Back AI 2nd Color","ai-engine"),AVATAR_MESSAGE_BACKGROUND_COLOR:n("Message Back","ai-engine"),AVATAR_MESSAGE_FONT_COLOR:n("Message Color","ai-engine"),ACCENT_COLOR:n("Accent Color","ai-engine"),POPUP_ICON:n("Popup Icon","ai-engine"),CUSTOM_ICON:n("Custom Icon (URL or Emoticon)","ai-engine"),FEATURES:n("Features","ai-engine"),TIMEFRAME:n("Timeframe","ai-engine"),ABSOLUTE:n("Absolute","ai-engine"),NONE:n("None","ai-engine"),EDITORS_ADMINS:n("Editors & Admins","ai-engine"),ADMINS_ONLY:n("Admins Only","ai-engine"),MAINTENANCE:n("Maintenance","ai-engine"),CREDITS:n("Credits","ai-engine"),TYPE:n("Type","ai-engine"),LIMITS:n("Limits","ai-engine"),USERS:n("Users","ai-engine"),USER:n("User","ai-engine"),GUESTS:n("Guests","ai-engine"),GUEST:n("Guest","ai-engine"),OPENAI:n("Open AI","ai-engine"),LICENSE_TAB:n("License","ai-engine"),FINETUNES:n("Finetunes","ai-engine"),MODELS:n("Models","ai-engine"),FILES:n("Files","ai-engine"),ASSISTANT:n("Assistant","ai-engine"),EDITOR_ASSISTANT:n("AI Assistant","ai-engine"),EDITOR_ASSISTANT_HELP:n("An AI sidebar in the block editor to draft, rewrite, and rearrange your post. Pro can edit the post directly.","ai-engine"),ASSISTANTS:n("Assistants","ai-engine"),UTILITIES:n("Utilities","ai-engine"),AI_COPILOT:n("AI Copilot","ai-engine"),AI_COPILOT_HELP:n("Brings AI straight into the post editor: a copilot triggered by pressing space for inline completions, Magic Wand buttons in the toolbar and sidebar to rewrite, translate, correct, or enrich any selection, plus suggested titles and excerpts.","ai-engine"),POSTS_SUGGESTIONS:n("AI Copilot, AI Suggestions, Magic Wands","ai-engine"),POSTS_SUGGESTIONS_HELP:n("Tools to brainstorm/write faster and better.","ai-engine"),GENERATORS:n("Generators","ai-engine"),CONTENT_GENERATOR:n("Content Generator","ai-engine"),CONTENT_GENERATOR_HELP:n("Generate long-form content (posts, drafts, product copy) from a prompt.","ai-engine"),IMAGES_GENERATOR:n("Images Generator","ai-engine"),IMAGES_GENERATOR_HELP:n("Generate images from text prompts using GPT Image and compatible models.","ai-engine"),IMAGES_GENERATOR_INTRO:n("Create stunning visuals with AI-powered image generation. Use detailed prompts, customize styles and resolutions, and generate multiple variations. Perfect for creative projects, marketing materials, and visual content.","ai-engine"),PLAYGROUND:n("Playground","ai-engine"),PLAYGROUND_HELP:n("Sandbox to test prompts, compare models, and tune parameters.","ai-engine"),FORMS:n("Forms","ai-engine"),FORMS_HELP:n("Smart forms with conditional logic, AI-generated answers, and text or file inputs.","ai-engine"),SEARCH:n("Search","ai-engine"),SEARCH_HELP:n("Replace WordPress search with smarter keyword matching or true semantic search via embeddings.","ai-engine"),INSIGHTS_HELP:n("Query logs, usage charts by user and role, and per-role limits to keep costs in check.","ai-engine"),CLIENT_DEBUG:n("Client Debug","ai-engine"),CLIENT_DEBUG_HELP:n("Debugging information for Chatbots and Forms will be displayed in the Browser Console.","ai-engine"),SERVER_DEBUG:n("Server Debug","ai-engine"),SERVER_DEBUG_HELP:n("API calls and server events will be logged and displayed in the Logs Console.","ai-engine"),MCP_DEBUG:n("MCP Debug","ai-engine"),MCP_DEBUG_HELP:n("Debugging information from MCP will be written directly to the PHP error logs using error_log().","ai-engine"),QUERIES_DEBUG:n("Queries Debug","ai-engine"),QUERIES_DEBUG_HELP:n("Full queries and responses will be written directly to the PHP error logs using error_log().","ai-engine"),DEV_MODE:n("Dev Mode","ai-engine"),DEV_MODE_HELP:n("Run tasks frequently for debugging.","ai-engine"),CLEAR_LOGS:n("Clear Logs","ai-engine"),REFRESH_LOGS:n("Refresh Logs","ai-engine"),API_KEY:n("API Key","ai-engine"),USAGE_HELP:n("Estimates only. Check your AI service for actual costs. Insights module provides better accuracy.","ai-engine"),RESET_USAGE_SURE:n("Are you sure you want to reset the usage data?","ai-engine"),USAGE_PRO_HELP:n("If you would like to have better control on the amounts, add conditions or set limits to the usage of the AI, consider %s.","ai-engine"),USAGE_PRO_HELP_URL:"https://meowapps.com/ai-engine/",USAGE_PRO_HELP_LINK_TEXT:n("AI Engine Pro ↗","ai-engine"),LANGUAGE:n("Language","ai-engine"),HIDE:n("Hide","ai-engine"),SHOW:n("Show","ai-engine"),CONTENT:n("Content","ai-engine"),IMAGES:n("Images","ai-engine"),IMAGES_AND_FILES:n("Images & Files","ai-engine"),EXCERPT:n("Excerpt","ai-engine"),GENERATE:n("Generate","ai-engine"),MODEL_PARAMS:n("Model Params","ai-engine"),CONTEXT_PARAMS:n("Context Params","ai-engine"),PROMPT:n("Prompt","ai-engine"),PROMPTS:n("Prompts","ai-engine"),LABEL:n("Label","ai-engine"),SYSTEM:n("System","ai-engine"),SHORTCODE:n("Shortcode","ai-engine"),SHORTCODES:n("Shortcodes","ai-engine"),RESOLVE:n("Resolve","ai-engine"),MAX_MESSAGES:n("Max Messages","ai-engine"),INPUT_MAX_LENGTH:n("Input Max Length","ai-engine"),COMPLIANCE_TEXT:n("Compliance Text","ai-engine"),MODERATION:n("Moderation","ai-engine"),MODERATION_HELP:n("Auto-flag offensive or unsafe messages in chatbots using OpenAI's moderation endpoint.","ai-engine"),FORMATTING:n("Formatting","ai-engine"),FORMATTING_HELP:n("Format the reply from AI into HTML. This is already done automatically if Markdown is detected in the reply.","ai-engine"),LOGS:n("Logs","ai-engine"),QUERY:n("Query","ai-engine"),REPLY:n("Reply","ai-engine"),CODE:n("Code","ai-engine"),EMBEDDINGS:n("Embeddings","ai-engine"),QUERY_LOGS:n("Query Logs","ai-engine"),KNOWLEDGE:n("Knowledge","ai-engine"),KNOWLEDGE_HELP:n("Turn posts, pages, and PDFs into embeddings so chatbots can answer from your own content. Pinecone, Qdrant, Chroma, and OpenAI Vector Store supported.","ai-engine"),REMOTE_ACCESS:n("Remote Access","ai-engine"),OTHERS:n("Others","ai-engine"),PINECONE_APIKEY_HELP:n("You can get your API Keys in your %s.","ai-engine"),PINECONE_APIKEY_URL:"https://app.pinecone.io/organizations/keys",PINECONE_APIKEY_LINK_TEXT:n("Pinecone Account ↗","ai-engine"),QDRANT_APIKEY_HELP:n("You can get your API Keys in your %s.","ai-engine"),QDRANT_APIKEY_URL:"https://cloud.qdrant.io/accounts/",QDRANT_APIKEY_LINK_TEXT:n("Qdrant Account ↗","ai-engine"),SERVER:n("Server","ai-engine"),PINECONE_SERVER_HELP:n("The URL of your host (check your Indexes).","ai-engine"),PINECONE_NAMESPACE_HELP:n("The namespace is used to separate the data from other data. This allows you to use the same server/index on more than one website. This is optional.","ai-engine"),QDRANT_SERVER_HELP:n("The URL of your cluster (known as Cluster URL).","ai-engine"),QDRANT_COLLECTION_HELP:n("The collection keeps data apart so you can use one cluster for many websites. If there's no collection, Qdrant makes one with 1536 dimensions and uses cosine similarity.","ai-engine"),COST:n("Cost","ai-engine"),USAGE:n("Usage","ai-engine"),USAGE_ESTIMATES_NOTE:n("Costs and tokens are estimates. For accurate data and detailed analytics, visit the Insights tab.","ai-engine"),ACTIVITY:n("Activity","ai-engine"),TRANSCRIPTION:n("Transcription","ai-engine"),TRANSCRIPTION_HELP:n("Convert audio to text with Whisper. Adds a dedicated Transcribe tab.","ai-engine"),AUDIO_TRANSCRIPTION:n("Audio-to-Text","ai-engine"),IMAGE_TRANSCRIPTION:n("Image-to-Text","ai-engine"),AUDIO_TO_TEXT:n("Audio ➡ Text","ai-engine"),IMAGE_TO_TEXT:n("Image ➡ Text","ai-engine"),EMBEDDINGS_ENV:n("Environment","ai-engine"),EMBEDDINGS_INDEX:n("Index","ai-engine"),NAMESPACE:n("Namespace","ai-engine"),NAMESPACES:n("Namespaces","ai-engine"),NAMESPACE_HELP:n("The namespace is used to separate the data from other data. This allows you to use the same index on more than one website.","ai-engine"),NAMESPACES_HELP:n("Enter the namespaces you would like to use on this site, separated by commas.","ai-engine"),ERROR:n("Error","ai-engine"),RETRY:n("Retry","ai-engine"),AUTO_RETRY:n("Auto Retry","ai-engine"),SKIP:n("Skip","ai-engine"),AUTO_SKIP:n("Auto Skip","ai-engine"),STOP:n("Stop","ai-engine"),AUTO_RETRY_DESCRIPTION:n("Auto Retry retries actions up to 10 times with increasing delay to avoid timeouts.","ai-engine"),WIDTH:n("Width","ai-engine"),MAX_HEIGHT:n("Max Height","ai-engine"),APPEARANCE:n("Appearance","ai-engine"),THRESHOLDS:n("Thresholds","ai-engine"),DASHBOARD:n("Dashboard","ai-engine"),ADVANCED:n("Advanced","ai-engine"),DISCUSSIONS:n("Discussions","ai-engine"),DISCUSSION_TITLES:n("Discussion Titles","ai-engine"),SUMMARIZE:n("Summarize","ai-engine"),ROWS:n("Rows","ai-engine"),POST_TYPE:n("Post Type","ai-engine"),GENERATE_CONTENT:n("Generate Content","ai-engine"),GENERATE_IMAGES:n("Generate Images","ai-engine"),REST_API:n("Public API","ai-engine"),ADMIN_BAR:n("Admin Bar","ai-engine"),REFRESH:n("Refresh","ai-engine"),DELETE:n("Delete","ai-engine"),DELETE_ALL:n("Delete All","ai-engine"),DELETE_SELECTED:n("Delete Selected","ai-engine"),OPENAI_ORGANIZATION_ID:n("Organization ID","ai-engine"),OPENAI_AZURE_API_KEY:n("API Key","ai-engine"),OPENAI_AZURE_DEPLOYMENT_NAME:n("Deployment Name","ai-engine"),OPENAI_AZURE_DEPLOYMENTS:n("Deployments","ai-engine"),ENDPOINT:n("Endpoint","ai-engine"),HUGGINGFACE_MODELS:n("Models","ai-engine"),HUGGINGFACE_MODEL_NAME:n("Name","ai-engine"),HUGGINGFACE_MODEL_URL:n("API URL","ai-engine"),THEME:n("Theme","ai-engine"),THEMES:n("Themes","ai-engine"),BANNED_WORDS:n("Banned Words","ai-engine"),WORD_BOUNDARIES:n("Word Boundaries","ai-engine"),IGNORE:n("Ignore","ai-engine"),BANNED_IPS:n("Banned IPs","ai-engine"),SECURITY:n("Security","ai-engine"),POST_TYPES:n("Post Types","ai-engine"),COPY_BUTTON:n("Copy Button","ai-engine"),PDF_BUTTON:n("PDF Button","ai-engine"),PDF_BUTTON_HELP:n("Show a print-to-PDF icon on the last AI message, so users can save the whole conversation.","ai-engine"),MORE_OPTIONS:n("More options...","ai-engine"),MORE_APPEARANCE_OPTIONS:n("More Appearance Options","ai-engine"),DONE:n("Done","ai-engine"),AI_AVATAR:n("AI Avatar","ai-engine"),GUEST_AVATAR:n("Guest Avatar","ai-engine"),SITE_WIDE_CHATBOT:n("Site-Wide Chatbot","ai-engine"),QUERIES_DATA:n("Queries Data","ai-engine"),QUERIES_FORMS_DATA:n("Queries Form Data","ai-engine"),WEBSPEECH_API:n("Web Speech API","ai-engine"),GDPR_CONSENT:n("GDPR Consent","ai-engine"),GDPR_TEXT:n("GDPR Text","ai-engine"),GDPR_BUTTON:n("GDPR Button","ai-engine"),FIX:n("Fix","ai-engine"),SPEECH_RECOGNITION:n("Speech Recognition","ai-engine"),SPEECH_SYNTHESIS:n("Speech Synthesis","ai-engine"),QUERIES:n("Queries","ai-engine"),LOCAL_MEMORY:n("Local Memory","ai-engine"),ACTIONS:n("Actions","ai-engine"),RESET:n("Reset","ai-engine"),INCIDENTS_OPENAI:n("Incidents (OpenAI)","ai-engine"),PREVIEW:n("Preview","ai-engine"),LEGACY_FORMS:n("Legacy Forms","ai-engine"),LEGACY_FEATURES:n("Legacy Features","ai-engine"),DUPLICATE:n("Duplicate","ai-engine"),CHATBOT_EDITOR:n("Chatbot Editor","ai-engine"),THEME_EDITOR:n("Theme Editor","ai-engine"),STREAMING:n("Streaming","ai-engine"),SYNTAX_HIGHLIGHT:n("Syntax Highlight","ai-engine"),EVENT_LOGS:n("Event Logs","ai-engine"),PRIVACY_FIRST:n("Privacy First","ai-engine"),DATA_NOT_AVAILABLE:n("Data not available.","ai-engine"),DATA_NOT_AVAILABLE_HINT:n('Enable "Queries Data" in Settings > Others > Insights to record the content of queries and replies.',"ai-engine"),USAGE_EMPTY_SUBTITLE:n("Usage will appear here once AI queries start running.","ai-engine"),ENVIRONMENTS:n("Environments","ai-engine"),ENVIRONMENT_EMPTY_TITLE:n("No AI environment set up yet","ai-engine"),ENVIRONMENT_EMPTY_SUBTITLE:n("Add OpenAI, Anthropic, Google, or any other provider to start.","ai-engine"),SET_UP_ENVIRONMENT:n("Set up an environment","ai-engine"),NO_API_KEY:n("No API key","ai-engine"),TYPE_UNAVAILABLE:n("Type unavailable","ai-engine"),CONFIGURE:n("Configure","ai-engine"),EXPORT:n("Export","ai-engine"),IMPORT:n("Import","ai-engine"),MODIFY_EMBEDDING:n("Modify Embedding","ai-engine"),ADD_EMBEDDING:n("Add Embedding","ai-engine"),DEV_TOOLS:n("Dev Tools","ai-engine"),SINGLE_GENERATE:n("Single Generate","ai-engine"),PUBLIC_API:n("Public API","ai-engine"),USER_INTERFACE:n("User Interface","ai-engine"),INTRO_MESSAGE:n("Intro Message","ai-engine"),ADDONS:n("Add-ons","ai-engine"),AI_ENVIRONMENT_DEFAULTS:n("Default Environments for AI","ai-engine"),ENVIRONMENTS_FOR_AI:n("Environments for AI","ai-engine"),ENVIRONMENT_ID:n("Environment ID","ai-engine"),EMBEDDINGS_ENVIRONMENT_DEFAULT:n("Default Embeddings Environment","ai-engine"),ENVIRONMENT:n("Environment","ai-engine"),PLUGIN_DATA:n("Plugin Data","ai-engine"),PLUGIN_DATA_DESCRIPTION:n("The database and all the options of the plugin will be removed on uninstall.","ai-engine"),RESET_LIMITS:n("Reset Limits","ai-engine"),VISION:n("Vision","ai-engine"),FILE_SEARCH:n("File Search","ai-engine"),PROMPT_TO_JSON:n("Prompt ➡ JSON","ai-engine"),RESOLUTION:n("Resolution","ai-engine"),QUALITY:n("Quality","ai-engine"),DEFAULT:n("Default","ai-engine"),DEFAULTS:n("Defaults","ai-engine"),DEFAULT_FAST:n("Fast","ai-engine"),REFRESH_MODELS:n("Refresh Models","ai-engine"),AUDIO:n("Audio","ai-engine"),JSON:n("JSON","ai-engine"),AI_ENVIRONMENT:n("AI Environment","ai-engine"),OVERRIDE_DEFAULTS:n("Override Defaults","ai-engine"),REGION:n("Region","ai-engine"),PROJECT_ID:n("Project ID","ai-engine"),BEARER_TOKEN:n("Bearer Token","ai-engine"),DIMENSIONS:n("Dimensions","ai-engine"),EMBEDDINGS_MODEL:n("Embeddings Model","ai-engine"),MIN_SCORE:n("Min Score","ai-engine"),MAX_SELECT:n("Max Results","ai-engine"),QDRANT_COLLECTION:n("Collection","ai-engine"),INSTRUCTIONS:n("Instructions","ai-engine"),FUNCTIONS:n("Functions","ai-engine"),TOOLS:n("Tools & Capabilities","ai-engine"),WEB_SEARCH:n("Web Search","ai-engine"),IMAGE_GENERATION:n("Image Generation","ai-engine"),CODE_INTERPRETER:n("Code Interpreter","ai-engine"),ALLOWED_MIME_TYPES:n("Allowed Mime Types","ai-engine"),SELECT_MIME_TYPES:n("Select","ai-engine"),MIME_TYPE_SELECTOR:n("MIME Type Selector","ai-engine"),AUTO_SELECT:n("Auto-Select","ai-engine"),CUSTOM_MIME_TYPES:n("Custom MIME Types","ai-engine"),HISTORY_STRATEGY:n("History Strategy","ai-engine"),AUTOMATIC:n("Automatic","ai-engine"),FULL_HISTORY:n("Full History","ai-engine"),INCREMENTAL:n("Incremental","ai-engine"),BUBBLE:n("Bubble","ai-engine"),TABS:n("Tabs","ai-engine"),DROPDOWN:n("Dropdown","ai-engine"),CHATBOT_SELECT:n("Chatbot Select","ai-engine"),CONDITIONS:n("Conditions","ai-engine"),CONDITION:n("Condition","ai-engine"),ADD_CONDITION:n("Add Condition","ai-engine"),REMOVE:n("Remove","ai-engine"),MCP_NO_OPTIONS:n("MCP is enabled but no options are selected. Please enable at least one option.","ai-engine"),ORCHESTRATION:n("Orchestration","ai-engine"),ORCHESTRATION_HELP:n("Let chatbots reach out and use tools from external MCP servers. Configure servers in Settings → Orchestration.","ai-engine"),MCP_SERVERS:n("MCP Servers","ai-engine"),MCP_FUNCTIONS:n("MCP Functions","ai-engine"),URL:n("URL","ai-engine"),TOKEN:n("Token","ai-engine"),SERVER_ID:n("Server ID","ai-engine"),PRICE:n("Price","ai-engine"),UNITS:n("Units","ai-engine"),TOKENS:n("Tokens","ai-engine"),FAMILY:n("Family","ai-engine"),DAILY:n("Daily","ai-engine"),MONTHLY:n("Monthly","ai-engine"),UNKNOWN_MODEL:n("Unknown Model","ai-engine"),CONTEXTUAL:n("Contextual","ai-engine"),COMPLETION:n("Completion","ai-engine"),TOTAL_MAX_TOKENS:n("Total Max Tokens","ai-engine"),RECOMMENDED:n("Recommended","ai-engine"),SESSION:n("Session","ai-engine"),LAST_REQUEST:n("Last Request","ai-engine"),RESET_USAGE:n("Reset Usage","ai-engine"),COPIED:n("Copied!","ai-engine"),CLIPBOARD_ERROR:n("Clipboard is not enabled (only works with https).","ai-engine"),VIEW_IN_PLATFORM:n("View in OpenAI Platform","ai-engine")},o.FORMS={PROMPT_INFO:n("The template of your prompt. To re-use the data entered by the user, use the name of that field between curly braces. Example: Recommend me {MUSIC_TYPE} artists. You can also use an ID as an input, like this: ${#myfield}. Finally, if you wish the output to be formatted, add: 'Use Markdown.'.\"","ai-engine"),OUTPUT:n("Output","ai-engine"),OUTPUT_ELEMENT:n("Output Element","ai-engine"),OUTPUT_ELEMENT_INFO:n("The result will be written to this element. If you wish to simply display the result in an Output Block, use its ID. For instance, if its ID is mwai-666, use '#mwai-666'.","ai-engine")},o.HELP={TEMPERATURE:n("Between 0 and 1. Higher values means the model will take more risks.","ai-engine"),MAX_TOKENS:n("The maximum number of tokens to generate. The model will stop generating once it hits this limit.","ai-engine"),STOP_SEQUENCE:n("The sequence of tokens that will cause the model to stop generating text. You absolutely need this with fine-tuned models.","ai-engine"),COST:n("Keeps track of the current costs.","ai-engine"),RESOLVE_SHORTCODE:n("Will resolve the shortcode in your content when needed (Content-Aware will use this, for instance).","ai-engine"),FINETUNES:n("Train your own AI models.","ai-engine"),DISCUSSIONS:n("Keep the conversations and enable browsing them via the Conversations tab.","ai-engine"),DISCUSSION_TITLES:n("Generate titles for the discussions automatically with AI.","ai-engine"),DISCUSSION_SUMMARY:n("Automatically generate a brief summary of the discussion using the default (fast) model. It will be used as the discussion title.","ai-engine"),AZURE_DEPLOYMENTS:n("Add your deployments below and define what kind of model they are. GPT-5 models will automatically use the Responses API, while other models will use the Chat Completions API.","ai-engine"),BANNED_WORDS:n("Reject queries containing these words; separate with commas.","ai-engine"),WORD_BOUNDARIES:n("Ignore standard word separation (space) and match banned words anywhere in the text.","ai-engine"),BANNED_IPS:n("Block access from specified IP addresses or ranges using CIDR notation; separate with commas.","ai-engine"),GDPR_CONSENT:n("If enabled, the user will have to accept the conditions before using the chatbot.","ai-engine"),POST_TYPES:n("Enable for these post types; separate with commas.","ai-engine"),POST_STATUS:n("Enable for these post statuses (publish, draft, future, private, etc); separate with commas.","ai-engine"),POST_CATEGORIES:n("Enable for these categories (slugs); separate with commas. If none, it will be enabled for all.","ai-engine"),CONTEXT_MAX_LENGTH:n("Truncate the context (Content-Aware, Embeddings, etc) to make sure it is below this number of characters.","ai-engine"),INSTRUCTIONS:n("Placeholders: {DATE_TIME}, {DISPLAY_NAME}, {FIRST_NAME}, {LAST_NAME}, {USER_LOGIN}. With Content-Aware: {CONTENT}, {EXCERPT}, {TITLE}, {URL}.","ai-engine"),MAX_MESSAGES:n("Maximum number of historical messages that is sent to the AI model.","ai-engine"),INPUT_MAX_LENGTH:n("Maximum number of characters that can be input by the user.","ai-engine"),STATISTICS:n(" In the Insights tab, you can browse through all your users' activity. Contextual data is excluded unless you activate the options below. Make sure your users are aware of this.","ai-engine"),QUERIES_DATA:n("Record the queries and their replies.","ai-engine"),QUERIES_FORMS_DATA:n("Capture form data neatly for simple reuse.","ai-engine"),SPEECH_RECOGNITION:n("Enable speech-to-text. Depends on the browser and OS used by the user.","ai-engine"),SPEECH_SYNTHESIS:n("Enable text-to-speech.","ai-engine"),CUSTOM_SHORTCODE:n("Prefer the above version. If you need many chatbots, you can custom shortcodes, like the one below. Custom shortcodes are based on the default chatbot, and their attributes override the default ones.","ai-engine"),USER_FILTER:n("Type an User ID, or an IP.","ai-engine"),STREAMING:n("The AI's response will appear as it's being created. Be cautious: this feature's ability to manage statistics, limits, and filters is still in its beta phase.","ai-engine"),SYNTAX_HIGHLIGHT:n("Enable syntax highlighting for the code blocks.","ai-engine"),EVENT_LOGS:n("Display streaming events and function calls in the chatbot interface for debugging. Requires Streaming to be enabled. Currently only visible in chatbots.","ai-engine"),PRIVACY_FIRST:n("Only essential data is stored. IPs, conversations, and other private details are minimized and kept as anonymous as possible.","ai-engine"),DEV_TOOLS:n("Enable a new tab with debugging tools. For developers only.","ai-engine"),DEV_MODE:n("Run tasks very frequently for debugging.","ai-engine"),PUBLIC_API:n("Expose AI Engine over REST endpoints so external tools like n8n, Make, Zapier, or your own scripts can call your chatbots, generate text and images, transcribe audio, and run vision queries. Bearer-token authenticated.","ai-engine"),INTRO_MESSAGE:n("Enable introduction messages on some modules.","ai-engine"),ADDONS:n("Enable the AI Addons section under the Meow Apps menu.","ai-engine"),OPENAI_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),OPENAI_API_KEY_URL:"https://platform.openai.com/api-keys",OPENAI_API_KEY_LINK_TEXT:n("OpenAI Account ↗","ai-engine"),OPENAI_ORGANIZATION_ID:n("You can link this environment to an %s. This is optional.","ai-engine"),OPENAI_ORGANIZATION_URL:"https://platform.openai.com/account/organization",OPENAI_ORGANIZATION_LINK_TEXT:n("Organization ↗","ai-engine"),AZURE_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),AZURE_API_KEY_URL:"https://oai.azure.com/portal",AZURE_API_KEY_LINK_TEXT:n("Azure Account ↗","ai-engine"),AZURE_ENDPOINT:n("Enter just your Azure resource domain (e.g., myresource.openai.azure.com). AI Engine will automatically construct the appropriate API endpoint based on the model type.","ai-engine"),AZURE_REGION:n("Optional: Specify your Azure deployment region (e.g., swedencentral, eastus2, westus). This is required for Realtime API connections. If not specified, AI Engine will attempt to auto-detect the region from your endpoint or use eastus2 as default.","ai-engine"),ANTHROPIC_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),ANTHROPIC_API_KEY_URL:"https://console.anthropic.com/settings/keys",ANTHROPIC_API_KEY_LINK_TEXT:n("Anthropic Account ↗","ai-engine"),GOOGLE_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),GOOGLE_API_KEY_URL:"https://aistudio.google.com/apikey",GOOGLE_API_KEY_LINK_TEXT:n("Google AI Studio ↗","ai-engine"),OPENROUTER_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),OPENROUTER_API_KEY_URL:"https://openrouter.ai/keys",OPENROUTER_API_KEY_LINK_TEXT:n("OpenRouter Account ↗","ai-engine"),QDRANT:n("Use the code #AIENGINE5 when you %s. You will get 5% off.","ai-engine"),QDRANT_URL:"https://qdrant.to/cloud",QDRANT_LINK_TEXT:n("Create a Qdrant Account ↗","ai-engine"),ASSISTANTS:n("OpenAI Assistants API integration. Largely superseded by MCP for new projects.","ai-engine"),ASSISTANTS_INTRO:n("The Assistants API is designed to help developers build powerful AI assistants capable of performing a variety of tasks. To create them, head to the %s dashboard, then Refresh Assistants here. You can use an assistant in your chatbots by switching the Mode to Assistant.","ai-engine"),ASSISTANTS_INTRO_URL:"https://beta.openai.com/assistants",ASSISTANTS_INTRO_LINK_TEXT:n("OpenAI Assistants ↗","ai-engine"),ASSISTANTS_WARNINGS:n("Assistants are also %1$s, both for OpenAI and AI Engine. OpenAI did not add streaming support for them yet. Pricing is still quite unclear and %2$s. AI Engine can only perform an estimation. If you want to discuss assistants with other users, visit the %3$s.","ai-engine"),ASSISTANTS_BETA_URL:"https://platform.openai.com/docs/api-reference/assistants",ASSISTANTS_BETA_TEXT:n("in beta ↗","ai-engine"),ASSISTANTS_PRICING_URL:"https://openai.com/pricing",ASSISTANTS_PRICING_TEXT:n("tricky ↗","ai-engine"),ASSISTANTS_DISCORD_URL:"https://discord.gg/bHDGh38",ASSISTANTS_DISCORD_TEXT:n("Meow Apps Discord Server ↗","ai-engine"),BEARER_TOKEN:n("The Public API will be usable by using this Bearer Token. If not set, you will need to %s by using the mwai_allow_public_api filter.","ai-engine"),BEARER_TOKEN_URL:"https://meowapps.com/ai-engine/api/#public-rest-api",BEARER_TOKEN_LINK_TEXT:n("build your own authentication ↗","ai-engine"),REST_API_INTRO:n("The Public API enables integration with automation platforms and external applications. Use it with %s, n8n, Zapier, or any platform that supports HTTP requests to automate AI workflows and connect your WordPress site with other services.","ai-engine"),REST_API_MAKE_URL:"https://www.make.com/en/integrations/ai-engine",REST_API_MAKE_TEXT:n("Make.com ↗","ai-engine"),MCP_BEARER_TOKEN:n("A secret token used to authenticate AI assistants. Required for secure access to your WordPress site.","ai-engine"),MCP_INTRO:n("ChatGPT works perfectly with the No-Auth URL. %s for step-by-step setup. For Claude, which cannot handle SSE directly, %s is needed.","ai-engine"),MCP_TUTORIAL_URL:"https://ai.thehiddendocs.com/mcp/",MCP_TUTORIAL_TEXT:n("Check this tutorial ↗","ai-engine"),MCP_CLAUDE_TUTORIAL_URL:"https://ai.thehiddendocs.com/mcp/mcp-server-claude/",MCP_CLAUDE_TUTORIAL_TEXT:n("a relay ↗","ai-engine"),MCP_SERVER_URL:n("The URL of the MCP server. Must start with https://","ai-engine"),MCP_SERVER_TOKEN:n("Bearer token for authenticating with the MCP server.","ai-engine"),REST_API_DOCS_URL:"https://ai.thehiddendocs.com/public-rest-api/",REST_API_DOCS_TEXT:n("documentation ↗","ai-engine"),PHP_API_FUNCTIONS_URL:"https://ai.thehiddendocs.com/php-functions/",PHP_API_FUNCTIONS_TEXT:n("PHP Functions ↗","ai-engine"),PHP_API_CLASSES_URL:"https://ai.thehiddendocs.com/php-classes/",PHP_API_CLASSES_TEXT:n("PHP Classes ↗","ai-engine"),PHP_API_FILTERS_URL:"https://ai.thehiddendocs.com/php-filters/",PHP_API_FILTERS_TEXT:n("WordPress Filters ↗","ai-engine"),NO_EMBEDDINGS_RESULTS:n("No results for this search. Make sure the Minimum Score is not too high.","ai-engine"),NO_EMBEDDINGS_ROWS:n("No embeddings yet in this environment.","ai-engine"),MIN_SCORE:n("The minimum score the embeddings need to have to be returned. Between 0 and 100 and defaults to 35.","ai-engine"),MAX_SELECT:n("The maximum number of embeddings to return and to use as context. Between 1 and 100 and defaults to 10.","ai-engine"),FUNCTIONS:n("Select the functions to make available for the AI model's choice. It will use them to enhance responses and perform specific actions. This feature is known as %s.","ai-engine"),FUNCTIONS_LINK_URL:"https://ai.thehiddendocs.com/use-function-calling/",FUNCTIONS_LINK_TEXT:n("Function Calling ↗","ai-engine"),FUNCTIONS_UNAVAILABLE:n("Function calling requires %s. With Pro, define callables via %s (no-code) or register them programmatically via the mwai_functions_list filter.","ai-engine"),FUNCTIONS_UNAVAILABLE_PRO:n("No functions registered yet. You can create them with %s, or register them from your own code via the mwai_functions_list filter.","ai-engine"),FUNCTIONS_PRO_URL:"https://meowapps.com/ai-engine/",FUNCTIONS_PRO_TEXT:n("AI Engine Pro ↗","ai-engine"),FUNCTIONS_CODE_ENGINE_URL:"https://wordpress.org/plugins/code-engine/",FUNCTIONS_CODE_ENGINE_TEXT:n("Code Engine ↗","ai-engine"),MCP_SERVERS:n("Select the MCP servers to make available for the AI model. These servers provide external tools and capabilities that the AI can use to enhance responses and perform specialized actions.","ai-engine"),MCP_SERVERS_UNAVAILABLE:n("No MCP servers are available. Configure them in Settings → Orchestration.","ai-engine"),TOOLS:n("Enable AI tools to enhance your chatbot capabilities. Availability depends on the model, so please test to confirm they work with your chosen model.","ai-engine"),WEB_SEARCH:n("Allow the AI to search the web for current information","ai-engine"),IMAGE_GENERATION:n("Allow the AI to generate images based on text descriptions","ai-engine"),CODE_INTERPRETER:n("Allow the AI to write and run Python code to solve complex problems, process data, and generate visualizations","ai-engine"),ALLOWED_MIME_TYPES:n("Restrict file uploads to specific mime types. Leave empty to use defaults. Comma-separated list (e.g., image/png, image/jpeg, application/pdf).","ai-engine"),HISTORY_STRATEGY:n("Control how conversation history is sent to the Responses API. Incremental uses previous_response_id for efficiency, Full History sends all messages.","ai-engine"),ADVISOR:n("In your Dashboard will be displayed daily recommendations tailored to your WordPress setup. Admins only.","ai-engine"),BUBBLE:n("The popup will be displayed as a bubble.","ai-engine"),ICON_TEXT:n("If set, this text will appear next to the icon/bubble.","ai-engine"),ICON_TEXT_DELAY:n("Delay before text appears.","ai-engine"),WIDTH:n("Width of the chatbot when open.","ai-engine"),OPEN_DELAY:n("Auto-open after X seconds. Skipped on mobile so it does not hijack the screen.","ai-engine"),CHATBOT_SELECT:n("Choose how you want to select the chatbot. By default, tabs are used, but you can also use a filterable dropdown if you have many chatbots.","ai-engine")},o.SETTINGS={AI_ENV_SETUP:n("Add your API key in Settings → AI → Environments. %s covers most cases, so it's a no-brainer. Let's try? 🐱","ai-engine"),AI_FRESH_INSTALL:n("Hello! 🐱 We have prepared an OpenAI environment for you, just paste your key in Settings → Environments for AI. Prefer Claude, Gemini, or another provider? Switch the environment type any time.","ai-engine"),AI_DEFAULT_NO_KEY:n("Your default environment is %s, but it has no API key. Set one, or pick a different default in Settings → AI → Environments.","ai-engine"),AI_DEFAULT_TYPE_UNAVAILABLE:n("Your default environment is %s, but its engine type is no longer available. Pick a different default or re-install the matching add-on.","ai-engine"),AI_DEFAULT_MISSING:n("The Default environment or model isn't set. Pick one in Settings → AI → AI Environment Defaults.","ai-engine"),AI_DEFAULT_DEPRECATED:n("The Default model is marked as deprecated and may stop working soon. Pick a current model in Settings → AI → AI Environment Defaults.","ai-engine"),AI_FAST_MISSING:n("The Fast environment or model isn't set. Pick one in Settings → AI → AI Environment Defaults.","ai-engine"),AI_FAST_DEPRECATED:n("The Fast model is marked as deprecated and may stop working soon. Pick a current model in Settings → AI → AI Environment Defaults.","ai-engine"),AI_ENV_SETUP_URL:"https://platform.openai.com/api-keys",AI_ENV_SETUP_LINK_TEXT:n("OpenAI ↗","ai-engine"),PINECONE_SETUP:n("You choose to use Embeddings. To use them, you need to a Pinecone account. Visit the %s website to create an account, then insert your Pinecone API Key in the Settings tab.","ai-engine"),PINECONE_SETUP_URL:"https://app.pinecone.io",PINECONE_SETUP_LINK_TEXT:n("Pinecone ↗","ai-engine"),INTRO:n("Boost your WordPress with AI, now! Please start with our %1$s. Then move to our %2$s. Have a look at our %3$s. And make sure you read the %4$s. Have fun! 🎵","ai-engine"),INTRO_TUTORIAL_URL:"https://meowapps.com/ai-engine/tutorial/",INTRO_TUTORIAL_TEXT:n("tutorial","ai-engine"),INTRO_DOCS_URL:"https://ai.thehiddendocs.com/",INTRO_DOCS_TEXT:n("documentation","ai-engine"),INTRO_ADDONS_URL:"https://meowapps.com/products/category/ai-add-ons/",INTRO_ADDONS_TEXT:n("add-ons","ai-engine"),INTRO_DISCLAIMER_URL:"https://meowapps.com/ai-engine/disclaimer/",INTRO_DISCLAIMER_TEXT:n("disclaimer","ai-engine"),MODULES_INTRO:n("To avoid cluttering the UI and your WP, only enable the features you need.","ai-engine"),ALERT_INJECT_BUT_NO_POPUP:n("You choose to inject the chatbot in your website. You probably also want to use the chatbot in a Popup.","ai-engine"),ALERT_CASUALLY_BUT_NO_FINETUNE:n("Normally, you should not check the Casually Fine Tuned option with a non-finetuned model. Make sure that's what you want.","ai-engine"),ALERT_CONTENTAWARE_BUT_NO_CONTENT:n("Content Aware requires your Instructions to use at least one placeholder. More info %s.","ai-engine"),ALERT_CONTENTAWARE_URL:"https://meowapps.com/ai-engine/tutorial/#contextualization",ALERT_CONTENTAWARE_LINK_TEXT:n("here ↗","ai-engine"),SET_AS_DEFAULT_PARAMETERS:n("Set as Default Parameters","ai-engine"),SET_AS_DEFAULT_PARAMETERS_HELP:n("Set the parameters above as the default parameters for the chatbot. You can then use the shortcode [mwai_chat] anywhere on your website.","ai-engine"),INJECT_DEFAULT_CHATBOT:n("Inject Default Chatbot in Entire Website","ai-engine"),INJECT_DEFAULT_CHATBOT_HELP:n("Inject the chatbot [mwai_chat] in the entire website.","ai-engine"),CHATGPT_STYLE_INTRO:n("Keep in mind that you can also style the chatbot (or a specific chatbot, if you use many) by injecting CSS. Have a look %1$s. More information in the %2$s.","ai-engine"),CHATGPT_STYLE_CSS_URL:"https://meowapps.com/ai-engine/tutorial/#apply-custom-style-to-the-chatbot",CHATGPT_STYLE_CSS_TEXT:n("here ↗","ai-engine"),CHATGPT_STYLE_FAQ_URL:"https://meowapps.com/ai-engine/faq",CHATGPT_STYLE_FAQ_TEXT:n("FAQ ↗","ai-engine"),TYPEWRITER_EFFECT:n("Typewriter Effect","ai-engine"),TYPEWRITER_EFFECT_HELP:n("The reply from AI will be typewrited. This delays the final output! Absolutely not recommended. Please use Streaming instead.","ai-engine"),CHATBOT_MODERATION_HELP:n("If the conversation seems offensive, the chatbot will reject it.","ai-engine"),CUSTOM_URL:n("Custom URL","ai-engine"),ASSISTANT_NO_FILE_SEARCH:n("This assistant does not support File Search. You can activate it on the %s dashboard. Then, use the Refresh button in the Assistants tab.","ai-engine"),ASSISTANT_NO_FILE_SEARCH_URL:"https://platform.openai.com/assistants",ASSISTANT_NO_FILE_SEARCH_LINK_TEXT:n("OpenAI Assistants ↗","ai-engine"),ASSISTANT_FILE_SEARCH:n("File Search will be used when the users upload documents. If the user uploads images, those will be handled by AI Vision if the model supports it and if it is enabled.","ai-engine"),MCP_SERVERS_INFO:n("MCP (Model Context Protocol) servers enable AI models to interact with external tools and systems. The URL must be a secure HTTPS endpoint that implements the MCP protocol. You can configure multiple servers to provide different capabilities to your AI models.","ai-engine"),REMOTE_ACCESS_INFO:n("AI Engine provides two ways to integrate with external systems: REST API and Model Context Protocol (MCP).

REST API

Ideal for automation platforms like Make.com, Zapier, or n8n. Use this when you want to trigger AI operations from external services or integrate AI Engine into your existing workflows.

MCP

How to Use

Available Tools

For Developers

Extend functionality using mwai_mcp_tools and mwai_mcp_callback filters. See dev-notes.md for details.

Note: This makes WordPress an MCP server. For connecting TO external MCP servers, use the Orchestration module.

","ai-engine"),KNOWLEDGE_INFO:n("Embeddings are textual data converted into vectors for similarity search. You can manage embeddings in the Knowledge tab, where you can switch from EDIT to AI SEARCH mode to query your knowledge base.

Embeddings are synchronized with vector databases like %1$s or Qdrant. You can create, edit, and search embeddings, then use Sync to process your posts and create/update embeddings as needed.

Both chatbots and AI Forms can use embeddings to enrich their answers with relevant context from your knowledge base.

If you want to discuss embeddings with other users, visit the %2$s.","ai-engine"),KNOWLEDGE_PINECONE_URL:"https://www.pinecone.io/",KNOWLEDGE_PINECONE_TEXT:n("Pinecone ↗","ai-engine"),KNOWLEDGE_DISCORD_URL:"https://discord.gg/bHDGh38",KNOWLEDGE_DISCORD_TEXT:n("Meow Apps Discord Server ↗","ai-engine"),ORCHESTRATION_INFO:n("MCP servers extend AI capabilities by providing tools and functions that AI models can call during conversations. Configure external MCP servers here to give your chatbots access to specialized tools like web browsing, file system access, database queries, or custom business logic.

Each server requires a secure HTTPS URL implementing the MCP protocol and may require authentication via bearer token. Once configured, the tools from these servers become available to AI models through function calling.

Note: This is for connecting TO external MCP servers. To make your WordPress accessible AS an MCP server for AI agents like Claude, use the MCP option under Remote Access.","ai-engine")},o.CHATBOT={CHATBOT_BUILDER:n("Chatbot Builder","ai-engine"),RESET_PARAMS:n("Reset Parameters","ai-engine")},o.STATISTICS={ABSOLUTE_HELP:n("Using Absolute, Day represents today. Otherwise, the past 24 hours. Same logic applies to the other timeframes.","ai-engine"),NO_CREDITS_MESSAGE:n("Message for No Credits","ai-engine"),FULL_ACCESS_USERS:n("Full-Access Users","ai-engine"),ENABLE_LIMITS:n("Enable Limits","ai-engine")},o.CONTENT_GENERATOR={INTRO:n("Generate high-quality articles with AI assistance. Create comprehensive content with customizable templates, writing styles, and automatic SEO optimization. Perfect for blogs, documentation, and marketing materials.","ai-engine"),TITLE_MISSING:n("Title is missing!","ai-engine"),SECTIONS_MISSING:n("Sections are missing!","ai-engine"),SINGLE_GENERATE:n("Single Generate","ai-engine"),BULK_GENERATE:n("Bulk Generate","ai-engine"),CONTENT_PARAMS:n("Content Params","ai-engine"),POST_PARAMS:n("Post Params","ai-engine"),CONTENT_PARAMS_INTRO:n("Input fields are displayed for certain placeholders used in prompts, such as {LANGUAGE} or {WRITING_TONE}","ai-engine"),CUSTOM_LANGUAGE:n("Custom Language","ai-engine"),WRITING_STYLE:n("Writing Style","ai-engine"),WRITING_TONE:n("Writing Tone","ai-engine"),CUSTOM_LANGUAGE_HELP:n("AI supports all languages with varying quality. %s.","ai-engine"),CUSTOM_LANGUAGE_URL:"https://meowapps.com/ai-engine/faq/#languages",CUSTOM_LANGUAGE_LINK_TEXT:n("Learn more ↗","ai-engine"),MODEL_HELP:n("It is recommended to use Turbo or GPT-4 to write texts.","ai-engine"),PROMPTS_INTRO:n("Prompts represent the exact request sent to the AI. The variables between curly braces will be replaced by the content of the corresponding field. Prompts are saved in your templates.","ai-engine"),PROMPT_TITLE:n("Prompt for Title","ai-engine"),PROMPT_SECTIONS:n("Prompt for Sections","ai-engine"),PROMPT_CONTENT:n("Prompt for Content","ai-engine"),PROMPT_EXCERPT:n("Prompt for Excerpt","ai-engine"),POST_CREATED:n("Post Created","ai-engine"),POST_CREATED_AS_DRAFT:n("The post was created as a draft.","ai-engine"),CONTENT_HELP:n('You can modify the content before using "Create Post". Markdown is supported, and will be converted to HTML when the post is created.',"ai-engine"),SECTIONS_HELP:n('Add, rewrite, remove, or reorganize those sections as you wish before (re)clicking on "Generate Content". Markdown format is recommended.',"ai-engine"),GENERATE_EXCERPT:n("Generate Excerpt","ai-engine"),GENERATE_CONTENT:n("Generate Content","ai-engine"),GENERATE_SECTIONS:n("Generate Sections","ai-engine"),PARAGRAPHS_PER_SECTION:n("# of Paragraphs per Section","ai-engine"),NUMBER_OF_SECTIONS:n("# of Sections","ai-engine"),ADVICE:n("Advice","ai-engine"),SECTIONS:n("Sections","ai-engine"),USE_MAX_TOKENS:n("Use Max Tokens","ai-engine"),TOPICS_HELP:n("Write or paste your topics below. Each line will be used as a topic. The Context on the left will be applied to all topics. The same Params and Prompts will be used as with the Single Generate, so make sure you get satisfying results with it first. This takes time, so relax and enjoy some coffee ☕️ and tea 🍵 :)","ai-engine"),GENERATED_POSTS:n("Generated Posts","ai-engine"),USE_TOPICS_AS_TITLES:n("Use Topics as Titles","ai-engine"),NOTHING_YET:n("Nothing yet.","ai-engine"),BULK_ERROR_CONFIRM:n("An error was caught ({MESSAGE}). Should we continue?","ai-engine"),GENERATE_ALL:n("Generate All","ai-engine"),EDIT_POST:n("Edit Post","ai-engine"),CREATE_POST:n("Create Post","ai-engine"),TITLE_TOO_SHORT:n("The title is too short. It should be at least 3 words.","ai-engine"),TITLE_TOO_SHORT_2:n("The title is too short. It should be at least 40 characters.","ai-engine"),TITLE_TOO_LONG:n("The title is too long. It should be less than 8 words.","ai-engine"),TITLE_TOO_LONG_2:n("The title is too long. It should be less than 70 characters.","ai-engine")},o.TEMPLATES={TEMPLATE:n("Template","ai-engine"),TEMPLATES:n("Templates","ai-engine"),DELETE_CONFIRM:n("Are you sure you want to delete this template?","ai-engine"),DELETE_ALL_CONFIRM:n("Are you sure you want to delete all the templates?","ai-engine"),NEW_TEMPLATE_NAME:n("New Template","ai-engine"),EDIT:n("EDIT","ai-engine")},o.PLAYGROUND={INTRO:n("Welcome to the AI Playground! Here, you can play with different AI models and ask the UI to perform various tasks for you. You can ask it to write, rewrite, or translate an article, categorize words or elements into groups, write an email, etc. Let me know if there are any new features you would like to see! Have fun 🥳","ai-engine"),PROMPT:n("Query / Prompt","ai-engine"),REPLY:n("Reply","ai-engine")},o.ALERTS={FINETUNING_STARTED:n("Fine-tuning started! Check its progress in the Models section. Depending on your dataset size, it may take a while (from a few minutes to days).","ai-engine"),RESET_BUILDER:n("This will delete all the rows in the builder. Are you sure?","ai-engine"),DELETE_FINETUNE:n("You are going to delete this fine-tune. Are you sure?\n\nPlease note that it will take a while before it is actually deleted. This might be a temporary issue of OpenAI.","ai-engine"),FINETUNE_ALREADY_DELETED:n("This fine-tune was already deleted. It will be removed from the list.","ai-engine"),CHECK_CONSOLE:n("Error! Check your console for more details.","ai-engine"),DATASET_UPLOADED:n("Uploaded successfully! You can now train a model based on this dataset.","ai-engine"),ONLY_SUPPORTS_FILES:n("This only supports JSON, JSONL, and CSV files. Check the Instructions section below.","ai-engine"),EMPTY_LINES_DATASET:n("Some lines were empty. Make sure the CSV has a header row and that the columns are named 'prompt' and 'completion'. For debugging, an empty line was logged to the console.","ai-engine"),EMPTY_LINES_EMBEDDINGS:n("Some lines were empty. Make sure the CSV has a header row and that the columns are named 'title' and 'content'. For debugging, an empty line was logged to the console.","ai-engine"),ARE_YOU_SURE:n("Are you sure?","ai-engine")},o.FINETUNING={MODELS_INTRO:n("The AI models you have fine-tuned. To create more, visit Files.","ai-engine"),LEGACY_MODELS_INTRO:n("The AI models you have fine-tuned. Do not use legacy fine-tuning anymore (based on models prior to GPT 3.5). Their deprecation has been %s for January 4th, 2024.
","ai-engine"),LEGACY_MODELS_DEPRECATION_URL:"https://platform.openai.com/docs/guides/legacy-fine-tuning",LEGACY_MODELS_DEPRECATION_TEXT:n("announced by OpenAI ↗","ai-engine"),FILES_INTRO:n("The files you have uploaded to OpenAI. To create a new dataset file, switch from Model & Files to Dataset Editor. To train a new model, click on the magic wand.","ai-engine"),MODEL_FINETUNE:n("Model Finetune","ai-engine"),MODELS_FILES:n("Models & Files","ai-engine"),DATASET_EDITOR:n("Dataset Editor","ai-engine"),EDITOR:n("Editor","ai-engine"),GENERATOR:n("Generator","ai-engine"),HUGE_DATASET_WARNING:n("Caution: The data is too large to be saved in your browser's local storage.","ai-engine"),NO_FINETUNES_YET:n("No fine-tunes found. Refresh the list, or create a new one (via a dataset).","ai-engine"),CLEAN_MODELS_LIST:n("Clean Models List","ai-engine"),DELETED_FINETUNE_ISSUE:n("For some reason, OpenAI still return the models even after you deleted them. Don't worry, AI Engine will do the cleanup for you! You can force the cleanup by using this button. It takes a bit of time depending on the total of models you have.","ai-engine")},o.DISCUSSIONS={NEW_CHAT:n("New Chat","ai-engine"),NO_MESSAGES_YET:n("No messages yet","ai-engine"),RENAME:n("Rename","ai-engine"),DELETE:n("Delete","ai-engine"),UNTITLED:n("Untitled","ai-engine"),TITLE_GENERATION_PROMPT:n("Based on the following conversation, generate a concise and specific title for the discussion, strictly less than 64 characters. Focus on the main topic, avoiding unnecessary words such as articles, pronouns, or adjectives. Do not include any punctuation at the end. Do not include anything else than the title itself, only one sentence, no line breaks, just the title.","ai-engine")},o.WRITING_STYLES={INFORMATIVE:n("Informative","ai-engine"),DESCRIPTIVE:n("Descriptive","ai-engine"),CREATIVE:n("Creative","ai-engine"),NARRATIVE:n("Narrative","ai-engine"),PERSUASIVE:n("Persuasive","ai-engine"),REFLECTIVE:n("Reflective","ai-engine"),ARGUMENTATIVE:n("Argumentative","ai-engine"),ANALYTICAL:n("Analytical","ai-engine"),EVALUATIVE:n("Evaluative","ai-engine"),JOURNALISTIC:n("Journalistic","ai-engine"),TECHNICAL:n("Technical","ai-engine")},o.WRITING_TONES={NEUTRAL:n("Neutral","ai-engine"),FORMAL:n("Formal","ai-engine"),ASSERTIVE:n("Assertive","ai-engine"),CHEERFUL:n("Cheerful","ai-engine"),HUMOROUS:n("Humorous","ai-engine"),INFORMAL:n("Informal","ai-engine"),INSPIRATIONAL:n("Inspirational","ai-engine"),PROFESSIONAL:n("Professional","ai-engine"),CONFLUENT:n("Confluent","ai-engine"),EMOTIONAL:n("Emotional","ai-engine"),PERSUASIVE:n("Persuasive","ai-engine"),SUPPORTIVE:n("Supportive","ai-engine"),SARCASTIC:n("Sarcastic","ai-engine"),CONDESCENDING:n("Condescending","ai-engine"),SKEPTICAL:n("Skeptical","ai-engine"),NARRATIVE:n("Narrative","ai-engine"),JOURNALISTIC:n("Journalistic","ai-engine")},o.EMBEDDINGS={EDIT:n("EDIT","ai-engine"),AI_SEARCH:n("AI SEARCH","ai-engine"),SYNC_POSTS:n("Sync Posts","ai-engine"),AUTO_SYNC_POSTS:n("Auto-Sync Posts","ai-engine"),AUTO_SYNC_POSTS_DESCRIPTION:n("Embeddings will be created, updated or removed based on the activity related to your posts.","ai-engine"),REWRITE_CONTENT:n("Rewrite Content","ai-engine"),REWRITE_CONTENT_DESCRIPTION:n("Shorten and improve the content for your embedding using the default model.","ai-engine"),FORCE_RECREATE:n("Force Recreate","ai-engine"),FORCE_RECREATE_DESCRIPTION:n("Force recreation of existing embeddings even when content, model, and dimensions haven't changed. Note: New posts without embeddings will always be synced regardless of this setting.","ai-engine"),DELETE_ALL_EMBEDDINGS:n("Delete All Embeddings","ai-engine"),DELETE_ALL_EMBEDDINGS_CONFIRM:n("Are you sure you want to delete all the embeddings in this environment?","ai-engine"),REWRITE_PROMPT_DESCRIPTION:n("Prompt for the rewrite. Supports {CONTENT}, {TITLE}, {URL}, {EXCERPT}, {LANGUAGE}, {ID}.","ai-engine"),SYNC_ALL:n("Sync All","ai-engine"),SYNC_ONE:n("Sync One","ai-engine"),ADD_INDEX:n("Add Index","ai-engine"),ADD_INDEX_DESCRIPTION:n("An index is like a database, and contains embeddings. You can have many indexes and switch between them. The indexes are hosted on Pinecone.","ai-engine"),NO_NAMESPACE_SUPPORT:n("Note: This server does not support namespaces.","ai-engine"),REWRITE_REMOTE_CONTENT:n("Rewrite Remote Content","ai-engine"),REWRITE_REMOTE_CONTENT_DESCRIPTION:n("Clean and optimize content fetched from remote URLs using the default model.","ai-engine"),FORCE_REMOTE_RECREATE:n("Force Remote Recreate","ai-engine"),FORCE_REMOTE_RECREATE_DESCRIPTION:n("Force recreation of remote URL embeddings even when content hasn't changed.","ai-engine"),REWRITE_REMOTE_PROMPT_DESCRIPTION:n("Prompt for the remote URL rewrite. Supports {CONTENT}, {URL}.","ai-engine"),DEFAULT_REMOTE_REWRITE_PROMPT:n("Extract and clean the main content from this web page. Remove all website elements that are not part of the actual content: navigation menus, headers, footers, sidebars, breadcrumbs, ads, cookie notices, social sharing buttons, and related links sections.\n\nKeep only the primary content of the page. Use minimal formatting:\n- Use line breaks to separate distinct sections\n- Use simple lists (with dashes) only when the original has clear list items\n- For products or items: keep name, price, and key details on separate lines\n- Do not add markdown headers, bold, or other rich formatting\n\nThe result should be clean, readable text that preserves the essential information and structure. Keep it concise (under 1000 words). Output only the cleaned content, nothing else.\n\n{CONTENT}","ai-engine"),SYNC_REMOTE_URLS_INTERVAL:n("Sync Interval","ai-engine"),SYNC_REMOTE_URLS_INTERVAL_DESCRIPTION:n("How often to check remote URLs for content updates.","ai-engine"),INTERVAL_1H:n("Every hour","ai-engine"),INTERVAL_6H:n("Every 6 hours","ai-engine"),INTERVAL_12H:n("Every 12 hours","ai-engine"),INTERVAL_24H:n("Every 24 hours","ai-engine"),INTERVAL_48H:n("Every 48 hours","ai-engine"),INTERVAL_72H:n("Every 72 hours","ai-engine"),INTERVAL_1W:n("Every week","ai-engine"),INTERVAL_1M:n("Every month","ai-engine"),LOCAL_CONTENT:n("Local Content","ai-engine"),REMOTE_URLS:n("Remote URLs","ai-engine"),SYNC_SETTINGS:n("Sync Settings","ai-engine"),SYNC_SETTINGS_DESCRIPTION:n("Settings for synchronizing embeddings with your content.","ai-engine"),SEARCH_SETTINGS:n("Search Settings","ai-engine"),SEARCH_SETTINGS_DESCRIPTION:n("Settings for how embeddings are retrieved during conversations.","ai-engine")},o.ERROR={UPDATING_OPTIONS:n("An error occurred while updating the options."),GETTING_OPTIONS:n("An error occurred while getting the options."),CHECK_YOUR_CONSOLE:n('For more information, check your console ↗. You might also want to check your PHP Error Logs ↗.',"ai-engine"),SESSION_EXPIRED:n("Your session has expired. Please refresh the page to continue using AI Engine.","ai-engine"),COULD_NOT_PARSE_ERROR_STREAM:n("Could not parse the 'error' stream.","ai-engine"),COULD_NOT_PARSE_END_STREAM:n("Could not parse the 'end' stream.","ai-engine"),INVALID_API_KEY:n("Invalid API key: Please check your OpenAI API key in settings.","ai-engine"),RATE_LIMIT_EXCEEDED:n("Rate limit exceeded: Too many requests. Please try again later.","ai-engine"),NETWORK_ERROR:n("Network error: Failed to establish connection to the AI service.","ai-engine"),AUTHENTICATION_FAILED:n("Authentication failed: Your session has expired. Please refresh the page.","ai-engine"),INTERNAL_SERVER_ERROR:n("Internal server error: An unexpected error occurred. Please try again.","ai-engine"),PROCESSING_ERROR:n("An error occurred while processing your request. Please try again.","ai-engine"),MEDIADEVICES_NOT_AVAILABLE:n("MediaDevices API not available. Please ensure you are using HTTPS and a modern browser.","ai-engine"),MICROPHONE_ACCESS_FAILED:n("Failed to access microphone. Please ensure microphone permissions are granted and try again.","ai-engine"),CONNECTION_FAILED:n("Failed to establish connection with OpenAI servers. Please try again.","ai-engine")},o.DEBUG={CRASH_IN_MARKDOWN:n("Crash in markdown-to-jsx! Reverting to plain text.","ai-engine"),AI_ENGINE_COULD_NOT_FIND_BLOCK:n("AI Engine: Could not find block element for","ai-engine"),AI_WAND_TABLE_REQUIRES_DATA:n("AI Wand: Table requires structured data for proper update","ai-engine"),AI_WAND_COULD_NOT_FIND_SELECTION:n("AI Wand: Could not find selection, replacing entire block content","ai-engine"),NEW_TOKEN_RECEIVED:n("[MWAI] 🔐 New token received","ai-engine"),NONCE_ERROR_DETECTED:n("[MWAI] Nonce error detected, attempting to refresh...","ai-engine")};const r=o},384(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{G1:()=>ChatbotContextProvider,oS:()=>useChatbotContext,tn:()=>ChatbotContext});var _app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(7437),_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(6422),_app_helpers__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(2509),_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(9328);const{useContext,createContext,useState,useMemo,useEffect,useCallback,useRef}=wp.element,__=e=>"undefined"!=typeof wp&&wp.i18n&&wp.i18n.__?wp.i18n.__(e,"ai-engine"):e,rawAiName="AI: ",rawUserName="User: ",ChatbotContext=createContext(),useChatbotContext=()=>{const e=useContext(ChatbotContext);if(!e)throw new Error("useChatbotContext must be used within a ChatbotContextProvider");return e},clamp01=e=>Math.min(1,Math.max(0,e)),hexToRgb=e=>{if(!e||"string"!=typeof e)return null;const t=e.replace("#","").trim(),a=3===t.length?t.split("").map((e=>e+e)).join(""):t,n=parseInt(a,16);return Number.isNaN(n)||6!==a.length?null:{r:n>>16&255,g:n>>8&255,b:255&n}},rgbToHsl=({r:e,g:t,b:a})=>{e/=255,t/=255,a/=255;const n=Math.max(e,t,a),l=Math.min(e,t,a);let o=0,r=0,i=(n+l)/2;if(n!==l){const s=n-l;switch(r=i>.5?s/(2-n-l):s/(n+l),n){case e:o=(t-a)/s+(t{const n=(e,t,a)=>(a<0&&(a+=1),a>1&&(a-=1),a<1/6?e+6*(t-e)*a:a<.5?t:a<2/3?e+(t-e)*(2/3-a)*6:e);let l,o,r;if(0===t)l=o=r=a;else{const i=a<.5?a*(1+t):a+t-a*t,s=2*a-i;l=n(s,i,e+1/3),o=n(s,i,e),r=n(s,i,e-1/3)}return{r:Math.round(255*l),g:Math.round(255*o),b:Math.round(255*r)}},rgbToHex=({r:e,g:t,b:a})=>`#${[e,t,a].map((e=>e.toString(16).padStart(2,"0"))).join("")}`,lightenHex=(e,t=.4)=>{const a=hexToRgb(e);if(!a)return e;const n=rgbToHsl(a);return n.l=clamp01(n.l+(1-n.l)*t),n.s=clamp01(1.05*n.s),rgbToHex(hslToRgb(n))},gradientFromBase=(e,t=.55)=>`linear-gradient(130deg, ${e} 0%, ${lightenHex(e,t)} 100%)`,ChatbotContextProvider=({children,...rest})=>{var _params$startSentence;const{params,system,theme,atts}=rest,{timeElapsed,startChrono,stopChrono}=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.dh)(),shortcodeStyles=useMemo((()=>(null==theme?void 0:theme.settings)||{}),[theme]),[restNonce,setRestNonce]=useState(system.restNonce||_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_3__.A.getToken()),restNonceRef=useRef(system.restNonce||_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_3__.A.getToken());useEffect((()=>_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_3__.A.subscribe((e=>{setRestNonce(e),restNonceRef.current=e}))),[]);const[messages,setMessages]=useState([]),[shortcuts,setShortcuts]=useState([]),[blocks,setBlocks]=useState([]),[locked,setLocked]=useState(!1),[chatId,setChatId]=useState((0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()),[inputText,setInputText]=useState(""),[chatbotTriggered,setChatbotTriggered]=useState(!1),[showIconMessage,setShowIconMessage]=useState(!1),[uploadedFile,setUploadedFile]=useState({localFile:null,uploadedId:null,uploadedUrl:null,uploadProgress:null}),[uploadedFiles,setUploadedFiles]=useState([]),[windowed,setWindowed]=useState((()=>{const e=Boolean(params.window),t=Boolean(params.fullscreen);return e||!t})),[open,setOpen]=useState(!1),[opening,setOpening]=useState(!1),[closing,setClosing]=useState(!1),[error,setError]=useState(null),[busy,setBusy]=useState(!1),[busyNonce,setBusyNonce]=useState(!1),[lastFailedQuery,setLastFailedQuery]=useState(null),[serverReply,setServerReply]=useState(),[previousResponseId,setPreviousResponseId]=useState(null),chatbotInputRef=useRef(),conversationRef=useRef(),hasFocusRef=useRef(!1),[containerType,setContainerType]=useState(params.containerType),[headerType,setHeaderType]=useState(params.headerType),[messagesType,setMessagesType]=useState(params.messagesType||"standard"),[inputType,setInputType]=useState(params.inputType||"standard"),[footerType,setFooterType]=useState(params.footerType);useEffect((()=>{setContainerType(params.containerType),setHeaderType(params.headerType),setMessagesType(params.messagesType||"standard"),setInputType(params.inputType||"standard"),setFooterType(params.footerType)}),[params.containerType,params.headerType,params.messagesType,params.inputType,params.footerType]);const{isListening,setIsListening,speechRecognitionAvailable}=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.Vw)((e=>{setInputText(e)})),stream=system.stream||!1,internalId=useMemo((()=>(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()),[]),botId=system.botId,customId=system.customId,userData=system.userData,[sessionId,setSessionId]=useState(system.sessionId),contextId=system.contextId,pluginUrl=system.pluginUrl,restUrl=system.restUrl,debugMode=system.debugMode,eventLogs=system.eventLogs,typewriter=(null==system?void 0:system.typewriter)??!1,speechRecognition=(null==system?void 0:system.speech_recognition)??!1,speechSynthesis=(null==system?void 0:system.speech_synthesis)??!1,startSentence=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.Mc)((null===(_params$startSentence=params.startSentence)||void 0===_params$startSentence?void 0:_params$startSentence.trim())??"",userData),initialActions=system.actions||[],initialShortcuts=system.shortcuts||[],initialBlocks=system.blocks||[],isMobile=document.innerWidth<=768,processedParams=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__._$)(params,userData),{aiName,userName,guestName,aiAvatar,userAvatar,guestAvatar}=processedParams,{textSend,textClear,textInputMaxLength,textInputPlaceholder,textCompliance,window:isWindow,copyButton,pdfButton,headerSubtitle,popupTitle,fullscreen,localMemory:localMemoryParam,icon,iconText,iconTextDelay,iconAlt,iconPosition,iconSize,centerOpen,width,maxHeight,openDelay,iconBubble,fileUpload,multiUpload,maxUploads,fileSearch,allowedMimeTypes,windowAnimation}=processedParams,isRealtime="realtime"===processedParams.mode,localMemory=localMemoryParam&&(!!customId||!!botId),localStorageKey=localMemory?`mwai-chat-${customId||botId}`:null,{cssVariables,iconUrl,aiAvatarUrl,userAvatarUrl,guestAvatarUrl}=useMemo((()=>{const e=e=>e?(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Ve)(e)||(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.mv)(e)?e:`${pluginUrl}/images/${e}`:null,t=icon?e(icon):`${pluginUrl}/images/chat-traditional-1.svg`,a=e(processedParams.aiAvatarUrl),n=e(processedParams.userAvatarUrl),l=e(processedParams.guestAvatarUrl);let o=Object.keys(shortcodeStyles).reduce(((e,t)=>(e[`--mwai-${t}`]=shortcodeStyles[t],e)),{});if(null!=shortcodeStyles&&shortcodeStyles.iconTextBackgroundColor||null==shortcodeStyles||!shortcodeStyles.avatarMessageBackgroundColor||(o["--mwai-iconTextBackgroundColor"]=shortcodeStyles.avatarMessageBackgroundColor),null!=shortcodeStyles&&shortcodeStyles.iconTextColor||null==shortcodeStyles||!shortcodeStyles.avatarMessageFontColor||(o["--mwai-iconTextColor"]=shortcodeStyles.avatarMessageFontColor),"timeless"===(null==theme?void 0:theme.themeId)&&null!=shortcodeStyles&&shortcodeStyles.backgroundHeaderColor){const e=shortcodeStyles.backgroundHeaderColor;"string"==typeof e&&e.trim().startsWith("#")&&(o["--mwai-backgroundHeaderColor"]=gradientFromBase(e,.55),o["--mwai-accentColor"]=e)}if("timeless"===(null==theme?void 0:theme.themeId)&&null!=shortcodeStyles&&shortcodeStyles.backgroundUserColor){const e=shortcodeStyles.backgroundUserColor;"string"==typeof e&&e.trim().startsWith("#")&&(o["--mwai-backgroundUserColor"]=gradientFromBase(e,.16))}return"chatgpt"!==(null==theme?void 0:theme.themeId)&&"foundation"!==(null==theme?void 0:theme.themeId)||null==shortcodeStyles||!shortcodeStyles.accentColor||(o["--mwai-accentColor"]=shortcodeStyles.accentColor),maxHeight&&(o["--mwai-maxHeight"]=maxHeight),iconSize&&(o["--mwai-iconSize"]=/^\d+(\.\d+)?$/.test(iconSize)?`${iconSize}px`:iconSize),{cssVariables:o,iconUrl:t,aiAvatarUrl:a,userAvatarUrl:n,guestAvatarUrl:l}}),[icon,pluginUrl,shortcodeStyles,processedParams]),[draggingType,setDraggingType]=useState(!1),[isBlocked,setIsBlocked]=useState(!1),uploadIconPosition=useMemo((()=>"timeless"===(null==theme?void 0:theme.themeId)?"mwai-tools":"mwai-input"),[null==theme?void 0:theme.themeId]),submitButtonConf=useMemo((()=>{const e="timeless"===(null==theme?void 0:theme.themeId);return{text:textSend,textSend,textClear,imageSend:null,imageClear:null,useLucide:e,lucideSend:"send-horizontal"}}),[textClear,textSend,null==theme?void 0:theme.themeId]),resetMessages=()=>{if(resetUploadedFile(),setPreviousResponseId(null),startSentence){const e=[{id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"assistant",content:startSentence,who:rawAiName,timestamp:(new Date).getTime(),key:`start-${Date.now()}`}];setMessages(e)}else setMessages([])},refreshRestNonce=useCallback((async(e=!1)=>{try{if(!e&&restNonce)return restNonce;setBusyNonce(!0);const t=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai/v1/start_session`),a=await t.json();if(setRestNonce(a.restNonce),restNonceRef.current=a.restNonce,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_3__.A.setToken(a.restNonce),a.sessionId&&"N/A"!==a.sessionId&&setSessionId(a.sessionId),a.new_token){if(a.token_expires_at){const e=new Date(1e3*a.token_expires_at);console.log(`[MWAI] 🔐 New token received - expires at ${e.toLocaleTimeString()} (in ${a.token_expires_in}s)`)}return setRestNonce(a.new_token),restNonceRef.current=a.new_token,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_3__.A.setToken(a.new_token),a.new_token}return a.restNonce}catch(e){console.error("Error while fetching the restNonce.",e)}finally{setBusyNonce(!1)}}),[restNonce,setRestNonce,restUrl,setSessionId]),[isResumingConversation,setIsResumingConversation]=useState(!1),[isConversationLoaded,setIsConversationLoaded]=useState(!1);useEffect((()=>{if(!isConversationLoaded)return;isResumingConversation||messages.length>1||1===messages.length&&messages[0].content!==startSentence||(initialActions.length>0&&handleActions(initialActions),initialShortcuts.length>0&&handleShortcuts(initialShortcuts),initialBlocks.length>0&&handleBlocks(initialBlocks))}),[isConversationLoaded,isResumingConversation,messages,startSentence]),useEffect((()=>{chatbotTriggered&&!restNonce&&refreshRestNonce()}),[chatbotTriggered]),useEffect((()=>{inputText.length>0&&!chatbotTriggered&&setChatbotTriggered(!0)}),[chatbotTriggered,inputText]),useEffect((()=>{resetMessages()}),[startSentence]),useEffect((()=>{if(customId||botId){const e=_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__.HX.chatbots.findIndex((e=>e.internalId===internalId)),t={internalId,botId,chatId,customId,localStorageKey,open:()=>{setTasks((e=>[...e,{action:"open"}]))},close:()=>{setTasks((e=>[...e,{action:"close"}]))},clear:e=>{const{chatId:t=null}=e||{};setTasks((e=>[...e,{action:"clear",data:{chatId:t}}]))},toggle:()=>{setTasks((e=>[...e,{action:"toggle"}]))},ask:(e,t=!1)=>{setTasks((a=>[...a,{action:"ask",data:{text:e,submit:t}}]))},lock:()=>{setLocked(!0)},unlock:()=>{setLocked(!1)},setShortcuts:e=>{setTasks((t=>[...t,{action:"setShortcuts",data:e}]))},setBlocks:e=>{setTasks((t=>[...t,{action:"setBlocks",data:e}]))},addBlock:e=>{setTasks((t=>[...t,{action:"addBlock",data:e}]))},removeBlockById:e=>{setTasks((t=>[...t,{action:"removeBlockById",data:e}]))},getBlocks:()=>blocks,setContext:({chatId:e,messages:t,previousResponseId:a})=>{console.warn("MwaiAPI: setContext is deprecated. Please use setConversation instead."),setTasks((n=>[...n,{action:"setContext",data:{chatId:e,messages:t,previousResponseId:a}}]))},setConversation:({chatId:e,messages:t,previousResponseId:a})=>{setTasks((n=>[...n,{action:"setContext",data:{chatId:e,messages:t,previousResponseId:a}}]))}};-1!==e?_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__.HX.chatbots[e]=t:_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__.HX.chatbots.push(t)}}),[botId,chatId,customId,internalId,localStorageKey,blocks]),useEffect((()=>{var e;open&&!isMobile&&null!==(e=chatbotInputRef.current)&&void 0!==e&&e.focusInput&&setTimeout((()=>{chatbotInputRef.current.focusInput()}),100)}),[open,isMobile]),useEffect((()=>{var e;busy?startChrono():(!isMobile&&hasFocusRef.current&&null!==(e=chatbotInputRef.current)&&void 0!==e&&e.focusInput&&chatbotInputRef.current.focusInput(),stopChrono())}),[busy,startChrono,stopChrono,isMobile]);const saveMessages=useCallback((e=>{localStorageKey&&localStorage.setItem(localStorageKey,(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.F1)({chatId,messages:e}))}),[localStorageKey,chatId]),resetError=()=>{setError(null)},addErrorMessage=useCallback(((e,t=null)=>{const a={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"error",content:e,who:"Error",timestamp:(new Date).getTime(),isError:!0,failedQuery:t};setMessages((e=>[...e,a])),setLastFailedQuery(t)}),[]);useEffect((()=>{let e=[];if(localStorageKey&&(e=localStorage.getItem(localStorageKey),e))return e=JSON.parse(e),setMessages(e.messages),setChatId(e.chatId),setIsResumingConversation(!0),void setIsConversationLoaded(!0);setIsResumingConversation(!1),setIsConversationLoaded(!0),setChatId((0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()),resetMessages()}),[botId]);const executedActionsRef=useRef(new Set),handleActions=useCallback(((actions,lastMessage)=>{actions=actions||[];let callsCount=0;for(const action of actions)if("function"===action.type){const data=action.data||{},{name=null,args=[]}=data,actionKey=`${name}_${JSON.stringify(args)}`;if(executedActionsRef.current.has(actionKey)){debugMode&&console.log(`[CHATBOT] Skipping duplicate execution of ${name}`);continue}const finalArgs=args?Object.values(args).map((e=>JSON.stringify(e))):[];try{debugMode&&console.log(`[CHATBOT] CALL ${name}(${finalArgs.join(", ")})`),executedActionsRef.current.add(actionKey),eval(`${name}(${finalArgs.join(", ")})`),callsCount++,setTimeout((()=>{executedActionsRef.current.delete(actionKey)}),5e3)}catch(e){console.error("Error while executing an action.",e),executedActionsRef.current.delete(actionKey)}}!lastMessage.content&&callsCount>0&&(lastMessage.content="*Done!*")}),[debugMode]),handleShortcuts=useCallback((e=>{setShortcuts(e||[])}),[]),handleBlocks=useCallback((e=>{setBlocks(e||[])}),[]);useEffect((()=>{if(!serverReply)return;setBusy(!1);const e=[...messages],t=e.length>0?e[e.length-1]:null;if(!serverReply.success){"assistant"===t.role&&t.isQuerying&&e.pop();const a=e.length-1;let n=null,l=null;if(a>=0&&"user"===e[a].role){const t=e[a].content,o=t.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);n=o?o[1]:t,o&&uploadedFile&&(l=uploadedFile)}return setMessages(e),saveMessages(e),void addErrorMessage(serverReply.message,n?{text:n,file:l}:null)}if("assistant"===t.role&&t.isQuerying)t.content=(0,_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__.W5)("ai.reply",serverReply.reply,{chatId,botId}),serverReply.images&&(t.images=serverReply.images),t.timestamp=(new Date).getTime(),delete t.isQuerying,handleActions(null==serverReply?void 0:serverReply.actions,t),handleBlocks(null==serverReply?void 0:serverReply.blocks),handleShortcuts(null==serverReply?void 0:serverReply.shortcuts);else if("assistant"===t.role&&t.isStreaming){if(t.content=(0,_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__.W5)("ai.reply",serverReply.reply,{chatId,botId}),serverReply.images&&(t.images=serverReply.images),t.timestamp=(new Date).getTime(),delete t.isStreaming,(debugMode||eventLogs)&&t.streamEvents){var a;const e=(new Date).getTime(),n=e-((null===(a=t.streamEvents[0])||void 0===a?void 0:a.timestamp)||e);let l;if(n<1e3)l=`${n}ms`;else if(n<6e4)l=`${(n/1e3).toFixed(1)}s`;else{l=`${Math.floor(n/6e4)}m ${(n%6e4/1e3).toFixed(0)}s`}t.streamEvents.push({type:"event",subtype:"status",data:`Request completed in ${l}.`,timestamp:e})}handleActions(null==serverReply?void 0:serverReply.actions,t),handleBlocks(null==serverReply?void 0:serverReply.blocks),handleShortcuts(null==serverReply?void 0:serverReply.shortcuts)}else{const t={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"assistant",content:(0,_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__.W5)("ai.reply",serverReply.reply,{botId,chatId,customId}),who:rawAiName,timestamp:(new Date).getTime()};serverReply.images&&(t.images=serverReply.images),handleActions(null==serverReply?void 0:serverReply.actions,t),handleBlocks(null==serverReply?void 0:serverReply.blocks),handleShortcuts(null==serverReply?void 0:serverReply.shortcuts),e.push(t)}serverReply.responseId&&setPreviousResponseId(serverReply.responseId),setMessages(e),saveMessages(e)}),[serverReply]);const onClear=useCallback((async({chatId:e=null}={})=>{e||(e=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()),await setChatId(e),localStorageKey&&localStorage.removeItem(localStorageKey),resetMessages(),setInputText(""),setIsResumingConversation(!1),setIsConversationLoaded(!0),initialShortcuts.length>0?handleShortcuts(initialShortcuts):setShortcuts([]),setBlocks([]),setPreviousResponseId(null)}),[botId,initialShortcuts,handleShortcuts]),onStartRealtimeSession=useCallback((async(e="hands-free")=>{const t={botId,customId,contextId,chatId,talkMode:e},a=restNonceRef.current??await refreshRestNonce(),n=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/start`,t,a);return await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,null,null,null,debugMode)}),[botId,customId,contextId,chatId,restNonce,refreshRestNonce,restUrl]),onCommitStats=useCallback((async(e,t=null)=>{try{const a=restNonceRef.current??await refreshRestNonce(),n=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/stats`,{botId,session:sessionId,refId:t||chatId,stats:e},a),l=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,null,null,null,debugMode);return{success:l.success,message:l.message,overLimit:l.overLimit||!1,limitMessage:l.limitMessage||null}}catch(e){return console.error("Error while committing stats.",e),{success:!1,message:__("An error occurred while committing the stats.")}}}),[botId,restNonce,refreshRestNonce,restUrl,sessionId,chatId]),onCommitDiscussions=useCallback((async(e=[])=>{try{const t=restNonceRef.current??await refreshRestNonce(),a={botId,session:sessionId,chatId,messages:(e??[]).filter((e=>"error"!==e.role&&!e.isError))},n=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/discussions`,a,t),l=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,null,null,null,debugMode);return{success:l.success,message:l.message}}catch(e){return console.error("Error while committing discussion.",e),{success:!1,message:__("An error occurred while committing the discussion.")}}}),[botId,chatId,restNonce,refreshRestNonce,restUrl,sessionId]),onRealtimeFunctionCallback=useCallback((async(functionId,functionType,functionName,functionTarget,args)=>{const body={functionId,functionType,functionName,functionTarget,arguments:args};if("js"!==functionTarget){const e=restNonceRef.current??await refreshRestNonce(),t=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/call`,body,e),a=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(t,null,null,null,debugMode);return a}{const finalArgs=args?Object.values(args).map((e=>JSON.stringify(e))):[];try{return debugMode&&console.log(`[CHATBOT] CALL ${functionName}(${finalArgs.join(", ")})`),eval(`${functionName}(${finalArgs.join(", ")})`),{success:!0,message:"The function was executed",data:null}}catch(e){return console.error("Error while executing an action.",e),{success:!1,message:__("An error occurred while executing the function."),data:null}}}}),[restNonce,refreshRestNonce,restUrl,debugMode]),onSubmit=useCallback((async(e,t={})=>{var a;const{shortcutId:n=null,displayText:l=null}=t;if(locked)return void console.warn("AI Engine: Chatbot is locked (e.g., GDPR consent required).");if(busy)return void console.error("AI Engine: There is already a query in progress.");"string"!=typeof e&&(e=inputText);const o=uploadedFile,r=multiUpload?uploadedFiles:[],i=(0,_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_1__.W5)("user.query",e,{chatId,botId,customId,files:r,messageCount:messages.length});if(!i&&0!==i&&!n)return;e=i;const s=null==uploadedFile?void 0:uploadedFile.uploadedUrl,c=null==uploadedFile||null===(a=uploadedFile.localFile)||void 0===a?void 0:a.type,d=!!c&&c.startsWith("image");let m=l||e,u=[],p=[];if(multiUpload&&r.length>0){const t=[];r.forEach((e=>{var a;const n=null===(a=e.localFile)||void 0===a?void 0:a.type;var l,o;!!n&&n.startsWith("image")?u.push(e.uploadedUrl):(p.push({name:(null===(l=e.localFile)||void 0===l?void 0:l.name)||"Uploaded File",url:e.uploadedUrl}),t.push(`[${(null===(o=e.localFile)||void 0===o?void 0:o.name)||"Uploaded File"}](${e.uploadedUrl})`))})),t.length>0&&(m=`${t.join(" ")}\n\n${e}`)}else s&&(d?u.push(s):(p.push({name:"Uploaded File",url:s}),m=`[Uploaded File](${s})\n\n${e}`));setBusy(!0),setInputText(""),setShortcuts([]),setBlocks([]),resetUploadedFile(),multiUpload&&resetUploadedFiles();const g=[...messages,{id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"user",content:m,who:rawUserName,timestamp:(new Date).getTime(),...u.length>0&&{userImages:u},...l&&{shortcutName:l}}];saveMessages(g);const E=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),h=[...g,{id:E,role:"assistant",content:stream?"":null,who:rawAiName,timestamp:null,isQuerying:!stream,isStreaming:!!stream,streamEvents:stream&&(debugMode||eventLogs)?[]:void 0}];if(setMessages(h),"[ERROR]"===e){setBusy(!1);const t=messages.slice(0,-1);setMessages(t);const a=[__("Connection timeout: The server took too long to respond."),__("Invalid API key: Please check your OpenAI API key in settings."),__("Rate limit exceeded: Too many requests. Please try again later."),__("Model overloaded: The AI model is currently experiencing high demand."),__("Network error: Failed to establish connection to the AI service."),__("Authentication failed: Your session has expired. Please refresh the page."),__("Service unavailable: The AI service is temporarily down for maintenance."),__("Invalid request: The message format was not recognized by the server."),__("Quota exceeded: You have reached your usage limit for this period."),__("Internal server error: An unexpected error occurred. Please try again.")],n=a[Math.floor(Math.random()*a.length)],l={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"error",content:`[TEST ERROR] ${n}`,who:"Error",timestamp:(new Date).getTime(),isError:!0,failedQuery:{text:e,file:o}},r=[...g,l];return setMessages(r),saveMessages(r),void setLastFailedQuery({text:e,file:o})}const R={botId,customId,session:sessionId,chatId,contextId,messages:messages.filter((e=>"error"!==e.role&&!e.isError)),newMessage:n?"":e,newFileId:multiUpload?null:null==o?void 0:o.uploadedId,newFileIds:multiUpload?r.map((e=>e.uploadedId)).filter((e=>e)):null,stream,...atts};n&&(R.shortcutId=n,l&&(R.shortcutName=l)),previousResponseId&&(R.previousResponseId=previousResponseId);try{debugMode&&console.log("[CHATBOT] OUT: ",R);const e=stream?(e,t)=>{debugMode&&t&&t.subtype&&console.log("[CHATBOT] STREAM EVENT:",t),setMessages((a=>{const n=[...a],l=n.length>0?n[n.length-1]:null;return l&&l.id===E&&(l.content=e,l.timestamp=(new Date).getTime(),t&&t.subtype&&(l.streamEvents||(l.streamEvents=[]),l.streamEvents.push({...t,timestamp:(new Date).getTime()}))),n}))}:null,t=restNonceRef.current??await refreshRestNonce();stream&&(debugMode||eventLogs)&&e&&e("",{type:"event",subtype:"status",data:"Request sent...",timestamp:(new Date).getTime()});const a=e=>{setRestNonce(e),restNonceRef.current=e,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_3__.A.setToken(e)},n=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/chats/submit`,R,t,stream,void 0,a),l=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,e,debugMode?"CHATBOT":null,a,debugMode);if(!l.success&&l.message){const e=[...h];e.pop();const t=e.length-1;let a=null,n=null;if(t>=0&&"user"===e[t].role){const l=e[t].content,r=l.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);a=r?r[1]:l,r&&(n=o)}return setMessages(e),saveMessages(e),addErrorMessage(l.message,a?{text:a,file:n}:null),void setBusy(!1)}setServerReply(l)}catch(e){console.error("An error happened in the handling of the chatbot response.",{err:e}),setBusy(!1),setMessages((e=>{const t=e[e.length-1];return!t||"assistant"!==t.role||""!==t.content&&null!==t.content?e:e.slice(0,-1)}));const t=messages.length;let a=null,n=null;if(t>=0&&"user"===h[t].role){const e=h[t].content,l=e.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);a=l?l[1]:e,l&&(n=o)}addErrorMessage(e.message||__("An error occurred while processing your request. Please try again."),a?{text:a,file:n}:null)}}),[locked,busy,uploadedFile,uploadedFiles,multiUpload,messages,saveMessages,stream,botId,customId,sessionId,chatId,contextId,atts,inputText,debugMode,restNonce,refreshRestNonce,restUrl]),onSubmitAction=useCallback(((e=null)=>{var t;if(locked)return void console.warn("AI Engine: Chatbot is locked (e.g., GDPR consent required).");const a=!(null==uploadedFile||!uploadedFile.uploadedId);hasFocusRef.current=(null===(t=chatbotInputRef.current)||void 0===t?void 0:t.currentElement)&&document.activeElement===chatbotInputRef.current.currentElement(),e?onSubmit(e):(a||inputText.length>0)&&onSubmit(inputText)}),[locked,inputText,onSubmit,null==uploadedFile?void 0:uploadedFile.uploadedId]),retryLastQuery=useCallback((()=>{var e;lastFailedQuery&&(setInputText(lastFailedQuery.text),lastFailedQuery.file&&setUploadedFile(lastFailedQuery.file),setLastFailedQuery(null),null!==(e=chatbotInputRef.current)&&void 0!==e&&e.focusInput&&setTimeout((()=>{chatbotInputRef.current.focusInput()}),100))}),[lastFailedQuery,setInputText,chatbotInputRef]),onFileUpload=async(e,t="N/A",a="N/A")=>{try{if(null===e)return void resetUploadedFile();const n={type:t,purpose:a},l=`${restUrl}/mwai-ui/v1/files/upload`,o=restNonceRef.current??await refreshRestNonce(),r=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.uE)(l,e,o,(t=>{setUploadedFile({localFile:e,uploadedId:null,uploadedUrl:null,uploadProgress:t})}),n);setUploadedFile({localFile:e,uploadedId:r.data.id,uploadedUrl:r.data.url,uploadProgress:null})}catch(e){console.error("onFileUpload Error",e),addErrorMessage(e.message||"An unknown error occurred"),resetUploadedFile()}},onUploadFile=async e=>(setMessages((e=>e.filter((e=>!e.isError)))),onFileUpload(e)),resetUploadedFile=()=>{setUploadedFile({localFile:null,uploadedId:null,uploadedUrl:null,uploadProgress:null})},addUploadedFile=e=>{setUploadedFiles((t=>[...t,e]))},removeUploadedFile=e=>{setUploadedFiles((t=>t.filter(((t,a)=>a!==e))))},resetUploadedFiles=()=>{setUploadedFiles([])},onMultiFileUpload=async(e,t="N/A",a="N/A")=>{const n=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)();try{if(null===e)return;const l=maxUploads||5;if(uploadedFiles.length>=l)return void addErrorMessage(__(`Maximum upload limit reached (${l} files). Please remove some files before uploading more.`));const o={type:t,purpose:a},r=`${restUrl}/mwai-ui/v1/files/upload`;addUploadedFile({localFile:e,uploadedId:null,uploadedUrl:null,uploadProgress:0,tempId:n});const i=restNonceRef.current??await refreshRestNonce(),s=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.uE)(r,e,i,(e=>{setUploadedFiles((t=>t.map((t=>t.tempId===n?{...t,uploadProgress:e}:t))))}),o);setUploadedFiles((t=>t.map((t=>t.tempId===n?{localFile:e,uploadedId:s.data.id,uploadedUrl:s.data.url,uploadProgress:null,tempId:n}:t))))}catch(e){console.error("onMultiFileUpload Error",e),addErrorMessage(e.message||"An unknown error occurred"),setUploadedFiles((e=>e.filter((e=>e.tempId!==n))))}},runTimer=useCallback((()=>{const e=setTimeout((()=>{setOpen((e=>(e||setShowIconMessage(!0),e)))}),1e3*iconTextDelay);return()=>clearTimeout(e)}),[iconText,iconTextDelay]);useEffect((()=>{if(iconText&&!iconTextDelay)setShowIconMessage(!0);else if(iconText&&iconTextDelay)return runTimer()}),[iconText]);const[tasks,setTasks]=useState([]),runTasks=useCallback((async()=>{if(tasks.length>0){const e=tasks[0];if("ask"===e.action){const{text:t,submit:a}=e.data;a?onSubmit(t):setInputText(t)}else if("toggle"===e.action)setOpen((e=>!e));else if("open"===e.action)setOpen(!0);else if("close"===e.action)setOpen(!1);else if("clear"===e.action){const{chatId:t}=e.data;onClear({chatId:t})}else if("setContext"===e.action){const{chatId:t,messages:a,previousResponseId:n}=e.data;setChatId(t),setMessages(a),n&&setPreviousResponseId(n),setIsResumingConversation(!0),setIsConversationLoaded(!0),setShortcuts([]),saveMessages(a)}else if("setShortcuts"===e.action){const t=e.data;handleShortcuts(t)}else if("setBlocks"===e.action){const t=e.data;handleBlocks(t)}else if("addBlock"===e.action){const t=e.data;setBlocks((e=>[...e,t]))}else if("removeBlockById"===e.action){const t=e.data;setBlocks((e=>e.filter((e=>e.id!==t))))}setTasks((e=>e.slice(1)))}}),[tasks,onClear,onSubmit,setChatId,setInputText,setMessages,setOpen,handleShortcuts,handleBlocks]);useEffect((()=>{runTasks()}),[runTasks]);const updateComponentConfig=e=>{void 0!==e.containerType&&setContainerType(e.containerType),void 0!==e.headerType&&setHeaderType(e.headerType),void 0!==e.contentType&&setContentType(e.contentType),void 0!==e.footerType&&setFooterType(e.footerType)},actions={setInputText,saveMessages,setMessages,resetMessages,setError,resetError,addErrorMessage,retryLastQuery,onClear,onSubmit,onSubmitAction,onFileUpload,onUploadFile,resetUploadedFile,setUploadedFile,onMultiFileUpload,addUploadedFile,removeUploadedFile,resetUploadedFiles,setUploadedFiles,setOpen,setOpening,setClosing,setWindowed,setShowIconMessage,setIsListening,setDraggingType,setIsBlocked,onStartRealtimeSession,onRealtimeFunctionCallback,onCommitStats,onCommitDiscussions,updateComponentConfig},state={theme,params,botId,customId,userData,pluginUrl,inputText,messages,shortcuts,blocks,busy,error,setBusy,typewriter,speechRecognition,speechSynthesis,localMemory,isRealtime,fileUpload,multiUpload,maxUploads,uploadedFile,uploadedFiles,fileSearch,allowedMimeTypes,textSend,textClear,textInputMaxLength,textInputPlaceholder,textCompliance,aiName,userName,guestName,aiAvatar,userAvatar,guestAvatar,aiAvatarUrl,userAvatarUrl,guestAvatarUrl,isWindow,copyButton,pdfButton,headerSubtitle,popupTitle,fullscreen,icon,iconText,iconAlt,iconPosition,iconSize,centerOpen,width,openDelay,iconBubble,windowAnimation,cssVariables,iconUrl,chatbotInputRef,conversationRef,isMobile,open,opening,closing,locked,windowed,showIconMessage,timeElapsed,isListening,speechRecognitionAvailable,uploadIconPosition,submitButtonConf,draggingType,isBlocked,busyNonce,debugMode,eventLogs,system,containerType,headerType,messagesType,inputType,footerType};return React.createElement(ChatbotContext.Provider,{value:{state,actions}},children)}},6422(e,t,a){a.d(t,{HX:()=>l,W5:()=>o});class n{constructor(){if("undefined"!=typeof window&&window.MwaiAPI)return window.MwaiAPI;this.chatbots=[],this.forms=[],this.filters={},this.actions={},"undefined"!=typeof window&&(window.MwaiAPI=this)}getChatbot(e=null){return e?this.chatbots.find((t=>t.botId===e||t.customId===e)):this.chatbots[0]}getForm(e=null){return e?this.forms.find((t=>t.formId===e)):this.forms[0]}addFilter(e,t,a=10){this.filters[e]||(this.filters[e]=[]),this.filters[e].push({callback:t,priority:a}),this.filters[e].sort(((e,t)=>e.priority-t.priority))}applyFilters(e,t,...a){return this.filters[e]?this.filters[e].reduce(((e,t)=>t.callback(e,...a)),t):t}addAction(e,t,a=10){this.actions[e]||(this.actions[e]=[]),this.actions[e].push({callback:t,priority:a}),this.actions[e].sort(((e,t)=>e.priority-t.priority))}doAction(e,...t){this.actions[e]&&this.actions[e].forEach((e=>{e.callback(...t)}))}clearCookies(){document.cookie="mwai_gdpr_accepted=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";document.cookie.split(";").forEach((e=>{const[t]=e.trim().split("=");t.startsWith("mwai_")&&(document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`)}))}}const l=(()=>{if("undefined"!=typeof window&&window.MwaiAPI)return window.MwaiAPI;const e=new n;return"undefined"!=typeof window&&(window.MwaiAPI=e),e})(),o=(e,t,...a)=>l.applyFilters(e,t,...a)},7437(e,t,a){a.d(t,{Mc:()=>g,Vw:()=>R,_$:()=>h,bE:()=>f,dh:()=>p,gR:()=>m,mv:()=>u,tm:()=>d,ux:()=>y});var n=a(6046);function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;tReact.createElement("div",l({active:e?"true":"false",disabled:t},a),React.createElement(n.A,{size:"24"}));const m=()=>r((()=>(e,t)=>(Array.isArray(e)||(e=[e]),t&&Object.entries(t).forEach((([t,a])=>{a&&e.push(t)})),e.join(" "))),[]);function u(e){return!(!e||"string"!=typeof e)&&0===e.indexOf("http")}function p(){const[e,t]=o(null),a=s(null);function n(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`}return i((()=>()=>{clearInterval(a.current)}),[]),{timeElapsed:e,startChrono:function(){if(null!==a.current)return;const e=Date.now();t(n(0)),a.current=setInterval((()=>{const a=Math.floor((Date.now()-e)/1e3);t(n(a))}),500)},stopChrono:function(){clearInterval(a.current),a.current=null,t(null)}}}const g=(e,t)=>"string"==typeof e&&t?(Object.entries(t).forEach((([t,a])=>{e=e.replace(new RegExp(`{${t}}`,"g"),(()=>a))})),e):e,E=(e,t="")=>"string"==typeof e?e.trim():t,h=(e,t=[])=>{const a=E(e.guestName),n=E(e.textSend),l=E(e.textClear),o=parseInt(e.textInputMaxLength),r=E(e.textInputPlaceholder);let i=E(e.textCompliance),s="",c="";const d=Boolean(e.window),m=Boolean(e.copyButton),u=void 0===e.pdfButton||Boolean(e.pdfButton),p=Boolean(e.fullscreen),h=E(e.icon);let R=E(e.iconText);const f=parseInt(e.iconTextDelay||1),y=E(e.iconAlt),v=E(e.iconPosition),b=E(e.iconSize),w=Boolean(e.centerOpen),_=E(e.width),C=E(e.maxHeight),A=e.openDelay?parseInt(e.openDelay):null,T=Boolean(e.iconBubble),I=E(e.windowAnimation,"zoom"),N=E(e.aiName),x=E(e.userName),O=Boolean(null==e?void 0:e.aiAvatar),k=Boolean(null==e?void 0:e.userAvatar),S=Boolean(null==e?void 0:e.guestAvatar),M=O?E(null==e?void 0:e.aiAvatarUrl):null,P=k?E(null==e?void 0:e.userAvatarUrl):null,L=S?E(null==e?void 0:e.guestAvatarUrl):null,D=Boolean(e.localMemory),F=Boolean(e.fileUpload||e.imageUpload),U=Boolean(e.multiUpload),B=e.maxUploads?parseInt(e.maxUploads):1,$=Boolean(e.fileSearch),H=E(e.allowedMimeTypes),j=E(e.mode,"chat");return s=null===e.headerSubtitle||void 0===e.headerSubtitle?"Discuss with":E(e.headerSubtitle),c="string"==typeof e.popupTitle?e.popupTitle.trim():null,t&&(i=g(i,t),R=g(R,t)),{textSend:n,textClear:l,textInputMaxLength:o,textInputPlaceholder:r,textCompliance:i,mode:j,window:d,copyButton:m,pdfButton:u,fullscreen:p,localMemory:D,fileUpload:F,multiUpload:U,maxUploads:B,fileSearch:$,allowedMimeTypes:H,icon:h,iconText:R,iconTextDelay:f,iconAlt:y,iconPosition:v,iconSize:b,centerOpen:w,width:_,maxHeight:C,openDelay:A,iconBubble:T,windowAnimation:I,headerSubtitle:s,popupTitle:c,aiName:N,userName:x,guestName:a,aiAvatar:O,userAvatar:k,guestAvatar:S,aiAvatarUrl:M,userAvatarUrl:P,guestAvatarUrl:L}},R=e=>{const[t,a]=o(!1),[n,l]=o(!1);return i((()=>{"undefined"!=typeof window&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)&&l(!0)}),[]),i((()=>{if(!n)return;const l=new(window.SpeechRecognition||window.webkitSpeechRecognition);let o=null;return navigator.userAgent.toLowerCase().indexOf("android")>-1?(l.interimResults=!1,l.continuous=!1,o=t=>{const n=Array.from(t.results).filter((e=>e.isFinal)).map((e=>e[0].transcript)).join("");e(n),a(!1)}):(l.interimResults=!0,l.continuous=!0,o=t=>{const a=Array.from(t.results).map((e=>e[0])).map((e=>e.transcript)).join("");e(a)}),t?(l.addEventListener("result",o),l.start()):(l.removeEventListener("result",o),l.abort()),()=>{l.abort()}}),[t,n]),{isListening:t,setIsListening:a,speechRecognitionAvailable:n}},f=({if:e,className:t,disableTransition:a=!1,children:n,...r})=>{const[s,c]=o(!1),[d,m]=o("mwai-transition");i((()=>{a?c(e):e?(c(!0),setTimeout((()=>{m("mwai-transition mwai-transition-visible")}),150)):m("mwai-transition")}),[e,a]);return s?React.createElement("div",l({className:`${t} ${a?"":d}`,onTransitionEnd:()=>{"mwai-transition"!==d||a||c(!1)}},r),n):null},y=(e,t)=>{i((()=>{if(!t||"undefined"==typeof window||!window.visualViewport||!e)return;const a=window.visualViewport,n=()=>{const t=document.getElementById(e);if(!t)return;const n=Math.max(0,a.offsetTop||0),l=Math.max(0,window.innerHeight-a.height-(a.offsetTop||0));t.style.setProperty("--mwai-vv-offset-top",`${n}px`),t.style.setProperty("--mwai-vv-offset-bottom",`${l}px`),t.style.setProperty("--mwai-vv-height",`${a.height}px`)};return n(),a.addEventListener("resize",n),a.addEventListener("scroll",n),()=>{var t;a.removeEventListener("resize",n),a.removeEventListener("scroll",n),(t=document.getElementById(e))&&(t.style.removeProperty("--mwai-vv-offset-top"),t.style.removeProperty("--mwai-vv-offset-bottom"),t.style.removeProperty("--mwai-vv-height"))}}),[e,t])}},2509(e,t,a){a.d(t,{CI:()=>g,F1:()=>s,Pn:()=>c,Ve:()=>h,rn:()=>p,ti:()=>d,uE:()=>m,vx:()=>u});var n=a(5907);const{useMemo:l,useEffect:o,useState:r}=wp.element;let i=null;try{i=a(3233).A}catch(e){i={ERRORS:{COULD_NOT_PARSE_ERROR_STREAM:"Could not parse the 'error' stream.",COULD_NOT_PARSE_END_STREAM:"Could not parse the 'end' stream.",SESSION_EXPIRED:"Your session has expired. Please refresh the page to continue using AI Engine."}}}function s(e,t=null,a=!0){const n=[];return JSON.stringify(e,((e,t)=>{if("object"==typeof t&&null!==t){if(n.includes(t)){if(!a)throw console.warn("Circular reference found.",{key:e,value:t,cache:n,cacheIndex:n.indexOf(t)}),new Error("Circular reference found. Cancelled.");return}n.push(t)}return t}),t)}async function c(e,t,a=null,n=null,l=!1){if(!t){let t;try{return t=await e.json(),a&&console.log(`[${a}] IN: `,t),t.new_token&&(l&&console.log("[MWAI] Token refreshed!"),n&&n(t.new_token)),t}catch(e){return console.error("Could not parse the regular response.",{err:e,data:t}),{success:!1,message:"Could not parse the regular response."}}}const o=e.body.getReader(),r=new TextDecoder("utf-8");let s="",c="";for(;;){const{value:e,done:d}=await o.read();if(s+=r.decode(e,{stream:!0}),d)break;const m=s.split("\n");for(let e=0;e{const i=new FormData;i.append("file",t);for(const[e,t]of Object.entries(l))i.append(e,t);const s=new XMLHttpRequest;s.open("POST",e,!0),a&&s.setRequestHeader("X-WP-Nonce",a),s.upload.onprogress=function(e){if(e.lengthComputable&&n){const t=e.loaded/e.total*100;n(t)}},s.onload=function(){if(s.status>=200&&s.status<300)try{const e=JSON.parse(s.responseText);o(e)}catch(e){r({status:s.status,statusText:s.statusText,error:"The server response is not valid JSON"})}else{try{const e=JSON.parse(s.responseText);return void r({status:s.status,message:e.message})}catch(e){}r({status:s.status,statusText:s.statusText})}},s.onerror=function(){r({status:s.status,statusText:s.statusText})},s.send(i)}))}function u(){return Math.random().toString(36).substring(2)}const p=()=>{const[e,t]=r(!0);o((()=>{const e=setTimeout((()=>{const e=setInterval((()=>{t((e=>!e))}),500);return()=>clearInterval(e)}),200);return()=>clearTimeout(e)}),[]);const a={opacity:e?1:0,width:"1px",height:"1em",borderLeft:"8px solid",marginLeft:"2px"};return React.createElement("span",{style:a})},g=e=>{const{content:t,error:a,isStreaming:o,baseClass:r="mwai-output-handler"}=e;let i=(!!a?a:t)??"";(i.match(/```/g)||[]).length%2!=0?i+="\n```":o&&(i+=""),i=(e=>{if("string"!=typeof e)return e;let t=e;const a=[];t=t.replace(/```[\s\S]*?```/g,(e=>(a.push(e),`__CODE_BLOCK_${a.length-1}__`)));const n=[];return t=t.replace(/`[^`]+`/g,(e=>(n.push(e),`__INLINE_CODE_${n.length-1}__`))),t=t.replace(/(?{t=t.replace(`__CODE_BLOCK_${a}__`,(()=>e))})),n.forEach(((e,a)=>{t=t.replace(`__INLINE_CODE_${a}__`,(()=>e))})),t})(i);const s=l((()=>{const e=[r];return a&&e.push("mwai-error"),e}),[a]),c=l((()=>({wrapper:"div",forceWrapper:!0,breaks:!0,overrides:{BlinkingCursor:{component:p},a:{props:{target:"_blank"}}}})),[]);return React.createElement(n.Ay,{options:c,className:s.join(" "),children:i})},E=/([\u2700-\u27BF]|[\uE000-\uF8FF]|[\uD800-\uDFFF]|[\uFE00-\uFE0F]|[\u1F100-\u1F1FF]|[\u1F200-\u1F2FF]|[\u1F300-\u1F5FF]|[\u1F600-\u1F64F]|[\u1F680-\u1F6FF]|[\u1F700-\u1F77F]|[\u1F780-\u1F7FF]|[\u1F800-\u1F8FF]|[\u1F900-\u1F9FF]|[\u1FA00-\u1FA6F])/;function h(e){return e&&2===e.length&&E.test(e)}},6523(e,t,a){a.d(t,{UT:()=>o,zM:()=>l});var n=a(1594);const l=()=>{const[e,t]=(0,n.useState)(!1),[a,l]=(0,n.useState)(!1),[o,r]=(0,n.useState)(!1),[i,s]=(0,n.useState)(!1),[c,d]=(0,n.useState)(0),[m,u]=(0,n.useState)(0),[p,g]=(0,n.useState)([]),E=(0,n.useRef)(!1),h=(0,n.useRef)(null),R=(0,n.useRef)(null),f=(0,n.useCallback)((async(e,a={})=>{const{onProgress:n=null,onError:i=null,delayBetweenTasks:c=100}=a,m=`op_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;R.current=m,E.current=!1,h.current=new AbortController,l(!1),t(!0),r(!1),s(!1),d(0),u(e.length),g([]);const p={completed:0,errors:[],stopped:!1,aborted:!1};try{for(let t=0;t[...e,a])),i&&i(a)}const a=t+1;d(a),n&&n(a,e.length),t0&&await new Promise((e=>setTimeout(e,c)))}}finally{E.current&&p.stopped?(r(!1),s(!0),setTimeout((()=>{t(!1),s(!1)}),1e3)):(t(!1),r(!1)),h.current=null,E.current=!1,R.current=null}return p}),[]),y=(0,n.useCallback)((()=>{l(!0),t(!1),r(!1),s(!1),d(0),u(0),g([]),E.current=!1}),[]),v=(0,n.useCallback)((()=>(console.log("[AsyncProcessor] Soft stop requested"),E.current=!0,r(!0),Promise.resolve())),[]),b=(0,n.useCallback)((()=>{if(console.log("[AsyncProcessor] Hard stop requested"),E.current=!0,R.current=null,h.current)try{h.current.abort()}catch(e){}return t(!1),l(!1),r(!1),s(!1),new Promise((e=>setTimeout(e,100)))}),[]),w=(0,n.useCallback)((()=>{if(t(!1),l(!1),r(!1),s(!1),d(0),u(0),g([]),E.current=!1,R.current=null,h.current){try{h.current.abort()}catch(e){}h.current=null}}),[]);return{isProcessing:e,isPreparing:a,isStopping:o,justStopped:i,progress:c,total:m,errors:p,processTasks:f,startPreparing:y,stop:v,hardStop:b,reset:w,percentage:m>0?Math.round(c/m*100):0,isActive:e||a||i,variant:o?"danger":i?"info":null}},o=(e,t={})=>async(t,a)=>{if(t&&t.aborted)return{success:!0};try{return await e(t,a)}catch(e){var n,l;if("AbortError"===e.name||null!==(n=e.message)&&void 0!==n&&n.includes("abort")||null!==(l=e.message)&&void 0!==l&&l.includes("cancelled"))return{success:!0};throw e}}},9328(e,t,a){a.d(t,{A:()=>l});const n=new class{constructor(){this.token=null,this.listeners=new Set}setToken(e){this.token!==e&&(this.token=e,this.notifyListeners())}getToken(){return this.token}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach((e=>e(this.token)))}};"undefined"!=typeof window&&window.mwai&&window.mwai.rest_nonce&&n.setToken(window.mwai.rest_nonce);const l=n},218(e,t,a){var n=a(5091),l=a(3773),o=a(5373),r=a(4377),i=a(4583),s=a(1317),c=a(1854),d=a(9804),m=a(9649),u=a(4764),p=a(9330),g=a(3646),E=a(9390),h=a(3447),R=a(1863),f=a(4588),y=a(1947),v=a(6847),b=a(6416),w=a(5396);const _=w.Ay.div` color: rgba(255, 255, 255, 0.92); padding: 18px 20px 8px; margin-bottom: -6px; a { color: #7dedff; text-decoration: none; } p { font-size: 13px; line-height: 1.55; margin: 0; } p + p { margin-top: 6px; } `,C=w.Ay.div` display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; margin-top: 22px; padding: 0 4px 6px; @media (max-width: 780px) { grid-template-columns: 1fr; } `,A=w.Ay.div` position: relative; display: flex; flex-direction: column; background: linear-gradient(135deg, rgba(255, 255, 255, 0.10) 0%, rgba(255, 255, 255, 0.04) 100%); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); border: 1px solid rgba(255, 255, 255, 0.18); border-radius: 14px; box-shadow: 0 4px 14px rgba(0, 0, 0, 0.14); transition: transform 0.22s var(--neko-ease-out, ease-out), box-shadow 0.22s var(--neko-ease-out, ease-out), background 0.22s var(--neko-ease-out, ease-out), border-color 0.22s var(--neko-ease-out, ease-out); overflow: hidden; &::before { content: ''; position: absolute; inset: 0; background: radial-gradient(ellipse at top left, rgba(255, 255, 255, 0.10), transparent 60%); pointer-events: none; } &:hover { transform: translateY(-2px); background: linear-gradient(135deg, rgba(255, 255, 255, 0.18) 0%, rgba(255, 255, 255, 0.08) 100%); border-color: rgba(255, 255, 255, 0.32); box-shadow: 0 14px 30px rgba(0, 0, 0, 0.22), 0 0 0 1px rgba(255, 255, 255, 0.10) inset; } .tile-top { display: flex; align-items: center; gap: 18px; padding: 18px 20px 16px; flex: 1 1 auto; } .tile-icon { flex: 0 0 auto; display: block; width: 88px; height: 88px; transition: transform 0.25s var(--neko-ease-out, ease-out); img { width: 100%; height: 100%; border-radius: 16px; object-fit: cover; display: block; box-shadow: 0 6px 16px rgba(0, 0, 0, 0.22); } } &:hover .tile-icon { transform: scale(1.05) rotate(-2deg); } .tile-body { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; justify-content: center; gap: 6px; position: relative; } .tile-body h3 { margin: 0; font-size: 16px; font-weight: 700; line-height: 1.2; letter-spacing: 0; } .tile-body h3 a { color: white; text-decoration: none; } .tile-body h3 a:hover { color: rgba(255, 255, 255, 0.85); } .tile-status { position: absolute; top: 12px; right: 12px; z-index: 2; display: inline-flex; align-items: center; gap: 5px; font-size: 9.5px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; padding: 3px 8px 3px 7px; border-radius: 999px; line-height: 1; backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); } .tile-status .dot { width: 6px; height: 6px; border-radius: 50%; box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.08); } .tile-status.active { background: rgba(43, 182, 115, 0.18); color: #b6f5d4; border: 1px solid rgba(43, 182, 115, 0.42); } .tile-status.active .dot { background: #2bd47d; box-shadow: 0 0 0 2px rgba(43, 212, 125, 0.25), 0 0 8px rgba(43, 212, 125, 0.6); } .tile-status.inactive { background: rgba(255, 255, 255, 0.10); color: rgba(255, 255, 255, 0.78); border: 1px solid rgba(255, 255, 255, 0.22); } .tile-status.inactive .dot { background: rgba(255, 255, 255, 0.55); } &.is-active { border-color: rgba(43, 182, 115, 0.32); box-shadow: 0 4px 14px rgba(0, 0, 0, 0.14), 0 0 0 1px rgba(43, 182, 115, 0.18) inset; } &.is-active:hover { border-color: rgba(43, 182, 115, 0.5); } .tile-desc { margin: 0; font-size: 12.5px; line-height: 1.45; color: rgba(255, 255, 255, 0.78); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } .tile-actions { display: grid; grid-template-columns: 1fr 1fr; border-top: 1px solid rgba(255, 255, 255, 0.14); position: relative; z-index: 1; } .tile-actions a { padding: 11px 12px; text-align: center; font-size: 11px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; text-decoration: none; transition: background 0.15s var(--neko-ease-out, ease-out), color 0.15s var(--neko-ease-out, ease-out); } .tile-actions a.free { color: #b6f5d4; border-right: 1px solid rgba(255, 255, 255, 0.14); } .tile-actions a.free:hover { background: rgba(43, 182, 115, 0.20); color: white; } .tile-actions a.pro { color: #ffd98a; } .tile-actions a.pro:hover { background: rgba(255, 184, 60, 0.20); color: white; } `,T=w.Ay.div` display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 14px; margin: 18px 4px 6px; `,I=w.Ay.a` position: relative; display: flex; align-items: center; gap: 14px; padding: 14px 16px; background: linear-gradient(135deg, rgba(255, 255, 255, 0.10) 0%, rgba(255, 255, 255, 0.04) 100%); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); border: 1px solid rgba(255, 255, 255, 0.18); border-radius: 12px; text-decoration: none; box-shadow: 0 3px 10px rgba(0, 0, 0, 0.12); transition: transform 0.2s var(--neko-ease-out, ease-out), box-shadow 0.2s var(--neko-ease-out, ease-out), background 0.2s var(--neko-ease-out, ease-out), border-color 0.2s var(--neko-ease-out, ease-out); overflow: hidden; &:hover { transform: translateY(-2px); background: linear-gradient(135deg, rgba(255, 255, 255, 0.18) 0%, rgba(255, 255, 255, 0.08) 100%); border-color: rgba(255, 255, 255, 0.32); box-shadow: 0 10px 24px rgba(0, 0, 0, 0.20); } .article-emoji { flex: 0 0 auto; width: 44px; height: 44px; display: flex; align-items: center; justify-content: center; font-size: 22px; border-radius: 12px; background: rgba(255, 255, 255, 0.10); border: 1px solid rgba(255, 255, 255, 0.14); } .article-body { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 2px; } .article-title { color: white; font-size: 14px; font-weight: 600; line-height: 1.25; letter-spacing: 0; } .article-blurb { color: rgba(255, 255, 255, 0.7); font-size: 12px; line-height: 1.4; } .article-arrow { flex: 0 0 auto; color: rgba(255, 255, 255, 0.55); font-size: 18px; transition: transform 0.22s var(--neko-ease-out, ease-out), color 0.22s var(--neko-ease-out, ease-out); } &:hover .article-arrow { transform: translateX(3px); color: white; } `,N=w.Ay.div` margin: 15px; .center { background: white; color: black; border-radius: 10px; padding: 10px; max-width: 100% overflow: none; h2 { font-size: 26px; } table { width: 100%; tr td:first-child { width: 220px; font-weight: bold; color: #1e7cba; } * { overflow-wrap: anywhere; } } } hr { border-color: #1e7cba; } `,x=w.Ay.ul` margin-top: 10px; background: rgb(0, 72, 88); padding: 10px; color: rgb(58, 212, 58); max-height: 600px; min-height: 200px; display: block; font-family: monospace; font-size: 12px; white-space: pre; overflow-x: auto; width: calc(100vw - 276px); color: white; .log-date { color: var(--neko-yellow); margin-left: 8px; } .log-type { background: #0000004d; padding: 2px 5px; border-radius: 8px; text-transform: uppercase; } .log-content { display: block; } .log-warning .log-type { background: var(--neko-yellow); color: white; } .log-fatal .log-type { background: var(--neko-red); color: white; } `,{useState:O,useEffect:k}=wp.element,S=`${v.gh}/meow-common/v1`,M=({request:e,title:t,max:a})=>{const[n,l]=O(!1),[o,r]=O([]),i=o.length>0?o.reduce((function(e,t){return e+t})):0,s=o.length>0?Math.ceil(i/o.length):0,d=!o.length&&n;k((()=>{n&&setTimeout((async()=>{const t=(new Date).getTime();await(0,y.IU)(`${S}/${e}`,{method:"POST",nonce:v.ok});const a=(new Date).getTime()-t;r((e=>[...e,a]))}),1e3)}),[o]);return React.createElement(_,{style:{width:200,textAlign:"center"}},React.createElement(c.s,{h2:!0,style:{color:"white"}},t),React.createElement(b.X,{size:200,value:d?a:s,max:a},React.createElement("span",{style:{fontSize:20}},d?"START":s+" ms"),React.createElement("span",{style:{fontSize:12}},d?"YOUR ENGINE":o.length+" requests")),React.createElement(R.M,{style:{width:"100%",marginTop:10},color:n?"#cc3627":"#ccb027",onClick:()=>{n||r([]),l(!n)}},n?"Stop":"Start"))},{useState:P,useEffect:L}=wp.element;v.y0&&v.gh&&v.Hm||console.error("[@common/dashboard] apiUrl, restUrl and pluginUrl are mandatory.");const D=`${v.gh}/meow-common/v1`,F=React.createElement(s.W,null,"Hi! ☀️ Meow Apps isn't your typical plugin suite. It's a passion project led by me, ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://jordymeow.com"},"Jordy Meow"),", and a stellar team. 💕 Based in ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://offbeatjapan.org"},"Japan"),", we focus on making your WordPress experience smoother, faster, and more enjoyable. Ready to level up your site? Check out ",React.createElement("a",{href:"http://meowapps.com",rel:"noreferrer",target:"_blank"},"Meow Apps")," and let's make magic happen! 🌴🙀"),U=[{slug:"ai-engine",name:"AI Engine",icon:"https://ps.w.org/ai-engine/assets/icon-256x256.png",desc:"Your all-in-one AI suite for WordPress: chatbots, content generation, APIs and full REST support."},{slug:"media-cleaner",name:"Media Cleaner",icon:"https://ps.w.org/media-cleaner/assets/icon-256x256.png",desc:"Detect and remove orphan files, unused entries and broken references from your library."},{slug:"database-cleaner",name:"Database Cleaner",icon:"https://ps.w.org/database-cleaner/assets/icon-256x256.png",desc:"A friendly UI for trimming your database, even when it's grown huge."},{slug:"media-file-renamer",name:"Media File Renamer",icon:"https://ps.w.org/media-file-renamer/assets/icon-256x256.png",desc:"Rename and move files manually, automatically or with AI, one by one or in bulk."},{slug:"social-engine",name:"Social Engine",icon:"https://ps.w.org/social-engine/assets/icon-256x256.png",desc:"Schedule and automate posts across every network you care about. Free and unlimited."},{slug:"seo-engine",name:"SEO Engine",icon:"https://ps.w.org/seo-engine/assets/icon-256x256.png",desc:"Tune your content for classic SEO and AI assistants, while staying fast and simple. ✌️"},{slug:"meow-gallery",name:"Meow Gallery",icon:"https://ps.w.org/meow-gallery/assets/icon-256x256.png",desc:"Beautiful, fast galleries with plenty of layouts. A lightweight alternative to bloated plugins. 💕"},{slug:"meow-lightbox",name:"Meow Lightbox",icon:"https://ps.w.org/meow-lightbox/assets/icon-256x256.gif",desc:"A sleek, performant lightbox with full EXIF support."},{slug:"code-engine",name:"Code Engine",icon:"https://ps.w.org/code-engine/assets/icon-256x256.png",desc:"Manage and run snippets, custom functions and integrations directly from WordPress."},{slug:"wp-retina-2x",name:"Perfect Images",icon:"https://ps.w.org/wp-retina-2x/assets/icon-256x256.png",desc:"Retina-ready imagery: manage, optimize and replace every image on your site."},{slug:"wplr-sync",name:"Photo Engine",icon:"https://ps.w.org/wplr-sync/assets/icon-256x256.png",desc:"Organize photos in folders and collections. Sync with Lightroom and speed up your workflow."},{slug:"contact-form-block",name:"Contact Form Block",icon:"https://ps.w.org/contact-form-block/assets/icon-256x256.png",desc:"A simple, fast and efficient contact form. Exactly what you need, nothing more."}],B=(e,t)=>{if(!t)return null;const a=[e,`${e}-pro`];let n=null;for(const e of a){const a=t[e];if("active"===a)return"active";"inactive"===a&&(n="inactive")}return n},$=({plugin:e,installState:t})=>React.createElement(A,{className:t?`is-${t}`:""},"active"===t&&React.createElement("span",{className:"tile-status active"},React.createElement("span",{className:"dot"}),"Installed"),"inactive"===t&&React.createElement("span",{className:"tile-status inactive"},React.createElement("span",{className:"dot"}),"Inactive"),React.createElement("div",{className:"tile-top"},React.createElement("a",{className:"tile-icon",target:"_blank",rel:"noreferrer",href:`https://wordpress.org/plugins/${e.slug}/`},React.createElement("img",{src:e.icon,alt:e.name})),React.createElement("div",{className:"tile-body"},React.createElement("h3",null,React.createElement("a",{target:"_blank",rel:"noreferrer",href:`https://wordpress.org/plugins/${e.slug}/`},e.name)),React.createElement("p",{className:"tile-desc"},e.desc))),React.createElement("div",{className:"tile-actions"},React.createElement("a",{className:"free",target:"_blank",rel:"noreferrer",href:`https://wordpress.org/plugins/${e.slug}/`},"Free"),React.createElement("a",{className:"pro",target:"_blank",rel:"noreferrer",href:`https://meowapps.com/${e.slug}/`},"Pro"))),H=React.createElement(_,null,React.createElement(c.s,{p:!0},"The ",React.createElement("b",null,"Empty Request Time")," measures your installation's basic performance by showing the average time needed to process an empty request on your server. To see how disabling plugins affects the results, turn some off and run the test again. Aim for a time under 2,000 ms, but ideally, keep it below 500 ms. The ",React.createElement("b",null,"File Operation Time")," creates a temporary 10MB file each time it runs. ",React.createElement("b",null,"The SQL Request Time")," calculates the total number of posts. This process should be quick and have a similar duration to the Empty Request Time.")),j=React.createElement(React.Fragment,null,React.createElement(_,null,React.createElement(c.s,{p:!0},"Maintain a streamlined WordPress setup by using essential plugins and a dependable hosting provider. Avoid self-hosting unless you really know what you're doing. Want to dig deeper? Have a read:")),React.createElement(T,null,[{emoji:"🔍",title:"SEO Checklist & Optimization",blurb:"Make your content findable on Google and AI assistants.",href:"https://meowapps.com/tutorial-improve-seo-wordpress/"},{emoji:"⚡️",title:"Optimize Your WordPress Speed",blurb:"Practical tips to make WordPress fast.",href:"https://meowapps.com/tutorial-faster-wordpress-optimize/"},{emoji:"🖼️",title:"Optimize Images (CDN & More)",blurb:"Lighter images, faster pages, happier visitors.",href:"https://meowapps.com/tutorial-optimize-images-wordpress/"},{emoji:"🏠",title:"The Best Hosting Services",blurb:"Pick a host that won't hold your site back.",href:"https://meowapps.com/tutorial-hosting-service-wordpress/"}].map((e=>React.createElement(I,{key:e.href,href:e.href,target:"_blank",rel:"noreferrer"},React.createElement("span",{className:"article-emoji"},e.emoji),React.createElement("span",{className:"article-body"},React.createElement("span",{className:"article-title"},e.title),React.createElement("span",{className:"article-blurb"},e.blurb)),React.createElement("span",{className:"article-arrow"},"→")))))),z=async()=>(await(0,y.IU)(`${D}/all_settings/`,{method:"POST",nonce:v.ok})).data,G=async({value:e,id:t})=>await(0,y.IU)(`${D}/update_option`,{method:"POST",nonce:v.ok,json:{name:t,value:e}}),W=async()=>(await(0,y.IU)(`${D}/installed_plugins/`,{method:"POST",nonce:v.ok})).data||{},q=async()=>(await(0,y.IU)(`${D}/error_logs`,{method:"POST",nonce:v.ok})).data.reverse(),V=()=>{const e=(0,l.jE)(),[t,a]=P(!1),[n,o]=P(""),{data:s,error:y}=(0,r.I)({queryKey:["all_settings"],queryFn:z}),{data:v}=(0,r.I)({queryKey:["installed_plugins"],queryFn:W,staleTime:6e4}),b=(0,i.n)({mutationFn:G,onSuccess:()=>{e.invalidateQueries(["all_settings"])}}),w=(0,i.n)({mutationFn:q}),A=null==s?void 0:s.meowapps_hide_meowapps,T=null==s?void 0:s.force_sslverify;L((()=>{y&&!t&&(a(!0),console.error("Error from useQuery",y.message))}),[y]),L((()=>{const e=document.getElementById("meow-common-phpinfo");e&&o(e.innerHTML)}),[]);const I=(e,t)=>{b.mutate({value:e,id:t})},O=React.createElement(d.d,{title:"Main Menu"},React.createElement(m.E,{max:"1"},React.createElement(u.R,{name:"meowapps_hide_meowapps",label:"Hide (Not Recommended)",description:React.createElement(c.s,{p:!0},"This will hide the Meow Apps Menu (on the left side) and everything it contains. You can re-enable it through though an option that will be added in Settings → General."),value:"1",disabled:b.isPending,checked:A,onChange:I}))),k=React.createElement(d.d,{title:"SSL Verify"},React.createElement(m.E,{max:"1"},React.createElement(u.R,{name:"force_sslverify",label:"Force (Not Recommended)",description:React.createElement(c.s,{p:!0},"This will enforce the usage of SSL when checking the license or updating the plugin."),value:"1",disabled:b.isPending,checked:T,onChange:I})));return React.createElement(p.z,{showRestError:t},React.createElement(g.n,{title:"The Dashboard"}),React.createElement(E.N,null,React.createElement(E.Y,{full:!0},F,React.createElement(h._,{keepTabOnReload:!0},React.createElement(h.V,{title:"Meow Apps"},React.createElement(C,null,[...U].map((e=>({plugin:e,state:B(e.slug,v)}))).sort(((e,t)=>{const a={active:0,inactive:1};return(e.state in a?a[e.state]:2)-(t.state in a?a[t.state]:2)})).map((({plugin:e,state:t})=>React.createElement($,{key:e.slug,plugin:e,installState:t}))))),React.createElement(h.V,{title:"Performance"},H,React.createElement("div",{style:{display:"flex",justifyContent:"space-around",marginBottom:25}},React.createElement(M,{title:"Empty Request Time",request:"empty_request",max:2500}),React.createElement(M,{title:"File Operation Time",request:"file_operation",max:2600}),React.createElement(M,{title:"SQL Request Time",request:"sql_request",max:2800})),j),React.createElement(h.V,{title:"PHP Info"},React.createElement(N,{dangerouslySetInnerHTML:{__html:n}})),React.createElement(h.V,{title:"PHP Error Logs"},React.createElement(_,null,React.createElement(R.M,{style:{marginBottom:10},color:"#ccb027",onClick:()=>{w.mutate()},disabled:w.isPending,isBusy:w.isPending},"Load PHP Error Logs"),React.createElement(x,null,(w.data||[]).map((e=>React.createElement("li",{className:`log-${e.type}`,key:e.id},React.createElement("span",{className:"log-type"},e.type),React.createElement("span",{className:"log-date"},e.date),React.createElement("span",{className:"log-content"},e.content))))),React.createElement(c.s,{p:!0},"If you don't see any errors, your host might not allow remote access to PHP error logs. Contact them for assistance, or look in your hosting control panel."))),React.createElement(h.V,{title:"Settings"},React.createElement(f.z,{title:"Settings",className:"primary"},O,k))))))};var K=a(7080),Y=a(3878),X=a(4228),Q=a(5635),J=a(1928),Z=a(9557),ee=a(4709),te=a(6242),ae=a(8865),ne=a(5930),le=a(9449),oe=a(60),re=a(4928),ie=a(127),se=a(6709),ce=a(1845);const{useState:de,useEffect:me}=wp.element,ue=`${v.gh}/meow-licenser/${v.Pl}/v1`,pe=()=>{const[e,t]=de(!1),[a,n]=de(!1),[l,o]=de(null),[r,i]=de(null),[s,d]=de(""),[m,u]=de(!1),[p,g]=de(!1),E=v.zN&&(!r||"valid"!==r.license),h=async()=>{t(!0);try{(await(0,y.IU)(`${ue}/set_license`,{method:"POST",nonce:v.ok,json:{serialKey:null}})).success&&(d(""),i(null),o("licenseRemoved"))}catch(e){alert("Error while removing the license. Check your console for more information."),console.error(e)}t(!1)},b=async()=>{if("MEOW_OVERRIDE"===s){n(!0);return(0,ce._)()?(i(null),void d("")):void g(!0)}t(!0);try{const e=await(0,y.IU)(`${ue}/set_license`,{method:"POST",nonce:v.ok,json:{serialKey:s}});e.success&&(i(e.data),e.data&&!e.data.issue&&(u(!1),o("licenseAdded")))}catch(e){alert("Error while validating the license. Check your console for more information."),console.error(e)}t(!1)};me((()=>{if(!v.am)return;(0,ce._)()||g(!0)}),[]),me((()=>{(async()=>{if(v.am){t(!0);try{const e=await(0,y.IU)(`${ue}/get_license`,{method:"POST",nonce:v.ok});if(i(e.data),e.data&&e.data.key){if(!(32===e.data.key.length&&/^[0-9a-f]{32}$/.test(e.data.key)||e.data.issue))return g(!0),void t(!1);d(e.data.key)}}catch(e){alert("Error while checking the license. Check your console for more information."),console.error(e)}t(!1)}})()}),[]);const w=E?"Forced License":v.zN?"Enabled":"Disabled",_=!p&&(E||r&&"valid"===r.license);let C="Your license is active. Thanks a lot for your support :)";E&&(C="This license has been force-enabled for you.",r&&r.check_url&&(C=React.createElement(React.Fragment,null,React.createElement("span",null,C),React.createElement("br",null),React.createElement("small",null,"To check your license status, please click ",React.createElement("a",{target:"_blank",href:r.check_url+"&cache="+642e3*Math.random(),rel:"noreferrer"},"here"),".")))),_||(p?C=React.createElement(React.Fragment,null,React.createElement("p",null,"This copy does not match the official release. It appears to have been tampered with and may contain ",React.createElement("strong",null,"malicious code, spyware, or other security risks"),". For your safety, delete this version immediately and download only from the official source: ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com"},"Meow Apps"),"."),React.createElement("p",null,"If you obtained this from any other website than Meow Apps, ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com/contact/"},"contact us")," and dispute the charge with your credit card provider or bank immediately.")):r&&r.key?"no_activations_left"===r.issue?C=React.createElement("span",null,"There are no activations left for this license. You can visit your account at ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com"},"Meow Apps"),", unregister a site, and click on ",React.createElement("i",null,"Retry to validate"),"."):"expired"===r.issue?C=React.createElement("span",null,"Your license has expired. You can get another license or renew the current one by visiting your account at ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com"},"Meow Apps"),"."):"missing"===r.issue?C="This license does not exist.":"disabled"===r.issue?C="This license has been disabled.":"item_name_mismatch"===r.issue?C="This license seems to be for a different plugin... isn't it? :)":"forced"===r.issue?C="ABC":(C=React.createElement("span",null,"There is an unknown error related to the system or this serial key. Really sorry about this! Make sure your security plugins and systems are off temporarily. If you are still experiencing an issue, please ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com/contact/"},"contact us"),"."),console.error({license:r})):C="Please enter your license key below to activate Pro features.");const A=React.createElement(f.z,{title:"Pro Version (Not Installed)",className:"primary"},"You will find more information about the Pro Version ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com"},"here"),". If you actually bought the Pro Version already, please remove the current plugin and download the Pro Version from your account at ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com/"},"Meow Apps"),"."),T=React.createElement(f.z,{title:`Pro Version (${w})`,busy:e,className:"primary"},!p&&!E&&(m||!(r&&r.key===s))&&React.createElement(React.Fragment,null,React.createElement("div",{style:{marginBottom:10}},"License Key:"),React.createElement(ae.A,{id:"mfrh_pro_serial",name:"mfrh_pro_serial",disabled:e,value:s,onChange:e=>d(e.trim()),placeholder:"Type your license key..."}),React.createElement(c.s,{p:!0},"Insert your serial key above. If you don't have one yet, you can get one ",React.createElement("a",{href:"https://meowapps.com"},"here"),". If there was an error during the validation, try the ",React.createElement("i",null,"Retry")," to ",React.createElement("i",null,"validate")," button.")),!_&&React.createElement(oe.X,{variant:"danger"},C),_&&!m&&React.createElement(oe.X,{variant:"success"},C),!p&&React.createElement("div",{style:{marginTop:15,display:"flex",justifyContent:"end",gap:5}},_&&!m&&React.createElement(React.Fragment,null,React.createElement(R.M,{className:"secondary",disabled:e,onClick:b},"Re-Validate License"),React.createElement(R.M,{className:"secondary",disabled:e,onClick:()=>{u(!0),d("")}},"Modify License"),React.createElement(R.M,{className:"danger",disabled:e,onClick:h},"Remove License")),_&&m&&React.createElement(React.Fragment,null,React.createElement(R.M,{className:"secondary",disabled:e,onClick:()=>{u(!1),d(r&&r.key?r.key:"")}},"Cancel"),React.createElement(R.M,{disabled:e||!s,onClick:b},"Validate License")),!_&&React.createElement(React.Fragment,null,r&&React.createElement(R.M,{className:"secondary",disabled:e||!s,onClick:b},"Retry to validate"),r&&r.key===s&&React.createElement(R.M,{className:"danger",disabled:e||!s,onClick:h},"Remove License"),React.createElement(R.M,{disabled:e||!s||r&&r.key===s,onClick:b},"Validate License"),a&&React.createElement(R.M,{disabled:e||!s||r&&r.key===s,onClick:async()=>{t(!0);try{const e=await(0,y.IU)(`${ue}/set_license`,{method:"POST",nonce:v.ok,json:{serialKey:s,override:!0}});e.success&&(i(e.data),e.data&&!e.data.issue&&o("licenseAdded"))}catch(e){alert("Error while forcing the license. Check your console for more information."),console.error(e)}t(!1)},className:"danger"},"Force License"))),React.createElement(se.n,{isOpen:"licenseAdded"===l,title:"Thank you :)",content:"The Pro features have been enabled. This page should be now reloaded.",okButton:{label:"Reload",onClick:()=>location.reload()}}),React.createElement(se.n,{isOpen:"licenseRemoved"===l,title:"Goodbye :(",content:"The Pro features have been disabled. This page should be now reloaded.",okButton:{label:"Reload",onClick:()=>location.reload()}}));return v.am?T:A};var ge=a(3233);function Ee(){return Ee=Object.assign?Object.assign.bind():function(e){for(var t=1;t{try{const a=await(0,y.IU)(e,t);if(!a||a.error){const e=(null==a?void 0:a.message)||(null==a?void 0:a.error)||"Request failed";if("rest_cookie_invalid_nonce"===(null==a?void 0:a.code)||"rest_forbidden"===(null==a?void 0:a.code))throw new Error("Your session has expired. Please refresh the page to continue using AI Engine.");throw new Error(e)}return a&&a.new_token&&((0,v.pK)(a.new_token),console.log("[MWAI] Token refreshed!")),a}catch(e){if(e instanceof Error)throw e;throw new Error(e.message||e.toString()||"Unknown error occurred")}},be=(e,t)=>!(!e||!e.tags)&&(!!Array.isArray(e.tags)&&e.tags.includes(t)),we={title:"",content:"",refId:null,type:"manual",behavior:"context"},_e=({options:e})=>!(null!=e&&e.module_embeddings)||(null==e?void 0:e.embeddings_envs)&&(null==e?void 0:e.embeddings_envs.length)>0?null:React.createElement(oe.X,{variant:"danger",style:{marginTop:0,marginBottom:25}},$e(ge.A.SETTINGS.PINECONE_SETUP,ge.A.SETTINGS.PINECONE_SETUP_URL,ge.A.SETTINGS.PINECONE_SETUP_LINK_TEXT)),Ce=({options:e,defaultModels:t,fastModels:a,style:n})=>{const l=(null==e?void 0:e.ai_envs)||[],o=(null==e?void 0:e.ai_engines)||[],r=l.find((t=>t.id===(null==e?void 0:e.ai_default_env)))||l[0],i=r&&o.find((e=>e.type===r.type)),{sprintf:s}=wp.i18n,c=e=>String(e||"").replace(/[<>&]/g,(e=>({"<":"<",">":">","&":"&"}[e])));if(!l.length)return React.createElement(oe.X,{variant:"danger",style:{marginTop:0,marginBottom:0,...n}},$e(ge.A.SETTINGS.AI_ENV_SETUP,ge.A.SETTINGS.AI_ENV_SETUP_URL,ge.A.SETTINGS.AI_ENV_SETUP_LINK_TEXT));if(r&&!i){const e=s(ge.A.SETTINGS.AI_DEFAULT_TYPE_UNAVAILABLE,`${c(r.name)}`);return React.createElement(oe.X,{variant:"danger",style:{marginTop:0,marginBottom:0,...n}},(0,y.FE)(e))}const d=i&&Array.isArray(i.inputs)&&i.inputs.includes("apikey"),m=!!(r&&r.apikey&&r.apikey.length>0);if(d&&!m){if(1===l.length&&"openai"===r.type&&"OpenAI"===r.name)return React.createElement(oe.X,{variant:"danger",style:{marginTop:0,marginBottom:0,...n}},(0,y.FE)(ge.A.SETTINGS.AI_FRESH_INSTALL));const e=s(ge.A.SETTINGS.AI_DEFAULT_NO_KEY,`${c(r.name)}`);return React.createElement(oe.X,{variant:"danger",style:{marginTop:0,marginBottom:0,...n}},(0,y.FE)(e))}const u=(e,t,a)=>{if(!e||!t)return"missing";if(!a||0===a.length)return null;const n=a.find((e=>e.model===t));return n?be(n,"deprecated")?"deprecated":null:"missing"},p=(g=t,u(null==e?void 0:e.ai_default_env,null==e?void 0:e.ai_default_model,g));var g;const E=(t=>u(null==e?void 0:e.ai_fast_default_env,null==e?void 0:e.ai_fast_default_model,t))(a);if(p||E){const e=[];return"missing"===p&&e.push(ge.A.SETTINGS.AI_DEFAULT_MISSING),"deprecated"===p&&e.push(ge.A.SETTINGS.AI_DEFAULT_DEPRECATED),"missing"===E&&e.push(ge.A.SETTINGS.AI_FAST_MISSING),"deprecated"===E&&e.push(ge.A.SETTINGS.AI_FAST_DEPRECATED),React.createElement(oe.X,{variant:"warning",style:{marginTop:0,marginBottom:0,...n}},e.map(((e,t)=>React.createElement("div",{key:t},(0,y.FE)(e)))))}return null},Ae=(e,t,a)=>{const n=(null==e?void 0:e.ai_envs)||[];if(!n.length)return!0;const l=(null==e?void 0:e.ai_engines)||[],o=n.find((t=>t.id===(null==e?void 0:e.ai_default_env)))||n[0],r=o&&l.find((e=>e.type===o.type));if(o&&!r)return!0;if(r&&Array.isArray(r.inputs)&&r.inputs.includes("apikey")&&!(o.apikey&&o.apikey.length>0))return!0;const i=(e,t,a)=>{if(!e||!t)return!0;if(!a||0===a.length)return!1;const n=a.find((e=>e.model===t));return!n||!!be(n,"deprecated")};return i(null==e?void 0:e.ai_default_env,null==e?void 0:e.ai_default_model,t)||i(null==e?void 0:e.ai_fast_default_env,null==e?void 0:e.ai_fast_default_model,a)};const Te=(e,t,a=!1)=>{const[n,l]=Re(null==e?void 0:e.ai_default_model),o=ye(new Set),r=t||(null==e?void 0:e.ai_default_env),i=(null==e?void 0:e.ai_envs)??[],s=he((()=>{if(a&&null!=e&&e.ai_envs){const e={fake:!0,finetunes:[],legacy_finetunes:[],legacy_finetunes_deleted:[],finetunes_deleted:[],deployments:[]};return i.forEach((t=>{t.finetunes&&e.finetunes.push(...t.finetunes),t.legacy_finetunes&&e.legacy_finetunes.push(...t.legacy_finetunes),t.legacy_finetunes_deleted&&e.legacy_finetunes_deleted.push(...t.legacy_finetunes_deleted),t.finetunes_deleted&&e.finetunes_deleted.push(...t.finetunes_deleted),t.deployments&&e.deployments.push(...t.deployments)})),e}return null}),[i,a]),c=he((()=>{var t;if(a)return s;if(!r)return console.warn("useModels: Environment ID is null. Please provide a valid envId."),null;const n=null==e||null===(t=e.ai_envs)||void 0===t?void 0:t.find((e=>e.id===r));return n||(console.warn(`useModels: Environment with ID ${r} could not be resolved.`,{envs:i,envId:r}),null)}),[i,r,a,s]),d=he((()=>{let e=(null==c?void 0:c.finetunes_deleted)||[];return Array.isArray(null==c?void 0:c.legacy_finetunes_deleted)&&(e=[...e,...c.legacy_finetunes_deleted]),e}),[c]),m=e=>({background:{deprecated:"var(--neko-red)",tuned:"var(--neko-green)",preview:"var(--neko-orange)",experimental:"var(--neko-red)",latest:"var(--neko-blue)"}[e],color:"white",padding:"3px 4px",margin:"1px 0px 0px 3px",borderRadius:4,fontSize:9,lineHeight:"100%"}),u={deprecated:"DEPRECATED",tuned:"TUNED",preview:"PREVIEW",experimental:"EXPERIMENTAL",latest:"LATEST"},p=(e,t)=>{var a;const n=(null===(a=e.tags)||void 0===a?void 0:a.find((e=>["deprecated","preview","experimental","latest"].includes(e))))||(t?"tuned":"");return React.createElement(React.Fragment,null,e.name??e.suffix??e.model,n&&React.createElement("small",{style:m(n)},u[n]))},g=he((()=>{let t=[];if(!0===(null==c?void 0:c.fake))for(const a of e.ai_engines)Array.isArray(a.models)&&(t=[...t,...a.models]);else if("azure"===(null==c?void 0:c.type)){const a=e.ai_engines.find((e=>"openai"===e.type));t=(Array.isArray(null==a?void 0:a.models)?a.models:[]).filter((e=>{var t;return null===(t=c.deployments)||void 0===t?void 0:t.find((t=>t.model===e.model))}))??[]}else if("huggingface"===(null==c?void 0:c.type)){var a;t=(null==c||null===(a=c.customModels)||void 0===a?void 0:a.map((e=>{const t=e.tags?[...new Set([...e.tags,"core","chat"])]:["core","chat"],a=t.includes("image")?"text-to-image":"completion";return{model:e.name,name:e.name,features:a,tags:t,options:[]}})))??[]}else{var n;const a=(null==e||null===(n=e.ai_models)||void 0===n?void 0:n.filter((e=>e.type===(null==c?void 0:c.type)&&(!e.envId||e.envId===(null==c?void 0:c.id)))))??[];if(a.length>0)t=a;else{const a=e.ai_engines.find((e=>e.type===(null==c?void 0:c.type)));t=Array.isArray(null==a?void 0:a.models)?a.models:[]}}let l=(null==c?void 0:c.finetunes)??[];return Array.isArray(null==c?void 0:c.legacy_finetunes)&&(l=[...l,...c.legacy_finetunes]),l=l.filter((e=>"succeeded"===e.status&&e.model)),t=t.map((e=>({...e,name:p(e),rawName:e.name}))),l.length&&(t=[...t,...l.map((e=>{const t=e.model.split(":")[0];return{model:e.model,name:p(e,!0),rawName:e.suffix,suffix:e.suffix,features:["completion"],family:t,description:"finetuned",finetuned:!0,tags:["chat","finetune"]}}))]),t}),[e,c]),E=he((()=>g.filter((e=>!d.includes(e.model)))),[g,d]),h=he((()=>g.filter((e=>be(e,"core")))),[g]),R=he((()=>E.filter((e=>be(e,"image")||be(e,"image-generation")))),[E]),f=he((()=>E.filter((e=>be(e,"video")))),[E]),y=he((()=>Array.isArray(E)?E.filter((e=>be(e,"embedding"))):[]),[E]),v=he((()=>E.filter((e=>be(e,"vision")))),[E]),b=he((()=>E.filter((e=>be(e,"chat")))),[E]),w=he((()=>E.filter((e=>be(e,"audio")))),[E]),_=he((()=>E.filter((e=>be(e,"json")))),[E]),C=he((()=>E.filter((e=>be(e,"realtime")))),[E]),A=t=>{if(!t)return null;let a=g.find((e=>e.model===t));return a||(t.startsWith("gpt-3.5-turbo-")||t.startsWith("gpt-35-turbo")?t="gpt-3.5-turbo":t.startsWith("gpt-4o-mini")?t="gpt-4o-mini":t.startsWith("gpt-4o")?t="gpt-4o":t.startsWith("gpt-4.1-nano")?t="gpt-4.1-nano":t.startsWith("gpt-4.1-mini")?t="gpt-4.1-mini":t.startsWith("gpt-4.1")?t="gpt-4.1":t.startsWith("gpt-4")?t="gpt-4":t.startsWith("gpt-5-nano")?t="gpt-5-nano":t.startsWith("gpt-5-mini")?t="gpt-5-mini":t.startsWith("gpt-5.1")?t="gpt-5.1":t.startsWith("gpt-5")?t="gpt-5":t.startsWith("o1-preview")?t="o1-preview":t.startsWith("o1-mini")?t="o1-mini":t.startsWith("o1-")?t="o1":t.startsWith("claude-opus-4")?t="claude-opus-4-20250514":t.startsWith("claude-sonnet-4")?t="claude-sonnet-4-20250514":t.startsWith("claude-3-7-sonnet")?t="claude-3-7-sonnet-latest":t.startsWith("claude-3-5-sonnet-2024")?t="claude-3-5-sonnet-20241022"===t?"claude-3-5-sonnet-20241022":"claude-3-5-sonnet-20240620"===t?"claude-3-5-sonnet-20240620":"claude-3-5-sonnet-latest":t.startsWith("claude-3-5-sonnet")||t.startsWith("claude-3.5-sonnet")?t="claude-3-5-sonnet-latest":t.startsWith("claude-3-opus-2024")||t.startsWith("claude-3-opus")?t="claude-3-opus-latest":t.startsWith("claude-3-sonnet")?t="claude-3-sonnet-20240229":t.startsWith("claude-3-5-haiku")?t="claude-3-5-haiku-20241022":t.startsWith("claude-3-haiku")&&(t="claude-3-haiku-20240307"),a=g.find((e=>e.model===t)),a||o.current.has(t)||(console.warn(`Model ${t} not found.`,{allModels:g,options:e}),o.current.add(t)),a)},T=(e,t="1024x1024")=>{const a=A(e);if("image"===(null==a?void 0:a.type)&&null!=a&&a.resolutions){const e=a.resolutions.find((e=>e.name===t));return(null==e?void 0:e.price)||null}return(null==a?void 0:a.price)||null};return{allModels:g,model:n,models:E,completionModels:b,imageModels:R,videoModels:f,visionModels:v,coreModels:h,embeddingsModels:y,audioModels:w,jsonModels:_,realtimeModels:C,setModel:l,isFineTunedModel:e=>{const t=A(e);return(null==t?void 0:t.finetuned)||!1},getModelName:(e,t=!1)=>{const a=A(e);return a?t&&a?a.rawName:(null==a?void 0:a.name)||(null==a?void 0:a.model)||e:e},getFamilyName:e=>{const t=A(e);return(null==t?void 0:t.family)||null},getPrice:T,getModel:A,calculatePrice:(e,t,a,n="1024x1024")=>{const l=A(e),o=T(e,n);let r=o,i=o;return"object"==typeof o&&null!==o&&(r=o.in,i=o.out),r&&i?r*t*l.unit+i*a*l.unit:0}}},Ie=async e=>{const t=await ve(`${v.y0}/vectors/remote_list`,{nonce:(0,v.c3)(),method:"POST",json:e});return t?{total:t.total,vectors:t.vectors}:{total:0,vectors:[]}},Ne=async e=>{const t={...e,offset:(e.page-1)*e.limit},a=await ve(`${v.y0}/discussions/list`,{nonce:(0,v.c3)(),method:"POST",json:t});if(a&&!1===a.success)throw new Error(a.message||"Failed to retrieve discussions");return a?{total:a.total,chats:a.chats}:{total:0,chats:[]}},xe=async(e=31,t=!1,a=null)=>{const n={days:e,byModel:t};a&&(n.feature=a);const l=await ve(`${v.y0}/system/logs/activity_daily`,{nonce:(0,v.c3)(),method:"POST",json:n});return null!=l&&l.data?l.data:[]},Oe=async e=>{var t,a,n;const l=null!==(null==e||null===(t=e.filters)||void 0===t?void 0:t.search);if(""===(null==e||null===(a=e.filters)||void 0===a?void 0:a.search))return[];if(!e.filters.envId)return{total:0,vectors:[]};console.log("[API CALL] retrieveVectors (list)",{envId:e.filters.envId,page:e.page,limit:e.limit});const o=await ve(`${v.y0}/vectors/list`,{nonce:(0,v.c3)(),method:"POST",json:e});if(l&&null!=o&&null!==(n=o.vectors)&&void 0!==n&&n.length){const t=o.vectors.sort(((t,a)=>{var n;return"asc"===(null==e||null===(n=e.sort)||void 0===n?void 0:n.by)?t.score-a.score:a.score-t.score}));o.vectors=t}return o?{total:o.total,vectors:o.vectors}:{total:0,vectors:[]}};function ke(e){let t=new Date(e);t=new Date(t.getTime()-60*t.getTimezoneOffset()*1e3);const a=t.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"}),n=t.toLocaleTimeString("ja-JP",{hour:"2-digit",minute:"2-digit",second:"2-digit"});return React.createElement(React.Fragment,null,a,React.createElement("br",null),React.createElement("small",null,n))}function Se(e,t){const a=t?(()=>{if(t.startsWith("hashed_")){const e=13;return t.length>e?t.substring(0,e)+"~":t}if((t.match(/:/g)||[]).length>=3){const e=t.split(":");if(e.length>3)return e.slice(0,3).join(":")+"~"}let e=t.substring(0,16);return e.length{const t="abcdefghijklmnopqrstuvwxyz0123456789";let a="";for(let n=0;n{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",Ee({width:e,height:e},n,{style:l,alt:"OpenAI",src:v.Hm+"/images/chat-openai.svg"}))},Le=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",Ee({width:e,height:e},n,{style:l,alt:"Anthropic",src:v.Hm+"/images/chat-anthropic.svg"}))},De=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",Ee({width:e,height:e},n,{style:l,alt:"Google",src:v.Hm+"/images/chat-google.svg"}))},Fe=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",Ee({width:e,height:e},n,{style:l,alt:"JavaScript",src:v.Hm+"/images/code-js.svg"}))},Ue=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",Ee({width:e,height:e},n,{style:l,alt:"PHP",src:v.Hm+"/images/code-php.svg"}))},Be=(e=null)=>{const{getBlocks:t,getSelectedBlockClientId:a}=wp.data.select("core/block-editor"),{getEditedPostAttribute:n}=wp.data.select("core/editor"),l=t(),o=n("title"),r=a();let i=o+"\n\n";return l.forEach(((t,a)=>{e&&t.clientId===r?i+=e+"\n\n":i+=(t.attributes.content||"")+"\n\n"})),i.trim()},$e=(e,t,a,n="_blank")=>{const{sprintf:l}=wp.i18n,o=`${a}`;return(0,y.FE)(l(e,o))},He=(e,t)=>{const{sprintf:a}=wp.i18n,n=t.map((({url:e,text:t,target:a="_blank"})=>`${t}`));return(0,y.FE)(a(e,...n))},je=async()=>await ve(`${v.y0}/vectors/ignored`,{nonce:(0,v.c3)()}),ze=(e,t)=>{const a=new Blob([e],{type:"text/plain;charset=utf-8;"}),n=document.createElement("a");n.href=URL.createObjectURL(a),n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)},{useState:Ge,useEffect:We,useMemo:qe}=wp.element,Ve=React.createElement("g",null,React.createElement("g",null,React.createElement("path",{d:"m391 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#39326c"}),React.createElement("path",{d:"m331 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#39326c"}),React.createElement("path",{d:"m271 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#39326c"}),React.createElement("path",{d:"m211 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#5f55af"}),React.createElement("path",{d:"m151 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#5f55af"}),React.createElement("path",{d:"m91 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#5f55af"}),React.createElement("path",{d:"m406 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z",fill:"#39326c"}),React.createElement("path",{d:"m346 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z",fill:"#39326c"}),React.createElement("path",{d:"m286 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z",fill:"#39326c"}),React.createElement("g",{fill:"#5f55af"},React.createElement("path",{d:"m226 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m166 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m106 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 121h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 181h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 241h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 301h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 361h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 421h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"})),React.createElement("path",{d:"m431 91v30h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15z",fill:"#39326c"}),React.createElement("path",{d:"m431 181h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 241h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 301h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 361h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 421h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"})),React.createElement("g",null,React.createElement("path",{d:"m446 51h-380c-8.284 0-15 6.716-15 15v380c0 8.284 6.716 15 15 15h380c8.284 0 15-6.716 15-15v-380c0-8.284-6.716-15-15-15z",fill:"#aed0ff"}),React.createElement("g",null,React.createElement("path",{d:"m461 446v-380c0-8.284-6.716-15-15-15h-190v410h190c8.284 0 15-6.716 15-15z",fill:"#7c84e8"})),React.createElement("path",{d:"m386 111h-260c-8.284 0-15 6.716-15 15v260c0 8.284 6.716 15 15 15h260c8.284 0 15-6.716 15-15v-260c0-8.284-6.716-15-15-15z",fill:"#5f55af"}),React.createElement("g",null,React.createElement("path",{d:"m401 386v-260c0-8.284-6.716-15-15-15h-130v290h130c8.284 0 15-6.716 15-15z",fill:"#39326c"}))),React.createElement("g",null,React.createElement("path",{d:"m247.626 192.389c-.052-.138-.106-.274-.162-.411-2.744-6.671-9.175-10.978-16.387-10.978-.006 0-.012 0-.018 0-7.219.007-13.65 4.329-16.383 11.01-.046.113-.091.227-.134.341l-45.06 118.31c-2.949 7.742.937 16.408 8.679 19.356 7.742 2.95 16.408-.937 19.356-8.679l7.543-19.804h51.691l7.458 19.762c2.267 6.007 7.974 9.708 14.036 9.708 1.76 0 3.55-.312 5.294-.97 7.75-2.925 11.663-11.579 8.737-19.33zm-31.14 79.146 14.538-38.171 14.406 38.171z",fill:"#f9f9f9"}),React.createElement("g",{fill:"#e2dff4"},React.createElement("path",{d:"m264.209 321.296c2.267 6.007 7.974 9.708 14.036 9.708 1.76 0 3.55-.312 5.294-.97 7.75-2.925 11.663-11.579 8.737-19.33l-36.276-96.126v86.956h.751z"}),React.createElement("path",{d:"m328.5 181c-8.284 0-15 6.716-15 15v120c0 8.284 6.716 15 15 15s15-6.716 15-15v-120c0-8.284-6.716-15-15-15z"})))),Ke=React.createElement("g",null,React.createElement("path",{d:"m213.46 341.461-139.26 156.08c-16.17 18.48-44.53 19.33-61.8 2.06-17.32-17.32-16.37-45.67 2.06-61.8l156.08-139.26s13.46-2.54 29.46 13.46 13.46 29.46 13.46 29.46z",fill:"#0052be"}),React.createElement("path",{d:"m213.46 341.461-139.26 156.08c-16.17 18.48-44.53 19.33-61.8 2.06l187.6-187.6c16 16 13.46 29.46 13.46 29.46z",fill:"#00429b"}),React.createElement("path",{d:"m304 240.001-90.54 101.46c-14.997-14.997-27.922-27.922-42.92-42.92l101.46-90.54z",fill:"#00429b"}),React.createElement("path",{d:"m304 240.001-90.54 101.46-21.46-21.46 96-96z",fill:"#00337a"}),React.createElement("path",{d:"m400 279.001h-64.4l-42.47 57.87c-7.88 10.735-24.824 6.606-26.91-6.52l-11.56-73.01-73.01-11.56c-13.139-2.087-17.244-19.042-6.52-26.91l57.87-42.47v-64.4c0-12.176 13.797-19.289 23.72-12.21l50.15 35.83 70.92-19.9c11.25-3.168 21.656 7.245 18.49 18.49l-19.9 70.92 35.83 50.15c7.071 9.913-.02 23.72-12.21 23.72z",fill:"#ffdd54"}),React.createElement("path",{d:"m412.21 255.281c7.071 9.913-.02 23.72-12.21 23.72h-64.4l-42.47 57.87c-7.875 10.728-24.823 6.616-26.91-6.52l-11.56-73.01 137.79-137.79c3.83 3.84 5.3 9.44 3.83 14.66l-19.9 70.92z",fill:"#ffb454"}),React.createElement("path",{d:"m512 39.001c0 8.28-6.72 15-15 15h-9v9c0 8.28-6.72 15-15 15s-15-6.72-15-15v-9h-9c-8.28 0-15-6.72-15-15s6.72-15 15-15h9v-9c0-8.28 6.72-15 15-15s15 6.72 15 15v9h9c8.28 0 15 6.719 15 15z",fill:"#bee75e"}),React.createElement("path",{d:"m512 39.001c0 8.28-6.72 15-15 15h-9v9c0 8.28-6.72 15-15 15s-15-6.72-15-15v-9l30-30h9c8.28 0 15 6.719 15 15z",fill:"#00cb75"}),React.createElement("path",{d:"m336 41.001h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9v9c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15z",fill:"#f6f9f9"}),React.createElement("path",{d:"m441 224.001c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9z",fill:"#e2dff4"}),React.createElement("path",{d:"m497 329.001h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9v9c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15z",fill:"#ff4a4a"}),React.createElement("path",{d:"m192 24.001h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9v9c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15z",fill:"#ff8659"}),React.createElement("path",{d:"m159.442 122.977-56-32c-7.191-4.109-16.355-1.611-20.466 5.581-4.11 7.193-1.611 16.355 5.581 20.466l56 32c7.16 4.093 16.337 1.644 20.466-5.581 4.111-7.193 1.612-16.355-5.581-20.466z",fill:"#f6f9f9"}),React.createElement("path",{d:"m118.14 169.117-64 8c-8.221 1.027-14.052 8.524-13.023 16.744 1.027 8.218 8.523 14.054 16.744 13.023l64-8c8.221-1.027 14.052-8.524 13.023-16.744-1.028-8.22-8.527-14.062-16.744-13.023z",fill:"#acceff"}),React.createElement("path",{d:"m389.023 352.558c-4.111-7.193-13.274-9.693-20.466-5.581-7.192 4.11-9.691 13.272-5.581 20.466l32 56c2.769 4.845 7.83 7.561 13.037 7.561 11.319 0 18.784-12.341 13.01-22.445z",fill:"#e2dff4"}),React.createElement("path",{d:"m329.86 377.117c-8.222-1.031-15.717 4.804-16.744 13.023l-8 64c-1.117 8.925 5.834 16.862 14.902 16.862 7.455 0 13.917-5.553 14.865-13.142l8-64c1.029-8.219-4.802-15.716-13.023-16.743z",fill:"#6ba7ff"})),Ye=({icon:e="ai",size:t=20,style:a={}}={})=>{const n=qe((()=>{switch(e){case"ai":default:return Ve;case"wand":return Ke}}),[e]);return React.createElement("svg",{style:{width:t,height:t,marginRight:5,...a},"enable-background":"new 0 0 512 512",height:"512",viewBox:"0 0 512 512",width:"512",xmlns:"http://www.w3.org/2000/svg"},n)},Xe=({title:e=ge.A.COMMON.SETTINGS,options:t=v.fF})=>{const a=null==t?void 0:t.module_playground,n=null==t?void 0:t.module_generator_content,l=null==t?void 0:t.module_generator_images,o=null==t?void 0:t.module_generator_videos;return React.createElement(g.n,{title:"AI Engine",section:e,subtitle:"By Meow Apps",isPro:v.am},React.createElement("div",{style:{display:"flex",justifyContent:"flex-end"}},n&&React.createElement(R.M,{className:"header",onClick:()=>location.href="edit.php?page=mwai_content_generator"},React.createElement(Ye,{icon:"wand",style:{marginRight:8}}),ge.A.COMMON.CONTENT),l&&React.createElement(R.M,{className:"header",icon:"",onClick:()=>location.href="edit.php?page=mwai_images_generator"},React.createElement(Ye,{icon:"wand",style:{marginRight:8}}),ge.A.COMMON.IMAGES),o&&React.createElement(R.M,{className:"header",icon:"",onClick:()=>location.href="tools.php?page=mwai_videos_generator"},React.createElement(Ye,{icon:"wand",style:{marginRight:8}}),"Videos"),a&&React.createElement(R.M,{className:"header",icon:"",onClick:()=>location.href="tools.php?page=mwai_dashboard"},React.createElement(Ye,{icon:"wand",style:{marginRight:8}}),ge.A.COMMON.PLAYGROUND),React.createElement(R.M,{className:"header",icon:"tools",onClick:()=>location.href="admin.php?page=mwai_settings"})))},Qe=((0,w.Ay)(R.M)` `,w.Ay.div` display: flex; justify-content: unset; align-items: center; justify-content: space-between; padding: 0 0 2px 0; h2 { margin: 7px 0 0 0; padding: 0; } `);w.Ay.div` display: grid; grid-template-columns: repeat(auto-fit, minmax(30%, 1fr)); grid-template-rows: repeat(auto-fit, minmax(30%, 1fr)); grid-gap: 10px; margin-top: 20px; img, div { width: 100%; cursor: pointer; } .image-wrapper { position: relative; } .delete-icon { display: none; position: absolute; top: 5px; right: 5px; background: rgba(0,0,0,0.7); color: #fff; width: 20px; height: 20px; border-radius: 50%; align-items: center; justify-content: center; font-size: 14px; } .image-wrapper:hover .delete-icon { display: flex; } .media-label { position: absolute; bottom: 0; left: 0; right: 0; background: rgba(0,0,0,0.6); color: #fff; text-align: center; font-size: 12px; padding: 2px 0; text-decoration: underline; cursor: pointer; } .empty-image { width: 100%; padding-bottom: 100%; background-color: #f5f5f5; } `;var Je=a(9277),Ze=a.n(Je),et=a(9018),tt=a(5510),at=a(7753),nt=a(2861),lt=a(7282),ot=a(9659),rt=a(5146),it=a(2448),st=a(6038);const ct=async(e,t={})=>{const a=(0,v.c3)(),n={...t,nonce:a};try{const t=await(0,y.IU)(e,n);if(t&&t.new_token){if(t.token_expires_at){const e=new Date(1e3*t.token_expires_at);console.log(`[MWAI] 🔐 New token received - expires at ${e.toLocaleTimeString()} (in ${t.token_expires_in}s)`)}else console.log(ge.A.DEBUG.NEW_TOKEN_RECEIVED);(0,v.pK)(t.new_token)}return t}catch(a){if(a.message&&a.message.includes("nonce")){console.log(ge.A.DEBUG.NONCE_ERROR_DETECTED);const a=await(0,y.IU)(`${v.y0}/start_session`,{method:"POST"});if(a&&a.restNonce)return(0,v.pK)(a.restNonce),await(0,y.IU)(e,{...t,nonce:a.restNonce})}throw a}},dt=async()=>{const e=await ct(`${v.y0}/helpers/post_types`);if(!e.success)throw new Error(e.message);return e.postTypes},mt=async e=>{const t=await ct(`${v.gh}/mwai-ui/v1/files/delete`,{method:"POST",json:{files:e}});if(!t.success)throw new Error(t.message);return t},ut=async({userId:e=null,purpose:t=null,metadata:a=null,envId:n=null,limit:l=10,page:o=0})=>{const r=await ct(`${v.gh}/mwai-ui/v1/files/list`,{method:"POST",json:{userId:e,purpose:t,metadata:a,envId:n,limit:l,page:o}});if(!r.success)throw new Error(r.message);return null==r?void 0:r.data},pt=async(e=null,t=!1)=>{const a=await ct(`${v.y0}/openai/finetunes/list_deleted?envId=${e}&legacy=${t}`);if(!a.success)throw new Error(a.message);return null==a?void 0:a.finetunes},gt=async()=>{const e=await ct(`${v.y0}/settings/themes`,{method:"GET"});return null==e?void 0:e.themes},Et=async e=>{const t=[];for(let a=0;a{const e=await ct(`${v.y0}/settings/chatbots`,{method:"GET"});if(!e.success)throw new Error(null==e?void 0:e.message);return null==e?void 0:e.chatbots},Rt=async e=>{const t=await ct(`${v.y0}/settings/chatbots`,{method:"POST",json:{chatbots:e}});if(!t.success)throw new Error(null==t?void 0:t.message);return null==t?void 0:t.chatbots},ft=async()=>{const e=await ct(`${v.y0}/settings/options`,{method:"GET"});return null==e?void 0:e.options},yt=async()=>{try{return(await ct(`${v.y0}/get_logs`,{method:"GET"})).data}catch(e){throw new Error(e.message)}},vt=async()=>{try{await ct(`${v.y0}/clear_logs`)}catch(e){throw new Error(e.message)}},bt=async()=>{const e=await ct(`${v.y0}/forms/list`);if(!e.success)throw new Error(e.message);return e.forms},wt=async()=>{const e=await ct(`${v.y0}/helpers/cron_events`);if(!e.success)throw new Error(e.message);return e.events},_t=async()=>{const e=await ct(`${v.y0}/helpers/tasks_list`);if(!e.success)throw new Error(e.message);return e.tasks},Ct=async e=>{const t=await ct(`${v.y0}/helpers/task_run`,{method:"POST",json:{task_name:e}});if(!t.success)throw new Error(t.message);return t},At=async e=>{const t=await ct(`${v.y0}/helpers/task_pause`,{method:"POST",json:{task_name:e}});if(!t.success)throw new Error(t.message);return t},Tt=async e=>{const t=await ct(`${v.y0}/helpers/task_resume`,{method:"POST",json:{task_name:e}});if(!t.success)throw new Error(t.message);return t},It=async e=>{const t=await ct(`${v.y0}/helpers/task_delete`,{method:"POST",json:{task_name:e,delete_logs:!0}});if(!t.success)throw new Error(t.message);return t},{useState:Nt,useRef:xt}=wp.element,Ot=({instructions:e,setMessages:t})=>{const[a,n]=Nt("post"),[l,o]=Nt(0),[i,s]=Nt(!1),[c,d]=Nt("Generate 30 questions and answers from this text. Questions use a neutral tone. Answers use the same tone as the text."),m=xt(),{isLoading:u,data:p}=(0,r.I)({queryKey:["postTypes"],queryFn:dt}),{isLoading:g,data:E}=(0,r.I)({queryKey:["postsCount-"+a],queryFn:()=>(async e=>{const t=await ct(`${v.y0}/helpers/count_posts?postType=${e}`);return null!=t&&t.count?parseInt(null==t?void 0:t.count):null})(a)}),h=(0,st.XS)({i18n:ge.A,onStop:()=>{s(),h.reset()}}),f=i||h.busy||g||u,b=async(t=0,n=void 0,l=void 0)=>{let r=c+"\n\nUse this format:\n\nQ: Question?\nA: Answer.\n\nQ: Question?\nA: Answer.\nText:\n\n{CONTENT}";const i=await(async(e,t=0,a=0)=>await ct(`${v.y0}/helpers/post_content?postType=${e}&offset=${t}&postId=${a}`))(a,t,n||void 0);let s=null,d=null;const m=null==i?void 0:i.content,u=null==i?void 0:i.url,p=null==i?void 0:i.title;let g=0;if(i.success)if(m.length<64)console.log("Issue: Content is too short! Skipped.",{content:m});else{var E;r=r.replace("{CONTENT}",m),r=r.replace("{URL}",u),r=r.replace("{TITLE}",p);const e=await(0,y.IU)(`${v.y0}/ai/completions`,{method:"POST",json:{scope:"admin-tools",session:v.dZ,message:r},signal:l,nonce:v.ok});if(!e.success){var h;if(null!==(h=e.error)&&void 0!==h&&h.cancelledByUser)return null;throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}d=null==e?void 0:e.data,null!=e&&null!==(E=e.usage)&&void 0!==E&&E.total_tokens&&(g=e.usage.total_tokens,o((t=>t+e.usage.total_tokens)))}else alert(i.message),s=i.message;null!=l&&l.aborted&&w();const R=(t=>{if(!t)return[];const a=t.split("\n").filter((e=>""!==e.trim())),n=[];let l=[];for(let t=0;t{console.log("User aborted."),setBusy(!1),h.reset()};return React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",width:"100%"}},React.createElement(R.M,{disabled:f,onClick:async()=>{try{o(0);const e=prompt("Enter the ID of a post (leave blank to use the very first one).");if(null===e)return;s("singleGenerate"),m.current=new AbortController;const a=await b(0,e,m.current.signal);if(a.entries.length){confirm(`Got ${a.entries.length} entries! Do you want to add them to your data? If not, they will be displayed in your console.`)&&t((e=>[...e,...a.entries]))}else alert("No entries were generated. Check the console for more information.")}catch(e){console.error(e),alert(e.message)}finally{s(!1)}},busy:"singleGenerate"===i},ge.A.COMMON.SINGLE_GENERATE),React.createElement("span",{style:{color:"#d1e8f2",fontSize:"22px",padding:5}},"|"),React.createElement(R.M,{disabled:f,onClick:()=>(async()=>{o(0);const e=Array.from(Array(E).keys()),a=prompt("There are "+e.length+" entries. If you want to start from a certain entry offset, type it here. Otherwise, just press OK, and everything will be processed."),n=e.map((e=>async n=>{var l;if(console.log("Task "+e),a&&e0&&t((e=>[...e,...o.entries])),{success:!0}}));await h.start(n),s(!1),alert("All done!"),h.reset()})()},"Bulk Generate"),React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",paddingLeft:10}},"Based on ",g&&"...",!g&&E),React.createElement(te.u,{id:"postType",scrolldown:!0,disabled:f,name:"postType",style:{width:100,marginLeft:10},onChange:n,value:a},null==p?void 0:p.map((e=>React.createElement(te.j,{key:e.type,value:e.type,label:e.name})))),React.createElement(it.j,{busy:h.busy,style:{marginLeft:10,flex:"auto"},value:h.value,max:h.max,onStopClick:h.stop}),React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",paddingLeft:10}},"Tokens: ",l)),React.createElement("div",{style:{width:"100%"}},React.createElement(ie.m,{id:"generatePrompt",name:"generatePrompt",rows:2,style:{marginTop:10,marginBottom:5},value:c,onBlur:d,disabled:f})),h.TasksErrorModal)},{useState:kt,useMemo:St,useRef:Mt,useEffect:Pt}=wp.element,Lt=({createdOn:e,estimatedOn:t})=>{if(!e||!t)return null;const a=new Date;e=new Date(e),t=new Date(t);const n=e=>new Date(e).toLocaleString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"});return React.createElement("div",null,"Start: ",n(e),".",React.createElement("br",null),"Finish: ",n(t),".",React.createElement("br",null),"Time Left: ",React.createElement("b",null,((e,t)=>{const a=t-e,n=Math.floor(a/6e4),l=Math.floor(n/60);return l>0?`${l} hour${l>1?"s":""} and ${n%60} minute${n%60!=1?"s":""}`:`${n} minute${1!==n?"s":""}`})(a,t)),".",React.createElement("br",null),React.createElement("br",null),React.createElement("small",null,"Use Refresh Models to update the status."))},Dt=[{accessor:"row",title:"#",width:"25px",verticalAlign:"top"},{accessor:"question",title:"Question",width:"50%",verticalAlign:"top"},{accessor:"answer",title:"Answer",width:"50%",verticalAlign:"top"},{accessor:"actions",title:"",width:"36px",align:"center"}],Ft=[{accessor:"row",title:"#",width:"25px",verticalAlign:"top"},{accessor:"messages",title:"Messages",width:"100%",verticalAlign:"top"},{accessor:"actions",title:"",width:"68px",align:"top"}],Ut=[{accessor:"status",title:"Status",sortable:!0,width:"120px"},{accessor:"id",title:"ID",width:"120px"},{accessor:"filename",title:"File",width:"50%"},{accessor:"purpose",title:"Purpose",width:"50%"},{accessor:"filesize",title:"Size",width:"80px",sortable:!0},{accessor:"createdOn",title:"Date",sortable:!0,width:"120px"},{accessor:"actions",title:"",width:"200px"}],Bt=[{accessor:"status",title:"Status",sortable:!0,width:"120px"},{accessor:"id",title:"ID",width:"120px"},{accessor:"suffix",title:"Suffix",width:"20%"},{accessor:"model",title:"Model",width:"40%"},{accessor:"base_model",title:"Based On",width:"40%"},{accessor:"createdOn",title:"Date",sortable:!0,width:"120px"},{accessor:"actions",title:"",width:"40px"}],$t=({status:e,includeText:t=!1})=>{const{colors:a}=(0,o.z)(),n=a.orange,l=a.green,r=a.red;let i=null;switch(e){case"pending":case"running":i=React.createElement(et.z,{title:e,icon:"replay",spinning:!0,width:24,color:n});break;case"succeeded":case"processed":i=React.createElement(et.z,{title:e,icon:"check-circle",width:24,color:l});break;case"failed":i=React.createElement(et.z,{title:e,icon:"close",width:24,color:r});break;case"cancelled":i=React.createElement(et.z,{title:e,icon:"close",width:24,color:n});break;default:i=React.createElement(et.z,{title:e,icon:"alert",width:24,color:n})}return t?React.createElement("div",{style:{display:"flex",alignItems:"center"}},i,React.createElement("span",{style:{textTransform:"uppercase",fontSize:9,marginLeft:3}},e)):i},Ht=({children:e,data:t,onChange:a=(()=>{})})=>{const[n,l]=kt(!1),o=e=>{l(!1),e!==t&&a(e)},r=e=>{"Escape"===e.key&&o(t)};return n?React.createElement("div",{onKeyUp:r,style:{height:"100%",display:"flex",flexDirection:"column",width:"100%"}},React.createElement(ie.m,{onBlurForce:!0,autoFocus:!0,fullHeight:!0,rows:3,style:{height:"100%",width:"100%"},onEnter:o,onBlur:o,value:t}),React.createElement(R.M,{onClick:o,fullWidth:!0,style:{marginTop:2,height:35}},"Save")):React.createElement("pre",{style:{width:"100%",height:"100%",whiteSpace:"break-spaces",margin:0,padding:0,fontSize:13,fontFamily:"inherit"},onClick:()=>l(!0)},e)},jt=({options:e,updateOption:t,refreshOptions:a})=>{var n;const{colors:i}=(0,o.z)(),s=(0,l.jE)(),[c,d]=kt(!1),[m,p]=kt(),[g,f]=kt(!1),[b,w]=kt("finetunes"),[_,C]=kt("current"),[A,T]=kt("fine-tune"),[I,N]=kt("meow"),[x,O]=kt(!1),[k,S]=kt(4),[M,P]=kt(4),[L,D]=kt(.1),[F,U]=kt(.01),[B,$]=kt(!1),[H,j]=kt(null==e||null===(n=e.ai_envs)||void 0===n||null===(n=n[0])||void 0===n?void 0:n.id),z=St((()=>(null==e?void 0:e.ai_envs)||[]),[e]),G=St((()=>null==z?void 0:z.find((e=>e.id===H))),[H,z]),W=(null==G?void 0:G.finetunes_deleted)||[],q=(null==G?void 0:G.finetunes)||[],{isFetching:V,error:K,data:Y}=(0,r.I)({queryKey:["datasets-"+H+"-"+A],enabled:B,queryFn:()=>(async(e=null,t=null)=>{var a;let n=`${v.y0}/openai/files/list?envId=${e}`;t&&(n+=`&purpose=${t}`);const l=await ct(n);if(!l.success)throw new Error(l.message);return null==l||null===(a=l.files)||void 0===a?void 0:a.data})(H,A)}),[X,Q]=kt("gpt-4o-mini-2024-07-18"),J=async(e,a)=>{const n=z.map((t=>t.id===H?{...t,[e]:a}:t));return t(n,"ai_envs")};Pt((()=>{"files"!==b||B||$(!0)}),[b]),Pt((()=>{K&&!c&&d(K)}),[K]);const Z=10,[re,ce]=kt(!0),[de,me]=kt(1),[ue,pe]=kt([]),[Ee,he]=kt(!1),[Re,fe]=kt("You are Chihiro, an AI Assistant. Your primary objective is to assist website visitors by directing them to the appropriate page or succinctly answering their questions with precision."),[ye,ve]=kt(""),[be,we]=kt(!1),[_e,Ce]=kt([]),Ae=St((()=>ue.length),[ue]);Pt((()=>{if(0===ue.length)return void we(!1);const e=ue.map(((e,t)=>{if(!e.messages||e.messages.length<3)return t+1;if("system"!==e.messages[0].role||"user"!==e.messages[1].role||"assistant"!==e.messages[2].role)return t+1;for(let a=3;anull!==e));Ce(e),we(0===e.length)}),[ue]);const Te=({messages:e,currentRow:t,onUpdateDataRow:a,onDeleteDataRow:n})=>React.createElement(React.Fragment,null,e.map(((e,l)=>React.createElement("div",{key:l,style:{display:"flex"}},React.createElement(R.M,{rounded:!0,icon:"trash",onClick:()=>n(t,l+1)}),React.createElement("div",{style:{width:120,paddingLeft:5,paddingTop:0,paddingBottom:4,marginRight:10}},React.createElement(te.u,{scrolldown:!0,name:"role",value:e.role,style:{width:120},onChange:n=>a(t,n,e.content,l+1)},React.createElement(te.j,{value:"assistant",label:"Assistant"}),React.createElement(te.j,{value:"user",label:"User"}),React.createElement(te.j,{value:"system",label:"System"}))),React.createElement(Ht,{data:e.content,style:{flex:"auto"},onChange:n=>a(t,e.role,n,l+1)},e.content))))),Ie=async()=>{await s.invalidateQueries("datasets")},Ne=async()=>{f("finetunes"),q.length?await(async(e=null,t=!1)=>{const a=await ct(`${v.y0}/openai/finetunes/list?envId=${e}&legacy=${t}`);if(!a.success)throw new Error(a.message);return null==a?void 0:a.finetunes})(H):await pt(H),await a(),f(!1)},xe=(e=!0)=>{e&&!confirm(ge.A.ALERTS.RESET_BUILDER)||(pe([]),Se({instructions:Re,entries:[]}))};Pt((()=>{if(!ue||0===ue.length){const e=localStorage.getItem("mwai_builder_data_v2");if(e){const t=JSON.parse(e);pe(t.entries),t.instructions&&fe(t.instructions)}}}),[]);const Oe=e=>{let t=!1,a=!1;for(let n=0;n0)if("system"===l[0].role){if(l[0].content!==e){if(!t){if(!confirm("The instructions in your data do not match the ones in your entries. Do you want to replace it for every entry?"))return;t=!0}const a=[...ue];a[n].messages[0].content=e,pe((()=>a))}}else{if(!a){if(!confirm("Some entries are missing the system role as the first message. Do you want to add it for every entry where it's missing?"))return;a=!0}const t=[...ue];t[n].messages.unshift({role:"system",content:e}),pe((()=>t))}else{if(!a){if(!confirm("Some entries are missing the system role as the first message. Do you want to add it for every entry where it's missing?"))return;a=!0}const t=[...ue];t[n].messages=[{role:"system",content:e},...l],pe((()=>t))}}},ke=e=>{fe(e),Ee||Oe(e)},Se=e=>{(()=>{const e=new Date;let t=e.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"});t=t.replace(/\//g,"."),t+="-"+e.getHours().toString().padStart(2,"0")+"."+e.getMinutes().toString().padStart(2,"0"),ve(`MEOW-${t}.jsonl`)})();try{e?localStorage.setItem("mwai_builder_data_v2",(0,y.F1)(e)):localStorage.removeItem("mwai_builder_data_v2"),ce(!0)}catch(e){localStorage.removeItem("mwai_builder_data_v2"),ce(!1)}};Pt((()=>{ue&&(null==ue?void 0:ue.length)>0&&Se({instructions:Re,entries:ue})}),[ue]),Pt((()=>{Re&&(null==Re?void 0:Re.length)>0&&Se({instructions:Re,entries:ue})}),[Re]);const Me=(e,t)=>{const a=[...ue];a[e-1].messages.splice(t-1,1),pe(a)},Pe=(e,t,a,n=null)=>{const l=ue.map(((l,o)=>{if(o===e-1){if(n)return{...l,messages:l.messages.map(((e,l)=>l===n-1?{...e,role:t,content:a}:e))};if("assistant"===t)return{...l,messages:l.messages.map((e=>"assistant"===e.role?{...e,content:a}:e))};if("user"===t)return{...l,messages:l.messages.map((e=>"user"===e.role?{...e,content:a}:e))}}return l}));pe(l)},Le=St((()=>{let e=(de-1)*Z;const t=null==ue?void 0:ue.slice((de-1)*Z,(de-1)*Z+Z);return null==t?void 0:t.map((t=>{const a=++e;let n="",l="",o=[];if(Ee)o=t.messages;else{const e=t.messages.find((e=>"user"===e.role));e&&(n=e.content);const a=t.messages.find((e=>"assistant"===e.role));a&&(l=a.content)}return{row:a,messages:React.createElement(Te,{entries:ue,messages:o,currentRow:a,onUpdateDataRow:Pe,onDeleteDataRow:Me}),question:React.createElement(Ht,{data:n,onChange:e=>Pe(a,"user",e)},n),answer:React.createElement(Ht,{data:l,onChange:e=>Pe(a,"assistant",e)},l),actions:React.createElement(React.Fragment,null,Ee&&React.createElement(R.M,{rounded:!0,icon:"plus",onClick:()=>Ge(a)}),React.createElement(R.M,{rounded:!0,icon:"trash",onClick:()=>(e=>{const t=ue.filter(((t,a)=>a!==e-1));pe(t),0===t.length&&Se({instructions:Re,entries:[]})})(a)}))}}))}),[ue,de,Z,Ee,Pe,Me]),De=async e=>{if(confirm(ge.A.ALERTS.DELETE_FINETUNE)){f(!0);try{await J("finetunes_deleted",[...W,e])}catch(e){console.error(e),alert(ge.A.ALERTS.CHECK_CONSOLE)}f(!1)}},Fe=St((()=>null==Y?void 0:Y.sort(((e,t)=>t.created_at-e.created_at)).map((e=>{const t=e.id,a=e.filename,n=new Date(1e3*e.created_at),l="fine-tune"===e.purpose;return{status:React.createElement($t,{status:e.status,includeText:!0}),id:t,filename:a,purpose:e.purpose,filesize:(0,y.z3)(e.bytes),createdOn:React.createElement(React.Fragment,null,n.toLocaleDateString(),React.createElement("br",null),n.toLocaleTimeString()),actions:React.createElement(React.Fragment,null,React.createElement(R.M,{disabled:!l,icon:"wand",onClick:()=>p(t)},"Train Model"),React.createElement(R.M,{rounded:!0,icon:"arrow-down",onClick:()=>(async(e,t)=>{f(!0);try{const a=await(0,y.IU)(`${v.y0}/openai/files/download`,{method:"POST",nonce:v.ok,json:{envId:H,fileId:e}});if(a.success){const e=new Blob([a.data],{type:"text/plain"}),n=window.URL.createObjectURL(e),l=document.createElement("a");l.setAttribute("href",n),l.setAttribute("download",`${t}`),document.body.appendChild(l),l.click(),l.remove()}else alert(a.message)}catch(e){console.error(e),alert(ge.A.ALERTS.CHECK_CONSOLE)}f(!1)})(t,a)}),React.createElement(R.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>(async e=>{f(!0);try{const t=await(0,y.IU)(`${v.y0}/openai/files/delete`,{method:"POST",nonce:v.ok,json:{envId:H,fileId:e}});t.success?await Ie():alert(t.message)}catch(e){console.error(e),alert(ge.A.ALERTS.CHECK_CONSOLE)}f(!1)})(t)}))}}))),[Y]),Ue=e=>W.includes(e.model)||W.includes(e.id),Be=e=>"failed"===e.status||"cancelled"===e.status,$e=e=>!Be(e)&&!Ue(e),He=St((()=>{if(!q)return[];let e=q;return"current"===_?e=e.filter($e):"deleted"===_?e=e.filter(Ue):"failed"===_&&(e=e.filter(Be)),e.map((e=>{const t=new Date(e.createdOn);return{...e,model:e.model?e.model:React.createElement(Lt,{createdOn:e.createdOn,estimatedOn:e.estimatedOn}),status:React.createElement($t,{status:e.status,includeText:!0}),createdOn:React.createElement(React.Fragment,null,t.toLocaleDateString(),React.createElement("br",null),t.toLocaleTimeString()),actions:React.createElement(React.Fragment,null,"succeeded"===e.status&&React.createElement(R.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>(async e=>{if(confirm(ge.A.ALERTS.DELETE_FINETUNE)){f(!0);try{const t=await(0,y.IU)(`${v.y0}/openai/finetunes/delete`,{method:"POST",nonce:v.ok,json:{envId:H,modelId:e}});t.success?await J("finetunes_deleted",[...W,e]):t.message.indexOf("does not exist")>-1?(alert(ge.A.ALERTS.FINETUNE_ALREADY_DELETED),await J("finetunes_deleted",[...W,e])):alert(t.message)}catch(e){console.error(e),alert(ge.A.ALERTS.CHECK_CONSOLE)}f(!1)}})(e.model)}),"cancelled"===e.status&&React.createElement(R.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>De(e.id)}),"failed"===e.status&&React.createElement(R.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>De(e.id)}),"pending"===e.status&&React.createElement(R.M,{className:"danger",rounded:!0,icon:"close",onClick:()=>(async e=>{f(!0);try{const t=await(0,y.IU)(`${v.y0}/openai/finetunes/cancel`,{method:"POST",nonce:v.ok,json:{envId:H,finetuneId:e}});t.success?Ne():alert(t.message)}catch(e){console.error(e),alert(ge.A.ALERTS.CHECK_CONSOLE)}f(!1)})(e.id)}))}}))}),[_,W,q]),je=V||g,ze=St((()=>{const e=new Date,t=e.getFullYear(),a=e.getMonth()+1,n=e.getDate(),l=e.getHours(),o=e.getMinutes(),r=e.getSeconds();return`${X}:ft-your-org:${I}-${t}-${a<10?"0"+a:a}-${n<10?"0"+n:n}-${l<10?"0"+l:l}-${o<10?"0"+o:o}-${r<10?"0"+r:r}`}),[I,X]),Ge=(e,t="user",a="Hello!")=>{const n=ue.map(((n,l)=>l===e-1?{...n,messages:[...n.messages,{role:t,content:a}]}:n));pe(n)},We=Mt(null),qe=null==q?void 0:q.filter($e).length,Ve=null==q?void 0:q.filter(Be).length,Ke=null==q?void 0:q.filter(Ue).length,Ye=St((()=>React.createElement(te.u,{scrolldown:!0,value:H,onChange:j,style:{marginLeft:5}},z.filter((e=>"openai"===e.type)).map((e=>React.createElement(te.j,{key:e.id,value:e.id,label:e.name}))))),[H,z]),Xe=St((()=>{if(0===_e.length)return null;const e=_e.slice(0,10).map(((e,t)=>React.createElement("span",{key:e,style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>(e=>{const t=Math.floor(e/Z);me(t+1)})(e)},e,t<_e.slice(0,10).length-1?", ":"")));return _e.length>10?React.createElement(React.Fragment,null,"Some entries are invalid, for example those ones: ",e,", and ",_e.length-10," more."):React.createElement(React.Fragment,null,"Some entries are invalid, for example those ones: ",e)}),[_e,Z]);return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{fullWidth:!0,minimal:!0},React.createElement(oe.X,{variant:"warning",style:{marginBottom:10}},React.createElement("b",null,"OpenAI is phasing out self-serve fine-tuning.")," New fine-tuning jobs have been blocked for organizations without prior fine-tuning activity since ",React.createElement("b",null,"May 7, 2026"),", and the ability to create new fine-tuning jobs will be removed for all organizations on ",React.createElement("b",null,"January 6, 2027"),". Already-trained models continue to work for inference. See OpenAI's ",React.createElement("a",{href:"https://developers.openai.com/api/docs/deprecations",target:"_blank",rel:"noreferrer"},"deprecations page")," for details."),React.createElement(h._,{inversed:!0,currentTab:b,onChange:(e,t)=>{w(t.key)},action:React.createElement(React.Fragment,null,React.createElement("div",{style:{flex:"auto"}}),"finetunes"===b&&React.createElement(React.Fragment,null,React.createElement(R.M,{disabled:g,busy:"finetunes"===g,onClick:Ne,className:"secondary"},ge.A.COMMON.REFRESH_MODELS),Ye),"files"===b&&React.createElement(React.Fragment,null,React.createElement(R.M,{disabled:g,onClick:async()=>{f(!0),await Ie(),f(!1)},className:"secondary"},"Refresh Files"),Ye),"editor"===b&&React.createElement(React.Fragment,null,React.createElement("label",{style:{marginRight:10}},"Filename:"),React.createElement(ae.A,{disabled:!Ae||g,value:Ae?ye:"",onChange:ve,style:{width:220,marginRight:5}}),React.createElement(R.M,{className:"secondary",disabled:!be||g,icon:"upload",onClick:async()=>{f(!0);try{const e=ue.map((e=>(0,y.F1)(e))).join("\n"),t=await(0,y.IU)(`${v.y0}/openai/files/upload`,{method:"POST",nonce:v.ok,json:{envId:H,filename:ye,data:e}});await Ie(),t.success?(xe(!1),alert(ge.A.ALERTS.DATASET_UPLOADED),w("files")):alert(t.message)}catch(e){console.error(e),alert(ge.A.ALERTS.CHECK_CONSOLE)}f(!1)}},"Upload to OpenAI"),Ye))},React.createElement(h.V,{title:ge.A.COMMON.MODELS,key:"finetunes"},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("div",null,(0,y.FE)(ge.A.FINETUNING.MODELS_INTRO)),React.createElement(ne.o,{value:_,onChange:e=>{C(e)}},React.createElement(ne.K,{title:"Current",value:"current",count:qe??"-"}),React.createElement(ne.K,{title:"Failed",value:"failed",count:Ve??"-"}),React.createElement(ne.K,{title:"Deleted",value:"deleted",count:Ke??"-"}))),React.createElement(ee.g,null),React.createElement(tt.o,{busy:je,data:He,columns:Bt,emptyMessage:ge.A.FINETUNING.NO_FINETUNES_YET}),React.createElement("div",{style:{marginTop:5,display:"flex",justifyContent:"end",lineHeight:"12px",alignItems:"center"}},React.createElement(R.M,{small:!0,disabled:g,busy:"clean"===g,onClick:async()=>{f("clean"),await pt(H),await a(),f(!1)},className:"primary"},ge.A.FINETUNING.CLEAN_MODELS_LIST),React.createElement("small",{style:{marginLeft:5}},ge.A.FINETUNING.DELETED_FINETUNE_ISSUE))),React.createElement(h.V,{title:ge.A.COMMON.FILES,key:"files"},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("div",null,(0,y.FE)(ge.A.FINETUNING.FILES_INTRO)),React.createElement(ne.o,{value:A,onChange:e=>{T(e)}},React.createElement(ne.K,{title:"Datasets",value:"fine-tune"}),React.createElement(ne.K,{title:"All",value:null}))),React.createElement(ee.g,null),React.createElement(tt.o,{busy:je,data:Fe,columns:Ut,emptyMessage:React.createElement(React.Fragment,null,"You do not have any dataset files yet.")})),React.createElement(h.V,{title:ge.A.FINETUNING.DATASET_EDITOR,key:"editor"},!re&&React.createElement("p",{style:{color:"red"}},ge.A.FINETUNING.HUGE_DATASET_WARNING),React.createElement(at.V,{style:{display:"flex"}},React.createElement(R.M,{icon:"plus",onClick:()=>((e="Question?",t="Answer.")=>{pe([...ue,{messages:[{role:"system",content:Re},{role:"user",content:e},{role:"assistant",content:t}]}])})(),disabled:g},"Add Entry"),Ee&&React.createElement(R.M,{onClick:()=>Oe(Re),disabled:g},"Rewrite Instructions"),React.createElement("div",{style:{flex:"auto"}}),React.createElement(nt.S,{style:{marginLeft:5},onLabel:"Expert",offLabel:"Easy",width:90,onBackgroundColor:i.purple,offBackgroundColor:i.green,onChange:he,checked:Ee}),React.createElement(lt.Z,{ref:We,onSelectFiles:async e=>{for(let t=0;t{const t=e.target.result;let a=[];if(l)try{a=JSON.parse(t)}catch(e){return console.error(e),void alert(ge.A.ALERTS.ONLY_SUPPORTS_FILES)}else if(o){a=t.split("\n").map((e=>{e=e.trim();try{return JSON.parse(e)}catch(t){return console.error(t,e),null}}));const e=a.every((e=>e.messages));e||(i=!0)}else if(r){a=Ze().parse(t,{header:!0,skipEmptyLines:!0}).data,console.log("The CSV was loaded!",a),i=!0}const n=["prompt","question","q"],s=["completion","reply","a"],c=Array.isArray(a)?a.length:0;if(i&&(a=a.map((e=>{const t=Object.keys(e).reduce(((t,a)=>(t[a.toLowerCase()]=e[a],t)),{}),a=n.find((e=>t[e])),l=s.find((e=>t[e])),o=t[a],r=t[l],i=null==r?void 0:r.replace(/\n\n$/g,""),c=null==o?void 0:o.replace(/\n\n###\n\n$/g,"");return o&&r?{messages:[{role:"system",content:Re},{role:"user",content:c.trim()},{role:"assistant",content:i.trim()}]}:null}))),a=a.filter((e=>e)),i&&c>0&&0===a.length)return void alert(`No usable rows were found. Expected a prompt column (one of: ${n.join(", ")}) and a completion column (one of: ${s.join(", ")}).`);const d=a.length>0&&a.every((e=>null==e?void 0:e.messages));d?pe(a):alert(ge.A.ALERTS.ONLY_SUPPORTS_FILES)},n.readAsText(a)):(alert(ge.A.ALERTS.ONLY_SUPPORTS_FILES),console.warn(a))}},accept:"",style:{paddingLeft:5}},React.createElement(R.M,{className:"secondary",onClick:()=>We.current.click()},"Import")),React.createElement(R.M,{disabled:!Ae,onClick:xe,className:"secondary"},"Clear")),React.createElement(ee.g,null),ue.length>0&&(null==_e?void 0:_e.length)>0&&React.createElement(React.Fragment,null,React.createElement(oe.X,{variant:"danger"},Xe),React.createElement(ee.g,null)),React.createElement(le.Zc,{keepState:"datasetEditor"},React.createElement(le.y2,{title:"Dataset"},React.createElement(ee.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(ot.Q,{currentPage:de,limit:Z,total:Ae,onCurrentPageChanged:me,onClick:me})),React.createElement(ee.g,{tiny:!0}),React.createElement(tt.o,{busy:g,data:Le,columns:Ee?Ft:Dt,emptyMessage:React.createElement(React.Fragment,null,"You can import a file, or create manually each entry by clicking ",React.createElement("b",null,"Add"),".")}),React.createElement(ee.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(ot.Q,{currentPage:de,limit:Z,total:Ae,onCurrentPageChanged:me,onClick:me}),React.createElement(R.M,{disabled:!Ae,style:{marginLeft:5},onClick:()=>{const e=(0,y.F1)(ue,2),t=new Blob([e],{type:"text/plain"}),a=URL.createObjectURL(t),n=document.createElement("a");n.href=a;const l=new Date,o=`${l.getFullYear()}-${l.getMonth()+1}-${l.getDate()}-WP.json`;n.download=o,document.body.appendChild(n),n.click(),document.body.removeChild(n)}},"Export as JSON"))),React.createElement(le.y2,{title:ge.A.COMMON.CONTEXT},React.createElement(ee.g,null),React.createElement("span",null,"The instructions are the same for all entries. It is used as the ",React.createElement("i",null,"system")," (and first) message in each conversation. More information ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset",target:"_blank",rel:"noreferrer"},"here"),"."),React.createElement(ee.g,null),React.createElement(ie.m,{id:"instructions",name:"instructions",rows:2,value:Re,onBlur:ke,onEnter:ke})),React.createElement(le.y2,{title:"Generator"},React.createElement(ee.g,null),React.createElement(Ot,{options:e,instructions:Re,setMessages:pe}),React.createElement(oe.X,{variant:"danger"},"Use this feature with caution. The AI will generate questions and answers for each of your post based on the given prompt, and they will be added to your dataset. Keep in mind that this process may be ",React.createElement("u",null,"extremely slow")," and require a ",React.createElement("u",null,"significant number of API calls"),", resulting in a ",React.createElement("u",null,"high cost"),".")),React.createElement(le.y2,{title:"Instructions"},React.createElement("p",null,"You can create your dataset by importing a file (two columns, in the CSV, JSON or JSONL format) or manually by clicking ",React.createElement("b",null,"Add Entry"),". For the format, check this ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://gist.github.com/jordymeow/a855df4a1f644bb3df8c78ea87c1a2ca"},"JSON Example")," (more complex) or this ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://gist.github.com/jordymeow/e0c80ebeefe4d4d07ae39995c561ba4a"},"CSV Example")," (simpler). ",React.createElement("b",null,"Writing datasets is actually complex.")," Please have a look at OpenAI's ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/fine-tuning",target:"_blank",rel:"noreferrer"},"tutorials"),". And here is Meow Apps' ",React.createElement("a",{href:"https://meowapps.com/wordpress-chatbot-finetuned-model-ai/",target:"_blank",rel:"noreferrer"},"simplified tutorial"),". Is your dataset ready? Modify the filename to your liking and click ",React.createElement("b",null,"Upload to OpenAI"),"."),React.createElement("p",null,"To avoid losing your work, this data is kept in your browser's local storage."))))))),React.createElement(rt.L,null,React.createElement(se.n,{isOpen:c,title:"Error",onRequestClose:()=>d(),okButton:{label:"Ok",onClick:()=>d()},content:React.createElement(React.Fragment,null,React.createElement("p",null,null==c?void 0:c.message))}),React.createElement(se.n,{isOpen:m,title:"Train a new model",onRequestClose:()=>p(),okButton:{label:"Start",disabled:g,onClick:async()=>{const e=m,t=I;f(!0);let a={envId:H,fileId:e,model:X,suffix:t};x&&(a={...a,nEpochs:k,batchSize:M,learningRateMultiplier:L,promptLossWeight:F});try{const e=await(0,y.IU)(`${v.y0}/openai/files/finetune`,{method:"POST",nonce:v.ok,json:a});e.success?(Ne(),alert(ge.A.ALERTS.FINETUNING_STARTED),w("finetunes"),p()):alert(e.message)}catch(e){console.log(e.message),alert(e.message)}f(!1)}},cancelButton:{label:"Close",disabled:g,onClick:()=>p()},content:React.createElement(React.Fragment,null,React.createElement("p",null,"Exciting! 🎵 You are about to create your own new model, based on your dataset. You simply need to select a base model, and optionally, to modify the ",React.createElement("a",{href:"https://beta.openai.com/docs/guides/fine-tuning/hyperparameters",target:"_blank",rel:"noreferrer"},"hyperparameters"),". Before starting the process, make sure that:"),React.createElement("ul",null,React.createElement("li",null,"✅ The dataset is well-defined."),React.createElement("li",null,"✅ You understand ",React.createElement("a",{href:"https://openai.com/api/pricing/#faq-fine-tuning-pricing-calculation",target:"_blank",rel:"noreferrer"},"OpenAI pricing")," about fine-tuning.")),React.createElement("label",null,"Base model:"),React.createElement(ee.g,{height:5}),React.createElement(ae.A,{value:X,onChange:Q,description:React.createElement(React.Fragment,null,"As of August 2024, you can use ",React.createElement("a",{href:"#",onClick:()=>Q("gpt-4o-mini-2024-07-18")},"gpt-4o-mini-2024-07-18"),", ",React.createElement("a",{href:"#",onClick:()=>Q("gpt-3.5-turbo-0125")},"gpt-3.5-turbo-0125"),", or any of your previously fine-tuned models. Check all the available models ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/model-optimization",target:"_blank",rel:"noreferrer"},"here"),".")}),React.createElement(ee.g,{height:10}),React.createElement("label",null,"Suffix (for new model name):"),React.createElement(ee.g,{height:5}),React.createElement(ae.A,{value:I,onChange:N}),React.createElement(ee.g,{height:5}),React.createElement("small",null,"The name of the new model name will be decided by OpenAI. You can customize it a bit with a ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/fine-tuning/create-a-fine-tuned-model",target:"_blank",rel:"noreferrer"},"suffix"),". Preview: ",React.createElement("b",null,ze),"."),React.createElement(ee.g,{line:!0,height:20}),React.createElement(u.R,{label:"Enable HyperParams",checked:x,onChange:O}),x&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"}},React.createElement("label",{style:{marginRight:5}},"Number of Epochs:"),React.createElement(ae.A,{style:{marginRight:5},value:k,onChange:S,type:"number"}),React.createElement("label",{style:{marginRight:5}},"Batch Size:"),React.createElement(ae.A,{value:M,onChange:P,type:"number"})),React.createElement("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"}},React.createElement("label",{style:{marginRight:5}},"Learning Rate Multiplier:"),React.createElement(ae.A,{style:{marginRight:5},value:L,onChange:D,type:"number"}),React.createElement("label",{style:{marginRight:5}},"Prompt Loss Weight:"),React.createElement(ae.A,{value:F,onChange:U,type:"number"}))))})))},{useState:zt}=wp.element,Gt=({options:e,updateOption:t,busy:a})=>{const[n,l]=zt("I would love to live on a tropical island with beautiful and sexy felines, where we could bask in the sun on the sandy beaches, sip on refreshing coconut milk, and enjoy each other's company. While we might occasionally fight in the trees, our days would mostly be spent in peaceful slumber. However, I am not sure of how we would handle any potential disruptions to our idyllic existence if human were to come..."),[o,r]=zt([]),[i,s]=zt(""),[c,m]=zt(!1),p=null==e?void 0:e.chatbot_moderation,g=c||a,h=React.createElement(d.d,{title:ge.A.COMMON.CHATBOT},React.createElement(u.R,{name:"chatbot_moderation",label:ge.A.COMMON.ENABLE,value:"1",checked:p,description:ge.A.SETTINGS.CHATBOT_MODERATION_HELP,onChange:t}));return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(f.z,{busy:g,title:ge.A.COMMON.SETTINGS,className:"primary"},React.createElement("p",null,"You can enable moderation various parts of WordPress. It will slow down the processing a little."),h)),React.createElement(E.Y,{minimal:!0},React.createElement(f.z,{busy:g,title:"AI Moderation Tester",className:"primary"},React.createElement("p",null,"Paste a text below, and check if it is safe for your website. ",React.createElement("b",null,"OpenAI Moderation Model is free!")," Learn more about it ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/moderation/overview",target:"_blank"},"here"),"."),React.createElement(ie.m,{name:"context",rows:8,value:n,onChange:l}),React.createElement(ee.g,null),React.createElement(R.M,{fullWidth:!0,onClick:async()=>{m(!0);const e=await(0,y.IU)(`${v.y0}/ai/moderate`,{method:"POST",nonce:v.ok,json:{text:n}});if(e.success){let t=e.results;r(null==t?void 0:t.results)}else s(e.message);m(!1)}},"Moderation Check"),React.createElement(ee.g,null),React.createElement("label",null,"Results:"),React.createElement("pre",null,(0,y.F1)(o,2))))))};var Wt=a(8970),qt=a(8832),Vt=a(4366),Kt=a(6523);const{useState:Yt,useEffect:Xt,useMemo:Qt}=wp.element,Jt=({modal:e,busy:t,setModal:a,onAddEmbedding:n,onModifyEmbedding:l,supportsImageEmbeddings:o})=>{const[r,i]=Yt(!1);Xt((()=>{"edit"!==(null==e?void 0:e.type)&&"add"!==(null==e?void 0:e.type)||i((null==e?void 0:e.data)||{})}),[e]);const s=Qt((()=>{var t,a,n,l,o,i,s,c,d;return null==e||!e.data||((null==e||null===(t=e.data)||void 0===t?void 0:t.title)!==(null==r?void 0:r.title)||((null==e||null===(a=e.data)||void 0===a?void 0:a.content)!==(null==r?void 0:r.content)||((null==e||null===(n=e.data)||void 0===n?void 0:n.behavior)!==(null==r?void 0:r.behavior)||((null==e||null===(l=e.data)||void 0===l?void 0:l.type)!==(null==r?void 0:r.type)||((null==e||null===(o=e.data)||void 0===o?void 0:o.refId)!==(null==r?void 0:r.refId)||((null==e||null===(i=e.data)||void 0===i?void 0:i.refUrl)!==(null==r?void 0:r.refUrl)||(((null==e||null===(s=e.data)||void 0===s?void 0:s.source)??"")!==((null==r?void 0:r.source)??"")||(((null==e||null===(c=e.data)||void 0===c?void 0:c.partIndex)??"")!==((null==r?void 0:r.partIndex)??"")||((null==e||null===(d=e.data)||void 0===d?void 0:d.partTotal)??"")!==((null==r?void 0:r.partTotal)??"")))))))))}),[e,r]),c="remoteUrl"===(null==r?void 0:r.type),d="mediaId"===(null==r?void 0:r.type),m="edit"===(null==e?void 0:e.type);return React.createElement(React.Fragment,null,React.createElement(se.n,{isOpen:"edit"===(null==e?void 0:e.type)||"add"===(null==e?void 0:e.type),title:"edit"===(null==e?void 0:e.type)?ge.A.COMMON.MODIFY_EMBEDDING:ge.A.COMMON.ADD_EMBEDDING,okButton:{label:"edit"===(null==e?void 0:e.type)?ge.A.COMMON.MODIFY_EMBEDDING:ge.A.COMMON.ADD_EMBEDDING,disabled:!s||t,busy:"addEmbedding"===t,onClick:()=>{"edit"===(null==e?void 0:e.type)?(async()=>{try{await l(r),a(null)}catch(e){alert(e.message)}})():(async()=>{try{await n(r),a(null)}catch(e){alert(e.message)}})()}},cancelButton:{disabled:t,onClick:()=>a(null)},onRequestClose:()=>a(null),content:React.createElement(React.Fragment,null,React.createElement("p",null,"A custom embedding can be a sentence, a paragraph or a whole article. When an user input is made, the AI will search for the best embedding that matches the user input and will be able to reply with more accuracy."),React.createElement(ee.g,null),React.createElement("label",null,"Title:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ae.A,{value:null==r?void 0:r.title,placeholder:'Title, like "My Website Information"',description:"This is for your convenience only, it's not used anywhere.",onChange:e=>i({...r,title:e})}),React.createElement(ee.g,null),(m||!c&&!d)&&React.createElement(React.Fragment,null,React.createElement("label",null,"Content:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ie.m,{countable:"chars",maxLength:64e3,description:c?"Content is fetched automatically from the URL.":d?"Content is generated from image metadata.":"The content of your embeddings that will be used by the AI if it matches the user input.",value:null==r?void 0:r.content,onChange:e=>i({...r,content:e}),readOnly:c||d})),React.createElement(ee.g,null),React.createElement("div",{style:{display:"flex",justifyContent:"space-between"}},React.createElement("div",{style:{flex:3}},React.createElement("label",null,"Behavior:"),React.createElement(ee.g,{tiny:!0}),React.createElement(te.u,{scrolldown:!0,name:"behavior",disabled:t||!0,value:null==r?void 0:r.behavior,onChange:e=>{i({...r,behavior:e})}},React.createElement(te.j,{value:"context",label:"Context"}),React.createElement(te.j,{value:"reply",label:"Reply"}))),React.createElement("div",{style:{flex:3,marginLeft:5}},React.createElement("label",null,"Type:"),React.createElement(ee.g,{tiny:!0}),React.createElement(te.u,{scrolldown:!0,name:"type",disabled:t||m,value:null==r?void 0:r.type,onChange:e=>{i("remoteUrl"===e||"mediaId"===e?{...r,type:e,content:""}:{...r,type:e})}},React.createElement(te.j,{value:"manual",label:"Manual"}),React.createElement(te.j,{value:"remoteUrl",label:"Remote URL"}),React.createElement(te.j,{value:"postId",label:"Related to Post"}),o&&React.createElement(te.j,{value:"mediaId",label:"Related to Media"}))),"postId"===(null==r?void 0:r.type)&&React.createElement("div",{style:{flex:1,marginLeft:5}},React.createElement("label",null,"Post ID:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ae.A,{value:null==r?void 0:r.refId,disabled:!0,onChange:e=>i({...r,refId:e})})),d&&React.createElement("div",{style:{flex:1,marginLeft:5}},React.createElement("label",null,"Media ID:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ae.A,{value:(null==r?void 0:r.refId)||"",disabled:m,onChange:e=>i({...r,refId:e})})),c&&React.createElement("div",{style:{flex:3,marginLeft:5}},React.createElement("label",null,"URL:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ae.A,{value:(null==r?void 0:r.refUrl)||"",placeholder:"https://example.com/article",disabled:m,onChange:e=>i({...r,refUrl:e})}))),React.createElement(ee.g,null),React.createElement("div",{style:{display:"flex",justifyContent:"space-between"}},React.createElement("div",{style:{flex:3}},React.createElement("label",null,"Source:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ae.A,{value:(null==r?void 0:r.source)||"",placeholder:"Filename, URL, post title, manual...",description:"Where this chunk came from. Written to the vector DB metadata.",onChange:e=>i({...r,source:e})})),React.createElement("div",{style:{flex:1,marginLeft:5}},React.createElement("label",null,"Part #:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ae.A,{type:"number",value:(null==r?void 0:r.partIndex)??"",onChange:e=>i({...r,partIndex:""===e?null:Number(e)})})),React.createElement("div",{style:{flex:1,marginLeft:5}},React.createElement("label",null,"Of:"),React.createElement(ee.g,{tiny:!0}),React.createElement(ae.A,{type:"number",value:(null==r?void 0:r.partTotal)??"",onChange:e=>i({...r,partTotal:""===e?null:Number(e)})}))))}))},{useState:Zt}=wp.element,ea=({modal:e,setModal:t})=>{const[a,n]=Zt(!1),[l,o]=Zt(0),[r,i]=Zt(0),s=null==e?void 0:e.data,c=async()=>{let e=!1;const t={page:1,limit:20,filters:{envId:s.envId,dbIndex:s.dbIndex,dbNS:s.dbNS}};let a=[];for(;!e;){const n=await Oe(t);n.vectors.length<2&&(e=!0),o((()=>n.total)),a=a.concat(n.vectors),i((()=>a.length)),t.page++}return a};return React.createElement(React.Fragment,null,React.createElement(se.n,{isOpen:"export"===(null==e?void 0:e.type),title:"Export Embeddings",onRequestClose:()=>t(null),okButton:{label:"Close",disabled:a,onClick:()=>t(null)},customButtons:React.createElement(React.Fragment,null,React.createElement(R.M,{onClick:async()=>{try{n(!0);const e=await c(),t=Ze().unparse(e),a=new Date,l=a.getFullYear(),r=a.getMonth()+1,i=a.getDate();ze(t,`vectors-${l}-${r}-${i}.csv`),setTimeout((()=>{o(0)}),1e3)}catch(e){console.error(e),alert("An error occurred while exporting vectors. Check your console.")}finally{n(!1)}},disabled:a},"Export CSV"),React.createElement(R.M,{onClick:async()=>{try{n(!0);const e=await c(),t=(0,y.F1)(e,2),a=new Date,l=a.getFullYear(),r=a.getMonth()+1,i=a.getDate();ze(t,`vectors-${l}-${r}-${i}.json`),setTimeout((()=>{o(0)}),1e3)}catch(e){console.error(e),alert("An error occurred while exporting vectors. Check your console.")}finally{n(!1)}},disabled:a},"Export JSON")),content:React.createElement(React.Fragment,null,React.createElement(it.j,{busy:a,style:{flex:"auto"},value:r,max:l}))}))},{useState:ta,useRef:aa}=wp.element,na=({modal:e,setModal:t,onAddEmbedding:a,onModifyEmbedding:n,refreshEmbeddings:l})=>{var o;const[r,i]=ta(!1),[s,c]=ta(0),[d,m]=ta(0),[p,g]=ta({add:[],modify:[],same:[],total:0,isReady:!1}),E=(null==e||null===(o=e.data)||void 0===o?void 0:o.importVectors)??[],[h,f]=ta({envId:!1,dbId:!1,dbIndex:!1,dbNS:!1,title:!0,refId:!0,refUrl:!1}),y=null==e?void 0:e.data,[v,b]=ta(!1),w=aa(!1),_=e=>({id:e.id??null,type:e.type??"manual",title:e.title??"N/A",behavior:e.behavior??"context",envId:(null==y?void 0:y.envId)??null,dbId:e.dbId??null,dbIndex:y.dbIndex??null,dbNS:y.dbNS??null,content:e.content??"",refId:e.refId??null,refUrl:e.refUrl??null}),C=(e,t,a)=>Object.keys(a).every((n=>!a[n]||e[n]===t[n])),A=()=>{t(null),i(!1),c(0),m(0),g({add:[],modify:[],same:[],total:0,isReady:!1})};return React.createElement(React.Fragment,null,React.createElement(se.n,{isOpen:"import"===(null==e?void 0:e.type),title:"Import Embeddings",onRequestClose:A,okButton:{label:"Close",onClick:A,disabled:r},customButtons:React.createElement(React.Fragment,null,React.createElement(R.M,{onClick:async()=>{try{let e=!1;const t={page:1,limit:20,filters:{envId:y.envId,dbIndex:y.dbIndex,dbNS:y.dbNS}};let a=[];for(i("stepOne");!e;){const n=await Oe(t);n.vectors.length<2&&(e=!0),c((()=>n.total)),a=a.concat(n.vectors),m((()=>a.length)),t.page++}(async(e,t)=>{const a=[],n=[],l=[];console.log("Calculate Diff",{currentVectors:e,importVectors:t});for(const o of t){const t=_(o),r=e.find((e=>C(e,t,h)));console.log("Matched Vector",{cleanVector:{...t},matchedVector:{...r}}),r?t.id=r.id:delete t.id;const i=e.find((e=>e.id===t.id));i&&t.content===i.content&&t.title===i.title?l.push(t):t.id?n.push(t):a.push(t)}const o=a.length+n.length;g({add:a,modify:n,same:l,total:o,isReady:!0}),console.log("Embeddings Diff",{add:a,modify:n,same:l,total:o})})(a,E)}catch(e){console.error(e),alert("An error occurred while retrieving your current embeddings. Check your console.")}finally{i(!1)}},disabled:r},"Check Differences"),React.createElement(R.M,{onClick:async()=>{try{c(p.add.length+p.modify.length),m(0),b(!1),w.current=!1,i("stepTwo");for(const e of p.add){if(w.current)break;await a(e,!0,!0),m((e=>e+1))}for(const e of p.modify){if(w.current)break;await n(e,!0,!0),m((e=>e+1))}l&&l(),w.current?alert(`Import stopped. ${d} of ${p.total} embeddings were updated.`):alert("All embeddings have been updated."),g({add:[],modify:[],same:[],total:0,isReady:!1}),A()}catch(e){console.error(e),alert("An error occurred while updating embeddings. Check your console.")}finally{i(!1),b(!1),w.current=!1}},disabled:r||0===p.total},"Apply Changes")),content:React.createElement(React.Fragment,null,React.createElement("p",null,"There are ",React.createElement("b",null,E.length," embeddings")," in the file."),React.createElement(ee.g,null),React.createElement(le.y2,{title:"1 - Check Differences"}),React.createElement("p",null,"Calculates the differences between the embeddings in your file and the ones currently registered in AI Engine. Based on that, a list of changes will be created. Please note that the environment, index and namespace that might be set in the file will be ignored."),React.createElement("p",{style:{marginTop:10}},"An embedding will be considered the same entry based on:"),React.createElement(ee.g,null),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{marginLeft:15}},React.createElement(u.R,{small:!0,label:"DB ID",disabled:!1,checked:h.dbId,onChange:()=>f({...h,dbId:!h.dbId})})),React.createElement("div",{style:{marginLeft:15}},React.createElement(u.R,{small:!0,label:"Title",disabled:!1,checked:h.title,onChange:()=>f({...h,title:!h.title})})),React.createElement("div",{style:{marginLeft:15}},React.createElement(u.R,{small:!0,label:"Ref (Post ID)",disabled:!1,checked:h.refId,onChange:()=>f({...h,refId:!h.refId})})),React.createElement("div",{style:{marginLeft:15}},React.createElement(u.R,{small:!0,label:"Ref (URL)",disabled:!1,checked:h.refUrl,onChange:()=>f({...h,refUrl:!h.refUrl})}))),"stepOne"===r&&React.createElement(React.Fragment,null,React.createElement(ee.g,null),React.createElement(it.j,{busy:r,style:{flex:"auto"},value:d,max:s})),React.createElement(ee.g,null),React.createElement(le.y2,{title:"2 - Apply Changes"}),!p.isReady&&React.createElement("i",null,"Waiting for diff..."),p.isReady&&React.createElement(React.Fragment,null,React.createElement("p",null,"There are ",p.same.length>=1&&React.createElement("span",null,React.createElement("b",null,p.same.length," identical embeddings")," (with the same title and content). They will be ignored. "),React.createElement("span",null,"Changes to apply:")),React.createElement("ul",null,React.createElement("li",null,"👉 Add: ",React.createElement("b",null,p.add.length)),React.createElement("li",null,"👉 Modify: ",React.createElement("b",null,p.modify.length)))),"stepTwo"===r&&React.createElement(React.Fragment,null,React.createElement(ee.g,null),React.createElement(it.j,{busy:!v,style:{flex:"auto"},value:d,max:s,onStopClick:v?null:()=>{b(!0),w.current=!0}})),React.createElement(ee.g,null))}))},{useState:la,useRef:oa}=wp.element,ra=({modal:e,setModal:t,onAddEmbedding:a,refreshEmbeddings:n})=>{var l;const[o,r]=la(1),[i,s]=la(""),[c,d]=la([]),[m,u]=la(!1),[p,g]=la(0),[E,h]=la(0),[f,b]=la(!1),w=oa(!1),_="bulk-url"===(null==e?void 0:e.type),C=null==e||null===(l=e.data)||void 0===l?void 0:l.envId,A=e=>e.split("\n").map((e=>e.trim())).filter((e=>{try{return new URL(e),!0}catch{return!1}})).filter(((e,t,a)=>a.indexOf(e)===t)),T=c.length>0&&c.every((e=>e.title.trim())),I=()=>{t(null),r(1),s(""),d([]),u(!1),g(0),h(0),b(!1),w.current=!1},N=A(i).length;return React.createElement(se.n,{isOpen:_,title:1===o?"Bulk Add Remote URLs":`Review URLs (${c.length})`,onRequestClose:I,okButton:{label:"Close",onClick:I,disabled:!!m},customButtons:React.createElement(React.Fragment,null,1===o&&React.createElement(R.M,{onClick:()=>{const e=A(i);if(0===e.length)return;const t={};for(const e of c)e.title&&(t[e.url]=e.title);const a=e.map((e=>({url:e,title:t[e]||""})));d(a),r(2)},disabled:0===N},"Next (",N," URL",1!==N?"s":"",")"),2===o&&!m&&React.createElement(React.Fragment,null,React.createElement(R.M,{onClick:()=>{r(1)}},"Previous"),React.createElement(R.M,{onClick:async()=>{const e=c.filter((e=>!e.title)).map((e=>e.url));if(0!==e.length){u("fetchingTitles"),g(e.length),h(0);try{for(let t=0;te.map((e=>n.titles[e.url]&&!e.title?{...e,title:n.titles[e.url]}:e)))),h((t=>Math.min(t+a.length,e.length)))}}catch(e){console.error("Failed to fetch titles:",e)}finally{u(!1)}}},disabled:c.every((e=>e.title.trim()))},"Get Titles"),React.createElement(R.M,{className:"primary",onClick:async()=>{u("adding"),g(c.length),h(0),b(!1),w.current=!1;try{for(const e of c){if(w.current)break;await a({type:"remoteUrl",title:e.title,refUrl:e.url,envId:C,content:""},!0,!0),h((e=>e+1))}n&&n()}catch(e){console.error("Bulk add error:",e)}finally{u(!1),b(!1),w.current=!1}},disabled:!T},"Bulk Add"))),content:React.createElement(React.Fragment,null,1===o&&React.createElement(React.Fragment,null,React.createElement("p",null,"Paste URLs below, one per line. They will be added as Remote URL embeddings."),React.createElement(ee.g,null),React.createElement(ie.m,{value:i,onChange:s,placeholder:"https://example.com/page-1\nhttps://example.com/page-2\nhttps://example.com/page-3",style:{minHeight:200,fontFamily:"monospace",fontSize:12}})),2===o&&React.createElement(React.Fragment,null,React.createElement("div",{style:{maxHeight:400,overflowY:"auto"}},React.createElement("table",{style:{width:"100%",borderCollapse:"collapse"}},React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",{style:{textAlign:"left",padding:"4px 8px",borderBottom:"1px solid #ddd",width:"40%"}},"URL"),React.createElement("th",{style:{textAlign:"left",padding:"4px 8px",borderBottom:"1px solid #ddd"}},"Title"),React.createElement("th",{style:{padding:"4px",borderBottom:"1px solid #ddd",width:30}}))),React.createElement("tbody",null,c.map(((e,t)=>React.createElement("tr",{key:t},React.createElement("td",{style:{padding:"4px 8px",borderBottom:"1px solid #eee",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},title:e.url},e.url),React.createElement("td",{style:{padding:"4px 8px",borderBottom:"1px solid #eee"}},React.createElement(ae.A,{value:e.title,placeholder:"Title (required)",style:{width:"100%"},onChange:e=>((e,t)=>{d((a=>a.map(((a,n)=>n===e?{...a,title:t}:a))))})(t,e)})),React.createElement("td",{style:{padding:"4px",borderBottom:"1px solid #eee",textAlign:"center"}},React.createElement(R.M,{className:"danger",rounded:!0,icon:"trash",disabled:!!m,onClick:()=>(e=>{d((t=>t.filter(((t,a)=>a!==e))))})(t)})))))))),"fetchingTitles"===m&&React.createElement(React.Fragment,null,React.createElement(ee.g,null),React.createElement(it.j,{busy:!0,value:E,max:p})),"adding"===m&&React.createElement(React.Fragment,null,React.createElement(ee.g,null),React.createElement(it.j,{busy:!f,value:E,max:p,onStopClick:f?null:()=>{b(!0),w.current=!0}}))))})},{useState:ia,useRef:sa}=wp.element,ca=[".pdf",".docx",".doc",".pptx",".xlsx",".csv",".md",".txt",".json",".html",".htm",".tex",".c",".cpp",".cs",".css",".go",".java",".js",".ts",".php",".py",".rb",".sh"];function da(e){if(!e||e<=0)return"0 B";const t=["B","KB","MB","GB"];let a=0,n=e;for(;n>=1024&&a=10?0:1)} ${t[a]}`}const ma=({modal:e,setModal:t,onAdded:a})=>{var n;const l="upload-file"===(null==e?void 0:e.type),o=(null==e||null===(n=e.data)||void 0===n?void 0:n.envId)??null,r=sa(null),[i,s]=ia(!1),[c,d]=ia(null),[m,u]=ia(null),p=()=>{i||(u(null),d(null),t({type:null,data:null}))};return React.createElement(se.n,{isOpen:l,onRequestClose:p,title:"Upload File to OpenAI Vector Store",content:React.createElement("div",null,React.createElement("p",{style:{marginTop:0}},"Drop or select a file to send it directly to OpenAI. OpenAI handles parsing, chunking and embedding internally — no local processing required."),React.createElement(ee.g,null),React.createElement("input",{ref:r,type:"file",style:{display:"none"},accept:ca.join(","),onChange:e=>{var t;d(null);const a=null==e||null===(t=e.target)||void 0===t?void 0:t.files;a&&0!==a.length&&u(a[0])}}),React.createElement(R.M,{fullWidth:!0,className:"primary",icon:"file-upload",disabled:i,onClick:()=>{var e;return null===(e=r.current)||void 0===e?void 0:e.click()}},m?`Selected: ${m.name}`:"Choose a file"),m&&React.createElement("p",{style:{fontSize:12,color:"#666",marginTop:8}},m.name," — ",da(m.size)),c&&React.createElement(React.Fragment,null,React.createElement(ee.g,null),React.createElement(oe.X,{variant:"danger"},c))),okButton:{label:i?"Uploading…":"Upload",onClick:async()=>{if(m&&o){s(!0),d(null);try{const e=new FormData;e.append("file",m),e.append("envId",o);const n=await fetch(`${v.y0}/vectors/upload_file`,{method:"POST",headers:{"X-WP-Nonce":v.ok},body:e}),l=await n.json();if(!n.ok||!l.success)throw new Error(l.message||`Upload failed (HTTP ${n.status}).`);a&&a(l.vector),u(null),t({type:null,data:null})}catch(e){console.error(e),d(e.message||"Upload failed.")}finally{s(!1)}}},disabled:!m||i},cancelButton:{label:"Cancel",onClick:p,disabled:i}})},{useState:ua}=wp.element,pa=e=>"chroma"===e?{name:"New Chroma Environment",type:"chroma",apikey:"",server:"https://api.trychroma.com",deployment:"cloud",tenant:"",database:"default_database",collection:"mwai",embeddings_source:"Qwen/Qwen3-Embedding-0.6B"}:"qdrant"===e?{name:"New Qdrant Environment",type:"qdrant",apikey:"",server:""}:"pinecone"===e?{name:"New Pinecone Environment",type:"pinecone",apikey:"",server:""}:{name:"New OpenAI Vector Store",type:"openai-vector-store",openai_env_id:null,store_id:""},ga=[{type:"openai-vector-store",name:"OpenAI Vector Store",tagline:"Easiest if you already use OpenAI",description:"Single API. No extra account, no extra bill. Uses your existing OpenAI environment.",accent:"#10a37f",badge:"Recommended"},{type:"chroma",name:"Chroma",tagline:"Provider-agnostic, free tier available",description:"Fast and affordable. Works with any AI provider. Cloud or self-hosted.",accent:"#3b82f6"},{type:"qdrant",name:"Qdrant",tagline:"High-performance, self-hostable",description:"Production-grade vector search. Cloud or self-hosted, with rich filtering.",accent:"#7c3aed"},{type:"pinecone",name:"Pinecone",tagline:"Managed, enterprise-ready",description:"Fully-managed vector database. Established, with broad ecosystem support.",accent:"#f59e0b"}],Ea=({card:e,hovered:t,onHover:a,onLeave:n,onClick:l})=>{const o=t===e.type;return React.createElement("div",{onMouseEnter:()=>a(e.type),onMouseLeave:n,onClick:()=>l(e.type),style:{flex:1,minWidth:200,padding:16,border:o?`2px solid ${e.accent}`:"2px solid #e5e7eb",borderRadius:8,background:o?"#f9fafb":"#fff",cursor:"pointer",transition:"all 0.15s ease",boxShadow:o?"0 4px 12px rgba(0,0,0,0.08)":"none"}},e.badge&&React.createElement("div",{style:{display:"inline-block",background:e.accent,color:"#fff",fontSize:9,fontWeight:600,padding:"2px 7px",borderRadius:10,textTransform:"uppercase",letterSpacing:.5,marginBottom:6}},e.badge),React.createElement("div",{style:{fontWeight:600,fontSize:15,color:e.accent,marginBottom:4}},e.name),React.createElement("div",{style:{fontSize:12,color:"#6b7280",fontStyle:"italic",marginBottom:8}},e.tagline),React.createElement("div",{style:{fontSize:12,color:"#374151",lineHeight:1.4}},e.description))},ha=({isOpen:e,onClose:t,onPick:a})=>{const[n,l]=ua(null);return React.createElement(se.n,{isOpen:e,title:"New Knowledge Environment",onRequestClose:t,okButton:{label:"Cancel",onClick:t},content:React.createElement(React.Fragment,null,React.createElement("p",{style:{marginTop:0,marginBottom:16,color:"#374151"}},"Pick a vector database to store your knowledge."," ",React.createElement("a",{href:"https://ai.thehiddendocs.com/knowledge/",target:"_blank",rel:"noopener noreferrer"},"Learn more ↗")),React.createElement("div",{style:{display:"flex",gap:12,flexWrap:"wrap"}},ga.map((e=>React.createElement(Ea,{key:e.type,card:e,hovered:n,onHover:l,onLeave:()=>l(null),onClick:a})))))})},{useState:Ra,useMemo:fa,useEffect:ya,useRef:va}=wp.element,ba=({modal:e,setModal:t,onAddEmbedding:n,environment:l})=>{const[o,r]=Ra(null);return ya((()=>{v.am&&!o&&Promise.all([a.e(121),a.e(115)]).then(a.bind(a,9964)).then((e=>{r((()=>e.default))}))}),[v.am]),v.am&&o?React.createElement(o,{modal:e,setModal:t,onAddEmbedding:n,environment:l}):null},wa=[{accessor:"status",title:"Status",width:"90px"},{accessor:"title",title:"Title / Model",sortable:!0,width:"100%",filters:{type:"text",description:"Filter by title."}},{accessor:"type",title:"Ref",sortable:!1,width:"90px",filters:{type:"text",description:"Filter by ref (post ID, checksum, etc.)"}},{accessor:"score",title:"Score",sortable:!0,width:"75px"},{accessor:"updated",title:"Updated",sortable:!1,width:"90px"},{accessor:"actions",title:"",width:"120px"}],_a=[{accessor:"status",title:"Status",sortable:!0,width:"90px"},{accessor:"title",title:"Title / Model",sortable:!0,width:"100%",filters:{type:"text",description:"Filter by title."}},{accessor:"type",title:"Ref",sortable:!0,width:"90px",filters:{type:"text",description:"Filter by ref (post ID, checksum, etc.)"}},{accessor:"updated",title:"Updated",sortable:!0,width:"90px"},{accessor:"actions",title:"",width:"120px"}],Ca=({embedding:e,envName:t,isDifferentModel:a})=>{const{colors:n}=(0,o.z)(),{status:l,content:r,error:i}=e,s=fa((()=>{if("ok"===l){if(!t)return"env_issue";if(!r&&"oai_file"!==e.type)return"empty";if(a)return"warning"}return"outdated"===l?"stale":l}),[l,t,r,a,e.type]),c=fa((()=>"orphan"===s?"This embedding was retrieved from the Vector DB, but it has no content. Add some, or delete it.":"env_issue"===s?"This embedding is not related to any Embeddings Environment. Make sure you have an Embeddings Environment selected, and Sync/Refresh it; it will be linked to the current environment. You can also delete it.":"empty"===s?"This embedding has no content.":"warning"===s?"This embedding was created with a different model. Sync will update it to use the current model.":i||null),[s,i]),{icon:d,color:m}=fa((()=>{const e={outdated:{icon:"alert",color:n.orange},stale:{icon:"alert",color:n.orange},ok:{icon:"check-circle",color:n.green},error:{icon:"alert",color:n.red},orphan:{icon:"pencil",color:n.orange},env_issue:{icon:"database",color:n.red},empty:{icon:"alert",color:n.orange},warning:{icon:"alert",color:n.orange},processing:{icon:"lightning",color:n.blue},default:{icon:"alert",color:n.orange}};return e[s]||e.default}),[s,n]);return React.createElement("div",{style:{display:"flex",alignItems:"center"},title:c},React.createElement(et.z,{icon:d,width:24,color:m,title:c}),React.createElement("span",{style:{textTransform:"uppercase",fontSize:9,marginLeft:3,whiteSpace:"nowrap"}},s))},Aa=({environmentId:e,isSidebarCollapsed:t})=>{const a=Ta(),n={environmentId:void 0!==e?e||null:a.environmentId,isSidebarCollapsed:void 0!==t?t:a.isSidebarCollapsed};localStorage.setItem("mwai-admin-embeddings",(0,y.F1)(n))},Ta=()=>{const e=localStorage.getItem("mwai-admin-embeddings");try{const t=JSON.parse(e);return{environmentId:(null==t?void 0:t.environmentId)||null,isSidebarCollapsed:(null==t?void 0:t.isSidebarCollapsed)||!1}}catch(e){return{environmentId:null,isSidebarCollapsed:!1}}},Ia=({isOpen:e,onClose:t,queryClient:a,postType:n,syncPostStatus:l})=>{const{data:o,isFetching:i}=(0,r.I)({queryKey:["ignoredPosts"],queryFn:je,enabled:e}),s=(null==o?void 0:o.posts)||[],c=async e=>{await(async e=>await ve(`${v.y0}/vectors/unignore`,{nonce:(0,v.c3)(),method:"POST",json:{postId:e}}))(e),a.invalidateQueries({queryKey:["ignoredPosts"]}),a.invalidateQueries({queryKey:["vectors"]}),a.invalidateQueries({queryKey:["postsCount-"+n+"-"+l]})};return React.createElement(se.n,{isOpen:e,onRequestClose:t,title:"Ignored Posts",okButton:{label:"Close",onClick:t},content:i?React.createElement("p",{style:{color:"var(--neko-grey)",lineHeight:"1.6"}},"Loading..."):0===s.length?React.createElement("p",{style:{color:"var(--neko-grey)",lineHeight:"1.6"}},"No ignored posts yet. Use the hide icon on a post embedding to exclude it from sync."):React.createElement("div",{style:{maxHeight:400,overflowY:"auto"}},s.map((e=>React.createElement("div",{key:e.ID,style:{display:"flex",alignItems:"center",padding:"8px 0",borderBottom:"1px solid #eee",gap:10}},React.createElement("div",{style:{flex:1,lineHeight:"1.4"}},React.createElement("div",null,e.post_title||"(No title)"),React.createElement("small",{style:{color:"var(--neko-grey)"}},"#",e.ID," · ",e.post_type)),React.createElement(R.M,{className:"danger",rounded:!0,icon:"close",title:"Remove from ignored list",onClick:()=>c(e.ID)})))))})},Na=({options:e,updateOption:t})=>{var a;const n=(0,l.jE)(),{colors:i}=(0,o.z)(),[s,c]=Ra("post"),[d,m]=Ra(""),[p,g]=Ra(!1),[E,b]=Ra((()=>"true"===localStorage.getItem("mwai_embeddings_queryMode"))),[w,_]=Ra((()=>"true"===localStorage.getItem("mwai_embeddings_expertMode"))),[C,A]=Ra(null),[T,I]=Ra(""),[N,x]=Ra(!1),[O,k]=Ra([]),[S,M]=Ra({type:null,data:null}),[P,L]=Ra(null),[D,F]=Ra(!1),[U,B]=Ra(null),[$,H]=Ra(null),[j,z]=Ra(!1),[G,W]=Ra("embeddings");ya((()=>{if($&&0===$.stats.errors){const e=setTimeout((()=>H(null)),1e4);return()=>clearTimeout(e)}}),[$]);const[q,V]=Ra((()=>Ta().isSidebarCollapsed)),[K,Y]=Ra((()=>_a.filter((e=>e.filters)).map((e=>({accessor:e.accessor,value:[]}))))),X=e.embeddings||{},Q=va(null),J=Te(e,!1,!0),Z=e.embeddings_envs||[],[ne,le]=Ra(Ta().environmentId),re=fa((()=>Z.find((e=>e.id===ne))||null),[Z,ne]),ie="openai-vector-store"===(null==re?void 0:re.type),ce=ie?G:"embeddings",de=(null==re?void 0:re.min_score)>=0?re.min_score:35,me=((null==re?void 0:re.max_select)>=0&&re.max_select,fa((()=>"chroma"===(null==re?void 0:re.type)&&null!=re&&re.embeddings_source&&"ai-engine"!==re.embeddings_source?{model:re.embeddings_source}:null!=re&&re.ai_embeddings_override&&null!=re&&re.ai_embeddings_env&&null!=re&&re.ai_embeddings_model?J.getModel(re.ai_embeddings_model):J.getModel(e.ai_embeddings_default_model)),[re,X.model])),ue=(null==me||null===(a=me.tags)||void 0===a?void 0:a.includes("image"))??!1,{isLoading:pe,data:Ee}=(0,r.I)({queryKey:["postTypes"],queryFn:dt}),he=fa((()=>{if(!Ee)return[];const e=[...Ee];return ue&&e.push({type:"attachment",name:"Media (Images)"}),e}),[Ee,ue]),Re="attachment"===s?"inherit":(null==X?void 0:X.syncPostStatus)??"publish",{isLoading:fe,data:ye}=(0,r.I)({queryKey:["postsCount-"+s+"-"+Re],queryFn:()=>(async(e,t="publish")=>{const a=await ve(`${v.y0}/helpers/count_posts?postType=${e}&postStatus=${t}`,{nonce:(0,v.c3)()});return null!=(null==a?void 0:a.count)?parseInt(a.count):0})(s,Re)}),[be,_e]=Ra({filters:{envId:ne,search:C,debugMode:!1},sort:{accessor:"updated",by:"desc"},page:1,limit:20}),{isFetching:Ce,data:Ae,error:Ne}=(0,r.I)({queryKey:["vectors",(0,y.F1)(be)],queryFn:()=>Oe(be),staleTime:3e5,gcTime:6e5}),xe=Ce||"searchVectors"===p,ke=E?wa:_a,Se=(0,Kt.zM)(),Me=p||xe||Se.isActive||Se.isPreparing||pe,Pe=E?"search":"edit",Le=async e=>{g("updateSettings"),await t({...e},"embeddings"),g(null)},De=fa((()=>X.syncPosts&&(null==X?void 0:X.syncPostsEnvId)!==ne),[ne,X]);ya((()=>{!X.syncPosts&&X.syncPostsEnvId&&Le({...X,syncPostsEnvId:null})}),[X.syncPosts]),ya((()=>{const e=((null==Ae?void 0:Ae.vectors)||[]).filter((e=>"oai_file"===e.type&&"processing"===e.status));if(0===e.length)return;let t=!1;const a=setInterval((async()=>{for(const a of e){if(t)return;try{const e=await(0,y.IU)(`${v.y0}/vectors/refresh_status`,{nonce:v.ok,method:"POST",json:{vectorId:a.id}});if(null!=e&&e.vector&&e.vector.status!==a.status)return void n.invalidateQueries({queryKey:["vectors"]})}catch(e){console.warn("[Embeddings] refresh_status failed",e)}}}),5e3);return()=>{t=!0,clearInterval(a)}}),[Ae]);const Fe=fa((()=>Z.find((e=>e.id===X.syncPostsEnvId))||null),[X.syncPostsEnvId]),Ue=fa((()=>{const e=K.find((e=>"title"===e.accessor));return(null==e?void 0:e.value)||""}),[K]),Be=fa((()=>{const e=K.find((e=>"type"===e.accessor));return(null==e?void 0:e.value)||""}),[K]);ya((()=>{const e=ie&&"documents"===ce?"oai_file":void 0,t=ie&&"embeddings"===ce?["oai_file"]:void 0;_e((a=>a.filters.envId===ne&&a.filters.search===C&&a.filters.debugMode===P&&a.filters.title===Ue&&a.filters.ref===Be&&a.filters.type===e&&(0,y.F1)(a.filters.excludeTypes)===(0,y.F1)(t)?a:{...a,page:1,filters:{envId:ne,search:C,debugMode:P,title:Ue,ref:Be,type:e,excludeTypes:t}})),Aa({environmentId:ne})}),[ne,P,C,Ue,Be,ie,ce]),ya((()=>{W("embeddings")}),[ne]),ya((()=>{Aa({isSidebarCollapsed:q})}),[q]),ya((()=>{const e="edit"===Pe?null:"";A(e),I(e||""),_e((t=>{const a="edit"===Pe?"created":"score";return t.filters.search===e&&t.sort.accessor===a&&"desc"===t.sort.by&&1===t.page&&20===t.limit?t:{...t,filters:{...t.filters,search:e},sort:{accessor:a,by:"desc"},page:1,limit:20}}))}),[Pe]),ya((()=>{var e,t;null!=X&&null!==(e=X.syncPostTypes)&&void 0!==e&&e.length&&null!=X&&null!==(t=X.syncPostStatus)&&void 0!==t&&t.length||Le({...X,syncPostTypes:["post","page","product"],syncPostStatus:["publish"]})}),[X.syncPostTypes]);const $e=fa((()=>{const e={padding:"8px 10px"};return X.syncPosts&&!Fe?React.createElement(oe.X,{variant:"danger",style:e},"Pick a valid environment for Sync."):X.syncPosts?React.createElement(oe.X,{variant:"success",style:e},"Sync Active on ",React.createElement("b",null,null==Fe?void 0:Fe.name)):React.createElement(oe.X,{variant:"disabled",style:e},"Sync Inactive")}),[X]),He=async()=>{A(T),T!==be.filters.search?_e((e=>({...e,filters:{...e.filters,search:T}}))):n.invalidateQueries({queryKey:["vectors"]})},je=async(e=N,t=!1,a=!1)=>{t||g("addEmbedding");try{const t={...e};t.envId||(t.envId=re.id);const n=await(0,y.IU)(`${v.y0}/vectors/add`,{nonce:v.ok,method:"POST",json:{vector:t}});Ye(null==n?void 0:n.vector,!0,a),x(!1),console.log("Embedding Added",e)}catch(e){throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}finally{t||g(!1)}return!0},ze=async(e=N,t=!1,a=!1)=>{t||g("addEmbedding");try{const t={...e};t.envId||(t.envId=re.id);const n=await(0,y.IU)(`${v.y0}/vectors/update`,{nonce:v.ok,method:"POST",json:{vector:t}});Ye(null==n?void 0:n.vector,!1,a),x(!1),console.log("Embeddings updated.",n)}catch(e){throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}finally{t||g(!1)}return!0},Ge=async(e,t)=>{t||g("deleteEmbedding");try{await(0,y.IU)(`${v.y0}/vectors/delete`,{nonce:v.ok,method:"POST",json:{envId:re.id,ids:e}})}catch(t){if(console.error(t),!confirm(`Got an error from the vector database:\n\n${t.message}\n\nDo you want to force the deletion locally?`))throw new Error(t.message??"Unknown error, check your console logs.");await(0,y.IU)(`${v.y0}/vectors/delete`,{nonce:v.ok,method:"POST",json:{envId:re.id,ids:e,force:!0}})}finally{t||g(!1)}console.log("Embeddings deleted.",{ids:e}),n.invalidateQueries({queryKey:["vectors"]}),E&&console.error("We should update the vectors data with the deleted embeddings.")},We=async e=>{g("ignorePost");try{await(async(e,t=null)=>await ve(`${v.y0}/vectors/ignore`,{nonce:(0,v.c3)(),method:"POST",json:{postId:e,envId:t}}))(e,ne),n.invalidateQueries({queryKey:["vectors"]}),n.invalidateQueries({queryKey:["ignoredPosts"]}),n.invalidateQueries({queryKey:["postsCount-"+s+"-"+(null==X?void 0:X.syncPostStatus)]})}catch(e){console.error(e),alert((null==e?void 0:e.message)??"Failed to ignore post.")}g(!1)},qe=fa((()=>(null==Ae?void 0:Ae.total)||0),[Ae]),Ve=fa((()=>{const t=Ae;return null!=t&&t.vectors?null==t?void 0:t.vectors.map((t=>{var a;let n=new Date(t.updated);n=new Date(n.getTime()-60*n.getTimezoneOffset()*1e3);const l=n.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"}),o=n.toLocaleTimeString("ja-JP",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),r=React.createElement("span",null,l,React.createElement("br",null),React.createElement("small",null,o));let s=new Date(t.created);s=new Date(s.getTime()-60*s.getTimezoneOffset()*1e3);const c=s.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),d=t.score?React.createElement("span",{style:{color:t.score>de/100?"var(--neko-green)":"inherit"}},(100*t.score.toFixed(4)).toFixed(2)):"-";let m=null;t.subType&&"string"==typeof t.subType&&(m=t.subType.toUpperCase());const u=J.getModel(t.model),p=(null==u?void 0:u.rawName)??t.model,g=(t.model,t.model&&(null==me?void 0:me.model)&&t.model!==me.model),E=t.envId!==ne,h=null===(a=Z.find((e=>e.id===t.envId)))||void 0===a?void 0:a.name,f="outdated"===t.status||"stale"===t.status||"ok"!==t.status||g||E;let y,v=null;if("error"===t.status&&t.error){let e=t.error;e.includes("Error code:")&&(e=e.split("Error code:")[0].trim(),e.endsWith(".")&&(e=e.slice(0,-1))),v=React.createElement(React.Fragment,null,React.createElement("b",{style:{color:i.red}},"Error: "),React.createElement("span",{style:{color:i.red}},e," "))}else if(g){let a="";if("chroma"===(null==re?void 0:re.type)&&null!=re&&re.embeddings_source&&"ai-engine"!==re.embeddings_source)a=`Chroma (${re.embeddings_source})`;else if(null!=re&&re.ai_embeddings_override&&null!=re&&re.ai_embeddings_env&&null!=re&&re.ai_embeddings_model){var b;a=`Override (${(null==e||null===(b=e.ai_envs)||void 0===b||null===(b=b.find((e=>e.id===re.ai_embeddings_env)))||void 0===b?void 0:b.name)||re.ai_embeddings_env})`}else a="Default AI Environment";const n=J.getModel(null==me?void 0:me.model),l=(null==n?void 0:n.rawName)||(null==n?void 0:n.name)||(null==me?void 0:me.model);v=React.createElement(React.Fragment,null,React.createElement("b",{style:{color:i.orange}},"Mismatch:")," ",a," is set to ",l,"."),console.error(`Embeddings Model Mismatch for #${t.id}: "${t.title}". Should be "${null==me?void 0:me.model}" but "${t.model}" was found.`)}else E&&h&&(v=React.createElement("b",{style:{color:i.green}},"[ENV: ",h,"] "));if("oai_file"===t.type){const e=t.dbId||"",a=e.length>8?e.slice(-5):e;y=e?React.createElement("span",{title:e,style:{whiteSpace:"nowrap"}},React.createElement("a",{href:`https://platform.openai.com/storage/files/${e}`,target:"_blank",rel:"noopener noreferrer"},"#",a," ↗"),React.createElement("br",null),React.createElement("small",null,"OAI FILE")):React.createElement("span",null,"FILE",React.createElement("br",null),React.createElement("small",null,"OAI"))}else if("remoteUrl"===t.type&&t.refUrl)y=React.createElement("a",{href:t.refUrl,target:"_blank",rel:"noopener noreferrer",title:t.refUrl},((e,t=30)=>!e||e.length<=t?e:e.slice(0,t)+"...")(t.refUrl,25)," ↗");else if("upload"===t.type&&t.refChecksum){const e=t.refChecksum.match(/^pdf_(\d+)/),a=e?e[1].slice(-4):t.refChecksum.slice(-4);y=React.createElement("span",{title:t.refChecksum},"PDF ",React.createElement("a",{href:"#",onClick:e=>e.preventDefault()},"#",a),React.createElement("br",null),React.createElement("small",null,"UPLOAD"))}else y=t.refId?React.createElement(React.Fragment,null,"ID ",React.createElement("a",{href:`/wp-admin/post.php?post=${t.refId}&action=edit`,target:"_blank",rel:"noreferrer"},"#",t.refId),React.createElement("br",null),React.createElement("small",null,m)):"MANUAL";return{id:t.id,type:React.createElement("small",null,y),score:d,title:React.createElement("div",null,React.createElement("span",null,t.title),React.createElement("div",{style:{lineHeight:"1.2",marginTop:2}},React.createElement("small",null,"error"!==t.status&&React.createElement(React.Fragment,null,p,t.dimensions&&React.createElement(React.Fragment,null,", ",t.dimensions," dimensions"),v&&React.createElement("br",null)),v))),status:React.createElement(Ca,{embedding:t,envName:h,isDifferentModel:g}),updated:r,created:c,actions:React.createElement("div",null,React.createElement(R.M,{className:"primary",rounded:!0,icon:"pencil",disabled:Me||"oai_file"===t.type,title:"oai_file"===t.type?"Documents are managed by OpenAI and cannot be edited from here":"Edit this embedding",onClick:()=>M({type:"edit",data:t})}),React.createElement(R.M,{className:f?"warning":"primary",rounded:!0,icon:"lightning",disabled:Me||"oai_file"===t.type,title:"oai_file"===t.type?"Documents are pushed by OpenAI on upload; nothing to sync from this side":"Sync this embedding now",onClick:()=>Ke(t.id)}),"postId"===t.type&&t.refId?React.createElement(R.M,{className:"danger",rounded:!0,icon:"eye-off",disabled:Me,title:"Delete and ignore this post from sync",onClick:()=>We(t.refId)}):React.createElement(R.M,{className:"danger",rounded:!0,icon:"trash",disabled:Me,title:"oai_file"===t.type?"Delete this document":"Delete this embedding",onClick:()=>Ge([t.id])}))}})):[]}),[Pe,Ae,Me]),Ke=async e=>{g("syncEmbedding");try{await Xe(e)}catch(e){console.error(e),alert((null==e?void 0:e.message)??e)}g(!1)},Ye=(e,t=!1,a=!1)=>{a||n.invalidateQueries({queryKey:["vectors"]})},Xe=async(e=null,t=null,a=void 0,n=!1)=>{if(a&&a.aborted)throw new DOMException("Operation was cancelled","AbortError");const l=await(async({vectorId:e,postId:t,envId:a},n=null)=>(console.log("[API CALL] synchronizeEmbedding (sync)",{vectorId:e,postId:t,envId:a}),await ve(`${v.y0}/vectors/sync`,{nonce:(0,v.c3)(),method:"POST",json:{vectorId:e,postId:t,envId:a},signal:n})))({vectorId:e,postId:t,envId:ne},a);return l.success&&!n&&Ye(l.vector),l},Qe=async()=>{if(Se.isActive)Se.stop();else{H(null),Se.startPreparing(),g("bulkPullAll");try{await new Promise((e=>setTimeout(e,10)));const e={page:1,limit:1e4,filters:{envId:ne}};let t=[],a=[],l=!1;for(;!l;){const a=await Ie(e);a.vectors.lengthe.dbId)),console.log("Local vectors retrieved.",{vectors:a});const o=t.filter((e=>!a.includes(e)));if(console.log("Vectors to pull from Vector DB to AI Engine.",{vectorsToPull:o}),!o.length)return g(!1),Se.reset(),void H({type:"pull",stats:{total:0,added:0,errors:0,errorDetails:[],remoteTotal:t.length,alreadySynced:a.length}});const r={total:o.length,added:0,errors:0,errorDetails:[],remoteTotal:t.length,alreadySynced:a.length},i=o.map((e=>(0,Kt.UT)((async t=>(await(async(e,t)=>await ve(`${v.y0}/vectors/add_from_remote`,{nonce:(0,v.c3)(),method:"POST",json:e,signal:t}))({envId:ne,dbId:e},t),await n.invalidateQueries({queryKey:["vectors"]}),r.added++,{success:!0}))))),s=await Se.processTasks(i,{onError:({index:e,error:t})=>{r.errors++,r.errorDetails.push({dbId:o[e],error:t})}});g(!1),!s.stopped&&r.total>0&&H({type:"pull",stats:r})}catch(e){console.error("Pull All error:",e),alert((null==e?void 0:e.message)??e),g(!1),Se.reset()}}},Je=async(e=!1)=>{if(Se.isActive)return void Se.stop();H(null),Se.startPreparing(),g("bulkPushAll"),await new Promise((e=>setTimeout(e,10)));let t=[];const a={total:0,added:0,updated:0,upToDate:0,skipped:0,errors:0,errorDetails:[]};if(e||0===O.length){const e="attachment"===s,n=e?"inherit":X.syncPostStatus,l=await(async(e,t="publish")=>{const a=await ve(`${v.y0}/helpers/posts_ids?postType=${e}&postStatus=${t}`,{nonce:(0,v.c3)()});return null!=a&&a.postIds?a.postIds:[]})(s,n),o=await Oe({filters:{envId:ne},page:1,limit:1e4}),r=new Map;null!=o&&o.vectors&&o.vectors.forEach((e=>{e.refId&&(r.set(e.refId,e),r.set(String(e.refId),e),r.set(Number(e.refId),e))}));const i=l.filter((e=>{const t=r.get(e);return!t||(!!X.forceRecreate||("ok"!==t.status||(a.upToDate++,!1)))})),c=i.filter((e=>!r.get(e)));let d=[];e?d=c:c.length>0&&(d=await(async e=>{console.log("[API CALL] checkPostsContent",{count:e.length});const t=await ve(`${v.y0}/helpers/check_posts_content`,{nonce:(0,v.c3)(),method:"POST",json:{postIds:e}});return(null==t?void 0:t.postsWithContent)||[]})(c));const m=i.filter((e=>!!r.get(e)||(!!d.includes(e)||(a.skipped++,!1))));a.total=l.length,console.log(`Push All: ${m.length} posts to sync, ${a.upToDate} already up-to-date, ${a.skipped} no content (skipped)`),t=m.map(((e,t)=>(0,Kt.UT)((async t=>{const n=await Xe(null,e,t,!0);if(n.success)switch(n.action){case"added":a.added++;break;case"updated":a.updated++;break;case"up-to-date":a.upToDate++;break;case"skipped":a.skipped++;break;default:n.message&&n.message.includes("no content")?a.skipped++:n.vector&&a.upToDate++}else a.errors++,n.message&&a.errorDetails.push({postId:e,error:n.message});return{success:!0}}))))}else{const e=Ae.vectors.filter((e=>O.includes(e.id))),n=e.filter((e=>{if(X.forceRecreate)return!0;const t=e.model&&(null==me?void 0:me.model)&&e.model!==me.model,n=e.envId!==ne;return!("ok"===e.status&&!t&&!n)||(a.upToDate++,!1)}));a.total=e.length,console.log(`Sync Selected: ${n.length} vectors to sync, ${a.upToDate} already up-to-date (skipped)`),t=n.map(((e,t)=>(0,Kt.UT)((async t=>{let n;if(e.refId?n=await Xe(e.id,null,t,!0):(await ze(e,t),n={success:!0}),n.success)switch(n.action){case"added":a.added++;break;case"updated":a.updated++;break;case"up-to-date":default:a.upToDate++;break;case"skipped":a.skipped++}else a.errors++,n.message&&a.errorDetails.push({title:e.title,error:n.message});return{success:!0}}))))}const l=await Se.processTasks(t);t.length>0&&n.invalidateQueries({queryKey:["vectors"]}),g(!1),!l.stopped&&a.total>0&&H({type:"push",stats:a,selectedType:e?`All ${s}s`:"Selected items"})},et=async(e=null)=>{if(e){g("singleRun");try{await Xe(null,e),m("")}catch(e){console.error(e),alert((null==e?void 0:e.message)??e)}g(!1)}},rt=fa((()=>{if(null!=Ne&&Ne.message)return React.createElement(oe.X,{variant:"danger",style:{margin:"5px 5px"}},React.createElement("b",null,Ne.message),React.createElement("br",null),React.createElement("small",null,"Check your Console Logs and PHP Error Logs for more information."));if(E)return ge.A.HELP.NO_EMBEDDINGS_RESULTS;if(!re)return React.createElement(Wt.b,{icon:"database",title:"Let's Create a Knowledge Base",subtitle:React.createElement(React.Fragment,null,"Click ",React.createElement("b",null,"+ New Environment")," above to get started. If you are already using OpenAI, the ",React.createElement("b",null,"OpenAI Vector Store")," is the easiest path. Chroma, Qdrant and Pinecone are great if you want to stay provider-agnostic.",React.createElement("br",null),React.createElement("br",null),React.createElement("a",{href:"https://ai.thehiddendocs.com/knowledge/",target:"_blank",rel:"noopener noreferrer"},"Learn more about Knowledge Bases ↗"))});if(E)return React.createElement(Wt.b,{icon:"search",title:"No results",subtitle:"Try different keywords or adjust your search parameters."});const e={color:i.green,whiteSpace:"nowrap"},t={color:i.blue,whiteSpace:"nowrap"},a={wordBreak:"normal",overflowWrap:"normal"};return ie&&"documents"===ce?React.createElement(Wt.b,{style:a,icon:"database",title:"Let's Upload a Document",subtitle:React.createElement(React.Fragment,null,"Your ",React.createElement("b",null,null==re?void 0:re.name)," environment is ready. Use ",React.createElement("b",{style:e},"Upload Document")," to send a file (PDF, DOCX, MD…) to OpenAI. It will parse, chunk and embed it on its side, then the chatbot can search it.",React.createElement("br",null),React.createElement("br",null),React.createElement("a",{href:"https://ai.thehiddendocs.com/knowledge/",target:"_blank",rel:"noopener noreferrer"},"Learn more about Knowledge Bases ↗"))}):React.createElement(Wt.b,{style:a,icon:"database",title:"Let's Create a Knowledge Base",subtitle:React.createElement(React.Fragment,null,"Your ",React.createElement("b",null,null==re?void 0:re.name)," environment is ready. Use ",React.createElement("b",{style:e},"Create New"),","," ",React.createElement("b",{style:t},"Push All"),", or ",React.createElement("b",{style:t},"Upload PDF")," to start filling it with embeddings.",React.createElement("br",null),React.createElement("br",null),React.createElement("a",{href:"https://ai.thehiddendocs.com/knowledge/",target:"_blank",rel:"noopener noreferrer"},"Learn more about Knowledge Bases ↗"))})}),[Pe,Ne,re,ie,ce,i]);return React.createElement(React.Fragment,null,React.createElement(qt.J,{mainFlex:2,sidebarFlex:1,minimal:!0,isCollapsed:q,onToggle:()=>V(!q),showToggle:!1},React.createElement(qt.J.Main,null,React.createElement(f.z,{className:"primary",title:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",null,"documents"===ce?"Documents":"Embeddings"),E&&React.createElement("span",{style:{opacity:.7}},"(Query Mode)"),!E&&"documents"===ce&&React.createElement(R.M,{className:"success",rounded:!0,small:!0,icon:"file-upload",title:"Upload a file directly to OpenAI Vector Store",disabled:!re||Me,onClick:()=>M({type:"upload-file",data:{envId:re.id}})}),!E&&"embeddings"===ce&&React.createElement(R.M,{className:"success",rounded:!0,small:!0,icon:"plus",title:"Add a new embedding",disabled:!re||Me,onClick:()=>M({type:"add",data:we})})),action:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:5}},React.createElement(te.u,{scrolldown:!0,name:"environment",style:{width:180},disabled:Me,value:(null==re?void 0:re.id)??null,onChange:e=>{le(e)}},Z.map((e=>React.createElement(te.j,{key:e.id,value:e.id,label:e.name}))),!(null!=Z&&Z.length)&&React.createElement(te.j,{value:null,label:"None"})),React.createElement(R.M,{className:"primary",icon:"plus",title:"Create a new Knowledge environment",disabled:Me,onClick:()=>z(!0)},"New"),React.createElement(R.M,{className:"secondary",title:"Refresh the list of embeddings",disabled:!re||xe||Se.isActive,onClick:()=>{n.invalidateQueries({queryKey:["vectors"]})}},ge.A.COMMON.REFRESH),React.createElement(Vt.A,{isCollapsed:q,onClick:()=>V(!q),border:"left",direction:"right"}))},ie&&React.createElement(React.Fragment,null,React.createElement("p",{style:{marginTop:0,marginBottom:12,color:"var(--neko-grey)",fontSize:13,lineHeight:1.5}},React.createElement("b",null,"OpenAI Vector Store")," supports two complementary approaches."," ",React.createElement("b",null,"Embeddings")," are chunks you craft yourself (manual entries, posts, URLs) — you control title, content and metadata."," ",React.createElement("b",null,"Documents")," are files (PDF, DOCX, MD…) handed directly to OpenAI, which parses, chunks and embeds them on its side."," ","Both are searched together when the chatbot queries this store. This split is specific to OpenAI Vector Store."),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:5,marginBottom:12}},React.createElement(R.M,{className:"embeddings"===G?"primary":"secondary",onClick:()=>W("embeddings")},"Embeddings"),React.createElement(R.M,{className:"documents"===G?"primary":"secondary",onClick:()=>W("documents")},"Documents"),React.createElement("div",{style:{flex:"auto"}}),"documents"===G&&React.createElement(R.M,{className:"secondary",icon:"sync",disabled:!re||Me,busy:"syncRemoteFiles"===p,title:"Pull files that were added directly via the OpenAI platform",onClick:async()=>{if(re){g("syncRemoteFiles");try{const e=await(0,y.IU)(`${v.y0}/vectors/sync_remote_files`,{nonce:v.ok,method:"POST",json:{envId:re.id}});n.invalidateQueries({queryKey:["vectors"]}),0===((null==e?void 0:e.added)??0)?alert("Already in sync — no new documents found on OpenAI."):alert(`Synced ${e.added} new document${e.added>1?"s":""} from OpenAI.`)}catch(e){alert("Could not sync from OpenAI: "+(e.message||"Unknown error"))}finally{g(!1)}}}},"Sync from OpenAI"))),Se.isActive&&React.createElement(at.V,{style:{marginBottom:15}},React.createElement(it.j,{busy:!Se.justStopped,style:{width:"100%"},value:Se.progress,max:Se.total,status:Se.isPreparing?"Preparing...":Se.isStopping?"Please wait...":Se.justStopped?"Stopped":void 0,variant:Se.variant,onStopClick:Se.justStopped?null:Se.stop})),E&&React.createElement(at.V,{style:{marginBottom:15}},React.createElement("div",{style:{display:"flex",width:"100%"}},React.createElement(ae.A,{style:{flex:"auto",marginRight:5},placeholder:`Query the '${(null==re?void 0:re.name)||"embeddings"}' environment`,disabled:!re||Me,value:T,onChange:I,onEnter:He,onReset:async()=>{A(""),I(""),_e((e=>({...e,filters:{...e.filters,search:""}})))}}),React.createElement(R.M,{className:"primary",onClick:He,disabled:!re||Me||!T,busy:"searchVectors"===p},"AI Search"))),React.createElement(tt.o,{busy:Me,sort:be.sort,onSortChange:(e,t)=>{_e((a=>({...a,sort:{accessor:e,by:t}})))},emptyMessage:rt,data:Ve,columns:ke,onSelectRow:e=>{1===O.length&&O[0]===e&&k([]),k([e])},onSelect:e=>{k([...O,...e])},onUnselect:e=>{k([...O.filter((t=>!e.includes(t)))])},selectedItems:O,filters:K,onFilterChange:(e,t)=>{const a=[...K.filter((t=>t.accessor!==e)),{accessor:e,value:t}];Y(a)}}),React.createElement(ee.g,null),!E&&React.createElement("div",{style:{display:"flex",alignItems:"center"}},!E&&O.length>0&&React.createElement(React.Fragment,null,React.createElement(R.M,{className:"primary",icon:"lightning",disabled:Me,busy:"bulkPushAll"===p,title:"Sync the selected embeddings",onClick:()=>Je(!1)},"Sync"),React.createElement(R.M,{className:"danger",style:{marginLeft:5},disabled:Me,title:"Delete the selected embeddings",onClick:async()=>{confirm("Are you sure you want to delete the selected embeddings?")&&(g("deleteEmbeddings"),await Ge(O),k([]),g(!1))}},"Delete"),React.createElement("div",{style:{display:"flex",alignItems:"center",marginLeft:10}},O.length," selected")),React.createElement("div",{style:{flex:"auto"}}),React.createElement(ot.Q,{currentPage:be.page,limit:be.limit,onCurrentPageChanged:e=>_e((t=>({...t,page:e}))),total:qe,onClick:e=>{_e((t=>({...t,page:e})))}}),w&&React.createElement(R.M,{className:"primary",style:{marginLeft:5},disabled:!re,title:"Export embeddings as CSV or JSON",onClick:()=>{M({type:"export",data:{envId:ne}})}},ge.A.COMMON.EXPORT)))),React.createElement(qt.J.Sidebar,null,React.createElement(f.z,{className:"primary",title:"Mode"},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}},React.createElement("label",{style:{fontWeight:"normal"}},"Query Mode"),React.createElement(nt.S,{checked:E,onChange:e=>{b(e),localStorage.setItem("mwai_embeddings_queryMode",e)},disabled:Me})),React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("label",{style:{fontWeight:"normal"}},"Expert Mode"),React.createElement(nt.S,{checked:w,onChange:e=>{_(e),localStorage.setItem("mwai_embeddings_expertMode",e)},disabled:Me}))),React.createElement(h._,{inversed:!0,title:"Environment"},React.createElement(h.V,{title:"Info",inversed:!0},re?React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",gap:10,marginBottom:10}},React.createElement("div",{style:{flex:1}},React.createElement("label",null,"Min Score (%)"),React.createElement(ae.A,{type:"number",value:void 0!==(null==re?void 0:re.min_score)?re.min_score:35,min:0,max:100,disabled:!re||Me||D,onFinalChange:async e=>{if(re){F(!0);try{const a=Z.map((t=>t.id===ne?{...t,min_score:parseInt(e)||0}:t));await t(a,"embeddings_envs")}finally{F(!1)}}}})),React.createElement("div",{style:{flex:1}},React.createElement("label",null,"Max Results"),React.createElement(ae.A,{type:"number",value:void 0!==(null==re?void 0:re.max_select)?re.max_select:10,min:1,max:100,disabled:!re||Me||D,onFinalChange:async e=>{if(re){F(!0);try{const a=Z.map((t=>t.id===ne?{...t,max_select:parseInt(e)||1}:t));await t(a,"embeddings_envs")}finally{F(!1)}}}}))),React.createElement("p",{style:{fontSize:12,color:"var(--neko-grey)",marginBottom:10}},"The best ",React.createElement("b",null,(null==re?void 0:re.max_select)||10)," embedding(s) with a score of ",React.createElement("b",null,(null==re?void 0:re.min_score)||35,"%")," or more will provide additional context to your AI queries."),React.createElement(ee.g,{tiny:!0}),$e,React.createElement(ee.g,{tiny:!0}),React.createElement("p",{style:{fontSize:11,color:"var(--neko-grey)",margin:0}},React.createElement("b",null,"Tip:")," Sync and search settings are configured globally in ",React.createElement("b",null,"Settings → Knowledge"),".")):React.createElement("p",{style:{color:"var(--neko-grey)",margin:0}},"No environment selected. Select one from the dropdown above.")),React.createElement(h.V,{title:"Sync",inversed:!0},re&&De&&React.createElement(React.Fragment,null,React.createElement(oe.X,{variant:"danger",style:{marginBottom:10}},"The currently selected environment is not used for Sync. Do you want to use this one?"),React.createElement(R.M,{fullWidth:!0,className:"primary",disabled:Me,onClick:()=>Le({...X,syncPostsEnvId:ne}),style:{marginBottom:10}},"Use Current Environment")),React.createElement(u.R,{label:"Enable Sync",checked:X.syncPosts,disabled:p,onChange:e=>{Le({...X,syncPosts:e})},description:ge.A.EMBEDDINGS.AUTO_SYNC_POSTS_DESCRIPTION}),X.syncPosts&&React.createElement(React.Fragment,null,React.createElement(ee.g,null),React.createElement(ae.A,{name:"syncPostTypes",value:X.syncPostTypes,isCommaSeparatedArray:!0,description:ge.A.HELP.POST_TYPES,onBlur:e=>{Le({...X,syncPostTypes:e})}}),w&&React.createElement(React.Fragment,null,React.createElement(ee.g,null),React.createElement(ae.A,{name:"syncPostStatus",value:X.syncPostStatus||"publish",isCommaSeparatedArray:!0,description:ge.A.HELP.POST_STATUS,onBlur:e=>{Le({...X,syncPostStatus:e})}}),React.createElement(ee.g,null),React.createElement(ae.A,{name:"syncPostCategories",value:X.syncPostCategories||"publish",isCommaSeparatedArray:!0,description:ge.A.HELP.POST_CATEGORIES,onBlur:e=>{Le({...X,syncPostCategories:e})}}))),React.createElement(ee.g,null),React.createElement(R.M,{fullWidth:!0,className:"secondary",disabled:Me,title:"Show posts excluded from sync",onClick:()=>M({type:"ignored"})},"Show Ignored")),w&&React.createElement(h.V,{title:"Admin",inversed:!0},React.createElement(R.M,{fullWidth:!0,className:"primary",title:"Fetch all embeddings from the vector database",disabled:!re||Me,busy:"bulkPullAll"===p,onClick:()=>Qe()},"Pull All"),React.createElement(ee.g,{tiny:!0}),React.createElement(R.M,{className:"danger",fullWidth:!0,title:"Delete all embeddings for this environment",disabled:!re||p,busy:"deleteAllEmbeddings"===p,onClick:async()=>{if(re&&confirm(ge.A.EMBEDDINGS.DELETE_ALL_EMBEDDINGS_CONFIRM+`\n\n${re.name}`)){g("deleteAllEmbeddings");try{await(0,y.IU)(`${v.y0}/vectors/delete_all`,{nonce:v.ok,method:"POST",json:{envId:ne}}),n.invalidateQueries({queryKey:["vectors"]})}catch(e){alert((null==e?void 0:e.message)??e)}g(!1)}}},"deleteAllEmbeddings"===p?"Deleting...":"Delete All"),React.createElement(ee.g,null),React.createElement("div",{style:{marginBottom:10}},React.createElement("label",{style:{fontWeight:"bold",marginBottom:5,display:"block"}},"Debug Filter"),React.createElement(te.u,{scrolldown:!0,name:"debugMode",style:{width:"100%"},disabled:Me,value:P||null,onChange:L},React.createElement(te.j,{value:null,label:"Current Environment"}),React.createElement(te.j,{value:"includeOrphans",label:"With Orphans"}),React.createElement(te.j,{value:"includeAll",label:"All Envs & Orphans"}))),React.createElement("p",{style:{fontSize:12,color:"var(--neko-grey)",margin:0}},React.createElement("b",null,"Current Environment:")," Shows embeddings from the selected environment only.",React.createElement("br",null),React.createElement("b",null,"With Orphans:")," Includes embeddings that exist in the vector database but have no local content.",React.createElement("br",null),React.createElement("b",null,"All Envs & Orphans:")," Shows all embeddings across all environments, including orphans."))),!E&&ie&&"documents"===ce&&React.createElement(React.Fragment,null,React.createElement(f.z,{className:"primary",title:"Documents"},v.am&&React.createElement(R.M,{fullWidth:!0,className:"success",icon:"file-upload",disabled:!re||Me,title:"Upload a file (PDF, DOCX, MD…) directly to OpenAI Vector Store",onClick:()=>M({type:"upload-file",data:{envId:re.id}})},"Upload Document"),(null==re?void 0:re.store_id)&&React.createElement("p",{style:{marginTop:12,marginBottom:0,fontSize:11,color:"var(--neko-grey)",lineHeight:1.5}},"Too big for this server? Upload it on the"," ",React.createElement("a",{href:`https://platform.openai.com/storage/vector_stores/${re.store_id}`,target:"_blank",rel:"noopener noreferrer"},"OpenAI Platform ↗")," ","then click ",React.createElement("b",null,"Sync from OpenAI"),"."))),!E&&"embeddings"===ce&&React.createElement(f.z,{className:"primary",title:"Build Knowledge"},React.createElement(R.M,{fullWidth:!0,className:"success",icon:"plus",disabled:!re||Me,title:"Add a new embedding manually",onClick:()=>M({type:"add"}),style:{marginBottom:w?15:8}},"Create New"),React.createElement("div",{style:{marginBottom:w?15:0}},w&&React.createElement("label",{style:{fontWeight:"bold",marginBottom:5,display:"block"}},"From Internal"),w&&React.createElement("div",{style:{display:"flex",alignItems:"center",marginBottom:8,gap:8}},React.createElement(R.M,{className:"primary",icon:"sync",style:{flex:"0 0 55%"},title:"Create an embedding for this post",disabled:!re||Me,busy:"singleRun"===p,onClick:()=>{d&&et(d)}},"Push"),React.createElement(ae.A,{type:"number",placeholder:"Post ID",value:d,onChange:m,style:{flex:"0 0 45%"},disabled:!re||Me,onEnter:e=>{e&&(et(e),m(""))}})),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:w?0:8}},React.createElement(R.M,{className:"primary",icon:"sync",style:{flex:"0 0 55%"},title:"Create embeddings for all posts of this type",disabled:!re||Me,busy:"bulkPushAll"===p,onClick:()=>Je(!0)},"Push All ",!fe&&React.createElement(React.Fragment,null,"(",`${ye}`,")")),React.createElement(te.u,{id:"postType",scrolldown:!0,disabled:Me,name:"postType",style:{flex:"0 0 45%"},onChange:c,value:s},null==he?void 0:he.map((e=>React.createElement(te.j,{key:e.type,value:e.type,label:e.name})))))),React.createElement("div",null,w&&React.createElement("label",{style:{fontWeight:"bold",marginBottom:5,display:"block"}},"From External"),v.am&&React.createElement(React.Fragment,null,React.createElement(R.M,{fullWidth:!0,className:"primary",icon:"file-upload",disabled:!re||Me,title:"Import a PDF and create embeddings from its content",onClick:()=>M({type:"pdf-import"}),style:{marginBottom:w?8:0}},"Upload PDF")),w&&React.createElement(lt.Z,{ref:Q,onSelectFiles:async e=>{for(let t=0;t{B({title:"File Read Error",message:`Failed to read the file: ${a.name}`,details:"Please check if the file is accessible and not corrupted."})},n.onload=async e=>{try{const t=e.target.result;let n=[],i=[];if(l)try{if(n=JSON.parse(t),!Array.isArray(n))throw new Error("JSON file must contain an array of objects")}catch(e){return void B({title:"Invalid JSON Format",message:`Failed to parse JSON file: ${a.name}`,details:e.message,help:'Ensure your JSON file contains an array of objects with \'title\' and \'content\' fields.\n\nExample:\n[\n {"title": "Example Title", "content": "Example content"},\n {"title": "Another Title", "content": "More content"}\n]'})}else if(o){const l=t.split("\n").filter((e=>e.trim()));for(let t=0;t0&&(B({title:"JSONL Parse Errors",message:`Failed to parse some lines in JSONL file: ${a.name}`,details:i.slice(0,5).join("\n")+(i.length>5?`\n...and ${i.length-5} more errors`:""),help:'Each line in a JSONL file must be a valid JSON object with \'title\' and \'content\' fields.\n\nExample line:\n{"title": "Example Title", "content": "Example content"}'}),0===n.length))return}else if(r){const e=Ze().parse(t,{header:!0,skipEmptyLines:!0});if(e.errors.length>0){const t=e.errors.slice(0,5).map((e=>`Row ${e.row||"unknown"}: ${e.message}`)).join("\n");if(B({title:"CSV Parse Errors",message:`Failed to parse CSV file: ${a.name}`,details:t+(e.errors.length>5?`\n...and ${e.errors.length-5} more errors`:""),help:'Ensure your CSV file has headers including \'title\' and \'content\' columns.\n\nExample CSV format:\ntitle,content\n"Example Title","Example content"\n"Another Title","More content"'}),0===e.data.length)return}if(n=e.data,n.length>0){const e=Object.keys(n[0]);if(!e.includes("title")||!e.includes("content"))return void B({title:"Missing Required Columns",message:"CSV file must have 'title' and 'content' columns",details:`Found columns: ${e.join(", ")}`,help:"The first row of your CSV must contain column headers, including 'title' and 'content'.\n\nOptional columns: 'type', 'refId', 'refUrl'"})}}if(!Array.isArray(n)||0===n.length)return void B({title:"No Data Found",message:"The file appears to be empty or contains no valid data",details:`File: ${a.name}`,help:"Please ensure your file contains at least one record with 'title' and 'content' fields."});const s=[],c=[];if(n.forEach(((e,t)=>{var a,n;if(!e||"object"!=typeof e)return void c.push(`Row ${t+1}: Invalid data structure`);const l=null===(a=e.title)||void 0===a?void 0:a.toString().trim(),o=null===(n=e.content)||void 0===n?void 0:n.toString().trim();l||o?l?o?s.push({title:l,content:o,type:e.type||null,refId:e.refId||null,refUrl:e.refUrl||null}):c.push(`Row ${t+1}: Missing content`):c.push(`Row ${t+1}: Missing title`):c.push(`Row ${t+1}: Both title and content are empty`)})),0===s.length)return void B({title:"No Valid Entries",message:"No entries with both title and content were found",details:c.slice(0,5).join("\n")+(c.length>5?`\n...and ${c.length-5} more issues`:""),help:"Each entry must have both a 'title' and 'content' field with non-empty values."});c.length>0&&console.warn("Import validation issues:",c),M({type:"import",data:{importVectors:s,envId:ne,totalEntries:n.length,validEntries:s.length,invalidEntries:c.length}})}catch(e){console.error("Import error:",e),B({title:"Import Failed",message:"An unexpected error occurred while processing the file",details:e.message,help:"Please check the file format and try again. If the problem persists, check the browser console for more details."})}},n.readAsText(a)):B({title:"Unsupported File Type",message:`Only JSON, JSONL, and CSV files are supported. You provided: ${a.name}`,details:"Please ensure your file has one of these extensions: .json, .jsonl, or .csv"})}},accept:""},React.createElement(R.M,{fullWidth:!0,className:"secondary",icon:"file-upload",disabled:!re||Me,title:"Import embeddings from a CSV or JSON file",onClick:()=>Q.current.click()},"Upload CSV or JSON")),w&&v.am&&React.createElement(R.M,{fullWidth:!0,className:"secondary",icon:"link",title:"Fetch and create embeddings from a list of URLs",disabled:!re||Me,onClick:()=>M({type:"bulk-url",data:{envId:re.id}}),style:{marginTop:8}},"Bulk Add Remote URLs"))))),React.createElement(Jt,{modal:S,setModal:M,busy:p,onAddEmbedding:je,onModifyEmbedding:ze,supportsImageEmbeddings:ue}),React.createElement(ea,{modal:S,setModal:M,busy:p}),React.createElement(na,{modal:S,setModal:M,busy:p,onAddEmbedding:je,onModifyEmbedding:ze,refreshEmbeddings:()=>n.invalidateQueries({queryKey:["vectors"]})}),React.createElement(ra,{modal:S,setModal:M,onAddEmbedding:je,refreshEmbeddings:()=>n.invalidateQueries({queryKey:["vectors"]})}),React.createElement(ma,{modal:S,setModal:M,onAdded:()=>n.invalidateQueries({queryKey:["vectors"]})}),v.am&&React.createElement(ba,{modal:S,setModal:M,onAddEmbedding:je,environment:re}),React.createElement(ha,{isOpen:j,onClose:()=>z(!1),onPick:async e=>{const a=pa(e),n=[...Z,a];await t(n,"embeddings_envs"),z(!1);try{localStorage.setItem("mwai_settings_section","knowledge")}catch(e){}const l=new URL(window.location.href);l.searchParams.set("nekoTab","settings"),window.location.href=l.toString()}}),React.createElement(Ia,{isOpen:"ignored"===(null==S?void 0:S.type),onClose:()=>M({type:null,data:null}),queryClient:n,postType:s,syncPostStatus:null==X?void 0:X.syncPostStatus}),React.createElement(se.n,{isOpen:!!U,title:(null==U?void 0:U.title)||"Import Error",onRequestClose:()=>B(null),okButton:{label:"Close",onClick:()=>B(null)},content:React.createElement("div",null,React.createElement("p",{style:{marginBottom:10}},null==U?void 0:U.message),(null==U?void 0:U.details)&&React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:10,borderRadius:4,marginBottom:10,fontFamily:"monospace",fontSize:"12px",whiteSpace:"pre-wrap",maxHeight:"150px",overflowY:"auto"}},U.details),(null==U?void 0:U.help)&&React.createElement("div",{style:{backgroundColor:"#e8f4f8",padding:10,borderRadius:4,fontSize:"13px",whiteSpace:"pre-wrap"}},React.createElement("strong",null,"Help:"),React.createElement("br",null),U.help))}),React.createElement(se.n,{isOpen:!!$,title:"push"===(null==$?void 0:$.type)?"Push Complete":"Pull Complete",onRequestClose:()=>H(null),okButton:{label:"Close",onClick:()=>H(null)},content:$&&React.createElement("div",null,React.createElement(oe.X,{variant:0===$.stats.errors?"success":"warning",style:{marginBottom:15}},React.createElement("strong",null,0===$.stats.errors?"Success":"⚠️ Completed with Issues"),React.createElement("br",null),"push"===$.type?React.createElement(React.Fragment,null,React.createElement("strong",null,$.stats.added)," added •",React.createElement("strong",null,$.stats.updated)," updated •",React.createElement("strong",null,$.stats.upToDate)," up-to-date",$.stats.skipped>0&&React.createElement(React.Fragment,null," • ",React.createElement("strong",null,$.stats.skipped)," skipped")):`Successfully pulled ${$.stats.added} embeddings`,$.stats.errors>0&&React.createElement(React.Fragment,null,React.createElement("br",null),React.createElement("strong",{style:{color:"var(--neko-red)"}},$.stats.errors," error",$.stats.errors>1?"s":""))),$.stats.errors>0&&$.stats.errorDetails.length>0&&React.createElement(oe.X,{variant:"danger",style:{marginBottom:15}},React.createElement("strong",null,"Error Details:"),React.createElement("div",{style:{maxHeight:150,overflowY:"auto",marginTop:8}},$.stats.errorDetails.slice(0,5).map(((e,t)=>React.createElement("div",{key:t,style:{fontSize:12,marginTop:4}},"• ",e.postId?`Post #${e.postId}`:e.title||e.dbId||`Item ${t+1}`,": ",e.error))),$.stats.errorDetails.length>5&&React.createElement("div",{style:{marginTop:8,fontSize:12,fontStyle:"italic"}},"...and ",$.stats.errorDetails.length-5," more errors"))),"pull"===$.type&&$.stats.remoteTotal>0&&React.createElement(oe.X,{variant:"info",style:{marginTop:15}},React.createElement("strong",null,$.stats.remoteTotal)," total embeddings found in the vector database"))}))};var xa=a(5719);const{useState:Oa,useMemo:ka}=wp.element,Sa={price:"PRICE",tokens:"TOKENS",queries:"QUERIES"},Ma=(e,t)=>"price"===t?e?`$${e.toFixed(2)}`:"$0":Math.round(e).toLocaleString(),Pa=(e,t)=>{if("daily"===t){const[t,a,n]=e.split("-").map((e=>parseInt(e,10)));return new Date(t,a-1,n).toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}const[a,n]=e.split("-").map((e=>parseInt(e,10)));return new Date(a,n-1,1).toLocaleDateString(void 0,{month:"short",year:"numeric"})},La=(e,t,a=0)=>{const n=new Date,l=[];if("daily"===e)for(let e=a+t-1;e>=a;e--){const t=new Date(n);t.setDate(t.getDate()-e),l.push(`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`)}else for(let e=a+t-1;e>=a;e--){const t=new Date(n.getFullYear(),n.getMonth()-e,1);l.push(`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`)}return l},Da=(e,t,a,n,l,o)=>{const r=(a,n)=>[e+a*Math.sin(n),t-a*Math.cos(n)],[i,s]=r(a,l),[c,d]=r(a,o),[m,u]=r(n,o),[p,g]=r(n,l),E=o-l>Math.PI?1:0;return`M ${i} ${s} A ${a} ${a} 0 ${E} 1 ${c} ${d} L ${m} ${u} A ${n} ${n} 0 ${E} 0 ${p} ${g} Z`},Fa=({options:e})=>{const{getModel:t,calculatePrice:a}=Te(e,null,!0),n=null==e?void 0:e.ai_models_usage,l=null==e?void 0:e.ai_models_usage_daily,[o,r]=Oa((()=>{const e=localStorage.getItem("mwai_usage_metric");return["price","tokens","queries"].includes(e)?e:"queries"})),[i,s]=Oa((()=>{const e=localStorage.getItem("mwai_usage_view_mode");return["daily","monthly"].includes(e)?e:"daily"})),c=ka((()=>{const t={};return((null==e?void 0:e.ai_engines)||[]).forEach((e=>{(e.models||[]).forEach((a=>{a.model&&(t[a.model]=e.type)}))})),((null==e?void 0:e.ai_models)||[]).forEach((e=>{e.model&&e.type&&(t[e.model]=e.type)})),t}),[null==e?void 0:e.ai_engines,null==e?void 0:e.ai_models]),d="daily"===i?7:6,m=ka((()=>La(i,d,0)),[i,d]),u=ka((()=>La(i,d,d)),[i,d]),p=e=>{const r="daily"===i?l||{}:n||{},s={};let d=0;return e.forEach((e=>{const n=r[e]||{},l={};let i=0;Object.keys(n).forEach((e=>{const r=n[e]||{},s=t(e),d=c[null==s?void 0:s.model]||c[e]||"unknown",m=((e,n)=>{const l=t(e);return"queries"===o?n.queries||0:"tokens"===o?"image"===(null==l?void 0:l.type)?n.images||0:"second"===(null==l?void 0:l.type)?n.seconds||0:(n.prompt_tokens||0)+(n.completion_tokens||0):l?a(e,n.prompt_tokens||0,n.completion_tokens||0):0})(e,r);m<=0||(l[d]=(l[d]||0)+m,i+=m)})),s[e]={byProvider:l,total:i},d+=i})),{perPeriod:s,grandTotal:d}},{perPeriod:g,grandTotal:E}=ka((()=>p(m)),[m,n,l,o,i,t,a,c]),{grandTotal:h}=ka((()=>p(u)),[u,n,l,o,i,t,a,c]),R=ka((()=>Math.max(0,...m.map((e=>{var t;return(null===(t=g[e])||void 0===t?void 0:t.total)||0})))),[m,g]),f=ka((()=>{let e={period:null,value:0};return m.forEach((t=>{var a;const n=(null===(a=g[t])||void 0===a?void 0:a.total)||0;n>e.value&&(e={period:t,value:n})})),e}),[m,g]),y=ka((()=>{const e={};return m.forEach((t=>{var a;const n=(null===(a=g[t])||void 0===a?void 0:a.byProvider)||{};Object.entries(n).forEach((([t,a])=>{e[t]=(e[t]||0)+a}))})),Object.entries(e).sort(((e,t)=>t[1]-e[1]))}),[m,g]),v=ka((()=>{const e="daily"===i?l||{}:n||{};let o=0,r=0;return m.forEach((n=>{const l=e[n]||{};Object.keys(l).forEach((e=>{const n=l[e]||{};t(e)&&(o+=a(e,n.prompt_tokens||0,n.completion_tokens||0),r+=n.queries||0)}))})),r>0?o/r:0}),[m,n,l,i,t,a]),b=E/d,w=h>0?(E-h)/h*100:null;if(!(n&&Object.keys(n).length>0||l&&Object.keys(l).length>0))return React.createElement(Wt.b,{icon:"bar-chart-2",title:ge.A.COMMON.DATA_NOT_AVAILABLE,subtitle:ge.A.COMMON.USAGE_EMPTY_SUBTITLE});const _=(ge.A.COMMON[Sa[o]]||"queries").toLowerCase(),C="daily"===i?"week":"period",A="daily"===i?"day":"month",T="price"===o?"spent":_,I=164,N=764/m.length*.55,x=764/m.length,O=(()=>{if(R<=0)return"price"===o?.04:4;const e=Math.pow(10,Math.floor(Math.log10(R))),t=R/e;let a;a=t<=1?1:t<=2?2:t<=4?4:t<=8?8:10;const n=a*e;return"price"!==o?Math.max(4,n):n})(),k=[0,O/4,O/2,3*O/4,O],S=y.reduce(((e,[,t])=>e+t),0);let M=0;return React.createElement(React.Fragment,null,React.createElement("style",null,"\n .mwai-usage {\n display: flex;\n flex-direction: column;\n gap: 18px;\n color: var(--neko-gray-20, #2a303c);\n }\n\n .mwai-usage-controls {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 12px;\n flex-wrap: wrap;\n }\n\n /* Headline row: big number + supporting pills. */\n .mwai-usage-headline {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 12px 14px;\n padding: 4px 0 0;\n }\n .mwai-usage-big {\n font-size: 38px;\n font-weight: 700;\n line-height: 1;\n color: var(--neko-main-color);\n letter-spacing: -0.02em;\n font-variant-numeric: tabular-nums;\n }\n .mwai-usage-headline-desc {\n font-size: 13px;\n color: var(--neko-gray-40, #6b7280);\n }\n .mwai-usage-pill {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 4px 10px;\n border-radius: 999px;\n font-size: 12px;\n font-weight: 500;\n line-height: 1;\n background: rgba(13, 125, 242, 0.08);\n color: #0d7df2;\n border: 1px solid rgba(13, 125, 242, 0.15);\n }\n .mwai-usage-pill.up {\n background: rgba(239, 68, 68, 0.08);\n color: #dc2626;\n border-color: rgba(239, 68, 68, 0.18);\n }\n .mwai-usage-pill.down {\n background: rgba(34, 197, 94, 0.08);\n color: #16a34a;\n border-color: rgba(34, 197, 94, 0.18);\n }\n\n /* Bar chart. */\n .mwai-usage-chart-wrap {\n background: var(--neko-gray-99, #fbfcfd);\n border: 1px solid var(--neko-gray-95, #f1f2f4);\n border-radius: 10px;\n padding: 14px 14px 8px;\n }\n .mwai-usage-chart svg {\n display: block;\n width: 100%;\n height: auto;\n overflow: visible;\n font-family: inherit;\n }\n .mwai-usage-chart .grid-line {\n stroke: rgba(0, 0, 0, 0.06);\n stroke-dasharray: 3 4;\n }\n .mwai-usage-chart .y-label {\n font-size: 10.5px;\n fill: var(--neko-gray-50, #8b95a3);\n font-variant-numeric: tabular-nums;\n }\n .mwai-usage-chart .x-label {\n font-size: 10.5px;\n fill: var(--neko-gray-40, #6b7280);\n }\n .mwai-usage-chart .x-label.dim {\n fill: var(--neko-gray-60, #a8b0bb);\n }\n .mwai-usage-chart .bar {\n transition: opacity 0.15s ease;\n }\n .mwai-usage-chart .bar:hover {\n opacity: 0.85;\n }\n .mwai-usage-chart .bar-value {\n font-size: 11px;\n font-weight: 600;\n fill: var(--neko-gray-20, #2a303c);\n font-variant-numeric: tabular-nums;\n }\n .mwai-usage-chart .bar-value.dim {\n fill: var(--neko-gray-60, #a8b0bb);\n font-weight: 500;\n }\n .mwai-usage-chart .bar-value.inside {\n fill: #ffffff;\n }\n\n /* Metric tiles row. */\n .mwai-usage-tiles {\n display: grid;\n grid-template-columns: 1.5fr 1fr 1fr 1fr;\n gap: 10px;\n }\n @media (max-width: 900px) {\n .mwai-usage-tiles {\n grid-template-columns: 1fr 1fr;\n }\n }\n .mwai-usage-tile {\n background: var(--neko-gray-99, #fbfcfd);\n border: 1px solid var(--neko-gray-95, #f1f2f4);\n border-radius: 10px;\n padding: 14px 16px;\n display: flex;\n flex-direction: column;\n justify-content: center;\n gap: 4px;\n min-height: 104px;\n box-sizing: border-box;\n }\n .mwai-usage-tile-label {\n font-size: 11.5px;\n font-weight: 600;\n color: var(--neko-gray-40, #6b7280);\n letter-spacing: 0.02em;\n text-transform: uppercase;\n }\n .mwai-usage-tile-big {\n font-size: 24px;\n font-weight: 700;\n color: var(--neko-gray-10, #1a1f29);\n line-height: 1.1;\n font-variant-numeric: tabular-nums;\n margin-top: 2px;\n }\n .mwai-usage-tile-sub {\n font-size: 11.5px;\n color: var(--neko-gray-50, #8b95a3);\n }\n\n /* Provider tile: donut on the left, label + legend stacked on the right. */\n .mwai-usage-tile.provider {\n flex-direction: row;\n align-items: center;\n gap: 14px;\n padding: 14px 16px;\n }\n .mwai-usage-tile.provider .donut-wrap {\n flex: 0 0 64px;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .mwai-usage-tile.provider .right {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .mwai-usage-tile.provider .legend {\n display: flex;\n flex-direction: column;\n gap: 3px;\n font-size: 11.5px;\n }\n .mwai-usage-tile.provider .legend-row {\n display: grid;\n grid-template-columns: 10px 1fr auto;\n gap: 7px;\n align-items: center;\n min-width: 0;\n }\n .mwai-usage-tile.provider .legend-dot {\n width: 9px;\n height: 9px;\n border-radius: 50%;\n flex-shrink: 0;\n }\n .mwai-usage-tile.provider .legend-name {\n color: var(--neko-gray-20, #2a303c);\n font-weight: 500;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .mwai-usage-tile.provider .legend-value {\n color: var(--neko-gray-50, #8b95a3);\n font-variant-numeric: tabular-nums;\n font-size: 11px;\n white-space: nowrap;\n }\n"),React.createElement("div",{className:"mwai-usage"},React.createElement("div",{className:"mwai-usage-controls"},React.createElement(ne.o,{name:"metric",value:o,onChange:e=>{r(e),localStorage.setItem("mwai_usage_metric",e)}},React.createElement(ne.K,{title:ge.A.COMMON.PRICE,value:"price"}),React.createElement(ne.K,{title:ge.A.COMMON.TOKENS,value:"tokens"}),React.createElement(ne.K,{title:ge.A.COMMON.QUERIES,value:"queries"})),React.createElement(ne.o,{name:"viewMode",value:i,onChange:e=>{s(e),localStorage.setItem("mwai_usage_view_mode",e)}},React.createElement(ne.K,{title:ge.A.COMMON.DAILY,value:"daily"}),React.createElement(ne.K,{title:ge.A.COMMON.MONTHLY,value:"monthly"}))),React.createElement("div",{className:"mwai-usage-headline"},React.createElement("span",{className:"mwai-usage-big"},Ma(E,o)),React.createElement("span",{className:"mwai-usage-headline-desc"},T," this ",C),null!==w&&Number.isFinite(w)&&(()=>{const e=w>=0,t="price"===o?!e:e;return React.createElement("span",{className:"mwai-usage-pill "+(t?"down":"up")},e?"↑":"↓"," ",Math.abs(Math.round(w)),"% vs last ",C)})(),React.createElement("span",{className:"mwai-usage-pill"},"Avg ",Ma(b,o),"/",A)),React.createElement("div",{className:"mwai-usage-chart-wrap"},React.createElement("div",{className:"mwai-usage-chart"},React.createElement("svg",{viewBox:"0 0 800 220",preserveAspectRatio:"none"},k.map(((e,t)=>{const a=182-e/O*I;return React.createElement("g",{key:t},React.createElement("line",{className:"grid-line",x1:30,y1:a,x2:794,y2:a}),React.createElement("text",{className:"y-label",x:24,y:a+3,textAnchor:"end"},0===e?"price"===o?"$0":"0":Ma(e,o)))})),m.map(((e,t)=>{const a=g[e]||{total:0,byProvider:{}},n=a.total,l=0===n,r=Object.entries(a.byProvider).sort(((e,t)=>t[1]-e[1])),s=30+t*x+(x-N)/2,c=n/O*I,d=182-c,m=Pa(e,i),[u,p]=m.includes(",")?m.split(",").map((e=>e.trim())):[m,""];return React.createElement("g",{key:e},!l&&(()=>{let e=d;return r.map((([t,a])=>{const l=a/n*c,o=React.createElement("rect",{key:t,className:"bar",x:s,y:e,width:N,height:l,fill:(0,xa.uN)(t).color,rx:"3",ry:"3"});return e+=l,o}))})(),l&&React.createElement("rect",{x:s,y:180,width:N,height:2,fill:"rgba(0, 0, 0, 0.08)",rx:"1"}),(()=>{const e=d-6,t=!l&&e<24,a=l?176:t?d+14:e,r=l?"dim":t?"inside":"";return React.createElement("text",{className:`bar-value ${r}`,x:s+N/2,y:a,textAnchor:"middle"},l?"0":Ma(n,o))})(),React.createElement("text",{className:"x-label",x:s+N/2,y:198,textAnchor:"middle"},u),p&&React.createElement("text",{className:"x-label dim",x:s+N/2,y:210,textAnchor:"middle"},p))}))))),React.createElement("div",{className:"mwai-usage-tiles"},React.createElement("div",{className:"mwai-usage-tile provider"},React.createElement("div",{className:"donut-wrap"},S>0?React.createElement("svg",{width:"60",height:"60",viewBox:"0 0 60 60"},y.map((([e,t])=>{const a=M,n=M+t/S*Math.PI*2;return M=n,1===y.length?React.createElement("g",{key:e},React.createElement("circle",{cx:"30",cy:"30",r:"26",fill:(0,xa.uN)(e).color}),React.createElement("circle",{cx:"30",cy:"30",r:"15",fill:"var(--neko-gray-99, #fbfcfd)"})):React.createElement("path",{key:e,d:Da(30,30,26,15,a,n),fill:(0,xa.uN)(e).color})}))):React.createElement("div",{style:{width:60,height:60,borderRadius:"50%",background:"rgba(0,0,0,0.04)"}})),React.createElement("div",{className:"right"},React.createElement("div",{className:"mwai-usage-tile-label"},"Providers"),React.createElement("div",{className:"legend"},0===y.length&&React.createElement("span",{style:{fontSize:11.5,color:"var(--neko-gray-50, #8b95a3)"}},"No activity"),y.slice(0,3).map((([e,t])=>{const a=S>0?Math.round(t/S*100):0;return React.createElement("div",{className:"legend-row",key:e},React.createElement("span",{className:"legend-dot",style:{background:(0,xa.uN)(e).color}}),React.createElement("span",{className:"legend-name"},{openai:"OpenAI",anthropic:"Anthropic",claude:"Claude",google:"Google",gemini:"Gemini",azure:"Azure",mistral:"Mistral",openrouter:"OpenRouter",ollama:"Ollama",perplexity:"Perplexity",unknown:"Unknown"}[n=e]||(n?n.charAt(0).toUpperCase()+n.slice(1):"Unknown")),React.createElement("span",{className:"legend-value"},a,"%"));var n})),y.length>3&&React.createElement("div",{className:"legend-row",style:{fontStyle:"italic",color:"var(--neko-gray-50, #8b95a3)"}},React.createElement("span",null),React.createElement("span",{className:"legend-name"},"+ ",y.length-3," more"),React.createElement("span",null))))),React.createElement("div",{className:"mwai-usage-tile"},React.createElement("div",{className:"mwai-usage-tile-label"},"Peak ",A),React.createElement("div",{className:"mwai-usage-tile-big"},f.value>0?Ma(f.value,o):"—"),React.createElement("div",{className:"mwai-usage-tile-sub"},f.period?Pa(f.period,i):"no activity")),React.createElement("div",{className:"mwai-usage-tile"},React.createElement("div",{className:"mwai-usage-tile-label"},"Average / ",A),React.createElement("div",{className:"mwai-usage-tile-big"},Ma(b,o)),React.createElement("div",{className:"mwai-usage-tile-sub"},"price"===o?`per ${A}`:_)),React.createElement("div",{className:"mwai-usage-tile"},React.createElement("div",{className:"mwai-usage-tile-label"},"Per query"),React.createElement("div",{className:"mwai-usage-tile-big"},v>0?(P=v)?P<.01?`$${P.toFixed(3)}`:`$${P.toFixed(2)}`:"$0":"—"),React.createElement("div",{className:"mwai-usage-tile-sub"},"average cost")))));var P},{useCallback:Ua,useMemo:Ba}=wp.element,$a={openai:"chat-openai.svg",anthropic:"chat-anthropic.svg",claude:"chat-anthropic.svg",google:"chat-google.svg",gemini:"chat-google.svg"},Ha="\n .mwai-env-list {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n\n .mwai-env-row {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 14px 10px 11px;\n background: white;\n border: 1px solid var(--neko-gray-90, #e5e7eb);\n border-left: 3px solid var(--_brand);\n border-radius: 8px;\n cursor: pointer;\n transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;\n }\n .mwai-env-row:hover,\n .mwai-env-row:focus-visible {\n transform: translateX(1px);\n box-shadow: 0 2px 12px -4px rgba(0, 0, 0, 0.12);\n outline: none;\n }\n\n .mwai-env-logo {\n width: 34px;\n height: 34px;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .mwai-env-logo img {\n width: 100%;\n height: 100%;\n display: block;\n border-radius: 7px;\n }\n .mwai-env-monogram {\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n font-family: var(--neko-font-family);\n font-size: 16px;\n font-weight: 700;\n color: white;\n background: var(--_brand);\n border-radius: 7px;\n }\n\n .mwai-env-text {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 1px;\n }\n .mwai-env-company {\n font-size: 10px;\n font-weight: 700;\n letter-spacing: 1.1px;\n text-transform: uppercase;\n color: var(--_brand-dark);\n line-height: 1.2;\n }\n .mwai-env-name {\n font-size: 13px;\n font-weight: 500;\n color: var(--neko-gray-20, #2a303c);\n line-height: 1.3;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .mwai-env-status {\n display: flex;\n align-items: center;\n gap: 8px;\n flex-shrink: 0;\n }\n .mwai-env-default {\n color: #f5c518;\n display: inline-flex;\n align-items: center;\n }\n .mwai-env-badge {\n font-size: 9px;\n font-weight: 600;\n letter-spacing: 0.8px;\n text-transform: uppercase;\n color: var(--neko-red, #dc2626);\n background: rgba(220, 38, 38, 0.08);\n padding: 3px 8px;\n border-radius: 999px;\n white-space: nowrap;\n }\n\n",ja=({env:e,engine:t,engineLabel:a,isDefault:n,onClick:l})=>{const o=(0,xa.uN)(e.type),r=(e=>{const t=$a[null==e?void 0:e.toLowerCase()];return t?`${v.Hm}/images/${t}`:null})(e.type),i=((e,t)=>t?!Array.isArray(t.inputs)||!t.inputs.includes("apikey")||e.apikey&&e.apikey.length>0?null:"no-key":"unavailable")(e,t),s={"--_brand":o.color,"--_brand-dark":`color-mix(in oklab, ${o.color} 75%, #000)`};return React.createElement("div",{className:"mwai-env-row",style:s,role:"button",tabIndex:0,onClick:l,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),l())},title:ge.A.COMMON.CONFIGURE},React.createElement("div",{className:"mwai-env-logo"},r?React.createElement("img",{src:r,alt:a}):React.createElement("span",{className:"mwai-env-monogram"},o.label)),React.createElement("div",{className:"mwai-env-text"},React.createElement("div",{className:"mwai-env-company"},a),React.createElement("div",{className:"mwai-env-name",title:e.name},e.name||ge.A.COMMON.ENVIRONMENT)),React.createElement("div",{className:"mwai-env-status"},"unavailable"===i&&React.createElement("span",{className:"mwai-env-badge"},ge.A.COMMON.TYPE_UNAVAILABLE),"no-key"===i&&React.createElement("span",{className:"mwai-env-badge"},ge.A.COMMON.NO_API_KEY),n&&React.createElement("span",{className:"mwai-env-default",title:ge.A.COMMON.DEFAULT},React.createElement(et.z,{icon:"star",width:14,fill:"currentColor"}))))},za=({options:e,defaultModels:t,fastModels:a,belowUsageNote:n})=>{const l=(null==e?void 0:e.ai_envs)||[],o=(null==e?void 0:e.ai_engines)||[],r=null==e?void 0:e.ai_default_env,i=Ba((()=>o.reduce(((e,t)=>(e[t.type]=t,e)),{})),[o]),s=Ua((()=>{window.location.href=`${window.location.pathname}?page=mwai_settings&nekoTab=settings`}),[]);return l.length?React.createElement(React.Fragment,null,React.createElement("style",null,Ha),React.createElement("div",{className:"mwai-env-list"},l.map((e=>{const t=i[e.type];return React.createElement(ja,{key:e.id,env:e,engine:t,engineLabel:(null==t?void 0:t.name)||e.type,isDefault:e.id===r,onClick:s})}))),React.createElement(Ce,{options:e,defaultModels:t,fastModels:a,style:{marginTop:12}}),n&&React.createElement("div",{style:{marginTop:8,fontSize:11,color:"var(--neko-gray-60)",lineHeight:1.4}},ge.A.COMMON.ENV_MOVES_BELOW_USAGE||"Once everything is set up, this panel moves below Usage automatically.")):React.createElement(React.Fragment,null,React.createElement("style",null,Ha),React.createElement(Wt.b,{icon:"plug",title:ge.A.COMMON.ENVIRONMENT_EMPTY_TITLE,subtitle:ge.A.COMMON.ENVIRONMENT_EMPTY_SUBTITLE,action:React.createElement(R.M,{className:"primary",onClick:s},ge.A.COMMON.SET_UP_ENVIRONMENT)}))},{useState:Ga,useCallback:Wa,useMemo:qa}=wp.element,Va="mwai_setup_assistant",Ka="#e0e0e0",Ya="#48c7be",Xa="#f0a030",Qa="#e05050",Ja=w.Ay.div` display: flex; align-items: center; gap: 12px; margin: 16px 0 18px; font-size: 12px; color: #666; `,Za=w.Ay.div` flex: 1; height: 6px; background: rgba(0, 0, 0, 0.06); border-radius: 3px; overflow: hidden; `,en=w.Ay.div` height: 100%; background: linear-gradient(90deg, #48c7be, #2ea99f); border-radius: 3px; transition: width 0.4s ease; width: ${e=>e.$pct}%; `,tn=w.Ay.div` display: flex; align-items: flex-start; gap: 12px; padding: 14px 12px; margin: 0 -12px; border-bottom: 1px solid rgba(0, 0, 0, 0.06); border-radius: 6px; transition: background 0.15s ease; /* The first grey/red step (= next action) gets a subtle accent so the user always knows where to look without us shouting. */ ${e=>e.$isNext&&"\n background: rgba(72, 199, 190, 0.04);\n box-shadow: inset 2px 0 0 #48c7be;\n "} &:hover { background: rgba(0, 0, 0, 0.015); } &:last-child { border-bottom: none; } `,an=w.Ay.div` margin: 14px 0 4px; padding: 18px 22px; background: linear-gradient(135deg, rgba(72, 199, 190, 0.12), rgba(13, 125, 242, 0.08)); border-radius: 10px; border: 1px solid rgba(72, 199, 190, 0.25); display: flex; align-items: center; gap: 14px; .emoji { font-size: 28px; line-height: 1; } .text { flex: 1; font-size: 14px; color: #1e1e1e; line-height: 1.45; b { display: block; font-size: 15px; margin-bottom: 2px; } } `,nn=w.Ay.div` width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 13px; flex-shrink: 0; background: ${e=>e.$color||Ka}; color: ${e=>e.$color&&e.$color!==Ka?"#fff":"#666"}; transition: all 0.2s ease; `,ln=w.Ay.div` flex: 1; min-width: 0; `,on=w.Ay.div` font-weight: 600; font-size: 14px; margin-bottom: 4px; color: #1e1e1e; display: flex; align-items: center; gap: 8px; `,rn=w.Ay.span` display: inline-block; background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; font-size: 10px; font-weight: 600; padding: 1px 7px; border-radius: 4px; letter-spacing: 0.3px; `,sn=w.Ay.div` font-size: 13px; color: #555; line-height: 1.5; `,cn=w.Ay.div` display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; `,dn=w.Ay.button` padding: 4px 14px; border-radius: 4px; border: 1px solid ${e=>e.$active?"#48c7be":"#ccc"}; background: ${e=>e.$active?"#48c7be":"#fff"}; color: ${e=>e.$active?"#fff":"#333"}; cursor: pointer; font-size: 12px; font-weight: 500; transition: all 0.15s ease; &:hover { border-color: #48c7be; } `,mn=w.Ay.div` margin-top: 8px; padding: 10px 14px; background: rgba(72, 199, 190, 0.06); border-radius: 6px; border-left: 3px solid #48c7be; font-size: 13px; color: #555; line-height: 1.55; b { color: #1e1e1e; } `,un=w.Ay.div` margin-top: 8px; padding: 10px 14px; background: rgba(0, 0, 0, 0.03); border-radius: 6px; border-left: 3px solid #999; font-size: 13px; color: #555; line-height: 1.6; b { color: #1e1e1e; } a { color: #0d7df2; } `,pn=w.Ay.div` margin-top: 6px; font-size: 12px; color: #888; font-style: italic; `,gn=()=>{try{const e=localStorage.getItem(Va);if(e)return JSON.parse(e)}catch(e){}return{dismissed:!1,steps:{}}},En=e=>{const t=new URL(window.location.href);t.searchParams.set("nekoTab",e),window.location.href=t.toString()},hn=({options:e,defaultModels:t,fastModels:a,hasAiEnvIssues:n,isRegistered:l,updateOption:o,onDismiss:r})=>{var i;const[s,d]=Ga(gn),m=Wa((e=>{d(e);try{localStorage.setItem(Va,JSON.stringify(e))}catch(e){}}),[]),u=Wa(((e,t)=>{m({...s,steps:{...s.steps,[e]:t}})}),[s,m]),p=Wa((()=>{m({...s,dismissed:!0}),r&&r()}),[s,m,r]),g=!qa((()=>n(e,t,a)),[e,t,a,n]),E=!(null==e||!e.module_chatbots),h=!(null==e||!e.module_generator_content),y=!(null==e||!e.module_assistant),v=!(null==e||!e.module_generator_images),b=!(null==e||!e.module_embeddings),w=(null==e||null===(i=e.server_mcp)||void 0===i||i.enabled,e=>e?"ok"===e?Ya:Xa:Ka),_=(e,t)=>"info"===e?Xa:!1===e||"no"===e||t?Ya:e?Qa:Ka,C=g?Ya:Qa;if(s.dismissed)return null;const A=[g,"ok"===s.steps.modules,E,"ok"===s.steps.behavior,h||y||"no"===s.steps.content,v||"no"===s.steps.images,b||"no"===s.steps.knowledge,"ok"===s.steps.mcp],T=A.filter(Boolean).length,I=8===T,N=A.findIndex((e=>!e)),x=e=>N===e-1;return React.createElement(f.z,{className:"primary",title:"Setup Assistant",action:React.createElement(R.M,{className:"secondary",onClick:p,title:"Dismiss the assistant. You can bring it back from Settings → Maintenance."},"Dismiss")},React.createElement(c.s,{p:!0,style:{marginTop:0,marginBottom:4}},"Welcome! Here's the fastest path through AI Engine. Each step is optional, so skip anything you don't need."),React.createElement(Ja,null,React.createElement("b",null,T," of 8 complete"),React.createElement(Za,null,React.createElement(en,{$pct:Math.round(T/8*100)}))),I&&React.createElement(an,null,React.createElement("div",{className:"emoji","aria-hidden":!0},"🎉"),React.createElement("div",{className:"text"},React.createElement("b",null,"You're all set!"),"AI Engine is ready to go. You can dismiss this assistant now; to bring it back later, go to Settings, Others, Maintenance, and click Show Setup Assistant.")),React.createElement(tn,{$isNext:x(1)},React.createElement(nn,{$color:C},"1"),React.createElement(ln,null,React.createElement(on,null,"Connect an AI Provider"),React.createElement(sn,null,"AI Engine needs at least one AI environment: an API key from OpenAI, Anthropic, Google, or any compatible provider (Ollama, OpenRouter, Azure, xAI, etc.). Without one, nothing else works.",g&&React.createElement(React.Fragment,null," ",React.createElement("b",{style:{color:Ya}},"Done!")," You have a working environment on the right."),!g&&React.createElement(React.Fragment,null," ","Set one up in the ",React.createElement("b",null,"AI Environments")," panel on the right.")),React.createElement(cn,null,React.createElement(dn,{$active:"info"===s.steps.env,onClick:()=>u("env","info")},"Tell me more")),"info"===s.steps.env&&React.createElement(un,null,"AI Engine is ",React.createElement("b",null,"Bring Your Own Key"),": you pay the AI provider directly, not us. This keeps you in control of cost and data. The most common choice is ",React.createElement("b",null,"OpenAI")," (best support, broadest model line-up), but ",React.createElement("b",null,"Anthropic Claude")," is a great alternative and the free tier of ",React.createElement("b",null,"Google Gemini")," is generous for testing. You can mix and match later, since different chatbots can use different environments."))),React.createElement(tn,{$isNext:x(2)},React.createElement(nn,{$color:w(s.steps.modules)},"2"),React.createElement(ln,null,React.createElement(on,null,"Pick the Modules You Need"),React.createElement(sn,null,"AI Engine is modular: chatbots, content generators, knowledge bases, MCP, and more. Open the ",React.createElement("b",null,"Modules")," tab and toggle on only what you'll use. The rest stays out of your way."),React.createElement(cn,null,React.createElement(dn,{$active:"ok"===s.steps.modules,onClick:()=>{u("modules","ok"),En("modules")}},"ok"===s.steps.modules?"Got it ✓":"Open Modules"),React.createElement(dn,{$active:"info"===s.steps.modules,onClick:()=>u("modules","info")},"Tell me more")),"info"===s.steps.modules&&React.createElement(un,null,"Modules are grouped by purpose: ",React.createElement("b",null,"Chatbots & Frontend")," (what visitors see), ",React.createElement("b",null,"Content Creation")," (writing assistance for authors), ",React.createElement("b",null,"Knowledge & Data")," (embeddings, transcription, library search), and ",React.createElement("b",null,"Tools & Insights")," (analytics, moderation, fine-tunes). Enabling a module reveals its dedicated tab and settings; disabling hides them. Some modules are ",React.createElement("b",null,"Pro"),"-only."))),React.createElement(tn,{$isNext:x(3)},React.createElement(nn,{$color:_(s.steps.chatbot,E)},"3"),React.createElement(ln,null,React.createElement(on,null,"Build Your First Chatbot"),React.createElement(sn,null,"Chatbots are the #1 reason people install AI Engine. They live as a popup, an inline widget, or a fullscreen page, and connect directly to the environment you set up in step 1.",E&&React.createElement(React.Fragment,null," ","The Chatbots module is on; open the tab to create, embed, and test one."),!E&&React.createElement(React.Fragment,null," ","Enable the ",React.createElement("b",null,"Chatbots")," module first (in the Modules tab).")),React.createElement(cn,null,E&&React.createElement(dn,{$active:"ok"===s.steps.chatbot,onClick:()=>{u("chatbot","ok"),En("chatbots")}},"ok"===s.steps.chatbot?"Got it ✓":"Open Chatbots"),!E&&React.createElement(dn,{onClick:()=>{o(!0,"module_chatbots"),u("chatbot","enabled")}},"Enable Chatbots"),React.createElement(dn,{$active:"info"===s.steps.chatbot,onClick:()=>u("chatbot","info")},"Tell me more")),"info"===s.steps.chatbot&&React.createElement(un,null,"Every chatbot has a ",React.createElement("b",null,"Name"),", an ",React.createElement("b",null,"Environment"),", a ",React.createElement("b",null,"Model"),", and an ",React.createElement("b",null,"Instructions")," field (its system prompt, covered in the next step). You can give it a personality, restrict its topic, hand it function-calling tools, attach a knowledge base, or let it remember conversations. Start simple: one chatbot, one model, a single line of instructions. Iterate from there."))),React.createElement(tn,{$isNext:x(4)},React.createElement(nn,{$color:w(s.steps.behavior)},"4"),React.createElement(ln,null,React.createElement(on,null,"Tweak the Chatbot's Behavior"),React.createElement(sn,null,"The ",React.createElement("b",null,"Instructions")," field on a chatbot is its personality and rules. A few well-chosen sentences here change everything: tone, scope, how it handles off-topic questions. Don't ship the default."),React.createElement(cn,null,React.createElement(dn,{$active:"ok"===s.steps.behavior,onClick:()=>u("behavior","ok")},"Got it"),React.createElement(dn,{$active:"info"===s.steps.behavior,onClick:()=>u("behavior","info")},"Tell me more")),"info"===s.steps.behavior&&React.createElement(un,null,"A good instructions prompt usually has three parts: ",React.createElement("b",null,"(1) Identity"),' ("You are a friendly assistant for a bakery website."), ',React.createElement("b",null,"(2) Scope"),' ("Answer questions about our menu, hours, and orders. For anything else, ask the user to email us."), and ',React.createElement("b",null,"(3) Style"),' ("Be concise, warm, and avoid jargon."). Test by sending edge cases (off-topic questions, very long questions, hostile prompts) and refine. ',React.createElement("b",null,"Pro tip:")," in the Pro version, you can attach a Knowledge base so the AI quotes from your real content instead of guessing."))),React.createElement(tn,{$isNext:x(5)},React.createElement(nn,{$color:_(s.steps.content,h||y)},"5"),React.createElement(ln,null,React.createElement(on,null,"Write with AI Inside WordPress"),React.createElement(sn,null,"Two complementary tools live in the post editor: the ",React.createElement("b",null,"Content Generator")," (a separate screen for bulk drafts) and the ",React.createElement("b",null,"AI Editor Assistant")," (a sidebar that rewrites, translates, and edits the post you have open)."),React.createElement(cn,null,React.createElement(dn,{$active:"yes"===s.steps.content,onClick:()=>{o(!0,"module_generator_content"),o(!0,"module_assistant"),u("content","yes")}},"Enable both"),React.createElement(dn,{$active:"no"===s.steps.content,onClick:()=>{o(!1,"module_generator_content"),o(!1,"module_assistant"),u("content","no")}},"Not for me"),React.createElement(dn,{$active:"info"===s.steps.content,onClick:()=>u("content","info")},"Tell me more")),"yes"===s.steps.content&&(h||y)&&React.createElement(mn,null,"Enabled. Open any post in the editor: you'll see the AI Engine sidebar with quick actions, and a new ",React.createElement("b",null,"AI Engine → Content Generator")," menu entry for bulk drafts."),"info"===s.steps.content&&React.createElement(un,null,"The ",React.createElement("b",null,"Content Generator")," is great for first drafts, batch translations, and product descriptions. The ",React.createElement("b",null,"Editor Assistant"),' sits in the post sidebar and acts on the post you have open: "make this paragraph shorter", "translate to Spanish", "rewrite in a friendlier tone". They share the same model and environment, so you only configure one thing. Both are ',React.createElement("b",null,"free"),"."))),React.createElement(tn,{$isNext:x(6)},React.createElement(nn,{$color:_(s.steps.images,v)},"6"),React.createElement(ln,null,React.createElement(on,null,"Generate Images & Process Vision"),React.createElement(sn,null,"The ",React.createElement("b",null,"Image Generator")," creates featured images, illustrations, and product visuals from a text prompt. Vision-capable models can also describe images, draft alt text, and answer questions about uploads."),React.createElement(cn,null,React.createElement(dn,{$active:"yes"===s.steps.images,onClick:()=>{o(!0,"module_generator_images"),u("images","yes")}},"Enable"),React.createElement(dn,{$active:"no"===s.steps.images,onClick:()=>{o(!1,"module_generator_images"),u("images","no")}},"Not for me"),React.createElement(dn,{$active:"info"===s.steps.images,onClick:()=>u("images","info")},"Tell me more")),"yes"===s.steps.images&&v&&React.createElement(mn,null,"Enabled. Look for ",React.createElement("b",null,"AI Engine → Image Generator")," in the menu. The default model is OpenAI's GPT Image, but you can switch in Settings."),"info"===s.steps.images&&React.createElement(un,null,"Image generation pricing varies a lot by model and resolution. Start with the ",React.createElement("b",null,"auto")," quality on GPT Image for the best price/quality balance, and bump to ",React.createElement("b",null,"high")," only when you need it. Self-hosted options (Replicate, custom backends) work too, but they take more setup."))),React.createElement(tn,{$isNext:x(7)},React.createElement(nn,{$color:_(s.steps.knowledge,b)},"7"),React.createElement(ln,null,React.createElement(on,null,"Ground Answers in Your Content ",React.createElement(rn,null,"Pro")),React.createElement(sn,null,"Embeddings let a chatbot quote from your posts, pages, and PDFs instead of guessing. This is what turns it from a generic assistant into a true expert on your site."),React.createElement(cn,null,React.createElement(dn,{$active:"yes"===s.steps.knowledge,disabled:!l,onClick:()=>{o(!0,"module_embeddings"),u("knowledge","yes")}},l?"Enable":"Available in Pro"),React.createElement(dn,{$active:"no"===s.steps.knowledge,onClick:()=>{o(!1,"module_embeddings"),u("knowledge","no")}},"Not for me"),React.createElement(dn,{$active:"info"===s.steps.knowledge,onClick:()=>u("knowledge","info")},"Tell me more")),!l&&React.createElement(pn,null,"Knowledge bases require AI Engine Pro."),"yes"===s.steps.knowledge&&b&&React.createElement(mn,null,"Enabled. Open the ",React.createElement("b",null,"Knowledge")," tab to create an index, point it at posts or upload PDFs, and then attach it to a chatbot."),"info"===s.steps.knowledge&&React.createElement(un,null,'"Embeddings" turn each chunk of your content into a high-dimensional vector. When someone asks a question, AI Engine finds the most relevant chunks and feeds them to the model as context. The model then answers using ',React.createElement("i",null,"your")," words. You can use OpenAI's vector store, Pinecone, Qdrant, or Chroma. Start with OpenAI for the simplest setup."," ",React.createElement("a",{href:"https://ai.thehiddendocs.com/knowledge/",target:"_blank",rel:"noreferrer"},"Read the Knowledge docs ↗")))),React.createElement(tn,{$isNext:x(8)},React.createElement(nn,{$color:w(s.steps.mcp)},"8"),React.createElement(ln,null,React.createElement(on,null,"Let AI Agents Drive Your Site (MCP)"),React.createElement(sn,null,"With MCP, you can connect ",React.createElement("b",null,"Claude Desktop"),", ",React.createElement("b",null,"ChatGPT"),", or ",React.createElement("b",null,"Claude Code")," directly to this WordPress site. They can create posts, manage media, run reports, and edit settings, all through natural conversation, securely, with OAuth."),React.createElement(cn,null,React.createElement(dn,{$active:"ok"===s.steps.mcp,onClick:()=>u("mcp","ok")},"Got it"),React.createElement(dn,{$active:"info"===s.steps.mcp,onClick:()=>u("mcp","info")},"Tell me more")),"info"===s.steps.mcp&&React.createElement(un,null,"MCP (Model Context Protocol) is the new standard for exposing tools to AI agents. AI Engine ships an MCP server that lives at ",React.createElement("code",null,"/wp-json/mwai/v1/mcp"),". Configuration lives under ",React.createElement("b",null,"Settings → MCP"),": bearer token or OAuth, plus a tool catalog (create/edit posts, WooCommerce, media, etc.). Pro adds plugin and theme management tools."," ",React.createElement("a",{href:"https://meowapps.com/claude-wordpress-mcp/",target:"_blank",rel:"noreferrer"},"Read the full walkthrough ↗")))))};var Rn=a(9995),fn=a(212),yn=a(7770),vn=a(1879),bn=a(4293),wn=a(8996),_n=a(7121),Cn=a(6046),An=a(4232),Tn=a(6019),In=a(4667),Nn=a(2591),xn=a(8766),On=a(3638),kn=a(4934),Sn=a(5747),Mn=a(3326);const Pn=w.Ay.div` display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); /* All rows same height regardless of label length — keeps the grid tidy. */ grid-auto-rows: 104px; gap: 10px; margin-top: 4px; `,Ln=w.Ay.button` display: flex; flex-direction: column; align-items: flex-start; justify-content: flex-start; gap: 10px; padding: 14px; background: #fff; border: 1px solid rgba(0, 0, 0, 0.08); border-radius: 8px; cursor: pointer; text-align: left; transition: all 0.18s ease; position: relative; /* Uniform height across rows so a 1-line label doesn't look squat next to a card whose label wrapped to 2 lines. */ min-height: 102px; &:hover { border-color: rgba(72, 199, 190, 0.5); box-shadow: 0 2px 8px rgba(72, 199, 190, 0.08); transform: translateY(-1px); } &:active { transform: translateY(0); } .icon-wrap { display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; border-radius: 7px; background: ${e=>e.$accent||"rgba(13, 125, 242, 0.10)"}; color: ${e=>e.$accentText||"#0d7df2"}; } .label { font-size: 13px; font-weight: 600; color: #1e1e1e; line-height: 1.3; } .pro { position: absolute; top: 8px; right: 8px; font-size: 9px; font-weight: 700; padding: 1px 6px; border-radius: 3px; background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; letter-spacing: 0.3px; } `,Dn=w.Ay.div` padding: 26px 18px; text-align: center; background: rgba(0, 0, 0, 0.02); border-radius: 8px; color: #777; font-size: 13px; line-height: 1.5; .emoji { font-size: 24px; display: block; margin-bottom: 8px; } `,Fn={blue:{bg:"rgba(13, 125, 242, 0.10)",fg:"#0d7df2"},teal:{bg:"rgba(72, 199, 190, 0.12)",fg:"#2ea99f"},orange:{bg:"rgba(240, 160, 48, 0.14)",fg:"#c87a14"},purple:{bg:"rgba(139, 92, 246, 0.12)",fg:"#7c3aed"},pink:{bg:"rgba(236, 72, 153, 0.10)",fg:"#db2777"},green:{bg:"rgba(34, 197, 94, 0.10)",fg:"#16a34a"},red:{bg:"rgba(239, 68, 68, 0.10)",fg:"#dc2626"},slate:{bg:"rgba(100, 116, 139, 0.12)",fg:"#475569"}},Un=[{key:"module_chatbots",icon:J.A,label:"Chatbots",tab:"chatbots",color:"blue"},{key:"module_generator_content",icon:Rn.A,label:"Content Generator",tab:null,color:"teal"},{key:"module_assistant",icon:Y.A,label:"AI Editor Assistant",tab:null,color:"purple"},{key:"module_generator_images",icon:fn.A,label:"Image Generator",tab:null,color:"orange"},{key:"module_generator_videos",icon:yn.A,label:"Video Generator",tab:null,color:"pink"},{key:"module_embeddings",icon:X.A,label:"Knowledge",tab:"knowledge",color:"teal",pro:!0},{key:"module_library_search",icon:vn.A,label:"Library Search",tab:null,color:"purple"},{key:"module_search",icon:bn.A,label:"AI Search",tab:"search",color:"green"},{key:"module_forms",icon:Q.A,label:"AI Forms",tab:"forms",color:"pink",pro:!0},{key:"module_cross_site",icon:wn.A,label:"Cross-Site",tab:null,color:"blue",pro:!0},{key:"module_assistants",icon:_n.A,label:"OpenAI Assistants",tab:null,color:"slate",pro:!0},{key:"module_transcription",icon:Cn.A,label:"Transcription",tab:"transcription",color:"orange"},{key:"module_statistics",icon:An.A,label:"Insights",tab:"insights",color:"green",pro:!0},{key:"module_moderation",icon:Tn.A,label:"Moderation",tab:null,color:"red"},{key:"module_finetunes",icon:In.A,label:"Finetunes",tab:"finetunes",color:"slate"},{key:"module_orchestration",icon:Nn.A,label:"Orchestration",tab:null,color:"purple",pro:!0},{key:"module_mcp",icon:xn.A,label:"MCP Server",tab:null,color:"slate"},{key:"public_api",icon:On.A,label:"Public API",tab:null,color:"blue"},{key:"module_advisor",icon:kn.A,label:"Advisor",tab:null,color:"orange"},{key:"module_suggestions",icon:Sn.A,label:"AI Copilot",tab:null,color:"teal"},{key:"module_playground",icon:Mn.A,label:"Playground",tab:null,color:"slate"}],Bn=e=>{const t=new URL(window.location.href);t.searchParams.set("nekoTab",e),window.location.href=t.toString()},$n=({options:e,isRegistered:t})=>{const a=Un.filter((t=>!(null==e||!e[t.key])));return React.createElement(f.z,{className:"primary",title:"Active Modules"},React.createElement(c.s,{p:!0,style:{marginTop:0,marginBottom:12,color:"#555",fontSize:13}},0===a.length?"You haven't enabled any modules yet.":`${a.length} module${1===a.length?"":"s"} active. Click any card to jump straight to it, or open the Modules tab to enable more.`),0===a.length&&React.createElement(Dn,null,React.createElement("span",{className:"emoji","aria-hidden":!0},"🧩"),"Open the ",React.createElement("b",null,"Modules")," tab to enable the features you want: chatbots, content tools, knowledge bases, MCP, and more."),a.length>0&&React.createElement(Pn,null,a.map((e=>{const a=e.icon,n=Fn[e.color]||Fn.blue;return React.createElement(Ln,{key:e.key,$accent:n.bg,$accentText:n.fg,onClick:()=>e.tab?Bn(e.tab):Bn("modules"),title:e.tab?`Open ${e.label}`:"Open Modules tab"},React.createElement("span",{className:"icon-wrap"},React.createElement(a,{size:18,strokeWidth:2})),React.createElement("span",{className:"label"},e.label),e.pro&&t&&React.createElement("span",{className:"pro"},"PRO"))}))))};var Hn=a(5907);const{useState:jn}=wp.element,zn=({modal:e,setModal:t})=>{const[a,n]=jn(!1),[l,o]=jn(0),[r,i]=jn(0),s=async()=>{let e=!1;const t={page:1,limit:20,filters:{}};let a=[];for(;!e;){const n=await Ne(t);n.chats.length<2&&(e=!0),o((()=>n.total)),n.chats.forEach((e=>{e.messages=JSON.parse(e.messages),e.extra=JSON.parse(e.extra)})),a=a.concat(n.chats),i((()=>a.length)),t.page++}return a};return React.createElement(React.Fragment,null,React.createElement(se.n,{isOpen:"export"===(null==e?void 0:e.type),title:"Export Discussions",onRequestClose:()=>t(null),okButton:{label:"Close",disabled:a,onClick:()=>t(null)},customButtons:React.createElement(React.Fragment,null,React.createElement(R.M,{onClick:async()=>{try{n(!0);const e=await s(),t=(0,y.F1)(e,2),a=new Date,l=a.getFullYear(),r=a.getMonth()+1,i=a.getDate();ze(t,`discussions-${l}-${r}-${i}.json`),setTimeout((()=>{o(0)}),1e3)}catch(e){console.error(e),alert("An error occurred while exporting discussions. Check your console.")}finally{n(!1)}},disabled:a},"Export JSON")),content:React.createElement(React.Fragment,null,React.createElement(it.j,{busy:a,style:{flex:"auto"},value:r,max:l}))}))},{useMemo:Gn,useState:Wn,useEffect:qn,useCallback:Vn}=wp.element,Kn=()=>{const e=localStorage.getItem("mwai-admin-discussions");try{const t=JSON.parse(e);return{isSidebarCollapsed:(null==t?void 0:t.isSidebarCollapsed)||!1}}catch(e){return{isSidebarCollapsed:!1}}},Yn=w.Ay.div` font-size: 12px; padding: 2px 8px; background: ${e=>{var t;return(null===(t=e.$colors)||void 0===t?void 0:t.label)||"#616161"}}; color: white; border-radius: 3px 3px 0 0; `,Xn=w.Ay.span` font-weight: bold; text-transform: uppercase; font-size: 10px; `,Qn=w.Ay.div` font-size: 12px; color: white; background: var(--neko-purple); opacity: 0.65; padding: 4px 8px; `,Jn=w.Ay.div` font-size: 13px; padding: 10px; border: 1px solid #eaeaea; border-top: none; background: ${e=>e.$background||"white"}; color: #333333; word-break: break-word; overflow-wrap: break-word; word-wrap: break-word; hyphens: auto; border-radius: 0 0 3px 3px; p, ul, ol, li, span, div, a, strong, em, blockquote, table, td, th { font-size: 13px !important; } pre, code { font-size: 12px !important; } ul, ol { margin-left: 15px; } img { max-width: 100%; height: auto; } a { color: #333333; text-decoration: underline; } a:hover { color: #333333; text-decoration: none; } blockquote { border-left: 4px solid #dddddd; padding-left: 10px; margin-left: 0; font-style: italic; } pre { background: #eeeeee; padding: 10px; border-radius: 5px; overflow-x: auto; text-wrap: pretty; } code { background: #eeeeee; padding: 2px 5px; border-radius: 5px; } table { border-collapse: collapse; width: 100%; margin-bottom: 10px; } table td, table th { border: 1px solid #dddddd; text-align: left; padding: 5px; } table tr:nth-child(even) { background-color: #dddddd; } .mwai-dead-image { color: #9e9e9e; background: #ededed; padding: 8px 8px; text-align: center; } `,Zn={overrides:{object:{component:({children:e,...t})=>``${e}="${t[e]}"`)).join(" ")}>${e}`},script:{component:({children:e,...t})=>`