@helpai/elements 1.1.13 → 1.1.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/index.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=`1.1.13`,S={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`,resizeHandle:`Drag to resize`,scrollToBottom:`Scroll to latest`,send:`Send`,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`},C={en:S,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`,resizeHandle:`Glisser pour redimensionner`,scrollToBottom:`Aller au plus récent`,send:`Envoyer`,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:`الدردشة`,resizeHandle:`اسحب لتغيير الحجم`,scrollToBottom:`الانتقال إلى الأحدث`,send:`إرسال`,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`,resizeHandle:`Arrastra para cambiar el tamaño`,scrollToBottom:`Ir a lo más reciente`,send:`Enviar`,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:`צ׳אט`,resizeHandle:`גרור לשינוי הגודל`,scrollToBottom:`מעבר לחדש ביותר`,send:`שליחה`,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 w(e,t){let n=T(e),r=k(t),i=n===`en`?{}:C[n]??{},a=r?t[n]??{}:t??{},o=r?t.en??{}:{};return{...S,...i,...o,...a}}function T(e){return(e.split(`-`)[0]??`en`).toLowerCase()}const E=new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`,`ks`,`nqo`,`prs`,`syr`]);function D(e){return E.has(T(e))}function O(e,t){return e[t]??t}function k(e){if(!e)return!1;for(let t of Object.values(e))if(t&&typeof t==`object`)return!0;return!1}function A(e,t){if(!(!e?.length||!t))return e.find(e=>e.locale===t)}function j(e,t){let{translations:n,defaultLocale:r,...i}=e,a=A(n,t);return a?{...i,title:a.title??i.title,description:a.description??i.description,content:a.content??i.content}:i}function M(e,t){let{translations:n,defaultLocale:r,...i}=e,a=A(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 ee=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{}}},te=[`off`,`error`,`warn`,`info`,`debug`,`trace`],N=b.cssPrefix,ne=`${N}.debug`,re=`__${b.global}_DEBUG__`,ie=`${N}-debug`;let P=2,ae=null;function oe(){if(typeof window>`u`)return 2;try{let e=new URLSearchParams(window.location.search).get(ie);if(e!==null){let t=F(e);if(t>=0)return t}}catch{}try{let e=window.localStorage?.getItem(ne);if(e){let t=F(e);if(t>=0)return t}}catch{}return Reflect.get(window,re)?4:2}function F(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=te.indexOf(e);if(t>=0)return t}return-1}function I(e){let t=F(e);if(!(t<0)){P=t;try{window.localStorage?.setItem(ne,te[t])}catch{}}}function se(){return te[P]}P=oe();function ce(e){let t=`[${N}:${e}]`,n=(n,r,i)=>(a,o)=>{if(!(P<n)&&(o===void 0?console[r](t,a):console[r](t,a,o),ae))try{ae({level:i,scope:e,message:a,payload:o})}catch{}};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=>ce(`${e}:${t}`)}}const L=ce(`core`);function le(e){ae=e}const R=L.scope(`context`),ue=new Set([`visitorId`,`conversationId`,`conversationId`,`jwt`,`token`,`authorization`,`password`]),z=1024,de=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function fe(e){return me(e,`userContext`,!0)}function pe(e){return me(e,`pageContext`,!1)}function me(e,t,n){if(e==null)return;if(typeof e!=`object`||Array.isArray(e)){R.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(ue.has(n)){R.warn(`dropped reserved ${t} key "${n}" — managed by the widget, not host-settable`);continue}if(a==null)continue;if(i>=50){R.warn(`${t} truncated at 50 keys — dropped "${n}"`);continue}let e=he(t,n,a);e!==void 0&&(r[n]=e,i++)}return n&&typeof r.email==`string`&&!de.test(r.email)&&(R.warn(`dropped malformed ${t}.email "${r.email}"`),delete r.email),Object.keys(r).length>0?r:void 0}function he(e,t,n){if(typeof n==`boolean`)return n;if(typeof n==`number`){if(!Number.isFinite(n)){R.warn(`dropped non-finite ${e}.${t}`);return}return n}if(typeof n==`string`){let r=n.trim();return r===``?void 0:r.length>z?(R.warn(`truncated ${e}.${t} to ${z} chars`),r.slice(0,z)):r}R.warn(`dropped ${e}.${t} — only string/number/boolean values are allowed`,{type:typeof n})}const ge={maxBytes:10*1024*1024,maxCount:10,accept:`*/*`},_e={voice:`local`},ve={list:[],byTrigger:{}},ye={enabled:!0,sampleRate:1},be={upload:`/pai/upload-file`,transcribe:`/pai/transcribe-audio`,submitForm:`/pai/submit-form`},xe={variant:`circle`,size:`md`,label:void 0,icon:`chat`,hidden:!1},Se={floating:[`theme`,`textSize`,`history`,`close`,`clear`,`expand`,`fullscreen`,`sound`,`language`],inline:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`sound`,`language`],standalone:[`theme`,`textSize`,`history`,`clear`,`sound`,`language`],page:[`theme`,`textSize`,`history`,`clear`,`sound`,`language`],modal:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`sound`,`language`],drawer:[`theme`,`textSize`,`history`,`close`,`clear`,`fullscreen`,`sound`,`language`]},Ce={enabled:!0,volume:.3,events:void 0},we={enabled:!0,events:void 0},Te=[{label:`tabConversations`,layout:`chat`}];function Ee(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}=De(t.theme),u=n.mode??`floating`,d=Oe(i.defaultLocale),f=i.availableLocales??[i.locale??d],p=ke(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:fe(t.userContext),pageContext:pe(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,features:{voice:t.features?.voice??_e.voice,fileUpload:!(t.features?.disableFileUpload??!1),humanInLoop:!(t.features?.disableHumanInLoop??!1),operatorRequest:t.features?.enableOperatorRequest===!0},forms:Le(t.forms,p),endpoints:{upload:t.endpoints?.upload??be.upload,transcribe:t.endpoints?.transcribe??be.transcribe,submitForm:t.endpoints?.submitForm??be.submitForm},attachments:{accept:t.composer?.attachments?.accept??ge.accept,maxBytes:t.composer?.attachments?.maxBytes??ge.maxBytes,maxCount:t.composer?.attachments?.maxCount??ge.maxCount},locale:p,defaultLocale:d,availableLocales:f,startMinimized:r.startMinimized??!0,actions:Ae(u,s.actions),size:n.size??{},launcher:ze(t.launcher),sound:je(a.sound),haptics:Me(a.haptics),strings:w(p,i.strings),stringsOverride:i.strings,composerDisclaimer:o.composerDisclaimer??``,poweredBy:Pe(o.poweredBy),composer:Fe(t.composer),modules:Ie(t.modules),tracking:Ne(t.tracking,g),storage:t.storage??ee,onMessage:t.onMessage,onOpen:t.onOpen,onClose:t.onClose,onError:t.onError}}function De(e){return typeof e==`string`?{themeMode:e,themeOverrides:{}}:e&&typeof e==`object`?{themeMode:`auto`,themeOverrides:e}:{themeMode:`auto`,themeOverrides:{}}}function Oe(e){return e&&e!==`auto`?e:typeof navigator<`u`&&navigator.language?navigator.language:`en`}function ke(e,t,n){return t.length<=1||t.includes(e)?e:t.includes(n)?n:t[0]??e}function Ae(e,t){return t??Se[e]}function je(e){return{enabled:e?.enabled??Ce.enabled,volume:e?.volume??Ce.volume,events:e?.events}}function Me(e){return{enabled:e?.enabled??we.enabled,events:e?.events}}function Ne(e,t){let n=e?.sampleRate??ye.sampleRate;return{enabled:e?.enabled??ye.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 Pe(e){let t={text:`Powered by ${b.displayName}`,href:b.siteUrl,...e};return t.text||t.logoUrl?t:null}function Fe(e){let t=e?.sendButton;return{sendButton:{shape:t?.shape??`circle`,icon:t?.icon??`arrowUp`,variant:t?.variant??`filled`}}}function Ie(e){let t=e===void 0?Te: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 Le(e,t){if(!e?.length)return ve;let n=[],r=new Set;for(let i of e){if(!i?.id||r.has(i.id))continue;let e=M(i,t),a=(e.fields??[]).filter(e=>!!(e&&e.name&&e.label&&e.type)),o=(Array.isArray(e.on)?e.on:[e.on]).map(Re).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 Re(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 ze(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??xe.variant,size:e?.size??xe.size,label:e?.label??xe.label,icon:e?.icon??xe.icon,hidden:e?.hidden??xe.hidden,callout:t}}function Be(e,t,n,r){let i=ke(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=w(i,e.stringsOverride)),n!==e.themeMode&&(a.themeMode=n),r!==e.textSize&&(a.textSize=r),a}const Ve=[`presentation`,`behavior`,`theme`,`launcher`,`header`,`composer`,`feedback`,`i18n`,`footer`,`features`,`tracking`,`endpoints`];function He(e,t){if(!t)return e;let n={...e};for(let r of Ve){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]=Ue(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=Ue(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=We(a,t)),n.i18n=e}return n}function Ue(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 We(e,t){if(!e)return t;if(!t)return e;let n=k(e),r=k(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 Ge=[`clear`,`expand`,`fullscreen`,`sound`,`history`,`language`,`theme`,`textSize`,`close`],Ke=e=>e!==`false`,qe=[[`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]],Je=[[`mode`,`mode`,e=>e],[`position`,`position`,e=>e],[`iframe`,`iframe`,Ke]],B=[[`width`,`width`],[`height`,`height`]],Ye=[[`response-mode`,`responseMode`,e=>e],[`start-minimized`,`startMinimized`,Ke],[`show-reasoning`,`showReasoning`,Ke],[`show-tool-calls`,`showToolCalls`,Ke],[`show-sources`,`showSources`,Ke],[`disable-message-feedback`,`disableMessageFeedback`,Ke],[`auto-send-suggestions`,`autoSendSuggestions`,Ke]],Xe=[[`locale`,`locale`]];new Set(Ge);const Ze=[[`launcher-variant`,`variant`,e=>e],[`launcher-size`,`size`,e=>e],[`launcher-icon`,`icon`],[`launcher-hidden`,`hidden`,Ke]],Qe=[[`features-disable-file-upload`,`disableFileUpload`,Ke],[`features-voice`,`voice`,e=>e]],$e=[[`endpoint-upload`,`upload`],[`endpoint-transcribe`,`transcribe`]],et=[[`user-id`,`id`],[`user-email`,`email`],[`user-name`,`name`]],tt=[[`page-area`,`area`],[`page-url`,`url`],[`page-path`,`path`],[`page-title`,`title`]],nt=[`launcher-label`,`callout-text`,`callout-delay`,`actions`,`user-context`,`page-context`],rt=[qe,Je,B,Ye,Xe,Ze,Qe,$e,et,tt],it=new Set([`iframe`,`start-minimized`]);[...rt.flatMap(e=>e.map(([e])=>e).filter(e=>!it.has(e))),...nt];function at(e){return`${b.cssPrefix}:${e}`}function ot(e,t,n){e.dispatchEvent(new CustomEvent(at(t),{detail:n}))}function st(e,t){let n=Object.entries(t).map(([t,n])=>{let r=at(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 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=L.scope(`persistence`);function dt(e,t=ee,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},setVisitorId(e){ut.debug(`setVisitorId (rebind)`,{id:e,scope:r}),t.set(c,e)},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)},loadUserPrefs(){let e=t.get(u);if(!e)return{};try{let t=JSON.parse(e);return ft(t)?t:{}}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)?t:{}}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)}const pt=[`: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=`1.1.15`,S={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`,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`},C={en:S,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`,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:`إرسال`,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`,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:`שליחה`,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 w(e,t){let n=T(e),r=k(t),i=n===`en`?{}:C[n]??{},a=r?t[n]??{}:t??{},o=r?t.en??{}:{};return{...S,...i,...o,...a}}function T(e){return(e.split(`-`)[0]??`en`).toLowerCase()}const E=new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`,`ks`,`nqo`,`prs`,`syr`]);function D(e){return E.has(T(e))}function O(e,t){return e[t]??t}function k(e){if(!e)return!1;for(let t of Object.values(e))if(t&&typeof t==`object`)return!0;return!1}function A(e,t){if(!(!e?.length||!t))return e.find(e=>e.locale===t)}function j(e,t){let{translations:n,defaultLocale:r,...i}=e,a=A(n,t);return a?{...i,title:a.title??i.title,description:a.description??i.description,content:a.content??i.content}:i}function M(e,t){let{translations:n,defaultLocale:r,...i}=e,a=A(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 ee=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{}}},te=[`off`,`error`,`warn`,`info`,`debug`,`trace`],N=b.cssPrefix,ne=`${N}.debug`,re=`__${b.global}_DEBUG__`,ie=`${N}-debug`;let P=2,ae=null;function oe(){if(typeof window>`u`)return 2;try{let e=new URLSearchParams(window.location.search).get(ie);if(e!==null){let t=F(e);if(t>=0)return t}}catch{}try{let e=window.localStorage?.getItem(ne);if(e){let t=F(e);if(t>=0)return t}}catch{}return Reflect.get(window,re)?4:2}function F(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=te.findIndex(t=>t===e);if(t>=0)return t}return-1}function I(e){let t=F(e);if(!(t<0)){P=t;try{window.localStorage?.setItem(ne,te[t]??`off`)}catch{}}}function se(){return te[P]??`warn`}P=oe();function ce(e){let t=`[${N}:${e}]`,n=(n,r,i)=>(a,o)=>{if(!(P<n)&&(o===void 0?console[r](t,a):console[r](t,a,o),ae))try{ae({level:i,scope:e,message:a,payload:o})}catch{}};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=>ce(`${e}:${t}`)}}const L=ce(`core`);function le(e){ae=e}const R=L.scope(`context`),ue=new Set([`visitorId`,`conversationId`,`conversationId`,`jwt`,`token`,`authorization`,`password`]),z=1024,de=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function fe(e){return me(e,`userContext`,!0)}function pe(e){return me(e,`pageContext`,!1)}function me(e,t,n){if(e==null)return;if(typeof e!=`object`||Array.isArray(e)){R.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(ue.has(n)){R.warn(`dropped reserved ${t} key "${n}" — managed by the widget, not host-settable`);continue}if(a==null)continue;if(i>=50){R.warn(`${t} truncated at 50 keys — dropped "${n}"`);continue}let e=he(t,n,a);e!==void 0&&(r[n]=e,i++)}return n&&typeof r.email==`string`&&!de.test(r.email)&&(R.warn(`dropped malformed ${t}.email "${r.email}"`),delete r.email),Object.keys(r).length>0?r:void 0}function he(e,t,n){if(typeof n==`boolean`)return n;if(typeof n==`number`){if(!Number.isFinite(n)){R.warn(`dropped non-finite ${e}.${t}`);return}return n}if(typeof n==`string`){let r=n.trim();return r===``?void 0:r.length>z?(R.warn(`truncated ${e}.${t} to ${z} chars`),r.slice(0,z)):r}R.warn(`dropped ${e}.${t} — only string/number/boolean values are allowed`,{type:typeof n})}const ge={maxBytes:10*1024*1024,maxCount:10,accept:`*/*`},_e={voice:`local`},ve={list:[],byTrigger:{}},ye={enabled:!0,sampleRate:1},be={upload:`/pai/upload-file`,transcribe:`/pai/transcribe-audio`,submitForm:`/pai/submit-form`},xe={variant:`circle`,size:`md`,label:void 0,icon:`chat`,hidden:!1},Se={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`]},Ce={enabled:!0,volume:.3,events:void 0},we={enabled:!0,events:void 0},Te=[{label:`tabConversations`,layout:`chat`}];function Ee(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}=De(t.theme),u=n.mode??`floating`,d=Oe(i.defaultLocale),f=i.availableLocales??[i.locale??d],p=ke(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:fe(t.userContext),pageContext:pe(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??_e.voice,fileUpload:!(t.features?.disableFileUpload??!1),humanInLoop:!(t.features?.disableHumanInLoop??!1),operatorRequest:t.features?.enableOperatorRequest===!0},forms:Le(t.forms,p),endpoints:{upload:t.endpoints?.upload??be.upload,transcribe:t.endpoints?.transcribe??be.transcribe,submitForm:t.endpoints?.submitForm??be.submitForm},attachments:{accept:t.composer?.attachments?.accept??ge.accept,maxBytes:t.composer?.attachments?.maxBytes??ge.maxBytes,maxCount:t.composer?.attachments?.maxCount??ge.maxCount},locale:p,defaultLocale:d,availableLocales:f,startMinimized:r.startMinimized??!0,actions:Ae(u,s.actions),size:n.size??{},launcher:ze(t.launcher),sound:je(a.sound),haptics:Me(a.haptics),strings:w(p,i.strings),stringsOverride:i.strings,composerDisclaimer:o.composerDisclaimer??``,poweredBy:Pe(o.poweredBy),composer:Fe(t.composer),modules:Ie(t.modules),tracking:Ne(t.tracking,g),storage:t.storage??ee,onMessage:t.onMessage,onOpen:t.onOpen,onClose:t.onClose,onError:t.onError}}function De(e){return typeof e==`string`?{themeMode:e,themeOverrides:{}}:e&&typeof e==`object`?{themeMode:`auto`,themeOverrides:e}:{themeMode:`auto`,themeOverrides:{}}}function Oe(e){return e&&e!==`auto`?e:typeof navigator<`u`&&navigator.language?navigator.language:`en`}function ke(e,t,n){return t.length<=1||t.includes(e)?e:t.includes(n)?n:t[0]??e}function Ae(e,t){return t??Se[e]}function je(e){return{enabled:e?.enabled??Ce.enabled,volume:e?.volume??Ce.volume,events:e?.events}}function Me(e){return{enabled:e?.enabled??we.enabled,events:e?.events}}function Ne(e,t){let n=e?.sampleRate??ye.sampleRate;return{enabled:e?.enabled??ye.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 Pe(e){let t={text:`Powered by ${b.displayName}`,href:b.siteUrl,...e};return t.text||t.logoUrl?t:null}function Fe(e){let t=e?.sendButton;return{sendButton:{shape:t?.shape??`circle`,icon:t?.icon??`arrowUp`,variant:t?.variant??`filled`}}}function Ie(e){let t=e===void 0?Te: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 Le(e,t){if(!e?.length)return ve;let n=[],r=new Set;for(let i of e){if(!i?.id||r.has(i.id))continue;let e=M(i,t),a=(e.fields??[]).filter(e=>!!(e&&e.name&&e.label&&e.type)),o=(Array.isArray(e.on)?e.on:[e.on]).map(Re).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 Re(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 ze(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??xe.variant,size:e?.size??xe.size,label:e?.label??xe.label,icon:e?.icon??xe.icon,hidden:e?.hidden??xe.hidden,callout:t}}function Be(e,t,n,r){let i=ke(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=w(i,e.stringsOverride)),n!==e.themeMode&&(a.themeMode=n),r!==e.textSize&&(a.textSize=r),a}const Ve=[`presentation`,`behavior`,`theme`,`launcher`,`header`,`composer`,`feedback`,`i18n`,`footer`,`features`,`tracking`,`endpoints`];function He(e,t){if(!t)return e;let n={...e};for(let r of Ve){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]=Ue(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=Ue(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=We(a,t)),n.i18n=e}return n}function Ue(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 We(e,t){if(!e)return t;if(!t)return e;let n=k(e),r=k(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 Ge=[`clear`,`expand`,`fullscreen`,`popOut`,`sound`,`history`,`language`,`theme`,`textSize`,`close`],Ke=e=>e!==`false`,qe=[[`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]],Je=[[`mode`,`mode`,e=>e],[`position`,`position`,e=>e],[`iframe`,`iframe`,Ke]],B=[[`width`,`width`],[`height`,`height`]],Ye=[[`response-mode`,`responseMode`,e=>e],[`start-minimized`,`startMinimized`,Ke],[`show-reasoning`,`showReasoning`,Ke],[`show-tool-calls`,`showToolCalls`,Ke],[`show-sources`,`showSources`,Ke],[`disable-message-feedback`,`disableMessageFeedback`,Ke],[`auto-send-suggestions`,`autoSendSuggestions`,Ke],[`pop-out-url`,`popOutUrl`]],Xe=[[`locale`,`locale`]];new Set(Ge);const Ze=[[`launcher-variant`,`variant`,e=>e],[`launcher-size`,`size`,e=>e],[`launcher-icon`,`icon`],[`launcher-hidden`,`hidden`,Ke]],Qe=[[`features-disable-file-upload`,`disableFileUpload`,Ke],[`features-voice`,`voice`,e=>e]],$e=[[`endpoint-upload`,`upload`],[`endpoint-transcribe`,`transcribe`]],et=[[`user-id`,`id`],[`user-email`,`email`],[`user-name`,`name`]],tt=[[`page-area`,`area`],[`page-url`,`url`],[`page-path`,`path`],[`page-title`,`title`]],nt=[`launcher-label`,`callout-text`,`callout-delay`,`actions`,`user-context`,`page-context`],rt=[qe,Je,B,Ye,Xe,Ze,Qe,$e,et,tt],it=new Set([`iframe`,`start-minimized`]);[...rt.flatMap(e=>e.map(([e])=>e).filter(e=>!it.has(e))),...nt];function at(e){return`${b.cssPrefix}:${e}`}function ot(e,t,n){e.dispatchEvent(new CustomEvent(at(t),{detail:n}))}function st(e,t){let n=Object.entries(t).map(([t,n])=>{let r=at(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 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=L.scope(`persistence`);function dt(e,t=ee,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)},loadUserPrefs(){let e=t.get(u);if(!e)return{};try{return pt(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){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 mt=[`: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__-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`),mt=L.scope(`mount`),ht=new WeakMap,gt={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 _t(e,t){e.style.cssText=gt[t]}function vt(e){return e===`floating`||e===`modal`||e===`drawer`?`floating`:e===`standalone`||e===`page`?`viewport`:`flow`}function yt(e={}){let t=e.position??`flow`;mt.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=gt[t];let i=r.shadowRoot??r.attachShadow({mode:`open`}),a=r.ownerDocument;if(!bt(i,a)){let e=a.createElement(`style`);e.textContent=pt,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 bt(e,t){if(!(`adoptedStyleSheets`in e))return!1;let n=t.defaultView;if(!n||typeof n.CSSStyleSheet!=`function`)return!1;let r=ht.get(t);if(!r)try{r=new n.CSSStyleSheet,r.replaceSync(pt),ht.set(t,r)}catch{return!1}try{return e.adoptedStyleSheets=[r],!0}catch{return!1}}function xt(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 St(e,t){e.dataset.theme=t}function Ct(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 wt(e,t){e.dataset.position=t}function Tt(e,t){e.dataset.mode=t}function Et(e,t){St(e,t.themeMode),xt(e,t.themeOverrides),wt(e,t.position),Ct(e,t.size)}const Dt=L.scope(`iframe`);function Ot(e,t,n=`closed`,r=`floating`,i=null){Dt.debug(`createIframeMount`,{position:t,initialMode:n,layoutMode:r,hasTarget:!!i});let a=document.createElement(`iframe`);a.title=`${b.name} chat`,a.setAttribute(`allow`,`microphone; clipboard-write`),jt(a,t,n,r),(r===`inline`&&i?i:document.body).appendChild(a);let o=a.contentDocument;if(!o)throw Error(`iframe contentDocument unavailable (cross-origin?)`);o.open(),o.write(`<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style></head><body></body></html>`),o.close();let s=yt({...e,target:o.body}),c=new MutationObserver(()=>{jt(a,t,s.hostElement.dataset.mode??`closed`,r)});return c.observe(s.hostElement,{attributes:!0,attributeFilter:[`data-mode`]}),{...s,iframeElement:a,destroy(){c.disconnect(),s.destroy(),a.remove()}}}const kt=`border:0;background:transparent;z-index:2147483647;pointer-events:auto;`,At={closed:{w:`88px`,h:`88px`},expanded:{w:`min(calc(100vw - 32px), 680px)`,h:`min(calc(100vh - 32px), 860px)`},open:{w:`min(calc(100vw - 32px), 440px)`,h:`min(calc(100vh - 32px), 700px)`}};function jt(e,t,n,r){if(n===`fullscreen`||r===`standalone`){e.style.cssText=`${kt}position:fixed;inset:0;width:100vw;height:100vh;`;return}if(r===`inline`){e.style.cssText=`${kt}position:static;display:block;width:100%;height:100%;`;return}if(typeof matchMedia==`function`&&matchMedia(`(max-width: 640px)`).matches&&(n===`open`||n===`expanded`)){e.style.cssText=`${kt}position:fixed;inset:0;width:100vw;height:100vh;`;return}let i=t.startsWith(`top-`)?`top`:`bottom`,a=t.endsWith(`-left`)?`left`:`right`,{w:o,h:s}=At[n]??At.open;e.style.cssText=`${kt}position:fixed;${i}:16px;${a}:16px;width:${o};height:${s};`}function Mt(e){"@babel/helpers - typeof";return Mt=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},Mt(e)}function Nt(e,t){if(Mt(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Mt(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Pt(e){var t=Nt(e,`string`);return Mt(t)==`symbol`?t:t+``}function V(e,t,n){return(t=Pt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Ft=class{constructor(){V(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()}};function It(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Lt(e){return It(e)}function Rt(e){return!(!It(e)||e.navigation!==void 0&&!Array.isArray(e.navigation)||e.linkCards!==void 0&&!Array.isArray(e.linkCards))}function zt(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 Bt(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 Vt(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:Bt(e.mode,e.size,t)}}function Ht(){return typeof window>`u`?0:window.innerWidth}function Ut(e){return{headers(){let t={};return e.aiAgentDeploymentId&&(t[`x-ai-agent-deployment-id`]=e.aiAgentDeploymentId),e.publicKey&&(t[e.publicKeyHeader??`x-public-key`]=e.publicKey),t}}}function Wt(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()}})}var Gt=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.status=n,this.cause=r,this.name=`StreamError`}};const Kt=L.scope(`parser`);async function*qt(e,t,n){if(!e.ok){let t=await e.text().catch(()=>``);throw new Gt(`server responded ${e.status}: ${t.slice(0,200)}`,`server`,e.status)}for await(let r of Jt(e,t)){let e=Yt(r,n);if(e===`done`)return;e&&(yield e)}}async function*Jt(e,t){if(!e.body)throw new Gt(`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(`
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`),ht=L.scope(`mount`),gt=new WeakMap,_t={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 vt(e,t){e.style.cssText=_t[t]}function yt(e){return e===`floating`||e===`modal`||e===`drawer`?`floating`:e===`standalone`||e===`page`?`viewport`:`flow`}function bt(e={}){let t=e.position??`flow`;ht.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=_t[t];let i=r.shadowRoot??r.attachShadow({mode:`open`}),a=r.ownerDocument;if(!xt(i,a)){let e=a.createElement(`style`);e.textContent=mt,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 xt(e,t){if(!(`adoptedStyleSheets`in e))return!1;let n=t.defaultView;if(!n||typeof n.CSSStyleSheet!=`function`)return!1;let r=gt.get(t);if(!r)try{r=new n.CSSStyleSheet,r.replaceSync(mt),gt.set(t,r)}catch{return!1}try{return e.adoptedStyleSheets=[r],!0}catch{return!1}}function St(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 Ct(e,t){e.dataset.theme=t}function wt(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 Tt(e,t){e.dataset.position=t}function Et(e,t){e.dataset.mode=t}function Dt(e,t){Ct(e,t.themeMode),St(e,t.themeOverrides),Tt(e,t.position),wt(e,t.size)}const Ot=L.scope(`iframe`);function kt(e,t,n=`closed`,r=`floating`,i=null){Ot.debug(`createIframeMount`,{position:t,initialMode:n,layoutMode:r,hasTarget:!!i});let a=document.createElement(`iframe`);a.title=`${b.name} chat`,a.setAttribute(`allow`,`microphone; clipboard-write`),Mt(a,t,n,r),(r===`inline`&&i?i:document.body).appendChild(a);let o=a.contentDocument;if(!o)throw Error(`iframe contentDocument unavailable (cross-origin?)`);o.open(),o.write(`<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style></head><body></body></html>`),o.close();let s=bt({...e,target:o.body}),c=new MutationObserver(()=>{Mt(a,t,s.hostElement.dataset.mode??`closed`,r)});return c.observe(s.hostElement,{attributes:!0,attributeFilter:[`data-mode`]}),{...s,iframeElement:a,destroy(){c.disconnect(),s.destroy(),a.remove()}}}const At=`border:0;background:transparent;z-index:2147483647;pointer-events:auto;`,jt={closed:{w:`88px`,h:`88px`},expanded:{w:`min(calc(100vw - 32px), 680px)`,h:`min(calc(100vh - 32px), 860px)`},open:{w:`min(calc(100vw - 32px), 440px)`,h:`min(calc(100vh - 32px), 700px)`}};function Mt(e,t,n,r){if(n===`fullscreen`||r===`standalone`){e.style.cssText=`${At}position:fixed;inset:0;width:100vw;height:100vh;`;return}if(r===`inline`){e.style.cssText=`${At}position:static;display:block;width:100%;height:100%;`;return}if(typeof matchMedia==`function`&&matchMedia(`(max-width: 640px)`).matches&&(n===`open`||n===`expanded`)){e.style.cssText=`${At}position:fixed;inset:0;width:100vw;height:100vh;`;return}let i=t.startsWith(`top-`)?`top`:`bottom`,a=t.endsWith(`-left`)?`left`:`right`,{w:o,h:s}=jt[n]??jt.open;e.style.cssText=`${At}position:fixed;${i}:16px;${a}:16px;width:${o};height:${s};`}function Nt(e){"@babel/helpers - typeof";return Nt=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},Nt(e)}function Pt(e,t){if(Nt(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Nt(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ft(e){var t=Pt(e,`string`);return Nt(t)==`symbol`?t:t+``}function V(e,t,n){return(t=Ft(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var It=class{constructor(){V(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()}};function Lt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Rt(e){return Lt(e)}function zt(e){return!(!Lt(e)||e.navigation!==void 0&&!Array.isArray(e.navigation)||e.linkCards!==void 0&&!Array.isArray(e.linkCards))}function Bt(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 Vt(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 Ht(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:Vt(e.mode,e.size,t)}}function Ut(){return typeof window>`u`?0:window.innerWidth}function Wt(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 Gt(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()}})}var Kt=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.status=n,this.cause=r,this.name=`StreamError`}};const qt=L.scope(`parser`);async function*Jt(e,t,n){if(!e.ok){let t=await e.text().catch(()=>``);throw new Kt(`server responded ${e.status}: ${t.slice(0,200)}`,`server`,e.status)}for await(let r of Yt(e,t)){let e=Xt(r,n);if(e===`done`)return;e&&(yield e)}}async function*Yt(e,t){if(!e.body)throw new Kt(`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
- `))!==-1;){let e=r.slice(0,a);r=r.slice(a+2),yield e}}}finally{n.releaseLock()}}function Yt(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 Kt.trace(`chunk`,{type:e.type,eventId:r}),{chunk:e,eventId:r}}catch(e){throw Kt.trace(`frame parse failed`,{err:e,payload:n.slice(0,200)}),new Gt(`invalid SSE frame`,`network`,void 0,e)}}function Xt(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 Zt=e=>e&&Object.keys(e).length>0?e:void 0;function Qt(e,t){let n=Zt(e),r=Zt(t);if(!n&&!r)return;let i={};return n&&(i.user=n),r&&(i.page=r),Xt(JSON.stringify(i))}function $t(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function H(e){return`tool-${e.startsWith(`tool:`)?e.slice(5):e}`}function en(e){return e.startsWith(`tool-`)?e.slice(5):e}const tn={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 nn(e){let t=e??{},n=t.controlMode;return{controlMode:n===`awaiting_operator`||n===`operator`?n:`ai-agent`,controlRevision:typeof t.controlRevision==`number`&&Number.isSafeInteger(t.controlRevision)&&t.controlRevision>=0?t.controlRevision:void 0,assignedOperatorInitials:typeof t.assignedOperatorInitials==`string`&&t.assignedOperatorInitials?t.assignedOperatorInitials:void 0,operatorAvailable:typeof t.operatorAvailable==`boolean`?t.operatorAvailable:void 0}}function rn(e){let t=e?.suggestions;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)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 an(e){let t={messages:e.messages.map(e=>({id:e.serverMessageId??e.id,parts:sn(e),role:e.role,createdAt:e.createdAt===void 0?void 0:new Date(e.createdAt).toISOString()})),conversationId:e.conversationId,responseType:`ack`};return e.visitorId&&(t.visitorId=e.visitorId),e.userPrefs&&(t.userPrefs=e.userPrefs),t}function on(e){return e.state===`output-available`||e.state===`output-error`||e.state===`output-denied`||e.approval?.approved!==void 0}function sn(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`&&on(n)){let e=n.dynamic?{type:`dynamic-tool`,toolName:n.toolName,toolCallId:n.toolCallId,state:n.state}:{type:H(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}const U=L.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,V(this,`map`,new Map)}getOrFetch(e,t){let n=this.map.get(e);if(n&&Date.now()-n.at<this.ttlMs)return n.result;let r={at:Date.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&&Date.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,V(this,`conversationListeners`,new Set),V(this,`conversationRevision`,0),V(this,`visitorId`,void 0),V(this,`conversationId`,void 0),V(this,`userContext`,void 0),V(this,`pageContext`,void 0),V(this,`locale`,void 0),V(this,`conversationsCache`,new vn(1e4)),V(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:x};this.visitorId&&(e.visitorId=this.visitorId),this.conversationId&&(e.conversationId=this.conversationId),this.locale&&(e.locale=this.locale);let t=Qt(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){U.debug(`handshake →`,{visitorId:e.visitorId,conversationId:e.conversationId,locale:e.locale});let t=await this.postJson(tn.handshake,e,`handshake`);return U.debug(`handshake ←`,{visitorId:t.visitorId,conversationId:t.conversationId,hasWelcome:!!t.welcome,hasConfig:!!t.config,rebind:t.rebind}),Sn(t)||U.warn(`handshake response did not match expected shape; using raw response`,{response:t}),this.visitorId=t.visitorId??e.visitorId,this.conversationId=t.conversationId,t}async uploadFile(e,t){U.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 U.debug(`uploadFile ←`,{id:r.id,url:r.url}),r}async transcribe(e,t=`audio/webm`){U.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 U.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(tn.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}={}){let r=new URL(this.url(tn.listMessages));r.searchParams.set(`conversationId`,e),r.searchParams.set(`limit`,`50`),r.searchParams.set(`sortBy`,`_id`),r.searchParams.set(`sortOrder`,`desc`),t.length>0&&r.searchParams.set(`ids`,t.join(`,`)),n&&r.searchParams.set(`beforeId`,n);let i=await this.getJson(r.toString(),`loadConversation`),a=(i.messages??[]).toReversed();return{...i,messages:a,canContinue:i.canContinue??!0}}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(tn.markRead,{conversationId:e},`markRead`,!0)}catch(e){U.debug(`markRead failed (non-fatal)`,{err:e})}}async requestOperator(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(tn.requestOperator,{},`requestOperator`)).controlState}catch(e){U.debug(`requestOperator failed (non-fatal)`,{err:e});return}}async cancelOperatorRequest(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(tn.cancelOperatorRequest,{},`cancelOperatorRequest`)).controlState}catch(e){U.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(tn.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=>j(e,this.locale));return{...n,items:r}}async bootstrap(e){let t=new URL(this.dataUrl(tn.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(tn.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??tn.submitForm}async submitForm(e){U.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){U.debug(`submitForm failed (non-fatal)`,{err:e})}}async submitFeedback(e){U.debug(`submitFeedback →`,{messageId:e.messageId,value:e.value});try{await this.postJson(tn.messageFeedback,{messageId:e.messageId,set:{feedback:e.value}},`submitFeedback`)}catch(e){U.debug(`submitFeedback failed (non-fatal)`,{err:e})}}async sendTurn(e){U.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(tn.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 Gt(`sendTurn failed: expected 202, received ${n.status}`,`server`,n.status);let r;try{r=await n.json()}catch(e){throw t?.aborted?e:new Gt(`sendTurn failed: invalid acknowledgement`,`server`,n.status,e)}if(!xn(r))throw new Gt(`sendTurn failed: invalid acknowledgement`,`server`,n.status);return r},void 0,3e4)}catch(e){throw e instanceof Gt?e:new Gt(`sendTurn failed: network error`,`network`,void 0,e)}}cancelTurn(e,t){!this.visitorId||!e||!t||(U.debug(`cancel stream`,{conversationId:e,runId:t,visitorId:this.visitorId}),this.fetchImpl(this.url(tn.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=>U.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||U.debug(`resume-stream fetch failed — reconnecting`,{err:t}),`held`}if(!a.ok)return i(),a.status===409||mn.has(a.status)?(U.debug(`resume-stream → transient response; reconnecting`,{status:a.status}),`held`):(U.debug(`resume-stream → endpoint unavailable`,{status:a.status}),`unavailable`);if(!a.body)return i(),U.debug(`resume-stream → bodyless response; stopping`,{status:a.status}),`unavailable`;if(!(a.headers.get(`content-type`)??``).includes(`text/event-stream`))return i(),U.debug(`resume-stream → non-SSE response; stopping`),`unavailable`;let o=!1;try{for await(let{chunk:n}of qt(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`;U.debug(`resume-stream segment dropped — reconnecting`,{err:t})}finally{i()}return`held`}resumeUrl(){return this.withEnvelopeQuery(tn.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 Gt(`${t} failed: network error`,`network`,void 0,e);U.debug(`request network error — retrying`,{label:t,attempt:n}),await Wt(hn(n));continue}if(a.ok||!mn.has(a.status)||n>=3)return a;let o=_n(a.headers)??hn(n);U.debug(`request retryable status — retrying`,{label:t,status:a.status,attempt:n,wait:o}),await Wt(o)}}async assertOk(e,t){if(!e.ok)throw new Gt(`${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){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.visitorId==`string`&&typeof t.conversationId==`string`}function Cn(e,t){let n=e?[{kind:`text`,id:`t0`,textSig:f(e),doneSig:f(!0)}]:[];return{id:ct(),role:`user`,createdAt:Date.now(),status:`complete`,attachments:t,partsSig:f(n)}}function wn(){return{id:ct(),role:`assistant`,createdAt:Date.now(),status:`streaming`,partsSig:f([])}}function Tn(e){let t=ct();return En({id:t,role:e.role,createdAt:Date.now(),status:`complete`,ephemeral:!0,parts:[{kind:`text`,id:`${t}-t0`,text:e.text,done:!0}]})}function En(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(cr))}}const Dn=new Set([`completed`,`failed`,`canceled`]);function On(e){return e.status===`failed`?`error`:e.role===`assistant`&&e.status!=null&&!Dn.has(e.status)?`streaming`:`complete`}function kn(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:en(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`?rn(r.data):void 0,serverMessageId:e.id,createdAt:$t(e.createdAt)??Date.now(),status:On(e),canceled:e.status===`canceled`,feedback:e.feedback??null,partsSig:f(n)}}function An(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 jn(e){return e.role===`assistant`&&e.status!=null&&!Dn.has(e.status)&&An(e)}function Mn(e){let t=e.length-1;return e.filter((e,n)=>n===t||!jn(e)).map(kn)}function Nn(e,t){let n=!t&&e.at(-1)?.role===`assistant`?-2:-1,r=e.at(n);return!r||r.ephemeral?[]:[r]}function Pn(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(lr)}}function W(e){let t=``;for(let n of e.partsSig.value)n.kind===`text`&&(t+=n.textSig.value);return t}function Fn(e,t,n,r,i,a=t.createdAt){let o=e.find(e=>e.role===`user`&&!e.ephemeral),s=(e,t)=>W(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 In(e){return W(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`||e.kind===`source`)}function Ln(e){return W(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`)}function Rn(e){return e===`approval-responded`||e===`output-available`||e===`output-denied`||e===`output-error`}const zn=e=>e.kind===`tool`,Bn=e=>e.kind===`text`&&e.textSig.value.trim()!==``||e.kind===`file`;function Vn(e){let t=e.partsSig.value,n=t.findLastIndex(e=>e.kind===`tool`);return t.slice(n+1).some(Bn)}function Hn(e){if(e.role!==`assistant`)return!1;let t=e.partsSig.value.filter(zn);return t.length>0&&t.every(e=>Rn(e.stateSig.value))}function Un(e){return e.role===`assistant`&&e.partsSig.value.some(e=>e.kind===`tool`)&&!Vn(e)}function Wn(e,t){return!e.partsSig.value.slice(t+1).some(e=>e.kind===`step-start`||Bn(e))}function Gn(e){return e.partsSig.value.some(e=>zn(e)&&!Rn(e.stateSig.value))}function Kn(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 qn(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 Jn(e,t,n,r){if(!Yn(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&&W(n).length>=W(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&&W(t).length>=W(e).length)}function Yn(e){return e?.role===`assistant`&&e.status===`streaming`&&e.serverMessageId===void 0}function Xn(e,t){let n=new Map(t.partsSig.value.filter(zn).filter(e=>Rn(e.stateSig.value)).map(e=>[e.toolCallId,e]));if(n.size===0)return;let r=!1,i=e.partsSig.value.map(e=>{if(!zn(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 Zn(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||In(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`)?qn(t,e):t.status===`streaming`||W(t).length>=W(e).length?(Xn(t,e),t.suggestions??(t.suggestions=e.suggestions),t.feedback===void 0&&(t.feedback=e.feedback),e.canceled&&(t.canceled=!0),t):qn(t,e):e)}),s=n.filter(e=>!i.has(e)),c=s.findLast(Yn),l=new Map;e.forEach((e,t)=>{l.set(e.id,t),e.serverMessageId!==void 0&&l.set(e.serverMessageId,t)});let u=Jn(c,c?n.slice(0,n.indexOf(c)):[],a,l);if(c&&u){let e=o.indexOf(u);e>=0&&(o[e]=qn(c,u)),s=s.filter(e=>e!==c)}return[...o,...s]}function Qn(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,qn(e,t);if(e.serverMessageId===void 0)return e;let r=W(t),i=W(e),o=t.status!==`streaming`&&r.length>=i.length&&rr(e,t);if(r.length>i.length||r===i&&t.partsSig.value.length>e.partsSig.value.length||o)return a=!0,qn(e,t);if(e.status===`streaming`&&t.status!==`streaming`&&er(e,t)){if(e.continuationStreaming&&Gn(t))return e;if(!rr(t,e))return a=!0,qn(e,t)}return e}),s=[...n.values()].filter(e=>!i.has(e.serverMessageId)),c=o.findLastIndex(Yn),l=o[c],u=Jn(l,o.slice(0,c),s,r);if(l!==void 0&&u!==void 0&&W(u).length>=W(l).length&&(qn(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 $n(e,t){if(e.role!==t.role)return!1;let n=W(t),r=W(e);return n.length>r.length||t.partsSig.value.length>e.partsSig.value.length||rr(e,t)}function er(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&&tr(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 tr(e,t){return(e.startsWith(`tool:`)?e.slice(5):e)===(t.startsWith(`tool:`)?t.slice(5):t)}const nr={"input-streaming":0,"input-available":1,"approval-requested":2,"approval-responded":3,"output-available":4,"output-denied":4,"output-error":4};function rr(e,t){let n=new Map(e.partsSig.value.filter(zn).map(e=>[e.toolCallId,e]));return t.partsSig.value.filter(zn).some(e=>{let t=n.get(e.toolCallId);if(!t||nr[e.stateSig.value]>nr[t.stateSig.value])return!0;let r=e.approvalSig.value?.approved;return r!==void 0&&r!==t.approvalSig.value?.approved})}function ir(e){return e.role===`assistant`&&e.status!==`streaming`&&!In(e)}function ar(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`&&!ir(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 or(e){return e.canceled===!0&&e.role===`assistant`&&e.status!==`streaming`&&!Ln(e)}function sr(e,t){return e.operatorRoutedTurn?ir(e)?`drop`:`complete-operator-routed`:t||ir(e)?`error`:`complete`}function cr(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 lr(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 ur=L.scope(`feedback:audio`);var dr=class{constructor(){V(this,`ctx`,null),V(this,`master`,null),V(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){ur.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=>(ur.warn(`audio fetch/decode failed`,{url:e,err:t}),this.buffers.delete(e),null));return this.buffers.set(e,r),r}};const fr={messageReceived:10,messageSent:0,error:[20,40,20],voiceStart:10,voiceStop:0},pr={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 mr=null,hr=0;function gr(){return typeof navigator<`u`&&typeof navigator.vibrate==`function`}function _r(){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 vr(e){if(!(e===0||Array.isArray(e)&&e.every(e=>e===0))){if(gr())try{navigator.vibrate(e);return}catch{}if(mr||(mr=_r()),mr)try{mr.label.click()}catch{}}}function yr(){hr++;let e=!1;return()=>{e||(e=!0,hr=Math.max(0,hr-1),hr===0&&mr&&(mr.input.remove(),mr.label.remove(),mr=null))}}const br=L.scope(`feedback`);var xr=class{constructor(e,t){V(this,`mutedSig`,f(!1)),V(this,`audio`,new dr),V(this,`releaseHaptics`,void 0),V(this,`sound`,void 0),V(this,`haptics`,void 0),V(this,`lastPlayed`,new Map),V(this,`reducedMotionMq`,null),this.sound=e,this.haptics=t,this.releaseHaptics=yr(),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=>br.warn(`audio play failed`,{err:e,url:t}));return}let n=pr[e];n&&this.audio.playTone(n)}playHaptic(e){if(this.reducedMotionMq?.matches)return;let t=this.haptics.events?.[e];t!==!1&&vr(t===!0||t===void 0?fr[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`},Sr=`${b.cssPrefix}-icon-dir`,Cr=()=>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`})}),wr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M18 6 6 18M6 6l12 12`})}),Tr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 5v14M5 12h14`})}),Er=()=>_(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:[g(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),g(`path`,{d:`M22 2 11 13`})]}),Dr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 19V5M5 12l7-7 7 7`})}),Or=()=>g(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:g(`path`,{d:`M3 20V4l18 8-18 8Z`})}),kr=()=>g(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:g(`path`,{d:`m9 18 6-6-6-6`})}),Ar=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})}),jr=()=>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`})}),Mr=()=>_(`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`})]}),Nr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 8V3h5M21 8V3h-5M3 16v5h5M21 16v5h-5`})}),Pr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M8 3v5H3M16 3v5h5M8 21v-5H3M16 21v-5h5`})}),Fr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 3h7v2H5v5H3zM21 3h-7v2h5v5h2zM3 21h7v-2H5v-5H3zM21 21h-7v-2h5v-5h2z`})}),Ir=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M10 3v5H3M14 3v5h7M10 21v-5H3M14 21v-5h7`})}),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:Sr,"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:Sr,"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:Cr,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`,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:O(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:O(n,e.text)}),g(`button`,{type:`button`,class:`${wi}-callout-close`,onClick:a,"aria-label":r,title:r,"data-testid":q.calloutDismiss,children:g(wr,{})})]}):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`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=O(t,e.name),i=e.title?O(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=L.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(wr,{})})]})}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 oa=b.cssPrefix,sa=L.scope(`composer`);function ca(e){return e.reduce((e,t)=>e+t.size,0)}const la={arrowUp:Dr,paperPlane:Er,send:Or,chevron:kr};function ua(e){return`activeElement`in e}function da(e){return`host`in e&&`activeElement`in e}function fa({options:e,transport:t,feedback:n,bus:a,persistence:o,conversationId:l,isStreaming:u,active:d=!0,isPreparing:f=!1,operatorRequestEnabled:p,canRequestOperator:m=!1,controlMode:h,onRequestOperator:v,onSend:y,onStop:b,attachApiRef:x}){let S=e.strings,[C,w]=c(()=>o.loadDraft(l)),[T,E]=c([]),[D,O]=c(!1),[k,A]=c(!1),j=s(!1),M=s(null),ee=s(null),te=s(null),N=s(0),ne=s(l);ne.current=l;let re=s(d);re.current=d;let ie=s(f);ie.current=f;let P=k||f||!d,ae=r(e=>{w(t=>{let n=typeof e==`function`?e(t):e;return n===t?t:(o.saveDraft(ne.current,n),n)})},[o]),oe=e.features.fileUpload,F=e.features.voice,[I,se]=c(()=>ea(F,e.locale,(e,n)=>t.transcribe(e,n))),ce=s(I);ce.current=I;let L=s({mode:F,locale:e.locale,transport:t});i(()=>{let n=L.current;(n.mode!==F||n.locale!==e.locale||n.transport!==t)&&(L.current={mode:F,locale:e.locale,transport:t},N.current++,ce.current.cancel(),te.current=null,O(!1),se(ea(F,e.locale,(e,n)=>t.transcribe(e,n))))},[e.locale,F,t]),i(()=>()=>{N.current++,I.cancel()},[I]);let le=r(e=>{let t=te.current;if(t===null)return!1;let n=Date.now()-t;return sa[e](`voiceStop`,{durationMs:n}),a.emit(`voiceStop`,{durationMs:n}),te.current=null,!0},[a]),R=r(()=>{te.current!==null&&(I.stop(),O(!1),le(`info`)&&n.play(`voiceStop`))},[le,n,I]),ue=r(()=>{N.current++,I.cancel(),O(!1),le(`info`)&&n.play(`voiceStop`)},[le,n,I]);i(()=>{(f||!d)&&ue()},[d,ue,f]),i(()=>{let e=M.current;if(!e)return;let t=e.getRootNode(),n=ua(t)?t.activeElement:null;n&&e.closest(`.${oa}-panel`)?.contains(n)||e.focus({preventScroll:!0})},[]),i(()=>{let e=M.current;if(!e)return;if(C.length===0){e.style.height=``;return}e.style.height=`auto`;let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--${oa}-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`},[C]);let z=s(T);z.current=T,i(()=>()=>z.current.forEach(Wi),[]),i(()=>{if(x)return x.current={attachFromDrop:t=>{if(!oe||!re.current||j.current||ie.current)return;let n=Ui(t,z.current,e.attachments);n.accepted.length!==0&&(sa.info(`attach (drop)`,{count:n.accepted.length,totalBytes:ca(n.accepted)}),a.emit(`attach`,{count:n.accepted.length,totalBytes:ca(n.accepted)}),E(e=>[...e,...n.accepted]))},fill:e=>{if(!re.current||j.current||ie.current)return;ae(e);let t=M.current;t&&(t.focus({preventScroll:!0}),requestAnimationFrame(()=>t.setSelectionRange(t.value.length,t.value.length)))}},()=>{x.current&&(x.current=null)}},[x,oe,f,e.attachments,ae]),i(()=>{let t=M.current;if(!t)return;let n=t.closest(`.${oa}-panel`);if(!n)return;let r=n=>{if(!re.current||j.current||ie.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(oe){let t=Ui(r.items,z.current,e.attachments);if(t.accepted.length>0){n.preventDefault(),sa.info(`attach (paste)`,{count:t.accepted.length,totalBytes:ca(t.accepted)}),a.emit(`attach`,{count:t.accepted.length,totalBytes:ca(t.accepted)}),E(e=>[...e,...t.accepted]);return}}if(i===t)return;let o=r.getData(`text/plain`);o&&(n.preventDefault(),ae(e=>e+o),t.focus())};return n.addEventListener(`paste`,r),()=>n.removeEventListener(`paste`,r)},[oe,e.attachments,ae]);let de=async()=>{let e=C.trim();if(!e&&T.length===0||!d||u||j.current||f)return;ue(),j.current=!0,A(!0);let t=C,n=T;try{await y(e,n)&&(ae(e=>e===t?``:e),E(e=>e===n?(n.forEach(Wi),z.current=[],[]):e))}finally{j.current=!1,A(!1),requestAnimationFrame(()=>{let e=M.current;if(!e||e.disabled||!re.current)return;let t=e.getRootNode(),n=ua(t)?t.activeElement:null,r=n?.getAttribute(`data-testid`);if(!(n&&n!==e&&r!==q.composerSend&&r!==q.composerStop)){if(da(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})}})}},fe=e=>{e.key!==`Enter`||e.shiftKey||e.isComposing||(e.preventDefault(),u?b():de())},pe=t=>{let n=t.target;if(!d||j.current||f){n.value=``;return}let r=Ui(n.files,T,e.attachments);r.accepted.length>0&&(sa.info(`attach (file picker)`,{count:r.accepted.length,totalBytes:ca(r.accepted)}),a.emit(`attach`,{count:r.accepted.length,totalBytes:ca(r.accepted)}),E(e=>[...e,...r.accepted])),n.value=``},me=e=>{!d||j.current||f||(sa.info(`removeAttachment`,{id:e}),a.emit(`removeAttachment`,{id:e}),E(t=>{let n=t.find(t=>t.id===e);return n&&Wi(n),t.filter(t=>t.id!==e)}))},he=()=>{if(D){R();return}if(!d||!I.isSupported||j.current||f)return;let e=++N.current;te.current=Date.now(),sa.info(`voiceStart`),a.emit(`voiceStart`,void 0),O(!0),n.play(`voiceStart`),I.start((t,n)=>{N.current!==e||!re.current||ie.current||j.current||!n||ae(e=>`${e}${t} `)},()=>{N.current!==e||!re.current||(O(!1),le(`debug`))})},ge=la[e.composer.sendButton.icon];return _(`div`,{class:`${oa}-composer`,"data-testid":q.composer,children:[T.length>0?g(`div`,{class:`${oa}-attachments`,children:T.map(e=>g(Qi,{attachment:e,onRemove:()=>me(e.id),disabled:P},e.id))}):null,_(`div`,{class:`${oa}-composer-row`,children:[_(`div`,{class:`${oa}-composer-actions`,children:[oe?g(`button`,{type:`button`,class:`${oa}-icon-btn`,onClick:()=>ee.current?.click(),disabled:P,"aria-label":S.attach,"data-testid":q.composerAttach,children:g(jr,{})}):null,I.isSupported?g(`button`,{type:`button`,class:`${oa}-icon-btn`,onClick:he,disabled:P,"aria-label":D?S.micStop:S.micStart,"aria-pressed":D,"data-recording":D?`true`:void 0,"data-testid":q.composerVoice,children:g(Mr,{})}):null]}),g(`textarea`,{ref:M,name:`message`,class:`${oa}-textarea`,rows:1,value:C,placeholder:S.composerPlaceholder,onInput:e=>ae(e.currentTarget.value),onKeyDown:fe,disabled:P,"aria-label":S.composerPlaceholder,"data-testid":q.composerInput}),u?g(`button`,{type:`button`,class:`${oa}-send`,onClick:b,disabled:P,"aria-label":S.stop,"data-testid":q.composerStop,children:g(Ar,{})}):g(`button`,{type:`button`,class:`${oa}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:()=>void de(),disabled:P||!C.trim()&&T.length===0,"aria-label":S.send,"data-testid":q.composerSend,children:g(ge,{})}),p&&h===`ai-agent`&&v?g(`button`,{type:`button`,class:`${oa}-icon-btn`,onClick:v,disabled:P||!m,"aria-label":S.talkToOperator,title:S.talkToOperator,"data-testid":q.operatorRequest,children:g(ti,{})}):null]}),g(`input`,{ref:ee,name:`attachments`,type:`file`,multiple:!0,accept:e.attachments.accept,onChange:pe,disabled:P,class:`${oa}-sr-only`,"data-testid":q.composerFileInput})]})}const pa=b.cssPrefix;function ma({visible:e,strings:t}){return e?g(`div`,{class:`${pa}-dropzone`,role:`status`,"aria-live":`polite`,children:t.dropZone}):null}function ha({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 ga({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 _a({items:e,triggerLabel:t}){let n=b.cssPrefix,r=ga({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 va=b.cssPrefix;function ya(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 ba={normal:`large`,large:`small`,small:`normal`};function xa(e){return g(e===`light`?ci:e===`dark`?li:ui,{})}function Sa(e){return(e.split(`-`)[0]??e).toUpperCase()}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?Pr:Nr,{}),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?Ir:Fr,{}),label:e?h.exitFullscreen:h.fullscreen,type:`switch`,on:e,onSelect:c})}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:xa(T),label:`${h.theme}: ${E[T]}`,onSelect:()=>f(ya(T)),keepOpen:!0}),S(`textSize`)&&k.push({id:`textSize`,icon:g(Vr,{}),label:`${h.textSize}: ${O[D]}`,onSelect:()=>m(ba[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:Sa(e),lang:e})),value:n.locale,onSelectValue:d});let A=!!a&&Ii(v,r,n.actions),j=y&&S(`history`);return _(`div`,{class:`${va}-header-actions`,children:[j?g(`button`,{type:`button`,class:`${va}-icon-btn`,onClick:u,"aria-label":h.history,title:h.history,"data-testid":q.actionHistory,children:g(Wr,{})}):null,k.length>0?g(_a,{items:k,triggerLabel:h.moreActions}):null,A?g(`button`,{type:`button`,class:`${va}-icon-btn`,onClick:a,"aria-label":h.close,title:h.close,"data-testid":q.actionClose,children:g(wr,{})}):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 J=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:`${J}-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:`${J}-form-actions`,children:[o?g(`span`,{class:`${J}-form-hint`,children:o}):null,i&&a?g(`button`,{type:`button`,class:`${J}-form-skip`,onClick:a,disabled:l,"data-testid":h,children:i}):null,g(`button`,{type:`submit`,class:`${J}-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:`${J}-field`,"data-field":e.name,"data-invalid":r?`true`:void 0,children:[_(`span`,{class:`${J}-field-head`,children:[_(`span`,{class:`${J}-field-label`,children:[e.label,e.required??!0?g(`span`,{class:`${J}-field-req`,"aria-hidden":`true`,children:` *`}):null]}),a?g(`span`,{class:`${J}-field-type`,children:a}):null]}),l,e.validationHint&&!r?g(`span`,{class:`${J}-field-hint`,children:e.validationHint}):null,r?g(`span`,{class:`${J}-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:`${J}-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:`${J}-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:`${J}-field-choices`,role:`radiogroup`,"data-testid":c,children:[(t.options??[]).map(e=>_(`label`,{class:`${J}-choice`,children:[g(`input`,{type:`radio`,name:`${J}-${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:`${J}-choice`,children:[g(`input`,{type:`radio`,name:`${J}-${t.name}`,checked:l===Ma,disabled:i,onChange:()=>o(Ma)}),g(`span`,{children:a.formOther})]}):null,e?g(`input`,{class:`${J}-field-input`,value:r,placeholder:t.placeholder??a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.target.value)}):null]})}case`checkbox`:return _(`label`,{class:`${J}-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:`${J}-field-choices`,"data-testid":c,children:[(t.options??[]).map(t=>_(`label`,{class:`${J}-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:`${J}-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:`${J}-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(kr,{})]}),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?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 Y=b.cssPrefix,To={text:`qtypeText`,email:`qtypeEmail`,phone:`qtypePhone`,number:`qtypeNumber`,date:`qtypeDate`,"single-select":`qtypeChooseOne`,"multi-select":`qtypeChooseAny`,boolean:`qtypeBoolean`};function Eo(e,t){let n={};for(let r of e)n[r.key]=t[To[r.type]];return n}function Do({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?Cr:Qr,k=y?t.inputRequired:t.inputBadge,A=v?g(`p`,{class:`${Y}-toolui-subtle`,children:t.approvalSubmitting}):y?g(Oo,{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:Eo(S,t),initialValues:h?Po(S,d?.reason):void 0}):g(ko,{questions:S,answers:h?No(d?.reason):{},strings:t}),j=`completed`,M=t.inputAnswered;return b?(j=`superseded`,M=t.inputSkipped):v&&(j=`responded`,M=t.statusResponded),_(`details`,{class:`${Y}-toolui ${Y}-toolui-collapsible${r?` ${Y}-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:`${Y}-toolui-head`,children:[_(`span`,{class:`${Y}-toolui-q-pill`,children:[g(O,{}),k]}),_(`span`,{class:`${Y}-toolui-head-end`,children:[y?null:g(Ka,{status:j,icon:g(b?xi:bi,{}),label:M}),g(`span`,{class:`${Y}-toolui-chevron`,children:g(Jr,{})})]})]}),_(`div`,{class:`${Y}-toolui-collapse-body`,children:[f.intro?g(`div`,{class:`${Y}-toolui-desc`,children:f.intro}):null,A,y||v?null:_(`div`,{class:`${Y}-toolui-footer`,children:[_(`button`,{type:`button`,class:`${Y}-toolui-options-toggle`,onClick:()=>D(e=>!e),"data-testid":q.toolAskOptions,children:[g(`span`,{class:`${Y}-toolui-options-chevron${E?` ${Y}-open`:``}`,children:g(Jr,{})}),E?t.hideOptions:t.showOptions]}),x?g(`button`,{type:`button`,class:`${Y}-form-skip`,onClick:()=>s(e.toolCallId),"data-testid":q.toolEdit,children:t.edit}):null]})]})]})}function Oo({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(jo(e.questions,t),!0),skipLabel:t.inputSkip,onSkip:()=>r(void 0,!1),submitOnEnter:a,fieldTypeLabels:Eo(e.questions,t),submitTestId:q.toolInputSubmit,skipTestId:q.toolInputSkip})}function ko({questions:e,answers:t,strings:n}){return g(`div`,{class:`${Y}-toolui-summary`,"data-testid":q.toolAskSummary,children:e.map(e=>_(`div`,{class:`${Y}-field`,children:[g(`span`,{class:`${Y}-field-head`,children:_(`span`,{class:`${Y}-field-label`,children:[e.question,e.required?g(`span`,{class:`${Y}-field-req`,"aria-hidden":`true`,children:` *`}):null]})}),g(`p`,{class:`${Y}-toolui-answer`,children:Ao(e,t[e.key],n)||`—`})]},e.key))})}function Ao(e,t,n){return e.type===`boolean`?t===`yes`?n.confirmYes:t===`no`?n.confirmNo:t??``:t??``}function jo(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 Mo(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 No(e){let t=Mo(e),n={};for(let[e,r]of Object.entries(t))n[e]=Array.isArray(r)?r.join(`, `):r;return n}function Po(e,t){let n=Mo(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 Fo({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 X=b.cssPrefix,Io=v(Lo);function Lo({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(()=>ir(e)),[e]),y=o(()=>u(()=>or(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=zo(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(`
9
+ `))!==-1;){let e=r.slice(0,a);r=r.slice(a+2),yield e}}}finally{n.releaseLock()}}function Xt(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 qt.trace(`chunk`,{type:e.type,eventId:r}),{chunk:e,eventId:r}}catch(e){throw qt.trace(`frame parse failed`,{err:e,payload:n.slice(0,200)}),new Kt(`invalid SSE frame`,`network`,void 0,e)}}function Zt(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 $t(e,t){let n=Qt(e),r=Qt(t);if(!n&&!r)return;let i={};return n&&(i.user=n),r&&(i.page=r),Zt(JSON.stringify(i))}function en(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function H(e){return`tool-${e.startsWith(`tool:`)?e.slice(5):e}`}function tn(e){return e.startsWith(`tool-`)?e.slice(5):e}const nn={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 rn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function an(e){if(!rn(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 on(e){let t=rn(e)?e.suggestions:void 0;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!rn(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 sn(e){let t={messages:e.messages.map(e=>({id:e.serverMessageId??e.id,parts:ln(e),role:e.role})),conversationId:e.conversationId,responseType:`ack`};return e.visitorId&&(t.visitorId=e.visitorId),e.userPrefs&&(t.userPrefs=e.userPrefs),t}function cn(e){return e.state===`output-available`||e.state===`output-error`||e.state===`output-denied`||e.approval?.approved!==void 0}function ln(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`&&cn(n)){let e=n.dynamic?{type:`dynamic-tool`,toolName:n.toolName,toolCallId:n.toolCallId,state:n.state}:{type:H(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}const U=L.scope(`transport`),un=new WeakMap;function dn(e){return un.get(e)}function fn(e,t){return un.set(e,t),e}function pn(e){return Math.max(e?.upsertRevision??0,e?.read?.revision??0)}function mn(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 hn(e,t,n=!0){switch(t.type){case`snapshot`:{let n=new Map(e.map(e=>[e.conversationId,e])),r=e.filter(e=>(dn(e)?.activityRevision??0)>t.requestedRevision).toSorted((e,t)=>dn(t).activityRevision-dn(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=dn(r);return(i?.upsertRevision??0)>t.requestedRevision?r:i?.read&&!r.hasUnread&&i.read.lastMessageAt===e.lastMessageAt?fn({...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=dn(r);if(pn(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?fn({...e,hasUnread:!1},o):e):(fn(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?dn(i):void 0;if(pn(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&&mn(i,c)?(fn(i,s),e):(fn(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 gn=new Set([408,425,429,500,502,503,504]);function _n(e){return 400*2**e+Math.floor(Math.random()*250)}function vn(e){return 6e4+Math.ceil(e/1048576)*15e3}function yn(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 bn=class{constructor(e){this.ttlMs=e,V(this,`map`,new Map)}getOrFetch(e,t){let n=this.map.get(e);if(n&&Date.now()-n.at<this.ttlMs)return n.result;let r={at:Date.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&&Date.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)}},xn=class{constructor(e){this.opts=e,V(this,`conversationListeners`,new Set),V(this,`conversationRevision`,0),V(this,`visitorId`,void 0),V(this,`conversationId`,void 0),V(this,`userContext`,void 0),V(this,`pageContext`,void 0),V(this,`locale`,void 0),V(this,`conversationsCache`,new bn(1e4)),V(this,`contentCache`,new bn(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:x};this.visitorId&&(e.visitorId=this.visitorId),this.conversationId&&(e.conversationId=this.conversationId),this.locale&&(e.locale=this.locale);let t=$t(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){U.debug(`handshake →`,{visitorId:e.visitorId,conversationId:e.conversationId,locale:e.locale});let t=await this.postJson(nn.handshake,e,`handshake`);return U.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){U.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,vn(e.size));return U.debug(`uploadFile ←`,{id:r.id,url:r.url}),r}async transcribe(e,t=`audio/webm`){U.debug(`transcribe →`,{size:e.size,mimeType:t});let n=new FormData;n.append(`audio`,e,`voice.${Sn(t)}`),n.append(`mimeType`,t);let r=await this.postForm(this.transcribePath,n,`transcribe`);return U.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=hn(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(nn.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}={}){let r=new URL(this.url(nn.listMessages));r.searchParams.set(`conversationId`,e),r.searchParams.set(`limit`,`50`),r.searchParams.set(`sortBy`,`_id`),r.searchParams.set(`sortOrder`,`desc`),t.length>0&&r.searchParams.set(`ids`,t.join(`,`)),n&&r.searchParams.set(`beforeId`,n);let i=await this.getJson(r.toString(),`loadConversation`);return{...i,messages:i.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=hn(e.conversations,n);return t===e.conversations?e:{...e,conversations:t}});for(let e of this.conversationListeners)e(n);try{await this.postJson(nn.markRead,{conversationId:e},`markRead`,!0)}catch(e){U.debug(`markRead failed (non-fatal)`,{err:e})}}async requestOperator(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(nn.requestOperator,{},`requestOperator`)).controlState}catch(e){U.debug(`requestOperator failed (non-fatal)`,{err:e});return}}async cancelOperatorRequest(){if(!(!this.visitorId||!this.conversationId))try{return(await this.postJson(nn.cancelOperatorRequest,{},`cancelOperatorRequest`)).controlState}catch(e){U.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(nn.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=>j(e,this.locale));return{...n,items:r}}async bootstrap(e){let t=new URL(this.dataUrl(nn.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(nn.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??nn.submitForm}async submitForm(e){U.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){U.debug(`submitForm failed (non-fatal)`,{err:e})}}async submitFeedback(e){U.debug(`submitFeedback →`,{messageId:e.messageId,value:e.value});try{await this.postJson(nn.messageFeedback,{messageId:e.messageId,set:{feedback:e.value}},`submitFeedback`)}catch(e){U.debug(`submitFeedback failed (non-fatal)`,{err:e})}}async sendTurn(e){U.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(nn.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 Kt(`sendTurn failed: expected 202, received ${n.status}`,`server`,n.status);let r;try{r=await n.json()}catch(e){throw t?.aborted?e:new Kt(`sendTurn failed: invalid acknowledgement`,`server`,n.status,e)}if(!Cn(r))throw new Kt(`sendTurn failed: invalid acknowledgement`,`server`,n.status);return r},void 0,3e4)}catch(e){throw e instanceof Kt?e:new Kt(`sendTurn failed: network error`,`network`,void 0,e)}}cancelTurn(e,t){!this.visitorId||!e||!t||(U.debug(`cancel stream`,{conversationId:e,runId:t,visitorId:this.visitorId}),this.fetchImpl(this.url(nn.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=>U.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||U.debug(`resume-stream fetch failed — reconnecting`,{err:t}),`held`}if(!a.ok)return i(),a.status===409||gn.has(a.status)?(U.debug(`resume-stream → transient response; reconnecting`,{status:a.status}),`held`):(U.debug(`resume-stream → endpoint unavailable`,{status:a.status}),`unavailable`);if(!a.body)return i(),U.debug(`resume-stream → bodyless response; stopping`,{status:a.status}),`unavailable`;if(!(a.headers.get(`content-type`)??``).includes(`text/event-stream`))return i(),U.debug(`resume-stream → non-SSE response; stopping`),`unavailable`;let o=!1;try{for await(let{chunk:n}of Jt(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`;U.debug(`resume-stream segment dropped — reconnecting`,{err:t})}finally{i()}return`held`}resumeUrl(){return this.withEnvelopeQuery(nn.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 Kt(`${t} failed: network error`,`network`,void 0,e);U.debug(`request network error — retrying`,{label:t,attempt:n}),await Gt(_n(n));continue}if(a.ok||!gn.has(a.status)||n>=3)return a;let o=yn(a.headers)??_n(n);U.debug(`request retryable status — retrying`,{label:t,status:a.status,attempt:n,wait:o}),await Gt(o)}}async assertOk(e,t){if(!e.ok)throw new Kt(`${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 Sn(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 Cn(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 wn(e,t){let n=e?[{kind:`text`,id:`t0`,textSig:f(e),doneSig:f(!0)}]:[];return{id:ct(),role:`user`,createdAt:Date.now(),status:`complete`,attachments:t,partsSig:f(n)}}function Tn(){return{id:ct(),role:`assistant`,createdAt:Date.now(),status:`streaming`,partsSig:f([])}}function En(e){let t=ct();return Dn({id:t,role:e.role,createdAt:Date.now(),status:`complete`,ephemeral:!0,parts:[{kind:`text`,id:`${t}-t0`,text:e.text,done:!0}]})}function Dn(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(cr))}}function On(e){return e.status===`failed`?`error`:e.role===`assistant`&&e.status===`streaming`?`streaming`:`complete`}function kn(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:tn(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`?on(r.data):void 0,serverMessageId:e.id,createdAt:Date.parse(e.createdAt),status:On(e),canceled:e.status===`canceled`,feedback:e.feedback??null,partsSig:f(n)}}function An(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 jn(e){return e.role===`assistant`&&e.status===`streaming`&&An(e)}function Mn(e){let t=e.length-1;return e.filter((e,n)=>n===t||!jn(e)).map(kn)}function Nn(e,t){let n=!t&&e.at(-1)?.role===`assistant`?-2:-1,r=e.at(n);return!r||r.ephemeral?[]:[r]}function Pn(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(lr)}}function W(e){let t=``;for(let n of e.partsSig.value)n.kind===`text`&&(t+=n.textSig.value);return t}function Fn(e,t,n,r,i,a=t.createdAt){let o=e.find(e=>e.role===`user`&&!e.ephemeral),s=(e,t)=>W(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 In(e){return W(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`||e.kind===`source`)}function Ln(e){return W(e).trim()!==``||e.partsSig.value.some(e=>e.kind===`tool`||e.kind===`file`)}function Rn(e){return e===`approval-responded`||e===`output-available`||e===`output-denied`||e===`output-error`}const zn=e=>e.kind===`tool`,Bn=e=>e.kind===`text`&&e.textSig.value.trim()!==``||e.kind===`file`;function Vn(e){let t=e.partsSig.value,n=t.findLastIndex(e=>e.kind===`tool`);return t.slice(n+1).some(Bn)}function Hn(e){if(e.role!==`assistant`)return!1;let t=e.partsSig.value.filter(zn);return t.length>0&&t.every(e=>Rn(e.stateSig.value))}function Un(e){return e.role===`assistant`&&e.partsSig.value.some(e=>e.kind===`tool`)&&!Vn(e)}function Wn(e,t){return!e.partsSig.value.slice(t+1).some(e=>e.kind===`step-start`||Bn(e))}function Gn(e){return e.partsSig.value.some(e=>zn(e)&&!Rn(e.stateSig.value))}function Kn(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 qn(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 Jn(e,t,n,r){if(!Yn(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&&W(n).length>=W(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&&W(t).length>=W(e).length)}function Yn(e){return e?.role===`assistant`&&e.status===`streaming`&&e.serverMessageId===void 0}function Xn(e,t){let n=new Map(t.partsSig.value.filter(zn).filter(e=>Rn(e.stateSig.value)).map(e=>[e.toolCallId,e]));if(n.size===0)return;let r=!1,i=e.partsSig.value.map(e=>{if(!zn(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 Zn(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||In(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`)?qn(t,e):t.status===`streaming`||W(t).length>=W(e).length?(Xn(t,e),t.suggestions??(t.suggestions=e.suggestions),t.feedback===void 0&&(t.feedback=e.feedback),e.canceled&&(t.canceled=!0),t):qn(t,e):e)}),s=n.filter(e=>!i.has(e)),c=s.findLast(Yn),l=new Map;e.forEach((e,t)=>{l.set(e.id,t),e.serverMessageId!==void 0&&l.set(e.serverMessageId,t)});let u=Jn(c,c?n.slice(0,n.indexOf(c)):[],a,l);if(c&&u){let e=o.indexOf(u);e>=0&&(o[e]=qn(c,u)),s=s.filter(e=>e!==c)}return[...o,...s]}function Qn(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,qn(e,t);if(e.serverMessageId===void 0)return e;let r=W(t),i=W(e),o=t.status!==`streaming`&&r.length>=i.length&&rr(e,t);if(r.length>i.length||r===i&&t.partsSig.value.length>e.partsSig.value.length||o)return a=!0,qn(e,t);if(e.status===`streaming`&&t.status!==`streaming`&&er(e,t)){if(e.continuationStreaming&&Gn(t))return e;if(!rr(t,e))return a=!0,qn(e,t)}return e}),s=[...n.values()].filter(e=>!i.has(e.serverMessageId)),c=o.findLastIndex(Yn),l=o[c],u=Jn(l,o.slice(0,c),s,r);if(l!==void 0&&u!==void 0&&W(u).length>=W(l).length&&(qn(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 $n(e,t){if(e.role!==t.role)return!1;let n=W(t),r=W(e);return n.length>r.length||t.partsSig.value.length>e.partsSig.value.length||rr(e,t)}function er(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&&tr(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 tr(e,t){return(e.startsWith(`tool:`)?e.slice(5):e)===(t.startsWith(`tool:`)?t.slice(5):t)}const nr={"input-streaming":0,"input-available":1,"approval-requested":2,"approval-responded":3,"output-available":4,"output-denied":4,"output-error":4};function rr(e,t){let n=new Map(e.partsSig.value.filter(zn).map(e=>[e.toolCallId,e]));return t.partsSig.value.filter(zn).some(e=>{let t=n.get(e.toolCallId);if(!t||nr[e.stateSig.value]>nr[t.stateSig.value])return!0;let r=e.approvalSig.value?.approved;return r!==void 0&&r!==t.approvalSig.value?.approved})}function ir(e){return e.role===`assistant`&&e.status!==`streaming`&&!In(e)}function ar(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`&&!ir(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 or(e){return e.canceled===!0&&e.role===`assistant`&&e.status!==`streaming`&&!Ln(e)}function sr(e,t){return e.operatorRoutedTurn?ir(e)?`drop`:`complete-operator-routed`:t||ir(e)?`error`:`complete`}function cr(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 lr(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 ur=L.scope(`feedback:audio`);var dr=class{constructor(){V(this,`ctx`,null),V(this,`master`,null),V(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){ur.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=>(ur.warn(`audio fetch/decode failed`,{url:e,err:t}),this.buffers.delete(e),null));return this.buffers.set(e,r),r}};const fr={messageReceived:10,messageSent:0,error:[20,40,20],voiceStart:10,voiceStop:0},pr={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 mr=null,hr=0;function gr(){return typeof navigator<`u`&&typeof navigator.vibrate==`function`}function _r(){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 vr(e){if(!(e===0||Array.isArray(e)&&e.every(e=>e===0))){if(gr())try{navigator.vibrate(e);return}catch{}if(mr||(mr=_r()),mr)try{mr.label.click()}catch{}}}function yr(){hr++;let e=!1;return()=>{e||(e=!0,hr=Math.max(0,hr-1),hr===0&&mr&&(mr.input.remove(),mr.label.remove(),mr=null))}}const br=L.scope(`feedback`);var xr=class{constructor(e,t){V(this,`mutedSig`,f(!1)),V(this,`audio`,new dr),V(this,`releaseHaptics`,void 0),V(this,`sound`,void 0),V(this,`haptics`,void 0),V(this,`lastPlayed`,new Map),V(this,`reducedMotionMq`,null),this.sound=e,this.haptics=t,this.releaseHaptics=yr(),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=>br.warn(`audio play failed`,{err:e,url:t}));return}let n=pr[e];n&&this.audio.playTone(n)}playHaptic(e){if(this.reducedMotionMq?.matches)return;let t=this.haptics.events?.[e];t!==!1&&vr(t===!0||t===void 0?fr[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`},Sr=`${b.cssPrefix}-icon-dir`,Cr=()=>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`})}),wr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M18 6 6 18M6 6l12 12`})}),Tr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 5v14M5 12h14`})}),Er=()=>_(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:[g(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),g(`path`,{d:`M22 2 11 13`})]}),Dr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M12 19V5M5 12l7-7 7 7`})}),Or=()=>g(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:g(`path`,{d:`M3 20V4l18 8-18 8Z`})}),kr=()=>g(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:g(`path`,{d:`m9 18 6-6-6-6`})}),Ar=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})}),jr=()=>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`})}),Mr=()=>_(`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`})]}),Nr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 8V3h5M21 8V3h-5M3 16v5h5M21 16v5h-5`})}),Pr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M8 3v5H3M16 3v5h5M8 21v-5H3M16 21v-5h5`})}),Fr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M3 3h7v2H5v5H3zM21 3h-7v2h5v5h2zM3 21h7v-2H5v-5H3zM21 21h-7v-2h5v-5h2z`})}),Ir=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M10 3v5H3M14 3v5h7M10 21v-5H3M14 21v-5h7`})}),Lr=()=>_(`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`})]}),Rr=()=>g(`svg`,{...G,"aria-hidden":`true`,viewBox:`0 0 10 10`,children:g(`path`,{d:`M9 1L1 9M9 5L5 9M9 9H9`,strokeWidth:`1.5`})}),zr=()=>_(`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`})]}),Br=()=>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`})}),Vr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M11 5 6 9H2v6h4l5 4zM22 9l-6 6M16 9l6 6`})}),Hr=()=>_(`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`})]}),Ur=()=>g(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:g(`path`,{d:`m5 6 6 6-6 6M13 6l6 6-6 6`})}),Wr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`M20 6 9 17l-5-5`})}),Gr=()=>_(`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`})]}),Kr=()=>_(`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`})]}),qr=()=>g(`svg`,{...G,class:Sr,"aria-hidden":`true`,children:g(`path`,{d:`M19 12H5M12 19l-7-7 7-7`})}),Jr=()=>_(`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`})]}),Yr=()=>g(`svg`,{...G,"aria-hidden":`true`,children:g(`path`,{d:`m6 9 6 6 6-6`})}),Xr=()=>_(`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`})]}),Zr=()=>_(`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`})]}),Qr=()=>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`})}),$r=()=>_(`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`})]}),ei=()=>_(`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`})]}),ti=()=>_(`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`})]}),ni=()=>_(`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`})]}),ri=()=>_(`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`})]}),ii=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`11`,cy:`11`,r:`7`}),g(`path`,{d:`m21 21-4.3-4.3`})]}),ai=()=>_(`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`})]}),oi=()=>_(`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`})]}),si=()=>_(`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`})]}),ci=()=>_(`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`})]}),li=()=>_(`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`})]}),ui=()=>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`})}),di=()=>_(`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`})]}),fi=()=>_(`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`})]}),pi=()=>_(`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`})]}),mi=()=>_(`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`})]}),hi=()=>_(`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`})]}),gi=()=>_(`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`})]}),_i=()=>_(`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`})]}),vi=()=>_(`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`})]}),yi=()=>_(`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`})]}),bi=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`M12 7v5l3 2`})]}),xi=()=>_(`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`})]}),Si=()=>_(`svg`,{...G,"aria-hidden":`true`,children:[g(`circle`,{cx:`12`,cy:`12`,r:`9`}),g(`path`,{d:`m15 9-6 6M9 9l6 6`})]}),Ci={chat:Cr,message:Qr,bubbles:ci,spark:Zr,wand:ei,bot:ti,help:$r,lifebuoy:ri,headset:ni,search:fi,sparkles:pi,concierge:mi,wave:hi},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`,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 wi(e,t){return`${e}-${t}`}const Ti=b.cssPrefix;function Ei({onToggle:e,launcher:t,strings:n,leaving:r,edgeTab:i}){let a=t.variant!==`circle`&&!!t.label;return _(`button`,{type:`button`,class:`${Ti}-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:[Di(t.icon),a?g(`span`,{class:`${Ti}-fab-label`,children:O(n,t.label??``)}):null]})}function Di(e){let t=Ci[e];return t?g(t,{}):g(Oi,{source:e})}function Oi({source:e}){return g(`span`,{ref:t=>{t&&ki(t,e)},"aria-hidden":`true`})}function ki(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 Ai({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:`${Ti}-callout`,role:`status`,"data-shape":e.shape,"data-position":ji(e.position,t),"data-animated":e.animated?`true`:void 0,"data-testid":q.callout,children:[g(`span`,{children:O(n,e.text)}),g(`button`,{type:`button`,class:`${Ti}-callout-close`,onClick:a,"aria-label":r,title:r,"data-testid":q.calloutDismiss,children:g(wr,{})})]}):null}function ji(e,t){let n=t.endsWith(`-right`),r=t.startsWith(`bottom-`);return e===`vertical`?r?`top`:`bottom`:n?`left`:`right`}function Mi({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(Rr,{})})}const Ni=b.cssPrefix,Pi=`.${Ni}-header, .${Ni}-back-header, .${Ni}-home-hero`;function Fi(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(Pi)||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(`--${Ni}-modal-dx`)),dy:n(e.style.getPropertyValue(`--${Ni}-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(`--${Ni}-modal-dx`,`${n}px`),e.style.setProperty(`--${Ni}-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 Ii(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 Li(e,t,n){return Ii(`close`,e,t)?n.includes(`close`):!1}function Ri(e,t){return e===`inline`&&t===`fullscreen`?`exit-fullscreen`:`close`}function zi(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 Bi(e){return e.trim().split(/\s+/).slice(0,2).map(e=>e.charAt(0).toUpperCase()).join(``)}const Vi=b.cssPrefix;function Hi({agent:e,strings:t}){let n=e.status??`online`,r=O(t,e.name),i=e.title?O(t,e.title):null;return _(`div`,{class:`${Vi}-agent`,children:[g(`div`,{class:`${Vi}-agent-avatar`,"data-status":n,children:e.avatar?g(`img`,{src:e.avatar,alt:``}):g(`span`,{children:Bi(r)})}),_(`div`,{class:`${Vi}-agent-meta`,children:[g(`strong`,{children:r}),i?g(`span`,{children:i}):null]})]})}const Ui=L.scope(`attachments`);function Wi(e,t,n){let r=qi(e),i=[],a=[],o=Xi(n.accept),s=t.reduce((e,t)=>e+t.size,0),c=t.length;for(let e of r){let t=Ki(e,c,s,n,o);if(t){a.push({file:e,reason:t});continue}i.push(Yi(e)),s+=e.size,c+=1}return(i.length||a.length)&&Ui.debug(`ingest`,{accepted:i.length,rejected:a.map(e=>({name:e.file.name,reason:e.reason}))}),{accepted:i,rejected:a}}function Gi(e){try{URL.revokeObjectURL(e.previewUrl)}catch(e){Ui.debug(`revokeObjectURL failed`,{error:e})}}function Ki(e,t,n,r,i){return t>=r.maxCount?`count`:n+e.size>r.maxBytes?`bytes`:Zi(e,i)?null:`mime`}function qi(e){return e?Array.isArray(e)?e.filter(e=>e instanceof File):[...e].map(e=>e instanceof File?e:Ji(e)).filter(e=>e!==null):[]}function Ji(e){let t=e;return!t?.getAsFile||t.kind!==`file`?null:t.getAsFile()}function Yi(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 Xi(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 Zi(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 Qi=b.cssPrefix;function $i({attachment:e,onRemove:t,disabled:n=!1}){let r=e.mediaType.startsWith(`image/`);return _(`span`,{class:`${Qi}-attachment-chip`,title:e.name,"data-testid":wi(q.attachmentChip,e.id),children:[r?g(`img`,{class:`${Qi}-attachment-thumb`,src:e.previewUrl,alt:``}):g(`span`,{class:`${Qi}-attachment-thumb`,"aria-hidden":`true`,children:g(Xr,{})}),g(`span`,{class:`${Qi}-attachment-name`,children:e.name}),g(`button`,{type:`button`,class:`${Qi}-attachment-remove`,onClick:t,disabled:n,"aria-label":`Remove ${e.name}`,"data-testid":wi(q.attachmentRemove,e.id),children:g(wr,{})})]})}const ea={isSupported:!1,start:()=>void 0,stop:()=>void 0,cancel:()=>void 0};function ta(e,t,n){return e===`disabled`?ea:e===`server`?aa(n):na(t)}function na(e){let t=ra();if(!t)return ea;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 ra(){return window.SpeechRecognition??window.webkitSpeechRecognition}const ia=[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/mp4`];function aa(e){if(typeof MediaRecorder>`u`||!navigator?.mediaDevices?.getUserMedia)return ea;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=oa(),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 oa(){for(let e of ia)if(MediaRecorder.isTypeSupported(e))return e}const sa=b.cssPrefix,ca=L.scope(`composer`);function la(e){return e.reduce((e,t)=>e+t.size,0)}const ua={arrowUp:Dr,paperPlane:Er,send:Or,chevron:kr};function da(e){return`activeElement`in e}function fa(e){return`host`in e&&`activeElement`in e}function pa({options:e,transport:t,feedback:n,bus:a,persistence:o,conversationId:l,isStreaming:u,active:d=!0,isPreparing:f=!1,operatorRequestEnabled:p,canRequestOperator:m=!1,controlMode:h,onRequestOperator:v,onSend:y,onStop:b,attachApiRef:x}){let S=e.strings,[C,w]=c(()=>o.loadDraft(l)),[T,E]=c([]),[D,O]=c(!1),[k,A]=c(!1),j=s(!1),M=s(null),ee=s(null),te=s(null),N=s(0),ne=s(l);ne.current=l;let re=s(d);re.current=d;let ie=s(f);ie.current=f;let P=k||f||!d,ae=r(e=>{w(t=>{let n=typeof e==`function`?e(t):e;return n===t?t:(o.saveDraft(ne.current,n),n)})},[o]),oe=e.features.fileUpload,F=e.features.voice,[I,se]=c(()=>ta(F,e.locale,(e,n)=>t.transcribe(e,n))),ce=s(I);ce.current=I;let L=s({mode:F,locale:e.locale,transport:t});i(()=>{let n=L.current;(n.mode!==F||n.locale!==e.locale||n.transport!==t)&&(L.current={mode:F,locale:e.locale,transport:t},N.current++,ce.current.cancel(),te.current=null,O(!1),se(ta(F,e.locale,(e,n)=>t.transcribe(e,n))))},[e.locale,F,t]),i(()=>()=>{N.current++,I.cancel()},[I]);let le=r(e=>{let t=te.current;if(t===null)return!1;let n=Date.now()-t;return ca[e](`voiceStop`,{durationMs:n}),a.emit(`voiceStop`,{durationMs:n}),te.current=null,!0},[a]),R=r(()=>{te.current!==null&&(I.stop(),O(!1),le(`info`)&&n.play(`voiceStop`))},[le,n,I]),ue=r(()=>{N.current++,I.cancel(),O(!1),le(`info`)&&n.play(`voiceStop`)},[le,n,I]);i(()=>{(f||!d)&&ue()},[d,ue,f]),i(()=>{let e=M.current;if(!e)return;let t=e.getRootNode(),n=da(t)?t.activeElement:null;n&&e.closest(`.${sa}-panel`)?.contains(n)||e.focus({preventScroll:!0})},[]),i(()=>{let e=M.current;if(!e)return;if(C.length===0){e.style.height=``;return}e.style.height=`auto`;let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--${sa}-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`},[C]);let z=s(T);z.current=T,i(()=>()=>z.current.forEach(Gi),[]),i(()=>{if(x)return x.current={attachFromDrop:t=>{if(!oe||!re.current||j.current||ie.current)return;let n=Wi(t,z.current,e.attachments);n.accepted.length!==0&&(ca.info(`attach (drop)`,{count:n.accepted.length,totalBytes:la(n.accepted)}),a.emit(`attach`,{count:n.accepted.length,totalBytes:la(n.accepted)}),E(e=>[...e,...n.accepted]))},fill:e=>{if(!re.current||j.current||ie.current)return;ae(e);let t=M.current;t&&(t.focus({preventScroll:!0}),requestAnimationFrame(()=>t.setSelectionRange(t.value.length,t.value.length)))}},()=>{x.current&&(x.current=null)}},[x,oe,f,e.attachments,ae]),i(()=>{let t=M.current;if(!t)return;let n=t.closest(`.${sa}-panel`);if(!n)return;let r=n=>{if(!re.current||j.current||ie.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(oe){let t=Wi(r.items,z.current,e.attachments);if(t.accepted.length>0){n.preventDefault(),ca.info(`attach (paste)`,{count:t.accepted.length,totalBytes:la(t.accepted)}),a.emit(`attach`,{count:t.accepted.length,totalBytes:la(t.accepted)}),E(e=>[...e,...t.accepted]);return}}if(i===t)return;let o=r.getData(`text/plain`);o&&(n.preventDefault(),ae(e=>e+o),t.focus())};return n.addEventListener(`paste`,r),()=>n.removeEventListener(`paste`,r)},[oe,e.attachments,ae]);let de=async()=>{let e=C.trim();if(!e&&T.length===0||!d||u||j.current||f)return;ue(),j.current=!0,A(!0);let t=C,n=T;try{await y(e,n)&&(ae(e=>e===t?``:e),E(e=>e===n?(n.forEach(Gi),z.current=[],[]):e))}finally{j.current=!1,A(!1),requestAnimationFrame(()=>{let e=M.current;if(!e||e.disabled||!re.current)return;let t=e.getRootNode(),n=da(t)?t.activeElement:null,r=n?.getAttribute(`data-testid`);if(!(n&&n!==e&&r!==q.composerSend&&r!==q.composerStop)){if(fa(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})}})}},fe=e=>{e.key!==`Enter`||e.shiftKey||e.isComposing||(e.preventDefault(),u?b():de())},pe=t=>{let n=t.target;if(!d||j.current||f){n.value=``;return}let r=Wi(n.files,T,e.attachments);r.accepted.length>0&&(ca.info(`attach (file picker)`,{count:r.accepted.length,totalBytes:la(r.accepted)}),a.emit(`attach`,{count:r.accepted.length,totalBytes:la(r.accepted)}),E(e=>[...e,...r.accepted])),n.value=``},me=e=>{!d||j.current||f||(ca.info(`removeAttachment`,{id:e}),a.emit(`removeAttachment`,{id:e}),E(t=>{let n=t.find(t=>t.id===e);return n&&Gi(n),t.filter(t=>t.id!==e)}))},he=()=>{if(D){R();return}if(!d||!I.isSupported||j.current||f)return;let e=++N.current;te.current=Date.now(),ca.info(`voiceStart`),a.emit(`voiceStart`,void 0),O(!0),n.play(`voiceStart`),I.start((t,n)=>{N.current!==e||!re.current||ie.current||j.current||!n||ae(e=>`${e}${t} `)},()=>{N.current!==e||!re.current||(O(!1),le(`debug`))})},ge=ua[e.composer.sendButton.icon];return _(`div`,{class:`${sa}-composer`,"data-testid":q.composer,children:[T.length>0?g(`div`,{class:`${sa}-attachments`,children:T.map(e=>g($i,{attachment:e,onRemove:()=>me(e.id),disabled:P},e.id))}):null,_(`div`,{class:`${sa}-composer-row`,children:[_(`div`,{class:`${sa}-composer-actions`,children:[oe?g(`button`,{type:`button`,class:`${sa}-icon-btn`,onClick:()=>ee.current?.click(),disabled:P,"aria-label":S.attach,"data-testid":q.composerAttach,children:g(jr,{})}):null,I.isSupported?g(`button`,{type:`button`,class:`${sa}-icon-btn`,onClick:he,disabled:P,"aria-label":D?S.micStop:S.micStart,"aria-pressed":D,"data-recording":D?`true`:void 0,"data-testid":q.composerVoice,children:g(Mr,{})}):null]}),g(`textarea`,{ref:M,name:`message`,class:`${sa}-textarea`,rows:1,value:C,placeholder:S.composerPlaceholder,onInput:e=>ae(e.currentTarget.value),onKeyDown:fe,disabled:P,"aria-label":S.composerPlaceholder,"data-testid":q.composerInput}),u?g(`button`,{type:`button`,class:`${sa}-send`,onClick:b,disabled:P,"aria-label":S.stop,"data-testid":q.composerStop,children:g(Ar,{})}):g(`button`,{type:`button`,class:`${sa}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:()=>void de(),disabled:P||!C.trim()&&T.length===0,"aria-label":S.send,"data-testid":q.composerSend,children:g(ge,{})}),p&&h===`ai-agent`&&v?g(`button`,{type:`button`,class:`${sa}-icon-btn`,onClick:v,disabled:P||!m,"aria-label":S.talkToOperator,title:S.talkToOperator,"data-testid":q.operatorRequest,children:g(ni,{})}):null]}),g(`input`,{ref:ee,name:`attachments`,type:`file`,multiple:!0,accept:e.attachments.accept,onChange:pe,disabled:P,class:`${sa}-sr-only`,"data-testid":q.composerFileInput})]})}const ma=b.cssPrefix;function ha({visible:e,strings:t}){return e?g(`div`,{class:`${ma}-dropzone`,role:`status`,"aria-live":`polite`,children:t.dropZone}):null}function ga({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 _a({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 va({items:e,triggerLabel:t}){let n=b.cssPrefix,r=_a({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(zr,{})}),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(Wr,{})}):null]},e.id))}):null]})}const ya=b.cssPrefix;function ba(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 xa={normal:`large`,large:`small`,small:`normal`};function Sa(e){return g(e===`light`?li:e===`dark`?ui:di,{})}function Ca(e){return(e.split(`-`)[0]??e).toUpperCase()}function wa(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 Ta({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&&Ii(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(Jr,{}),label:h.newConversation,onSelect:o}),S(`expand`)&&w(`expand`)){let e=r===`expanded`;k.push({id:`expand`,icon:g(e?Pr:Nr,{}),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?Ir:Fr,{}),label:e?h.exitFullscreen:h.fullscreen,type:`switch`,on:e,onSelect:c})}let A=n.popOutUrl,j=n.aiAgentDeploymentId;S(`popOut`)&&A&&j&&Ii(`popOut`,v,r)&&k.push({id:`popOut`,icon:g(Lr,{}),label:h.popOut,onSelect:()=>{let t=wa(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?Vr:Br,{}),label:b?h.soundOff:h.soundOn,type:`switch`,on:!b,onSelect:l}),S(`theme`)&&k.push({id:`theme`,icon:Sa(T),label:`${h.theme}: ${E[T]}`,onSelect:()=>f(ba(T)),keepOpen:!0}),S(`textSize`)&&k.push({id:`textSize`,icon:g(Hr,{}),label:`${h.textSize}: ${O[D]}`,onSelect:()=>m(xa[D]),keepOpen:!0}),S(`language`)&&n.availableLocales.length>1&&k.push({id:`language`,icon:g(Kr,{}),label:h.language,segments:n.availableLocales.map(e=>({value:e,label:Ca(e),lang:e})),value:n.locale,onSelectValue:d});let M=!!a&&Li(v,r,n.actions),ee=y&&S(`history`);return _(`div`,{class:`${ya}-header-actions`,children:[ee?g(`button`,{type:`button`,class:`${ya}-icon-btn`,onClick:u,"aria-label":h.history,title:h.history,"data-testid":q.actionHistory,children:g(Gr,{})}):null,k.length>0?g(va,{items:k,triggerLabel:h.moreActions}):null,M?g(`button`,{type:`button`,class:`${ya}-icon-btn`,onClick:a,"aria-label":h.close,title:h.close,"data-testid":q.actionClose,children:g(wr,{})}):null]})}const Ea=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Da=/^https?:\/\/[^\s.]+\.[^\s]+$/i,Oa=/^[+]?[\d\s().-]{6,}$/;function ka(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>String(t[n]??`{${n}}`))}function Aa(e){return Array.isArray(e)?e.length:e&&e.trim()?1:0}function ja(e,t,n){let r=e.required??!0,i=e.validation;if(e.type===`multiselect`){let e=Aa(t);return r&&e===0?n.formRequired:e===0?void 0:i?.minSelections!=null&&e<i.minSelections?ka(n.formChooseAtLeast,{min:i.minSelections}):i?.maxSelections!=null&&e>i.maxSelections?ka(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(!Ea.test(a))return n.formInvalidEmail;break;case`url`:if(!Da.test(a))return n.formInvalidUrl;break;case`tel`:if(!Oa.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 ka(n.formNumberTooSmall,{min:i.min});if(i?.max!=null&&e>i.max)return ka(n.formNumberTooLarge,{max:i.max});break}default:break}if(i?.minLength!=null&&a.length<i.minLength)return ka(n.formTooShort,{min:i.minLength});if(i?.maxLength!=null&&a.length>i.maxLength)return ka(n.formTooLong,{max:i.maxLength});if(i?.pattern)try{if(!new RegExp(i.pattern).test(a))return n.formPatternMismatch}catch{}}function Ma(e,t,n){let r={};for(let i of e){let e=ja(i,t[i.name],n);e&&(r[i.name]=e)}return r}function Na(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 J=b.cssPrefix,Pa=`__other__`;function Fa({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(()=>({...za(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=Ba(e,v,b),a=Ma(e,i,t);if(Object.keys(a).length>0){C(a);return}r(Na(i))};return _(`form`,{class:`${J}-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(Ia,{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:`${J}-form-actions`,children:[o?g(`span`,{class:`${J}-form-hint`,children:o}):null,i&&a?g(`button`,{type:`button`,class:`${J}-form-skip`,onClick:a,disabled:l,"data-testid":h,children:i}):null,g(`button`,{type:`submit`,class:`${J}-form-submit`,disabled:l,"data-testid":m,children:n})]})]})}function Ia({field:e,value:t,otherText:n,error:r,disabled:i,typeLabel:a,strings:o,onChange:s,onOtherChange:c}){let l=La({field:e,value:t,otherText:n,disabled:i,strings:o,onChange:s,onOtherChange:c,fieldTid:wi(q.formField,e.name)});return _(`label`,{class:`${J}-field`,"data-field":e.name,"data-invalid":r?`true`:void 0,children:[_(`span`,{class:`${J}-field-head`,children:[_(`span`,{class:`${J}-field-label`,children:[e.label,e.required??!0?g(`span`,{class:`${J}-field-req`,"aria-hidden":`true`,children:` *`}):null]}),a?g(`span`,{class:`${J}-field-type`,children:a}):null]}),l,e.validationHint&&!r?g(`span`,{class:`${J}-field-hint`,children:e.validationHint}):null,r?g(`span`,{class:`${J}-field-error`,role:`alert`,children:r}):null]})}function La(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:`${J}-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:`${J}-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===Pa;return _(`div`,{class:`${J}-field-choices`,role:`radiogroup`,"data-testid":c,children:[(t.options??[]).map(e=>_(`label`,{class:`${J}-choice`,children:[g(`input`,{type:`radio`,name:`${J}-${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:`${J}-choice`,children:[g(`input`,{type:`radio`,name:`${J}-${t.name}`,checked:l===Pa,disabled:i,onChange:()=>o(Pa)}),g(`span`,{children:a.formOther})]}):null,e?g(`input`,{class:`${J}-field-input`,value:r,placeholder:t.placeholder??a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.target.value)}):null]})}case`checkbox`:return _(`label`,{class:`${J}-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:`${J}-field-choices`,"data-testid":c,children:[(t.options??[]).map(t=>_(`label`,{class:`${J}-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:`${J}-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:`${J}-field-input`,type:Ra(t.type),value:l,placeholder:t.placeholder,disabled:i,onInput:e=>o(e.target.value),"data-testid":c})}}function Ra(e){switch(e){case`number`:case`email`:case`tel`:case`url`:case`date`:case`time`:return e;default:return`text`}}function za(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 Ba(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]===Pa)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 Va=b.cssPrefix;function Ha({form:e,strings:t,onSubmit:n,onSkip:r}){return _(`div`,{class:`${Va}-form-gate`,"data-testid":q.formGate,children:[e.title?g(`h3`,{class:`${Va}-form-gate-title`,children:e.title}):null,e.description?g(`p`,{class:`${Va}-form-gate-desc`,children:e.description}):null,g(Fa,{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 Ua({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:`${Va}-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:`${Va}-form-done`,"data-outcome":e.outcome,"data-testid":q.formDone,children:[_(`summary`,{class:`${Va}-form-done-summary`,"data-testid":q.formDoneToggle,children:[g(Wr,{}),a,g(kr,{})]}),g(`dl`,{class:`${Va}-form-answers`,"data-testid":q.formAnswers,children:Object.entries(s).map(([e,n])=>_(`div`,{class:`${Va}-form-answer`,children:[g(`dt`,{children:t(e)}),g(`dd`,{children:n})]},e))})]})}return _(`div`,{class:`${Va}-form-done`,"data-outcome":e.outcome,"data-testid":q.formDone,role:`status`,children:[g(r?Ur:Wr,{}),a,r&&e.form?.reopenable&&n?g(`button`,{type:`button`,class:`${Va}-form-done-fill`,"data-testid":q.formFill,onClick:n,children:t.formFillOut}):null]})}function Wa(e){if(!e)return!1;let t=e.startsWith(`tool:`)?e.slice(5):e;return t===`ask-user-questions`||t===`ask_user_questions`}const Ga=b.cssPrefix;function Ka(e){return e.startsWith(`tool:`)||e.startsWith(`tool-`)?e.slice(5):e}function qa(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 Ja({status:e,icon:t,label:n}){return _(`span`,{class:`${Ga}-toolui-badge ${Ga}-toolui-status`,"data-status":e,children:[g(`span`,{class:`${Ga}-toolui-status-icon`,children:t}),n]})}function Ya(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 Xa(e,t,n={}){return n.submitted?`responded`:$a(Ya(e,t),n.superseded,n.live??!0)}function Za({status:e}){return g(e===`denied`||e===`error`||e===`superseded`?Si:e===`completed`||e===`responded`?xi:bi,{})}function Qa(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 $a(e,t,n){return t&&(e===`awaiting`||e===`running`)?`superseded`:!n&&e===`running`?`error`:e}function eo({state:e,approval:t,strings:n,superseded:r,live:i=!0,submitted:a=!1}){let o=Xa(e,t,{superseded:r,live:i,submitted:a});return g(Ja,{status:o,icon:g(Za,{status:o}),label:Qa(o,n)})}function to({name:e,state:t,approval:n,strings:r,superseded:i,live:a,submitted:o}){return _(h,{children:[_(`span`,{class:`${Ga}-toolui-name-pill`,children:[g(yi,{}),g(`span`,{class:`${Ga}-toolui-name-text`,children:e})]}),g(eo,{state:t,approval:n,strings:r,superseded:i,live:a,submitted:o}),g(`span`,{class:`${Ga}-toolui-chevron`,children:g(Yr,{})})]})}function no({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:`${Ga}-toolui ${Ga}-toolui-collapsible`,"data-testid":n,children:[g(`summary`,{class:`${Ga}-toolui-head`,children:g(to,{name:Ka(e.toolName),state:d.value,approval:f.value,strings:t,superseded:r,live:i,submitted:a})}),g(ro,{label:t.toolParameters,value:s.value}),c.value===void 0?null:g(ro,{label:t.toolResult,value:c.value}),l.value?g(ro,{label:t.statusError,value:l.value,error:!0}):null]})}function ro({label:e,value:t,error:n}){let r=n?String(t??``):ao(io(t));return r?_(`div`,{class:`${Ga}-toolui-section`,children:[g(`span`,{class:`${Ga}-toolui-label`,children:e}),g(`pre`,{class:`${Ga}-toolui-code`,"data-error":n?`true`:void 0,children:r})]}):null}function io(e){if(e&&typeof e==`object`){let t=e;if(t.storage===`tool-result-ref`&&`summary`in t)return t.summary}return e}function ao(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 oo(e){return e.partsSig.value.some(e=>e.kind===`text`&&e.textSig.value.length>0)}function so(e){return e.partsSig.value.some(e=>e.kind===`reasoning`)}function co(e){return e.streaming&&!e.bufferedHold&&!(e.reasoningVisible&&e.working)}function lo(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:co({streaming:t,bufferedHold:a,reasoningVisible:n,working:o}),emptyReply:r,hidden:i}}function uo(e,t){let n=e.stateSig.value,r=e.approvalSig.value,{terminal:i,responded:a,decided:o}=qa(n,r),s=t.continuationStreaming===!0&&!o,c=t.superseded&&!o&&!s;return{pill:Xa(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 fo({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)mo(e)}});c.observe(r,{childList:!0,subtree:!0});for(let e of r.querySelectorAll(`a`))mo(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 po({text:e}){return g(fo,{textSig:o(()=>f(e),[e]),doneSig:o(()=>f(!0),[])})}function mo(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 ho=b.cssPrefix;function go({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:`${ho}-feedback`,role:`group`,"data-testid":q.messageFeedback,children:[g(`button`,{type:`button`,class:`${ho}-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(_i,{})}),g(`button`,{type:`button`,class:`${ho}-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(vi,{})}),g(`span`,{class:`${ho}-sr-only`,role:`status`,"aria-live":`polite`,children:a?n.feedbackThanks:``})]})}const _o=b.cssPrefix;function vo({part:e,strings:t}){let n=e.title||e.filename||e.url||t.sources;return e.url?_(`a`,{class:`${_o}-source`,href:e.url,target:`_blank`,rel:`noreferrer noopener`,"data-testid":q.source,children:[g(`span`,{class:`${_o}-source-icon`,"aria-hidden":`true`,children:`🔗`}),g(`span`,{class:`${_o}-source-label`,children:n})]}):_(`span`,{class:`${_o}-source`,"data-testid":q.source,children:[g(`span`,{class:`${_o}-source-icon`,"aria-hidden":`true`,children:`📄`}),g(`span`,{class:`${_o}-source-label`,children:n})]})}const yo=b.cssPrefix;function bo({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(()=>uo(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=Ka(e.toolName),x=l.answeredApproved,S=e.toolCallId,C=_(h,{children:[g(`p`,{class:`${yo}-toolui-prompt`,children:t.approvalPrompt.replace(`{tool}`,b)}),g(`p`,{class:`${yo}-toolui-subtle`,children:t.approvalBody})]});m?C=g(`p`,{class:`${yo}-toolui-subtle`,children:t.approvalSubmitting}):p&&x!==!1?C=_(h,{children:[_(`p`,{class:`${yo}-toolui-prompt`,children:[t.approvalYourResponse.replace(`{decision}`,x?t.approve:t.reject),c.value?.reason?` — ${c.value.reason}`:``]}),v?g(`p`,{class:`${yo}-toolui-subtle`,children:t.approvalEditHint}):null,v?null:g(`p`,{class:`${yo}-toolui-subtle`,children:t.approvalSubmitting})]}):p&&(C=g(h,{}));let w=f||m||v||p&&x!==!1;return _(`div`,{class:`${yo}-toolui-group`,"data-testid":l.decided?q.toolDecision:q.toolApproval,children:[g(no,{part:e,strings:t,superseded:y,submitted:m}),y||d||!w?null:_(`div`,{class:`${yo}-toolui ${yo}-toolui-body`,children:[C,f?_(`div`,{class:`${yo}-toolui-actions`,children:[g(`button`,{type:`button`,class:`${yo}-form-skip`,disabled:!n,onClick:()=>a(S,!1),"data-testid":q.toolReject,children:t.reject}),g(`button`,{type:`button`,class:`${yo}-form-submit`,disabled:!n,onClick:()=>a(S,!0),"data-testid":q.toolApprove,children:t.approve})]}):null,v?g(`div`,{class:`${yo}-toolui-actions`,children:g(`button`,{type:`button`,class:`${yo}-form-skip`,onClick:()=>s(S),"data-testid":q.toolEdit,children:t.edit})}):null]})]})}const xo=new Set([`text`,`email`,`phone`,`number`,`date`,`single-select`,`multi-select`,`boolean`]);function So(e){let t=e&&typeof e==`object`?e:{},n=(Array.isArray(t.questions)?t.questions:[]).map(Co).filter(e=>e!==null);return{intro:Eo(t.intro),questions:n}}function Co(e,t){if(!e||typeof e!=`object`)return null;let n=e,r=xo.has(n.type)?n.type:`text`;return{key:Eo(n.key)??`q${t+1}`,question:Eo(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:Eo(n.helpText)}}function wo(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 To(e,t,n){return e.questions.map(e=>{let r=wo(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 Eo(e){return typeof e==`string`&&e.trim()?e.trim():void 0}const Y=b.cssPrefix,Do={text:`qtypeText`,email:`qtypeEmail`,phone:`qtypePhone`,number:`qtypeNumber`,date:`qtypeDate`,"single-select":`qtypeChooseOne`,"multi-select":`qtypeChooseAny`,boolean:`qtypeBoolean`};function Oo(e,t){let n={};for(let r of e)n[r.key]=t[Do[r.type]];return n}function ko({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(()=>So(e.inputSig.value)),[e]).value,{terminal:p,decided:m}=qa(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?Cr:$r,k=y?t.inputRequired:t.inputBadge,A=v?g(`p`,{class:`${Y}-toolui-subtle`,children:t.approvalSubmitting}):y?g(Ao,{req:f,strings:t,active:n,resolve:(t,n)=>a(e.toolCallId,n,t)}):E?g(Fa,{fields:To(f,t.confirmYes,t.confirmNo),strings:t,submitLabel:t.inputSubmit,onSubmit:()=>{},disabled:!0,hideActions:!0,fieldTypeLabels:Oo(S,t),initialValues:h?Io(S,d?.reason):void 0}):g(jo,{questions:S,answers:h?Fo(d?.reason):{},strings:t}),j=`completed`,M=t.inputAnswered;return b?(j=`superseded`,M=t.inputSkipped):v&&(j=`responded`,M=t.statusResponded),_(`details`,{class:`${Y}-toolui ${Y}-toolui-collapsible${r?` ${Y}-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:`${Y}-toolui-head`,children:[_(`span`,{class:`${Y}-toolui-q-pill`,children:[g(O,{}),k]}),_(`span`,{class:`${Y}-toolui-head-end`,children:[y?null:g(Ja,{status:j,icon:g(b?Si:xi,{}),label:M}),g(`span`,{class:`${Y}-toolui-chevron`,children:g(Yr,{})})]})]}),_(`div`,{class:`${Y}-toolui-collapse-body`,children:[f.intro?g(`div`,{class:`${Y}-toolui-desc`,children:f.intro}):null,A,y||v?null:_(`div`,{class:`${Y}-toolui-footer`,children:[_(`button`,{type:`button`,class:`${Y}-toolui-options-toggle`,onClick:()=>D(e=>!e),"data-testid":q.toolAskOptions,children:[g(`span`,{class:`${Y}-toolui-options-chevron${E?` ${Y}-open`:``}`,children:g(Yr,{})}),E?t.hideOptions:t.showOptions]}),x?g(`button`,{type:`button`,class:`${Y}-form-skip`,onClick:()=>s(e.toolCallId),"data-testid":q.toolEdit,children:t.edit}):null]})]})]})}function Ao({req:e,strings:t,active:n,resolve:r}){let i=To(e,t.confirmYes,t.confirmNo),a=e.questions.length===1&&e.questions[0]?.type===`text`;return g(Fa,{fields:i,strings:t,disabled:!n,submitLabel:t.inputSubmit,footerHint:a?t.inputSubmitHint:void 0,onSubmit:t=>r(No(e.questions,t),!0),skipLabel:t.inputSkip,onSkip:()=>r(void 0,!1),submitOnEnter:a,fieldTypeLabels:Oo(e.questions,t),submitTestId:q.toolInputSubmit,skipTestId:q.toolInputSkip})}function jo({questions:e,answers:t,strings:n}){return g(`div`,{class:`${Y}-toolui-summary`,"data-testid":q.toolAskSummary,children:e.map(e=>_(`div`,{class:`${Y}-field`,children:[g(`span`,{class:`${Y}-field-head`,children:_(`span`,{class:`${Y}-field-label`,children:[e.question,e.required?g(`span`,{class:`${Y}-field-req`,"aria-hidden":`true`,children:` *`}):null]})}),g(`p`,{class:`${Y}-toolui-answer`,children:Mo(e,t[e.key],n)||`—`})]},e.key))})}function Mo(e,t,n){return e.type===`boolean`?t===`yes`?n.confirmYes:t===`no`?n.confirmNo:t??``:t??``}function No(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 Po(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 Fo(e){let t=Po(e),n={};for(let[e,r]of Object.entries(t))n[e]=Array.isArray(r)?r.join(`, `):r;return n}function Io(e,t){let n=Po(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 Lo({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(()=>!!ao(r.value)||!!a.value||!!ao(io(i.value))),[r,i,a]).value?g(no,{part:e,strings:t,testid:q.toolCall,live:n}):null}const X=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(()=>ir(e)),[e]),y=o(()=>u(()=>or(e)),[e]),b=o(()=>u(()=>oo(e)),[e]),x=o(()=>u(()=>i&&so(e)),[e,i]),S=t===`streaming`,C=e.role===`assistant`&&S,w=lo({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:`${X}-bubble-row`,"data-role":e.role,"data-testid":Ci(q.messageBubble,e.serverMessageId??e.id),children:_(`div`,{class:`${X}-bubble-col`,children:[_(`div`,{class:`${X}-bubble`,children:[e.role===`operator`&&e.operatorInitials?g(`span`,{class:`${X}-bubble-author`,children:e.operatorInitials}):null,_(`div`,{class:`${X}-bubble-body`,children:[T?g(Go,{label:n.loading}):h.map((r,o)=>g(Bo,{part:r,active:E,live:C,strings:n,showReasoning:i,showToolCalls:a,showSources:s,interactive:c&&t===`complete`&&(r.kind!==`tool`||Wn(e,o)),superseded:l,continuationStreaming:e.continuationStreaming===!0,tool:d},`${Uo(r)}#${o}`)),D&&g(Wo,{}),t===`error`||v.value?_(`div`,{class:`${X}-error`,role:`alert`,children:[g(`span`,{children:e.errorText??n.errorGeneric}),f?g(`button`,{type:`button`,class:`${X}-error-retry`,onClick:()=>f(e),"data-testid":q.messageRetry,children:n.errorRetry}):null]}):null]})]}),O||ee?_(`div`,{class:`${X}-bubble-meta`,children:[O?g(`time`,{class:`${X}-bubble-time`,dateTime:O.iso,title:O.full,children:O.short}):null,ee?_(`div`,{class:`${X}-bubble-actions`,children:[A&&e.serverMessageId?g(mo,{messageId:e.serverMessageId,initial:e.feedback??null,strings:n,onFeedback:m}):null,M?g(Ro,{text:j,strings:n}):null]}):null]}):null]})})}function Ro({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:`${X}-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 zo(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 Bo({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(Ho,{part:e,active:t,strings:r}):null;case`tool`:return g(Vo,{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 Vo({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(Do,{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(Fo,{part:e,strings:t,live:s}):null}function Ho({part:e,active:t,strings:n}){return _(`details`,{class:`${X}-reasoning`,"data-testid":q.reasoning,open:t,"data-active":t?`true`:void 0,children:[g(`summary`,{class:`${X}-reasoning-summary`,children:g(`span`,{class:`${X}-reasoning-label`,children:t?n.thinking:n.thoughts})}),g(`div`,{class:`${X}-reasoning-body`,children:g(lo,{textSig:e.textSig,doneSig:e.doneSig})})]})}function Uo(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 Wo(){return _(`span`,{class:`${X}-typing`,"data-testid":q.typingDots,"aria-hidden":`true`,children:[g(`span`,{}),g(`span`,{}),g(`span`,{})]})}function Go({label:e}){return _(`span`,{class:`${X}-loading`,role:`status`,children:[g(`span`,{class:`${X}-loading-spinner`,"aria-hidden":`true`}),g(`span`,{class:`${X}-loading-label`,children:e})]})}const Ko=b.cssPrefix;function qo({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),ie=()=>ne.current||performance.now()-re.current<350,P=s(0),ae=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`},oe=e=>D(e.scrollHeight-e.scrollTop-e.clientHeight>240),F=e=>{P.current=performance.now(),e.scrollTop=e.scrollHeight,ae(e)},I=(e,t)=>{F(e);let n=t,r=0,i=()=>{N.current||ie()||(F(e),--n>0&&(r=requestAnimationFrame(i)))};return t>0&&(r=requestAnimationFrame(i)),()=>cancelAnimationFrame(r)},se=(e,t)=>{let n,r,i,a=-1,o=()=>{n.disconnect(),r.disconnect(),clearTimeout(i)},s=()=>{if(N.current||ie()||a>=0&&e.scrollTop<a-4)return o();F(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},ce=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 se(e,300)},[ce]);let L=s(0);i(()=>{let e=w.current,t=T.value,n=L.current;if(L.current=t.length,e&&te.current&&!j.current){if(t.slice(n).some(e=>e.role===`user`))return N.current=!1,I(e,3);t.some(e=>e.role===`user`)&&(N.current||ie()||e.scrollHeight-e.scrollTop-e.clientHeight<120&&F(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,I(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||ie()||e.scrollHeight-e.scrollTop-e.clientHeight<240&&F(e)};if(t.status!==`streaming`)return se(e,300);n();let r=new MutationObserver(n);return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>r.disconnect()},[T.value]);let R=x?.form.id,ue=!!x&&(S??[]).some(e=>e.formId===x.form.id);a(()=>{let e=w.current;!e||!R||N.current||T.value.some(e=>e.role===`user`)&&(ue?e.querySelector(`[data-testid="${q.formGate}"]`)?.scrollIntoView({block:`nearest`}):F(e))},[R,ue]),i(()=>{let e=w.current;if(!e)return;let t=()=>{oe(e),ae(e),performance.now()-P.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}),oe(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 z=()=>{let e=w.current;e&&(N.current=!1,F(e))},de=T.value.filter(e=>!e.ephemeral),fe=de[0],pe=fe?.serverMessageId??fe?.id,me=!!(m&&de.length>=50&&pe!==M),he=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&&pe&&ee(pe),r&&e&&(await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),e.scrollTop=n+e.scrollHeight-t,ae(e),oe(e))}finally{j.current=!1,A.current=!1,k(!1)}},ge=[],_e=``,ve=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(),ge.push(be(t))};for(let e of T.value){if(e.role===`assistant`&&e.id!==ve&&ir(e))continue;xe(e.createdAt);let i=Jo(e.createdAt);i&&i!==_e&&(ge.push(g(`div`,{class:`${Ko}-date-divider`,children:g(`span`,{class:`${Ko}-date-pill`,title:Yo(e.createdAt),children:Xo(e.createdAt,t)})},`day:${i}`)),_e=i);let a=e.retryAction!==void 0||e.role===`assistant`&&e.id===ve?ar(T.value,e):void 0,s=a!==void 0&&(a.kind!==`continue-assistant`||v===`ai-agent`);ge.push(g(Io,{message:e,status:e.status,strings:t,responseMode:n,showReasoning:r,showToolCalls:o,showSources:l,interactive:!!h&&v===`ai-agent`&&e.id===ve,superseded:e.id!==ve,tool:y,onRetry:h&&s&&(e.role===`user`||e.id===ve)?b:void 0,enableMessageFeedback:u,onFeedback:d},e.id))}for(let e of ye)ge.push(be(e));return _(`div`,{class:`${Ko}-list-wrap`,children:[_(`div`,{ref:w,class:`${Ko}-list ${Ko}-list--fade`,role:`log`,"aria-live":`polite`,"aria-relevant":`additions text`,children:[f&&T.value.length===0?g(`div`,{class:`${Ko}-list-loading`,role:`status`,children:t.conversationLoading}):null,me?g(`div`,{class:`${Ko}-load-previous`,children:g(`button`,{type:`button`,onClick:he,disabled:O,"aria-busy":O,"data-testid":q.loadPreviousMessages,children:t.loadPreviousMessages})}):null,ge,x&&!ue?g(Ba,{form:x.form,strings:t,onSubmit:x.onSubmit,onSkip:x.onSkip}):null]}),E?g(`button`,{type:`button`,class:`${Ko}-jump`,onClick:z,"aria-label":t.scrollToBottom,title:t.scrollToBottom,"data-testid":q.scrollToBottom,children:g(Jr,{})}):null]})}function Jo(e){if(typeof e!=`number`||!Number.isFinite(e))return``;let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`}function Yo(e){if(typeof e!=`number`||!Number.isFinite(e))return``;try{return new Date(e).toLocaleDateString(void 0,{dateStyle:`full`})}catch{return``}}function Xo(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 Zo=[`today`,`yesterday`,`lastWeek`,`older`];function Qo(e,t){let n=Date.parse(t);if(!Number.isFinite(n))return`older`;let r=Math.floor((es(e)-es(n))/(1440*60*1e3));return r<=0?`today`:r===1?`yesterday`:r<7?`lastWeek`:`older`}function $o(e,t){let n=new Map;for(let r of t){let t=Qo(e,r.lastMessageAt),i=n.get(t);i?i.push(r):n.set(t,[r])}return Zo.filter(e=>n.has(e)).map(e=>({bucket:e,conversations:n.get(e)}))}function es(e){let t=new Date(e);return t.setUTCHours(0,0,0,0),t.getTime()}const ts=L.scope(`history`),ns={today:`dateToday`,yesterday:`dateYesterday`,lastWeek:`dateLastWeek`,older:`dateOlder`};function rs(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 is(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 as({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&&rs(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=rs(a,e);i=[],n=!1,m(a),f(`loaded`),r.saveHistoryCount(a.conversations.length)}).catch(e=>{t||(i=[],n=!1,ts.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;ts.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(Tr,{}),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=$o(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[ns[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:is(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 os=b.cssPrefix;function ss({suggestions:e,onPick:t,disabled:n=!1}){return e.length===0?null:g(`div`,{class:`${os}-suggestions`,role:`group`,"aria-label":`Suggested replies`,children:e.map((e,r)=>g(`button`,{type:`button`,class:`${os}-suggestion`,onClick:()=>t(e),disabled:n,"data-testid":Ci(q.suggestion,r),children:e.label},e.id))})}const Z=b.cssPrefix;function cs(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}=ha({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(ls,{...e,containerEl:o.current,dragOver:u,composerAttachApiRef:c}),g(hs,{poweredBy:e.options.poweredBy})]})}function ls(e){let{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,composerKey:s,panelSize:c,view:l,canSend:u,isStreaming:d,sendPreparing:f,controlMode:m,assignedOperatorInitials:v,operatorAvailable:y,operatorRequestEnabled:b,onRequestOperator:x,onCancelOperatorRequest:S,loadingMessages:C,onLoadPreviousMessages:w,messagesSig:T,agent:E,suggestions:D,initialWidgetSize:O,onClose:k,onBack:A,onClear:j,onToggleHistory:M,onSelectHistoryConversation:ee,onNewConversation:te,onWidgetSizeChange:N,onSend:ne,onStop:re,onSuggestion:ie,activeForm:P,formMarkers:ae,onFormSubmit:oe,onFormSkip:F,onFormFill:I,tool:se,onRetry:ce,onMessageFeedback:L,containerEl:le,dragOver:R,composerAttachApiRef:ue}=e,z=t.strings,de=p(()=>T.value.some(e=>!e.ephemeral&&e.role!==`system`)).value,fe;return fe=P?null:u?_(h,{children:[m&&m!==`ai-agent`?g(fs,{controlMode:m,operatorInitials:v,operatorAvailable:y,onCancelOperatorRequest:S,strings:z}):null,!d&&m===`ai-agent`&&g(ss,{suggestions:D,onPick:ie,disabled:f}),g(fa,{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,isStreaming:d,active:e.composerActive&&l===`chat`,isPreparing:f,operatorRequestEnabled:b,canRequestOperator:de,controlMode:m,onRequestOperator:x,onSend:ne,onStop:re,attachApiRef:ue},s)]}):g(ds,{label:z.conversationClosed,ctaLabel:z.startNewConversation,onNewConversation:j}),_(h,{children:[l===`history`?g(us,{strings:z,onBack:M,onClose:k,showClose:Ii(t.mode,c,t.actions)}):_(`header`,{class:`${Z}-header`,"data-testid":q.panelHeader,children:[A?g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:A,"aria-label":z.moduleBack,title:z.moduleBack,children:g(Kr,{})}):null,E?g(Vi,{agent:E,strings:z}):g(`h1`,{children:z.panelTitle}),g(Ca,{panelProps:e,variant:`chat`})]}),l===`history`?g(as,{transport:n,strings:z,locale:t.locale,persistence:a,onSelect:ee,onNewConversation:te}):_(h,{children:[g(ma,{visible:R,strings:z}),g(qo,{messagesSig:T,strings:z,responseMode:t.responseMode,showReasoning:t.showReasoning,showToolCalls:t.showToolCalls,showSources:t.showSources,enableMessageFeedback:t.enableMessageFeedback,onFeedback:L,loading:C,onLoadPreviousMessages:w,idle:!d&&!f&&u&&!P,controlMode:m,tool:se,onRetry:ce,form:P?{form:P,onSubmit:oe,onSkip:F}:null,formMarkers:ae,onFillForm:I}),fe,g(ms,{disclaimer:t.composerDisclaimer})]}),t.size.resize?.enabled?g(ji,{panelEl:le,resize:t.size.resize,position:t.position,initialSize:O,onSizeChange:N,strings:z}):null]})}function us({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(wr,{})}):null]})}function ds({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 fs({controlMode:e,operatorInitials:t,operatorAvailable:n,onCancelOperatorRequest:r,strings:i}){let a=ps(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 ps(e,t,n,r){return e===`operator`?r.chattingWithOperator.replace(`{operator}`,t??``):n===!1?r.noOperatorAvailable:r.connectingOperator}function ms({disclaimer:e}){return e?g(`div`,{class:`${Z}-composer-footer`,children:g(`div`,{class:`${Z}-disclaimer`,children:e})}):null}function hs({poweredBy:e}){return e?g(`div`,{class:`${Z}-poweredby-bar`,children:g(gs,{logoUrl:e.logoUrl,text:e.text,href:e.href})}):null}function gs({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 _s(e){let t=s(e);t.current=e;let n=s(null);return n.current??(n.current=vs(t)),n.current}function vs(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||!ys(r,a)||i(e)||!bs(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 ys(e,t){return e.kind===`after-messages`?t.messageCount()>=Number(e.param??0):e.kind!==`page-area`||t.pageArea()===e.param}function bs(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 xs(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(Ss,{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(Cs,{collapsed:a})})]}),a?null:_(h,{children:[o.length>0?g(`nav`,{class:`${t}-sidebar-section`,"data-section":`navigation`,children:g(ws,{items:o})}):null,s.length>0?g(`div`,{class:`${t}-sidebar-section`,"data-section":`link-cards`,children:g(Ts,{items:s})}):null,e.showConversations?g(`div`,{class:`${t}-sidebar-conversations`,children:g(as,{transport:e.transport,strings:e.strings,locale:e.locale,persistence:e.persistence,onSelect:e.onSelectConversation,onNewConversation:e.onNewConversation})}):null]})]})}function Ss({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 Cs({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 ws({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 Ts({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 Es=b.cssPrefix;function Ds(e){return _(`main`,{class:`${Es}-page-shell`,"data-sidebar-collapsed":e.sidebarCollapsed?`true`:`false`,children:[g(xs,{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:`${Es}-page-chat`,"aria-label":`Chat`,children:e.children})]})}const Os=e=>Object.fromEntries(e.map(e=>[e,[]]));function ks(e,t,n){return e.includes(t)?t:e.includes(n)?n:e[0]??``}function As(e,t,n){let r=[...new Set(t)],i=f({activeTab:ks(r,e,``),stacks:Os(r)});return{sig:i,reconcile(e,t){let a=[...new Set(e)],o=i.value,s=ks(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:ks(r,e,``),stacks:Os(r)}}}}const js=e=>e.stacks[e.activeTab]??[],Ms=e=>js(e).at(-1),Ns=e=>js(e).length===0,Ps={Icon:si},Fs=b.cssPrefix;function Is({title:e,actions:t}){return _(`header`,{class:`${Fs}-back-header`,"data-variant":`title`,children:[g(`span`,{class:`${Fs}-back-spacer`,"aria-hidden":`true`}),g(`h1`,{class:`${Fs}-back-title`,children:e}),t??g(`span`,{class:`${Fs}-back-spacer`,"aria-hidden":`true`})]})}function Ls({title:e,backLabel:t,onBack:n,actions:r,testid:i}){return _(`header`,{class:`${Fs}-back-header`,"data-testid":i,children:[g(`button`,{type:`button`,class:`${Fs}-icon-btn`,onClick:n,"aria-label":t,title:t,children:g(Kr,{})}),g(`h1`,{class:`${Fs}-back-title`,children:e}),r??g(`span`,{class:`${Fs}-back-spacer`,"aria-hidden":`true`})]})}function Rs(e,t){return e instanceof Gt&&e.status===429?t.errorRateLimited:t.errorGeneric}const zs=b.cssPrefix;function Bs({placeholder:e,onActivate:t}){return _(`button`,{type:`button`,class:`${zs}-home-search`,onClick:t,"data-testid":q.homeSearch,children:[g(`span`,{class:`${zs}-home-search-text`,children:e}),g(`span`,{class:`${zs}-home-search-icon`,"aria-hidden":`true`,children:g(ri,{})})]})}function Vs({placeholder:e,value:t,onInput:n}){return _(`div`,{class:`${zs}-home-search`,"data-input":`true`,children:[g(`input`,{type:`search`,class:`${zs}-home-search-input`,placeholder:e,value:t,onInput:e=>n(e.currentTarget.value),"data-testid":q.helpSearch}),g(`span`,{class:`${zs}-home-search-icon`,"aria-hidden":`true`,children:g(ri,{})})]})}const Hs=b.cssPrefix;function Us({title:e,subtitle:t,onClick:n,testid:r}){return _(`button`,{type:`button`,class:`${Hs}-list-row`,onClick:n,"data-testid":r,children:[_(`span`,{class:`${Hs}-list-row-body`,children:[g(`span`,{class:`${Hs}-list-row-title`,children:e}),t?g(`span`,{class:`${Hs}-list-row-sub`,children:t}):null]}),g(`span`,{class:`${Hs}-list-row-chevron`,"aria-hidden":`true`,children:g(kr,{})})]})}const Ws=b.cssPrefix;function Gs({tone:e=`info`,message:t,onRetry:n,strings:r}){return _(`div`,{class:`${Ws}-module-empty`,role:e===`error`?`alert`:`status`,"aria-live":`polite`,children:[g(`span`,{children:t}),n?g(`button`,{type:`button`,class:`${Ws}-module-retry`,onClick:n,children:r.errorRetry}):null]})}const Ks=b.cssPrefix,qs=L.scope(`help`),Js=(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 Ys(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 Xs(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 Zs(e,t){let n=t.toLowerCase().trim();return n?e.map(e=>({item:e,score:Math.max(Xs(n,e.title)*2,Xs(n,e.description??``))})).filter(e=>e.score>0).toSorted((e,t)=>t.score-e.score).map(e=>e.item):[]}function Qs({article:e,nav:t}){return g(Us,{title:e.title,subtitle:e.description,onClick:()=>Js(t,e),testid:Ci(q.helpArticle,e.id)})}function $s({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||(qs.warn(`listContent (help) failed`,{err:e}),p(Rs(e,t)),d(`error`))}),()=>{n=!0}},[e,l,b,a]);let S=o(()=>Zs(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(Gs,{message:t.helpSearchEmpty,strings:t}):g(`div`,{class:`${Ks}-help-card`,children:S.map(e=>g(Qs,{article:e,nav:r},e.id))}):u===`loading`?g(Gs,{message:t.helpLoading,strings:t}):u===`error`?g(Gs,{tone:`error`,message:f,onRetry:()=>x(e=>e+1),strings:t}):m.length===0?g(Gs,{message:t.helpEmpty,strings:t}):Ys(m).map(([e,t])=>_(`section`,{class:`${Ks}-help-group`,children:[e?g(`h2`,{class:`${Ks}-help-section-title`,children:e}):null,g(`div`,{class:`${Ks}-help-card`,children:t.map(e=>g(Qs,{article:e,nav:r},e.id))})]},e))}return _(`div`,{class:`${Ks}-module`,children:[g(Is,{title:t.helpTitle,actions:g(Ca,{panelProps:s,variant:`plain`})}),g(`div`,{class:`${Ks}-module-pad`,children:g(Vs,{placeholder:t.helpSearchPlaceholder,value:v,onInput:y})}),g(`div`,{class:`${Ks}-help-list`,children:C()})]})}const ec={Icon:Qr,Root:e=>g($s,{...e})},tc=b.cssPrefix;function nc({onClick:e,children:t,testid:n}){return e?g(`button`,{type:`button`,class:`${tc}-home-card`,"data-interactive":`true`,onClick:e,"data-testid":n,children:t}):g(`div`,{class:`${tc}-home-card`,"data-testid":n,children:t})}const Q=b.cssPrefix,rc=L.scope(`home`);function ic(e){let t=e.options.userContext?.name,n=e.config.greetingText?O(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 ac=(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 oc(e,t){return pn(e,t,t.type!==`upsert`||t.activity===!0)}function sc(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=>oc(t?[t]:[],e)[0]??null)});return t.listConversations({limit:m?50:1}).then(t=>{if(e)return;let r=i.reduce(oc,t.conversations);i=[],n=!1,u(r[0]??null)}).catch(t=>{e||(i=[],n=!1,rc.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&&rc.warn(`listContent (home) failed`,{err:t})),()=>{e=!0}},[t,p,o]);let v=ic(e),y=r.userAvatars??[],b=r.status,x=b?.text?O(n,b.text):n.homeStatus,S=r.contentBlockTitle?O(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(Bs,{placeholder:n.homeSearchPlaceholder,onActivate:()=>a.switchToLayout(`help`)}),l?g(nc,{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(nc,{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(Us,{title:e.title,subtitle:e.description,onClick:()=>ac(a,e),testid:Ci(q.homeContentRow,e.id)},e.id))})]}):null]})]})})}const cc={Icon:ai,Root:e=>g(sc,{...e})},lc=b.cssPrefix,uc=L.scope(`news`);function dc({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||(uc.warn(`listContent (news) failed`,{err:e}),f(Rs(e,t)),u(`error`))}),()=>{n=!0}},[e,s,h,a]);function y(){return l===`loading`?g(Gs,{message:t.newsLoading,strings:t}):l===`error`?g(Gs,{tone:`error`,message:d,onRetry:()=>v(e=>e+1),strings:t}):p.length===0?g(Gs,{message:t.newsEmpty,strings:t}):g(`div`,{class:`${lc}-news-list`,children:p.map(e=>_(`button`,{type:`button`,class:`${lc}-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:`${lc}-news-hero`,src:e.image,alt:``,loading:`lazy`}):null,_(`span`,{class:`${lc}-news-body`,children:[g(`span`,{class:`${lc}-news-title`,children:e.title}),e.description?g(`span`,{class:`${lc}-news-summary`,children:e.description}):null]})]},e.id))})}return _(`div`,{class:`${lc}-module`,children:[g(Is,{title:t.newsTitle,actions:g(Ca,{panelProps:o,variant:`plain`})}),g(`div`,{class:`${lc}-module-scroll`,children:y()})]})}const fc={chat:Ps,home:cc,help:ec,news:{Icon:oi,Root:e=>g(dc,{...e})}},pc=b.cssPrefix;function mc({modules:e,activeTab:t,strings:n,hasUnread:r,onSelect:i}){return g(`nav`,{class:`${pc}-tabbar`,role:`tablist`,"aria-label":n.panelTitle,children:e.map(e=>{let a=fc[e.layout].Icon,o=e.id===t,s=e.layout===`chat`&&r;return _(`button`,{type:`button`,role:`tab`,"aria-selected":o,class:`${pc}-tab`,onClick:()=>i(e.id),"data-testid":Ci(q.tab,e.id),children:[_(`span`,{class:`${pc}-tab-icon`,"aria-hidden":`true`,children:[g(a,{}),s?g(`span`,{class:`${pc}-tab-badge`,"data-testid":q.tabBadge,"aria-label":`Unread`}):null]}),g(`span`,{class:`${pc}-tab-label`,children:O(n,e.label)})]},e.id)})})}const hc=b.cssPrefix;function gc({url:e,title:t,strings:n,onBack:r,actions:i}){return _(`div`,{class:`${hc}-module`,children:[g(Ls,{title:t||n.moduleBack,backLabel:n.moduleBack,onBack:r,actions:i}),g(`iframe`,{class:`${hc}-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 _c=b.cssPrefix,vc=L.scope(`content`);function yc({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||(vc.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(Gs,{tone:`error`,message:a.errorGeneric,onRetry:v,strings:a}):u===null?g(Gs,{message:a.contentLoading,strings:a}):_(`article`,{class:`${_c}-content`,"data-testid":q.contentView,onClick:y,children:[u.image?g(`img`,{class:`${_c}-content-hero`,src:u.image,alt:``,loading:`lazy`}):null,u.description?g(`p`,{class:`${_c}-content-subtitle`,children:u.description}):null,g(uo,{text:u.content??``})]})}return _(`div`,{class:`${_c}-module`,children:[g(Ls,{title:u?.title||t||a.moduleBack,backLabel:a.moduleBack,onBack:s,actions:l,testid:q.backHeader}),g(`div`,{class:`${_c}-module-scroll`,"data-testid":q.contentScroll,children:b()})]})}const bc=b.cssPrefix;function xc({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=Ms(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}=ha({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&&(Ns(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:n.push,pop:n.pop,switchTab:n.switchTab,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(ls,{...e,composerActive:x,containerEl:m.current,dragOver:w,composerAttachApiRef:S});let n=fc[t.layout].Root;return n?g(n,{...k(t)}):null};return _(`div`,{ref:m,class:`${bc}-panel ${bc}-messenger`,role:`dialog`,"aria-modal":`false`,"aria-label":f.panelTitle,style:{position:`relative`},"data-testid":q.messengerHome,children:[_(`div`,{class:`${bc}-messenger-body`,children:[j.map(e=>g(`div`,{class:`${bc}-messenger-pane`,hidden:T||e.id!==b?.id,children:M(e)},e.id)),y?.kind===`iframe`?g(gc,{url:y.url,title:y.title,strings:f,onBack:n.pop,actions:A}):y?.kind===`content`?g(yc,{id:y.id,title:y.title,transport:e.transport,strings:f,bus:a,onBack:n.pop,actions:A}):null]}),E?g(mc,{modules:t,activeTab:v.activeTab,strings:f,hasUnread:o,onSelect:n.switchTab}):null,g(hs,{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 Sc=b.cssPrefix;function Cc({strings:e,onClose:t}){return _(`div`,{class:`${Sc}-panel ${Sc}-modules-empty`,role:`dialog`,"aria-label":e.panelTitle,"data-testid":q.modulesEmpty,children:[t?g(`button`,{type:`button`,class:`${Sc}-icon-btn ${Sc}-modules-empty-close`,onClick:t,"aria-label":e.close,title:e.close,children:g(wr,{})}):null,g(`p`,{class:`${Sc}-modules-empty-text`,children:e.modulesEmpty})]})}function wc(e,t,n,r){let i={role:n,text:r};e.emit(`message`,i),t.onMessage?.(i)}const Tc=L.scope(`hitl`);function Ec(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`?(Tc.warn(`decideTool: tool part not found`,{toolCallId:e}),!1):o.status!==`complete`||!Wn(o,s)||!t(c)?!1:(r(c),o.partsSig.value=[...o.partsSig.value],Hn(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){Tc.info(`toolResult`,{toolCallId:e}),c.emit(`toolResult`,{toolCallId:e});return}Tc.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 Dc({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 Oc(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??0,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=>{e.type===`data-control-state`&&l(nn(e.data))},[l]),requestOperator:r(async()=>{let e=n.value,r=await t.requestOperator();r&&n.value===e&&l(nn(r))},[t,n,l]),cancelOperatorRequest:r(async()=>{let e=n.value,r=await t.cancelOperatorRequest();r&&n.value===e&&l(nn(r))},[t,n,l])}}const kc=b.cssPrefix,Ac=`--${kc}-visual-viewport-height`,jc=`--${kc}-visual-viewport-top`;function Mc(e){let{hostElement:t,mode:n,panelSize:r,isOpen:o,surfaceReady:s,setIsOpen:c}=e;a(()=>{Tt(t,zt(n,r,o))},[t,o,r,n]),a(()=>{if(!o||!s)return;let e=t.ownerDocument.defaultView,n=e?.visualViewport,r=t.shadowRoot?.querySelector(`.${kc}-anchor`);if(!e||!n||!r)return;let i=()=>{r.style.setProperty(Ac,`${n.height}px`),r.style.setProperty(jc,`${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(Ac),r.style.removeProperty(jc)}},[t,o,s]),i(()=>{if(n!==`modal`||!o)return;let e=e=>{e.composedPath().some(e=>e instanceof HTMLElement&&e.classList.contains(`${kc}-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 Nc=L.scope(`reducer`);var Pc=class{constructor(e,t){this.messagesSig=e,this.onReconcileNeeded=t,V(this,`active`,null),V(this,`openTextParts`,new Map),V(this,`partSeq`,0),V(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=wn();n.id=e.id;let r=Ic(e)||Un(e)&&(e.status!==`streaming`||Hn(e)),i=e.status===`streaming`&&Hn(e)&&Vn(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,Lc(a,i),e.liveCatchUp&&Ic(e.shadow)&&(i.status===`streaming`||Un(i))?(e.probeContinuation=!1,e.continuationTailReplay=!1,e):(e.probeContinuation=Ic(i)||Un(i)&&(i.status!==`streaming`||Hn(i)),e.continuationTailReplay=i.status===`streaming`&&Hn(i)&&Vn(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;Lc(e,i);let a=Ic(e)&&Un(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=Gn(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=Gn(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&&!In(a))return this.attach(a),this.apply(e),null;let o=wn();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(!Vc(n,r,e))return s&&(Gc(n,r)&&(n.continuationStreaming=!0,this.messagesSig.value=[...this.messagesSig.value],this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id})),this.detach()),null;let t=Ic(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&&zc(n,r)){let e=this.promoteContinuation(!0);return s?(this.detach(),e):null}if(!o)return s&&this.detach(),null;if(s&&!In(n)&&In(r)){let e=this.promoteReplay();return this.detach(),e}if(!Rc(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),qc(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`:qc(t,{kind:`step-start`,id:`ss-${this.partSeq++}`});return;case`finish`:Nc.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`:Nc.warn(`stream error chunk`,{errorText:e.errorText}),t.status=`error`,t.errorText=e.errorText,this.bumpDone(t);return;case`abort`:Nc.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`:Yc(t,e);return;case`file`:qc(t,{kind:`file`,url:e.url,mediaType:e.mediaType});return;case`source-url`:Jc(t,{kind:`source`,sourceId:e.sourceId,url:e.url,title:e.title});return;case`source-document`:Jc(t,{kind:`source`,sourceId:e.sourceId,title:e.title,filename:e.filename,mediaType:e.mediaType});return;case`data-suggestions`:t.suggestions=rn(e.data);return;case`data-control-state`:t.operatorRoutedTurn=e.data.controlMode!==`ai-agent`;return;default:}}bumpDone(e){l(()=>{e.partsSig.value=[...e.partsSig.value],this.messagesSig.value.includes(e)&&(this.messagesSig.value=[...this.messagesSig.value])})}};const Fc={"input-streaming":0,"input-available":1,"approval-requested":2,"approval-responded":3,"output-available":4,"output-denied":4,"output-error":4};function Ic(e){return e.awaitingContinuation===!0||e.continuationStreaming===!0||e.retryAction?.kind===`continue-assistant`}function Lc(e,t){e.canceled&&(t.canceled=!0),!(!Ic(e)||t.status!==`streaming`&&!Un(t))&&(t.awaitingContinuation??(t.awaitingContinuation=e.awaitingContinuation),t.continuationStreaming??(t.continuationStreaming=e.continuationStreaming),t.retryAction===void 0&&(t.retryAction=e.retryAction))}function Rc(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)=>Bc(e,r[t]))}function zc(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)=>Bc(e,a[t]))}function Bc(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||!tr(t.toolName,e.toolName)||Fc[t.stateSig.value]<Fc[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 Vc(e,t,n){return Hc(e,n)||!Uc(e,t)?!0:n.type!==`finish`&&n.type!==`error`&&n.type!==`abort`?!1:Vn(t)||e.awaitingContinuation===!0&&n.type!==`finish`?!0:e.awaitingContinuation===!0&&t.partsSig.value.every(e=>e.kind===`step-start`)}function Hc(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&&Fc[n.stateSig.value]<4}function Uc(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)=>Wc(r[t+n],e)))}function Wc(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`||tr(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 Gc(e,t){if(Ic(e)||!Un(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 Kc(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 qc(e,a),a}function qc(e,t){e.partsSig.value=[...e.partsSig.value,t]}function Jc(e,t){e.partsSig.value.some(e=>e.kind===`source`&&e.sourceId===t.sourceId)||qc(e,t)}function Yc(e,t){switch(t.type){case`tool-input-start`:Kc(e,t.toolCallId,t.toolName,t.dynamic);return;case`tool-input-delta`:{let n=Kc(e,t.toolCallId);n.inputPartialSig.value+=t.inputTextDelta;return}case`tool-input-available`:{let n=Kc(e,t.toolCallId,t.toolName,t.dynamic);n.inputSig.value=t.input,n.stateSig.value=`input-available`;return}case`tool-input-error`:{let n=Kc(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=Kc(e,t.toolCallId,t.toolName);n.approvalSig.value={id:t.approvalId},n.stateSig.value=`approval-requested`;return}case`tool-output-available`:{let n=Kc(e,t.toolCallId,void 0,t.dynamic);n.outputSig.value=t.output,n.stateSig.value=`output-available`;return}case`tool-output-error`:{let n=Kc(e,t.toolCallId,void 0,t.dynamic);n.errorSig.value=t.errorText,n.stateSig.value=`output-error`;return}case`tool-output-denied`:{let n=Kc(e,t.toolCallId);n.stateSig.value=`output-denied`;return}default:return}}const Xc=1e3;async function Zc(e){let t=Xc,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=Xc),await e.sleep(t),t=Math.min(t*2,15e3)}}function Qc(e){let{activated:t,conversationReady:n,conversationIdSig:r,messagesSig:a,optionsRef:o,transport:c,visitorId:l,adoptControlStateChunk:u,settleSuggestions:d,recordConversationReply:f,transcriptRecoverySig:p,beginConversationTranscript:m,commitConversationTranscript:h,onReplyLanded:g,runCancellation:_,canContinueRef:v,setCanSend:y,feedback:b,bus:x,loadInitialThread:S,shouldReconcileOnConnect:C}=e,w=s(0);i(()=>{if(!t||!n||!r.value)return;let e=r.value,i=new AbortController,s=e=>{},T=new Pc(a,e=>s(e));c.primeIdentity(l,e);let E=!1,D=!1,O,k=!1,A,j=0,M=v.current,ee,te,N=Date.now(),ne,re=!1,ie=!1,P=(t,n,r)=>{if(!In(t))return;let i=a.value.findLast(e=>!e.ephemeral),s=t.serverMessageId??t.id;if(!(i&&(i.serverMessageId??i.id)!==s))return Fn(a.value,t,e,o.current.strings.newConversation,n,r)},ae=(e,t,n,r)=>{let i=P(e,t,r);if(!i)return;let a=`${e.serverMessageId??e.id}:${n}:${i.preview??``}`;a!==te&&(te=a,c.publishConversation({...i,hasUnread:!0},!0))},oe,F=()=>{oe&&(clearTimeout(oe.timer),oe=void 0)},I=()=>{let e=oe;if(!e)return;clearTimeout(e.timer),oe=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)=>{F(),oe={replyId:e.serverMessageId??e.id,canContinue:t,generation:n,activityAt:r,timer:setTimeout(I,120)}},ce=(e,t,n,r=Date.now(),i=!0)=>{F();let a=P(e,t,r);if(!a)return;let o=`${e.serverMessageId??e.id}:${n}`;o!==ee&&(ee=o,f(a),i&&ne&&(re=!0))},L=(e,t)=>{(e||!_.localSendRef.current)&&_.settle(t),e&&g()},le=(e,t=[],n=!1,r,i=M,s=j,c=Date.now(),l=!0)=>{let u=o.current;if(e.canceled){ce(e,i,s,c,l),L(n,r);return}let f=!0,p=e.status===`error`;switch(sr(e,p)){case`drop`:a.value=a.value.filter(t=>t!==e),f=!1;break;case`complete-operator-routed`:e.status=`complete`,n&&(b.play(`messageReceived`),wc(x,u,`assistant`,W(e)));break;case`error`:if(e.status=`error`,e.errorText=u.strings.errorGeneric,n){b.play(`error`);let e=Error(p?`stream error chunk`:`empty reply`);x.emit(`error`,e),u.onError?.(e)}break;case`complete`:e.status=`complete`,n&&(b.play(`messageReceived`),wc(x,u,`assistant`,W(e))),d(e,t);break}f&&ce(e,i,s,c,l),L(n,r)},R=t=>{if(i.signal.aborted||r.value!==e)return;if(u(t),t.type===`start`){I();let n=t.messageId===void 0?void 0:a.value.find(e=>e.serverMessageId===t.messageId||e.id===t.messageId);k=n!==void 0&&n.status!==`streaming`;let r=A?.senderRole===`visitor`?A.messageId:void 0;if(A={messageId:t.messageId,senderRole:t.messageMetadata?.senderRole},j+=1,N=Date.now(),te=void 0,E=t.messageMetadata?.senderRole===void 0,D=!1,O=E?t.messageMetadata?.runId:void 0,E){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=_.localSendRef.current&&(!n||o)&&i?.role===`assistant`&&i.status===`streaming`&&(o||i.serverMessageId===void 0&&i.partsSig.value.length===0);D=_.captureStart(e,t,s,r)}}let n=E&&(t.type===`finish`||t.type===`error`||t.type===`abort`),s=n?O:void 0,c=n&&(D||_.ownsLocalRun(s)),l=j,d=k;t.type===`finish`&&t.canContinue!==void 0&&(M=t.canContinue);let f=M;n&&(E=!1,D=!1,O=void 0);let p=T.applyResume(t),m=A?.messageId,h=m===void 0?void 0:a.value.find(e=>e.serverMessageId===m||e.id===m);k&&A?.senderRole!==`visitor`&&(p!==null||h?.status===`streaming`)&&(k=!1,d=!1);let g=!k&&(h?.role===`assistant`||h?.role===`operator`);if(t.type===`text-delta`&&g&&se(h,M,j,N),t.type===`text-end`&&(F(),g&&ae(h,M,j,N)),t.type===`finish`&&t.canContinue===!1&&y(!1),!p){n&&(c||!_.localSendRef.current)&&_.settle(s);return}if(p.role===`operator`){d||(b.play(`messageReceived`),wc(x,o.current,`operator`,W(p))),ce(p,f,l,N),k=!1,n&&(c||!_.localSendRef.current)&&_.settle(s);return}p.role===`assistant`&&(le(p,[],c,s,f,l,N),k=!1)},ue=async t=>{let n=j,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===j&&(t===void 0||s!==void 0&&(s.serverMessageId===t||s.id===t));if(!o.messages?.length)return!0;l&&(M=o.canContinue??M,y(M));let f=a.value,p=t===void 0?f.at(-1):f.find(e=>e.serverMessageId===t||e.id===t),{messages:m,changed:h}=Qn(f,Mn(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),v=p!==void 0&&g!==void 0&&(p.id===g.id||p.serverMessageId!==void 0&&p.serverMessageId===g.serverMessageId),b=g!==void 0&&g.status!==`streaming`&&(!v||p?.status===`streaming`),x=v&&p?.status===`streaming`?Date.now():g?.createdAt;return l&&b&&g.role===`assistant`?le(g,o.suggestions??[],_.localSendRef.current,void 0,o.canContinue??M,n,x,!1):l&&b&&g.role===`operator`?ce(g,o.canContinue??M,n,x,!1):l&&g?.role===`assistant`&&g.status!==`streaming`&&d(g,o.suggestions??[]),!0},z=new Set;s=({messageId:e})=>{if(z.has(e)||!a.value.some(t=>t.serverMessageId===e||t.id===e))return;z.add(e);let t=()=>z.delete(e);ue(e).then(t,t)};let de=(t=!1)=>{if(i.signal.aborted||r.value!==e){re=!1;return}if(ne){re=!0;return}let n=t?S(e)??(C()?ue():void 0):ue();if(!n)return;m(e),ne=n;let a=(t=!1)=>{if(ne===n){if(ne=void 0,re){re=!1,de();return}t&&h(e)}};n.then(a,()=>a(!1))},fe=p.subscribe(e=>{e<=w.current||(w.current=e,ie&&de())});return Zc({signal:i.signal,now:()=>performance.now(),sleep:e=>Wt(e,i.signal),connect:e=>c.connectResumeStream({signal:i.signal,onChunk:R,onConnected:e}),onInitialBoundaryReady:()=>{ie=!0,de(!0)},backfill:()=>de()}),()=>{i.abort(),F(),fe(),T.detach()}},[t,n,r,r.value,l,c,u,d,f,p,m,h,g,_,v,y,a,x,b,S,C])}function $c(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 el=L.scope(`send`);function tl(e,t,n,r,i,a=!0){e.publishConversation({...Fn(t,n,r,i,a),hasUnread:!1},!0)}function nl(e,t){return e.id===t.id||(e.serverMessageId??e.id)===(t.serverMessageId??t.id)}function rl(e){return e.findLast(e=>!e.ephemeral&&e.role!==`system`&&(e.role===`user`||e.status!==`streaming`||In(e)))}function il(e,t,n,r,i){let a=rl(t);!a||a.role!==`user`||!nl(a,n)||tl(e,t,a,r,i)}function al(e){return!(e instanceof Gt)||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 ol(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]:Nn(n.value,e),y=v[0],b=an({messages:v.map(Pn),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;if(u(r.conversationId),r.runId&&y?.role===`user`&&il(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;if(o){o.controlState&&d(o.controlState),f(o.canContinue??!0);let i=Mn(o.messages??[]),{messages:s,changed:c}=Qn(n.value,i);c&&(n.value=s);let l=i.findLast(e=>!e.ephemeral&&e.role!==`system`),u=rl(n.value);u&&l&&nl(u,l)&&tl(t,n.value,u,r.conversationId,a.strings.newConversation,o.canContinue??!0);let m=_?n.value.find(e=>e.id===_.id&&e.role===`assistant`&&e.status!==`streaming`):void 0;m&&p(m,o.suggestions??[]),!e&&_?.role===`assistant`&&n.value.includes(_)&&_.serverMessageId===void 0&&!In(_)&&(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])}}catch(c){if(i.value!==g)return;if(!m.reject(x)){y?.role===`user`&&il(t,n.value,y,g,a.strings.newConversation);return}let l=Rs(c,a.strings),u=al(c),h=r?.role===`assistant`?r:n.value.at(-1);if(e&&h?.role===`assistant`&&c instanceof Gt&&c.status===409){let e=h.serverMessageId??h.id,r=await t.loadConversation(g,{ids:[e]}).catch(()=>null);if(i.value!==g)return;if(r){r.controlState&&d(r.controlState),f(r.canContinue??!0);let t=Mn(r.messages??[]),i=t.find(t=>(t.serverMessageId??t.id)===e);if(i&&$n(h,i)){let{messages:i,changed:a}=Qn(n.value,t),o=i.find(t=>(t.serverMessageId??t.id)===e);if(a&&o&&o!==h){o.awaitingContinuation=!1,o.continuationStreaming=void 0,o.retryAction=null,n.value=i,o.status!==`streaming`&&p(o,r.suggestions??[]);return}}}if(!n.value.includes(h)||h.status!==`streaming`)return;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=wn();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]}s.play(`error`),o.emit(`error`,c),a.onError?.(c)}},[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=an({messages:[Pn(e)],conversationId:r,visitorId:l,userPrefs:c.loadUserPrefs()}),f=t.sendTurn(d);m.beginRouted(f,e.id);try{let o=await f;if(i.value!==r){m.rejectRouted(f);return}if(!m.acceptRoutedAck(f,o))return;u(o.conversationId),il(t,n.value,e,o.conversationId,a.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value]))}catch(c){let l=m.rejectRouted(f);if(i.value!==r)return;if(!l){il(t,n.value,e,r,a.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value]));return}if(e.status!==`pending`){il(t,n.value,e,r,a.strings.newConversation);return}el.debug(`operator-routed send failed`,{error:c});let u=c instanceof Error?c:Error(String(c));e.status=`error`,e.errorText=Rs(c,a.strings),e.retryAction=al(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)}},[t,n,a,o,s,c,l,u,h,m])}}const sl=L.scope(`unread`);function cl(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=>sl.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 ll=L.scope(`settings`);function ul(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=>ll.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=ke(d,t.availableLocales,t.defaultLocale);return i(()=>{a.setLocale(v)},[a,v]),i(()=>{s.dir=D(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=>{ll.info(`localeChange`,{locale:e}),f(e),_({locale:e}),l.emit(`localeChange`,e)},[_,l]),handleThemeChange:r(e=>{ll.info(`themeChange`,{mode:e}),m(e),s.dataset.theme=e,_({themeMode:e}),l.emit(`themeChange`,e)},[s,_,l]),handleTextSizeChange:r(e=>{ll.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;ll.info(`soundToggle`,{muted:e}),l.emit(`soundToggle`,{muted:e})},[o,l])}}const $=L.scope(`app`),dl=b.cssPrefix;function fl(e,t){return Tn({...e,text:O(t,e.text)})}function pl({options:e,hostElement:t,bus:n}){let[u]=c(()=>dt(e.widgetId,e.storage,e.aiAgentDeploymentId)),[d,f]=c(()=>u.getVisitorId()),h=u.loadUserPrefs(),v=m(u.loadConversationId()),y=s(v.value!==void 0),b=m(v.value??``),x=m([]),[S,C]=c(!1),w=s(),[T,E]=c([]);function D(){let t=e.modules.list,n=new Set(t.map(e=>e.id)),r=u.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=u.loadActiveModule()??t[0]??``;j.current=As(n,n?[...t,n]:t,e=>u.saveActiveModule(e))}let M=j.current,ee=p(()=>M.sig.value.activeTab).value,te=p(()=>v.value).value,[N,ne]=c(!1),[re,ie]=c(null),[P,ae]=c(!1),oe=e.mode===`standalone`||e.mode===`inline`,F=s(Vt(e,Ht(),u.loadPanelOpen(),u.loadPanelSize())),[I,se]=c(F.current.panelOpen),[ce,L]=c(F.current.panelOpen),le=s(),R=s(),ue=s(!1),z=s(void 0);i(()=>{I&&L(!0)},[I]);let de=s(!1),[fe,pe]=c(!1),{dismissed:me,dismissCallout:he}=Dc({callout:e.launcher.callout,persistence:u}),ge=e.launcher.callout?.persistent??!0,_e=r(()=>{$.info(`calloutDismiss`),n.emit(`calloutDismiss`,void 0),he()},[n,he]),[ve,ye]=c(F.current.panelSize),be=s(!1),[xe,Se]=c(`chat`),Ce=s(()=>!1);Ce.current=()=>I&&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,Me]=c(!1),[Ne,Pe]=c(null),[Fe,Ie]=c([]),Re=s(e.strings),ze=s(e);ze.current=e;let[Ve,He]=c(void 0),[Ue,We]=c(void 0),[Ge,Ke]=c(()=>u.loadSidebarCollapsed()??!1),[qe,Je]=c({}),[B]=c(()=>new yn({agentApiBaseUrl:e.agentApiBaseUrl,dataApiBaseUrl:e.dataApiBaseUrl,auth:Ut({publicKey:e.publicKey,aiAgentDeploymentId:e.aiAgentDeploymentId,publicKeyHeader:`x-public-key`}),endpoints:e.endpoints})),[Ye]=c(()=>new xr(e.sound,e.haptics)),Xe=$c({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:lt,handleSoundToggle:ut}=ul({options:e,persistence:u,transport:B,feedback:Ye,hostElement:t,bus:n}),{controlModeSig:ft,assignedOperatorInitialsSig:pt,operatorAvailableSig:mt,applyControlState:ht,adoptControlStateChunk:gt,requestOperator:_t,cancelOperatorRequest:vt}=Oc({transport:B,conversationIdSig:v}),{hasUnreadSig:yt,transcriptRecoverySig:bt,markVisibleConversationRead:xt,beginConversationTranscript:St,commitConversationTranscript:Ct,isConversationTranscriptCommitted:wt,recordConversationReply:Tt}=cl({transport:B,options:e,conversationIdSig:v,isConversationVisibleRef:Ce,activated:ce,conversationReady:N});i(()=>{xt()},[ee,I,xe,te,xt]),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,!u.loadPanelSize()&&ye(Bt(e.mode,e.size,Ht())))},[e.mode,e.size,u]),i(()=>{if(!N||de.current)return;de.current=!0;let t=Vt(e,Ht(),u.loadPanelOpen(),u.loadPanelSize());se(t.panelOpen),ye(t.panelSize)},[N,e,u]);let Et=s(null);i(()=>{N&&M.reconcile(e.modules.list.map(e=>e.id),D())},[N,e.modules.list,M]);let Dt=r(e=>{!e||e.length===0||(x.value=e.map(e=>fl(e,Re.current)))},[x]),Ot=s(null),kt=r(async e=>{try{let{formSubmissions:t}=await(e?B.bootstrap(e):Ot.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:$t(e.createdAt),values:e.values}))}catch(e){return $.debug(`bootstrap failed — no form markers (non-fatal)`,{err:e}),[]}},[B]),At=s(0),jt=s(0),Mt=r((e,t)=>{if(e===v.value)return;let r=v.value;jt.current++,C(!1),r&&(u.saveDraft(e,u.loadDraft(r)),u.saveDraft(r,``)),v.value=e,u.saveConversationId(e),B.primeIdentity(void 0,e),$.info(`conversation rebound`,{previous:r,current:e,reason:t}),r&&n.emit(`conversationRebound`,{previous:r,current:e,...t?{reason:t}:{}})},[n,v,u,B]),Nt=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[...(z.current?.messages??[]).map(e=>{let t=fl(e,Re.current);return t.createdAt=r,t}),...e]},[]),Pt=r(async e=>{let t=jt.current,r=()=>t!==jt.current||v.value!==e;R.current===e&&(R.current=void 0),C(!0);try{let[t,n]=await Promise.all([B.loadConversation(e),kt()]);if(r())return!1;let i=Mn(t.messages??[]);E(n);let a=Nt(Zn(i,x.value),n);if(x.value=a,R.current=a.some(e=>e.role===`user`)?void 0:e,i.length>0||t.controlState!==void 0){Te(t.canContinue??!0),ht(nn(t.controlState));let e=i.findLast(e=>e.role===`assistant`&&!e.ephemeral);Ie(e?.suggestions??t.suggestions??[])}return!0}catch(t){return r()?!1:($.warn(`loadThread failed; keeping conversation active`,{err:t,conversationId:e}),n.emit(`error`,t),ze.current.onError?.(t),!1)}finally{r()||C(!1)}},[B,kt,x,v,Nt,n]),V=r(e=>{if(le.current===e)return le.current=void 0,Pt(e)},[Pt]),Ft=r(()=>{if(w.current)return Promise.resolve(void 0);let t=v.value,r=x.value.find(e=>!e.ephemeral),i=r?.serverMessageId??r?.id;if(!t||!i)return Promise.resolve(void 0);let a=jt.current,o={};return w.current=o,(async()=>{try{let e=await B.loadConversation(t,{beforeId:i});if(w.current!==o||jt.current!==a||v.value!==t)return;if(e.messages.length===0)return!1;let n=e.messages.map(kn),r=x.value,s=Kn(r,n);if(s!==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=s}return!0}catch(r){if(w.current!==o||jt.current!==a||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===o&&(w.current=void 0)}})()},[n,v,T,x,e,B]),It=r(async({newConversation:t})=>{let r=++At.current,i=()=>r!==At.current,a=v.value,o=t||!a?ct():a;o!==a&&(jt.current++,C(!1),l(()=>{v.value=o,b.value=o}),u.saveConversationId(o)),B.primeIdentity(d,o);let s;try{s=await B.handshake({visitorId:d,conversationId:o,userPrefs:u.loadUserPrefs(),locale:Ze})}catch(r){if(i())return;n.emit(`error`,r),e.onError?.(r),t||ne(!0);return}if(i())return;if(s.visitorId&&s.visitorId!==d&&($.info(`visitor rebound`,{previous:d,current:s.visitorId,reason:s.rebind?.visitorId}),u.setVisitorId(s.visitorId),f(s.visitorId),n.emit(`visitorRebound`,{previous:d,current:s.visitorId,reason:s.rebind?.visitorId})),s.conversationId!==o&&Mt(s.conversationId,s.rebind?.conversationId),s.agent&&Pe(s.agent),ht(nn(s.controlState)),e.mode===`page`&&(s.site&&Lt(s.site)?He(s.site):s.site&&$.warn(`invalid site config, using fallback`,{site:s.site}),s.blocks&&Rt(s.blocks)?We(s.blocks):s.blocks&&$.warn(`invalid blocks config, using fallback`,{blocks:s.blocks})),s.userPrefs&&!t&&(u.saveUserPrefs(s.userPrefs),s.userPrefs.locale&&tt(s.userPrefs.locale),s.userPrefs.soundMuted!==void 0&&Ye.setMuted(s.userPrefs.soundMuted),s.userPrefs.themeMode&&nt(s.userPrefs.themeMode),s.userPrefs.textSize&&rt(s.userPrefs.textSize)),z.current=s.welcome,t||n.emit(`handshake`,s),s.welcome?.suggestions){let e=Re.current;Ie(s.welcome.suggestions.map(t=>({...t,label:O(e,t.label),...t.text===void 0?{}:{text:O(e,t.text)}})))}let c=!t&&a&&s.conversationId===a;y.current=!!c,c?ue.current||(le.current=s.conversationId):(R.current=s.conversationId,Dt(s.welcome?.messages),Ct(s.conversationId)),t||ne(!0)},[B,d,u,e,n,v,b,Ye,Dt,Ze,Mt,Ct]),zt=JSON.stringify(e.userContext??null);i(()=>{let t=Object.keys(qe).length?{...qe,...e.userContext}:e.userContext;B.setContext(t,ml(e.pageContext))},[B,zt,JSON.stringify(e.pageContext??null),JSON.stringify(qe)]);let Wt=r((e,t=[])=>Ie(e.suggestions??t),[]);i(()=>(B.primeIdentity(d,v.value),It({newConversation:!1}),()=>{At.current++,jt.current++}),[]),i(()=>{!ce||!N||ue.current||(ue.current=!0,Ot.current=B.bootstrap(),(async()=>{try{let e=await Ot.current;ie(Le((e??{forms:[]}).forms,et))}catch(e){$.debug(`bootstrap failed — treating as no forms`,{err:e})}finally{ae(!0)}})(),le.current===v.value&&C(!0))},[ce,N]);let Gt=s(null);i(()=>{if(!ce||!N)return;if(Gt.current===null){Gt.current=et;return}if(Gt.current===et)return;Gt.current=et;let e=!1;return B.bootstrap().then(t=>{e||ie(Le((t??{forms:[]}).forms,et))}).catch(e=>$.debug(`forms re-localize failed — keeping current copy`,{err:e})),()=>{e=!0}},[ce,N,et,B]);let Kt=s(zt);i(()=>{!N||Kt.current===zt||(Kt.current=zt,It({newConversation:!1}))},[zt,N,It]),Mc({hostElement:t,mode:e.mode,panelSize:ve,isOpen:I,surfaceReady:N,setIsOpen:se});let{sendAiTurn:qt,sendRoutedTurn:Jt}=ol({transport:B,messagesSig:x,conversationIdSig:v,options:e,bus:n,feedback:Ye,persistence:u,visitorId:d,adoptConversationId:Mt,applyControlState:ht,setCanSend:Te,settleSuggestions:Wt,runCancellation:Xe}),{toolInteraction:Yt}=Ec({streaming:De,controlModeSig:ft,messagesSig:x,sendAiTurn:qt,bus:n,humanInLoop:e.features.humanInLoop}),Xt=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]),Zt=()=>x.value.reduce((e,t)=>e+ +(t.role===`user`),0),Qt=e.forms.list.length>0?e.forms:re??e.forms,H=_s({forms:Qt,persistence:u,userContext:()=>e.userContext,messageCount:Zt,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,u.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})}}),en=p(()=>H.activeForm.value);Qc({activated:ce,conversationReady:N,conversationIdSig:v,messagesSig:x,optionsRef:ze,transport:B,visitorId:d,adoptControlStateChunk:gt,settleSuggestions:Wt,recordConversationReply:Tt,transcriptRecoverySig:bt,beginConversationTranscript:St,commitConversationTranscript:Ct,onReplyLanded:r(()=>H.fire(`after-messages`),[H]),runCancellation:Xe,canContinueRef:Ee,setCanSend:Te,feedback:Ye,bus:n,loadInitialThread:V,shouldReconcileOnConnect:r(()=>y.current||x.value.some(e=>!e.ephemeral&&e.role===`user`),[x])}),i(()=>{H.refresh()},[Qt,H]);let tn=e.pageContext?.area?String(e.pageContext.area):void 0,rn=p(()=>x.value.length);i(()=>{N&&P&&H.fire(`pre-chat`)},[N,P,H]),i(()=>{P&&!we&&H.fire(`conversation-closed`)},[P,we,H]),i(()=>{N&&P&&tn&&H.fire(`page-area`)},[N,P,tn,H]);let an=o(()=>{let e=Qt.list.flatMap(e=>e.triggers).filter(e=>e.kind===`idle`).map(e=>Number(e.param));return e.length?Math.min(...e)*1e3:0},[Qt]);i(()=>{if(!an||!I)return;let e=setTimeout(()=>H.fire(`idle`),an);return()=>clearTimeout(e)},[an,I,H,rn.value]);let on=r(async(t,r)=>{if(Ae.current)return!1;let i=v.value,a=ft.value!==`ai-agent`;if($.info(`send`,{textLen:t.length,attachments:r.length,streaming:ke.current,routedToOperator:a}),ke.current&&!a)return!1;let o=new AbortController,s={conversationId:i,controller:o};Ae.current=s,Me(!0);try{Ye.unlock();let a=await gl(B,r,o.signal,t=>{o.signal.aborted||($.warn(`upload failed`,{err:t}),n.emit(`error`,t),e.onError?.(t))});if(o.signal.aborted||v.value!==i||!Ee.current||H.activeForm.value)return!1;let s=ft.value!==`ai-agent`;if(ke.current&&!s||!t&&a.length===0)return!1;n.emit(`send`,{text:t,attachmentCount:r.length}),Fe.length>0&&Ie([]),Ye.play(`messageSent`);let c=Cn(t,a);return wc(n,e,`user`,t),s?(x.value=[...x.value,c],Jt(c),!0):(x.value=[...x.value,c,wn()],qt({continueExisting:!1}),!0)}finally{Ae.current===s&&(Ae.current=null,Me(!1))}},[B,n,e,Fe.length,x,v,qt,Jt,ft]);i(()=>{let e=v.value;return()=>{let t=Ae.current;!t||t.conversationId!==e||(Ae.current=null,Me(!1),t.controller.abort())}},[v.value]),i(()=>{we&&!en.value||Ae.current?.controller.abort()},[en.value,we]);let sn=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]),U=r(e=>{if(De)return;let t=x.value,n=ar(t,e);if(n)switch($.info(`retry`,{kind:n.kind,messageId:n.messageId}),n.kind){case`continue-assistant`:if(ft.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],qt({continueExisting:!0,turn:e});return;case`resend-user`:{let r=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!r)return;if(r.status=`complete`,r.errorText=void 0,r.retryAction=void 0,ft.value!==`ai-agent`){x.value=e.role===`assistant`?t.filter(t=>t!==e):[...t],Jt(r);return}let i=wn();x.value=e.role===`assistant`?t.map(t=>t===e?i:t):[...t,i],qt({continueExisting:!1,turn:r});return}case`repeat-user`:{let e=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!e)return;let r=Cn(W(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]),ft.value!==`ai-agent`){x.value=[...t,r],Jt(r);return}x.value=[...t,r,wn()],qt({continueExisting:!1,turn:r});return}default:return n}},[De,x,ft,qt,Jt]),cn=r(()=>{if(Li(e.mode,ve)===`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`),se(!1),u.savePanelOpen(!1),n.emit(`close`,void 0),e.onClose?.()},[n,e,u,ve,H]),ln=r(()=>{$.info(`open`,{mode:e.mode}),Ye.unlock(),pe(!0),se(!0),u.savePanelOpen(!0),!me&&!ge&&_e(),setTimeout(()=>pe(!1),hl),n.emit(`open`,void 0),e.onOpen?.()},[n,e,Ye,u,me,ge,_e]),un=r(()=>{let e=x.value.some(e=>e.role===`user`);if(R.current===v.value&&!e&&we&&v.value){$.info(`clear → reusing empty conversation`,{conversationId:v.value}),x.value.length===0&&Dt(z.current?.messages);return}$.info(`clear → new conversation`,{wasStreaming:De}),n.emit(`clear`,void 0),Xe.settle(),y.current=!1,le.current=void 0,R.current=void 0,l(()=>{x.value=[],v.value=void 0,ht({controlMode:`ai-agent`,controlRevision:0})}),u.clearConversation(),Te(!0),E([]),Ie([]),It({newConversation:!0})},[De,x,v,u,It,n,we,Dt,Xe,ht]),dn=r(()=>{un(),Se(`chat`);let t=e.modules.list.find(e=>e.layout===`chat`)?.id;t&&M.switchTab(t)},[un,M,e]),fn=r(()=>{let e=ve===`expanded`?`normal`:`expanded`;$.info(`expand`,{from:ve,expanded:e===`expanded`}),ye(e),u.savePanelSize(e),n.emit(`expand`,e===`expanded`)},[n,ve,u]),pn=r(()=>{let e=ve===`fullscreen`?`normal`:`fullscreen`;$.info(`fullscreen`,{from:ve,fullscreen:e===`fullscreen`}),ye(e),u.savePanelSize(e),n.emit(`fullscreen`,e===`fullscreen`)},[n,ve,u]),mn=r(()=>{Se(e=>{let t=e===`history`?`chat`:`history`;return $.info(`toggleHistory`,{view:t}),n.emit(`toggleHistory`,{view:t}),t})},[n]),hn=r(()=>{Ke(e=>{let t=!e;return $.info(`sidebarToggle`,{collapsed:t}),u.saveSidebarCollapsed(t),n.emit(`sidebarToggle`,{collapsed:t}),t})},[u,n]),gn=r(e=>{$.info(`resize`,e),it({widgetSize:e}),n.emit(`resize`,e)},[it,n]),_n=r(async t=>{let r=t.conversationId;if(r===v.value&&wt(r)){$.info(`selectConversation`,{conversationId:r,cached:!0}),n.emit(`selectConversation`,{conversationId:r}),B.publishConversation(t),Se(`chat`);let e=k();e&&M.switchTab(e),Ct(r);return}let i=++At.current;jt.current++,C(!1);let a=()=>i!==At.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),kt(r)]);if(a())return;Xe.settle(),y.current=!0,le.current=void 0;let n=Mn(e.messages),i=e.conversationId!==v.value,o=i?n:Zn(n,x.value);R.current=o.some(e=>e.role===`user`)?void 0:e.conversationId,l(()=>{x.value=Nt(o,t),i&&(b.value=e.conversationId),v.value=e.conversationId}),E(t),u.saveConversationId(e.conversationId),B.primeIdentity(d,e.conversationId),e.agent&&Pe(e.agent),Te(e.canContinue),ht(nn(e.controlState));let s=o.findLast(e=>e.role===`assistant`&&!e.ephemeral);Ie(s?.suggestions??e.suggestions??[]),i?St(e.conversationId):Ct(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,u,kt,Nt,De,d,Xe,St,Ct,wt,M]),vn=s(null),bn=r(e=>{typeof e==`string`&&(P?H.fire(`manual`,e):vn.current=e)},[P,H]);i(()=>{!P||!vn.current||(H.fire(`manual`,vn.current),vn.current=null)},[P,H]);let xn=s({handleOpen:ln,handleClose:cn,handleExpand:fn,handleFullscreen:pn,openForm:bn});xn.current={handleOpen:ln,handleClose:cn,handleExpand:fn,handleFullscreen:pn,openForm:bn},a(()=>st(t,{open:()=>xn.current.handleOpen(),close:()=>xn.current.handleClose(),expand:()=>xn.current.handleExpand(),fullscreen:()=>xn.current.handleFullscreen(),openForm:e=>xn.current.openForm(e)}),[t]);let Sn=o(()=>Be(e,Ze,Qe,$e),[e,Ze,Qe,$e]);Re.current=Sn.strings;let Tn=o(()=>T.map(e=>{let t=Qt.list.find(t=>t.id===e.formId);return{...e,title:t?.title,form:t}}),[T,Qt]),En=e=>{_n(e)},Dn={options:Sn,transport:B,feedback:Ye,bus:n,persistence:u,conversationId:v.value??``,composerKey:b.value,composerApiRef:Et,view:xe,canSend:we,isStreaming:De,sendPreparing:je,composerActive:Sn.mode===`page`||Sn.mode===`inline`||Sn.mode===`standalone`||I,controlMode:ft.value,assignedOperatorInitials:pt.value,operatorAvailable:mt.value,operatorRequestEnabled:e.features.operatorRequest,onRequestOperator:_t,onCancelOperatorRequest:vt,loadingMessages:S,onLoadPreviousMessages:Ft,messagesSig:x,agent:Ne,suggestions:Fe,initialWidgetSize:h.widgetSize??null,onClose:cn,onClear:un,onExpand:fn,onFullscreen:pn,onSoundToggle:ut,onToggleHistory:mn,onSelectHistoryConversation:En,onNewConversation:dn,onLocaleChange:at,onThemeChange:ot,onTextSizeChange:lt,onWidgetSizeChange:gn,onSend:on,onStop:sn,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?on(r,[]):Et.current?.fill(r)},activeForm:en.value?.form??null,formMarkers:Tn,onFormSubmit:H.complete,onFormSkip:H.skip,onFormFill:e=>H.fire(`manual`,e),tool:Yt,onRetry:U,onMessageFeedback:Xt};if(!N)return null;let On=Sn.modules.list,An=e=>{let t=Fi(`close`,Sn.mode,e);return On.length===0?g(Cc,{strings:Sn.strings,onClose:t?cn:void 0}):On.length===1&&On[0]?.layout===`chat`?g(cs,{...Dn,panelSize:e}):g(xc,{panelProps:{...Dn,panelSize:e,onClose:t?cn:void 0},enabledModules:On,nav:M,bus:n,hasUnread:yt.value,onSelectConversation:En,onStartNewConversation:dn,onSetPanelSize:ye})};if(e.mode===`page`){let e=On.some(e=>e.layout===`chat`);return g(`div`,{class:`${dl}-anchor`,children:g(Ds,{site:Ve,blocks:Ue,transport:B,strings:Sn.strings,locale:Sn.locale,persistence:u,showConversations:e,onSelectConversation:En,onNewConversation:dn,sidebarCollapsed:Ge,onToggleSidebarCollapsed:hn,children:An(`fullscreen`)})})}if(oe){let t=e.mode===`standalone`?`fullscreen`:ve;return g(`div`,{class:`${dl}-anchor`,children:An(t)})}let jn=e.mode===`drawer`,Nn=e.mode!==`modal`&&!e.launcher.hidden&&(!I||fe),Pn=Nn&&!fe&&!me&&!jn?Sn.launcher.callout:null;return _(`div`,{class:`${dl}-anchor`,"data-launcher-size":Sn.launcher.size,children:[I||ce?g(`div`,{class:`${dl}-surface`,hidden:!I,children:An(ve)}):null,Nn?g(Ti,{onToggle:ln,launcher:Sn.launcher,strings:Sn.strings,leaving:fe,edgeTab:jn}):null,Pn?g(ki,{callout:Pn,launcherPosition:Sn.position,strings:Sn.strings,closeLabel:Sn.strings.close,onDismiss:_e}):null]})}function ml(e){let t=e?.url??(typeof location<`u`?location.href:void 0);if(!(!e&&!t))return{...e,...t?{url:t}:{}}}const hl=120;async function gl(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 _l=L.scope(`error-boundary`);var vl=class extends e{constructor(...e){super(...e),V(this,`state`,{crashed:!1})}componentDidCatch(e,t){_l.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 yl={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 bl(){let e=navigator;return e.globalPrivacyControl===!0||e.doNotTrack===`1`}function xl(){return location.origin+location.pathname}function Sl(){try{return document.referrer?new URL(document.referrer).origin:``}catch{return``}}function Cl(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||bl()||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`,x),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`,xl());let h=Sl();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(yl).map(t=>e.on(t,e=>o(t,yl[t]?.(e))));return()=>{for(let e of s)e();a.clear()}}function wl(e){let{bus:r,host:i,appRoot:a,persistence:o,reportError:s}=e,c=e.initialRaw,l,u=Ee(c),d=!0,f=()=>{u=Ee(l?He(c,l):c)},p=()=>{_t(i,vt(u.mode));let e=o.loadUserPrefs().themeMode;Et(i,e?{...u,themeMode:e}:u),d&&(Tt(i,Tl(u)),d=!1)},m=()=>{p(),n(t(vl,{onError:s},t(pl,{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=Cl(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 Tl(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}=Vt(e,Ht(),t.loadPanelOpen(),t.loadPanelSize());return zt(e.mode,r,n)}const El=L.scope(`hooks`),Dl=`*`,Ol=new Set;function kl(e,t,n){let r={widgetId:e,event:t,listener:n};return Ol.add(r),()=>{Ol.delete(r)}}function Al(e,t,n){let r=[...Ol];for(let i of r)if(Ml(i.widgetId,e.widgetId)&&(i.event===`*`||i.event===t))try{i.listener(e,t,n)}catch(e){El.warn(`hook listener threw`,{event:t,error:e})}}function jl(e,t){let n=[];for(let r of Nl)n.push(t.on(r,t=>{Al(e,r,t)}));return()=>{for(let e of n)e()}}function Ml(e,t){return e===`*`||e===t}const Nl=`open.close.expand.fullscreen.resize.message.send.stop.clear.selectConversation.suggestion.toggleHistory.formSubmit.toolResult.toolDecision.messageFeedback.contentView.contentOpen.contentSearch.contentRead.contentLinkClick.attach.removeAttachment.voiceStart.voiceStop.voiceCancel.localeChange.themeChange.textSizeChange.soundToggle.sidebarToggle.calloutDismiss.error.handshake.visitorRebound.conversationRebound`.split(`.`),Pl=new Map;function Fl(e){e.debug!==void 0&&I(e.debug);let t=L.scope(`mount`);t.info(`mount`,{widgetId:e.widgetId,publicKey:e.publicKey,mode:e.presentation?.mode});let r=Ee(e),i=r.widgetId,a=Pl.get(i);a&&(t.debug(`destroy existing instance at slot`,{widgetId:i}),a.destroy());let o=Tl(r),s=r.iframe?Ot({position:vt(r.mode)},r.position,o,r.mode,e.target??null):yt({position:vt(r.mode),target:e.target??null});s.hostElement.dataset.widgetId=i;let c=new Ft,l=dt(i,r.storage,r.aiAgentDeploymentId),u=wl({bus:c,host:s.hostElement,appRoot:s.appRoot,persistence:l,initialRaw:e,reportError:e=>{c.emit(`error`,e),u.getOptions().onError?.(e)}});u.render();let d=s.hostElement,f=null,p=e=>{e.debug!==void 0&&I(e.debug),u.patchUserOptions(e)},m={widgetId:i,open:()=>ot(d,`open`),close:()=>ot(d,`close`),expand:()=>ot(d,`expand`),openForm:e=>ot(d,`openForm`,e),on:(e,t)=>c.on(e,t),update:e=>{t.debug(`update`,{patch:e}),p(e)},setUserContext:e=>{t.debug(`setUserContext`,{keys:Object.keys(e)}),p({userContext:{...u.getUserOptions().userContext,...e}})},clearUserContext:()=>{t.debug(`clearUserContext`),p({userContext:void 0})},setPageContext:e=>{t.debug(`setPageContext`,{keys:Object.keys(e)}),p({pageContext:{...u.getUserOptions().pageContext,...e}})},clearPageContext:()=>{t.debug(`clearPageContext`),p({pageContext:void 0})},setDebug:e=>{I(e),t.info(`debug level set`,{level:se()})},debugLevel:()=>se(),onLog:e=>le(e),destroy:()=>{t.info(`destroy`,{widgetId:i}),f?.(),u.destroy(),c.clear(),n(null,s.appRoot),s.destroy(),Pl.get(i)===m&&Pl.delete(i)}};return f=jl(m,c),Pl.set(i,m),m}function Il(e){let t=e.widgetId??`default`,n=Pl.get(t);return n?(n.update(e),n):Fl(e)}function Ll(e){if(e!==void 0){Pl.get(e)?.destroy();return}let t=[...Pl.values()];for(let e of t)e.destroy()}function Rl(e=`default`){return Pl.get(e)??null}function zl(){return[...Pl.values()]}function Bl(e,t,n){return kl(e,t,n)}const Vl=x,Hl=b;export{Dl as HOOK_WILDCARD,Hl as brand,Ll as destroy,zl as getAllInstances,Rl as getInstance,Bl as hook,Il as init,Fl as mount,Tl as resolveInitialHostMode,Vl as version};
12
+ `).trim(),M=!S&&t!==`error`&&!v.value&&j.length>0,ee=A||M;return g(`div`,{class:`${X}-bubble-row`,"data-role":e.role,"data-testid":wi(q.messageBubble,e.serverMessageId??e.id),children:_(`div`,{class:`${X}-bubble-col`,children:[_(`div`,{class:`${X}-bubble`,children:[e.role===`operator`&&e.operatorInitials?g(`span`,{class:`${X}-bubble-author`,children:e.operatorInitials}):null,_(`div`,{class:`${X}-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`||Wn(e,o)),superseded:l,continuationStreaming:e.continuationStreaming===!0,tool:d},`${Go(r)}#${o}`)),D&&g(Ko,{}),t===`error`||v.value?_(`div`,{class:`${X}-error`,role:`alert`,children:[g(`span`,{children:e.errorText??n.errorGeneric}),f?g(`button`,{type:`button`,class:`${X}-error-retry`,onClick:()=>f(e),"data-testid":q.messageRetry,children:n.errorRetry}):null]}):null]})]}),O||ee?_(`div`,{class:`${X}-bubble-meta`,children:[O?g(`time`,{class:`${X}-bubble-time`,dateTime:O.iso,title:O.full,children:O.short}):null,ee?_(`div`,{class:`${X}-bubble-actions`,children:[A&&e.serverMessageId?g(go,{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:`${X}-msg-action`,"data-active":n?`true`:void 0,"aria-label":a,title:a,onClick:i,"data-testid":q.messageCopy,children:g(n?Wr:gi,{})})}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(fo,{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(vo,{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?Wa(e.toolName)?g(ko,{part:e,strings:t,active:r,superseded:i,continuationStreaming:a,onDecision:c.onDecision,onEdit:c.onEdit}):g(bo,{part:e,strings:t,active:r,superseded:i,continuationStreaming:a,onDecision:c.onDecision,onEdit:c.onEdit}):n?g(Lo,{part:e,strings:t,live:s}):null}function Wo({part:e,active:t,strings:n}){return _(`details`,{class:`${X}-reasoning`,"data-testid":q.reasoning,open:t,"data-active":t?`true`:void 0,children:[g(`summary`,{class:`${X}-reasoning-summary`,children:g(`span`,{class:`${X}-reasoning-label`,children:t?n.thinking:n.thoughts})}),g(`div`,{class:`${X}-reasoning-body`,children:g(fo,{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:`${X}-typing`,"data-testid":q.typingDots,"aria-hidden":`true`,children:[g(`span`,{}),g(`span`,{}),g(`span`,{})]})}function qo({label:e}){return _(`span`,{class:`${X}-loading`,role:`status`,children:[g(`span`,{class:`${X}-loading-spinner`,"aria-hidden":`true`}),g(`span`,{class:`${X}-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),ie=()=>ne.current||performance.now()-re.current<350,P=s(0),ae=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`},oe=e=>D(e.scrollHeight-e.scrollTop-e.clientHeight>240),F=e=>{P.current=performance.now(),e.scrollTop=e.scrollHeight,ae(e)},I=(e,t)=>{F(e);let n=t,r=0,i=()=>{N.current||ie()||(F(e),--n>0&&(r=requestAnimationFrame(i)))};return t>0&&(r=requestAnimationFrame(i)),()=>cancelAnimationFrame(r)},se=(e,t)=>{let n,r,i,a=-1,o=()=>{n.disconnect(),r.disconnect(),clearTimeout(i)},s=()=>{if(N.current||ie()||a>=0&&e.scrollTop<a-4)return o();F(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},ce=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 se(e,300)},[ce]);let L=s(0);i(()=>{let e=w.current,t=T.value,n=L.current;if(L.current=t.length,e&&te.current&&!j.current){if(t.slice(n).some(e=>e.role===`user`))return N.current=!1,I(e,3);t.some(e=>e.role===`user`)&&(N.current||ie()||e.scrollHeight-e.scrollTop-e.clientHeight<120&&F(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,I(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||ie()||e.scrollHeight-e.scrollTop-e.clientHeight<240&&F(e)};if(t.status!==`streaming`)return se(e,300);n();let r=new MutationObserver(n);return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>r.disconnect()},[T.value]);let R=x?.form.id,ue=!!x&&(S??[]).some(e=>e.formId===x.form.id);a(()=>{let e=w.current;!e||!R||N.current||T.value.some(e=>e.role===`user`)&&(ue?e.querySelector(`[data-testid="${q.formGate}"]`)?.scrollIntoView({block:`nearest`}):F(e))},[R,ue]),i(()=>{let e=w.current;if(!e)return;let t=()=>{oe(e),ae(e),performance.now()-P.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}),oe(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 z=()=>{let e=w.current;e&&(N.current=!1,F(e))},de=T.value.filter(e=>!e.ephemeral),fe=de[0],pe=fe?.serverMessageId??fe?.id,me=!!(m&&de.length>=50&&pe!==M),he=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&&pe&&ee(pe),r&&e&&(await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),e.scrollTop=n+e.scrollHeight-t,ae(e),oe(e))}finally{j.current=!1,A.current=!1,k(!1)}},ge=[],_e=``,ve=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(Ha,{form:x.form,strings:t,onSubmit:x.onSubmit,onSkip:x.onSkip},`gate:${e.formId}`):g(Ua,{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(),ge.push(be(t))};for(let e of T.value){if(e.role===`assistant`&&e.id!==ve&&ir(e))continue;xe(e.createdAt);let i=Xo(e.createdAt);i&&i!==_e&&(ge.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}`)),_e=i);let a=e.retryAction!==void 0||e.role===`assistant`&&e.id===ve?ar(T.value,e):void 0,s=a!==void 0&&(a.kind!==`continue-assistant`||v===`ai-agent`);ge.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===ve,superseded:e.id!==ve,tool:y,onRetry:h&&s&&(e.role===`user`||e.id===ve)?b:void 0,enableMessageFeedback:u,onFeedback:d},e.id))}for(let e of ye)ge.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,me?g(`div`,{class:`${Jo}-load-previous`,children:g(`button`,{type:`button`,onClick:he,disabled:O,"aria-busy":O,"data-testid":q.loadPreviousMessages,children:t.loadPreviousMessages})}):null,ge,x&&!ue?g(Ha,{form:x.form,strings:t,onSubmit:x.onSubmit,onSkip:x.onSkip}):null]}),E?g(`button`,{type:`button`,class:`${Jo}-jump`,onClick:z,"aria-label":t.scrollToBottom,title:t.scrollToBottom,"data-testid":q.scrollToBottom,children:g(Yr,{})}):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=L.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=hn(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=hn(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(Tr,{}),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":wi(q.historyItem,e.conversationId),children:[g(`span`,{class:`${l}-history-avatar`,"aria-hidden":`true`,children:g(Qr,{})}),_(`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":wi(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=zi(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}=ga({containerRef:o,onDrop:r(e=>{l&&c.current?.attachFromDrop(e)},[c,l]),disabled:!l});return Fi(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,composerAttachApiRef:c}),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,sendPreparing:f,controlMode:m,assignedOperatorInitials:v,operatorAvailable:y,operatorRequestEnabled:b,onRequestOperator:x,onCancelOperatorRequest:S,loadingMessages:C,onLoadPreviousMessages:w,messagesSig:T,agent:E,suggestions:D,initialWidgetSize:O,onClose:k,onBack:A,onClear:j,onToggleHistory:M,onSelectHistoryConversation:ee,onNewConversation:te,onWidgetSizeChange:N,onSend:ne,onStop:re,onSuggestion:ie,activeForm:P,formMarkers:ae,onFormSubmit:oe,onFormSkip:F,onFormFill:I,tool:se,onRetry:ce,onMessageFeedback:L,containerEl:le,dragOver:R,composerAttachApiRef:ue}=e,z=t.strings,de=p(()=>T.value.some(e=>!e.ephemeral&&e.role!==`system`)).value,fe;return fe=P?null:u?_(h,{children:[m&&m!==`ai-agent`?g(ms,{controlMode:m,operatorInitials:v,operatorAvailable:y,onCancelOperatorRequest:S,strings:z}):null,!d&&m===`ai-agent`&&g(ls,{suggestions:D,onPick:ie,disabled:f}),g(pa,{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,isStreaming:d,active:e.composerActive&&l===`chat`,isPreparing:f,operatorRequestEnabled:b,canRequestOperator:de,controlMode:m,onRequestOperator:x,onSend:ne,onStop:re,attachApiRef:ue},s)]}):g(ps,{label:z.conversationClosed,ctaLabel:z.startNewConversation,onNewConversation:j}),_(h,{children:[l===`history`?g(fs,{strings:z,onBack:M,onClose:k,showClose:Li(t.mode,c,t.actions)}):_(`header`,{class:`${Z}-header`,"data-testid":q.panelHeader,children:[A?g(`button`,{type:`button`,class:`${Z}-icon-btn`,onClick:A,"aria-label":z.moduleBack,title:z.moduleBack,children:g(qr,{})}):null,E?g(Hi,{agent:E,strings:z}):g(`h1`,{children:z.panelTitle}),g(Ta,{panelProps:e,variant:`chat`})]}),l===`history`?g(ss,{transport:n,strings:z,locale:t.locale,persistence:a,onSelect:ee,onNewConversation:te}):_(h,{children:[g(ha,{visible:R,strings:z}),g(Yo,{messagesSig:T,strings:z,responseMode:t.responseMode,showReasoning:t.showReasoning,showToolCalls:t.showToolCalls,showSources:t.showSources,enableMessageFeedback:t.enableMessageFeedback,onFeedback:L,loading:C,onLoadPreviousMessages:w,idle:!d&&!f&&u&&!P,controlMode:m,tool:se,onRetry:ce,form:P?{form:P,onSubmit:oe,onSkip:F}:null,formMarkers:ae,onFillForm:I}),fe,g(gs,{disclaimer:t.composerDisclaimer})]}),t.size.resize?.enabled?g(Mi,{panelEl:le,resize:t.size.resize,position:t.position,initialSize:O,onSizeChange:N,strings:z}):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(qr,{})}),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(wr,{})}):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":`Chat`,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:ci},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(qr,{})}),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 Kt&&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(ii,{})})]})}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(ii,{})})]})}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(kr,{})})]})}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=L.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:wi(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(Ta,{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:$r,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=L.scope(`home`);function oc(e){let t=e.options.userContext?.name,n=e.config.greetingText?O(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 hn(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?O(n,b.text):n.homeStatus,S=r.contentBlockTitle?O(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:Bi(e.name)})},e.name))}):null,g(Ta,{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(ci,{})}),_(`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(ai,{})}),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:wi(q.homeContentRow,e.id)},e.id))})]}):null]})]})})}const uc={Icon:oi,Root:e=>g(lc,{...e})},dc=b.cssPrefix,fc=L.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":wi(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(Ta,{panelProps:o,variant:`plain`})}),g(`div`,{class:`${dc}-module-scroll`,children:y()})]})}const mc={chat:Is,home:uc,help:nc,news:{Icon:si,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":wi(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:O(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=L.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(po,{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=zi(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}=ga({containerRef:m,onDrop:r(e=>{C&&S.current?.attachFromDrop(e)},[S,C]),disabled:!C});Fi(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:n.push,pop:n.pop,switchTab:n.switchTab,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(Ta,{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,composerAttachApiRef:S});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:n.switchTab}):null,g(_s,{poweredBy:d.poweredBy}),d.size.resize?.enabled&&!(b?.layout===`chat`&&!y)?g(Mi,{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(wr,{})}):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=L.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`||!Wn(o,s)||!t(c)?!1:(r(c),o.partsSig.value=[...o.partsSig.value],Hn(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=Wa(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=an(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(()=>{Et(t,Bt(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=L.scope(`reducer`);var Ic=class{constructor(e,t){this.messagesSig=e,this.onReconcileNeeded=t,V(this,`active`,null),V(this,`openTextParts`,new Map),V(this,`partSeq`,0),V(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=Tn();n.id=e.id;let r=Rc(e)||Un(e)&&(e.status!==`streaming`||Hn(e)),i=e.status===`streaming`&&Hn(e)&&Vn(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`||Un(i))?(e.probeContinuation=!1,e.continuationTailReplay=!1,e):(e.probeContinuation=Rc(i)||Un(i)&&(i.status!==`streaming`||Hn(i)),e.continuationTailReplay=i.status===`streaming`&&Hn(i)&&Vn(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)&&Un(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=Gn(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=Gn(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&&!In(a))return this.attach(a),this.apply(e),null;let o=Tn();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&&!In(n)&&In(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=on(e.data);return;case`data-control-state`:t.operatorRoutedTurn=e.data.controlMode!==`ai-agent`;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`&&!Un(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||!tr(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:Vn(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`||tr(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)||!Un(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,settleSuggestions:d,recordConversationReply:f,transcriptRecoverySig:p,beginConversationTranscript:m,commitConversationTranscript:h,onReplyLanded:g,runCancellation:_,canContinueRef:v,setCanSend:y,feedback:b,bus:x,loadInitialThread:S,shouldReconcileOnConnect:C}=e,w=s(0);i(()=>{if(!t||!n||!r.value)return;let e=r.value,i=new AbortController,s=e=>{},T=new Ic(a,e=>s(e));c.primeIdentity(l,e);let E=!1,D=!1,O,k=!1,A,j=0,M=v.current,ee,te,N=Date.now(),ne,re=!1,ie=!1,P=(t,n,r)=>{if(!In(t))return;let i=a.value.findLast(e=>!e.ephemeral),s=t.serverMessageId??t.id;if(!(i&&(i.serverMessageId??i.id)!==s))return Fn(a.value,t,e,o.current.strings.newConversation,n,r)},ae=(e,t,n,r)=>{let i=P(e,t,r);if(!i)return;let a=`${e.serverMessageId??e.id}:${n}:${i.preview??``}`;a!==te&&(te=a,c.publishConversation({...i,hasUnread:!0},!0))},oe,F=()=>{oe&&(clearTimeout(oe.timer),oe=void 0)},I=()=>{let e=oe;if(!e)return;clearTimeout(e.timer),oe=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)=>{F(),oe={replyId:e.serverMessageId??e.id,canContinue:t,generation:n,activityAt:r,timer:setTimeout(I,120)}},ce=(e,t,n,r=Date.now(),i=!0)=>{F();let a=P(e,t,r);if(!a)return;let o=`${e.serverMessageId??e.id}:${n}`;o!==ee&&(ee=o,f(a),i&&ne&&(re=!0))},L=(e,t)=>{(e||!_.localSendRef.current)&&_.settle(t),e&&g()},le=(e,t=[],n=!1,r,i=M,s=j,c=Date.now(),l=!0)=>{let u=o.current;if(e.canceled){ce(e,i,s,c,l),L(n,r);return}let f=!0,p=e.status===`error`;switch(sr(e,p)){case`drop`:a.value=a.value.filter(t=>t!==e),f=!1;break;case`complete-operator-routed`:e.status=`complete`,n&&(b.play(`messageReceived`),Ec(x,u,`assistant`,W(e)));break;case`error`:if(e.status=`error`,e.errorText=u.strings.errorGeneric,n){b.play(`error`);let e=Error(p?`stream error chunk`:`empty reply`);x.emit(`error`,e),u.onError?.(e)}break;case`complete`:e.status=`complete`,n&&(b.play(`messageReceived`),Ec(x,u,`assistant`,W(e))),d(e,t);break}f&&ce(e,i,s,c,l),L(n,r)},R=t=>{if(i.signal.aborted||r.value!==e)return;if(u(t),t.type===`start`){I();let n=t.messageId===void 0?void 0:a.value.find(e=>e.serverMessageId===t.messageId||e.id===t.messageId);k=n!==void 0&&n.status!==`streaming`;let r=A?.senderRole===`visitor`?A.messageId:void 0;if(A={messageId:t.messageId,senderRole:t.messageMetadata?.senderRole},j+=1,N=Date.now(),te=void 0,E=t.messageMetadata?.senderRole===void 0,D=!1,O=E?t.messageMetadata?.runId:void 0,E){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=_.localSendRef.current&&(!n||o)&&i?.role===`assistant`&&i.status===`streaming`&&(o||i.serverMessageId===void 0&&i.partsSig.value.length===0);D=_.captureStart(e,t,s,r)}}let n=E&&(t.type===`finish`||t.type===`error`||t.type===`abort`),s=n?O:void 0,c=n&&(D||_.ownsLocalRun(s)),l=j,d=k;t.type===`finish`&&t.canContinue!==void 0&&(M=t.canContinue);let f=M;n&&(E=!1,D=!1,O=void 0);let p=T.applyResume(t),m=A?.messageId,h=m===void 0?void 0:a.value.find(e=>e.serverMessageId===m||e.id===m);k&&A?.senderRole!==`visitor`&&(p!==null||h?.status===`streaming`)&&(k=!1,d=!1);let g=!k&&(h?.role===`assistant`||h?.role===`operator`);if(t.type===`text-delta`&&g&&se(h,M,j,N),t.type===`text-end`&&(F(),g&&ae(h,M,j,N)),t.type===`finish`&&t.canContinue===!1&&y(!1),!p){n&&(c||!_.localSendRef.current)&&_.settle(s);return}if(p.role===`operator`){d||(b.play(`messageReceived`),Ec(x,o.current,`operator`,W(p))),ce(p,f,l,N),k=!1,n&&(c||!_.localSendRef.current)&&_.settle(s);return}p.role===`assistant`&&(le(p,[],c,s,f,l,N),k=!1)},ue=async t=>{let n=j,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===j&&(t===void 0||s!==void 0&&(s.serverMessageId===t||s.id===t));if(o.messages.length===0)return!0;l&&(M=o.canContinue,y(M));let f=a.value,p=t===void 0?f.at(-1):f.find(e=>e.serverMessageId===t||e.id===t),{messages:m,changed:h}=Qn(f,Mn(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),v=p!==void 0&&g!==void 0&&(p.id===g.id||p.serverMessageId!==void 0&&p.serverMessageId===g.serverMessageId),b=g!==void 0&&g.status!==`streaming`&&(!v||p?.status===`streaming`),x=v&&p?.status===`streaming`?Date.now():g?.createdAt;return l&&b&&g.role===`assistant`?le(g,g.suggestions??[],_.localSendRef.current,void 0,o.canContinue,n,x,!1):l&&b&&g.role===`operator`?ce(g,o.canContinue,n,x,!1):l&&g?.role===`assistant`&&g.status!==`streaming`&&d(g,g.suggestions??[]),!0},z=new Set;s=({messageId:e})=>{if(z.has(e)||!a.value.some(t=>t.serverMessageId===e||t.id===e))return;z.add(e);let t=()=>z.delete(e);ue(e).then(t,t)};let de=(t=!1)=>{if(i.signal.aborted||r.value!==e){re=!1;return}if(ne){re=!0;return}let n=t?S(e)??(C()?ue():void 0):ue();if(!n)return;m(e),ne=n;let a=(t=!1)=>{if(ne===n){if(ne=void 0,re){re=!1,de();return}t&&h(e)}};n.then(a,()=>a(!1))},fe=p.subscribe(e=>{e<=w.current||(w.current=e,ie&&de())});return $c({signal:i.signal,now:()=>performance.now(),sleep:e=>Gt(e,i.signal),connect:e=>c.connectResumeStream({signal:i.signal,onChunk:R,onConnected:e}),onInitialBoundaryReady:()=>{ie=!0,de(!0)},backfill:()=>de()}),()=>{i.abort(),F(),fe(),T.detach()}},[t,n,r,r.value,l,c,u,d,f,p,m,h,g,_,v,y,a,x,b,S,C])}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=L.scope(`send`);function rl(e,t,n,r,i,a=!0){e.publishConversation({...Fn(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`||In(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 Kt)||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]:Nn(n.value,e),y=v[0],b=sn({messages:v.map(Pn),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;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;if(o){o.controlState&&d(o.controlState),f(o.canContinue);let i=Mn(o.messages),{messages:s,changed:c}=Qn(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&&!In(_)&&(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])}}catch(c){if(i.value!==g)return;if(!m.reject(x)){y?.role===`user`&&ol(t,n.value,y,g,a.strings.newConversation);return}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 Kt&&c.status===409){let e=h.serverMessageId??h.id,r=await t.loadConversation(g,{ids:[e]}).catch(()=>null);if(i.value!==g)return;if(r){r.controlState&&d(r.controlState),f(r.canContinue);let t=Mn(r.messages),i=t.find(t=>(t.serverMessageId??t.id)===e);if(i&&$n(h,i)){let{messages:r,changed:i}=Qn(n.value,t),a=r.find(t=>(t.serverMessageId??t.id)===e);if(i&&a&&a!==h){a.awaitingContinuation=!1,a.continuationStreaming=void 0,a.retryAction=null,n.value=r,a.status!==`streaming`&&p(a,a.suggestions??[]);return}}}if(!n.value.includes(h)||h.status!==`streaming`)return;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=Tn();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]}s.play(`error`),o.emit(`error`,c),a.onError?.(c)}},[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=sn({messages:[Pn(e)],conversationId:r,visitorId:l,userPrefs:c.loadUserPrefs()}),f=t.sendTurn(d);m.beginRouted(f,e.id);try{let o=await f;if(i.value!==r){m.rejectRouted(f);return}if(!m.acceptRoutedAck(f,o))return;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]))}catch(c){let l=m.rejectRouted(f);if(i.value!==r)return;if(!l){ol(t,n.value,e,r,a.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value]));return}if(e.status!==`pending`){ol(t,n.value,e,r,a.strings.newConversation);return}nl.debug(`operator-routed send failed`,{error:c});let u=c instanceof Error?c:Error(String(c));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)}},[t,n,a,o,s,c,l,u,h,m])}}const ll=L.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=hn(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=L.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=ke(d,t.availableLocales,t.defaultLocale);return i(()=>{a.setLocale(v)},[a,v]),i(()=>{s.dir=D(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 $=L.scope(`app`),pl=b.cssPrefix;function ml(e,t){return En({...e,text:O(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 D(){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,ie]=c(null),[P,ae]=c(!1),oe=e.mode===`standalone`||e.mode===`inline`,F=s(Ht(e,Ut(),d.loadPanelOpen(),d.loadPanelSize())),[I,se]=c(F.current.panelOpen),[ce,L]=c(F.current.panelOpen),le=s(),R=s(),ue=s(!1),z=s(void 0);i(()=>{I&&L(!0)},[I]);let de=s(!1),[fe,pe]=c(!1),{dismissed:me,dismissCallout:he}=kc({callout:e.launcher.callout,persistence:d}),ge=e.launcher.callout?.persistent??!0,_e=r(()=>{$.info(`calloutDismiss`),n.emit(`calloutDismiss`,void 0),he()},[n,he]),[ve,ye]=c(F.current.panelSize),be=s(!1),[xe,Se]=c(`chat`),Ce=s(()=>!1);Ce.current=()=>I&&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,Me]=c(!1),[Ne,Pe]=c(null),[Fe,Ie]=c([]),Re=s(e.strings),ze=s(e);ze.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 xn({agentApiBaseUrl:e.agentApiBaseUrl,dataApiBaseUrl:e.dataApiBaseUrl,auth:Wt({publicKey:e.publicKey,aiAgentDeploymentId:u,publicKeyHeader:`x-public-key`}),endpoints:e.endpoints})),[Ye]=c(()=>new xr(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:lt,handleSoundToggle:ut}=fl({options:e,persistence:d,transport:B,feedback:Ye,hostElement:t,bus:n}),{controlModeSig:ft,assignedOperatorInitialsSig:mt,operatorAvailableSig:ht,applyControlState:gt,adoptControlStateChunk:_t,requestOperator:vt,cancelOperatorRequest:yt}=Ac({transport:B,conversationIdSig:v}),{hasUnreadSig:bt,transcriptRecoverySig:xt,markVisibleConversationRead:St,beginConversationTranscript:Ct,commitConversationTranscript:wt,isConversationTranscriptCommitted:Tt,recordConversationReply:Et}=ul({transport:B,options:e,conversationIdSig:v,isConversationVisibleRef:Ce,activated:ce,conversationReady:N});i(()=>{St()},[ee,I,xe,te,St]),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(Vt(e.mode,e.size,Ut())))},[e.mode,e.size,d]),i(()=>{if(!N||de.current)return;de.current=!0;let t=Ht(e,Ut(),d.loadPanelOpen(),d.loadPanelSize());se(t.panelOpen),ye(t.panelSize)},[N,e,d]);let Dt=s(null);i(()=>{N&&M.reconcile(e.modules.list.map(e=>e.id),D())},[N,e.modules.list,M]);let Ot=r(e=>{!e||e.length===0||(x.value=e.map(e=>ml(e,Re.current)))},[x]),kt=s(null),At=r(async e=>{try{let{formSubmissions:t}=await(e?B.bootstrap(e):kt.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:en(e.createdAt),values:e.values}))}catch(e){return $.debug(`bootstrap failed — no form markers (non-fatal)`,{err:e}),[]}},[B]),jt=s(0),Mt=s(0),Nt=r(e=>{if(e===v.value)return;let t=v.value;Mt.current++,C(!1),t&&(d.saveDraft(e,d.loadDraft(t)),d.saveDraft(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]),Pt=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[...(z.current?.messages??[]).map(e=>{let t=ml(e,Re.current);return t.createdAt=r,t}),...e]},[]),Ft=r(async e=>{let t=Mt.current,r=()=>t!==Mt.current||v.value!==e;R.current===e&&(R.current=void 0),C(!0);try{let[t,n]=await Promise.all([B.loadConversation(e),At()]);if(r())return!1;let i=Mn(t.messages);E(n);let a=Pt(Zn(i,x.value),n);if(x.value=a,R.current=a.some(e=>e.role===`user`)?void 0:e,i.length>0||t.controlState!==void 0){Te(t.canContinue),t.controlState&&gt(t.controlState);let e=i.findLast(e=>e.role===`assistant`&&!e.ephemeral);Ie(e?.suggestions??[])}return!0}catch(t){return r()?!1:($.warn(`loadThread failed; keeping conversation active`,{err:t,conversationId:e}),n.emit(`error`,t),ze.current.onError?.(t),!1)}finally{r()||C(!1)}},[B,At,x,v,Pt,n]),V=r(e=>{if(le.current===e)return le.current=void 0,Ft(e)},[Ft]),It=r(()=>{if(w.current)return Promise.resolve(void 0);let t=v.value,r=x.value.find(e=>!e.ephemeral),i=r?.serverMessageId??r?.id;if(!t||!i)return Promise.resolve(void 0);let a=Mt.current,o={};return w.current=o,(async()=>{try{let e=await B.loadConversation(t,{beforeId:i});if(w.current!==o||Mt.current!==a||v.value!==t)return;if(e.messages.length===0)return!1;let n=e.messages.map(kn),r=x.value,s=Kn(r,n);if(s!==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=s}return!0}catch(r){if(w.current!==o||Mt.current!==a||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===o&&(w.current=void 0)}})()},[n,v,T,x,e,B]),Lt=r(async({newConversation:t})=>{let r=++jt.current,i=()=>r!==jt.current,a=v.value,o=t||!a?ct():a;o!==a&&(Mt.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&&Nt(s.conversationId),Pe(s.agent),e.mode===`page`&&(s.site&&Rt(s.site)?He(s.site):s.site&&$.warn(`invalid site config, using fallback`,{site:s.site}),s.blocks&&zt(s.blocks)?We(s.blocks):s.blocks&&$.warn(`invalid blocks config, using fallback`,{blocks:s.blocks}));let c=pt(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)),z.current=s.welcome,t||n.emit(`handshake`,s),s.welcome?.suggestions){let e=Re.current;Ie(s.welcome.suggestions.map(t=>({...t,label:O(e,t.label),...t.text===void 0?{}:{text:O(e,t.text)}})))}let u=!t&&a&&s.conversationId===a;y.current=!!u,u?ue.current||(le.current=s.conversationId):(R.current=s.conversationId,Ot(s.welcome?.messages),wt(s.conversationId)),t||ne(!0)},[B,f,d,e,n,v,b,Ye,Ot,Ze,Nt,wt]),Bt=JSON.stringify(e.userContext??null);i(()=>{let t=Object.keys(qe).length?{...qe,...e.userContext}:e.userContext;B.setContext(t,gl(e.pageContext))},[B,Bt,JSON.stringify(e.pageContext??null),JSON.stringify(qe)]);let Gt=r((e,t=[])=>Ie(e.suggestions??t),[]);i(()=>(B.primeIdentity(f,v.value),Lt({newConversation:!1}),()=>{jt.current++,Mt.current++}),[]),i(()=>{!ce||!N||ue.current||(ue.current=!0,kt.current=B.bootstrap(),(async()=>{try{let e=await kt.current;ie(Le((e??{forms:[]}).forms,et))}catch(e){$.debug(`bootstrap failed — treating as no forms`,{err:e})}finally{ae(!0)}})(),le.current===v.value&&C(!0))},[ce,N]);let Kt=s(null);i(()=>{if(!ce||!N)return;if(Kt.current===null){Kt.current=et;return}if(Kt.current===et)return;Kt.current=et;let e=!1;return B.bootstrap().then(t=>{e||ie(Le((t??{forms:[]}).forms,et))}).catch(e=>$.debug(`forms re-localize failed — keeping current copy`,{err:e})),()=>{e=!0}},[ce,N,et,B]);let qt=s(Bt);i(()=>{!N||qt.current===Bt||(qt.current=Bt,Lt({newConversation:!1}))},[Bt,N,Lt]),Pc({hostElement:t,mode:e.mode,panelSize:ve,isOpen:I,surfaceReady:N,setIsOpen:se});let{sendAiTurn:Jt,sendRoutedTurn:Yt}=cl({transport:B,messagesSig:x,conversationIdSig:v,options:e,bus:n,feedback:Ye,persistence:d,visitorId:f,adoptConversationId:Nt,applyControlState:gt,setCanSend:Te,settleSuggestions:Gt,runCancellation:Xe}),{toolInteraction:Xt}=Oc({streaming:De,controlModeSig:ft,messagesSig:x,sendAiTurn:Jt,bus:n,humanInLoop:e.features.humanInLoop}),Zt=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]),Qt=()=>x.value.reduce((e,t)=>e+ +(t.role===`user`),0),$t=e.forms.list.length>0?e.forms:re??e.forms,H=ys({forms:$t,persistence:d,userContext:()=>e.userContext,messageCount:Qt,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})}}),tn=p(()=>H.activeForm.value);el({activated:ce,conversationReady:N,conversationIdSig:v,messagesSig:x,optionsRef:ze,transport:B,visitorId:f,adoptControlStateChunk:_t,settleSuggestions:Gt,recordConversationReply:Et,transcriptRecoverySig:xt,beginConversationTranscript:Ct,commitConversationTranscript:wt,onReplyLanded:r(()=>H.fire(`after-messages`),[H]),runCancellation:Xe,canContinueRef:Ee,setCanSend:Te,feedback:Ye,bus:n,loadInitialThread:V,shouldReconcileOnConnect:r(()=>y.current||x.value.some(e=>!e.ephemeral&&e.role===`user`),[x])}),i(()=>{H.refresh()},[$t,H]);let nn=e.pageContext?.area?String(e.pageContext.area):void 0,rn=p(()=>x.value.length);i(()=>{N&&P&&H.fire(`pre-chat`)},[N,P,H]),i(()=>{P&&!we&&H.fire(`conversation-closed`)},[P,we,H]),i(()=>{N&&P&&nn&&H.fire(`page-area`)},[N,P,nn,H]);let an=o(()=>{let e=$t.list.flatMap(e=>e.triggers).filter(e=>e.kind===`idle`).map(e=>Number(e.param));return e.length?Math.min(...e)*1e3:0},[$t]);i(()=>{if(!an||!I)return;let e=setTimeout(()=>H.fire(`idle`),an);return()=>clearTimeout(e)},[an,I,H,rn.value]);let on=r(async(t,r)=>{if(Ae.current)return!1;let i=v.value,a=ft.value!==`ai-agent`;if($.info(`send`,{textLen:t.length,attachments:r.length,streaming:ke.current,routedToOperator:a}),ke.current&&!a)return!1;let o=new AbortController,s={conversationId:i,controller:o};Ae.current=s,Me(!0);try{Ye.unlock();let a=await vl(B,r,o.signal,t=>{o.signal.aborted||($.warn(`upload failed`,{err:t}),n.emit(`error`,t),e.onError?.(t))});if(o.signal.aborted||v.value!==i||!Ee.current||H.activeForm.value)return!1;let s=ft.value!==`ai-agent`;if(ke.current&&!s||!t&&a.length===0)return!1;n.emit(`send`,{text:t,attachmentCount:r.length}),Fe.length>0&&Ie([]),Ye.play(`messageSent`);let c=wn(t,a);return Ec(n,e,`user`,t),s?(x.value=[...x.value,c],Yt(c),!0):(x.value=[...x.value,c,Tn()],Jt({continueExisting:!1}),!0)}finally{Ae.current===s&&(Ae.current=null,Me(!1))}},[B,n,e,Fe.length,x,v,Jt,Yt,ft]);i(()=>{let e=v.value;return()=>{let t=Ae.current;!t||t.conversationId!==e||(Ae.current=null,Me(!1),t.controller.abort())}},[v.value]),i(()=>{we&&!tn.value||Ae.current?.controller.abort()},[tn.value,we]);let sn=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]),cn=r(e=>{if(De)return;let t=x.value,n=ar(t,e);if(n)switch($.info(`retry`,{kind:n.kind,messageId:n.messageId}),n.kind){case`continue-assistant`:if(ft.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],Jt({continueExisting:!0,turn:e});return;case`resend-user`:{let r=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!r)return;if(r.status=`complete`,r.errorText=void 0,r.retryAction=void 0,ft.value!==`ai-agent`){x.value=e.role===`assistant`?t.filter(t=>t!==e):[...t],Yt(r);return}let i=Tn();x.value=e.role===`assistant`?t.map(t=>t===e?i:t):[...t,i],Jt({continueExisting:!1,turn:r});return}case`repeat-user`:{let e=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!e)return;let r=wn(W(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]),ft.value!==`ai-agent`){x.value=[...t,r],Yt(r);return}x.value=[...t,r,Tn()],Jt({continueExisting:!1,turn:r});return}default:return n}},[De,x,ft,Jt,Yt]),ln=r(()=>{if(Ri(e.mode,ve)===`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`),se(!1),d.savePanelOpen(!1),n.emit(`close`,void 0),e.onClose?.()},[n,e,d,ve,H]),U=r(()=>{$.info(`open`,{mode:e.mode}),Ye.unlock(),pe(!0),se(!0),d.savePanelOpen(!0),!me&&!ge&&_e(),setTimeout(()=>pe(!1),_l),n.emit(`open`,void 0),e.onOpen?.()},[n,e,Ye,d,me,ge,_e]),un=r(()=>{let e=x.value.some(e=>e.role===`user`);if(R.current===v.value&&!e&&we&&v.value){$.info(`clear → reusing empty conversation`,{conversationId:v.value}),x.value.length===0&&Ot(z.current?.messages);return}$.info(`clear → new conversation`,{wasStreaming:De}),n.emit(`clear`,void 0),Xe.settle(),y.current=!1,le.current=void 0,R.current=void 0,l(()=>{x.value=[],v.value=void 0,gt({controlMode:`ai-agent`,controlRevision:0})}),d.clearConversation(),Te(!0),E([]),Ie([]),Lt({newConversation:!0})},[De,x,v,d,Lt,n,we,Ot,Xe,gt]),dn=r(()=>{un(),Se(`chat`);let t=e.modules.list.find(e=>e.layout===`chat`)?.id;t&&M.switchTab(t)},[un,M,e]),fn=r(()=>{let e=ve===`expanded`?`normal`:`expanded`;$.info(`expand`,{from:ve,expanded:e===`expanded`}),ye(e),d.savePanelSize(e),n.emit(`expand`,e===`expanded`)},[n,ve,d]),pn=r(()=>{let e=ve===`fullscreen`?`normal`:`fullscreen`;$.info(`fullscreen`,{from:ve,fullscreen:e===`fullscreen`}),ye(e),d.savePanelSize(e),n.emit(`fullscreen`,e===`fullscreen`)},[n,ve,d]),mn=r(()=>{Se(e=>{let t=e===`history`?`chat`:`history`;return $.info(`toggleHistory`,{view:t}),n.emit(`toggleHistory`,{view:t}),t})},[n]),hn=r(()=>{Ke(e=>{let t=!e;return $.info(`sidebarToggle`,{collapsed:t}),d.saveSidebarCollapsed(t),n.emit(`sidebarToggle`,{collapsed:t}),t})},[d,n]),gn=r(e=>{$.info(`resize`,e),it({widgetSize:e}),n.emit(`resize`,e)},[it,n]),_n=r(async t=>{let r=t.conversationId;if(r===v.value&&Tt(r)){$.info(`selectConversation`,{conversationId:r,cached:!0}),n.emit(`selectConversation`,{conversationId:r}),B.publishConversation(t),Se(`chat`);let e=k();e&&M.switchTab(e),wt(r);return}let i=++jt.current;Mt.current++,C(!1);let a=()=>i!==jt.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),At(r)]);if(a())return;Xe.settle(),y.current=!0,le.current=void 0;let n=Mn(e.messages),i=e.conversationId!==v.value,o=i?n:Zn(n,x.value);R.current=o.some(e=>e.role===`user`)?void 0:e.conversationId,l(()=>{x.value=Pt(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&&gt(e.controlState);let s=o.findLast(e=>e.role===`assistant`&&!e.ephemeral);Ie(s?.suggestions??[]),i?Ct(e.conversationId):wt(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,At,Pt,De,f,Xe,Ct,wt,Tt,M]),vn=s(null),yn=r(e=>{typeof e==`string`&&(P?H.fire(`manual`,e):vn.current=e)},[P,H]);i(()=>{!P||!vn.current||(H.fire(`manual`,vn.current),vn.current=null)},[P,H]);let bn=s({handleOpen:U,handleClose:ln,handleExpand:fn,handleFullscreen:pn,openForm:yn});bn.current={handleOpen:U,handleClose:ln,handleExpand:fn,handleFullscreen:pn,openForm:yn},a(()=>st(t,{open:()=>bn.current.handleOpen(),close:()=>bn.current.handleClose(),expand:()=>bn.current.handleExpand(),fullscreen:()=>bn.current.handleFullscreen(),openForm:e=>bn.current.openForm(e)}),[t]);let Sn=o(()=>Be(e,Ze,Qe,$e),[e,Ze,Qe,$e]);Re.current=Sn.strings;let Cn=o(()=>T.map(e=>{let t=$t.list.find(t=>t.id===e.formId);return{...e,title:t?.title,form:t}}),[T,$t]),En=e=>{_n(e)},Dn={options:Sn,transport:B,feedback:Ye,bus:n,persistence:d,conversationId:v.value??``,composerKey:b.value,composerApiRef:Dt,view:xe,canSend:we,isStreaming:De,sendPreparing:je,composerActive:Sn.mode===`page`||Sn.mode===`inline`||Sn.mode===`standalone`||I,controlMode:ft.value,assignedOperatorInitials:mt.value,operatorAvailable:ht.value,operatorRequestEnabled:e.features.operatorRequest,onRequestOperator:vt,onCancelOperatorRequest:yt,loadingMessages:S,onLoadPreviousMessages:It,messagesSig:x,agent:Ne,suggestions:Fe,initialWidgetSize:h.widgetSize??null,onClose:ln,onClear:un,onExpand:fn,onFullscreen:pn,onSoundToggle:ut,onToggleHistory:mn,onSelectHistoryConversation:En,onNewConversation:dn,onLocaleChange:at,onThemeChange:ot,onTextSizeChange:lt,onWidgetSizeChange:gn,onSend:on,onStop:sn,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?on(r,[]):Dt.current?.fill(r)},activeForm:tn.value?.form??null,formMarkers:Cn,onFormSubmit:H.complete,onFormSkip:H.skip,onFormFill:e=>H.fire(`manual`,e),tool:Xt,onRetry:cn,onMessageFeedback:Zt};if(!N)return null;let On=Sn.modules.list,An=e=>{let t=Ii(`close`,Sn.mode,e);return On.length===0?g(Tc,{strings:Sn.strings,onClose:t?ln:void 0}):On.length===1&&On[0]?.layout===`chat`?g(us,{...Dn,panelSize:e}):g(Cc,{panelProps:{...Dn,panelSize:e,onClose:t?ln:void 0},enabledModules:On,nav:M,bus:n,hasUnread:bt.value,onSelectConversation:En,onStartNewConversation:dn,onSetPanelSize:ye})};if(e.mode===`page`){let e=On.some(e=>e.layout===`chat`);return g(`div`,{class:`${pl}-anchor`,children:g(ks,{site:Ve,blocks:Ue,transport:B,strings:Sn.strings,locale:Sn.locale,persistence:d,showConversations:e,onSelectConversation:En,onNewConversation:dn,sidebarCollapsed:Ge,onToggleSidebarCollapsed:hn,children:An(`fullscreen`)})})}if(oe){let t=e.mode===`standalone`?`fullscreen`:ve;return g(`div`,{class:`${pl}-anchor`,children:An(t)})}let jn=e.mode===`drawer`,Nn=e.mode!==`modal`&&!e.launcher.hidden&&(!I||fe),Pn=Nn&&!fe&&!me&&!jn?Sn.launcher.callout:null;return _(`div`,{class:`${pl}-anchor`,"data-launcher-size":Sn.launcher.size,children:[I||ce?g(`div`,{class:`${pl}-surface`,hidden:!I,children:An(ve)}):null,Nn?g(Ei,{onToggle:U,launcher:Sn.launcher,strings:Sn.strings,leaving:fe,edgeTab:jn}):null,Pn?g(Ai,{callout:Pn,launcherPosition:Sn.position,strings:Sn.strings,closeLabel:Sn.strings.close,onDismiss:_e}):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=L.scope(`error-boundary`);var bl=class extends e{constructor(...e){super(...e),V(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`,x),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=Ee(c),d=!0,f=()=>{u=Ee(l?He(c,l):c)},p=()=>{vt(i,yt(u.mode));let e=o.loadUserPrefs().themeMode;Dt(i,e?{...u,themeMode:e}:u),d&&(Et(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}=Ht(e,Ut(),t.loadPanelOpen(),t.loadPanelSize());return Bt(e.mode,r,n)}const Ol=L.scope(`hooks`),kl=`*`,Al=new Set;function jl(e,t,n){let r={widgetId:e,event:t,listener:n};return Al.add(r),()=>{Al.delete(r)}}function Ml(e,t,n){let r=[...Al];for(let i of r)if(Pl(i.widgetId,e.widgetId)&&(i.event===`*`||i.event===t))try{i.listener(e,t,n)}catch(e){Ol.warn(`hook listener threw`,{event:t,error:e})}}function Nl(e,t){let n=[];for(let r of Fl)n.push(t.on(r,t=>{Ml(e,r,t)}));return()=>{for(let e of n)e()}}function Pl(e,t){return e===`*`||e===t}const Fl=`open.close.expand.fullscreen.resize.message.send.stop.clear.selectConversation.suggestion.toggleHistory.formSubmit.toolResult.toolDecision.messageFeedback.contentView.contentOpen.contentSearch.contentRead.contentLinkClick.attach.removeAttachment.voiceStart.voiceStop.voiceCancel.localeChange.themeChange.textSizeChange.soundToggle.sidebarToggle.calloutDismiss.error.handshake.conversationRebound`.split(`.`),Il=new Map;function Ll(e){if(!e.aiAgentDeploymentId)throw Error(`aiAgentDeploymentId is required`);e.debug!==void 0&&I(e.debug);let t=L.scope(`mount`);t.info(`mount`,{widgetId:e.widgetId,publicKey:e.publicKey,mode:e.presentation?.mode});let r=Ee(e),i=r.widgetId,a=Il.get(i);a&&(t.debug(`destroy existing instance at slot`,{widgetId:i}),a.destroy());let o=Dl(r),s=r.iframe?kt({position:yt(r.mode)},r.position,o,r.mode,e.target??null):bt({position:yt(r.mode),target:e.target??null});s.hostElement.dataset.widgetId=i;let c=new It,l=dt(i,r.storage,r.aiAgentDeploymentId),u=El({bus:c,host:s.hostElement,appRoot:s.appRoot,persistence:l,initialRaw:e,reportError:e=>{c.emit(`error`,e),u.getOptions().onError?.(e)}});u.render();let d=s.hostElement,f=null,p=e=>{e.debug!==void 0&&I(e.debug),u.patchUserOptions(e)},m={widgetId:i,open:()=>ot(d,`open`),close:()=>ot(d,`close`),expand:()=>ot(d,`expand`),openForm:e=>ot(d,`openForm`,e),on:(e,t)=>c.on(e,t),update:e=>{t.debug(`update`,{patch:e}),p(e)},setUserContext:e=>{t.debug(`setUserContext`,{keys:Object.keys(e)}),p({userContext:{...u.getUserOptions().userContext,...e}})},clearUserContext:()=>{t.debug(`clearUserContext`),p({userContext:void 0})},setPageContext:e=>{t.debug(`setPageContext`,{keys:Object.keys(e)}),p({pageContext:{...u.getUserOptions().pageContext,...e}})},clearPageContext:()=>{t.debug(`clearPageContext`),p({pageContext:void 0})},setDebug:e=>{I(e),t.info(`debug level set`,{level:se()})},debugLevel:()=>se(),onLog:e=>le(e),destroy:()=>{t.info(`destroy`,{widgetId:i}),f?.(),u.destroy(),c.clear(),n(null,s.appRoot),s.destroy(),Il.get(i)===m&&Il.delete(i)}};return f=Nl(m,c),Il.set(i,m),m}function Rl(e){if(!e.aiAgentDeploymentId)throw Error(`aiAgentDeploymentId is required`);let t=e.widgetId??`default`,n=Il.get(t);return n?(n.update(e),n):Ll(e)}function zl(e){if(e!==void 0){Il.get(e)?.destroy();return}let t=[...Il.values()];for(let e of t)e.destroy()}function Bl(e=`default`){return Il.get(e)??null}function Vl(){return[...Il.values()]}function Hl(e,t,n){return jl(e,t,n)}const Ul=x,Wl=b;export{kl as HOOK_WILDCARD,Wl as brand,zl as destroy,Vl as getAllInstances,Bl as getInstance,Hl as hook,Rl as init,Ll as mount,Dl as resolveInitialHostMode,Ul as version};
13
13
  //# sourceMappingURL=index.mjs.map