@helpai/elements 1.3.10 → 1.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/elements-web-component.esm.js +5 -5
- package/elements-web-component.esm.js.map +3 -3
- package/elements.cjs.js +5 -5
- package/elements.cjs.js.map +3 -3
- package/elements.esm.js +5 -5
- package/elements.esm.js.map +3 -3
- package/elements.js +5 -5
- package/elements.js.map +3 -3
- package/index.mjs +3 -3
- package/package.json +1 -1
- package/web-component.mjs +4 -4
package/web-component.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{Component as e,h as t,render as n}from"preact";import{useCallback as r,useEffect as i,useLayoutEffect as a,useMemo as o,useRef as s,useState as c}from"preact/hooks";import{batch as l,computed as u,effect as d,signal as f,useComputed as p,useSignal as m}from"@preact/signals";import{Fragment as h,jsx as g,jsxs as _}from"preact/jsx-runtime";import{memo as v}from"preact/compat";import*as y from"streaming-markdown";const b={id:`help-ai`,name:`@helpai/elements`,global:`HelpAI`,tagName:`web-ai-chat`,cssPrefix:`helpai`,defaultBaseUrl:`https://help.ai`,displayName:`Help AI`,domain:`help.ai`,siteUrl:`https://help.ai`},x={attach:`Attach files`,attachmentMimeRejected:`File type not supported`,attachmentTooLarge:`File is too large`,attachmentTooMany:`Attachment limit reached`,conversationClosed:`This chat is closed`,conversationLoading:`Loading chat…`,loadPreviousMessages:`Load previous messages`,close:`Close`,collapse:`Collapse`,collapseSidebar:`Collapse sidebar`,composerPlaceholder:`Type a message…`,dateLastWeek:`Last 7 days`,dateOlder:`Older`,dateToday:`Today`,dateYesterday:`Yesterday`,dropZone:`Drop files to attach`,errorGeneric:`Something went wrong`,errorRateLimited:`Too many requests — please try again in a moment.`,errorRetry:`Retry`,expand:`Expand`,expandSidebar:`Expand sidebar`,exitFullscreen:`Exit fullscreen`,fullscreen:`Fullscreen`,history:`History`,historyBack:`Back to chat`,historyEmpty:`No previous chats yet`,historyLoading:`Loading your chats…`,historyContinue:`Continue the chat`,historyTitle:`Chat history`,loadMoreConversations:`Load more conversations`,language:`Language`,launcherOpen:`Open chat`,launcherLabel:`Chat with us`,micStart:`Start voice input`,micStop:`Stop voice input`,micUnsupported:`Voice input is not supported in this browser`,moreActions:`More actions`,newConversation:`New chat`,panelTitle:`Chat`,popOut:`Open in new tab`,resizeHandle:`Drag to resize`,scrollToBottom:`Scroll to latest`,send:`Send`,queueMessage:`Queue message`,removeQueuedMessage:`Remove queued message`,compactingContext:`Optimizing conversation context…`,soundOff:`Sound off`,soundOn:`Sound on`,startNewConversation:`Start a new chat`,talkToOperator:`Talk to an operator`,connectingOperator:`Connecting you to an operator…`,noOperatorAvailable:`No one's available right now — leave your details and we'll follow up.`,chattingWithOperator:`You're chatting with {operator}`,cancelOperatorRequest:`Keep chatting with the AI`,stop:`Stop`,theme:`Theme`,themeAuto:`Auto`,themeDark:`Dark`,themeLight:`Light`,textSize:`Text size`,textSizeSmall:`Small`,textSizeNormal:`Normal`,textSizeLarge:`Large`,loading:`Loading…`,thinking:`Thinking…`,thoughts:`Thoughts`,toolResult:`Result`,sources:`Sources`,feedbackUp:`Good response`,feedbackDown:`Bad response`,feedbackThanks:`Thanks for your feedback`,copy:`Copy`,copied:`Copied`,tabHome:`Home`,tabConversations:`Chats`,tabHelp:`Help`,tabNews:`News`,modulesEmpty:`Nothing here yet`,moduleBack:`Back`,contentLoading:`Loading…`,homeGreeting:`How can we help?`,homeGreetingNamed:`Hi {name} 👋`,homeGreetingLead:`How can we help?`,homeSearchPlaceholder:`Search for help`,homeContentTitle:`Popular articles`,homeStatus:`Status`,helpTitle:`Help`,helpSearchPlaceholder:`Search for help`,helpEmpty:`No help articles yet`,helpLoading:`Loading help…`,helpSearchEmpty:`No results found`,newsTitle:`News`,newsEmpty:`No news yet`,newsLoading:`Loading news…`,newsBack:`Back to news`,newsPublishedAt:`Published {date}`,formSubmit:`Submit`,formSkip:`Maybe later`,formSubmitted:`Completed`,formSkipped:`Maybe later`,formFillOut:`Fill out`,formRequired:`This field is required`,formInvalidEmail:`Enter a valid email address`,formInvalidTel:`Enter a valid phone number`,formInvalidUrl:`Enter a valid URL`,formInvalidNumber:`Enter a valid number`,formTooShort:`Too short (min {min} characters)`,formTooLong:`Too long (max {max} characters)`,formNumberTooSmall:`Must be at least {min}`,formNumberTooLarge:`Must be at most {max}`,formPatternMismatch:`Please match the requested format`,formChooseAtLeast:`Choose at least {min}`,formChooseAtMost:`Choose at most {max}`,formOther:`Other`,formOtherPlaceholder:`Type your answer…`,inputRequired:`Questions for you`,inputBadge:`Questions`,inputAnswered:`Answered`,inputSkipped:`Skipped`,showOptions:`Show options`,hideOptions:`Hide options`,qtypeText:`Your answer`,qtypeEmail:`Email address`,qtypePhone:`Phone number`,qtypeNumber:`Number`,qtypeDate:`Date`,qtypeChooseOne:`Pick one`,qtypeChooseAny:`Pick any`,qtypeBoolean:`Yes / No`,inputSubmit:`Submit answers`,inputSubmitHint:`Enter to send · Shift+Enter = new line`,inputSkip:`Skip`,confirmYes:`Yes`,confirmNo:`No`,approve:`Approve`,reject:`Reject`,approvalPrompt:`{tool} requires your approval to execute.`,approvalBody:`Review the tool input above and decide whether to allow this action.`,approvalYourResponse:`Your response: {decision}`,approvalEditHint:`You can edit this response until this step continues.`,approvalSubmitting:`Response submitted. Request in progress…`,edit:`Edit`,toolParameters:`Parameters`,statusAwaiting:`Awaiting Approval`,statusResponded:`Submitted`,statusRunning:`Running`,statusCompleted:`Completed`,statusDenied:`Denied`,statusError:`Error`,statusSuperseded:`Skipped`},S={en:x,fr:{attach:`Joindre des fichiers`,attachmentMimeRejected:`Type de fichier non pris en charge`,attachmentTooLarge:`Le fichier est trop volumineux`,attachmentTooMany:`Limite de pièces jointes atteinte`,conversationClosed:`Ce chat est fermé`,conversationLoading:`Chargement du chat…`,loadPreviousMessages:`Charger les messages précédents`,close:`Fermer`,collapse:`Réduire`,collapseSidebar:`Réduire la barre latérale`,composerPlaceholder:`Écrivez un message…`,dateLastWeek:`7 derniers jours`,dateOlder:`Plus ancien`,dateToday:`Aujourd'hui`,dateYesterday:`Hier`,dropZone:`Déposez les fichiers à joindre`,errorGeneric:`Une erreur s'est produite`,errorRateLimited:`Trop de requêtes — veuillez réessayer dans un instant.`,errorRetry:`Réessayer`,expand:`Agrandir`,expandSidebar:`Développer la barre latérale`,exitFullscreen:`Quitter le plein écran`,fullscreen:`Plein écran`,history:`Historique`,historyBack:`Retour au chat`,historyEmpty:`Aucun chat pour le moment`,historyContinue:`Poursuivre le chat`,historyLoading:`Chargement de vos chats…`,historyTitle:`Historique des chats`,loadMoreConversations:`Charger plus de conversations`,language:`Langue`,launcherOpen:`Ouvrir le chat`,launcherLabel:`Discuter avec nous`,micStart:`Démarrer la saisie vocale`,micStop:`Arrêter la saisie vocale`,micUnsupported:`La saisie vocale n'est pas prise en charge par ce navigateur`,moreActions:`Plus d'actions`,newConversation:`Nouveau chat`,panelTitle:`Chat`,popOut:`Ouvrir dans un nouvel onglet`,resizeHandle:`Glisser pour redimensionner`,scrollToBottom:`Aller au plus récent`,send:`Envoyer`,queueMessage:`Mettre le message en attente`,removeQueuedMessage:`Retirer le message en attente`,compactingContext:`Optimisation du contexte de la conversation…`,soundOff:`Son désactivé`,soundOn:`Son activé`,startNewConversation:`Démarrer un nouveau chat`,talkToOperator:`Parler à un opérateur`,connectingOperator:`Mise en relation avec un opérateur…`,noOperatorAvailable:`Personne n'est disponible pour le moment — laissez vos coordonnées et nous reviendrons vers vous.`,chattingWithOperator:`Vous discutez avec {operator}`,cancelOperatorRequest:`Continuer avec l'IA`,stop:`Arrêter`,theme:`Thème`,themeAuto:`Auto`,themeDark:`Sombre`,themeLight:`Clair`,textSize:`Taille du texte`,textSizeSmall:`Petite`,textSizeNormal:`Normale`,textSizeLarge:`Grande`,loading:`Chargement…`,thinking:`Réflexion…`,thoughts:`Réflexions`,toolResult:`Résultat`,sources:`Sources`,feedbackUp:`Bonne réponse`,feedbackDown:`Mauvaise réponse`,feedbackThanks:`Merci pour votre retour`,copy:`Copier`,copied:`Copié`,tabHome:`Accueil`,tabConversations:`Chats`,tabHelp:`Aide`,tabNews:`Actualités`,modulesEmpty:`Rien pour le moment`,moduleBack:`Retour`,contentLoading:`Chargement…`,homeGreeting:`Comment pouvons-nous vous aider ?`,homeGreetingNamed:`Bonjour {name} 👋`,homeGreetingLead:`Comment pouvons-nous vous aider ?`,homeSearchPlaceholder:`Rechercher de l'aide`,homeContentTitle:`Articles populaires`,homeStatus:`Statut`,helpTitle:`Aide`,helpSearchPlaceholder:`Rechercher de l'aide`,helpEmpty:`Aucun article d'aide pour le moment`,helpLoading:`Chargement de l'aide…`,helpSearchEmpty:`Aucun résultat trouvé`,newsTitle:`Actualités`,newsEmpty:`Aucune actualité pour le moment`,newsLoading:`Chargement des actualités…`,newsBack:`Retour aux actualités`,newsPublishedAt:`Publié le {date}`,formSubmit:`Envoyer`,formSkip:`Plus tard`,formSubmitted:`Terminé`,formSkipped:`Plus tard`,formFillOut:`Remplir`,formRequired:`Ce champ est obligatoire`,formInvalidEmail:`Saisissez une adresse e-mail valide`,formInvalidTel:`Saisissez un numéro de téléphone valide`,formInvalidUrl:`Saisissez une URL valide`,formInvalidNumber:`Saisissez un nombre valide`,formTooShort:`Trop court (min. {min} caractères)`,formTooLong:`Trop long (max. {max} caractères)`,formNumberTooSmall:`Doit être au moins {min}`,formNumberTooLarge:`Doit être au plus {max}`,formPatternMismatch:`Veuillez respecter le format demandé`,formChooseAtLeast:`Choisissez au moins {min}`,formChooseAtMost:`Choisissez au plus {max}`,formOther:`Autre`,formOtherPlaceholder:`Saisissez votre réponse…`,inputRequired:`Questions pour vous`,inputBadge:`Questions`,inputAnswered:`Répondu`,inputSkipped:`Ignoré`,showOptions:`Afficher les options`,hideOptions:`Masquer les options`,qtypeText:`Votre réponse`,qtypeEmail:`Adresse e-mail`,qtypePhone:`Numéro de téléphone`,qtypeNumber:`Nombre`,qtypeDate:`Date`,qtypeChooseOne:`Choisir une`,qtypeChooseAny:`Choisir plusieurs`,qtypeBoolean:`Oui / Non`,inputSubmit:`Envoyer les réponses`,inputSubmitHint:`Entrée pour envoyer · Maj+Entrée = saut de ligne`,inputSkip:`Ignorer`,confirmYes:`Oui`,confirmNo:`Non`,approve:`Approuver`,reject:`Refuser`,approvalPrompt:`{tool} nécessite votre approbation pour s'exécuter.`,approvalBody:`Vérifiez les paramètres ci-dessus et décidez d'autoriser ou non cette action.`,approvalYourResponse:`Votre réponse : {decision}`,approvalEditHint:`Vous pouvez modifier votre réponse jusqu'à la reprise de cette étape.`,approvalSubmitting:`Réponse envoyée. Traitement en cours…`,edit:`Modifier`,toolParameters:`Paramètres`,statusAwaiting:`En attente d'approbation`,statusResponded:`Envoyé`,statusRunning:`En cours`,statusCompleted:`Terminé`,statusDenied:`Refusé`,statusError:`Erreur`,statusSuperseded:`Ignoré`},ar:{attach:`إرفاق ملفات`,attachmentMimeRejected:`نوع الملف غير مدعوم`,attachmentTooLarge:`حجم الملف كبير جدًا`,attachmentTooMany:`تم بلوغ الحد الأقصى للمرفقات`,conversationClosed:`تم إغلاق هذه الدردشة`,conversationLoading:`جارٍ تحميل الدردشة…`,loadPreviousMessages:`تحميل الرسائل السابقة`,close:`إغلاق`,collapse:`طيّ`,collapseSidebar:`طيّ الشريط الجانبي`,composerPlaceholder:`اكتب رسالة…`,dateLastWeek:`آخر ٧ أيام`,dateOlder:`أقدم`,dateToday:`اليوم`,dateYesterday:`أمس`,dropZone:`أفلت الملفات لإرفاقها`,errorGeneric:`حدث خطأ ما`,errorRateLimited:`طلبات كثيرة جدًا — يرجى المحاولة بعد لحظة.`,errorRetry:`إعادة المحاولة`,expand:`توسيع`,expandSidebar:`توسيع الشريط الجانبي`,exitFullscreen:`إنهاء ملء الشاشة`,fullscreen:`ملء الشاشة`,history:`السجل`,historyBack:`العودة إلى الدردشة`,historyEmpty:`لا توجد دردشات سابقة بعد`,historyContinue:`متابعة الدردشة`,historyLoading:`جارٍ تحميل دردشاتك…`,historyTitle:`سجل الدردشات`,loadMoreConversations:`تحميل المزيد من المحادثات`,language:`اللغة`,launcherOpen:`فتح الدردشة`,launcherLabel:`تحدث معنا`,micStart:`بدء الإدخال الصوتي`,micStop:`إيقاف الإدخال الصوتي`,micUnsupported:`الإدخال الصوتي غير مدعوم في هذا المتصفح`,moreActions:`إجراءات إضافية`,newConversation:`دردشة جديدة`,panelTitle:`الدردشة`,popOut:`فتح في علامة تبويب جديدة`,resizeHandle:`اسحب لتغيير الحجم`,scrollToBottom:`الانتقال إلى الأحدث`,send:`إرسال`,queueMessage:`إضافة الرسالة إلى قائمة الانتظار`,removeQueuedMessage:`إزالة الرسالة من قائمة الانتظار`,compactingContext:`جارٍ تحسين سياق المحادثة…`,soundOff:`كتم الصوت`,soundOn:`تشغيل الصوت`,startNewConversation:`بدء دردشة جديدة`,talkToOperator:`التحدث إلى موظف`,connectingOperator:`جاري توصيلك بأحد الموظفين…`,noOperatorAvailable:`لا يوجد موظفون متاحون الآن — اترك بياناتك وسنتواصل معك.`,chattingWithOperator:`أنت تتحدث مع {operator}`,cancelOperatorRequest:`متابعة المحادثة مع الذكاء الاصطناعي`,stop:`إيقاف`,theme:`المظهر`,themeAuto:`تلقائي`,themeDark:`داكن`,themeLight:`فاتح`,textSize:`حجم النص`,textSizeSmall:`صغير`,textSizeNormal:`عادي`,textSizeLarge:`كبير`,loading:`جارٍ التحميل…`,thinking:`يفكّر…`,thoughts:`الأفكار`,toolResult:`النتيجة`,sources:`المصادر`,feedbackUp:`رد جيد`,feedbackDown:`رد سيئ`,feedbackThanks:`شكرًا على ملاحظاتك`,copy:`نسخ`,copied:`تم النسخ`,tabHome:`الرئيسية`,tabConversations:`الدردشات`,tabHelp:`المساعدة`,tabNews:`الأخبار`,modulesEmpty:`لا شيء هنا بعد`,moduleBack:`رجوع`,contentLoading:`جارٍ التحميل…`,homeGreeting:`كيف يمكننا مساعدتك؟`,homeGreetingNamed:`مرحبًا {name} 👋`,homeGreetingLead:`كيف يمكننا مساعدتك؟`,homeSearchPlaceholder:`ابحث عن مساعدة`,homeContentTitle:`مقالات شائعة`,homeStatus:`الحالة`,helpTitle:`المساعدة`,helpSearchPlaceholder:`ابحث عن مساعدة`,helpEmpty:`لا توجد مقالات مساعدة بعد`,helpLoading:`جارٍ تحميل المساعدة…`,helpSearchEmpty:`لا توجد نتائج`,newsTitle:`الأخبار`,newsEmpty:`لا توجد أخبار بعد`,newsLoading:`جارٍ تحميل الأخبار…`,newsBack:`العودة إلى الأخبار`,newsPublishedAt:`نُشر في {date}`,formSubmit:`إرسال`,formSkip:`لاحقًا`,formSubmitted:`تم`,formSkipped:`لاحقًا`,formFillOut:`تعبئة`,formRequired:`هذا الحقل مطلوب`,formInvalidEmail:`أدخل بريدًا إلكترونيًا صحيحًا`,formInvalidTel:`أدخل رقم هاتف صحيحًا`,formInvalidUrl:`أدخل رابطًا صحيحًا`,formInvalidNumber:`أدخل رقمًا صحيحًا`,formTooShort:`قصير جدًا (الحد الأدنى {min} حرفًا)`,formTooLong:`طويل جدًا (الحد الأقصى {max} حرفًا)`,formNumberTooSmall:`يجب ألا يقل عن {min}`,formNumberTooLarge:`يجب ألا يزيد عن {max}`,formPatternMismatch:`يرجى مطابقة الصيغة المطلوبة`,formChooseAtLeast:`اختر {min} على الأقل`,formChooseAtMost:`اختر {max} على الأكثر`,formOther:`أخرى`,formOtherPlaceholder:`اكتب إجابتك…`,inputRequired:`أسئلة لك`,inputBadge:`أسئلة`,inputAnswered:`تمت الإجابة`,inputSkipped:`تم التخطي`,showOptions:`إظهار الخيارات`,hideOptions:`إخفاء الخيارات`,qtypeText:`إجابتك`,qtypeEmail:`عنوان البريد الإلكتروني`,qtypePhone:`رقم الهاتف`,qtypeNumber:`رقم`,qtypeDate:`تاريخ`,qtypeChooseOne:`اختر واحدًا`,qtypeChooseAny:`اختر أيًا`,qtypeBoolean:`نعم / لا`,inputSubmit:`إرسال الإجابات`,inputSubmitHint:`Enter للإرسال · Shift+Enter = سطر جديد`,inputSkip:`تخطٍّ`,confirmYes:`نعم`,confirmNo:`لا`,approve:`موافقة`,reject:`رفض`,approvalPrompt:`تتطلب {tool} موافقتك للتنفيذ.`,approvalBody:`راجع مُعطيات الأداة أعلاه وقرّر السماح بهذا الإجراء أو رفضه.`,approvalYourResponse:`ردّك: {decision}`,approvalEditHint:`يمكنك تعديل ردّك حتى تستأنف هذه الخطوة.`,approvalSubmitting:`تم إرسال الرد. جارٍ التنفيذ…`,edit:`تعديل`,toolParameters:`المعطيات`,statusAwaiting:`بانتظار الموافقة`,statusResponded:`تم الإرسال`,statusRunning:`قيد التنفيذ`,statusCompleted:`مكتمل`,statusDenied:`مرفوض`,statusError:`خطأ`,statusSuperseded:`تم التخطي`},es:{attach:`Adjuntar archivos`,attachmentMimeRejected:`Tipo de archivo no admitido`,attachmentTooLarge:`El archivo es demasiado grande`,attachmentTooMany:`Se alcanzó el límite de adjuntos`,conversationClosed:`Este chat está cerrado`,conversationLoading:`Cargando chat…`,loadPreviousMessages:`Cargar mensajes anteriores`,close:`Cerrar`,collapse:`Contraer`,collapseSidebar:`Contraer la barra lateral`,composerPlaceholder:`Escribe un mensaje…`,dateLastWeek:`Últimos 7 días`,dateOlder:`Anteriores`,dateToday:`Hoy`,dateYesterday:`Ayer`,dropZone:`Suelta los archivos para adjuntarlos`,errorGeneric:`Algo salió mal`,errorRateLimited:`Demasiadas solicitudes: inténtalo de nuevo en un momento.`,errorRetry:`Reintentar`,expand:`Ampliar`,expandSidebar:`Expandir la barra lateral`,exitFullscreen:`Salir de pantalla completa`,fullscreen:`Pantalla completa`,history:`Historial`,historyBack:`Volver al chat`,historyEmpty:`Aún no tienes chats`,historyContinue:`Continuar el chat`,historyLoading:`Cargando tus chats…`,historyTitle:`Historial de chats`,loadMoreConversations:`Cargar más conversaciones`,language:`Idioma`,launcherOpen:`Abrir el chat`,launcherLabel:`Chatea con nosotros`,micStart:`Iniciar entrada de voz`,micStop:`Detener entrada de voz`,micUnsupported:`Este navegador no admite la entrada de voz`,moreActions:`Más acciones`,newConversation:`Nuevo chat`,panelTitle:`Chat`,popOut:`Abrir en una pestaña nueva`,resizeHandle:`Arrastra para cambiar el tamaño`,scrollToBottom:`Ir a lo más reciente`,send:`Enviar`,queueMessage:`Poner mensaje en cola`,removeQueuedMessage:`Quitar mensaje de la cola`,compactingContext:`Optimizando el contexto de la conversación…`,soundOff:`Sonido desactivado`,soundOn:`Sonido activado`,startNewConversation:`Iniciar un chat nuevo`,talkToOperator:`Hablar con un operador`,connectingOperator:`Conectándote con un operador…`,noOperatorAvailable:`Nadie está disponible ahora — deja tus datos y te contactaremos.`,chattingWithOperator:`Estás chateando con {operator}`,cancelOperatorRequest:`Seguir con la IA`,stop:`Detener`,theme:`Tema`,themeAuto:`Automático`,themeDark:`Oscuro`,themeLight:`Claro`,textSize:`Tamaño del texto`,textSizeSmall:`Pequeño`,textSizeNormal:`Normal`,textSizeLarge:`Grande`,loading:`Cargando…`,thinking:`Pensando…`,thoughts:`Razonamiento`,toolResult:`Resultado`,sources:`Fuentes`,feedbackUp:`Buena respuesta`,feedbackDown:`Mala respuesta`,feedbackThanks:`Gracias por tu opinión`,copy:`Copiar`,copied:`Copiado`,tabHome:`Inicio`,tabConversations:`Chats`,tabHelp:`Ayuda`,tabNews:`Novedades`,modulesEmpty:`Aún no hay nada aquí`,moduleBack:`Atrás`,contentLoading:`Cargando…`,homeGreeting:`¿Cómo podemos ayudarte?`,homeGreetingNamed:`Hola, {name} 👋`,homeGreetingLead:`¿Cómo podemos ayudarte?`,homeSearchPlaceholder:`Buscar ayuda`,homeContentTitle:`Artículos populares`,homeStatus:`Estado`,helpTitle:`Ayuda`,helpSearchPlaceholder:`Buscar ayuda`,helpEmpty:`Aún no hay artículos de ayuda`,helpLoading:`Cargando la ayuda…`,helpSearchEmpty:`No se encontraron resultados`,newsTitle:`Novedades`,newsEmpty:`Aún no hay novedades`,newsLoading:`Cargando novedades…`,newsBack:`Volver a novedades`,newsPublishedAt:`Publicado el {date}`,formSubmit:`Enviar`,formSkip:`Quizá más tarde`,formSubmitted:`Completado`,formSkipped:`Quizá más tarde`,formFillOut:`Completar`,formRequired:`Este campo es obligatorio`,formInvalidEmail:`Introduce un correo electrónico válido`,formInvalidTel:`Introduce un número de teléfono válido`,formInvalidUrl:`Introduce una URL válida`,formInvalidNumber:`Introduce un número válido`,formTooShort:`Demasiado corto (mín. {min} caracteres)`,formTooLong:`Demasiado largo (máx. {max} caracteres)`,formNumberTooSmall:`Debe ser al menos {min}`,formNumberTooLarge:`Debe ser como máximo {max}`,formPatternMismatch:`Respeta el formato solicitado`,formChooseAtLeast:`Elige al menos {min}`,formChooseAtMost:`Elige como máximo {max}`,formOther:`Otro`,formOtherPlaceholder:`Escribe tu respuesta…`,inputRequired:`Preguntas para ti`,inputBadge:`Preguntas`,inputAnswered:`Respondido`,inputSkipped:`Omitido`,showOptions:`Mostrar opciones`,hideOptions:`Ocultar opciones`,qtypeText:`Tu respuesta`,qtypeEmail:`Correo electrónico`,qtypePhone:`Número de teléfono`,qtypeNumber:`Número`,qtypeDate:`Fecha`,qtypeChooseOne:`Elige una`,qtypeChooseAny:`Elige varias`,qtypeBoolean:`Sí / No`,inputSubmit:`Enviar respuestas`,inputSubmitHint:`Enter para enviar · Mayús+Enter = nueva línea`,inputSkip:`Omitir`,confirmYes:`Sí`,confirmNo:`No`,approve:`Aprobar`,reject:`Rechazar`,approvalPrompt:`{tool} requiere tu aprobación para ejecutarse.`,approvalBody:`Revisa los parámetros de arriba y decide si permites esta acción.`,approvalYourResponse:`Tu respuesta: {decision}`,approvalEditHint:`Puedes cambiar tu respuesta hasta que este paso continúe.`,approvalSubmitting:`Respuesta enviada. Procesando…`,edit:`Editar`,toolParameters:`Parámetros`,statusAwaiting:`Esperando aprobación`,statusResponded:`Enviado`,statusRunning:`En curso`,statusCompleted:`Completado`,statusDenied:`Denegado`,statusError:`Error`,statusSuperseded:`Omitido`},he:{attach:`צירוף קבצים`,attachmentMimeRejected:`סוג הקובץ אינו נתמך`,attachmentTooLarge:`הקובץ גדול מדי`,attachmentTooMany:`הגעת למספר המרבי של קבצים מצורפים`,conversationClosed:`הצ׳אט הזה נסגר`,conversationLoading:`טוען צ׳אט…`,loadPreviousMessages:`טעינת הודעות קודמות`,close:`סגירה`,collapse:`כיווץ`,collapseSidebar:`כיווץ סרגל הצד`,composerPlaceholder:`כתוב הודעה…`,dateLastWeek:`7 הימים האחרונים`,dateOlder:`ישן יותר`,dateToday:`היום`,dateYesterday:`אתמול`,dropZone:`שחרר קבצים כדי לצרף`,errorGeneric:`משהו השתבש`,errorRateLimited:`יותר מדי בקשות — נסה שוב בעוד רגע.`,errorRetry:`נסה שוב`,expand:`הרחבה`,expandSidebar:`הרחבת סרגל הצד`,exitFullscreen:`יציאה ממסך מלא`,fullscreen:`מסך מלא`,history:`היסטוריה`,historyBack:`חזרה לצ׳אט`,historyEmpty:`אין עדיין צ׳אטים קודמים`,historyContinue:`המשך צ׳אט`,historyLoading:`טוען את הצ׳אטים שלך…`,historyTitle:`היסטוריית צ׳אטים`,loadMoreConversations:`טעינת שיחות נוספות`,language:`שפה`,launcherOpen:`פתיחת צ׳אט`,launcherLabel:`דברו איתנו`,micStart:`התחלת קלט קולי`,micStop:`עצירת קלט קולי`,micUnsupported:`קלט קולי אינו נתמך בדפדפן זה`,moreActions:`פעולות נוספות`,newConversation:`צ׳אט חדש`,panelTitle:`צ׳אט`,popOut:`פתיחה בכרטיסייה חדשה`,resizeHandle:`גרור לשינוי הגודל`,scrollToBottom:`מעבר לחדש ביותר`,send:`שליחה`,queueMessage:`הוספת ההודעה לתור`,removeQueuedMessage:`הסרת ההודעה מהתור`,compactingContext:`מבצע אופטימיזציה להקשר השיחה…`,soundOff:`השתקת הצליל`,soundOn:`הפעלת הצליל`,startNewConversation:`התחלת צ׳אט חדש`,talkToOperator:`דבר עם נציג`,connectingOperator:`מחבר אותך לנציג…`,noOperatorAvailable:`אין נציגים זמינים כעת — השאר את הפרטים שלך ונחזור אליך.`,chattingWithOperator:`אתה מצ׳וטט עם {operator}`,cancelOperatorRequest:`המשך לשוחח עם ה-AI`,stop:`עצירה`,theme:`ערכת נושא`,themeAuto:`אוטומטי`,themeDark:`כהה`,themeLight:`בהיר`,textSize:`גודל טקסט`,textSizeSmall:`קטן`,textSizeNormal:`רגיל`,textSizeLarge:`גדול`,loading:`טוען…`,thinking:`חושב…`,thoughts:`מחשבות`,toolResult:`תוצאה`,sources:`מקורות`,feedbackUp:`תשובה טובה`,feedbackDown:`תשובה גרועה`,feedbackThanks:`תודה על המשוב`,copy:`העתק`,copied:`הועתק`,tabHome:`בית`,tabConversations:`צ׳אטים`,tabHelp:`עזרה`,tabNews:`חדשות`,modulesEmpty:`אין כאן עדיין כלום`,moduleBack:`חזרה`,contentLoading:`טוען…`,homeGreeting:`כיצד נוכל לעזור?`,homeGreetingNamed:`שלום {name} 👋`,homeGreetingLead:`כיצד נוכל לעזור?`,homeSearchPlaceholder:`חיפוש עזרה`,homeContentTitle:`מאמרים פופולריים`,homeStatus:`סטטוס`,helpTitle:`עזרה`,helpSearchPlaceholder:`חיפוש עזרה`,helpEmpty:`אין עדיין מאמרי עזרה`,helpLoading:`טוען עזרה…`,helpSearchEmpty:`לא נמצאו תוצאות`,newsTitle:`חדשות`,newsEmpty:`אין עדיין חדשות`,newsLoading:`טוען חדשות…`,newsBack:`חזרה לחדשות`,newsPublishedAt:`פורסם ב-{date}`,formSubmit:`שליחה`,formSkip:`אחר כך`,formSubmitted:`נשלח`,formSkipped:`דולג`,formFillOut:`מילוי`,formRequired:`שדה חובה`,formInvalidEmail:`הזן כתובת אימייל תקינה`,formInvalidTel:`הזן מספר טלפון תקין`,formInvalidUrl:`הזן כתובת URL תקינה`,formInvalidNumber:`הזן מספר תקין`,formTooShort:`קצר מדי (לפחות {min} תווים)`,formTooLong:`ארוך מדי (לכל היותר {max} תווים)`,formNumberTooSmall:`חייב להיות לפחות {min}`,formNumberTooLarge:`חייב להיות לכל היותר {max}`,formPatternMismatch:`התאם לתבנית הנדרשת`,formChooseAtLeast:`בחר לפחות {min}`,formChooseAtMost:`בחר לכל היותר {max}`,formOther:`אחר`,formOtherPlaceholder:`כתוב את תשובתך…`,inputRequired:`שאלות עבורך`,inputBadge:`שאלות`,inputAnswered:`נענה`,inputSkipped:`דולג`,showOptions:`הצג אפשרויות`,hideOptions:`הסתר אפשרויות`,qtypeText:`התשובה שלך`,qtypeEmail:`כתובת אימייל`,qtypePhone:`מספר טלפון`,qtypeNumber:`מספר`,qtypeDate:`תאריך`,qtypeChooseOne:`בחר אחת`,qtypeChooseAny:`בחר כמה`,qtypeBoolean:`כן / לא`,inputSubmit:`שליחת תשובות`,inputSubmitHint:`Enter לשליחה · Shift+Enter = שורה חדשה`,inputSkip:`דילוג`,confirmYes:`כן`,confirmNo:`לא`,approve:`אישור`,reject:`דחייה`,approvalPrompt:`הכלי {tool} דורש את אישורך כדי לפעול.`,approvalBody:`בדוק את פרמטרי הכלי שלמעלה והחלט אם לאשר פעולה זו.`,approvalYourResponse:`התגובה שלך: {decision}`,approvalEditHint:`ניתן לערוך את תגובתך עד שהשלב הזה יתחדש.`,approvalSubmitting:`התגובה נשלחה. מבצע…`,edit:`עריכה`,toolParameters:`פרמטרים`,statusAwaiting:`ממתין לאישור`,statusResponded:`נשלח`,statusRunning:`פועל`,statusCompleted:`הושלם`,statusDenied:`נדחה`,statusError:`שגיאה`,statusSuperseded:`דולג`}};function C(e,t){let n=w(e),r=O(t),i=n===`en`?{}:S[n]??{},a=r?t[n]??{}:t??{},o=r?t.en??{}:{};return{...x,...i,...o,...a}}function w(e){return(e.split(`-`)[0]??`en`).toLowerCase()}const T=new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`,`ks`,`nqo`,`prs`,`syr`]);function E(e){return T.has(w(e))}function D(e,t){return e[t]??t}function O(e){if(!e)return!1;for(let t of Object.values(e))if(t&&typeof t==`object`)return!0;return!1}function k(e,t){if(!(!e?.length||!t))return e.find(e=>e.locale===t)}function A(e,t){let{translations:n,defaultLocale:r,...i}=e,a=k(n,t);return a?{...i,title:a.title??i.title,description:a.description??i.description,content:a.content??i.content}:i}function j(e,t){let{translations:n,defaultLocale:r,...i}=e,a=k(n,t);if(!a)return i;let o=new Map((a.fields??[]).map(e=>[e.name,e])),s=i.fields.map(e=>{let t=o.get(e.name);if(!t)return e;let n=new Map((t.options??[]).map(e=>[e.value,e]));return{...e,label:t.label??e.label,placeholder:t.placeholder??e.placeholder,validationHint:t.validationHint??e.validationHint,options:e.options?.map(e=>{let t=n.get(e.value);return t?{...e,label:t.label??e.label,description:t.description??e.description}:e})}});return{...i,title:a.title??i.title,description:a.description??i.description,submitLabel:a.submitLabel??i.submitLabel,fields:s}}const M=new class{get(e){try{return localStorage.getItem(e)}catch{return null}}set(e,t){try{localStorage.setItem(e,t)}catch{}}remove(e){try{localStorage.removeItem(e)}catch{}}},ee=[`off`,`error`,`warn`,`info`,`debug`,`trace`],te=b.cssPrefix,N=`${te}.debug`,ne=`__${b.global}_DEBUG__`,re=`${te}-debug`;let P=2;function F(){if(typeof window>`u`)return 2;try{let e=new URLSearchParams(window.location.search).get(re);if(e!==null){let t=ie(e);if(t>=0)return t}}catch{}try{let e=window.localStorage?.getItem(N);if(e){let t=ie(e);if(t>=0)return t}}catch{}return Reflect.get(window,ne)?4:2}function ie(e){if(e===!0||e===`1`||e===`true`)return 4;if(e===!1||e===`0`||e===`false`||e===`off`)return 0;if(typeof e==`number`)return Math.max(0,Math.min(5,Math.floor(e)));if(typeof e==`string`){let t=ee.findIndex(t=>t===e);if(t>=0)return t}return-1}P=F();function ae(e){let t=`[${te}:${e}]`,n=(e,n,r)=>(r,i)=>{P<e||(i===void 0?console[n](t,r):console[n](t,r,i))};return{error:n(1,`error`,`error`),warn:n(2,`warn`,`warn`),info:n(3,`info`,`info`),debug:n(4,`debug`,`debug`),trace:n(5,`debug`,`trace`),scope:t=>ae(`${e}:${t}`)}}const I=ae(`core`),L=I.scope(`context`),oe=new Set([`visitorId`,`conversationId`,`jwt`,`token`,`authorization`,`password`]),se=1024,ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function le(e){return de(e,`userContext`,!0)}function ue(e){return de(e,`pageContext`,!1)}function de(e,t,n){if(e==null)return;if(typeof e!=`object`||Array.isArray(e)){L.warn(`ignored ${t} — expected an object`,{type:Array.isArray(e)?`array`:typeof e});return}let r={},i=0;for(let[n,a]of Object.entries(e)){if(oe.has(n)){L.warn(`dropped reserved ${t} key "${n}" — managed by the widget, not host-settable`);continue}if(a==null)continue;if(i>=50){L.warn(`${t} truncated at 50 keys — dropped "${n}"`);continue}let e=fe(t,n,a);e!==void 0&&(r[n]=e,i++)}return n&&typeof r.email==`string`&&!ce.test(r.email)&&(L.warn(`dropped malformed context field`,{field:`${t}.email`,reason:`invalid format`}),delete r.email),Object.keys(r).length>0?r:void 0}function fe(e,t,n){if(typeof n==`boolean`)return n;if(typeof n==`number`){if(!Number.isFinite(n)){L.warn(`dropped non-finite ${e}.${t}`);return}return n}if(typeof n==`string`){let r=n.trim();return r===``?void 0:r.length>se?(L.warn(`truncated ${e}.${t} to ${se} chars`),r.slice(0,se)):r}L.warn(`dropped ${e}.${t} — only string/number/boolean values are allowed`,{type:typeof n})}const pe={maxBytes:10*1024*1024,maxCount:10,accept:`*/*`},me={voice:`local`},R={list:[],byTrigger:{}},he={enabled:!0,sampleRate:1},ge={upload:`/pai/upload-file`,transcribe:`/pai/transcribe-audio`,submitForm:`/pai/submit-form`},_e={variant:`circle`,size:`md`,label:void 0,icon:`chat`,hidden:!1},ve={floating:[`theme`,`textSize`,`history`,`close`,`clear`,`expand`,`fullscreen`,`popOut`,`sound`,`language`],inline:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`popOut`,`sound`,`language`],standalone:[`theme`,`textSize`,`history`,`clear`,`sound`,`language`],page:[`theme`,`textSize`,`history`,`clear`,`sound`,`language`],modal:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`popOut`,`sound`,`language`],drawer:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`popOut`,`sound`,`language`]},z={enabled:!0,volume:.3,events:void 0},ye={enabled:!0,events:void 0},be=[{label:`tabConversations`,layout:`chat`}];function xe(e){let t=typeof e==`object`&&e?e:{},n=t.presentation??{},r=t.behavior??{},i=t.i18n??{},a=t.feedback??{},o=t.footer??{},s=t.header??{},{themeMode:c,themeOverrides:l}=Se(t.theme),u=n.mode??`floating`,d=Ce(i.defaultLocale),f=i.availableLocales??[i.locale??d],p=we(i.locale??d,f,d),m=(t.baseUrl??b.defaultBaseUrl).replace(/\/$/,``),h=(t.agentApiBaseUrl??`${m}/api/agent`).replace(/\/$/,``),g=(t.dataApiBaseUrl??`${m}/api/data`).replace(/\/$/,``);return{widgetId:t.widgetId??`default`,publicKey:t.publicKey,aiAgentDeploymentId:t.aiAgentDeploymentId,baseUrl:m,agentApiBaseUrl:h,dataApiBaseUrl:g,userContext:le(t.userContext),pageContext:ue(t.pageContext),position:n.position??`bottom-right`,themeMode:c,textSize:`normal`,themeOverrides:l,mode:u,iframe:n.iframe??!1,responseMode:r.responseMode??`streaming`,showReasoning:r.showReasoning??!1,showToolCalls:r.showToolCalls??!1,showSources:r.showSources??!1,enableMessageFeedback:!(r.disableMessageFeedback??!1),autoSendSuggestions:r.autoSendSuggestions??!1,popOutUrl:r.popOutUrl,features:{voice:t.features?.voice??me.voice,fileUpload:!(t.features?.disableFileUpload??!1),humanInLoop:!(t.features?.disableHumanInLoop??!1),operatorRequest:t.features?.enableOperatorRequest===!0},forms:Me(t.forms,p),endpoints:{upload:t.endpoints?.upload??ge.upload,transcribe:t.endpoints?.transcribe??ge.transcribe,submitForm:t.endpoints?.submitForm??ge.submitForm},attachments:{accept:t.composer?.attachments?.accept??pe.accept,maxBytes:t.composer?.attachments?.maxBytes??pe.maxBytes,maxCount:t.composer?.attachments?.maxCount??pe.maxCount},locale:p,defaultLocale:d,availableLocales:f,startMinimized:r.startMinimized??!0,actions:Te(u,s.actions),size:n.size??{},launcher:Pe(t.launcher),sound:Ee(a.sound),haptics:De(a.haptics),strings:C(p,i.strings),stringsOverride:i.strings,composerDisclaimer:o.composerDisclaimer??``,poweredBy:ke(o.poweredBy),composer:Ae(t.composer),modules:je(t.modules),tracking:Oe(t.tracking,g),storage:t.storage??M,onMessage:t.onMessage,onOpen:t.onOpen,onClose:t.onClose,onError:t.onError}}function Se(e){return typeof e==`string`?{themeMode:e,themeOverrides:{}}:e&&typeof e==`object`?{themeMode:`auto`,themeOverrides:e}:{themeMode:`auto`,themeOverrides:{}}}function Ce(e){return e&&e!==`auto`?e:typeof navigator<`u`&&navigator.language?navigator.language:`en`}function we(e,t,n){return t.length<=1||t.includes(e)?e:t.includes(n)?n:t[0]??e}function Te(e,t){return t??ve[e]}function Ee(e){return{enabled:e?.enabled??z.enabled,volume:e?.volume??z.volume,events:e?.events}}function De(e){return{enabled:e?.enabled??ye.enabled,events:e?.events}}function Oe(e,t){let n=e?.sampleRate??he.sampleRate;return{enabled:e?.enabled??he.enabled,endpoint:e?.endpoint??`${t}/pai/elements-px.gif`,sampleRate:Math.min(1,Math.max(0,Number.isFinite(n)?n:1)),token:e?.token}}function ke(e){let t={text:`Powered by ${b.displayName}`,href:b.siteUrl,...e};return t.text||t.logoUrl?t:null}function Ae(e){let t=e?.sendButton;return{sendButton:{shape:t?.shape??`circle`,icon:t?.icon??`arrowUp`,variant:t?.variant??`filled`}}}function je(e){let t=e===void 0?be:e,n=new Set,r=[];for(let e of t.slice(0,4)){if(!e?.label||!e?.layout)continue;let t=e.contentTags?.filter(Boolean),i=e.id??t?.[0]??e.layout;for(;n.has(i);)i=`${i}-${r.length}`;n.add(i);let a={id:i,label:e.label,layout:e.layout};t&&t.length>0&&(a.contentTags=t),e.layout===`home`&&(a.brandName=e.brandName,a.greetingText=e.greetingText,a.showGreeting=!(e.hideGreeting??!1),a.showSearchBar=!(e.hideSearchBar??!1),a.showRecentConversations=!(e.hideRecentConversations??!1),e.userAvatars&&e.userAvatars.length>0&&(a.userAvatars=e.userAvatars),e.status&&(a.status=e.status),a.contentBlockTitle=e.contentBlockTitle),r.push(a)}return{list:r,byId:Object.fromEntries(r.map(e=>[e.id,e]))}}function Me(e,t){if(!e?.length)return R;let n=[],r=new Set;for(let i of e){if(!i?.id||r.has(i.id))continue;let e=j(i,t),a=(e.fields??[]).filter(e=>!!(e&&e.name&&e.label&&e.type)),o=(Array.isArray(e.on)?e.on:[e.on]).map(Ne).filter(e=>e!==null);a.length!==0&&o.length!==0&&(r.add(e.id),n.push({id:e.id,triggers:o,when:e.when,fields:a,title:e.title,description:e.description,submitLabel:e.submitLabel,skippable:e.skippable??!1,frequency:e.frequency??`once`,mirrorToContext:e.mirrorToContext??!0,reopenable:e.reopenable??!0,reviewable:e.reviewable??!0}))}let i={};for(let e of n){var a;for(let t of e.triggers)(i[a=t.kind]??(i[a]=[])).push(e)}return{list:n,byTrigger:i}}function Ne(e){if(typeof e!=`string`)return null;if(e===`pre-chat`||e===`conversation-closed`||e===`panel-close`||e===`manual`)return{kind:e};let[t,n]=e.split(`:`,2);if(t===`after-messages`){let e=Number(n);return Number.isFinite(e)&&e>0?{kind:`after-messages`,param:e}:null}if(t===`idle`){let e=Number(n);return Number.isFinite(e)&&e>0?{kind:`idle`,param:e}:null}return t===`page-area`&&n?{kind:`page-area`,param:n}:null}function Pe(e){let t=e?.callout?.text?{shape:`pill`,position:`auto`,delayMs:1200,autoDismissMs:0,animated:!0,persistent:!0,...e.callout}:null;return{variant:e?.variant??_e.variant,size:e?.size??_e.size,label:e?.label??_e.label,icon:e?.icon??_e.icon,hidden:e?.hidden??_e.hidden,callout:t}}function Fe(e,t,n,r){let i=we(t,e.availableLocales,e.defaultLocale);if(i===e.locale&&n===e.themeMode&&r===e.textSize)return e;let a={...e};return i!==e.locale&&(a.locale=i,a.strings=C(i,e.stringsOverride)),n!==e.themeMode&&(a.themeMode=n),r!==e.textSize&&(a.textSize=r),a}const Ie=[`presentation`,`behavior`,`theme`,`launcher`,`header`,`composer`,`feedback`,`i18n`,`footer`,`features`,`tracking`,`endpoints`];function Le(e,t){if(!t)return e;let n={...e};for(let r of Ie){let i=t[r];if(i===void 0)continue;let a=e[r];if(r===`theme`){a===void 0&&(n[r]=i);continue}r!==`i18n`&&(n[r]=Re(i,a))}t.modules!==void 0&&e.modules===void 0&&(n.modules=t.modules),t.dataApiBaseUrl!==void 0&&e.dataApiBaseUrl===void 0&&(n.dataApiBaseUrl=t.dataApiBaseUrl);let r=e.i18n,i=t.i18n;if(r||i){let e=Re(i??{},r);i?.availableLocales!==void 0&&(e.availableLocales=i.availableLocales),i?.defaultLocale!==void 0&&(e.defaultLocale=i.defaultLocale);let t=r?.strings,a=i?.strings;(t||a)&&(e.strings=ze(a,t)),n.i18n=e}return n}function Re(e,t){if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t))r!==void 0&&(n[e]=r);return n}function ze(e,t){if(!e)return t;if(!t)return e;let n=O(e),r=O(t);if(!n&&!r)return{...e,...t};let i={},a=n?e:{en:e},o=r?t:{en:t};for(let[e,t]of Object.entries(a))i[e]={...t};for(let[e,t]of Object.entries(o))i[e]={...i[e],...t};return i}const Be=[`clear`,`expand`,`fullscreen`,`popOut`,`sound`,`history`,`language`,`theme`,`textSize`,`close`],Ve=e=>e!==`false`,He=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),Ue=[[`public-key`,`publicKey`],[`ai-agent-deployment-id`,`aiAgentDeploymentId`],[`base-url`,`baseUrl`],[`agent-api-base-url`,`agentApiBaseUrl`],[`data-api-base-url`,`dataApiBaseUrl`],[`theme`,`theme`,e=>e]],We=[[`mode`,`mode`,e=>e],[`position`,`position`,e=>e],[`iframe`,`iframe`,Ve]],Ge=[[`width`,`width`],[`height`,`height`]],Ke=[[`response-mode`,`responseMode`,e=>e],[`start-minimized`,`startMinimized`,Ve],[`show-reasoning`,`showReasoning`,Ve],[`show-tool-calls`,`showToolCalls`,Ve],[`show-sources`,`showSources`,Ve],[`disable-message-feedback`,`disableMessageFeedback`,Ve],[`auto-send-suggestions`,`autoSendSuggestions`,Ve],[`pop-out-url`,`popOutUrl`]],qe=[[`locale`,`locale`]],Je=new Set(Be),B=e=>He(e).filter(e=>Je.has(e)),Ye=[[`launcher-variant`,`variant`,e=>e],[`launcher-size`,`size`,e=>e],[`launcher-icon`,`icon`],[`launcher-hidden`,`hidden`,Ve]],Xe=[[`features-disable-file-upload`,`disableFileUpload`,Ve],[`features-voice`,`voice`,e=>e]],Ze=[[`endpoint-upload`,`upload`],[`endpoint-transcribe`,`transcribe`]],Qe=[[`user-id`,`id`],[`user-email`,`email`],[`user-name`,`name`]],$e=[[`page-area`,`area`],[`page-url`,`url`],[`page-path`,`path`],[`page-title`,`title`]],et=[`launcher-label`,`callout-text`,`callout-delay`,`actions`,`user-context`,`page-context`],tt=[Ue,We,Ge,Ke,qe,Ye,Xe,Ze,Qe,$e],nt=new Set([`iframe`,`start-minimized`]),rt=[...tt.flatMap(e=>e.map(([e])=>e).filter(e=>!nt.has(e))),...et];function it(e){let t={},n=t=>{let n=e(t);return n===null||n===``?void 0:n};for(let[e,r,i]of Ue){let a=n(e);a!==void 0&&(t[r]=i?i(a):a)}let r=at(n,We),i=at(n,Ge);(r||i)&&(t.presentation={...r,...i?{size:i}:{}});let a=at(n,Ke);a&&(t.behavior=a);let o=at(n,qe);o&&(t.i18n=o);let s=st(e,n);s&&(t.launcher=s);let c=at(n,Xe);c&&(t.features=c);let l=at(n,Ze);l&&(t.endpoints=l);let u=ot(n,Qe,`user-context`);u&&(t.userContext=u);let d=ot(n,$e,`page-context`);d&&(t.pageContext=d);let f=n(`actions`);return f!==void 0&&(t.header={actions:B(f)}),t}function at(e,t){let n={};for(let[r,i,a]of t){let t=e(r);t!==void 0&&(n[i]=a?a(t):t)}return Object.keys(n).length>0?n:null}function ot(e,t,n){let r={};for(let[n,i]of t){let t=e(n);t!==void 0&&(r[i]=t)}let i={},a=e(n);if(a)try{let e=JSON.parse(a);e&&typeof e==`object`&&!Array.isArray(e)&&(i=e)}catch{}let o={...i,...r};return Object.keys(o).length>0?o:null}function st(e,t){let n=at(t,Ye)??{},r=e(`launcher-label`);r!==null&&(n.label=r);let i=t(`callout-text`);if(i){let e=Number.parseInt(t(`callout-delay`)??``,10);n.callout={text:i,...Number.isFinite(e)?{delayMs:e}:{}}}return Object.keys(n).length>0?n:null}function ct(){let e=Date.now(),t=new Uint8Array(16);t[0]=Math.floor(e/2**40)&255,t[1]=Math.floor(e/2**32)&255,t[2]=e>>>24&255,t[3]=e>>>16&255,t[4]=e>>>8&255,t[5]=e&255,lt(t.subarray(6)),t[6]=t[6]&15|112,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function lt(e){if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){crypto.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const ut=I.scope(`persistence`);function dt(e,t=M,n){let r=n?`${e}.${n}`:e,i=`${b.cssPrefix}.storageVersion`,a=t.get(i)??void 0,o=a?`.v${a}`:``,s=`${b.cssPrefix}.${r}${o}`,c=`${b.cssPrefix}${o}.visitorId`,l=`${s}.conversationId`,u=`${s}.userPrefs`,d=`${s}.panelOpen`,f=`${s}.panelSize`,p=`${s}.calloutDismissed`,m=`${s}.sidebarCollapsed`,h=`${s}.activeModule`,g=`${s}.historyCount`,_=`${s}.formsDone`,v={getVisitorId(){let e=t.get(c);if(e)return e;let n=ct();return t.set(c,n),n},loadConversationId(){return t.get(l)??void 0},saveConversationId(e){ut.trace(`saveConversationId`,{id:e,scope:r}),e?t.set(l,e):t.remove(l)},loadDraft(e){return t.get(`${s}.draft.${e}`)??``},saveDraft(e,n){let r=`${s}.draft.${e}`;n?t.set(r,n):t.remove(r)},loadMessageQueue(e){let n=t.get(`${s}.messageQueue.${e}`);if(!n)return[];try{let e=JSON.parse(n);return!Array.isArray(e)||!e.every(pt)?[]:e}catch(e){return ut.warn(`loadMessageQueue parse failed`,{error:e}),[]}},saveMessageQueue(e,n){let r=`${s}.messageQueue.${e}`;if(n.length===0){t.remove(r);return}try{t.set(r,JSON.stringify(n))}catch(e){ut.warn(`saveMessageQueue serialise failed`,{error:e})}},loadUserPrefs(){let e=t.get(u);if(!e)return{};try{return mt(JSON.parse(e))}catch(e){return ut.warn(`loadUserPrefs parse failed`,{error:e}),{}}},saveUserPrefs(e){try{t.set(u,JSON.stringify(e))}catch(e){ut.warn(`saveUserPrefs serialise failed`,{error:e})}},patchUserPrefs(e){let t=v.loadUserPrefs();v.saveUserPrefs({...t,...e})},loadPanelOpen(){let e=t.get(d);return e===`1`||e!==`0`&&null},savePanelOpen(e){t.set(d,e?`1`:`0`)},loadPanelSize(){let e=t.get(f);return e===`normal`||e===`expanded`||e===`fullscreen`?e:null},savePanelSize(e){t.set(f,e)},loadCalloutDismissed(e){if(!e)return!1;let n=t.get(p);return!!n&&n===e},saveCalloutDismissed(e){e?t.set(p,e):t.remove(p)},loadSidebarCollapsed(){let e=t.get(m);return e===`1`||e!==`0`&&null},saveSidebarCollapsed(e){t.set(m,e?`1`:`0`)},loadActiveModule(){return t.get(h)||null},saveActiveModule(e){t.set(h,e)},loadHistoryCount(){let e=t.get(g);if(!e)return null;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:null},saveHistoryCount(e){t.set(g,String(e))},loadFormsDone(){let e=t.get(_);if(!e)return{};try{let t=JSON.parse(e);return ft(t)?Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`number`)):{}}catch(e){return ut.warn(`loadFormsDone parse failed`,{error:e}),{}}},saveFormDone(e){try{let n=v.loadFormsDone();n[e]=Date.now(),t.set(_,JSON.stringify(n))}catch(e){ut.warn(`saveFormDone serialise failed`,{error:e})}},rememberStorageVersion(e){e&&e!==t.get(i)&&(ut.debug(`rememberStorageVersion (force-reset on next load)`,{version:e}),t.set(i,e))},clearConversation(){t.remove(l)}};return v}function ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pt(e){return ft(e)&&typeof e.id==`string`&&e.id.length>0&&typeof e.text==`string`}function mt(e){if(!ft(e))return{};let t={};return typeof e.locale==`string`&&(t.locale=e.locale),typeof e.soundMuted==`boolean`&&(t.soundMuted=e.soundMuted),(e.themeMode===`auto`||e.themeMode===`light`||e.themeMode===`dark`)&&(t.themeMode=e.themeMode),(e.textSize===`small`||e.textSize===`normal`||e.textSize===`large`)&&(t.textSize=e.textSize),ft(e.widgetSize)&&typeof e.widgetSize.width==`number`&&typeof e.widgetSize.height==`number`&&(t.widgetSize={width:e.widgetSize.width,height:e.widgetSize.height}),t}const ht=[`:host{--__P__-accent-user: __BRAND_ACCENT__;--__P__-accent: var(--__P__-accent-user);--__P__-accent-text-user: __BRAND_ACCENT_TEXT__;--__P__-accent-text: var(--__P__-accent-text-user);--__P__-accent-fg: var(--__P__-accent);--__P__-radius: __BRAND_RADIUS__;--__P__-radius-sm: 8px;--__P__-radius-md: 10px;--__P__-radius-lg: 16px;--__P__-font: __BRAND_FONT__;--__P__-font-display: var(--__P__-font);--__P__-font-mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;--__P__-bg: oklch(1 0 0);--__P__-bg-elevated: oklch(.9789 .0029 278.3);--__P__-surface: var(--__P__-bg-elevated);--__P__-muted: var(--__P__-fg-muted);--__P__-hover: oklch(.1686 .011 278.3 / .06);--__P__-fg: oklch(.1686 .011 278.3);--__P__-fg-muted: oklch(.4932 .0301 278.3);--__P__-border: oklch(.9312 .0084 278.3);--__P__-border-strong: oklch(.8757 .0131 278.3);--__P__-bubble-user: var(--__P__-accent);--__P__-bubble-user-text: var(--__P__-accent-text);--__P__-bubble-assistant: oklch(.9638 .0058 278.3);--__P__-bubble-assistant-text: var(--__P__-fg);--__P__-on-accent: var(--__P__-accent-text);--__P__-success: oklch(.6456 .1654 151.53);--__P__-warning: oklch(.7135 .1494 74.05);--__P__-danger: oklch(.5966 .1818 24.51);--__P__-danger-text: oklch(.5054 .1905 27.52);--__P__-danger-bg: oklch(.5966 .1818 24.51 / .1);--__P__-neutral: oklch(.7137 .0192 278.3);--__P__-pill-l-min: .3;--__P__-pill-l-max: .46;--__P__-focus: var(--__P__-accent);--__P__-shadow-panel: 0 8px 24px -8px rgba(13, 15, 20, .18), 0 24px 64px -24px rgba(13, 15, 20, .24);--__P__-shadow-card: 0 1px 2px rgba(13, 15, 20, .06), 0 4px 12px -6px rgba(13, 15, 20, .12);--__P__-backdrop: oklch(.1686 .011 278.3 / .55);--__P__-shadow-fab: 0 6px 16px -4px color-mix(in oklch, var(--__P__-accent) 45%, transparent), 0 12px 32px -12px rgba(13, 15, 20, .25);--__P__-z-fab: 2147483600;--__P__-z-panel: 2147483601;--__P__-panel-w: 380px;--__P__-panel-h: 600px;--__P__-fab-size: 56px;--__P__-conversation-max: 768px;--__P__-space-1: 4px;--__P__-space-2: 8px;--__P__-space-3: 12px;--__P__-space-4: 16px;--__P__-space-5: 20px;--__P__-space-6: 24px;--__P__-space-8: 32px;--__P__-text-scale: 1;--__P__-text-xs: calc(12px * var(--__P__-text-scale));--__P__-text-sm: calc(13px * var(--__P__-text-scale));--__P__-text-base: calc(15px * var(--__P__-text-scale));--__P__-text-md: calc(16px * var(--__P__-text-scale));--__P__-text-lg: calc(18px * var(--__P__-text-scale));--__P__-text-xl: calc(22px * var(--__P__-text-scale));--__P__-text-2xl: calc(30px * var(--__P__-text-scale))}:host([data-mode="modal"]),:host([data-mode="drawer"]){--__P__-conversation-max: 100%}:host([data-text-size="small"]){--__P__-text-scale: .9}:host([data-text-size="large"]){--__P__-text-scale: 1.15}:host{--__P__-ease: cubic-bezier(.2, .7, .2, 1);--__P__-ease-out: cubic-bezier(.2, .7, .2, 1);--__P__-ease-in: cubic-bezier(.4, 0, 1, 1);--__P__-ease-in-out: cubic-bezier(.65, 0, .35, 1);--__P__-dur-quick: .12s;--__P__-dur-base: .22s;--__P__-dur-slow: .32s;font-family:var(--__P__-font);color:var(--__P__-fg);color-scheme:light;--__P__-color-scheme: light}:host([data-theme="dark"]){--__P__-bg: oklch(.1783 .0128 278.3);--__P__-bg-elevated: oklch(.2232 .0182 278.3);--__P__-fg: oklch(.9368 .01 278.3);--__P__-fg-muted: oklch(.7048 .0296 278.3);--__P__-border: oklch(.2752 .0266 278.3);--__P__-border-strong: oklch(.335 .0291 278.3);--__P__-hover: oklch(.9368 .01 278.3 / .08);--__P__-bubble-assistant: oklch(.2474 .0311 278.3);--__P__-bubble-assistant-text: var(--__P__-fg);--__P__-danger-text: oklch(.8077 .1035 19.57);--__P__-danger-bg: oklch(.5966 .1818 24.51 / .18);--__P__-shadow-panel: 0 8px 24px -8px rgba(0, 0, 0, .6), 0 24px 64px -24px rgba(0, 0, 0, .7);--__P__-shadow-card: 0 1px 2px rgba(0, 0, 0, .4), 0 4px 12px -6px rgba(0, 0, 0, .5);--__P__-backdrop: rgba(0, 0, 0, .65);--__P__-pill-l-min: .75;--__P__-pill-l-max: .92;color-scheme:dark;--__P__-color-scheme: dark}@media(prefers-color-scheme:dark){:host([data-theme="auto"]){--__P__-bg: oklch(.1783 .0128 278.3);--__P__-bg-elevated: oklch(.2232 .0182 278.3);--__P__-fg: oklch(.9368 .01 278.3);--__P__-fg-muted: oklch(.7048 .0296 278.3);--__P__-border: oklch(.2752 .0266 278.3);--__P__-border-strong: oklch(.335 .0291 278.3);--__P__-hover: oklch(.9368 .01 278.3 / .08);--__P__-bubble-assistant: oklch(.2474 .0311 278.3);--__P__-bubble-assistant-text: var(--__P__-fg);--__P__-pill-l-min: .75;--__P__-pill-l-max: .92;--__P__-shadow-panel: 0 8px 24px -8px rgba(0, 0, 0, .6), 0 24px 64px -24px rgba(0, 0, 0, .7);color-scheme:dark;--__P__-color-scheme: dark}}@supports (color: oklch(from red l c h)){:host{--__P__-accent: oklch(from var(--__P__-accent-user) clamp(.3, l, .62) c h);--__P__-accent-text: oklch(from var(--__P__-accent) clamp(0, (l / .623 - 1) * -infinity, 1) 0 h);--__P__-accent-fg: oklch(from var(--__P__-accent-user) clamp(.3, l, .46) c h)}:host([data-theme="dark"]){--__P__-accent: oklch(from var(--__P__-accent-user) clamp(.65, l, .85) c h);--__P__-accent-fg: var(--__P__-accent)}@media(prefers-color-scheme:dark){:host([data-theme="auto"]){--__P__-accent: oklch(from var(--__P__-accent-user) clamp(.65, l, .85) c h);--__P__-accent-fg: var(--__P__-accent)}}}@media(prefers-reduced-motion:reduce){:host{--__P__-dur-quick: 1ms;--__P__-dur-base: 1ms;--__P__-dur-slow: 1ms}}
|
|
1
|
+
import{Component as e,h as t,render as n}from"preact";import{useCallback as r,useEffect as i,useLayoutEffect as a,useMemo as o,useRef as s,useState as c}from"preact/hooks";import{batch as l,computed as u,effect as d,signal as f,useComputed as p,useSignal as m}from"@preact/signals";import{Fragment as h,jsx as g,jsxs as _}from"preact/jsx-runtime";import{memo as v}from"preact/compat";import*as y from"streaming-markdown";const b={id:`help-ai`,name:`@helpai/elements`,global:`HelpAI`,tagName:`web-ai-chat`,cssPrefix:`helpai`,defaultBaseUrl:`https://help.ai`,displayName:`Help AI`,domain:`help.ai`,siteUrl:`https://help.ai`},x={attach:`Attach files`,attachmentMimeRejected:`File type not supported`,attachmentTooLarge:`File is too large`,attachmentTooMany:`Attachment limit reached`,conversationClosed:`This chat is closed`,conversationLoading:`Loading chat…`,loadPreviousMessages:`Load previous messages`,close:`Close`,collapse:`Collapse`,collapseSidebar:`Collapse sidebar`,composerPlaceholder:`Type a message…`,dateLastWeek:`Last 7 days`,dateOlder:`Older`,dateToday:`Today`,dateYesterday:`Yesterday`,dropZone:`Drop files to attach`,errorGeneric:`Something went wrong`,errorRateLimited:`Too many requests — please try again in a moment.`,errorRetry:`Retry`,expand:`Expand`,expandSidebar:`Expand sidebar`,exitFullscreen:`Exit fullscreen`,fullscreen:`Fullscreen`,history:`History`,historyBack:`Back to chat`,historyEmpty:`No previous chats yet`,historyLoading:`Loading your chats…`,historyContinue:`Continue the chat`,historyTitle:`Chat history`,loadMoreConversations:`Load more conversations`,language:`Language`,launcherOpen:`Open chat`,launcherLabel:`Chat with us`,micStart:`Start voice input`,micStop:`Stop voice input`,micUnsupported:`Voice input is not supported in this browser`,moreActions:`More actions`,newConversation:`New chat`,panelTitle:`Chat`,popOut:`Open in new tab`,resizeHandle:`Drag to resize`,scrollToBottom:`Scroll to latest`,send:`Send`,queueMessage:`Queue message`,removeQueuedMessage:`Remove queued message`,compactingContext:`Optimizing conversation context…`,soundOff:`Sound off`,soundOn:`Sound on`,startNewConversation:`Start a new chat`,talkToOperator:`Talk to an operator`,connectingOperator:`Connecting you to an operator…`,noOperatorAvailable:`No one's available right now — leave your details and we'll follow up.`,chattingWithOperator:`You're chatting with {operator}`,cancelOperatorRequest:`Keep chatting with the AI`,stop:`Stop`,theme:`Theme`,themeAuto:`Auto`,themeDark:`Dark`,themeLight:`Light`,textSize:`Text size`,textSizeSmall:`Small`,textSizeNormal:`Normal`,textSizeLarge:`Large`,loading:`Loading…`,thinking:`Thinking…`,thoughts:`Thoughts`,toolResult:`Result`,sources:`Sources`,feedbackUp:`Good response`,feedbackDown:`Bad response`,feedbackThanks:`Thanks for your feedback`,copy:`Copy`,copied:`Copied`,tabHome:`Home`,tabConversations:`Chats`,tabHelp:`Help`,tabNews:`News`,modulesEmpty:`Nothing here yet`,moduleBack:`Back`,contentLoading:`Loading…`,homeGreeting:`How can we help?`,homeGreetingNamed:`Hi {name} 👋`,homeGreetingLead:`How can we help?`,homeSearchPlaceholder:`Search for help`,homeContentTitle:`Popular articles`,homeStatus:`Status`,helpTitle:`Help`,helpSearchPlaceholder:`Search for help`,helpEmpty:`No help articles yet`,helpLoading:`Loading help…`,helpSearchEmpty:`No results found`,newsTitle:`News`,newsEmpty:`No news yet`,newsLoading:`Loading news…`,newsBack:`Back to news`,newsPublishedAt:`Published {date}`,formSubmit:`Submit`,formSkip:`Maybe later`,formSubmitted:`Completed`,formSkipped:`Maybe later`,formFillOut:`Fill out`,formRequired:`This field is required`,formInvalidEmail:`Enter a valid email address`,formInvalidTel:`Enter a valid phone number`,formInvalidUrl:`Enter a valid URL`,formInvalidNumber:`Enter a valid number`,formTooShort:`Too short (min {min} characters)`,formTooLong:`Too long (max {max} characters)`,formNumberTooSmall:`Must be at least {min}`,formNumberTooLarge:`Must be at most {max}`,formPatternMismatch:`Please match the requested format`,formChooseAtLeast:`Choose at least {min}`,formChooseAtMost:`Choose at most {max}`,formOther:`Other`,formOtherPlaceholder:`Type your answer…`,inputRequired:`Questions for you`,inputBadge:`Questions`,inputAnswered:`Answered`,inputSkipped:`Skipped`,showOptions:`Show options`,hideOptions:`Hide options`,qtypeText:`Your answer`,qtypeEmail:`Email address`,qtypePhone:`Phone number`,qtypeNumber:`Number`,qtypeDate:`Date`,qtypeChooseOne:`Pick one`,qtypeChooseAny:`Pick any`,qtypeBoolean:`Yes / No`,inputSubmit:`Submit answers`,inputSubmitHint:`Enter to send · Shift+Enter = new line`,inputSkip:`Skip`,confirmYes:`Yes`,confirmNo:`No`,approve:`Approve`,reject:`Reject`,approvalPrompt:`{tool} requires your approval to execute.`,approvalBody:`Review the tool input above and decide whether to allow this action.`,approvalYourResponse:`Your response: {decision}`,approvalEditHint:`You can edit this response until this step continues.`,approvalSubmitting:`Response submitted. Request in progress…`,edit:`Edit`,toolParameters:`Parameters`,statusAwaiting:`Awaiting Approval`,statusResponded:`Submitted`,statusRunning:`Running`,statusCompleted:`Completed`,statusDenied:`Denied`,statusError:`Error`,statusSuperseded:`Skipped`},S={en:x,fr:{attach:`Joindre des fichiers`,attachmentMimeRejected:`Type de fichier non pris en charge`,attachmentTooLarge:`Le fichier est trop volumineux`,attachmentTooMany:`Limite de pièces jointes atteinte`,conversationClosed:`Ce chat est fermé`,conversationLoading:`Chargement du chat…`,loadPreviousMessages:`Charger les messages précédents`,close:`Fermer`,collapse:`Réduire`,collapseSidebar:`Réduire la barre latérale`,composerPlaceholder:`Écrivez un message…`,dateLastWeek:`7 derniers jours`,dateOlder:`Plus ancien`,dateToday:`Aujourd'hui`,dateYesterday:`Hier`,dropZone:`Déposez les fichiers à joindre`,errorGeneric:`Une erreur s'est produite`,errorRateLimited:`Trop de requêtes — veuillez réessayer dans un instant.`,errorRetry:`Réessayer`,expand:`Agrandir`,expandSidebar:`Développer la barre latérale`,exitFullscreen:`Quitter le plein écran`,fullscreen:`Plein écran`,history:`Historique`,historyBack:`Retour au chat`,historyEmpty:`Aucun chat pour le moment`,historyContinue:`Poursuivre le chat`,historyLoading:`Chargement de vos chats…`,historyTitle:`Historique des chats`,loadMoreConversations:`Charger plus de conversations`,language:`Langue`,launcherOpen:`Ouvrir le chat`,launcherLabel:`Discuter avec nous`,micStart:`Démarrer la saisie vocale`,micStop:`Arrêter la saisie vocale`,micUnsupported:`La saisie vocale n'est pas prise en charge par ce navigateur`,moreActions:`Plus d'actions`,newConversation:`Nouveau chat`,panelTitle:`Chat`,popOut:`Ouvrir dans un nouvel onglet`,resizeHandle:`Glisser pour redimensionner`,scrollToBottom:`Aller au plus récent`,send:`Envoyer`,queueMessage:`Mettre le message en attente`,removeQueuedMessage:`Retirer le message en attente`,compactingContext:`Optimisation du contexte de la conversation…`,soundOff:`Son désactivé`,soundOn:`Son activé`,startNewConversation:`Démarrer un nouveau chat`,talkToOperator:`Parler à un opérateur`,connectingOperator:`Mise en relation avec un opérateur…`,noOperatorAvailable:`Personne n'est disponible pour le moment — laissez vos coordonnées et nous reviendrons vers vous.`,chattingWithOperator:`Vous discutez avec {operator}`,cancelOperatorRequest:`Continuer avec l'IA`,stop:`Arrêter`,theme:`Thème`,themeAuto:`Auto`,themeDark:`Sombre`,themeLight:`Clair`,textSize:`Taille du texte`,textSizeSmall:`Petite`,textSizeNormal:`Normale`,textSizeLarge:`Grande`,loading:`Chargement…`,thinking:`Réflexion…`,thoughts:`Réflexions`,toolResult:`Résultat`,sources:`Sources`,feedbackUp:`Bonne réponse`,feedbackDown:`Mauvaise réponse`,feedbackThanks:`Merci pour votre retour`,copy:`Copier`,copied:`Copié`,tabHome:`Accueil`,tabConversations:`Chats`,tabHelp:`Aide`,tabNews:`Actualités`,modulesEmpty:`Rien pour le moment`,moduleBack:`Retour`,contentLoading:`Chargement…`,homeGreeting:`Comment pouvons-nous vous aider ?`,homeGreetingNamed:`Bonjour {name} 👋`,homeGreetingLead:`Comment pouvons-nous vous aider ?`,homeSearchPlaceholder:`Rechercher de l'aide`,homeContentTitle:`Articles populaires`,homeStatus:`Statut`,helpTitle:`Aide`,helpSearchPlaceholder:`Rechercher de l'aide`,helpEmpty:`Aucun article d'aide pour le moment`,helpLoading:`Chargement de l'aide…`,helpSearchEmpty:`Aucun résultat trouvé`,newsTitle:`Actualités`,newsEmpty:`Aucune actualité pour le moment`,newsLoading:`Chargement des actualités…`,newsBack:`Retour aux actualités`,newsPublishedAt:`Publié le {date}`,formSubmit:`Envoyer`,formSkip:`Plus tard`,formSubmitted:`Terminé`,formSkipped:`Plus tard`,formFillOut:`Remplir`,formRequired:`Ce champ est obligatoire`,formInvalidEmail:`Saisissez une adresse e-mail valide`,formInvalidTel:`Saisissez un numéro de téléphone valide`,formInvalidUrl:`Saisissez une URL valide`,formInvalidNumber:`Saisissez un nombre valide`,formTooShort:`Trop court (min. {min} caractères)`,formTooLong:`Trop long (max. {max} caractères)`,formNumberTooSmall:`Doit être au moins {min}`,formNumberTooLarge:`Doit être au plus {max}`,formPatternMismatch:`Veuillez respecter le format demandé`,formChooseAtLeast:`Choisissez au moins {min}`,formChooseAtMost:`Choisissez au plus {max}`,formOther:`Autre`,formOtherPlaceholder:`Saisissez votre réponse…`,inputRequired:`Questions pour vous`,inputBadge:`Questions`,inputAnswered:`Répondu`,inputSkipped:`Ignoré`,showOptions:`Afficher les options`,hideOptions:`Masquer les options`,qtypeText:`Votre réponse`,qtypeEmail:`Adresse e-mail`,qtypePhone:`Numéro de téléphone`,qtypeNumber:`Nombre`,qtypeDate:`Date`,qtypeChooseOne:`Choisir une`,qtypeChooseAny:`Choisir plusieurs`,qtypeBoolean:`Oui / Non`,inputSubmit:`Envoyer les réponses`,inputSubmitHint:`Entrée pour envoyer · Maj+Entrée = saut de ligne`,inputSkip:`Ignorer`,confirmYes:`Oui`,confirmNo:`Non`,approve:`Approuver`,reject:`Refuser`,approvalPrompt:`{tool} nécessite votre approbation pour s'exécuter.`,approvalBody:`Vérifiez les paramètres ci-dessus et décidez d'autoriser ou non cette action.`,approvalYourResponse:`Votre réponse : {decision}`,approvalEditHint:`Vous pouvez modifier votre réponse jusqu'à la reprise de cette étape.`,approvalSubmitting:`Réponse envoyée. Traitement en cours…`,edit:`Modifier`,toolParameters:`Paramètres`,statusAwaiting:`En attente d'approbation`,statusResponded:`Envoyé`,statusRunning:`En cours`,statusCompleted:`Terminé`,statusDenied:`Refusé`,statusError:`Erreur`,statusSuperseded:`Ignoré`},ar:{attach:`إرفاق ملفات`,attachmentMimeRejected:`نوع الملف غير مدعوم`,attachmentTooLarge:`حجم الملف كبير جدًا`,attachmentTooMany:`تم بلوغ الحد الأقصى للمرفقات`,conversationClosed:`تم إغلاق هذه الدردشة`,conversationLoading:`جارٍ تحميل الدردشة…`,loadPreviousMessages:`تحميل الرسائل السابقة`,close:`إغلاق`,collapse:`طيّ`,collapseSidebar:`طيّ الشريط الجانبي`,composerPlaceholder:`اكتب رسالة…`,dateLastWeek:`آخر ٧ أيام`,dateOlder:`أقدم`,dateToday:`اليوم`,dateYesterday:`أمس`,dropZone:`أفلت الملفات لإرفاقها`,errorGeneric:`حدث خطأ ما`,errorRateLimited:`طلبات كثيرة جدًا — يرجى المحاولة بعد لحظة.`,errorRetry:`إعادة المحاولة`,expand:`توسيع`,expandSidebar:`توسيع الشريط الجانبي`,exitFullscreen:`إنهاء ملء الشاشة`,fullscreen:`ملء الشاشة`,history:`السجل`,historyBack:`العودة إلى الدردشة`,historyEmpty:`لا توجد دردشات سابقة بعد`,historyContinue:`متابعة الدردشة`,historyLoading:`جارٍ تحميل دردشاتك…`,historyTitle:`سجل الدردشات`,loadMoreConversations:`تحميل المزيد من المحادثات`,language:`اللغة`,launcherOpen:`فتح الدردشة`,launcherLabel:`تحدث معنا`,micStart:`بدء الإدخال الصوتي`,micStop:`إيقاف الإدخال الصوتي`,micUnsupported:`الإدخال الصوتي غير مدعوم في هذا المتصفح`,moreActions:`إجراءات إضافية`,newConversation:`دردشة جديدة`,panelTitle:`الدردشة`,popOut:`فتح في علامة تبويب جديدة`,resizeHandle:`اسحب لتغيير الحجم`,scrollToBottom:`الانتقال إلى الأحدث`,send:`إرسال`,queueMessage:`إضافة الرسالة إلى قائمة الانتظار`,removeQueuedMessage:`إزالة الرسالة من قائمة الانتظار`,compactingContext:`جارٍ تحسين سياق المحادثة…`,soundOff:`كتم الصوت`,soundOn:`تشغيل الصوت`,startNewConversation:`بدء دردشة جديدة`,talkToOperator:`التحدث إلى موظف`,connectingOperator:`جاري توصيلك بأحد الموظفين…`,noOperatorAvailable:`لا يوجد موظفون متاحون الآن — اترك بياناتك وسنتواصل معك.`,chattingWithOperator:`أنت تتحدث مع {operator}`,cancelOperatorRequest:`متابعة المحادثة مع الذكاء الاصطناعي`,stop:`إيقاف`,theme:`المظهر`,themeAuto:`تلقائي`,themeDark:`داكن`,themeLight:`فاتح`,textSize:`حجم النص`,textSizeSmall:`صغير`,textSizeNormal:`عادي`,textSizeLarge:`كبير`,loading:`جارٍ التحميل…`,thinking:`يفكّر…`,thoughts:`الأفكار`,toolResult:`النتيجة`,sources:`المصادر`,feedbackUp:`رد جيد`,feedbackDown:`رد سيئ`,feedbackThanks:`شكرًا على ملاحظاتك`,copy:`نسخ`,copied:`تم النسخ`,tabHome:`الرئيسية`,tabConversations:`الدردشات`,tabHelp:`المساعدة`,tabNews:`الأخبار`,modulesEmpty:`لا شيء هنا بعد`,moduleBack:`رجوع`,contentLoading:`جارٍ التحميل…`,homeGreeting:`كيف يمكننا مساعدتك؟`,homeGreetingNamed:`مرحبًا {name} 👋`,homeGreetingLead:`كيف يمكننا مساعدتك؟`,homeSearchPlaceholder:`ابحث عن مساعدة`,homeContentTitle:`مقالات شائعة`,homeStatus:`الحالة`,helpTitle:`المساعدة`,helpSearchPlaceholder:`ابحث عن مساعدة`,helpEmpty:`لا توجد مقالات مساعدة بعد`,helpLoading:`جارٍ تحميل المساعدة…`,helpSearchEmpty:`لا توجد نتائج`,newsTitle:`الأخبار`,newsEmpty:`لا توجد أخبار بعد`,newsLoading:`جارٍ تحميل الأخبار…`,newsBack:`العودة إلى الأخبار`,newsPublishedAt:`نُشر في {date}`,formSubmit:`إرسال`,formSkip:`لاحقًا`,formSubmitted:`تم`,formSkipped:`لاحقًا`,formFillOut:`تعبئة`,formRequired:`هذا الحقل مطلوب`,formInvalidEmail:`أدخل بريدًا إلكترونيًا صحيحًا`,formInvalidTel:`أدخل رقم هاتف صحيحًا`,formInvalidUrl:`أدخل رابطًا صحيحًا`,formInvalidNumber:`أدخل رقمًا صحيحًا`,formTooShort:`قصير جدًا (الحد الأدنى {min} حرفًا)`,formTooLong:`طويل جدًا (الحد الأقصى {max} حرفًا)`,formNumberTooSmall:`يجب ألا يقل عن {min}`,formNumberTooLarge:`يجب ألا يزيد عن {max}`,formPatternMismatch:`يرجى مطابقة الصيغة المطلوبة`,formChooseAtLeast:`اختر {min} على الأقل`,formChooseAtMost:`اختر {max} على الأكثر`,formOther:`أخرى`,formOtherPlaceholder:`اكتب إجابتك…`,inputRequired:`أسئلة لك`,inputBadge:`أسئلة`,inputAnswered:`تمت الإجابة`,inputSkipped:`تم التخطي`,showOptions:`إظهار الخيارات`,hideOptions:`إخفاء الخيارات`,qtypeText:`إجابتك`,qtypeEmail:`عنوان البريد الإلكتروني`,qtypePhone:`رقم الهاتف`,qtypeNumber:`رقم`,qtypeDate:`تاريخ`,qtypeChooseOne:`اختر واحدًا`,qtypeChooseAny:`اختر أيًا`,qtypeBoolean:`نعم / لا`,inputSubmit:`إرسال الإجابات`,inputSubmitHint:`Enter للإرسال · Shift+Enter = سطر جديد`,inputSkip:`تخطٍّ`,confirmYes:`نعم`,confirmNo:`لا`,approve:`موافقة`,reject:`رفض`,approvalPrompt:`تتطلب {tool} موافقتك للتنفيذ.`,approvalBody:`راجع مُعطيات الأداة أعلاه وقرّر السماح بهذا الإجراء أو رفضه.`,approvalYourResponse:`ردّك: {decision}`,approvalEditHint:`يمكنك تعديل ردّك حتى تستأنف هذه الخطوة.`,approvalSubmitting:`تم إرسال الرد. جارٍ التنفيذ…`,edit:`تعديل`,toolParameters:`المعطيات`,statusAwaiting:`بانتظار الموافقة`,statusResponded:`تم الإرسال`,statusRunning:`قيد التنفيذ`,statusCompleted:`مكتمل`,statusDenied:`مرفوض`,statusError:`خطأ`,statusSuperseded:`تم التخطي`},es:{attach:`Adjuntar archivos`,attachmentMimeRejected:`Tipo de archivo no admitido`,attachmentTooLarge:`El archivo es demasiado grande`,attachmentTooMany:`Se alcanzó el límite de adjuntos`,conversationClosed:`Este chat está cerrado`,conversationLoading:`Cargando chat…`,loadPreviousMessages:`Cargar mensajes anteriores`,close:`Cerrar`,collapse:`Contraer`,collapseSidebar:`Contraer la barra lateral`,composerPlaceholder:`Escribe un mensaje…`,dateLastWeek:`Últimos 7 días`,dateOlder:`Anteriores`,dateToday:`Hoy`,dateYesterday:`Ayer`,dropZone:`Suelta los archivos para adjuntarlos`,errorGeneric:`Algo salió mal`,errorRateLimited:`Demasiadas solicitudes: inténtalo de nuevo en un momento.`,errorRetry:`Reintentar`,expand:`Ampliar`,expandSidebar:`Expandir la barra lateral`,exitFullscreen:`Salir de pantalla completa`,fullscreen:`Pantalla completa`,history:`Historial`,historyBack:`Volver al chat`,historyEmpty:`Aún no tienes chats`,historyContinue:`Continuar el chat`,historyLoading:`Cargando tus chats…`,historyTitle:`Historial de chats`,loadMoreConversations:`Cargar más conversaciones`,language:`Idioma`,launcherOpen:`Abrir el chat`,launcherLabel:`Chatea con nosotros`,micStart:`Iniciar entrada de voz`,micStop:`Detener entrada de voz`,micUnsupported:`Este navegador no admite la entrada de voz`,moreActions:`Más acciones`,newConversation:`Nuevo chat`,panelTitle:`Chat`,popOut:`Abrir en una pestaña nueva`,resizeHandle:`Arrastra para cambiar el tamaño`,scrollToBottom:`Ir a lo más reciente`,send:`Enviar`,queueMessage:`Poner mensaje en cola`,removeQueuedMessage:`Quitar mensaje de la cola`,compactingContext:`Optimizando el contexto de la conversación…`,soundOff:`Sonido desactivado`,soundOn:`Sonido activado`,startNewConversation:`Iniciar un chat nuevo`,talkToOperator:`Hablar con un operador`,connectingOperator:`Conectándote con un operador…`,noOperatorAvailable:`Nadie está disponible ahora — deja tus datos y te contactaremos.`,chattingWithOperator:`Estás chateando con {operator}`,cancelOperatorRequest:`Seguir con la IA`,stop:`Detener`,theme:`Tema`,themeAuto:`Automático`,themeDark:`Oscuro`,themeLight:`Claro`,textSize:`Tamaño del texto`,textSizeSmall:`Pequeño`,textSizeNormal:`Normal`,textSizeLarge:`Grande`,loading:`Cargando…`,thinking:`Pensando…`,thoughts:`Razonamiento`,toolResult:`Resultado`,sources:`Fuentes`,feedbackUp:`Buena respuesta`,feedbackDown:`Mala respuesta`,feedbackThanks:`Gracias por tu opinión`,copy:`Copiar`,copied:`Copiado`,tabHome:`Inicio`,tabConversations:`Chats`,tabHelp:`Ayuda`,tabNews:`Novedades`,modulesEmpty:`Aún no hay nada aquí`,moduleBack:`Atrás`,contentLoading:`Cargando…`,homeGreeting:`¿Cómo podemos ayudarte?`,homeGreetingNamed:`Hola, {name} 👋`,homeGreetingLead:`¿Cómo podemos ayudarte?`,homeSearchPlaceholder:`Buscar ayuda`,homeContentTitle:`Artículos populares`,homeStatus:`Estado`,helpTitle:`Ayuda`,helpSearchPlaceholder:`Buscar ayuda`,helpEmpty:`Aún no hay artículos de ayuda`,helpLoading:`Cargando la ayuda…`,helpSearchEmpty:`No se encontraron resultados`,newsTitle:`Novedades`,newsEmpty:`Aún no hay novedades`,newsLoading:`Cargando novedades…`,newsBack:`Volver a novedades`,newsPublishedAt:`Publicado el {date}`,formSubmit:`Enviar`,formSkip:`Quizá más tarde`,formSubmitted:`Completado`,formSkipped:`Quizá más tarde`,formFillOut:`Completar`,formRequired:`Este campo es obligatorio`,formInvalidEmail:`Introduce un correo electrónico válido`,formInvalidTel:`Introduce un número de teléfono válido`,formInvalidUrl:`Introduce una URL válida`,formInvalidNumber:`Introduce un número válido`,formTooShort:`Demasiado corto (mín. {min} caracteres)`,formTooLong:`Demasiado largo (máx. {max} caracteres)`,formNumberTooSmall:`Debe ser al menos {min}`,formNumberTooLarge:`Debe ser como máximo {max}`,formPatternMismatch:`Respeta el formato solicitado`,formChooseAtLeast:`Elige al menos {min}`,formChooseAtMost:`Elige como máximo {max}`,formOther:`Otro`,formOtherPlaceholder:`Escribe tu respuesta…`,inputRequired:`Preguntas para ti`,inputBadge:`Preguntas`,inputAnswered:`Respondido`,inputSkipped:`Omitido`,showOptions:`Mostrar opciones`,hideOptions:`Ocultar opciones`,qtypeText:`Tu respuesta`,qtypeEmail:`Correo electrónico`,qtypePhone:`Número de teléfono`,qtypeNumber:`Número`,qtypeDate:`Fecha`,qtypeChooseOne:`Elige una`,qtypeChooseAny:`Elige varias`,qtypeBoolean:`Sí / No`,inputSubmit:`Enviar respuestas`,inputSubmitHint:`Enter para enviar · Mayús+Enter = nueva línea`,inputSkip:`Omitir`,confirmYes:`Sí`,confirmNo:`No`,approve:`Aprobar`,reject:`Rechazar`,approvalPrompt:`{tool} requiere tu aprobación para ejecutarse.`,approvalBody:`Revisa los parámetros de arriba y decide si permites esta acción.`,approvalYourResponse:`Tu respuesta: {decision}`,approvalEditHint:`Puedes cambiar tu respuesta hasta que este paso continúe.`,approvalSubmitting:`Respuesta enviada. Procesando…`,edit:`Editar`,toolParameters:`Parámetros`,statusAwaiting:`Esperando aprobación`,statusResponded:`Enviado`,statusRunning:`En curso`,statusCompleted:`Completado`,statusDenied:`Denegado`,statusError:`Error`,statusSuperseded:`Omitido`},he:{attach:`צירוף קבצים`,attachmentMimeRejected:`סוג הקובץ אינו נתמך`,attachmentTooLarge:`הקובץ גדול מדי`,attachmentTooMany:`הגעת למספר המרבי של קבצים מצורפים`,conversationClosed:`הצ׳אט הזה נסגר`,conversationLoading:`טוען צ׳אט…`,loadPreviousMessages:`טעינת הודעות קודמות`,close:`סגירה`,collapse:`כיווץ`,collapseSidebar:`כיווץ סרגל הצד`,composerPlaceholder:`כתוב הודעה…`,dateLastWeek:`7 הימים האחרונים`,dateOlder:`ישן יותר`,dateToday:`היום`,dateYesterday:`אתמול`,dropZone:`שחרר קבצים כדי לצרף`,errorGeneric:`משהו השתבש`,errorRateLimited:`יותר מדי בקשות — נסה שוב בעוד רגע.`,errorRetry:`נסה שוב`,expand:`הרחבה`,expandSidebar:`הרחבת סרגל הצד`,exitFullscreen:`יציאה ממסך מלא`,fullscreen:`מסך מלא`,history:`היסטוריה`,historyBack:`חזרה לצ׳אט`,historyEmpty:`אין עדיין צ׳אטים קודמים`,historyContinue:`המשך צ׳אט`,historyLoading:`טוען את הצ׳אטים שלך…`,historyTitle:`היסטוריית צ׳אטים`,loadMoreConversations:`טעינת שיחות נוספות`,language:`שפה`,launcherOpen:`פתיחת צ׳אט`,launcherLabel:`דברו איתנו`,micStart:`התחלת קלט קולי`,micStop:`עצירת קלט קולי`,micUnsupported:`קלט קולי אינו נתמך בדפדפן זה`,moreActions:`פעולות נוספות`,newConversation:`צ׳אט חדש`,panelTitle:`צ׳אט`,popOut:`פתיחה בכרטיסייה חדשה`,resizeHandle:`גרור לשינוי הגודל`,scrollToBottom:`מעבר לחדש ביותר`,send:`שליחה`,queueMessage:`הוספת ההודעה לתור`,removeQueuedMessage:`הסרת ההודעה מהתור`,compactingContext:`מבצע אופטימיזציה להקשר השיחה…`,soundOff:`השתקת הצליל`,soundOn:`הפעלת הצליל`,startNewConversation:`התחלת צ׳אט חדש`,talkToOperator:`דבר עם נציג`,connectingOperator:`מחבר אותך לנציג…`,noOperatorAvailable:`אין נציגים זמינים כעת — השאר את הפרטים שלך ונחזור אליך.`,chattingWithOperator:`אתה מצ׳וטט עם {operator}`,cancelOperatorRequest:`המשך לשוחח עם ה-AI`,stop:`עצירה`,theme:`ערכת נושא`,themeAuto:`אוטומטי`,themeDark:`כהה`,themeLight:`בהיר`,textSize:`גודל טקסט`,textSizeSmall:`קטן`,textSizeNormal:`רגיל`,textSizeLarge:`גדול`,loading:`טוען…`,thinking:`חושב…`,thoughts:`מחשבות`,toolResult:`תוצאה`,sources:`מקורות`,feedbackUp:`תשובה טובה`,feedbackDown:`תשובה גרועה`,feedbackThanks:`תודה על המשוב`,copy:`העתק`,copied:`הועתק`,tabHome:`בית`,tabConversations:`צ׳אטים`,tabHelp:`עזרה`,tabNews:`חדשות`,modulesEmpty:`אין כאן עדיין כלום`,moduleBack:`חזרה`,contentLoading:`טוען…`,homeGreeting:`כיצד נוכל לעזור?`,homeGreetingNamed:`שלום {name} 👋`,homeGreetingLead:`כיצד נוכל לעזור?`,homeSearchPlaceholder:`חיפוש עזרה`,homeContentTitle:`מאמרים פופולריים`,homeStatus:`סטטוס`,helpTitle:`עזרה`,helpSearchPlaceholder:`חיפוש עזרה`,helpEmpty:`אין עדיין מאמרי עזרה`,helpLoading:`טוען עזרה…`,helpSearchEmpty:`לא נמצאו תוצאות`,newsTitle:`חדשות`,newsEmpty:`אין עדיין חדשות`,newsLoading:`טוען חדשות…`,newsBack:`חזרה לחדשות`,newsPublishedAt:`פורסם ב-{date}`,formSubmit:`שליחה`,formSkip:`אחר כך`,formSubmitted:`נשלח`,formSkipped:`דולג`,formFillOut:`מילוי`,formRequired:`שדה חובה`,formInvalidEmail:`הזן כתובת אימייל תקינה`,formInvalidTel:`הזן מספר טלפון תקין`,formInvalidUrl:`הזן כתובת URL תקינה`,formInvalidNumber:`הזן מספר תקין`,formTooShort:`קצר מדי (לפחות {min} תווים)`,formTooLong:`ארוך מדי (לכל היותר {max} תווים)`,formNumberTooSmall:`חייב להיות לפחות {min}`,formNumberTooLarge:`חייב להיות לכל היותר {max}`,formPatternMismatch:`התאם לתבנית הנדרשת`,formChooseAtLeast:`בחר לפחות {min}`,formChooseAtMost:`בחר לכל היותר {max}`,formOther:`אחר`,formOtherPlaceholder:`כתוב את תשובתך…`,inputRequired:`שאלות עבורך`,inputBadge:`שאלות`,inputAnswered:`נענה`,inputSkipped:`דולג`,showOptions:`הצג אפשרויות`,hideOptions:`הסתר אפשרויות`,qtypeText:`התשובה שלך`,qtypeEmail:`כתובת אימייל`,qtypePhone:`מספר טלפון`,qtypeNumber:`מספר`,qtypeDate:`תאריך`,qtypeChooseOne:`בחר אחת`,qtypeChooseAny:`בחר כמה`,qtypeBoolean:`כן / לא`,inputSubmit:`שליחת תשובות`,inputSubmitHint:`Enter לשליחה · Shift+Enter = שורה חדשה`,inputSkip:`דילוג`,confirmYes:`כן`,confirmNo:`לא`,approve:`אישור`,reject:`דחייה`,approvalPrompt:`הכלי {tool} דורש את אישורך כדי לפעול.`,approvalBody:`בדוק את פרמטרי הכלי שלמעלה והחלט אם לאשר פעולה זו.`,approvalYourResponse:`התגובה שלך: {decision}`,approvalEditHint:`ניתן לערוך את תגובתך עד שהשלב הזה יתחדש.`,approvalSubmitting:`התגובה נשלחה. מבצע…`,edit:`עריכה`,toolParameters:`פרמטרים`,statusAwaiting:`ממתין לאישור`,statusResponded:`נשלח`,statusRunning:`פועל`,statusCompleted:`הושלם`,statusDenied:`נדחה`,statusError:`שגיאה`,statusSuperseded:`דולג`}};function C(e,t){let n=w(e),r=O(t),i=n===`en`?{}:S[n]??{},a=r?t[n]??{}:t??{},o=r?t.en??{}:{};return{...x,...i,...o,...a}}function w(e){return(e.split(`-`)[0]??`en`).toLowerCase()}const T=new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`,`ks`,`nqo`,`prs`,`syr`]);function E(e){return T.has(w(e))}function D(e,t){return e[t]??t}function O(e){if(!e)return!1;for(let t of Object.values(e))if(t&&typeof t==`object`)return!0;return!1}function k(e,t){if(!(!e?.length||!t))return e.find(e=>e.locale===t)}function A(e,t){let{translations:n,defaultLocale:r,...i}=e,a=k(n,t);return a?{...i,title:a.title??i.title,description:a.description??i.description,content:a.content??i.content}:i}function j(e,t){let{translations:n,defaultLocale:r,...i}=e,a=k(n,t);if(!a)return i;let o=new Map((a.fields??[]).map(e=>[e.name,e])),s=i.fields.map(e=>{let t=o.get(e.name);if(!t)return e;let n=new Map((t.options??[]).map(e=>[e.value,e]));return{...e,label:t.label??e.label,placeholder:t.placeholder??e.placeholder,validationHint:t.validationHint??e.validationHint,options:e.options?.map(e=>{let t=n.get(e.value);return t?{...e,label:t.label??e.label,description:t.description??e.description}:e})}});return{...i,title:a.title??i.title,description:a.description??i.description,submitLabel:a.submitLabel??i.submitLabel,fields:s}}const M=new class{get(e){try{return localStorage.getItem(e)}catch{return null}}set(e,t){try{localStorage.setItem(e,t)}catch{}}remove(e){try{localStorage.removeItem(e)}catch{}}},ee=[`off`,`error`,`warn`,`info`,`debug`,`trace`],te=b.cssPrefix,N=`${te}.debug`,ne=`__${b.global}_DEBUG__`,re=`${te}-debug`;let P=2;function F(){if(typeof window>`u`)return 2;try{let e=new URLSearchParams(window.location.search).get(re);if(e!==null){let t=ie(e);if(t>=0)return t}}catch{}try{let e=window.localStorage?.getItem(N);if(e){let t=ie(e);if(t>=0)return t}}catch{}return Reflect.get(window,ne)?4:2}function ie(e){if(e===!0||e===`1`||e===`true`)return 4;if(e===!1||e===`0`||e===`false`||e===`off`)return 0;if(typeof e==`number`)return Math.max(0,Math.min(5,Math.floor(e)));if(typeof e==`string`){let t=ee.findIndex(t=>t===e);if(t>=0)return t}return-1}P=F();function ae(e){let t=`[${te}:${e}]`,n=(e,n,r)=>(r,i)=>{P<e||(i===void 0?console[n](t,r):console[n](t,r,i))};return{error:n(1,`error`,`error`),warn:n(2,`warn`,`warn`),info:n(3,`info`,`info`),debug:n(4,`debug`,`debug`),trace:n(5,`debug`,`trace`),scope:t=>ae(`${e}:${t}`)}}const I=ae(`core`),L=I.scope(`context`),oe=new Set([`visitorId`,`conversationId`,`jwt`,`token`,`authorization`,`password`]),se=1024,ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function le(e){return de(e,`userContext`,!0)}function ue(e){return de(e,`pageContext`,!1)}function de(e,t,n){if(e==null)return;if(typeof e!=`object`||Array.isArray(e)){L.warn(`ignored ${t} — expected an object`,{type:Array.isArray(e)?`array`:typeof e});return}let r={},i=0;for(let[n,a]of Object.entries(e)){if(oe.has(n)){L.warn(`dropped reserved ${t} key "${n}" — managed by the widget, not host-settable`);continue}if(a==null)continue;if(i>=50){L.warn(`${t} truncated at 50 keys — dropped "${n}"`);continue}let e=fe(t,n,a);e!==void 0&&(r[n]=e,i++)}return n&&typeof r.email==`string`&&!ce.test(r.email)&&(L.warn(`dropped malformed context field`,{field:`${t}.email`,reason:`invalid format`}),delete r.email),Object.keys(r).length>0?r:void 0}function fe(e,t,n){if(typeof n==`boolean`)return n;if(typeof n==`number`){if(!Number.isFinite(n)){L.warn(`dropped non-finite ${e}.${t}`);return}return n}if(typeof n==`string`){let r=n.trim();return r===``?void 0:r.length>se?(L.warn(`truncated ${e}.${t} to ${se} chars`),r.slice(0,se)):r}L.warn(`dropped ${e}.${t} — only string/number/boolean values are allowed`,{type:typeof n})}const pe={maxBytes:10*1024*1024,maxCount:10,accept:`*/*`},me={voice:`local`},R={list:[],byTrigger:{}},he={enabled:!0,sampleRate:1},ge={upload:`/pai/upload-file`,transcribe:`/pai/transcribe-audio`,submitForm:`/pai/submit-form`},_e={variant:`circle`,size:`md`,label:void 0,icon:`chat`,hidden:!1},ve={floating:[`theme`,`textSize`,`history`,`close`,`clear`,`expand`,`fullscreen`,`popOut`,`sound`,`language`],inline:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`popOut`,`sound`,`language`],standalone:[`theme`,`textSize`,`history`,`clear`,`sound`,`language`],page:[`theme`,`textSize`,`history`,`clear`,`sound`,`language`],modal:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`popOut`,`sound`,`language`],drawer:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`popOut`,`sound`,`language`]},z={enabled:!0,volume:.3,events:void 0},ye={enabled:!0,events:void 0},be=[{label:`tabConversations`,layout:`chat`}];function xe(e){let t=typeof e==`object`&&e?e:{},n=t.presentation??{},r=t.behavior??{},i=t.i18n??{},a=t.feedback??{},o=t.footer??{},s=t.header??{},{themeMode:c,themeOverrides:l}=Se(t.theme),u=n.mode??`floating`,d=Ce(i.defaultLocale),f=i.availableLocales??[i.locale??d],p=we(i.locale??d,f,d),m=(t.baseUrl??b.defaultBaseUrl).replace(/\/$/,``),h=(t.agentApiBaseUrl??`${m}/api/agent`).replace(/\/$/,``),g=(t.dataApiBaseUrl??`${m}/api/data`).replace(/\/$/,``);return{widgetId:t.widgetId??`default`,publicKey:t.publicKey,aiAgentDeploymentId:t.aiAgentDeploymentId,baseUrl:m,agentApiBaseUrl:h,dataApiBaseUrl:g,userContext:le(t.userContext),pageContext:ue(t.pageContext),position:n.position??`bottom-right`,themeMode:c,textSize:`normal`,themeOverrides:l,mode:u,iframe:n.iframe??!1,responseMode:r.responseMode??`streaming`,showReasoning:r.showReasoning??!1,showToolCalls:r.showToolCalls??!1,showSources:r.showSources??!1,enableMessageFeedback:!(r.disableMessageFeedback??!1),autoSendSuggestions:r.autoSendSuggestions??!1,popOutUrl:r.popOutUrl,features:{voice:t.features?.voice??me.voice,fileUpload:!(t.features?.disableFileUpload??!1),humanInLoop:!(t.features?.disableHumanInLoop??!1),operatorRequest:t.features?.enableOperatorRequest===!0},forms:Me(t.forms,p),endpoints:{upload:t.endpoints?.upload??ge.upload,transcribe:t.endpoints?.transcribe??ge.transcribe,submitForm:t.endpoints?.submitForm??ge.submitForm},attachments:{accept:t.composer?.attachments?.accept??pe.accept,maxBytes:t.composer?.attachments?.maxBytes??pe.maxBytes,maxCount:t.composer?.attachments?.maxCount??pe.maxCount},locale:p,defaultLocale:d,availableLocales:f,startMinimized:r.startMinimized??!0,actions:Te(u,s.actions),size:n.size??{},launcher:Pe(t.launcher),sound:Ee(a.sound),haptics:De(a.haptics),strings:C(p,i.strings),stringsOverride:i.strings,composerDisclaimer:o.composerDisclaimer??``,poweredBy:ke(o.poweredBy),composer:Ae(t.composer),modules:je(t.modules),tracking:Oe(t.tracking,g),storage:t.storage??M,onMessage:t.onMessage,onOpen:t.onOpen,onClose:t.onClose,onError:t.onError}}function Se(e){return typeof e==`string`?{themeMode:e,themeOverrides:{}}:e&&typeof e==`object`?{themeMode:`auto`,themeOverrides:e}:{themeMode:`auto`,themeOverrides:{}}}function Ce(e){return e&&e!==`auto`?e:globalThis.navigator?.language||`en`}function we(e,t,n){return t.length<=1||t.includes(e)?e:t.includes(n)?n:t[0]??e}function Te(e,t){return t??ve[e]}function Ee(e){return{enabled:e?.enabled??z.enabled,volume:e?.volume??z.volume,events:e?.events}}function De(e){return{enabled:e?.enabled??ye.enabled,events:e?.events}}function Oe(e,t){let n=e?.sampleRate??he.sampleRate;return{enabled:e?.enabled??he.enabled,endpoint:e?.endpoint??`${t}/pai/elements-px.gif`,sampleRate:Math.min(1,Math.max(0,Number.isFinite(n)?n:1)),token:e?.token}}function ke(e){let t={text:`Powered by ${b.displayName}`,href:b.siteUrl,...e};return t.text||t.logoUrl?t:null}function Ae(e){let t=e?.sendButton;return{sendButton:{shape:t?.shape??`circle`,icon:t?.icon??`arrowUp`,variant:t?.variant??`filled`}}}function je(e){let t=e??be,n=new Set,r=[];for(let e of t.slice(0,4)){if(!e?.label||!e?.layout)continue;let t=e.contentTags?.filter(Boolean),i=e.id??t?.[0]??e.layout;for(;n.has(i);)i=`${i}-${r.length}`;n.add(i);let a={id:i,label:e.label,layout:e.layout};t?.length&&(a.contentTags=t),e.layout===`home`&&(a.brandName=e.brandName,a.greetingText=e.greetingText,a.showGreeting=!(e.hideGreeting??!1),a.showSearchBar=!(e.hideSearchBar??!1),a.showRecentConversations=!(e.hideRecentConversations??!1),e.userAvatars?.length&&(a.userAvatars=e.userAvatars),e.status&&(a.status=e.status),a.contentBlockTitle=e.contentBlockTitle),r.push(a)}return{list:r,byId:Object.fromEntries(r.map(e=>[e.id,e]))}}function Me(e,t){if(!e?.length)return R;let n=[],r=new Set;for(let i of e){if(!i?.id||r.has(i.id))continue;let e=j(i,t),a=(e.fields??[]).filter(e=>!!(e?.name&&e.label&&e.type)),o=(Array.isArray(e.on)?e.on:[e.on]).map(Ne).filter(e=>e!==null);a.length!==0&&o.length!==0&&(r.add(e.id),n.push({id:e.id,triggers:o,when:e.when,fields:a,title:e.title,description:e.description,submitLabel:e.submitLabel,skippable:e.skippable??!1,frequency:e.frequency??`once`,mirrorToContext:e.mirrorToContext??!0,reopenable:e.reopenable??!0,reviewable:e.reviewable??!0}))}let i={};for(let e of n){var a;for(let t of e.triggers)(i[a=t.kind]??(i[a]=[])).push(e)}return{list:n,byTrigger:i}}function Ne(e){if(typeof e!=`string`)return null;if(e===`pre-chat`||e===`conversation-closed`||e===`panel-close`||e===`manual`)return{kind:e};let[t,n]=e.split(`:`,2);if(t===`after-messages`){let e=Number(n);return Number.isFinite(e)&&e>0?{kind:`after-messages`,param:e}:null}if(t===`idle`){let e=Number(n);return Number.isFinite(e)&&e>0?{kind:`idle`,param:e}:null}return t===`page-area`&&n?{kind:`page-area`,param:n}:null}function Pe(e){let t=e?.callout?.text?{shape:`pill`,position:`auto`,delayMs:1200,autoDismissMs:0,animated:!0,persistent:!0,...e.callout}:null;return{variant:e?.variant??_e.variant,size:e?.size??_e.size,label:e?.label??_e.label,icon:e?.icon??_e.icon,hidden:e?.hidden??_e.hidden,callout:t}}function Fe(e,t,n,r){let i=we(t,e.availableLocales,e.defaultLocale);if(i===e.locale&&n===e.themeMode&&r===e.textSize)return e;let a={...e};return i!==e.locale&&(a.locale=i,a.strings=C(i,e.stringsOverride)),n!==e.themeMode&&(a.themeMode=n),r!==e.textSize&&(a.textSize=r),a}const Ie=[`presentation`,`behavior`,`theme`,`launcher`,`header`,`composer`,`feedback`,`i18n`,`footer`,`features`,`tracking`,`endpoints`];function Le(e,t){if(!t)return e;let n={...e};for(let r of Ie){let i=t[r];if(i===void 0)continue;let a=e[r];if(r===`theme`){a===void 0&&(n[r]=i);continue}r!==`i18n`&&(n[r]=Re(i,a))}t.modules!==void 0&&e.modules===void 0&&(n.modules=t.modules),t.dataApiBaseUrl!==void 0&&e.dataApiBaseUrl===void 0&&(n.dataApiBaseUrl=t.dataApiBaseUrl);let r=e.i18n,i=t.i18n;if(r||i){let e=Re(i??{},r);i?.availableLocales!==void 0&&(e.availableLocales=i.availableLocales),i?.defaultLocale!==void 0&&(e.defaultLocale=i.defaultLocale);let t=r?.strings,a=i?.strings;(t||a)&&(e.strings=ze(a,t)),n.i18n=e}return n}function Re(e,t){if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t))r!==void 0&&(n[e]=r);return n}function ze(e,t){if(!e)return t;if(!t)return e;let n=O(e),r=O(t);if(!n&&!r)return{...e,...t};let i={},a=n?e:{en:e},o=r?t:{en:t};for(let[e,t]of Object.entries(a))i[e]={...t};for(let[e,t]of Object.entries(o))i[e]={...i[e],...t};return i}const Be=[`clear`,`expand`,`fullscreen`,`popOut`,`sound`,`history`,`language`,`theme`,`textSize`,`close`],Ve=e=>e!==`false`,He=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),Ue=[[`public-key`,`publicKey`],[`ai-agent-deployment-id`,`aiAgentDeploymentId`],[`base-url`,`baseUrl`],[`agent-api-base-url`,`agentApiBaseUrl`],[`data-api-base-url`,`dataApiBaseUrl`],[`theme`,`theme`,e=>e]],We=[[`mode`,`mode`,e=>e],[`position`,`position`,e=>e],[`iframe`,`iframe`,Ve]],Ge=[[`width`,`width`],[`height`,`height`]],Ke=[[`response-mode`,`responseMode`,e=>e],[`start-minimized`,`startMinimized`,Ve],[`show-reasoning`,`showReasoning`,Ve],[`show-tool-calls`,`showToolCalls`,Ve],[`show-sources`,`showSources`,Ve],[`disable-message-feedback`,`disableMessageFeedback`,Ve],[`auto-send-suggestions`,`autoSendSuggestions`,Ve],[`pop-out-url`,`popOutUrl`]],qe=[[`locale`,`locale`]],Je=new Set(Be),B=e=>He(e).filter(e=>Je.has(e)),Ye=[[`launcher-variant`,`variant`,e=>e],[`launcher-size`,`size`,e=>e],[`launcher-icon`,`icon`],[`launcher-hidden`,`hidden`,Ve]],Xe=[[`features-disable-file-upload`,`disableFileUpload`,Ve],[`features-voice`,`voice`,e=>e]],Ze=[[`endpoint-upload`,`upload`],[`endpoint-transcribe`,`transcribe`]],Qe=[[`user-id`,`id`],[`user-email`,`email`],[`user-name`,`name`]],$e=[[`page-area`,`area`],[`page-url`,`url`],[`page-path`,`path`],[`page-title`,`title`]],et=[`launcher-label`,`callout-text`,`callout-delay`,`actions`,`user-context`,`page-context`],tt=[Ue,We,Ge,Ke,qe,Ye,Xe,Ze,Qe,$e],nt=new Set([`iframe`,`start-minimized`]),rt=[...tt.flatMap(e=>e.map(([e])=>e).filter(e=>!nt.has(e))),...et];function it(e){let t={},n=t=>{let n=e(t);return n===null||n===``?void 0:n};for(let[e,r,i]of Ue){let a=n(e);a!==void 0&&(t[r]=i?i(a):a)}let r=at(n,We),i=at(n,Ge);(r||i)&&(t.presentation={...r,...i?{size:i}:{}});let a=at(n,Ke);a&&(t.behavior=a);let o=at(n,qe);o&&(t.i18n=o);let s=st(e,n);s&&(t.launcher=s);let c=at(n,Xe);c&&(t.features=c);let l=at(n,Ze);l&&(t.endpoints=l);let u=ot(n,Qe,`user-context`);u&&(t.userContext=u);let d=ot(n,$e,`page-context`);d&&(t.pageContext=d);let f=n(`actions`);return f!==void 0&&(t.header={actions:B(f)}),t}function at(e,t){let n={};for(let[r,i,a]of t){let t=e(r);t!==void 0&&(n[i]=a?a(t):t)}return Object.keys(n).length>0?n:null}function ot(e,t,n){let r={};for(let[n,i]of t){let t=e(n);t!==void 0&&(r[i]=t)}let i={},a=e(n);if(a)try{let e=JSON.parse(a);e&&typeof e==`object`&&!Array.isArray(e)&&(i=e)}catch{}let o={...i,...r};return Object.keys(o).length>0?o:null}function st(e,t){let n=at(t,Ye)??{},r=e(`launcher-label`);r!==null&&(n.label=r);let i=t(`callout-text`);if(i){let e=Number.parseInt(t(`callout-delay`)??``,10);n.callout={text:i,...Number.isFinite(e)?{delayMs:e}:{}}}return Object.keys(n).length>0?n:null}function ct(){let e=Date.now(),t=new Uint8Array(16);t[0]=Math.floor(e/2**40)&255,t[1]=Math.floor(e/2**32)&255,t[2]=e>>>24&255,t[3]=e>>>16&255,t[4]=e>>>8&255,t[5]=e&255,lt(t.subarray(6)),t[6]=t[6]&15|112,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function lt(e){if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){crypto.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const ut=I.scope(`persistence`);function dt(e,t=M,n){let r=n?`${e}.${n}`:e,i=`${b.cssPrefix}.storageVersion`,a=t.get(i)??void 0,o=a?`.v${a}`:``,s=`${b.cssPrefix}.${r}${o}`,c=`${b.cssPrefix}${o}.visitorId`,l=`${s}.conversationId`,u=`${s}.userPrefs`,d=`${s}.panelOpen`,f=`${s}.panelSize`,p=`${s}.calloutDismissed`,m=`${s}.sidebarCollapsed`,h=`${s}.activeModule`,g=`${s}.historyCount`,_=`${s}.formsDone`,v={getVisitorId(){let e=t.get(c);if(e)return e;let n=ct();return t.set(c,n),n},loadConversationId(){return t.get(l)??void 0},saveConversationId(e){ut.trace(`saveConversationId`,{id:e,scope:r}),e?t.set(l,e):t.remove(l)},loadDraft(e){return t.get(`${s}.draft.${e}`)??``},saveDraft(e,n){let r=`${s}.draft.${e}`;n?t.set(r,n):t.remove(r)},loadMessageQueue(e){let n=t.get(`${s}.messageQueue.${e}`);if(!n)return[];try{let e=JSON.parse(n);return!Array.isArray(e)||!e.every(pt)?[]:e}catch(e){return ut.warn(`loadMessageQueue parse failed`,{error:e}),[]}},saveMessageQueue(e,n){let r=`${s}.messageQueue.${e}`;if(n.length===0){t.remove(r);return}try{t.set(r,JSON.stringify(n))}catch(e){ut.warn(`saveMessageQueue serialise failed`,{error:e})}},loadUserPrefs(){let e=t.get(u);if(!e)return{};try{return mt(JSON.parse(e))}catch(e){return ut.warn(`loadUserPrefs parse failed`,{error:e}),{}}},saveUserPrefs(e){try{t.set(u,JSON.stringify(e))}catch(e){ut.warn(`saveUserPrefs serialise failed`,{error:e})}},patchUserPrefs(e){let t=v.loadUserPrefs();v.saveUserPrefs({...t,...e})},loadPanelOpen(){let e=t.get(d);return e===`1`||e!==`0`&&null},savePanelOpen(e){t.set(d,e?`1`:`0`)},loadPanelSize(){let e=t.get(f);return e===`normal`||e===`expanded`||e===`fullscreen`?e:null},savePanelSize(e){t.set(f,e)},loadCalloutDismissed(e){if(!e)return!1;let n=t.get(p);return!!n&&n===e},saveCalloutDismissed(e){e?t.set(p,e):t.remove(p)},loadSidebarCollapsed(){let e=t.get(m);return e===`1`||e!==`0`&&null},saveSidebarCollapsed(e){t.set(m,e?`1`:`0`)},loadActiveModule(){return t.get(h)||null},saveActiveModule(e){t.set(h,e)},loadHistoryCount(){let e=t.get(g);if(!e)return null;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:null},saveHistoryCount(e){t.set(g,String(e))},loadFormsDone(){let e=t.get(_);if(!e)return{};try{let t=JSON.parse(e);return ft(t)?Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`number`)):{}}catch(e){return ut.warn(`loadFormsDone parse failed`,{error:e}),{}}},saveFormDone(e){try{let n=v.loadFormsDone();n[e]=Date.now(),t.set(_,JSON.stringify(n))}catch(e){ut.warn(`saveFormDone serialise failed`,{error:e})}},rememberStorageVersion(e){e&&e!==t.get(i)&&(ut.debug(`rememberStorageVersion (force-reset on next load)`,{version:e}),t.set(i,e))},clearConversation(){t.remove(l)}};return v}function ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pt(e){return ft(e)&&typeof e.id==`string`&&e.id.length>0&&typeof e.text==`string`}function mt(e){if(!ft(e))return{};let t={};return typeof e.locale==`string`&&(t.locale=e.locale),typeof e.soundMuted==`boolean`&&(t.soundMuted=e.soundMuted),(e.themeMode===`auto`||e.themeMode===`light`||e.themeMode===`dark`)&&(t.themeMode=e.themeMode),(e.textSize===`small`||e.textSize===`normal`||e.textSize===`large`)&&(t.textSize=e.textSize),ft(e.widgetSize)&&typeof e.widgetSize.width==`number`&&typeof e.widgetSize.height==`number`&&(t.widgetSize={width:e.widgetSize.width,height:e.widgetSize.height}),t}const ht=[`:host{--__P__-accent-user: __BRAND_ACCENT__;--__P__-accent: var(--__P__-accent-user);--__P__-accent-text-user: __BRAND_ACCENT_TEXT__;--__P__-accent-text: var(--__P__-accent-text-user);--__P__-accent-fg: var(--__P__-accent);--__P__-radius: __BRAND_RADIUS__;--__P__-radius-sm: 8px;--__P__-radius-md: 10px;--__P__-radius-lg: 16px;--__P__-font: __BRAND_FONT__;--__P__-font-display: var(--__P__-font);--__P__-font-mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;--__P__-bg: oklch(1 0 0);--__P__-bg-elevated: oklch(.9789 .0029 278.3);--__P__-surface: var(--__P__-bg-elevated);--__P__-muted: var(--__P__-fg-muted);--__P__-hover: oklch(.1686 .011 278.3 / .06);--__P__-fg: oklch(.1686 .011 278.3);--__P__-fg-muted: oklch(.4932 .0301 278.3);--__P__-border: oklch(.9312 .0084 278.3);--__P__-border-strong: oklch(.8757 .0131 278.3);--__P__-bubble-user: var(--__P__-accent);--__P__-bubble-user-text: var(--__P__-accent-text);--__P__-bubble-assistant: oklch(.9638 .0058 278.3);--__P__-bubble-assistant-text: var(--__P__-fg);--__P__-on-accent: var(--__P__-accent-text);--__P__-success: oklch(.6456 .1654 151.53);--__P__-warning: oklch(.7135 .1494 74.05);--__P__-danger: oklch(.5966 .1818 24.51);--__P__-danger-text: oklch(.5054 .1905 27.52);--__P__-danger-bg: oklch(.5966 .1818 24.51 / .1);--__P__-neutral: oklch(.7137 .0192 278.3);--__P__-pill-l-min: .3;--__P__-pill-l-max: .46;--__P__-focus: var(--__P__-accent);--__P__-shadow-panel: 0 8px 24px -8px rgba(13, 15, 20, .18), 0 24px 64px -24px rgba(13, 15, 20, .24);--__P__-shadow-card: 0 1px 2px rgba(13, 15, 20, .06), 0 4px 12px -6px rgba(13, 15, 20, .12);--__P__-backdrop: oklch(.1686 .011 278.3 / .55);--__P__-shadow-fab: 0 6px 16px -4px color-mix(in oklch, var(--__P__-accent) 45%, transparent), 0 12px 32px -12px rgba(13, 15, 20, .25);--__P__-z-fab: 2147483600;--__P__-z-panel: 2147483601;--__P__-panel-w: 380px;--__P__-panel-h: 600px;--__P__-fab-size: 56px;--__P__-conversation-max: 768px;--__P__-space-1: 4px;--__P__-space-2: 8px;--__P__-space-3: 12px;--__P__-space-4: 16px;--__P__-space-5: 20px;--__P__-space-6: 24px;--__P__-space-8: 32px;--__P__-text-scale: 1;--__P__-text-xs: calc(12px * var(--__P__-text-scale));--__P__-text-sm: calc(13px * var(--__P__-text-scale));--__P__-text-base: calc(15px * var(--__P__-text-scale));--__P__-text-md: calc(16px * var(--__P__-text-scale));--__P__-text-lg: calc(18px * var(--__P__-text-scale));--__P__-text-xl: calc(22px * var(--__P__-text-scale));--__P__-text-2xl: calc(30px * var(--__P__-text-scale))}:host([data-mode="modal"]),:host([data-mode="drawer"]){--__P__-conversation-max: 100%}:host([data-text-size="small"]){--__P__-text-scale: .9}:host([data-text-size="large"]){--__P__-text-scale: 1.15}:host{--__P__-ease: cubic-bezier(.2, .7, .2, 1);--__P__-ease-out: cubic-bezier(.2, .7, .2, 1);--__P__-ease-in: cubic-bezier(.4, 0, 1, 1);--__P__-ease-in-out: cubic-bezier(.65, 0, .35, 1);--__P__-dur-quick: .12s;--__P__-dur-base: .22s;--__P__-dur-slow: .32s;font-family:var(--__P__-font);color:var(--__P__-fg);color-scheme:light;--__P__-color-scheme: light}:host([data-theme="dark"]){--__P__-bg: oklch(.1783 .0128 278.3);--__P__-bg-elevated: oklch(.2232 .0182 278.3);--__P__-fg: oklch(.9368 .01 278.3);--__P__-fg-muted: oklch(.7048 .0296 278.3);--__P__-border: oklch(.2752 .0266 278.3);--__P__-border-strong: oklch(.335 .0291 278.3);--__P__-hover: oklch(.9368 .01 278.3 / .08);--__P__-bubble-assistant: oklch(.2474 .0311 278.3);--__P__-bubble-assistant-text: var(--__P__-fg);--__P__-danger-text: oklch(.8077 .1035 19.57);--__P__-danger-bg: oklch(.5966 .1818 24.51 / .18);--__P__-shadow-panel: 0 8px 24px -8px rgba(0, 0, 0, .6), 0 24px 64px -24px rgba(0, 0, 0, .7);--__P__-shadow-card: 0 1px 2px rgba(0, 0, 0, .4), 0 4px 12px -6px rgba(0, 0, 0, .5);--__P__-backdrop: rgba(0, 0, 0, .65);--__P__-pill-l-min: .75;--__P__-pill-l-max: .92;color-scheme:dark;--__P__-color-scheme: dark}@media(prefers-color-scheme:dark){:host([data-theme="auto"]){--__P__-bg: oklch(.1783 .0128 278.3);--__P__-bg-elevated: oklch(.2232 .0182 278.3);--__P__-fg: oklch(.9368 .01 278.3);--__P__-fg-muted: oklch(.7048 .0296 278.3);--__P__-border: oklch(.2752 .0266 278.3);--__P__-border-strong: oklch(.335 .0291 278.3);--__P__-hover: oklch(.9368 .01 278.3 / .08);--__P__-bubble-assistant: oklch(.2474 .0311 278.3);--__P__-bubble-assistant-text: var(--__P__-fg);--__P__-pill-l-min: .75;--__P__-pill-l-max: .92;--__P__-shadow-panel: 0 8px 24px -8px rgba(0, 0, 0, .6), 0 24px 64px -24px rgba(0, 0, 0, .7);color-scheme:dark;--__P__-color-scheme: dark}}@supports (color: oklch(from red l c h)){:host{--__P__-accent: oklch(from var(--__P__-accent-user) clamp(.3, l, .62) c h);--__P__-accent-text: oklch(from var(--__P__-accent) clamp(0, (l / .623 - 1) * -infinity, 1) 0 h);--__P__-accent-fg: oklch(from var(--__P__-accent-user) clamp(.3, l, .46) c h)}:host([data-theme="dark"]){--__P__-accent: oklch(from var(--__P__-accent-user) clamp(.65, l, .85) c h);--__P__-accent-fg: var(--__P__-accent)}@media(prefers-color-scheme:dark){:host([data-theme="auto"]){--__P__-accent: oklch(from var(--__P__-accent-user) clamp(.65, l, .85) c h);--__P__-accent-fg: var(--__P__-accent)}}}@media(prefers-reduced-motion:reduce){:host{--__P__-dur-quick: 1ms;--__P__-dur-base: 1ms;--__P__-dur-slow: 1ms}}
|
|
2
2
|
`,`*,*:before,*:after{box-sizing:border-box;margin:0;padding:0;border:0}button{font:inherit;color:inherit;background:none;cursor:pointer;-webkit-appearance:none;appearance:none;line-height:1}button:focus-visible,[tabindex]:focus-visible,textarea:focus-visible,input:focus-visible{outline:2px solid var(--__P__-accent);outline-offset:2px}textarea,input{font:inherit;color:inherit;background:none;border:0;outline:0;resize:none}a{color:var(--__P__-accent-fg);text-decoration:underline;text-underline-offset:2px}img,svg{display:block;max-width:100%}ul,ol{list-style:none}.__P__-app{display:block;width:100%;height:100%;font-family:var(--__P__-font);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-feature-settings:"cv11","ss01","ss03"}.__P__-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
|
|
3
3
|
`,`.__P__-anchor{color-scheme:var(--__P__-color-scheme, light);right:16px;bottom:16px}.__P__-surface{display:contents}.__P__-surface[hidden]{display:none}:host([data-position="bottom-left"]) .__P__-anchor,:host([data-position="top-left"]) .__P__-anchor{right:auto;left:16px}:host([data-position="top-right"]) .__P__-anchor,:host([data-position="top-left"]) .__P__-anchor{bottom:auto;top:16px}.__P__-anchor{position:fixed;display:flex;flex-direction:column;align-items:flex-end;gap:var(--__P__-space-3);pointer-events:none}.__P__-anchor{--__P__-fab-size: 56px}.__P__-anchor[data-launcher-size=sm]{--__P__-fab-size: 44px}.__P__-anchor[data-launcher-size=md]{--__P__-fab-size: 56px}.__P__-anchor[data-launcher-size=lg]{--__P__-fab-size: 68px}.__P__-anchor>*{pointer-events:auto}.__P__-fab[data-size=sm]{--__P__-fab-size: 44px;font-size:var(--__P__-text-sm)}.__P__-fab[data-size=md]{--__P__-fab-size: 56px;font-size:calc(14px * var(--__P__-text-scale))}.__P__-fab[data-size=lg]{--__P__-fab-size: 68px;font-size:var(--__P__-text-base)}.__P__-fab{display:inline-flex;align-items:center;justify-content:center;gap:var(--__P__-space-2);color:var(--__P__-accent-text);background:var(--__P__-accent);box-shadow:var(--__P__-shadow-fab);font-weight:600;line-height:1;transform-origin:bottom right;animation:__P__-fab-in var(--__P__-dur-base) var(--__P__-ease) both;transition:transform var(--__P__-dur-base) var(--__P__-ease),opacity var(--__P__-dur-base) var(--__P__-ease),box-shadow var(--__P__-dur-base) var(--__P__-ease)}.__P__-fab:hover{transform:translateY(-2px)}.__P__-fab:active{transform:translateY(0)}.__P__-fab:focus-visible{outline:2px solid var(--__P__-on-accent);outline-offset:3px}.__P__-fab svg{width:24px;height:24px;flex-shrink:0}@keyframes __P__-fab-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:none}}.__P__-fab[data-leaving]{position:absolute;right:0;bottom:0;animation:__P__-fab-out var(--__P__-dur-quick) var(--__P__-ease) forwards;pointer-events:none}:host([data-position^="top-"]) .__P__-fab[data-leaving]{bottom:auto;top:0}:host([data-position$="-left"]) .__P__-fab[data-leaving]{right:auto;left:0}@keyframes __P__-fab-out{0%{opacity:1;transform:none}to{opacity:0;transform:scale(.85)}}.__P__-fab[data-variant=circle]{width:var(--__P__-fab-size);height:var(--__P__-fab-size);border-radius:999px}.__P__-fab[data-variant=circle] .__P__-fab-label{display:none}.__P__-fab[data-variant=pill]{height:var(--__P__-fab-size);padding:0 18px 0 16px;border-radius:999px}.__P__-fab[data-variant=bar]{height:var(--__P__-fab-size);padding:0 22px;border-radius:var(--__P__-radius)}.__P__-fab[data-variant=minimal]{height:var(--__P__-fab-size);padding:0 var(--__P__-space-4);border-radius:999px;background:transparent;color:var(--__P__-accent-fg);box-shadow:none;border:1px solid currentColor}.__P__-fab[data-variant=minimal]:hover{background:color-mix(in srgb,var(--__P__-accent) 12%,transparent)}.__P__-callout{--__P__-callout-fab-h: var(--__P__-fab-size, 56px);--__P__-callout-gap: clamp(12px, calc(var(--__P__-callout-fab-h) * .25), 22px);--__P__-callout-nudge-direction: -1;position:absolute;display:inline-flex;align-items:center;gap:var(--__P__-space-2);padding:10px 14px;background:var(--__P__-fg);color:var(--__P__-bg);border-radius:999px;font-size:var(--__P__-text-sm);font-weight:600;line-height:1.2;box-shadow:0 10px 30px -8px #00000059;pointer-events:auto;animation:__P__-callout-in var(--__P__-dur-slow) var(--__P__-ease);z-index:1;max-width:240px;white-space:nowrap}.__P__-callout[data-position=left]{right:calc(100% + var(--__P__-callout-gap));bottom:calc(var(--__P__-callout-fab-h) / 2);transform:translateY(50%)}.__P__-callout[data-position=right]{left:calc(100% + var(--__P__-callout-gap));bottom:calc(var(--__P__-callout-fab-h) / 2);transform:translateY(50%);--__P__-callout-nudge-direction: 1}.__P__-callout[data-position=top]{bottom:calc(100% + var(--__P__-callout-gap));right:0;max-width:min(280px,calc(100vw - 32px))}.__P__-callout[data-position=bottom]{top:calc(100% + var(--__P__-callout-gap));right:0;max-width:min(280px,calc(100vw - 32px))}:host([data-position$="-left"]) .__P__-callout[data-position=top],:host([data-position$="-left"]) .__P__-callout[data-position=bottom]{right:auto;left:0}.__P__-callout[data-shape=bubble]{border-radius:var(--__P__-radius-md);white-space:normal;width:max-content;max-width:min(280px,calc(100vw - 32px))}.__P__-callout[data-shape=callout]{padding:12px 18px;font-size:calc(14px * var(--__P__-text-scale));background:var(--__P__-accent);color:var(--__P__-accent-text)}.__P__-callout:after{content:"";position:absolute;width:12px;height:12px;background:inherit;border-radius:2px;transform:rotate(45deg)}.__P__-callout[data-position=left]:after{right:-5px;top:50%;margin-top:-6px}.__P__-callout[data-position=right]:after{left:-5px;top:50%;margin-top:-6px}.__P__-callout[data-position=top]:after{bottom:-5px;right:calc(var(--__P__-fab-size, 56px) / 2 - 6px)}.__P__-callout[data-position=bottom]:after{top:-5px;right:calc(var(--__P__-fab-size, 56px) / 2 - 6px)}:host([data-position$="-left"]) .__P__-callout[data-position=top]:after,:host([data-position$="-left"]) .__P__-callout[data-position=bottom]:after{right:auto;left:calc(var(--__P__-fab-size, 56px) / 2 - 6px)}.__P__-callout[data-animated]{animation:__P__-callout-in var(--__P__-dur-slow) var(--__P__-ease),__P__-callout-nudge 1.6s var(--__P__-ease-in-out) var(--__P__-dur-slow) infinite}@keyframes __P__-callout-in{0%{opacity:0}to{opacity:1}}@keyframes __P__-callout-nudge{0%,to{margin-left:0;margin-right:0}50%{margin-left:calc(6px * var(--__P__-callout-nudge-direction));margin-right:calc(-6px * var(--__P__-callout-nudge-direction))}}@media(prefers-reduced-motion:reduce){.__P__-callout[data-animated]{animation:__P__-callout-in 1ms var(--__P__-ease)}.__P__-icon-btn[data-recording=true],.__P__-typing span{animation:none}}.__P__-callout-close{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:999px;color:inherit;opacity:.7;cursor:pointer}.__P__-callout-close:hover{opacity:1;background:color-mix(in srgb,currentColor 15%,transparent)}.__P__-callout-close:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-callout-close svg{width:12px;height:12px}.__P__-panel{width:var(--__P__-panel-w);height:var(--__P__-panel-h);max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);background:var(--__P__-bg);color:var(--__P__-fg);border-radius:var(--__P__-radius-lg);box-shadow:var(--__P__-shadow-panel);display:flex;flex-direction:column;overflow:hidden;overscroll-behavior:none;transform-origin:bottom right;animation:__P__-panel-in var(--__P__-dur-slow) var(--__P__-ease);border:1px solid var(--__P__-border)}@media(prefers-reduced-motion:no-preference){.__P__-panel{transition:width var(--__P__-dur-base) var(--__P__-ease),height var(--__P__-dur-base) var(--__P__-ease),max-width var(--__P__-dur-base) var(--__P__-ease),max-height var(--__P__-dur-base) var(--__P__-ease)}.__P__-panel[data-resizing]{transition:none}}:host([data-mode="open"]) .__P__-panel{width:var(--__P__-widget-w, var(--__P__-panel-w));height:var(--__P__-widget-h, var(--__P__-panel-h));min-width:var(--__P__-resize-min-w, auto);min-height:var(--__P__-resize-min-h, auto);max-width:var(--__P__-resize-max-w, calc(100vw - 32px) );max-height:var(--__P__-resize-max-h, calc(100dvh - 32px) )}@keyframes __P__-panel-in{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}:host([data-mode="expanded"]) .__P__-panel{width:var(--__P__-expanded-w, 640px);height:var(--__P__-expanded-h, 820px);max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px)}:host([data-mode="fullscreen"]){z-index:var(--__P__-z-panel)!important}:host([data-mode="fullscreen"]) .__P__-anchor{inset:var(--__P__-visual-viewport-top, 0px) 0 auto;height:var(--__P__-visual-viewport-height, 100dvh);padding:0;justify-content:flex-end;align-items:flex-end}:host([data-mode="fullscreen"][data-position*="top"]) .__P__-anchor{justify-content:flex-start}:host([data-mode="fullscreen"][data-position*="left"]) .__P__-anchor{align-items:flex-start}:host([data-mode="fullscreen"]) .__P__-panel{width:100vw;height:100%;max-width:none;max-height:none;border-radius:0;border:0}:host([data-mode="fullscreen"]) .__P__-fab{display:none}@media(max-width:640px){:host([data-mode="open"]) .__P__-anchor,:host([data-mode="expanded"]) .__P__-anchor{inset:var(--__P__-visual-viewport-top, 0px) 0 auto;align-items:stretch;height:var(--__P__-visual-viewport-height, 100dvh);padding:0}:host([data-mode="open"]) .__P__-panel,:host([data-mode="expanded"]) .__P__-panel{width:100vw;height:100%;max-width:none;max-height:none;border-radius:0;border:0}}:host([data-mode="inline"]) .__P__-anchor,:host([data-mode="standalone"]) .__P__-anchor{position:static;inset:auto;padding:0;align-items:stretch;width:100%;height:100%;min-height:0}:host([data-mode="inline"]) .__P__-panel,:host([data-mode="standalone"]) .__P__-panel{width:100%;height:100%;min-width:0;min-height:0;max-width:none;max-height:none;animation:none}:host([data-mode="inline"]) .__P__-fab,:host([data-mode="standalone"]) .__P__-fab{display:none}:host([data-mode="inline"]){min-height:320px}:host([data-mode="inline"]) .__P__-panel{border-radius:var(--__P__-radius)}:host([data-mode="standalone"]) .__P__-panel{border-radius:0;border:0;box-shadow:none}:host([data-mode="modal"]){position:fixed!important;inset:0!important;z-index:var(--__P__-z-panel)!important;display:block!important;width:100vw;height:100dvh;background:var(--__P__-modal-backdrop, var(--__P__-backdrop));animation:__P__-backdrop-in var(--__P__-dur-base) var(--__P__-ease) both;--__P__-panel-w: min(960px, 92vw);--__P__-panel-h: min(720px, 88dvh)}:host([data-mode="modal"]) .__P__-anchor{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:var(--__P__-space-6);pointer-events:none}:host([data-mode="modal"]) .__P__-panel{pointer-events:auto;width:var(--__P__-widget-w, var(--__P__-panel-w));height:var(--__P__-widget-h, var(--__P__-panel-h));max-width:calc(100vw - 48px);max-height:calc(100dvh - 48px);min-width:0;min-height:0;border-radius:var(--__P__-radius);box-shadow:var(--__P__-shadow-panel);animation:__P__-modal-in var(--__P__-dur-base) var(--__P__-ease);translate:var(--__P__-modal-dx, 0px) var(--__P__-modal-dy, 0px)}:host([data-mode="modal"]) .__P__-header,:host([data-mode="modal"]) .__P__-back-header,:host([data-mode="modal"]) .__P__-home-hero{cursor:grab;touch-action:none}:host([data-mode="modal"]) .__P__-panel[data-dragging]{cursor:grabbing;user-select:none}:host([data-mode="modal"]) .__P__-panel[data-dragging] *{cursor:grabbing}:host([data-mode="modal"]) .__P__-fab{display:none}@keyframes __P__-backdrop-in{0%{background:#0000}to{background:var(--__P__-modal-backdrop, var(--__P__-backdrop))}}@keyframes __P__-modal-in{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}:host([data-mode="drawer"]){--__P__-panel-w: min(440px, calc(100vw - 32px) );--__P__-panel-h: 100dvh}:host([data-mode="drawer"]) .__P__-anchor{position:fixed;--__P__-inset-x: var(--__P__-panel-inset, 12px);--__P__-inset-y: var(--__P__-panel-inset, 3dvh);top:var(--__P__-inset-y);bottom:auto;right:var(--__P__-inset-x);left:auto;width:min(var(--__P__-widget-w, var(--__P__-panel-w)),calc(100vw - var(--__P__-inset-x) * 2));height:min(var(--__P__-widget-h, var(--__P__-panel-h)),calc(100dvh - var(--__P__-inset-y) * 2));padding:0;display:block;pointer-events:auto}:host([data-mode="drawer"][data-position$="-left"]) .__P__-anchor{right:auto;left:var(--__P__-inset-x)}:host([data-mode="drawer"][data-position^="bottom-"]) .__P__-anchor{top:auto;bottom:var(--__P__-inset-y)}:host([data-mode="drawer"]) .__P__-panel{width:100%;height:100%;max-width:none;max-height:none;min-width:0;min-height:0;border-radius:var(--__P__-radius, 12px);border:1px solid var(--__P__-border);box-shadow:-8px 16px 32px -12px #00000038;animation:__P__-drawer-in var(--__P__-dur-base) var(--__P__-ease)}:host([data-mode="drawer"][data-position$="-left"]) .__P__-panel{box-shadow:8px 16px 32px -12px #00000038;animation:__P__-drawer-in-left var(--__P__-dur-base) var(--__P__-ease)}.__P__-fab[data-edge-tab]{display:inline-flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--__P__-space-2);position:fixed;top:50%;height:140px;width:auto;min-width:0;padding:10px 8px;writing-mode:vertical-rl;text-orientation:mixed;transform:translateY(-50%);transform-origin:center;animation:__P__-edge-tab-in var(--__P__-dur-base) var(--__P__-ease) both}.__P__-fab[data-edge-tab] svg{writing-mode:horizontal-tb}.__P__-fab[data-edge-tab]:hover{transform:translateY(-50%) scale(1.03)}.__P__-fab[data-edge-tab]:active{transform:translateY(-50%) scale(.97)}:host([data-position$="-right"]) .__P__-fab[data-edge-tab]{right:0;left:auto;border-radius:12px 0 0 12px;box-shadow:-6px 0 18px -8px #0000004d}:host([data-position$="-left"]) .__P__-fab[data-edge-tab]{left:0;right:auto;border-radius:0 12px 12px 0;box-shadow:6px 0 18px -8px #0000004d}.__P__-fab[data-edge-tab][data-leaving]{position:fixed;top:50%;bottom:auto;animation:__P__-edge-tab-out var(--__P__-dur-quick) var(--__P__-ease) forwards}@keyframes __P__-edge-tab-in{0%{opacity:0;transform:translateY(-50%) scale(.9)}to{opacity:1;transform:translateY(-50%) scale(1)}}@keyframes __P__-edge-tab-out{0%{opacity:1;transform:translateY(-50%) scale(1)}to{opacity:0;transform:translateY(-50%) scale(.85)}}@keyframes __P__-drawer-in{0%{transform:translate(100%)}to{transform:translate(0)}}@keyframes __P__-drawer-in-left{0%{transform:translate(-100%)}to{transform:translate(0)}}@media(prefers-reduced-motion:reduce){:host([data-mode="drawer"]) .__P__-panel,.__P__-fab[data-edge-tab]{animation:none}}.__P__-header{display:flex;align-items:center;gap:var(--__P__-space-2);padding:10px 12px;border-bottom:1px solid var(--__P__-border);background:var(--__P__-bg)}.__P__-header h1{font-size:calc(14px * var(--__P__-text-scale));font-weight:600;flex:1;letter-spacing:-.01em}.__P__-header-actions{margin-inline-start:auto;display:flex;align-items:center;gap:var(--__P__-space-1);flex-shrink:0}.__P__-agent{flex:1;display:inline-flex;align-items:center;gap:10px;min-width:0}.__P__-agent-avatar{position:relative;width:32px;height:32px;border-radius:999px;background:var(--__P__-bg-elevated);color:var(--__P__-fg-muted);display:inline-flex;align-items:center;justify-content:center;font-weight:700;font-size:var(--__P__-text-xs);overflow:hidden;flex-shrink:0}.__P__-agent-avatar img{width:100%;height:100%;object-fit:cover}.__P__-agent-avatar:after{content:"";position:absolute;right:-1px;bottom:-1px;width:10px;height:10px;border-radius:999px;border:2px solid var(--__P__-bg);background:var(--__P__-neutral)}.__P__-agent-avatar[data-status=online]:after{background:var(--__P__-success)}.__P__-agent-avatar[data-status=away]:after{background:var(--__P__-warning)}.__P__-agent-avatar[data-status=offline]:after{background:var(--__P__-neutral)}.__P__-agent-meta{display:flex;flex-direction:column;line-height:1.15;min-width:0}.__P__-agent-meta strong{font-size:calc(14px * var(--__P__-text-scale));font-weight:600;letter-spacing:-.01em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.__P__-agent-meta span{font-size:var(--__P__-text-xs);color:var(--__P__-fg-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.__P__-suggestions{display:flex;flex-wrap:nowrap;gap:var(--__P__-space-2);padding:6px 14px 10px;overflow-x:auto;overflow-y:hidden;scroll-behavior:smooth;scroll-snap-type:x proximity;scrollbar-width:none;-ms-overflow-style:none;min-width:0}.__P__-suggestions::-webkit-scrollbar{display:none}.__P__-suggestions:before,.__P__-suggestions:after{content:"";flex:1 1 0;min-width:0}.__P__-suggestion{flex:0 0 auto;scroll-snap-align:center;padding:7px 14px;border-radius:999px;background:var(--__P__-bg-elevated);border:1px solid var(--__P__-border);color:var(--__P__-fg);font-size:var(--__P__-text-sm);font-weight:500;white-space:nowrap;transition:background var(--__P__-dur-quick) var(--__P__-ease),border-color var(--__P__-dur-quick) var(--__P__-ease),transform var(--__P__-dur-quick) var(--__P__-ease)}.__P__-suggestion:hover{border-color:var(--__P__-accent);color:var(--__P__-accent-fg);transform:translateY(-1px)}.__P__-suggestion:focus-visible{outline:2px solid var(--__P__-accent);outline-offset:2px;border-color:var(--__P__-accent)}.__P__-suggestion:active{transform:translateY(0)}.__P__-icon-btn{width:32px;height:32px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center;color:var(--__P__-fg-muted);transition:background var(--__P__-dur-quick) var(--__P__-ease),color var(--__P__-dur-quick) var(--__P__-ease)}.__P__-icon-btn:hover{background:var(--__P__-bg-elevated);color:var(--__P__-fg)}.__P__-icon-btn:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-icon-btn:active{background:var(--__P__-border)}.__P__-icon-btn:disabled{opacity:.45;cursor:not-allowed}.__P__-icon-btn:before{content:"";position:absolute;inset:-6px}.__P__-icon-btn{position:relative}.__P__-icon-btn svg{width:18px;height:18px}.__P__-icon-btn[data-recording=true]{color:var(--__P__-accent-fg);background:color-mix(in srgb,var(--__P__-accent) 12%,transparent);animation:__P__-pulse 1.2s var(--__P__-ease) infinite}@keyframes __P__-pulse{0%,to{box-shadow:0 0 color-mix(in srgb,var(--__P__-accent) 40%,transparent)}50%{box-shadow:0 0 0 6px color-mix(in srgb,var(--__P__-accent) 0%,transparent)}}.__P__-list,.__P__-history,.__P__-module-scroll,.__P__-home-scroll,.__P__-help-list,.__P__-toolui-code,.__P__-sidebar-conversations{scrollbar-width:thin;scrollbar-color:var(--__P__-border-strong) transparent;overscroll-behavior:contain;scrollbar-gutter:stable}.__P__-list::-webkit-scrollbar,.__P__-history::-webkit-scrollbar,.__P__-module-scroll::-webkit-scrollbar,.__P__-home-scroll::-webkit-scrollbar,.__P__-help-list::-webkit-scrollbar,.__P__-toolui-code::-webkit-scrollbar,.__P__-sidebar-conversations::-webkit-scrollbar{width:8px}.__P__-list::-webkit-scrollbar-thumb,.__P__-history::-webkit-scrollbar-thumb,.__P__-module-scroll::-webkit-scrollbar-thumb,.__P__-home-scroll::-webkit-scrollbar-thumb,.__P__-help-list::-webkit-scrollbar-thumb,.__P__-toolui-code::-webkit-scrollbar-thumb,.__P__-sidebar-conversations::-webkit-scrollbar-thumb{background:var(--__P__-border-strong);border-radius:8px}.__P__-list-wrap{position:relative;flex:1;min-height:0;display:flex;flex-direction:column}.__P__-jump{position:absolute;inset-inline-end:14px;bottom:14px;z-index:2;display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:999px;border:1px solid var(--__P__-border);background:var(--__P__-bg-elevated);color:var(--__P__-fg);box-shadow:var(--__P__-shadow-panel);cursor:pointer;opacity:.85;transition:opacity var(--__P__-dur-quick) var(--__P__-ease),transform var(--__P__-dur-quick) var(--__P__-ease);animation:__P__-bubble-in var(--__P__-dur-base) var(--__P__-ease)}.__P__-jump:hover{opacity:1}.__P__-jump:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px;opacity:1}.__P__-jump:active{transform:translateY(1px)}.__P__-jump svg{width:18px;height:18px}.__P__-list{flex:1;min-height:0;overflow-y:auto;padding:var(--__P__-space-4);padding-bottom:var(--__P__-space-8);display:flex;flex-direction:column;gap:14px}.__P__-list--fade{--__P__-fade-size: 20px;--__P__-fade-top: 0px;--__P__-fade-bottom: 0px;-webkit-mask-image:linear-gradient(to bottom,transparent 0,#000 var(--__P__-fade-top),#000 calc(100% - var(--__P__-fade-bottom)),transparent 100%);mask-image:linear-gradient(to bottom,transparent 0,#000 var(--__P__-fade-top),#000 calc(100% - var(--__P__-fade-bottom)),transparent 100%)}.__P__-list--fade[data-fade-top=true]{--__P__-fade-top: var(--__P__-fade-size)}.__P__-list--fade[data-fade-bottom=true]{--__P__-fade-bottom: var(--__P__-fade-size)}.__P__-list>*{width:100%;max-width:var(--__P__-conversation-max, 768px);margin-inline:auto}.__P__-load-previous,.__P__-history-more{display:flex;justify-content:center}.__P__-load-previous button,.__P__-history-more button{border:0;padding:4px 8px;background:transparent;color:var(--__P__-accent);font:inherit;font-size:var(--__P__-text-sm);font-weight:600;cursor:pointer}.__P__-load-previous button:hover,.__P__-history-more button:hover{text-decoration:underline}.__P__-load-previous button:focus-visible,.__P__-history-more button:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px;border-radius:var(--__P__-radius-sm)}.__P__-load-previous button:disabled,.__P__-history-more button:disabled{cursor:wait;opacity:.6}.__P__-date-divider{display:flex;justify-content:center;margin-block:var(--__P__-space-3)}.__P__-date-pill{padding:3px 10px;border-radius:999px;font-size:calc(11px * var(--__P__-text-scale));font-weight:600;color:var(--__P__-fg-muted);background:var(--__P__-bg-elevated);border:1px solid var(--__P__-border);box-shadow:var(--__P__-shadow-card)}.__P__-bubble-row{display:flex}.__P__-bubble-row[data-role=user]{justify-content:flex-end}.__P__-bubble-row[data-role=assistant]{justify-content:flex-start}.__P__-bubble{max-width:100%;min-width:0;padding:var(--__P__-space-3) var(--__P__-space-4);border-radius:var(--__P__-radius);line-height:1.6;font-size:calc(14px * var(--__P__-text-scale));word-wrap:break-word;overflow-wrap:break-word;box-shadow:0 1px 2px #0000000a,0 1px 8px -4px #0000000f;animation:__P__-bubble-in var(--__P__-dur-base) var(--__P__-ease)}.__P__-bubble ::selection{background:color-mix(in srgb,var(--__P__-accent) 30%,transparent)}.__P__-bubble-row[data-role=user] .__P__-bubble ::selection{background:#fff6;color:var(--__P__-bubble-user-text)}@keyframes __P__-bubble-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.__P__-bubble-row[data-role=user] .__P__-bubble{background:var(--__P__-bubble-user);color:var(--__P__-bubble-user-text);border-end-end-radius:5px}.__P__-bubble-row[data-role=assistant] .__P__-bubble{background:var(--__P__-bubble-assistant);color:var(--__P__-bubble-assistant-text);border:1px solid var(--__P__-border);border-end-start-radius:5px}.__P__-bubble-row[data-role=operator] .__P__-bubble{display:flex;align-items:stretch;padding:0;overflow:hidden;background:var(--__P__-bubble-assistant);color:var(--__P__-bubble-assistant-text);border-end-start-radius:5px}.__P__-bubble-row[data-role=operator] .__P__-bubble-col{align-items:flex-start}.__P__-bubble-author{display:flex;flex:0 0 auto;align-items:center;padding:0 .875rem;border-inline-end:1px solid color-mix(in oklab,var(--__P__-accent),transparent 60%);color:var(--__P__-accent);font-size:calc(13px * var(--__P__-text-scale));font-weight:600;letter-spacing:.025em;user-select:none}.__P__-bubble-row[data-role=operator] .__P__-bubble-body{flex:1 1 auto;min-width:0;padding:var(--__P__-space-3) var(--__P__-space-4)}.__P__-bubble-col{display:flex;flex-direction:column;max-width:85%;min-width:0}.__P__-bubble-row[data-role=user] .__P__-bubble-col{align-items:flex-end}.__P__-bubble-row[data-role=assistant] .__P__-bubble-col{align-items:flex-start}.__P__-bubble-row[data-role=assistant] .__P__-bubble-col:has(.__P__-toolui){width:100%}.__P__-bubble-row[data-role=assistant] .__P__-bubble-col:has(.__P__-toolui) .__P__-bubble{width:100%}@media(max-width:640px){.__P__-bubble-col{max-width:92%}.__P__-toolui:not(.__P__-toolui-collapsible){padding:var(--__P__-space-3);gap:var(--__P__-space-2)}details.__P__-toolui-collapsible>summary{padding:var(--__P__-space-2) var(--__P__-space-3)}details.__P__-toolui-collapsible>.__P__-toolui-section{margin:var(--__P__-space-3)}.__P__-toolui-section,.__P__-toolui-desc{padding:var(--__P__-space-2) var(--__P__-space-3)}}.__P__-bubble-meta{display:flex;align-items:center;gap:8px;margin-top:2px;padding:0 2px;min-height:24px}.__P__-bubble-actions{display:flex;align-items:center;gap:2px}.__P__-bubble-time{font-size:calc(11px * var(--__P__-text-scale));line-height:1;color:var(--__P__-fg-muted);user-select:none}.__P__-feedback{display:flex;align-items:center;gap:2px}.__P__-msg-action{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border:0;border-radius:var(--__P__-radius-sm);background:transparent;color:var(--__P__-fg-muted);cursor:pointer;opacity:.65;transition:opacity var(--__P__-dur-quick) var(--__P__-ease),background var(--__P__-dur-quick) var(--__P__-ease),color var(--__P__-dur-quick) var(--__P__-ease)}.__P__-msg-action:hover{opacity:1;background:var(--__P__-bg-elevated);color:var(--__P__-fg)}.__P__-msg-action:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px;opacity:1}.__P__-msg-action[data-active=true]{opacity:1;color:var(--__P__-accent-fg)}.__P__-msg-action svg{width:15px;height:15px}.__P__-md>*:first-child{margin-top:0}.__P__-md>*:last-child{margin-bottom:0}.__P__-md p{margin:10px 0}.__P__-md h1,.__P__-md h2,.__P__-md h3,.__P__-md h4,.__P__-md h5,.__P__-md h6{margin:18px 0 8px;line-height:1.3;letter-spacing:-.01em;font-weight:700}.__P__-md h1{font-size:1.4em}.__P__-md h2{font-size:1.22em}.__P__-md h3{font-size:1.08em}.__P__-md h4,.__P__-md h5,.__P__-md h6{font-size:1em}.__P__-md>h1:first-child,.__P__-md>h2:first-child,.__P__-md>h3:first-child,.__P__-md>h4:first-child,.__P__-md>h5:first-child,.__P__-md>h6:first-child{margin-top:0}.__P__-md ul,.__P__-md ol{padding-inline-start:1.5em;margin:10px 0}.__P__-md ul{list-style:disc}.__P__-md ol{list-style:decimal}.__P__-md li{margin:6px 0;padding-inline-start:2px}.__P__-md li::marker{color:var(--__P__-fg-muted)}.__P__-md li>p{margin:6px 0}.__P__-md li>ul,.__P__-md li>ol{margin:6px 0}.__P__-md strong,.__P__-md b{font-weight:650;letter-spacing:-.005em}.__P__-md em,.__P__-md i{font-style:italic}.__P__-md code{font-family:var(--__P__-font-mono);font-size:.86em;padding:1px 6px;border-radius:5px;background:color-mix(in srgb,var(--__P__-accent) 10%,transparent);color:var(--__P__-fg);border:1px solid color-mix(in srgb,var(--__P__-accent) 16%,transparent)}.__P__-md pre{font-family:var(--__P__-font-mono);font-size:calc(12.5px * var(--__P__-text-scale));padding:12px 14px;border-radius:var(--__P__-radius-sm);background:#7f7f7f1f;overflow-x:auto;margin:var(--__P__-space-3) 0;line-height:1.5}.__P__-md pre code{padding:0;background:none}.__P__-md a{color:inherit;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:2px}.__P__-md a:hover{text-decoration-thickness:2px}.__P__-md blockquote{margin:14px 0;padding:6px 14px;border-inline-start:3px solid color-mix(in srgb,var(--__P__-accent) 50%,transparent);background:color-mix(in srgb,var(--__P__-accent) 5%,transparent);border-start-end-radius:var(--__P__-radius-sm);border-end-end-radius:var(--__P__-radius-sm);color:var(--__P__-fg-muted)}.__P__-md blockquote>:first-child{margin-top:0}.__P__-md blockquote>:last-child{margin-bottom:0}.__P__-md hr{border:0;height:1px;background:color-mix(in srgb,currentColor 18%,transparent);margin:var(--__P__-space-4) 0}.__P__-md table{border-collapse:collapse;margin:var(--__P__-space-3) 0;font-size:.95em;display:block;overflow-x:auto;max-width:100%;font-variant-numeric:tabular-nums}.__P__-md th,.__P__-md td{padding:6px 10px;border-bottom:1px solid color-mix(in srgb,currentColor 12%,transparent);text-align:start}.__P__-md th{font-weight:700;background:color-mix(in srgb,currentColor 6%,transparent)}.__P__-md h1+ul,.__P__-md h1+ol,.__P__-md h2+ul,.__P__-md h2+ol,.__P__-md h3+ul,.__P__-md h3+ol,.__P__-md h4+ul,.__P__-md h4+ol{margin-top:var(--__P__-space-1)}.__P__-loading{display:inline-flex;align-items:center;gap:var(--__P__-space-2);color:var(--__P__-fg-muted);font-size:var(--__P__-text-sm)}.__P__-loading-spinner{width:14px;height:14px;border-radius:999px;border:2px solid currentColor;border-top-color:transparent;animation:__P__-spin .8s linear infinite}@keyframes __P__-spin{to{transform:rotate(1turn)}}.__P__-typing{display:inline-flex;gap:var(--__P__-space-1);padding:var(--__P__-space-1) 0}.__P__-typing span{width:5px;height:5px;border-radius:999px;background:currentColor;opacity:.4;animation:__P__-blink 1.2s var(--__P__-ease) infinite}.__P__-typing span:nth-child(2){animation-delay:.2s}.__P__-typing span:nth-child(3){animation-delay:.4s}@keyframes __P__-blink{0%,80%,to{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-2px)}}.__P__-reasoning{margin:var(--__P__-space-1) 0 var(--__P__-space-2);padding-inline-start:var(--__P__-space-3);border-inline-start:2px solid var(--__P__-border-strong)}.__P__-reasoning-summary{display:inline-flex;align-items:center;gap:var(--__P__-space-1);cursor:pointer;list-style:none;user-select:none;color:var(--__P__-fg-muted);font-size:var(--__P__-text-xs);font-weight:600}.__P__-reasoning-summary:hover{color:var(--__P__-fg)}.__P__-reasoning-summary:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px;border-radius:var(--__P__-radius-sm)}.__P__-reasoning-summary::-webkit-details-marker{display:none}.__P__-reasoning-summary:before{content:"";width:5px;height:5px;border-inline-end:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:rotate(-45deg);opacity:.7;transition:transform var(--__P__-dur-quick) var(--__P__-ease)}.__P__-reasoning[open] .__P__-reasoning-summary:before{transform:rotate(45deg)}.__P__-reasoning[data-active=true] .__P__-reasoning-label{animation:__P__-reasoning-pulse 1.4s var(--__P__-ease) infinite}@keyframes __P__-reasoning-pulse{0%,to{opacity:.5}50%{opacity:1}}@media(prefers-reduced-motion:reduce){.__P__-reasoning[data-active=true] .__P__-reasoning-label{animation:none}}.__P__-reasoning-body{margin-top:var(--__P__-space-1);color:var(--__P__-fg-muted);font-size:var(--__P__-text-sm)}.__P__-reasoning-body>:first-child{margin-top:0}.__P__-reasoning-body>:last-child{margin-bottom:0}.__P__-source{display:inline-flex;align-items:center;gap:6px;max-width:100%;margin-top:6px;margin-inline-end:6px;padding:var(--__P__-space-1) var(--__P__-space-2);border-radius:999px;background:var(--__P__-bg-elevated);border:1px solid var(--__P__-border);color:var(--__P__-fg-muted);font-size:var(--__P__-text-xs);text-decoration:none}a.__P__-source:hover{color:var(--__P__-fg);border-color:var(--__P__-accent)}.__P__-source-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.__P__-composer{border-top:1px solid var(--__P__-border);padding:10px 12px;background:var(--__P__-bg);display:flex;flex-direction:column;gap:var(--__P__-space-2)}.__P__-composer>*{width:100%;max-width:var(--__P__-conversation-max, 768px);margin-inline:auto}.__P__-compaction-status{width:100%;padding:10px 14px;justify-content:center;font-size:var(--__P__-text-xs)}.__P__-message-queue{display:flex;max-height:112px;flex-direction:column;gap:var(--__P__-space-1);overflow-y:auto}.__P__-attachment-chip.__P__-queued-message{width:100%;max-width:none}.__P__-queued-text{min-width:0;flex:1}.__P__-composer-row{display:flex;align-items:flex-end;gap:6px}.__P__-textarea{flex:1;--__P__-textarea-base-height: 40px;height:var(--__P__-textarea-base-height);max-height:160px;padding:10px 12px;border-radius:var(--__P__-radius);background:var(--__P__-bg-elevated);border:1px solid transparent;font-size:calc(14px * var(--__P__-text-scale));line-height:1.4;transition:height var(--__P__-dur-quick) var(--__P__-ease),border-color var(--__P__-dur-quick) var(--__P__-ease)}.__P__-textarea:focus-visible{outline:none;border-color:var(--__P__-focus)}@media(pointer:coarse){.__P__-textarea{--__P__-textarea-base-height: 44px}}.__P__-send{width:40px;height:40px;display:inline-flex;align-items:center;justify-content:center;border:1px solid transparent;transition:opacity var(--__P__-dur-quick) var(--__P__-ease),transform var(--__P__-dur-quick) var(--__P__-ease),background var(--__P__-dur-quick) var(--__P__-ease)}.__P__-send[data-shape=circle]{border-radius:999px}.__P__-send[data-shape=square]{border-radius:var(--__P__-radius-sm)}.__P__-send[data-shape=pill]{width:auto;padding:0 18px;border-radius:999px}.__P__-send[data-variant=filled]{background:var(--__P__-accent);color:var(--__P__-accent-text)}.__P__-send[data-variant=outline]{background:transparent;color:var(--__P__-accent-fg);border-color:var(--__P__-accent)}.__P__-send[data-variant=outline]:not(:disabled):hover{background:color-mix(in srgb,var(--__P__-accent) 10%,transparent)}.__P__-send[data-variant=ghost]{background:transparent;color:var(--__P__-accent-fg)}.__P__-send[data-variant=ghost]:not(:disabled):hover{background:color-mix(in srgb,var(--__P__-accent) 8%,transparent)}.__P__-send:disabled{opacity:.4;cursor:not-allowed}.__P__-send:not(:disabled):hover{transform:translateY(-1px)}.__P__-send:not(:disabled):active{transform:translateY(0)}.__P__-send:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-send svg{width:18px;height:18px}.__P__-composer-actions{display:flex;gap:var(--__P__-space-1);flex-wrap:wrap}.__P__-attachments{display:flex;flex-wrap:wrap;gap:6px}.__P__-attachment-chip{display:inline-flex;align-items:center;gap:6px;padding:var(--__P__-space-1) var(--__P__-space-2) var(--__P__-space-1) var(--__P__-space-1);border-radius:999px;background:var(--__P__-bg-elevated);border:1px solid var(--__P__-border);font-size:var(--__P__-text-xs);max-width:200px}.__P__-attachment-thumb{width:24px;height:24px;border-radius:999px;object-fit:cover;background:var(--__P__-border)}.__P__-attachment-name{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.__P__-attachment-remove{width:18px;height:18px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center;color:var(--__P__-fg-muted)}.__P__-attachment-remove:hover{background:var(--__P__-border);color:var(--__P__-fg)}.__P__-dropzone{position:absolute;inset:8px;border:2px dashed var(--__P__-accent);border-radius:var(--__P__-radius);background:color-mix(in srgb,var(--__P__-accent) 8%,transparent);display:flex;align-items:center;justify-content:center;font-weight:600;color:var(--__P__-accent-fg);pointer-events:none;z-index:10;animation:__P__-fade-in var(--__P__-dur-quick) var(--__P__-ease)}@keyframes __P__-fade-in{0%{opacity:0}to{opacity:1}}.__P__-error{margin-top:var(--__P__-space-1);padding:8px 12px;border-radius:var(--__P__-radius-sm);background:color-mix(in oklab,var(--__P__-danger) 8%,var(--__P__-bg-elevated));border:1px solid color-mix(in oklab,var(--__P__-danger) 20%,transparent);color:var(--__P__-fg-muted);font-size:var(--__P__-text-sm);display:flex;align-items:center;gap:var(--__P__-space-2)}.__P__-error span{min-width:0}.__P__-error button{margin-inline-start:auto;flex-shrink:0;border:0;background:none;padding:0;color:var(--__P__-accent-fg);font:inherit;font-size:var(--__P__-text-sm);font-weight:600;text-decoration:underline;white-space:nowrap;cursor:pointer}.__P__-history{flex:1;overflow-y:auto;padding:var(--__P__-space-2) var(--__P__-space-1) var(--__P__-space-3)}.__P__-history-footer{flex:none;padding:var(--__P__-space-2) var(--__P__-space-3) var(--__P__-space-3);border-top:1px solid var(--__P__-border);background:var(--__P__-surface)}.__P__-history-new{width:100%;display:flex;align-items:center;justify-content:center;gap:var(--__P__-space-2);padding:var(--__P__-space-2) var(--__P__-space-3);border:none;border-radius:var(--__P__-radius-md);background:var(--__P__-accent);color:var(--__P__-on-accent);cursor:pointer;font-size:var(--__P__-text-sm);font-weight:600;transition:filter var(--__P__-dur-quick) var(--__P__-ease-out),transform var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-history-new svg{width:16px;height:16px}.__P__-history-new:hover{filter:brightness(1.08)}.__P__-history-new:active{transform:translateY(1px)}.__P__-history-new:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-history-empty{flex:1;display:flex;align-items:center;justify-content:center;padding:40px 16px;color:var(--__P__-fg-muted);font-size:calc(14px * var(--__P__-text-scale));text-align:center}.__P__-history-group{display:flex;flex-direction:column;padding:0 var(--__P__-space-3)}.__P__-history-heading{font-size:var(--__P__-text-xs);font-weight:600;color:var(--__P__-fg-muted);padding:14px 4px 8px;text-transform:uppercase;letter-spacing:.04em}.__P__-history-card{display:flex;flex-direction:column;background:var(--__P__-surface);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-lg, 14px);overflow:hidden}.__P__-history-item{all:unset;display:flex;align-items:center;gap:var(--__P__-space-3);padding:12px var(--__P__-space-3);cursor:pointer;transition:background var(--__P__-dur-base) var(--__P__-ease)}.__P__-history-item+.__P__-history-item{border-top:1px solid var(--__P__-border)}.__P__-history-item:hover{background:var(--__P__-bg-elevated)}.__P__-history-item:focus-visible{background:var(--__P__-bg-elevated);outline:2px solid var(--__P__-focus);outline-offset:-2px}.__P__-history-avatar{flex:none;display:grid;place-items:center;width:36px;height:36px;border-radius:50%;background:color-mix(in oklab,var(--__P__-accent) 12%,transparent);color:var(--__P__-accent-fg)}.__P__-history-avatar svg{width:18px;height:18px}.__P__-history-body{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.__P__-history-row{display:flex;align-items:center;justify-content:space-between;gap:var(--__P__-space-2)}.__P__-history-title{flex:1;min-width:0;font-size:calc(14px * var(--__P__-text-scale));font-weight:500;color:var(--__P__-fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.__P__-history-time{flex:none;font-size:var(--__P__-text-xs);color:var(--__P__-fg-muted)}.__P__-history-preview{flex:1;min-width:0;font-size:var(--__P__-text-xs);color:var(--__P__-fg-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.__P__-history-dot{flex:none;width:8px;height:8px;border-radius:50%;background:var(--__P__-accent)}.__P__-history-item[data-unread=true] .__P__-history-title{font-weight:600}.__P__-history-item[data-closed=true] .__P__-history-title{color:var(--__P__-fg-muted)}.__P__-history-item-skeleton{cursor:default;pointer-events:none}.__P__-skeleton{display:block;border-radius:4px;background:linear-gradient(90deg,color-mix(in oklab,var(--__P__-fg) 9%,transparent) 30%,color-mix(in oklab,var(--__P__-fg) 17%,transparent),color-mix(in oklab,var(--__P__-fg) 9%,transparent) 70%);background-size:200% 100%;animation:__P__-skeleton-shimmer 1.8s ease-in-out infinite}.__P__-history-avatar.__P__-skeleton{border-radius:50%}.__P__-skeleton-heading{width:52px;height:8px}.__P__-skeleton-title{width:55%;height:12px}.__P__-skeleton-time{width:34px;height:10px}.__P__-skeleton-preview{width:80%;height:10px}@keyframes __P__-skeleton-shimmer{0%{background-position:200% 0}to{background-position:-200% 0}}@media(prefers-reduced-motion:reduce){.__P__-skeleton{animation:none}}.__P__-list-loading{margin:auto;padding:var(--__P__-space-6) var(--__P__-space-4);color:var(--__P__-fg-muted);font-size:var(--__P__-text-sm);text-align:center}.__P__-readonly-banner{display:flex;flex-direction:column;align-items:center;gap:10px;padding:14px 12px;margin:0 var(--__P__-space-3) var(--__P__-space-3);border-radius:var(--__P__-radius-md);background:var(--__P__-bg-elevated);color:var(--__P__-fg-muted);text-align:center;font-size:var(--__P__-text-sm)}.__P__-readonly-label{line-height:1.4}.__P__-readonly-cta{appearance:none;border:0;cursor:pointer;padding:var(--__P__-space-2) var(--__P__-space-4);border-radius:999px;background:var(--__P__-accent);color:var(--__P__-accent-text, #fff);font:inherit;font-weight:600;font-size:var(--__P__-text-sm);transition:filter var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-readonly-cta:hover,.__P__-readonly-cta:focus-visible{filter:brightness(1.1)}.__P__-operator-banner{display:flex;align-items:center;justify-content:center;gap:8px;margin:0 var(--__P__-space-3) var(--__P__-space-1);padding:8px 12px;border-radius:var(--__P__-radius-md);background:color-mix(in oklab,var(--__P__-bg-elevated),var(--__P__-accent) 6%);color:var(--__P__-fg-muted);font-size:var(--__P__-text-sm);line-height:1.3;text-align:center}.__P__-operator-pulse{flex:0 0 auto;width:8px;height:8px;border-radius:50%;background:var(--__P__-accent)}.__P__-operator-banner[data-mode=awaiting-operator] .__P__-operator-pulse{animation:__P__-operator-pulse 1.4s var(--__P__-ease-out) infinite}.__P__-cancel-operator-request{flex:0 0 auto;padding:0;border:0;background:none;color:var(--__P__-accent);font:inherit;font-weight:600;text-decoration:underline;text-underline-offset:2px;cursor:pointer}.__P__-cancel-operator-request:hover{opacity:.8}.__P__-cancel-operator-request:focus-visible{outline:2px solid var(--__P__-accent);outline-offset:2px;border-radius:var(--__P__-radius-sm)}@keyframes __P__-operator-pulse{0%,to{opacity:1;transform:scale(1)}50%{opacity:.4;transform:scale(.7)}}.__P__-readonly-cta:focus-visible{outline:2px solid var(--__P__-accent);outline-offset:2px}.__P__-composer-footer{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;padding:10px 16px;margin:0 var(--__P__-space-3);border-top:1px solid var(--__P__-border);text-align:center;font-size:calc(11px * var(--__P__-text-scale));line-height:1.4;color:var(--__P__-fg-muted)}.__P__-disclaimer{max-width:320px;margin:0 auto;opacity:.9;letter-spacing:.01em}.__P__-poweredby{display:inline-flex;align-items:center;justify-content:center;gap:6px;color:inherit;text-decoration:none;opacity:.7;transition:opacity var(--__P__-dur-base) var(--__P__-ease);font-size:calc(11px * var(--__P__-text-scale));letter-spacing:.02em}.__P__-poweredby:hover{opacity:1}.__P__-poweredby-logo{height:12px;width:auto;display:inline-block;vertical-align:middle}.__P__-poweredby-bar{flex:none;display:flex;align-items:center;justify-content:center;padding:6px 16px;border-top:1px solid var(--__P__-border);background:var(--__P__-bg-elevated)}.__P__-menu-wrap{position:relative;display:inline-flex}.__P__-menu{position:absolute;top:100%;inset-inline-end:0;margin-top:6px;min-width:200px;padding:6px;background:var(--__P__-bg);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-md);box-shadow:var(--__P__-shadow-panel);z-index:10;display:flex;flex-direction:column;gap:2px;animation:__P__-menu-in var(--__P__-dur-base) var(--__P__-ease)}@media(prefers-reduced-motion:reduce){.__P__-menu{animation:none}}@keyframes __P__-menu-in{0%{opacity:0;transform:translateY(-4px) scale(.98);transform-origin:top right}to{opacity:1;transform:none}}.__P__-menu-item{all:unset;display:flex;align-items:center;gap:10px;padding:8px 10px;font-size:var(--__P__-text-sm);color:var(--__P__-fg);border-radius:var(--__P__-radius-sm);cursor:pointer;user-select:none}.__P__-menu-item:hover{background:var(--__P__-bg-elevated)}.__P__-menu-item:focus-visible{background:var(--__P__-bg-elevated);outline:2px solid var(--__P__-focus);outline-offset:-2px}.__P__-menu-item[disabled]{opacity:.45;cursor:not-allowed}.__P__-menu-icon{display:inline-flex;width:16px;height:16px;color:var(--__P__-fg-muted)}.__P__-menu-icon svg{width:16px;height:16px}.__P__-menu-label{flex:1}.__P__-menu-check{display:inline-flex;color:var(--__P__-accent-fg)}.__P__-menu-check svg{width:14px;height:14px}.__P__-menu-item-segmented{cursor:default}.__P__-menu-item-segmented:hover{background:transparent}.__P__-segmented{display:inline-flex;gap:2px;padding:2px;background:var(--__P__-bg-elevated);border-radius:var(--__P__-radius-sm)}.__P__-segment{all:unset;min-width:26px;padding:3px 8px;font-size:var(--__P__-text-xs);font-weight:600;letter-spacing:.02em;text-align:center;color:var(--__P__-fg-muted);border-radius:calc(var(--__P__-radius-sm) - 2px);cursor:pointer;transition:color .12s ease,background .12s ease}.__P__-segment:hover{color:var(--__P__-fg)}.__P__-segment[data-on=true]{background:var(--__P__-bg);color:var(--__P__-accent-fg);box-shadow:var(--__P__-shadow-card)}.__P__-segment:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:-2px}.__P__-resize-grip{position:absolute;width:18px;height:18px;display:flex;align-items:center;justify-content:center;color:var(--__P__-fg-muted);opacity:.45;transition:opacity var(--__P__-dur-base) var(--__P__-ease);z-index:2;touch-action:none;user-select:none}.__P__-resize-grip:hover,.__P__-resize-grip:focus-visible{opacity:1}.__P__-resize-grip svg{width:10px;height:10px}.__P__-resize-grip--bottom-left{bottom:2px;left:2px;cursor:nesw-resize;transform:scaleX(-1)}.__P__-resize-grip--bottom-right{bottom:2px;right:2px;cursor:nwse-resize}.__P__-resize-grip--top-left{top:2px;left:2px;cursor:nwse-resize;transform:rotate(180deg)}.__P__-resize-grip--top-right{top:2px;right:2px;cursor:nesw-resize;transform:scaleY(-1)}:host(:not([data-mode="open"])) .__P__-resize-grip{display:none}.__P__-messenger{display:flex;flex-direction:column;overflow:hidden}.__P__-messenger-body,.__P__-messenger-pane{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}.__P__-messenger-pane[hidden]{display:none}@keyframes __P__-view-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.__P__-module{display:flex;flex-direction:column;height:100%;min-height:0}@media(prefers-reduced-motion:no-preference){.__P__-module,.__P__-history{animation:__P__-view-in .18s var(--__P__-ease-out)}}.__P__-module-scroll{flex:1;min-height:0;overflow-y:auto;padding:var(--__P__-space-3);display:flex;flex-direction:column;gap:var(--__P__-space-3)}.__P__-home{container-type:inline-size;background:radial-gradient(125% 65% at 88% 0%,color-mix(in srgb,#fff 16%,transparent),transparent 55%),linear-gradient(180deg,var(--__P__-accent) 0%,var(--__P__-accent) 22%,color-mix(in srgb,var(--__P__-accent) 28%,var(--__P__-surface)) 44%,var(--__P__-surface) 70%);border-radius:var(--__P__-radius-lg) var(--__P__-radius-lg) 0 0}.__P__-home-scroll{flex:1;min-height:0;overflow-y:auto;display:flex;flex-direction:column;background:transparent}.__P__-home-cards{display:flex;flex-direction:column;gap:var(--__P__-space-3);padding:4px 14px 16px}.__P__-module-pad{padding:var(--__P__-space-3) var(--__P__-space-3) 0}.__P__-module-empty{display:flex;flex-direction:column;align-items:center;gap:var(--__P__-space-3);padding:var(--__P__-space-8) var(--__P__-space-4);text-align:center;color:var(--__P__-fg-muted);font-size:var(--__P__-text-base)}.__P__-module-retry{padding:var(--__P__-space-2) var(--__P__-space-4);border:1px solid var(--__P__-border-strong);border-radius:var(--__P__-radius-sm);color:var(--__P__-fg);font-weight:600;cursor:pointer;transition:background var(--__P__-dur-quick) var(--__P__-ease-out),border-color var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-module-retry:hover{background:var(--__P__-hover);border-color:var(--__P__-accent)}.__P__-module-retry:active{background:var(--__P__-border)}.__P__-module-retry:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-help-list{flex:1;min-height:0;overflow-y:auto;padding-bottom:var(--__P__-space-3)}.__P__-help-group{display:flex;flex-direction:column}.__P__-help-section-title{position:sticky;top:0;z-index:1;margin:0;padding:var(--__P__-space-3) var(--__P__-space-5) var(--__P__-space-2);font-size:var(--__P__-text-xs);font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--__P__-fg-muted);background:var(--__P__-bg)}.__P__-help-card{margin:0 var(--__P__-space-3) var(--__P__-space-3);background:var(--__P__-surface);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius);overflow:hidden}.__P__-help-card .__P__-list-row{border-bottom:0;border-radius:0}.__P__-help-card .__P__-list-row+.__P__-list-row{border-top:1px solid var(--__P__-border)}.__P__-tabbar{display:flex;border-top:1px solid var(--__P__-border);background:var(--__P__-bg-elevated);flex-shrink:0}.__P__-tab{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--__P__-space-1);min-height:48px;padding:var(--__P__-space-2) var(--__P__-space-1);color:var(--__P__-fg-muted);font-size:var(--__P__-text-xs);font-weight:600;transition:color var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-tab:hover{color:var(--__P__-fg)}.__P__-tab[aria-selected=true]{color:var(--__P__-accent-fg)}.__P__-tab:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:-2px}.__P__-tab:active{background:var(--__P__-hover)}.__P__-tab-icon{position:relative;display:inline-flex}.__P__-tab-icon svg{width:22px;height:22px}.__P__-tab-badge{position:absolute;top:-2px;left:calc(50% + 6px);width:8px;height:8px;border-radius:50%;background:var(--__P__-accent);box-shadow:0 0 0 2px var(--__P__-bg-elevated)}.__P__-home-hero{flex-shrink:0;padding:var(--__P__-space-5) var(--__P__-space-5) var(--__P__-space-3);color:var(--__P__-on-accent);--__P__-focus: var(--__P__-on-accent)}.__P__-home-hero-top{display:flex;align-items:center;justify-content:space-between;gap:var(--__P__-space-3);min-height:32px}.__P__-home-brand{font-size:clamp(calc(12px * var(--__P__-text-scale)),calc(3.2cqi * var(--__P__-text-scale)),calc(14px * var(--__P__-text-scale)));font-weight:600;letter-spacing:.01em;color:color-mix(in srgb,#fff 82%,transparent);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.__P__-home-brand-spacer{flex:1}.__P__-home-hero-actions{display:flex;align-items:center;gap:var(--__P__-space-2);flex-shrink:0}.__P__-home-hero-actions .__P__-icon-btn{color:#fff}.__P__-home-hero-actions .__P__-icon-btn:hover{background:color-mix(in srgb,#fff 18%,transparent);color:#fff}.__P__-home-hero-actions .__P__-icon-btn:active{background:color-mix(in srgb,#fff 26%,transparent)}.__P__-home-greeting{margin:28px 0 0;font-family:var(--__P__-font-display);font-size:clamp(calc(19px * var(--__P__-text-scale)),calc(5.5cqi * var(--__P__-text-scale)),var(--__P__-text-2xl));font-weight:800;line-height:1.18;letter-spacing:-.01em;overflow-wrap:anywhere}.__P__-home-lead{margin:10px 0 0;font-family:var(--__P__-font-display);font-size:clamp(calc(15px * var(--__P__-text-scale)),calc(4.2cqi * var(--__P__-text-scale)),var(--__P__-text-xl));font-weight:600;line-height:1.25;letter-spacing:-.005em;color:color-mix(in srgb,var(--__P__-on-accent) 78%,transparent);overflow-wrap:anywhere}.__P__-home-avatars{display:flex}.__P__-home-avatar{width:30px;height:30px;border-radius:999px;overflow:hidden;margin-inline-start:-10px;border:2px solid color-mix(in srgb,#fff 92%,transparent);box-shadow:0 1px 3px #0000002e;background:var(--__P__-surface);display:inline-flex;align-items:center;justify-content:center;font-size:var(--__P__-text-xs);font-weight:700;color:var(--__P__-fg)}.__P__-home-avatar:first-child{margin-inline-start:0}.__P__-home-avatar img{width:100%;height:100%;object-fit:cover}.__P__-home-content{background:var(--__P__-surface);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius);box-shadow:var(--__P__-shadow-card);overflow:hidden}.__P__-home-content-title{padding:var(--__P__-space-4) var(--__P__-space-4) var(--__P__-space-3);font-size:var(--__P__-text-sm);font-weight:700}.__P__-home-content-list{display:flex;flex-direction:column;padding:0 var(--__P__-space-2) var(--__P__-space-2)}.__P__-home-content-list .__P__-list-row+.__P__-list-row{border-top:1px solid var(--__P__-border)}.__P__-home-card{display:block;width:100%;text-align:start;background:var(--__P__-surface);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius);padding:var(--__P__-space-4);box-shadow:var(--__P__-shadow-card)}.__P__-home-card[data-interactive=true]{cursor:pointer;transition:background var(--__P__-dur-quick) var(--__P__-ease-out),transform var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-home-card[data-interactive=true]:hover{background:var(--__P__-bg-elevated)}.__P__-home-card[data-interactive=true]:active{transform:translateY(1px)}.__P__-home-card[data-interactive=true]:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-home-recent-row{display:flex;align-items:center;gap:var(--__P__-space-3)}.__P__-home-recent-avatar{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;flex-shrink:0;border-radius:999px;background:color-mix(in oklch,var(--__P__-accent) 14%,transparent);color:var(--__P__-accent-fg)}.__P__-home-recent-avatar svg{width:20px;height:20px}.__P__-home-recent-body{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}.__P__-home-recent-title{font-weight:600;font-size:calc(14px * var(--__P__-text-scale))}.__P__-home-recent-preview{color:var(--__P__-fg-muted);font-size:var(--__P__-text-sm);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.__P__-home-recent-dot{width:8px;height:8px;border-radius:999px;background:var(--__P__-accent);flex-shrink:0}.__P__-home-recent-row[data-unread=true] .__P__-home-recent-title{font-weight:700}.__P__-home-status{display:flex;align-items:center;gap:var(--__P__-space-3)}.__P__-home-status-icon svg{width:22px;height:22px;color:var(--__P__-success)}.__P__-home-status[data-level=degraded] .__P__-home-status-icon svg{color:var(--__P__-warning)}.__P__-home-status[data-level=down] .__P__-home-status-icon svg{color:var(--__P__-danger)}.__P__-home-status-text{font-weight:600;font-size:calc(14px * var(--__P__-text-scale))}.__P__-home-search{display:flex;align-items:center;gap:var(--__P__-space-2);width:100%;padding:var(--__P__-space-3) var(--__P__-space-4);border-radius:var(--__P__-radius);border:1px solid var(--__P__-border);background:var(--__P__-surface);text-align:start}.__P__-home-search[data-input=true]{background:var(--__P__-bg-elevated)}.__P__-home-search:hover{border-color:var(--__P__-border-strong)}.__P__-home-search:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-home-search[data-input=true]:focus-within{outline:none;border-color:var(--__P__-focus)}.__P__-home-search-text{flex:1;color:var(--__P__-fg-muted);font-size:calc(14px * var(--__P__-text-scale))}.__P__-home-search-input{flex:1;border:0;background:transparent;font-size:calc(14px * var(--__P__-text-scale));color:var(--__P__-fg);outline:none}.__P__-home-search-input:focus-visible{outline:none}.__P__-home-search-icon svg{width:18px;height:18px;color:var(--__P__-accent-fg)}.__P__-list-row{display:flex;align-items:center;gap:var(--__P__-space-3);width:100%;min-height:44px;text-align:start;padding:var(--__P__-space-3) var(--__P__-space-2);border-radius:var(--__P__-radius-sm)}.__P__-list-row:hover{background:var(--__P__-hover)}.__P__-list-row:active{background:var(--__P__-border)}.__P__-list-row:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:-2px}.__P__-list-row-body{display:flex;flex-direction:column;min-width:0;flex:1}.__P__-list-row-title{font-weight:600;font-size:var(--__P__-text-md);line-height:1.35}.__P__-list-row-sub{color:var(--__P__-fg-muted);font-size:var(--__P__-text-sm);margin-top:var(--__P__-space-1);line-height:1.45;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.__P__-list-row-chevron svg{width:18px;height:18px;color:var(--__P__-accent-fg);flex-shrink:0}.__P__-back-header{display:flex;align-items:center;gap:var(--__P__-space-2);padding:10px 12px;border-bottom:1px solid var(--__P__-border);flex-shrink:0}.__P__-back-title{flex:1;text-align:center;font-size:var(--__P__-text-md);font-weight:700;margin:0;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.__P__-back-spacer{width:32px;height:1px}.__P__-history>*,.__P__-home-scroll>*,.__P__-module-scroll>*,.__P__-help-list>*,.__P__-history-footer>*,.__P__-module-pad{width:100%;max-width:var(--__P__-conversation-max, 768px);margin-inline:auto}.__P__-header,.__P__-back-header{padding-inline:max(12px,calc((100% - var(--__P__-conversation-max, 768px)) / 2))}.__P__-tabbar{padding-inline:max(0px,calc((100% - var(--__P__-conversation-max, 768px)) / 2))}.__P__-content{display:flex;flex-direction:column;gap:14px;width:100%;max-width:68ch;margin:0 auto}.__P__-content-hero{width:100%;border-radius:var(--__P__-radius)}.__P__-content-subtitle{color:var(--__P__-fg-muted);margin:0}.__P__-content-frame{flex:1;min-height:0;width:100%;border:0;background:#fff}.__P__-news-list{display:flex;flex-direction:column;gap:var(--__P__-space-3)}.__P__-news-card{display:block;width:100%;text-align:start;border:1px solid var(--__P__-border);border-radius:var(--__P__-radius);overflow:hidden;background:var(--__P__-surface)}.__P__-news-card{transition:background var(--__P__-dur-quick) var(--__P__-ease-out),transform var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-news-card:hover{background:var(--__P__-bg-elevated)}.__P__-news-card:active{transform:translateY(1px)}.__P__-news-card:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}.__P__-news-hero{width:100%;display:block}.__P__-news-body{display:flex;flex-direction:column;gap:6px;padding:14px 16px}.__P__-news-title{font-weight:700;font-size:var(--__P__-text-md)}.__P__-news-summary{color:var(--__P__-fg-muted);font-size:calc(14px * var(--__P__-text-scale));display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.__P__-modules-empty{display:flex;align-items:center;justify-content:center;position:relative}.__P__-modules-empty-close{position:absolute;top:12px;inset-inline-end:12px}.__P__-modules-empty-text{color:var(--__P__-fg-muted);font-size:var(--__P__-text-base)}.__P__-form{display:flex;flex-direction:column;gap:var(--__P__-space-4)}.__P__-field{display:flex;flex-direction:column;gap:6px}.__P__-field-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:var(--__P__-space-2)}.__P__-field-label{font-size:var(--__P__-text-sm);font-weight:600;color:var(--__P__-fg)}.__P__-field-req{color:var(--__P__-danger)}.__P__-field-type{flex-shrink:0;align-self:center;margin-inline-start:auto;border:1px solid var(--__P__-border);border-radius:5px;background:color-mix(in oklab,var(--__P__-fg-muted) 9%,transparent);padding:1px 7px;font-size:var(--__P__-text-xs);font-weight:600;color:var(--__P__-fg-muted);white-space:nowrap}.__P__-field-input{width:100%;min-width:0;max-width:100%;box-sizing:border-box;padding:10px var(--__P__-space-3);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-md);background:var(--__P__-bg);color:var(--__P__-fg);font:inherit;font-size:var(--__P__-text-sm);resize:vertical;transition:border-color var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-field-input:focus-visible{outline:none;border-color:var(--__P__-accent)}.__P__-field[data-invalid=true] .__P__-field-input{border-color:var(--__P__-danger)}.__P__-field-input[type=date],.__P__-field-input[type=time]{appearance:none;-webkit-appearance:none}@media(pointer:coarse){.__P__-textarea,.__P__-home-search-input,.__P__-field-input{font-size:max(16px,calc(16px * var(--__P__-text-scale)))}}.__P__-field-hint{font-size:var(--__P__-text-xs);color:var(--__P__-fg-muted)}.__P__-field-error{font-size:var(--__P__-text-xs);color:var(--__P__-danger)}.__P__-field-choices{display:flex;flex-direction:column;gap:10px;padding-top:2px}.__P__-choice{display:flex;align-items:flex-start;gap:10px;font-size:var(--__P__-text-sm);color:var(--__P__-fg);cursor:pointer}.__P__-choice input{margin-top:2px;accent-color:var(--__P__-accent)}.__P__-form-actions{display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:var(--__P__-space-2);margin-top:var(--__P__-space-2)}.__P__-form-hint{flex:1 1 auto;min-width:6rem;margin-inline-end:auto;font-size:var(--__P__-text-xs);color:var(--__P__-fg-muted)}.__P__-form-submit{padding:var(--__P__-space-2) var(--__P__-space-4);border:none;border-radius:var(--__P__-radius-md);background:var(--__P__-accent);color:var(--__P__-accent-text, #fff);font:inherit;font-weight:600;font-size:var(--__P__-text-sm);white-space:nowrap;flex-shrink:0;cursor:pointer;transition:filter var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-form-submit:hover:not(:disabled){filter:brightness(1.06)}.__P__-form-submit:disabled{opacity:.6;cursor:default}.__P__-form-skip{padding:var(--__P__-space-2) var(--__P__-space-4);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-md);background:transparent;color:var(--__P__-fg-muted);font:inherit;font-size:var(--__P__-text-sm);white-space:nowrap;flex-shrink:0;cursor:pointer;transition:background var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-form-skip:hover:not(:disabled){background:var(--__P__-bg-elevated)}@media(max-width:640px){.__P__-form-hint{flex-basis:100%;margin-inline-end:0;font-size:var(--__P__-text-xs)}.__P__-form-submit,.__P__-form-skip{flex:1 1 0;text-align:center}}.__P__-form-gate{display:flex;flex-direction:column;gap:var(--__P__-space-3);padding:var(--__P__-space-4);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-md);background:var(--__P__-bg-elevated)}.__P__-form-gate-title{margin:0;font-size:var(--__P__-text-base);font-weight:700;color:var(--__P__-fg)}.__P__-form-gate-desc{margin:0 0 var(--__P__-space-1);font-size:var(--__P__-text-sm);color:var(--__P__-fg-muted)}.__P__-form-done{display:flex;align-items:center;justify-content:center;gap:6px;padding:6px 12px;border:1px dashed var(--__P__-border);border-radius:999px;align-self:center;font-size:var(--__P__-text-xs);font-weight:600;color:var(--__P__-fg-muted)}.__P__-form-done svg{width:14px;height:14px;color:var(--__P__-success, #22c55e)}.__P__-form-done[data-outcome=skipped] svg{color:var(--__P__-fg-muted)}.__P__-form-done-fill{border:0;background:none;padding:0 2px;cursor:pointer;font:inherit;font-weight:600;color:var(--__P__-accent-fg)}.__P__-form-done-fill:hover{text-decoration:underline}details.__P__-form-done{display:block;padding:0;border-radius:var(--__P__-radius-md)}details[open].__P__-form-done{width:min(100%,420px);background:var(--__P__-surface)}.__P__-form-done-summary{display:flex;align-items:center;justify-content:center;gap:6px;padding:8px 12px;cursor:pointer;list-style:none}.__P__-form-done-summary::-webkit-details-marker{display:none}.__P__-form-done-summary>svg:last-child{color:var(--__P__-fg-muted);transition:transform .15s var(--__P__-ease)}details[open]>.__P__-form-done-summary>svg:last-child{transform:rotate(90deg)}.__P__-form-answers{margin:0;padding:var(--__P__-space-2) var(--__P__-space-3) var(--__P__-space-3);display:grid;gap:var(--__P__-space-3);text-align:start}.__P__-form-answer{display:grid;gap:6px}.__P__-form-answer dt{font-size:var(--__P__-text-sm);font-weight:600;color:var(--__P__-fg)}.__P__-form-answer dd{margin:0;padding:10px var(--__P__-space-3);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-md);background:var(--__P__-bg);font-size:var(--__P__-text-sm);font-weight:400;color:var(--__P__-fg);overflow-wrap:anywhere}.__P__-toolui{margin-block:var(--__P__-space-3);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-lg, 14px);background:var(--__P__-bg-elevated);font-size:var(--__P__-text-sm)}.__P__-toolui:not(.__P__-toolui-collapsible){display:flex;flex-direction:column;gap:var(--__P__-space-3);padding:var(--__P__-space-4)}.__P__-toolui-group{display:flex;flex-direction:column;gap:var(--__P__-space-3);margin-block:var(--__P__-space-3)}.__P__-toolui-group>.__P__-toolui{margin-block:0}.__P__-toolui-stale{opacity:.7}details.__P__-toolui-collapsible>summary{display:flex;align-items:center;gap:var(--__P__-space-2);padding:var(--__P__-space-3) var(--__P__-space-4);cursor:pointer;list-style:none;-webkit-tap-highlight-color:transparent;user-select:none}details.__P__-toolui-collapsible>summary::-webkit-details-marker{display:none}details.__P__-toolui-collapsible[open]>summary{border-bottom:1px solid var(--__P__-border)}details.__P__-toolui-collapsible>.__P__-toolui-section{margin:var(--__P__-space-4)}details.__P__-toolui-collapsible>.__P__-toolui-section~.__P__-toolui-section{margin-top:calc(-1 * var(--__P__-space-2))}.__P__-toolui-name-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.__P__-toolui-chevron{display:inline-flex;color:var(--__P__-fg-muted);transition:transform var(--__P__-dur-quick) var(--__P__-ease-out)}details.__P__-toolui-collapsible>summary .__P__-toolui-status{margin-inline-start:auto}.__P__-toolui-chevron svg{width:16px;height:16px}details.__P__-toolui-collapsible[open]>summary .__P__-toolui-chevron{transform:rotate(180deg)}.__P__-toolui-badge,.__P__-toolui-name-pill,.__P__-toolui-q-pill{--__P__-pill: var(--__P__-fg-muted);display:inline-flex;min-width:0;align-items:center;gap:5px;padding:3px 7px;border-radius:5px;border:1px solid var(--__P__-border);background:color-mix(in oklab,var(--__P__-fg-muted) 9%,transparent);color:var(--__P__-pill);font-size:var(--__P__-text-xs);font-weight:600;white-space:nowrap}.__P__-toolui-badge svg,.__P__-toolui-name-pill svg,.__P__-toolui-q-pill svg{flex-shrink:0;width:14px;height:14px}.__P__-toolui-status-icon{display:inline-flex}.__P__-toolui-name-pill{--__P__-pill: oklch(.68 .13 233)}.__P__-toolui-q-pill{--__P__-pill: oklch(.66 .12 195)}.__P__-toolui-status[data-status=completed]{--__P__-pill: var(--__P__-success, #16a34a)}.__P__-toolui-status[data-status=responded]{--__P__-pill: oklch(.62 .15 255)}.__P__-toolui-status[data-status=awaiting]{--__P__-pill: var(--__P__-warning, #f59e0b)}.__P__-toolui-status[data-status=denied]{--__P__-pill: oklch(.66 .16 45)}.__P__-toolui-status[data-status=error]{--__P__-pill: var(--__P__-danger, #dc2626)}.__P__-toolui-status[data-status=superseded]{--__P__-pill: var(--__P__-fg-muted)}@supports (color: oklch(from red l c h)){.__P__-toolui-badge,.__P__-toolui-name-pill,.__P__-toolui-q-pill{color:oklch(from var(--__P__-pill) clamp(var(--__P__-pill-l-min),l,var(--__P__-pill-l-max)) c h)}}.__P__-toolui-head{display:flex;align-items:center;flex-wrap:wrap;gap:var(--__P__-space-2)}.__P__-toolui-head-end{display:inline-flex;align-items:center;gap:var(--__P__-space-2);margin-inline-start:auto}.__P__-toolui-collapse-body{display:flex;flex-direction:column;gap:var(--__P__-space-3);padding:var(--__P__-space-4)}.__P__-toolui-summary{display:flex;flex-direction:column;gap:var(--__P__-space-3)}.__P__-toolui-collapse-body>.__P__-form{gap:var(--__P__-space-3)}.__P__-toolui-collapse-body>.__P__-form>.__P__-field,.__P__-toolui-summary>.__P__-field{padding:10px var(--__P__-space-3);border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-md);background:color-mix(in oklab,var(--__P__-bg) 80%,transparent);line-height:1.5}.__P__-toolui-collapse-body>.__P__-form>.__P__-field{gap:var(--__P__-space-2)}.__P__-toolui-summary>.__P__-field{gap:var(--__P__-space-1)}.__P__-toolui-summary .__P__-field-label{color:var(--__P__-fg-muted)}.__P__-toolui-answer{margin:0;font-size:var(--__P__-text-sm);color:var(--__P__-fg-muted);overflow-wrap:anywhere;white-space:pre-wrap}.__P__-toolui-footer{display:flex;align-items:center;justify-content:space-between;gap:var(--__P__-space-3);margin-inline:calc(-1 * var(--__P__-space-4));padding:var(--__P__-space-3) var(--__P__-space-4) 0;border-top:1px solid var(--__P__-border)}.__P__-toolui-options-toggle{display:inline-flex;align-items:center;gap:4px;border:0;background:transparent;padding:0;cursor:pointer;font-size:var(--__P__-text-xs);font-weight:600;color:var(--__P__-fg-muted);transition:color var(--__P__-dur-quick) var(--__P__-ease)}.__P__-toolui-options-toggle:hover{color:var(--__P__-fg)}.__P__-toolui-options-chevron{display:inline-flex;transition:transform var(--__P__-dur-quick) var(--__P__-ease-out)}.__P__-toolui-options-chevron svg{width:14px;height:14px}.__P__-toolui-options-chevron.__P__-open{transform:rotate(180deg)}.__P__-toolui-desc{margin:0;padding:var(--__P__-space-3);border-radius:var(--__P__-radius-md);background:var(--__P__-bg);border:1px solid var(--__P__-border);color:var(--__P__-fg-muted);line-height:1.5}.__P__-toolui-section{display:flex;flex-direction:column;gap:8px;padding:var(--__P__-space-3);border-radius:var(--__P__-radius-md);background:var(--__P__-bg);border:1px solid var(--__P__-border)}.__P__-toolui:not(.__P__-toolui-collapsible) .__P__-toolui-section,.__P__-toolui:not(.__P__-toolui-collapsible) .__P__-toolui-desc{padding:0;background:none;border:0;border-radius:0}.__P__-toolui-label{font-size:var(--__P__-text-xs);font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--__P__-fg-muted)}.__P__-toolui-code{margin:0;max-height:240px;overflow:auto;color:var(--__P__-fg);font-family:var(--__P__-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);font-size:var(--__P__-text-xs);line-height:1.5;white-space:pre-wrap;word-break:break-word}.__P__-toolui-code[data-error=true]{color:var(--__P__-danger, #dc2626)}.__P__-toolui-body{gap:6px}.__P__-toolui-prompt{margin:0;font-weight:600;color:var(--__P__-fg);overflow-wrap:anywhere}.__P__-toolui-subtle{margin:0;font-size:var(--__P__-text-xs);color:var(--__P__-fg-muted);line-height:1.5}.__P__-toolui-actions{display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:var(--__P__-space-2);margin-top:var(--__P__-space-2)}:host([dir="rtl"]) .__P__-icon-dir{transform:scaleX(-1)}:host([dir="rtl"]) .__P__-field-input[type=date],:host([dir="rtl"]) .__P__-field-input[type=time]{position:relative;text-align:right;padding-left:34px}:host([dir="rtl"]) .__P__-field-input[type=date]::-webkit-datetime-edit,:host([dir="rtl"]) .__P__-field-input[type=time]::-webkit-datetime-edit{text-align:right}:host([dir="rtl"]) .__P__-field-input[type=date]::-webkit-calendar-picker-indicator,:host([dir="rtl"]) .__P__-field-input[type=time]::-webkit-calendar-picker-indicator{position:absolute;left:var(--__P__-space-3);margin:0}
|
|
4
4
|
`,`.__P__-standalone-page{margin:0;height:100vh;background:var(--__P__-bg, #fff);display:grid;place-items:stretch}
|
|
5
5
|
`,`:host([data-mode="page"]){min-height:0}:host([data-mode="page"]) .__P__-page-shell{display:grid;grid-template-columns:280px 1fr;width:100%;height:100%;min-height:0;background:var(--__P__-bg);color:var(--__P__-fg);transition:grid-template-columns var(--__P__-dur-base) var(--__P__-ease-in-out)}:host([data-mode="page"]) .__P__-page-shell[data-sidebar-collapsed=true]{grid-template-columns:48px 1fr}:host([data-mode="page"]) .__P__-page-chat{display:flex;flex-direction:column;min-width:0;min-height:0;overflow:hidden}:host([data-mode="page"]) .__P__-anchor{position:static;inset:auto;padding:0;align-items:stretch;width:100%;height:100%;min-width:0;min-height:0;flex:1 1 0}:host([data-mode="page"]) .__P__-panel{width:100%;height:100%;min-width:0;min-height:0;max-width:none;max-height:none;border-radius:0;border:0;box-shadow:none;animation:none}:host([data-mode="page"]) .__P__-sidebar{border-inline-end:1px solid var(--__P__-border);display:flex;flex-direction:column;overflow:hidden;background:var(--__P__-surface)}:host([data-mode="page"]) .__P__-sidebar-header{padding:var(--__P__-space-4) var(--__P__-space-5);border-bottom:1px solid var(--__P__-border);display:flex;align-items:center;justify-content:space-between;gap:var(--__P__-space-2);min-height:56px;box-sizing:border-box}:host([data-mode="page"]) .__P__-sidebar[data-collapsed=true] .__P__-sidebar-header{padding:var(--__P__-space-4) var(--__P__-space-2);justify-content:center}:host([data-mode="page"]) .__P__-sidebar[data-collapsed=true] .__P__-sidebar-logo,:host([data-mode="page"]) .__P__-sidebar[data-collapsed=true] .__P__-sidebar-title{display:none}:host([data-mode="page"]) .__P__-sidebar-toggle{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:1px solid var(--__P__-border);border-radius:6px;background:transparent;color:var(--__P__-fg);cursor:pointer;transition:background .12s,border-color .12s}:host([data-mode="page"]) .__P__-sidebar-toggle:hover{background:var(--__P__-hover);border-color:var(--__P__-accent)}:host([data-mode="page"]) .__P__-sidebar-toggle:focus-visible{outline:2px solid var(--__P__-accent);outline-offset:2px}:host([data-mode="page"]) .__P__-sidebar-logo{height:32px;display:block}:host([data-mode="page"]) .__P__-sidebar-title{font-size:var(--__P__-text-md);font-weight:600}:host([data-mode="page"]) .__P__-sidebar-section{padding:var(--__P__-space-3) var(--__P__-space-4);border-bottom:1px solid var(--__P__-border)}:host([data-mode="page"]) .__P__-sidebar-nav{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px}:host([data-mode="page"]) .__P__-sidebar-nav-item{display:flex;align-items:center;gap:10px;padding:var(--__P__-space-2) var(--__P__-space-3);border-radius:var(--__P__-radius-sm);color:var(--__P__-fg);text-decoration:none;font-size:calc(14px * var(--__P__-text-scale));transition:background var(--__P__-dur-quick) var(--__P__-ease-out)}:host([data-mode="page"]) .__P__-sidebar-nav-item:hover{background:var(--__P__-hover)}:host([data-mode="page"]) .__P__-sidebar-nav-item:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:-2px}:host([data-mode="page"]) .__P__-sidebar-cards{display:grid;grid-template-columns:1fr;gap:var(--__P__-space-2)}:host([data-mode="page"]) .__P__-sidebar-card{display:block;padding:10px 12px;border:1px solid var(--__P__-border);border-radius:var(--__P__-radius-sm);text-decoration:none;color:var(--__P__-fg);transition:border-color var(--__P__-dur-quick) var(--__P__-ease-out)}:host([data-mode="page"]) .__P__-sidebar-card:hover{border-color:var(--__P__-accent)}:host([data-mode="page"]) .__P__-sidebar-card:focus-visible{outline:2px solid var(--__P__-focus);outline-offset:2px}:host([data-mode="page"]) .__P__-sidebar-card-label{font-weight:600;font-size:calc(14px * var(--__P__-text-scale))}:host([data-mode="page"]) .__P__-sidebar-card-desc{font-size:var(--__P__-text-xs);color:var(--__P__-muted);margin-top:2px}:host([data-mode="page"]) .__P__-sidebar-conversations{flex:1 1 auto;overflow-y:auto;padding:var(--__P__-space-3) var(--__P__-space-4)}:host([data-mode="page"]) .__P__-page-chat{display:flex;flex-direction:column;overflow:hidden}@media(max-width:768px){:host([data-mode="page"]) .__P__-page-shell{grid-template-columns:1fr}:host([data-mode="page"]) .__P__-sidebar{display:none}}
|
|
6
6
|
`].join(`
|
|
7
|
-
`).replace(/__P__/g,`helpai`).replaceAll(`__BRAND_ACCENT_TEXT__`,`#FFFFFF`).replaceAll(`__BRAND_ACCENT__`,`#5B5BD6`).replaceAll(`__BRAND_RADIUS__`,`12px`).replaceAll(`__BRAND_FONT__`,`Inter, system-ui, -apple-system, 'Segoe UI', sans-serif`),gt=I.scope(`mount`),_t=new WeakMap,vt={floating:`all: initial; position: fixed; z-index: 2147483600;`,flow:`all: initial; display: block; position: relative; width: 100%; height: 100%; z-index: 1; contain: size;`,viewport:`all: initial; display: block; position: absolute; inset: 0; width: 100%; height: 100%; z-index: 1;`};function yt(e,t){e.style.cssText=vt[t]}function bt(e){return e===`floating`||e===`modal`||e===`drawer`?`floating`:e===`standalone`||e===`page`?`viewport`:`flow`}function xt(e={}){let t=e.position??`flow`;gt.debug(`createShadowMount`,{position:t,hasTarget:!!e.target,hasHost:!!e.existingHost});let n=`${b.cssPrefix}-chat-host`;typeof customElements<`u`&&!customElements.get(n)&&customElements.define(n,class extends HTMLElement{});let r;e.existingHost?r=e.existingHost:(r=document.createElement(n),(e.target??document.body).appendChild(r)),r.setAttribute(`data-brand`,b.id),r.style.cssText=vt[t];let i=r.shadowRoot??r.attachShadow({mode:`open`}),a=r.ownerDocument;if(!St(i,a)){let e=a.createElement(`style`);e.textContent=ht,i.appendChild(e)}let o=document.createElement(`div`);return o.className=`${b.cssPrefix}-app`,i.appendChild(o),{appRoot:o,destroy:()=>r.remove(),hostElement:r,shadowRoot:i}}function St(e,t){if(!(`adoptedStyleSheets`in e))return!1;let n=t.defaultView;if(!n||typeof n.CSSStyleSheet!=`function`)return!1;let r=_t.get(t);if(!r)try{r=new n.CSSStyleSheet,r.replaceSync(ht),_t.set(t,r)}catch{return!1}try{return e.adoptedStyleSheets=[r],!0}catch{return!1}}function Ct(e,t){let n=b.cssPrefix;t.accent&&e.style.setProperty(`--${n}-accent-user`,t.accent),t.accentText&&e.style.setProperty(`--${n}-accent-text-user`,t.accentText),t.radius&&e.style.setProperty(`--${n}-radius`,t.radius),t.fontFamily&&e.style.setProperty(`--${n}-font`,t.fontFamily),t.contentMaxWidth&&e.style.setProperty(`--${n}-conversation-max`,t.contentMaxWidth)}function wt(e,t){e.dataset.theme=t}function Tt(e,t){let n=b.cssPrefix;t.width!==void 0&&e.style.setProperty(`--${n}-panel-w`,t.width),t.height!==void 0&&e.style.setProperty(`--${n}-panel-h`,t.height),t.expanded?.width!==void 0&&e.style.setProperty(`--${n}-expanded-w`,t.expanded.width),t.expanded?.height!==void 0&&e.style.setProperty(`--${n}-expanded-h`,t.expanded.height),t.inset!==void 0&&e.style.setProperty(`--${n}-panel-inset`,t.inset)}function Et(e,t){e.dataset.position=t}function Dt(e,t){e.dataset.mode=t}function Ot(e,t){wt(e,t.themeMode),Ct(e,t.themeOverrides),Et(e,t.position),Tt(e,t.size)}function kt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function At(e){return kt(e)}function jt(e){return!(!kt(e)||e.navigation!==void 0&&!Array.isArray(e.navigation)||e.linkCards!==void 0&&!Array.isArray(e.linkCards))}function Mt(e){return`${b.cssPrefix}:${e}`}function Nt(e,t){let n=Object.entries(t).map(([t,n])=>{let r=Mt(t),i=e=>n(e.detail);return e.addEventListener(r,i),[r,i]});return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}function Pt(e,t,n){return e===`page`?`page`:e===`standalone`?`standalone`:e===`inline`?t===`fullscreen`?`fullscreen`:`inline`:e===`modal`||e===`drawer`?n?t===`fullscreen`?`fullscreen`:e:`closed`:n?t===`fullscreen`?`fullscreen`:t===`expanded`?`expanded`:`open`:`closed`}function Ft(e,t,n){if(e===`standalone`||e===`page`)return`fullscreen`;let r=t.initialSize;return r===`expanded`||r===`fullscreen`||r===`normal`?r:n>0&&n<640?`fullscreen`:n>=(t.autoSizeBreakpoint??900)?`expanded`:`normal`}function It(e,t,n,r=null){return{panelOpen:e.mode===`inline`||e.mode===`standalone`||e.mode===`page`||(n??!e.startMinimized),panelSize:e.mode!==`standalone`&&e.mode!==`page`&&e.mode!==`inline`&&r?r:Ft(e.mode,e.size,t)}}function Lt(){return typeof window>`u`?0:window.innerWidth}function Rt(e){if(!e.aiAgentDeploymentId)throw Error(`aiAgentDeploymentId is required`);return{headers(){let t={"x-ai-agent-deployment-id":e.aiAgentDeploymentId};return e.publicKey&&(t[e.publicKeyHeader??`x-public-key`]=e.publicKey),t}}}function zt(e,t){return new Promise(n=>{if(t?.aborted)return n();let r=setTimeout(a,e),i=()=>a();t?.addEventListener(`abort`,i,{once:!0});function a(){clearTimeout(r),t?.removeEventListener(`abort`,i),n()}})}const Bt=`1.3.
|
|
7
|
+
`).replace(/__P__/g,`helpai`).replaceAll(`__BRAND_ACCENT_TEXT__`,`#FFFFFF`).replaceAll(`__BRAND_ACCENT__`,`#5B5BD6`).replaceAll(`__BRAND_RADIUS__`,`12px`).replaceAll(`__BRAND_FONT__`,`Inter, system-ui, -apple-system, 'Segoe UI', sans-serif`),gt=I.scope(`mount`),_t=new WeakMap,vt={floating:`all: initial; position: fixed; z-index: 2147483600;`,flow:`all: initial; display: block; position: relative; width: 100%; height: 100%; z-index: 1; contain: size;`,viewport:`all: initial; display: block; position: absolute; inset: 0; width: 100%; height: 100%; z-index: 1;`};function yt(e,t){e.style.cssText=vt[t]}function bt(e){return e===`floating`||e===`modal`||e===`drawer`?`floating`:e===`standalone`||e===`page`?`viewport`:`flow`}function xt(e={}){let t=e.position??`flow`;gt.debug(`createShadowMount`,{position:t,hasTarget:!!e.target,hasHost:!!e.existingHost});let n=`${b.cssPrefix}-chat-host`;typeof customElements<`u`&&!customElements.get(n)&&customElements.define(n,class extends HTMLElement{});let r;e.existingHost?r=e.existingHost:(r=document.createElement(n),(e.target??document.body).appendChild(r)),r.setAttribute(`data-brand`,b.id),r.style.cssText=vt[t];let i=r.shadowRoot??r.attachShadow({mode:`open`}),a=r.ownerDocument;if(!St(i,a)){let e=a.createElement(`style`);e.textContent=ht,i.appendChild(e)}let o=document.createElement(`div`);return o.className=`${b.cssPrefix}-app`,i.appendChild(o),{appRoot:o,destroy:()=>r.remove(),hostElement:r,shadowRoot:i}}function St(e,t){if(!(`adoptedStyleSheets`in e))return!1;let n=t.defaultView;if(!n||typeof n.CSSStyleSheet!=`function`)return!1;let r=_t.get(t);if(!r)try{r=new n.CSSStyleSheet,r.replaceSync(ht),_t.set(t,r)}catch{return!1}try{return e.adoptedStyleSheets=[r],!0}catch{return!1}}function Ct(e,t){let n=b.cssPrefix;t.accent&&e.style.setProperty(`--${n}-accent-user`,t.accent),t.accentText&&e.style.setProperty(`--${n}-accent-text-user`,t.accentText),t.radius&&e.style.setProperty(`--${n}-radius`,t.radius),t.fontFamily&&e.style.setProperty(`--${n}-font`,t.fontFamily),t.contentMaxWidth&&e.style.setProperty(`--${n}-conversation-max`,t.contentMaxWidth)}function wt(e,t){e.dataset.theme=t}function Tt(e,t){let n=b.cssPrefix;t.width!==void 0&&e.style.setProperty(`--${n}-panel-w`,t.width),t.height!==void 0&&e.style.setProperty(`--${n}-panel-h`,t.height),t.expanded?.width!==void 0&&e.style.setProperty(`--${n}-expanded-w`,t.expanded.width),t.expanded?.height!==void 0&&e.style.setProperty(`--${n}-expanded-h`,t.expanded.height),t.inset!==void 0&&e.style.setProperty(`--${n}-panel-inset`,t.inset)}function Et(e,t){e.dataset.position=t}function Dt(e,t){e.dataset.mode=t}function Ot(e,t){wt(e,t.themeMode),Ct(e,t.themeOverrides),Et(e,t.position),Tt(e,t.size)}function kt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function At(e){return kt(e)}function jt(e){return!(!kt(e)||e.navigation!==void 0&&!Array.isArray(e.navigation)||e.linkCards!==void 0&&!Array.isArray(e.linkCards))}function Mt(e){return`${b.cssPrefix}:${e}`}function Nt(e,t){let n=Object.entries(t).map(([t,n])=>{let r=Mt(t),i=e=>n(e.detail);return e.addEventListener(r,i),[r,i]});return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}function Pt(e,t,n){return e===`page`?`page`:e===`standalone`?`standalone`:e===`inline`?t===`fullscreen`?`fullscreen`:`inline`:e===`modal`||e===`drawer`?n?t===`fullscreen`?`fullscreen`:e:`closed`:n?t===`fullscreen`?`fullscreen`:t===`expanded`?`expanded`:`open`:`closed`}function Ft(e,t,n){if(e===`standalone`||e===`page`)return`fullscreen`;let r=t.initialSize;return r===`expanded`||r===`fullscreen`||r===`normal`?r:n>0&&n<640?`fullscreen`:n>=(t.autoSizeBreakpoint??900)?`expanded`:`normal`}function It(e,t,n,r=null){return{panelOpen:e.mode===`inline`||e.mode===`standalone`||e.mode===`page`||(n??!e.startMinimized),panelSize:e.mode!==`standalone`&&e.mode!==`page`&&e.mode!==`inline`&&r?r:Ft(e.mode,e.size,t)}}function Lt(){return typeof window>`u`?0:window.innerWidth}function Rt(e){if(!e.aiAgentDeploymentId)throw Error(`aiAgentDeploymentId is required`);return{headers(){let t={"x-ai-agent-deployment-id":e.aiAgentDeploymentId};return e.publicKey&&(t[e.publicKeyHeader??`x-public-key`]=e.publicKey),t}}}function zt(e,t){return new Promise(n=>{if(t?.aborted)return n();let r=setTimeout(a,e),i=()=>a();t?.addEventListener(`abort`,i,{once:!0});function a(){clearTimeout(r),t?.removeEventListener(`abort`,i),n()}})}const Bt=`1.3.15`;var Vt=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.status=n,this.cause=r,this.name=`StreamError`}};const Ht=I.scope(`parser`);async function*Ut(e,t,n){if(!e.ok){let t=await e.text().catch(()=>``);throw new Vt(`server responded ${e.status}: ${t.slice(0,200)}`,`server`,e.status)}for await(let r of Wt(e,t)){let e=Gt(r,n);if(e===`done`)return;e&&(yield e)}}async function*Wt(e,t){if(!e.body)throw new Vt(`response has no body`,`no-body`);let n=e.body.pipeThrough(new TextDecoderStream).getReader(),r=``;try{for(;;){if(t.aborted)throw new DOMException(`aborted`,`AbortError`);let{done:e,value:i}=await n.read();if(e){let e=r.trim();e&&(yield e);return}r+=i;let a;for(;(a=r.indexOf(`
|
|
8
8
|
|
|
9
9
|
`))!==-1;){let e=r.slice(0,a);r=r.slice(a+2),yield e}}}finally{n.releaseLock()}}function Gt(e,t){let n=``,r;for(let i of e.split(`
|
|
10
|
-
`))if(i!==``){if(i.startsWith(`:`)){t?.(i.slice(1).trim());continue}if(i.startsWith(`data:`)){let e=i.slice(5).replace(/^ /,``);n=n?`${n}\n${e}`:e;continue}i.startsWith(`id:`)&&(r=i.slice(3).trim())}if(n===`[DONE]`)return`done`;if(!n)return null;try{let e=JSON.parse(n);return Ht.trace(`chunk`,{type:e.type,eventId:r}),{chunk:e,eventId:r}}catch(e){throw Ht.trace(`frame parse failed`,{errorType:e instanceof Error?e.name:typeof e,payloadLength:n.length}),new Vt(`invalid SSE frame`,`network`,void 0,e)}}function Kt(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const qt=e=>e&&Object.keys(e).length>0?e:void 0;function Jt(e,t){let n=qt(e),r=qt(t);if(!n&&!r)return;let i={};return n&&(i.user=n),r&&(i.page=r),Kt(JSON.stringify(i))}function Yt(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Xt(e){return`tool-${e.startsWith(`tool:`)?e.slice(5):e}`}function Zt(e){return e.startsWith(`tool-`)?e.slice(5):e}const V={handshake:`/pai/handshake`,streamMessage:`/pai/stream-message`,streamResume:`/pai/stream-resume`,cancelStream:`/pai/cancel-stream`,listConversations:`/pai/list-conversations`,listMessages:`/pai/list-messages`,updateSettings:`/pai/update-settings`,markRead:`/pai/mark-read`,messageFeedback:`/pai/message-feedback`,requestOperator:`/pai/request-operator`,cancelOperatorRequest:`/pai/cancel-request-operator`,bootstrap:`/pai/bootstrap`,content:`/pai/content`,submitForm:`/pai/submit-form`};function Qt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $t(e){if(!Qt(e))return;let t=e,n=t.controlMode,r=t.controlRevision;if(!(n!==`ai-agent`&&n!==`awaiting-operator`&&n!==`operator`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0))return{controlMode:n,controlRevision:r,assignedOperatorInitials:typeof t.assignedOperatorInitials==`string`&&t.assignedOperatorInitials?t.assignedOperatorInitials:void 0,operatorAvailable:typeof t.operatorAvailable==`boolean`?t.operatorAvailable:void 0}}function en(e){if(!Qt(e))return;let t=e.status,n=e.postFinishSequence;if(!(t!==`compacting`&&t!==`ready`||typeof n!=`number`||!Number.isSafeInteger(n)||n<0))return{status:t,postFinishSequence:n}}function tn(e){let t=Qt(e)?e.suggestions:void 0;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!Qt(e))continue;let{id:t,label:r,text:i}=e;typeof r!=`string`||!r||n.push({id:typeof t==`string`&&t?t:`s${n.length}`,label:r,text:typeof i==`string`&&i?i:r})}return n}function nn(e){let t={messages:e.messages.map(e=>({id:e.serverMessageId??e.id,parts:H(e),role:e.role})),conversationId:e.conversationId,responseType:`ack`};return e.visitorId&&(t.visitorId=e.visitorId),e.userPrefs&&(t.userPrefs=e.userPrefs),t}function rn(e){return e.state===`output-available`||e.state===`output-error`||e.state===`output-denied`||e.approval?.approved!==void 0}function H(e){let t=[];for(let n of e.parts)if(n.kind===`step-start`&&t.push({type:`step-start`}),n.kind===`reasoning`&&n.text&&t.push({type:`reasoning`,text:n.text,state:n.done?`done`:`streaming`}),n.kind===`text`&&n.text&&t.push({text:n.text,type:`text`}),n.kind===`file`&&n.url&&t.push({mediaType:n.mediaType,type:`file`,url:n.url}),n.kind===`tool`&&rn(n)){let e=n.dynamic?{type:`dynamic-tool`,toolName:n.toolName,toolCallId:n.toolCallId,state:n.state}:{type:Xt(n.toolName),toolCallId:n.toolCallId,state:n.state};n.input!==void 0&&(e.input=n.input),n.output!==void 0&&(e.output=n.output),n.error!==void 0&&(e.errorText=n.error),n.approval&&n.approval.approved!==void 0&&(e.approval=n.approval),t.push(e)}for(let n of e.attachments??[])n.url&&t.push({type:`file`,url:n.url,mediaType:n.mediaType,filename:n.name,fileId:n.id,fileSize:n.size});return t}function an(e){"@babel/helpers - typeof";return an=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},an(e)}function on(e,t){if(an(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(an(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function sn(e){var t=on(e,`string`);return an(t)==`symbol`?t:t+``}function U(e,t,n){return(t=sn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const W=I.scope(`transport`),cn=new WeakMap;function ln(e){return cn.get(e)}function un(e,t){return cn.set(e,t),e}function dn(e){return Math.max(e?.upsertRevision??0,e?.read?.revision??0)}function fn(e,t){return e.conversationId===t.conversationId&&e.title===t.title&&e.lastMessageAt===t.lastMessageAt&&e.preview===t.preview&&e.canContinue===t.canContinue&&e.hasUnread===t.hasUnread&&e.controlState===t.controlState}function pn(e,t,n=!0){switch(t.type){case`snapshot`:{let n=new Map(e.map(e=>[e.conversationId,e])),r=e.filter(e=>(ln(e)?.activityRevision??0)>t.requestedRevision).toSorted((e,t)=>ln(t).activityRevision-ln(e).activityRevision),i=new Set(r.map(e=>e.conversationId));return[...r,...t.result.conversations.filter(e=>!i.has(e.conversationId)).map(e=>{let r=n.get(e.conversationId);if(!r)return e;let i=ln(r);return(i?.upsertRevision??0)>t.requestedRevision?r:i?.read&&!r.hasUnread&&i.read.lastMessageAt===e.lastMessageAt?un({...e,hasUnread:!1},{upsertRevision:0,read:i.read}):e})]}case`read`:{let n=e.findIndex(e=>e.conversationId===t.conversationId&&(t.lastMessageAt===void 0||e.lastMessageAt===t.lastMessageAt));if(n<0)return e;let r=e[n],i=ln(r);if(dn(i)>t.revision)return e;let a=t.lastMessageAt??r.lastMessageAt,o={upsertRevision:i?.upsertRevision??0,...i?.activityRevision===void 0?{}:{activityRevision:i.activityRevision},read:{revision:t.revision,...a?{lastMessageAt:a}:{}}};return r.hasUnread?e.map((e,t)=>t===n?un({...e,hasUnread:!1},o):e):(un(r,o),e)}case`upsert`:{let r=e.findIndex(e=>e.conversationId===t.conversation.conversationId);if(r<0&&!n)return e;let i=r<0?void 0:e[r],a=i?ln(i):void 0;if(dn(a)>t.revision)return e;let o=t.activity?t.revision:a?.activityRevision,s={upsertRevision:t.revision,...o===void 0?{}:{activityRevision:o},...!t.conversation.hasUnread&&a?.read?{read:a.read}:{}},c=i?{...i,...t.conversation,title:i.title}:{...t.conversation};return i&&fn(i,c)?(un(i,s),e):(un(c,s),t.activity?[c,...e.filter(e=>e.conversationId!==c.conversationId)]:i?e.map((e,t)=>t===r?c:e):[...e,c])}default:return t}}const mn=new Set([408,425,429,500,502,503,504]);function hn(e){return 400*2**e+Math.floor(Math.random()*250)}function gn(e){return 6e4+Math.ceil(e/1048576)*15e3}function _n(e){let t=e.get(`retry-after`);if(!t)return null;let n=Number(t),r=Number.isFinite(n)?n*1e3:Date.parse(t)-Date.now();return Number.isFinite(r)&&r>=0?Math.min(r,3e4):null}var vn=class{constructor(e){this.ttlMs=e,U(this,`map`,new Map)}getOrFetch(e,t){let n=this.map.get(e);if(n&&performance.now()-n.at<this.ttlMs)return n.result;let r={at:performance.now(),result:t().then(e=>(r.value=e,e)).catch(t=>{throw this.map.get(e)===r&&this.map.delete(e),t})};return this.map.set(e,r),r.result}peek(e){let t=this.map.get(e);if(t?.value!==void 0&&performance.now()-t.at<this.ttlMs)return t.value}update(e){for(let t of this.map.values()){if(t.value!==void 0){let n=e(t.value);t.value=n,t.result=Promise.resolve(n);continue}t.result=t.result.then(n=>{let r=e(n);return t.value=r,r})}}delete(e){this.map.delete(e)}},yn=class{constructor(e){this.opts=e,U(this,`conversationListeners`,new Set),U(this,`conversationRevision`,0),U(this,`visitorId`,void 0),U(this,`conversationId`,void 0),U(this,`userContext`,void 0),U(this,`pageContext`,void 0),U(this,`locale`,void 0),U(this,`conversationsCache`,new vn(1e4)),U(this,`contentCache`,new vn(6e4))}setContext(e,t){this.userContext=e,this.pageContext=t}setLocale(e){this.locale=e}primeIdentity(e,t){e&&(this.visitorId=e),t&&(this.conversationId=t)}envelope(){let e={_ev:Bt};this.visitorId&&(e.visitorId=this.visitorId),this.conversationId&&(e.conversationId=this.conversationId),this.locale&&(e.locale=this.locale);let t=Jt(this.userContext,this.pageContext);return t&&(e.context=t),e}withEnvelope(e){return{...this.envelope(),...e}}appendEnvelope(e){for(let[t,n]of Object.entries(this.envelope()))e.append(t,n);return e}withEnvelopeQuery(e){let t=new URL(this.url(e));for(let[e,n]of Object.entries(this.envelope()))t.searchParams.has(e)||t.searchParams.set(e,n);return t.toString()}async handshake(e){W.debug(`handshake →`,{visitorId:e.visitorId,conversationId:e.conversationId,locale:e.locale});let t=await this.postJson(V.handshake,e,`handshake`);return W.debug(`handshake ←`,{visitorId:t.visitorId,conversationId:t.conversationId,hasWelcome:!!t.welcome,hasConfig:!!t.config,rebind:t.rebind}),this.visitorId=e.visitorId,this.conversationId=t.conversationId,t}async uploadFile(e,t){W.debug(`uploadFile →`,{name:e.name,size:e.size,type:e.type});let n=new FormData;n.append(`file`,e,e.name);let r=await this.postForm(this.uploadPath,n,`upload`,t,gn(e.size));return W.debug(`uploadFile ←`,{id:r.id,url:r.url}),r}async transcribe(e,t=`audio/webm`){W.debug(`transcribe →`,{size:e.size,mimeType:t});let n=new FormData;n.append(`audio`,e,`voice.${bn(t)}`),n.append(`mimeType`,t);let r=await this.postForm(this.transcribePath,n,`transcribe`);return W.debug(`transcribe ←`,{textLen:r.text.length}),r}subscribeConversationChanges(e){return this.conversationListeners.add(e),()=>this.conversationListeners.delete(e)}publishConversation(e,t=!1){let n={type:`upsert`,conversation:e,revision:++this.conversationRevision,...t?{activity:!0}:{}};this.conversationsCache.update(r=>{let i=r.pagination.page===1,a=r.conversations.some(t=>t.conversationId===e.conversationId),o=pn(r.conversations,n,i&&t),s=i&&o.length>r.pagination.limit?o.slice(0,r.pagination.limit):o;if(!i||!t||a||r.pagination.hasNext)return s===r.conversations?r:{...r,conversations:s};let c=Math.max(r.pagination.total,r.conversations.length)+1,l=Math.ceil(c/r.pagination.limit);return{...r,conversations:s,pagination:{...r.pagination,total:c,totalPages:l,hasNext:r.pagination.page<l}}});for(let e of this.conversationListeners)e(n)}localeCacheKey(e){return`${this.locale??``}|${JSON.stringify(e,Object.keys(e).toSorted())}`}peekConversations(e={}){return this.conversationsCache.peek(this.localeCacheKey(e))}listConversations(e={},t=!1){if((e.page??1)>1)return this.fetchConversations(e);let n=this.localeCacheKey(e),r=this.conversationRevision;t&&this.conversationsCache.delete(n);let i=this.conversationsCache.getOrFetch(n,()=>this.fetchConversations(e));return t?i.then(e=>{let t={type:`snapshot`,result:e,requestedRevision:r};for(let e of this.conversationListeners)e(t);return e}):i}async fetchConversations(e){let t=new URL(this.url(V.listConversations));return e.visitorId&&t.searchParams.set(`visitorId`,e.visitorId),e.page&&t.searchParams.set(`page`,String(e.page)),e.limit&&t.searchParams.set(`limit`,String(e.limit)),e.ids?.length&&t.searchParams.set(`ids`,e.ids.join(`,`)),this.getJson(t.toString(),`listConversations`)}async loadConversation(e,{ids:t=[],beforeId:n,beforeCreatedAt:r}={}){let i=new URL(this.url(V.listMessages));i.searchParams.set(`conversationId`,e),i.searchParams.set(`limit`,`50`),t.length>0&&i.searchParams.set(`ids`,t.join(`,`)),n&&i.searchParams.set(`beforeId`,n),r&&i.searchParams.set(`beforeCreatedAt`,r);let a=await this.getJson(i.toString(),`loadConversation`);return{...a,messages:a.messages.toReversed()}}async markRead(e,t){if(!this.visitorId||!e)return;let n={type:`read`,conversationId:e,...t===void 0?{}:{lastMessageAt:t},revision:++this.conversationRevision};this.conversationsCache.update(e=>{let t=pn(e.conversations,n);return t===e.conversations?e:{...e,conversations:t}});for(let e of this.conversationListeners)e(n);try{await this.postJson(V.markRead,{conversationId:e},`markRead`,!0)}catch(e){W.debug(`markRead failed (non-fatal)`,{err:e})}}async requestOperator(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(V.requestOperator,{},`requestOperator`)).controlState}catch(e){W.debug(`requestOperator failed (non-fatal)`,{err:e});return}}async cancelOperatorRequest(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(V.cancelOperatorRequest,{},`cancelOperatorRequest`)).controlState}catch(e){W.debug(`cancelOperatorRequest failed (non-fatal)`,{err:e});return}}listContent(e={}){return this.contentCache.getOrFetch(this.localeCacheKey(e),()=>this.fetchContent(e))}async fetchContent(e){let t=new URL(this.dataUrl(V.content));for(let[n,r]of Object.entries(e))r!==void 0&&t.searchParams.set(n,Array.isArray(r)?r.join(`,`):String(r));let n=await this.getJson(t.toString(),`listContent`),r=(n.items??[]).map(e=>A(e,this.locale));return{...n,items:r}}async bootstrap(e){let t=new URL(this.dataUrl(V.bootstrap));e&&t.searchParams.set(`conversationId`,e);let n=await this.getJson(t.toString(),`bootstrap`);return{forms:n.forms??[],formSubmissions:n.formSubmissions??[]}}async saveUserPrefs(e){return this.postJson(V.updateSettings,{userPrefs:e},`saveUserPrefs`)}get uploadPath(){return this.opts.endpoints?.upload??`/pai/upload-file`}get transcribePath(){return this.opts.endpoints?.transcribe??`/pai/transcribe-audio`}get submitFormPath(){return this.opts.endpoints?.submitForm??V.submitForm}async submitForm(e){W.debug(`submitForm →`,{formId:e.formId,trigger:e.trigger,fields:Object.keys(e.values).length});try{await this.postJson(this.dataUrl(this.submitFormPath),e,`submitForm`)}catch(e){W.debug(`submitForm failed (non-fatal)`,{err:e})}}async submitFeedback(e){W.debug(`submitFeedback →`,{messageId:e.messageId,value:e.value});try{await this.postJson(V.messageFeedback,{messageId:e.messageId,set:{feedback:e.value}},`submitFeedback`)}catch(e){W.debug(`submitFeedback failed (non-fatal)`,{err:e})}}async sendTurn(e){W.debug(`message →`,{conversationId:e.conversationId,visitorId:e.visitorId,messageCount:e.messages.length});try{return await this.runWithAbort(async t=>{let n=await this.fetchImpl(this.url(V.streamMessage),{method:`POST`,credentials:`omit`,headers:{accept:`application/json`,"content-type":`application/json`,...this.opts.auth.headers()},body:JSON.stringify(this.withEnvelope(e)),signal:t});if(n.status!==202)throw new Vt(`sendTurn failed: expected 202, received ${n.status}`,`server`,n.status);let r;try{r=await n.json()}catch(e){throw t?.aborted?e:new Vt(`sendTurn failed: invalid acknowledgement`,`server`,n.status,e)}if(!xn(r))throw new Vt(`sendTurn failed: invalid acknowledgement`,`server`,n.status);return r},void 0,3e4)}catch(e){throw e instanceof Vt?e:new Vt(`sendTurn failed: network error`,`network`,void 0,e)}}cancelTurn(e,t){!this.visitorId||!e||!t||(W.debug(`cancel stream`,{conversationId:e,runId:t,visitorId:this.visitorId}),this.fetchImpl(this.url(V.cancelStream),{method:`POST`,credentials:`omit`,headers:{"content-type":`application/json`,...this.opts.auth.headers()},body:JSON.stringify(this.withEnvelope({conversationId:e,runId:t})),keepalive:!0}).catch(e=>W.debug(`cancel POST failed (non-fatal)`,{err:e})))}async connectResumeStream(e){let t=new AbortController,n=()=>t.abort(e.signal.reason);e.signal.aborted?n():e.signal.addEventListener(`abort`,n,{once:!0});let r=setTimeout(()=>t.abort(),1e4),i=()=>{clearTimeout(r),e.signal.removeEventListener(`abort`,n)},a;try{a=await this.fetchImpl(this.resumeUrl(),{method:`GET`,credentials:`omit`,headers:{accept:`text/event-stream`,...this.opts.auth.headers()},signal:t.signal})}catch(t){return i(),e.signal.aborted||W.debug(`resume-stream fetch failed — reconnecting`,{err:t}),`held`}if(!a.ok)return i(),a.status===409||mn.has(a.status)?(W.debug(`resume-stream → transient response; reconnecting`,{status:a.status}),`held`):(W.debug(`resume-stream → endpoint unavailable`,{status:a.status}),`unavailable`);if(!a.body)return i(),W.debug(`resume-stream → bodyless response; stopping`,{status:a.status}),`unavailable`;if(!(a.headers.get(`content-type`)??``).includes(`text/event-stream`))return i(),W.debug(`resume-stream → non-SSE response; stopping`),`unavailable`;let o=!1;try{for await(let{chunk:n}of Ut(a,t.signal,t=>{o||t!==`connected`||(o=!0,clearTimeout(r),e.onConnected())})){if(e.signal.aborted)return`held`;e.onChunk(n)}}catch(t){if(e.signal.aborted)return`held`;W.debug(`resume-stream segment dropped — reconnecting`,{err:t})}finally{i()}return`held`}resumeUrl(){return this.withEnvelopeQuery(V.streamResume)}async postJson(e,t,n,r=!1){let i=await this.fetchWithRetry(()=>[this.url(e),{method:`POST`,credentials:`omit`,headers:{"content-type":`application/json`,...this.opts.auth.headers()},body:JSON.stringify(this.withEnvelope(t)),...r?{keepalive:!0}:{}}],n);return this.assertOk(i,n)}async postForm(e,t,n,r,i){return this.runWithAbort(async r=>{let i=await this.fetchImpl(this.url(e),{method:`POST`,credentials:`omit`,headers:this.opts.auth.headers(),body:this.appendEnvelope(t),signal:r});return this.assertOk(i,n)},r,i)}async runWithAbort(e,t,n){if(!t&&n===void 0)return e();let r=new AbortController,i=()=>r.abort(t?.reason);t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0});let a=n===void 0?void 0:setTimeout(()=>r.abort(),n);try{return await e(r.signal)}finally{a!==void 0&&clearTimeout(a),t?.removeEventListener(`abort`,i)}}async getJson(e,t){let n=await this.fetchWithRetry(()=>[this.withEnvelopeQuery(e),{method:`GET`,credentials:`omit`,headers:{accept:`application/json`,...this.opts.auth.headers()}}],t);return this.assertOk(n,t)}async fetchWithRetry(e,t){for(let n=0;;n++){let[r,i]=e(),a;try{a=await this.fetchImpl(r,i)}catch(e){if(n>=3)throw new Vt(`${t} failed: network error`,`network`,void 0,e);W.debug(`request network error — retrying`,{label:t,attempt:n}),await zt(hn(n));continue}if(a.ok||!mn.has(a.status)||n>=3)return a;let o=_n(a.headers)??hn(n);W.debug(`request retryable status — retrying`,{label:t,status:a.status,attempt:n,wait:o}),await zt(o)}}async assertOk(e,t){if(!e.ok)throw new Vt(`${t} failed: ${e.status}`,`server`,e.status);return await e.json()}url(e){return/^https?:\/\//i.test(e)?e:`${this.opts.agentApiBaseUrl}${e}`}dataUrl(e){return/^https?:\/\//i.test(e)?e:`${this.opts.dataApiBaseUrl}${e}`}get fetchImpl(){return this.opts.fetchImpl??globalThis.fetch.bind(globalThis)}};function bn(e){return e.includes(`webm`)?`webm`:e.includes(`ogg`)?`ogg`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`mpeg`)?`mp3`:e.includes(`wav`)?`wav`:`bin`}function xn(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`status`),n=Reflect.get(e,`conversationId`),r=Reflect.get(e,`runId`);return t===`accepted`&&typeof n==`string`&&n.length>0&&(r===void 0||typeof r==`string`&&r.length>0)}function Sn(e,t,n=ct()){let r=e?[{kind:`text`,id:`t0`,textSig:f(e),doneSig:f(!0)}]:[];return{id:n,role:`user`,createdAt:Date.now(),status:`complete`,attachments:t,partsSig:f(r)}}function Cn(){return{id:ct(),role:`assistant`,createdAt:Date.now(),status:`streaming`,partsSig:f([])}}function wn(e){let t=ct();return Tn({id:t,role:e.role,createdAt:Date.now(),status:`complete`,ephemeral:!0,parts:[{kind:`text`,id:`${t}-t0`,text:e.text,done:!0}]})}function Tn(e){return{id:e.id,role:e.role,createdAt:e.createdAt,status:e.status,canceled:e.canceled,errorText:e.errorText,finishReason:e.finishReason,serverMessageId:e.serverMessageId,ephemeral:e.ephemeral,attachments:e.attachments,feedback:e.feedback,partsSig:f(e.parts.map(sr))}}function En(e){return e.status===`failed`?`error`:e.role===`assistant`&&e.status===`streaming`?`streaming`:`complete`}function Dn(e){let t=new Set,n=e.parts.map((t,n)=>t.type===`text`?{kind:`text`,id:`${e.id}-t${n}`,textSig:f(t.text),doneSig:f(!0)}:t.type===`reasoning`?{kind:`reasoning`,id:`${e.id}-r${n}`,textSig:f(t.text),doneSig:f(t.state!==`streaming`)}:t.type===`step-start`?{kind:`step-start`,id:`${e.id}-ss${n}`}:t.type===`file`?{kind:`file`,url:t.url,mediaType:t.mediaType}:t.type===`source-url`?{kind:`source`,sourceId:t.sourceId,url:t.url,title:t.title}:t.type===`source-document`?{kind:`source`,sourceId:t.sourceId,title:t.title,filename:t.filename,mediaType:t.mediaType}:t.type===`data-suggestions`?null:t.type===`dynamic-tool`||t.type.startsWith(`tool-`)?{kind:`tool`,toolCallId:t.toolCallId,toolName:t.type===`dynamic-tool`?t.toolName:Zt(t.type),dynamic:t.type===`dynamic-tool`||void 0,inputPartialSig:f(``),inputSig:f(t.input),outputSig:f(t.output),errorSig:f(t.errorText),stateSig:f(t.state),approvalSig:f(t.approval)}:null).filter(e=>e!==null).filter(e=>e.kind===`source`?t.has(e.sourceId)?!1:(t.add(e.sourceId),!0):!0),r=e.parts.find(e=>e.type===`data-suggestions`);return{id:e.id,role:e.role,operatorInitials:e.operatorInitials,suggestions:r?.type===`data-suggestions`?tn(r.data):void 0,serverMessageId:e.id,createdAt:Date.parse(e.createdAt),status:En(e),canceled:e.status===`canceled`,feedback:e.feedback??null,partsSig:f(n)}}function On(e){return!e.parts.some(e=>e.type===`text`&&e.text.trim()!==``||e.type===`dynamic-tool`||e.type.startsWith(`tool-`)||e.type===`file`||e.type===`source-url`||e.type===`source-document`)}function kn(e){return e.role===`assistant`&&e.status===`streaming`&&On(e)}function An(e){let t=e.length-1;return e.filter((e,n)=>n===t||!kn(e)).map(Dn)}function jn(e,t){let n=!t&&e.at(-1)?.role===`assistant`?-2:-1,r=e.at(n);return!r||r.ephemeral?[]:[r]}function Mn(e){return{id:e.id,role:e.role,createdAt:e.createdAt,status:e.status,canceled:e.canceled,errorText:e.errorText,finishReason:e.finishReason,serverMessageId:e.serverMessageId,ephemeral:e.ephemeral,attachments:e.attachments,parts:e.partsSig.value.map(cr)}}function Nn(e){let t=``;for(let n of e.partsSig.value)n.kind===`text`&&(t+=n.textSig.value);return t}function Pn(e,t,n,r,i,a=t.createdAt){let o=e.find(e=>e.role===`user`&&!e.ephemeral),s=(e,t)=>Nn(e).replace(/\s+/g,` `).trim().slice(0,t),c=o?s(o,80):``,l=s(t,120);return{conversationId:n,title:c||r,lastMessageAt:new Date(a).toISOString(),preview:l||void 0,canContinue:i}}function Fn(e){return Nn(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`||e.kind===`source`)}function In(e){return Nn(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`)}function Ln(e){return e===`approval-responded`||e===`output-available`||e===`output-denied`||e===`output-error`}const Rn=e=>e.kind===`tool`,zn=e=>e.kind===`text`&&e.textSig.value.trim()!==``||e.kind===`file`;function Bn(e){let t=e.partsSig.value,n=t.findLastIndex(e=>e.kind===`tool`);return t.slice(n+1).some(zn)}function Vn(e){if(e.role!==`assistant`)return!1;let t=e.partsSig.value.filter(Rn);return t.length>0&&t.every(e=>Ln(e.stateSig.value))}function Hn(e){return e.role===`assistant`&&e.partsSig.value.some(e=>e.kind===`tool`)&&!Bn(e)}function Un(e,t){return!e.partsSig.value.slice(t+1).some(e=>e.kind===`step-start`||zn(e))}function Wn(e){return e.partsSig.value.some(e=>Rn(e)&&!Ln(e.stateSig.value))}function Gn(e,t){if(t.length===0)return e;let n=new Set;for(let t of e)n.add(t.id),t.serverMessageId&&n.add(t.serverMessageId);let r=t.filter(e=>{let t=[e.id,e.serverMessageId].filter(e=>e!==void 0);return t.some(e=>n.has(e))?!1:(t.forEach(e=>n.add(e)),!0)});if(r.length===0)return e;let i=e.findIndex(e=>!e.ephemeral),a=i<0?e.length:i;return[...e.slice(0,a),...r,...e.slice(a)]}function Kn(e,t){return t.id=e.id,e.canceled&&(t.canceled=!0),e.feedback!==void 0&&(t.feedback=e.feedback),t.suggestions??(t.suggestions=e.suggestions),t}function qn(e,t,n,r){if(!Jn(e))return;if(t.length===0){let t=Math.max(...r.values());return n.find(n=>n.role===`assistant`&&r.get(n.serverMessageId??n.id)===t&&Nn(n).length>=Nn(e).length)}let i=t.at(-1);if(i?.role!==`user`)return;let a=r.get(i.serverMessageId??i.id);if(a!==void 0)return n.find(t=>t.role===`assistant`&&r.get(t.serverMessageId??t.id)===a+1&&Nn(t).length>=Nn(e).length)}function Jn(e){return e?.role===`assistant`&&e.status===`streaming`&&e.serverMessageId===void 0}function Yn(e,t){let n=new Map(t.partsSig.value.filter(Rn).filter(e=>Ln(e.stateSig.value)).map(e=>[e.toolCallId,e]));if(n.size===0)return;let r=!1,i=e.partsSig.value.map(e=>{if(!Rn(e))return e;let t=n.get(e.toolCallId);if(!t)return e;let i=e.approvalSig.value,a=t.approvalSig.value,o=i===void 0||i.approved===void 0&&a?.approved!==void 0?t.approvalSig:e.approvalSig,s=e.inputSig.value===void 0?t.inputSig:e.inputSig,c=e.toolName===`tool`?t.toolName:e.toolName,l=e.dynamic??t.dynamic;return o===e.approvalSig&&s===e.inputSig&&c===e.toolName&&l===e.dynamic?e:(r=!0,{...e,toolName:c,dynamic:l,inputSig:s,approvalSig:o})});r&&(e.partsSig.value=i)}function Xn(e,t){let n=t.filter(e=>!e.ephemeral&&(e.status===`streaming`||e.status===`pending`||e.status===`error`||e.retryAction!==void 0||(e.attachments?.length??0)>0||Fn(e))),r=new Map;for(let e of n)r.set(e.id,e),e.serverMessageId!==void 0&&r.set(e.serverMessageId,e);let i=new Set,a=[],o=e.map(e=>{let t=(e.serverMessageId===void 0?void 0:r.get(e.serverMessageId))??r.get(e.id);return t===void 0?(a.push(e),e):(i.add(t),t.role===e.role?t.role===`user`&&t.serverMessageId===void 0&&(t.status===`pending`||t.status===`error`)?Kn(t,e):t.status===`streaming`||Nn(t).length>=Nn(e).length?(Yn(t,e),t.suggestions??(t.suggestions=e.suggestions),t.feedback===void 0&&(t.feedback=e.feedback),e.canceled&&(t.canceled=!0),t):Kn(t,e):e)}),s=n.filter(e=>!i.has(e)),c=s.findLast(Jn),l=new Map;e.forEach((e,t)=>{l.set(e.id,t),e.serverMessageId!==void 0&&l.set(e.serverMessageId,t)});let u=qn(c,c?n.slice(0,n.indexOf(c)):[],a,l);if(c&&u){let e=o.indexOf(u);e>=0&&(o[e]=Kn(c,u)),s=s.filter(e=>e!==c)}return[...o,...s]}function Zn(e,t){let n=new Map(t.filter(e=>e.serverMessageId!==void 0).map(e=>[e.serverMessageId,e])),r=new Map;t.forEach((e,t)=>{r.set(e.id,t),e.serverMessageId!==void 0&&r.set(e.serverMessageId,t)});let i=new Set(e.flatMap(e=>[e.serverMessageId,e.id].filter(e=>e!==void 0))),a=!1,o=e.map(e=>{let t=n.get(e.serverMessageId??e.id);if(t===void 0||t.role!==e.role)return e;if(e.role===`user`&&e.serverMessageId===void 0)return a=!0,Kn(e,t);if(e.serverMessageId===void 0)return e;let r=Nn(t),i=Nn(e),o=t.status!==`streaming`&&r.length>=i.length&&nr(e,t);if(r.length>i.length||r===i&&t.partsSig.value.length>e.partsSig.value.length||o)return a=!0,Kn(e,t);if(e.status===`streaming`&&t.status!==`streaming`&&$n(e,t)){if(e.continuationStreaming&&Wn(t))return e;if(!nr(t,e))return a=!0,Kn(e,t)}return e}),s=[...n.values()].filter(e=>!i.has(e.serverMessageId)),c=o.findLastIndex(Jn),l=o[c],u=qn(l,o.slice(0,c),s,r);if(l!==void 0&&u!==void 0&&Nn(u).length>=Nn(l).length&&(Kn(l,u),o[c]=u,s.splice(s.indexOf(u),1),a=!0),s.length===0)return{messages:a?o:e,changed:a};for(let e of s){let t=r.get(e.serverMessageId??e.id),n=!1,i=o.findIndex(e=>{let i=r.get(e.serverMessageId??e.id);return t===void 0?!1:i===void 0?n:i>t?!0:(n=!0,!1)});i===-1?o.push(e):o.splice(i,0,e)}return{messages:o,changed:!0}}function Qn(e,t){if(e.role!==t.role)return!1;let n=Nn(t),r=Nn(e);return n.length>r.length||t.partsSig.value.length>e.partsSig.value.length||nr(e,t)}function $n(e,t){let n=e.partsSig.value,r=t.partsSig.value;return n.length===r.length&&n.every((e,t)=>{let n=r[t];switch(e.kind){case`text`:return n?.kind===`text`&&n.textSig.value===e.textSig.value;case`reasoning`:return n?.kind===`reasoning`&&n.textSig.value===e.textSig.value;case`step-start`:return n?.kind===`step-start`;case`tool`:return n?.kind===`tool`&&n.toolCallId===e.toolCallId&&er(n.toolName,e.toolName);case`file`:return n?.kind===`file`&&n.url===e.url&&n.mediaType===e.mediaType;case`source`:return n?.kind===`source`&&n.sourceId===e.sourceId&&n.url===e.url&&n.title===e.title&&n.filename===e.filename&&n.mediaType===e.mediaType;default:return e}})}function er(e,t){return(e.startsWith(`tool:`)?e.slice(5):e)===(t.startsWith(`tool:`)?t.slice(5):t)}const tr={"input-streaming":0,"input-available":1,"approval-requested":2,"approval-responded":3,"output-available":4,"output-denied":4,"output-error":4};function nr(e,t){let n=new Map(e.partsSig.value.filter(Rn).map(e=>[e.toolCallId,e]));return t.partsSig.value.filter(Rn).some(e=>{let t=n.get(e.toolCallId);if(!t||tr[e.stateSig.value]>tr[t.stateSig.value])return!0;let r=e.approvalSig.value?.approved;return r!==void 0&&r!==t.approvalSig.value?.approved})}function rr(e){return e.role===`assistant`&&e.status!==`streaming`&&!Fn(e)}function ir(e,t){if(!e.includes(t)||t.retryAction===null)return;if(t.retryAction)return t.retryAction;if(t!==e.at(-1)||t.role!==`assistant`||t.serverMessageId===void 0||t.status!==`error`&&!rr(t))return;let n=e.indexOf(t);for(let t=n-1;t>=0;t--){let n=e[t];if(n?.role===`user`&&!n.ephemeral)return{kind:`repeat-user`,messageId:n.id}}}function ar(e){return e.canceled===!0&&e.role===`assistant`&&e.status!==`streaming`&&!In(e)}function or(e,t){return e.operatorRoutedTurn?rr(e)?`drop`:`complete-operator-routed`:t||rr(e)?`error`:`complete`}function sr(e){return e.kind===`text`||e.kind===`reasoning`?{kind:e.kind,id:e.id,textSig:f(e.text),doneSig:f(e.done)}:e.kind===`tool`?{kind:`tool`,toolCallId:e.toolCallId,toolName:e.toolName,dynamic:e.dynamic,inputPartialSig:f(e.inputPartial),inputSig:f(e.input),outputSig:f(e.output),errorSig:f(e.error),stateSig:f(e.state),approvalSig:f(e.approval)}:e}function cr(e){return e.kind===`text`||e.kind===`reasoning`?{kind:e.kind,id:e.id,text:e.textSig.value,done:e.doneSig.value}:e.kind===`tool`?{kind:`tool`,toolCallId:e.toolCallId,toolName:e.toolName,dynamic:e.dynamic,inputPartial:e.inputPartialSig.value,input:e.inputSig.value,output:e.outputSig.value,error:e.errorSig.value,state:e.stateSig.value,approval:e.approvalSig.value}:e}const lr=I.scope(`feedback:audio`);var ur=class{constructor(){U(this,`ctx`,null),U(this,`master`,null),U(this,`buffers`,new Map)}unlock(){if(this.ctx){this.ctx.state===`suspended`&&this.ctx.resume();return}let e=globalThis.AudioContext??globalThis.webkitAudioContext;if(e)try{this.ctx=new e,this.master=this.ctx.createGain(),this.master.gain.value=1,this.master.connect(this.ctx.destination)}catch(e){lr.warn(`AudioContext init failed`,{err:e})}}setVolume(e){if(!this.master||!this.ctx)return;let t=Math.max(0,Math.min(1,e));this.master.gain.setTargetAtTime(t,this.ctx.currentTime,.01)}playTone(e){let t=this.ctx,n=this.master;if(!t||!n||t.state!==`running`)return;let r=t.currentTime,i=e.noteMs/1e3;e.notes.forEach((a,o)=>{let s=t.createOscillator();s.type=e.type,s.frequency.value=a;let c=t.createGain(),l=r+o*i;c.gain.setValueAtTime(1e-4,l),c.gain.exponentialRampToValueAtTime(e.peakGain,l+.005),c.gain.exponentialRampToValueAtTime(1e-4,l+i),s.connect(c).connect(n),s.start(l),s.stop(l+i+.01)})}async playUrl(e){let t=this.ctx,n=this.master;if(!t||!n||t.state!==`running`)return;let r=await this.getBuffer(e);if(!r)return;let i=t.createBufferSource();i.buffer=r,i.connect(n),i.start()}destroy(){this.ctx&&this.ctx.close().catch(()=>void 0),this.ctx=null,this.master=null,this.buffers.clear()}async getBuffer(e){if(!this.ctx)return null;let t=this.buffers.get(e);if(t)return t instanceof Promise,t;let n=this.ctx,r=fetch(e).then(e=>e.ok?e.arrayBuffer():Promise.reject(Error(`fetch ${e.status}`))).then(e=>n.decodeAudioData(e)).then(t=>(this.buffers.set(e,t),t)).catch(t=>(lr.warn(`audio fetch/decode failed`,{url:e,err:t}),this.buffers.delete(e),null));return this.buffers.set(e,r),r}};const dr={messageReceived:10,messageSent:0,error:[20,40,20],voiceStart:10,voiceStop:0},fr={messageReceived:{notes:[880,1318.51],noteMs:90,type:`sine`,peakGain:.45},messageSent:{notes:[1568],noteMs:60,type:`sine`,peakGain:.25},error:{notes:[523.25,392],noteMs:120,type:`triangle`,peakGain:.55},voiceStart:{notes:[1318.51],noteMs:50,type:`sine`,peakGain:.3},voiceStop:{notes:[880],noteMs:50,type:`sine`,peakGain:.3}};let pr=null,mr=0;function hr(){return typeof navigator<`u`&&typeof navigator.vibrate==`function`}function gr(){if(typeof document>`u`)return null;let e=document.createElement(`input`);e.type=`checkbox`,e.setAttribute(`switch`,``),e.setAttribute(`aria-hidden`,`true`),e.tabIndex=-1,e.id=`__${b.cssPrefix}_haptic_${Math.random().toString(36).slice(2)}`;let t=document.createElement(`label`);t.htmlFor=e.id,t.setAttribute(`aria-hidden`,`true`);let n=`position:absolute!important;width:1px!important;height:1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;opacity:0!important;pointer-events:none!important;`;return e.style.cssText=n,t.style.cssText=n,document.body.append(e,t),{input:e,label:t}}function _r(e){if(!(e===0||Array.isArray(e)&&e.every(e=>e===0))){if(hr())try{navigator.vibrate(e);return}catch{}if(pr||(pr=gr()),pr)try{pr.label.click()}catch{}}}function vr(){mr++;let e=!1;return()=>{e||(e=!0,mr=Math.max(0,mr-1),mr===0&&pr&&(pr.input.remove(),pr.label.remove(),pr=null))}}const yr=I.scope(`feedback`);var br=class{constructor(e,t){U(this,`mutedSig`,f(!1)),U(this,`audio`,new ur),U(this,`releaseHaptics`,void 0),U(this,`sound`,void 0),U(this,`haptics`,void 0),U(this,`lastPlayed`,new Map),U(this,`reducedMotionMq`,null),this.sound=e,this.haptics=t,this.releaseHaptics=vr(),this.audio.setVolume(this.effectiveVolume()),typeof matchMedia<`u`&&(this.reducedMotionMq=matchMedia(`(prefers-reduced-motion: reduce)`))}unlock(){this.audio.unlock(),this.audio.setVolume(this.effectiveVolume())}update(e,t){this.sound=e,this.haptics=t,this.audio.setVolume(this.effectiveVolume())}setMuted(e){this.mutedSig.value!==e&&(this.mutedSig.value=e)}toggleMuted(){this.mutedSig.value=!this.mutedSig.value}play(e){this.mutedSig.value||this.isDeduped(e)||(this.lastPlayed.set(e,performance.now()),this.sound.enabled&&this.playSound(e),this.haptics.enabled&&this.isTouchDevice()&&this.playHaptic(e))}destroy(){this.audio.destroy(),this.releaseHaptics()}isDeduped(e){let t=this.lastPlayed.get(e);return t!==void 0&&performance.now()-t<100}playSound(e){let t=this.sound.events?.[e];if(t===!1)return;if(typeof t==`string`){this.audio.playUrl(t).catch(e=>yr.warn(`audio play failed`,{err:e,url:t}));return}let n=fr[e];n&&this.audio.playTone(n)}playHaptic(e){if(this.reducedMotionMq?.matches)return;let t=this.haptics.events?.[e];t!==!1&&_r(t===!0||t===void 0?dr[e]:t)}effectiveVolume(){let e=this.sound.volume??.3;return this.reducedMotionMq?.matches?e*.5:e}isTouchDevice(){return typeof window>`u`?!1:matchMedia(`(hover: none) and (pointer: coarse)`).matches}};const G={fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,viewBox:`0 0 24 24`},xr=`${b.cssPrefix}-icon-dir`,Sr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M21 12a8 8 0 0 1-12 6.93L3 21l1.65-5.16A8 8 0 1 1 21 12Z`})}),Cr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M18 6 6 18M6 6l12 12`})}),wr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 5v14M5 12h14`})}),Tr=()=>_(`svg`,{...G,class:xr,"aria-hidden":`true`,children:[g(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),g(`path`,{d:`M22 2 11 13`})]}),Er=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 19V5M5 12l7-7 7 7`})}),Dr=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`M3 20V4l18 8-18 8Z`})}),Or=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`m9 18 6-6-6-6`})}),kr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})}),Ar=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`m21 11-9 9a5.5 5.5 0 0 1-7.78-7.78l8.49-8.49a3.67 3.67 0 0 1 5.19 5.19l-8.49 8.49a1.83 1.83 0 0 1-2.6-2.6l7.78-7.78`})}),jr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`rect`,{x:`9`,y:`2`,width:`6`,height:`12`,rx:`3`}),g(`path`,{d:`M5 10a7 7 0 0 0 14 0M12 19v3`})]}),Mr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 8V3h5M21 8V3h-5M3 16v5h5M21 16v5h-5`})}),Nr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M8 3v5H3M16 3v5h5M8 21v-5H3M16 21v-5h5`})}),Pr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 3h7v2H5v5H3zM21 3h-7v2h5v5h2zM3 21h7v-2H5v-5H3zM21 21h-7v-2h5v-5h2z`})}),Fr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M10 3v5H3M14 3v5h7M10 21v-5H3M14 21v-5h7`})}),Ir=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M14 3h7v7M21 3l-9 9`}),g(`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`})]}),Lr=()=>g(`svg`,{...G,"aria-hidden":`true`,viewBox:`0 0 10 10`,children:g(`path`,{d:`M9 1L1 9M9 5L5 9M9 9H9`,strokeWidth:`1.5`})}),Rr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:`currentColor`,stroke:`none`}),g(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:`currentColor`,stroke:`none`}),g(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:`currentColor`,stroke:`none`})]}),zr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M11 5 6 9H2v6h4l5 4zM15 9a5 5 0 0 1 0 6M18 7a9 9 0 0 1 0 10`})}),Br=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M11 5 6 9H2v6h4l5 4zM22 9l-6 6M16 9l6 6`})}),Vr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M3 18 8 6l5 12M4.7 14h6.6`}),g(`path`,{d:`M14.5 18l3.2-7 3.2 7M15.6 15.8h4.2`})]}),Hr=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`m5 6 6 6-6 6M13 6l6 6-6 6`})}),Ur=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M20 6 9 17l-5-5`})}),Wr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M3 3v6h6`}),g(`path`,{d:`M3.05 13A9 9 0 1 0 6 5.3L3 9`}),g(`path`,{d:`M12 7v5l3 2`})]}),Gr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`10`}),g(`path`,{d:`M2 12h20`}),g(`path`,{d:`M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z`})]}),Kr=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`M19 12H5M12 19l-7-7 7-7`})}),qr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M12 20h9`}),g(`path`,{d:`M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z`})]}),Jr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`m6 9 6 6 6-6`})}),Yr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z`}),g(`path`,{d:`M14 2v6h6`})]}),Xr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`m12 3-1.5 4.5L6 9l4.5 1.5L12 15l1.5-4.5L18 9l-4.5-1.5Z`}),g(`path`,{d:`M19 15v4M17 17h4M5 3v2M4 4h2`})]}),Zr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z`})}),Qr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`10`}),g(`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`}),g(`path`,{d:`M12 17h.01`})]}),$r=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`m15 4 3 3-9 9-3-3z`}),g(`path`,{d:`M18 2v2M20 4h2M3 20l3-3M3 16h2M5 14v2`})]}),ei=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`rect`,{x:`4`,y:`8`,width:`16`,height:`12`,rx:`2`}),g(`path`,{d:`M12 8V4`}),g(`circle`,{cx:`12`,cy:`3`,r:`1`}),g(`path`,{d:`M2 14h2M20 14h2M9 13h.01M15 13h.01M9.5 17h5`})]}),ti=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M4 14v-2a8 8 0 0 1 16 0v2`}),g(`rect`,{x:`2`,y:`14`,width:`4`,height:`6`,rx:`1.5`}),g(`rect`,{x:`18`,y:`14`,width:`4`,height:`6`,rx:`1.5`}),g(`path`,{d:`M20 20v1a3 3 0 0 1-3 3h-5`})]}),ni=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`10`}),g(`circle`,{cx:`12`,cy:`12`,r:`4`}),g(`path`,{d:`m4.93 4.93 4.24 4.24M14.83 14.83l4.24 4.24M14.83 9.17l4.24-4.24M4.93 19.07l4.24-4.24`})]}),ri=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`11`,cy:`11`,r:`7`}),g(`path`,{d:`m21 21-4.3-4.3`})]}),ii=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`m8.5 12 2.5 2.5 4.5-5`})]}),ai=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M3 9.5 12 3l9 6.5`}),g(`path`,{d:`M5 9v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9`})]}),oi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`m3 11 15-5v12L3 13z`}),g(`path`,{d:`M3 11v2a2 2 0 0 0 2 2h1V9H5a2 2 0 0 0-2 2z`}),g(`path`,{d:`M7 15v3a2 2 0 0 0 4 0v-2`}),g(`path`,{d:`M21 10a3 3 0 0 1 0 4`})]}),si=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z`}),g(`path`,{d:`M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1`})]}),ci=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`4`}),g(`path`,{d:`M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41`})]}),li=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z`})}),ui=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`M12 3v18`}),g(`path`,{d:`M12 3a9 9 0 0 1 0 18z`,fill:`currentColor`,stroke:`none`})]}),di=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`10.5`,cy:`10.5`,r:`6.5`}),g(`path`,{d:`M8 11a2.5 2.5 0 0 0 5 0`}),g(`path`,{d:`m20 20-4.4-4.4`})]}),fi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M12 3.5 13.6 9 19 10.5 13.6 12 12 17.5 10.4 12 5 10.5 10.4 9z`}),g(`path`,{d:`M18.5 4v3M20 5.5h-3M5.5 16v2.5M6.75 17.25h-2.5`})]}),pi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M4 18h16`}),g(`path`,{d:`M5 18a7 7 0 0 1 14 0`}),g(`path`,{d:`M12 8V6`}),g(`path`,{d:`M10 6h4`})]}),mi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M7 11V6.5a1.5 1.5 0 0 1 3 0V10`}),g(`path`,{d:`M10 10V5.5a1.5 1.5 0 0 1 3 0V10`}),g(`path`,{d:`M13 10V6.5a1.5 1.5 0 0 1 3 0V12`}),g(`path`,{d:`M16 9.5a1.5 1.5 0 0 1 3 0v2.5a7 7 0 0 1-7 7 7 7 0 0 1-6.4-4.2L4 12.5a1.5 1.5 0 0 1 2.6-1.5L7 11`})]}),hi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`rect`,{x:`9`,y:`9`,width:`11`,height:`11`,rx:`2`}),g(`path`,{d:`M5 15a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2`})]}),gi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M7 10v11H4a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z`}),g(`path`,{d:`M7 10l4-7a2.5 2.5 0 0 1 2.5 2.5V8h5a2 2 0 0 1 2 2.3l-1.2 8A2 2 0 0 1 17.3 20H7`})]}),_i=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M17 14V3h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1z`}),g(`path`,{d:`M17 14l-4 7a2.5 2.5 0 0 1-2.5-2.5V16h-5a2 2 0 0 1-2-2.3l1.2-8A2 2 0 0 1 6.7 4H17`})]}),vi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`3.5`}),g(`path`,{d:`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9l-2.1 2.1M7 17l-2.1 2.1`})]}),yi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`M12 7v5l3 2`})]}),bi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`m8.5 12 2.5 2.5 4.5-5`})]}),xi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`m15 9-6 6M9 9l6 6`})]}),Si={chat:Sr,message:Zr,bubbles:si,spark:Xr,wand:$r,bot:ei,help:Qr,lifebuoy:ni,headset:ti,search:di,sparkles:fi,concierge:pi,wave:mi},K=b.cssPrefix,q={launcher:`${K}-launcher`,callout:`${K}-callout`,calloutDismiss:`${K}-callout-dismiss`,panel:`${K}-panel`,panelHeader:`${K}-panel-header`,resizeGrip:`${K}-resize-grip`,scrollToBottom:`${K}-scroll-to-bottom`,loadPreviousMessages:`${K}-load-previous-messages`,actionHistory:`${K}-action-history`,actionClose:`${K}-action-close`,langSegment:`${K}-lang-segment`,composer:`${K}-composer`,composerInput:`${K}-composer-input`,composerSend:`${K}-composer-send`,composerStop:`${K}-composer-stop`,compactionStatus:`${K}-compaction-status`,messageQueue:`${K}-message-queue`,queuedMessage:`${K}-queued-message`,queuedMessageRemove:`${K}-queued-message-remove`,composerAttach:`${K}-composer-attach`,composerFileInput:`${K}-composer-file-input`,composerVoice:`${K}-composer-voice`,attachmentChip:`${K}-attachment-chip`,attachmentRemove:`${K}-attachment-remove`,suggestion:`${K}-suggestion`,messageBubble:`${K}-message`,messageRetry:`${K}-message-retry`,messageFeedback:`${K}-message-feedback`,feedbackUp:`${K}-feedback-up`,feedbackDown:`${K}-feedback-down`,messageCopy:`${K}-message-copy`,historyPane:`${K}-history-pane`,historyBack:`${K}-history-back`,historyItem:`${K}-history-item`,historyLoadMore:`${K}-history-load-more`,sidebar:`${K}-sidebar`,sidebarToggle:`${K}-sidebar-toggle`,sidebarNewConversation:`${K}-sidebar-new-conversation`,sidebarItem:`${K}-sidebar-item`,messengerHome:`${K}-messenger-home`,modulesEmpty:`${K}-modules-empty`,tab:`${K}-tab`,tabBadge:`${K}-tab-badge`,homeView:`${K}-home-view`,homeGreeting:`${K}-home-greeting`,homeBrand:`${K}-home-brand`,backHeader:`${K}-back-header`,contentView:`${K}-content-view`,contentScroll:`${K}-content-scroll`,homeSearch:`${K}-home-search`,helpSearch:`${K}-help-search`,homeRecent:`${K}-home-recent`,homeContentRow:`${K}-home-content-row`,helpArticle:`${K}-help-article`,newsItem:`${K}-news-item`,formGate:`${K}-form-gate`,formDone:`${K}-form-done`,formDoneToggle:`${K}-form-done-toggle`,formAnswers:`${K}-form-answers`,formFill:`${K}-form-fill`,formSubmit:`${K}-form-submit`,formSkip:`${K}-form-skip`,formField:`${K}-form-field`,toolAskQuestions:`${K}-tool-ask-questions`,toolInputSubmit:`${K}-tool-input-submit`,toolInputSkip:`${K}-tool-input-skip`,toolApproval:`${K}-tool-approval`,toolApprove:`${K}-tool-approve`,toolReject:`${K}-tool-reject`,toolEdit:`${K}-tool-edit`,toolDecision:`${K}-tool-decision`,typingDots:`${K}-typing-dots`,reasoning:`${K}-reasoning`,toolAskSummary:`${K}-ask-questions-summary`,toolAskOptions:`${K}-ask-questions-options-toggle`,toolCall:`${K}-tool-call`,source:`${K}-source`,operatorRequest:`${K}-operator-request`,operatorBanner:`${K}-operator-banner`,cancelOperatorRequest:`${K}-cancel-operator-request`};function Ci(e,t){return`${e}-${t}`}const wi=b.cssPrefix;function Ti({onToggle:e,launcher:t,strings:n,leaving:r,edgeTab:i}){let a=t.variant!==`circle`&&!!t.label;return _(`button`,{type:`button`,class:`${wi}-fab`,"data-variant":t.variant,"data-size":t.size,"data-edge-tab":i?`true`:void 0,"data-leaving":r?`true`:void 0,"data-testid":q.launcher,onClick:e,"aria-label":n.launcherOpen,children:[Ei(t.icon),a?g(`span`,{class:`${wi}-fab-label`,children:D(n,t.label??``)}):null]})}function Ei(e){let t=Si[e];return t?g(t,{}):g(Di,{source:e})}function Di({source:e}){return g(`span`,{ref:t=>{t&&Oi(t,e)},"aria-hidden":`true`})}function Oi(e,t){if(e.dataset.svgMounted!==t)try{let n=new DOMParser().parseFromString(t,`image/svg+xml`).documentElement;n&&n.tagName.toLowerCase()===`svg`&&(e.replaceChildren(document.importNode(n,!0)),e.dataset.svgMounted=t)}catch{}}function ki({callout:e,launcherPosition:t,strings:n,closeLabel:r,onDismiss:a}){let[o,s]=c(!1);return i(()=>{let t=setTimeout(()=>s(!0),e.delayMs);return()=>clearTimeout(t)},[e.delayMs]),i(()=>{if(!o||e.autoDismissMs<=0)return;let t=setTimeout(a,e.autoDismissMs);return()=>clearTimeout(t)},[o,e.autoDismissMs,a]),o?_(`div`,{class:`${wi}-callout`,role:`status`,"data-shape":e.shape,"data-position":Ai(e.position,t),"data-animated":e.animated?`true`:void 0,"data-testid":q.callout,children:[g(`span`,{children:D(n,e.text)}),g(`button`,{type:`button`,class:`${wi}-callout-close`,onClick:a,"aria-label":r,title:r,"data-testid":q.calloutDismiss,children:g(Cr,{})})]}):null}function Ai(e,t){let n=t.endsWith(`-right`),r=t.startsWith(`bottom-`);return e===`vertical`?r?`top`:`bottom`:n?`left`:`right`}function ji({panelEl:e,resize:t,position:n,initialSize:r,onSizeChange:a,strings:o}){let c=b.cssPrefix,l=s(null);if(i(()=>{if(!e)return;let n=e.style;t.minWidth&&n.setProperty(`--${c}-resize-min-w`,t.minWidth),t.maxWidth&&n.setProperty(`--${c}-resize-max-w`,t.maxWidth),t.minHeight&&n.setProperty(`--${c}-resize-min-h`,t.minHeight),t.maxHeight&&n.setProperty(`--${c}-resize-max-h`,t.maxHeight),r&&(n.setProperty(`--${c}-widget-w`,`${r.width}px`),n.setProperty(`--${c}-widget-h`,`${r.height}px`))},[e,t.minWidth,t.maxWidth,t.minHeight,t.maxHeight,c,r]),!e)return null;let u=n.startsWith(`top-`),d=n.endsWith(`-right`),f=`${c}-resize-grip ${c}-resize-grip--${u?`bottom`:`top`}-${d?`left`:`right`}`,p=t=>{if(!e)return;let n=t.currentTarget,r=e.getBoundingClientRect();l.current={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,startW:r.width,startH:r.height,dirX:d?-1:1,dirY:u?1:-1},n.setPointerCapture(t.pointerId),e.setAttribute(`data-resizing`,``),t.preventDefault()},m=t=>{let n=l.current;if(!n||t.pointerId!==n.pointerId||!e)return;let r=(t.clientX-n.startX)*n.dirX,i=(t.clientY-n.startY)*n.dirY;e.style.setProperty(`--${c}-widget-w`,`${n.startW+r}px`),e.style.setProperty(`--${c}-widget-h`,`${n.startH+i}px`)},h=t=>{let n=l.current;if(!n||t.pointerId!==n.pointerId||!e)return;t.currentTarget.releasePointerCapture(t.pointerId),e.removeAttribute(`data-resizing`);let r=e.getBoundingClientRect();a({width:Math.round(r.width),height:Math.round(r.height)}),l.current=null};return g(`div`,{class:f,role:`separator`,"aria-orientation":`vertical`,"aria-label":o.resizeHandle,title:o.resizeHandle,onPointerDown:p,onPointerMove:m,onPointerUp:h,onPointerCancel:h,"data-testid":q.resizeGrip,children:g(Lr,{})})}const Mi=b.cssPrefix,Ni=`.${Mi}-header, .${Mi}-back-header, .${Mi}-home-hero`;function Pi(e,t){i(()=>{if(!t||!e)return;let n=e=>Number.parseFloat(e)||0,r=(e,t)=>Math.min(t,Math.max(-t,e)),i=null,a=t=>{let r=t.target;if(!(r instanceof Element)||!r.closest(Ni)||r.closest(`button, a, input, textarea, select, [role="tab"], [contenteditable]`))return;let a=e.getBoundingClientRect();i={id:t.pointerId,x:t.clientX,y:t.clientY,dx:n(e.style.getPropertyValue(`--${Mi}-modal-dx`)),dy:n(e.style.getPropertyValue(`--${Mi}-modal-dy`)),maxX:(window.innerWidth+a.width)/2-56,maxY:(window.innerHeight+a.height)/2-56},e.dataset.dragging=`true`,t.preventDefault()},o=t=>{if(!i||t.pointerId!==i.id)return;let n=r(i.dx+t.clientX-i.x,i.maxX),a=r(i.dy+t.clientY-i.y,i.maxY);e.style.setProperty(`--${Mi}-modal-dx`,`${n}px`),e.style.setProperty(`--${Mi}-modal-dy`,`${a}px`)},s=t=>{!i||t.pointerId!==i.id||(i=null,delete e.dataset.dragging)};return e.addEventListener(`pointerdown`,a),window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s),window.addEventListener(`pointercancel`,s),()=>{e.removeEventListener(`pointerdown`,a),window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s)}},[e,t])}function Fi(e,t,n){switch(e){case`clear`:case`sound`:case`history`:case`language`:case`theme`:case`textSize`:return!0;case`popOut`:return t!==`standalone`&&t!==`page`;case`expand`:return t===`floating`;case`fullscreen`:return t!==`standalone`;case`close`:return t===`standalone`||t===`page`?!1:t!==`inline`||n===`fullscreen`}}function Ii(e,t,n){return Fi(`close`,e,t)?n.includes(`close`):!1}function Li(e,t){return e===`inline`&&t===`fullscreen`?`exit-fullscreen`:`close`}function Ri(e){let t=t=>{if(t.key!==`Tab`)return;let n=[...e.querySelectorAll(`a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),[tabindex]:not([tabindex="-1"])`)].filter(e=>e.offsetParent!==null||e===document.activeElement);if(n.length===0){t.preventDefault();return}let r=n[0],i=n[n.length-1];if(!r||!i)return;let a=e.getRootNode().activeElement;t.shiftKey&&a===r?(t.preventDefault(),i.focus()):!t.shiftKey&&a===i&&(t.preventDefault(),r.focus())};return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)}function zi(e){return e.trim().split(/\s+/).slice(0,2).map(e=>e.charAt(0).toUpperCase()).join(``)}const Bi=b.cssPrefix;function Vi({agent:e,strings:t}){let n=e.status??`online`,r=D(t,e.name),i=e.title?D(t,e.title):null;return _(`div`,{class:`${Bi}-agent`,children:[g(`div`,{class:`${Bi}-agent-avatar`,"data-status":n,children:e.avatar?g(`img`,{src:e.avatar,alt:``}):g(`span`,{children:zi(r)})}),_(`div`,{class:`${Bi}-agent-meta`,children:[g(`strong`,{children:r}),i?g(`span`,{children:i}):null]})]})}const Hi=I.scope(`attachments`);function Ui(e,t,n){let r=Ki(e),i=[],a=[],o=Yi(n.accept),s=t.reduce((e,t)=>e+t.size,0),c=t.length;for(let e of r){let t=Gi(e,c,s,n,o);if(t){a.push({file:e,reason:t});continue}i.push(Ji(e)),s+=e.size,c+=1}return(i.length||a.length)&&Hi.debug(`ingest`,{accepted:i.length,rejected:a.map(e=>({name:e.file.name,reason:e.reason}))}),{accepted:i,rejected:a}}function Wi(e){try{URL.revokeObjectURL(e.previewUrl)}catch(e){Hi.debug(`revokeObjectURL failed`,{error:e})}}function Gi(e,t,n,r,i){return t>=r.maxCount?`count`:n+e.size>r.maxBytes?`bytes`:Xi(e,i)?null:`mime`}function Ki(e){return e?Array.isArray(e)?e.filter(e=>e instanceof File):[...e].map(e=>e instanceof File?e:qi(e)).filter(e=>e!==null):[]}function qi(e){let t=e;return!t?.getAsFile||t.kind!==`file`?null:t.getAsFile()}function Ji(e){return{file:e,id:ct(),mediaType:e.type||`application/octet-stream`,name:e.name||`pasted-file`,previewUrl:URL.createObjectURL(e),size:e.size}}function Yi(e){return e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean).map(e=>{if(e.startsWith(`.`))return{kind:`ext`,ext:e};let[t=`*`,n=`*`]=e.split(`/`);return{kind:`mime`,type:t,subtype:n}})}function Xi(e,t){if(t.length===0)return!0;let[n=`*`,r=`*`]=(e.type||``).toLowerCase().split(`/`),i=(e.name||``).toLowerCase();return t.some(e=>e.kind===`ext`?i.endsWith(e.ext):(e.type===`*`||e.type===n)&&(e.subtype===`*`||e.subtype===r))}const Zi=b.cssPrefix;function Qi({attachment:e,onRemove:t,disabled:n=!1}){let r=e.mediaType.startsWith(`image/`);return _(`span`,{class:`${Zi}-attachment-chip`,title:e.name,"data-testid":Ci(q.attachmentChip,e.id),children:[r?g(`img`,{class:`${Zi}-attachment-thumb`,src:e.previewUrl,alt:``}):g(`span`,{class:`${Zi}-attachment-thumb`,"aria-hidden":`true`,children:g(Yr,{})}),g(`span`,{class:`${Zi}-attachment-name`,children:e.name}),g(`button`,{type:`button`,class:`${Zi}-attachment-remove`,onClick:t,disabled:n,"aria-label":`Remove ${e.name}`,"data-testid":Ci(q.attachmentRemove,e.id),children:g(Cr,{})})]})}const $i={isSupported:!1,start:()=>void 0,stop:()=>void 0,cancel:()=>void 0};function ea(e,t,n){return e===`disabled`?$i:e===`server`?ia(n):ta(t)}function ta(e){let t=na();if(!t)return $i;let n=null,r=0;return{isSupported:!0,start(i,a){let o=n,s=++r;n=null,o?.abort();let c=new t;n=c,c.continuous=!0,c.interimResults=!0,c.lang=e;let l=!1;c.addEventListener(`result`,e=>{if(r!==s||n!==c)return;let t=e,a=``,o=!1;for(let e=t.resultIndex;e<t.results.length;e++){let n=t.results[e];n&&(a+=n[0].transcript,n.isFinal&&(o=!0))}i(a,o)});let u=()=>{l||r!==s||n!==c||(l=!0,n=null,a())};c.addEventListener(`end`,u),c.addEventListener(`error`,u);try{c.start()}catch{u()}},stop(){n?.stop()},cancel(){r++;let e=n;n=null,e?.abort()}}}function na(){return window.SpeechRecognition??window.webkitSpeechRecognition}const ra=[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/mp4`];function ia(e){if(typeof MediaRecorder>`u`||!navigator?.mediaDevices?.getUserMedia)return $i;let t=0,n=null,r=e=>{for(let t of e.stream?.getTracks()??[])t.stop();e.stream=null},i=()=>{t++;let e=n;n=null,e&&(r(e),e.recorder?.state!==`inactive`&&e.recorder?.stop())},a=async i=>{if(i.finishing)return;i.finishing=!0;let a=i.recorder?.mimeType??`audio/webm`;r(i);let o=new Blob(i.chunks,{type:a});i.chunks=[];try{let{text:r}=await e(o,a);n===i&&t===i.generation&&r&&i.onText(r,!0)}catch{}finally{n===i&&t===i.generation&&(n=null,i.onEnd())}};return{isSupported:!0,async start(e,o){i();let s={generation:t,recorder:null,stream:null,chunks:[],onText:e,onEnd:o,finishing:!1};n=s;try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});if(n!==s||t!==s.generation){for(let t of e.getTracks())t.stop();return}s.stream=e;let r=aa(),i=new MediaRecorder(e,r?{mimeType:r}:void 0);s.recorder=i,i.addEventListener(`dataavailable`,e=>{n===s&&t===s.generation&&e.data.size>0&&s.chunks.push(e.data)}),i.addEventListener(`stop`,()=>{n===s&&t===s.generation&&a(s)}),i.start()}catch{r(s),n===s&&t===s.generation&&(n=null,o())}},stop(){let e=n;if(e){if(!e.recorder){i();return}e.recorder.state!==`inactive`&&e.recorder.stop()}},cancel(){i()}}}function aa(){for(let e of ra)if(MediaRecorder.isTypeSupported(e))return e}const J=b.cssPrefix,oa=I.scope(`composer`);function sa(e){return e.reduce((e,t)=>e+t.size,0)}const ca={arrowUp:Er,paperPlane:Tr,send:Dr,chevron:Or};function la(e){return`activeElement`in e}function ua(e){return`host`in e&&`activeElement`in e}function da({options:e,transport:t,feedback:n,bus:a,persistence:o,conversationId:l,isStreaming:u,isMemoryCompacting:d=!1,canReleaseQueuedMessages:f=!0,queueManualMessages:p=!1,active:m=!0,isPreparing:h=!1,operatorRequestEnabled:v,canRequestOperator:y=!1,controlMode:b=`ai-agent`,onRequestOperator:x,onSend:S,onStop:C,apiRef:w}){let T=e.strings,[E,D]=c(()=>o.loadDraft(l)),[O,k]=c([]),[A,j]=c(()=>o.loadMessageQueue(l).map(e=>({id:e.id,text:e.text,attachments:[]}))),M=s(A),ee=s(!1),[te,N]=c(!1),[ne,re]=c(!1),P=s(!1),F=s(null),ie=s(null),ae=s(null),I=s(0),L=s(l);L.current=l;let oe=s(m);oe.current=m;let se=s(h);se.current=h;let ce=ne||h||!m,le=u&&b===`ai-agent`,ue=le||d&&b===`ai-agent`,de=b===`ai-agent`&&(ue||p||A.length>0),fe=r(e=>{j(t=>{let n=e(t);return o.saveMessageQueue(L.current,n.filter(e=>e.attachments.length===0).map(({id:e,text:t})=>({id:e,text:t}))),M.current=n,n})},[o]),pe=r(e=>{fe(t=>(t.find(t=>t.id===e)?.attachments.forEach(Wi),t.filter(t=>t.id!==e)))},[fe]),me=r(e=>{D(t=>{let n=typeof e==`function`?e(t):e;return n===t?t:(o.saveDraft(L.current,n),n)})},[o]),R=e.features.fileUpload,he=e.features.voice,[ge,_e]=c(()=>ea(he,e.locale,(e,n)=>t.transcribe(e,n))),ve=s(ge);ve.current=ge;let z=s({mode:he,locale:e.locale,transport:t});i(()=>{let n=z.current;(n.mode!==he||n.locale!==e.locale||n.transport!==t)&&(z.current={mode:he,locale:e.locale,transport:t},I.current++,ve.current.cancel(),ae.current=null,N(!1),_e(ea(he,e.locale,(e,n)=>t.transcribe(e,n))))},[e.locale,he,t]),i(()=>()=>{I.current++,ge.cancel()},[ge]);let ye=r(e=>{let t=ae.current;if(t===null)return!1;let n=Math.round(performance.now()-t);return oa[e](`voiceStop`,{durationMs:n}),a.emit(`voiceStop`,{durationMs:n}),ae.current=null,!0},[a]),be=r(()=>{ae.current!==null&&(ge.stop(),N(!1),ye(`info`)&&n.play(`voiceStop`))},[ye,n,ge]),xe=r(()=>{I.current++,ge.cancel(),N(!1),ye(`info`)&&n.play(`voiceStop`)},[ye,n,ge]);i(()=>{(h||!m)&&xe()},[m,xe,h]),i(()=>{let e=F.current;if(!e)return;let t=e.getRootNode(),n=la(t)?t.activeElement:null;n&&e.closest(`.${J}-panel`)?.contains(n)||e.focus({preventScroll:!0})},[]),i(()=>{let e=F.current;if(!e)return;if(E.length===0){e.style.height=``;return}e.style.height=`auto`;let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--${J}-textarea-base-height`)),r=Number.parseFloat(t.borderTopWidth)+Number.parseFloat(t.borderBottomWidth),i=Math.min(e.scrollHeight+r,Number.parseFloat(t.maxHeight)),a=Number.parseFloat(t.fontSize)*.7;e.style.height=`${i<n+a?n:i}px`},[E]);let Se=s(O);Se.current=O,i(()=>()=>{Se.current.forEach(Wi);for(let e of M.current)e.attachments.forEach(Wi)},[]),i(()=>{if(w)return w.current={attachFromDrop:t=>{if(!R||!oe.current||P.current||se.current)return;let n=Ui(t,Se.current,e.attachments);n.accepted.length!==0&&(oa.info(`attach (drop)`,{count:n.accepted.length,totalBytes:sa(n.accepted)}),a.emit(`attach`,{count:n.accepted.length,totalBytes:sa(n.accepted)}),k(e=>[...e,...n.accepted]))},fill:e=>{if(!oe.current||P.current||se.current)return;me(e);let t=F.current;t&&(t.focus({preventScroll:!0}),requestAnimationFrame(()=>t.setSelectionRange(t.value.length,t.value.length)))},acceptQueuedMessage:pe},()=>{w.current&&(w.current=null)}},[w,R,h,e.attachments,pe,me]),i(()=>{let t=F.current;if(!t)return;let n=t.closest(`.${J}-panel`);if(!n)return;let r=n=>{if(!oe.current||P.current||se.current)return;let r=n.clipboardData;if(!r)return;let i=n.target?.closest?.(`input, textarea, [contenteditable]:not([contenteditable='false'])`);if(i&&i!==t)return;if(R){let t=Ui(r.items,Se.current,e.attachments);if(t.accepted.length>0){n.preventDefault(),oa.info(`attach (paste)`,{count:t.accepted.length,totalBytes:sa(t.accepted)}),a.emit(`attach`,{count:t.accepted.length,totalBytes:sa(t.accepted)}),k(e=>[...e,...t.accepted]);return}}if(i===t)return;let o=r.getData(`text/plain`);o&&(n.preventDefault(),me(e=>e+o),t.focus())};return n.addEventListener(`paste`,r),()=>n.removeEventListener(`paste`,r)},[R,e.attachments,me]);let Ce=async()=>{let e=E.trim();if(!e&&O.length===0||!m||le||P.current||h)return;xe(),P.current=!0,re(!0);let t=E,n=O;try{await S(e,n)&&(me(e=>e===t?``:e),k(e=>e===n?(n.forEach(Wi),Se.current=[],[]):e))}finally{P.current=!1,re(!1),requestAnimationFrame(()=>{let e=F.current;if(!e||e.disabled||!oe.current)return;let t=e.getRootNode(),n=la(t)?t.activeElement:null,r=n?.getAttribute(`data-testid`);if(!(n&&n!==e&&r!==q.composerSend&&r!==q.composerStop)){if(ua(t)){let e=t.host.ownerDocument;if(!e.hasFocus())return;let n=e.activeElement;if(n&&n!==t.host&&n!==e.body)return}e.focus({preventScroll:!0})}})}},we=()=>{let e=E.trim();if(!e&&O.length===0||!m||!de||P.current||h)return;xe();let t=O;fe(n=>[...n,{id:ct(),text:e,attachments:t}]),me(``),k(e=>e===t?(Se.current=[],[]):e),F.current?.focus({preventScroll:!0})};i(()=>{ue&&(ee.current=!1)},[ue]),i(()=>{let e=A[0];if(!e||!f||ue||ee.current||ne||h||!m)return;let t=setTimeout(()=>{ee.current=!0,S(e.text,e.attachments,e.id).then(t=>{if(t){pe(e.id);return}ee.current=!1})},300);return()=>clearTimeout(t)},[m,f,h,S,ue,A,pe,ne]);let Te=e=>{e.key!==`Enter`||e.shiftKey||e.isComposing||(e.preventDefault(),de&&(E.trim()||O.length>0)?we():le?C():Ce())},Ee=t=>{let n=t.target;if(!m||P.current||h){n.value=``;return}let r=Ui(n.files,O,e.attachments);r.accepted.length>0&&(oa.info(`attach (file picker)`,{count:r.accepted.length,totalBytes:sa(r.accepted)}),a.emit(`attach`,{count:r.accepted.length,totalBytes:sa(r.accepted)}),k(e=>[...e,...r.accepted])),n.value=``},De=e=>{!m||P.current||h||(oa.info(`removeAttachment`,{id:e}),a.emit(`removeAttachment`,{id:e}),k(t=>{let n=t.find(t=>t.id===e);return n&&Wi(n),t.filter(t=>t.id!==e)}))},Oe=()=>{if(te){be();return}if(!m||!ge.isSupported||P.current||h)return;let e=++I.current;ae.current=performance.now(),oa.info(`voiceStart`),a.emit(`voiceStart`,void 0),N(!0),n.play(`voiceStart`),ge.start((t,n)=>{I.current!==e||!oe.current||se.current||P.current||!n||me(e=>`${e}${t} `)},()=>{I.current!==e||!oe.current||(N(!1),ye(`debug`))})},ke=ca[e.composer.sendButton.icon],Ae=!!(E.trim()||O.length>0);return _(`div`,{class:`${J}-composer`,"data-testid":q.composer,children:[A.length>0?g(`div`,{class:`${J}-message-queue`,"aria-label":T.queueMessage,"data-testid":q.messageQueue,children:A.map(e=>_(`div`,{class:`${J}-attachment-chip ${J}-queued-message`,"data-testid":`${q.queuedMessage}-${e.id}`,children:[g(`span`,{class:`${J}-attachment-name ${J}-queued-text`,children:e.text||e.attachments.map(e=>e.name).join(`, `)}),g(`button`,{type:`button`,class:`${J}-attachment-remove`,onClick:()=>pe(e.id),"aria-label":T.removeQueuedMessage,title:T.removeQueuedMessage,"data-testid":`${q.queuedMessageRemove}-${e.id}`,children:g(Cr,{})})]},e.id))}):null,O.length>0?g(`div`,{class:`${J}-attachments`,children:O.map(e=>g(Qi,{attachment:e,onRemove:()=>De(e.id),disabled:ce},e.id))}):null,_(`div`,{class:`${J}-composer-row`,children:[_(`div`,{class:`${J}-composer-actions`,children:[R?g(`button`,{type:`button`,class:`${J}-icon-btn`,onClick:()=>ie.current?.click(),disabled:ce,"aria-label":T.attach,"data-testid":q.composerAttach,children:g(Ar,{})}):null,ge.isSupported?g(`button`,{type:`button`,class:`${J}-icon-btn`,onClick:Oe,disabled:ce,"aria-label":te?T.micStop:T.micStart,"aria-pressed":te,"data-recording":te?`true`:void 0,"data-testid":q.composerVoice,children:g(jr,{})}):null]}),g(`textarea`,{ref:F,name:`message`,class:`${J}-textarea`,rows:1,value:E,placeholder:T.composerPlaceholder,onInput:e=>me(e.currentTarget.value),onKeyDown:Te,disabled:ce,"aria-label":T.composerPlaceholder,"data-testid":q.composerInput}),de&&Ae?g(`button`,{type:`button`,class:`${J}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:we,disabled:ce,"aria-label":T.queueMessage,title:T.queueMessage,"data-testid":q.composerSend,children:g(ke,{})}):null,le?g(`button`,{type:`button`,class:`${J}-send`,onClick:C,disabled:ce,"aria-label":T.stop,"data-testid":q.composerStop,children:g(kr,{})}):null,!le&&(!de||!Ae)?g(`button`,{type:`button`,class:`${J}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:()=>void Ce(),disabled:ce||!E.trim()&&O.length===0,"aria-label":T.send,"data-testid":q.composerSend,children:g(ke,{})}):null,v&&b===`ai-agent`&&x?g(`button`,{type:`button`,class:`${J}-icon-btn`,onClick:x,disabled:ce||!y,"aria-label":T.talkToOperator,title:T.talkToOperator,"data-testid":q.operatorRequest,children:g(ti,{})}):null]}),g(`input`,{ref:ie,name:`attachments`,type:`file`,multiple:!0,accept:e.attachments.accept,onChange:Ee,disabled:ce,class:`${J}-sr-only`,"data-testid":q.composerFileInput})]})}const fa=b.cssPrefix;function pa({visible:e,strings:t}){return e?g(`div`,{class:`${fa}-dropzone`,role:`status`,"aria-live":`polite`,children:t.dropZone}):null}function ma({containerRef:e,onDrop:t,disabled:n=!1}){let[r,a]=c(!1);return i(()=>{if(n){a(!1);return}let r=e.current;if(!r)return;let i=0,o=e=>{i+=1,e.dataTransfer?.types.includes(`Files`)&&(e.preventDefault(),a(!0))},s=()=>{--i,!(i>0)&&(i=0,a(!1))},c=e=>{e.dataTransfer?.types.includes(`Files`)&&e.preventDefault()},l=e=>{i=0,a(!1),e.dataTransfer&&(e.preventDefault(),t(e.dataTransfer.items))};return r.addEventListener(`dragenter`,o),r.addEventListener(`dragleave`,s),r.addEventListener(`dragover`,c),r.addEventListener(`drop`,l),()=>{r.removeEventListener(`dragenter`,o),r.removeEventListener(`dragleave`,s),r.removeEventListener(`dragover`,c),r.removeEventListener(`drop`,l)}},[e,n,t]),{visible:!n&&r}}function ha({itemCount:e,initialFocusIndex:t}){let[n,a]=c(!1),o=s(null),l=s(null),[u,d]=c(-1),f=r(()=>{a(!1),d(-1),o.current?.focus()},[]),p=r(()=>a(e=>!e),[]);return i(()=>{if(!n)return;let e=e=>{let t=l.current,n=o.current;if(!t||!n)return;let r=e.composedPath();r.includes(t)||r.includes(n)||(a(!1),d(-1))};return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[n]),i(()=>{if(!n||e===0)return;let r=t?.()??0;d(r<0||r>=e?0:r)},[n,e,t]),i(()=>{!n||u<0||(l.current?.querySelectorAll(`[role='menuitem']`))?.[u]?.focus()},[n,u]),{open:n,focusIndex:u,triggerRef:o,menuRef:l,toggle:p,close:f,onTriggerKey:r(e=>{(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a(!0))},[]),onMenuKey:r(t=>{if(e!==0)switch(t.key){case`Escape`:t.preventDefault(),f();return;case`ArrowDown`:t.preventDefault(),d(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),d(t=>(t-1+e)%e);return;case`Home`:t.preventDefault(),d(0);return;case`End`:t.preventDefault(),d(e-1)}},[e,f])}}function ga({items:e,triggerLabel:t}){let n=b.cssPrefix,r=ha({itemCount:e.length}),i=e=>{e.disabled||(e.onSelect?.(),e.keepOpen||r.close())},a=(e,t)=>e.onSelectValue?.(t),o=(e,t)=>{let n=t.segments;if(!n?.length)return;let r=Math.max(0,n.findIndex(e=>e.value===t.value)),i=-1;if(e.key===`ArrowRight`||e.key===`Enter`||e.key===` `)i=(r+1)%n.length;else if(e.key===`ArrowLeft`)i=(r-1+n.length)%n.length;else return;e.preventDefault(),e.stopPropagation(),a(t,n[i].value)};return _(`div`,{class:`${n}-menu-wrap`,children:[g(`button`,{ref:r.triggerRef,type:`button`,class:`${n}-icon-btn`,"aria-label":t,"aria-haspopup":`menu`,"aria-expanded":r.open,title:t,onClick:r.toggle,onKeyDown:r.onTriggerKey,children:g(Rr,{})}),r.open?g(`div`,{ref:r.menuRef,class:`${n}-menu`,role:`menu`,"aria-label":t,onKeyDown:r.onMenuKey,tabIndex:-1,children:e.map(e=>e.segments?_(`div`,{role:`menuitem`,class:`${n}-menu-item ${n}-menu-item-segmented`,"aria-label":e.label,tabIndex:-1,onKeyDown:t=>o(t,e),children:[e.icon?g(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,g(`span`,{class:`${n}-menu-label`,children:e.label}),g(`span`,{class:`${n}-segmented`,role:`group`,"aria-label":e.label,children:e.segments.map(t=>{let r=t.value===e.value;return g(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":r,class:`${n}-segment`,"data-on":r?`true`:void 0,lang:t.lang,title:t.value,tabIndex:-1,"data-testid":`${q.langSegment}-${t.value}`,onClick:()=>a(e,t.value),children:t.label},t.value)})})]},e.id):_(`button`,{type:`button`,role:`menuitem`,class:`${n}-menu-item`,"aria-pressed":e.type===`switch`?e.on:void 0,disabled:e.disabled,onClick:()=>i(e),children:[e.icon?g(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,g(`span`,{class:`${n}-menu-label`,children:e.label}),e.type===`switch`&&e.on?g(`span`,{class:`${n}-menu-check`,"aria-hidden":`true`,children:g(Ur,{})}):null]},e.id))}):null]})}const _a=b.cssPrefix;function va(e){let t=typeof matchMedia!=`function`||matchMedia(`(prefers-color-scheme: dark)`).matches;return e===`auto`?t?`light`:`dark`:t?e===`light`?`dark`:`auto`:e===`dark`?`light`:`auto`}const ya={normal:`large`,large:`small`,small:`normal`};function ba(e){return g(e===`light`?ci:e===`dark`?li:ui,{})}function xa(e){return(e.split(`-`)[0]??e).toUpperCase()}function Sa(e,t){let n;try{n=new URL(e,window.location.href)}catch{return}if(n.protocol===`http:`||n.protocol===`https:`)return t.conversationId&&n.searchParams.set(`chat`,t.conversationId),n.searchParams.set(`widgetId`,t.widgetId),t.publicKey&&n.searchParams.set(`public_key`,t.publicKey),n.searchParams.set(`ai_agent_deployment_id`,t.aiAgentDeploymentId),n.href}function Ca({panelProps:e,variant:t}){let{options:n,panelSize:r,feedback:i,onClose:a,onClear:o,onExpand:s,onFullscreen:c,onSoundToggle:l}=e,{onToggleHistory:u,onLocaleChange:d,onThemeChange:f,onTextSizeChange:m}=e,h=n.strings,v=n.mode,y=t===`chat`,b=p(()=>i.mutedSig.value).value,x=new Set(n.actions),S=e=>x.has(e),C=typeof matchMedia==`function`&&matchMedia(`(max-width: 640px)`).matches,w=e=>!C&&Fi(e,v,r),T=n.themeMode,E={auto:h.themeAuto,light:h.themeLight,dark:h.themeDark},D=n.textSize,O={small:h.textSizeSmall,normal:h.textSizeNormal,large:h.textSizeLarge},k=[];if(y&&S(`clear`)&&k.push({id:`clear`,icon:g(qr,{}),label:h.newConversation,onSelect:o}),S(`expand`)&&w(`expand`)){let e=r===`expanded`;k.push({id:`expand`,icon:g(e?Nr:Mr,{}),label:e?h.collapse:h.expand,type:`switch`,on:e,onSelect:s})}if(S(`fullscreen`)&&w(`fullscreen`)){let e=r===`fullscreen`;k.push({id:`fullscreen`,icon:g(e?Fr:Pr,{}),label:e?h.exitFullscreen:h.fullscreen,type:`switch`,on:e,onSelect:c})}let A=n.popOutUrl,j=n.aiAgentDeploymentId;S(`popOut`)&&A&&j&&Fi(`popOut`,v,r)&&k.push({id:`popOut`,icon:g(Ir,{}),label:h.popOut,onSelect:()=>{let t=Sa(A,{conversationId:e.conversationId,widgetId:n.widgetId,publicKey:n.publicKey,aiAgentDeploymentId:j});t&&window.open(t,`_blank`,`noopener,noreferrer`)}}),y&&S(`sound`)&&k.push({id:`sound`,icon:g(b?Br:zr,{}),label:b?h.soundOff:h.soundOn,type:`switch`,on:!b,onSelect:l}),S(`theme`)&&k.push({id:`theme`,icon:ba(T),label:`${h.theme}: ${E[T]}`,onSelect:()=>f(va(T)),keepOpen:!0}),S(`textSize`)&&k.push({id:`textSize`,icon:g(Vr,{}),label:`${h.textSize}: ${O[D]}`,onSelect:()=>m(ya[D]),keepOpen:!0}),S(`language`)&&n.availableLocales.length>1&&k.push({id:`language`,icon:g(Gr,{}),label:h.language,segments:n.availableLocales.map(e=>({value:e,label:xa(e),lang:e})),value:n.locale,onSelectValue:d});let M=!!a&&Ii(v,r,n.actions),ee=y&&S(`history`);return _(`div`,{class:`${_a}-header-actions`,children:[ee?g(`button`,{type:`button`,class:`${_a}-icon-btn`,onClick:u,"aria-label":h.history,title:h.history,"data-testid":q.actionHistory,children:g(Wr,{})}):null,k.length>0?g(ga,{items:k,triggerLabel:h.moreActions}):null,M?g(`button`,{type:`button`,class:`${_a}-icon-btn`,onClick:a,"aria-label":h.close,title:h.close,"data-testid":q.actionClose,children:g(Cr,{})}):null]})}const wa=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ta=/^https?:\/\/[^\s.]+\.[^\s]+$/i,Ea=/^[+]?[\d\s().-]{6,}$/;function Da(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>String(t[n]??`{${n}}`))}function Oa(e){return Array.isArray(e)?e.length:e&&e.trim()?1:0}function ka(e,t,n){let r=e.required??!0,i=e.validation;if(e.type===`multiselect`){let e=Oa(t);return r&&e===0?n.formRequired:e===0?void 0:i?.minSelections!=null&&e<i.minSelections?Da(n.formChooseAtLeast,{min:i.minSelections}):i?.maxSelections!=null&&e>i.maxSelections?Da(n.formChooseAtMost,{max:i.maxSelections}):void 0}let a=typeof t==`string`?t.trim():``;if(!a)return r?n.formRequired:void 0;switch(e.type){case`email`:if(!wa.test(a))return n.formInvalidEmail;break;case`url`:if(!Ta.test(a))return n.formInvalidUrl;break;case`tel`:if(!Ea.test(a))return n.formInvalidTel;break;case`number`:{let e=Number(a);if(!Number.isFinite(e))return n.formInvalidNumber;if(i?.min!=null&&e<i.min)return Da(n.formNumberTooSmall,{min:i.min});if(i?.max!=null&&e>i.max)return Da(n.formNumberTooLarge,{max:i.max});break}default:break}if(i?.minLength!=null&&a.length<i.minLength)return Da(n.formTooShort,{min:i.minLength});if(i?.maxLength!=null&&a.length>i.maxLength)return Da(n.formTooLong,{max:i.maxLength});if(i?.pattern)try{if(!new RegExp(i.pattern).test(a))return n.formPatternMismatch}catch{}}function Aa(e,t,n){let r={};for(let i of e){let e=ka(i,t[i.name],n);e&&(r[i.name]=e)}return r}function ja(e){let t={};for(let[n,r]of Object.entries(e)){let e=Array.isArray(r)?r.join(`, `):r;e&&e.trim()&&(t[n]=e.trim())}return t}const Y=b.cssPrefix,Ma=`__other__`;function Na({fields:e,strings:t,submitLabel:n,onSubmit:r,skipLabel:i,onSkip:a,footerHint:o,submitOnEnter:s,disabled:l,initialValues:u,hideActions:d,fieldTypeLabels:f,rootTestId:p,submitTestId:m,skipTestId:h}){let[v,y]=c(()=>({...La(e),...u})),[b,x]=c({}),[S,C]=c({}),w=e=>{S[e]&&C(t=>({...t,[e]:``}))},T=(e,t)=>{y(n=>({...n,[e]:t})),w(e)},E=(e,t)=>{x(n=>({...n,[e]:t})),w(e)},D=n=>{if(n.preventDefault(),l)return;let i=Ra(e,v,b),a=Aa(e,i,t);if(Object.keys(a).length>0){C(a);return}r(ja(i))};return _(`form`,{class:`${Y}-form`,onSubmit:D,onKeyDown:e=>{!s||e.key!==`Enter`||e.shiftKey||e.isComposing||e.target?.tagName===`TEXTAREA`&&D(e)},"data-testid":p,noValidate:!0,children:[e.map(e=>g(Pa,{field:e,value:v[e.name],otherText:b[e.name]??``,error:S[e.name],disabled:l,typeLabel:f?.[e.name],strings:t,onChange:t=>T(e.name,t),onOtherChange:t=>E(e.name,t)},e.name)),d?null:_(`div`,{class:`${Y}-form-actions`,children:[o?g(`span`,{class:`${Y}-form-hint`,children:o}):null,i&&a?g(`button`,{type:`button`,class:`${Y}-form-skip`,onClick:a,disabled:l,"data-testid":h,children:i}):null,g(`button`,{type:`submit`,class:`${Y}-form-submit`,disabled:l,"data-testid":m,children:n})]})]})}function Pa({field:e,value:t,otherText:n,error:r,disabled:i,typeLabel:a,strings:o,onChange:s,onOtherChange:c}){let l=Fa({field:e,value:t,otherText:n,disabled:i,strings:o,onChange:s,onOtherChange:c,fieldTid:Ci(q.formField,e.name)});return _(`label`,{class:`${Y}-field`,"data-field":e.name,"data-invalid":r?`true`:void 0,children:[_(`span`,{class:`${Y}-field-head`,children:[_(`span`,{class:`${Y}-field-label`,children:[e.label,e.required??!0?g(`span`,{class:`${Y}-field-req`,"aria-hidden":`true`,children:` *`}):null]}),a?g(`span`,{class:`${Y}-field-type`,children:a}):null]}),l,e.validationHint&&!r?g(`span`,{class:`${Y}-field-hint`,children:e.validationHint}):null,r?g(`span`,{class:`${Y}-field-error`,role:`alert`,children:r}):null]})}function Fa(e){let{field:t,value:n,otherText:r,disabled:i,strings:a,onChange:o,onOtherChange:s,fieldTid:c}=e,l=typeof n==`string`?n:``;switch(t.type){case`textarea`:return g(`textarea`,{class:`${Y}-field-input`,rows:3,value:l,placeholder:t.placeholder,disabled:i,onInput:e=>o(e.target.value),"data-testid":c});case`select`:return _(`select`,{class:`${Y}-field-input`,value:l,disabled:i,onChange:e=>o(e.target.value),"data-testid":c,children:[g(`option`,{value:``,children:t.placeholder??`—`}),(t.options??[]).map(e=>g(`option`,{value:e.value,children:e.label??e.value},e.value))]});case`radio`:{let e=t.allowOther&&l===Ma;return _(`div`,{class:`${Y}-field-choices`,role:`radiogroup`,"data-testid":c,children:[(t.options??[]).map(e=>_(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`radio`,name:`${Y}-${t.name}`,checked:l===e.value,disabled:i,onChange:()=>o(e.value)}),g(`span`,{children:e.label??e.value})]},e.value)),t.allowOther?_(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`radio`,name:`${Y}-${t.name}`,checked:l===Ma,disabled:i,onChange:()=>o(Ma)}),g(`span`,{children:a.formOther})]}):null,e?g(`input`,{class:`${Y}-field-input`,value:r,placeholder:t.placeholder??a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.target.value)}):null]})}case`checkbox`:return _(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`checkbox`,checked:l===`true`,disabled:i,onChange:e=>o(e.target.checked?`true`:``),"data-testid":c}),g(`span`,{children:t.placeholder??t.label})]});case`multiselect`:{let e=Array.isArray(n)?n:[],l=(t,n)=>o(n?[...e,t]:e.filter(e=>e!==t));return _(`div`,{class:`${Y}-field-choices`,"data-testid":c,children:[(t.options??[]).map(t=>_(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`checkbox`,checked:e.includes(t.value),disabled:i,onChange:e=>l(t.value,e.target.checked)}),g(`span`,{children:t.label??t.value})]},t.value)),t.allowOther||(t.options??[]).length===0?g(`textarea`,{class:`${Y}-field-input`,rows:2,value:r,placeholder:t.placeholder??a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.target.value)}):null]})}default:return g(`input`,{class:`${Y}-field-input`,type:Ia(t.type),value:l,placeholder:t.placeholder,disabled:i,onInput:e=>o(e.target.value),"data-testid":c})}}function Ia(e){switch(e){case`number`:case`email`:case`tel`:case`url`:case`date`:case`time`:return e;default:return`text`}}function La(e){let t={};for(let n of e)n.defaultValue!=null&&(t[n.name]=n.type===`multiselect`?n.defaultValue.split(`,`).map(e=>e.trim()).filter(Boolean):n.defaultValue);return t}function Ra(e,t,n){let r={...t};for(let i of e){let e=n[i.name]?.trim();if(i.type===`radio`&&i.allowOther&&t[i.name]===Ma)r[i.name]=e??``;else if(i.type===`multiselect`&&e){let n=e.split(/[,\n;]+/).map(e=>e.trim()).filter(Boolean),a=Array.isArray(t[i.name])?t[i.name]:[];r[i.name]=[...a,...n]}}return r}const za=b.cssPrefix;function Ba({form:e,strings:t,onSubmit:n,onSkip:r}){return _(`div`,{class:`${za}-form-gate`,"data-testid":q.formGate,children:[e.title?g(`h3`,{class:`${za}-form-gate-title`,children:e.title}):null,e.description?g(`p`,{class:`${za}-form-gate-desc`,children:e.description}):null,g(Na,{fields:e.fields,strings:t,submitLabel:e.submitLabel??t.formSubmit,onSubmit:n,skipLabel:e.skippable?t.formSkip:void 0,onSkip:e.skippable?r:void 0,submitTestId:q.formSubmit,skipTestId:q.formSkip})]})}function Va({marker:e,strings:t,onFill:n}){let r=e.outcome===`skipped`,i=r?t.formSkipped:t.formSubmitted,a=e.title?_(h,{children:[g(`span`,{children:e.title}),g(`span`,{class:`${za}-sr-only`,children:i})]}):g(`span`,{children:i}),o=e.form?.reviewable??!1,s=!r&&o&&e.values&&Object.keys(e.values).length>0?e.values:null;if(s){let t=t=>e.form?.fields.find(e=>e.name===t)?.label??t;return _(`details`,{class:`${za}-form-done`,"data-outcome":e.outcome,"data-testid":q.formDone,children:[_(`summary`,{class:`${za}-form-done-summary`,"data-testid":q.formDoneToggle,children:[g(Ur,{}),a,g(Or,{})]}),g(`dl`,{class:`${za}-form-answers`,"data-testid":q.formAnswers,children:Object.entries(s).map(([e,n])=>_(`div`,{class:`${za}-form-answer`,children:[g(`dt`,{children:t(e)}),g(`dd`,{children:n})]},e))})]})}return _(`div`,{class:`${za}-form-done`,"data-outcome":e.outcome,"data-testid":q.formDone,role:`status`,children:[g(r?Hr:Ur,{}),a,r&&e.form?.reopenable&&n?g(`button`,{type:`button`,class:`${za}-form-done-fill`,"data-testid":q.formFill,onClick:n,children:t.formFillOut}):null]})}function Ha(e){if(!e)return!1;let t=e.startsWith(`tool:`)?e.slice(5):e;return t===`ask-user-questions`||t===`ask_user_questions`}const Ua=b.cssPrefix;function Wa(e){return e.startsWith(`tool:`)||e.startsWith(`tool-`)?e.slice(5):e}function Ga(e,t){let n=e===`output-available`||e===`output-error`||e===`output-denied`,r=e===`approval-responded`||t?.approved!==void 0;return{terminal:n,responded:r,decided:n||r}}function Ka({status:e,icon:t,label:n}){return _(`span`,{class:`${Ua}-toolui-badge ${Ua}-toolui-status`,"data-status":e,children:[g(`span`,{class:`${Ua}-toolui-status-icon`,children:t}),n]})}function qa(e,t){return e===`output-error`?`error`:e===`output-denied`||t?.approved===!1?`denied`:e===`output-available`?`completed`:e===`approval-responded`||t?.approved===!0?`responded`:e===`approval-requested`?`awaiting`:`running`}function Ja(e,t,n={}){return n.submitted?`responded`:Za(qa(e,t),n.superseded,n.live??!0)}function Ya({status:e}){return g(e===`denied`||e===`error`||e===`superseded`?xi:e===`completed`||e===`responded`?bi:yi,{})}function Xa(e,t){switch(e){case`awaiting`:return t.statusAwaiting;case`responded`:return t.statusResponded;case`completed`:return t.statusCompleted;case`denied`:return t.statusDenied;case`error`:return t.statusError;case`superseded`:return t.statusSuperseded;default:return t.statusRunning}}function Za(e,t,n){return t&&(e===`awaiting`||e===`running`)?`superseded`:!n&&e===`running`?`error`:e}function Qa({state:e,approval:t,strings:n,superseded:r,live:i=!0,submitted:a=!1}){let o=Ja(e,t,{superseded:r,live:i,submitted:a});return g(Ka,{status:o,icon:g(Ya,{status:o}),label:Xa(o,n)})}function $a({name:e,state:t,approval:n,strings:r,superseded:i,live:a,submitted:o}){return _(h,{children:[_(`span`,{class:`${Ua}-toolui-name-pill`,children:[g(vi,{}),g(`span`,{class:`${Ua}-toolui-name-text`,children:e})]}),g(Qa,{state:t,approval:n,strings:r,superseded:i,live:a,submitted:o}),g(`span`,{class:`${Ua}-toolui-chevron`,children:g(Jr,{})})]})}function eo({part:e,strings:t,testid:n,superseded:r,live:i,submitted:a}){let s=o(()=>u(()=>e.inputSig.value),[e]),c=o(()=>u(()=>e.outputSig.value),[e]),l=o(()=>u(()=>e.errorSig.value),[e]),d=o(()=>u(()=>e.stateSig.value),[e]),f=o(()=>u(()=>e.approvalSig.value),[e]);return _(`details`,{class:`${Ua}-toolui ${Ua}-toolui-collapsible`,"data-testid":n,children:[g(`summary`,{class:`${Ua}-toolui-head`,children:g($a,{name:Wa(e.toolName),state:d.value,approval:f.value,strings:t,superseded:r,live:i,submitted:a})}),g(to,{label:t.toolParameters,value:s.value}),c.value===void 0?null:g(to,{label:t.toolResult,value:c.value}),l.value?g(to,{label:t.statusError,value:l.value,error:!0}):null]})}function to({label:e,value:t,error:n}){let r=n?typeof t==`string`?t:``:ro(no(t));return r?_(`div`,{class:`${Ua}-toolui-section`,children:[g(`span`,{class:`${Ua}-toolui-label`,children:e}),g(`pre`,{class:`${Ua}-toolui-code`,"data-error":n?`true`:void 0,children:r})]}):null}function no(e){if(e&&typeof e==`object`){let t=e;if(t.storage===`tool-result-ref`&&`summary`in t)return t.summary}return e}function ro(e){if(e==null)return``;try{let t=typeof e==`string`?e:JSON.stringify(e,null,2);return!t||t===`{}`||t===`[]`||t===`""`?``:t.length>800?`${t.slice(0,800)}…`:t}catch{return``}}function io(e){return e.partsSig.value.some(e=>e.kind===`text`&&e.textSig.value.length>0)}function ao(e){return e.partsSig.value.some(e=>e.kind===`reasoning`)}function oo(e){return e.streaming&&!e.bufferedHold&&!(e.reasoningVisible&&e.working)}function so(e){let{streaming:t,reasoningVisible:n,emptyReply:r,hidden:i}=e,a=e.responseMode===`buffered`&&t,o=t&&!e.hasAnswerText;return{streaming:t,bufferedHold:a,reasoningVisible:n,working:o,showStreamDots:oo({streaming:t,bufferedHold:a,reasoningVisible:n,working:o}),emptyReply:r,hidden:i}}function co(e,t){let n=e.stateSig.value,r=e.approvalSig.value,{terminal:i,responded:a,decided:o}=Ga(n,r),s=t.continuationStreaming===!0&&!o,c=t.superseded&&!o&&!s;return{pill:Ja(n,r,{superseded:c,live:t.live,submitted:s}),state:n,terminal:i,decided:o||s,showApproveReject:!o&&!t.superseded&&!s,showAnswered:a&&!i&&!c,showSubmitted:s,showEdit:a&&t.active&&!i,skipped:c,answeredApproved:r?.approved}}function lo({textSig:e,doneSig:t}){let n=s(null);return a(()=>{let r=n.current;if(!r)return;r.classList.add(`${b.cssPrefix}-md`),r.replaceChildren();let i=y.default_renderer(r),a=y.parser(i),o=0,s=d(()=>{let n=e.value,s=t.value;n.length<o&&(r.replaceChildren(),i=y.default_renderer(r),a=y.parser(i),o=0);let c=n.slice(o);c&&y.parser_write(a,c),o=n.length,s&&y.parser_end(a)}),c=new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes){if(!(e instanceof HTMLElement))continue;let t=e.matches?.(`a`)?[e]:[...e.querySelectorAll?.(`a`)??[]];for(let e of t)fo(e)}});c.observe(r,{childList:!0,subtree:!0});for(let e of r.querySelectorAll(`a`))fo(e);let l=e=>{let t=e.target?.closest?.(`a`);if(!t||!(t instanceof HTMLAnchorElement))return;let n=t.getAttribute(`href`)??``;!n||n.startsWith(`#`)||(e.preventDefault(),window.open(n,`_blank`,`noopener,noreferrer`))};return r.addEventListener(`click`,l),()=>{s(),c.disconnect(),r.removeEventListener(`click`,l)}},[e,t]),g(`div`,{ref:n})}function uo({text:e}){return g(lo,{textSig:o(()=>f(e),[e]),doneSig:o(()=>f(!0),[])})}function fo(e){let t=e.getAttribute(`href`)??``;if(!t||t.startsWith(`#`))return;e.target!==`_blank`&&(e.target=`_blank`);let n=new Set((e.rel||``).split(/\s+/).filter(Boolean));n.add(`noopener`),n.add(`noreferrer`),e.rel=[...n].join(` `)}const po=b.cssPrefix;function mo({messageId:e,initial:t,strings:n,onFeedback:r}){let[a,o]=c(t);i(()=>o(t),[e,t]);let s=t=>{let n=a===t?null:t;o(n),r(e,n)};return _(`div`,{class:`${po}-feedback`,role:`group`,"data-testid":q.messageFeedback,children:[g(`button`,{type:`button`,class:`${po}-msg-action`,"data-active":a===`up`?`true`:void 0,"aria-pressed":a===`up`,"aria-label":n.feedbackUp,title:n.feedbackUp,onClick:()=>s(`up`),"data-testid":q.feedbackUp,children:g(gi,{})}),g(`button`,{type:`button`,class:`${po}-msg-action`,"data-active":a===`down`?`true`:void 0,"aria-pressed":a===`down`,"aria-label":n.feedbackDown,title:n.feedbackDown,onClick:()=>s(`down`),"data-testid":q.feedbackDown,children:g(_i,{})}),g(`span`,{class:`${po}-sr-only`,role:`status`,"aria-live":`polite`,children:a?n.feedbackThanks:``})]})}const ho=b.cssPrefix;function go({part:e,strings:t}){let n=e.title||e.filename||e.url||t.sources;return e.url?_(`a`,{class:`${ho}-source`,href:e.url,target:`_blank`,rel:`noreferrer noopener`,"data-testid":q.source,children:[g(`span`,{class:`${ho}-source-icon`,"aria-hidden":`true`,children:`🔗`}),g(`span`,{class:`${ho}-source-label`,children:n})]}):_(`span`,{class:`${ho}-source`,"data-testid":q.source,children:[g(`span`,{class:`${ho}-source-icon`,"aria-hidden":`true`,children:`📄`}),g(`span`,{class:`${ho}-source-label`,children:n})]})}const _o=b.cssPrefix;function vo({part:e,strings:t,active:n,superseded:r=!1,continuationStreaming:i=!1,onDecision:a,onEdit:s}){let c=o(()=>u(()=>e.approvalSig.value),[e]),l=o(()=>u(()=>co(e,{active:n,superseded:r,continuationStreaming:i})),[e,n,r,i]).value,{terminal:d,showApproveReject:f,showAnswered:p,showSubmitted:m,showEdit:v,skipped:y}=l,b=Wa(e.toolName),x=l.answeredApproved,S=e.toolCallId,C=_(h,{children:[g(`p`,{class:`${_o}-toolui-prompt`,children:t.approvalPrompt.replace(`{tool}`,b)}),g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalBody})]});m?C=g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalSubmitting}):p&&x!==!1?C=_(h,{children:[_(`p`,{class:`${_o}-toolui-prompt`,children:[t.approvalYourResponse.replace(`{decision}`,x?t.approve:t.reject),c.value?.reason?` — ${c.value.reason}`:``]}),v?g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalEditHint}):null,v?null:g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalSubmitting})]}):p&&(C=g(h,{}));let w=f||m||v||p&&x!==!1;return _(`div`,{class:`${_o}-toolui-group`,"data-testid":l.decided?q.toolDecision:q.toolApproval,children:[g(eo,{part:e,strings:t,superseded:y,submitted:m}),y||d||!w?null:_(`div`,{class:`${_o}-toolui ${_o}-toolui-body`,children:[C,f?_(`div`,{class:`${_o}-toolui-actions`,children:[g(`button`,{type:`button`,class:`${_o}-form-skip`,disabled:!n,onClick:()=>a(S,!1),"data-testid":q.toolReject,children:t.reject}),g(`button`,{type:`button`,class:`${_o}-form-submit`,disabled:!n,onClick:()=>a(S,!0),"data-testid":q.toolApprove,children:t.approve})]}):null,v?g(`div`,{class:`${_o}-toolui-actions`,children:g(`button`,{type:`button`,class:`${_o}-form-skip`,onClick:()=>s(S),"data-testid":q.toolEdit,children:t.edit})}):null]})]})}const yo=new Set([`text`,`email`,`phone`,`number`,`date`,`single-select`,`multi-select`,`boolean`]);function bo(e){let t=e&&typeof e==`object`?e:{},n=(Array.isArray(t.questions)?t.questions:[]).map(xo).filter(e=>e!==null);return{intro:wo(t.intro),questions:n}}function xo(e,t){if(!e||typeof e!=`object`)return null;let n=e,r=yo.has(n.type)?n.type:`text`;return{key:wo(n.key)??`q${t+1}`,question:wo(n.question)??`Please provide the missing information.`,type:r,options:Array.isArray(n.options)?n.options.filter(e=>typeof e==`string`&&e.trim().length>0):void 0,required:typeof n.required==`boolean`?n.required:void 0,helpText:wo(n.helpText)}}function So(e){switch(e){case`text`:return`textarea`;case`phone`:return`tel`;case`single-select`:case`boolean`:return`radio`;case`multi-select`:return`multiselect`;default:return e}}function Co(e,t,n){return e.questions.map(e=>{let r=So(e.type),i=e.type===`boolean`?[{value:`yes`,label:t},{value:`no`,label:n}]:(e.options??[]).map(e=>({value:e,label:e}));return{name:e.key,label:e.question,type:r,required:e.required??!1,options:i.length>0?i:void 0,validationHint:e.helpText}})}function wo(e){return typeof e==`string`&&e.trim()?e.trim():void 0}const X=b.cssPrefix;function To({skipped:e,submitted:t,strings:n}){return e?{status:`superseded`,statusLabel:n.inputSkipped}:t?{status:`responded`,statusLabel:n.statusResponded}:{status:`completed`,statusLabel:n.inputAnswered}}const Eo={text:`qtypeText`,email:`qtypeEmail`,phone:`qtypePhone`,number:`qtypeNumber`,date:`qtypeDate`,"single-select":`qtypeChooseOne`,"multi-select":`qtypeChooseAny`,boolean:`qtypeBoolean`};function Do(e,t){let n={};for(let r of e)n[r.key]=t[Eo[r.type]];return n}function Oo({part:e,strings:t,active:n,superseded:r=!1,continuationStreaming:i=!1,onDecision:a,onEdit:s}){let l=o(()=>u(()=>e.stateSig.value),[e]).value,d=o(()=>u(()=>e.approvalSig.value),[e]).value,f=o(()=>u(()=>bo(e.inputSig.value)),[e]).value,{terminal:p,decided:m}=Ga(l,d),h=m&&d?.approved===!0,v=i&&!m,y=!m&&!r&&!v,b=!y&&!h&&!v,x=h&&n&&!p,S=f.questions,[C,w]=c(null),T=C??(y||h||v),[E,D]=c(!1),O=S.length>1?Sr:Qr,k=y?t.inputRequired:t.inputBadge,A=v?g(`p`,{class:`${X}-toolui-subtle`,children:t.approvalSubmitting}):y?g(ko,{req:f,strings:t,active:n,resolve:(t,n)=>a(e.toolCallId,n,t)}):E?g(Na,{fields:Co(f,t.confirmYes,t.confirmNo),strings:t,submitLabel:t.inputSubmit,onSubmit:()=>{},disabled:!0,hideActions:!0,fieldTypeLabels:Do(S,t),initialValues:h?Fo(S,d?.reason):void 0}):g(Ao,{questions:S,answers:h?Po(d?.reason):{},strings:t}),{status:j,statusLabel:M}=To({skipped:b,submitted:v,strings:t});return _(`details`,{class:`${X}-toolui ${X}-toolui-collapsible${r?` ${X}-toolui-stale`:``}`,open:T,onToggle:e=>{let t=e.currentTarget.open;t!==T&&w(t)},"data-testid":y?q.toolAskQuestions:q.toolDecision,children:[_(`summary`,{class:`${X}-toolui-head`,children:[_(`span`,{class:`${X}-toolui-q-pill`,children:[g(O,{}),k]}),_(`span`,{class:`${X}-toolui-head-end`,children:[y?null:g(Ka,{status:j,icon:g(b?xi:bi,{}),label:M}),g(`span`,{class:`${X}-toolui-chevron`,children:g(Jr,{})})]})]}),_(`div`,{class:`${X}-toolui-collapse-body`,children:[f.intro?g(`div`,{class:`${X}-toolui-desc`,children:f.intro}):null,A,y||v?null:_(`div`,{class:`${X}-toolui-footer`,children:[_(`button`,{type:`button`,class:`${X}-toolui-options-toggle`,onClick:()=>D(e=>!e),"data-testid":q.toolAskOptions,children:[g(`span`,{class:`${X}-toolui-options-chevron${E?` ${X}-open`:``}`,children:g(Jr,{})}),E?t.hideOptions:t.showOptions]}),x?g(`button`,{type:`button`,class:`${X}-form-skip`,onClick:()=>s(e.toolCallId),"data-testid":q.toolEdit,children:t.edit}):null]})]})]})}function ko({req:e,strings:t,active:n,resolve:r}){let i=Co(e,t.confirmYes,t.confirmNo),a=e.questions.length===1&&e.questions[0]?.type===`text`;return g(Na,{fields:i,strings:t,disabled:!n,submitLabel:t.inputSubmit,footerHint:a?t.inputSubmitHint:void 0,onSubmit:t=>r(Mo(e.questions,t),!0),skipLabel:t.inputSkip,onSkip:()=>r(void 0,!1),submitOnEnter:a,fieldTypeLabels:Do(e.questions,t),submitTestId:q.toolInputSubmit,skipTestId:q.toolInputSkip})}function Ao({questions:e,answers:t,strings:n}){return g(`div`,{class:`${X}-toolui-summary`,"data-testid":q.toolAskSummary,children:e.map(e=>_(`div`,{class:`${X}-field`,children:[g(`span`,{class:`${X}-field-head`,children:_(`span`,{class:`${X}-field-label`,children:[e.question,e.required?g(`span`,{class:`${X}-field-req`,"aria-hidden":`true`,children:` *`}):null]})}),g(`p`,{class:`${X}-toolui-answer`,children:jo(e,t[e.key],n)||`—`})]},e.key))})}function jo(e,t,n){return e.type===`boolean`?t===`yes`?n.confirmYes:t===`no`?n.confirmNo:t??``:t??``}function Mo(e,t){let n=e.flatMap(e=>{let n=t[e.key];if(n==null||n.trim()===``)return[];let r=e.type===`multi-select`?n.split(`,`).map(e=>e.trim()).filter(Boolean):n;return[{key:e.key,value:r}]});return JSON.stringify({answers:n})}function No(e){if(!e)return{};let t=(()=>{try{return JSON.parse(e)}catch{return}})()?.answers;if(!Array.isArray(t))return{};let n={};for(let e of t)if(e&&typeof e==`object`&&`key`in e){let{key:t,value:r}=e;if(typeof t!=`string`)continue;typeof r==`string`?n[t]=r:Array.isArray(r)&&(n[t]=r.filter(e=>typeof e==`string`))}return n}function Po(e){let t=No(e),n={};for(let[e,r]of Object.entries(t))n[e]=Array.isArray(r)?r.join(`, `):r;return n}function Fo(e,t){let n=No(t),r={};for(let t of e){let e=n[t.key];e!==void 0&&(t.type===`multi-select`?r[t.key]=Array.isArray(e)?e:[e]:r[t.key]=Array.isArray(e)?e[0]??``:e)}return r}function Io({part:e,strings:t,live:n}){let r=o(()=>u(()=>e.inputSig.value),[e]),i=o(()=>u(()=>e.outputSig.value),[e]),a=o(()=>u(()=>e.errorSig.value),[e]);return o(()=>u(()=>!!ro(r.value)||!!a.value||!!ro(no(i.value))),[r,i,a]).value?g(eo,{part:e,strings:t,testid:q.toolCall,live:n}):null}const Lo=b.cssPrefix,Ro=v(zo);function zo({message:e,status:t,strings:n,responseMode:r,showReasoning:i,showToolCalls:a,showSources:s,interactive:c=!1,superseded:l=!1,tool:d,onRetry:f,enableMessageFeedback:p=!1,onFeedback:m}){let h=o(()=>u(()=>e.partsSig.value),[e]).value,v=o(()=>u(()=>rr(e)),[e]),y=o(()=>u(()=>ar(e)),[e]),b=o(()=>u(()=>io(e)),[e]),x=o(()=>u(()=>i&&ao(e)),[e,i]),S=t===`streaming`,C=e.role===`assistant`&&S,w=so({streaming:C,responseMode:r,reasoningVisible:x.value,hasAnswerText:b.value,emptyReply:v.value,hidden:y.value}),{bufferedHold:T,working:E,showStreamDots:D}=w;if(w.hidden)return null;let O=Vo(e.createdAt),k=e.role===`assistant`||e.role===`operator`,A=p&&!!m&&!!e.serverMessageId&&k&&!S&&t!==`error`&&!v.value,j=S?``:h.filter(e=>e.kind===`text`).map(e=>e.textSig.peek()).join(`
|
|
10
|
+
`))if(i!==``){if(i.startsWith(`:`)){t?.(i.slice(1).trim());continue}if(i.startsWith(`data:`)){let e=i.slice(5).replace(/^ /,``);n=n?`${n}\n${e}`:e;continue}i.startsWith(`id:`)&&(r=i.slice(3).trim())}if(n===`[DONE]`)return`done`;if(!n)return null;try{let e=JSON.parse(n);return Ht.trace(`chunk`,{type:e.type,eventId:r}),{chunk:e,eventId:r}}catch(e){throw Ht.trace(`frame parse failed`,{errorType:e instanceof Error?e.name:typeof e,payloadLength:n.length}),new Vt(`invalid SSE frame`,`network`,void 0,e)}}function Kt(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const qt=e=>e&&Object.keys(e).length>0?e:void 0;function Jt(e,t){let n=qt(e),r=qt(t);if(!n&&!r)return;let i={};return n&&(i.user=n),r&&(i.page=r),Kt(JSON.stringify(i))}function Yt(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Xt(e){return`tool-${e.startsWith(`tool:`)?e.slice(5):e}`}function Zt(e){return e.startsWith(`tool-`)?e.slice(5):e}const V={handshake:`/pai/handshake`,streamMessage:`/pai/stream-message`,streamResume:`/pai/stream-resume`,cancelStream:`/pai/cancel-stream`,listConversations:`/pai/list-conversations`,listMessages:`/pai/list-messages`,updateSettings:`/pai/update-settings`,markRead:`/pai/mark-read`,messageFeedback:`/pai/message-feedback`,requestOperator:`/pai/request-operator`,cancelOperatorRequest:`/pai/cancel-request-operator`,bootstrap:`/pai/bootstrap`,content:`/pai/content`,submitForm:`/pai/submit-form`};function Qt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $t(e){if(!Qt(e))return;let t=e,n=t.controlMode,r=t.controlRevision;if(!(n!==`ai-agent`&&n!==`awaiting-operator`&&n!==`operator`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0))return{controlMode:n,controlRevision:r,assignedOperatorInitials:typeof t.assignedOperatorInitials==`string`&&t.assignedOperatorInitials?t.assignedOperatorInitials:void 0,operatorAvailable:typeof t.operatorAvailable==`boolean`?t.operatorAvailable:void 0}}function en(e){if(!Qt(e))return;let t=e.status,n=e.postFinishSequence;if(!(t!==`compacting`&&t!==`ready`||typeof n!=`number`||!Number.isSafeInteger(n)||n<0))return{status:t,postFinishSequence:n}}function tn(e){let t=Qt(e)?e.suggestions:void 0;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!Qt(e))continue;let{id:t,label:r,text:i}=e;typeof r!=`string`||!r||n.push({id:typeof t==`string`&&t?t:`s${n.length}`,label:r,text:typeof i==`string`&&i?i:r})}return n}function nn(e){let t={messages:e.messages.map(e=>({id:e.serverMessageId??e.id,parts:H(e),role:e.role})),conversationId:e.conversationId,responseType:`ack`};return e.visitorId&&(t.visitorId=e.visitorId),e.userPrefs&&(t.userPrefs=e.userPrefs),t}function rn(e){return e.state===`output-available`||e.state===`output-error`||e.state===`output-denied`||e.approval?.approved!==void 0}function H(e){let t=[];for(let n of e.parts)if(n.kind===`step-start`&&t.push({type:`step-start`}),n.kind===`reasoning`&&n.text&&t.push({type:`reasoning`,text:n.text,state:n.done?`done`:`streaming`}),n.kind===`text`&&n.text&&t.push({text:n.text,type:`text`}),n.kind===`file`&&n.url&&t.push({mediaType:n.mediaType,type:`file`,url:n.url}),n.kind===`tool`&&rn(n)){let e=n.dynamic?{type:`dynamic-tool`,toolName:n.toolName,toolCallId:n.toolCallId,state:n.state}:{type:Xt(n.toolName),toolCallId:n.toolCallId,state:n.state};n.input!==void 0&&(e.input=n.input),n.output!==void 0&&(e.output=n.output),n.error!==void 0&&(e.errorText=n.error),n.approval?.approved!==void 0&&(e.approval=n.approval),t.push(e)}for(let n of e.attachments??[])n.url&&t.push({type:`file`,url:n.url,mediaType:n.mediaType,filename:n.name,fileId:n.id,fileSize:n.size});return t}function an(e){"@babel/helpers - typeof";return an=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},an(e)}function on(e,t){if(an(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(an(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function sn(e){var t=on(e,`string`);return an(t)==`symbol`?t:t+``}function U(e,t,n){return(t=sn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const W=I.scope(`transport`),cn=new WeakMap;function ln(e){return cn.get(e)}function un(e,t){return cn.set(e,t),e}function dn(e){return Math.max(e?.upsertRevision??0,e?.read?.revision??0)}function fn(e,t){return e.conversationId===t.conversationId&&e.title===t.title&&e.lastMessageAt===t.lastMessageAt&&e.preview===t.preview&&e.canContinue===t.canContinue&&e.hasUnread===t.hasUnread&&e.controlState===t.controlState}function pn(e,t,n=!0){switch(t.type){case`snapshot`:{let n=new Map(e.map(e=>[e.conversationId,e])),r=e.filter(e=>(ln(e)?.activityRevision??0)>t.requestedRevision).toSorted((e,t)=>ln(t).activityRevision-ln(e).activityRevision),i=new Set(r.map(e=>e.conversationId));return[...r,...t.result.conversations.filter(e=>!i.has(e.conversationId)).map(e=>{let r=n.get(e.conversationId);if(!r)return e;let i=ln(r);return(i?.upsertRevision??0)>t.requestedRevision?r:i?.read&&!r.hasUnread&&i.read.lastMessageAt===e.lastMessageAt?un({...e,hasUnread:!1},{upsertRevision:0,read:i.read}):e})]}case`read`:{let n=e.findIndex(e=>e.conversationId===t.conversationId&&(t.lastMessageAt===void 0||e.lastMessageAt===t.lastMessageAt));if(n<0)return e;let r=e[n],i=ln(r);if(dn(i)>t.revision)return e;let a=t.lastMessageAt??r.lastMessageAt,o={upsertRevision:i?.upsertRevision??0,...i?.activityRevision===void 0?{}:{activityRevision:i.activityRevision},read:{revision:t.revision,...a?{lastMessageAt:a}:{}}};return r.hasUnread?e.map((e,t)=>t===n?un({...e,hasUnread:!1},o):e):(un(r,o),e)}case`upsert`:{let r=e.findIndex(e=>e.conversationId===t.conversation.conversationId);if(r<0&&!n)return e;let i=r<0?void 0:e[r],a=i?ln(i):void 0;if(dn(a)>t.revision)return e;let o=t.activity?t.revision:a?.activityRevision,s={upsertRevision:t.revision,...o===void 0?{}:{activityRevision:o},...!t.conversation.hasUnread&&a?.read?{read:a.read}:{}},c=i?{...i,...t.conversation,title:i.title}:{...t.conversation};return i&&fn(i,c)?(un(i,s),e):(un(c,s),t.activity?[c,...e.filter(e=>e.conversationId!==c.conversationId)]:i?e.map((e,t)=>t===r?c:e):[...e,c])}default:return t}}const mn=new Set([408,425,429,500,502,503,504]);function hn(e){return 400*2**e+Math.floor(Math.random()*250)}function gn(e){return 6e4+Math.ceil(e/1048576)*15e3}function _n(e){let t=e.get(`retry-after`);if(!t)return null;let n=Number(t),r=Number.isFinite(n)?n*1e3:Date.parse(t)-Date.now();return Number.isFinite(r)&&r>=0?Math.min(r,3e4):null}var vn=class{constructor(e){this.ttlMs=e,U(this,`map`,new Map)}getOrFetch(e,t){let n=this.map.get(e);if(n&&performance.now()-n.at<this.ttlMs)return n.result;let r={at:performance.now(),result:t().then(e=>(r.value=e,e)).catch(t=>{throw this.map.get(e)===r&&this.map.delete(e),t})};return this.map.set(e,r),r.result}peek(e){let t=this.map.get(e);if(t?.value!==void 0&&performance.now()-t.at<this.ttlMs)return t.value}update(e){for(let t of this.map.values()){if(t.value!==void 0){let n=e(t.value);t.value=n,t.result=Promise.resolve(n);continue}t.result=t.result.then(n=>{let r=e(n);return t.value=r,r})}}delete(e){this.map.delete(e)}},yn=class{constructor(e){this.opts=e,U(this,`conversationListeners`,new Set),U(this,`conversationRevision`,0),U(this,`visitorId`,void 0),U(this,`conversationId`,void 0),U(this,`userContext`,void 0),U(this,`pageContext`,void 0),U(this,`locale`,void 0),U(this,`conversationsCache`,new vn(1e4)),U(this,`contentCache`,new vn(6e4))}setContext(e,t){this.userContext=e,this.pageContext=t}setLocale(e){this.locale=e}primeIdentity(e,t){e&&(this.visitorId=e),t&&(this.conversationId=t)}envelope(){let e={_ev:Bt};this.visitorId&&(e.visitorId=this.visitorId),this.conversationId&&(e.conversationId=this.conversationId),this.locale&&(e.locale=this.locale);let t=Jt(this.userContext,this.pageContext);return t&&(e.context=t),e}withEnvelope(e){return{...this.envelope(),...e}}appendEnvelope(e){for(let[t,n]of Object.entries(this.envelope()))e.append(t,n);return e}withEnvelopeQuery(e){let t=new URL(this.url(e));for(let[e,n]of Object.entries(this.envelope()))t.searchParams.has(e)||t.searchParams.set(e,n);return t.toString()}async handshake(e){W.debug(`handshake →`,{visitorId:e.visitorId,conversationId:e.conversationId,locale:e.locale});let t=await this.postJson(V.handshake,e,`handshake`);return W.debug(`handshake ←`,{visitorId:t.visitorId,conversationId:t.conversationId,hasWelcome:!!t.welcome,hasConfig:!!t.config,rebind:t.rebind}),this.visitorId=e.visitorId,this.conversationId=t.conversationId,t}async uploadFile(e,t){W.debug(`uploadFile →`,{name:e.name,size:e.size,type:e.type});let n=new FormData;n.append(`file`,e,e.name);let r=await this.postForm(this.uploadPath,n,`upload`,t,gn(e.size));return W.debug(`uploadFile ←`,{id:r.id,url:r.url}),r}async transcribe(e,t=`audio/webm`){W.debug(`transcribe →`,{size:e.size,mimeType:t});let n=new FormData;n.append(`audio`,e,`voice.${bn(t)}`),n.append(`mimeType`,t);let r=await this.postForm(this.transcribePath,n,`transcribe`);return W.debug(`transcribe ←`,{textLen:r.text.length}),r}subscribeConversationChanges(e){return this.conversationListeners.add(e),()=>this.conversationListeners.delete(e)}publishConversation(e,t=!1){let n={type:`upsert`,conversation:e,revision:++this.conversationRevision,...t?{activity:!0}:{}};this.conversationsCache.update(r=>{let i=r.pagination.page===1,a=r.conversations.some(t=>t.conversationId===e.conversationId),o=pn(r.conversations,n,i&&t),s=i&&o.length>r.pagination.limit?o.slice(0,r.pagination.limit):o;if(!i||!t||a||r.pagination.hasNext)return s===r.conversations?r:{...r,conversations:s};let c=Math.max(r.pagination.total,r.conversations.length)+1,l=Math.ceil(c/r.pagination.limit);return{...r,conversations:s,pagination:{...r.pagination,total:c,totalPages:l,hasNext:r.pagination.page<l}}});for(let e of this.conversationListeners)e(n)}localeCacheKey(e){return`${this.locale??``}|${JSON.stringify(e,Object.keys(e).toSorted())}`}peekConversations(e={}){return this.conversationsCache.peek(this.localeCacheKey(e))}listConversations(e={},t=!1){if((e.page??1)>1)return this.fetchConversations(e);let n=this.localeCacheKey(e),r=this.conversationRevision;t&&this.conversationsCache.delete(n);let i=this.conversationsCache.getOrFetch(n,()=>this.fetchConversations(e));return t?i.then(e=>{let t={type:`snapshot`,result:e,requestedRevision:r};for(let e of this.conversationListeners)e(t);return e}):i}async fetchConversations(e){let t=new URL(this.url(V.listConversations));return e.visitorId&&t.searchParams.set(`visitorId`,e.visitorId),e.page&&t.searchParams.set(`page`,String(e.page)),e.limit&&t.searchParams.set(`limit`,String(e.limit)),e.ids?.length&&t.searchParams.set(`ids`,e.ids.join(`,`)),this.getJson(t.toString(),`listConversations`)}async loadConversation(e,{ids:t=[],beforeId:n,beforeCreatedAt:r}={}){let i=new URL(this.url(V.listMessages));i.searchParams.set(`conversationId`,e),i.searchParams.set(`limit`,`50`),t.length>0&&i.searchParams.set(`ids`,t.join(`,`)),n&&i.searchParams.set(`beforeId`,n),r&&i.searchParams.set(`beforeCreatedAt`,r);let a=await this.getJson(i.toString(),`loadConversation`);return{...a,messages:a.messages.toReversed()}}async markRead(e,t){if(!this.visitorId||!e)return;let n={type:`read`,conversationId:e,...t===void 0?{}:{lastMessageAt:t},revision:++this.conversationRevision};this.conversationsCache.update(e=>{let t=pn(e.conversations,n);return t===e.conversations?e:{...e,conversations:t}});for(let e of this.conversationListeners)e(n);try{await this.postJson(V.markRead,{conversationId:e},`markRead`,!0)}catch(e){W.debug(`markRead failed (non-fatal)`,{err:e})}}async requestOperator(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(V.requestOperator,{},`requestOperator`)).controlState}catch(e){W.debug(`requestOperator failed (non-fatal)`,{err:e});return}}async cancelOperatorRequest(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(V.cancelOperatorRequest,{},`cancelOperatorRequest`)).controlState}catch(e){W.debug(`cancelOperatorRequest failed (non-fatal)`,{err:e});return}}listContent(e={}){return this.contentCache.getOrFetch(this.localeCacheKey(e),()=>this.fetchContent(e))}async fetchContent(e){let t=new URL(this.dataUrl(V.content));for(let[n,r]of Object.entries(e))r!==void 0&&t.searchParams.set(n,Array.isArray(r)?r.join(`,`):String(r));let n=await this.getJson(t.toString(),`listContent`),r=(n.items??[]).map(e=>A(e,this.locale));return{...n,items:r}}async bootstrap(e){let t=new URL(this.dataUrl(V.bootstrap));e&&t.searchParams.set(`conversationId`,e);let n=await this.getJson(t.toString(),`bootstrap`);return{forms:n.forms??[],formSubmissions:n.formSubmissions??[]}}async saveUserPrefs(e){return this.postJson(V.updateSettings,{userPrefs:e},`saveUserPrefs`)}get uploadPath(){return this.opts.endpoints?.upload??`/pai/upload-file`}get transcribePath(){return this.opts.endpoints?.transcribe??`/pai/transcribe-audio`}get submitFormPath(){return this.opts.endpoints?.submitForm??V.submitForm}async submitForm(e){W.debug(`submitForm →`,{formId:e.formId,trigger:e.trigger,fields:Object.keys(e.values).length});try{await this.postJson(this.dataUrl(this.submitFormPath),e,`submitForm`)}catch(e){W.debug(`submitForm failed (non-fatal)`,{err:e})}}async submitFeedback(e){W.debug(`submitFeedback →`,{messageId:e.messageId,value:e.value});try{await this.postJson(V.messageFeedback,{messageId:e.messageId,set:{feedback:e.value}},`submitFeedback`)}catch(e){W.debug(`submitFeedback failed (non-fatal)`,{err:e})}}async sendTurn(e){W.debug(`message →`,{conversationId:e.conversationId,visitorId:e.visitorId,messageCount:e.messages.length});try{return await this.runWithAbort(async t=>{let n=await this.fetchImpl(this.url(V.streamMessage),{method:`POST`,credentials:`omit`,headers:{accept:`application/json`,"content-type":`application/json`,...this.opts.auth.headers()},body:JSON.stringify(this.withEnvelope(e)),signal:t});if(n.status!==202)throw new Vt(`sendTurn failed: expected 202, received ${n.status}`,`server`,n.status);let r;try{r=await n.json()}catch(e){throw t?.aborted?e:new Vt(`sendTurn failed: invalid acknowledgement`,`server`,n.status,e)}if(!xn(r))throw new Vt(`sendTurn failed: invalid acknowledgement`,`server`,n.status);return r},void 0,3e4)}catch(e){throw e instanceof Vt?e:new Vt(`sendTurn failed: network error`,`network`,void 0,e)}}cancelTurn(e,t){!this.visitorId||!e||!t||(W.debug(`cancel stream`,{conversationId:e,runId:t,visitorId:this.visitorId}),this.fetchImpl(this.url(V.cancelStream),{method:`POST`,credentials:`omit`,headers:{"content-type":`application/json`,...this.opts.auth.headers()},body:JSON.stringify(this.withEnvelope({conversationId:e,runId:t})),keepalive:!0}).catch(e=>W.debug(`cancel POST failed (non-fatal)`,{err:e})))}async connectResumeStream(e){let t=new AbortController,n=()=>t.abort(e.signal.reason);e.signal.aborted?n():e.signal.addEventListener(`abort`,n,{once:!0});let r=setTimeout(()=>t.abort(),1e4),i=()=>{clearTimeout(r),e.signal.removeEventListener(`abort`,n)},a;try{a=await this.fetchImpl(this.resumeUrl(),{method:`GET`,credentials:`omit`,headers:{accept:`text/event-stream`,...this.opts.auth.headers()},signal:t.signal})}catch(t){return i(),e.signal.aborted||W.debug(`resume-stream fetch failed — reconnecting`,{err:t}),`held`}if(!a.ok)return i(),a.status===409||mn.has(a.status)?(W.debug(`resume-stream → transient response; reconnecting`,{status:a.status}),`held`):(W.debug(`resume-stream → endpoint unavailable`,{status:a.status}),`unavailable`);if(!a.body)return i(),W.debug(`resume-stream → bodyless response; stopping`,{status:a.status}),`unavailable`;if(!(a.headers.get(`content-type`)??``).includes(`text/event-stream`))return i(),W.debug(`resume-stream → non-SSE response; stopping`),`unavailable`;let o=!1;try{for await(let{chunk:n}of Ut(a,t.signal,t=>{o||t!==`connected`||(o=!0,clearTimeout(r),e.onConnected())})){if(e.signal.aborted)return`held`;e.onChunk(n)}}catch(t){if(e.signal.aborted)return`held`;W.debug(`resume-stream segment dropped — reconnecting`,{err:t})}finally{i()}return`held`}resumeUrl(){return this.withEnvelopeQuery(V.streamResume)}async postJson(e,t,n,r=!1){let i=await this.fetchWithRetry(()=>[this.url(e),{method:`POST`,credentials:`omit`,headers:{"content-type":`application/json`,...this.opts.auth.headers()},body:JSON.stringify(this.withEnvelope(t)),...r?{keepalive:!0}:{}}],n);return this.assertOk(i,n)}async postForm(e,t,n,r,i){return this.runWithAbort(async r=>{let i=await this.fetchImpl(this.url(e),{method:`POST`,credentials:`omit`,headers:this.opts.auth.headers(),body:this.appendEnvelope(t),signal:r});return this.assertOk(i,n)},r,i)}async runWithAbort(e,t,n){if(!t&&n===void 0)return e();let r=new AbortController,i=()=>r.abort(t?.reason);t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0});let a=n===void 0?void 0:setTimeout(()=>r.abort(),n);try{return await e(r.signal)}finally{a!==void 0&&clearTimeout(a),t?.removeEventListener(`abort`,i)}}async getJson(e,t){let n=await this.fetchWithRetry(()=>[this.withEnvelopeQuery(e),{method:`GET`,credentials:`omit`,headers:{accept:`application/json`,...this.opts.auth.headers()}}],t);return this.assertOk(n,t)}async fetchWithRetry(e,t){for(let n=0;;n++){let[r,i]=e(),a;try{a=await this.fetchImpl(r,i)}catch(e){if(n>=3)throw new Vt(`${t} failed: network error`,`network`,void 0,e);W.debug(`request network error — retrying`,{label:t,attempt:n}),await zt(hn(n));continue}if(a.ok||!mn.has(a.status)||n>=3)return a;let o=_n(a.headers)??hn(n);W.debug(`request retryable status — retrying`,{label:t,status:a.status,attempt:n,wait:o}),await zt(o)}}async assertOk(e,t){if(!e.ok)throw new Vt(`${t} failed: ${e.status}`,`server`,e.status);return await e.json()}url(e){return/^https?:\/\//i.test(e)?e:`${this.opts.agentApiBaseUrl}${e}`}dataUrl(e){return/^https?:\/\//i.test(e)?e:`${this.opts.dataApiBaseUrl}${e}`}get fetchImpl(){return this.opts.fetchImpl??globalThis.fetch.bind(globalThis)}};function bn(e){return e.includes(`webm`)?`webm`:e.includes(`ogg`)?`ogg`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`mpeg`)?`mp3`:e.includes(`wav`)?`wav`:`bin`}function xn(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`status`),n=Reflect.get(e,`conversationId`),r=Reflect.get(e,`runId`);return t===`accepted`&&typeof n==`string`&&n.length>0&&(r===void 0||typeof r==`string`&&r.length>0)}function Sn(e,t,n=ct()){let r=e?[{kind:`text`,id:`t0`,textSig:f(e),doneSig:f(!0)}]:[];return{id:n,role:`user`,createdAt:Date.now(),status:`complete`,attachments:t,partsSig:f(r)}}function Cn(){return{id:ct(),role:`assistant`,createdAt:Date.now(),status:`streaming`,partsSig:f([])}}function wn(e){let t=ct();return Tn({id:t,role:e.role,createdAt:Date.now(),status:`complete`,ephemeral:!0,parts:[{kind:`text`,id:`${t}-t0`,text:e.text,done:!0}]})}function Tn(e){return{id:e.id,role:e.role,createdAt:e.createdAt,status:e.status,canceled:e.canceled,errorText:e.errorText,finishReason:e.finishReason,serverMessageId:e.serverMessageId,ephemeral:e.ephemeral,attachments:e.attachments,feedback:e.feedback,partsSig:f(e.parts.map(sr))}}function En(e){return e.status===`failed`?`error`:e.role===`assistant`&&e.status===`streaming`?`streaming`:`complete`}function Dn(e){let t=new Set,n=e.parts.map((t,n)=>t.type===`text`?{kind:`text`,id:`${e.id}-t${n}`,textSig:f(t.text),doneSig:f(!0)}:t.type===`reasoning`?{kind:`reasoning`,id:`${e.id}-r${n}`,textSig:f(t.text),doneSig:f(t.state!==`streaming`)}:t.type===`step-start`?{kind:`step-start`,id:`${e.id}-ss${n}`}:t.type===`file`?{kind:`file`,url:t.url,mediaType:t.mediaType}:t.type===`source-url`?{kind:`source`,sourceId:t.sourceId,url:t.url,title:t.title}:t.type===`source-document`?{kind:`source`,sourceId:t.sourceId,title:t.title,filename:t.filename,mediaType:t.mediaType}:t.type===`data-suggestions`?null:t.type===`dynamic-tool`||t.type.startsWith(`tool-`)?{kind:`tool`,toolCallId:t.toolCallId,toolName:t.type===`dynamic-tool`?t.toolName:Zt(t.type),dynamic:t.type===`dynamic-tool`||void 0,inputPartialSig:f(``),inputSig:f(t.input),outputSig:f(t.output),errorSig:f(t.errorText),stateSig:f(t.state),approvalSig:f(t.approval)}:null).filter(e=>e!==null).filter(e=>e.kind===`source`?t.has(e.sourceId)?!1:(t.add(e.sourceId),!0):!0),r=e.parts.find(e=>e.type===`data-suggestions`);return{id:e.id,role:e.role,operatorInitials:e.operatorInitials,suggestions:r?.type===`data-suggestions`?tn(r.data):void 0,serverMessageId:e.id,createdAt:Date.parse(e.createdAt),status:En(e),canceled:e.status===`canceled`,feedback:e.feedback??null,partsSig:f(n)}}function On(e){return!e.parts.some(e=>e.type===`text`&&e.text.trim()!==``||e.type===`dynamic-tool`||e.type.startsWith(`tool-`)||e.type===`file`||e.type===`source-url`||e.type===`source-document`)}function kn(e){return e.role===`assistant`&&e.status===`streaming`&&On(e)}function An(e){let t=e.length-1;return e.filter((e,n)=>n===t||!kn(e)).map(Dn)}function jn(e,t){let n=!t&&e.at(-1)?.role===`assistant`?-2:-1,r=e.at(n);return!r||r.ephemeral?[]:[r]}function Mn(e){return{id:e.id,role:e.role,createdAt:e.createdAt,status:e.status,canceled:e.canceled,errorText:e.errorText,finishReason:e.finishReason,serverMessageId:e.serverMessageId,ephemeral:e.ephemeral,attachments:e.attachments,parts:e.partsSig.value.map(cr)}}function Nn(e){let t=``;for(let n of e.partsSig.value)n.kind===`text`&&(t+=n.textSig.value);return t}function Pn(e,t,n,r,i,a=t.createdAt){let o=e.find(e=>e.role===`user`&&!e.ephemeral),s=(e,t)=>Nn(e).replace(/\s+/g,` `).trim().slice(0,t),c=o?s(o,80):``,l=s(t,120);return{conversationId:n,title:c||r,lastMessageAt:new Date(a).toISOString(),preview:l||void 0,canContinue:i}}function Fn(e){return Nn(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`||e.kind===`source`)}function In(e){return Nn(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`)}function Ln(e){return e===`approval-responded`||e===`output-available`||e===`output-denied`||e===`output-error`}const Rn=e=>e.kind===`tool`,zn=e=>e.kind===`text`&&e.textSig.value.trim()!==``||e.kind===`file`;function Bn(e){let t=e.partsSig.value,n=t.findLastIndex(e=>e.kind===`tool`);return t.slice(n+1).some(zn)}function Vn(e){if(e.role!==`assistant`)return!1;let t=e.partsSig.value.filter(Rn);return t.length>0&&t.every(e=>Ln(e.stateSig.value))}function Hn(e){return e.role===`assistant`&&e.partsSig.value.some(e=>e.kind===`tool`)&&!Bn(e)}function Un(e,t){return!e.partsSig.value.slice(t+1).some(e=>e.kind===`step-start`||zn(e))}function Wn(e){return e.partsSig.value.some(e=>Rn(e)&&!Ln(e.stateSig.value))}function Gn(e,t){if(t.length===0)return e;let n=new Set;for(let t of e)n.add(t.id),t.serverMessageId&&n.add(t.serverMessageId);let r=t.filter(e=>{let t=[e.id,e.serverMessageId].filter(e=>e!==void 0);return t.some(e=>n.has(e))?!1:(t.forEach(e=>n.add(e)),!0)});if(r.length===0)return e;let i=e.findIndex(e=>!e.ephemeral),a=i<0?e.length:i;return[...e.slice(0,a),...r,...e.slice(a)]}function Kn(e,t){return t.id=e.id,e.canceled&&(t.canceled=!0),e.feedback!==void 0&&(t.feedback=e.feedback),t.suggestions??(t.suggestions=e.suggestions),t}function qn(e,t,n,r){if(!Jn(e))return;if(t.length===0){let t=Math.max(...r.values());return n.find(n=>n.role===`assistant`&&r.get(n.serverMessageId??n.id)===t&&Nn(n).length>=Nn(e).length)}let i=t.at(-1);if(i?.role!==`user`)return;let a=r.get(i.serverMessageId??i.id);if(a!==void 0)return n.find(t=>t.role===`assistant`&&r.get(t.serverMessageId??t.id)===a+1&&Nn(t).length>=Nn(e).length)}function Jn(e){return e?.role===`assistant`&&e.status===`streaming`&&e.serverMessageId===void 0}function Yn(e,t){let n=new Map(t.partsSig.value.filter(Rn).filter(e=>Ln(e.stateSig.value)).map(e=>[e.toolCallId,e]));if(n.size===0)return;let r=!1,i=e.partsSig.value.map(e=>{if(!Rn(e))return e;let t=n.get(e.toolCallId);if(!t)return e;let i=e.approvalSig.value,a=t.approvalSig.value,o=i===void 0||i.approved===void 0&&a?.approved!==void 0?t.approvalSig:e.approvalSig,s=e.inputSig.value===void 0?t.inputSig:e.inputSig,c=e.toolName===`tool`?t.toolName:e.toolName,l=e.dynamic??t.dynamic;return o===e.approvalSig&&s===e.inputSig&&c===e.toolName&&l===e.dynamic?e:(r=!0,{...e,toolName:c,dynamic:l,inputSig:s,approvalSig:o})});r&&(e.partsSig.value=i)}function Xn(e,t){let n=t.filter(e=>!e.ephemeral&&(e.status===`streaming`||e.status===`pending`||e.status===`error`||e.retryAction!==void 0||(e.attachments?.length??0)>0||Fn(e))),r=new Map;for(let e of n)r.set(e.id,e),e.serverMessageId!==void 0&&r.set(e.serverMessageId,e);let i=new Set,a=[],o=e.map(e=>{let t=(e.serverMessageId===void 0?void 0:r.get(e.serverMessageId))??r.get(e.id);return t===void 0?(a.push(e),e):(i.add(t),t.role===e.role?t.role===`user`&&t.serverMessageId===void 0&&(t.status===`pending`||t.status===`error`)?Kn(t,e):t.status===`streaming`||Nn(t).length>=Nn(e).length?(Yn(t,e),t.suggestions??(t.suggestions=e.suggestions),t.feedback===void 0&&(t.feedback=e.feedback),e.canceled&&(t.canceled=!0),t):Kn(t,e):e)}),s=n.filter(e=>!i.has(e)),c=s.findLast(Jn),l=new Map;e.forEach((e,t)=>{l.set(e.id,t),e.serverMessageId!==void 0&&l.set(e.serverMessageId,t)});let u=qn(c,c?n.slice(0,n.indexOf(c)):[],a,l);if(c&&u){let e=o.indexOf(u);e>=0&&(o[e]=Kn(c,u)),s=s.filter(e=>e!==c)}return[...o,...s]}function Zn(e,t){let n=new Map(t.filter(e=>e.serverMessageId!==void 0).map(e=>[e.serverMessageId,e])),r=new Map;t.forEach((e,t)=>{r.set(e.id,t),e.serverMessageId!==void 0&&r.set(e.serverMessageId,t)});let i=new Set(e.flatMap(e=>[e.serverMessageId,e.id].filter(e=>e!==void 0))),a=!1,o=e.map(e=>{let t=n.get(e.serverMessageId??e.id);if(t===void 0||t.role!==e.role)return e;if(e.role===`user`&&e.serverMessageId===void 0)return a=!0,Kn(e,t);if(e.serverMessageId===void 0)return e;let r=Nn(t),i=Nn(e),o=t.status!==`streaming`&&r.length>=i.length&&nr(e,t);if(r.length>i.length||r===i&&t.partsSig.value.length>e.partsSig.value.length||o)return a=!0,Kn(e,t);if(e.status===`streaming`&&t.status!==`streaming`&&$n(e,t)){if(e.continuationStreaming&&Wn(t))return e;if(!nr(t,e))return a=!0,Kn(e,t)}return e}),s=[...n.values()].filter(e=>!i.has(e.serverMessageId)),c=o.findLastIndex(Jn),l=o[c],u=qn(l,o.slice(0,c),s,r);if(l!==void 0&&u!==void 0&&Nn(u).length>=Nn(l).length&&(Kn(l,u),o[c]=u,s.splice(s.indexOf(u),1),a=!0),s.length===0)return{messages:a?o:e,changed:a};for(let e of s){let t=r.get(e.serverMessageId??e.id),n=!1,i=o.findIndex(e=>{let i=r.get(e.serverMessageId??e.id);return t===void 0?!1:i===void 0?n:i>t?!0:(n=!0,!1)});i===-1?o.push(e):o.splice(i,0,e)}return{messages:o,changed:!0}}function Qn(e,t){if(e.role!==t.role)return!1;let n=Nn(t),r=Nn(e);return n.length>r.length||t.partsSig.value.length>e.partsSig.value.length||nr(e,t)}function $n(e,t){let n=e.partsSig.value,r=t.partsSig.value;return n.length===r.length&&n.every((e,t)=>{let n=r[t];switch(e.kind){case`text`:return n?.kind===`text`&&n.textSig.value===e.textSig.value;case`reasoning`:return n?.kind===`reasoning`&&n.textSig.value===e.textSig.value;case`step-start`:return n?.kind===`step-start`;case`tool`:return n?.kind===`tool`&&n.toolCallId===e.toolCallId&&er(n.toolName,e.toolName);case`file`:return n?.kind===`file`&&n.url===e.url&&n.mediaType===e.mediaType;case`source`:return n?.kind===`source`&&n.sourceId===e.sourceId&&n.url===e.url&&n.title===e.title&&n.filename===e.filename&&n.mediaType===e.mediaType;default:return e}})}function er(e,t){return(e.startsWith(`tool:`)?e.slice(5):e)===(t.startsWith(`tool:`)?t.slice(5):t)}const tr={"input-streaming":0,"input-available":1,"approval-requested":2,"approval-responded":3,"output-available":4,"output-denied":4,"output-error":4};function nr(e,t){let n=new Map(e.partsSig.value.filter(Rn).map(e=>[e.toolCallId,e]));return t.partsSig.value.filter(Rn).some(e=>{let t=n.get(e.toolCallId);if(!t||tr[e.stateSig.value]>tr[t.stateSig.value])return!0;let r=e.approvalSig.value?.approved;return r!==void 0&&r!==t.approvalSig.value?.approved})}function rr(e){return e.role===`assistant`&&e.status!==`streaming`&&!Fn(e)}function ir(e,t){if(!e.includes(t)||t.retryAction===null)return;if(t.retryAction)return t.retryAction;if(t!==e.at(-1)||t.role!==`assistant`||t.serverMessageId===void 0||t.status!==`error`&&!rr(t))return;let n=e.indexOf(t);for(let t=n-1;t>=0;t--){let n=e[t];if(n?.role===`user`&&!n.ephemeral)return{kind:`repeat-user`,messageId:n.id}}}function ar(e){return e.canceled===!0&&e.role===`assistant`&&e.status!==`streaming`&&!In(e)}function or(e,t){return e.operatorRoutedTurn?rr(e)?`drop`:`complete-operator-routed`:t||rr(e)?`error`:`complete`}function sr(e){return e.kind===`text`||e.kind===`reasoning`?{kind:e.kind,id:e.id,textSig:f(e.text),doneSig:f(e.done)}:e.kind===`tool`?{kind:`tool`,toolCallId:e.toolCallId,toolName:e.toolName,dynamic:e.dynamic,inputPartialSig:f(e.inputPartial),inputSig:f(e.input),outputSig:f(e.output),errorSig:f(e.error),stateSig:f(e.state),approvalSig:f(e.approval)}:e}function cr(e){return e.kind===`text`||e.kind===`reasoning`?{kind:e.kind,id:e.id,text:e.textSig.value,done:e.doneSig.value}:e.kind===`tool`?{kind:`tool`,toolCallId:e.toolCallId,toolName:e.toolName,dynamic:e.dynamic,inputPartial:e.inputPartialSig.value,input:e.inputSig.value,output:e.outputSig.value,error:e.errorSig.value,state:e.stateSig.value,approval:e.approvalSig.value}:e}const lr=I.scope(`feedback:audio`);var ur=class{constructor(){U(this,`ctx`,null),U(this,`master`,null),U(this,`buffers`,new Map)}unlock(){if(this.ctx){this.ctx.state===`suspended`&&this.ctx.resume();return}let e=globalThis.AudioContext??globalThis.webkitAudioContext;if(e)try{this.ctx=new e,this.master=this.ctx.createGain(),this.master.gain.value=1,this.master.connect(this.ctx.destination)}catch(e){lr.warn(`AudioContext init failed`,{err:e})}}setVolume(e){if(!this.master||!this.ctx)return;let t=Math.max(0,Math.min(1,e));this.master.gain.setTargetAtTime(t,this.ctx.currentTime,.01)}playTone(e){let t=this.ctx,n=this.master;if(!t||!n||t.state!==`running`)return;let r=t.currentTime,i=e.noteMs/1e3;e.notes.forEach((a,o)=>{let s=t.createOscillator();s.type=e.type,s.frequency.value=a;let c=t.createGain(),l=r+o*i;c.gain.setValueAtTime(1e-4,l),c.gain.exponentialRampToValueAtTime(e.peakGain,l+.005),c.gain.exponentialRampToValueAtTime(1e-4,l+i),s.connect(c).connect(n),s.start(l),s.stop(l+i+.01)})}async playUrl(e){let t=this.ctx,n=this.master;if(!t||!n||t.state!==`running`)return;let r=await this.getBuffer(e);if(!r)return;let i=t.createBufferSource();i.buffer=r,i.connect(n),i.start()}destroy(){this.ctx&&this.ctx.close().catch(()=>void 0),this.ctx=null,this.master=null,this.buffers.clear()}async getBuffer(e){if(!this.ctx)return null;let t=this.buffers.get(e);if(t)return t instanceof Promise,t;let n=this.ctx,r=fetch(e).then(e=>e.ok?e.arrayBuffer():Promise.reject(Error(`fetch ${e.status}`))).then(e=>n.decodeAudioData(e)).then(t=>(this.buffers.set(e,t),t)).catch(t=>(lr.warn(`audio fetch/decode failed`,{url:e,err:t}),this.buffers.delete(e),null));return this.buffers.set(e,r),r}};const dr={messageReceived:10,messageSent:0,error:[20,40,20],voiceStart:10,voiceStop:0},fr={messageReceived:{notes:[880,1318.51],noteMs:90,type:`sine`,peakGain:.45},messageSent:{notes:[1568],noteMs:60,type:`sine`,peakGain:.25},error:{notes:[523.25,392],noteMs:120,type:`triangle`,peakGain:.55},voiceStart:{notes:[1318.51],noteMs:50,type:`sine`,peakGain:.3},voiceStop:{notes:[880],noteMs:50,type:`sine`,peakGain:.3}};let pr=null,mr=0;function hr(){return typeof navigator<`u`&&typeof navigator.vibrate==`function`}function gr(){if(typeof document>`u`)return null;let e=document.createElement(`input`);e.type=`checkbox`,e.setAttribute(`switch`,``),e.setAttribute(`aria-hidden`,`true`),e.tabIndex=-1,e.id=`__${b.cssPrefix}_haptic_${Math.random().toString(36).slice(2)}`;let t=document.createElement(`label`);t.htmlFor=e.id,t.setAttribute(`aria-hidden`,`true`);let n=`position:absolute!important;width:1px!important;height:1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;opacity:0!important;pointer-events:none!important;`;return e.style.cssText=n,t.style.cssText=n,document.body.append(e,t),{input:e,label:t}}function _r(e){if(!(e===0||Array.isArray(e)&&e.every(e=>e===0))){if(hr())try{navigator.vibrate(e);return}catch{}if(pr??(pr=gr()),pr)try{pr.label.click()}catch{}}}function vr(){mr++;let e=!1;return()=>{e||(e=!0,mr=Math.max(0,mr-1),mr===0&&pr&&(pr.input.remove(),pr.label.remove(),pr=null))}}const yr=I.scope(`feedback`);var br=class{constructor(e,t){U(this,`mutedSig`,f(!1)),U(this,`audio`,new ur),U(this,`releaseHaptics`,void 0),U(this,`sound`,void 0),U(this,`haptics`,void 0),U(this,`lastPlayed`,new Map),U(this,`reducedMotionMq`,null),this.sound=e,this.haptics=t,this.releaseHaptics=vr(),this.audio.setVolume(this.effectiveVolume()),typeof matchMedia<`u`&&(this.reducedMotionMq=matchMedia(`(prefers-reduced-motion: reduce)`))}unlock(){this.audio.unlock(),this.audio.setVolume(this.effectiveVolume())}update(e,t){this.sound=e,this.haptics=t,this.audio.setVolume(this.effectiveVolume())}setMuted(e){this.mutedSig.value!==e&&(this.mutedSig.value=e)}toggleMuted(){this.mutedSig.value=!this.mutedSig.value}play(e){this.mutedSig.value||this.isDeduped(e)||(this.lastPlayed.set(e,performance.now()),this.sound.enabled&&this.playSound(e),this.haptics.enabled&&this.isTouchDevice()&&this.playHaptic(e))}destroy(){this.audio.destroy(),this.releaseHaptics()}isDeduped(e){let t=this.lastPlayed.get(e);return t!==void 0&&performance.now()-t<100}playSound(e){let t=this.sound.events?.[e];if(t===!1)return;if(typeof t==`string`){this.audio.playUrl(t).catch(e=>yr.warn(`audio play failed`,{err:e,url:t}));return}let n=fr[e];n&&this.audio.playTone(n)}playHaptic(e){if(this.reducedMotionMq?.matches)return;let t=this.haptics.events?.[e];t!==!1&&_r(t===!0||t===void 0?dr[e]:t)}effectiveVolume(){let e=this.sound.volume??.3;return this.reducedMotionMq?.matches?e*.5:e}isTouchDevice(){return typeof window>`u`?!1:matchMedia(`(hover: none) and (pointer: coarse)`).matches}};const G={fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,viewBox:`0 0 24 24`},xr=`${b.cssPrefix}-icon-dir`,Sr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M21 12a8 8 0 0 1-12 6.93L3 21l1.65-5.16A8 8 0 1 1 21 12Z`})}),Cr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M18 6 6 18M6 6l12 12`})}),wr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 5v14M5 12h14`})}),Tr=()=>_(`svg`,{...G,class:xr,"aria-hidden":`true`,children:[g(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),g(`path`,{d:`M22 2 11 13`})]}),Er=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 19V5M5 12l7-7 7 7`})}),Dr=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`M3 20V4l18 8-18 8Z`})}),Or=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`m9 18 6-6-6-6`})}),kr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})}),Ar=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`m21 11-9 9a5.5 5.5 0 0 1-7.78-7.78l8.49-8.49a3.67 3.67 0 0 1 5.19 5.19l-8.49 8.49a1.83 1.83 0 0 1-2.6-2.6l7.78-7.78`})}),jr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`rect`,{x:`9`,y:`2`,width:`6`,height:`12`,rx:`3`}),g(`path`,{d:`M5 10a7 7 0 0 0 14 0M12 19v3`})]}),Mr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 8V3h5M21 8V3h-5M3 16v5h5M21 16v5h-5`})}),Nr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M8 3v5H3M16 3v5h5M8 21v-5H3M16 21v-5h5`})}),Pr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 3h7v2H5v5H3zM21 3h-7v2h5v5h2zM3 21h7v-2H5v-5H3zM21 21h-7v-2h5v-5h2z`})}),Fr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M10 3v5H3M14 3v5h7M10 21v-5H3M14 21v-5h7`})}),Ir=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M14 3h7v7M21 3l-9 9`}),g(`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`})]}),Lr=()=>g(`svg`,{...G,"aria-hidden":`true`,viewBox:`0 0 10 10`,children:g(`path`,{d:`M9 1L1 9M9 5L5 9M9 9H9`,strokeWidth:`1.5`})}),Rr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:`currentColor`,stroke:`none`}),g(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:`currentColor`,stroke:`none`}),g(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:`currentColor`,stroke:`none`})]}),zr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M11 5 6 9H2v6h4l5 4zM15 9a5 5 0 0 1 0 6M18 7a9 9 0 0 1 0 10`})}),Br=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M11 5 6 9H2v6h4l5 4zM22 9l-6 6M16 9l6 6`})}),Vr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M3 18 8 6l5 12M4.7 14h6.6`}),g(`path`,{d:`M14.5 18l3.2-7 3.2 7M15.6 15.8h4.2`})]}),Hr=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`m5 6 6 6-6 6M13 6l6 6-6 6`})}),Ur=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M20 6 9 17l-5-5`})}),Wr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M3 3v6h6`}),g(`path`,{d:`M3.05 13A9 9 0 1 0 6 5.3L3 9`}),g(`path`,{d:`M12 7v5l3 2`})]}),Gr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`10`}),g(`path`,{d:`M2 12h20`}),g(`path`,{d:`M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z`})]}),Kr=()=>g(`svg`,{...G,class:xr,"aria-hidden":`true`,children:g(`path`,{d:`M19 12H5M12 19l-7-7 7-7`})}),qr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M12 20h9`}),g(`path`,{d:`M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z`})]}),Jr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`m6 9 6 6 6-6`})}),Yr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z`}),g(`path`,{d:`M14 2v6h6`})]}),Xr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`m12 3-1.5 4.5L6 9l4.5 1.5L12 15l1.5-4.5L18 9l-4.5-1.5Z`}),g(`path`,{d:`M19 15v4M17 17h4M5 3v2M4 4h2`})]}),Zr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z`})}),Qr=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`10`}),g(`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`}),g(`path`,{d:`M12 17h.01`})]}),$r=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`m15 4 3 3-9 9-3-3z`}),g(`path`,{d:`M18 2v2M20 4h2M3 20l3-3M3 16h2M5 14v2`})]}),ei=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`rect`,{x:`4`,y:`8`,width:`16`,height:`12`,rx:`2`}),g(`path`,{d:`M12 8V4`}),g(`circle`,{cx:`12`,cy:`3`,r:`1`}),g(`path`,{d:`M2 14h2M20 14h2M9 13h.01M15 13h.01M9.5 17h5`})]}),ti=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M4 14v-2a8 8 0 0 1 16 0v2`}),g(`rect`,{x:`2`,y:`14`,width:`4`,height:`6`,rx:`1.5`}),g(`rect`,{x:`18`,y:`14`,width:`4`,height:`6`,rx:`1.5`}),g(`path`,{d:`M20 20v1a3 3 0 0 1-3 3h-5`})]}),ni=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`10`}),g(`circle`,{cx:`12`,cy:`12`,r:`4`}),g(`path`,{d:`m4.93 4.93 4.24 4.24M14.83 14.83l4.24 4.24M14.83 9.17l4.24-4.24M4.93 19.07l4.24-4.24`})]}),ri=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`11`,cy:`11`,r:`7`}),g(`path`,{d:`m21 21-4.3-4.3`})]}),ii=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`m8.5 12 2.5 2.5 4.5-5`})]}),ai=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M3 9.5 12 3l9 6.5`}),g(`path`,{d:`M5 9v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9`})]}),oi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`m3 11 15-5v12L3 13z`}),g(`path`,{d:`M3 11v2a2 2 0 0 0 2 2h1V9H5a2 2 0 0 0-2 2z`}),g(`path`,{d:`M7 15v3a2 2 0 0 0 4 0v-2`}),g(`path`,{d:`M21 10a3 3 0 0 1 0 4`})]}),si=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z`}),g(`path`,{d:`M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1`})]}),ci=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`4`}),g(`path`,{d:`M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41`})]}),li=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z`})}),ui=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`M12 3v18`}),g(`path`,{d:`M12 3a9 9 0 0 1 0 18z`,fill:`currentColor`,stroke:`none`})]}),di=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`10.5`,cy:`10.5`,r:`6.5`}),g(`path`,{d:`M8 11a2.5 2.5 0 0 0 5 0`}),g(`path`,{d:`m20 20-4.4-4.4`})]}),fi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M12 3.5 13.6 9 19 10.5 13.6 12 12 17.5 10.4 12 5 10.5 10.4 9z`}),g(`path`,{d:`M18.5 4v3M20 5.5h-3M5.5 16v2.5M6.75 17.25h-2.5`})]}),pi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M4 18h16`}),g(`path`,{d:`M5 18a7 7 0 0 1 14 0`}),g(`path`,{d:`M12 8V6`}),g(`path`,{d:`M10 6h4`})]}),mi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M7 11V6.5a1.5 1.5 0 0 1 3 0V10`}),g(`path`,{d:`M10 10V5.5a1.5 1.5 0 0 1 3 0V10`}),g(`path`,{d:`M13 10V6.5a1.5 1.5 0 0 1 3 0V12`}),g(`path`,{d:`M16 9.5a1.5 1.5 0 0 1 3 0v2.5a7 7 0 0 1-7 7 7 7 0 0 1-6.4-4.2L4 12.5a1.5 1.5 0 0 1 2.6-1.5L7 11`})]}),hi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`rect`,{x:`9`,y:`9`,width:`11`,height:`11`,rx:`2`}),g(`path`,{d:`M5 15a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2`})]}),gi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M7 10v11H4a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z`}),g(`path`,{d:`M7 10l4-7a2.5 2.5 0 0 1 2.5 2.5V8h5a2 2 0 0 1 2 2.3l-1.2 8A2 2 0 0 1 17.3 20H7`})]}),_i=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`path`,{d:`M17 14V3h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1z`}),g(`path`,{d:`M17 14l-4 7a2.5 2.5 0 0 1-2.5-2.5V16h-5a2 2 0 0 1-2-2.3l1.2-8A2 2 0 0 1 6.7 4H17`})]}),vi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`3.5`}),g(`path`,{d:`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9l-2.1 2.1M7 17l-2.1 2.1`})]}),yi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`M12 7v5l3 2`})]}),bi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`m8.5 12 2.5 2.5 4.5-5`})]}),xi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`m15 9-6 6M9 9l6 6`})]}),Si={chat:Sr,message:Zr,bubbles:si,spark:Xr,wand:$r,bot:ei,help:Qr,lifebuoy:ni,headset:ti,search:di,sparkles:fi,concierge:pi,wave:mi},K=b.cssPrefix,q={launcher:`${K}-launcher`,callout:`${K}-callout`,calloutDismiss:`${K}-callout-dismiss`,panel:`${K}-panel`,panelHeader:`${K}-panel-header`,resizeGrip:`${K}-resize-grip`,scrollToBottom:`${K}-scroll-to-bottom`,loadPreviousMessages:`${K}-load-previous-messages`,actionHistory:`${K}-action-history`,actionClose:`${K}-action-close`,langSegment:`${K}-lang-segment`,composer:`${K}-composer`,composerInput:`${K}-composer-input`,composerSend:`${K}-composer-send`,composerStop:`${K}-composer-stop`,compactionStatus:`${K}-compaction-status`,messageQueue:`${K}-message-queue`,queuedMessage:`${K}-queued-message`,queuedMessageRemove:`${K}-queued-message-remove`,composerAttach:`${K}-composer-attach`,composerFileInput:`${K}-composer-file-input`,composerVoice:`${K}-composer-voice`,attachmentChip:`${K}-attachment-chip`,attachmentRemove:`${K}-attachment-remove`,suggestion:`${K}-suggestion`,messageBubble:`${K}-message`,messageRetry:`${K}-message-retry`,messageFeedback:`${K}-message-feedback`,feedbackUp:`${K}-feedback-up`,feedbackDown:`${K}-feedback-down`,messageCopy:`${K}-message-copy`,historyPane:`${K}-history-pane`,historyBack:`${K}-history-back`,historyItem:`${K}-history-item`,historyLoadMore:`${K}-history-load-more`,sidebar:`${K}-sidebar`,sidebarToggle:`${K}-sidebar-toggle`,sidebarNewConversation:`${K}-sidebar-new-conversation`,sidebarItem:`${K}-sidebar-item`,messengerHome:`${K}-messenger-home`,modulesEmpty:`${K}-modules-empty`,tab:`${K}-tab`,tabBadge:`${K}-tab-badge`,homeView:`${K}-home-view`,homeGreeting:`${K}-home-greeting`,homeBrand:`${K}-home-brand`,backHeader:`${K}-back-header`,contentView:`${K}-content-view`,contentScroll:`${K}-content-scroll`,homeSearch:`${K}-home-search`,helpSearch:`${K}-help-search`,homeRecent:`${K}-home-recent`,homeContentRow:`${K}-home-content-row`,helpArticle:`${K}-help-article`,newsItem:`${K}-news-item`,formGate:`${K}-form-gate`,formDone:`${K}-form-done`,formDoneToggle:`${K}-form-done-toggle`,formAnswers:`${K}-form-answers`,formFill:`${K}-form-fill`,formSubmit:`${K}-form-submit`,formSkip:`${K}-form-skip`,formField:`${K}-form-field`,toolAskQuestions:`${K}-tool-ask-questions`,toolInputSubmit:`${K}-tool-input-submit`,toolInputSkip:`${K}-tool-input-skip`,toolApproval:`${K}-tool-approval`,toolApprove:`${K}-tool-approve`,toolReject:`${K}-tool-reject`,toolEdit:`${K}-tool-edit`,toolDecision:`${K}-tool-decision`,typingDots:`${K}-typing-dots`,reasoning:`${K}-reasoning`,toolAskSummary:`${K}-ask-questions-summary`,toolAskOptions:`${K}-ask-questions-options-toggle`,toolCall:`${K}-tool-call`,source:`${K}-source`,operatorRequest:`${K}-operator-request`,operatorBanner:`${K}-operator-banner`,cancelOperatorRequest:`${K}-cancel-operator-request`};function Ci(e,t){return`${e}-${t}`}const wi=b.cssPrefix;function Ti({onToggle:e,launcher:t,strings:n,leaving:r,edgeTab:i}){let a=t.variant!==`circle`&&!!t.label;return _(`button`,{type:`button`,class:`${wi}-fab`,"data-variant":t.variant,"data-size":t.size,"data-edge-tab":i?`true`:void 0,"data-leaving":r?`true`:void 0,"data-testid":q.launcher,onClick:e,"aria-label":n.launcherOpen,children:[Ei(t.icon),a?g(`span`,{class:`${wi}-fab-label`,children:D(n,t.label??``)}):null]})}function Ei(e){let t=Si[e];return t?g(t,{}):g(Di,{source:e})}function Di({source:e}){return g(`span`,{ref:t=>{t&&Oi(t,e)},"aria-hidden":`true`})}function Oi(e,t){if(e.dataset.svgMounted!==t)try{let n=new DOMParser().parseFromString(t,`image/svg+xml`).documentElement;n.tagName.toLowerCase()===`svg`&&(e.replaceChildren(document.importNode(n,!0)),e.dataset.svgMounted=t)}catch{}}function ki({callout:e,launcherPosition:t,strings:n,closeLabel:r,onDismiss:a}){let[o,s]=c(!1);return i(()=>{let t=setTimeout(()=>s(!0),e.delayMs);return()=>clearTimeout(t)},[e.delayMs]),i(()=>{if(!o||e.autoDismissMs<=0)return;let t=setTimeout(a,e.autoDismissMs);return()=>clearTimeout(t)},[o,e.autoDismissMs,a]),o?_(`div`,{class:`${wi}-callout`,role:`status`,"data-shape":e.shape,"data-position":Ai(e.position,t),"data-animated":e.animated?`true`:void 0,"data-testid":q.callout,children:[g(`span`,{children:D(n,e.text)}),g(`button`,{type:`button`,class:`${wi}-callout-close`,onClick:a,"aria-label":r,title:r,"data-testid":q.calloutDismiss,children:g(Cr,{})})]}):null}function Ai(e,t){let n=t.endsWith(`-right`),r=t.startsWith(`bottom-`);return e===`vertical`?r?`top`:`bottom`:n?`left`:`right`}function ji({panelEl:e,resize:t,position:n,initialSize:r,onSizeChange:a,strings:o}){let c=b.cssPrefix,l=s(null);if(i(()=>{if(!e)return;let n=e.style;t.minWidth&&n.setProperty(`--${c}-resize-min-w`,t.minWidth),t.maxWidth&&n.setProperty(`--${c}-resize-max-w`,t.maxWidth),t.minHeight&&n.setProperty(`--${c}-resize-min-h`,t.minHeight),t.maxHeight&&n.setProperty(`--${c}-resize-max-h`,t.maxHeight),r&&(n.setProperty(`--${c}-widget-w`,`${r.width}px`),n.setProperty(`--${c}-widget-h`,`${r.height}px`))},[e,t.minWidth,t.maxWidth,t.minHeight,t.maxHeight,c,r]),!e)return null;let u=n.startsWith(`top-`),d=n.endsWith(`-right`),f=`${c}-resize-grip ${c}-resize-grip--${u?`bottom`:`top`}-${d?`left`:`right`}`,p=t=>{if(!e)return;let n=t.currentTarget,r=e.getBoundingClientRect();l.current={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,startW:r.width,startH:r.height,dirX:d?-1:1,dirY:u?1:-1},n.setPointerCapture(t.pointerId),e.setAttribute(`data-resizing`,``),t.preventDefault()},m=t=>{let n=l.current;if(!n||t.pointerId!==n.pointerId||!e)return;let r=(t.clientX-n.startX)*n.dirX,i=(t.clientY-n.startY)*n.dirY;e.style.setProperty(`--${c}-widget-w`,`${n.startW+r}px`),e.style.setProperty(`--${c}-widget-h`,`${n.startH+i}px`)},h=t=>{let n=l.current;if(!n||t.pointerId!==n.pointerId||!e)return;t.currentTarget.releasePointerCapture(t.pointerId),e.removeAttribute(`data-resizing`);let r=e.getBoundingClientRect();a({width:Math.round(r.width),height:Math.round(r.height)}),l.current=null};return g(`div`,{class:f,role:`separator`,"aria-orientation":`vertical`,"aria-label":o.resizeHandle,title:o.resizeHandle,onPointerDown:p,onPointerMove:m,onPointerUp:h,onPointerCancel:h,"data-testid":q.resizeGrip,children:g(Lr,{})})}const Mi=b.cssPrefix,Ni=`.${Mi}-header, .${Mi}-back-header, .${Mi}-home-hero`;function Pi(e,t){i(()=>{if(!t||!e)return;let n=e=>Number.parseFloat(e)||0,r=(e,t)=>Math.min(t,Math.max(-t,e)),i=null,a=t=>{let r=t.target;if(!(r instanceof Element)||!r.closest(Ni)||r.closest(`button, a, input, textarea, select, [role="tab"], [contenteditable]`))return;let a=e.getBoundingClientRect();i={id:t.pointerId,x:t.clientX,y:t.clientY,dx:n(e.style.getPropertyValue(`--${Mi}-modal-dx`)),dy:n(e.style.getPropertyValue(`--${Mi}-modal-dy`)),maxX:(window.innerWidth+a.width)/2-56,maxY:(window.innerHeight+a.height)/2-56},e.dataset.dragging=`true`,t.preventDefault()},o=t=>{if(!i||t.pointerId!==i.id)return;let n=r(i.dx+t.clientX-i.x,i.maxX),a=r(i.dy+t.clientY-i.y,i.maxY);e.style.setProperty(`--${Mi}-modal-dx`,`${n}px`),e.style.setProperty(`--${Mi}-modal-dy`,`${a}px`)},s=t=>{!i||t.pointerId!==i.id||(i=null,delete e.dataset.dragging)};return e.addEventListener(`pointerdown`,a),window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s),window.addEventListener(`pointercancel`,s),()=>{e.removeEventListener(`pointerdown`,a),window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s)}},[e,t])}function Fi(e,t,n){switch(e){case`clear`:case`sound`:case`history`:case`language`:case`theme`:case`textSize`:return!0;case`popOut`:return t!==`standalone`&&t!==`page`;case`expand`:return t===`floating`;case`fullscreen`:return t!==`standalone`;case`close`:return t===`standalone`||t===`page`?!1:t!==`inline`||n===`fullscreen`}}function Ii(e,t,n){return Fi(`close`,e,t)?n.includes(`close`):!1}function Li(e,t){return e===`inline`&&t===`fullscreen`?`exit-fullscreen`:`close`}function Ri(e){let t=t=>{if(t.key!==`Tab`)return;let n=[...e.querySelectorAll(`a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),[tabindex]:not([tabindex="-1"])`)].filter(e=>e.offsetParent!==null||e===document.activeElement);if(n.length===0){t.preventDefault();return}let r=n[0],i=n[n.length-1];if(!r||!i)return;let a=e.getRootNode().activeElement;t.shiftKey&&a===r?(t.preventDefault(),i.focus()):!t.shiftKey&&a===i&&(t.preventDefault(),r.focus())};return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)}function zi(e){return e.trim().split(/\s+/).slice(0,2).map(e=>e.charAt(0).toUpperCase()).join(``)}const Bi=b.cssPrefix;function Vi({agent:e,strings:t}){let n=e.status??`online`,r=D(t,e.name),i=e.title?D(t,e.title):null;return _(`div`,{class:`${Bi}-agent`,children:[g(`div`,{class:`${Bi}-agent-avatar`,"data-status":n,children:e.avatar?g(`img`,{src:e.avatar,alt:``}):g(`span`,{children:zi(r)})}),_(`div`,{class:`${Bi}-agent-meta`,children:[g(`strong`,{children:r}),i?g(`span`,{children:i}):null]})]})}const Hi=I.scope(`attachments`);function Ui(e,t,n){let r=Ki(e),i=[],a=[],o=Yi(n.accept),s=t.reduce((e,t)=>e+t.size,0),c=t.length;for(let e of r){let t=Gi(e,c,s,n,o);if(t){a.push({file:e,reason:t});continue}i.push(Ji(e)),s+=e.size,c+=1}return(i.length||a.length)&&Hi.debug(`ingest`,{accepted:i.length,rejected:a.map(e=>({name:e.file.name,reason:e.reason}))}),{accepted:i,rejected:a}}function Wi(e){try{URL.revokeObjectURL(e.previewUrl)}catch(e){Hi.debug(`revokeObjectURL failed`,{error:e})}}function Gi(e,t,n,r,i){return t>=r.maxCount?`count`:n+e.size>r.maxBytes?`bytes`:Xi(e,i)?null:`mime`}function Ki(e){return e?Array.isArray(e)?e.filter(e=>e instanceof File):[...e].map(e=>e instanceof File?e:qi(e)).filter(e=>e!==null):[]}function qi(e){let t=e;return!t?.getAsFile||t.kind!==`file`?null:t.getAsFile()}function Ji(e){return{file:e,id:ct(),mediaType:e.type||`application/octet-stream`,name:e.name||`pasted-file`,previewUrl:URL.createObjectURL(e),size:e.size}}function Yi(e){return e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean).map(e=>{if(e.startsWith(`.`))return{kind:`ext`,ext:e};let[t=`*`,n=`*`]=e.split(`/`);return{kind:`mime`,type:t,subtype:n}})}function Xi(e,t){if(t.length===0)return!0;let[n=`*`,r=`*`]=(e.type||``).toLowerCase().split(`/`),i=(e.name||``).toLowerCase();return t.some(e=>e.kind===`ext`?i.endsWith(e.ext):(e.type===`*`||e.type===n)&&(e.subtype===`*`||e.subtype===r))}const Zi=b.cssPrefix;function Qi({attachment:e,onRemove:t,disabled:n=!1}){let r=e.mediaType.startsWith(`image/`);return _(`span`,{class:`${Zi}-attachment-chip`,title:e.name,"data-testid":Ci(q.attachmentChip,e.id),children:[r?g(`img`,{class:`${Zi}-attachment-thumb`,src:e.previewUrl,alt:``}):g(`span`,{class:`${Zi}-attachment-thumb`,"aria-hidden":`true`,children:g(Yr,{})}),g(`span`,{class:`${Zi}-attachment-name`,children:e.name}),g(`button`,{type:`button`,class:`${Zi}-attachment-remove`,onClick:t,disabled:n,"aria-label":`Remove ${e.name}`,"data-testid":Ci(q.attachmentRemove,e.id),children:g(Cr,{})})]})}const $i={isSupported:!1,start:()=>void 0,stop:()=>void 0,cancel:()=>void 0};function ea(e,t,n){return e===`disabled`?$i:e===`server`?ia(n):ta(t)}function ta(e){let t=na();if(!t)return $i;let n=null,r=0;return{isSupported:!0,start(i,a){let o=n,s=++r;n=null,o?.abort();let c=new t;n=c,c.continuous=!0,c.interimResults=!0,c.lang=e;let l=!1;c.addEventListener(`result`,e=>{if(r!==s||n!==c)return;let t=e,a=``,o=!1;for(let e=t.resultIndex;e<t.results.length;e++){let n=t.results[e];n&&(a+=n[0].transcript,n.isFinal&&(o=!0))}i(a,o)});let u=()=>{l||r!==s||n!==c||(l=!0,n=null,a())};c.addEventListener(`end`,u),c.addEventListener(`error`,u);try{c.start()}catch{u()}},stop(){n?.stop()},cancel(){r++;let e=n;n=null,e?.abort()}}}function na(){return window.SpeechRecognition??window.webkitSpeechRecognition}const ra=[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/mp4`];function ia(e){if(typeof MediaRecorder>`u`||!navigator?.mediaDevices?.getUserMedia)return $i;let t=0,n=null,r=e=>{for(let t of e.stream?.getTracks()??[])t.stop();e.stream=null},i=()=>{t++;let e=n;n=null,e&&(r(e),e.recorder?.state!==`inactive`&&e.recorder?.stop())},a=async i=>{if(i.finishing)return;i.finishing=!0;let a=i.recorder?.mimeType??`audio/webm`;r(i);let o=new Blob(i.chunks,{type:a});i.chunks=[];try{let{text:r}=await e(o,a);n===i&&t===i.generation&&r&&i.onText(r,!0)}catch{}finally{n===i&&t===i.generation&&(n=null,i.onEnd())}};return{isSupported:!0,async start(e,o){i();let s={generation:t,recorder:null,stream:null,chunks:[],onText:e,onEnd:o,finishing:!1};n=s;try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});if(n!==s||t!==s.generation){for(let t of e.getTracks())t.stop();return}s.stream=e;let r=aa(),i=new MediaRecorder(e,r?{mimeType:r}:void 0);s.recorder=i,i.addEventListener(`dataavailable`,e=>{n===s&&t===s.generation&&e.data.size>0&&s.chunks.push(e.data)}),i.addEventListener(`stop`,()=>{n===s&&t===s.generation&&a(s)}),i.start()}catch{r(s),n===s&&t===s.generation&&(n=null,o())}},stop(){let e=n;if(e){if(!e.recorder){i();return}e.recorder.state!==`inactive`&&e.recorder.stop()}},cancel(){i()}}}function aa(){for(let e of ra)if(MediaRecorder.isTypeSupported(e))return e}const J=b.cssPrefix,oa=I.scope(`composer`);function sa(e){return e.reduce((e,t)=>e+t.size,0)}const ca={arrowUp:Er,paperPlane:Tr,send:Dr,chevron:Or};function la(e){return`activeElement`in e}function ua(e){return`host`in e&&`activeElement`in e}function da({options:e,transport:t,feedback:n,bus:a,persistence:o,conversationId:l,isStreaming:u,isMemoryCompacting:d=!1,canReleaseQueuedMessages:f=!0,queueManualMessages:p=!1,active:m=!0,isPreparing:h=!1,operatorRequestEnabled:v,canRequestOperator:y=!1,controlMode:b=`ai-agent`,onRequestOperator:x,onSend:S,onStop:C,apiRef:w}){let T=e.strings,[E,D]=c(()=>o.loadDraft(l)),[O,k]=c([]),[A,j]=c(()=>o.loadMessageQueue(l).map(e=>({id:e.id,text:e.text,attachments:[]}))),M=s(A),ee=s(!1),[te,N]=c(!1),[ne,re]=c(!1),P=s(!1),F=s(null),ie=s(null),ae=s(null),I=s(0),L=s(l);L.current=l;let oe=s(m);oe.current=m;let se=s(h);se.current=h;let ce=ne||h||!m,le=u&&b===`ai-agent`,ue=le||d&&b===`ai-agent`,de=b===`ai-agent`&&(ue||p||A.length>0),fe=r(e=>{j(t=>{let n=e(t);return o.saveMessageQueue(L.current,n.filter(e=>e.attachments.length===0).map(({id:e,text:t})=>({id:e,text:t}))),M.current=n,n})},[o]),pe=r(e=>{fe(t=>(t.find(t=>t.id===e)?.attachments.forEach(Wi),t.filter(t=>t.id!==e)))},[fe]),me=r(e=>{D(t=>{let n=typeof e==`function`?e(t):e;return n===t?t:(o.saveDraft(L.current,n),n)})},[o]),R=e.features.fileUpload,he=e.features.voice,[ge,_e]=c(()=>ea(he,e.locale,(e,n)=>t.transcribe(e,n))),ve=s(ge);ve.current=ge;let z=s({mode:he,locale:e.locale,transport:t});i(()=>{let n=z.current;(n.mode!==he||n.locale!==e.locale||n.transport!==t)&&(z.current={mode:he,locale:e.locale,transport:t},I.current++,ve.current.cancel(),ae.current=null,N(!1),_e(ea(he,e.locale,(e,n)=>t.transcribe(e,n))))},[e.locale,he,t]),i(()=>()=>{I.current++,ge.cancel()},[ge]);let ye=r(e=>{let t=ae.current;if(t===null)return!1;let n=Math.round(performance.now()-t);return oa[e](`voiceStop`,{durationMs:n}),a.emit(`voiceStop`,{durationMs:n}),ae.current=null,!0},[a]),be=r(()=>{ae.current!==null&&(ge.stop(),N(!1),ye(`info`)&&n.play(`voiceStop`))},[ye,n,ge]),xe=r(()=>{I.current++,ge.cancel(),N(!1),ye(`info`)&&n.play(`voiceStop`)},[ye,n,ge]);i(()=>{(h||!m)&&xe()},[m,xe,h]),i(()=>{let e=F.current;if(!e)return;let t=e.getRootNode(),n=la(t)?t.activeElement:null;n&&e.closest(`.${J}-panel`)?.contains(n)||e.focus({preventScroll:!0})},[]),i(()=>{let e=F.current;if(!e)return;if(E.length===0){e.style.height=``;return}e.style.height=`auto`;let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--${J}-textarea-base-height`)),r=Number.parseFloat(t.borderTopWidth)+Number.parseFloat(t.borderBottomWidth),i=Math.min(e.scrollHeight+r,Number.parseFloat(t.maxHeight)),a=Number.parseFloat(t.fontSize)*.7;e.style.height=`${i<n+a?n:i}px`},[E]);let Se=s(O);Se.current=O,i(()=>()=>{Se.current.forEach(Wi);for(let e of M.current)e.attachments.forEach(Wi)},[]),i(()=>{if(w)return w.current={attachFromDrop:t=>{if(!R||!oe.current||P.current||se.current)return;let n=Ui(t,Se.current,e.attachments);n.accepted.length!==0&&(oa.info(`attach (drop)`,{count:n.accepted.length,totalBytes:sa(n.accepted)}),a.emit(`attach`,{count:n.accepted.length,totalBytes:sa(n.accepted)}),k(e=>[...e,...n.accepted]))},fill:e=>{if(!oe.current||P.current||se.current)return;me(e);let t=F.current;t&&(t.focus({preventScroll:!0}),requestAnimationFrame(()=>t.setSelectionRange(t.value.length,t.value.length)))},acceptQueuedMessage:pe},()=>{w.current&&(w.current=null)}},[w,R,h,e.attachments,pe,me]),i(()=>{let t=F.current;if(!t)return;let n=t.closest(`.${J}-panel`);if(!n)return;let r=n=>{if(!oe.current||P.current||se.current)return;let r=n.clipboardData;if(!r)return;let i=n.target?.closest?.(`input, textarea, [contenteditable]:not([contenteditable='false'])`);if(i&&i!==t)return;if(R){let t=Ui(r.items,Se.current,e.attachments);if(t.accepted.length>0){n.preventDefault(),oa.info(`attach (paste)`,{count:t.accepted.length,totalBytes:sa(t.accepted)}),a.emit(`attach`,{count:t.accepted.length,totalBytes:sa(t.accepted)}),k(e=>[...e,...t.accepted]);return}}if(i===t)return;let o=r.getData(`text/plain`);o&&(n.preventDefault(),me(e=>e+o),t.focus())};return n.addEventListener(`paste`,r),()=>n.removeEventListener(`paste`,r)},[R,e.attachments,me]);let Ce=async()=>{let e=E.trim();if(!e&&O.length===0||!m||le||P.current||h)return;xe(),P.current=!0,re(!0);let t=E,n=O;try{await S(e,n)&&(me(e=>e===t?``:e),k(e=>e===n?(n.forEach(Wi),Se.current=[],[]):e))}finally{P.current=!1,re(!1),requestAnimationFrame(()=>{let e=F.current;if(!e||e.disabled||!oe.current)return;let t=e.getRootNode(),n=la(t)?t.activeElement:null,r=n?.getAttribute(`data-testid`);if(!(n&&n!==e&&r!==q.composerSend&&r!==q.composerStop)){if(ua(t)){let e=t.host.ownerDocument;if(!e.hasFocus())return;let n=e.activeElement;if(n&&n!==t.host&&n!==e.body)return}e.focus({preventScroll:!0})}})}},we=()=>{let e=E.trim();if(!e&&O.length===0||!m||!de||P.current||h)return;xe();let t=O;fe(n=>[...n,{id:ct(),text:e,attachments:t}]),me(``),k(e=>e===t?(Se.current=[],[]):e),F.current?.focus({preventScroll:!0})};i(()=>{ue&&(ee.current=!1)},[ue]),i(()=>{let e=A[0];if(!e||!f||ue||ee.current||ne||h||!m)return;let t=setTimeout(()=>{ee.current=!0,S(e.text,e.attachments,e.id).then(t=>{if(t){pe(e.id);return}ee.current=!1})},300);return()=>clearTimeout(t)},[m,f,h,S,ue,A,pe,ne]);let Te=e=>{e.key!==`Enter`||e.shiftKey||e.isComposing||(e.preventDefault(),de&&(E.trim()||O.length>0)?we():le?C():Ce())},Ee=t=>{let n=t.target;if(!m||P.current||h){n.value=``;return}let r=Ui(n.files,O,e.attachments);r.accepted.length>0&&(oa.info(`attach (file picker)`,{count:r.accepted.length,totalBytes:sa(r.accepted)}),a.emit(`attach`,{count:r.accepted.length,totalBytes:sa(r.accepted)}),k(e=>[...e,...r.accepted])),n.value=``},De=e=>{!m||P.current||h||(oa.info(`removeAttachment`,{id:e}),a.emit(`removeAttachment`,{id:e}),k(t=>{let n=t.find(t=>t.id===e);return n&&Wi(n),t.filter(t=>t.id!==e)}))},Oe=()=>{if(te){be();return}if(!m||!ge.isSupported||P.current||h)return;let e=++I.current;ae.current=performance.now(),oa.info(`voiceStart`),a.emit(`voiceStart`,void 0),N(!0),n.play(`voiceStart`),ge.start((t,n)=>{I.current!==e||!oe.current||se.current||P.current||!n||me(e=>`${e}${t} `)},()=>{I.current!==e||!oe.current||(N(!1),ye(`debug`))})},ke=ca[e.composer.sendButton.icon],Ae=!!(E.trim()||O.length>0);return _(`div`,{class:`${J}-composer`,"data-testid":q.composer,children:[A.length>0?g(`div`,{class:`${J}-message-queue`,"aria-label":T.queueMessage,"data-testid":q.messageQueue,children:A.map(e=>_(`div`,{class:`${J}-attachment-chip ${J}-queued-message`,"data-testid":`${q.queuedMessage}-${e.id}`,children:[g(`span`,{class:`${J}-attachment-name ${J}-queued-text`,children:e.text||e.attachments.map(e=>e.name).join(`, `)}),g(`button`,{type:`button`,class:`${J}-attachment-remove`,onClick:()=>pe(e.id),"aria-label":T.removeQueuedMessage,title:T.removeQueuedMessage,"data-testid":`${q.queuedMessageRemove}-${e.id}`,children:g(Cr,{})})]},e.id))}):null,O.length>0?g(`div`,{class:`${J}-attachments`,children:O.map(e=>g(Qi,{attachment:e,onRemove:()=>De(e.id),disabled:ce},e.id))}):null,_(`div`,{class:`${J}-composer-row`,children:[_(`div`,{class:`${J}-composer-actions`,children:[R?g(`button`,{type:`button`,class:`${J}-icon-btn`,onClick:()=>ie.current?.click(),disabled:ce,"aria-label":T.attach,"data-testid":q.composerAttach,children:g(Ar,{})}):null,ge.isSupported?g(`button`,{type:`button`,class:`${J}-icon-btn`,onClick:Oe,disabled:ce,"aria-label":te?T.micStop:T.micStart,"aria-pressed":te,"data-recording":te?`true`:void 0,"data-testid":q.composerVoice,children:g(jr,{})}):null]}),g(`textarea`,{ref:F,name:`message`,class:`${J}-textarea`,rows:1,value:E,placeholder:T.composerPlaceholder,onInput:e=>me(e.currentTarget.value),onKeyDown:Te,disabled:ce,"aria-label":T.composerPlaceholder,"data-testid":q.composerInput}),de&&Ae?g(`button`,{type:`button`,class:`${J}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:we,disabled:ce,"aria-label":T.queueMessage,title:T.queueMessage,"data-testid":q.composerSend,children:g(ke,{})}):null,le?g(`button`,{type:`button`,class:`${J}-send`,onClick:C,disabled:ce,"aria-label":T.stop,"data-testid":q.composerStop,children:g(kr,{})}):null,!le&&(!de||!Ae)?g(`button`,{type:`button`,class:`${J}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:()=>void Ce(),disabled:ce||!E.trim()&&O.length===0,"aria-label":T.send,"data-testid":q.composerSend,children:g(ke,{})}):null,v&&b===`ai-agent`&&x?g(`button`,{type:`button`,class:`${J}-icon-btn`,onClick:x,disabled:ce||!y,"aria-label":T.talkToOperator,title:T.talkToOperator,"data-testid":q.operatorRequest,children:g(ti,{})}):null]}),g(`input`,{ref:ie,name:`attachments`,type:`file`,multiple:!0,accept:e.attachments.accept,onChange:Ee,disabled:ce,class:`${J}-sr-only`,"data-testid":q.composerFileInput})]})}const fa=b.cssPrefix;function pa({visible:e,strings:t}){return e?g(`div`,{class:`${fa}-dropzone`,role:`status`,"aria-live":`polite`,children:t.dropZone}):null}function ma({containerRef:e,onDrop:t,disabled:n=!1}){let[r,a]=c(!1);return i(()=>{if(n){a(!1);return}let r=e.current;if(!r)return;let i=0,o=e=>{i+=1,e.dataTransfer?.types.includes(`Files`)&&(e.preventDefault(),a(!0))},s=()=>{--i,!(i>0)&&(i=0,a(!1))},c=e=>{e.dataTransfer?.types.includes(`Files`)&&e.preventDefault()},l=e=>{i=0,a(!1),e.dataTransfer&&(e.preventDefault(),t(e.dataTransfer.items))};return r.addEventListener(`dragenter`,o),r.addEventListener(`dragleave`,s),r.addEventListener(`dragover`,c),r.addEventListener(`drop`,l),()=>{r.removeEventListener(`dragenter`,o),r.removeEventListener(`dragleave`,s),r.removeEventListener(`dragover`,c),r.removeEventListener(`drop`,l)}},[e,n,t]),{visible:!n&&r}}function ha({itemCount:e,initialFocusIndex:t}){let[n,a]=c(!1),o=s(null),l=s(null),[u,d]=c(-1),f=r(()=>{a(!1),d(-1),o.current?.focus()},[]),p=r(()=>a(e=>!e),[]);return i(()=>{if(!n)return;let e=e=>{let t=l.current,n=o.current;if(!t||!n)return;let r=e.composedPath();r.includes(t)||r.includes(n)||(a(!1),d(-1))};return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[n]),i(()=>{if(!n||e===0)return;let r=t?.()??0;d(r<0||r>=e?0:r)},[n,e,t]),i(()=>{!n||u<0||(l.current?.querySelectorAll(`[role='menuitem']`))?.[u]?.focus()},[n,u]),{open:n,focusIndex:u,triggerRef:o,menuRef:l,toggle:p,close:f,onTriggerKey:r(e=>{(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a(!0))},[]),onMenuKey:r(t=>{if(e!==0)switch(t.key){case`Escape`:t.preventDefault(),f();return;case`ArrowDown`:t.preventDefault(),d(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),d(t=>(t-1+e)%e);return;case`Home`:t.preventDefault(),d(0);return;case`End`:t.preventDefault(),d(e-1)}},[e,f])}}function ga({items:e,triggerLabel:t}){let n=b.cssPrefix,r=ha({itemCount:e.length}),i=e=>{e.disabled||(e.onSelect?.(),e.keepOpen||r.close())},a=(e,t)=>e.onSelectValue?.(t),o=(e,t)=>{let n=t.segments;if(!n?.length)return;let r=Math.max(0,n.findIndex(e=>e.value===t.value)),i=-1;if(e.key===`ArrowRight`||e.key===`Enter`||e.key===` `)i=(r+1)%n.length;else if(e.key===`ArrowLeft`)i=(r-1+n.length)%n.length;else return;e.preventDefault(),e.stopPropagation(),a(t,n[i].value)};return _(`div`,{class:`${n}-menu-wrap`,children:[g(`button`,{ref:r.triggerRef,type:`button`,class:`${n}-icon-btn`,"aria-label":t,"aria-haspopup":`menu`,"aria-expanded":r.open,title:t,onClick:r.toggle,onKeyDown:r.onTriggerKey,children:g(Rr,{})}),r.open?g(`div`,{ref:r.menuRef,class:`${n}-menu`,role:`menu`,"aria-label":t,onKeyDown:r.onMenuKey,tabIndex:-1,children:e.map(e=>e.segments?_(`div`,{role:`menuitem`,class:`${n}-menu-item ${n}-menu-item-segmented`,"aria-label":e.label,tabIndex:-1,onKeyDown:t=>o(t,e),children:[e.icon?g(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,g(`span`,{class:`${n}-menu-label`,children:e.label}),g(`span`,{class:`${n}-segmented`,role:`group`,"aria-label":e.label,children:e.segments.map(t=>{let r=t.value===e.value;return g(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":r,class:`${n}-segment`,"data-on":r?`true`:void 0,lang:t.lang,title:t.value,tabIndex:-1,"data-testid":`${q.langSegment}-${t.value}`,onClick:()=>a(e,t.value),children:t.label},t.value)})})]},e.id):_(`button`,{type:`button`,role:`menuitem`,class:`${n}-menu-item`,"aria-pressed":e.type===`switch`?e.on:void 0,disabled:e.disabled,onClick:()=>i(e),children:[e.icon?g(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,g(`span`,{class:`${n}-menu-label`,children:e.label}),e.type===`switch`&&e.on?g(`span`,{class:`${n}-menu-check`,"aria-hidden":`true`,children:g(Ur,{})}):null]},e.id))}):null]})}const _a=b.cssPrefix;function va(e){let t=typeof matchMedia!=`function`||matchMedia(`(prefers-color-scheme: dark)`).matches;return e===`auto`?t?`light`:`dark`:t?e===`light`?`dark`:`auto`:e===`dark`?`light`:`auto`}const ya={normal:`large`,large:`small`,small:`normal`};function ba(e){return g(e===`light`?ci:e===`dark`?li:ui,{})}function xa(e){return(e.split(`-`)[0]??e).toUpperCase()}function Sa(e,t){let n;try{n=new URL(e,window.location.href)}catch{return}if(n.protocol===`http:`||n.protocol===`https:`)return t.conversationId&&n.searchParams.set(`chat`,t.conversationId),n.searchParams.set(`widgetId`,t.widgetId),t.publicKey&&n.searchParams.set(`public_key`,t.publicKey),n.searchParams.set(`ai_agent_deployment_id`,t.aiAgentDeploymentId),n.href}function Ca({panelProps:e,variant:t}){let{options:n,panelSize:r,feedback:i,onClose:a,onClear:o,onExpand:s,onFullscreen:c,onSoundToggle:l}=e,{onToggleHistory:u,onLocaleChange:d,onThemeChange:f,onTextSizeChange:m}=e,h=n.strings,v=n.mode,y=t===`chat`,b=p(()=>i.mutedSig.value).value,x=new Set(n.actions),S=e=>x.has(e),C=typeof matchMedia==`function`&&matchMedia(`(max-width: 640px)`).matches,w=e=>!C&&Fi(e,v,r),T=n.themeMode,E={auto:h.themeAuto,light:h.themeLight,dark:h.themeDark},D=n.textSize,O={small:h.textSizeSmall,normal:h.textSizeNormal,large:h.textSizeLarge},k=[];if(y&&S(`clear`)&&k.push({id:`clear`,icon:g(qr,{}),label:h.newConversation,onSelect:o}),S(`expand`)&&w(`expand`)){let e=r===`expanded`;k.push({id:`expand`,icon:g(e?Nr:Mr,{}),label:e?h.collapse:h.expand,type:`switch`,on:e,onSelect:s})}if(S(`fullscreen`)&&w(`fullscreen`)){let e=r===`fullscreen`;k.push({id:`fullscreen`,icon:g(e?Fr:Pr,{}),label:e?h.exitFullscreen:h.fullscreen,type:`switch`,on:e,onSelect:c})}let A=n.popOutUrl,j=n.aiAgentDeploymentId;S(`popOut`)&&A&&j&&Fi(`popOut`,v,r)&&k.push({id:`popOut`,icon:g(Ir,{}),label:h.popOut,onSelect:()=>{let t=Sa(A,{conversationId:e.conversationId,widgetId:n.widgetId,publicKey:n.publicKey,aiAgentDeploymentId:j});t&&window.open(t,`_blank`,`noopener,noreferrer`)}}),y&&S(`sound`)&&k.push({id:`sound`,icon:g(b?Br:zr,{}),label:b?h.soundOff:h.soundOn,type:`switch`,on:!b,onSelect:l}),S(`theme`)&&k.push({id:`theme`,icon:ba(T),label:`${h.theme}: ${E[T]}`,onSelect:()=>f(va(T)),keepOpen:!0}),S(`textSize`)&&k.push({id:`textSize`,icon:g(Vr,{}),label:`${h.textSize}: ${O[D]}`,onSelect:()=>m(ya[D]),keepOpen:!0}),S(`language`)&&n.availableLocales.length>1&&k.push({id:`language`,icon:g(Gr,{}),label:h.language,segments:n.availableLocales.map(e=>({value:e,label:xa(e),lang:e})),value:n.locale,onSelectValue:d});let M=!!a&&Ii(v,r,n.actions),ee=y&&S(`history`);return _(`div`,{class:`${_a}-header-actions`,children:[ee?g(`button`,{type:`button`,class:`${_a}-icon-btn`,onClick:u,"aria-label":h.history,title:h.history,"data-testid":q.actionHistory,children:g(Wr,{})}):null,k.length>0?g(ga,{items:k,triggerLabel:h.moreActions}):null,M?g(`button`,{type:`button`,class:`${_a}-icon-btn`,onClick:a,"aria-label":h.close,title:h.close,"data-testid":q.actionClose,children:g(Cr,{})}):null]})}const wa=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ta=/^https?:\/\/[^\s.]+\.[^\s]+$/i,Ea=/^[+]?[\d\s().-]{6,}$/;function Da(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>String(t[n]??`{${n}}`))}function Oa(e){return Array.isArray(e)?e.length:+!!e?.trim()}function ka(e,t,n){let r=e.required??!0,i=e.validation;if(e.type===`multiselect`){let e=Oa(t);return r&&e===0?n.formRequired:e===0?void 0:i?.minSelections!=null&&e<i.minSelections?Da(n.formChooseAtLeast,{min:i.minSelections}):i?.maxSelections!=null&&e>i.maxSelections?Da(n.formChooseAtMost,{max:i.maxSelections}):void 0}let a=typeof t==`string`?t.trim():``;if(!a)return r?n.formRequired:void 0;switch(e.type){case`email`:if(!wa.test(a))return n.formInvalidEmail;break;case`url`:if(!Ta.test(a))return n.formInvalidUrl;break;case`tel`:if(!Ea.test(a))return n.formInvalidTel;break;case`number`:{let e=Number(a);if(!Number.isFinite(e))return n.formInvalidNumber;if(i?.min!=null&&e<i.min)return Da(n.formNumberTooSmall,{min:i.min});if(i?.max!=null&&e>i.max)return Da(n.formNumberTooLarge,{max:i.max});break}default:break}if(i?.minLength!=null&&a.length<i.minLength)return Da(n.formTooShort,{min:i.minLength});if(i?.maxLength!=null&&a.length>i.maxLength)return Da(n.formTooLong,{max:i.maxLength});if(i?.pattern)try{if(!new RegExp(i.pattern).test(a))return n.formPatternMismatch}catch{}}function Aa(e,t,n){let r={};for(let i of e){let e=ka(i,t[i.name],n);e&&(r[i.name]=e)}return r}function ja(e){let t={};for(let[n,r]of Object.entries(e)){let e=Array.isArray(r)?r.join(`, `):r;e.trim()&&(t[n]=e.trim())}return t}const Y=b.cssPrefix,Ma=`__other__`;function Na({fields:e,strings:t,submitLabel:n,onSubmit:r,skipLabel:i,onSkip:a,footerHint:o,submitOnEnter:s,disabled:l,initialValues:u,hideActions:d,fieldTypeLabels:f,rootTestId:p,submitTestId:m,skipTestId:h}){let[v,y]=c(()=>({...La(e),...u})),[b,x]=c({}),[S,C]=c({}),w=e=>{S[e]&&C(t=>({...t,[e]:``}))},T=(e,t)=>{y(n=>({...n,[e]:t})),w(e)},E=(e,t)=>{x(n=>({...n,[e]:t})),w(e)},D=n=>{if(n.preventDefault(),l)return;let i=Ra(e,v,b),a=Aa(e,i,t);if(Object.keys(a).length>0){C(a);return}r(ja(i))};return _(`form`,{class:`${Y}-form`,onSubmit:D,onKeyDown:e=>{!s||e.key!==`Enter`||e.shiftKey||e.isComposing||e.target?.tagName===`TEXTAREA`&&D(e)},"data-testid":p,noValidate:!0,children:[e.map(e=>g(Pa,{field:e,value:v[e.name],otherText:b[e.name]??``,error:S[e.name],disabled:l,typeLabel:f?.[e.name],strings:t,onChange:t=>T(e.name,t),onOtherChange:t=>E(e.name,t)},e.name)),d?null:_(`div`,{class:`${Y}-form-actions`,children:[o?g(`span`,{class:`${Y}-form-hint`,children:o}):null,i&&a?g(`button`,{type:`button`,class:`${Y}-form-skip`,onClick:a,disabled:l,"data-testid":h,children:i}):null,g(`button`,{type:`submit`,class:`${Y}-form-submit`,disabled:l,"data-testid":m,children:n})]})]})}function Pa({field:e,value:t,otherText:n,error:r,disabled:i,typeLabel:a,strings:o,onChange:s,onOtherChange:c}){let l=Fa({field:e,value:t,otherText:n,disabled:i,strings:o,onChange:s,onOtherChange:c,fieldTid:Ci(q.formField,e.name)});return _(`label`,{class:`${Y}-field`,"data-field":e.name,"data-invalid":r?`true`:void 0,children:[_(`span`,{class:`${Y}-field-head`,children:[_(`span`,{class:`${Y}-field-label`,children:[e.label,e.required??!0?g(`span`,{class:`${Y}-field-req`,"aria-hidden":`true`,children:` *`}):null]}),a?g(`span`,{class:`${Y}-field-type`,children:a}):null]}),l,e.validationHint&&!r?g(`span`,{class:`${Y}-field-hint`,children:e.validationHint}):null,r?g(`span`,{class:`${Y}-field-error`,role:`alert`,children:r}):null]})}function Fa(e){let{field:t,value:n,otherText:r,disabled:i,strings:a,onChange:o,onOtherChange:s,fieldTid:c}=e,l=typeof n==`string`?n:``;switch(t.type){case`textarea`:return g(`textarea`,{class:`${Y}-field-input`,rows:3,value:l,placeholder:t.placeholder,disabled:i,onInput:e=>o(e.target.value),"data-testid":c});case`select`:return _(`select`,{class:`${Y}-field-input`,value:l,disabled:i,onChange:e=>o(e.target.value),"data-testid":c,children:[g(`option`,{value:``,children:t.placeholder??`—`}),(t.options??[]).map(e=>g(`option`,{value:e.value,children:e.label??e.value},e.value))]});case`radio`:{let e=t.allowOther&&l===Ma;return _(`div`,{class:`${Y}-field-choices`,role:`radiogroup`,"data-testid":c,children:[(t.options??[]).map(e=>_(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`radio`,name:`${Y}-${t.name}`,checked:l===e.value,disabled:i,onChange:()=>o(e.value)}),g(`span`,{children:e.label??e.value})]},e.value)),t.allowOther?_(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`radio`,name:`${Y}-${t.name}`,checked:l===Ma,disabled:i,onChange:()=>o(Ma)}),g(`span`,{children:a.formOther})]}):null,e?g(`input`,{class:`${Y}-field-input`,value:r,placeholder:t.placeholder??a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.target.value)}):null]})}case`checkbox`:return _(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`checkbox`,checked:l===`true`,disabled:i,onChange:e=>o(e.target.checked?`true`:``),"data-testid":c}),g(`span`,{children:t.placeholder??t.label})]});case`multiselect`:{let e=Array.isArray(n)?n:[],l=(t,n)=>o(n?[...e,t]:e.filter(e=>e!==t));return _(`div`,{class:`${Y}-field-choices`,"data-testid":c,children:[(t.options??[]).map(t=>_(`label`,{class:`${Y}-choice`,children:[g(`input`,{type:`checkbox`,checked:e.includes(t.value),disabled:i,onChange:e=>l(t.value,e.target.checked)}),g(`span`,{children:t.label??t.value})]},t.value)),t.allowOther||(t.options??[]).length===0?g(`textarea`,{class:`${Y}-field-input`,rows:2,value:r,placeholder:t.placeholder??a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.target.value)}):null]})}default:return g(`input`,{class:`${Y}-field-input`,type:Ia(t.type),value:l,placeholder:t.placeholder,disabled:i,onInput:e=>o(e.target.value),"data-testid":c})}}function Ia(e){switch(e){case`number`:case`email`:case`tel`:case`url`:case`date`:case`time`:return e;default:return`text`}}function La(e){let t={};for(let n of e)n.defaultValue!=null&&(t[n.name]=n.type===`multiselect`?n.defaultValue.split(`,`).map(e=>e.trim()).filter(Boolean):n.defaultValue);return t}function Ra(e,t,n){let r={...t};for(let i of e){let e=n[i.name]?.trim();if(i.type===`radio`&&i.allowOther&&t[i.name]===Ma)r[i.name]=e??``;else if(i.type===`multiselect`&&e){let n=e.split(/[,\n;]+/).map(e=>e.trim()).filter(Boolean),a=Array.isArray(t[i.name])?t[i.name]:[];r[i.name]=[...a,...n]}}return r}const za=b.cssPrefix;function Ba({form:e,strings:t,onSubmit:n,onSkip:r}){return _(`div`,{class:`${za}-form-gate`,"data-testid":q.formGate,children:[e.title?g(`h3`,{class:`${za}-form-gate-title`,children:e.title}):null,e.description?g(`p`,{class:`${za}-form-gate-desc`,children:e.description}):null,g(Na,{fields:e.fields,strings:t,submitLabel:e.submitLabel??t.formSubmit,onSubmit:n,skipLabel:e.skippable?t.formSkip:void 0,onSkip:e.skippable?r:void 0,submitTestId:q.formSubmit,skipTestId:q.formSkip})]})}function Va({marker:e,strings:t,onFill:n}){let r=e.outcome===`skipped`,i=r?t.formSkipped:t.formSubmitted,a=e.title?_(h,{children:[g(`span`,{children:e.title}),g(`span`,{class:`${za}-sr-only`,children:i})]}):g(`span`,{children:i}),o=e.form?.reviewable??!1,s=!r&&o&&e.values&&Object.keys(e.values).length>0?e.values:null;if(s){let t=t=>e.form?.fields.find(e=>e.name===t)?.label??t;return _(`details`,{class:`${za}-form-done`,"data-outcome":e.outcome,"data-testid":q.formDone,children:[_(`summary`,{class:`${za}-form-done-summary`,"data-testid":q.formDoneToggle,children:[g(Ur,{}),a,g(Or,{})]}),g(`dl`,{class:`${za}-form-answers`,"data-testid":q.formAnswers,children:Object.entries(s).map(([e,n])=>_(`div`,{class:`${za}-form-answer`,children:[g(`dt`,{children:t(e)}),g(`dd`,{children:n})]},e))})]})}return _(`div`,{class:`${za}-form-done`,"data-outcome":e.outcome,"data-testid":q.formDone,role:`status`,children:[g(r?Hr:Ur,{}),a,r&&e.form?.reopenable&&n?g(`button`,{type:`button`,class:`${za}-form-done-fill`,"data-testid":q.formFill,onClick:n,children:t.formFillOut}):null]})}function Ha(e){return e?(e.startsWith(`tool:`)?e.slice(5):e)===`ask-user-questions`:!1}const Ua=b.cssPrefix;function Wa(e){return e.startsWith(`tool:`)||e.startsWith(`tool-`)?e.slice(5):e}function Ga(e,t){let n=e===`output-available`||e===`output-error`||e===`output-denied`,r=e===`approval-responded`||t?.approved!==void 0;return{terminal:n,responded:r,decided:n||r}}function Ka({status:e,icon:t,label:n}){return _(`span`,{class:`${Ua}-toolui-badge ${Ua}-toolui-status`,"data-status":e,children:[g(`span`,{class:`${Ua}-toolui-status-icon`,children:t}),n]})}function qa(e,t){return e===`output-error`?`error`:e===`output-denied`||t?.approved===!1?`denied`:e===`output-available`?`completed`:e===`approval-responded`||t?.approved===!0?`responded`:e===`approval-requested`?`awaiting`:`running`}function Ja(e,t,n={}){return n.submitted?`responded`:Za(qa(e,t),n.superseded,n.live??!0)}function Ya({status:e}){return g(e===`denied`||e===`error`||e===`superseded`?xi:e===`completed`||e===`responded`?bi:yi,{})}function Xa(e,t){switch(e){case`awaiting`:return t.statusAwaiting;case`responded`:return t.statusResponded;case`completed`:return t.statusCompleted;case`denied`:return t.statusDenied;case`error`:return t.statusError;case`superseded`:return t.statusSuperseded;default:return t.statusRunning}}function Za(e,t,n){return t&&(e===`awaiting`||e===`running`)?`superseded`:!n&&e===`running`?`error`:e}function Qa({state:e,approval:t,strings:n,superseded:r,live:i=!0,submitted:a=!1}){let o=Ja(e,t,{superseded:r,live:i,submitted:a});return g(Ka,{status:o,icon:g(Ya,{status:o}),label:Xa(o,n)})}function $a({name:e,state:t,approval:n,strings:r,superseded:i,live:a,submitted:o}){return _(h,{children:[_(`span`,{class:`${Ua}-toolui-name-pill`,children:[g(vi,{}),g(`span`,{class:`${Ua}-toolui-name-text`,children:e})]}),g(Qa,{state:t,approval:n,strings:r,superseded:i,live:a,submitted:o}),g(`span`,{class:`${Ua}-toolui-chevron`,children:g(Jr,{})})]})}function eo({part:e,strings:t,testid:n,superseded:r,live:i,submitted:a}){let s=o(()=>u(()=>e.inputSig.value),[e]),c=o(()=>u(()=>e.outputSig.value),[e]),l=o(()=>u(()=>e.errorSig.value),[e]),d=o(()=>u(()=>e.stateSig.value),[e]),f=o(()=>u(()=>e.approvalSig.value),[e]);return _(`details`,{class:`${Ua}-toolui ${Ua}-toolui-collapsible`,"data-testid":n,children:[g(`summary`,{class:`${Ua}-toolui-head`,children:g($a,{name:Wa(e.toolName),state:d.value,approval:f.value,strings:t,superseded:r,live:i,submitted:a})}),g(to,{label:t.toolParameters,value:s.value}),c.value===void 0?null:g(to,{label:t.toolResult,value:c.value}),l.value?g(to,{label:t.statusError,value:l.value,error:!0}):null]})}function to({label:e,value:t,error:n}){let r=n?typeof t==`string`?t:``:ro(no(t));return r?_(`div`,{class:`${Ua}-toolui-section`,children:[g(`span`,{class:`${Ua}-toolui-label`,children:e}),g(`pre`,{class:`${Ua}-toolui-code`,"data-error":n?`true`:void 0,children:r})]}):null}function no(e){if(e&&typeof e==`object`){let t=e;if(t.storage===`tool-result-ref`&&`summary`in t)return t.summary}return e}function ro(e){if(e==null)return``;try{let t=typeof e==`string`?e:JSON.stringify(e,null,2);return!t||t===`{}`||t===`[]`||t===`""`?``:t.length>800?`${t.slice(0,800)}…`:t}catch{return``}}function io(e){return e.partsSig.value.some(e=>e.kind===`text`&&e.textSig.value.length>0)}function ao(e){return e.partsSig.value.some(e=>e.kind===`reasoning`)}function oo(e){return e.streaming&&!e.bufferedHold&&!(e.reasoningVisible&&e.working)}function so(e){let{streaming:t,reasoningVisible:n,emptyReply:r,hidden:i}=e,a=e.responseMode===`buffered`&&t,o=t&&!e.hasAnswerText;return{streaming:t,bufferedHold:a,reasoningVisible:n,working:o,showStreamDots:oo({streaming:t,bufferedHold:a,reasoningVisible:n,working:o}),emptyReply:r,hidden:i}}function co(e,t){let n=e.stateSig.value,r=e.approvalSig.value,{terminal:i,responded:a,decided:o}=Ga(n,r),s=t.continuationStreaming===!0&&!o,c=t.superseded&&!o&&!s;return{pill:Ja(n,r,{superseded:c,live:t.live,submitted:s}),state:n,terminal:i,decided:o||s,showApproveReject:!o&&!t.superseded&&!s,showAnswered:a&&!i&&!c,showSubmitted:s,showEdit:a&&t.active&&!i,skipped:c,answeredApproved:r?.approved}}function lo({textSig:e,doneSig:t}){let n=s(null);return a(()=>{let r=n.current;if(!r)return;r.classList.add(`${b.cssPrefix}-md`),r.replaceChildren();let i=y.default_renderer(r),a=y.parser(i),o=0,s=d(()=>{let n=e.value,s=t.value;n.length<o&&(r.replaceChildren(),i=y.default_renderer(r),a=y.parser(i),o=0);let c=n.slice(o);c&&y.parser_write(a,c),o=n.length,s&&y.parser_end(a)}),c=new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes){if(!(e instanceof HTMLElement))continue;let t=e.matches?.(`a`)?[e]:[...e.querySelectorAll?.(`a`)??[]];for(let e of t)fo(e)}});c.observe(r,{childList:!0,subtree:!0});for(let e of r.querySelectorAll(`a`))fo(e);let l=e=>{let t=e.target?.closest?.(`a`);if(!t||!(t instanceof HTMLAnchorElement))return;let n=t.getAttribute(`href`)??``;!n||n.startsWith(`#`)||(e.preventDefault(),window.open(n,`_blank`,`noopener,noreferrer`))};return r.addEventListener(`click`,l),()=>{s(),c.disconnect(),r.removeEventListener(`click`,l)}},[e,t]),g(`div`,{ref:n})}function uo({text:e}){return g(lo,{textSig:o(()=>f(e),[e]),doneSig:o(()=>f(!0),[])})}function fo(e){let t=e.getAttribute(`href`)??``;if(!t||t.startsWith(`#`))return;e.target!==`_blank`&&(e.target=`_blank`);let n=new Set((e.rel||``).split(/\s+/).filter(Boolean));n.add(`noopener`),n.add(`noreferrer`),e.rel=[...n].join(` `)}const po=b.cssPrefix;function mo({messageId:e,initial:t,strings:n,onFeedback:r}){let[a,o]=c(t);i(()=>o(t),[e,t]);let s=t=>{let n=a===t?null:t;o(n),r(e,n)};return _(`div`,{class:`${po}-feedback`,role:`group`,"data-testid":q.messageFeedback,children:[g(`button`,{type:`button`,class:`${po}-msg-action`,"data-active":a===`up`?`true`:void 0,"aria-pressed":a===`up`,"aria-label":n.feedbackUp,title:n.feedbackUp,onClick:()=>s(`up`),"data-testid":q.feedbackUp,children:g(gi,{})}),g(`button`,{type:`button`,class:`${po}-msg-action`,"data-active":a===`down`?`true`:void 0,"aria-pressed":a===`down`,"aria-label":n.feedbackDown,title:n.feedbackDown,onClick:()=>s(`down`),"data-testid":q.feedbackDown,children:g(_i,{})}),g(`span`,{class:`${po}-sr-only`,role:`status`,"aria-live":`polite`,children:a?n.feedbackThanks:``})]})}const ho=b.cssPrefix;function go({part:e,strings:t}){let n=e.title||e.filename||e.url||t.sources;return e.url?_(`a`,{class:`${ho}-source`,href:e.url,target:`_blank`,rel:`noreferrer noopener`,"data-testid":q.source,children:[g(`span`,{class:`${ho}-source-icon`,"aria-hidden":`true`,children:`🔗`}),g(`span`,{class:`${ho}-source-label`,children:n})]}):_(`span`,{class:`${ho}-source`,"data-testid":q.source,children:[g(`span`,{class:`${ho}-source-icon`,"aria-hidden":`true`,children:`📄`}),g(`span`,{class:`${ho}-source-label`,children:n})]})}const _o=b.cssPrefix;function vo({part:e,strings:t,active:n,superseded:r=!1,continuationStreaming:i=!1,onDecision:a,onEdit:s}){let c=o(()=>u(()=>e.approvalSig.value),[e]),l=o(()=>u(()=>co(e,{active:n,superseded:r,continuationStreaming:i})),[e,n,r,i]).value,{terminal:d,showApproveReject:f,showAnswered:p,showSubmitted:m,showEdit:v,skipped:y}=l,b=Wa(e.toolName),x=l.answeredApproved,S=e.toolCallId,C=_(h,{children:[g(`p`,{class:`${_o}-toolui-prompt`,children:t.approvalPrompt.replace(`{tool}`,b)}),g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalBody})]});m?C=g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalSubmitting}):p&&x!==!1?C=_(h,{children:[_(`p`,{class:`${_o}-toolui-prompt`,children:[t.approvalYourResponse.replace(`{decision}`,x?t.approve:t.reject),c.value?.reason?` — ${c.value.reason}`:``]}),v?g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalEditHint}):null,v?null:g(`p`,{class:`${_o}-toolui-subtle`,children:t.approvalSubmitting})]}):p&&(C=g(h,{}));let w=f||m||v||p&&x!==!1;return _(`div`,{class:`${_o}-toolui-group`,"data-testid":l.decided?q.toolDecision:q.toolApproval,children:[g(eo,{part:e,strings:t,superseded:y,submitted:m}),y||d||!w?null:_(`div`,{class:`${_o}-toolui ${_o}-toolui-body`,children:[C,f?_(`div`,{class:`${_o}-toolui-actions`,children:[g(`button`,{type:`button`,class:`${_o}-form-skip`,disabled:!n,onClick:()=>a(S,!1),"data-testid":q.toolReject,children:t.reject}),g(`button`,{type:`button`,class:`${_o}-form-submit`,disabled:!n,onClick:()=>a(S,!0),"data-testid":q.toolApprove,children:t.approve})]}):null,v?g(`div`,{class:`${_o}-toolui-actions`,children:g(`button`,{type:`button`,class:`${_o}-form-skip`,onClick:()=>s(S),"data-testid":q.toolEdit,children:t.edit})}):null]})]})}const yo=new Set([`text`,`email`,`phone`,`number`,`date`,`single-select`,`multi-select`,`boolean`]);function bo(e){let t=e&&typeof e==`object`?e:{},n=(Array.isArray(t.questions)?t.questions:[]).map(xo).filter(e=>e!==null);return{intro:wo(t.intro),questions:n}}function xo(e,t){if(!e||typeof e!=`object`)return null;let n=e,r=yo.has(n.type)?n.type:`text`;return{key:wo(n.key)??`q${t+1}`,question:wo(n.question)??`Please provide the missing information.`,type:r,options:Array.isArray(n.options)?n.options.filter(e=>typeof e==`string`&&e.trim().length>0):void 0,required:typeof n.required==`boolean`?n.required:void 0,helpText:wo(n.helpText)}}function So(e){switch(e){case`text`:return`textarea`;case`phone`:return`tel`;case`single-select`:case`boolean`:return`radio`;case`multi-select`:return`multiselect`;default:return e}}function Co(e,t,n){return e.questions.map(e=>{let r=So(e.type),i=e.type===`boolean`?[{value:`yes`,label:t},{value:`no`,label:n}]:(e.options??[]).map(e=>({value:e,label:e}));return{name:e.key,label:e.question,type:r,required:e.required??!1,options:i.length>0?i:void 0,validationHint:e.helpText}})}function wo(e){return typeof e==`string`&&e.trim()?e.trim():void 0}const X=b.cssPrefix;function To({skipped:e,submitted:t,strings:n}){return e?{status:`superseded`,statusLabel:n.inputSkipped}:t?{status:`responded`,statusLabel:n.statusResponded}:{status:`completed`,statusLabel:n.inputAnswered}}const Eo={text:`qtypeText`,email:`qtypeEmail`,phone:`qtypePhone`,number:`qtypeNumber`,date:`qtypeDate`,"single-select":`qtypeChooseOne`,"multi-select":`qtypeChooseAny`,boolean:`qtypeBoolean`};function Do(e,t){let n={};for(let r of e)n[r.key]=t[Eo[r.type]];return n}function Oo({part:e,strings:t,active:n,superseded:r=!1,continuationStreaming:i=!1,onDecision:a,onEdit:s}){let l=o(()=>u(()=>e.stateSig.value),[e]).value,d=o(()=>u(()=>e.approvalSig.value),[e]).value,f=o(()=>u(()=>bo(e.inputSig.value)),[e]).value,{terminal:p,decided:m}=Ga(l,d),h=m&&d?.approved===!0,v=i&&!m,y=!m&&!r&&!v,b=!y&&!h&&!v,x=h&&n&&!p,S=f.questions,[C,w]=c(null),T=C??(y||h||v),[E,D]=c(!1),O=S.length>1?Sr:Qr,k=y?t.inputRequired:t.inputBadge,A=v?g(`p`,{class:`${X}-toolui-subtle`,children:t.approvalSubmitting}):y?g(ko,{req:f,strings:t,active:n,resolve:(t,n)=>a(e.toolCallId,n,t)}):E?g(Na,{fields:Co(f,t.confirmYes,t.confirmNo),strings:t,submitLabel:t.inputSubmit,onSubmit:()=>{},disabled:!0,hideActions:!0,fieldTypeLabels:Do(S,t),initialValues:h?Fo(S,d?.reason):void 0}):g(Ao,{questions:S,answers:h?Po(d?.reason):{},strings:t}),{status:j,statusLabel:M}=To({skipped:b,submitted:v,strings:t});return _(`details`,{class:`${X}-toolui ${X}-toolui-collapsible${r?` ${X}-toolui-stale`:``}`,open:T,onToggle:e=>{let t=e.currentTarget.open;t!==T&&w(t)},"data-testid":y?q.toolAskQuestions:q.toolDecision,children:[_(`summary`,{class:`${X}-toolui-head`,children:[_(`span`,{class:`${X}-toolui-q-pill`,children:[g(O,{}),k]}),_(`span`,{class:`${X}-toolui-head-end`,children:[y?null:g(Ka,{status:j,icon:g(b?xi:bi,{}),label:M}),g(`span`,{class:`${X}-toolui-chevron`,children:g(Jr,{})})]})]}),_(`div`,{class:`${X}-toolui-collapse-body`,children:[f.intro?g(`div`,{class:`${X}-toolui-desc`,children:f.intro}):null,A,y||v?null:_(`div`,{class:`${X}-toolui-footer`,children:[_(`button`,{type:`button`,class:`${X}-toolui-options-toggle`,onClick:()=>D(e=>!e),"data-testid":q.toolAskOptions,children:[g(`span`,{class:`${X}-toolui-options-chevron${E?` ${X}-open`:``}`,children:g(Jr,{})}),E?t.hideOptions:t.showOptions]}),x?g(`button`,{type:`button`,class:`${X}-form-skip`,onClick:()=>s(e.toolCallId),"data-testid":q.toolEdit,children:t.edit}):null]})]})]})}function ko({req:e,strings:t,active:n,resolve:r}){let i=Co(e,t.confirmYes,t.confirmNo),a=e.questions.length===1&&e.questions[0]?.type===`text`;return g(Na,{fields:i,strings:t,disabled:!n,submitLabel:t.inputSubmit,footerHint:a?t.inputSubmitHint:void 0,onSubmit:t=>r(Mo(e.questions,t),!0),skipLabel:t.inputSkip,onSkip:()=>r(void 0,!1),submitOnEnter:a,fieldTypeLabels:Do(e.questions,t),submitTestId:q.toolInputSubmit,skipTestId:q.toolInputSkip})}function Ao({questions:e,answers:t,strings:n}){return g(`div`,{class:`${X}-toolui-summary`,"data-testid":q.toolAskSummary,children:e.map(e=>_(`div`,{class:`${X}-field`,children:[g(`span`,{class:`${X}-field-head`,children:_(`span`,{class:`${X}-field-label`,children:[e.question,e.required?g(`span`,{class:`${X}-field-req`,"aria-hidden":`true`,children:` *`}):null]})}),g(`p`,{class:`${X}-toolui-answer`,children:jo(e,t[e.key],n)||`—`})]},e.key))})}function jo(e,t,n){return e.type===`boolean`?t===`yes`?n.confirmYes:t===`no`?n.confirmNo:t??``:t??``}function Mo(e,t){let n=e.flatMap(e=>{let n=t[e.key];if(n==null||n.trim()===``)return[];let r=e.type===`multi-select`?n.split(`,`).map(e=>e.trim()).filter(Boolean):n;return[{key:e.key,value:r}]});return JSON.stringify({answers:n})}function No(e){if(!e)return{};let t=(()=>{try{return JSON.parse(e)}catch{return}})()?.answers;if(!Array.isArray(t))return{};let n={};for(let e of t)if(e&&typeof e==`object`&&`key`in e){let{key:t,value:r}=e;if(typeof t!=`string`)continue;typeof r==`string`?n[t]=r:Array.isArray(r)&&(n[t]=r.filter(e=>typeof e==`string`))}return n}function Po(e){let t=No(e),n={};for(let[e,r]of Object.entries(t))n[e]=Array.isArray(r)?r.join(`, `):r;return n}function Fo(e,t){let n=No(t),r={};for(let t of e){let e=n[t.key];e!==void 0&&(t.type===`multi-select`?r[t.key]=Array.isArray(e)?e:[e]:r[t.key]=Array.isArray(e)?e[0]??``:e)}return r}function Io({part:e,strings:t,live:n}){let r=o(()=>u(()=>e.inputSig.value),[e]),i=o(()=>u(()=>e.outputSig.value),[e]),a=o(()=>u(()=>e.errorSig.value),[e]);return o(()=>u(()=>!!ro(r.value)||!!a.value||!!ro(no(i.value))),[r,i,a]).value?g(eo,{part:e,strings:t,testid:q.toolCall,live:n}):null}const Lo=b.cssPrefix,Ro=v(zo);function zo({message:e,status:t,strings:n,responseMode:r,showReasoning:i,showToolCalls:a,showSources:s,interactive:c=!1,superseded:l=!1,tool:d,onRetry:f,enableMessageFeedback:p=!1,onFeedback:m}){let h=o(()=>u(()=>e.partsSig.value),[e]).value,v=o(()=>u(()=>rr(e)),[e]),y=o(()=>u(()=>ar(e)),[e]),b=o(()=>u(()=>io(e)),[e]),x=o(()=>u(()=>i&&ao(e)),[e,i]),S=t===`streaming`,C=e.role===`assistant`&&S,w=so({streaming:C,responseMode:r,reasoningVisible:x.value,hasAnswerText:b.value,emptyReply:v.value,hidden:y.value}),{bufferedHold:T,working:E,showStreamDots:D}=w;if(w.hidden)return null;let O=Vo(e.createdAt),k=e.role===`assistant`||e.role===`operator`,A=p&&!!m&&!!e.serverMessageId&&k&&!S&&t!==`error`&&!v.value,j=S?``:h.filter(e=>e.kind===`text`).map(e=>e.textSig.peek()).join(`
|
|
11
11
|
|
|
12
|
-
`).trim(),M=!S&&t!==`error`&&!v.value&&j.length>0,ee=A||M;return g(`div`,{class:`${Lo}-bubble-row`,"data-role":e.role,"data-testid":Ci(q.messageBubble,e.serverMessageId??e.id),children:_(`div`,{class:`${Lo}-bubble-col`,children:[_(`div`,{class:`${Lo}-bubble`,children:[e.role===`operator`&&e.operatorInitials?g(`span`,{class:`${Lo}-bubble-author`,children:e.operatorInitials}):null,_(`div`,{class:`${Lo}-bubble-body`,children:[T?g(qo,{label:n.loading}):h.map((r,o)=>g(Ho,{part:r,active:E,live:C,strings:n,showReasoning:i,showToolCalls:a,showSources:s,interactive:c&&t===`complete`&&(r.kind!==`tool`||Un(e,o)),superseded:l,continuationStreaming:e.continuationStreaming===!0,tool:d},`${Go(r)}#${o}`)),D&&g(Ko,{}),t===`error`||v.value?_(`div`,{class:`${Lo}-error`,role:`alert`,children:[g(`span`,{children:e.errorText??n.errorGeneric}),f?g(`button`,{type:`button`,class:`${Lo}-error-retry`,onClick:()=>f(e),"data-testid":q.messageRetry,children:n.errorRetry}):null]}):null]})]}),O||ee?_(`div`,{class:`${Lo}-bubble-meta`,children:[O?g(`time`,{class:`${Lo}-bubble-time`,dateTime:O.iso,title:O.full,children:O.short}):null,ee?_(`div`,{class:`${Lo}-bubble-actions`,children:[A&&e.serverMessageId?g(mo,{messageId:e.serverMessageId,initial:e.feedback??null,strings:n,onFeedback:m}):null,M?g(Bo,{text:j,strings:n}):null]}):null]}):null]})})}function Bo({text:e,strings:t}){let[n,r]=c(!1),i=()=>{navigator.clipboard?.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})},a=n?t.copied:t.copy;return g(`button`,{type:`button`,class:`${Lo}-msg-action`,"data-active":n?`true`:void 0,"aria-label":a,title:a,onClick:i,"data-testid":q.messageCopy,children:g(n?Ur:hi,{})})}function Vo(e){if(typeof e!=`number`||!Number.isFinite(e))return null;try{let t=new Date(e);return{short:t.toLocaleTimeString(void 0,{hour:`numeric`,minute:`2-digit`}),full:t.toLocaleString(void 0,{dateStyle:`full`,timeStyle:`short`}),iso:t.toISOString()}}catch{return null}}function Ho({part:e,active:t,live:n,strings:r,showReasoning:i,showToolCalls:a,showSources:o,interactive:s,superseded:c,continuationStreaming:l,tool:u}){switch(e.kind){case`step-start`:return null;case`text`:return g(lo,{textSig:e.textSig,doneSig:e.doneSig});case`reasoning`:return i?g(Wo,{part:e,active:t,strings:r}):null;case`tool`:return g(Uo,{part:e,strings:r,showToolCalls:a,interactive:s,superseded:c,continuationStreaming:l,live:n,tool:u});case`file`:return e.mediaType.startsWith(`image/`)?g(`img`,{src:e.url,alt:``,loading:`lazy`}):g(`a`,{href:e.url,target:`_blank`,rel:`noreferrer noopener`,children:e.url});case`source`:return o?g(go,{part:e,strings:r}):null}}function Uo({part:e,strings:t,showToolCalls:n,interactive:r,superseded:i,continuationStreaming:a,live:s,tool:c}){let l=o(()=>u(()=>e.approvalSig.value!==void 0),[e]);return c?.humanInLoop&&l.value?Ha(e.toolName)?g(Oo,{part:e,strings:t,active:r,superseded:i,continuationStreaming:a,onDecision:c.onDecision,onEdit:c.onEdit}):g(vo,{part:e,strings:t,active:r,superseded:i,continuationStreaming:a,onDecision:c.onDecision,onEdit:c.onEdit}):n?g(Io,{part:e,strings:t,live:s}):null}function Wo({part:e,active:t,strings:n}){return _(`details`,{class:`${Lo}-reasoning`,"data-testid":q.reasoning,open:t,"data-active":t?`true`:void 0,children:[g(`summary`,{class:`${Lo}-reasoning-summary`,children:g(`span`,{class:`${Lo}-reasoning-label`,children:t?n.thinking:n.thoughts})}),g(`div`,{class:`${Lo}-reasoning-body`,children:g(lo,{textSig:e.textSig,doneSig:e.doneSig})})]})}function Go(e){switch(e.kind){case`text`:case`reasoning`:case`step-start`:return`${e.kind}:${e.id}`;case`tool`:return`tool:${e.toolCallId}`;case`file`:return`file:${e.url}`;case`source`:return`source:${e.sourceId}`}}function Ko(){return _(`span`,{class:`${Lo}-typing`,"data-testid":q.typingDots,"aria-hidden":`true`,children:[g(`span`,{}),g(`span`,{}),g(`span`,{})]})}function qo({label:e}){return _(`span`,{class:`${Lo}-loading`,role:`status`,children:[g(`span`,{class:`${Lo}-loading-spinner`,"aria-hidden":`true`}),g(`span`,{class:`${Lo}-loading-label`,children:e})]})}const Jo=b.cssPrefix;function Yo({messagesSig:e,strings:t,responseMode:n,showReasoning:r,showToolCalls:o,showSources:l,enableMessageFeedback:u,onFeedback:d,loading:f,onLoadPreviousMessages:m,idle:h,controlMode:v=`ai-agent`,tool:y,onRetry:b,form:x,formMarkers:S,onFillForm:C}){let w=s(null),T=p(()=>e.value),[E,D]=c(!1),[O,k]=c(!1),A=s(!1),j=s(!1),[M,ee]=c(),te=s(!1),N=s(!1),ne=s(!1),re=s(0),P=()=>ne.current||performance.now()-re.current<350,F=s(0),ie=e=>{let t=e.scrollHeight-e.clientHeight>1;e.dataset.fadeTop=t&&e.scrollTop>1?`true`:`false`,e.dataset.fadeBottom=t&&e.scrollHeight-e.scrollTop-e.clientHeight>1?`true`:`false`},ae=e=>D(e.scrollHeight-e.scrollTop-e.clientHeight>240),I=e=>{F.current=performance.now(),e.scrollTop=e.scrollHeight,ie(e)},L=(e,t)=>{I(e);let n=t,r=0,i=()=>{N.current||P()||(I(e),--n>0&&(r=requestAnimationFrame(i)))};return t>0&&(r=requestAnimationFrame(i)),()=>cancelAnimationFrame(r)},oe=(e,t)=>{let n,r,i,a=-1,o=()=>{n.disconnect(),r.disconnect(),clearTimeout(i)},s=()=>{if(N.current||P()||a>=0&&e.scrollTop<a-4)return o();I(e),a=e.scrollTop};return n=new ResizeObserver(s),r=new MutationObserver(s),s(),n.observe(e),r.observe(e,{childList:!0,subtree:!0,characterData:!0}),i=setTimeout(o,t),o},se=T.value[0]?.id;a(()=>{let e=w.current;if(e&&T.value.length!==0&&!j.current&&(te.current=!0,T.value.some(e=>e.role===`user`)))return oe(e,300)},[se]);let ce=s(0);i(()=>{let e=w.current,t=T.value,n=ce.current;if(ce.current=t.length,e&&te.current&&!j.current){if(t.slice(n).some(e=>e.role===`user`))return N.current=!1,L(e,3);t.some(e=>e.role===`user`)&&(N.current||P()||e.scrollHeight-e.scrollTop-e.clientHeight<120&&I(e))}},[T.value.length]);let le=s(null);i(()=>{let e=w.current,t=T.value.at(-1),n=le.current;if(le.current=t?{id:t.id,streaming:t.status===`streaming`}:null,e&&te.current&&!(!t||t.id!==n?.id||n.streaming||t.status!==`streaming`))return N.current=!1,L(e,3)},[T.value]),i(()=>{let e=w.current;if(!e)return;let t=T.value.at(-1);if(!t||t.status!==`streaming`&&!T.value.some(e=>e.role===`user`))return;let n=()=>{N.current||P()||e.scrollHeight-e.scrollTop-e.clientHeight<240&&I(e)};if(t.status!==`streaming`)return oe(e,300);n();let r=new MutationObserver(n);return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>r.disconnect()},[T.value]);let ue=x?.form.id,de=!!x&&(S??[]).some(e=>e.formId===x.form.id);a(()=>{let e=w.current;!e||!ue||N.current||T.value.some(e=>e.role===`user`)&&(de?e.querySelector(`[data-testid="${q.formGate}"]`)?.scrollIntoView({block:`nearest`}):I(e))},[ue,de]),i(()=>{let e=w.current;if(!e)return;let t=()=>{ae(e),ie(e),performance.now()-F.current>150&&(N.current=e.scrollHeight-e.scrollTop-e.clientHeight>8)},n=()=>{N.current=!0},r=e=>{e.deltaY<0&&n()},i=0,a=e=>{i=e.touches[0]?.clientY??0,ne.current=!0},o=e=>{(e.touches[0]?.clientY??0)>i+4&&n()},s=()=>{ne.current=!1,re.current=performance.now()},c=()=>{ne.current=!0};return e.addEventListener(`scroll`,t,{passive:!0}),e.addEventListener(`wheel`,r,{passive:!0}),e.addEventListener(`touchstart`,a,{passive:!0}),e.addEventListener(`touchmove`,o,{passive:!0}),e.addEventListener(`touchend`,s,{passive:!0}),e.addEventListener(`touchcancel`,s,{passive:!0}),e.addEventListener(`pointerdown`,c,{passive:!0}),window.addEventListener(`pointerup`,s,{passive:!0}),window.addEventListener(`pointercancel`,s,{passive:!0}),ae(e),()=>{e.removeEventListener(`scroll`,t),e.removeEventListener(`wheel`,r),e.removeEventListener(`touchstart`,a),e.removeEventListener(`touchmove`,o),e.removeEventListener(`touchend`,s),e.removeEventListener(`touchcancel`,s),e.removeEventListener(`pointerdown`,c),window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s)}},[]);let fe=()=>{let e=w.current;e&&(N.current=!1,I(e))},pe=T.value.filter(e=>!e.ephemeral),me=pe[0],R=me?.serverMessageId??me?.id,he=!!(m&&pe.length>=50&&R!==M),ge=async()=>{if(!m||A.current)return;let e=w.current,t=e?.scrollHeight??0,n=e?.scrollTop??0;A.current=!0,j.current=!0,k(!0);try{let r=await m();r===!1&&R&&ee(R),r&&e&&(await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),e.scrollTop=n+e.scrollHeight-t,ie(e),ae(e))}finally{j.current=!1,A.current=!1,k(!1)}},_e=[],ve=``,z=T.value.at(-1)?.id,ye=[...S??[]].toSorted((e,t)=>(e.createdAt??1/0)-(t.createdAt??1/0)),be=e=>x&&e.formId===x.form.id?g(Ba,{form:x.form,strings:t,onSubmit:x.onSubmit,onSkip:x.onSkip},`gate:${e.formId}`):g(Va,{marker:e,strings:t,onFill:!x&&C?()=>C(e.formId):void 0},e.key),xe=e=>{for(let t=ye[0];t?.createdAt!==void 0&&!(e!==void 0&&t.createdAt>e);t=ye[0])ye.shift(),_e.push(be(t))};for(let e of T.value){if(e.role===`assistant`&&e.id!==z&&rr(e))continue;xe(e.createdAt);let i=Xo(e.createdAt);i&&i!==ve&&(_e.push(g(`div`,{class:`${Jo}-date-divider`,children:g(`span`,{class:`${Jo}-date-pill`,title:Zo(e.createdAt),children:Qo(e.createdAt,t)})},`day:${i}`)),ve=i);let a=e.retryAction!==void 0||e.role===`assistant`&&e.id===z?ir(T.value,e):void 0,s=a!==void 0&&(a.kind!==`continue-assistant`||v===`ai-agent`);_e.push(g(Ro,{message:e,status:e.status,strings:t,responseMode:n,showReasoning:r,showToolCalls:o,showSources:l,interactive:!!h&&v===`ai-agent`&&e.id===z,superseded:e.id!==z,tool:y,onRetry:h&&s&&(e.role===`user`||e.id===z)?b:void 0,enableMessageFeedback:u,onFeedback:d},e.id))}for(let e of ye)_e.push(be(e));return _(`div`,{class:`${Jo}-list-wrap`,children:[_(`div`,{ref:w,class:`${Jo}-list ${Jo}-list--fade`,role:`log`,"aria-live":`polite`,"aria-relevant":`additions text`,children:[f&&T.value.length===0?g(`div`,{class:`${Jo}-list-loading`,role:`status`,children:t.conversationLoading}):null,he?g(`div`,{class:`${Jo}-load-previous`,children:g(`button`,{type:`button`,onClick:ge,disabled:O,"aria-busy":O,"data-testid":q.loadPreviousMessages,children:t.loadPreviousMessages})}):null,_e,x&&!de?g(Ba,{form:x.form,strings:t,onSubmit:x.onSubmit,onSkip:x.onSkip}):null]}),E?g(`button`,{type:`button`,class:`${Jo}-jump`,onClick:fe,"aria-label":t.scrollToBottom,title:t.scrollToBottom,"data-testid":q.scrollToBottom,children:g(Jr,{})}):null]})}function Xo(e){if(typeof e!=`number`||!Number.isFinite(e))return``;let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`}function Zo(e){if(typeof e!=`number`||!Number.isFinite(e))return``;try{return new Date(e).toLocaleDateString(void 0,{dateStyle:`full`})}catch{return``}}function Qo(e,t){let n=new Date(e),r=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),i=Math.round((r(new Date)-r(n))/864e5);return i<=0?t.dateToday:i===1?t.dateYesterday:i<7?n.toLocaleDateString(void 0,{weekday:`long`}):n.toLocaleDateString(void 0,{month:`long`,day:`numeric`,year:`numeric`})}const $o=[`today`,`yesterday`,`lastWeek`,`older`];function es(e,t){let n=Date.parse(t);if(!Number.isFinite(n))return`older`;let r=Math.floor((ns(e)-ns(n))/(1440*60*1e3));return r<=0?`today`:r===1?`yesterday`:r<7?`lastWeek`:`older`}function ts(e,t){let n=new Map;for(let r of t){let t=es(e,r.lastMessageAt),i=n.get(t);i?i.push(r):n.set(t,[r])}return $o.filter(e=>n.has(e)).map(e=>({bucket:e,conversations:n.get(e)}))}function ns(e){let t=new Date(e);return t.setUTCHours(0,0,0,0),t.getTime()}const rs=I.scope(`history`),is={today:`dateToday`,yesterday:`dateYesterday`,lastWeek:`dateLastWeek`,older:`dateOlder`};function as(e,t){let n=t.type!==`upsert`||t.activity===!0;if(t.type===`snapshot`&&t.result.pagination.page===1&&e.pagination.page>1){let r=pn(e.conversations.slice(0,t.result.pagination.limit),t,n);if(t.result.conversations.length===0){if(r.length===0)return t.result;let e=Math.max(t.result.pagination.total,r.length);return{...t.result,conversations:r,pagination:{...t.result.pagination,total:e,totalPages:Math.ceil(e/t.result.pagination.limit)}}}let i=new Set(r.map(e=>e.conversationId)),a=e.conversations.slice(t.result.pagination.limit).filter(e=>!i.has(e.conversationId)),o=e.pagination.page,s={...t.result.pagination,page:o,hasPrev:o>1,hasNext:o<t.result.pagination.totalPages};return{conversations:[...r,...a],pagination:s}}let r=pn(e.conversations,t,n);return r===e.conversations?e:{...t.type===`snapshot`?t.result:e,conversations:r}}function os(e,t,n){let r=Date.parse(e);return Number.isFinite(r)?new Date(r).toDateString()===new Date(t).toDateString()?new Intl.DateTimeFormat(n,{hour:`numeric`,minute:`2-digit`}).format(r):t-r<10080*60*1e3?new Intl.DateTimeFormat(n,{weekday:`short`}).format(r):new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`}).format(r):``}function ss({transport:e,strings:t,locale:n,persistence:r,onSelect:a,onNewConversation:o}){let l=b.cssPrefix,u=e.peekConversations({limit:50}),[d,f]=c(u?`loaded`:`loading`),[p,m]=c(u),[v,y]=c(!1),x=s(),S=p?.conversations??[],C=p?.pagination;i(()=>{let t=!1,n=!0,i=[],a=e.subscribeConversationChanges(e=>{n&&i.push(e),m(t=>t&&as(t,e))});x.current=void 0,y(!1);let o=e.peekConversations({limit:50});return m(o),f(o?`loaded`:`loading`),e.listConversations({limit:50}).then(e=>{if(t)return;let a=e;for(let e of i)a=as(a,e);i=[],n=!1,m(a),f(`loaded`),r.saveHistoryCount(a.conversations.length)}).catch(e=>{t||(i=[],n=!1,rs.warn(`listConversations failed`,{err:e}),f(`error`))}),()=>{t=!0,a(),x.current=void 0}},[e,r,n]);let w=async()=>{if(x.current||!C?.hasNext)return;let t={};x.current=t,y(!0);try{let n=await e.listConversations({page:C.page+1,limit:C.limit});if(x.current!==t)return;m(e=>{if(!e)return e;let t=new Set(e.conversations.map(e=>e.conversationId)),i=n.conversations.filter(e=>t.has(e.conversationId)?!1:(t.add(e.conversationId),!0)),a={conversations:[...e.conversations,...i],pagination:n.pagination};return r.saveHistoryCount(a.conversations.length),a})}catch(e){if(x.current!==t)return;rs.warn(`listConversations page failed`,{err:e,page:C.page+1})}finally{x.current===t&&(x.current=void 0,y(!1))}},T=o?g(`div`,{class:`${l}-history-footer`,children:_(`button`,{type:`button`,class:`${l}-history-new`,onClick:o,"data-testid":q.sidebarNewConversation,children:[g(wr,{}),t.newConversation]})}):null;if(d===`loading`){let e=Math.min(r.loadHistoryCount()??3,6);return _(h,{children:[g(`div`,{class:`${l}-history`,"aria-busy":`true`,"aria-label":t.historyLoading,children:_(`div`,{class:`${l}-history-group`,"aria-hidden":`true`,children:[g(`div`,{class:`${l}-history-heading`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-heading`})}),g(`div`,{class:`${l}-history-card`,children:Array.from({length:Math.max(1,e)},(e,t)=>_(`div`,{class:`${l}-history-item ${l}-history-item-skeleton`,children:[g(`span`,{class:`${l}-history-avatar ${l}-skeleton`}),_(`span`,{class:`${l}-history-body`,children:[_(`span`,{class:`${l}-history-row`,children:[g(`span`,{class:`${l}-history-title`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-title`})}),g(`span`,{class:`${l}-history-time`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-time`})})]}),g(`span`,{class:`${l}-history-row`,children:g(`span`,{class:`${l}-history-preview`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-preview`})})})]})]},t))})]})}),T]})}if(d===`error`||S.length===0)return _(h,{children:[g(`div`,{class:`${l}-history-empty`,children:t.historyEmpty}),T]});let E=Date.now(),D=ts(E,S);return _(h,{children:[_(`div`,{class:`${l}-history`,role:`list`,children:[D.map(e=>_(`div`,{class:`${l}-history-group`,children:[g(`div`,{class:`${l}-history-heading`,children:t[is[e.bucket]]}),g(`div`,{class:`${l}-history-card`,children:e.conversations.map(e=>_(`button`,{type:`button`,role:`listitem`,class:`${l}-history-item`,onClick:()=>a(e),"data-closed":e.canContinue?void 0:`true`,"data-unread":e.hasUnread?`true`:void 0,"data-testid":Ci(q.historyItem,e.conversationId),children:[g(`span`,{class:`${l}-history-avatar`,"aria-hidden":`true`,children:g(Zr,{})}),_(`span`,{class:`${l}-history-body`,children:[_(`span`,{class:`${l}-history-row`,children:[g(`span`,{class:`${l}-history-title`,children:e.title}),g(`span`,{class:`${l}-history-time`,children:os(e.lastMessageAt,E,n)})]}),_(`span`,{class:`${l}-history-row`,children:[g(`span`,{class:`${l}-history-preview`,children:e.preview??(e.canContinue?t.historyContinue:t.conversationClosed)}),e.hasUnread?g(`span`,{class:`${l}-history-dot`}):null]})]})]},e.conversationId))})]},e.bucket)),C?.hasNext?g(`div`,{class:`${l}-history-more`,children:g(`button`,{type:`button`,onClick:w,disabled:v,"aria-busy":v,"data-testid":q.historyLoadMore,children:t.loadMoreConversations})}):null]}),T]})}const cs=b.cssPrefix;function ls({suggestions:e,onPick:t,disabled:n=!1}){return e.length===0?null:g(`div`,{class:`${cs}-suggestions`,role:`group`,"aria-label":`Suggested replies`,children:e.map((e,r)=>g(`button`,{type:`button`,class:`${cs}-suggestion`,onClick:()=>t(e),disabled:n,"data-testid":Ci(q.suggestion,r),children:e.label},e.id))})}const Z=b.cssPrefix;function us(e){let{options:t,onClose:n}=e,a=t.strings,o=s(null);i(()=>{let e=o.current;if(!e)return;let t=Ri(e),r=e=>{e.key===`Escape`&&n?.()};return e.addEventListener(`keydown`,r),()=>{t(),e.removeEventListener(`keydown`,r)}},[n]);let c=e.composerApiRef,l=e.composerActive&&e.view===`chat`&&e.canSend&&!e.activeForm&&!e.sendPreparing&&e.options.features.fileUpload,{visible:u}=ma({containerRef:o,onDrop:r(e=>{l&&c.current?.attachFromDrop(e)},[c,l]),disabled:!l});return Pi(o.current,t.mode===`modal`),_(`div`,{ref:o,class:`${Z}-panel`,role:`dialog`,"aria-modal":`false`,"aria-label":a.panelTitle,style:{position:`relative`},"data-testid":q.panel,children:[g(ds,{...e,containerEl:o.current,dragOver:u}),g(_s,{poweredBy:e.options.poweredBy})]})}function ds(e){let{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,composerKey:s,panelSize:c,view:l,canSend:u,isStreaming:d,isMemoryCompacting:f,canReleaseQueuedMessages:m,queueManualMessages:v,sendPreparing:y,controlMode:b,assignedOperatorInitials:x,operatorAvailable:S,operatorRequestEnabled:C,onRequestOperator:w,onCancelOperatorRequest:T,loadingMessages:E,onLoadPreviousMessages:D,messagesSig:O,agent:k,suggestions:A,initialWidgetSize:j,onClose:M,onBack:ee,onClear:te,onToggleHistory:N,onSelectHistoryConversation:ne,onNewConversation:re,onWidgetSizeChange:P,onSend:F,onStop:ie,onSuggestion:ae,activeForm:I,formMarkers:L,onFormSubmit:oe,onFormSkip:se,onFormFill:ce,tool:le,onRetry:ue,onMessageFeedback:de,containerEl:fe,dragOver:pe,composerApiRef:me}=e,R=t.strings,he=p(()=>O.value.some(e=>!e.ephemeral&&e.role!==`system`)).value,ge;return ge=I?null:u?_(h,{children:[b&&b!==`ai-agent`?g(ms,{controlMode:b,operatorInitials:x,operatorAvailable:S,onCancelOperatorRequest:T,strings:R}):null,f&&b===`ai-agent`?_(`div`,{class:`${Z}-loading ${Z}-compaction-status`,role:`status`,"data-testid":q.compactionStatus,children:[g(`span`,{class:`${Z}-loading-spinner`,"aria-hidden":`true`}),R.compactingContext]}):null,!d&&!f&&b===`ai-agent`&&g(ls,{suggestions:A,onPick:ae,disabled:y}),g(da,{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,isStreaming:d,isMemoryCompacting:f,canReleaseQueuedMessages:m,queueManualMessages:v,active:e.composerActive&&l===`chat`,isPreparing:y,operatorRequestEnabled:C,canRequestOperator:he,controlMode:b,onRequestOperator:w,onSend:F,onStop:ie,apiRef:me},s)]}):g(ps,{label:R.conversationClosed,ctaLabel:R.startNewConversation,onNewConversation:te}),_(h,{children:[l===`history`?g(fs,{strings:R,onBack:N,onClose:M,showClose:Ii(t.mode,c,t.actions)}):_(`header`,{class:`${Z}-header`,"data-testid":q.panelHeader,children:[ee?g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:ee,"aria-label":R.moduleBack,title:R.moduleBack,children:g(Kr,{})}):null,k?g(Vi,{agent:k,strings:R}):g(`h1`,{children:R.panelTitle}),g(Ca,{panelProps:e,variant:`chat`})]}),l===`history`?g(ss,{transport:n,strings:R,locale:t.locale,persistence:a,onSelect:ne,onNewConversation:re}):_(h,{children:[g(pa,{visible:pe,strings:R}),g(Yo,{messagesSig:O,strings:R,responseMode:t.responseMode,showReasoning:t.showReasoning,showToolCalls:t.showToolCalls,showSources:t.showSources,enableMessageFeedback:t.enableMessageFeedback,onFeedback:de,loading:E,onLoadPreviousMessages:D,idle:!d&&!y&&u&&!I,controlMode:b,tool:le,onRetry:ue,form:I?{form:I,onSubmit:oe,onSkip:se}:null,formMarkers:L,onFillForm:ce}),ge,g(gs,{disclaimer:t.composerDisclaimer})]}),t.size.resize?.enabled?g(ji,{panelEl:fe,resize:t.size.resize,position:t.position,initialSize:j,onSizeChange:P,strings:R}):null]})}function fs({strings:e,onBack:t,onClose:n,showClose:r}){return _(`header`,{class:`${Z}-header`,children:[g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:t,"aria-label":e.historyBack,title:e.historyBack,children:g(Kr,{})}),g(`h1`,{children:e.historyTitle}),r?g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:n,"aria-label":e.close,title:e.close,children:g(Cr,{})}):null]})}function ps({label:e,ctaLabel:t,onNewConversation:n}){return _(`div`,{class:`${Z}-readonly-banner`,role:`note`,children:[g(`span`,{class:`${Z}-readonly-label`,children:e}),g(`button`,{type:`button`,class:`${Z}-readonly-cta`,onClick:n,children:t})]})}function ms({controlMode:e,operatorInitials:t,operatorAvailable:n,onCancelOperatorRequest:r,strings:i}){let a=hs(e,t,n,i);return _(`div`,{class:`${Z}-operator-banner`,role:`status`,"data-mode":e,"data-testid":q.operatorBanner,children:[g(`span`,{class:`${Z}-operator-pulse`,"aria-hidden":`true`}),g(`span`,{class:`${Z}-operator-label`,children:a}),e===`awaiting-operator`&&r?g(`button`,{type:`button`,class:`${Z}-cancel-operator-request`,"data-testid":q.cancelOperatorRequest,onClick:r,children:i.cancelOperatorRequest}):null]})}function hs(e,t,n,r){return e===`operator`?r.chattingWithOperator.replace(`{operator}`,t??``):n===!1?r.noOperatorAvailable:r.connectingOperator}function gs({disclaimer:e}){return e?g(`div`,{class:`${Z}-composer-footer`,children:g(`div`,{class:`${Z}-disclaimer`,children:e})}):null}function _s({poweredBy:e}){return e?g(`div`,{class:`${Z}-poweredby-bar`,children:g(vs,{logoUrl:e.logoUrl,text:e.text,href:e.href})}):null}function vs({logoUrl:e,text:t,href:n}){let r=_(h,{children:[e?g(`img`,{class:`${Z}-poweredby-logo`,src:e,alt:``,loading:`lazy`}):null,t?g(`span`,{children:t}):null]});return n?g(`a`,{class:`${Z}-poweredby`,href:n,target:`_blank`,rel:`noopener noreferrer`,children:r}):g(`span`,{class:`${Z}-poweredby`,children:r})}function ys(e){let t=s(e);t.current=e;let n=s(null);return n.current??(n.current=bs(t)),n.current}function bs(e){let t=f(null),n=new Set,r=t=>`${e.current.conversationId()??``}:${t}`,i=t=>t.frequency===`always`?!1:t.frequency===`conversation`?n.has(r(t.id)):t.id in e.current.persistence.loadFormsDone(),a=(n,r)=>{if(t.value)return;let a=e.current;if(n===`manual`){let e=a.forms.list.find(e=>e.id===r);e&&(t.value={form:e,trigger:`manual`});return}for(let e of a.forms.byTrigger[n]??[]){let r=e.triggers.find(e=>e.kind===n);if(!(!r||!xs(r,a)||i(e)||!Ss(e,a))){t.value={form:e,trigger:n};return}}},o=(i,a)=>{let o=t.value;if(!o)return;t.value=null;let{form:s,trigger:c}=o;s.frequency===`conversation`?n.add(r(s.id)):s.frequency!==`always`&&e.current.persistence.saveFormDone(s.id),e.current.onComplete(s,c,i,a)};return{activeForm:t,fire:a,refresh:()=>{let n=t.value;if(!n)return;let r=e.current.forms.list.find(e=>e.id===n.form.id);r&&r!==n.form&&(t.value={form:r,trigger:n.trigger})},complete:e=>o(e,!1),skip:()=>o({},!0)}}function xs(e,t){return e.kind===`after-messages`?t.messageCount()>=Number(e.param??0):e.kind!==`page-area`||t.pageArea()===e.param}function Ss(e,t){let n=e.when;if(!n)return!0;if(n.missingContext?.length){let e=t.userContext()??{};if(n.missingContext.some(t=>e[t]!==void 0&&e[t]!==``))return!1}if(n.pageArea&&!(Array.isArray(n.pageArea)?n.pageArea:[n.pageArea]).includes(t.pageArea()??``))return!1;let r=t.messageCount();return!(n.minMessages!=null&&r<n.minMessages||n.maxMessages!=null&&r>n.maxMessages)}function Cs(e){let t=b.cssPrefix,{site:n,blocks:r,strings:i,collapsed:a}=e,o=r?.navigation??[],s=r?.linkCards??[],c=a?i.expandSidebar:i.collapseSidebar;return _(`aside`,{class:`${t}-sidebar`,"data-collapsed":a?`true`:`false`,"data-testid":q.sidebar,children:[_(`div`,{class:`${t}-sidebar-header`,children:[g(ws,{site:n}),g(`button`,{type:`button`,class:`${t}-sidebar-toggle`,"aria-label":c,"aria-expanded":a?`false`:`true`,title:c,onClick:e.onToggleCollapsed,"data-testid":q.sidebarToggle,children:g(Ts,{collapsed:a})})]}),a?null:_(h,{children:[o.length>0?g(`nav`,{class:`${t}-sidebar-section`,"data-section":`navigation`,children:g(Es,{items:o})}):null,s.length>0?g(`div`,{class:`${t}-sidebar-section`,"data-section":`link-cards`,children:g(Ds,{items:s})}):null,e.showConversations?g(`div`,{class:`${t}-sidebar-conversations`,children:g(ss,{transport:e.transport,strings:e.strings,locale:e.locale,persistence:e.persistence,onSelect:e.onSelectConversation,onNewConversation:e.onNewConversation})}):null]})]})}function ws({site:e}){let t=b.cssPrefix;if(e?.logo?.url){let n=e.logo.alt??e.title??`Logo`;return _(`picture`,{children:[e.logoDark?.url?g(`source`,{srcset:e.logoDark.url,media:`(prefers-color-scheme: dark)`}):null,g(`img`,{class:`${t}-sidebar-logo`,src:e.logo.url,alt:n})]})}return g(`div`,{class:`${t}-sidebar-title`,children:e?.title??b.name})}function Ts({collapsed:e}){return g(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`,"aria-hidden":`true`,children:e?g(`polyline`,{points:`9 6 15 12 9 18`}):g(`polyline`,{points:`15 6 9 12 15 18`})})}function Es({items:e}){let t=b.cssPrefix;return g(`ul`,{class:`${t}-sidebar-nav`,children:e.map(e=>g(`li`,{children:_(`a`,{class:`${t}-sidebar-nav-item`,href:e.href,target:e.href?`_blank`:void 0,rel:e.href?`noreferrer`:void 0,children:[e.icon?g(`span`,{class:`${t}-sidebar-nav-icon`,"data-icon":e.icon}):null,g(`span`,{class:`${t}-sidebar-nav-label`,children:e.label})]})},e.id??e.label))})}function Ds({items:e}){let t=b.cssPrefix;return g(`div`,{class:`${t}-sidebar-cards`,children:e.map(e=>_(`a`,{class:`${t}-sidebar-card`,href:e.href,target:e.href?`_blank`:void 0,rel:e.href?`noreferrer`:void 0,children:[g(`div`,{class:`${t}-sidebar-card-label`,children:e.label}),e.description?g(`div`,{class:`${t}-sidebar-card-desc`,children:e.description}):null]},e.id??e.label))})}const Os=b.cssPrefix;function ks(e){return _(`main`,{class:`${Os}-page-shell`,"data-sidebar-collapsed":e.sidebarCollapsed?`true`:`false`,children:[g(Cs,{site:e.site,blocks:e.blocks,transport:e.transport,strings:e.strings,locale:e.locale,persistence:e.persistence,showConversations:e.showConversations,onSelectConversation:e.onSelectConversation,onNewConversation:e.onNewConversation,collapsed:e.sidebarCollapsed,onToggleCollapsed:e.onToggleSidebarCollapsed}),g(`section`,{class:`${Os}-page-chat`,"aria-label":e.strings.panelTitle,children:e.children})]})}const As=e=>Object.fromEntries(e.map(e=>[e,[]]));function js(e,t,n){return e.includes(t)?t:e.includes(n)?n:e[0]??``}function Ms(e,t,n){let r=[...new Set(t)],i=f({activeTab:js(r,e,``),stacks:As(r)});return{sig:i,reconcile(e,t){let a=[...new Set(e)],o=i.value,s=js(a,o.activeTab,t),c=Object.fromEntries(a.map(e=>[e,o.stacks[e]??[]])),l=s===o.activeTab&&a.length===Object.keys(o.stacks).length&&a.every(e=>o.stacks[e]===c[e]);r=a,!l&&(i.value={activeTab:s,stacks:c},s!==o.activeTab&&s&&n?.(s))},switchTab(e){!(e in i.value.stacks)||i.value.activeTab===e||(i.value={...i.value,activeTab:e},n?.(e))},push(e){let t=i.value,n=t.stacks[t.activeTab]??[];i.value={...t,stacks:{...t.stacks,[t.activeTab]:[...n,e]}}},pop(){let e=i.value,t=e.stacks[e.activeTab]??[];t.length!==0&&(i.value={...e,stacks:{...e.stacks,[e.activeTab]:t.slice(0,-1)}})},reset(e){i.value={activeTab:js(r,e,``),stacks:As(r)}}}}const Ns=e=>e.stacks[e.activeTab]??[],Ps=e=>Ns(e).at(-1),Fs=e=>Ns(e).length===0,Is={Icon:si},Ls=b.cssPrefix;function Rs({title:e,actions:t}){return _(`header`,{class:`${Ls}-back-header`,"data-variant":`title`,children:[g(`span`,{class:`${Ls}-back-spacer`,"aria-hidden":`true`}),g(`h1`,{class:`${Ls}-back-title`,children:e}),t??g(`span`,{class:`${Ls}-back-spacer`,"aria-hidden":`true`})]})}function zs({title:e,backLabel:t,onBack:n,actions:r,testid:i}){return _(`header`,{class:`${Ls}-back-header`,"data-testid":i,children:[g(`button`,{type:`button`,class:`${Ls}-icon-btn`,onClick:n,"aria-label":t,title:t,children:g(Kr,{})}),g(`h1`,{class:`${Ls}-back-title`,children:e}),r??g(`span`,{class:`${Ls}-back-spacer`,"aria-hidden":`true`})]})}function Bs(e,t){return e instanceof Vt&&e.status===429?t.errorRateLimited:t.errorGeneric}const Vs=b.cssPrefix;function Hs({placeholder:e,onActivate:t}){return _(`button`,{type:`button`,class:`${Vs}-home-search`,onClick:t,"data-testid":q.homeSearch,children:[g(`span`,{class:`${Vs}-home-search-text`,children:e}),g(`span`,{class:`${Vs}-home-search-icon`,"aria-hidden":`true`,children:g(ri,{})})]})}function Us({placeholder:e,value:t,onInput:n}){return _(`div`,{class:`${Vs}-home-search`,"data-input":`true`,children:[g(`input`,{type:`search`,class:`${Vs}-home-search-input`,placeholder:e,value:t,onInput:e=>n(e.currentTarget.value),"data-testid":q.helpSearch}),g(`span`,{class:`${Vs}-home-search-icon`,"aria-hidden":`true`,children:g(ri,{})})]})}const Ws=b.cssPrefix;function Gs({title:e,subtitle:t,onClick:n,testid:r}){return _(`button`,{type:`button`,class:`${Ws}-list-row`,onClick:n,"data-testid":r,children:[_(`span`,{class:`${Ws}-list-row-body`,children:[g(`span`,{class:`${Ws}-list-row-title`,children:e}),t?g(`span`,{class:`${Ws}-list-row-sub`,children:t}):null]}),g(`span`,{class:`${Ws}-list-row-chevron`,"aria-hidden":`true`,children:g(Or,{})})]})}const Ks=b.cssPrefix;function qs({tone:e=`info`,message:t,onRetry:n,strings:r}){return _(`div`,{class:`${Ks}-module-empty`,role:e===`error`?`alert`:`status`,"aria-live":`polite`,children:[g(`span`,{children:t}),n?g(`button`,{type:`button`,class:`${Ks}-module-retry`,onClick:n,children:r.errorRetry}):null]})}const Js=b.cssPrefix,Ys=I.scope(`help`),Xs=(e,t)=>t.url?e.push({kind:`iframe`,url:t.url,title:t.title}):e.push({kind:`content`,id:t.id,title:t.title});function Zs(e){let t=new Map;for(let n of e){let e=n.categories?.[0]??``;(t.get(e)??t.set(e,[]).get(e)).push(n)}return[...t.entries()]}function Qs(e,t){let n=t.toLowerCase(),r=n.indexOf(e);if(r!==-1)return 100-Math.min(r,99);let i=0;for(let t of e){if(i=n.indexOf(t,i),i===-1)return 0;i+=1}return 1}function $s(e,t){let n=t.toLowerCase().trim();return n?e.map(e=>({item:e,score:Math.max(Qs(n,e.title)*2,Qs(n,e.description??``))})).filter(e=>e.score>0).toSorted((e,t)=>t.score-e.score).map(e=>e.item):[]}function ec({article:e,nav:t}){return g(Gs,{title:e.title,subtitle:e.description,onClick:()=>Xs(t,e),testid:Ci(q.helpArticle,e.id)})}function tc({transport:e,strings:t,config:n,nav:r,bus:a,panelProps:s}){let l=n.contentTags,[u,d]=c(`loading`),[f,p]=c(t.errorGeneric),[m,h]=c([]),[v,y]=c(``),[b,x]=c(0);i(()=>{let n=!1;return d(`loading`),e.listContent({tags:l,sortBy:`order`,limit:100}).then(e=>{if(n)return;let t=e.items??[];h(t),d(`loaded`),a.emit(`contentView`,{section:`help`,tags:l?.join(`,`),count:t.length})}).catch(e=>{n||(Ys.warn(`listContent (help) failed`,{err:e}),p(Bs(e,t)),d(`error`))}),()=>{n=!0}},[e,l,b,a]);let S=o(()=>$s(m,v),[m,v]);i(()=>{let e=v.trim();if(!e)return;let t=setTimeout(()=>a.emit(`contentSearch`,{queryLength:e.length,hitCount:S.length}),600);return()=>clearTimeout(t)},[v,S,a]);function C(){return v.trim().length>0?S.length===0?g(qs,{message:t.helpSearchEmpty,strings:t}):g(`div`,{class:`${Js}-help-card`,children:S.map(e=>g(ec,{article:e,nav:r},e.id))}):u===`loading`?g(qs,{message:t.helpLoading,strings:t}):u===`error`?g(qs,{tone:`error`,message:f,onRetry:()=>x(e=>e+1),strings:t}):m.length===0?g(qs,{message:t.helpEmpty,strings:t}):Zs(m).map(([e,t])=>_(`section`,{class:`${Js}-help-group`,children:[e?g(`h2`,{class:`${Js}-help-section-title`,children:e}):null,g(`div`,{class:`${Js}-help-card`,children:t.map(e=>g(ec,{article:e,nav:r},e.id))})]},e))}return _(`div`,{class:`${Js}-module`,children:[g(Rs,{title:t.helpTitle,actions:g(Ca,{panelProps:s,variant:`plain`})}),g(`div`,{class:`${Js}-module-pad`,children:g(Us,{placeholder:t.helpSearchPlaceholder,value:v,onInput:y})}),g(`div`,{class:`${Js}-help-list`,children:C()})]})}const nc={Icon:Qr,Root:e=>g(tc,{...e})},rc=b.cssPrefix;function ic({onClick:e,children:t,testid:n}){return e?g(`button`,{type:`button`,class:`${rc}-home-card`,"data-interactive":`true`,onClick:e,"data-testid":n,children:t}):g(`div`,{class:`${rc}-home-card`,"data-testid":n,children:t})}const Q=b.cssPrefix,ac=I.scope(`home`);function oc(e){let t=e.options.userContext?.name,n=e.config.greetingText?D(e.strings,e.config.greetingText):void 0;return n?{title:t?n.replace(`{name}`,t):n.replace(/\s*\{name\}\s*/,` `).trim(),subtitle:e.strings.homeGreetingLead}:t?{title:e.strings.homeGreetingNamed.replace(`{name}`,t),subtitle:e.strings.homeGreetingLead}:{title:e.strings.homeGreeting}}const sc=(e,t)=>t.url?e.push({kind:`iframe`,url:t.url,title:t.title}):e.push({kind:`content`,id:t.id,title:t.title});function cc(e,t){return pn(e,t,t.type!==`upsert`||t.activity===!0)}function lc(e){let{transport:t,strings:n,config:r,nav:a,bus:o,panelProps:s}=e,[l,u]=c(null),[d,f]=c([]),p=r.contentTags?.join(`,`),m=e.options.modules.list.some(e=>e.layout===`chat`);i(()=>{if(r.showRecentConversations===!1)return;let e=!1,n=!0,i=[],a=t.subscribeConversationChanges(e=>{n&&i.push(e),u(t=>cc(t?[t]:[],e)[0]??null)});return t.listConversations({limit:m?50:1}).then(t=>{if(e)return;let r=i.reduce(cc,t.conversations);i=[],n=!1,u(r[0]??null)}).catch(t=>{e||(i=[],n=!1,ac.warn(`listConversations (home) failed`,{err:t}))}),()=>{e=!0,a()}},[t,r.showRecentConversations,m]),i(()=>{if(!r.contentTags?.length)return;let e=!1;return t.listContent({tags:r.contentTags,limit:6}).then(t=>{if(e)return;let n=t.items??[];f(n),o.emit(`contentView`,{section:`home`,tags:p,count:n.length})}).catch(t=>!e&&ac.warn(`listContent (home) failed`,{err:t})),()=>{e=!0}},[t,p,o]);let v=oc(e),y=r.userAvatars??[],b=r.status,x=b?.text?D(n,b.text):n.homeStatus,S=r.contentBlockTitle?D(n,r.contentBlockTitle):n.homeContentTitle;return g(`div`,{class:`${Q}-module ${Q}-home`,"data-testid":q.homeView,children:_(`div`,{class:`${Q}-home-scroll`,children:[_(`div`,{class:`${Q}-home-hero`,children:[_(`div`,{class:`${Q}-home-hero-top`,children:[r.brandName?g(`span`,{class:`${Q}-home-brand`,"data-testid":q.homeBrand,children:r.brandName}):g(`span`,{class:`${Q}-home-brand-spacer`,"aria-hidden":`true`}),_(`div`,{class:`${Q}-home-hero-actions`,children:[y.length>0?g(`div`,{class:`${Q}-home-avatars`,children:y.map(e=>g(`span`,{class:`${Q}-home-avatar`,title:e.role?`${e.name} · ${e.role}`:e.name,children:e.avatar?g(`img`,{src:e.avatar,alt:``,loading:`lazy`}):g(`span`,{children:zi(e.name)})},e.name))}):null,g(Ca,{panelProps:s,variant:`plain`})]})]}),r.showGreeting===!1?null:_(h,{children:[g(`h1`,{class:`${Q}-home-greeting`,"data-testid":q.homeGreeting,children:v.title}),v.subtitle?g(`p`,{class:`${Q}-home-lead`,children:v.subtitle}):null]})]}),_(`div`,{class:`${Q}-home-cards`,children:[r.showSearchBar===!1?null:g(Hs,{placeholder:n.homeSearchPlaceholder,onActivate:()=>a.switchToLayout(`help`)}),l?g(ic,{onClick:()=>a.selectConversation(l),testid:q.homeRecent,children:_(`div`,{class:`${Q}-home-recent-row`,"data-unread":l.hasUnread?`true`:void 0,children:[g(`span`,{class:`${Q}-home-recent-avatar`,"aria-hidden":`true`,children:g(si,{})}),_(`span`,{class:`${Q}-home-recent-body`,children:[g(`span`,{class:`${Q}-home-recent-title`,children:l.title}),l.preview?g(`span`,{class:`${Q}-home-recent-preview`,children:l.preview}):null]}),l.hasUnread?g(`span`,{class:`${Q}-home-recent-dot`,"aria-label":`Unread`}):null]})}):null,b?g(ic,{onClick:b.url?()=>a.push({kind:`iframe`,url:b.url,title:x}):void 0,children:_(`div`,{class:`${Q}-home-status`,"data-level":b.level??`operational`,children:[g(`span`,{class:`${Q}-home-status-icon`,"aria-hidden":`true`,children:g(ii,{})}),g(`span`,{class:`${Q}-home-status-text`,children:x})]})}):null,d.length>0?_(`section`,{class:`${Q}-home-content`,children:[g(`div`,{class:`${Q}-home-content-title`,children:S}),g(`div`,{class:`${Q}-home-content-list`,children:d.map(e=>g(Gs,{title:e.title,subtitle:e.description,onClick:()=>sc(a,e),testid:Ci(q.homeContentRow,e.id)},e.id))})]}):null]})]})})}const uc={Icon:ai,Root:e=>g(lc,{...e})},dc=b.cssPrefix,fc=I.scope(`news`);function pc({transport:e,strings:t,config:n,nav:r,bus:a,panelProps:o}){let s=n.contentTags,[l,u]=c(`loading`),[d,f]=c(t.errorGeneric),[p,m]=c([]),[h,v]=c(0);i(()=>{let n=!1;return u(`loading`),e.listContent({tags:s,sortBy:`publishedAt`,sortOrder:`desc`}).then(e=>{if(n)return;let t=e.items??[];m(t),u(`loaded`),a.emit(`contentView`,{section:`news`,tags:s?.join(`,`),count:t.length})}).catch(e=>{n||(fc.warn(`listContent (news) failed`,{err:e}),f(Bs(e,t)),u(`error`))}),()=>{n=!0}},[e,s,h,a]);function y(){return l===`loading`?g(qs,{message:t.newsLoading,strings:t}):l===`error`?g(qs,{tone:`error`,message:d,onRetry:()=>v(e=>e+1),strings:t}):p.length===0?g(qs,{message:t.newsEmpty,strings:t}):g(`div`,{class:`${dc}-news-list`,children:p.map(e=>_(`button`,{type:`button`,class:`${dc}-news-card`,onClick:()=>r.push({kind:`content`,id:e.id,title:e.title}),"data-testid":Ci(q.newsItem,e.id),children:[e.image?g(`img`,{class:`${dc}-news-hero`,src:e.image,alt:``,loading:`lazy`}):null,_(`span`,{class:`${dc}-news-body`,children:[g(`span`,{class:`${dc}-news-title`,children:e.title}),e.description?g(`span`,{class:`${dc}-news-summary`,children:e.description}):null]})]},e.id))})}return _(`div`,{class:`${dc}-module`,children:[g(Rs,{title:t.newsTitle,actions:g(Ca,{panelProps:o,variant:`plain`})}),g(`div`,{class:`${dc}-module-scroll`,children:y()})]})}const mc={chat:Is,home:uc,help:nc,news:{Icon:oi,Root:e=>g(pc,{...e})}},hc=b.cssPrefix;function gc({modules:e,activeTab:t,strings:n,hasUnread:r,onSelect:i}){return g(`nav`,{class:`${hc}-tabbar`,role:`tablist`,"aria-label":n.panelTitle,children:e.map(e=>{let a=mc[e.layout].Icon,o=e.id===t,s=e.layout===`chat`&&r;return _(`button`,{type:`button`,role:`tab`,"aria-selected":o,class:`${hc}-tab`,onClick:()=>i(e.id),"data-testid":Ci(q.tab,e.id),children:[_(`span`,{class:`${hc}-tab-icon`,"aria-hidden":`true`,children:[g(a,{}),s?g(`span`,{class:`${hc}-tab-badge`,"data-testid":q.tabBadge,"aria-label":`Unread`}):null]}),g(`span`,{class:`${hc}-tab-label`,children:D(n,e.label)})]},e.id)})})}const _c=b.cssPrefix;function vc({url:e,title:t,strings:n,onBack:r,actions:i}){return _(`div`,{class:`${_c}-module`,children:[g(zs,{title:t||n.moduleBack,backLabel:n.moduleBack,onBack:r,actions:i}),g(`iframe`,{class:`${_c}-content-frame`,src:e,title:t||`content`,sandbox:`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads`,referrerpolicy:`no-referrer`,loading:`lazy`,allow:`fullscreen`})]})}const yc=b.cssPrefix,bc=I.scope(`content`);function xc({id:e,title:t,transport:n,strings:a,bus:o,onBack:s,actions:l}){let[u,d]=c(null),[f,p]=c(!1),[m,h]=c(0),v=r(()=>{p(!1),d(null),h(e=>e+1)},[]);i(()=>{let t=!1;return n.listContent({ids:[e],limit:1}).then(n=>{if(t)return;let r=n.items[0];r?(d(r),o.emit(`contentOpen`,{contentId:e,tags:r.tags?.length?r.tags.join(`,`):void 0})):p(!0)}).catch(e=>{t||(bc.warn(`listContent (reader) failed`,{err:e}),p(!0))}),()=>{t=!0}},[n,e,m,o]),i(()=>{if(!u)return;let t=setTimeout(()=>o.emit(`contentRead`,{contentId:e}),5e3);return()=>clearTimeout(t)},[u,e,o]);let y=r(t=>{let n=(t.target?.closest?.(`a`))?.getAttribute(`href`)??``;n&&!n.startsWith(`#`)&&o.emit(`contentLinkClick`,{contentId:e})},[o,e]);function b(){return f?g(qs,{tone:`error`,message:a.errorGeneric,onRetry:v,strings:a}):u===null?g(qs,{message:a.contentLoading,strings:a}):_(`article`,{class:`${yc}-content`,"data-testid":q.contentView,onClick:y,children:[u.image?g(`img`,{class:`${yc}-content-hero`,src:u.image,alt:``,loading:`lazy`}):null,u.description?g(`p`,{class:`${yc}-content-subtitle`,children:u.description}):null,g(uo,{text:u.content??``})]})}return _(`div`,{class:`${yc}-module`,children:[g(zs,{title:u?.title||t||a.moduleBack,backLabel:a.moduleBack,onBack:s,actions:l,testid:q.backHeader}),g(`div`,{class:`${yc}-module-scroll`,"data-testid":q.contentScroll,children:b()})]})}const Sc=b.cssPrefix;function Cc({panelProps:e,enabledModules:t,nav:n,bus:a,hasUnread:o,onSelectConversation:c,onStartNewConversation:l,onSetPanelSize:u}){let d=e.options,f=d.strings,m=s(null),h=s(new Set);i(()=>{let t=m.current;if(!t)return;let n=Ri(t),r=t=>{t.key===`Escape`&&e.onClose?.()};return t.addEventListener(`keydown`,r),()=>{n(),t.removeEventListener(`keydown`,r)}},[e.onClose]);let v=p(()=>n.sig.value).value,y=Ps(v),b=d.modules.byId[v.activeTab],x=e.composerActive&&b?.layout===`chat`&&y===void 0,S=e.composerApiRef,C=x&&e.view===`chat`&&e.canSend&&!e.activeForm&&!e.sendPreparing&&e.options.features.fileUpload,{visible:w}=ma({containerRef:m,onDrop:r(e=>{C&&S.current?.attachFromDrop(e)},[S,C]),disabled:!C});Pi(m.current,d.mode===`modal`);let T=y?.kind===`iframe`||y?.kind===`content`,E=t.length>1&&(Fs(v)||!T),D=s(null);i(()=>{if(T&&D.current===null)D.current=e.panelSize,e.panelSize===`normal`&&u(`expanded`);else if(!T&&D.current!==null){let e=D.current;D.current=null,u(e)}},[T]);let O={push:e=>n.push(e),pop:()=>n.pop(),switchTab:e=>n.switchTab(e),switchToLayout:e=>{let r=t.find(t=>t.layout===e);r&&n.switchTab(r.id)},selectConversation:c,startNewConversation:l},k=t=>({options:d,transport:e.transport,strings:f,config:t,nav:O,bus:a,panelProps:e}),A=g(Ca,{panelProps:e,variant:`plain`});b&&h.current.add(b.id);let j=t.filter(e=>h.current.has(e.id)),M=t=>{if(t.layout===`chat`)return g(ds,{...e,composerActive:x,containerEl:m.current,dragOver:w});let n=mc[t.layout].Root;return n?g(n,{...k(t)}):null};return _(`div`,{ref:m,class:`${Sc}-panel ${Sc}-messenger`,role:`dialog`,"aria-modal":`false`,"aria-label":f.panelTitle,style:{position:`relative`},"data-testid":q.messengerHome,children:[_(`div`,{class:`${Sc}-messenger-body`,children:[j.map(e=>g(`div`,{class:`${Sc}-messenger-pane`,hidden:T||e.id!==b?.id,children:M(e)},e.id)),y?.kind===`iframe`?g(vc,{url:y.url,title:y.title,strings:f,onBack:()=>n.pop(),actions:A}):y?.kind===`content`?g(xc,{id:y.id,title:y.title,transport:e.transport,strings:f,bus:a,onBack:()=>n.pop(),actions:A}):null]}),E?g(gc,{modules:t,activeTab:v.activeTab,strings:f,hasUnread:o,onSelect:e=>n.switchTab(e)}):null,g(_s,{poweredBy:d.poweredBy}),d.size.resize?.enabled&&!(b?.layout===`chat`&&!y)?g(ji,{panelEl:m.current,resize:d.size.resize,position:d.position,initialSize:e.initialWidgetSize,onSizeChange:e.onWidgetSizeChange,strings:f}):null]})}const wc=b.cssPrefix;function Tc({strings:e,onClose:t}){return _(`div`,{class:`${wc}-panel ${wc}-modules-empty`,role:`dialog`,"aria-label":e.panelTitle,"data-testid":q.modulesEmpty,children:[t?g(`button`,{type:`button`,class:`${wc}-icon-btn ${wc}-modules-empty-close`,onClick:t,"aria-label":e.close,title:e.close,children:g(Cr,{})}):null,g(`p`,{class:`${wc}-modules-empty-text`,children:e.modulesEmpty})]})}function Ec(e,t,n,r){let i={role:n,text:r};e.emit(`message`,i),t.onMessage?.(i)}const Dc=I.scope(`hitl`);function Oc(e){let{streaming:t,controlModeSig:n,messagesSig:i,sendAiTurn:a,bus:c,humanInLoop:l}=e,u=s(t);u.current=t;let d=r((e,t,r)=>{if(u.current||n.value!==`ai-agent`)return!1;let o=i.value.at(-1),s=o?.partsSig.value.findIndex(t=>t.kind===`tool`&&t.toolCallId===e)??-1,c=o?.partsSig.value[s];return!o||c?.kind!==`tool`?(Dc.warn(`decideTool: tool part not found`,{toolCallId:e}),!1):o.status!==`complete`||!Un(o,s)||!t(c)?!1:(r(c),o.partsSig.value=[...o.partsSig.value],Vn(o)?(o.status=`streaming`,o.retryAction={kind:`continue-assistant`,messageId:o.serverMessageId??o.id},o.awaitingContinuation=!0,i.value=[...i.value],a({continueExisting:!0}),!0):!0)},[n,i,a]),f=r((e,t,n)=>{let r=!1;if(d(e,e=>e.stateSig.value===`approval-requested`,i=>{r=Ha(i.toolName);let a=i.approvalSig.value?.id??e;i.approvalSig.value={id:a,approved:t,reason:n},i.stateSig.value=`approval-responded`})){if(r){Dc.info(`toolResult`,{toolCallId:e}),c.emit(`toolResult`,{toolCallId:e});return}Dc.info(`toolDecision`,{toolCallId:e,approved:t}),c.emit(`toolDecision`,{toolCallId:e,approved:t})}},[c,d]),p=r(e=>{d(e,e=>e.stateSig.value===`approval-responded`&&e.approvalSig.value?.approved!==void 0,t=>{let n=t.approvalSig.value?.id??e;t.approvalSig.value={id:n},t.stateSig.value=`approval-requested`})},[d]);return{toolInteraction:o(()=>({humanInLoop:l,onDecision:f,onEdit:p}),[l,f,p])}}function kc({callout:e,persistence:t}){let n=e?.text??``,a=e?.persistent??!0,[o,s]=c(()=>!a&&t.loadCalloutDismissed(n));return i(()=>{s(!a&&t.loadCalloutDismissed(n))},[n,a,t]),{dismissed:o,dismissCallout:r(()=>{s(!0),a||t.saveCalloutDismissed(n)},[t,n,a])}}function Ac(e){let{transport:t,conversationIdSig:n}=e,i=m(`ai-agent`),a=m(void 0),o=m(void 0),c=s(),l=r(e=>{let t=e.controlRevision,r=c.current;r&&r.conversationId===n.value&&t<r.revision||(c.current={conversationId:n.value,revision:t},i.value=e.controlMode,a.value=e.assignedOperatorInitials,e.controlMode===`awaiting-operator`?e.operatorAvailable!==void 0&&(o.value=e.operatorAvailable):o.value=void 0)},[n,i,a,o]);return{controlModeSig:i,assignedOperatorInitialsSig:a,operatorAvailableSig:o,applyControlState:l,adoptControlStateChunk:r(e=>{if(e.type!==`data-control-state`)return;let t=$t(e.data);t&&l(t)},[l]),requestOperator:r(async()=>{let e=n.value,r=await t.requestOperator();r&&n.value===e&&l(r)},[t,n,l]),cancelOperatorRequest:r(async()=>{let e=n.value,r=await t.cancelOperatorRequest();r&&n.value===e&&l(r)},[t,n,l])}}const jc=b.cssPrefix,Mc=`--${jc}-visual-viewport-height`,Nc=`--${jc}-visual-viewport-top`;function Pc(e){let{hostElement:t,mode:n,panelSize:r,isOpen:o,surfaceReady:s,setIsOpen:c}=e;a(()=>{Dt(t,Pt(n,r,o))},[t,o,r,n]),a(()=>{if(!o||!s)return;let e=t.ownerDocument.defaultView,n=e?.visualViewport,r=t.shadowRoot?.querySelector(`.${jc}-anchor`);if(!e||!n||!r)return;let i=()=>{r.style.setProperty(Mc,`${n.height}px`),r.style.setProperty(Nc,`${n.offsetTop}px`)},a=0,c=()=>{e.cancelAnimationFrame(a),a=e.requestAnimationFrame(()=>{a=e.requestAnimationFrame(i)})};return i(),n.addEventListener(`resize`,c),n.addEventListener(`scroll`,c),()=>{e.cancelAnimationFrame(a),n.removeEventListener(`resize`,c),n.removeEventListener(`scroll`,c),r.style.removeProperty(Mc),r.style.removeProperty(Nc)}},[t,o,s]),i(()=>{if(n!==`modal`||!o)return;let e=e=>{e.composedPath().some(e=>e instanceof HTMLElement&&e.classList.contains(`${jc}-panel`))||c(!1)};return t.addEventListener(`click`,e),()=>t.removeEventListener(`click`,e)},[t,o,n,c]),i(()=>{if(n!==`drawer`||!o)return;let e=e=>{e.key===`Escape`&&c(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[o,n,c])}const Fc=I.scope(`reducer`);var Ic=class{constructor(e,t){this.messagesSig=e,this.onReconcileNeeded=t,U(this,`active`,null),U(this,`openTextParts`,new Map),U(this,`partSeq`,0),U(this,`replay`,null)}attach(e){this.active=e,this.openTextParts.clear()}detach(){this.active=null,this.replay=null,this.openTextParts.clear()}beginReplay(e,t){let n=Cn();n.id=e.id;let r=Rc(e)||Hn(e)&&(e.status!==`streaming`||Vn(e)),i=e.status===`streaming`&&Vn(e)&&Bn(e);this.replay={baseline:e,shadow:n,chunks:[t],probeContinuation:r,continuationTailReplay:i,liveCatchUp:e.status===`streaming`&&!r},this.attach(n),this.apply(t)}refreshReplayBaseline(){let e=this.replay;if(!e)return null;let t=e.shadow.serverMessageId??e.baseline.serverMessageId,n=this.messagesSig.value,r=n.at(-1),i=r===e.baseline||r?.id===e.baseline.id||t!==void 0&&r?.serverMessageId===t?r:n.find(t=>t===e.baseline)??n.find(n=>n.id===e.baseline.id||t!==void 0&&n.serverMessageId===t);if(!i)return this.detach(),null;if(i===e.baseline)return e;let a=e.baseline;return e.baseline=i,zc(a,i),e.liveCatchUp&&Rc(e.shadow)&&(i.status===`streaming`||Hn(i))?(e.probeContinuation=!1,e.continuationTailReplay=!1,e):(e.probeContinuation=Rc(i)||Hn(i)&&(i.status!==`streaming`||Vn(i)),e.continuationTailReplay=i.status===`streaming`&&Vn(i)&&Bn(i),e.liveCatchUp=i.status===`streaming`&&!e.probeContinuation,e)}refreshActive(){let e=this.active;if(!e)return null;let t=e.serverMessageId,n=this.messagesSig.value,r=n.at(-1),i=r===e||r?.id===e.id||t!==void 0&&r?.serverMessageId===t?r:n.find(t=>t===e)??n.find(n=>n.id===e.id||t!==void 0&&n.serverMessageId===t);if(!i)return this.detach(),null;if(i===e)return e;zc(e,i);let a=Rc(e)&&Hn(i);return i.status!==`streaming`&&!a?(this.detach(),null):(this.replay={baseline:i,shadow:e,chunks:[],probeContinuation:!1,continuationTailReplay:!1,liveCatchUp:!0},e)}promoteReplay(){let{baseline:e,shadow:t}=this.replay;return l(()=>{e.role=t.role,e.serverMessageId=t.serverMessageId,e.operatorInitials=t.operatorInitials,e.status=t.status,t.canceled&&(e.canceled=!0),e.finishReason=t.finishReason,e.errorText=t.errorText,e.suggestions=t.suggestions??e.suggestions,e.partsSig.value=t.partsSig.value,this.messagesSig.value=[...this.messagesSig.value]}),this.replay=null,this.active=e,e}promoteContinuation(e=!1){let{baseline:t,chunks:n}=this.replay,r=Wn(t);return this.replay=null,l(()=>{if(e){let e=t.partsSig.value.findLastIndex(e=>e.kind===`tool`);t.partsSig.value=t.partsSig.value.slice(0,e+1)}t.awaitingContinuation=!1,t.status=`streaming`,t.finishReason=void 0,t.errorText=void 0,t.suggestions=void 0,this.attach(t);for(let e of n)this.apply(e);t.continuationStreaming=r||void 0,this.messagesSig.value=[...this.messagesSig.value]}),t}settleOwnedContinuation(e){let{baseline:t}=this.replay,n=Wn(t);return this.replay=null,l(()=>{t.awaitingContinuation=!1,t.status=`streaming`,t.finishReason=void 0,t.errorText=void 0,t.suggestions=void 0,this.attach(t),this.apply(e),t.continuationStreaming=n||void 0,this.messagesSig.value=[...this.messagesSig.value]}),t}applyResume(e){if(e.type===`start`){let t=(this.replay?.baseline??this.active)?.serverMessageId;t!==void 0&&e.messageId!==void 0&&t!==e.messageId&&this.onReconcileNeeded?.({messageId:t}),this.detach();let n=e.messageId,r=n===void 0?void 0:this.messagesSig.value.find(e=>e.serverMessageId===n||e.id===n);if(r!==void 0)return e.messageMetadata?.senderRole===`visitor`&&r.role===`user`&&(r.status===`pending`||r.status===`error`)&&(r.serverMessageId=n,r.status=`complete`,r.errorText=void 0,r.retryAction=void 0,this.messagesSig.value=[...this.messagesSig.value]),this.beginReplay(r,e),null;let i=e.messageMetadata?.senderRole,a=this.messagesSig.value.at(-1);if(i===void 0&&a?.role===`assistant`&&a.status===`streaming`&&a.serverMessageId===void 0&&!Fn(a))return this.attach(a),this.apply(e),null;let o=Cn();return this.attach(o),this.messagesSig.value=[...this.messagesSig.value,o],this.apply(e),null}if(this.replay){let t=this.refreshReplayBaseline();if(!t)return null;t.chunks.push(e),e.type===`data-control-state`&&(t.baseline.operatorRoutedTurn=e.data.controlMode!==`ai-agent`),this.apply(e);let{baseline:n,shadow:r,probeContinuation:i,continuationTailReplay:a,liveCatchUp:o}=t,s=e.type===`finish`||e.type===`error`||e.type===`abort`;if(i){if(!Uc(n,r,e))return s&&(qc(n,r)&&(n.continuationStreaming=!0,this.messagesSig.value=[...this.messagesSig.value],this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id})),this.detach()),null;let t=Rc(n)&&s?this.settleOwnedContinuation(e):this.promoteContinuation();return s?(t.continuationStreaming&&(e.type===`finish`?this.onReconcileNeeded?.({messageId:t.serverMessageId??t.id}):t.continuationStreaming=!1),this.detach(),t):null}if(a&&Vc(n,r)){let e=this.promoteContinuation(!0);return s?(this.detach(),e):null}if(!o)return s&&this.detach(),null;if(s&&!Fn(n)&&Fn(r)){let e=this.promoteReplay();return this.detach(),e}if(!Bc(n,r))return s&&(this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id}),this.detach()),null;let c=this.promoteReplay();return s?(this.detach(),c):null}let t=this.refreshActive();if(!t)return null;if(this.replay)return this.applyResume(e);if(this.apply(e),e.type===`finish`||e.type===`error`||e.type===`abort`){let n=t;return n.continuationStreaming&&(e.type===`finish`?this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id}):n.continuationStreaming=!1),this.detach(),n}return null}ensureTextPart(e,t,n){let r=`${t}:${n}`,i=this.openTextParts.get(r);if(i)return i;let a={kind:t,id:`${n}#${this.partSeq++}`,textSig:f(``),doneSig:f(!1)};return this.openTextParts.set(r,a),Yc(e,a),a}apply(e){let t=this.active;if(t)switch(e.type){case`start`:{e.messageId&&(t.serverMessageId=e.messageId);let n=e.messageMetadata;n?.senderRole===`operator`?(t.role=`operator`,n.operatorInitials&&(t.operatorInitials=n.operatorInitials)):n?.senderRole===`visitor`&&(t.role=`user`);return}case`finish-step`:this.openTextParts.clear();return;case`start-step`:Yc(t,{kind:`step-start`,id:`ss-${this.partSeq++}`});return;case`finish`:Fc.debug(`finish`,{reason:e.finishReason,canContinue:e.canContinue}),t.status=`complete`,t.retryAction=void 0,e.finishReason&&(t.finishReason=e.finishReason),this.bumpDone(t);return;case`error`:Fc.warn(`stream error chunk`,{errorText:e.errorText}),t.status=`error`,t.errorText=e.errorText,this.bumpDone(t);return;case`abort`:Fc.debug(`stream abort chunk (canceled)`),t.status=`complete`,t.canceled=!0,t.retryAction=void 0,this.bumpDone(t);return;case`text-start`:this.ensureTextPart(t,`text`,e.id);return;case`text-delta`:{let n=this.ensureTextPart(t,`text`,e.id);n.textSig.value+=e.delta;return}case`text-end`:this.ensureTextPart(t,`text`,e.id).doneSig.value=!0;return;case`reasoning-start`:this.ensureTextPart(t,`reasoning`,e.id).doneSig.value=!1;return;case`reasoning-delta`:{let n=this.ensureTextPart(t,`reasoning`,e.id);n.textSig.value+=e.delta;return}case`reasoning-end`:this.ensureTextPart(t,`reasoning`,e.id).doneSig.value=!0;return;case`tool-input-start`:case`tool-input-delta`:case`tool-input-available`:case`tool-input-error`:case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:Zc(t,e);return;case`file`:Yc(t,{kind:`file`,url:e.url,mediaType:e.mediaType});return;case`source-url`:Xc(t,{kind:`source`,sourceId:e.sourceId,url:e.url,title:e.title});return;case`source-document`:Xc(t,{kind:`source`,sourceId:e.sourceId,title:e.title,filename:e.filename,mediaType:e.mediaType});return;case`data-suggestions`:t.suggestions=tn(e.data);return;case`data-control-state`:t.operatorRoutedTurn=e.data.controlMode!==`ai-agent`;return;case`data-memory-compaction-state`:return;default:}}bumpDone(e){l(()=>{e.partsSig.value=[...e.partsSig.value],this.messagesSig.value.includes(e)&&(this.messagesSig.value=[...this.messagesSig.value])})}};const Lc={"input-streaming":0,"input-available":1,"approval-requested":2,"approval-responded":3,"output-available":4,"output-denied":4,"output-error":4};function Rc(e){return e.awaitingContinuation===!0||e.continuationStreaming===!0||e.retryAction?.kind===`continue-assistant`}function zc(e,t){e.canceled&&(t.canceled=!0),!(!Rc(e)||t.status!==`streaming`&&!Hn(t))&&(t.awaitingContinuation??(t.awaitingContinuation=e.awaitingContinuation),t.continuationStreaming??(t.continuationStreaming=e.continuationStreaming),t.retryAction===void 0&&(t.retryAction=e.retryAction))}function Bc(e,t){let n=e.partsSig.value,r=t.partsSig.value;return e.role!==t.role||r.length<n.length?!1:n.every((e,t)=>Hc(e,r[t]))}function Vc(e,t){let n=e.partsSig.value,r=n.findLastIndex(e=>e.kind===`tool`),i=new Set(n.slice(0,r+1).flatMap(e=>e.kind===`tool`?[e.toolCallId]:[])),a=t.partsSig.value.filter(e=>e.kind!==`tool`||!i.has(e.toolCallId)),o=n.slice(r+1);return a.length<o.length?!1:o.every((e,t)=>Hc(e,a[t]))}function Hc(e,t){switch(e.kind){case`text`:case`reasoning`:return t?.kind===e.kind&&t.textSig.value.startsWith(e.textSig.value);case`step-start`:return t?.kind===`step-start`;case`tool`:{if(t?.kind!==`tool`||t.toolCallId!==e.toolCallId||!er(t.toolName,e.toolName)||Lc[t.stateSig.value]<Lc[e.stateSig.value])return!1;let n=e.approvalSig.value?.approved;return n===void 0||t.approvalSig.value?.approved===n}case`file`:return t?.kind===`file`&&t.url===e.url&&t.mediaType===e.mediaType;case`source`:return t?.kind===`source`&&t.sourceId===e.sourceId&&t.url===e.url&&t.title===e.title&&t.filename===e.filename&&t.mediaType===e.mediaType;default:return e}}function Uc(e,t,n){return Wc(e,n)||!Gc(e,t)?!0:n.type!==`finish`&&n.type!==`error`&&n.type!==`abort`?!1:Bn(t)||e.awaitingContinuation===!0&&n.type!==`finish`?!0:e.awaitingContinuation===!0&&t.partsSig.value.every(e=>e.kind===`step-start`)}function Wc(e,t){if(t.type!==`tool-output-available`&&t.type!==`tool-output-error`&&t.type!==`tool-output-denied`)return!1;let n=e.partsSig.value.find(e=>e.kind===`tool`&&e.toolCallId===t.toolCallId);return n!==void 0&&Lc[n.stateSig.value]<4}function Gc(e,t){let n=t.partsSig.value;if(n.length===0)return!0;let r=e.partsSig.value;return r.some((e,t)=>n.every((e,n)=>Kc(r[t+n],e)))}function Kc(e,t){switch(t.kind){case`text`:case`reasoning`:return e?.kind===t.kind&&e.textSig.value.startsWith(t.textSig.value);case`step-start`:return e?.kind===`step-start`;case`tool`:return e?.kind===`tool`&&e.toolCallId===t.toolCallId&&(t.toolName===`tool`||er(e.toolName,t.toolName));case`file`:return e?.kind===`file`&&e.url===t.url&&e.mediaType===t.mediaType;case`source`:return e?.kind===`source`&&e.sourceId===t.sourceId&&e.url===t.url&&e.title===t.title&&e.filename===t.filename&&e.mediaType===t.mediaType;default:return t}}function qc(e,t){if(Rc(e)||!Hn(e))return!1;let n=new Set(e.partsSig.value.filter(e=>e.kind===`tool`).map(e=>e.toolCallId));return!t.partsSig.value.some(e=>e.kind===`tool`&&n.has(e.toolCallId))}function Jc(e,t,n,r){let i=e.partsSig.value.find(e=>e.kind===`tool`&&e.toolCallId===t);if(i)return r&&(i.dynamic=!0),i;let a={kind:`tool`,toolCallId:t,toolName:n??`tool`,dynamic:r?!0:void 0,inputPartialSig:f(``),inputSig:f(void 0),outputSig:f(void 0),errorSig:f(void 0),stateSig:f(`input-streaming`),approvalSig:f(void 0)};return Yc(e,a),a}function Yc(e,t){e.partsSig.value=[...e.partsSig.value,t]}function Xc(e,t){e.partsSig.value.some(e=>e.kind===`source`&&e.sourceId===t.sourceId)||Yc(e,t)}function Zc(e,t){switch(t.type){case`tool-input-start`:Jc(e,t.toolCallId,t.toolName,t.dynamic);return;case`tool-input-delta`:{let n=Jc(e,t.toolCallId);n.inputPartialSig.value+=t.inputTextDelta;return}case`tool-input-available`:{let n=Jc(e,t.toolCallId,t.toolName,t.dynamic);n.inputSig.value=t.input,n.stateSig.value=`input-available`;return}case`tool-input-error`:{let n=Jc(e,t.toolCallId,t.toolName,t.dynamic);n.inputSig.value=t.input,n.errorSig.value=t.errorText,n.stateSig.value=`output-error`;return}case`tool-approval-request`:{let n=Jc(e,t.toolCallId,t.toolName);n.approvalSig.value={id:t.approvalId},n.stateSig.value=`approval-requested`;return}case`tool-output-available`:{let n=Jc(e,t.toolCallId,void 0,t.dynamic);n.outputSig.value=t.output,n.stateSig.value=`output-available`;return}case`tool-output-error`:{let n=Jc(e,t.toolCallId,void 0,t.dynamic);n.errorSig.value=t.errorText,n.stateSig.value=`output-error`;return}case`tool-output-denied`:{let n=Jc(e,t.toolCallId);n.stateSig.value=`output-denied`;return}default:return}}const Qc=1e3;async function $c(e){let t=Qc,n=!1,r=!1,i=!1,a=()=>{i||e.signal.aborted||(i=!0,e.onInitialBoundaryReady())};for(;!e.signal.aborted;){let o,s=`held`;try{s=await e.connect(()=>{if(e.signal.aborted)return;o=e.now();let t=n||r;n=!0,r=!1,i?t&&e.backfill():a()})}catch{}if(e.signal.aborted||(!n&&o===void 0&&(r=!0,a()),s===`unavailable`))return;o!==void 0&&e.now()-o>=1e3&&(t=Qc),await e.sleep(t),t=Math.min(t*2,15e3)}}function el(e){let{activated:t,conversationReady:n,conversationIdSig:r,messagesSig:a,optionsRef:o,transport:c,visitorId:l,adoptControlStateChunk:u,adoptMemoryCompactionStateChunk:d,settleSuggestions:f,recordConversationReply:p,transcriptRecoverySig:m,beginConversationTranscript:h,commitConversationTranscript:g,onReplyLanded:_,runCancellation:v,canContinueRef:y,setCanSend:b,feedback:x,bus:S,loadInitialThread:C,shouldReconcileOnConnect:w}=e,T=s(0);i(()=>{if(!t||!n||!r.value)return;let e=r.value,i=new AbortController,s=e=>{},E=new Ic(a,e=>s(e));c.primeIdentity(l,e);let D=!1,O=!1,k,A=!1,j,M=0,ee=y.current,te,N,ne=Date.now(),re,P=!1,F=!1,ie=(t,n,r)=>{if(!Fn(t))return;let i=a.value.findLast(e=>!e.ephemeral),s=t.serverMessageId??t.id;if(!(i&&(i.serverMessageId??i.id)!==s))return Pn(a.value,t,e,o.current.strings.newConversation,n,r)},ae=(e,t,n,r)=>{let i=ie(e,t,r);if(!i)return;let a=`${e.serverMessageId??e.id}:${n}:${i.preview??``}`;a!==N&&(N=a,c.publishConversation({...i,hasUnread:!0},!0))},I,L=()=>{I&&(clearTimeout(I.timer),I=void 0)},oe=()=>{let e=I;if(!e)return;clearTimeout(e.timer),I=void 0;let t=a.value.find(t=>(t.serverMessageId??t.id)===e.replyId);(t?.role===`assistant`||t?.role===`operator`)&&ae(t,e.canContinue,e.generation,e.activityAt)},se=(e,t,n,r)=>{L(),I={replyId:e.serverMessageId??e.id,canContinue:t,generation:n,activityAt:r,timer:setTimeout(oe,120)}},ce=(e,t,n,r=Date.now(),i=!0)=>{L();let a=ie(e,t,r);if(!a)return;let o=`${e.serverMessageId??e.id}:${n}`;o!==te&&(te=o,p(a),i&&re&&(P=!0))},le=(e,t)=>{(e||!v.localSendRef.current)&&v.settle(t),e&&_()},ue=(e,t=[],n=!1,r,i=ee,s=M,c=Date.now(),l=!0)=>{let u=o.current;if(e.canceled){ce(e,i,s,c,l),le(n,r);return}let d=!0,p=e.status===`error`;switch(or(e,p)){case`drop`:a.value=a.value.filter(t=>t!==e),d=!1;break;case`complete-operator-routed`:e.status=`complete`,n&&(x.play(`messageReceived`),Ec(S,u,`assistant`,Nn(e)));break;case`error`:if(e.status=`error`,e.errorText=u.strings.errorGeneric,n){x.play(`error`);let e=Error(p?`stream error chunk`:`empty reply`);S.emit(`error`,e),u.onError?.(e)}break;case`complete`:e.status=`complete`,n&&(x.play(`messageReceived`),Ec(S,u,`assistant`,Nn(e))),f(e,t);break}d&&ce(e,i,s,c,l),le(n,r)},de=t=>{if(i.signal.aborted||r.value!==e)return;if(u(t),d?.(t),t.type===`start`){oe();let n=t.messageId===void 0?void 0:a.value.find(e=>e.serverMessageId===t.messageId||e.id===t.messageId);A=n!==void 0&&n.status!==`streaming`;let r=j?.senderRole===`visitor`?j.messageId:void 0;if(j={messageId:t.messageId,senderRole:t.messageMetadata?.senderRole},M+=1,ne=Date.now(),N=void 0,D=t.messageMetadata?.senderRole===void 0,O=!1,k=D?t.messageMetadata?.runId:void 0,D){let n=t.messageId!==void 0&&a.value.some(e=>e.serverMessageId===t.messageId||e.id===t.messageId),i=a.value.at(-1),o=t.messageId!==void 0&&(i?.serverMessageId===t.messageId||i?.id===t.messageId),s=v.localSendRef.current&&(!n||o)&&i?.role===`assistant`&&i.status===`streaming`&&(o||i.serverMessageId===void 0&&i.partsSig.value.length===0);O=v.captureStart(e,t,s,r)}}let n=D&&(t.type===`finish`||t.type===`error`||t.type===`abort`),s=n?k:void 0,c=n&&(O||v.ownsLocalRun(s)),l=M,f=A;t.type===`finish`&&t.canContinue!==void 0&&(ee=t.canContinue);let p=ee;n&&(D=!1,O=!1,k=void 0);let m=E.applyResume(t),h=j?.messageId,g=h===void 0?void 0:a.value.find(e=>e.serverMessageId===h||e.id===h);A&&j?.senderRole!==`visitor`&&(m!==null||g?.status===`streaming`)&&(A=!1,f=!1);let _=!A&&(g?.role===`assistant`||g?.role===`operator`);if(t.type===`text-delta`&&_&&se(g,ee,M,ne),t.type===`text-end`&&(L(),_&&ae(g,ee,M,ne)),t.type===`finish`&&t.canContinue===!1&&b(!1),!m){n&&(c||!v.localSendRef.current)&&v.settle(s);return}if(m.role===`operator`){f||(x.play(`messageReceived`),Ec(S,o.current,`operator`,Nn(m))),ce(m,p,l,ne),A=!1,n&&(c||!v.localSendRef.current)&&v.settle(s);return}m.role===`assistant`&&(ue(m,[],c,s,p,l,ne),A=!1)},fe=async t=>{let n=M,o=await c.loadConversation(e,t?{ids:[t]}:void 0).catch(()=>null);if(i.signal.aborted||r.value!==e||!o)return!1;o.controlState&&u({type:`data-control-state`,data:o.controlState});let s=a.value.at(-1),l=n===M&&(t===void 0||s!==void 0&&(s.serverMessageId===t||s.id===t));if(o.messages.length===0)return!0;l&&(ee=o.canContinue,b(ee));let d=a.value,p=t===void 0?d.at(-1):d.find(e=>e.serverMessageId===t||e.id===t),{messages:m,changed:h}=Zn(d,An(o.messages));if(!h)return!0;a.value=m;let g=t===void 0?m.at(-1):m.find(e=>e.serverMessageId===t||e.id===t),_=p!==void 0&&g!==void 0&&(p.id===g.id||p.serverMessageId!==void 0&&p.serverMessageId===g.serverMessageId),y=g!==void 0&&g.status!==`streaming`&&(!_||p?.status===`streaming`),x=_&&p?.status===`streaming`?Date.now():g?.createdAt;return l&&y&&g.role===`assistant`?ue(g,g.suggestions??[],v.localSendRef.current,void 0,o.canContinue,n,x,!1):l&&y&&g.role===`operator`?ce(g,o.canContinue,n,x,!1):l&&g?.role===`assistant`&&g.status!==`streaming`&&f(g,g.suggestions??[]),!0},pe=new Set;s=({messageId:e})=>{if(pe.has(e)||!a.value.some(t=>t.serverMessageId===e||t.id===e))return;pe.add(e);let t=()=>pe.delete(e);fe(e).then(t,t)};let me=(t=!1)=>{if(i.signal.aborted||r.value!==e){P=!1;return}if(re){P=!0;return}let n=t?C(e)??(w()?fe():void 0):fe();if(!n)return;h(e),re=n;let a=(t=!1)=>{if(re===n){if(re=void 0,P){P=!1,me();return}t&&g(e)}};n.then(a,()=>a(!1))},R=m.subscribe(e=>{e<=T.current||(T.current=e,F&&me())});return $c({signal:i.signal,now:()=>performance.now(),sleep:e=>zt(e,i.signal),connect:e=>c.connectResumeStream({signal:i.signal,onChunk:de,onConnected:e}),onInitialBoundaryReady:()=>{F=!0,me(!0)},backfill:()=>me()}),()=>{i.abort(),L(),R(),E.detach()}},[t,n,r,r.value,l,c,u,d,f,p,m,h,g,_,v,y,b,a,S,x,C,w])}function tl(e){let{transport:t,setStreaming:n}=e,i=s(),a=s(),c=s(!1),l=s(),u=s(!1),d=s(new Map),f=s(new Set),p=r((e,n)=>{let r=`${e}:${n}`;l.current!==r&&(l.current=r,t.cancelTurn(e,n))},[t]),m=r(e=>{i.current=void 0,a.current=e,c.current=!1,l.current=void 0,u.current=!0,n(!0)},[n]),h=r((e,t)=>{d.current.set(e,{messageId:t})},[]),g=r(e=>{e!==void 0&&(f.current.add(e),f.current.size>32&&f.current.delete(f.current.values().next().value)),(e===void 0||i.current?.runId===e)&&(i.current=void 0,a.current=void 0,c.current=!1,u.current=!1,n(!1))},[n]),_=r((e,t)=>a.current===e?(a.current=void 0,t.runId?(i.current={conversationId:t.conversationId,runId:t.runId},n(!0),c.current&&p(t.conversationId,t.runId),!0):(g(),!0)):t.runId&&i.current?.runId===t.runId?(i.current={conversationId:t.conversationId,runId:t.runId},c.current&&p(t.conversationId,t.runId),!0):!1,[p,n,g]),v=r((e,t)=>{let r=d.current.get(e);return r?(d.current.delete(e),!t.runId||f.current.has(t.runId)?!0:r.runId===void 0?u.current||a.current?!0:(i.current={conversationId:t.conversationId,runId:t.runId},a.current=void 0,c.current=!1,l.current=void 0,u.current=!0,n(!0),!0):(r.runId===t.runId&&i.current?.runId===t.runId&&(i.current={conversationId:t.conversationId,runId:t.runId},c.current&&p(t.conversationId,t.runId)),!0)):!1},[p,n]),y=r(e=>a.current===e?(g(),!0):!1,[g]),b=r(e=>{let t=d.current.get(e);return t?(d.current.delete(e),t.runId===void 0):!1},[]),x=r((e,t,r,o)=>{let s=t.messageMetadata?.runId;if(t.messageMetadata?.senderRole!==void 0||typeof s!=`string`||!s||f.current.has(s))return!1;if(i.current?.runId===s)return u.current;if(u.current)return i.current||!r?!1:(a.current=void 0,i.current={conversationId:e,runId:s},n(!0),c.current&&p(e,s),!0);let m=[...d.current.values()].filter(e=>e.runId===void 0).find(e=>e.messageId===o);return m?(m.runId=s,i.current={conversationId:e,runId:s},a.current=void 0,c.current=!1,l.current=void 0,u.current=!0,n(!0),!0):(a.current=void 0,i.current={conversationId:e,runId:s},n(!0),c.current&&p(e,s),u.current)},[p,n]),S=r(e=>typeof e==`string`&&i.current?.runId===e&&u.current,[]),C=r(()=>{let e=i.current;if(e)return c.current=!0,p(e.conversationId,e.runId),!0;let t=a.current;return t?(c.current=!0,t.then(e=>{e.runId&&p(e.conversationId,e.runId)}).catch(()=>void 0),!0):!1},[p]);return o(()=>({localSendRef:u,begin:m,beginRouted:h,acceptAck:_,acceptRoutedAck:v,reject:y,rejectRouted:b,captureStart:x,ownsLocalRun:S,settle:g,stop:C}),[_,v,m,h,x,S,y,b,g,C])}const nl=I.scope(`send`);function rl(e,t,n,r,i,a=!0){e.publishConversation({...Pn(t,n,r,i,a),hasUnread:!1},!0)}function il(e,t){return e.id===t.id||(e.serverMessageId??e.id)===(t.serverMessageId??t.id)}function al(e){return e.findLast(e=>!e.ephemeral&&e.role!==`system`&&(e.role===`user`||e.status!==`streaming`||Fn(e)))}function ol(e,t,n,r,i){let a=al(t);!a||a.role!==`user`||!il(a,n)||rl(e,t,a,r,i)}function sl(e){return!(e instanceof Vt)||e.code===`network`||e.status===void 0||e.status===202||e.status===408||e.status===425||e.status===429||e.status>=500&&e.status<600}function cl(e){let{transport:t,messagesSig:n,conversationIdSig:i,options:a,bus:o,feedback:s,persistence:c,visitorId:l,adoptConversationId:u,applyControlState:d,setCanSend:f,settleSuggestions:p,runCancellation:m}=e,h=r(()=>{let e=i.value??ct();return i.value||(i.value=e,c.saveConversationId(e)),e},[i,c]);return{sendAiTurn:r(async({continueExisting:e,turn:r})=>{let g=h(),_=n.value.at(-1),v=r?[r]:jn(n.value,e),y=v[0],b=nn({messages:v.map(Mn),conversationId:g,visitorId:l,userPrefs:c.loadUserPrefs()}),x=t.sendTurn(b);m.begin(x);try{let r=await x;if(i.value!==g||!m.acceptAck(x,r))return!1;if(u(r.conversationId),r.runId&&y?.role===`user`&&ol(t,n.value,y,r.conversationId,a.strings.newConversation),!r.runId){let o=await t.loadConversation(r.conversationId).catch(()=>null);if(i.value!==r.conversationId)return!0;if(o){o.controlState&&d(o.controlState),f(o.canContinue);let i=An(o.messages),{messages:s,changed:c}=Zn(n.value,i);c&&(n.value=s);let l=i.findLast(e=>!e.ephemeral&&e.role!==`system`),u=al(n.value);u&&l&&il(u,l)&&rl(t,n.value,u,r.conversationId,a.strings.newConversation,o.canContinue);let m=_?n.value.find(e=>e.id===_.id&&e.role===`assistant`&&e.status!==`streaming`):void 0;m&&p(m,m.suggestions??[]),!e&&_?.role===`assistant`&&n.value.includes(_)&&_.serverMessageId===void 0&&!Fn(_)&&(n.value=n.value.filter(e=>e!==_))}else _?.role===`assistant`&&n.value.includes(_)&&(_.status=`error`,_.errorText=a.strings.errorGeneric,e?_.retryAction={kind:`continue-assistant`,messageId:_.serverMessageId??_.id}:_.retryAction=y?.role===`user`?{kind:`resend-user`,messageId:y.id}:null,n.value=[...n.value])}return!0}catch(c){if(i.value!==g)return!1;if(!m.reject(x))return y?.role===`user`&&ol(t,n.value,y,g,a.strings.newConversation),!0;let l=Bs(c,a.strings),u=sl(c),h=r?.role===`assistant`?r:n.value.at(-1);if(e&&h?.role===`assistant`&&c instanceof Vt&&c.status===409){let e=h.serverMessageId??h.id,r=await t.loadConversation(g,{ids:[e]}).catch(()=>null);if(i.value!==g)return!1;if(r){r.controlState&&d(r.controlState),f(r.canContinue);let t=An(r.messages),i=t.find(t=>(t.serverMessageId??t.id)===e);if(i&&Qn(h,i)){let{messages:r,changed:i}=Zn(n.value,t),a=r.find(t=>(t.serverMessageId??t.id)===e);if(i&&a&&a!==h)return a.awaitingContinuation=!1,a.continuationStreaming=void 0,a.retryAction=null,n.value=r,a.status!==`streaming`&&p(a,a.suggestions??[]),!0}}if(!n.value.includes(h)||h.status!==`streaming`)return!1;h.continuationStreaming=!0}if(e&&h?.role===`assistant`)h.status=`error`,h.errorText=l,h.retryAction=u?{kind:`continue-assistant`,messageId:h.serverMessageId??h.id}:null,n.value=[...n.value];else if(_?.role===`assistant`&&n.value.includes(_)){_.status=`error`,_.errorText=l;let e=v[0];_.retryAction=u&&e?.role===`user`?{kind:`resend-user`,messageId:e.id}:null,n.value=[...n.value]}else{let e=Cn();e.status=`error`,e.errorText=l;let t=v[0];e.retryAction=u&&t?.role===`user`?{kind:`resend-user`,messageId:t.id}:null,n.value=[...n.value,e]}return s.play(`error`),o.emit(`error`,c),a.onError?.(c),!1}},[t,n,a,o,s,c,l,u,d,f,p,h,m]),sendRoutedTurn:r(async e=>{let r=h();e.status=`pending`,e.errorText=void 0,e.retryAction=void 0,n.value.includes(e)&&(n.value=[...n.value]);let d=nn({messages:[Mn(e)],conversationId:r,visitorId:l,userPrefs:c.loadUserPrefs()}),f=t.sendTurn(d);m.beginRouted(f,e.id);try{let o=await f;return i.value===r?m.acceptRoutedAck(f,o)?(u(o.conversationId),ol(t,n.value,e,o.conversationId,a.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value])),!0):!1:(m.rejectRouted(f),!1)}catch(c){let l=m.rejectRouted(f);if(i.value!==r)return!1;if(!l)return ol(t,n.value,e,r,a.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value])),!0;if(e.status!==`pending`)return ol(t,n.value,e,r,a.strings.newConversation),!0;nl.debug(`operator-routed send failed`,{error:c});let u=c instanceof Error?c:Error(String(c));return e.status=`error`,e.errorText=Bs(c,a.strings),e.retryAction=sl(c)?{kind:`resend-user`,messageId:e.id}:null,n.value.includes(e)&&(n.value=[...n.value]),s.play(`error`),o.emit(`error`,u),a.onError?.(u),!1}},[t,n,a,o,s,c,l,u,h,m])}}const ll=I.scope(`unread`);function ul(e){let{transport:t,options:n,conversationIdSig:a,isConversationVisibleRef:o,activated:c,conversationReady:l}=e,u=m(!1),d=m(0),f=s([]),p=s(),h=s(!1),g=r(()=>{let e=a.value,t=o.current()&&p.current===e?e:void 0;u.value=f.current.some(e=>e.hasUnread&&e.conversationId!==t)},[a,u,o]),_=r(e=>{let t=a.value,n=f.current.find(e=>e.conversationId===t),r=pn(f.current,e),i=r.find(e=>e.conversationId===t),o=e.type===`snapshot`&&t!==void 0&&i?.hasUnread===!0&&p.current===t&&n!==void 0&&n.lastMessageAt!==i.lastMessageAt;o&&(p.current=void 0),f.current=r,g(),o&&(d.value+=1)},[a,g,d]),v=r(()=>{if(g(),!o.current())return;let e=a.value;if(!e||p.current!==e)return;let n=f.current.find(t=>t.conversationId===e);n?.hasUnread&&t.markRead(e,n.lastMessageAt)},[a,o,g,t]),y=r(e=>{a.value===e&&(p.current=void 0,g())},[a,g]),b=r(e=>{a.value===e&&(p.current=e,v())},[a,v]),x=r(e=>p.current===e,[]),S=r((e=!1)=>{n.modules.list.some(e=>e.layout===`chat`)&&(h.current||(h.current=!0,t.listConversations({limit:50},e).then(t=>{e||_({type:`snapshot`,result:t,requestedRevision:0}),v()}).catch(e=>ll.debug(`refreshUnread failed (non-fatal)`,{err:e})).finally(()=>{h.current=!1})))},[_,v,n.modules,t]),C=r(e=>{let n=e.conversationId,r=o.current()&&a.value===n&&p.current===n,i=f.current.find(e=>e.conversationId===n),s=r&&(i?.lastMessageAt!==e.lastMessageAt||i.hasUnread);t.publishConversation({...e,hasUnread:!r},!0),s&&t.markRead(n,e.lastMessageAt)},[a,o,t]);i(()=>t.subscribeConversationChanges(_),[_,t]);let w=s(!1);return i(()=>{!c||!l||w.current||(w.current=!0,S())},[c,l,S]),i(()=>{if(!c)return;let e=()=>{document.visibilityState===`visible`&&(v(),S(!0))};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[c,v,S]),{hasUnreadSig:u,transcriptRecoverySig:d,markVisibleConversationRead:v,beginConversationTranscript:y,commitConversationTranscript:b,isConversationTranscriptCommitted:x,recordConversationReply:C}}const dl=I.scope(`settings`);function fl(e){let{options:t,persistence:n,transport:a,feedback:o,hostElement:s,bus:l}=e,u=n.loadUserPrefs(),[d,f]=c(()=>u.locale??t.locale),[p,m]=c(()=>u.themeMode??t.themeMode),[h,g]=c(()=>u.textSize??t.textSize),_=r(e=>{n.patchUserPrefs(e),a.saveUserPrefs(n.loadUserPrefs()).catch(e=>dl.warn(`saveUserPrefs failed`,{err:e}))},[n,a]);i(()=>{u.soundMuted!==void 0&&o.setMuted(u.soundMuted)},[]),i(()=>{s.dataset.theme=p},[s,p,t]),i(()=>{s.dataset.textSize=h},[s,h,t]),i(()=>{let e=!0;return o.mutedSig.subscribe(t=>{if(e){e=!1;return}_({soundMuted:t})})},[o,_]);let v=we(d,t.availableLocales,t.defaultLocale);return i(()=>{a.setLocale(v)},[a,v]),i(()=>{s.dir=E(v)?`rtl`:`ltr`},[s,v]),i(()=>{v!==d&&f(v)},[v,d]),{activeLocale:d,activeThemeMode:p,activeTextSize:h,effectiveLocale:v,setActiveLocale:f,setActiveThemeMode:m,setActiveTextSize:g,patchAndSync:_,handleLocaleChange:r(e=>{dl.info(`localeChange`,{locale:e}),f(e),_({locale:e}),l.emit(`localeChange`,e)},[_,l]),handleThemeChange:r(e=>{dl.info(`themeChange`,{mode:e}),m(e),s.dataset.theme=e,_({themeMode:e}),l.emit(`themeChange`,e)},[s,_,l]),handleTextSizeChange:r(e=>{dl.info(`textSizeChange`,{size:e}),g(e),s.dataset.textSize=e,_({textSize:e}),l.emit(`textSizeChange`,e)},[s,_,l]),handleSoundToggle:r(()=>{o.toggleMuted();let e=o.mutedSig.value;dl.info(`soundToggle`,{muted:e}),l.emit(`soundToggle`,{muted:e})},[o,l])}}const $=I.scope(`app`),pl=b.cssPrefix;function ml(e,t){return wn({...e,text:D(t,e.text)})}function hl({options:e,hostElement:t,bus:n}){let u=e.aiAgentDeploymentId;if(!u)throw Error(`aiAgentDeploymentId is required`);let[d]=c(()=>dt(e.widgetId,e.storage,e.aiAgentDeploymentId)),[f]=c(()=>d.getVisitorId()),h=d.loadUserPrefs(),v=m(d.loadConversationId()),y=s(v.value!==void 0),b=m(v.value??``),x=m([]),[S,C]=c(!1),w=s(),[T,E]=c([]);function O(){let t=e.modules.list,n=new Set(t.map(e=>e.id)),r=d.loadActiveModule();return r&&n.has(r)?r:t[0]?.id??``}function k(){return e.modules.list.find(e=>e.layout===`chat`)?.id}function A(){let t=k();return t?e.modules.list.length===1||M.sig.value.activeTab===t:!1}let j=s();if(!j.current){let t=e.modules.list.map(e=>e.id),n=d.loadActiveModule()??t[0]??``;j.current=Ms(n,n?[...t,n]:t,e=>d.saveActiveModule(e))}let M=j.current,ee=p(()=>M.sig.value.activeTab).value,te=p(()=>v.value).value,[N,ne]=c(!1),[re,P]=c(null),[F,ie]=c(!1),ae=e.mode===`standalone`||e.mode===`inline`,I=s(It(e,Lt(),d.loadPanelOpen(),d.loadPanelSize())),[L,oe]=c(I.current.panelOpen),[se,ce]=c(I.current.panelOpen),le=s(),ue=s(),de=s(!1),fe=s(void 0);i(()=>{L&&ce(!0)},[L]);let pe=s(!1),[me,R]=c(!1),{dismissed:he,dismissCallout:ge}=kc({callout:e.launcher.callout,persistence:d}),_e=e.launcher.callout?.persistent??!0,ve=r(()=>{$.info(`calloutDismiss`),n.emit(`calloutDismiss`,void 0),ge()},[n,ge]),[z,ye]=c(I.current.panelSize),be=s(!1),[xe,Se]=c(`chat`),Ce=s(()=>!1);Ce.current=()=>L&&xe===`chat`&&!document.hidden&&A();let[we,Te]=c(!0),Ee=s(we);Ee.current=we;let[De,Oe]=c(!1),ke=s(De);ke.current=De;let Ae=s(null),[je,Ne]=c(!1),[Pe,Ie]=c(null),[Le,Re]=c([]),ze=s(e.strings),Be=s(e);Be.current=e;let[Ve,He]=c(void 0),[Ue,We]=c(void 0),[Ge,Ke]=c(()=>d.loadSidebarCollapsed()??!1),[qe,Je]=c({}),[B]=c(()=>new yn({agentApiBaseUrl:e.agentApiBaseUrl,dataApiBaseUrl:e.dataApiBaseUrl,auth:Rt({publicKey:e.publicKey,aiAgentDeploymentId:u,publicKeyHeader:`x-public-key`}),endpoints:e.endpoints})),[Ye]=c(()=>new br(e.sound,e.haptics)),Xe=tl({transport:B,setStreaming:Oe}),{activeLocale:Ze,activeThemeMode:Qe,activeTextSize:$e,effectiveLocale:et,setActiveLocale:tt,setActiveThemeMode:nt,setActiveTextSize:rt,patchAndSync:it,handleLocaleChange:at,handleThemeChange:ot,handleTextSizeChange:st,handleSoundToggle:lt}=fl({options:e,persistence:d,transport:B,feedback:Ye,hostElement:t,bus:n}),{controlModeSig:ut,assignedOperatorInitialsSig:ft,operatorAvailableSig:pt,applyControlState:ht,adoptControlStateChunk:gt,requestOperator:_t,cancelOperatorRequest:vt}=Ac({transport:B,conversationIdSig:v}),yt=m(new Map),bt=r(e=>{if(e.type!==`data-memory-compaction-state`)return;let t=v.value;if(!t)return;let n=en(e.data);if(!n)return;let r=yt.value.get(t);if(r&&(n.postFinishSequence<r.postFinishSequence||n.postFinishSequence===r.postFinishSequence&&(r.status===`ready`||r.status===n.status)))return;let i=new Map(yt.value);i.set(t,n),yt.value=i},[v,yt]),{hasUnreadSig:xt,transcriptRecoverySig:St,markVisibleConversationRead:Ct,beginConversationTranscript:wt,commitConversationTranscript:Tt,isConversationTranscriptCommitted:Et,recordConversationReply:Dt}=ul({transport:B,options:e,conversationIdSig:v,isConversationVisibleRef:Ce,activated:se,conversationReady:N});i(()=>{Ct()},[ee,L,xe,te,Ct]),i(()=>{Ye.update(e.sound,e.haptics)},[Ye,e.sound,e.haptics]),i(()=>()=>Ye.destroy(),[Ye]),i(()=>{be.current||!e.size.initialSize||(be.current=!0,!d.loadPanelSize()&&ye(Ft(e.mode,e.size,Lt())))},[e.mode,e.size,d]),i(()=>{if(!N||pe.current)return;pe.current=!0;let t=It(e,Lt(),d.loadPanelOpen(),d.loadPanelSize());oe(t.panelOpen),ye(t.panelSize)},[N,e,d]);let Ot=s(null);i(()=>{N&&M.reconcile(e.modules.list.map(e=>e.id),O())},[N,e.modules.list,M]);let kt=r(e=>{!e||e.length===0||(x.value=e.map(e=>ml(e,ze.current)))},[x]),Mt=s(null),Pt=r(async e=>{try{let{formSubmissions:t}=await(e?B.bootstrap(e):Mt.current??B.bootstrap()),n=new Map;return t.forEach((e,t)=>n.set(e.formId,t)),t.filter((e,t)=>!e.skipped||n.get(e.formId)===t).map((e,t)=>({key:`wire:${e.formId}:${e.createdAt??t}`,formId:e.formId,outcome:e.skipped?`skipped`:`submitted`,createdAt:Yt(e.createdAt),values:e.values}))}catch(e){return $.debug(`bootstrap failed — no form markers (non-fatal)`,{err:e}),[]}},[B]),zt=s(0),Bt=s(0),Vt=r(e=>{if(e===v.value)return;let t=v.value;Bt.current++,C(!1),t&&(d.saveDraft(e,d.loadDraft(t)),d.saveDraft(t,``),d.saveMessageQueue(e,d.loadMessageQueue(t)),d.saveMessageQueue(t,[])),v.value=e,d.saveConversationId(e),B.primeIdentity(void 0,e),$.info(`conversation rebound`,{previous:t,current:e}),t&&n.emit(`conversationRebound`,{previous:t,current:e})},[n,v,d,B]),Ht=r((e,t)=>{let n=[...e.map(e=>e.createdAt),...t.map(e=>e.createdAt)].filter(e=>e!==void 0),r=(n.length?Math.min(...n):Date.now())-1;return[...(fe.current?.messages??[]).map(e=>{let t=ml(e,ze.current);return t.createdAt=r,t}),...e]},[]),Ut=r(async e=>{let t=Bt.current,r=()=>t!==Bt.current||v.value!==e;ue.current===e&&(ue.current=void 0),C(!0);try{let[t,n]=await Promise.all([B.loadConversation(e),Pt()]);if(r())return!1;let i=An(t.messages);E(n);let a=Ht(Xn(i,x.value),n);if(x.value=a,ue.current=a.some(e=>e.role===`user`)?void 0:e,i.length>0||t.controlState!==void 0){Te(t.canContinue),t.controlState&&ht(t.controlState);let e=i.findLast(e=>e.role===`assistant`&&!e.ephemeral);Re(e?.suggestions??[])}return!0}catch(t){return r()?!1:($.warn(`loadThread failed; keeping conversation active`,{err:t,conversationId:e}),n.emit(`error`,t),Be.current.onError?.(t),!1)}finally{r()||C(!1)}},[B,Pt,x,v,Ht,n]),Wt=r(e=>{if(le.current===e)return le.current=void 0,Ut(e)},[Ut]),Gt=r(()=>{if(w.current)return Promise.resolve(void 0);let t=v.value,r=x.value.find(e=>e.serverMessageId!==void 0),i=r?.serverMessageId,a=r?new Date(r.createdAt).toISOString():void 0;if(!t||!i||!a)return Promise.resolve(void 0);let o=Bt.current,s={};return w.current=s,(async()=>{try{let e=await B.loadConversation(t,{beforeId:i,beforeCreatedAt:a});if(w.current!==s||Bt.current!==o||v.value!==t)return;if(e.messages.length===0)return!1;let n=e.messages.map(Dn),r=x.value,c=Gn(r,n);if(c!==r){let e=Math.min(...n.map(e=>e.createdAt??1/0),...T.map(e=>e.createdAt??1/0));if(Number.isFinite(e))for(let t of r){if(!t.ephemeral)break;(t.createdAt??1/0)>=e&&(t.createdAt=e-1)}x.value=c}return!0}catch(r){if(w.current!==s||Bt.current!==o||v.value!==t)return;$.warn(`load previous messages failed`,{err:r,conversationId:t,beforeId:i}),n.emit(`error`,r),e.onError?.(r);return}finally{w.current===s&&(w.current=void 0)}})()},[n,v,T,x,e,B]),Kt=r(async({newConversation:t})=>{let r=++zt.current,i=()=>r!==zt.current,a=v.value,o=t||!a?ct():a;o!==a&&(Bt.current++,C(!1),l(()=>{v.value=o,b.value=o}),d.saveConversationId(o)),B.primeIdentity(f,o);let s;try{s=await B.handshake({visitorId:f,conversationId:o,userPrefs:d.loadUserPrefs(),locale:Ze})}catch(r){if(i())return;n.emit(`error`,r),e.onError?.(r),t||ne(!0);return}if(i())return;s.conversationId!==o&&Vt(s.conversationId),Ie(s.agent),e.mode===`page`&&(s.site&&At(s.site)?He(s.site):s.site&&$.warn(`invalid site config, using fallback`,{site:s.site}),s.blocks&&jt(s.blocks)?We(s.blocks):s.blocks&&$.warn(`invalid blocks config, using fallback`,{blocks:s.blocks}));let c=mt(s.userPrefs);if(Object.keys(c).length>0&&!t&&(d.saveUserPrefs(c),c.locale&&tt(c.locale),c.soundMuted!==void 0&&Ye.setMuted(c.soundMuted),c.themeMode&&nt(c.themeMode),c.textSize&&rt(c.textSize)),fe.current=s.welcome,t||n.emit(`handshake`,s),s.welcome?.suggestions){let e=ze.current;Re(s.welcome.suggestions.map(t=>({...t,label:D(e,t.label),...t.text===void 0?{}:{text:D(e,t.text)}})))}let u=!t&&a&&s.conversationId===a;y.current=!!u,u?de.current||(le.current=s.conversationId):(ue.current=s.conversationId,kt(s.welcome?.messages),Tt(s.conversationId)),t||ne(!0)},[B,f,d,e,n,v,b,Ye,kt,Ze,Vt,Tt]),qt=JSON.stringify(e.userContext??null);i(()=>{let t=Object.keys(qe).length?{...qe,...e.userContext}:e.userContext;B.setContext(t,gl(e.pageContext))},[B,qt,JSON.stringify(e.pageContext??null),JSON.stringify(qe)]);let Jt=r((e,t=[])=>Re(e.suggestions??t),[]);i(()=>(B.primeIdentity(f,v.value),Kt({newConversation:!1}),()=>{zt.current++,Bt.current++}),[]),i(()=>{!se||!N||de.current||(de.current=!0,Mt.current=B.bootstrap(),(async()=>{try{let e=await Mt.current;P(Me((e??{forms:[]}).forms,et))}catch(e){$.debug(`bootstrap failed — treating as no forms`,{err:e})}finally{ie(!0)}})(),le.current===v.value&&C(!0))},[se,N]);let Xt=s(null);i(()=>{if(!se||!N)return;if(Xt.current===null){Xt.current=et;return}if(Xt.current===et)return;Xt.current=et;let e=!1;return B.bootstrap().then(t=>{e||P(Me((t??{forms:[]}).forms,et))}).catch(e=>$.debug(`forms re-localize failed — keeping current copy`,{err:e})),()=>{e=!0}},[se,N,et,B]);let Zt=s(qt);i(()=>{!N||Zt.current===qt||(Zt.current=qt,Kt({newConversation:!1}))},[qt,N,Kt]),Pc({hostElement:t,mode:e.mode,panelSize:z,isOpen:L,surfaceReady:N,setIsOpen:oe});let{sendAiTurn:V,sendRoutedTurn:Qt}=cl({transport:B,messagesSig:x,conversationIdSig:v,options:e,bus:n,feedback:Ye,persistence:d,visitorId:f,adoptConversationId:Vt,applyControlState:ht,setCanSend:Te,settleSuggestions:Jt,runCancellation:Xe}),{toolInteraction:$t}=Oc({streaming:De,controlModeSig:ut,messagesSig:x,sendAiTurn:V,bus:n,humanInLoop:e.features.humanInLoop}),tn=r((e,t)=>{let r=x.value.find(t=>t.serverMessageId===e);r&&(r.feedback=t),$.info(`messageFeedback`,{messageId:e,value:t}),n.emit(`messageFeedback`,{messageId:e,value:t}),B.submitFeedback({messageId:e,value:t})},[n,x,B]),nn=()=>x.value.reduce((e,t)=>e+ +(t.role===`user`),0),rn=e.forms.list.length>0?e.forms:re??e.forms,H=ys({forms:rn,persistence:d,userContext:()=>e.userContext,messageCount:nn,pageArea:()=>e.pageContext?.area?String(e.pageContext.area):void 0,conversationId:()=>v.value,onComplete:(e,t,r,i)=>{$.info(`formSubmit`,{formId:e.id,trigger:t,skipped:i}),n.emit(`formSubmit`,{formId:e.id,values:r,skipped:i}),E(t=>{let n=t.find(t=>t.formId===e.id&&t.outcome===`skipped`)?.createdAt??Date.now();return[...t.filter(t=>t.formId!==e.id||t.outcome!==`skipped`),{key:`local:${e.id}:${n}`,formId:e.id,outcome:i?`skipped`:`submitted`,createdAt:n,...i?{}:{values:r}}]});let a=v.value??ct();v.value||(v.value=a,d.saveConversationId(a),B.primeIdentity(void 0,a)),!i&&e.mirrorToContext&&Je(e=>({...e,...r})),B.submitForm({formId:e.id,conversationId:a,trigger:t,values:r,skipped:i})}}),an=p(()=>H.activeForm.value);el({activated:se,conversationReady:N,conversationIdSig:v,messagesSig:x,optionsRef:Be,transport:B,visitorId:f,adoptControlStateChunk:gt,adoptMemoryCompactionStateChunk:bt,settleSuggestions:Jt,recordConversationReply:Dt,transcriptRecoverySig:St,beginConversationTranscript:wt,commitConversationTranscript:Tt,onReplyLanded:r(()=>H.fire(`after-messages`),[H]),runCancellation:Xe,canContinueRef:Ee,setCanSend:Te,feedback:Ye,bus:n,loadInitialThread:Wt,shouldReconcileOnConnect:r(()=>y.current||x.value.some(e=>!e.ephemeral&&e.role===`user`),[x])}),i(()=>{H.refresh()},[rn,H]);let on=e.pageContext?.area?String(e.pageContext.area):void 0,sn=p(()=>x.value.length);i(()=>{N&&F&&H.fire(`pre-chat`)},[N,F,H]),i(()=>{F&&!we&&H.fire(`conversation-closed`)},[F,we,H]),i(()=>{N&&F&&on&&H.fire(`page-area`)},[N,F,on,H]);let U=o(()=>{let e=rn.list.flatMap(e=>e.triggers).filter(e=>e.kind===`idle`).map(e=>Number(e.param));return e.length?Math.min(...e)*1e3:0},[rn]);i(()=>{if(!U||!L)return;let e=setTimeout(()=>H.fire(`idle`),U);return()=>clearTimeout(e)},[U,L,H,sn.value]);let W=r(async(t,r,i)=>{if(Ae.current)return!1;let a=v.value,o=a?yt.value.get(a):void 0,s=ut.value!==`ai-agent`;if(!s&&o?.status===`compacting`||($.info(`send`,{textLen:t.length,attachments:r.length,streaming:ke.current,routedToOperator:s}),ke.current&&!s))return!1;let c=new AbortController,l={conversationId:a,controller:c};Ae.current=l,Ne(!0);try{Ye.unlock();let o=await vl(B,r,c.signal,t=>{c.signal.aborted||($.warn(`upload failed`,{err:t}),n.emit(`error`,t),e.onError?.(t))});if(c.signal.aborted||v.value!==a||!Ee.current||H.activeForm.value)return!1;let s=a?yt.value.get(a):void 0,l=ut.value!==`ai-agent`;if(!l&&s?.status===`compacting`||ke.current&&!l||!t&&o.length===0)return!1;n.emit(`send`,{text:t,attachmentCount:r.length}),Le.length>0&&Re([]),Ye.play(`messageSent`);let u=Sn(t,o,i);return Ec(n,e,`user`,t),l?(x.value=[...x.value,u],i?await Qt(u):(Qt(u),!0)):(x.value=[...x.value,u,Cn()],i?await V({continueExisting:!1}):(V({continueExisting:!1}),!0))}finally{Ae.current===l&&(Ae.current=null,Ne(!1))}},[B,n,e,Le.length,x,v,yt,V,Qt,ut]),cn=v.value,ln=(cn?yt.value.get(cn):void 0)?.status===`compacting`,un=ut.value===`ai-agent`,dn=p(()=>{let e=x.value.at(-1);return e?.role===`assistant`&&e.partsSig.value.some(e=>e.kind===`tool`&&e.stateSig.value===`approval-requested`)}),fn=p(()=>x.value.some(e=>e.retryAction?.kind===`resend-user`||e.retryAction?.kind===`continue-assistant`));i(()=>{let e=v.value;return()=>{let t=Ae.current;!t||t.conversationId!==e||(Ae.current=null,Ne(!1),t.controller.abort())}},[v.value]),i(()=>{we&&!an.value||Ae.current?.controller.abort()},[an.value,we]);let pn=r(()=>{if(!Xe.stop())return;$.info(`stop`),n.emit(`stop`,void 0);let e=x.value.at(-1);e&&e.role!==`user`&&e.status===`streaming`&&(e.canceled=!0,x.value=[...x.value])},[Xe,n,x]),mn=r(e=>{if(De)return;let t=x.value,n=ir(t,e);if(n)switch($.info(`retry`,{kind:n.kind,messageId:n.messageId}),n.kind){case`continue-assistant`:if(ut.value!==`ai-agent`||e.role!==`assistant`||(e.serverMessageId??e.id)!==n.messageId)return;e.status=`streaming`,e.errorText=void 0,e.retryAction=void 0,e.awaitingContinuation=!0,x.value=[...t],V({continueExisting:!0,turn:e});return;case`resend-user`:{let r=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!r)return;let i=e=>{e&&Ot.current?.acceptQueuedMessage(n.messageId)};if(r.status=`complete`,r.errorText=void 0,r.retryAction=void 0,ut.value!==`ai-agent`){x.value=e.role===`assistant`?t.filter(t=>t!==e):[...t],Qt(r).then(i);return}let a=Cn();x.value=e.role===`assistant`?t.map(t=>t===e?a:t):[...t,a],V({continueExisting:!1,turn:r}).then(i);return}case`repeat-user`:{let e=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!e)return;let r=Sn(Nn(e),e.attachments?.map(e=>({...e}))??[]),i=new Set(r.attachments?.flatMap(e=>e.url?[e.url]:[])??[]),a=e.partsSig.value.flatMap(e=>e.kind===`file`&&!i.has(e.url)?[{...e}]:[]);if(a.length>0&&(r.partsSig.value=[...r.partsSig.value,...a]),ut.value!==`ai-agent`){x.value=[...t,r],Qt(r);return}x.value=[...t,r,Cn()],V({continueExisting:!1,turn:r});return}default:return n}},[De,x,ut,V,Qt]),hn=r(()=>{if(Li(e.mode,z)===`exit-fullscreen`){$.info(`close → exit-fullscreen`,{mode:e.mode}),ye(`normal`),n.emit(`fullscreen`,!1);return}$.info(`close → panel closed`,{mode:e.mode}),H.fire(`panel-close`),oe(!1),d.savePanelOpen(!1),n.emit(`close`,void 0),e.onClose?.()},[n,e,d,z,H]),gn=r(()=>{$.info(`open`,{mode:e.mode}),Ye.unlock(),R(!0),oe(!0),d.savePanelOpen(!0),!he&&!_e&&ve(),setTimeout(()=>R(!1),_l),n.emit(`open`,void 0),e.onOpen?.()},[n,e,Ye,d,he,_e,ve]),_n=r(()=>{let e=x.value.some(e=>e.role===`user`);if(ue.current===v.value&&!e&&we&&v.value){$.info(`clear → reusing empty conversation`,{conversationId:v.value}),x.value.length===0&&kt(fe.current?.messages);return}$.info(`clear → new conversation`,{wasStreaming:De}),n.emit(`clear`,void 0),Xe.settle(),y.current=!1,le.current=void 0,ue.current=void 0,l(()=>{x.value=[],v.value=void 0,ht({controlMode:`ai-agent`,controlRevision:0})}),d.clearConversation(),Te(!0),E([]),Re([]),Kt({newConversation:!0})},[De,x,v,d,Kt,n,we,kt,Xe,ht]),vn=r(()=>{_n(),Se(`chat`);let t=e.modules.list.find(e=>e.layout===`chat`)?.id;t&&M.switchTab(t)},[_n,M,e]),bn=r(()=>{let e=z===`expanded`?`normal`:`expanded`;$.info(`expand`,{from:z,expanded:e===`expanded`}),ye(e),d.savePanelSize(e),n.emit(`expand`,e===`expanded`)},[n,z,d]),xn=r(()=>{let e=z===`fullscreen`?`normal`:`fullscreen`;$.info(`fullscreen`,{from:z,fullscreen:e===`fullscreen`}),ye(e),d.savePanelSize(e),n.emit(`fullscreen`,e===`fullscreen`)},[n,z,d]),wn=r(()=>{Se(e=>{let t=e===`history`?`chat`:`history`;return $.info(`toggleHistory`,{view:t}),n.emit(`toggleHistory`,{view:t}),t})},[n]),Tn=r(()=>{Ke(e=>{let t=!e;return $.info(`sidebarToggle`,{collapsed:t}),d.saveSidebarCollapsed(t),n.emit(`sidebarToggle`,{collapsed:t}),t})},[d,n]),En=r(e=>{$.info(`resize`,e),it({widgetSize:e}),n.emit(`resize`,e)},[it,n]),On=r(async t=>{let r=t.conversationId;if(r===v.value&&Et(r)){$.info(`selectConversation`,{conversationId:r,cached:!0}),n.emit(`selectConversation`,{conversationId:r}),B.publishConversation(t),Se(`chat`);let e=k();e&&M.switchTab(e),Tt(r);return}let i=++zt.current;Bt.current++,C(!1);let a=()=>i!==zt.current;$.info(`selectConversation`,{conversationId:r,wasStreaming:De}),n.emit(`selectConversation`,{conversationId:r}),B.publishConversation(t);try{let[e,t]=await Promise.all([B.loadConversation(r),Pt(r)]);if(a())return;Xe.settle(),y.current=!0,le.current=void 0;let n=An(e.messages),i=e.conversationId!==v.value,o=i?n:Xn(n,x.value);ue.current=o.some(e=>e.role===`user`)?void 0:e.conversationId,l(()=>{x.value=Ht(o,t),i&&(b.value=e.conversationId),v.value=e.conversationId}),E(t),d.saveConversationId(e.conversationId),B.primeIdentity(f,e.conversationId),Te(e.canContinue),e.controlState&&ht(e.controlState);let s=o.findLast(e=>e.role===`assistant`&&!e.ephemeral);Re(s?.suggestions??[]),i?wt(e.conversationId):Tt(e.conversationId),Se(`chat`);let c=k();c&&M.switchTab(c)}catch(t){if(a())return;n.emit(`error`,t),e.onError?.(t)}},[B,x,v,b,n,e,d,Pt,Ht,De,f,Xe,wt,Tt,Et,M]),kn=s(null),jn=r(e=>{typeof e==`string`&&(F?H.fire(`manual`,e):kn.current=e)},[F,H]);i(()=>{!F||!kn.current||(H.fire(`manual`,kn.current),kn.current=null)},[F,H]);let Mn=s({handleOpen:gn,handleClose:hn,handleExpand:bn,handleFullscreen:xn,openForm:jn});Mn.current={handleOpen:gn,handleClose:hn,handleExpand:bn,handleFullscreen:xn,openForm:jn},a(()=>Nt(t,{open:()=>Mn.current.handleOpen(),close:()=>Mn.current.handleClose(),expand:()=>Mn.current.handleExpand(),fullscreen:()=>Mn.current.handleFullscreen(),openForm:e=>Mn.current.openForm(e)}),[t]);let Pn=o(()=>Fe(e,Ze,Qe,$e),[e,Ze,Qe,$e]);ze.current=Pn.strings;let Fn=o(()=>T.map(e=>{let t=rn.list.find(t=>t.id===e.formId);return{...e,title:t?.title,form:t}}),[T,rn]),In=e=>{On(e)},Ln={options:Pn,transport:B,feedback:Ye,bus:n,persistence:d,conversationId:v.value??``,composerKey:b.value,composerApiRef:Ot,view:xe,canSend:we,isStreaming:De,isMemoryCompacting:ln,canReleaseQueuedMessages:N&&!S&&!an.value&&(!un||!dn.value&&!fn.value),queueManualMessages:un&&(dn.value||fn.value),sendPreparing:je,composerActive:Pn.mode===`page`||Pn.mode===`inline`||Pn.mode===`standalone`||L,controlMode:ut.value,assignedOperatorInitials:ft.value,operatorAvailable:pt.value,operatorRequestEnabled:e.features.operatorRequest,onRequestOperator:_t,onCancelOperatorRequest:vt,loadingMessages:S,onLoadPreviousMessages:Gt,messagesSig:x,agent:Pe,suggestions:Le,initialWidgetSize:h.widgetSize??null,onClose:hn,onClear:_n,onExpand:bn,onFullscreen:xn,onSoundToggle:lt,onToggleHistory:wn,onSelectHistoryConversation:In,onNewConversation:vn,onLocaleChange:at,onThemeChange:ot,onTextSizeChange:st,onWidgetSizeChange:En,onSend:W,onStop:pn,onSuggestion:t=>{if(Ae.current)return;let r=t.text??t.label;$.info(`suggestion`,{text:r,autoSend:e.autoSendSuggestions}),n.emit(`suggestion`,{text:r}),e.autoSendSuggestions?W(r,[]):Ot.current?.fill(r)},activeForm:an.value?.form??null,formMarkers:Fn,onFormSubmit:H.complete,onFormSkip:H.skip,onFormFill:e=>H.fire(`manual`,e),tool:$t,onRetry:mn,onMessageFeedback:tn};if(!N)return null;let Rn=Pn.modules.list,zn=e=>{let t=Fi(`close`,Pn.mode,e);return Rn.length===0?g(Tc,{strings:Pn.strings,onClose:t?hn:void 0}):Rn.length===1&&Rn[0]?.layout===`chat`?g(us,{...Ln,panelSize:e}):g(Cc,{panelProps:{...Ln,panelSize:e,onClose:t?hn:void 0},enabledModules:Rn,nav:M,bus:n,hasUnread:xt.value,onSelectConversation:In,onStartNewConversation:vn,onSetPanelSize:ye})};if(e.mode===`page`){let e=Rn.some(e=>e.layout===`chat`);return g(`div`,{class:`${pl}-anchor`,children:g(ks,{site:Ve,blocks:Ue,transport:B,strings:Pn.strings,locale:Pn.locale,persistence:d,showConversations:e,onSelectConversation:In,onNewConversation:vn,sidebarCollapsed:Ge,onToggleSidebarCollapsed:Tn,children:zn(`fullscreen`)})})}if(ae){let t=e.mode===`standalone`?`fullscreen`:z;return g(`div`,{class:`${pl}-anchor`,children:zn(t)})}let Bn=e.mode===`drawer`,Vn=e.mode!==`modal`&&!e.launcher.hidden&&(!L||me),Hn=Vn&&!me&&!he&&!Bn?Pn.launcher.callout:null;return _(`div`,{class:`${pl}-anchor`,"data-launcher-size":Pn.launcher.size,children:[L||se?g(`div`,{class:`${pl}-surface`,hidden:!L,children:zn(z)}):null,Vn?g(Ti,{onToggle:gn,launcher:Pn.launcher,strings:Pn.strings,leaving:me,edgeTab:Bn}):null,Hn?g(ki,{callout:Hn,launcherPosition:Pn.position,strings:Pn.strings,closeLabel:Pn.strings.close,onDismiss:ve}):null]})}function gl(e){let t=e?.url??(typeof location<`u`?location.href:void 0);if(!(!e&&!t))return{...e,...t?{url:t}:{}}}const _l=120;async function vl(e,t,n,r){return(await Promise.all(t.map(async t=>{try{let{id:r,url:i}=await e.uploadFile(t.file,n);return{id:r,name:t.name,mediaType:t.mediaType,size:t.size,url:i}}catch(e){r(e);return}}))).filter(e=>e!==void 0)}const yl=I.scope(`error-boundary`);var bl=class extends e{constructor(...e){super(...e),U(this,`state`,{crashed:!1})}componentDidCatch(e,t){yl.error(`widget render crashed`,{error:e,componentStack:t?.componentStack}),this.setState({crashed:!0}),this.props.onError(e,t?.componentStack)}render(){return this.state.crashed?this.props.fallback:this.props.children}};const xl={open:()=>void 0,close:()=>void 0,expand:e=>({on:e}),fullscreen:e=>({on:e}),send:e=>({attachments:e.attachmentCount}),message:e=>({role:e.role}),stop:()=>void 0,clear:()=>void 0,suggestion:()=>void 0,toggleHistory:e=>({view:e.view}),handshake:()=>void 0,formSubmit:e=>({formId:e.formId,skipped:e.skipped}),toolResult:()=>void 0,toolDecision:e=>({approved:e.approved}),messageFeedback:e=>({value:e.value??`none`}),contentView:e=>({section:e.section,tags:e.tags,count:e.count}),contentOpen:e=>({contentId:e.contentId,tags:e.tags}),contentSearch:e=>({qlen:e.queryLength,hits:e.hitCount}),contentRead:e=>({contentId:e.contentId}),contentLinkClick:e=>({contentId:e.contentId}),attach:e=>({count:e.count,bytes:e.totalBytes}),voiceStart:()=>void 0,voiceStop:e=>({ms:e.durationMs}),voiceCancel:()=>void 0,localeChange:e=>({locale:e}),themeChange:e=>({theme:e}),textSizeChange:e=>({size:e}),soundToggle:e=>({muted:e.muted}),sidebarToggle:e=>({collapsed:e.collapsed}),calloutDismiss:()=>void 0,error:()=>void 0};function Sl(){let e=navigator;return e.globalPrivacyControl===!0||e.doNotTrack===`1`}function Cl(){return location.origin+location.pathname}function wl(){try{return document.referrer?new URL(document.referrer).origin:``}catch{return``}}function Tl(e,t){let n=Math.random(),r=0,i=0,a=new Set,o=(e,o)=>{let{tracking:s,publicKey:c,aiAgentDeploymentId:l,mode:u,themeMode:d}=t.getOptions();if(!s.enabled||Sl()||n>=s.sampleRate)return;let f=performance.now();if(f-r>6e4&&(r=f,i=0),++i>60)return;let p=new URLSearchParams;p.set(`v`,`1`),p.set(`_ev`,Bt),p.set(`e`,e),s.token&&p.set(`tk`,s.token),c&&p.set(`pk`,c),l&&p.set(`dep`,l),p.set(`vid`,t.getVisitorId());let m=t.getConversationId();m&&p.set(`cid`,m),p.set(`url`,Cl());let h=wl();h&&p.set(`ref`,h),p.set(`sw`,String(screen.width)),p.set(`sh`,String(screen.height)),p.set(`vw`,String(innerWidth)),p.set(`vh`,String(innerHeight)),p.set(`dpr`,String(devicePixelRatio)),p.set(`lang`,navigator.language);try{p.set(`tz`,Intl.DateTimeFormat().resolvedOptions().timeZone)}catch{}if(p.set(`m`,u),p.set(`th`,d),o)for(let[e,t]of Object.entries(o))t!==void 0&&p.set(e,String(t));p.set(`ts`,String(Date.now()));let g=`${s.endpoint}?${p}`;if(g.length>2e3)return;let _=new Image(1,1);a.add(_);let v=()=>a.delete(_);_.addEventListener(`load`,v,{once:!0}),_.addEventListener(`error`,v,{once:!0}),_.src=g},s=Object.keys(xl).map(t=>e.on(t,e=>o(t,xl[t]?.(e))));return()=>{for(let e of s)e();a.clear()}}function El(e){let{bus:r,host:i,appRoot:a,persistence:o,reportError:s}=e,c=e.initialRaw,l,u=xe(c),d=!0,f=()=>{u=xe(l?Le(c,l):c)},p=()=>{yt(i,bt(u.mode));let e=o.loadUserPrefs().themeMode;Ot(i,e?{...u,themeMode:e}:u),d&&(Dt(i,Dl(u)),d=!1)},m=()=>{p(),n(t(bl,{onError:s},t(hl,{bus:r,hostElement:i,options:u})),a)};r.on(`handshake`,e=>{e.config&&(e.config.storageVersion&&o.rememberStorageVersion(e.config.storageVersion),l=e.config,f(),m())});let h=Tl(r,{getOptions:()=>u,getVisitorId:()=>o.getVisitorId(),getConversationId:()=>o.loadConversationId()});return{getOptions:()=>u,getUserOptions:()=>c,render:m,setUserOptions:e=>{c=e,f(),m()},patchUserOptions:e=>{c={...c,...e},f(),m()},destroy:()=>h()}}function Dl(e){if(e.mode===`standalone`)return`standalone`;if(e.mode===`inline`)return`inline`;let t=dt(e.widgetId,e.storage,e.aiAgentDeploymentId),{panelOpen:n,panelSize:r}=It(e,Lt(),t.loadPanelOpen(),t.loadPanelSize());return Pt(e.mode,r,n)}var Ol=class{constructor(){U(this,`handlers`,new Map)}on(e,t){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(t),()=>this.handlers.get(e)?.delete(t)}emit(e,t){let n=this.handlers.get(e);if(n)for(let e of n)try{e(t)}catch{}}clear(){this.handlers.clear()}},kl=class extends HTMLElement{constructor(...e){super(...e),U(this,`bus`,new Ol),U(this,`mountResult`,null),U(this,`runtime`,null)}static get observedAttributes(){return rt}connectedCallback(){this.boot()}disconnectedCallback(){this.mountResult&&(this.runtime?.destroy(),this.runtime=null,n(null,this.mountResult.appRoot),this.bus.clear())}attributeChangedCallback(){this.isConnected&&this.boot()}boot(){let e=it(e=>this.getAttribute(e));if(!e.aiAgentDeploymentId)throw Error(`ai-agent-deployment-id is required`);if(this.runtime){this.runtime.setUserOptions(e);return}let t=xe(e);this.mountResult||(this.mountResult=xt({existingHost:this,position:bt(t.mode)}));let n=dt(t.widgetId,t.storage,t.aiAgentDeploymentId);this.runtime=El({bus:this.bus,host:this.mountResult.hostElement,appRoot:this.mountResult.appRoot,persistence:n,initialRaw:e,reportError:e=>this.bus.emit(`error`,e)}),this.runtime.render()}};let Al=!1;function jl(){if(Al||typeof customElements>`u`)return;let e=b.tagName;customElements.get(e)||customElements.define(e,kl),Al=!0}typeof customElements<`u`&&jl();export{jl as registerWebComponent};
|
|
12
|
+
`).trim(),M=!S&&t!==`error`&&!v.value&&j.length>0,ee=A||M;return g(`div`,{class:`${Lo}-bubble-row`,"data-role":e.role,"data-testid":Ci(q.messageBubble,e.serverMessageId??e.id),children:_(`div`,{class:`${Lo}-bubble-col`,children:[_(`div`,{class:`${Lo}-bubble`,children:[e.role===`operator`&&e.operatorInitials?g(`span`,{class:`${Lo}-bubble-author`,children:e.operatorInitials}):null,_(`div`,{class:`${Lo}-bubble-body`,children:[T?g(qo,{label:n.loading}):h.map((r,o)=>g(Ho,{part:r,active:E,live:C,strings:n,showReasoning:i,showToolCalls:a,showSources:s,interactive:c&&t===`complete`&&(r.kind!==`tool`||Un(e,o)),superseded:l,continuationStreaming:e.continuationStreaming===!0,tool:d},`${Go(r)}#${o}`)),D&&g(Ko,{}),t===`error`||v.value?_(`div`,{class:`${Lo}-error`,role:`alert`,children:[g(`span`,{children:e.errorText??n.errorGeneric}),f?g(`button`,{type:`button`,class:`${Lo}-error-retry`,onClick:()=>f(e),"data-testid":q.messageRetry,children:n.errorRetry}):null]}):null]})]}),O||ee?_(`div`,{class:`${Lo}-bubble-meta`,children:[O?g(`time`,{class:`${Lo}-bubble-time`,dateTime:O.iso,title:O.full,children:O.short}):null,ee?_(`div`,{class:`${Lo}-bubble-actions`,children:[A&&e.serverMessageId?g(mo,{messageId:e.serverMessageId,initial:e.feedback??null,strings:n,onFeedback:m}):null,M?g(Bo,{text:j,strings:n}):null]}):null]}):null]})})}function Bo({text:e,strings:t}){let[n,r]=c(!1),i=()=>{navigator.clipboard?.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})},a=n?t.copied:t.copy;return g(`button`,{type:`button`,class:`${Lo}-msg-action`,"data-active":n?`true`:void 0,"aria-label":a,title:a,onClick:i,"data-testid":q.messageCopy,children:g(n?Ur:hi,{})})}function Vo(e){if(typeof e!=`number`||!Number.isFinite(e))return null;try{let t=new Date(e);return{short:t.toLocaleTimeString(void 0,{hour:`numeric`,minute:`2-digit`}),full:t.toLocaleString(void 0,{dateStyle:`full`,timeStyle:`short`}),iso:t.toISOString()}}catch{return null}}function Ho({part:e,active:t,live:n,strings:r,showReasoning:i,showToolCalls:a,showSources:o,interactive:s,superseded:c,continuationStreaming:l,tool:u}){switch(e.kind){case`step-start`:return null;case`text`:return g(lo,{textSig:e.textSig,doneSig:e.doneSig});case`reasoning`:return i?g(Wo,{part:e,active:t,strings:r}):null;case`tool`:return g(Uo,{part:e,strings:r,showToolCalls:a,interactive:s,superseded:c,continuationStreaming:l,live:n,tool:u});case`file`:return e.mediaType.startsWith(`image/`)?g(`img`,{src:e.url,alt:``,loading:`lazy`}):g(`a`,{href:e.url,target:`_blank`,rel:`noreferrer noopener`,children:e.url});case`source`:return o?g(go,{part:e,strings:r}):null}}function Uo({part:e,strings:t,showToolCalls:n,interactive:r,superseded:i,continuationStreaming:a,live:s,tool:c}){let l=o(()=>u(()=>e.approvalSig.value!==void 0),[e]);return c?.humanInLoop&&l.value?Ha(e.toolName)?g(Oo,{part:e,strings:t,active:r,superseded:i,continuationStreaming:a,onDecision:c.onDecision,onEdit:c.onEdit}):g(vo,{part:e,strings:t,active:r,superseded:i,continuationStreaming:a,onDecision:c.onDecision,onEdit:c.onEdit}):n?g(Io,{part:e,strings:t,live:s}):null}function Wo({part:e,active:t,strings:n}){return _(`details`,{class:`${Lo}-reasoning`,"data-testid":q.reasoning,open:t,"data-active":t?`true`:void 0,children:[g(`summary`,{class:`${Lo}-reasoning-summary`,children:g(`span`,{class:`${Lo}-reasoning-label`,children:t?n.thinking:n.thoughts})}),g(`div`,{class:`${Lo}-reasoning-body`,children:g(lo,{textSig:e.textSig,doneSig:e.doneSig})})]})}function Go(e){switch(e.kind){case`text`:case`reasoning`:case`step-start`:return`${e.kind}:${e.id}`;case`tool`:return`tool:${e.toolCallId}`;case`file`:return`file:${e.url}`;case`source`:return`source:${e.sourceId}`}}function Ko(){return _(`span`,{class:`${Lo}-typing`,"data-testid":q.typingDots,"aria-hidden":`true`,children:[g(`span`,{}),g(`span`,{}),g(`span`,{})]})}function qo({label:e}){return _(`span`,{class:`${Lo}-loading`,role:`status`,children:[g(`span`,{class:`${Lo}-loading-spinner`,"aria-hidden":`true`}),g(`span`,{class:`${Lo}-loading-label`,children:e})]})}const Jo=b.cssPrefix;function Yo({messagesSig:e,strings:t,responseMode:n,showReasoning:r,showToolCalls:o,showSources:l,enableMessageFeedback:u,onFeedback:d,loading:f,onLoadPreviousMessages:m,idle:h,controlMode:v=`ai-agent`,tool:y,onRetry:b,form:x,formMarkers:S,onFillForm:C}){let w=s(null),T=p(()=>e.value),[E,D]=c(!1),[O,k]=c(!1),A=s(!1),j=s(!1),[M,ee]=c(),te=s(!1),N=s(!1),ne=s(!1),re=s(0),P=()=>ne.current||performance.now()-re.current<350,F=s(0),ie=e=>{let t=e.scrollHeight-e.clientHeight>1;e.dataset.fadeTop=t&&e.scrollTop>1?`true`:`false`,e.dataset.fadeBottom=t&&e.scrollHeight-e.scrollTop-e.clientHeight>1?`true`:`false`},ae=e=>D(e.scrollHeight-e.scrollTop-e.clientHeight>240),I=e=>{F.current=performance.now(),e.scrollTop=e.scrollHeight,ie(e)},L=(e,t)=>{I(e);let n=t,r=0,i=()=>{N.current||P()||(I(e),--n>0&&(r=requestAnimationFrame(i)))};return t>0&&(r=requestAnimationFrame(i)),()=>cancelAnimationFrame(r)},oe=(e,t)=>{let n,r,i,a=-1,o=()=>{n.disconnect(),r.disconnect(),clearTimeout(i)},s=()=>{if(N.current||P()||a>=0&&e.scrollTop<a-4)return o();I(e),a=e.scrollTop};return n=new ResizeObserver(s),r=new MutationObserver(s),s(),n.observe(e),r.observe(e,{childList:!0,subtree:!0,characterData:!0}),i=setTimeout(o,t),o},se=T.value[0]?.id;a(()=>{let e=w.current;if(e&&T.value.length!==0&&!j.current&&(te.current=!0,T.value.some(e=>e.role===`user`)))return oe(e,300)},[se]);let ce=s(0);i(()=>{let e=w.current,t=T.value,n=ce.current;if(ce.current=t.length,e&&te.current&&!j.current){if(t.slice(n).some(e=>e.role===`user`))return N.current=!1,L(e,3);t.some(e=>e.role===`user`)&&(N.current||P()||e.scrollHeight-e.scrollTop-e.clientHeight<120&&I(e))}},[T.value.length]);let le=s(null);i(()=>{let e=w.current,t=T.value.at(-1),n=le.current;if(le.current=t?{id:t.id,streaming:t.status===`streaming`}:null,e&&te.current&&!(!t||t.id!==n?.id||n.streaming||t.status!==`streaming`))return N.current=!1,L(e,3)},[T.value]),i(()=>{let e=w.current;if(!e)return;let t=T.value.at(-1);if(!t||t.status!==`streaming`&&!T.value.some(e=>e.role===`user`))return;let n=()=>{N.current||P()||e.scrollHeight-e.scrollTop-e.clientHeight<240&&I(e)};if(t.status!==`streaming`)return oe(e,300);n();let r=new MutationObserver(n);return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>r.disconnect()},[T.value]);let ue=x?.form.id,de=!!x&&(S??[]).some(e=>e.formId===x.form.id);a(()=>{let e=w.current;!e||!ue||N.current||T.value.some(e=>e.role===`user`)&&(de?e.querySelector(`[data-testid="${q.formGate}"]`)?.scrollIntoView({block:`nearest`}):I(e))},[ue,de]),i(()=>{let e=w.current;if(!e)return;let t=()=>{ae(e),ie(e),performance.now()-F.current>150&&(N.current=e.scrollHeight-e.scrollTop-e.clientHeight>8)},n=()=>{N.current=!0},r=e=>{e.deltaY<0&&n()},i=0,a=e=>{i=e.touches[0]?.clientY??0,ne.current=!0},o=e=>{(e.touches[0]?.clientY??0)>i+4&&n()},s=()=>{ne.current=!1,re.current=performance.now()},c=()=>{ne.current=!0};return e.addEventListener(`scroll`,t,{passive:!0}),e.addEventListener(`wheel`,r,{passive:!0}),e.addEventListener(`touchstart`,a,{passive:!0}),e.addEventListener(`touchmove`,o,{passive:!0}),e.addEventListener(`touchend`,s,{passive:!0}),e.addEventListener(`touchcancel`,s,{passive:!0}),e.addEventListener(`pointerdown`,c,{passive:!0}),window.addEventListener(`pointerup`,s,{passive:!0}),window.addEventListener(`pointercancel`,s,{passive:!0}),ae(e),()=>{e.removeEventListener(`scroll`,t),e.removeEventListener(`wheel`,r),e.removeEventListener(`touchstart`,a),e.removeEventListener(`touchmove`,o),e.removeEventListener(`touchend`,s),e.removeEventListener(`touchcancel`,s),e.removeEventListener(`pointerdown`,c),window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s)}},[]);let fe=()=>{let e=w.current;e&&(N.current=!1,I(e))},pe=T.value.filter(e=>!e.ephemeral),me=pe[0],R=me?.serverMessageId??me?.id,he=!!(m&&pe.length>=50&&R!==M),ge=async()=>{if(!m||A.current)return;let e=w.current,t=e?.scrollHeight??0,n=e?.scrollTop??0;A.current=!0,j.current=!0,k(!0);try{let r=await m();r===!1&&R&&ee(R),r&&e&&(await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),e.scrollTop=n+e.scrollHeight-t,ie(e),ae(e))}finally{j.current=!1,A.current=!1,k(!1)}},_e=[],ve=``,z=T.value.at(-1)?.id,ye=[...S??[]].toSorted((e,t)=>(e.createdAt??1/0)-(t.createdAt??1/0)),be=e=>x&&e.formId===x.form.id?g(Ba,{form:x.form,strings:t,onSubmit:x.onSubmit,onSkip:x.onSkip},`gate:${e.formId}`):g(Va,{marker:e,strings:t,onFill:!x&&C?()=>C(e.formId):void 0},e.key),xe=e=>{for(let t=ye[0];t?.createdAt!==void 0&&!(e!==void 0&&t.createdAt>e);t=ye[0])ye.shift(),_e.push(be(t))};for(let e of T.value){if(e.role===`assistant`&&e.id!==z&&rr(e))continue;xe(e.createdAt);let i=Xo(e.createdAt);i&&i!==ve&&(_e.push(g(`div`,{class:`${Jo}-date-divider`,children:g(`span`,{class:`${Jo}-date-pill`,title:Zo(e.createdAt),children:Qo(e.createdAt,t)})},`day:${i}`)),ve=i);let a=e.retryAction!==void 0||e.role===`assistant`&&e.id===z?ir(T.value,e):void 0,s=a!==void 0&&(a.kind!==`continue-assistant`||v===`ai-agent`);_e.push(g(Ro,{message:e,status:e.status,strings:t,responseMode:n,showReasoning:r,showToolCalls:o,showSources:l,interactive:!!h&&v===`ai-agent`&&e.id===z,superseded:e.id!==z,tool:y,onRetry:h&&s&&(e.role===`user`||e.id===z)?b:void 0,enableMessageFeedback:u,onFeedback:d},e.id))}for(let e of ye)_e.push(be(e));return _(`div`,{class:`${Jo}-list-wrap`,children:[_(`div`,{ref:w,class:`${Jo}-list ${Jo}-list--fade`,role:`log`,"aria-live":`polite`,"aria-relevant":`additions text`,children:[f&&T.value.length===0?g(`div`,{class:`${Jo}-list-loading`,role:`status`,children:t.conversationLoading}):null,he?g(`div`,{class:`${Jo}-load-previous`,children:g(`button`,{type:`button`,onClick:ge,disabled:O,"aria-busy":O,"data-testid":q.loadPreviousMessages,children:t.loadPreviousMessages})}):null,_e,x&&!de?g(Ba,{form:x.form,strings:t,onSubmit:x.onSubmit,onSkip:x.onSkip}):null]}),E?g(`button`,{type:`button`,class:`${Jo}-jump`,onClick:fe,"aria-label":t.scrollToBottom,title:t.scrollToBottom,"data-testid":q.scrollToBottom,children:g(Jr,{})}):null]})}function Xo(e){if(typeof e!=`number`||!Number.isFinite(e))return``;let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`}function Zo(e){if(typeof e!=`number`||!Number.isFinite(e))return``;try{return new Date(e).toLocaleDateString(void 0,{dateStyle:`full`})}catch{return``}}function Qo(e,t){let n=new Date(e),r=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),i=Math.round((r(new Date)-r(n))/864e5);return i<=0?t.dateToday:i===1?t.dateYesterday:i<7?n.toLocaleDateString(void 0,{weekday:`long`}):n.toLocaleDateString(void 0,{month:`long`,day:`numeric`,year:`numeric`})}const $o=[`today`,`yesterday`,`lastWeek`,`older`];function es(e,t){let n=Date.parse(t);if(!Number.isFinite(n))return`older`;let r=Math.floor((ns(e)-ns(n))/(1440*60*1e3));return r<=0?`today`:r===1?`yesterday`:r<7?`lastWeek`:`older`}function ts(e,t){let n=new Map;for(let r of t){let t=es(e,r.lastMessageAt),i=n.get(t);i?i.push(r):n.set(t,[r])}return $o.filter(e=>n.has(e)).map(e=>({bucket:e,conversations:n.get(e)}))}function ns(e){let t=new Date(e);return t.setUTCHours(0,0,0,0),t.getTime()}const rs=I.scope(`history`),is={today:`dateToday`,yesterday:`dateYesterday`,lastWeek:`dateLastWeek`,older:`dateOlder`};function as(e,t){let n=t.type!==`upsert`||t.activity===!0;if(t.type===`snapshot`&&t.result.pagination.page===1&&e.pagination.page>1){let r=pn(e.conversations.slice(0,t.result.pagination.limit),t,n);if(t.result.conversations.length===0){if(r.length===0)return t.result;let e=Math.max(t.result.pagination.total,r.length);return{...t.result,conversations:r,pagination:{...t.result.pagination,total:e,totalPages:Math.ceil(e/t.result.pagination.limit)}}}let i=new Set(r.map(e=>e.conversationId)),a=e.conversations.slice(t.result.pagination.limit).filter(e=>!i.has(e.conversationId)),o=e.pagination.page,s={...t.result.pagination,page:o,hasPrev:o>1,hasNext:o<t.result.pagination.totalPages};return{conversations:[...r,...a],pagination:s}}let r=pn(e.conversations,t,n);return r===e.conversations?e:{...t.type===`snapshot`?t.result:e,conversations:r}}function os(e,t,n){let r=Date.parse(e);return Number.isFinite(r)?new Date(r).toDateString()===new Date(t).toDateString()?new Intl.DateTimeFormat(n,{hour:`numeric`,minute:`2-digit`}).format(r):t-r<10080*60*1e3?new Intl.DateTimeFormat(n,{weekday:`short`}).format(r):new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`}).format(r):``}function ss({transport:e,strings:t,locale:n,persistence:r,onSelect:a,onNewConversation:o}){let l=b.cssPrefix,u=e.peekConversations({limit:50}),[d,f]=c(u?`loaded`:`loading`),[p,m]=c(u),[v,y]=c(!1),x=s(),S=p?.conversations??[],C=p?.pagination;i(()=>{let t=!1,n=!0,i=[],a=e.subscribeConversationChanges(e=>{n&&i.push(e),m(t=>t&&as(t,e))});x.current=void 0,y(!1);let o=e.peekConversations({limit:50});return m(o),f(o?`loaded`:`loading`),e.listConversations({limit:50}).then(e=>{if(t)return;let a=e;for(let e of i)a=as(a,e);i=[],n=!1,m(a),f(`loaded`),r.saveHistoryCount(a.conversations.length)}).catch(e=>{t||(i=[],n=!1,rs.warn(`listConversations failed`,{err:e}),f(`error`))}),()=>{t=!0,a(),x.current=void 0}},[e,r,n]);let w=async()=>{if(x.current||!C?.hasNext)return;let t={};x.current=t,y(!0);try{let n=await e.listConversations({page:C.page+1,limit:C.limit});if(x.current!==t)return;m(e=>{if(!e)return e;let t=new Set(e.conversations.map(e=>e.conversationId)),i=n.conversations.filter(e=>t.has(e.conversationId)?!1:(t.add(e.conversationId),!0)),a={conversations:[...e.conversations,...i],pagination:n.pagination};return r.saveHistoryCount(a.conversations.length),a})}catch(e){if(x.current!==t)return;rs.warn(`listConversations page failed`,{err:e,page:C.page+1})}finally{x.current===t&&(x.current=void 0,y(!1))}},T=o?g(`div`,{class:`${l}-history-footer`,children:_(`button`,{type:`button`,class:`${l}-history-new`,onClick:o,"data-testid":q.sidebarNewConversation,children:[g(wr,{}),t.newConversation]})}):null;if(d===`loading`){let e=Math.min(r.loadHistoryCount()??3,6);return _(h,{children:[g(`div`,{class:`${l}-history`,"aria-busy":`true`,"aria-label":t.historyLoading,children:_(`div`,{class:`${l}-history-group`,"aria-hidden":`true`,children:[g(`div`,{class:`${l}-history-heading`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-heading`})}),g(`div`,{class:`${l}-history-card`,children:Array.from({length:Math.max(1,e)},(e,t)=>_(`div`,{class:`${l}-history-item ${l}-history-item-skeleton`,children:[g(`span`,{class:`${l}-history-avatar ${l}-skeleton`}),_(`span`,{class:`${l}-history-body`,children:[_(`span`,{class:`${l}-history-row`,children:[g(`span`,{class:`${l}-history-title`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-title`})}),g(`span`,{class:`${l}-history-time`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-time`})})]}),g(`span`,{class:`${l}-history-row`,children:g(`span`,{class:`${l}-history-preview`,children:g(`span`,{class:`${l}-skeleton ${l}-skeleton-preview`})})})]})]},t))})]})}),T]})}if(d===`error`||S.length===0)return _(h,{children:[g(`div`,{class:`${l}-history-empty`,children:t.historyEmpty}),T]});let E=Date.now(),D=ts(E,S);return _(h,{children:[_(`div`,{class:`${l}-history`,role:`list`,children:[D.map(e=>_(`div`,{class:`${l}-history-group`,children:[g(`div`,{class:`${l}-history-heading`,children:t[is[e.bucket]]}),g(`div`,{class:`${l}-history-card`,children:e.conversations.map(e=>_(`button`,{type:`button`,role:`listitem`,class:`${l}-history-item`,onClick:()=>a(e),"data-closed":e.canContinue?void 0:`true`,"data-unread":e.hasUnread?`true`:void 0,"data-testid":Ci(q.historyItem,e.conversationId),children:[g(`span`,{class:`${l}-history-avatar`,"aria-hidden":`true`,children:g(Zr,{})}),_(`span`,{class:`${l}-history-body`,children:[_(`span`,{class:`${l}-history-row`,children:[g(`span`,{class:`${l}-history-title`,children:e.title}),g(`span`,{class:`${l}-history-time`,children:os(e.lastMessageAt,E,n)})]}),_(`span`,{class:`${l}-history-row`,children:[g(`span`,{class:`${l}-history-preview`,children:e.preview??(e.canContinue?t.historyContinue:t.conversationClosed)}),e.hasUnread?g(`span`,{class:`${l}-history-dot`}):null]})]})]},e.conversationId))})]},e.bucket)),C?.hasNext?g(`div`,{class:`${l}-history-more`,children:g(`button`,{type:`button`,onClick:w,disabled:v,"aria-busy":v,"data-testid":q.historyLoadMore,children:t.loadMoreConversations})}):null]}),T]})}const cs=b.cssPrefix;function ls({suggestions:e,onPick:t,disabled:n=!1}){return e.length===0?null:g(`div`,{class:`${cs}-suggestions`,role:`group`,"aria-label":`Suggested replies`,children:e.map((e,r)=>g(`button`,{type:`button`,class:`${cs}-suggestion`,onClick:()=>t(e),disabled:n,"data-testid":Ci(q.suggestion,r),children:e.label},e.id))})}const Z=b.cssPrefix;function us(e){let{options:t,onClose:n}=e,a=t.strings,o=s(null);i(()=>{let e=o.current;if(!e)return;let t=Ri(e),r=e=>{e.key===`Escape`&&n?.()};return e.addEventListener(`keydown`,r),()=>{t(),e.removeEventListener(`keydown`,r)}},[n]);let c=e.composerApiRef,l=e.composerActive&&e.view===`chat`&&e.canSend&&!e.activeForm&&!e.sendPreparing&&e.options.features.fileUpload,{visible:u}=ma({containerRef:o,onDrop:r(e=>{l&&c.current?.attachFromDrop(e)},[c,l]),disabled:!l});return Pi(o.current,t.mode===`modal`),_(`div`,{ref:o,class:`${Z}-panel`,role:`dialog`,"aria-modal":`false`,"aria-label":a.panelTitle,style:{position:`relative`},"data-testid":q.panel,children:[g(ds,{...e,containerEl:o.current,dragOver:u}),g(_s,{poweredBy:e.options.poweredBy})]})}function ds(e){let{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,composerKey:s,panelSize:c,view:l,canSend:u,isStreaming:d,isMemoryCompacting:f,canReleaseQueuedMessages:m,queueManualMessages:v,sendPreparing:y,controlMode:b,assignedOperatorInitials:x,operatorAvailable:S,operatorRequestEnabled:C,onRequestOperator:w,onCancelOperatorRequest:T,loadingMessages:E,onLoadPreviousMessages:D,messagesSig:O,agent:k,suggestions:A,initialWidgetSize:j,onClose:M,onBack:ee,onClear:te,onToggleHistory:N,onSelectHistoryConversation:ne,onNewConversation:re,onWidgetSizeChange:P,onSend:F,onStop:ie,onSuggestion:ae,activeForm:I,formMarkers:L,onFormSubmit:oe,onFormSkip:se,onFormFill:ce,tool:le,onRetry:ue,onMessageFeedback:de,containerEl:fe,dragOver:pe,composerApiRef:me}=e,R=t.strings,he=p(()=>O.value.some(e=>!e.ephemeral&&e.role!==`system`)).value,ge;return ge=I?null:u?_(h,{children:[b&&b!==`ai-agent`?g(ms,{controlMode:b,operatorInitials:x,operatorAvailable:S,onCancelOperatorRequest:T,strings:R}):null,f&&b===`ai-agent`?_(`div`,{class:`${Z}-loading ${Z}-compaction-status`,role:`status`,"data-testid":q.compactionStatus,children:[g(`span`,{class:`${Z}-loading-spinner`,"aria-hidden":`true`}),R.compactingContext]}):null,!d&&!f&&b===`ai-agent`&&g(ls,{suggestions:A,onPick:ae,disabled:y}),g(da,{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,isStreaming:d,isMemoryCompacting:f,canReleaseQueuedMessages:m,queueManualMessages:v,active:e.composerActive&&l===`chat`,isPreparing:y,operatorRequestEnabled:C,canRequestOperator:he,controlMode:b,onRequestOperator:w,onSend:F,onStop:ie,apiRef:me},s)]}):g(ps,{label:R.conversationClosed,ctaLabel:R.startNewConversation,onNewConversation:te}),_(h,{children:[l===`history`?g(fs,{strings:R,onBack:N,onClose:M,showClose:Ii(t.mode,c,t.actions)}):_(`header`,{class:`${Z}-header`,"data-testid":q.panelHeader,children:[ee?g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:ee,"aria-label":R.moduleBack,title:R.moduleBack,children:g(Kr,{})}):null,k?g(Vi,{agent:k,strings:R}):g(`h1`,{children:R.panelTitle}),g(Ca,{panelProps:e,variant:`chat`})]}),l===`history`?g(ss,{transport:n,strings:R,locale:t.locale,persistence:a,onSelect:ne,onNewConversation:re}):_(h,{children:[g(pa,{visible:pe,strings:R}),g(Yo,{messagesSig:O,strings:R,responseMode:t.responseMode,showReasoning:t.showReasoning,showToolCalls:t.showToolCalls,showSources:t.showSources,enableMessageFeedback:t.enableMessageFeedback,onFeedback:de,loading:E,onLoadPreviousMessages:D,idle:!d&&!y&&u&&!I,controlMode:b,tool:le,onRetry:ue,form:I?{form:I,onSubmit:oe,onSkip:se}:null,formMarkers:L,onFillForm:ce}),ge,g(gs,{disclaimer:t.composerDisclaimer})]}),t.size.resize?.enabled?g(ji,{panelEl:fe,resize:t.size.resize,position:t.position,initialSize:j,onSizeChange:P,strings:R}):null]})}function fs({strings:e,onBack:t,onClose:n,showClose:r}){return _(`header`,{class:`${Z}-header`,children:[g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:t,"aria-label":e.historyBack,title:e.historyBack,children:g(Kr,{})}),g(`h1`,{children:e.historyTitle}),r?g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:n,"aria-label":e.close,title:e.close,children:g(Cr,{})}):null]})}function ps({label:e,ctaLabel:t,onNewConversation:n}){return _(`div`,{class:`${Z}-readonly-banner`,role:`note`,children:[g(`span`,{class:`${Z}-readonly-label`,children:e}),g(`button`,{type:`button`,class:`${Z}-readonly-cta`,onClick:n,children:t})]})}function ms({controlMode:e,operatorInitials:t,operatorAvailable:n,onCancelOperatorRequest:r,strings:i}){let a=hs(e,t,n,i);return _(`div`,{class:`${Z}-operator-banner`,role:`status`,"data-mode":e,"data-testid":q.operatorBanner,children:[g(`span`,{class:`${Z}-operator-pulse`,"aria-hidden":`true`}),g(`span`,{class:`${Z}-operator-label`,children:a}),e===`awaiting-operator`&&r?g(`button`,{type:`button`,class:`${Z}-cancel-operator-request`,"data-testid":q.cancelOperatorRequest,onClick:r,children:i.cancelOperatorRequest}):null]})}function hs(e,t,n,r){return e===`operator`?r.chattingWithOperator.replace(`{operator}`,t??``):n===!1?r.noOperatorAvailable:r.connectingOperator}function gs({disclaimer:e}){return e?g(`div`,{class:`${Z}-composer-footer`,children:g(`div`,{class:`${Z}-disclaimer`,children:e})}):null}function _s({poweredBy:e}){return e?g(`div`,{class:`${Z}-poweredby-bar`,children:g(vs,{logoUrl:e.logoUrl,text:e.text,href:e.href})}):null}function vs({logoUrl:e,text:t,href:n}){let r=_(h,{children:[e?g(`img`,{class:`${Z}-poweredby-logo`,src:e,alt:``,loading:`lazy`}):null,t?g(`span`,{children:t}):null]});return n?g(`a`,{class:`${Z}-poweredby`,href:n,target:`_blank`,rel:`noopener noreferrer`,children:r}):g(`span`,{class:`${Z}-poweredby`,children:r})}function ys(e){let t=s(e);t.current=e;let n=s(null);return n.current??(n.current=bs(t)),n.current}function bs(e){let t=f(null),n=new Set,r=t=>`${e.current.conversationId()??``}:${t}`,i=t=>t.frequency===`always`?!1:t.frequency===`conversation`?n.has(r(t.id)):t.id in e.current.persistence.loadFormsDone(),a=(n,r)=>{if(t.value)return;let a=e.current;if(n===`manual`){let e=a.forms.list.find(e=>e.id===r);e&&(t.value={form:e,trigger:`manual`});return}for(let e of a.forms.byTrigger[n]??[]){let r=e.triggers.find(e=>e.kind===n);if(!(!r||!xs(r,a)||i(e)||!Ss(e,a))){t.value={form:e,trigger:n};return}}},o=(i,a)=>{let o=t.value;if(!o)return;t.value=null;let{form:s,trigger:c}=o;s.frequency===`conversation`?n.add(r(s.id)):s.frequency!==`always`&&e.current.persistence.saveFormDone(s.id),e.current.onComplete(s,c,i,a)};return{activeForm:t,fire:a,refresh:()=>{let n=t.value;if(!n)return;let r=e.current.forms.list.find(e=>e.id===n.form.id);r&&r!==n.form&&(t.value={form:r,trigger:n.trigger})},complete:e=>o(e,!1),skip:()=>o({},!0)}}function xs(e,t){return e.kind===`after-messages`?t.messageCount()>=Number(e.param??0):e.kind!==`page-area`||t.pageArea()===e.param}function Ss(e,t){let n=e.when;if(!n)return!0;if(n.missingContext?.length){let e=t.userContext()??{};if(n.missingContext.some(t=>e[t]!==void 0&&e[t]!==``))return!1}if(n.pageArea&&!(Array.isArray(n.pageArea)?n.pageArea:[n.pageArea]).includes(t.pageArea()??``))return!1;let r=t.messageCount();return!(n.minMessages!=null&&r<n.minMessages||n.maxMessages!=null&&r>n.maxMessages)}function Cs(e){let t=b.cssPrefix,{site:n,blocks:r,strings:i,collapsed:a}=e,o=r?.navigation??[],s=r?.linkCards??[],c=a?i.expandSidebar:i.collapseSidebar;return _(`aside`,{class:`${t}-sidebar`,"data-collapsed":a?`true`:`false`,"data-testid":q.sidebar,children:[_(`div`,{class:`${t}-sidebar-header`,children:[g(ws,{site:n}),g(`button`,{type:`button`,class:`${t}-sidebar-toggle`,"aria-label":c,"aria-expanded":a?`false`:`true`,title:c,onClick:e.onToggleCollapsed,"data-testid":q.sidebarToggle,children:g(Ts,{collapsed:a})})]}),a?null:_(h,{children:[o.length>0?g(`nav`,{class:`${t}-sidebar-section`,"data-section":`navigation`,children:g(Es,{items:o})}):null,s.length>0?g(`div`,{class:`${t}-sidebar-section`,"data-section":`link-cards`,children:g(Ds,{items:s})}):null,e.showConversations?g(`div`,{class:`${t}-sidebar-conversations`,children:g(ss,{transport:e.transport,strings:e.strings,locale:e.locale,persistence:e.persistence,onSelect:e.onSelectConversation,onNewConversation:e.onNewConversation})}):null]})]})}function ws({site:e}){let t=b.cssPrefix;if(e?.logo?.url){let n=e.logo.alt??e.title??`Logo`;return _(`picture`,{children:[e.logoDark?.url?g(`source`,{srcset:e.logoDark.url,media:`(prefers-color-scheme: dark)`}):null,g(`img`,{class:`${t}-sidebar-logo`,src:e.logo.url,alt:n})]})}return g(`div`,{class:`${t}-sidebar-title`,children:e?.title??b.name})}function Ts({collapsed:e}){return g(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`,"aria-hidden":`true`,children:e?g(`polyline`,{points:`9 6 15 12 9 18`}):g(`polyline`,{points:`15 6 9 12 15 18`})})}function Es({items:e}){let t=b.cssPrefix;return g(`ul`,{class:`${t}-sidebar-nav`,children:e.map(e=>g(`li`,{children:_(`a`,{class:`${t}-sidebar-nav-item`,href:e.href,target:e.href?`_blank`:void 0,rel:e.href?`noreferrer`:void 0,children:[e.icon?g(`span`,{class:`${t}-sidebar-nav-icon`,"data-icon":e.icon}):null,g(`span`,{class:`${t}-sidebar-nav-label`,children:e.label})]})},e.id??e.label))})}function Ds({items:e}){let t=b.cssPrefix;return g(`div`,{class:`${t}-sidebar-cards`,children:e.map(e=>_(`a`,{class:`${t}-sidebar-card`,href:e.href,target:e.href?`_blank`:void 0,rel:e.href?`noreferrer`:void 0,children:[g(`div`,{class:`${t}-sidebar-card-label`,children:e.label}),e.description?g(`div`,{class:`${t}-sidebar-card-desc`,children:e.description}):null]},e.id??e.label))})}const Os=b.cssPrefix;function ks(e){return _(`main`,{class:`${Os}-page-shell`,"data-sidebar-collapsed":e.sidebarCollapsed?`true`:`false`,children:[g(Cs,{site:e.site,blocks:e.blocks,transport:e.transport,strings:e.strings,locale:e.locale,persistence:e.persistence,showConversations:e.showConversations,onSelectConversation:e.onSelectConversation,onNewConversation:e.onNewConversation,collapsed:e.sidebarCollapsed,onToggleCollapsed:e.onToggleSidebarCollapsed}),g(`section`,{class:`${Os}-page-chat`,"aria-label":e.strings.panelTitle,children:e.children})]})}const As=e=>Object.fromEntries(e.map(e=>[e,[]]));function js(e,t,n){return e.includes(t)?t:e.includes(n)?n:e[0]??``}function Ms(e,t,n){let r=[...new Set(t)],i=f({activeTab:js(r,e,``),stacks:As(r)});return{sig:i,reconcile(e,t){let a=[...new Set(e)],o=i.value,s=js(a,o.activeTab,t),c=Object.fromEntries(a.map(e=>[e,o.stacks[e]??[]])),l=s===o.activeTab&&a.length===Object.keys(o.stacks).length&&a.every(e=>o.stacks[e]===c[e]);r=a,!l&&(i.value={activeTab:s,stacks:c},s!==o.activeTab&&s&&n?.(s))},switchTab(e){!(e in i.value.stacks)||i.value.activeTab===e||(i.value={...i.value,activeTab:e},n?.(e))},push(e){let t=i.value,n=t.stacks[t.activeTab]??[];i.value={...t,stacks:{...t.stacks,[t.activeTab]:[...n,e]}}},pop(){let e=i.value,t=e.stacks[e.activeTab]??[];t.length!==0&&(i.value={...e,stacks:{...e.stacks,[e.activeTab]:t.slice(0,-1)}})},reset(e){i.value={activeTab:js(r,e,``),stacks:As(r)}}}}const Ns=e=>e.stacks[e.activeTab]??[],Ps=e=>Ns(e).at(-1),Fs=e=>Ns(e).length===0,Is={Icon:si},Ls=b.cssPrefix;function Rs({title:e,actions:t}){return _(`header`,{class:`${Ls}-back-header`,"data-variant":`title`,children:[g(`span`,{class:`${Ls}-back-spacer`,"aria-hidden":`true`}),g(`h1`,{class:`${Ls}-back-title`,children:e}),t??g(`span`,{class:`${Ls}-back-spacer`,"aria-hidden":`true`})]})}function zs({title:e,backLabel:t,onBack:n,actions:r,testid:i}){return _(`header`,{class:`${Ls}-back-header`,"data-testid":i,children:[g(`button`,{type:`button`,class:`${Ls}-icon-btn`,onClick:n,"aria-label":t,title:t,children:g(Kr,{})}),g(`h1`,{class:`${Ls}-back-title`,children:e}),r??g(`span`,{class:`${Ls}-back-spacer`,"aria-hidden":`true`})]})}function Bs(e,t){return e instanceof Vt&&e.status===429?t.errorRateLimited:t.errorGeneric}const Vs=b.cssPrefix;function Hs({placeholder:e,onActivate:t}){return _(`button`,{type:`button`,class:`${Vs}-home-search`,onClick:t,"data-testid":q.homeSearch,children:[g(`span`,{class:`${Vs}-home-search-text`,children:e}),g(`span`,{class:`${Vs}-home-search-icon`,"aria-hidden":`true`,children:g(ri,{})})]})}function Us({placeholder:e,value:t,onInput:n}){return _(`div`,{class:`${Vs}-home-search`,"data-input":`true`,children:[g(`input`,{type:`search`,class:`${Vs}-home-search-input`,placeholder:e,value:t,onInput:e=>n(e.currentTarget.value),"data-testid":q.helpSearch}),g(`span`,{class:`${Vs}-home-search-icon`,"aria-hidden":`true`,children:g(ri,{})})]})}const Ws=b.cssPrefix;function Gs({title:e,subtitle:t,onClick:n,testid:r}){return _(`button`,{type:`button`,class:`${Ws}-list-row`,onClick:n,"data-testid":r,children:[_(`span`,{class:`${Ws}-list-row-body`,children:[g(`span`,{class:`${Ws}-list-row-title`,children:e}),t?g(`span`,{class:`${Ws}-list-row-sub`,children:t}):null]}),g(`span`,{class:`${Ws}-list-row-chevron`,"aria-hidden":`true`,children:g(Or,{})})]})}const Ks=b.cssPrefix;function qs({tone:e=`info`,message:t,onRetry:n,strings:r}){return _(`div`,{class:`${Ks}-module-empty`,role:e===`error`?`alert`:`status`,"aria-live":`polite`,children:[g(`span`,{children:t}),n?g(`button`,{type:`button`,class:`${Ks}-module-retry`,onClick:n,children:r.errorRetry}):null]})}const Js=b.cssPrefix,Ys=I.scope(`help`),Xs=(e,t)=>t.url?e.push({kind:`iframe`,url:t.url,title:t.title}):e.push({kind:`content`,id:t.id,title:t.title});function Zs(e){let t=new Map;for(let n of e){let e=n.categories?.[0]??``;(t.get(e)??t.set(e,[]).get(e)).push(n)}return[...t.entries()]}function Qs(e,t){let n=t.toLowerCase(),r=n.indexOf(e);if(r!==-1)return 100-Math.min(r,99);let i=0;for(let t of e){if(i=n.indexOf(t,i),i===-1)return 0;i+=1}return 1}function $s(e,t){let n=t.toLowerCase().trim();return n?e.map(e=>({item:e,score:Math.max(Qs(n,e.title)*2,Qs(n,e.description??``))})).filter(e=>e.score>0).toSorted((e,t)=>t.score-e.score).map(e=>e.item):[]}function ec({article:e,nav:t}){return g(Gs,{title:e.title,subtitle:e.description,onClick:()=>Xs(t,e),testid:Ci(q.helpArticle,e.id)})}function tc({transport:e,strings:t,config:n,nav:r,bus:a,panelProps:s}){let l=n.contentTags,[u,d]=c(`loading`),[f,p]=c(t.errorGeneric),[m,h]=c([]),[v,y]=c(``),[b,x]=c(0);i(()=>{let n=!1;return d(`loading`),e.listContent({tags:l,sortBy:`order`,limit:100}).then(e=>{if(n)return;let t=e.items??[];h(t),d(`loaded`),a.emit(`contentView`,{section:`help`,tags:l?.join(`,`),count:t.length})}).catch(e=>{n||(Ys.warn(`listContent (help) failed`,{err:e}),p(Bs(e,t)),d(`error`))}),()=>{n=!0}},[e,l,b,a]);let S=o(()=>$s(m,v),[m,v]);i(()=>{let e=v.trim();if(!e)return;let t=setTimeout(()=>a.emit(`contentSearch`,{queryLength:e.length,hitCount:S.length}),600);return()=>clearTimeout(t)},[v,S,a]);function C(){return v.trim().length>0?S.length===0?g(qs,{message:t.helpSearchEmpty,strings:t}):g(`div`,{class:`${Js}-help-card`,children:S.map(e=>g(ec,{article:e,nav:r},e.id))}):u===`loading`?g(qs,{message:t.helpLoading,strings:t}):u===`error`?g(qs,{tone:`error`,message:f,onRetry:()=>x(e=>e+1),strings:t}):m.length===0?g(qs,{message:t.helpEmpty,strings:t}):Zs(m).map(([e,t])=>_(`section`,{class:`${Js}-help-group`,children:[e?g(`h2`,{class:`${Js}-help-section-title`,children:e}):null,g(`div`,{class:`${Js}-help-card`,children:t.map(e=>g(ec,{article:e,nav:r},e.id))})]},e))}return _(`div`,{class:`${Js}-module`,children:[g(Rs,{title:t.helpTitle,actions:g(Ca,{panelProps:s,variant:`plain`})}),g(`div`,{class:`${Js}-module-pad`,children:g(Us,{placeholder:t.helpSearchPlaceholder,value:v,onInput:y})}),g(`div`,{class:`${Js}-help-list`,children:C()})]})}const nc={Icon:Qr,Root:e=>g(tc,{...e})},rc=b.cssPrefix;function ic({onClick:e,children:t,testid:n}){return e?g(`button`,{type:`button`,class:`${rc}-home-card`,"data-interactive":`true`,onClick:e,"data-testid":n,children:t}):g(`div`,{class:`${rc}-home-card`,"data-testid":n,children:t})}const Q=b.cssPrefix,ac=I.scope(`home`);function oc(e){let t=e.options.userContext?.name,n=e.config.greetingText?D(e.strings,e.config.greetingText):void 0;return n?{title:t?n.replace(`{name}`,t):n.replace(/\s*\{name\}\s*/,` `).trim(),subtitle:e.strings.homeGreetingLead}:t?{title:e.strings.homeGreetingNamed.replace(`{name}`,t),subtitle:e.strings.homeGreetingLead}:{title:e.strings.homeGreeting}}const sc=(e,t)=>t.url?e.push({kind:`iframe`,url:t.url,title:t.title}):e.push({kind:`content`,id:t.id,title:t.title});function cc(e,t){return pn(e,t,t.type!==`upsert`||t.activity===!0)}function lc(e){let{transport:t,strings:n,config:r,nav:a,bus:o,panelProps:s}=e,[l,u]=c(null),[d,f]=c([]),p=r.contentTags?.join(`,`),m=e.options.modules.list.some(e=>e.layout===`chat`);i(()=>{if(r.showRecentConversations===!1)return;let e=!1,n=!0,i=[],a=t.subscribeConversationChanges(e=>{n&&i.push(e),u(t=>cc(t?[t]:[],e)[0]??null)});return t.listConversations({limit:m?50:1}).then(t=>{if(e)return;let r=i.reduce(cc,t.conversations);i=[],n=!1,u(r[0]??null)}).catch(t=>{e||(i=[],n=!1,ac.warn(`listConversations (home) failed`,{err:t}))}),()=>{e=!0,a()}},[t,r.showRecentConversations,m]),i(()=>{if(!r.contentTags?.length)return;let e=!1;return t.listContent({tags:r.contentTags,limit:6}).then(t=>{if(e)return;let n=t.items??[];f(n),o.emit(`contentView`,{section:`home`,tags:p,count:n.length})}).catch(t=>!e&&ac.warn(`listContent (home) failed`,{err:t})),()=>{e=!0}},[t,p,o]);let v=oc(e),y=r.userAvatars??[],b=r.status,x=b?.text?D(n,b.text):n.homeStatus,S=r.contentBlockTitle?D(n,r.contentBlockTitle):n.homeContentTitle;return g(`div`,{class:`${Q}-module ${Q}-home`,"data-testid":q.homeView,children:_(`div`,{class:`${Q}-home-scroll`,children:[_(`div`,{class:`${Q}-home-hero`,children:[_(`div`,{class:`${Q}-home-hero-top`,children:[r.brandName?g(`span`,{class:`${Q}-home-brand`,"data-testid":q.homeBrand,children:r.brandName}):g(`span`,{class:`${Q}-home-brand-spacer`,"aria-hidden":`true`}),_(`div`,{class:`${Q}-home-hero-actions`,children:[y.length>0?g(`div`,{class:`${Q}-home-avatars`,children:y.map(e=>g(`span`,{class:`${Q}-home-avatar`,title:e.role?`${e.name} · ${e.role}`:e.name,children:e.avatar?g(`img`,{src:e.avatar,alt:``,loading:`lazy`}):g(`span`,{children:zi(e.name)})},e.name))}):null,g(Ca,{panelProps:s,variant:`plain`})]})]}),r.showGreeting===!1?null:_(h,{children:[g(`h1`,{class:`${Q}-home-greeting`,"data-testid":q.homeGreeting,children:v.title}),v.subtitle?g(`p`,{class:`${Q}-home-lead`,children:v.subtitle}):null]})]}),_(`div`,{class:`${Q}-home-cards`,children:[r.showSearchBar===!1?null:g(Hs,{placeholder:n.homeSearchPlaceholder,onActivate:()=>a.switchToLayout(`help`)}),l?g(ic,{onClick:()=>a.selectConversation(l),testid:q.homeRecent,children:_(`div`,{class:`${Q}-home-recent-row`,"data-unread":l.hasUnread?`true`:void 0,children:[g(`span`,{class:`${Q}-home-recent-avatar`,"aria-hidden":`true`,children:g(si,{})}),_(`span`,{class:`${Q}-home-recent-body`,children:[g(`span`,{class:`${Q}-home-recent-title`,children:l.title}),l.preview?g(`span`,{class:`${Q}-home-recent-preview`,children:l.preview}):null]}),l.hasUnread?g(`span`,{class:`${Q}-home-recent-dot`,"aria-label":`Unread`}):null]})}):null,b?g(ic,{onClick:b.url?()=>a.push({kind:`iframe`,url:b.url,title:x}):void 0,children:_(`div`,{class:`${Q}-home-status`,"data-level":b.level??`operational`,children:[g(`span`,{class:`${Q}-home-status-icon`,"aria-hidden":`true`,children:g(ii,{})}),g(`span`,{class:`${Q}-home-status-text`,children:x})]})}):null,d.length>0?_(`section`,{class:`${Q}-home-content`,children:[g(`div`,{class:`${Q}-home-content-title`,children:S}),g(`div`,{class:`${Q}-home-content-list`,children:d.map(e=>g(Gs,{title:e.title,subtitle:e.description,onClick:()=>sc(a,e),testid:Ci(q.homeContentRow,e.id)},e.id))})]}):null]})]})})}const uc={Icon:ai,Root:e=>g(lc,{...e})},dc=b.cssPrefix,fc=I.scope(`news`);function pc({transport:e,strings:t,config:n,nav:r,bus:a,panelProps:o}){let s=n.contentTags,[l,u]=c(`loading`),[d,f]=c(t.errorGeneric),[p,m]=c([]),[h,v]=c(0);i(()=>{let n=!1;return u(`loading`),e.listContent({tags:s,sortBy:`publishedAt`,sortOrder:`desc`}).then(e=>{if(n)return;let t=e.items??[];m(t),u(`loaded`),a.emit(`contentView`,{section:`news`,tags:s?.join(`,`),count:t.length})}).catch(e=>{n||(fc.warn(`listContent (news) failed`,{err:e}),f(Bs(e,t)),u(`error`))}),()=>{n=!0}},[e,s,h,a]);function y(){return l===`loading`?g(qs,{message:t.newsLoading,strings:t}):l===`error`?g(qs,{tone:`error`,message:d,onRetry:()=>v(e=>e+1),strings:t}):p.length===0?g(qs,{message:t.newsEmpty,strings:t}):g(`div`,{class:`${dc}-news-list`,children:p.map(e=>_(`button`,{type:`button`,class:`${dc}-news-card`,onClick:()=>r.push({kind:`content`,id:e.id,title:e.title}),"data-testid":Ci(q.newsItem,e.id),children:[e.image?g(`img`,{class:`${dc}-news-hero`,src:e.image,alt:``,loading:`lazy`}):null,_(`span`,{class:`${dc}-news-body`,children:[g(`span`,{class:`${dc}-news-title`,children:e.title}),e.description?g(`span`,{class:`${dc}-news-summary`,children:e.description}):null]})]},e.id))})}return _(`div`,{class:`${dc}-module`,children:[g(Rs,{title:t.newsTitle,actions:g(Ca,{panelProps:o,variant:`plain`})}),g(`div`,{class:`${dc}-module-scroll`,children:y()})]})}const mc={chat:Is,home:uc,help:nc,news:{Icon:oi,Root:e=>g(pc,{...e})}},hc=b.cssPrefix;function gc({modules:e,activeTab:t,strings:n,hasUnread:r,onSelect:i}){return g(`nav`,{class:`${hc}-tabbar`,role:`tablist`,"aria-label":n.panelTitle,children:e.map(e=>{let a=mc[e.layout].Icon,o=e.id===t,s=e.layout===`chat`&&r;return _(`button`,{type:`button`,role:`tab`,"aria-selected":o,class:`${hc}-tab`,onClick:()=>i(e.id),"data-testid":Ci(q.tab,e.id),children:[_(`span`,{class:`${hc}-tab-icon`,"aria-hidden":`true`,children:[g(a,{}),s?g(`span`,{class:`${hc}-tab-badge`,"data-testid":q.tabBadge,"aria-label":`Unread`}):null]}),g(`span`,{class:`${hc}-tab-label`,children:D(n,e.label)})]},e.id)})})}const _c=b.cssPrefix;function vc({url:e,title:t,strings:n,onBack:r,actions:i}){return _(`div`,{class:`${_c}-module`,children:[g(zs,{title:t||n.moduleBack,backLabel:n.moduleBack,onBack:r,actions:i}),g(`iframe`,{class:`${_c}-content-frame`,src:e,title:t||`content`,sandbox:`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads`,referrerpolicy:`no-referrer`,loading:`lazy`,allow:`fullscreen`})]})}const yc=b.cssPrefix,bc=I.scope(`content`);function xc({id:e,title:t,transport:n,strings:a,bus:o,onBack:s,actions:l}){let[u,d]=c(null),[f,p]=c(!1),[m,h]=c(0),v=r(()=>{p(!1),d(null),h(e=>e+1)},[]);i(()=>{let t=!1;return n.listContent({ids:[e],limit:1}).then(n=>{if(t)return;let r=n.items[0];r?(d(r),o.emit(`contentOpen`,{contentId:e,tags:r.tags?.length?r.tags.join(`,`):void 0})):p(!0)}).catch(e=>{t||(bc.warn(`listContent (reader) failed`,{err:e}),p(!0))}),()=>{t=!0}},[n,e,m,o]),i(()=>{if(!u)return;let t=setTimeout(()=>o.emit(`contentRead`,{contentId:e}),5e3);return()=>clearTimeout(t)},[u,e,o]);let y=r(t=>{let n=(t.target?.closest?.(`a`))?.getAttribute(`href`)??``;n&&!n.startsWith(`#`)&&o.emit(`contentLinkClick`,{contentId:e})},[o,e]);function b(){return f?g(qs,{tone:`error`,message:a.errorGeneric,onRetry:v,strings:a}):u===null?g(qs,{message:a.contentLoading,strings:a}):_(`article`,{class:`${yc}-content`,"data-testid":q.contentView,onClick:y,children:[u.image?g(`img`,{class:`${yc}-content-hero`,src:u.image,alt:``,loading:`lazy`}):null,u.description?g(`p`,{class:`${yc}-content-subtitle`,children:u.description}):null,g(uo,{text:u.content??``})]})}return _(`div`,{class:`${yc}-module`,children:[g(zs,{title:u?.title||t||a.moduleBack,backLabel:a.moduleBack,onBack:s,actions:l,testid:q.backHeader}),g(`div`,{class:`${yc}-module-scroll`,"data-testid":q.contentScroll,children:b()})]})}const Sc=b.cssPrefix;function Cc({panelProps:e,enabledModules:t,nav:n,bus:a,hasUnread:o,onSelectConversation:c,onStartNewConversation:l,onSetPanelSize:u}){let d=e.options,f=d.strings,m=s(null),h=s(new Set);i(()=>{let t=m.current;if(!t)return;let n=Ri(t),r=t=>{t.key===`Escape`&&e.onClose?.()};return t.addEventListener(`keydown`,r),()=>{n(),t.removeEventListener(`keydown`,r)}},[e.onClose]);let v=p(()=>n.sig.value).value,y=Ps(v),b=d.modules.byId[v.activeTab],x=e.composerActive&&b?.layout===`chat`&&y===void 0,S=e.composerApiRef,C=x&&e.view===`chat`&&e.canSend&&!e.activeForm&&!e.sendPreparing&&e.options.features.fileUpload,{visible:w}=ma({containerRef:m,onDrop:r(e=>{C&&S.current?.attachFromDrop(e)},[S,C]),disabled:!C});Pi(m.current,d.mode===`modal`);let T=y?.kind===`iframe`||y?.kind===`content`,E=t.length>1&&(Fs(v)||!T),D=s(null);i(()=>{if(T&&D.current===null)D.current=e.panelSize,e.panelSize===`normal`&&u(`expanded`);else if(!T&&D.current!==null){let e=D.current;D.current=null,u(e)}},[T]);let O={push:e=>n.push(e),pop:()=>n.pop(),switchTab:e=>n.switchTab(e),switchToLayout:e=>{let r=t.find(t=>t.layout===e);r&&n.switchTab(r.id)},selectConversation:c,startNewConversation:l},k=t=>({options:d,transport:e.transport,strings:f,config:t,nav:O,bus:a,panelProps:e}),A=g(Ca,{panelProps:e,variant:`plain`});b&&h.current.add(b.id);let j=t.filter(e=>h.current.has(e.id)),M=t=>{if(t.layout===`chat`)return g(ds,{...e,composerActive:x,containerEl:m.current,dragOver:w});let n=mc[t.layout].Root;return n?g(n,{...k(t)}):null};return _(`div`,{ref:m,class:`${Sc}-panel ${Sc}-messenger`,role:`dialog`,"aria-modal":`false`,"aria-label":f.panelTitle,style:{position:`relative`},"data-testid":q.messengerHome,children:[_(`div`,{class:`${Sc}-messenger-body`,children:[j.map(e=>g(`div`,{class:`${Sc}-messenger-pane`,hidden:T||e.id!==b?.id,children:M(e)},e.id)),y?.kind===`iframe`?g(vc,{url:y.url,title:y.title,strings:f,onBack:()=>n.pop(),actions:A}):y?.kind===`content`?g(xc,{id:y.id,title:y.title,transport:e.transport,strings:f,bus:a,onBack:()=>n.pop(),actions:A}):null]}),E?g(gc,{modules:t,activeTab:v.activeTab,strings:f,hasUnread:o,onSelect:e=>n.switchTab(e)}):null,g(_s,{poweredBy:d.poweredBy}),d.size.resize?.enabled&&!(b?.layout===`chat`&&!y)?g(ji,{panelEl:m.current,resize:d.size.resize,position:d.position,initialSize:e.initialWidgetSize,onSizeChange:e.onWidgetSizeChange,strings:f}):null]})}const wc=b.cssPrefix;function Tc({strings:e,onClose:t}){return _(`div`,{class:`${wc}-panel ${wc}-modules-empty`,role:`dialog`,"aria-label":e.panelTitle,"data-testid":q.modulesEmpty,children:[t?g(`button`,{type:`button`,class:`${wc}-icon-btn ${wc}-modules-empty-close`,onClick:t,"aria-label":e.close,title:e.close,children:g(Cr,{})}):null,g(`p`,{class:`${wc}-modules-empty-text`,children:e.modulesEmpty})]})}function Ec(e,t,n,r){let i={role:n,text:r};e.emit(`message`,i),t.onMessage?.(i)}const Dc=I.scope(`hitl`);function Oc(e){let{streaming:t,controlModeSig:n,messagesSig:i,sendAiTurn:a,bus:c,humanInLoop:l}=e,u=s(t);u.current=t;let d=r((e,t,r)=>{if(u.current||n.value!==`ai-agent`)return!1;let o=i.value.at(-1),s=o?.partsSig.value.findIndex(t=>t.kind===`tool`&&t.toolCallId===e)??-1,c=o?.partsSig.value[s];return!o||c?.kind!==`tool`?(Dc.warn(`decideTool: tool part not found`,{toolCallId:e}),!1):o.status!==`complete`||!Un(o,s)||!t(c)?!1:(r(c),o.partsSig.value=[...o.partsSig.value],Vn(o)?(o.status=`streaming`,o.retryAction={kind:`continue-assistant`,messageId:o.serverMessageId??o.id},o.awaitingContinuation=!0,i.value=[...i.value],a({continueExisting:!0}),!0):!0)},[n,i,a]),f=r((e,t,n)=>{let r=!1;if(d(e,e=>e.stateSig.value===`approval-requested`,i=>{r=Ha(i.toolName);let a=i.approvalSig.value?.id??e;i.approvalSig.value={id:a,approved:t,reason:n},i.stateSig.value=`approval-responded`})){if(r){Dc.info(`toolResult`,{toolCallId:e}),c.emit(`toolResult`,{toolCallId:e});return}Dc.info(`toolDecision`,{toolCallId:e,approved:t}),c.emit(`toolDecision`,{toolCallId:e,approved:t})}},[c,d]),p=r(e=>{d(e,e=>e.stateSig.value===`approval-responded`&&e.approvalSig.value?.approved!==void 0,t=>{let n=t.approvalSig.value?.id??e;t.approvalSig.value={id:n},t.stateSig.value=`approval-requested`})},[d]);return{toolInteraction:o(()=>({humanInLoop:l,onDecision:f,onEdit:p}),[l,f,p])}}function kc({callout:e,persistence:t}){let n=e?.text??``,a=e?.persistent??!0,[o,s]=c(()=>!a&&t.loadCalloutDismissed(n));return i(()=>{s(!a&&t.loadCalloutDismissed(n))},[n,a,t]),{dismissed:o,dismissCallout:r(()=>{s(!0),a||t.saveCalloutDismissed(n)},[t,n,a])}}function Ac(e){let{transport:t,conversationIdSig:n}=e,i=m(`ai-agent`),a=m(void 0),o=m(void 0),c=s(),l=r(e=>{let t=e.controlRevision,r=c.current;r&&r.conversationId===n.value&&t<r.revision||(c.current={conversationId:n.value,revision:t},i.value=e.controlMode,a.value=e.assignedOperatorInitials,e.controlMode===`awaiting-operator`?e.operatorAvailable!==void 0&&(o.value=e.operatorAvailable):o.value=void 0)},[n,i,a,o]);return{controlModeSig:i,assignedOperatorInitialsSig:a,operatorAvailableSig:o,applyControlState:l,adoptControlStateChunk:r(e=>{if(e.type!==`data-control-state`)return;let t=$t(e.data);t&&l(t)},[l]),requestOperator:r(async()=>{let e=n.value,r=await t.requestOperator();r&&n.value===e&&l(r)},[t,n,l]),cancelOperatorRequest:r(async()=>{let e=n.value,r=await t.cancelOperatorRequest();r&&n.value===e&&l(r)},[t,n,l])}}const jc=b.cssPrefix,Mc=`--${jc}-visual-viewport-height`,Nc=`--${jc}-visual-viewport-top`;function Pc(e){let{hostElement:t,mode:n,panelSize:r,isOpen:o,surfaceReady:s,setIsOpen:c}=e;a(()=>{Dt(t,Pt(n,r,o))},[t,o,r,n]),a(()=>{if(!o||!s)return;let e=t.ownerDocument.defaultView,n=e?.visualViewport,r=t.shadowRoot?.querySelector(`.${jc}-anchor`);if(!e||!n||!r)return;let i=()=>{r.style.setProperty(Mc,`${n.height}px`),r.style.setProperty(Nc,`${n.offsetTop}px`)},a=0,c=()=>{e.cancelAnimationFrame(a),a=e.requestAnimationFrame(()=>{a=e.requestAnimationFrame(i)})};return i(),n.addEventListener(`resize`,c),n.addEventListener(`scroll`,c),()=>{e.cancelAnimationFrame(a),n.removeEventListener(`resize`,c),n.removeEventListener(`scroll`,c),r.style.removeProperty(Mc),r.style.removeProperty(Nc)}},[t,o,s]),i(()=>{if(n!==`modal`||!o)return;let e=e=>{e.composedPath().some(e=>e instanceof HTMLElement&&e.classList.contains(`${jc}-panel`))||c(!1)};return t.addEventListener(`click`,e),()=>t.removeEventListener(`click`,e)},[t,o,n,c]),i(()=>{if(n!==`drawer`||!o)return;let e=e=>{e.key===`Escape`&&c(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[o,n,c])}const Fc=I.scope(`reducer`);var Ic=class{constructor(e,t){this.messagesSig=e,this.onReconcileNeeded=t,U(this,`active`,null),U(this,`openTextParts`,new Map),U(this,`partSeq`,0),U(this,`replay`,null)}attach(e){this.active=e,this.openTextParts.clear()}detach(){this.active=null,this.replay=null,this.openTextParts.clear()}beginReplay(e,t){let n=Cn();n.id=e.id;let r=Rc(e)||Hn(e)&&(e.status!==`streaming`||Vn(e)),i=e.status===`streaming`&&Vn(e)&&Bn(e);this.replay={baseline:e,shadow:n,chunks:[t],probeContinuation:r,continuationTailReplay:i,liveCatchUp:e.status===`streaming`&&!r},this.attach(n),this.apply(t)}refreshReplayBaseline(){let e=this.replay;if(!e)return null;let t=e.shadow.serverMessageId??e.baseline.serverMessageId,n=this.messagesSig.value,r=n.at(-1),i=r===e.baseline||r?.id===e.baseline.id||t!==void 0&&r?.serverMessageId===t?r:n.find(t=>t===e.baseline)??n.find(n=>n.id===e.baseline.id||t!==void 0&&n.serverMessageId===t);if(!i)return this.detach(),null;if(i===e.baseline)return e;let a=e.baseline;return e.baseline=i,zc(a,i),e.liveCatchUp&&Rc(e.shadow)&&(i.status===`streaming`||Hn(i))?(e.probeContinuation=!1,e.continuationTailReplay=!1,e):(e.probeContinuation=Rc(i)||Hn(i)&&(i.status!==`streaming`||Vn(i)),e.continuationTailReplay=i.status===`streaming`&&Vn(i)&&Bn(i),e.liveCatchUp=i.status===`streaming`&&!e.probeContinuation,e)}refreshActive(){let e=this.active;if(!e)return null;let t=e.serverMessageId,n=this.messagesSig.value,r=n.at(-1),i=r===e||r?.id===e.id||t!==void 0&&r?.serverMessageId===t?r:n.find(t=>t===e)??n.find(n=>n.id===e.id||t!==void 0&&n.serverMessageId===t);if(!i)return this.detach(),null;if(i===e)return e;zc(e,i);let a=Rc(e)&&Hn(i);return i.status!==`streaming`&&!a?(this.detach(),null):(this.replay={baseline:i,shadow:e,chunks:[],probeContinuation:!1,continuationTailReplay:!1,liveCatchUp:!0},e)}promoteReplay(){let{baseline:e,shadow:t}=this.replay;return l(()=>{e.role=t.role,e.serverMessageId=t.serverMessageId,e.operatorInitials=t.operatorInitials,e.status=t.status,t.canceled&&(e.canceled=!0),e.finishReason=t.finishReason,e.errorText=t.errorText,e.suggestions=t.suggestions??e.suggestions,e.partsSig.value=t.partsSig.value,this.messagesSig.value=[...this.messagesSig.value]}),this.replay=null,this.active=e,e}promoteContinuation(e=!1){let{baseline:t,chunks:n}=this.replay,r=Wn(t);return this.replay=null,l(()=>{if(e){let e=t.partsSig.value.findLastIndex(e=>e.kind===`tool`);t.partsSig.value=t.partsSig.value.slice(0,e+1)}t.awaitingContinuation=!1,t.status=`streaming`,t.finishReason=void 0,t.errorText=void 0,t.suggestions=void 0,this.attach(t);for(let e of n)this.apply(e);t.continuationStreaming=r||void 0,this.messagesSig.value=[...this.messagesSig.value]}),t}settleOwnedContinuation(e){let{baseline:t}=this.replay,n=Wn(t);return this.replay=null,l(()=>{t.awaitingContinuation=!1,t.status=`streaming`,t.finishReason=void 0,t.errorText=void 0,t.suggestions=void 0,this.attach(t),this.apply(e),t.continuationStreaming=n||void 0,this.messagesSig.value=[...this.messagesSig.value]}),t}applyResume(e){if(e.type===`start`){let t=(this.replay?.baseline??this.active)?.serverMessageId;t!==void 0&&e.messageId!==void 0&&t!==e.messageId&&this.onReconcileNeeded?.({messageId:t}),this.detach();let n=e.messageId,r=n===void 0?void 0:this.messagesSig.value.find(e=>e.serverMessageId===n||e.id===n);if(r!==void 0)return e.messageMetadata?.senderRole===`visitor`&&r.role===`user`&&(r.status===`pending`||r.status===`error`)&&(r.serverMessageId=n,r.status=`complete`,r.errorText=void 0,r.retryAction=void 0,this.messagesSig.value=[...this.messagesSig.value]),this.beginReplay(r,e),null;let i=e.messageMetadata?.senderRole,a=this.messagesSig.value.at(-1);if(i===void 0&&a?.role===`assistant`&&a.status===`streaming`&&a.serverMessageId===void 0&&!Fn(a))return this.attach(a),this.apply(e),null;let o=Cn();return this.attach(o),this.messagesSig.value=[...this.messagesSig.value,o],this.apply(e),null}if(this.replay){let t=this.refreshReplayBaseline();if(!t)return null;t.chunks.push(e),e.type===`data-control-state`&&(t.baseline.operatorRoutedTurn=e.data.controlMode!==`ai-agent`),this.apply(e);let{baseline:n,shadow:r,probeContinuation:i,continuationTailReplay:a,liveCatchUp:o}=t,s=e.type===`finish`||e.type===`error`||e.type===`abort`;if(i){if(!Uc(n,r,e))return s&&(qc(n,r)&&(n.continuationStreaming=!0,this.messagesSig.value=[...this.messagesSig.value],this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id})),this.detach()),null;let t=Rc(n)&&s?this.settleOwnedContinuation(e):this.promoteContinuation();return s?(t.continuationStreaming&&(e.type===`finish`?this.onReconcileNeeded?.({messageId:t.serverMessageId??t.id}):t.continuationStreaming=!1),this.detach(),t):null}if(a&&Vc(n,r)){let e=this.promoteContinuation(!0);return s?(this.detach(),e):null}if(!o)return s&&this.detach(),null;if(s&&!Fn(n)&&Fn(r)){let e=this.promoteReplay();return this.detach(),e}if(!Bc(n,r))return s&&(this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id}),this.detach()),null;let c=this.promoteReplay();return s?(this.detach(),c):null}let t=this.refreshActive();if(!t)return null;if(this.replay)return this.applyResume(e);if(this.apply(e),e.type===`finish`||e.type===`error`||e.type===`abort`){let n=t;return n.continuationStreaming&&(e.type===`finish`?this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id}):n.continuationStreaming=!1),this.detach(),n}return null}ensureTextPart(e,t,n){let r=`${t}:${n}`,i=this.openTextParts.get(r);if(i)return i;let a={kind:t,id:`${n}#${this.partSeq++}`,textSig:f(``),doneSig:f(!1)};return this.openTextParts.set(r,a),Yc(e,a),a}apply(e){let t=this.active;if(t)switch(e.type){case`start`:{e.messageId&&(t.serverMessageId=e.messageId);let n=e.messageMetadata;n?.senderRole===`operator`?(t.role=`operator`,n.operatorInitials&&(t.operatorInitials=n.operatorInitials)):n?.senderRole===`visitor`&&(t.role=`user`);return}case`finish-step`:this.openTextParts.clear();return;case`start-step`:Yc(t,{kind:`step-start`,id:`ss-${this.partSeq++}`});return;case`finish`:Fc.debug(`finish`,{reason:e.finishReason,canContinue:e.canContinue}),t.status=`complete`,t.retryAction=void 0,e.finishReason&&(t.finishReason=e.finishReason),this.bumpDone(t);return;case`error`:Fc.warn(`stream error chunk`,{errorText:e.errorText}),t.status=`error`,t.errorText=e.errorText,this.bumpDone(t);return;case`abort`:Fc.debug(`stream abort chunk (canceled)`),t.status=`complete`,t.canceled=!0,t.retryAction=void 0,this.bumpDone(t);return;case`text-start`:this.ensureTextPart(t,`text`,e.id);return;case`text-delta`:{let n=this.ensureTextPart(t,`text`,e.id);n.textSig.value+=e.delta;return}case`text-end`:this.ensureTextPart(t,`text`,e.id).doneSig.value=!0;return;case`reasoning-start`:this.ensureTextPart(t,`reasoning`,e.id).doneSig.value=!1;return;case`reasoning-delta`:{let n=this.ensureTextPart(t,`reasoning`,e.id);n.textSig.value+=e.delta;return}case`reasoning-end`:this.ensureTextPart(t,`reasoning`,e.id).doneSig.value=!0;return;case`tool-input-start`:case`tool-input-delta`:case`tool-input-available`:case`tool-input-error`:case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:case`tool-approval-request`:Zc(t,e);return;case`file`:Yc(t,{kind:`file`,url:e.url,mediaType:e.mediaType});return;case`source-url`:Xc(t,{kind:`source`,sourceId:e.sourceId,url:e.url,title:e.title});return;case`source-document`:Xc(t,{kind:`source`,sourceId:e.sourceId,title:e.title,filename:e.filename,mediaType:e.mediaType});return;case`data-suggestions`:t.suggestions=tn(e.data);return;case`data-control-state`:t.operatorRoutedTurn=e.data.controlMode!==`ai-agent`;return;case`data-memory-compaction-state`:return;default:}}bumpDone(e){l(()=>{e.partsSig.value=[...e.partsSig.value],this.messagesSig.value.includes(e)&&(this.messagesSig.value=[...this.messagesSig.value])})}};const Lc={"input-streaming":0,"input-available":1,"approval-requested":2,"approval-responded":3,"output-available":4,"output-denied":4,"output-error":4};function Rc(e){return e.awaitingContinuation===!0||e.continuationStreaming===!0||e.retryAction?.kind===`continue-assistant`}function zc(e,t){e.canceled&&(t.canceled=!0),!(!Rc(e)||t.status!==`streaming`&&!Hn(t))&&(t.awaitingContinuation??(t.awaitingContinuation=e.awaitingContinuation),t.continuationStreaming??(t.continuationStreaming=e.continuationStreaming),t.retryAction===void 0&&(t.retryAction=e.retryAction))}function Bc(e,t){let n=e.partsSig.value,r=t.partsSig.value;return e.role!==t.role||r.length<n.length?!1:n.every((e,t)=>Hc(e,r[t]))}function Vc(e,t){let n=e.partsSig.value,r=n.findLastIndex(e=>e.kind===`tool`),i=new Set(n.slice(0,r+1).flatMap(e=>e.kind===`tool`?[e.toolCallId]:[])),a=t.partsSig.value.filter(e=>e.kind!==`tool`||!i.has(e.toolCallId)),o=n.slice(r+1);return a.length<o.length?!1:o.every((e,t)=>Hc(e,a[t]))}function Hc(e,t){switch(e.kind){case`text`:case`reasoning`:return t?.kind===e.kind&&t.textSig.value.startsWith(e.textSig.value);case`step-start`:return t?.kind===`step-start`;case`tool`:{if(t?.kind!==`tool`||t.toolCallId!==e.toolCallId||!er(t.toolName,e.toolName)||Lc[t.stateSig.value]<Lc[e.stateSig.value])return!1;let n=e.approvalSig.value?.approved;return n===void 0||t.approvalSig.value?.approved===n}case`file`:return t?.kind===`file`&&t.url===e.url&&t.mediaType===e.mediaType;case`source`:return t?.kind===`source`&&t.sourceId===e.sourceId&&t.url===e.url&&t.title===e.title&&t.filename===e.filename&&t.mediaType===e.mediaType;default:return e}}function Uc(e,t,n){return Wc(e,n)||!Gc(e,t)?!0:n.type!==`finish`&&n.type!==`error`&&n.type!==`abort`?!1:Bn(t)||e.awaitingContinuation===!0&&n.type!==`finish`?!0:e.awaitingContinuation===!0&&t.partsSig.value.every(e=>e.kind===`step-start`)}function Wc(e,t){if(t.type!==`tool-output-available`&&t.type!==`tool-output-error`&&t.type!==`tool-output-denied`)return!1;let n=e.partsSig.value.find(e=>e.kind===`tool`&&e.toolCallId===t.toolCallId);return n!==void 0&&Lc[n.stateSig.value]<4}function Gc(e,t){let n=t.partsSig.value;if(n.length===0)return!0;let r=e.partsSig.value;return r.some((e,t)=>n.every((e,n)=>Kc(r[t+n],e)))}function Kc(e,t){switch(t.kind){case`text`:case`reasoning`:return e?.kind===t.kind&&e.textSig.value.startsWith(t.textSig.value);case`step-start`:return e?.kind===`step-start`;case`tool`:return e?.kind===`tool`&&e.toolCallId===t.toolCallId&&(t.toolName===`tool`||er(e.toolName,t.toolName));case`file`:return e?.kind===`file`&&e.url===t.url&&e.mediaType===t.mediaType;case`source`:return e?.kind===`source`&&e.sourceId===t.sourceId&&e.url===t.url&&e.title===t.title&&e.filename===t.filename&&e.mediaType===t.mediaType;default:return t}}function qc(e,t){if(Rc(e)||!Hn(e))return!1;let n=new Set(e.partsSig.value.filter(e=>e.kind===`tool`).map(e=>e.toolCallId));return!t.partsSig.value.some(e=>e.kind===`tool`&&n.has(e.toolCallId))}function Jc(e,t,n,r){let i=e.partsSig.value.find(e=>e.kind===`tool`&&e.toolCallId===t);if(i)return r&&(i.dynamic=!0),i;let a={kind:`tool`,toolCallId:t,toolName:n??`tool`,dynamic:r?!0:void 0,inputPartialSig:f(``),inputSig:f(void 0),outputSig:f(void 0),errorSig:f(void 0),stateSig:f(`input-streaming`),approvalSig:f(void 0)};return Yc(e,a),a}function Yc(e,t){e.partsSig.value=[...e.partsSig.value,t]}function Xc(e,t){e.partsSig.value.some(e=>e.kind===`source`&&e.sourceId===t.sourceId)||Yc(e,t)}function Zc(e,t){switch(t.type){case`tool-input-start`:Jc(e,t.toolCallId,t.toolName,t.dynamic);return;case`tool-input-delta`:{let n=Jc(e,t.toolCallId);n.inputPartialSig.value+=t.inputTextDelta;return}case`tool-input-available`:{let n=Jc(e,t.toolCallId,t.toolName,t.dynamic);n.inputSig.value=t.input,n.stateSig.value=`input-available`;return}case`tool-input-error`:{let n=Jc(e,t.toolCallId,t.toolName,t.dynamic);n.inputSig.value=t.input,n.errorSig.value=t.errorText,n.stateSig.value=`output-error`;return}case`tool-approval-request`:{let n=Jc(e,t.toolCallId,t.toolName);n.approvalSig.value={id:t.approvalId},n.stateSig.value=`approval-requested`;return}case`tool-output-available`:{let n=Jc(e,t.toolCallId,void 0,t.dynamic);n.outputSig.value=t.output,n.stateSig.value=`output-available`;return}case`tool-output-error`:{let n=Jc(e,t.toolCallId,void 0,t.dynamic);n.errorSig.value=t.errorText,n.stateSig.value=`output-error`;return}case`tool-output-denied`:{let n=Jc(e,t.toolCallId);n.stateSig.value=`output-denied`;return}default:return}}const Qc=1e3;async function $c(e){let t=Qc,n=!1,r=!1,i=!1,a=()=>{i||e.signal.aborted||(i=!0,e.onInitialBoundaryReady())};for(;!e.signal.aborted;){let o,s=`held`;try{s=await e.connect(()=>{if(e.signal.aborted)return;o=e.now();let t=n||r;n=!0,r=!1,i?t&&e.backfill():a()})}catch{}if(e.signal.aborted||(!n&&o===void 0&&(r=!0,a()),s===`unavailable`))return;o!==void 0&&e.now()-o>=1e3&&(t=Qc),await e.sleep(t),t=Math.min(t*2,15e3)}}function el(e){let{activated:t,conversationReady:n,conversationIdSig:r,messagesSig:a,optionsRef:o,transport:c,visitorId:l,adoptControlStateChunk:u,adoptMemoryCompactionStateChunk:d,settleSuggestions:f,recordConversationReply:p,transcriptRecoverySig:m,beginConversationTranscript:h,commitConversationTranscript:g,onReplyLanded:_,runCancellation:v,canContinueRef:y,setCanSend:b,feedback:x,bus:S,loadInitialThread:C,shouldReconcileOnConnect:w}=e,T=s(0);i(()=>{if(!t||!n||!r.value)return;let e=r.value,i=new AbortController,s=e=>{},E=new Ic(a,e=>s(e));c.primeIdentity(l,e);let D=!1,O=!1,k,A=!1,j,M=0,ee=y.current,te,N,ne=Date.now(),re,P=!1,F=!1,ie=(t,n,r)=>{if(!Fn(t))return;let i=a.value.findLast(e=>!e.ephemeral),s=t.serverMessageId??t.id;if(!(i&&(i.serverMessageId??i.id)!==s))return Pn(a.value,t,e,o.current.strings.newConversation,n,r)},ae=(e,t,n,r)=>{let i=ie(e,t,r);if(!i)return;let a=`${e.serverMessageId??e.id}:${n}:${i.preview??``}`;a!==N&&(N=a,c.publishConversation({...i,hasUnread:!0},!0))},I,L=()=>{I&&(clearTimeout(I.timer),I=void 0)},oe=()=>{let e=I;if(!e)return;clearTimeout(e.timer),I=void 0;let t=a.value.find(t=>(t.serverMessageId??t.id)===e.replyId);(t?.role===`assistant`||t?.role===`operator`)&&ae(t,e.canContinue,e.generation,e.activityAt)},se=(e,t,n,r)=>{L(),I={replyId:e.serverMessageId??e.id,canContinue:t,generation:n,activityAt:r,timer:setTimeout(oe,120)}},ce=(e,t,n,r=Date.now(),i=!0)=>{L();let a=ie(e,t,r);if(!a)return;let o=`${e.serverMessageId??e.id}:${n}`;o!==te&&(te=o,p(a),i&&re&&(P=!0))},le=(e,t)=>{(e||!v.localSendRef.current)&&v.settle(t),e&&_()},ue=(e,t=[],n=!1,r,i=ee,s=M,c=Date.now(),l=!0)=>{let u=o.current;if(e.canceled){ce(e,i,s,c,l),le(n,r);return}let d=!0,p=e.status===`error`;switch(or(e,p)){case`drop`:a.value=a.value.filter(t=>t!==e),d=!1;break;case`complete-operator-routed`:e.status=`complete`,n&&(x.play(`messageReceived`),Ec(S,u,`assistant`,Nn(e)));break;case`error`:if(e.status=`error`,e.errorText=u.strings.errorGeneric,n){x.play(`error`);let e=Error(p?`stream error chunk`:`empty reply`);S.emit(`error`,e),u.onError?.(e)}break;case`complete`:e.status=`complete`,n&&(x.play(`messageReceived`),Ec(S,u,`assistant`,Nn(e))),f(e,t);break}d&&ce(e,i,s,c,l),le(n,r)},de=t=>{if(i.signal.aborted||r.value!==e)return;if(u(t),d?.(t),t.type===`start`){oe();let n=t.messageId===void 0?void 0:a.value.find(e=>e.serverMessageId===t.messageId||e.id===t.messageId);A=n!==void 0&&n.status!==`streaming`;let r=j?.senderRole===`visitor`?j.messageId:void 0;if(j={messageId:t.messageId,senderRole:t.messageMetadata?.senderRole},M+=1,ne=Date.now(),N=void 0,D=t.messageMetadata?.senderRole===void 0,O=!1,k=D?t.messageMetadata?.runId:void 0,D){let n=t.messageId!==void 0&&a.value.some(e=>e.serverMessageId===t.messageId||e.id===t.messageId),i=a.value.at(-1),o=t.messageId!==void 0&&(i?.serverMessageId===t.messageId||i?.id===t.messageId),s=v.localSendRef.current&&(!n||o)&&i?.role===`assistant`&&i.status===`streaming`&&(o||i.serverMessageId===void 0&&i.partsSig.value.length===0);O=v.captureStart(e,t,s,r)}}let n=D&&(t.type===`finish`||t.type===`error`||t.type===`abort`),s=n?k:void 0,c=n&&(O||v.ownsLocalRun(s)),l=M,f=A;t.type===`finish`&&t.canContinue!==void 0&&(ee=t.canContinue);let p=ee;n&&(D=!1,O=!1,k=void 0);let m=E.applyResume(t),h=j?.messageId,g=h===void 0?void 0:a.value.find(e=>e.serverMessageId===h||e.id===h);A&&j?.senderRole!==`visitor`&&(m!==null||g?.status===`streaming`)&&(A=!1,f=!1);let _=!A&&(g?.role===`assistant`||g?.role===`operator`);if(t.type===`text-delta`&&_&&se(g,ee,M,ne),t.type===`text-end`&&(L(),_&&ae(g,ee,M,ne)),t.type===`finish`&&t.canContinue===!1&&b(!1),!m){n&&(c||!v.localSendRef.current)&&v.settle(s);return}if(m.role===`operator`){f||(x.play(`messageReceived`),Ec(S,o.current,`operator`,Nn(m))),ce(m,p,l,ne),A=!1,n&&(c||!v.localSendRef.current)&&v.settle(s);return}m.role===`assistant`&&(ue(m,[],c,s,p,l,ne),A=!1)},fe=async t=>{let n=M,o=await c.loadConversation(e,t?{ids:[t]}:void 0).catch(()=>null);if(i.signal.aborted||r.value!==e||!o)return!1;o.controlState&&u({type:`data-control-state`,data:o.controlState});let s=a.value.at(-1),l=n===M&&(t===void 0||s!==void 0&&(s.serverMessageId===t||s.id===t));if(o.messages.length===0)return!0;l&&(ee=o.canContinue,b(ee));let d=a.value,p=t===void 0?d.at(-1):d.find(e=>e.serverMessageId===t||e.id===t),{messages:m,changed:h}=Zn(d,An(o.messages));if(!h)return!0;a.value=m;let g=t===void 0?m.at(-1):m.find(e=>e.serverMessageId===t||e.id===t),_=p!==void 0&&g!==void 0&&(p.id===g.id||p.serverMessageId!==void 0&&p.serverMessageId===g.serverMessageId),y=g!==void 0&&g.status!==`streaming`&&(!_||p?.status===`streaming`),x=_&&p?.status===`streaming`?Date.now():g?.createdAt;return l&&y&&g.role===`assistant`?ue(g,g.suggestions??[],v.localSendRef.current,void 0,o.canContinue,n,x,!1):l&&y&&g.role===`operator`?ce(g,o.canContinue,n,x,!1):l&&g?.role===`assistant`&&g.status!==`streaming`&&f(g,g.suggestions??[]),!0},pe=new Set;s=({messageId:e})=>{if(pe.has(e)||!a.value.some(t=>t.serverMessageId===e||t.id===e))return;pe.add(e);let t=()=>pe.delete(e);fe(e).then(t,t)};let me=(t=!1)=>{if(i.signal.aborted||r.value!==e){P=!1;return}if(re){P=!0;return}let n=t?C(e)??(w()?fe():void 0):fe();if(!n)return;h(e),re=n;let a=(t=!1)=>{if(re===n){if(re=void 0,P){P=!1,me();return}t&&g(e)}};n.then(a,()=>a(!1))},R=m.subscribe(e=>{e<=T.current||(T.current=e,F&&me())});return $c({signal:i.signal,now:()=>performance.now(),sleep:e=>zt(e,i.signal),connect:e=>c.connectResumeStream({signal:i.signal,onChunk:de,onConnected:e}),onInitialBoundaryReady:()=>{F=!0,me(!0)},backfill:()=>me()}),()=>{i.abort(),L(),R(),E.detach()}},[t,n,r,r.value,l,c,u,d,f,p,m,h,g,_,v,y,b,a,S,x,C,w])}function tl(e){let{transport:t,setStreaming:n}=e,i=s(),a=s(),c=s(!1),l=s(),u=s(!1),d=s(new Map),f=s(new Set),p=r((e,n)=>{let r=`${e}:${n}`;l.current!==r&&(l.current=r,t.cancelTurn(e,n))},[t]),m=r(e=>{i.current=void 0,a.current=e,c.current=!1,l.current=void 0,u.current=!0,n(!0)},[n]),h=r((e,t)=>{d.current.set(e,{messageId:t})},[]),g=r(e=>{e!==void 0&&(f.current.add(e),f.current.size>32&&f.current.delete(f.current.values().next().value)),(e===void 0||i.current?.runId===e)&&(i.current=void 0,a.current=void 0,c.current=!1,u.current=!1,n(!1))},[n]),_=r((e,t)=>a.current===e?(a.current=void 0,t.runId?(i.current={conversationId:t.conversationId,runId:t.runId},n(!0),c.current&&p(t.conversationId,t.runId),!0):(g(),!0)):t.runId&&i.current?.runId===t.runId?(i.current={conversationId:t.conversationId,runId:t.runId},c.current&&p(t.conversationId,t.runId),!0):!1,[p,n,g]),v=r((e,t)=>{let r=d.current.get(e);return r?(d.current.delete(e),!t.runId||f.current.has(t.runId)?!0:r.runId===void 0?u.current||a.current?!0:(i.current={conversationId:t.conversationId,runId:t.runId},a.current=void 0,c.current=!1,l.current=void 0,u.current=!0,n(!0),!0):(r.runId===t.runId&&i.current?.runId===t.runId&&(i.current={conversationId:t.conversationId,runId:t.runId},c.current&&p(t.conversationId,t.runId)),!0)):!1},[p,n]),y=r(e=>a.current===e?(g(),!0):!1,[g]),b=r(e=>{let t=d.current.get(e);return t?(d.current.delete(e),t.runId===void 0):!1},[]),x=r((e,t,r,o)=>{let s=t.messageMetadata?.runId;if(t.messageMetadata?.senderRole!==void 0||typeof s!=`string`||!s||f.current.has(s))return!1;if(i.current?.runId===s)return u.current;if(u.current)return i.current||!r?!1:(a.current=void 0,i.current={conversationId:e,runId:s},n(!0),c.current&&p(e,s),!0);let m=[...d.current.values()].filter(e=>e.runId===void 0).find(e=>e.messageId===o);return m?(m.runId=s,i.current={conversationId:e,runId:s},a.current=void 0,c.current=!1,l.current=void 0,u.current=!0,n(!0),!0):(a.current=void 0,i.current={conversationId:e,runId:s},n(!0),c.current&&p(e,s),u.current)},[p,n]),S=r(e=>typeof e==`string`&&i.current?.runId===e&&u.current,[]),C=r(()=>{let e=i.current;if(e)return c.current=!0,p(e.conversationId,e.runId),!0;let t=a.current;return t?(c.current=!0,t.then(e=>{e.runId&&p(e.conversationId,e.runId)}).catch(()=>void 0),!0):!1},[p]);return o(()=>({localSendRef:u,begin:m,beginRouted:h,acceptAck:_,acceptRoutedAck:v,reject:y,rejectRouted:b,captureStart:x,ownsLocalRun:S,settle:g,stop:C}),[_,v,m,h,x,S,y,b,g,C])}const nl=I.scope(`send`);function rl(e,t,n,r,i,a=!0){e.publishConversation({...Pn(t,n,r,i,a),hasUnread:!1},!0)}function il(e,t){return e.id===t.id||(e.serverMessageId??e.id)===(t.serverMessageId??t.id)}function al(e){return e.findLast(e=>!e.ephemeral&&e.role!==`system`&&(e.role===`user`||e.status!==`streaming`||Fn(e)))}function ol(e,t,n,r,i){let a=al(t);a?.role!==`user`||!il(a,n)||rl(e,t,a,r,i)}function sl(e){return!(e instanceof Vt)||e.code===`network`||e.status===void 0||e.status===202||e.status===408||e.status===425||e.status===429||e.status>=500&&e.status<600}function cl(e){let{transport:t,messagesSig:n,conversationIdSig:i,options:a,bus:o,feedback:s,persistence:c,visitorId:l,adoptConversationId:u,applyControlState:d,setCanSend:f,settleSuggestions:p,runCancellation:m}=e,h=r(()=>{let e=i.value??ct();return i.value||(i.value=e,c.saveConversationId(e)),e},[i,c]);return{sendAiTurn:r(async({continueExisting:e,turn:r})=>{let g=h(),_=n.value.at(-1),v=r?[r]:jn(n.value,e),y=v[0],b=nn({messages:v.map(Mn),conversationId:g,visitorId:l,userPrefs:c.loadUserPrefs()}),x=t.sendTurn(b);m.begin(x);try{let r=await x;if(i.value!==g||!m.acceptAck(x,r))return!1;if(u(r.conversationId),r.runId&&y?.role===`user`&&ol(t,n.value,y,r.conversationId,a.strings.newConversation),!r.runId){let o=await t.loadConversation(r.conversationId).catch(()=>null);if(i.value!==r.conversationId)return!0;if(o){o.controlState&&d(o.controlState),f(o.canContinue);let i=An(o.messages),{messages:s,changed:c}=Zn(n.value,i);c&&(n.value=s);let l=i.findLast(e=>!e.ephemeral&&e.role!==`system`),u=al(n.value);u&&l&&il(u,l)&&rl(t,n.value,u,r.conversationId,a.strings.newConversation,o.canContinue);let m=_?n.value.find(e=>e.id===_.id&&e.role===`assistant`&&e.status!==`streaming`):void 0;m&&p(m,m.suggestions??[]),!e&&_?.role===`assistant`&&n.value.includes(_)&&_.serverMessageId===void 0&&!Fn(_)&&(n.value=n.value.filter(e=>e!==_))}else _?.role===`assistant`&&n.value.includes(_)&&(_.status=`error`,_.errorText=a.strings.errorGeneric,e?_.retryAction={kind:`continue-assistant`,messageId:_.serverMessageId??_.id}:_.retryAction=y?.role===`user`?{kind:`resend-user`,messageId:y.id}:null,n.value=[...n.value])}return!0}catch(c){if(i.value!==g)return!1;if(!m.reject(x))return y?.role===`user`&&ol(t,n.value,y,g,a.strings.newConversation),!0;let l=Bs(c,a.strings),u=sl(c),h=r?.role===`assistant`?r:n.value.at(-1);if(e&&h?.role===`assistant`&&c instanceof Vt&&c.status===409){let e=h.serverMessageId??h.id,r=await t.loadConversation(g,{ids:[e]}).catch(()=>null);if(i.value!==g)return!1;if(r){r.controlState&&d(r.controlState),f(r.canContinue);let t=An(r.messages),i=t.find(t=>(t.serverMessageId??t.id)===e);if(i&&Qn(h,i)){let{messages:r,changed:i}=Zn(n.value,t),a=r.find(t=>(t.serverMessageId??t.id)===e);if(i&&a&&a!==h)return a.awaitingContinuation=!1,a.continuationStreaming=void 0,a.retryAction=null,n.value=r,a.status!==`streaming`&&p(a,a.suggestions??[]),!0}}if(!n.value.includes(h)||h.status!==`streaming`)return!1;h.continuationStreaming=!0}if(e&&h?.role===`assistant`)h.status=`error`,h.errorText=l,h.retryAction=u?{kind:`continue-assistant`,messageId:h.serverMessageId??h.id}:null,n.value=[...n.value];else if(_?.role===`assistant`&&n.value.includes(_)){_.status=`error`,_.errorText=l;let e=v[0];_.retryAction=u&&e?.role===`user`?{kind:`resend-user`,messageId:e.id}:null,n.value=[...n.value]}else{let e=Cn();e.status=`error`,e.errorText=l;let t=v[0];e.retryAction=u&&t?.role===`user`?{kind:`resend-user`,messageId:t.id}:null,n.value=[...n.value,e]}return s.play(`error`),o.emit(`error`,c),a.onError?.(c),!1}},[t,n,a,o,s,c,l,u,d,f,p,h,m]),sendRoutedTurn:r(async e=>{let r=h();e.status=`pending`,e.errorText=void 0,e.retryAction=void 0,n.value.includes(e)&&(n.value=[...n.value]);let d=nn({messages:[Mn(e)],conversationId:r,visitorId:l,userPrefs:c.loadUserPrefs()}),f=t.sendTurn(d);m.beginRouted(f,e.id);try{let o=await f;return i.value===r?m.acceptRoutedAck(f,o)?(u(o.conversationId),ol(t,n.value,e,o.conversationId,a.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value])),!0):!1:(m.rejectRouted(f),!1)}catch(c){let l=m.rejectRouted(f);if(i.value!==r)return!1;if(!l)return ol(t,n.value,e,r,a.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value])),!0;if(e.status!==`pending`)return ol(t,n.value,e,r,a.strings.newConversation),!0;nl.debug(`operator-routed send failed`,{error:c});let u=c instanceof Error?c:Error(String(c));return e.status=`error`,e.errorText=Bs(c,a.strings),e.retryAction=sl(c)?{kind:`resend-user`,messageId:e.id}:null,n.value.includes(e)&&(n.value=[...n.value]),s.play(`error`),o.emit(`error`,u),a.onError?.(u),!1}},[t,n,a,o,s,c,l,u,h,m])}}const ll=I.scope(`unread`);function ul(e){let{transport:t,options:n,conversationIdSig:a,isConversationVisibleRef:o,activated:c,conversationReady:l}=e,u=m(!1),d=m(0),f=s([]),p=s(),h=s(!1),g=r(()=>{let e=a.value,t=o.current()&&p.current===e?e:void 0;u.value=f.current.some(e=>e.hasUnread&&e.conversationId!==t)},[a,u,o]),_=r(e=>{let t=a.value,n=f.current.find(e=>e.conversationId===t),r=pn(f.current,e),i=r.find(e=>e.conversationId===t),o=e.type===`snapshot`&&t!==void 0&&i?.hasUnread===!0&&p.current===t&&n!==void 0&&n.lastMessageAt!==i.lastMessageAt;o&&(p.current=void 0),f.current=r,g(),o&&(d.value+=1)},[a,g,d]),v=r(()=>{if(g(),!o.current())return;let e=a.value;if(!e||p.current!==e)return;let n=f.current.find(t=>t.conversationId===e);n?.hasUnread&&t.markRead(e,n.lastMessageAt)},[a,o,g,t]),y=r(e=>{a.value===e&&(p.current=void 0,g())},[a,g]),b=r(e=>{a.value===e&&(p.current=e,v())},[a,v]),x=r(e=>p.current===e,[]),S=r((e=!1)=>{n.modules.list.some(e=>e.layout===`chat`)&&(h.current||(h.current=!0,t.listConversations({limit:50},e).then(t=>{e||_({type:`snapshot`,result:t,requestedRevision:0}),v()}).catch(e=>ll.debug(`refreshUnread failed (non-fatal)`,{err:e})).finally(()=>{h.current=!1})))},[_,v,n.modules,t]),C=r(e=>{let n=e.conversationId,r=o.current()&&a.value===n&&p.current===n,i=f.current.find(e=>e.conversationId===n),s=r&&(i?.lastMessageAt!==e.lastMessageAt||i.hasUnread);t.publishConversation({...e,hasUnread:!r},!0),s&&t.markRead(n,e.lastMessageAt)},[a,o,t]);i(()=>t.subscribeConversationChanges(_),[_,t]);let w=s(!1);return i(()=>{!c||!l||w.current||(w.current=!0,S())},[c,l,S]),i(()=>{if(!c)return;let e=()=>{document.visibilityState===`visible`&&(v(),S(!0))};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[c,v,S]),{hasUnreadSig:u,transcriptRecoverySig:d,markVisibleConversationRead:v,beginConversationTranscript:y,commitConversationTranscript:b,isConversationTranscriptCommitted:x,recordConversationReply:C}}const dl=I.scope(`settings`);function fl(e){let{options:t,persistence:n,transport:a,feedback:o,hostElement:s,bus:l}=e,u=n.loadUserPrefs(),[d,f]=c(()=>u.locale??t.locale),[p,m]=c(()=>u.themeMode??t.themeMode),[h,g]=c(()=>u.textSize??t.textSize),_=r(e=>{n.patchUserPrefs(e),a.saveUserPrefs(n.loadUserPrefs()).catch(e=>dl.warn(`saveUserPrefs failed`,{err:e}))},[n,a]);i(()=>{u.soundMuted!==void 0&&o.setMuted(u.soundMuted)},[]),i(()=>{s.dataset.theme=p},[s,p,t]),i(()=>{s.dataset.textSize=h},[s,h,t]),i(()=>{let e=!0;return o.mutedSig.subscribe(t=>{if(e){e=!1;return}_({soundMuted:t})})},[o,_]);let v=we(d,t.availableLocales,t.defaultLocale);return i(()=>{a.setLocale(v)},[a,v]),i(()=>{s.dir=E(v)?`rtl`:`ltr`},[s,v]),i(()=>{v!==d&&f(v)},[v,d]),{activeLocale:d,activeThemeMode:p,activeTextSize:h,effectiveLocale:v,setActiveLocale:f,setActiveThemeMode:m,setActiveTextSize:g,patchAndSync:_,handleLocaleChange:r(e=>{dl.info(`localeChange`,{locale:e}),f(e),_({locale:e}),l.emit(`localeChange`,e)},[_,l]),handleThemeChange:r(e=>{dl.info(`themeChange`,{mode:e}),m(e),s.dataset.theme=e,_({themeMode:e}),l.emit(`themeChange`,e)},[s,_,l]),handleTextSizeChange:r(e=>{dl.info(`textSizeChange`,{size:e}),g(e),s.dataset.textSize=e,_({textSize:e}),l.emit(`textSizeChange`,e)},[s,_,l]),handleSoundToggle:r(()=>{o.toggleMuted();let e=o.mutedSig.value;dl.info(`soundToggle`,{muted:e}),l.emit(`soundToggle`,{muted:e})},[o,l])}}const $=I.scope(`app`),pl=b.cssPrefix;function ml(e,t){return wn({...e,text:D(t,e.text)})}function hl({options:e,hostElement:t,bus:n}){let u=e.aiAgentDeploymentId;if(!u)throw Error(`aiAgentDeploymentId is required`);let[d]=c(()=>dt(e.widgetId,e.storage,e.aiAgentDeploymentId)),[f]=c(()=>d.getVisitorId()),h=d.loadUserPrefs(),v=m(d.loadConversationId()),y=s(v.value!==void 0),b=m(v.value??``),x=m([]),[S,C]=c(!1),w=s(),[T,E]=c([]);function O(){let t=e.modules.list,n=new Set(t.map(e=>e.id)),r=d.loadActiveModule();return r&&n.has(r)?r:t[0]?.id??``}function k(){return e.modules.list.find(e=>e.layout===`chat`)?.id}function A(){let t=k();return t?e.modules.list.length===1||M.sig.value.activeTab===t:!1}let j=s();if(!j.current){let t=e.modules.list.map(e=>e.id),n=d.loadActiveModule()??t[0]??``;j.current=Ms(n,n?[...t,n]:t,e=>d.saveActiveModule(e))}let M=j.current,ee=p(()=>M.sig.value.activeTab).value,te=p(()=>v.value).value,[N,ne]=c(!1),[re,P]=c(null),[F,ie]=c(!1),ae=e.mode===`standalone`||e.mode===`inline`,I=s(It(e,Lt(),d.loadPanelOpen(),d.loadPanelSize())),[L,oe]=c(I.current.panelOpen),[se,ce]=c(I.current.panelOpen),le=s(),ue=s(),de=s(!1),fe=s(void 0);i(()=>{L&&ce(!0)},[L]);let pe=s(!1),[me,R]=c(!1),{dismissed:he,dismissCallout:ge}=kc({callout:e.launcher.callout,persistence:d}),_e=e.launcher.callout?.persistent??!0,ve=r(()=>{$.info(`calloutDismiss`),n.emit(`calloutDismiss`,void 0),ge()},[n,ge]),[z,ye]=c(I.current.panelSize),be=s(!1),[xe,Se]=c(`chat`),Ce=s(()=>!1);Ce.current=()=>L&&xe===`chat`&&!document.hidden&&A();let[we,Te]=c(!0),Ee=s(we);Ee.current=we;let[De,Oe]=c(!1),ke=s(De);ke.current=De;let Ae=s(null),[je,Ne]=c(!1),[Pe,Ie]=c(null),[Le,Re]=c([]),ze=s(e.strings),Be=s(e);Be.current=e;let[Ve,He]=c(void 0),[Ue,We]=c(void 0),[Ge,Ke]=c(()=>d.loadSidebarCollapsed()??!1),[qe,Je]=c({}),[B]=c(()=>new yn({agentApiBaseUrl:e.agentApiBaseUrl,dataApiBaseUrl:e.dataApiBaseUrl,auth:Rt({publicKey:e.publicKey,aiAgentDeploymentId:u,publicKeyHeader:`x-public-key`}),endpoints:e.endpoints})),[Ye]=c(()=>new br(e.sound,e.haptics)),Xe=tl({transport:B,setStreaming:Oe}),{activeLocale:Ze,activeThemeMode:Qe,activeTextSize:$e,effectiveLocale:et,setActiveLocale:tt,setActiveThemeMode:nt,setActiveTextSize:rt,patchAndSync:it,handleLocaleChange:at,handleThemeChange:ot,handleTextSizeChange:st,handleSoundToggle:lt}=fl({options:e,persistence:d,transport:B,feedback:Ye,hostElement:t,bus:n}),{controlModeSig:ut,assignedOperatorInitialsSig:ft,operatorAvailableSig:pt,applyControlState:ht,adoptControlStateChunk:gt,requestOperator:_t,cancelOperatorRequest:vt}=Ac({transport:B,conversationIdSig:v}),yt=m(new Map),bt=r(e=>{if(e.type!==`data-memory-compaction-state`)return;let t=v.value;if(!t)return;let n=en(e.data);if(!n)return;let r=yt.value.get(t);if(r&&(n.postFinishSequence<r.postFinishSequence||n.postFinishSequence===r.postFinishSequence&&(r.status===`ready`||r.status===n.status)))return;let i=new Map(yt.value);i.set(t,n),yt.value=i},[v,yt]),{hasUnreadSig:xt,transcriptRecoverySig:St,markVisibleConversationRead:Ct,beginConversationTranscript:wt,commitConversationTranscript:Tt,isConversationTranscriptCommitted:Et,recordConversationReply:Dt}=ul({transport:B,options:e,conversationIdSig:v,isConversationVisibleRef:Ce,activated:se,conversationReady:N});i(()=>{Ct()},[ee,L,xe,te,Ct]),i(()=>{Ye.update(e.sound,e.haptics)},[Ye,e.sound,e.haptics]),i(()=>()=>Ye.destroy(),[Ye]),i(()=>{be.current||!e.size.initialSize||(be.current=!0,!d.loadPanelSize()&&ye(Ft(e.mode,e.size,Lt())))},[e.mode,e.size,d]),i(()=>{if(!N||pe.current)return;pe.current=!0;let t=It(e,Lt(),d.loadPanelOpen(),d.loadPanelSize());oe(t.panelOpen),ye(t.panelSize)},[N,e,d]);let Ot=s(null);i(()=>{N&&M.reconcile(e.modules.list.map(e=>e.id),O())},[N,e.modules.list,M]);let kt=r(e=>{!e||e.length===0||(x.value=e.map(e=>ml(e,ze.current)))},[x]),Mt=s(null),Pt=r(async e=>{try{let{formSubmissions:t}=await(e?B.bootstrap(e):Mt.current??B.bootstrap()),n=new Map;return t.forEach((e,t)=>n.set(e.formId,t)),t.filter((e,t)=>!e.skipped||n.get(e.formId)===t).map((e,t)=>({key:`wire:${e.formId}:${e.createdAt??t}`,formId:e.formId,outcome:e.skipped?`skipped`:`submitted`,createdAt:Yt(e.createdAt),values:e.values}))}catch(e){return $.debug(`bootstrap failed — no form markers (non-fatal)`,{err:e}),[]}},[B]),zt=s(0),Bt=s(0),Vt=r(e=>{if(e===v.value)return;let t=v.value;Bt.current++,C(!1),t&&(d.saveDraft(e,d.loadDraft(t)),d.saveDraft(t,``),d.saveMessageQueue(e,d.loadMessageQueue(t)),d.saveMessageQueue(t,[])),v.value=e,d.saveConversationId(e),B.primeIdentity(void 0,e),$.info(`conversation rebound`,{previous:t,current:e}),t&&n.emit(`conversationRebound`,{previous:t,current:e})},[n,v,d,B]),Ht=r((e,t)=>{let n=[...e.map(e=>e.createdAt),...t.map(e=>e.createdAt)].filter(e=>e!==void 0),r=(n.length?Math.min(...n):Date.now())-1;return[...(fe.current?.messages??[]).map(e=>{let t=ml(e,ze.current);return t.createdAt=r,t}),...e]},[]),Ut=r(async e=>{let t=Bt.current,r=()=>t!==Bt.current||v.value!==e;ue.current===e&&(ue.current=void 0),C(!0);try{let[t,n]=await Promise.all([B.loadConversation(e),Pt()]);if(r())return!1;let i=An(t.messages);E(n);let a=Ht(Xn(i,x.value),n);if(x.value=a,ue.current=a.some(e=>e.role===`user`)?void 0:e,i.length>0||t.controlState!==void 0){Te(t.canContinue),t.controlState&&ht(t.controlState);let e=i.findLast(e=>e.role===`assistant`&&!e.ephemeral);Re(e?.suggestions??[])}return!0}catch(t){return r()?!1:($.warn(`loadThread failed; keeping conversation active`,{err:t,conversationId:e}),n.emit(`error`,t),Be.current.onError?.(t),!1)}finally{r()||C(!1)}},[B,Pt,x,v,Ht,n]),Wt=r(e=>{if(le.current===e)return le.current=void 0,Ut(e)},[Ut]),Gt=r(()=>{if(w.current)return Promise.resolve(void 0);let t=v.value,r=x.value.find(e=>e.serverMessageId!==void 0),i=r?.serverMessageId,a=r?new Date(r.createdAt).toISOString():void 0;if(!t||!i||!a)return Promise.resolve(void 0);let o=Bt.current,s={};return w.current=s,(async()=>{try{let e=await B.loadConversation(t,{beforeId:i,beforeCreatedAt:a});if(w.current!==s||Bt.current!==o||v.value!==t)return;if(e.messages.length===0)return!1;let n=e.messages.map(Dn),r=x.value,c=Gn(r,n);if(c!==r){let e=Math.min(...n.map(e=>e.createdAt??1/0),...T.map(e=>e.createdAt??1/0));if(Number.isFinite(e))for(let t of r){if(!t.ephemeral)break;(t.createdAt??1/0)>=e&&(t.createdAt=e-1)}x.value=c}return!0}catch(r){if(w.current!==s||Bt.current!==o||v.value!==t)return;$.warn(`load previous messages failed`,{err:r,conversationId:t,beforeId:i}),n.emit(`error`,r),e.onError?.(r);return}finally{w.current===s&&(w.current=void 0)}})()},[n,v,T,x,e,B]),Kt=r(async({newConversation:t})=>{let r=++zt.current,i=()=>r!==zt.current,a=v.value,o=t||!a?ct():a;o!==a&&(Bt.current++,C(!1),l(()=>{v.value=o,b.value=o}),d.saveConversationId(o)),B.primeIdentity(f,o);let s;try{s=await B.handshake({visitorId:f,conversationId:o,userPrefs:d.loadUserPrefs(),locale:Ze})}catch(r){if(i())return;n.emit(`error`,r),e.onError?.(r),t||ne(!0);return}if(i())return;s.conversationId!==o&&Vt(s.conversationId),Ie(s.agent),e.mode===`page`&&(s.site&&At(s.site)?He(s.site):s.site&&$.warn(`invalid site config, using fallback`,{site:s.site}),s.blocks&&jt(s.blocks)?We(s.blocks):s.blocks&&$.warn(`invalid blocks config, using fallback`,{blocks:s.blocks}));let c=mt(s.userPrefs);if(Object.keys(c).length>0&&!t&&(d.saveUserPrefs(c),c.locale&&tt(c.locale),c.soundMuted!==void 0&&Ye.setMuted(c.soundMuted),c.themeMode&&nt(c.themeMode),c.textSize&&rt(c.textSize)),fe.current=s.welcome,t||n.emit(`handshake`,s),s.welcome?.suggestions){let e=ze.current;Re(s.welcome.suggestions.map(t=>({...t,label:D(e,t.label),...t.text===void 0?{}:{text:D(e,t.text)}})))}let u=!t&&a&&s.conversationId===a;y.current=!!u,u?de.current||(le.current=s.conversationId):(ue.current=s.conversationId,kt(s.welcome?.messages),Tt(s.conversationId)),t||ne(!0)},[B,f,d,e,n,v,b,Ye,kt,Ze,Vt,Tt]),qt=JSON.stringify(e.userContext??null);i(()=>{let t=Object.keys(qe).length?{...qe,...e.userContext}:e.userContext;B.setContext(t,gl(e.pageContext))},[B,qt,JSON.stringify(e.pageContext??null),JSON.stringify(qe)]);let Jt=r((e,t=[])=>Re(e.suggestions??t),[]);i(()=>(B.primeIdentity(f,v.value),Kt({newConversation:!1}),()=>{zt.current++,Bt.current++}),[]),i(()=>{!se||!N||de.current||(de.current=!0,Mt.current=B.bootstrap(),(async()=>{try{let e=await Mt.current;P(Me((e??{forms:[]}).forms,et))}catch(e){$.debug(`bootstrap failed — treating as no forms`,{err:e})}finally{ie(!0)}})(),le.current===v.value&&C(!0))},[se,N]);let Xt=s(null);i(()=>{if(!se||!N||(Xt.current??(Xt.current=et),Xt.current===et))return;Xt.current=et;let e=!1;return B.bootstrap().then(t=>{e||P(Me((t??{forms:[]}).forms,et))}).catch(e=>$.debug(`forms re-localize failed — keeping current copy`,{err:e})),()=>{e=!0}},[se,N,et,B]);let Zt=s(qt);i(()=>{!N||Zt.current===qt||(Zt.current=qt,Kt({newConversation:!1}))},[qt,N,Kt]),Pc({hostElement:t,mode:e.mode,panelSize:z,isOpen:L,surfaceReady:N,setIsOpen:oe});let{sendAiTurn:V,sendRoutedTurn:Qt}=cl({transport:B,messagesSig:x,conversationIdSig:v,options:e,bus:n,feedback:Ye,persistence:d,visitorId:f,adoptConversationId:Vt,applyControlState:ht,setCanSend:Te,settleSuggestions:Jt,runCancellation:Xe}),{toolInteraction:$t}=Oc({streaming:De,controlModeSig:ut,messagesSig:x,sendAiTurn:V,bus:n,humanInLoop:e.features.humanInLoop}),tn=r((e,t)=>{let r=x.value.find(t=>t.serverMessageId===e);r&&(r.feedback=t),$.info(`messageFeedback`,{messageId:e,value:t}),n.emit(`messageFeedback`,{messageId:e,value:t}),B.submitFeedback({messageId:e,value:t})},[n,x,B]),nn=()=>x.value.reduce((e,t)=>e+ +(t.role===`user`),0),rn=e.forms.list.length>0?e.forms:re??e.forms,H=ys({forms:rn,persistence:d,userContext:()=>e.userContext,messageCount:nn,pageArea:()=>e.pageContext?.area?String(e.pageContext.area):void 0,conversationId:()=>v.value,onComplete:(e,t,r,i)=>{$.info(`formSubmit`,{formId:e.id,trigger:t,skipped:i}),n.emit(`formSubmit`,{formId:e.id,values:r,skipped:i}),E(t=>{let n=t.find(t=>t.formId===e.id&&t.outcome===`skipped`)?.createdAt??Date.now();return[...t.filter(t=>t.formId!==e.id||t.outcome!==`skipped`),{key:`local:${e.id}:${n}`,formId:e.id,outcome:i?`skipped`:`submitted`,createdAt:n,...i?{}:{values:r}}]});let a=v.value??ct();v.value||(v.value=a,d.saveConversationId(a),B.primeIdentity(void 0,a)),!i&&e.mirrorToContext&&Je(e=>({...e,...r})),B.submitForm({formId:e.id,conversationId:a,trigger:t,values:r,skipped:i})}}),an=p(()=>H.activeForm.value);el({activated:se,conversationReady:N,conversationIdSig:v,messagesSig:x,optionsRef:Be,transport:B,visitorId:f,adoptControlStateChunk:gt,adoptMemoryCompactionStateChunk:bt,settleSuggestions:Jt,recordConversationReply:Dt,transcriptRecoverySig:St,beginConversationTranscript:wt,commitConversationTranscript:Tt,onReplyLanded:r(()=>H.fire(`after-messages`),[H]),runCancellation:Xe,canContinueRef:Ee,setCanSend:Te,feedback:Ye,bus:n,loadInitialThread:Wt,shouldReconcileOnConnect:r(()=>y.current||x.value.some(e=>!e.ephemeral&&e.role===`user`),[x])}),i(()=>{H.refresh()},[rn,H]);let on=e.pageContext?.area?String(e.pageContext.area):void 0,sn=p(()=>x.value.length);i(()=>{N&&F&&H.fire(`pre-chat`)},[N,F,H]),i(()=>{F&&!we&&H.fire(`conversation-closed`)},[F,we,H]),i(()=>{N&&F&&on&&H.fire(`page-area`)},[N,F,on,H]);let U=o(()=>{let e=rn.list.flatMap(e=>e.triggers).filter(e=>e.kind===`idle`).map(e=>Number(e.param));return e.length?Math.min(...e)*1e3:0},[rn]);i(()=>{if(!U||!L)return;let e=setTimeout(()=>H.fire(`idle`),U);return()=>clearTimeout(e)},[U,L,H,sn.value]);let W=r(async(t,r,i)=>{if(Ae.current)return!1;let a=v.value,o=a?yt.value.get(a):void 0,s=ut.value!==`ai-agent`;if(!s&&o?.status===`compacting`||($.info(`send`,{textLen:t.length,attachments:r.length,streaming:ke.current,routedToOperator:s}),ke.current&&!s))return!1;let c=new AbortController,l={conversationId:a,controller:c};Ae.current=l,Ne(!0);try{Ye.unlock();let o=await vl(B,r,c.signal,t=>{c.signal.aborted||($.warn(`upload failed`,{err:t}),n.emit(`error`,t),e.onError?.(t))});if(c.signal.aborted||v.value!==a||!Ee.current||H.activeForm.value)return!1;let s=a?yt.value.get(a):void 0,l=ut.value!==`ai-agent`;if(!l&&s?.status===`compacting`||ke.current&&!l||!t&&o.length===0)return!1;n.emit(`send`,{text:t,attachmentCount:r.length}),Le.length>0&&Re([]),Ye.play(`messageSent`);let u=Sn(t,o,i);return Ec(n,e,`user`,t),l?(x.value=[...x.value,u],i?await Qt(u):(Qt(u),!0)):(x.value=[...x.value,u,Cn()],i?await V({continueExisting:!1}):(V({continueExisting:!1}),!0))}finally{Ae.current===l&&(Ae.current=null,Ne(!1))}},[B,n,e,Le.length,x,v,yt,V,Qt,ut]),cn=v.value,ln=(cn?yt.value.get(cn):void 0)?.status===`compacting`,un=ut.value===`ai-agent`,dn=p(()=>{let e=x.value.at(-1);return e?.role===`assistant`&&e.partsSig.value.some(e=>e.kind===`tool`&&e.stateSig.value===`approval-requested`)}),fn=p(()=>x.value.some(e=>e.retryAction?.kind===`resend-user`||e.retryAction?.kind===`continue-assistant`));i(()=>{let e=v.value;return()=>{let t=Ae.current;!t||t.conversationId!==e||(Ae.current=null,Ne(!1),t.controller.abort())}},[v.value]),i(()=>{we&&!an.value||Ae.current?.controller.abort()},[an.value,we]);let pn=r(()=>{if(!Xe.stop())return;$.info(`stop`),n.emit(`stop`,void 0);let e=x.value.at(-1);e&&e.role!==`user`&&e.status===`streaming`&&(e.canceled=!0,x.value=[...x.value])},[Xe,n,x]),mn=r(e=>{if(De)return;let t=x.value,n=ir(t,e);if(n)switch($.info(`retry`,{kind:n.kind,messageId:n.messageId}),n.kind){case`continue-assistant`:if(ut.value!==`ai-agent`||e.role!==`assistant`||(e.serverMessageId??e.id)!==n.messageId)return;e.status=`streaming`,e.errorText=void 0,e.retryAction=void 0,e.awaitingContinuation=!0,x.value=[...t],V({continueExisting:!0,turn:e});return;case`resend-user`:{let r=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!r)return;let i=e=>{e&&Ot.current?.acceptQueuedMessage(n.messageId)};if(r.status=`complete`,r.errorText=void 0,r.retryAction=void 0,ut.value!==`ai-agent`){x.value=e.role===`assistant`?t.filter(t=>t!==e):[...t],Qt(r).then(i);return}let a=Cn();x.value=e.role===`assistant`?t.map(t=>t===e?a:t):[...t,a],V({continueExisting:!1,turn:r}).then(i);return}case`repeat-user`:{let e=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!e)return;let r=Sn(Nn(e),e.attachments?.map(e=>({...e}))??[]),i=new Set(r.attachments?.flatMap(e=>e.url?[e.url]:[])??[]),a=e.partsSig.value.flatMap(e=>e.kind===`file`&&!i.has(e.url)?[{...e}]:[]);if(a.length>0&&(r.partsSig.value=[...r.partsSig.value,...a]),ut.value!==`ai-agent`){x.value=[...t,r],Qt(r);return}x.value=[...t,r,Cn()],V({continueExisting:!1,turn:r});return}default:return n}},[De,x,ut,V,Qt]),hn=r(()=>{if(Li(e.mode,z)===`exit-fullscreen`){$.info(`close → exit-fullscreen`,{mode:e.mode}),ye(`normal`),n.emit(`fullscreen`,!1);return}$.info(`close → panel closed`,{mode:e.mode}),H.fire(`panel-close`),oe(!1),d.savePanelOpen(!1),n.emit(`close`,void 0),e.onClose?.()},[n,e,d,z,H]),gn=r(()=>{$.info(`open`,{mode:e.mode}),Ye.unlock(),R(!0),oe(!0),d.savePanelOpen(!0),!he&&!_e&&ve(),setTimeout(()=>R(!1),_l),n.emit(`open`,void 0),e.onOpen?.()},[n,e,Ye,d,he,_e,ve]),_n=r(()=>{let e=x.value.some(e=>e.role===`user`);if(ue.current===v.value&&!e&&we&&v.value){$.info(`clear → reusing empty conversation`,{conversationId:v.value}),x.value.length===0&&kt(fe.current?.messages);return}$.info(`clear → new conversation`,{wasStreaming:De}),n.emit(`clear`,void 0),Xe.settle(),y.current=!1,le.current=void 0,ue.current=void 0,l(()=>{x.value=[],v.value=void 0,ht({controlMode:`ai-agent`,controlRevision:0})}),d.clearConversation(),Te(!0),E([]),Re([]),Kt({newConversation:!0})},[De,x,v,d,Kt,n,we,kt,Xe,ht]),vn=r(()=>{_n(),Se(`chat`);let t=e.modules.list.find(e=>e.layout===`chat`)?.id;t&&M.switchTab(t)},[_n,M,e]),bn=r(()=>{let e=z===`expanded`?`normal`:`expanded`;$.info(`expand`,{from:z,expanded:e===`expanded`}),ye(e),d.savePanelSize(e),n.emit(`expand`,e===`expanded`)},[n,z,d]),xn=r(()=>{let e=z===`fullscreen`?`normal`:`fullscreen`;$.info(`fullscreen`,{from:z,fullscreen:e===`fullscreen`}),ye(e),d.savePanelSize(e),n.emit(`fullscreen`,e===`fullscreen`)},[n,z,d]),wn=r(()=>{Se(e=>{let t=e===`history`?`chat`:`history`;return $.info(`toggleHistory`,{view:t}),n.emit(`toggleHistory`,{view:t}),t})},[n]),Tn=r(()=>{Ke(e=>{let t=!e;return $.info(`sidebarToggle`,{collapsed:t}),d.saveSidebarCollapsed(t),n.emit(`sidebarToggle`,{collapsed:t}),t})},[d,n]),En=r(e=>{$.info(`resize`,e),it({widgetSize:e}),n.emit(`resize`,e)},[it,n]),On=r(async t=>{let r=t.conversationId;if(r===v.value&&Et(r)){$.info(`selectConversation`,{conversationId:r,cached:!0}),n.emit(`selectConversation`,{conversationId:r}),B.publishConversation(t),Se(`chat`);let e=k();e&&M.switchTab(e),Tt(r);return}let i=++zt.current;Bt.current++,C(!1);let a=()=>i!==zt.current;$.info(`selectConversation`,{conversationId:r,wasStreaming:De}),n.emit(`selectConversation`,{conversationId:r}),B.publishConversation(t);try{let[e,t]=await Promise.all([B.loadConversation(r),Pt(r)]);if(a())return;Xe.settle(),y.current=!0,le.current=void 0;let n=An(e.messages),i=e.conversationId!==v.value,o=i?n:Xn(n,x.value);ue.current=o.some(e=>e.role===`user`)?void 0:e.conversationId,l(()=>{x.value=Ht(o,t),i&&(b.value=e.conversationId),v.value=e.conversationId}),E(t),d.saveConversationId(e.conversationId),B.primeIdentity(f,e.conversationId),Te(e.canContinue),e.controlState&&ht(e.controlState);let s=o.findLast(e=>e.role===`assistant`&&!e.ephemeral);Re(s?.suggestions??[]),i?wt(e.conversationId):Tt(e.conversationId),Se(`chat`);let c=k();c&&M.switchTab(c)}catch(t){if(a())return;n.emit(`error`,t),e.onError?.(t)}},[B,x,v,b,n,e,d,Pt,Ht,De,f,Xe,wt,Tt,Et,M]),kn=s(null),jn=r(e=>{typeof e==`string`&&(F?H.fire(`manual`,e):kn.current=e)},[F,H]);i(()=>{!F||!kn.current||(H.fire(`manual`,kn.current),kn.current=null)},[F,H]);let Mn=s({handleOpen:gn,handleClose:hn,handleExpand:bn,handleFullscreen:xn,openForm:jn});Mn.current={handleOpen:gn,handleClose:hn,handleExpand:bn,handleFullscreen:xn,openForm:jn},a(()=>Nt(t,{open:()=>Mn.current.handleOpen(),close:()=>Mn.current.handleClose(),expand:()=>Mn.current.handleExpand(),fullscreen:()=>Mn.current.handleFullscreen(),openForm:e=>Mn.current.openForm(e)}),[t]);let Pn=o(()=>Fe(e,Ze,Qe,$e),[e,Ze,Qe,$e]);ze.current=Pn.strings;let Fn=o(()=>T.map(e=>{let t=rn.list.find(t=>t.id===e.formId);return{...e,title:t?.title,form:t}}),[T,rn]),In=e=>{On(e)},Ln={options:Pn,transport:B,feedback:Ye,bus:n,persistence:d,conversationId:v.value??``,composerKey:b.value,composerApiRef:Ot,view:xe,canSend:we,isStreaming:De,isMemoryCompacting:ln,canReleaseQueuedMessages:N&&!S&&!an.value&&(!un||!dn.value&&!fn.value),queueManualMessages:un&&(dn.value||fn.value),sendPreparing:je,composerActive:Pn.mode===`page`||Pn.mode===`inline`||Pn.mode===`standalone`||L,controlMode:ut.value,assignedOperatorInitials:ft.value,operatorAvailable:pt.value,operatorRequestEnabled:e.features.operatorRequest,onRequestOperator:_t,onCancelOperatorRequest:vt,loadingMessages:S,onLoadPreviousMessages:Gt,messagesSig:x,agent:Pe,suggestions:Le,initialWidgetSize:h.widgetSize??null,onClose:hn,onClear:_n,onExpand:bn,onFullscreen:xn,onSoundToggle:lt,onToggleHistory:wn,onSelectHistoryConversation:In,onNewConversation:vn,onLocaleChange:at,onThemeChange:ot,onTextSizeChange:st,onWidgetSizeChange:En,onSend:W,onStop:pn,onSuggestion:t=>{if(Ae.current)return;let r=t.text??t.label;$.info(`suggestion`,{text:r,autoSend:e.autoSendSuggestions}),n.emit(`suggestion`,{text:r}),e.autoSendSuggestions?W(r,[]):Ot.current?.fill(r)},activeForm:an.value?.form??null,formMarkers:Fn,onFormSubmit:H.complete,onFormSkip:H.skip,onFormFill:e=>H.fire(`manual`,e),tool:$t,onRetry:mn,onMessageFeedback:tn};if(!N)return null;let Rn=Pn.modules.list,zn=e=>{let t=Fi(`close`,Pn.mode,e);return Rn.length===0?g(Tc,{strings:Pn.strings,onClose:t?hn:void 0}):Rn.length===1&&Rn[0]?.layout===`chat`?g(us,{...Ln,panelSize:e}):g(Cc,{panelProps:{...Ln,panelSize:e,onClose:t?hn:void 0},enabledModules:Rn,nav:M,bus:n,hasUnread:xt.value,onSelectConversation:In,onStartNewConversation:vn,onSetPanelSize:ye})};if(e.mode===`page`){let e=Rn.some(e=>e.layout===`chat`);return g(`div`,{class:`${pl}-anchor`,children:g(ks,{site:Ve,blocks:Ue,transport:B,strings:Pn.strings,locale:Pn.locale,persistence:d,showConversations:e,onSelectConversation:In,onNewConversation:vn,sidebarCollapsed:Ge,onToggleSidebarCollapsed:Tn,children:zn(`fullscreen`)})})}if(ae){let t=e.mode===`standalone`?`fullscreen`:z;return g(`div`,{class:`${pl}-anchor`,children:zn(t)})}let Bn=e.mode===`drawer`,Vn=e.mode!==`modal`&&!e.launcher.hidden&&(!L||me),Hn=Vn&&!me&&!he&&!Bn?Pn.launcher.callout:null;return _(`div`,{class:`${pl}-anchor`,"data-launcher-size":Pn.launcher.size,children:[L||se?g(`div`,{class:`${pl}-surface`,hidden:!L,children:zn(z)}):null,Vn?g(Ti,{onToggle:gn,launcher:Pn.launcher,strings:Pn.strings,leaving:me,edgeTab:Bn}):null,Hn?g(ki,{callout:Hn,launcherPosition:Pn.position,strings:Pn.strings,closeLabel:Pn.strings.close,onDismiss:ve}):null]})}function gl(e){let t=e?.url??(typeof location<`u`?location.href:void 0);if(!(!e&&!t))return{...e,...t?{url:t}:{}}}const _l=120;async function vl(e,t,n,r){return(await Promise.all(t.map(async t=>{try{let{id:r,url:i}=await e.uploadFile(t.file,n);return{id:r,name:t.name,mediaType:t.mediaType,size:t.size,url:i}}catch(e){r(e);return}}))).filter(e=>e!==void 0)}const yl=I.scope(`error-boundary`);var bl=class extends e{constructor(...e){super(...e),U(this,`state`,{crashed:!1})}componentDidCatch(e,t){yl.error(`widget render crashed`,{error:e,componentStack:t?.componentStack}),this.setState({crashed:!0}),this.props.onError(e,t?.componentStack)}render(){return this.state.crashed?this.props.fallback:this.props.children}};const xl={open:()=>void 0,close:()=>void 0,expand:e=>({on:e}),fullscreen:e=>({on:e}),send:e=>({attachments:e.attachmentCount}),message:e=>({role:e.role}),stop:()=>void 0,clear:()=>void 0,suggestion:()=>void 0,toggleHistory:e=>({view:e.view}),handshake:()=>void 0,formSubmit:e=>({formId:e.formId,skipped:e.skipped}),toolResult:()=>void 0,toolDecision:e=>({approved:e.approved}),messageFeedback:e=>({value:e.value??`none`}),contentView:e=>({section:e.section,tags:e.tags,count:e.count}),contentOpen:e=>({contentId:e.contentId,tags:e.tags}),contentSearch:e=>({qlen:e.queryLength,hits:e.hitCount}),contentRead:e=>({contentId:e.contentId}),contentLinkClick:e=>({contentId:e.contentId}),attach:e=>({count:e.count,bytes:e.totalBytes}),voiceStart:()=>void 0,voiceStop:e=>({ms:e.durationMs}),voiceCancel:()=>void 0,localeChange:e=>({locale:e}),themeChange:e=>({theme:e}),textSizeChange:e=>({size:e}),soundToggle:e=>({muted:e.muted}),sidebarToggle:e=>({collapsed:e.collapsed}),calloutDismiss:()=>void 0,error:()=>void 0};function Sl(){let e=navigator;return e.globalPrivacyControl===!0||e.doNotTrack===`1`}function Cl(){return location.origin+location.pathname}function wl(){try{return document.referrer?new URL(document.referrer).origin:``}catch{return``}}function Tl(e,t){let n=Math.random(),r=0,i=0,a=new Set,o=(e,o)=>{let{tracking:s,publicKey:c,aiAgentDeploymentId:l,mode:u,themeMode:d}=t.getOptions();if(!s.enabled||Sl()||n>=s.sampleRate)return;let f=performance.now();if(f-r>6e4&&(r=f,i=0),++i>60)return;let p=new URLSearchParams;p.set(`v`,`1`),p.set(`_ev`,Bt),p.set(`e`,e),s.token&&p.set(`tk`,s.token),c&&p.set(`pk`,c),l&&p.set(`dep`,l),p.set(`vid`,t.getVisitorId());let m=t.getConversationId();m&&p.set(`cid`,m),p.set(`url`,Cl());let h=wl();h&&p.set(`ref`,h),p.set(`sw`,String(screen.width)),p.set(`sh`,String(screen.height)),p.set(`vw`,String(innerWidth)),p.set(`vh`,String(innerHeight)),p.set(`dpr`,String(devicePixelRatio)),p.set(`lang`,navigator.language);try{p.set(`tz`,Intl.DateTimeFormat().resolvedOptions().timeZone)}catch{}if(p.set(`m`,u),p.set(`th`,d),o)for(let[e,t]of Object.entries(o))t!==void 0&&p.set(e,String(t));p.set(`ts`,String(Date.now()));let g=`${s.endpoint}?${p}`;if(g.length>2e3)return;let _=new Image(1,1);a.add(_);let v=()=>a.delete(_);_.addEventListener(`load`,v,{once:!0}),_.addEventListener(`error`,v,{once:!0}),_.src=g},s=Object.keys(xl).map(t=>e.on(t,e=>o(t,xl[t]?.(e))));return()=>{for(let e of s)e();a.clear()}}function El(e){let{bus:r,host:i,appRoot:a,persistence:o,reportError:s}=e,c=e.initialRaw,l,u=xe(c),d=!0,f=()=>{u=xe(l?Le(c,l):c)},p=()=>{yt(i,bt(u.mode));let e=o.loadUserPrefs().themeMode;Ot(i,e?{...u,themeMode:e}:u),d&&(Dt(i,Dl(u)),d=!1)},m=()=>{p(),n(t(bl,{onError:s},t(hl,{bus:r,hostElement:i,options:u})),a)};r.on(`handshake`,e=>{e.config&&(e.config.storageVersion&&o.rememberStorageVersion(e.config.storageVersion),l=e.config,f(),m())});let h=Tl(r,{getOptions:()=>u,getVisitorId:()=>o.getVisitorId(),getConversationId:()=>o.loadConversationId()});return{getOptions:()=>u,getUserOptions:()=>c,render:m,setUserOptions:e=>{c=e,f(),m()},patchUserOptions:e=>{c={...c,...e},f(),m()},destroy:()=>h()}}function Dl(e){if(e.mode===`standalone`)return`standalone`;if(e.mode===`inline`)return`inline`;let t=dt(e.widgetId,e.storage,e.aiAgentDeploymentId),{panelOpen:n,panelSize:r}=It(e,Lt(),t.loadPanelOpen(),t.loadPanelSize());return Pt(e.mode,r,n)}var Ol=class{constructor(){U(this,`handlers`,new Map)}on(e,t){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(t),()=>this.handlers.get(e)?.delete(t)}emit(e,t){let n=this.handlers.get(e);if(n)for(let e of n)try{e(t)}catch{}}clear(){this.handlers.clear()}},kl=class extends HTMLElement{constructor(...e){super(...e),U(this,`bus`,new Ol),U(this,`mountResult`,null),U(this,`runtime`,null)}static get observedAttributes(){return rt}connectedCallback(){this.boot()}disconnectedCallback(){this.mountResult&&(this.runtime?.destroy(),this.runtime=null,n(null,this.mountResult.appRoot),this.bus.clear())}attributeChangedCallback(){this.isConnected&&this.boot()}boot(){let e=it(e=>this.getAttribute(e));if(!e.aiAgentDeploymentId)throw Error(`ai-agent-deployment-id is required`);if(this.runtime){this.runtime.setUserOptions(e);return}let t=xe(e);this.mountResult??(this.mountResult=xt({existingHost:this,position:bt(t.mode)}));let n=dt(t.widgetId,t.storage,t.aiAgentDeploymentId);this.runtime=El({bus:this.bus,host:this.mountResult.hostElement,appRoot:this.mountResult.appRoot,persistence:n,initialRaw:e,reportError:e=>this.bus.emit(`error`,e)}),this.runtime.render()}};let Al=!1;function jl(){if(Al||typeof customElements>`u`)return;let e=b.tagName;customElements.get(e)||customElements.define(e,kl),Al=!0}typeof customElements<`u`&&jl();export{jl as registerWebComponent};
|
|
13
13
|
//# sourceMappingURL=web-component.mjs.map
|