@helpai/elements 6.6.0 → 6.6.1

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,5 +1,5 @@
1
- import{Component as e,h as t,render as n}from"preact";import{batch as r,computed as i,effect as a,signal as o,useComputed as s,useSignal as c}from"@preact/signals";import{useCallback as l,useEffect as u,useId as d,useLayoutEffect as f,useMemo as p,useRef as m,useState as h}from"preact/hooks";import{Fragment as g,jsx as _,jsxs as v}from"preact/jsx-runtime";import*as y from"streaming-markdown";import{memo as b}from"preact/compat";const x=[`en`,`fr`,`es`,`ar`,`he`,`zh`];function S(e){let t=e?.split(`-`)[0]?.toLowerCase();return x.find(e=>e===t)??`en`}function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function w(e){return C(e)?e.id??e.key:void 0}function T(e,t){return C(e)&&C(t)?Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(e),...Object.keys(t)])].map(n=>[n,T(e[n],t[n])])):Array.isArray(e)&&Array.isArray(t)&&t.length>0&&t.every(e=>w(e)!==void 0)?e.map(e=>T(e,t.find(t=>w(t)===w(e)))):t==null||typeof t==`string`&&!t.trim()?e:t}function E(e,t){let n=t?.toLowerCase(),r=n?.split(`-`)[0],i=e.translations??[],a=i.find(e=>e.locale.toLowerCase()===n)??i.find(e=>e.locale.toLowerCase().split(`-`)[0]===r);if(!a)return e;let{locale:o,...s}=a;return T(e,s)}const D={attach:`Attach files`,file:`File`,attachmentMimeRejected:`{name} isn't a file type this chat accepts.`,attachmentTooLarge:`{name} is too large. Files can be up to {max} together.`,poweredBy:`Powered by {name}`,attachmentTooMany:`The attachment limit is {count}.`,attachmentUploadFailed:`{name} couldn't be uploaded.`,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`,dropZoneRejected:`These files can't be attached here`,errorGeneric:`Something went wrong`,errorRateLimited:`Too many requests — please try again in a moment.`,errorRateLimitedIn:`Too many requests — please try again in {seconds} s.`,errorOffline:`Can't reach the server. Check your connection and try again.`,errorServer:`Something went wrong on our side. Please try again.`,errorOriginNotAllowed:`This chat isn't set up for this website yet.`,errorMessageTooLong:`That message is too long. Shorten it and send it again.`,errorReconnecting:`Connection lost. Reconnecting…`,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`,launcherAsk:`Ask {name}`,micBlocked:`The microphone is blocked for this site, so voice input can't start.`,micStart:`Start voice input`,micStop:`Stop voice input`,moreActions:`More actions`,newConversation:`New chat`,panelTitle:`Chat`,popOut:`Open in new tab`,resizeHandle:`Drag to resize`,scrollToBottom:`Scroll to latest`,send:`Send`,queueMessage:`Queue message`,removeQueuedMessage:`Remove queued message`,removeAttachment:`Remove {name}`,suggestedReplies:`Suggested replies`,compactingContext:`Optimizing conversation context…`,soundOff:`Sound off`,soundOn:`Sound on`,talkToOperator:`Talk to a person`,connectingOperator:`Connecting you to a person…`,noOperatorAvailable:`No one's available right now — leave your details and we'll follow up.`,chattingWithOperator:`You're chatting with {operator}`,operatorBadgeTitle:`Live chat`,chatNotice:`You're chatting with an AI assistant.`,cancelOperatorRequest:`Keep chatting with the AI`,loginPrompt:`Log in for faster, more personalized support`,loginAction:`Log in`,loginRequired:`Log in to chat with us`,loginExpired:`Your login expired. Log in to continue this chat.`,loginExpiredGuest:`Your login expired. Log in to continue this chat, or start a new conversation as a guest.`,startAsGuest:`Start new conversation`,loggedInAs:`Logged in as {name}`,loggedIn:`Logged in`,dismissLoginPrompt:`Hide`,emailTranscript:`Email transcript`,emailTranscriptPrompt:`Get a copy of this conversation by email.`,emailTranscriptEmailLabel:`Email address`,emailTranscriptSend:`Send transcript`,emailTranscriptSending:`Sending…`,emailTranscriptSent:`Sent to {email}.`,emailTranscriptAlreadySent:`This conversation was already emailed. Send a new message to email it again.`,emailTranscriptLimited:`You've reached the limit for now. Try again later.`,emailTranscriptFailed:`Couldn't send it. Try again.`,emailTranscriptNotDelivered:`Couldn't send to this address. Check it and try again.`,emailTranscriptCancel:`Cancel`,emailTranscriptDone:`Done`,stop:`Stop`,theme:`Theme`,themeAuto:`Auto`,themeDark:`Dark`,themeLight:`Light`,textSize:`Text size`,textSizeSmall:`Small`,textSizeNormal:`Normal`,textSizeLarge:`Large`,loading:`Loading…`,visualPreparing:`Preparing visual…`,visualError:`This visual could not be displayed.`,visualPartial:`Some parts of this visual could not be displayed.`,visualSoldOut:`Sold out`,visualCartEmpty:`Your cart is empty.`,visualQuantity:`Qty`,visualChoose:`Choose`,thinking:`Thinking…`,thought:`Thought`,thoughtFor:`Thought for {time}`,toolResult:`Result`,sources:`Sources`,feedbackUp:`Good response`,feedbackDown:`Bad response`,feedbackThanks:`Thanks for your feedback`,copy:`Copy`,copied:`Copied`,copyTicketReference:`Ticket {reference}, copy`,tabHome:`Home`,tabConversations:`Chats`,tabHelp:`Help`,tabNews:`News`,modulesEmpty:`Nothing here yet`,chatUnavailable:`This chat isn't available right now`,moduleBack:`Back`,contentLoading:`Loading…`,contentHelpful:`Was this helpful?`,homeGreeting:`How can we help?`,homeGreetingNamed:`Hi {name} 👋`,homeGreetingLead:`How can we help?`,homeSearchPlaceholder:`Search for help`,homeAskPlaceholder:`Ask a question…`,homeWhatsNew:`What's new`,homeContentTitle:`Popular articles`,homeStatus:`Status`,helpTitle:`Help`,helpSearchPlaceholder:`Search for help`,helpEmpty:`No help articles yet`,helpLoading:`Loading help…`,helpSearchEmpty:`No results for “{query}”`,helpShowMore:`Show more`,newsTitle:`News`,newsEmpty:`No news yet`,newsLoading:`Loading news…`,newsShowMore:`Show more`,newsUnseen:`New post`,unread:`Unread`,formRequired:`This field is required`,formInvalidEmail:`Enter a valid email address`,formInvalidTel:`Enter a valid phone number`,formInvalidNumber:`Enter a valid number`,formOtherPlaceholder:`Type your answer…`,inputRequired:`Questions for you`,askFallbackQuestion:`Please provide the missing information.`,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`,decline:`Decline`,changeAnswer:`Change answer`,approvalPrompt:`{action}?`,approvalEditHint:`You can change your answer until this step continues.`,stepInput:`Input`,stepWorking:`Working`,stepWorkingOnIt:`Working on it…`,stepNeedsYourApproval:`Needs your approval`,stepWaitingForVisitor:`Waiting for the visitor`,stepApproved:`Approved`,stepDeclined:`Declined`,stepReplaced:`Replaced`,stepFailed:`Failed`,stepDidNotWork:`Didn't work`,decidedYouApproved:`You approved`,decidedYouDeclined:`You declined`,decidedVisitorApproved:`Approved by the visitor`,decidedVisitorDeclined:`Declined by the visitor`,decidedTeamApproved:`Approved by a team member`,decidedTeamDeclined:`Declined by a team member`,decidedMemberApproved:`Approved by {name}`,decidedMemberDeclined:`Declined by {name}`,stepRawData:`Raw data`,decidedRulesApproved:`Approved automatically`,decidedRulesDeclined:`Declined automatically`,edit:`Edit`,statusError:`Error`,toolStepsFailed:`{count} failed`,statusStopped:`Stopped`,toolStepsStopped:`Stopped after {count} steps`,toolStepsStoppedOne:`Stopped after 1 step`},O={en:D,fr:{attach:`Joindre des fichiers`,file:`Fichier`,attachmentMimeRejected:`{name} n'est pas un type de fichier accepté ici.`,attachmentTooLarge:`{name} est trop volumineux. Les fichiers peuvent faire jusqu'à {max} au total.`,poweredBy:`Propulsé par {name}`,attachmentTooMany:`Limite de pièces jointes : {count}.`,attachmentUploadFailed:`{name} n'a pas pu être envoyé.`,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`,dropZoneRejected:`Ces fichiers ne peuvent pas être joints ici`,errorGeneric:`Une erreur s'est produite`,errorRateLimited:`Trop de requêtes — veuillez réessayer dans un instant.`,errorRateLimitedIn:`Trop de requêtes — veuillez réessayer dans {seconds} s.`,errorOffline:`Impossible de joindre le serveur. Vérifiez votre connexion et réessayez.`,errorServer:`Un problème est survenu de notre côté. Veuillez réessayer.`,errorOriginNotAllowed:`Ce chat n'est pas encore configuré pour ce site.`,errorMessageTooLong:`Ce message est trop long. Raccourcissez-le et renvoyez-le.`,errorReconnecting:`Connexion perdue. Reconnexion…`,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`,launcherAsk:`Demander à {name}`,micBlocked:`Le micro est bloqué pour ce site : la saisie vocale ne peut pas démarrer.`,micStart:`Démarrer la saisie vocale`,micStop:`Arrêter la saisie vocale`,moreActions:`Plus d'actions`,newConversation:`Nouveau chat`,panelTitle:`Chat`,popOut:`Ouvrir dans un nouvel onglet`,resizeHandle:`Glisser pour redimensionner`,scrollToBottom:`Aller au plus récent`,send:`Envoyer`,queueMessage:`Mettre le message en attente`,removeQueuedMessage:`Retirer le message en attente`,removeAttachment:`Retirer {name}`,suggestedReplies:`Réponses suggérées`,compactingContext:`Optimisation du contexte de la conversation…`,soundOff:`Son désactivé`,soundOn:`Son activé`,talkToOperator:`Parler à une personne`,connectingOperator:`Mise en relation avec une personne…`,noOperatorAvailable:`Personne n'est disponible pour le moment — laissez vos coordonnées et nous reviendrons vers vous.`,chattingWithOperator:`Vous discutez avec {operator}`,operatorBadgeTitle:`Chat en direct`,chatNotice:`Vous discutez avec un assistant IA.`,cancelOperatorRequest:`Continuer avec l'IA`,loginPrompt:`Connectez-vous pour une aide plus rapide et personnalisée`,loginAction:`Se connecter`,loginRequired:`Connectez-vous pour discuter avec nous`,loginExpired:`Votre connexion a expiré. Connectez-vous pour poursuivre cette conversation.`,loginExpiredGuest:`Votre connexion a expiré. Connectez-vous pour poursuivre cette conversation, ou démarrez-en une nouvelle en tant qu'invité.`,startAsGuest:`Démarrer une nouvelle conversation`,loggedInAs:`Connecté en tant que {name}`,loggedIn:`Connecté`,dismissLoginPrompt:`Masquer`,emailTranscript:`Envoyer la transcription`,emailTranscriptPrompt:`Recevez une copie de cette conversation par e-mail.`,emailTranscriptEmailLabel:`Adresse e-mail`,emailTranscriptSend:`Envoyer la transcription`,emailTranscriptSending:`Envoi…`,emailTranscriptSent:`Envoyé à {email}.`,emailTranscriptAlreadySent:`Cette conversation a déjà été envoyée. Envoyez un nouveau message pour l'envoyer à nouveau.`,emailTranscriptLimited:`Vous avez atteint la limite pour le moment. Réessayez plus tard.`,emailTranscriptFailed:`Envoi impossible. Réessayez.`,emailTranscriptNotDelivered:`Envoi impossible à cette adresse. Vérifiez-la et réessayez.`,emailTranscriptCancel:`Annuler`,emailTranscriptDone:`Terminé`,stop:`Arrêter`,theme:`Thème`,themeAuto:`Auto`,themeDark:`Sombre`,themeLight:`Clair`,textSize:`Taille du texte`,textSizeSmall:`Petite`,textSizeNormal:`Normale`,textSizeLarge:`Grande`,loading:`Chargement…`,visualPreparing:`Préparation du visuel…`,visualError:`Ce visuel n’a pas pu être affiché.`,visualPartial:`Certaines parties de ce visuel n’ont pas pu être affichées.`,visualSoldOut:`Épuisé`,visualCartEmpty:`Votre panier est vide.`,visualQuantity:`Qté`,visualChoose:`Choisissez`,thinking:`Réflexion…`,thought:`Réflexion`,thoughtFor:`Réflexion : {time}`,toolResult:`Résultat`,sources:`Sources`,feedbackUp:`Bonne réponse`,feedbackDown:`Mauvaise réponse`,feedbackThanks:`Merci pour votre retour`,copy:`Copier`,copied:`Copié`,copyTicketReference:`Ticket {reference}, copier`,tabHome:`Accueil`,tabConversations:`Chats`,tabHelp:`Aide`,tabNews:`Actualités`,modulesEmpty:`Rien pour le moment`,chatUnavailable:`Ce chat n'est pas disponible pour le moment`,moduleBack:`Retour`,contentLoading:`Chargement…`,contentHelpful:`Cela vous a-t-il aidé ?`,homeGreeting:`Comment pouvons-nous vous aider ?`,homeGreetingNamed:`Bonjour {name} 👋`,homeGreetingLead:`Comment pouvons-nous vous aider ?`,homeSearchPlaceholder:`Rechercher de l'aide`,homeAskPlaceholder:`Posez une question…`,homeWhatsNew:`Nouveautés`,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 pour «\xA0{query}\xA0»`,helpShowMore:`Afficher plus`,newsTitle:`Actualités`,newsEmpty:`Aucune actualité pour le moment`,newsLoading:`Chargement des actualités…`,newsShowMore:`Afficher plus`,newsUnseen:`Nouvelle publication`,unread:`Non lu`,formRequired:`Ce champ est obligatoire`,formInvalidEmail:`Saisissez une adresse e-mail valide`,formInvalidTel:`Saisissez un numéro de téléphone valide`,formInvalidNumber:`Saisissez un nombre valide`,formOtherPlaceholder:`Saisissez votre réponse…`,inputRequired:`Questions pour vous`,askFallbackQuestion:`Veuillez fournir les informations manquantes.`,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`,decline:`Refuser`,changeAnswer:`Modifier la réponse`,approvalPrompt:`{action} ?`,approvalEditHint:`Vous pouvez modifier votre réponse jusqu'à la reprise de cette étape.`,stepInput:`Entrée`,stepWorking:`En cours`,stepWorkingOnIt:`En cours…`,stepNeedsYourApproval:`Votre accord est requis`,stepWaitingForVisitor:`En attente du visiteur`,stepApproved:`Approuvé`,stepDeclined:`Refusé`,stepReplaced:`Remplacé`,stepFailed:`Échec`,stepDidNotWork:`N'a pas fonctionné`,decidedYouApproved:`Vous avez approuvé`,decidedYouDeclined:`Vous avez refusé`,decidedVisitorApproved:`Approuvé par le visiteur`,decidedVisitorDeclined:`Refusé par le visiteur`,decidedTeamApproved:`Approuvé par un membre de l'équipe`,decidedTeamDeclined:`Refusé par un membre de l'équipe`,decidedMemberApproved:`Approuvé par {name}`,decidedMemberDeclined:`Refusé par {name}`,stepRawData:`Données brutes`,decidedRulesApproved:`Approuvé automatiquement`,decidedRulesDeclined:`Refusé automatiquement`,edit:`Modifier`,statusError:`Erreur`,toolStepsFailed:`{count} en échec`,statusStopped:`Arrêté`,toolStepsStopped:`Arrêté après {count} étapes`,toolStepsStoppedOne:`Arrêté après 1 étape`},es:{attach:`Adjuntar archivos`,file:`Archivo`,attachmentMimeRejected:`{name} no es un tipo de archivo que acepte este chat.`,attachmentTooLarge:`{name} es demasiado grande. Los archivos pueden ocupar hasta {max} en total.`,poweredBy:`Con la tecnología de {name}`,attachmentTooMany:`Límite de adjuntos: {count}.`,attachmentUploadFailed:`No se pudo subir {name}.`,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`,dropZoneRejected:`Estos archivos no se pueden adjuntar aquí`,errorGeneric:`Algo salió mal`,errorRateLimited:`Demasiadas solicitudes: inténtalo de nuevo en un momento.`,errorRateLimitedIn:`Demasiadas solicitudes: inténtalo de nuevo en {seconds} s.`,errorOffline:`No se puede conectar con el servidor. Revisa tu conexión e inténtalo de nuevo.`,errorServer:`Algo salió mal por nuestra parte. Inténtalo de nuevo.`,errorOriginNotAllowed:`Este chat aún no está configurado para este sitio web.`,errorMessageTooLong:`Ese mensaje es demasiado largo. Acórtalo y envíalo de nuevo.`,errorReconnecting:`Se perdió la conexión. Reconectando…`,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`,launcherAsk:`Pregúntale a {name}`,micBlocked:`El micrófono está bloqueado para este sitio, así que la entrada de voz no puede iniciarse.`,micStart:`Iniciar entrada de voz`,micStop:`Detener entrada de voz`,moreActions:`Más acciones`,newConversation:`Nuevo chat`,panelTitle:`Chat`,popOut:`Abrir en una pestaña nueva`,resizeHandle:`Arrastra para cambiar el tamaño`,scrollToBottom:`Ir a lo más reciente`,send:`Enviar`,queueMessage:`Poner mensaje en cola`,removeQueuedMessage:`Quitar mensaje de la cola`,removeAttachment:`Quitar {name}`,suggestedReplies:`Respuestas sugeridas`,compactingContext:`Optimizando el contexto de la conversación…`,soundOff:`Sonido desactivado`,soundOn:`Sonido activado`,talkToOperator:`Hablar con una persona`,connectingOperator:`Conectándote con una persona…`,noOperatorAvailable:`Nadie está disponible ahora — deja tus datos y te contactaremos.`,chattingWithOperator:`Estás chateando con {operator}`,operatorBadgeTitle:`Chat en vivo`,chatNotice:`Estás chateando con un asistente de IA.`,cancelOperatorRequest:`Seguir con la IA`,loginPrompt:`Inicia sesión para recibir una ayuda más rápida y personalizada`,loginAction:`Iniciar sesión`,loginRequired:`Inicia sesión para chatear con nosotros`,loginExpired:`Tu sesión ha caducado. Inicia sesión para continuar esta conversación.`,loginExpiredGuest:`Tu sesión ha caducado. Inicia sesión para continuar esta conversación o empieza una nueva como invitado.`,startAsGuest:`Empezar una nueva conversación`,loggedInAs:`Sesión iniciada como {name}`,loggedIn:`Sesión iniciada`,dismissLoginPrompt:`Ocultar`,emailTranscript:`Enviar transcripción`,emailTranscriptPrompt:`Recibe una copia de esta conversación por correo.`,emailTranscriptEmailLabel:`Correo electrónico`,emailTranscriptSend:`Enviar transcripción`,emailTranscriptSending:`Enviando…`,emailTranscriptSent:`Enviado a {email}.`,emailTranscriptAlreadySent:`Esta conversación ya se envió. Envía un mensaje nuevo para enviarla otra vez.`,emailTranscriptLimited:`Has alcanzado el límite por ahora. Inténtalo más tarde.`,emailTranscriptFailed:`No se pudo enviar. Inténtalo de nuevo.`,emailTranscriptNotDelivered:`No se pudo enviar a esta dirección. Revísala e inténtalo de nuevo.`,emailTranscriptCancel:`Cancelar`,emailTranscriptDone:`Listo`,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…`,visualPreparing:`Preparando visualización…`,visualError:`No se pudo mostrar esta visualización.`,visualPartial:`No se pudieron mostrar algunas partes de esta visualización.`,visualSoldOut:`Agotado`,visualCartEmpty:`Tu carrito está vacío.`,visualQuantity:`Cant.`,visualChoose:`Elige`,thinking:`Pensando…`,thought:`Razonamiento`,thoughtFor:`Razonó durante {time}`,toolResult:`Resultado`,sources:`Fuentes`,feedbackUp:`Buena respuesta`,feedbackDown:`Mala respuesta`,feedbackThanks:`Gracias por tu opinión`,copy:`Copiar`,copied:`Copiado`,copyTicketReference:`Ticket {reference}, copiar`,tabHome:`Inicio`,tabConversations:`Chats`,tabHelp:`Ayuda`,tabNews:`Novedades`,modulesEmpty:`Aún no hay nada aquí`,chatUnavailable:`Este chat no está disponible en este momento`,moduleBack:`Atrás`,contentLoading:`Cargando…`,contentHelpful:`¿Te resultó útil?`,homeGreeting:`¿Cómo podemos ayudarte?`,homeGreetingNamed:`Hola, {name} 👋`,homeGreetingLead:`¿Cómo podemos ayudarte?`,homeSearchPlaceholder:`Buscar ayuda`,homeAskPlaceholder:`Haz una pregunta…`,homeWhatsNew:`Lo nuevo`,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:`Sin resultados para «{query}»`,helpShowMore:`Mostrar más`,newsTitle:`Novedades`,newsEmpty:`Aún no hay novedades`,newsLoading:`Cargando novedades…`,newsShowMore:`Mostrar más`,newsUnseen:`Publicación nueva`,unread:`No leído`,formRequired:`Este campo es obligatorio`,formInvalidEmail:`Introduce un correo electrónico válido`,formInvalidTel:`Introduce un número de teléfono válido`,formInvalidNumber:`Introduce un número válido`,formOtherPlaceholder:`Escribe tu respuesta…`,inputRequired:`Preguntas para ti`,askFallbackQuestion:`Indica la información que falta.`,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`,decline:`Rechazar`,changeAnswer:`Cambiar respuesta`,approvalPrompt:`¿{action}?`,approvalEditHint:`Puedes cambiar tu respuesta hasta que este paso continúe.`,stepInput:`Entrada`,stepWorking:`En curso`,stepWorkingOnIt:`En curso…`,stepNeedsYourApproval:`Necesita tu aprobación`,stepWaitingForVisitor:`Esperando al visitante`,stepApproved:`Aprobado`,stepDeclined:`Rechazado`,stepReplaced:`Reemplazado`,stepFailed:`Falló`,stepDidNotWork:`No funcionó`,decidedYouApproved:`Lo aprobaste`,decidedYouDeclined:`Lo rechazaste`,decidedVisitorApproved:`Aprobado por el visitante`,decidedVisitorDeclined:`Rechazado por el visitante`,decidedTeamApproved:`Aprobado por un miembro del equipo`,decidedTeamDeclined:`Rechazado por un miembro del equipo`,decidedMemberApproved:`Aprobado por {name}`,decidedMemberDeclined:`Rechazado por {name}`,stepRawData:`Datos sin procesar`,decidedRulesApproved:`Aprobado automáticamente`,decidedRulesDeclined:`Rechazado automáticamente`,edit:`Editar`,statusError:`Error`,toolStepsFailed:`{count} con error`,statusStopped:`Detenido`,toolStepsStopped:`Detenido tras {count} pasos`,toolStepsStoppedOne:`Detenido tras 1 paso`},ar:{attach:`إرفاق ملفات`,file:`ملف`,attachmentMimeRejected:`نوع الملف {name} غير مقبول في هذه المحادثة.`,attachmentTooLarge:`الملف {name} كبير جدًا. يمكن أن يصل حجم الملفات معًا إلى {max}.`,poweredBy:`مدعوم من {name}`,attachmentTooMany:`الحد الأقصى للمرفقات: {count}.`,attachmentUploadFailed:`تعذّر رفع {name}.`,conversationLoading:`جارٍ تحميل الدردشة…`,loadPreviousMessages:`تحميل الرسائل السابقة`,close:`إغلاق`,collapse:`طيّ`,collapseSidebar:`طيّ الشريط الجانبي`,composerPlaceholder:`اكتب رسالة…`,dateLastWeek:`آخر ٧ أيام`,dateOlder:`أقدم`,dateToday:`اليوم`,dateYesterday:`أمس`,dropZone:`أفلت الملفات لإرفاقها`,dropZoneRejected:`لا يمكن إرفاق هذه الملفات هنا`,errorGeneric:`حدث خطأ ما`,errorRateLimited:`طلبات كثيرة جدًا — يرجى المحاولة بعد لحظة.`,errorRateLimitedIn:`طلبات كثيرة جدًا — يرجى المحاولة بعد {seconds} ث.`,errorOffline:`تعذّر الوصول إلى الخادم. تحقّق من اتصالك وحاول مرة أخرى.`,errorServer:`حدث خطأ من جهتنا. يرجى المحاولة مرة أخرى.`,errorOriginNotAllowed:`هذه المحادثة غير مُعدّة لهذا الموقع بعد.`,errorMessageTooLong:`هذه الرسالة طويلة جدًا. اختصرها وأرسلها مرة أخرى.`,errorReconnecting:`انقطع الاتصال. جارٍ إعادة الاتصال…`,errorRetry:`إعادة المحاولة`,expand:`توسيع`,expandSidebar:`توسيع الشريط الجانبي`,exitFullscreen:`إنهاء ملء الشاشة`,fullscreen:`ملء الشاشة`,history:`السجل`,historyBack:`العودة إلى الدردشة`,historyEmpty:`لا توجد دردشات سابقة بعد`,historyContinue:`متابعة الدردشة`,historyLoading:`جارٍ تحميل دردشاتك…`,historyTitle:`سجل الدردشات`,loadMoreConversations:`تحميل المزيد من المحادثات`,language:`اللغة`,launcherOpen:`فتح الدردشة`,launcherAsk:`اسأل {name}`,micBlocked:`الميكروفون محظور لهذا الموقع، لذا لا يمكن بدء الإدخال الصوتي.`,micStart:`بدء الإدخال الصوتي`,micStop:`إيقاف الإدخال الصوتي`,moreActions:`إجراءات إضافية`,newConversation:`دردشة جديدة`,panelTitle:`الدردشة`,popOut:`فتح في علامة تبويب جديدة`,resizeHandle:`اسحب لتغيير الحجم`,scrollToBottom:`الانتقال إلى الأحدث`,send:`إرسال`,queueMessage:`إضافة الرسالة إلى قائمة الانتظار`,removeQueuedMessage:`إزالة الرسالة من قائمة الانتظار`,removeAttachment:`إزالة {name}`,suggestedReplies:`ردود مقترحة`,compactingContext:`جارٍ تحسين سياق المحادثة…`,soundOff:`كتم الصوت`,soundOn:`تشغيل الصوت`,talkToOperator:`التحدث إلى شخص`,connectingOperator:`جارٍ توصيلك بشخص…`,noOperatorAvailable:`لا يوجد موظفون متاحون الآن — اترك بياناتك وسنتواصل معك.`,chattingWithOperator:`أنت تتحدث مع {operator}`,operatorBadgeTitle:`محادثة مباشرة`,chatNotice:`أنت تتحدث مع مساعد ذكاء اصطناعي.`,cancelOperatorRequest:`متابعة المحادثة مع الذكاء الاصطناعي`,loginPrompt:`سجّل الدخول للحصول على دعم أسرع ومخصّص لك`,loginAction:`تسجيل الدخول`,loginRequired:`سجّل الدخول للدردشة معنا`,loginExpired:`انتهت صلاحية تسجيل دخولك. سجّل الدخول لمتابعة هذه المحادثة.`,loginExpiredGuest:`انتهت صلاحية تسجيل دخولك. سجّل الدخول لمتابعة هذه المحادثة، أو ابدأ محادثة جديدة كضيف.`,startAsGuest:`بدء محادثة جديدة`,loggedInAs:`تم تسجيل الدخول باسم {name}`,loggedIn:`تم تسجيل الدخول`,dismissLoginPrompt:`إخفاء`,emailTranscript:`إرسال نص المحادثة`,emailTranscriptPrompt:`احصل على نسخة من هذه المحادثة عبر البريد الإلكتروني.`,emailTranscriptEmailLabel:`عنوان البريد الإلكتروني`,emailTranscriptSend:`إرسال نص المحادثة`,emailTranscriptSending:`جارٍ الإرسال…`,emailTranscriptSent:`تم الإرسال إلى {email}.`,emailTranscriptAlreadySent:`تم إرسال هذه المحادثة بالفعل. أرسل رسالة جديدة لإرسالها مرة أخرى.`,emailTranscriptLimited:`لقد بلغت الحد المسموح به حاليًا. حاول مرة أخرى لاحقًا.`,emailTranscriptFailed:`تعذّر الإرسال. حاول مرة أخرى.`,emailTranscriptNotDelivered:`تعذّر الإرسال إلى هذا العنوان. تحقّق منه وحاول مرة أخرى.`,emailTranscriptCancel:`إلغاء`,emailTranscriptDone:`تم`,stop:`إيقاف`,theme:`المظهر`,themeAuto:`تلقائي`,themeDark:`داكن`,themeLight:`فاتح`,textSize:`حجم النص`,textSizeSmall:`صغير`,textSizeNormal:`عادي`,textSizeLarge:`كبير`,loading:`جارٍ التحميل…`,visualPreparing:`جارٍ إعداد المحتوى المرئي…`,visualError:`تعذر عرض هذا المحتوى المرئي.`,visualPartial:`تعذر عرض بعض أجزاء هذا المحتوى المرئي.`,visualSoldOut:`نفدت الكمية`,visualCartEmpty:`سلتك فارغة.`,visualQuantity:`الكمية`,visualChoose:`اختر`,thinking:`يفكّر…`,thought:`تفكير`,thoughtFor:`فكّر لمدة {time}`,toolResult:`النتيجة`,sources:`المصادر`,feedbackUp:`رد جيد`,feedbackDown:`رد سيئ`,feedbackThanks:`شكرًا على ملاحظاتك`,copy:`نسخ`,copied:`تم النسخ`,copyTicketReference:`التذكرة {reference}، نسخ`,tabHome:`الرئيسية`,tabConversations:`الدردشات`,tabHelp:`المساعدة`,tabNews:`الأخبار`,modulesEmpty:`لا شيء هنا بعد`,chatUnavailable:`هذه المحادثة غير متاحة حالياً`,moduleBack:`رجوع`,contentLoading:`جارٍ التحميل…`,contentHelpful:`هل كان هذا مفيدًا؟`,homeGreeting:`كيف يمكننا مساعدتك؟`,homeGreetingNamed:`مرحبًا {name} 👋`,homeGreetingLead:`كيف يمكننا مساعدتك؟`,homeSearchPlaceholder:`ابحث عن مساعدة`,homeAskPlaceholder:`اطرح سؤالاً…`,homeWhatsNew:`ما الجديد`,homeContentTitle:`مقالات شائعة`,homeStatus:`الحالة`,helpTitle:`المساعدة`,helpSearchPlaceholder:`ابحث عن مساعدة`,helpEmpty:`لا توجد مقالات مساعدة بعد`,helpLoading:`جارٍ تحميل المساعدة…`,helpSearchEmpty:`لا نتائج لـ «{query}»`,helpShowMore:`عرض المزيد`,newsTitle:`الأخبار`,newsEmpty:`لا توجد أخبار بعد`,newsLoading:`جارٍ تحميل الأخبار…`,newsShowMore:`عرض المزيد`,newsUnseen:`منشور جديد`,unread:`غير مقروء`,formRequired:`هذا الحقل مطلوب`,formInvalidEmail:`أدخل بريدًا إلكترونيًا صحيحًا`,formInvalidTel:`أدخل رقم هاتف صحيحًا`,formInvalidNumber:`أدخل رقمًا صحيحًا`,formOtherPlaceholder:`اكتب إجابتك…`,inputRequired:`أسئلة لك`,askFallbackQuestion:`يرجى تقديم المعلومات الناقصة.`,inputBadge:`أسئلة`,inputAnswered:`تمت الإجابة`,inputSkipped:`تم التخطي`,showOptions:`إظهار الخيارات`,hideOptions:`إخفاء الخيارات`,qtypeText:`إجابتك`,qtypeEmail:`عنوان البريد الإلكتروني`,qtypePhone:`رقم الهاتف`,qtypeNumber:`رقم`,qtypeDate:`تاريخ`,qtypeChooseOne:`اختر واحدًا`,qtypeChooseAny:`اختر أيًا`,qtypeBoolean:`نعم / لا`,inputSubmit:`إرسال الإجابات`,inputSubmitHint:`Enter للإرسال · Shift+Enter = سطر جديد`,inputSkip:`تخطٍّ`,confirmYes:`نعم`,confirmNo:`لا`,approve:`موافقة`,decline:`رفض`,changeAnswer:`تغيير الإجابة`,approvalPrompt:`{action}؟`,approvalEditHint:`يمكنك تغيير إجابتك حتى تستأنف هذه الخطوة.`,stepInput:`المدخلات`,stepWorking:`قيد التنفيذ`,stepWorkingOnIt:`جارٍ التنفيذ…`,stepNeedsYourApproval:`بحاجة إلى موافقتك`,stepWaitingForVisitor:`بانتظار الزائر`,stepApproved:`تمت الموافقة`,stepDeclined:`مرفوض`,stepReplaced:`تم الاستبدال`,stepFailed:`فشل`,stepDidNotWork:`لم ينجح`,decidedYouApproved:`وافقت`,decidedYouDeclined:`رفضت`,decidedVisitorApproved:`وافق الزائر`,decidedVisitorDeclined:`رفض الزائر`,decidedTeamApproved:`وافق عضو في الفريق`,decidedTeamDeclined:`رفض عضو في الفريق`,decidedMemberApproved:`وافق {name}`,decidedMemberDeclined:`رفض {name}`,stepRawData:`البيانات الأولية`,decidedRulesApproved:`تمت الموافقة تلقائيًا`,decidedRulesDeclined:`رُفض تلقائيًا`,edit:`تعديل`,statusError:`خطأ`,toolStepsFailed:`فشل {count}`,statusStopped:`أُوقف`,toolStepsStopped:`أُوقف بعد {count} خطوات`,toolStepsStoppedOne:`أُوقف بعد خطوة واحدة`},he:{attach:`צירוף קבצים`,file:`קובץ`,attachmentMimeRejected:`הקובץ {name} אינו מסוג שהצ׳אט הזה מקבל.`,attachmentTooLarge:`הקובץ {name} גדול מדי. הקבצים יכולים להגיע יחד עד {max}.`,poweredBy:`מופעל על ידי {name}`,attachmentTooMany:`מספר הקבצים המרבי לצירוף: {count}.`,attachmentUploadFailed:`לא ניתן היה להעלות את {name}.`,conversationLoading:`טוען צ׳אט…`,loadPreviousMessages:`טעינת הודעות קודמות`,close:`סגירה`,collapse:`כיווץ`,collapseSidebar:`כיווץ סרגל הצד`,composerPlaceholder:`כתוב הודעה…`,dateLastWeek:`7 הימים האחרונים`,dateOlder:`ישן יותר`,dateToday:`היום`,dateYesterday:`אתמול`,dropZone:`שחרר קבצים כדי לצרף`,dropZoneRejected:`לא ניתן לצרף כאן את הקבצים האלה`,errorGeneric:`משהו השתבש`,errorRateLimited:`יותר מדי בקשות — נסה שוב בעוד רגע.`,errorRateLimitedIn:`יותר מדי בקשות — נסה שוב בעוד {seconds} שנ׳.`,errorOffline:`אין חיבור לשרת. בדוק את החיבור ונסה שוב.`,errorServer:`משהו השתבש אצלנו. נסה שוב.`,errorOriginNotAllowed:`הצ'אט הזה עדיין לא מוגדר לאתר הזה.`,errorMessageTooLong:`ההודעה הזו ארוכה מדי. קצרו אותה ושלחו שוב.`,errorReconnecting:`החיבור אבד. מתחבר מחדש…`,errorRetry:`נסה שוב`,expand:`הרחבה`,expandSidebar:`הרחבת סרגל הצד`,exitFullscreen:`יציאה ממסך מלא`,fullscreen:`מסך מלא`,history:`היסטוריה`,historyBack:`חזרה לצ׳אט`,historyEmpty:`אין עדיין צ׳אטים קודמים`,historyContinue:`המשך צ׳אט`,historyLoading:`טוען את הצ׳אטים שלך…`,historyTitle:`היסטוריית צ׳אטים`,loadMoreConversations:`טעינת שיחות נוספות`,language:`שפה`,launcherOpen:`פתיחת צ׳אט`,launcherAsk:`לשאול את {name}`,micBlocked:`המיקרופון חסום באתר הזה, ולכן אי אפשר להתחיל קלט קולי.`,micStart:`התחלת קלט קולי`,micStop:`עצירת קלט קולי`,moreActions:`פעולות נוספות`,newConversation:`צ׳אט חדש`,panelTitle:`צ׳אט`,popOut:`פתיחה בכרטיסייה חדשה`,resizeHandle:`גרור לשינוי הגודל`,scrollToBottom:`מעבר לחדש ביותר`,send:`שליחה`,queueMessage:`הוספת ההודעה לתור`,removeQueuedMessage:`הסרת ההודעה מהתור`,removeAttachment:`הסרת {name}`,suggestedReplies:`תשובות מוצעות`,compactingContext:`מבצע אופטימיזציה להקשר השיחה…`,soundOff:`השתקת הצליל`,soundOn:`הפעלת הצליל`,talkToOperator:`דברו עם אדם`,connectingOperator:`מחברים אותך לאדם…`,noOperatorAvailable:`אין נציגים זמינים כעת — השאר את הפרטים שלך ונחזור אליך.`,chattingWithOperator:`אתה מצ׳וטט עם {operator}`,operatorBadgeTitle:`צ׳אט חי`,chatNotice:`אתה מצ׳וטט עם עוזר בינה מלאכותית.`,cancelOperatorRequest:`המשך לשוחח עם ה-AI`,loginPrompt:`התחברו לקבלת תמיכה מהירה ומותאמת אישית`,loginAction:`התחברות`,loginRequired:`התחברו כדי לשוחח איתנו`,loginExpired:`פג תוקף ההתחברות שלך. התחברו כדי להמשיך בשיחה הזו.`,loginExpiredGuest:`פג תוקף ההתחברות שלך. התחברו כדי להמשיך בשיחה הזו, או התחילו שיחה חדשה כאורחים.`,startAsGuest:`התחלת שיחה חדשה`,loggedInAs:`מחובר/ת בתור {name}`,loggedIn:`מחובר/ת`,dismissLoginPrompt:`הסתרה`,emailTranscript:`שליחת תמליל בדוא״ל`,emailTranscriptPrompt:`קבלו עותק של השיחה הזו בדוא״ל.`,emailTranscriptEmailLabel:`כתובת דוא״ל`,emailTranscriptSend:`שליחת התמליל`,emailTranscriptSending:`שולחים…`,emailTranscriptSent:`נשלח אל {email}.`,emailTranscriptAlreadySent:`השיחה הזו כבר נשלחה. שלחו הודעה חדשה כדי לשלוח אותה שוב.`,emailTranscriptLimited:`הגעתם למגבלה כרגע. נסו שוב מאוחר יותר.`,emailTranscriptFailed:`השליחה נכשלה. נסו שוב.`,emailTranscriptNotDelivered:`לא ניתן לשלוח לכתובת הזו. בדקו אותה ונסו שוב.`,emailTranscriptCancel:`ביטול`,emailTranscriptDone:`סיום`,stop:`עצירה`,theme:`ערכת נושא`,themeAuto:`אוטומטי`,themeDark:`כהה`,themeLight:`בהיר`,textSize:`גודל טקסט`,textSizeSmall:`קטן`,textSizeNormal:`רגיל`,textSizeLarge:`גדול`,loading:`טוען…`,visualPreparing:`מכין תצוגה…`,visualError:`לא ניתן היה להציג תצוגה זו.`,visualPartial:`לא ניתן היה להציג חלקים מתצוגה זו.`,visualSoldOut:`אזל מהמלאי`,visualCartEmpty:`העגלה שלך ריקה.`,visualQuantity:`כמות`,visualChoose:`בחרו`,thinking:`חושב…`,thought:`מחשבה`,thoughtFor:`חשב במשך {time}`,toolResult:`תוצאה`,sources:`מקורות`,feedbackUp:`תשובה טובה`,feedbackDown:`תשובה גרועה`,feedbackThanks:`תודה על המשוב`,copy:`העתק`,copied:`הועתק`,copyTicketReference:`פנייה {reference}, העתקה`,tabHome:`בית`,tabConversations:`צ׳אטים`,tabHelp:`עזרה`,tabNews:`חדשות`,modulesEmpty:`אין כאן עדיין כלום`,chatUnavailable:`הצ׳אט הזה אינו זמין כרגע`,moduleBack:`חזרה`,contentLoading:`טוען…`,contentHelpful:`האם זה עזר?`,homeGreeting:`כיצד נוכל לעזור?`,homeGreetingNamed:`שלום {name} 👋`,homeGreetingLead:`כיצד נוכל לעזור?`,homeSearchPlaceholder:`חיפוש עזרה`,homeAskPlaceholder:`שאלו שאלה…`,homeWhatsNew:`מה חדש`,homeContentTitle:`מאמרים פופולריים`,homeStatus:`סטטוס`,helpTitle:`עזרה`,helpSearchPlaceholder:`חיפוש עזרה`,helpEmpty:`אין עדיין מאמרי עזרה`,helpLoading:`טוען עזרה…`,helpSearchEmpty:`אין תוצאות עבור „{query}”`,helpShowMore:`הצגת עוד`,newsTitle:`חדשות`,newsEmpty:`אין עדיין חדשות`,newsLoading:`טוען חדשות…`,newsShowMore:`הצגת עוד`,newsUnseen:`פוסט חדש`,unread:`לא נקרא`,formRequired:`שדה חובה`,formInvalidEmail:`הזן כתובת אימייל תקינה`,formInvalidTel:`הזן מספר טלפון תקין`,formInvalidNumber:`הזן מספר תקין`,formOtherPlaceholder:`כתוב את תשובתך…`,inputRequired:`שאלות עבורך`,askFallbackQuestion:`אנא ספקו את המידע החסר.`,inputBadge:`שאלות`,inputAnswered:`נענה`,inputSkipped:`דולג`,showOptions:`הצג אפשרויות`,hideOptions:`הסתר אפשרויות`,qtypeText:`התשובה שלך`,qtypeEmail:`כתובת אימייל`,qtypePhone:`מספר טלפון`,qtypeNumber:`מספר`,qtypeDate:`תאריך`,qtypeChooseOne:`בחר אחת`,qtypeChooseAny:`בחר כמה`,qtypeBoolean:`כן / לא`,inputSubmit:`שליחת תשובות`,inputSubmitHint:`Enter לשליחה · Shift+Enter = שורה חדשה`,inputSkip:`דילוג`,confirmYes:`כן`,confirmNo:`לא`,approve:`אישור`,decline:`דחייה`,changeAnswer:`שינוי התשובה`,approvalPrompt:`{action}?`,approvalEditHint:`אפשר לשנות את התשובה עד שהשלב הזה ימשיך.`,stepInput:`קלט`,stepWorking:`בביצוע`,stepWorkingOnIt:`מטפלים בזה…`,stepNeedsYourApproval:`נדרש האישור שלך`,stepWaitingForVisitor:`ממתין למבקר`,stepApproved:`אושר`,stepDeclined:`נדחה`,stepReplaced:`הוחלף`,stepFailed:`נכשל`,stepDidNotWork:`לא הצליח`,decidedYouApproved:`אישרת`,decidedYouDeclined:`דחית`,decidedVisitorApproved:`אושר על ידי המבקר`,decidedVisitorDeclined:`נדחה על ידי המבקר`,decidedTeamApproved:`אושר על ידי חבר צוות`,decidedTeamDeclined:`נדחה על ידי חבר צוות`,decidedMemberApproved:`אושר על ידי {name}`,decidedMemberDeclined:`נדחה על ידי {name}`,stepRawData:`נתונים גולמיים`,decidedRulesApproved:`אושר אוטומטית`,decidedRulesDeclined:`נדחה אוטומטית`,edit:`עריכה`,statusError:`שגיאה`,toolStepsFailed:`{count} נכשלו`,statusStopped:`נעצר`,toolStepsStopped:`נעצר אחרי {count} שלבים`,toolStepsStoppedOne:`נעצר אחרי שלב אחד`},zh:{attach:`添加附件`,file:`文件`,attachmentMimeRejected:`此聊天不接受 {name} 的文件类型。`,attachmentTooLarge:`{name} 太大了。文件总大小不能超过 {max}。`,poweredBy:`由 {name} 提供支持`,attachmentTooMany:`最多可添加 {count} 个附件。`,attachmentUploadFailed:`{name} 上传失败。`,conversationLoading:`正在加载聊天…`,loadPreviousMessages:`加载更早的消息`,close:`关闭`,collapse:`收起`,collapseSidebar:`收起侧边栏`,composerPlaceholder:`输入消息…`,dateLastWeek:`最近 7 天`,dateOlder:`更早`,dateToday:`今天`,dateYesterday:`昨天`,dropZone:`拖放文件以添加附件`,dropZoneRejected:`这些文件无法在此添加`,errorGeneric:`出了点问题`,errorRateLimited:`请求过多,请稍后再试。`,errorRateLimitedIn:`请求过多,请在 {seconds} 秒后重试。`,errorOffline:`无法连接服务器。请检查网络后重试。`,errorServer:`我们这边出了点问题。请重试。`,errorOriginNotAllowed:`此聊天尚未为本网站设置。`,errorMessageTooLong:`消息太长了。请缩短后重新发送。`,errorReconnecting:`连接已断开,正在重新连接…`,errorRetry:`重试`,expand:`展开`,expandSidebar:`展开侧边栏`,exitFullscreen:`退出全屏`,fullscreen:`全屏`,history:`历史记录`,historyBack:`返回聊天`,historyEmpty:`还没有以前的聊天`,historyLoading:`正在加载你的聊天…`,historyContinue:`继续聊天`,historyTitle:`聊天记录`,loadMoreConversations:`加载更多对话`,language:`语言`,launcherOpen:`打开聊天`,launcherAsk:`询问 {name}`,micBlocked:`此网站的麦克风已被阻止,无法开始语音输入。`,micStart:`开始语音输入`,micStop:`停止语音输入`,moreActions:`更多操作`,newConversation:`新聊天`,panelTitle:`聊天`,popOut:`在新标签页中打开`,resizeHandle:`拖动以调整大小`,scrollToBottom:`滚动到最新`,send:`发送`,queueMessage:`排队发送`,removeQueuedMessage:`移除排队的消息`,removeAttachment:`移除 {name}`,suggestedReplies:`推荐回复`,compactingContext:`正在优化对话上下文…`,soundOff:`关闭声音`,soundOn:`打开声音`,talkToOperator:`与真人交谈`,connectingOperator:`正在为你联系真人…`,noOperatorAvailable:`目前没有人有空,请留下你的联系方式,我们会跟进。`,chattingWithOperator:`你正在与 {operator} 聊天`,operatorBadgeTitle:`在线聊天`,chatNotice:`你正在与 AI 助手聊天。`,cancelOperatorRequest:`继续与 AI 聊天`,loginPrompt:`登录以获得更快、更个性化的支持`,loginAction:`登录`,loginRequired:`登录后与我们聊天`,loginExpired:`你的登录已过期。请登录以继续此聊天。`,loginExpiredGuest:`你的登录已过期。请登录以继续此聊天,或以访客身份开始新对话。`,startAsGuest:`开始新对话`,loggedInAs:`已登录为 {name}`,loggedIn:`已登录`,dismissLoginPrompt:`隐藏`,emailTranscript:`通过邮件发送聊天记录`,emailTranscriptPrompt:`通过邮件获取此对话的副本。`,emailTranscriptEmailLabel:`邮箱地址`,emailTranscriptSend:`发送聊天记录`,emailTranscriptSending:`正在发送…`,emailTranscriptSent:`已发送至 {email}。`,emailTranscriptAlreadySent:`此对话已通过邮件发送。发送一条新消息后可再次发送。`,emailTranscriptLimited:`你已达到当前上限。请稍后再试。`,emailTranscriptFailed:`发送失败。请重试。`,emailTranscriptNotDelivered:`无法发送到此地址。请检查后重试。`,emailTranscriptCancel:`取消`,emailTranscriptDone:`完成`,stop:`停止`,theme:`主题`,themeAuto:`自动`,themeDark:`深色`,themeLight:`浅色`,textSize:`文字大小`,textSizeSmall:`小`,textSizeNormal:`标准`,textSizeLarge:`大`,loading:`正在加载…`,visualPreparing:`正在准备图表…`,visualError:`无法显示此图表。`,visualPartial:`此图表的部分内容无法显示。`,visualSoldOut:`已售罄`,visualCartEmpty:`你的购物车是空的。`,visualQuantity:`数量`,visualChoose:`选择`,thinking:`正在思考…`,thought:`思考过程`,thoughtFor:`思考了 {time}`,toolResult:`结果`,sources:`来源`,feedbackUp:`回答很好`,feedbackDown:`回答不好`,feedbackThanks:`感谢你的反馈`,copy:`复制`,copied:`已复制`,copyTicketReference:`工单 {reference},复制`,tabHome:`首页`,tabConversations:`聊天`,tabHelp:`帮助`,tabNews:`动态`,modulesEmpty:`这里还没有内容`,chatUnavailable:`此聊天目前不可用`,moduleBack:`返回`,contentLoading:`正在加载…`,contentHelpful:`这对你有帮助吗?`,homeGreeting:`有什么可以帮你?`,homeGreetingNamed:`你好,{name} 👋`,homeGreetingLead:`有什么可以帮你?`,homeSearchPlaceholder:`搜索帮助`,homeAskPlaceholder:`提出问题…`,homeWhatsNew:`最新动态`,homeContentTitle:`热门文章`,homeStatus:`状态`,helpTitle:`帮助`,helpSearchPlaceholder:`搜索帮助`,helpEmpty:`还没有帮助文章`,helpLoading:`正在加载帮助…`,helpSearchEmpty:`没有找到“{query}”的结果`,helpShowMore:`显示更多`,newsTitle:`动态`,newsEmpty:`还没有动态`,newsLoading:`正在加载动态…`,newsShowMore:`显示更多`,newsUnseen:`新文章`,unread:`未读`,formRequired:`此项为必填`,formInvalidEmail:`请输入有效的邮箱地址`,formInvalidTel:`请输入有效的电话号码`,formInvalidNumber:`请输入有效的数字`,formOtherPlaceholder:`输入你的回答…`,inputRequired:`需要你回答的问题`,askFallbackQuestion:`请提供缺少的信息。`,inputBadge:`问题`,inputAnswered:`已回答`,inputSkipped:`已跳过`,showOptions:`显示选项`,hideOptions:`隐藏选项`,qtypeText:`你的回答`,qtypeEmail:`邮箱地址`,qtypePhone:`电话号码`,qtypeNumber:`数字`,qtypeDate:`日期`,qtypeChooseOne:`选择一项`,qtypeChooseAny:`可多选`,qtypeBoolean:`是 / 否`,inputSubmit:`提交回答`,inputSubmitHint:`Enter 发送 · Shift+Enter 换行`,inputSkip:`跳过`,confirmYes:`是`,confirmNo:`否`,approve:`批准`,decline:`拒绝`,changeAnswer:`修改回答`,approvalPrompt:`{action}?`,approvalEditHint:`在此步骤继续之前,你可以修改回答。`,stepInput:`输入`,stepWorking:`进行中`,stepWorkingOnIt:`正在处理…`,stepNeedsYourApproval:`需要你的批准`,stepWaitingForVisitor:`等待访客`,stepApproved:`已批准`,stepDeclined:`已拒绝`,stepReplaced:`已替换`,stepFailed:`失败`,stepDidNotWork:`未成功`,decidedYouApproved:`你已批准`,decidedYouDeclined:`你已拒绝`,decidedVisitorApproved:`访客已批准`,decidedVisitorDeclined:`访客已拒绝`,decidedTeamApproved:`团队成员已批准`,decidedTeamDeclined:`团队成员已拒绝`,decidedMemberApproved:`{name} 已批准`,decidedMemberDeclined:`{name} 已拒绝`,stepRawData:`原始数据`,decidedRulesApproved:`已自动批准`,decidedRulesDeclined:`已自动拒绝`,edit:`编辑`,statusError:`错误`,toolStepsFailed:`{count} 个失败`,statusStopped:`已停止`,toolStepsStopped:`在 {count} 步后停止`,toolStepsStoppedOne:`在 1 步后停止`}};function k(e,t){let n=A(e),r=te(t),i=O[S(n)],a=r?{...t[n],...t[e]}:t??{},o=r?t.en??{}:{};return{...D,...i,...o,...a}}function A(e){return(e.split(`-`)[0]??`en`).toLowerCase()}const j=/* @__PURE__ */ new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`,`ks`,`nqo`,`prs`,`syr`]);function ee(e){return j.has(A(e))}function M(e,t){return e[t]??t}function te(e){if(!e)return!1;for(let t of Object.values(e))if(t&&typeof t==`object`)return!0;return!1}const N={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`},ne={simple:{showSteps:!1,showStepDetails:!1,showStepSystem:!1,showDecidedBy:!1,foldApprovals:!0},technical:{showSteps:!0,showStepDetails:!0,showStepSystem:!0,showDecidedBy:!0,foldApprovals:!0}};function re(e){return Object.hasOwn(ne,e)}function ie(e,t){return{...ne[t],...e}}const P=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ae(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function oe(e){if(e.title)return e.title;let t=e.toolName.replace(/^tool[:-]/,``),n=t.indexOf(`__`);return ae(n>0?t.slice(n+2):t)}function F(e,t,n){let r=e.approval;return r?.replacedByMessageId?`replaced`:e.state===`output-available`?n.error===void 0?`done`:`failed`:e.state===`output-error`?t.interrupted?`stopped`:`failed`:e.state===`output-denied`||r?.approved===!1?`declined`:e.state===`approval-responded`||r?.approved===!0?t.cutOff?`stopped`:`approved`:e.state===`approval-requested`?t.submitted?`submitted`:t.cutOff?`stopped`:t.superseded?`replaced`:`waiting`:t.live?`running`:`stopped`}function se(e,t){if(e.isAutomatic)return`rules`;let n=e.respondedBy;return n?.visitorId?`visitor`:n?.userId?n.userId===t.userId?`you`:`teamMember`:t.decides?`you`:`visitor`}function ce(e,t,n,r){return e===`teamMember`&&n?r[t?`decidedMemberApproved`:`decidedMemberDeclined`].replace(`{name}`,n):r[le[e][+!t]]}const le={you:[`decidedYouApproved`,`decidedYouDeclined`],visitor:[`decidedVisitorApproved`,`decidedVisitorDeclined`],teamMember:[`decidedTeamApproved`,`decidedTeamDeclined`],rules:[`decidedRulesApproved`,`decidedRulesDeclined`]};function ue(e,t){switch(e){case`running`:return t.strings.stepWorking;case`waiting`:return t.reader.decides?t.strings.stepNeedsYourApproval:t.strings.stepWaitingForVisitor;case`submitted`:return t.strings.stepWorkingOnIt;case`approved`:return t.strings.stepApproved;case`declined`:return t.strings.stepDeclined;case`replaced`:return t.strings.stepReplaced;case`stopped`:return t.strings.statusStopped;case`failed`:return t.display.showStepDetails?t.strings.stepFailed:t.strings.stepDidNotWork;case`done`:return``;default:return e}}function de(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e){return typeof e==`string`?e.trim():typeof e==`number`||typeof e==`boolean`?String(e):``}function fe(e){return I(e)||(typeof e==`object`&&e?JSON.stringify(e):``)}function pe(e){if(!de(e))return fe(e);let[t,...n]=Object.values(e).map(fe).filter(Boolean);return t===void 0?``:n.length>0?`${t} (${n.join(`, `)})`:t}function me(e,t){if(!de(e))return[];let n=[];function r(e,i){if(Array.isArray(e)){let t=e.map(pe).filter(Boolean).join(`, `);t&&n.push({path:i,value:t});return}if(de(e)){for(let[t,n]of Object.entries(e))r(n,[...i,t]);return}let a=I(e);a&&(t.withIds||!P.test(a))&&n.push({path:i,value:a})}r(e,[]);let i=n.map(({path:e})=>ae(e.at(-1)??``));return n.map(({path:e,value:t},n)=>{let r=i[n]??``;return{label:i.filter(e=>e===r).length>1&&e.length>1?`${ae(e.at(-2)??``)} · ${r.toLowerCase()}`:r,value:t}})}function he(e){if(de(e))return Object.values(e).find(e=>typeof e==`string`&&e.trim().length>0&&!P.test(e.trim()))?.trim()}function ge(e,t=1/0){if(e==null)return;let n=typeof e==`string`?e:JSON.stringify(e,null,2);if(n&&n!==`{}`&&n!==`[]`&&n!==`""`)return n.length>t?`${n.slice(0,t)}…`:n}function _e(e){let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function ve(e){if(de(e)&&e.storage===`tool-result-ref`&&`summary`in e)return{value:e.summary};if(de(e)&&Array.isArray(e.content)){let t=e.content.flatMap(e=>de(e)&&typeof e.text==`string`?[e.text]:[]).join(`
2
- `),n=de(e.structuredContent)?e.structuredContent:_e(t);return e.isError===!0?{value:n,error:de(n)&&typeof n.error==`string`?n.error:t}:{value:n}}return de(e)&&typeof e.error==`string`&&typeof e.instruction==`string`?{value:e,error:e.error}:{value:e}}function L(e){return ge(e.input)!==void 0||ge(e.output)!==void 0||!!e.errorText}function ye(e,t,n){let{display:r}=n,i=e.approval;if(typeof e.toolMetadata?.card==`string`&&i)return`card`;let a=i!==void 0&&!i.isAutomatic;if(a&&be(e,n.turn))return`card`;let o=t.decision?.by===`you`||a&&t.decision===void 0&&n.reader.decides;return a&&o?r.foldApprovals?`step`:`card`:a?r.showSteps||r.showDecidedBy?r.foldApprovals?`step`:`card`:`hidden`:i?.isAutomatic?r.showSteps||r.showDecidedBy?`step`:`hidden`:r.showSteps&&L(e)?`step`:`hidden`}function be(e,t){return e.approval?.replacedByMessageId||(t.superseded||t.cutOff)&&e.approval?.approved===void 0?!1:e.state===`approval-requested`||e.state===`approval-responded`}function xe(e,t){let{turn:n,reader:r,display:i,strings:a}=t,o=ve(e.output),s=F(e,n,o),c=e.approval,l=c?.replacedByMessageId?void 0:c?.approved,u=c&&l!==void 0?se(c,r):void 0,d=u===`teamMember`?c?.respondedBy?.userId:void 0,f=u&&l!==void 0&&(u===`you`||i.showDecidedBy)?{approved:l,by:u,label:ce(u,l,d&&t.names?.get(d),a),...d?{userId:d}:{}}:void 0,p=oe(e),m=typeof e.toolMetadata?.system==`string`&&(i.showStepSystem||e.toolMetadata.nameShared===!0)?e.toolMetadata.system:void 0,h=he(e.input),g=e.errorText??o.error,_=i.showStepDetails&&o.error===void 0?me(o.value,{withIds:!0}):[],v=i.showStepDetails?{input:ge(e.input),output:ge(o.value,4e3)}:void 0,y=c!==void 0&&!c.isAutomatic&&!e.toolMetadata?.card,b={toolCallId:e.toolCallId,placement:`hidden`,...typeof e.toolMetadata?.card==`string`&&c?{card:e.toolMetadata.card}:{},name:p,...m?{system:m}:{},status:s,statusLabel:ue(s,{reader:r,display:i,strings:a}),...f?{decision:f}:{},...f?.by===`rules`&&c?.reason?{reason:c.reason}:{},...h?{summary:h}:{},fields:me(e.input,{withIds:i.showStepDetails||c!==void 0&&!c.isAutomatic&&be(e,n)}),..._.length>0?{resultFields:_}:{},...g&&i.showStepDetails?{error:g}:{},...v?{raw:v}:{},...y?{approval:Se(e,s,{turn:n,reader:r,strings:a,name:p})}:{}};return{...b,placement:ye(e,b,{turn:n,reader:r,display:i})}}function Se(e,t,n){let r=n.strings.approvalPrompt.replace(`{action}`,n.name);return t===`waiting`?{ask:r,buttons:n.reader.decides?`decide`:`none`}:t===`submitted`||!be(e,n.turn)?{ask:r,buttons:`none`}:n.turn.canAct&&n.reader.decides?{ask:r,buttons:`change`,note:n.strings.approvalEditHint}:t===`approved`?{ask:r,buttons:`none`,note:n.strings.stepWorkingOnIt}:{ask:r,buttons:`none`}}function Ce(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.name,(t.get(n.name)??0)+1);let n=/* @__PURE__ */ new Map;for(let{decision:t}of e){if(!t)continue;let e=n.get(t.label)??{approved:t.approved,label:t.label,...t.userId?{userId:t.userId}:{},count:0};n.set(t.label,{...e,count:e.count+1})}let[r]=e,i=e.some(e=>e.status===`stopped`);return{tools:[...t].map(([e,t])=>({name:e,count:t})),...e.length===1&&r?{single:{name:r.name,...r.system?{system:r.system}:{},...r.summary?{summary:r.summary}:{},...we(r)}}:{},marks:[...n.values()].map(({count:e,...t})=>Object.assign(t,{label:e>1?`${t.label} ×${e}`:t.label})),failed:e.filter(e=>e.status===`failed`).length,...i?{stopped:{finished:e.filter(e=>e.status!==`stopped`).length}}:{}}}function we(e){return!e.decision&&(e.status===`replaced`||e.status===`declined`)?{outcome:e.statusLabel}:{}}function Te(e,t){return e===0?t.statusStopped:e===1?t.toolStepsStoppedOne:t.toolStepsStopped.replace(`{count}`,String(e))}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{}}},De={get(e){try{return sessionStorage.getItem(e)}catch{return null}},set(e,t){try{sessionStorage.setItem(e,t)}catch{}},remove(e){try{sessionStorage.removeItem(e)}catch{}}},Oe={maxBytes:10485760,maxCount:10,accept:`*/*`},ke={voice:`local`},Ae={enabled:!0,sampleRate:1},je={upload:`/pai/upload-file`,transcribe:`/pai/transcribe-audio`},Me={variant:`circle`,size:`md`,label:void 0,icon:`chat`,hidden:!1},Ne={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`]},Pe={enabled:!0,volume:.3,events:void 0},Fe={enabled:!0,events:void 0},Ie=[{label:`tabConversations`,layout:`chat`}],Le=[`off`,`error`,`warn`,`info`,`debug`,`trace`],Re=N.cssPrefix,ze=`${Re}.debug`,Be=`__${N.global}_DEBUG__`,Ve=`${Re}-debug`;let He=2,Ue=null;function We(){if(typeof window>`u`)return 2;try{let e=new URLSearchParams(window.location.search).get(Ve);if(e!==null){let t=Ge(e);if(t>=0)return t}}catch{}try{let e=window.localStorage?.getItem(ze);if(e){let t=Ge(e);if(t>=0)return t}}catch{}return Reflect.get(window,Be)?4:2}function Ge(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=Le.findIndex(t=>t===e);if(t>=0)return t}return-1}function Ke(e){let t=Ge(e);if(!(t<0)){He=t;try{window.localStorage?.setItem(ze,Le[t]??`off`)}catch{}}}function qe(){return Le[He]??`warn`}He=We();function Je(e){let t=`[${Re}:${e}]`;function n(n,r,i){return(a,o)=>{if(!(He<n)&&(o===void 0?console[r](t,a):console[r](t,a,o),Ue))try{Ue({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=>Je(`${e}:${t}`)}}const R=Je(`core`);function Ye(e){Ue=e}const Xe=R.scope(`context`),Ze=/* @__PURE__ */ new Set([`visitorId`,`conversationId`,`jwt`,`token`,`authorization`,`password`]),Qe=1024,$e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function et(e){return rt(e,`userContext`,!0)}function tt(e){return rt(e,`pageContext`,!1)}function nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rt(e,t,n){if(e==null)return;if(!nt(e)){Xe.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(Ze.has(n)){Xe.warn(`dropped reserved ${t} key "${n}" — managed by the widget, not host-settable`);continue}if(a==null)continue;if(i>=50){Xe.warn(`${t} truncated at 50 keys — dropped "${n}"`);continue}let e=it(t,n,a);e!==void 0&&(r[n]=e,i++)}return n&&typeof r.email==`string`&&!$e.test(r.email)&&(Xe.warn(`dropped malformed context field`,{field:`${t}.email`,reason:`invalid format`}),delete r.email),Object.keys(r).length>0?r:void 0}function it(e,t,n){if(typeof n==`boolean`)return n;if(typeof n==`number`){if(!Number.isFinite(n)){Xe.warn(`dropped non-finite ${e}.${t}`);return}return n}if(typeof n==`string`){let r=n.trim();return r===``?void 0:r.length>Qe?(Xe.warn(`truncated ${e}.${t} to ${Qe} chars`),r.slice(0,Qe)):r}Xe.warn(`dropped ${e}.${t} — only string/number/boolean values are allowed`,{type:typeof n})}function at(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??{},c={enabled:t.history?.enabled??!0},{themeMode:l,themeOverrides:u}=ot(t.theme),d=n.mode??`floating`,f=z(i.defaultLocale),p=i.availableLocales??[i.locale??f],m=st(i.locale??f,p,f),h=(t.baseUrl??N.defaultBaseUrl).replace(/\/$/,``),g=(t.agentApiBaseUrl??`${h}/api/agent`).replace(/\/$/,``),_=(t.dataApiBaseUrl??`${h}/api/data`).replace(/\/$/,``);return{widgetId:t.widgetId??`default`,publicKey:t.publicKey,aiAgentDeploymentId:t.aiAgentDeploymentId,baseUrl:h,agentApiBaseUrl:g,dataApiBaseUrl:_,userContext:et(t.userContext),pageContext:tt(t.pageContext),position:n.position??(ee(m)?`bottom-left`:`bottom-right`),themeMode:l,textSize:`normal`,themeOverrides:u,mode:d,responseMode:r.responseMode??`streaming`,showReasoning:r.showReasoning??!1,stepDisplay:ie(r.stepDisplay,`simple`),showSources:r.showSources??!1,enableMessageFeedback:!(r.disableMessageFeedback??!1),autoSendSuggestions:r.autoSendSuggestions??!1,cardAnswerWaitSeconds:r.cardAnswerWaitSeconds??60,popOutUrl:r.popOutUrl,features:{voice:t.features?.voice??ke.voice,fileUpload:!(t.features?.disableFileUpload??!1),humanInLoop:!(t.features?.disableHumanInLoop??!1),emailTranscript:!(t.features?.disableEmailTranscript??!1),operatorRequest:t.features?.enableOperatorRequest===!0&&!(t.features.hideRequestOperatorButton??!1)},endpoints:{upload:t.endpoints?.upload??je.upload,transcribe:t.endpoints?.transcribe??je.transcribe},attachments:{accept:t.composer?.attachments?.accept??Oe.accept,maxBytes:t.composer?.attachments?.maxBytes??Oe.maxBytes,maxCount:t.composer?.attachments?.maxCount??Oe.maxCount},locale:m,defaultLocale:f,availableLocales:p,startMinimized:r.startMinimized??!0,actions:ct(d,s.actions,c.enabled),size:{...n.size,resize:{...n.size?.resize,enabled:n.size?.resize?.enabled??!0}},launcher:ht(t.launcher,t.agent?.name),sound:lt(a.sound),haptics:ut(a.haptics),strings:k(m,i.strings),stringsOverride:i.strings,composerDisclaimer:o.composerDisclaimer??``,header:{variant:s.variant??`plain`,notice:s.notice,showNotice:!(s.hideNotice??!1)},poweredBy:ft(o.poweredBy),composer:pt(t.composer),modules:mt(t.modules,c.enabled),tracking:dt(t.tracking,_),history:c,storage:t.storage??Ee,userToken:t.userToken,continueLink:t.continueLink,tools:t.tools,onMessage:t.onMessage,onOpen:t.onOpen,onClose:t.onClose,onError:t.onError}}function ot(e){if(typeof e==`string`)return{themeMode:e,themeOverrides:{}};if(!e||typeof e!=`object`)return{themeMode:`host`,themeOverrides:{}};let{mode:t,...n}=e;return{themeMode:t??`host`,themeOverrides:n}}function z(e){return e&&e!==`auto`?e:globalThis.navigator?.language||`en`}function st(e,t,n){if(t.length<=1||t.includes(e))return e;let r=e.split(`-`)[0];return r&&t.includes(r)?r:t.includes(n)?n:t[0]??e}function ct(e,t,n){let r=t??Ne[e];return n?r:r.filter(e=>e!==`history`)}function lt(e){return{enabled:e?.enabled??Pe.enabled,volume:e?.volume??Pe.volume,events:e?.events}}function ut(e){return{enabled:e?.enabled??Fe.enabled,events:e?.events}}function dt(e,t){let n=e?.sampleRate??Ae.sampleRate;return{enabled:e?.enabled??Ae.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 ft(e){return e?.text===``&&!e.logoUrl?null:{href:N.siteUrl,...e}}function pt(e){let t=e?.sendButton;return{sendButton:{shape:t?.shape??`circle`,icon:t?.icon??`arrowUp`,variant:t?.variant??`filled`}}}function mt(e,t){let n=(e??Ie).slice(0,4),r=n.some(e=>e?.label&&e.layout===`help`),i=/* @__PURE__ */ new Set,a=[];for(let e of n){if(!e?.label||!e?.layout)continue;let n=e.contentCollectionIds?.filter(Boolean),o=e.id??n?.[0]??e.layout;for(;i.has(o);)o=`${o}-${a.length}`;i.add(o);let s={id:o,label:e.label,layout:e.layout};n?.length&&(s.contentCollectionIds=n),e.layout===`home`&&(s.brandName=e.brandName,s.greetingText=e.greetingText,s.showGreeting=!(e.hideGreeting??!1),s.showSearchBar=r&&!(e.hideSearchBar??!1),s.showRecentConversations=t&&!(e.hideRecentConversations??!1),e.userAvatars?.length&&(s.userAvatars=e.userAvatars),e.status&&(s.status=e.status),s.contentBlockTitle=e.contentBlockTitle),a.push(s)}return{list:a,byId:Object.fromEntries(a.map(e=>[e.id,e]))}}function ht(e,t){let n=e?.callout?.text?{shape:`pill`,position:`auto`,delayMs:1200,autoDismissMs:0,animated:!0,persistent:!0,...e.callout}:null;return{variant:e?.variant??Me.variant,size:e?.size??Me.size,label:e?.label??Me.label,icon:e?.icon??Me.icon,hidden:e?.hidden??Me.hidden,...t&&{personaName:t},callout:n}}function gt(e,t){return e===`host`?`host`:t??e}function _t(e,t,n,r){let i=st(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=k(i,e.stringsOverride)),n!==e.themeMode&&(a.themeMode=n),r!==e.textSize&&(a.textSize=r),a}function vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const yt=[`agent`,`presentation`,`behavior`,`theme`,`launcher`,`header`,`composer`,`feedback`,`i18n`,`footer`,`features`,`tracking`,`endpoints`,`history`];function bt(e,t){if(!t)return e;let n={...e};for(let r of yt){let i=t[r];if(i===void 0)continue;let a=e[r];r===`theme`?a===void 0?n[r]=i:typeof a==`string`&&typeof i==`object`&&i&&(n[r]={...i,mode:a}):r!==`i18n`&&(n[r]=xt(vt(i)?i:{},vt(a)?a:void 0))}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=xt(vt(i)?i:{},vt(r)?r:void 0);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=St(a,t)),n.i18n=e}return n}function xt(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 St(e,t){if(!e)return t;if(!t)return e;let n=te(e),r=te(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 Ct=[`clear`,`expand`,`fullscreen`,`popOut`,`sound`,`history`,`language`,`theme`,`textSize`,`close`];function wt(e){return e!==`false`}function Tt(e){return re(e)?ne[e]:void 0}function Et(e){let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>=0?t:void 0}const Dt=[[`public-key`,`publicKey`],[`ai-agent-deployment-id`,`aiAgentDeploymentId`],[`base-url`,`baseUrl`],[`agent-api-base-url`,`agentApiBaseUrl`],[`data-api-base-url`,`dataApiBaseUrl`],[`continue-link`,`continueLink`],[`theme`,`theme`,e=>e]],Ot=[[`mode`,`mode`,e=>e],[`position`,`position`,e=>e]],kt=[[`width`,`width`],[`height`,`height`]],At=[[`response-mode`,`responseMode`,e=>e],[`start-minimized`,`startMinimized`,wt],[`show-reasoning`,`showReasoning`,wt],[`step-display`,`stepDisplay`,Tt],[`show-sources`,`showSources`,wt],[`disable-message-feedback`,`disableMessageFeedback`,wt],[`auto-send-suggestions`,`autoSendSuggestions`,wt],[`card-answer-wait-seconds`,`cardAnswerWaitSeconds`,Et],[`pop-out-url`,`popOutUrl`]],jt=[[`locale`,`locale`]];new Set(Ct);const Mt=[[`launcher-variant`,`variant`,e=>e],[`launcher-size`,`size`,e=>e],[`launcher-icon`,`icon`],[`launcher-hidden`,`hidden`,wt]],Nt=[[`features-disable-file-upload`,`disableFileUpload`,wt],[`features-disable-email-transcript`,`disableEmailTranscript`,wt],[`features-voice`,`voice`,e=>e]],Pt=[[`endpoint-upload`,`upload`],[`endpoint-transcribe`,`transcribe`]],Ft=[[`user-id`,`id`],[`user-email`,`email`],[`user-name`,`name`]],It=[[`page-area`,`area`],[`page-url`,`url`],[`page-path`,`path`],[`page-title`,`title`]],Lt=[`launcher-label`,`callout-text`,`callout-delay`,`actions`,`user-context`,`page-context`],Rt=[Dt,Ot,kt,At,jt,Mt,Nt,Pt,Ft,It],zt=/* @__PURE__ */ new Set([`start-minimized`]);[...Rt.flatMap(e=>e.map(([e])=>e).filter(e=>!zt.has(e))),...Lt];const Bt=R.scope(`track`);function Vt(e,t){let n=typeof e==`string`?e.trim():``;if(!n||n.length>64){Bt.warn(`track: ignored an event without a name of 1–64 characters`,{name:e});return}let r=Object.fromEntries(Object.entries(typeof t==`object`&&t?t:{}).filter(e=>typeof e[1]==`string`||typeof e[1]==`boolean`||Number.isFinite(e[1])));return JSON.stringify(r).length>256?(Bt.warn(`track: sent the event without its data, which is over 256 characters`,{name:n}),{name:n}):Object.keys(r).length>0?{name:n,data:r}:{name:n}}function Ht(e){let t=[];return e.on(`hostEvent`,e=>{t.push({...e,at:Date.now()}),t.length>10&&t.shift()}),t}function Ut(){let e=Date.now(),t=/* @__PURE__ */ 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,Wt(t.subarray(6)),t[6]=(t[6]??0)&15|112,t[8]=(t[8]??0)&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 Wt(e){if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const Gt=R.scope(`persistence`);function Kt(e,t=Ee,n){let r=n?`${e}.${n}`:e,i=`${N.cssPrefix}.${r}.storageVersion`,a=t.get(i)??void 0,o=a?`.v${a}`:``,s=`${N.cssPrefix}.${r}${o}`,c=`${N.cssPrefix}${o}.visitorId`,l=`${N.cssPrefix}${o}.lastUserSub`,u=`${s}.conversationId`,d=`${s}.userPrefs`,f=`${s}.panelOpen`,p=`${s}.panelSize`,m=`${s}.calloutDismissed`,h=`${s}.sidebarCollapsed`,g=`${s}.activeModule`,_=`${s}.seenNewsId`,v=`${s}.historyCount`,y=`${s}.loginReturn`,b=`${s}.loginPromptDismissedIn`,x={getVisitorId(){let e=t.get(c);if(e)return e;let n=Ut();return t.set(c,n),n},loadLastUserSub(){return t.get(l)??void 0},saveLastUserSub(e){t.set(l,e)},loadConversationId(){return t.get(u)??void 0},saveConversationId(e){Gt.trace(`saveConversationId`,{id:e,scope:r}),e?t.set(u,e):t.remove(u)},loadDraft(e){return t.get(`${s}.draft.${e}`)??``},saveDraft(e,n){let r=`${s}.draft.${e}`;n?t.set(r,n):t.remove(r)},loadMessageQueue(e){let n=t.get(`${s}.messageQueue.${e}`);if(!n)return[];try{let e=JSON.parse(n);return!Array.isArray(e)||!e.every(Jt)?[]:e}catch(e){return Gt.warn(`loadMessageQueue parse failed`,{error:e}),[]}},saveMessageQueue(e,n){let r=`${s}.messageQueue.${e}`;if(n.length===0)t.remove(r);else try{t.set(r,JSON.stringify(n))}catch(e){Gt.warn(`saveMessageQueue serialise failed`,{error:e})}},loadUserPrefs(){let e=t.get(d);if(!e)return{};try{return Yt(JSON.parse(e))}catch(e){return Gt.warn(`loadUserPrefs parse failed`,{error:e}),{}}},saveUserPrefs(e){try{t.set(d,JSON.stringify(e))}catch(e){Gt.warn(`saveUserPrefs serialise failed`,{error:e})}},patchUserPrefs(e){let t=x.loadUserPrefs();x.saveUserPrefs({...t,...e})},loadPanelOpen(){let e=t.get(f);return e===`1`||e!==`0`&&null},savePanelOpen(e){t.set(f,e?`1`:`0`)},loadPanelSize(){let e=t.get(p);return e===`normal`||e===`expanded`||e===`fullscreen`?e:null},savePanelSize(e){t.set(p,e)},loadCalloutDismissed(e){if(!e)return!1;let n=t.get(m);return!!n&&n===e},saveCalloutDismissed(e){e?t.set(m,e):t.remove(m)},loadSidebarCollapsed(){let e=t.get(h);return e===`1`||e!==`0`&&null},saveSidebarCollapsed(e){t.set(h,e?`1`:`0`)},loadActiveModule(){return t.get(g)||null},saveActiveModule(e){t.set(g,e)},loadSeenNewsId(){return t.get(_)||null},saveSeenNewsId(e){t.set(_,e)},loadHistoryCount(){let e=t.get(v);if(!e)return null;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:null},saveHistoryCount(e){t.set(v,String(e))},rememberStorageVersion(e){e&&e!==t.get(i)&&(Gt.debug(`rememberStorageVersion (force-reset on next load)`,{version:e}),t.set(i,e))},saveLoginReturn(e){De.set(y,JSON.stringify(e))},takeLoginReturn(){let e=De.get(y);if(e){De.remove(y);try{let t=JSON.parse(e);return qt(t)&&typeof t.conversationId==`string`&&t.conversationId&&typeof t.draft==`string`?{conversationId:t.conversationId,draft:t.draft}:void 0}catch(e){Gt.warn(`takeLoginReturn parse failed`,{error:e});return}}},loadLoginPromptDismissedIn(){return De.get(b)??void 0},dismissLoginPromptIn(e){De.set(b,e)},clearConversation(){t.remove(u)},reset(){let e=t.get(u);e&&(t.remove(`${s}.draft.${e}`),t.remove(`${s}.messageQueue.${e}`));for(let e of[y,b])De.remove(e);for(let e of[c,l,u,d,p,m,h,g,_,v])t.remove(e);Gt.info(`reset: forgot the visitor`,{scope:r})}};return x}function qt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jt(e){return qt(e)&&typeof e.id==`string`&&e.id.length>0&&typeof e.text==`string`}function Yt(e){if(!qt(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),qt(e.widgetSize)&&typeof e.widgetSize.width==`number`&&typeof e.widgetSize.height==`number`&&(t.widgetSize={width:e.widgetSize.width,height:e.widgetSize.height}),t}const Xt=`6.6.0`,Zt={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,toolResult:()=>void 0,toolDecision:e=>({approved:e.approved}),hostEvent:e=>({name:e.name,data:e.data&&JSON.stringify(e.data)}),messageFeedback:e=>({value:e.value??`none`}),contentView:e=>({section:e.section,count:e.count}),contentOpen:e=>({contentId:e.contentId,contentCollectionId:e.contentCollectionId}),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 Qt(){let e=navigator;return e.globalPrivacyControl===!0||e.doNotTrack===`1`}function $t(){return location.origin+location.pathname}function en(){try{return document.referrer?new URL(document.referrer).origin:``}catch{return``}}function tn(e,t){let n=Math.random(),r=0,i=0,a=/* @__PURE__ */ new Set;function o(e,o){let{tracking:s,publicKey:c,aiAgentDeploymentId:l,mode:u,themeMode:d}=t.getOptions();if(!s.enabled||Qt()||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`,Xt),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`,$t());let h=en();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(_);function v(){return a.delete(_)}_.addEventListener(`load`,v,{once:!0}),_.addEventListener(`error`,v,{once:!0}),_.src=g}let s=[];function c(e,t){if(s&&e!==`handshake`){s.length<60&&s.push([e,t]);return}let n=s??[];s=void 0;for(let[e,t]of n)o(e,t);o(e,t)}function l(e,t){return Zt[e]?.(t)}let u=Object.keys(Zt).filter(e=>Object.hasOwn(Zt,e)).map(t=>e.on(t,e=>c(t,l(t,e))));return()=>{for(let e of u)e();a.clear()}}const nn=`: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, .55) 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{batch as r,computed as i,effect as a,signal as o,useComputed as s,useSignal as c}from"@preact/signals";import{useCallback as l,useEffect as u,useId as d,useLayoutEffect as f,useMemo as p,useRef as m,useState as h}from"preact/hooks";import{Fragment as g,jsx as _,jsxs as v}from"preact/jsx-runtime";import*as y from"streaming-markdown";import{memo as b}from"preact/compat";const x=[`en`,`fr`,`es`,`ar`,`he`,`zh`];function S(e){let t=e?.split(`-`)[0]?.toLowerCase();return x.find(e=>e===t)??`en`}function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function w(e){return C(e)?e.id??e.key:void 0}function T(e,t){return C(e)&&C(t)?Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(e),...Object.keys(t)])].map(n=>[n,T(e[n],t[n])])):Array.isArray(e)&&Array.isArray(t)&&t.length>0&&t.every(e=>w(e)!==void 0)?e.map(e=>T(e,t.find(t=>w(t)===w(e)))):t==null||typeof t==`string`&&!t.trim()?e:t}function E(e,t){let n=t?.toLowerCase(),r=n?.split(`-`)[0],i=e.translations??[],a=i.find(e=>e.locale.toLowerCase()===n)??i.find(e=>e.locale.toLowerCase().split(`-`)[0]===r);if(!a)return e;let{locale:o,...s}=a;return T(e,s)}const D={attach:`Attach files`,file:`File`,attachmentMimeRejected:`{name} isn't a file type this chat accepts.`,attachmentTooLarge:`{name} is too large. Files can be up to {max} together.`,poweredBy:`Powered by {name}`,attachmentTooMany:`The attachment limit is {count}.`,attachmentUploadFailed:`{name} couldn't be uploaded.`,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`,dropZoneRejected:`These files can't be attached here`,errorGeneric:`Something went wrong`,errorRateLimited:`Too many requests — please try again in a moment.`,errorRateLimitedIn:`Too many requests — please try again in {seconds} s.`,errorOffline:`Can't reach the server. Check your connection and try again.`,errorServer:`Something went wrong on our side. Please try again.`,errorOriginNotAllowed:`This chat isn't set up for this website yet.`,errorMessageTooLong:`That message is too long. Shorten it and send it again.`,errorReconnecting:`Connection lost. Reconnecting…`,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`,launcherAsk:`Ask {name}`,micBlocked:`The microphone is blocked for this site, so voice input can't start.`,micStart:`Start voice input`,micStop:`Stop voice input`,moreActions:`More actions`,newConversation:`New chat`,panelTitle:`Chat`,popOut:`Open in new tab`,resizeHandle:`Drag to resize`,scrollToBottom:`Scroll to latest`,send:`Send`,queueMessage:`Queue message`,removeQueuedMessage:`Remove queued message`,removeAttachment:`Remove {name}`,suggestedReplies:`Suggested replies`,compactingContext:`Optimizing conversation context…`,soundOff:`Sound off`,soundOn:`Sound on`,talkToOperator:`Talk to a person`,connectingOperator:`Connecting you to a person…`,noOperatorAvailable:`No one's available right now — leave your details and we'll follow up.`,chattingWithOperator:`You're chatting with {operator}`,operatorBadgeTitle:`Live chat`,chatNotice:`You're chatting with an AI assistant.`,cancelOperatorRequest:`Keep chatting with the AI`,loginPrompt:`Log in for faster, more personalized support`,loginAction:`Log in`,loginRequired:`Log in to chat with us`,loginExpired:`Your login expired. Log in to continue this chat.`,loginExpiredGuest:`Your login expired. Log in to continue this chat, or start a new conversation as a guest.`,startAsGuest:`Start new conversation`,loggedInAs:`Logged in as {name}`,loggedIn:`Logged in`,dismissLoginPrompt:`Hide`,emailTranscript:`Email transcript`,emailTranscriptPrompt:`Get a copy of this conversation by email.`,emailTranscriptEmailLabel:`Email address`,emailTranscriptSend:`Send transcript`,emailTranscriptSending:`Sending…`,emailTranscriptSent:`Sent to {email}.`,emailTranscriptAlreadySent:`This conversation was already emailed. Send a new message to email it again.`,emailTranscriptLimited:`You've reached the limit for now. Try again later.`,emailTranscriptFailed:`Couldn't send it. Try again.`,emailTranscriptNotDelivered:`Couldn't send to this address. Check it and try again.`,emailTranscriptCancel:`Cancel`,emailTranscriptDone:`Done`,stop:`Stop`,theme:`Theme`,themeAuto:`Auto`,themeDark:`Dark`,themeLight:`Light`,textSize:`Text size`,textSizeSmall:`Small`,textSizeNormal:`Normal`,textSizeLarge:`Large`,loading:`Loading…`,visualPreparing:`Preparing visual…`,visualError:`This visual could not be displayed.`,visualPartial:`Some parts of this visual could not be displayed.`,visualSoldOut:`Sold out`,visualCartEmpty:`Your cart is empty.`,visualQuantity:`Qty`,visualChoose:`Choose`,thinking:`Thinking…`,thought:`Thought`,thoughtFor:`Thought for {time}`,toolResult:`Result`,sources:`Sources`,feedbackUp:`Good response`,feedbackDown:`Bad response`,feedbackThanks:`Thanks for your feedback`,copy:`Copy`,copied:`Copied`,copyTicketReference:`Ticket {reference}, copy`,tabHome:`Home`,tabConversations:`Chats`,tabHelp:`Help`,tabNews:`News`,modulesEmpty:`Nothing here yet`,chatUnavailable:`This chat isn't available right now`,moduleBack:`Back`,contentLoading:`Loading…`,contentHelpful:`Was this helpful?`,homeGreeting:`How can we help?`,homeGreetingNamed:`Hi {name} 👋`,homeGreetingLead:`How can we help?`,homeSearchPlaceholder:`Search for help`,homeAskPlaceholder:`Ask a question…`,homeWhatsNew:`What's new`,homeContentTitle:`Popular articles`,homeStatus:`Status`,helpTitle:`Help`,helpSearchPlaceholder:`Search for help`,helpEmpty:`No help articles yet`,helpLoading:`Loading help…`,helpSearchEmpty:`No results for “{query}”`,helpShowMore:`Show more`,newsTitle:`News`,newsEmpty:`No news yet`,newsLoading:`Loading news…`,newsShowMore:`Show more`,newsUnseen:`New post`,unread:`Unread`,formRequired:`This field is required`,formInvalidEmail:`Enter a valid email address`,formInvalidTel:`Enter a valid phone number`,formInvalidNumber:`Enter a valid number`,formOtherPlaceholder:`Type your answer…`,inputRequired:`Questions for you`,askFallbackQuestion:`Please provide the missing information.`,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`,decline:`Decline`,changeAnswer:`Change answer`,approvalPrompt:`{action}?`,approvalEditHint:`You can change your answer until this step continues.`,stepInput:`Input`,stepWorking:`Working`,stepWorkingOnIt:`Working on it…`,stepNeedsYourApproval:`Needs your approval`,stepWaitingForVisitor:`Waiting for the visitor`,stepApproved:`Approved`,stepDeclined:`Declined`,stepReplaced:`Replaced`,stepFailed:`Failed`,stepDidNotWork:`Didn't work`,decidedYouApproved:`You approved`,decidedYouDeclined:`You declined`,decidedVisitorApproved:`Visitor approved`,decidedVisitorDeclined:`Visitor declined`,decidedTeamApproved:`Approved by a team member`,decidedTeamDeclined:`Declined by a team member`,decidedMemberApproved:`Approved by {name}`,decidedMemberDeclined:`Declined by {name}`,stepRawData:`Raw data`,decidedRulesApproved:`Auto-approved`,decidedRulesDeclined:`Auto-declined`,edit:`Edit`,statusError:`Error`,toolStepsFailed:`{count} failed`,statusStopped:`Stopped`,toolStepsStopped:`Stopped after {count} steps`,toolStepsStoppedOne:`Stopped after 1 step`},O={en:D,fr:{attach:`Joindre des fichiers`,file:`Fichier`,attachmentMimeRejected:`{name} n'est pas un type de fichier accepté ici.`,attachmentTooLarge:`{name} est trop volumineux. Les fichiers peuvent faire jusqu'à {max} au total.`,poweredBy:`Propulsé par {name}`,attachmentTooMany:`Limite de pièces jointes : {count}.`,attachmentUploadFailed:`{name} n'a pas pu être envoyé.`,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`,dropZoneRejected:`Ces fichiers ne peuvent pas être joints ici`,errorGeneric:`Une erreur s'est produite`,errorRateLimited:`Trop de requêtes — veuillez réessayer dans un instant.`,errorRateLimitedIn:`Trop de requêtes — veuillez réessayer dans {seconds} s.`,errorOffline:`Impossible de joindre le serveur. Vérifiez votre connexion et réessayez.`,errorServer:`Un problème est survenu de notre côté. Veuillez réessayer.`,errorOriginNotAllowed:`Ce chat n'est pas encore configuré pour ce site.`,errorMessageTooLong:`Ce message est trop long. Raccourcissez-le et renvoyez-le.`,errorReconnecting:`Connexion perdue. Reconnexion…`,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`,launcherAsk:`Demander à {name}`,micBlocked:`Le micro est bloqué pour ce site : la saisie vocale ne peut pas démarrer.`,micStart:`Démarrer la saisie vocale`,micStop:`Arrêter la saisie vocale`,moreActions:`Plus d'actions`,newConversation:`Nouveau chat`,panelTitle:`Chat`,popOut:`Ouvrir dans un nouvel onglet`,resizeHandle:`Glisser pour redimensionner`,scrollToBottom:`Aller au plus récent`,send:`Envoyer`,queueMessage:`Mettre le message en attente`,removeQueuedMessage:`Retirer le message en attente`,removeAttachment:`Retirer {name}`,suggestedReplies:`Réponses suggérées`,compactingContext:`Optimisation du contexte de la conversation…`,soundOff:`Son désactivé`,soundOn:`Son activé`,talkToOperator:`Parler à une personne`,connectingOperator:`Mise en relation avec une personne…`,noOperatorAvailable:`Personne n'est disponible pour le moment — laissez vos coordonnées et nous reviendrons vers vous.`,chattingWithOperator:`Vous discutez avec {operator}`,operatorBadgeTitle:`Chat en direct`,chatNotice:`Vous discutez avec un assistant IA.`,cancelOperatorRequest:`Continuer avec l'IA`,loginPrompt:`Connectez-vous pour une aide plus rapide et personnalisée`,loginAction:`Se connecter`,loginRequired:`Connectez-vous pour discuter avec nous`,loginExpired:`Votre connexion a expiré. Connectez-vous pour poursuivre cette conversation.`,loginExpiredGuest:`Votre connexion a expiré. Connectez-vous pour poursuivre cette conversation, ou démarrez-en une nouvelle en tant qu'invité.`,startAsGuest:`Démarrer une nouvelle conversation`,loggedInAs:`Connecté en tant que {name}`,loggedIn:`Connecté`,dismissLoginPrompt:`Masquer`,emailTranscript:`Envoyer la transcription`,emailTranscriptPrompt:`Recevez une copie de cette conversation par e-mail.`,emailTranscriptEmailLabel:`Adresse e-mail`,emailTranscriptSend:`Envoyer la transcription`,emailTranscriptSending:`Envoi…`,emailTranscriptSent:`Envoyé à {email}.`,emailTranscriptAlreadySent:`Cette conversation a déjà été envoyée. Envoyez un nouveau message pour l'envoyer à nouveau.`,emailTranscriptLimited:`Vous avez atteint la limite pour le moment. Réessayez plus tard.`,emailTranscriptFailed:`Envoi impossible. Réessayez.`,emailTranscriptNotDelivered:`Envoi impossible à cette adresse. Vérifiez-la et réessayez.`,emailTranscriptCancel:`Annuler`,emailTranscriptDone:`Terminé`,stop:`Arrêter`,theme:`Thème`,themeAuto:`Auto`,themeDark:`Sombre`,themeLight:`Clair`,textSize:`Taille du texte`,textSizeSmall:`Petite`,textSizeNormal:`Normale`,textSizeLarge:`Grande`,loading:`Chargement…`,visualPreparing:`Préparation du visuel…`,visualError:`Ce visuel n’a pas pu être affiché.`,visualPartial:`Certaines parties de ce visuel n’ont pas pu être affichées.`,visualSoldOut:`Épuisé`,visualCartEmpty:`Votre panier est vide.`,visualQuantity:`Qté`,visualChoose:`Choisissez`,thinking:`Réflexion…`,thought:`Réflexion`,thoughtFor:`Réflexion : {time}`,toolResult:`Résultat`,sources:`Sources`,feedbackUp:`Bonne réponse`,feedbackDown:`Mauvaise réponse`,feedbackThanks:`Merci pour votre retour`,copy:`Copier`,copied:`Copié`,copyTicketReference:`Ticket {reference}, copier`,tabHome:`Accueil`,tabConversations:`Chats`,tabHelp:`Aide`,tabNews:`Actualités`,modulesEmpty:`Rien pour le moment`,chatUnavailable:`Ce chat n'est pas disponible pour le moment`,moduleBack:`Retour`,contentLoading:`Chargement…`,contentHelpful:`Cela vous a-t-il aidé ?`,homeGreeting:`Comment pouvons-nous vous aider ?`,homeGreetingNamed:`Bonjour {name} 👋`,homeGreetingLead:`Comment pouvons-nous vous aider ?`,homeSearchPlaceholder:`Rechercher de l'aide`,homeAskPlaceholder:`Posez une question…`,homeWhatsNew:`Nouveautés`,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 pour «\xA0{query}\xA0»`,helpShowMore:`Afficher plus`,newsTitle:`Actualités`,newsEmpty:`Aucune actualité pour le moment`,newsLoading:`Chargement des actualités…`,newsShowMore:`Afficher plus`,newsUnseen:`Nouvelle publication`,unread:`Non lu`,formRequired:`Ce champ est obligatoire`,formInvalidEmail:`Saisissez une adresse e-mail valide`,formInvalidTel:`Saisissez un numéro de téléphone valide`,formInvalidNumber:`Saisissez un nombre valide`,formOtherPlaceholder:`Saisissez votre réponse…`,inputRequired:`Questions pour vous`,askFallbackQuestion:`Veuillez fournir les informations manquantes.`,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`,decline:`Refuser`,changeAnswer:`Modifier la réponse`,approvalPrompt:`{action} ?`,approvalEditHint:`Vous pouvez modifier votre réponse jusqu'à la reprise de cette étape.`,stepInput:`Entrée`,stepWorking:`En cours`,stepWorkingOnIt:`En cours…`,stepNeedsYourApproval:`Votre accord est requis`,stepWaitingForVisitor:`En attente du visiteur`,stepApproved:`Approuvé`,stepDeclined:`Refusé`,stepReplaced:`Remplacé`,stepFailed:`Échec`,stepDidNotWork:`N'a pas fonctionné`,decidedYouApproved:`Vous avez approuvé`,decidedYouDeclined:`Vous avez refusé`,decidedVisitorApproved:`Approuvé par le visiteur`,decidedVisitorDeclined:`Refusé par le visiteur`,decidedTeamApproved:`Approuvé par un membre de l'équipe`,decidedTeamDeclined:`Refusé par un membre de l'équipe`,decidedMemberApproved:`Approuvé par {name}`,decidedMemberDeclined:`Refusé par {name}`,stepRawData:`Données brutes`,decidedRulesApproved:`Approuvé automatiquement`,decidedRulesDeclined:`Refusé automatiquement`,edit:`Modifier`,statusError:`Erreur`,toolStepsFailed:`{count} en échec`,statusStopped:`Arrêté`,toolStepsStopped:`Arrêté après {count} étapes`,toolStepsStoppedOne:`Arrêté après 1 étape`},es:{attach:`Adjuntar archivos`,file:`Archivo`,attachmentMimeRejected:`{name} no es un tipo de archivo que acepte este chat.`,attachmentTooLarge:`{name} es demasiado grande. Los archivos pueden ocupar hasta {max} en total.`,poweredBy:`Con la tecnología de {name}`,attachmentTooMany:`Límite de adjuntos: {count}.`,attachmentUploadFailed:`No se pudo subir {name}.`,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`,dropZoneRejected:`Estos archivos no se pueden adjuntar aquí`,errorGeneric:`Algo salió mal`,errorRateLimited:`Demasiadas solicitudes: inténtalo de nuevo en un momento.`,errorRateLimitedIn:`Demasiadas solicitudes: inténtalo de nuevo en {seconds} s.`,errorOffline:`No se puede conectar con el servidor. Revisa tu conexión e inténtalo de nuevo.`,errorServer:`Algo salió mal por nuestra parte. Inténtalo de nuevo.`,errorOriginNotAllowed:`Este chat aún no está configurado para este sitio web.`,errorMessageTooLong:`Ese mensaje es demasiado largo. Acórtalo y envíalo de nuevo.`,errorReconnecting:`Se perdió la conexión. Reconectando…`,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`,launcherAsk:`Pregúntale a {name}`,micBlocked:`El micrófono está bloqueado para este sitio, así que la entrada de voz no puede iniciarse.`,micStart:`Iniciar entrada de voz`,micStop:`Detener entrada de voz`,moreActions:`Más acciones`,newConversation:`Nuevo chat`,panelTitle:`Chat`,popOut:`Abrir en una pestaña nueva`,resizeHandle:`Arrastra para cambiar el tamaño`,scrollToBottom:`Ir a lo más reciente`,send:`Enviar`,queueMessage:`Poner mensaje en cola`,removeQueuedMessage:`Quitar mensaje de la cola`,removeAttachment:`Quitar {name}`,suggestedReplies:`Respuestas sugeridas`,compactingContext:`Optimizando el contexto de la conversación…`,soundOff:`Sonido desactivado`,soundOn:`Sonido activado`,talkToOperator:`Hablar con una persona`,connectingOperator:`Conectándote con una persona…`,noOperatorAvailable:`Nadie está disponible ahora — deja tus datos y te contactaremos.`,chattingWithOperator:`Estás chateando con {operator}`,operatorBadgeTitle:`Chat en vivo`,chatNotice:`Estás chateando con un asistente de IA.`,cancelOperatorRequest:`Seguir con la IA`,loginPrompt:`Inicia sesión para recibir una ayuda más rápida y personalizada`,loginAction:`Iniciar sesión`,loginRequired:`Inicia sesión para chatear con nosotros`,loginExpired:`Tu sesión ha caducado. Inicia sesión para continuar esta conversación.`,loginExpiredGuest:`Tu sesión ha caducado. Inicia sesión para continuar esta conversación o empieza una nueva como invitado.`,startAsGuest:`Empezar una nueva conversación`,loggedInAs:`Sesión iniciada como {name}`,loggedIn:`Sesión iniciada`,dismissLoginPrompt:`Ocultar`,emailTranscript:`Enviar transcripción`,emailTranscriptPrompt:`Recibe una copia de esta conversación por correo.`,emailTranscriptEmailLabel:`Correo electrónico`,emailTranscriptSend:`Enviar transcripción`,emailTranscriptSending:`Enviando…`,emailTranscriptSent:`Enviado a {email}.`,emailTranscriptAlreadySent:`Esta conversación ya se envió. Envía un mensaje nuevo para enviarla otra vez.`,emailTranscriptLimited:`Has alcanzado el límite por ahora. Inténtalo más tarde.`,emailTranscriptFailed:`No se pudo enviar. Inténtalo de nuevo.`,emailTranscriptNotDelivered:`No se pudo enviar a esta dirección. Revísala e inténtalo de nuevo.`,emailTranscriptCancel:`Cancelar`,emailTranscriptDone:`Listo`,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…`,visualPreparing:`Preparando visualización…`,visualError:`No se pudo mostrar esta visualización.`,visualPartial:`No se pudieron mostrar algunas partes de esta visualización.`,visualSoldOut:`Agotado`,visualCartEmpty:`Tu carrito está vacío.`,visualQuantity:`Cant.`,visualChoose:`Elige`,thinking:`Pensando…`,thought:`Razonamiento`,thoughtFor:`Razonó durante {time}`,toolResult:`Resultado`,sources:`Fuentes`,feedbackUp:`Buena respuesta`,feedbackDown:`Mala respuesta`,feedbackThanks:`Gracias por tu opinión`,copy:`Copiar`,copied:`Copiado`,copyTicketReference:`Ticket {reference}, copiar`,tabHome:`Inicio`,tabConversations:`Chats`,tabHelp:`Ayuda`,tabNews:`Novedades`,modulesEmpty:`Aún no hay nada aquí`,chatUnavailable:`Este chat no está disponible en este momento`,moduleBack:`Atrás`,contentLoading:`Cargando…`,contentHelpful:`¿Te resultó útil?`,homeGreeting:`¿Cómo podemos ayudarte?`,homeGreetingNamed:`Hola, {name} 👋`,homeGreetingLead:`¿Cómo podemos ayudarte?`,homeSearchPlaceholder:`Buscar ayuda`,homeAskPlaceholder:`Haz una pregunta…`,homeWhatsNew:`Lo nuevo`,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:`Sin resultados para «{query}»`,helpShowMore:`Mostrar más`,newsTitle:`Novedades`,newsEmpty:`Aún no hay novedades`,newsLoading:`Cargando novedades…`,newsShowMore:`Mostrar más`,newsUnseen:`Publicación nueva`,unread:`No leído`,formRequired:`Este campo es obligatorio`,formInvalidEmail:`Introduce un correo electrónico válido`,formInvalidTel:`Introduce un número de teléfono válido`,formInvalidNumber:`Introduce un número válido`,formOtherPlaceholder:`Escribe tu respuesta…`,inputRequired:`Preguntas para ti`,askFallbackQuestion:`Indica la información que falta.`,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`,decline:`Rechazar`,changeAnswer:`Cambiar respuesta`,approvalPrompt:`¿{action}?`,approvalEditHint:`Puedes cambiar tu respuesta hasta que este paso continúe.`,stepInput:`Entrada`,stepWorking:`En curso`,stepWorkingOnIt:`En curso…`,stepNeedsYourApproval:`Necesita tu aprobación`,stepWaitingForVisitor:`Esperando al visitante`,stepApproved:`Aprobado`,stepDeclined:`Rechazado`,stepReplaced:`Reemplazado`,stepFailed:`Falló`,stepDidNotWork:`No funcionó`,decidedYouApproved:`Lo aprobaste`,decidedYouDeclined:`Lo rechazaste`,decidedVisitorApproved:`El visitante aprobó`,decidedVisitorDeclined:`El visitante rechazó`,decidedTeamApproved:`Aprobado por un miembro del equipo`,decidedTeamDeclined:`Rechazado por un miembro del equipo`,decidedMemberApproved:`Aprobado por {name}`,decidedMemberDeclined:`Rechazado por {name}`,stepRawData:`Datos sin procesar`,decidedRulesApproved:`Aprobado automáticamente`,decidedRulesDeclined:`Rechazado automáticamente`,edit:`Editar`,statusError:`Error`,toolStepsFailed:`{count} con error`,statusStopped:`Detenido`,toolStepsStopped:`Detenido tras {count} pasos`,toolStepsStoppedOne:`Detenido tras 1 paso`},ar:{attach:`إرفاق ملفات`,file:`ملف`,attachmentMimeRejected:`نوع الملف {name} غير مقبول في هذه المحادثة.`,attachmentTooLarge:`الملف {name} كبير جدًا. يمكن أن يصل حجم الملفات معًا إلى {max}.`,poweredBy:`مدعوم من {name}`,attachmentTooMany:`الحد الأقصى للمرفقات: {count}.`,attachmentUploadFailed:`تعذّر رفع {name}.`,conversationLoading:`جارٍ تحميل الدردشة…`,loadPreviousMessages:`تحميل الرسائل السابقة`,close:`إغلاق`,collapse:`طيّ`,collapseSidebar:`طيّ الشريط الجانبي`,composerPlaceholder:`اكتب رسالة…`,dateLastWeek:`آخر ٧ أيام`,dateOlder:`أقدم`,dateToday:`اليوم`,dateYesterday:`أمس`,dropZone:`أفلت الملفات لإرفاقها`,dropZoneRejected:`لا يمكن إرفاق هذه الملفات هنا`,errorGeneric:`حدث خطأ ما`,errorRateLimited:`طلبات كثيرة جدًا — يرجى المحاولة بعد لحظة.`,errorRateLimitedIn:`طلبات كثيرة جدًا — يرجى المحاولة بعد {seconds} ث.`,errorOffline:`تعذّر الوصول إلى الخادم. تحقّق من اتصالك وحاول مرة أخرى.`,errorServer:`حدث خطأ من جهتنا. يرجى المحاولة مرة أخرى.`,errorOriginNotAllowed:`هذه المحادثة غير مُعدّة لهذا الموقع بعد.`,errorMessageTooLong:`هذه الرسالة طويلة جدًا. اختصرها وأرسلها مرة أخرى.`,errorReconnecting:`انقطع الاتصال. جارٍ إعادة الاتصال…`,errorRetry:`إعادة المحاولة`,expand:`توسيع`,expandSidebar:`توسيع الشريط الجانبي`,exitFullscreen:`إنهاء ملء الشاشة`,fullscreen:`ملء الشاشة`,history:`السجل`,historyBack:`العودة إلى الدردشة`,historyEmpty:`لا توجد دردشات سابقة بعد`,historyContinue:`متابعة الدردشة`,historyLoading:`جارٍ تحميل دردشاتك…`,historyTitle:`سجل الدردشات`,loadMoreConversations:`تحميل المزيد من المحادثات`,language:`اللغة`,launcherOpen:`فتح الدردشة`,launcherAsk:`اسأل {name}`,micBlocked:`الميكروفون محظور لهذا الموقع، لذا لا يمكن بدء الإدخال الصوتي.`,micStart:`بدء الإدخال الصوتي`,micStop:`إيقاف الإدخال الصوتي`,moreActions:`إجراءات إضافية`,newConversation:`دردشة جديدة`,panelTitle:`الدردشة`,popOut:`فتح في علامة تبويب جديدة`,resizeHandle:`اسحب لتغيير الحجم`,scrollToBottom:`الانتقال إلى الأحدث`,send:`إرسال`,queueMessage:`إضافة الرسالة إلى قائمة الانتظار`,removeQueuedMessage:`إزالة الرسالة من قائمة الانتظار`,removeAttachment:`إزالة {name}`,suggestedReplies:`ردود مقترحة`,compactingContext:`جارٍ تحسين سياق المحادثة…`,soundOff:`كتم الصوت`,soundOn:`تشغيل الصوت`,talkToOperator:`التحدث إلى شخص`,connectingOperator:`جارٍ توصيلك بشخص…`,noOperatorAvailable:`لا يوجد موظفون متاحون الآن — اترك بياناتك وسنتواصل معك.`,chattingWithOperator:`أنت تتحدث مع {operator}`,operatorBadgeTitle:`محادثة مباشرة`,chatNotice:`أنت تتحدث مع مساعد ذكاء اصطناعي.`,cancelOperatorRequest:`متابعة المحادثة مع الذكاء الاصطناعي`,loginPrompt:`سجّل الدخول للحصول على دعم أسرع ومخصّص لك`,loginAction:`تسجيل الدخول`,loginRequired:`سجّل الدخول للدردشة معنا`,loginExpired:`انتهت صلاحية تسجيل دخولك. سجّل الدخول لمتابعة هذه المحادثة.`,loginExpiredGuest:`انتهت صلاحية تسجيل دخولك. سجّل الدخول لمتابعة هذه المحادثة، أو ابدأ محادثة جديدة كضيف.`,startAsGuest:`بدء محادثة جديدة`,loggedInAs:`تم تسجيل الدخول باسم {name}`,loggedIn:`تم تسجيل الدخول`,dismissLoginPrompt:`إخفاء`,emailTranscript:`إرسال نص المحادثة`,emailTranscriptPrompt:`احصل على نسخة من هذه المحادثة عبر البريد الإلكتروني.`,emailTranscriptEmailLabel:`عنوان البريد الإلكتروني`,emailTranscriptSend:`إرسال نص المحادثة`,emailTranscriptSending:`جارٍ الإرسال…`,emailTranscriptSent:`تم الإرسال إلى {email}.`,emailTranscriptAlreadySent:`تم إرسال هذه المحادثة بالفعل. أرسل رسالة جديدة لإرسالها مرة أخرى.`,emailTranscriptLimited:`لقد بلغت الحد المسموح به حاليًا. حاول مرة أخرى لاحقًا.`,emailTranscriptFailed:`تعذّر الإرسال. حاول مرة أخرى.`,emailTranscriptNotDelivered:`تعذّر الإرسال إلى هذا العنوان. تحقّق منه وحاول مرة أخرى.`,emailTranscriptCancel:`إلغاء`,emailTranscriptDone:`تم`,stop:`إيقاف`,theme:`المظهر`,themeAuto:`تلقائي`,themeDark:`داكن`,themeLight:`فاتح`,textSize:`حجم النص`,textSizeSmall:`صغير`,textSizeNormal:`عادي`,textSizeLarge:`كبير`,loading:`جارٍ التحميل…`,visualPreparing:`جارٍ إعداد المحتوى المرئي…`,visualError:`تعذر عرض هذا المحتوى المرئي.`,visualPartial:`تعذر عرض بعض أجزاء هذا المحتوى المرئي.`,visualSoldOut:`نفدت الكمية`,visualCartEmpty:`سلتك فارغة.`,visualQuantity:`الكمية`,visualChoose:`اختر`,thinking:`يفكّر…`,thought:`تفكير`,thoughtFor:`فكّر لمدة {time}`,toolResult:`النتيجة`,sources:`المصادر`,feedbackUp:`رد جيد`,feedbackDown:`رد سيئ`,feedbackThanks:`شكرًا على ملاحظاتك`,copy:`نسخ`,copied:`تم النسخ`,copyTicketReference:`التذكرة {reference}، نسخ`,tabHome:`الرئيسية`,tabConversations:`الدردشات`,tabHelp:`المساعدة`,tabNews:`الأخبار`,modulesEmpty:`لا شيء هنا بعد`,chatUnavailable:`هذه المحادثة غير متاحة حالياً`,moduleBack:`رجوع`,contentLoading:`جارٍ التحميل…`,contentHelpful:`هل كان هذا مفيدًا؟`,homeGreeting:`كيف يمكننا مساعدتك؟`,homeGreetingNamed:`مرحبًا {name} 👋`,homeGreetingLead:`كيف يمكننا مساعدتك؟`,homeSearchPlaceholder:`ابحث عن مساعدة`,homeAskPlaceholder:`اطرح سؤالاً…`,homeWhatsNew:`ما الجديد`,homeContentTitle:`مقالات شائعة`,homeStatus:`الحالة`,helpTitle:`المساعدة`,helpSearchPlaceholder:`ابحث عن مساعدة`,helpEmpty:`لا توجد مقالات مساعدة بعد`,helpLoading:`جارٍ تحميل المساعدة…`,helpSearchEmpty:`لا نتائج لـ «{query}»`,helpShowMore:`عرض المزيد`,newsTitle:`الأخبار`,newsEmpty:`لا توجد أخبار بعد`,newsLoading:`جارٍ تحميل الأخبار…`,newsShowMore:`عرض المزيد`,newsUnseen:`منشور جديد`,unread:`غير مقروء`,formRequired:`هذا الحقل مطلوب`,formInvalidEmail:`أدخل بريدًا إلكترونيًا صحيحًا`,formInvalidTel:`أدخل رقم هاتف صحيحًا`,formInvalidNumber:`أدخل رقمًا صحيحًا`,formOtherPlaceholder:`اكتب إجابتك…`,inputRequired:`أسئلة لك`,askFallbackQuestion:`يرجى تقديم المعلومات الناقصة.`,inputBadge:`أسئلة`,inputAnswered:`تمت الإجابة`,inputSkipped:`تم التخطي`,showOptions:`إظهار الخيارات`,hideOptions:`إخفاء الخيارات`,qtypeText:`إجابتك`,qtypeEmail:`عنوان البريد الإلكتروني`,qtypePhone:`رقم الهاتف`,qtypeNumber:`رقم`,qtypeDate:`تاريخ`,qtypeChooseOne:`اختر واحدًا`,qtypeChooseAny:`اختر أيًا`,qtypeBoolean:`نعم / لا`,inputSubmit:`إرسال الإجابات`,inputSubmitHint:`Enter للإرسال · Shift+Enter = سطر جديد`,inputSkip:`تخطٍّ`,confirmYes:`نعم`,confirmNo:`لا`,approve:`موافقة`,decline:`رفض`,changeAnswer:`تغيير الإجابة`,approvalPrompt:`{action}؟`,approvalEditHint:`يمكنك تغيير إجابتك حتى تستأنف هذه الخطوة.`,stepInput:`المدخلات`,stepWorking:`قيد التنفيذ`,stepWorkingOnIt:`جارٍ التنفيذ…`,stepNeedsYourApproval:`بحاجة إلى موافقتك`,stepWaitingForVisitor:`بانتظار الزائر`,stepApproved:`تمت الموافقة`,stepDeclined:`مرفوض`,stepReplaced:`تم الاستبدال`,stepFailed:`فشل`,stepDidNotWork:`لم ينجح`,decidedYouApproved:`وافقت`,decidedYouDeclined:`رفضت`,decidedVisitorApproved:`وافق الزائر`,decidedVisitorDeclined:`رفض الزائر`,decidedTeamApproved:`وافق عضو في الفريق`,decidedTeamDeclined:`رفض عضو في الفريق`,decidedMemberApproved:`وافق {name}`,decidedMemberDeclined:`رفض {name}`,stepRawData:`البيانات الأولية`,decidedRulesApproved:`تمت الموافقة تلقائيًا`,decidedRulesDeclined:`رُفض تلقائيًا`,edit:`تعديل`,statusError:`خطأ`,toolStepsFailed:`فشل {count}`,statusStopped:`أُوقف`,toolStepsStopped:`أُوقف بعد {count} خطوات`,toolStepsStoppedOne:`أُوقف بعد خطوة واحدة`},he:{attach:`צירוף קבצים`,file:`קובץ`,attachmentMimeRejected:`הקובץ {name} אינו מסוג שהצ׳אט הזה מקבל.`,attachmentTooLarge:`הקובץ {name} גדול מדי. הקבצים יכולים להגיע יחד עד {max}.`,poweredBy:`מופעל על ידי {name}`,attachmentTooMany:`מספר הקבצים המרבי לצירוף: {count}.`,attachmentUploadFailed:`לא ניתן היה להעלות את {name}.`,conversationLoading:`טוען צ׳אט…`,loadPreviousMessages:`טעינת הודעות קודמות`,close:`סגירה`,collapse:`כיווץ`,collapseSidebar:`כיווץ סרגל הצד`,composerPlaceholder:`כתוב הודעה…`,dateLastWeek:`7 הימים האחרונים`,dateOlder:`ישן יותר`,dateToday:`היום`,dateYesterday:`אתמול`,dropZone:`שחרר קבצים כדי לצרף`,dropZoneRejected:`לא ניתן לצרף כאן את הקבצים האלה`,errorGeneric:`משהו השתבש`,errorRateLimited:`יותר מדי בקשות — נסה שוב בעוד רגע.`,errorRateLimitedIn:`יותר מדי בקשות — נסה שוב בעוד {seconds} שנ׳.`,errorOffline:`אין חיבור לשרת. בדוק את החיבור ונסה שוב.`,errorServer:`משהו השתבש אצלנו. נסה שוב.`,errorOriginNotAllowed:`הצ'אט הזה עדיין לא מוגדר לאתר הזה.`,errorMessageTooLong:`ההודעה הזו ארוכה מדי. קצרו אותה ושלחו שוב.`,errorReconnecting:`החיבור אבד. מתחבר מחדש…`,errorRetry:`נסה שוב`,expand:`הרחבה`,expandSidebar:`הרחבת סרגל הצד`,exitFullscreen:`יציאה ממסך מלא`,fullscreen:`מסך מלא`,history:`היסטוריה`,historyBack:`חזרה לצ׳אט`,historyEmpty:`אין עדיין צ׳אטים קודמים`,historyContinue:`המשך צ׳אט`,historyLoading:`טוען את הצ׳אטים שלך…`,historyTitle:`היסטוריית צ׳אטים`,loadMoreConversations:`טעינת שיחות נוספות`,language:`שפה`,launcherOpen:`פתיחת צ׳אט`,launcherAsk:`לשאול את {name}`,micBlocked:`המיקרופון חסום באתר הזה, ולכן אי אפשר להתחיל קלט קולי.`,micStart:`התחלת קלט קולי`,micStop:`עצירת קלט קולי`,moreActions:`פעולות נוספות`,newConversation:`צ׳אט חדש`,panelTitle:`צ׳אט`,popOut:`פתיחה בכרטיסייה חדשה`,resizeHandle:`גרור לשינוי הגודל`,scrollToBottom:`מעבר לחדש ביותר`,send:`שליחה`,queueMessage:`הוספת ההודעה לתור`,removeQueuedMessage:`הסרת ההודעה מהתור`,removeAttachment:`הסרת {name}`,suggestedReplies:`תשובות מוצעות`,compactingContext:`מבצע אופטימיזציה להקשר השיחה…`,soundOff:`השתקת הצליל`,soundOn:`הפעלת הצליל`,talkToOperator:`דברו עם אדם`,connectingOperator:`מחברים אותך לאדם…`,noOperatorAvailable:`אין נציגים זמינים כעת — השאר את הפרטים שלך ונחזור אליך.`,chattingWithOperator:`אתה מצ׳וטט עם {operator}`,operatorBadgeTitle:`צ׳אט חי`,chatNotice:`אתה מצ׳וטט עם עוזר בינה מלאכותית.`,cancelOperatorRequest:`המשך לשוחח עם ה-AI`,loginPrompt:`התחברו לקבלת תמיכה מהירה ומותאמת אישית`,loginAction:`התחברות`,loginRequired:`התחברו כדי לשוחח איתנו`,loginExpired:`פג תוקף ההתחברות שלך. התחברו כדי להמשיך בשיחה הזו.`,loginExpiredGuest:`פג תוקף ההתחברות שלך. התחברו כדי להמשיך בשיחה הזו, או התחילו שיחה חדשה כאורחים.`,startAsGuest:`התחלת שיחה חדשה`,loggedInAs:`מחובר/ת בתור {name}`,loggedIn:`מחובר/ת`,dismissLoginPrompt:`הסתרה`,emailTranscript:`שליחת תמליל בדוא״ל`,emailTranscriptPrompt:`קבלו עותק של השיחה הזו בדוא״ל.`,emailTranscriptEmailLabel:`כתובת דוא״ל`,emailTranscriptSend:`שליחת התמליל`,emailTranscriptSending:`שולחים…`,emailTranscriptSent:`נשלח אל {email}.`,emailTranscriptAlreadySent:`השיחה הזו כבר נשלחה. שלחו הודעה חדשה כדי לשלוח אותה שוב.`,emailTranscriptLimited:`הגעתם למגבלה כרגע. נסו שוב מאוחר יותר.`,emailTranscriptFailed:`השליחה נכשלה. נסו שוב.`,emailTranscriptNotDelivered:`לא ניתן לשלוח לכתובת הזו. בדקו אותה ונסו שוב.`,emailTranscriptCancel:`ביטול`,emailTranscriptDone:`סיום`,stop:`עצירה`,theme:`ערכת נושא`,themeAuto:`אוטומטי`,themeDark:`כהה`,themeLight:`בהיר`,textSize:`גודל טקסט`,textSizeSmall:`קטן`,textSizeNormal:`רגיל`,textSizeLarge:`גדול`,loading:`טוען…`,visualPreparing:`מכין תצוגה…`,visualError:`לא ניתן היה להציג תצוגה זו.`,visualPartial:`לא ניתן היה להציג חלקים מתצוגה זו.`,visualSoldOut:`אזל מהמלאי`,visualCartEmpty:`העגלה שלך ריקה.`,visualQuantity:`כמות`,visualChoose:`בחרו`,thinking:`חושב…`,thought:`מחשבה`,thoughtFor:`חשב במשך {time}`,toolResult:`תוצאה`,sources:`מקורות`,feedbackUp:`תשובה טובה`,feedbackDown:`תשובה גרועה`,feedbackThanks:`תודה על המשוב`,copy:`העתק`,copied:`הועתק`,copyTicketReference:`פנייה {reference}, העתקה`,tabHome:`בית`,tabConversations:`צ׳אטים`,tabHelp:`עזרה`,tabNews:`חדשות`,modulesEmpty:`אין כאן עדיין כלום`,chatUnavailable:`הצ׳אט הזה אינו זמין כרגע`,moduleBack:`חזרה`,contentLoading:`טוען…`,contentHelpful:`האם זה עזר?`,homeGreeting:`כיצד נוכל לעזור?`,homeGreetingNamed:`שלום {name} 👋`,homeGreetingLead:`כיצד נוכל לעזור?`,homeSearchPlaceholder:`חיפוש עזרה`,homeAskPlaceholder:`שאלו שאלה…`,homeWhatsNew:`מה חדש`,homeContentTitle:`מאמרים פופולריים`,homeStatus:`סטטוס`,helpTitle:`עזרה`,helpSearchPlaceholder:`חיפוש עזרה`,helpEmpty:`אין עדיין מאמרי עזרה`,helpLoading:`טוען עזרה…`,helpSearchEmpty:`אין תוצאות עבור „{query}”`,helpShowMore:`הצגת עוד`,newsTitle:`חדשות`,newsEmpty:`אין עדיין חדשות`,newsLoading:`טוען חדשות…`,newsShowMore:`הצגת עוד`,newsUnseen:`פוסט חדש`,unread:`לא נקרא`,formRequired:`שדה חובה`,formInvalidEmail:`הזן כתובת אימייל תקינה`,formInvalidTel:`הזן מספר טלפון תקין`,formInvalidNumber:`הזן מספר תקין`,formOtherPlaceholder:`כתוב את תשובתך…`,inputRequired:`שאלות עבורך`,askFallbackQuestion:`אנא ספקו את המידע החסר.`,inputBadge:`שאלות`,inputAnswered:`נענה`,inputSkipped:`דולג`,showOptions:`הצג אפשרויות`,hideOptions:`הסתר אפשרויות`,qtypeText:`התשובה שלך`,qtypeEmail:`כתובת אימייל`,qtypePhone:`מספר טלפון`,qtypeNumber:`מספר`,qtypeDate:`תאריך`,qtypeChooseOne:`בחר אחת`,qtypeChooseAny:`בחר כמה`,qtypeBoolean:`כן / לא`,inputSubmit:`שליחת תשובות`,inputSubmitHint:`Enter לשליחה · Shift+Enter = שורה חדשה`,inputSkip:`דילוג`,confirmYes:`כן`,confirmNo:`לא`,approve:`אישור`,decline:`דחייה`,changeAnswer:`שינוי התשובה`,approvalPrompt:`{action}?`,approvalEditHint:`אפשר לשנות את התשובה עד שהשלב הזה ימשיך.`,stepInput:`קלט`,stepWorking:`בביצוע`,stepWorkingOnIt:`מטפלים בזה…`,stepNeedsYourApproval:`נדרש האישור שלך`,stepWaitingForVisitor:`ממתין למבקר`,stepApproved:`אושר`,stepDeclined:`נדחה`,stepReplaced:`הוחלף`,stepFailed:`נכשל`,stepDidNotWork:`לא הצליח`,decidedYouApproved:`אישרת`,decidedYouDeclined:`דחית`,decidedVisitorApproved:`אושר על ידי המבקר`,decidedVisitorDeclined:`נדחה על ידי המבקר`,decidedTeamApproved:`אושר על ידי חבר צוות`,decidedTeamDeclined:`נדחה על ידי חבר צוות`,decidedMemberApproved:`אושר על ידי {name}`,decidedMemberDeclined:`נדחה על ידי {name}`,stepRawData:`נתונים גולמיים`,decidedRulesApproved:`אושר אוטומטית`,decidedRulesDeclined:`נדחה אוטומטית`,edit:`עריכה`,statusError:`שגיאה`,toolStepsFailed:`{count} נכשלו`,statusStopped:`נעצר`,toolStepsStopped:`נעצר אחרי {count} שלבים`,toolStepsStoppedOne:`נעצר אחרי שלב אחד`},zh:{attach:`添加附件`,file:`文件`,attachmentMimeRejected:`此聊天不接受 {name} 的文件类型。`,attachmentTooLarge:`{name} 太大了。文件总大小不能超过 {max}。`,poweredBy:`由 {name} 提供支持`,attachmentTooMany:`最多可添加 {count} 个附件。`,attachmentUploadFailed:`{name} 上传失败。`,conversationLoading:`正在加载聊天…`,loadPreviousMessages:`加载更早的消息`,close:`关闭`,collapse:`收起`,collapseSidebar:`收起侧边栏`,composerPlaceholder:`输入消息…`,dateLastWeek:`最近 7 天`,dateOlder:`更早`,dateToday:`今天`,dateYesterday:`昨天`,dropZone:`拖放文件以添加附件`,dropZoneRejected:`这些文件无法在此添加`,errorGeneric:`出了点问题`,errorRateLimited:`请求过多,请稍后再试。`,errorRateLimitedIn:`请求过多,请在 {seconds} 秒后重试。`,errorOffline:`无法连接服务器。请检查网络后重试。`,errorServer:`我们这边出了点问题。请重试。`,errorOriginNotAllowed:`此聊天尚未为本网站设置。`,errorMessageTooLong:`消息太长了。请缩短后重新发送。`,errorReconnecting:`连接已断开,正在重新连接…`,errorRetry:`重试`,expand:`展开`,expandSidebar:`展开侧边栏`,exitFullscreen:`退出全屏`,fullscreen:`全屏`,history:`历史记录`,historyBack:`返回聊天`,historyEmpty:`还没有以前的聊天`,historyLoading:`正在加载你的聊天…`,historyContinue:`继续聊天`,historyTitle:`聊天记录`,loadMoreConversations:`加载更多对话`,language:`语言`,launcherOpen:`打开聊天`,launcherAsk:`询问 {name}`,micBlocked:`此网站的麦克风已被阻止,无法开始语音输入。`,micStart:`开始语音输入`,micStop:`停止语音输入`,moreActions:`更多操作`,newConversation:`新聊天`,panelTitle:`聊天`,popOut:`在新标签页中打开`,resizeHandle:`拖动以调整大小`,scrollToBottom:`滚动到最新`,send:`发送`,queueMessage:`排队发送`,removeQueuedMessage:`移除排队的消息`,removeAttachment:`移除 {name}`,suggestedReplies:`推荐回复`,compactingContext:`正在优化对话上下文…`,soundOff:`关闭声音`,soundOn:`打开声音`,talkToOperator:`与真人交谈`,connectingOperator:`正在为你联系真人…`,noOperatorAvailable:`目前没有人有空,请留下你的联系方式,我们会跟进。`,chattingWithOperator:`你正在与 {operator} 聊天`,operatorBadgeTitle:`在线聊天`,chatNotice:`你正在与 AI 助手聊天。`,cancelOperatorRequest:`继续与 AI 聊天`,loginPrompt:`登录以获得更快、更个性化的支持`,loginAction:`登录`,loginRequired:`登录后与我们聊天`,loginExpired:`你的登录已过期。请登录以继续此聊天。`,loginExpiredGuest:`你的登录已过期。请登录以继续此聊天,或以访客身份开始新对话。`,startAsGuest:`开始新对话`,loggedInAs:`已登录为 {name}`,loggedIn:`已登录`,dismissLoginPrompt:`隐藏`,emailTranscript:`通过邮件发送聊天记录`,emailTranscriptPrompt:`通过邮件获取此对话的副本。`,emailTranscriptEmailLabel:`邮箱地址`,emailTranscriptSend:`发送聊天记录`,emailTranscriptSending:`正在发送…`,emailTranscriptSent:`已发送至 {email}。`,emailTranscriptAlreadySent:`此对话已通过邮件发送。发送一条新消息后可再次发送。`,emailTranscriptLimited:`你已达到当前上限。请稍后再试。`,emailTranscriptFailed:`发送失败。请重试。`,emailTranscriptNotDelivered:`无法发送到此地址。请检查后重试。`,emailTranscriptCancel:`取消`,emailTranscriptDone:`完成`,stop:`停止`,theme:`主题`,themeAuto:`自动`,themeDark:`深色`,themeLight:`浅色`,textSize:`文字大小`,textSizeSmall:`小`,textSizeNormal:`标准`,textSizeLarge:`大`,loading:`正在加载…`,visualPreparing:`正在准备图表…`,visualError:`无法显示此图表。`,visualPartial:`此图表的部分内容无法显示。`,visualSoldOut:`已售罄`,visualCartEmpty:`你的购物车是空的。`,visualQuantity:`数量`,visualChoose:`选择`,thinking:`正在思考…`,thought:`思考过程`,thoughtFor:`思考了 {time}`,toolResult:`结果`,sources:`来源`,feedbackUp:`回答很好`,feedbackDown:`回答不好`,feedbackThanks:`感谢你的反馈`,copy:`复制`,copied:`已复制`,copyTicketReference:`工单 {reference},复制`,tabHome:`首页`,tabConversations:`聊天`,tabHelp:`帮助`,tabNews:`动态`,modulesEmpty:`这里还没有内容`,chatUnavailable:`此聊天目前不可用`,moduleBack:`返回`,contentLoading:`正在加载…`,contentHelpful:`这对你有帮助吗?`,homeGreeting:`有什么可以帮你?`,homeGreetingNamed:`你好,{name} 👋`,homeGreetingLead:`有什么可以帮你?`,homeSearchPlaceholder:`搜索帮助`,homeAskPlaceholder:`提出问题…`,homeWhatsNew:`最新动态`,homeContentTitle:`热门文章`,homeStatus:`状态`,helpTitle:`帮助`,helpSearchPlaceholder:`搜索帮助`,helpEmpty:`还没有帮助文章`,helpLoading:`正在加载帮助…`,helpSearchEmpty:`没有找到“{query}”的结果`,helpShowMore:`显示更多`,newsTitle:`动态`,newsEmpty:`还没有动态`,newsLoading:`正在加载动态…`,newsShowMore:`显示更多`,newsUnseen:`新文章`,unread:`未读`,formRequired:`此项为必填`,formInvalidEmail:`请输入有效的邮箱地址`,formInvalidTel:`请输入有效的电话号码`,formInvalidNumber:`请输入有效的数字`,formOtherPlaceholder:`输入你的回答…`,inputRequired:`需要你回答的问题`,askFallbackQuestion:`请提供缺少的信息。`,inputBadge:`问题`,inputAnswered:`已回答`,inputSkipped:`已跳过`,showOptions:`显示选项`,hideOptions:`隐藏选项`,qtypeText:`你的回答`,qtypeEmail:`邮箱地址`,qtypePhone:`电话号码`,qtypeNumber:`数字`,qtypeDate:`日期`,qtypeChooseOne:`选择一项`,qtypeChooseAny:`可多选`,qtypeBoolean:`是 / 否`,inputSubmit:`提交回答`,inputSubmitHint:`Enter 发送 · Shift+Enter 换行`,inputSkip:`跳过`,confirmYes:`是`,confirmNo:`否`,approve:`批准`,decline:`拒绝`,changeAnswer:`修改回答`,approvalPrompt:`{action}?`,approvalEditHint:`在此步骤继续之前,你可以修改回答。`,stepInput:`输入`,stepWorking:`进行中`,stepWorkingOnIt:`正在处理…`,stepNeedsYourApproval:`需要你的批准`,stepWaitingForVisitor:`等待访客`,stepApproved:`已批准`,stepDeclined:`已拒绝`,stepReplaced:`已替换`,stepFailed:`失败`,stepDidNotWork:`未成功`,decidedYouApproved:`你已批准`,decidedYouDeclined:`你已拒绝`,decidedVisitorApproved:`访客已批准`,decidedVisitorDeclined:`访客已拒绝`,decidedTeamApproved:`团队成员已批准`,decidedTeamDeclined:`团队成员已拒绝`,decidedMemberApproved:`{name} 已批准`,decidedMemberDeclined:`{name} 已拒绝`,stepRawData:`原始数据`,decidedRulesApproved:`已自动批准`,decidedRulesDeclined:`已自动拒绝`,edit:`编辑`,statusError:`错误`,toolStepsFailed:`{count} 个失败`,statusStopped:`已停止`,toolStepsStopped:`在 {count} 步后停止`,toolStepsStoppedOne:`在 1 步后停止`}};function k(e,t){let n=A(e),r=te(t),i=O[S(n)],a=r?{...t[n],...t[e]}:t??{},o=r?t.en??{}:{};return{...D,...i,...o,...a}}function A(e){return(e.split(`-`)[0]??`en`).toLowerCase()}const j=/* @__PURE__ */ new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`,`ks`,`nqo`,`prs`,`syr`]);function ee(e){return j.has(A(e))}function M(e,t){return e[t]??t}function te(e){if(!e)return!1;for(let t of Object.values(e))if(t&&typeof t==`object`)return!0;return!1}const N={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`},ne={simple:{showSteps:!1,showStepDetails:!1,showStepSystem:!1,showDecidedBy:!1,foldApprovals:!0},technical:{showSteps:!0,showStepDetails:!0,showStepSystem:!0,showDecidedBy:!0,foldApprovals:!0}};function re(e){return Object.hasOwn(ne,e)}function ie(e,t){return{...ne[t],...e}}const P=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ae(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function oe(e){if(e.title)return e.title;let t=e.toolName.replace(/^tool[:-]/,``),n=t.indexOf(`__`);return ae(n>0?t.slice(n+2):t)}function F(e,t,n){let r=e.approval;return r?.replacedByMessageId?`replaced`:e.state===`output-available`?n.error===void 0?`done`:`failed`:e.state===`output-error`?t.interrupted?`stopped`:`failed`:e.state===`output-denied`||r?.approved===!1?`declined`:e.state===`approval-responded`||r?.approved===!0?t.cutOff?`stopped`:`approved`:e.state===`approval-requested`?t.submitted?`submitted`:t.cutOff?`stopped`:t.superseded?`replaced`:`waiting`:t.live?`running`:`stopped`}function se(e,t){if(e.isAutomatic)return`rules`;let n=e.respondedBy;return n?.visitorId?`visitor`:n?.userId?n.userId===t.userId?`you`:`teamMember`:t.decides?`you`:`visitor`}function ce(e,t,n,r){let i=r[t?`stepApproved`:`stepDeclined`];if(e===`teamMember`&&n)return{label:i,title:r[t?`decidedMemberApproved`:`decidedMemberDeclined`].replace(`{name}`,n)};let a=r[le[e][+!t]];return e===`you`?{label:i,title:a}:{label:a,title:a}}const le={you:[`decidedYouApproved`,`decidedYouDeclined`],visitor:[`decidedVisitorApproved`,`decidedVisitorDeclined`],teamMember:[`decidedTeamApproved`,`decidedTeamDeclined`],rules:[`decidedRulesApproved`,`decidedRulesDeclined`]};function ue(e,t){switch(e){case`running`:return t.strings.stepWorking;case`waiting`:return t.reader.decides?t.strings.stepNeedsYourApproval:t.strings.stepWaitingForVisitor;case`submitted`:return t.strings.stepWorkingOnIt;case`approved`:return t.strings.stepApproved;case`declined`:return t.strings.stepDeclined;case`replaced`:return t.strings.stepReplaced;case`stopped`:return t.strings.statusStopped;case`failed`:return t.display.showStepDetails?t.strings.stepFailed:t.strings.stepDidNotWork;case`done`:return``;default:return e}}function de(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e){return typeof e==`string`?e.trim():typeof e==`number`||typeof e==`boolean`?String(e):``}function fe(e){return I(e)||(typeof e==`object`&&e?JSON.stringify(e):``)}function pe(e){if(!de(e))return fe(e);let[t,...n]=Object.values(e).map(fe).filter(Boolean);return t===void 0?``:n.length>0?`${t} (${n.join(`, `)})`:t}function me(e,t){if(!de(e))return[];let n=[];function r(e,i){if(Array.isArray(e)){let t=e.map(pe).filter(Boolean).join(`, `);t&&n.push({path:i,value:t});return}if(de(e)){for(let[t,n]of Object.entries(e))r(n,[...i,t]);return}let a=I(e);a&&(t.withIds||!P.test(a))&&n.push({path:i,value:a})}r(e,[]);let i=n.map(({path:e})=>ae(e.at(-1)??``));return n.map(({path:e,value:t},n)=>{let r=i[n]??``;return{label:i.filter(e=>e===r).length>1&&e.length>1?`${ae(e.at(-2)??``)} · ${r.toLowerCase()}`:r,value:t}})}function he(e){if(de(e))return Object.values(e).find(e=>typeof e==`string`&&e.trim().length>0&&!P.test(e.trim()))?.trim()}function ge(e,t=1/0){if(e==null)return;let n=typeof e==`string`?e:JSON.stringify(e,null,2);if(n&&n!==`{}`&&n!==`[]`&&n!==`""`)return n.length>t?`${n.slice(0,t)}…`:n}function _e(e){let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function ve(e){if(de(e)&&e.storage===`tool-result-ref`&&`summary`in e)return{value:e.summary};if(de(e)&&Array.isArray(e.content)){let t=e.content.flatMap(e=>de(e)&&typeof e.text==`string`?[e.text]:[]).join(`
2
+ `),n=de(e.structuredContent)?e.structuredContent:_e(t);return e.isError===!0?{value:n,error:de(n)&&typeof n.error==`string`?n.error:t}:{value:n}}return de(e)&&typeof e.error==`string`&&typeof e.instruction==`string`?{value:e,error:e.error}:{value:e}}function L(e){return ge(e.input)!==void 0||ge(e.output)!==void 0||!!e.errorText}function ye(e,t,n){let{display:r}=n,i=e.approval;if(typeof e.toolMetadata?.card==`string`&&i)return`card`;let a=i!==void 0&&!i.isAutomatic;if(a&&be(e,n.turn))return`card`;let o=t.decision?.by===`you`||a&&t.decision===void 0&&n.reader.decides;return a&&o?r.foldApprovals?`step`:`card`:a?r.showSteps||r.showDecidedBy?r.foldApprovals?`step`:`card`:`hidden`:i?.isAutomatic?r.showSteps||r.showDecidedBy?`step`:`hidden`:r.showSteps&&L(e)?`step`:`hidden`}function be(e,t){return e.approval?.replacedByMessageId||(t.superseded||t.cutOff)&&e.approval?.approved===void 0?!1:e.state===`approval-requested`||e.state===`approval-responded`}function xe(e,t){let{turn:n,reader:r,display:i,strings:a}=t,o=ve(e.output),s=F(e,n,o),c=e.approval,l=c?.replacedByMessageId?void 0:c?.approved,u=c&&l!==void 0?se(c,r):void 0,d=u===`teamMember`?c?.respondedBy?.userId:void 0,f=u&&l!==void 0&&(u===`you`||i.showDecidedBy)?{approved:l,by:u,...ce(u,l,d&&t.names?.get(d),a),...d?{userId:d}:{}}:void 0,p=oe(e),m=typeof e.toolMetadata?.system==`string`&&(i.showStepSystem||e.toolMetadata.nameShared===!0)?e.toolMetadata.system:void 0,h=he(e.input),g=e.errorText??o.error,_=i.showStepDetails&&o.error===void 0?me(o.value,{withIds:!0}):[],v=i.showStepDetails?{input:ge(e.input),output:ge(o.value,4e3)}:void 0,y=c!==void 0&&!c.isAutomatic&&!e.toolMetadata?.card,b={toolCallId:e.toolCallId,placement:`hidden`,...typeof e.toolMetadata?.card==`string`&&c?{card:e.toolMetadata.card}:{},name:p,...m?{system:m}:{},status:s,statusLabel:ue(s,{reader:r,display:i,strings:a}),...f?{decision:f}:{},...f?.by===`rules`&&c?.reason?{reason:c.reason}:{},...h?{summary:h}:{},fields:me(e.input,{withIds:i.showStepDetails||c!==void 0&&!c.isAutomatic&&be(e,n)}),..._.length>0?{resultFields:_}:{},...g&&i.showStepDetails?{error:g}:{},...v?{raw:v}:{},...y?{approval:Se(e,s,{turn:n,reader:r,strings:a,name:p})}:{}};return{...b,placement:ye(e,b,{turn:n,reader:r,display:i})}}function Se(e,t,n){let r=n.strings.approvalPrompt.replace(`{action}`,n.name);return t===`waiting`?{ask:r,buttons:n.reader.decides?`decide`:`none`}:t===`submitted`||!be(e,n.turn)?{ask:r,buttons:`none`}:n.turn.canAct&&n.reader.decides?{ask:r,buttons:`change`,note:n.strings.approvalEditHint}:t===`approved`?{ask:r,buttons:`none`,note:n.strings.stepWorkingOnIt}:{ask:r,buttons:`none`}}function Ce(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.name,(t.get(n.name)??0)+1);let n=/* @__PURE__ */ new Map;for(let{decision:t}of e){if(!t)continue;let e=n.get(t.title)??{approved:t.approved,label:t.label,title:t.title,...t.userId?{userId:t.userId}:{},count:0};n.set(t.title,{...e,count:e.count+1})}let[r]=e,i=e.some(e=>e.status===`stopped`);return{tools:[...t].map(([e,t])=>({name:e,count:t})),...e.length===1&&r?{single:{name:r.name,...r.system?{system:r.system}:{},...r.summary?{summary:r.summary}:{},...we(r)}}:{},marks:[...n.values()].map(({count:e,...t})=>Object.assign(t,{label:e>1?`${t.label} ×${e}`:t.label})),failed:e.filter(e=>e.status===`failed`).length,...i?{stopped:{finished:e.filter(e=>e.status!==`stopped`).length}}:{}}}function we(e){return!e.decision&&(e.status===`replaced`||e.status===`declined`)?{outcome:e.statusLabel}:{}}function Te(e,t){return e===0?t.statusStopped:e===1?t.toolStepsStoppedOne:t.toolStepsStopped.replace(`{count}`,String(e))}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{}}},De={get(e){try{return sessionStorage.getItem(e)}catch{return null}},set(e,t){try{sessionStorage.setItem(e,t)}catch{}},remove(e){try{sessionStorage.removeItem(e)}catch{}}},Oe={maxBytes:10485760,maxCount:10,accept:`*/*`},ke={voice:`local`},Ae={enabled:!0,sampleRate:1},je={upload:`/pai/upload-file`,transcribe:`/pai/transcribe-audio`},Me={variant:`circle`,size:`md`,label:void 0,icon:`chat`,hidden:!1},Ne={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`]},Pe={enabled:!0,volume:.3,events:void 0},Fe={enabled:!0,events:void 0},Ie=[{label:`tabConversations`,layout:`chat`}],Le=[`off`,`error`,`warn`,`info`,`debug`,`trace`],Re=N.cssPrefix,ze=`${Re}.debug`,Be=`__${N.global}_DEBUG__`,Ve=`${Re}-debug`;let He=2,Ue=null;function We(){if(typeof window>`u`)return 2;try{let e=new URLSearchParams(window.location.search).get(Ve);if(e!==null){let t=Ge(e);if(t>=0)return t}}catch{}try{let e=window.localStorage?.getItem(ze);if(e){let t=Ge(e);if(t>=0)return t}}catch{}return Reflect.get(window,Be)?4:2}function Ge(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=Le.findIndex(t=>t===e);if(t>=0)return t}return-1}function Ke(e){let t=Ge(e);if(!(t<0)){He=t;try{window.localStorage?.setItem(ze,Le[t]??`off`)}catch{}}}function qe(){return Le[He]??`warn`}He=We();function Je(e){let t=`[${Re}:${e}]`;function n(n,r,i){return(a,o)=>{if(!(He<n)&&(o===void 0?console[r](t,a):console[r](t,a,o),Ue))try{Ue({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=>Je(`${e}:${t}`)}}const R=Je(`core`);function Ye(e){Ue=e}const Xe=R.scope(`context`),Ze=/* @__PURE__ */ new Set([`visitorId`,`conversationId`,`jwt`,`token`,`authorization`,`password`]),Qe=1024,$e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function et(e){return rt(e,`userContext`,!0)}function tt(e){return rt(e,`pageContext`,!1)}function nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rt(e,t,n){if(e==null)return;if(!nt(e)){Xe.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(Ze.has(n)){Xe.warn(`dropped reserved ${t} key "${n}" — managed by the widget, not host-settable`);continue}if(a==null)continue;if(i>=50){Xe.warn(`${t} truncated at 50 keys — dropped "${n}"`);continue}let e=it(t,n,a);e!==void 0&&(r[n]=e,i++)}return n&&typeof r.email==`string`&&!$e.test(r.email)&&(Xe.warn(`dropped malformed context field`,{field:`${t}.email`,reason:`invalid format`}),delete r.email),Object.keys(r).length>0?r:void 0}function it(e,t,n){if(typeof n==`boolean`)return n;if(typeof n==`number`){if(!Number.isFinite(n)){Xe.warn(`dropped non-finite ${e}.${t}`);return}return n}if(typeof n==`string`){let r=n.trim();return r===``?void 0:r.length>Qe?(Xe.warn(`truncated ${e}.${t} to ${Qe} chars`),r.slice(0,Qe)):r}Xe.warn(`dropped ${e}.${t} — only string/number/boolean values are allowed`,{type:typeof n})}function at(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??{},c={enabled:t.history?.enabled??!0},{themeMode:l,themeOverrides:u}=ot(t.theme),d=n.mode??`floating`,f=z(i.defaultLocale),p=i.availableLocales??[i.locale??f],m=st(i.locale??f,p,f),h=(t.baseUrl??N.defaultBaseUrl).replace(/\/$/,``),g=(t.agentApiBaseUrl??`${h}/api/agent`).replace(/\/$/,``),_=(t.dataApiBaseUrl??`${h}/api/data`).replace(/\/$/,``);return{widgetId:t.widgetId??`default`,publicKey:t.publicKey,aiAgentDeploymentId:t.aiAgentDeploymentId,baseUrl:h,agentApiBaseUrl:g,dataApiBaseUrl:_,userContext:et(t.userContext),pageContext:tt(t.pageContext),position:n.position??(ee(m)?`bottom-left`:`bottom-right`),themeMode:l,textSize:`normal`,themeOverrides:u,mode:d,responseMode:r.responseMode??`streaming`,showReasoning:r.showReasoning??!1,stepDisplay:ie(r.stepDisplay,`simple`),showSources:r.showSources??!1,enableMessageFeedback:!(r.disableMessageFeedback??!1),autoSendSuggestions:r.autoSendSuggestions??!1,cardAnswerWaitSeconds:r.cardAnswerWaitSeconds??60,popOutUrl:r.popOutUrl,features:{voice:t.features?.voice??ke.voice,fileUpload:!(t.features?.disableFileUpload??!1),humanInLoop:!(t.features?.disableHumanInLoop??!1),emailTranscript:!(t.features?.disableEmailTranscript??!1),operatorRequest:t.features?.enableOperatorRequest===!0&&!(t.features.hideRequestOperatorButton??!1)},endpoints:{upload:t.endpoints?.upload??je.upload,transcribe:t.endpoints?.transcribe??je.transcribe},attachments:{accept:t.composer?.attachments?.accept??Oe.accept,maxBytes:t.composer?.attachments?.maxBytes??Oe.maxBytes,maxCount:t.composer?.attachments?.maxCount??Oe.maxCount},locale:m,defaultLocale:f,availableLocales:p,startMinimized:r.startMinimized??!0,actions:ct(d,s.actions,c.enabled),size:{...n.size,resize:{...n.size?.resize,enabled:n.size?.resize?.enabled??!0}},launcher:ht(t.launcher,t.agent?.name),sound:lt(a.sound),haptics:ut(a.haptics),strings:k(m,i.strings),stringsOverride:i.strings,composerDisclaimer:o.composerDisclaimer??``,header:{variant:s.variant??`plain`,notice:s.notice,showNotice:!(s.hideNotice??!1)},poweredBy:ft(o.poweredBy),composer:pt(t.composer),modules:mt(t.modules,c.enabled),tracking:dt(t.tracking,_),history:c,storage:t.storage??Ee,userToken:t.userToken,continueLink:t.continueLink,tools:t.tools,onMessage:t.onMessage,onOpen:t.onOpen,onClose:t.onClose,onError:t.onError}}function ot(e){if(typeof e==`string`)return{themeMode:e,themeOverrides:{}};if(!e||typeof e!=`object`)return{themeMode:`host`,themeOverrides:{}};let{mode:t,...n}=e;return{themeMode:t??`host`,themeOverrides:n}}function z(e){return e&&e!==`auto`?e:globalThis.navigator?.language||`en`}function st(e,t,n){if(t.length<=1||t.includes(e))return e;let r=e.split(`-`)[0];return r&&t.includes(r)?r:t.includes(n)?n:t[0]??e}function ct(e,t,n){let r=t??Ne[e];return n?r:r.filter(e=>e!==`history`)}function lt(e){return{enabled:e?.enabled??Pe.enabled,volume:e?.volume??Pe.volume,events:e?.events}}function ut(e){return{enabled:e?.enabled??Fe.enabled,events:e?.events}}function dt(e,t){let n=e?.sampleRate??Ae.sampleRate;return{enabled:e?.enabled??Ae.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 ft(e){return e?.text===``&&!e.logoUrl?null:{href:N.siteUrl,...e}}function pt(e){let t=e?.sendButton;return{sendButton:{shape:t?.shape??`circle`,icon:t?.icon??`arrowUp`,variant:t?.variant??`filled`}}}function mt(e,t){let n=(e??Ie).slice(0,4),r=n.some(e=>e?.label&&e.layout===`help`),i=/* @__PURE__ */ new Set,a=[];for(let e of n){if(!e?.label||!e?.layout)continue;let n=e.contentCollectionIds?.filter(Boolean),o=e.id??n?.[0]??e.layout;for(;i.has(o);)o=`${o}-${a.length}`;i.add(o);let s={id:o,label:e.label,layout:e.layout};n?.length&&(s.contentCollectionIds=n),e.layout===`home`&&(s.brandName=e.brandName,s.greetingText=e.greetingText,s.showGreeting=!(e.hideGreeting??!1),s.showSearchBar=r&&!(e.hideSearchBar??!1),s.showRecentConversations=t&&!(e.hideRecentConversations??!1),e.userAvatars?.length&&(s.userAvatars=e.userAvatars),e.status&&(s.status=e.status),s.contentBlockTitle=e.contentBlockTitle),a.push(s)}return{list:a,byId:Object.fromEntries(a.map(e=>[e.id,e]))}}function ht(e,t){let n=e?.callout?.text?{shape:`pill`,position:`auto`,delayMs:1200,autoDismissMs:0,animated:!0,persistent:!0,...e.callout}:null;return{variant:e?.variant??Me.variant,size:e?.size??Me.size,label:e?.label??Me.label,icon:e?.icon??Me.icon,hidden:e?.hidden??Me.hidden,...t&&{personaName:t},callout:n}}function gt(e,t){return e===`host`?`host`:t??e}function _t(e,t,n,r){let i=st(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=k(i,e.stringsOverride)),n!==e.themeMode&&(a.themeMode=n),r!==e.textSize&&(a.textSize=r),a}function vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const yt=[`agent`,`presentation`,`behavior`,`theme`,`launcher`,`header`,`composer`,`feedback`,`i18n`,`footer`,`features`,`tracking`,`endpoints`,`history`];function bt(e,t){if(!t)return e;let n={...e};for(let r of yt){let i=t[r];if(i===void 0)continue;let a=e[r];r===`theme`?a===void 0?n[r]=i:typeof a==`string`&&typeof i==`object`&&i&&(n[r]={...i,mode:a}):r!==`i18n`&&(n[r]=xt(vt(i)?i:{},vt(a)?a:void 0))}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=xt(vt(i)?i:{},vt(r)?r:void 0);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=St(a,t)),n.i18n=e}return n}function xt(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 St(e,t){if(!e)return t;if(!t)return e;let n=te(e),r=te(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 Ct=[`clear`,`expand`,`fullscreen`,`popOut`,`sound`,`history`,`language`,`theme`,`textSize`,`close`];function wt(e){return e!==`false`}function Tt(e){return re(e)?ne[e]:void 0}function Et(e){let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>=0?t:void 0}const Dt=[[`public-key`,`publicKey`],[`ai-agent-deployment-id`,`aiAgentDeploymentId`],[`base-url`,`baseUrl`],[`agent-api-base-url`,`agentApiBaseUrl`],[`data-api-base-url`,`dataApiBaseUrl`],[`continue-link`,`continueLink`],[`theme`,`theme`,e=>e]],Ot=[[`mode`,`mode`,e=>e],[`position`,`position`,e=>e]],kt=[[`width`,`width`],[`height`,`height`]],At=[[`response-mode`,`responseMode`,e=>e],[`start-minimized`,`startMinimized`,wt],[`show-reasoning`,`showReasoning`,wt],[`step-display`,`stepDisplay`,Tt],[`show-sources`,`showSources`,wt],[`disable-message-feedback`,`disableMessageFeedback`,wt],[`auto-send-suggestions`,`autoSendSuggestions`,wt],[`card-answer-wait-seconds`,`cardAnswerWaitSeconds`,Et],[`pop-out-url`,`popOutUrl`]],jt=[[`locale`,`locale`]];new Set(Ct);const Mt=[[`launcher-variant`,`variant`,e=>e],[`launcher-size`,`size`,e=>e],[`launcher-icon`,`icon`],[`launcher-hidden`,`hidden`,wt]],Nt=[[`features-disable-file-upload`,`disableFileUpload`,wt],[`features-disable-email-transcript`,`disableEmailTranscript`,wt],[`features-voice`,`voice`,e=>e]],Pt=[[`endpoint-upload`,`upload`],[`endpoint-transcribe`,`transcribe`]],Ft=[[`user-id`,`id`],[`user-email`,`email`],[`user-name`,`name`]],It=[[`page-area`,`area`],[`page-url`,`url`],[`page-path`,`path`],[`page-title`,`title`]],Lt=[`launcher-label`,`callout-text`,`callout-delay`,`actions`,`user-context`,`page-context`],Rt=[Dt,Ot,kt,At,jt,Mt,Nt,Pt,Ft,It],zt=/* @__PURE__ */ new Set([`start-minimized`]);[...Rt.flatMap(e=>e.map(([e])=>e).filter(e=>!zt.has(e))),...Lt];const Bt=R.scope(`track`);function Vt(e,t){let n=typeof e==`string`?e.trim():``;if(!n||n.length>64){Bt.warn(`track: ignored an event without a name of 1–64 characters`,{name:e});return}let r=Object.fromEntries(Object.entries(typeof t==`object`&&t?t:{}).filter(e=>typeof e[1]==`string`||typeof e[1]==`boolean`||Number.isFinite(e[1])));return JSON.stringify(r).length>256?(Bt.warn(`track: sent the event without its data, which is over 256 characters`,{name:n}),{name:n}):Object.keys(r).length>0?{name:n,data:r}:{name:n}}function Ht(e){let t=[];return e.on(`hostEvent`,e=>{t.push({...e,at:Date.now()}),t.length>10&&t.shift()}),t}function Ut(){let e=Date.now(),t=/* @__PURE__ */ 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,Wt(t.subarray(6)),t[6]=(t[6]??0)&15|112,t[8]=(t[8]??0)&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 Wt(e){if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const Gt=R.scope(`persistence`);function Kt(e,t=Ee,n){let r=n?`${e}.${n}`:e,i=`${N.cssPrefix}.${r}.storageVersion`,a=t.get(i)??void 0,o=a?`.v${a}`:``,s=`${N.cssPrefix}.${r}${o}`,c=`${N.cssPrefix}${o}.visitorId`,l=`${N.cssPrefix}${o}.lastUserSub`,u=`${s}.conversationId`,d=`${s}.userPrefs`,f=`${s}.panelOpen`,p=`${s}.panelSize`,m=`${s}.calloutDismissed`,h=`${s}.sidebarCollapsed`,g=`${s}.activeModule`,_=`${s}.seenNewsId`,v=`${s}.historyCount`,y=`${s}.loginReturn`,b=`${s}.loginPromptDismissedIn`,x={getVisitorId(){let e=t.get(c);if(e)return e;let n=Ut();return t.set(c,n),n},loadLastUserSub(){return t.get(l)??void 0},saveLastUserSub(e){t.set(l,e)},loadConversationId(){return t.get(u)??void 0},saveConversationId(e){Gt.trace(`saveConversationId`,{id:e,scope:r}),e?t.set(u,e):t.remove(u)},loadDraft(e){return t.get(`${s}.draft.${e}`)??``},saveDraft(e,n){let r=`${s}.draft.${e}`;n?t.set(r,n):t.remove(r)},loadMessageQueue(e){let n=t.get(`${s}.messageQueue.${e}`);if(!n)return[];try{let e=JSON.parse(n);return!Array.isArray(e)||!e.every(Jt)?[]:e}catch(e){return Gt.warn(`loadMessageQueue parse failed`,{error:e}),[]}},saveMessageQueue(e,n){let r=`${s}.messageQueue.${e}`;if(n.length===0)t.remove(r);else try{t.set(r,JSON.stringify(n))}catch(e){Gt.warn(`saveMessageQueue serialise failed`,{error:e})}},loadUserPrefs(){let e=t.get(d);if(!e)return{};try{return Yt(JSON.parse(e))}catch(e){return Gt.warn(`loadUserPrefs parse failed`,{error:e}),{}}},saveUserPrefs(e){try{t.set(d,JSON.stringify(e))}catch(e){Gt.warn(`saveUserPrefs serialise failed`,{error:e})}},patchUserPrefs(e){let t=x.loadUserPrefs();x.saveUserPrefs({...t,...e})},loadPanelOpen(){let e=t.get(f);return e===`1`||e!==`0`&&null},savePanelOpen(e){t.set(f,e?`1`:`0`)},loadPanelSize(){let e=t.get(p);return e===`normal`||e===`expanded`||e===`fullscreen`?e:null},savePanelSize(e){t.set(p,e)},loadCalloutDismissed(e){if(!e)return!1;let n=t.get(m);return!!n&&n===e},saveCalloutDismissed(e){e?t.set(m,e):t.remove(m)},loadSidebarCollapsed(){let e=t.get(h);return e===`1`||e!==`0`&&null},saveSidebarCollapsed(e){t.set(h,e?`1`:`0`)},loadActiveModule(){return t.get(g)||null},saveActiveModule(e){t.set(g,e)},loadSeenNewsId(){return t.get(_)||null},saveSeenNewsId(e){t.set(_,e)},loadHistoryCount(){let e=t.get(v);if(!e)return null;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:null},saveHistoryCount(e){t.set(v,String(e))},rememberStorageVersion(e){e&&e!==t.get(i)&&(Gt.debug(`rememberStorageVersion (force-reset on next load)`,{version:e}),t.set(i,e))},saveLoginReturn(e){De.set(y,JSON.stringify(e))},takeLoginReturn(){let e=De.get(y);if(e){De.remove(y);try{let t=JSON.parse(e);return qt(t)&&typeof t.conversationId==`string`&&t.conversationId&&typeof t.draft==`string`?{conversationId:t.conversationId,draft:t.draft}:void 0}catch(e){Gt.warn(`takeLoginReturn parse failed`,{error:e});return}}},loadLoginPromptDismissedIn(){return De.get(b)??void 0},dismissLoginPromptIn(e){De.set(b,e)},clearConversation(){t.remove(u)},reset(){let e=t.get(u);e&&(t.remove(`${s}.draft.${e}`),t.remove(`${s}.messageQueue.${e}`));for(let e of[y,b])De.remove(e);for(let e of[c,l,u,d,p,m,h,g,_,v])t.remove(e);Gt.info(`reset: forgot the visitor`,{scope:r})}};return x}function qt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jt(e){return qt(e)&&typeof e.id==`string`&&e.id.length>0&&typeof e.text==`string`}function Yt(e){if(!qt(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),qt(e.widgetSize)&&typeof e.widgetSize.width==`number`&&typeof e.widgetSize.height==`number`&&(t.widgetSize={width:e.widgetSize.width,height:e.widgetSize.height}),t}const Xt=`6.6.1`,Zt={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,toolResult:()=>void 0,toolDecision:e=>({approved:e.approved}),hostEvent:e=>({name:e.name,data:e.data&&JSON.stringify(e.data)}),messageFeedback:e=>({value:e.value??`none`}),contentView:e=>({section:e.section,count:e.count}),contentOpen:e=>({contentId:e.contentId,contentCollectionId:e.contentCollectionId}),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 Qt(){let e=navigator;return e.globalPrivacyControl===!0||e.doNotTrack===`1`}function $t(){return location.origin+location.pathname}function en(){try{return document.referrer?new URL(document.referrer).origin:``}catch{return``}}function tn(e,t){let n=Math.random(),r=0,i=0,a=/* @__PURE__ */ new Set;function o(e,o){let{tracking:s,publicKey:c,aiAgentDeploymentId:l,mode:u,themeMode:d}=t.getOptions();if(!s.enabled||Qt()||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`,Xt),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`,$t());let h=en();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(_);function v(){return a.delete(_)}_.addEventListener(`load`,v,{once:!0}),_.addEventListener(`error`,v,{once:!0}),_.src=g}let s=[];function c(e,t){if(s&&e!==`handshake`){s.length<60&&s.push([e,t]);return}let n=s??[];s=void 0;for(let[e,t]of n)o(e,t);o(e,t)}function l(e,t){return Zt[e]?.(t)}let u=Object.keys(Zt).filter(e=>Object.hasOwn(Zt,e)).map(t=>e.on(t,e=>c(t,l(t,e))));return()=>{for(let e of u)e();a.clear()}}const nn=`: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, .55) 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}}
3
3
 
4
4
  *,*: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}
5
5
 
@@ -32,7 +32,7 @@ import{Component as e,h as t,render as n}from"preact";import{batch as r,computed
32
32
 
33
33
  `))!==-1;){let e=r.slice(0,a);r=r.slice(a+2),yield e}}}finally{n.releaseLock()}}function Mo(e,t){let n=``,r;for(let i of e.split(`
34
34
  `))if(i!==``){if(i.startsWith(`:`))t?.(i.slice(1).trim());else if(i.startsWith(`data:`)){let e=i.slice(5).replace(/^ /,``);n=n?`${n}\n${e}`:e}else i.startsWith(`id:`)&&(r=i.slice(3).trim())}if(n===`[DONE]`)return`done`;if(!n)return null;try{let e=JSON.parse(n);if(!No(e))throw TypeError(`unrecognized chunk`);return ko.trace(`chunk`,{type:e.type,eventId:r}),{chunk:e,eventId:r}}catch(e){throw ko.trace(`frame parse failed`,{errorType:e instanceof Error?e.name:typeof e,payloadLength:n.length}),new Oo(`invalid SSE frame`,`network`,void 0,e)}}function No(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof Reflect.get(e,`type`)==`string`}const Po=/* @__PURE__ */ new Set([101,204,205,304]);function Fo(e){let t=new Headers;for(let n of e.trim().split(/[\r\n]+/)){let e=n.indexOf(`:`);e>0&&t.append(n.slice(0,e).trim(),n.slice(e+1).trim())}return t}function Io(e){return async function(t,n){let r=new Request(t,n),i=await r.blob();return new Promise((t,n)=>{if(r.signal.aborted){n(r.signal.reason);return}let a=new XMLHttpRequest;a.open(r.method,r.url),a.withCredentials=r.credentials===`include`,a.responseType=`blob`,r.headers.forEach((e,t)=>a.setRequestHeader(t,e)),a.upload.addEventListener(`progress`,t=>{t.lengthComputable&&t.total>0&&e(t.loaded/t.total)}),a.addEventListener(`load`,()=>{t(new Response(Po.has(a.status)?null:a.response,{status:a.status,statusText:a.statusText,headers:Fo(a.getAllResponseHeaders())}))}),a.addEventListener(`error`,()=>n(/* @__PURE__ */ TypeError(`Failed to fetch`))),a.addEventListener(`abort`,()=>n(r.signal.reason)),r.signal.addEventListener(`abort`,()=>a.abort(),{once:!0}),a.send(i)})}}const Lo=R.scope(`transport`);async function Ro(e){try{let t=await e.clone().json();if(typeof t!=`object`||!t)return{};let n=Reflect.get(t,`error`);return{error:typeof n==`string`?n:void 0,loginUrl:er(Reflect.get(t,`login`)).url}}catch{return{}}}const zo=6e4,Bo=/* @__PURE__ */ new WeakMap;function Vo(e){return Bo.get(e)}function Ho(e,t){return Bo.set(e,t),e}function Uo(e){return Math.max(e?.upsertRevision??0,e?.read?.revision??0)}function Wo(e,t){return e.conversationId===t.conversationId&&e.title===t.title&&e.lastMessageAt===t.lastMessageAt&&e.preview===t.preview&&e.hasUnread===t.hasUnread&&e.controlState===t.controlState}function Go(e,t,n=!0){switch(t.type){case`snapshot`:{let n=new Map(e.map(e=>[e.conversationId,e])),r=e.filter(e=>(Vo(e)?.activityRevision??0)>t.requestedRevision).toSorted((e,t)=>(Vo(t)?.activityRevision??0)-(Vo(e)?.activityRevision??0)),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=Vo(r);return(i?.upsertRevision??0)>t.requestedRevision?r:i?.read&&!r.hasUnread&&i.read.lastMessageAt===e.lastMessageAt?Ho({...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)),r=e[n];if(!r)return e;let i=Vo(r);if(Uo(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?Ho({...e,hasUnread:!1},o):e):(Ho(r,o),e)}case`upsert`:{let r=e.findIndex(e=>e.conversationId===t.conversation.conversationId);if(r<0&&!n)return e;let i=e[r],a=i?Vo(i):void 0;if(Uo(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&&Wo(i,c)?(Ho(i,s),e):(Ho(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 Ko=/* @__PURE__ */ new Set([408,425,429,500,502,503,504]);function qo(e){return 400*2**e+Math.floor(Math.random()*250)}function Jo(e){return 6e4+Math.ceil(e/1048576)*15e3}function Yo(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 Xo=class{constructor(e){this.ttlMs=e,B(this,`map`,/* @__PURE__ */ new Map)}getOrFetch(e,t){let n=this.map.get(e);if(n&&performance.now()-n.at<this.ttlMs)return n.result;let r={at:performance.now(),result:t().then(e=>(r.value=e,e)).catch(t=>{throw this.map.get(e)===r&&this.map.delete(e),t})};return this.map.set(e,r),r.result}peek(e){let t=this.map.get(e);if(t?.value!==void 0&&performance.now()-t.at<this.ttlMs)return t.value}update(e){for(let t of this.map.values())if(t.value!==void 0){let n=e(t.value);t.value=n,t.result=Promise.resolve(n)}else t.result=t.result.then(n=>{let r=e(n);return t.value=r,r})}delete(e){this.map.delete(e)}};function Zo(e,t){let{translations:n,defaultLocale:r,...i}=E(e,t);return i}var Qo=class{constructor(e){this.opts=e,B(this,`conversationListeners`,/* @__PURE__ */ new Set),B(this,`conversationRevision`,0),B(this,`visitorId`,void 0),B(this,`conversationId`,void 0),B(this,`userContext`,void 0),B(this,`pageContext`,void 0),B(this,`locale`,void 0),B(this,`userTokenSource`,void 0),B(this,`userToken`,void 0),B(this,`userTokenRequest`,void 0),B(this,`conversationsCache`,new Xo(1e4)),B(this,`contentCache`,new Xo(zo)),B(this,`contentCollectionsCache`,new Xo(zo))}setUserToken(e){this.userTokenSource=e,this.userToken=typeof e==`string`&&e||void 0,this.userTokenRequest=typeof e==`function`?this.fetchUserToken():void 0,this.opts.onLoginState?.(e?{status:`pending`}:{status:`anonymous`})}async userSub(){return this.userTokenRequest&&await this.userTokenRequest,this.userToken?ar(this.userToken):void 0}reportLogin(e){this.opts.onLoginState?.(e===`loggedIn`&&this.userToken?{status:e,...ir(this.userToken)}:{status:e===`loggedIn`?`anonymous`:e})}async refreshUserToken(){let e=this.userToken;return typeof this.userTokenSource==`function`&&(this.userTokenRequest&&await this.userTokenRequest,this.userToken===e&&await this.fetchUserToken(),!!this.userToken&&this.userToken!==e)}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:Xt};this.visitorId&&(e.visitorId=this.visitorId),this.conversationId&&(e.conversationId=this.conversationId),this.locale&&(e.locale=this.locale);let t=Do(this.userContext,this.pageContext);return t&&(e[wa]=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){Lo.debug(`handshake →`,{visitorId:e.visitorId,conversationId:e.conversationId,locale:e.locale});let t=ns(`handshake`,await this.postJson(Ca.handshake,e,`handshake`),is),n=t.loginStatus===`expired`&&await this.refreshUserToken()?ns(`handshake`,await this.postJson(Ca.handshake,e,`handshake`),is):t;return this.reportLogin(n.loginStatus??(this.userToken?`loggedIn`:`anonymous`)),Lo.debug(`handshake ←`,{visitorId:n.visitorId,conversationId:n.conversationId,hasWelcome:!!n.welcome,hasConfig:!!n.config,rebind:n.rebind}),this.visitorId=n.visitorId,this.conversationId=n.conversationId,n}async uploadFile(e,t,n){Lo.debug(`uploadFile →`,{name:e.name,size:e.size,type:e.type});let r=new FormData;r.append(`file`,e,e.name);let i=ns(`upload`,await this.postForm(this.uploadPath,r,`upload`,t,Jo(e.size),n),as);return Lo.debug(`uploadFile ←`,{id:i.id,url:i.url}),i}async transcribe(e,t=`audio/webm`){Lo.debug(`transcribe →`,{size:e.size,mimeType:t});let n=new FormData;n.append(`audio`,e,`voice.${$o(t)}`),n.append(`mimeType`,t);let r=ns(`transcribe`,await this.postForm(this.transcribePath,n,`transcribe`),os);return Lo.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=Go(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(Ca.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(`,`)),ns(`listConversations`,await this.getJson(t.toString(),`listConversations`),cs)}async loadConversation(e,{ids:t=[],beforeId:n,beforeCreatedAt:r}={}){let i=new URL(this.url(Ca.listMessages));i.searchParams.set(`conversationId`,e),i.searchParams.set(`limit`,`50`),t.length>0&&i.searchParams.set(`ids`,t.join(`,`)),n&&i.searchParams.set(`beforeId`,n),r&&i.searchParams.set(`beforeCreatedAt`,r);let a=ns(`loadConversation`,await this.getJson(i.toString(),`loadConversation`),ls);return{...a,messages:a.messages.toReversed()}}async markRead(e,t){if(!this.visitorId||!e)return;let n={type:`read`,conversationId:e,...t===void 0?{}:{lastMessageAt:t},revision:++this.conversationRevision};this.conversationsCache.update(e=>{let t=Go(e.conversations,n);return t===e.conversations?e:{...e,conversations:t}});for(let e of this.conversationListeners)e(n);try{await this.postJson(Ca.markRead,{conversationId:e},`markRead`,!0)}catch(e){Lo.debug(`markRead failed (non-fatal)`,{err:e})}}async requestOperator(){if(this.visitorId&&this.conversationId)try{return rs(`requestOperator`,await this.postJson(Ca.requestOperator,{},`requestOperator`))}catch(e){Lo.debug(`requestOperator failed (non-fatal)`,{err:e});return}}async emailTranscript(e){return ns(`emailTranscript`,await this.postJson(Ca.emailTranscript,{email:e},`emailTranscript`),us)}async cancelOperatorRequest(){if(this.visitorId&&this.conversationId)try{return rs(`cancelOperatorRequest`,await this.postJson(Ca.cancelOperatorRequest,{},`cancelOperatorRequest`))}catch(e){Lo.debug(`cancelOperatorRequest failed (non-fatal)`,{err:e});return}}listContent(e={}){return this.contentCache.getOrFetch(JSON.stringify(e,Object.keys(e).toSorted()),()=>this.fetchContent(e)).then(e=>({...e,items:e.items.map(e=>Zo(e,this.locale))}))}async fetchContent(e){let t=new URL(this.dataUrl(Ca.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=ns(`listContent`,await this.getJson(t.toString(),`listContent`),ds);return{...n,items:n.items??[]}}async setContentVote(e){try{await this.postJson(this.dataUrl(Ca.contentVoteSet),e,`setContentVote`)}catch{}}listContentCollections(e){return this.contentCollectionsCache.getOrFetch(e.join(`,`),()=>this.fetchContentCollections(e)).then(e=>({items:e.items.map(e=>Zo(e,this.locale))}))}async fetchContentCollections(e){let t=new URL(this.dataUrl(Ca.contentCollections));return e.length&&t.searchParams.set(`ids`,e.join(`,`)),{items:ns(`listContentCollections`,await this.getJson(t.toString(),`listContentCollections`),fs).items??[]}}async saveUserPrefs(e){await this.postJson(Ca.updateSettings,{userPrefs:e},`saveUserPrefs`)}get uploadPath(){return this.opts.endpoints?.upload??`/pai/upload-file`}get transcribePath(){return this.opts.endpoints?.transcribe??`/pai/transcribe-audio`}async submitFeedback(e){Lo.debug(`submitFeedback →`,{messageId:e.messageId,value:e.value});try{await this.postJson(Ca.messageFeedback,{messageId:e.messageId,set:{feedback:e.value}},`submitFeedback`)}catch(e){Lo.debug(`submitFeedback failed (non-fatal)`,{err:e})}}async sendTurn(e,t={}){Lo.debug(`message →`,{conversationId:e.conversationId,visitorId:e.visitorId,messageCount:e.messages.length});let n=JSON.stringify({...this.withEnvelope(e),[wa]:Do(this.userContext,this.pageContext,this.opts.recentHostEvents)}),r=t.keepalive===!0&&new Blob([n]).size<6e4;try{return await this.runWithAbort(async e=>{let t=await this.withFreshUserToken(()=>this.fetchImpl(this.url(Ca.streamMessage),{method:`POST`,credentials:`omit`,headers:{accept:`application/json`,"content-type":`application/json`,...this.headersFor(this.url(Ca.streamMessage))},body:n,keepalive:r,signal:e}));if(t.status!==202)throw new Oo(`sendTurn failed: expected 202, received ${t.status}`,`server`,t.status,void 0,ps(t),(await Ro(t)).error);let i;try{i=await t.json()}catch(n){throw e?.aborted?n:new Oo(`sendTurn failed: invalid acknowledgement`,`server`,t.status,n)}if(!es(i))throw new Oo(`sendTurn failed: invalid acknowledgement`,`server`,t.status);return i},void 0,3e4)}catch(e){throw e instanceof Oo?e:new Oo(`sendTurn failed: network error`,`network`,void 0,e)}}cancelTurn(e,t){this.visitorId&&e&&t&&(Lo.debug(`cancel stream`,{conversationId:e,runId:t,visitorId:this.visitorId}),this.fetchImpl(this.url(Ca.cancelStream),{method:`POST`,credentials:`omit`,headers:{"content-type":`application/json`,...this.headersFor(this.url(Ca.cancelStream))},body:JSON.stringify(this.withEnvelope({conversationId:e,runId:t})),keepalive:!0}).catch(e=>Lo.debug(`cancel POST failed (non-fatal)`,{err:e})))}async connectResumeStream(e){let t=new AbortController;function n(){return t.abort(e.signal.reason)}e.signal.aborted?n():e.signal.addEventListener(`abort`,n,{once:!0});let r=setTimeout(()=>t.abort(),1e4);function i(){clearTimeout(r),e.signal.removeEventListener(`abort`,n)}let a;try{a=await this.withFreshUserToken(()=>this.fetchImpl(this.resumeUrl(),{method:`GET`,credentials:`omit`,cache:`no-store`,headers:{accept:`text/event-stream`,...this.headersFor(this.resumeUrl())},signal:t.signal}))}catch(t){return i(),e.signal.aborted||Lo.debug(`resume-stream fetch failed — reconnecting`,{err:t}),`held`}if(!a.ok)return i(),a.status===409||Ko.has(a.status)?(Lo.debug(`resume-stream → transient response; reconnecting`,{status:a.status}),`held`):(Lo.debug(`resume-stream → endpoint unavailable`,{status:a.status}),`unavailable`);if(!a.body)return i(),Lo.debug(`resume-stream → bodyless response; stopping`,{status:a.status}),`unavailable`;if(!(a.headers.get(`content-type`)??``).includes(`text/event-stream`))return i(),Lo.debug(`resume-stream → non-SSE response; stopping`),`unavailable`;let o=!1;try{for await(let{chunk:n}of Ao(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`;Lo.debug(`resume-stream segment dropped — reconnecting`,{err:t})}finally{i()}return`held`}resumeUrl(){return this.withEnvelopeQuery(Ca.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.headersFor(this.url(e))},body:JSON.stringify(this.withEnvelope(t)),...r?{keepalive:!0}:{}}],n);return this.assertOk(i,n)}async postForm(e,t,n,r,i,a){let o=a?Io(a):this.fetchImpl;return this.runWithAbort(async r=>{let i=await this.withFreshUserToken(()=>o(this.url(e),{method:`POST`,credentials:`omit`,headers:this.headersFor(this.url(e)),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;function i(){return 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.headersFor(this.url(e))}}],t);return this.assertOk(n,t)}async fetchWithRetry(e,t){for(let n=0;;n++){let r;try{r=await this.withFreshUserToken(()=>this.fetchImpl(...e()))}catch(e){if(n>=3)throw new Oo(`${t} failed: network error`,`network`,void 0,e);Lo.debug(`request network error — retrying`,{label:t,attempt:n}),await wo(qo(n));continue}if(r.ok||!Ko.has(r.status)||n>=3)return r;let i=Yo(r.headers)??qo(n);Lo.debug(`request retryable status — retrying`,{label:t,status:r.status,attempt:n,wait:i}),await wo(i)}}async assertOk(e,t){if(!e.ok)throw new Oo(`${t} failed: ${e.status}`,`server`,e.status,void 0,void 0,(await Ro(e)).error);return await e.json()}fetchUserToken(){let e=this.userTokenSource;if(typeof e!=`function`)return Promise.resolve();let t=Promise.resolve().then(e).then(t=>{this.userTokenSource===e&&(this.userToken=t||void 0)},t=>{Lo.warn(`userToken function failed`,{err:t}),this.userTokenSource===e&&(this.userToken=void 0)});return this.userTokenRequest=t,t}headersFor(e){let t=!/^https?:\/\//i.test(e)||e.startsWith(`${this.opts.agentApiBaseUrl}/`);return{...this.opts.auth.headers(),...t&&this.userToken?{"x-user-token":this.userToken}:{},...t&&this.opts.continueLink?{"x-continue-link":this.opts.continueLink}:{}}}async withFreshUserToken(e){this.userTokenRequest&&await this.userTokenRequest;let t=await e();if(t.status!==401)return t;let n=await Ro(t);if(n.error===`USER_TOKEN_REQUIRED`)return this.opts.onLoginState?.({status:`required`,loginUrl:n.loginUrl}),t;if(!this.userToken)return t;if(!await this.refreshUserToken())return this.reportLogin(`expired`),t;this.reportLogin(`loggedIn`);let r=await e();return r.status===401&&this.reportLogin(`expired`),r}url(e){return/^https?:\/\//i.test(e)?e:`${this.opts.agentApiBaseUrl}${e}`}dataUrl(e){return`${this.opts.dataApiBaseUrl}${e}`}get fetchImpl(){return this.opts.fetchImpl??globalThis.fetch.bind(globalThis)}};function $o(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 es(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 ts(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ns(e,t,n){if(!n(t))throw new Oo(`${e} failed: invalid response body`,`server`);return t}function rs(e,t){let n=Ea(ts(t)?t.controlState:void 0);if(!n)throw new Oo(`${e} failed: invalid response body`,`server`);return n}function is(e){return!(!ts(e)||typeof e.visitorId!=`string`||typeof e.conversationId!=`string`||e.welcome!==void 0&&(!ts(e.welcome)||e.welcome.messages!==void 0&&!Array.isArray(e.welcome.messages)))}function as(e){return ts(e)&&typeof e.id==`string`&&typeof e.url==`string`&&typeof e.originalName==`string`&&typeof e.mimeType==`string`&&typeof e.fileSize==`number`}function os(e){return ts(e)&&typeof e.text==`string`}function ss(e){return ts(e)&&typeof e.page==`number`&&typeof e.limit==`number`&&typeof e.total==`number`&&typeof e.totalPages==`number`&&typeof e.hasNext==`boolean`&&typeof e.hasPrev==`boolean`}function cs(e){return ts(e)&&Array.isArray(e.conversations)&&e.conversations.every(ts)&&ss(e.pagination)}function ls(e){return ts(e)&&typeof e.conversationId==`string`&&Array.isArray(e.messages)&&e.messages.every(ts)}function us(e){return ts(e)&&typeof e.status==`string`&&typeof e.to==`string`}function ds(e){return ts(e)&&(e.items===void 0||Array.isArray(e.items)&&e.items.every(ts))&&(e.pagination===void 0||ss(e.pagination))}function fs(e){return ts(e)&&(e.items===void 0||Array.isArray(e.items)&&e.items.every(ts))}function ps(e){let t=Number(e.headers.get(`retry-after`));return Number.isInteger(t)&&t>0?t:void 0}function ms(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 hs(e,t,n){return ms(`close`,e,t)?n.includes(`close`):!1}function gs(e,t){return e===`inline`&&t===`fullscreen`?`exit-fullscreen`:`close`}function _s(e,t,n,r){let i={role:n,text:r};e.emit(`message`,i),t.onMessage?.(i)}function vs(e){return Object.fromEntries(e.map(e=>[e,[]]))}function ys(e,t,n){return e.includes(t)?t:e.includes(n)?n:e[0]??``}function bs(e,t,n){let r=[...new Set(t)],i=ys(r,e,``),a=o({activeTab:i,stacks:vs(r)});return{sig:a,reconcile(e,t){let i=[...new Set(e)],o=a.value,s=ys(i,o.activeTab,t),c=Object.fromEntries(i.map(e=>[e,o.stacks[e]??[]])),l=s===o.activeTab&&i.length===Object.keys(o.stacks).length&&i.every(e=>o.stacks[e]===c[e]);r=i,l||(a.value={activeTab:s,stacks:c},s!==o.activeTab&&s&&n?.(s))},switchTab(e){e in a.value.stacks&&a.value.activeTab!==e&&(a.value={...a.value,activeTab:e},n?.(e))},open(e,t){let r=a.value;e in r.stacks&&(a.value={activeTab:e,stacks:{...r.stacks,[e]:t?[t]:[]}},r.activeTab!==e&&n?.(e))},push(e){let t=a.value,n=t.stacks[t.activeTab]??[];a.value={...t,stacks:{...t.stacks,[t.activeTab]:[...n,e]}}},pop(){let e=a.value,t=e.stacks[e.activeTab]??[];t.length!==0&&(a.value={...e,stacks:{...e.stacks,[e.activeTab]:t.slice(0,-1)}})},reset(e){a.value={activeTab:ys(r,e,``),stacks:vs(r)}}}}function xs(e){return e.stacks[e.activeTab]??[]}function Ss(e){return xs(e).at(-1)}function Cs(e){return xs(e).length===0}function ws(e){/^(https?:)?\//i.test(e)&&window.open(e,`_blank`,`noopener,noreferrer`)}function Ts(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 Es(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 Ds(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:Es(e.mode,e.size,t)}}function Os(){return typeof window>`u`?0:window.innerWidth}const q={fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,viewBox:`0 0 24 24`},ks=`${N.cssPrefix}-icon-dir`;function As(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M21 12a8 8 0 0 1-12 6.93L3 21l1.65-5.16A8 8 0 1 1 21 12Z`})})}function js(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M18 6 6 18M6 6l12 12`})})}function Ms(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M12 5v14M5 12h14`})})}function Ns(){return/* @__PURE__ */ v(`svg`,{...q,class:ks,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),/* @__PURE__ */ _(`path`,{d:`M22 2 11 13`})]})}function Ps(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M12 19V5M5 12l7-7 7 7`})})}function Fs(){return/* @__PURE__ */ _(`svg`,{...q,class:ks,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M3 20V4l18 8-18 8Z`})})}function Is(){return/* @__PURE__ */ _(`svg`,{...q,class:ks,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`m9 18 6-6-6-6`})})}function Ls(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})})}function Rs(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`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`})})}function zs(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`rect`,{x:`9`,y:`2`,width:`6`,height:`12`,rx:`3`}),/* @__PURE__ */ _(`path`,{d:`M5 10a7 7 0 0 0 14 0M12 19v3`})]})}function Bs(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`8`,r:`4.5`}),/* @__PURE__ */ _(`path`,{d:`M4.5 20.5a7.5 7.5 0 0 1 15 0`})]})}function Vs(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M3 8V3h5M21 8V3h-5M3 16v5h5M21 16v5h-5`})})}function Hs(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M8 3v5H3M16 3v5h5M8 21v-5H3M16 21v-5h5`})})}function Us(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M3 3h7v2H5v5H3zM21 3h-7v2h5v5h2zM3 21h7v-2H5v-5H3zM21 21h-7v-2h5v-5h2z`})})}function Ws(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M10 3v5H3M14 3v5h7M10 21v-5H3M14 21v-5h7`})})}function Gs(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M14 3h7v7M21 3l-9 9`}),/* @__PURE__ */ _(`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`})]})}function Ks(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,viewBox:`0 0 10 10`,children:/* @__PURE__ */ _(`path`,{d:`M9 1L1 9M9 5L5 9M9 9H9`,strokeWidth:`1.5`})})}function qs(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:`currentColor`,stroke:`none`}),/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:`currentColor`,stroke:`none`}),/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:`currentColor`,stroke:`none`})]})}function Js(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M11 5 6 9H2v6h4l5 4zM15 9a5 5 0 0 1 0 6M18 7a9 9 0 0 1 0 10`})})}function Ys(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M11 5 6 9H2v6h4l5 4zM22 9l-6 6M16 9l6 6`})})}function Xs(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M3 18 8 6l5 12M4.7 14h6.6`}),/* @__PURE__ */ _(`path`,{d:`M14.5 18l3.2-7 3.2 7M15.6 15.8h4.2`})]})}function Zs(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M20 6 9 17l-5-5`})})}function Qs(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M3 3v6h6`}),/* @__PURE__ */ _(`path`,{d:`M3.05 13A9 9 0 1 0 6 5.3L3 9`}),/* @__PURE__ */ _(`path`,{d:`M12 7v5l3 2`})]})}function $s(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`10`}),/* @__PURE__ */ _(`path`,{d:`M2 12h20`}),/* @__PURE__ */ _(`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`})]})}function ec(){return/* @__PURE__ */ _(`svg`,{...q,class:ks,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M19 12H5M12 19l-7-7 7-7`})})}function tc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M12 20h9`}),/* @__PURE__ */ _(`path`,{d:`M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z`})]})}function nc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`rect`,{x:`3`,y:`5`,width:`18`,height:`14`,rx:`2`}),/* @__PURE__ */ _(`path`,{d:`m3 7 9 6 9-6`})]})}function rc(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`m6 9 6 6 6-6`})})}function ic(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z`}),/* @__PURE__ */ _(`path`,{d:`M14 2v6h6`})]})}function ac(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`m12 3-1.5 4.5L6 9l4.5 1.5L12 15l1.5-4.5L18 9l-4.5-1.5Z`}),/* @__PURE__ */ _(`path`,{d:`M19 15v4M17 17h4M5 3v2M4 4h2`})]})}function oc(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z`})})}function sc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`10`}),/* @__PURE__ */ _(`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`}),/* @__PURE__ */ _(`path`,{d:`M12 17h.01`})]})}function cc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`m15 4 3 3-9 9-3-3z`}),/* @__PURE__ */ _(`path`,{d:`M18 2v2M20 4h2M3 20l3-3M3 16h2M5 14v2`})]})}function lc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`rect`,{x:`4`,y:`8`,width:`16`,height:`12`,rx:`2`}),/* @__PURE__ */ _(`path`,{d:`M12 8V4`}),/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`3`,r:`1`}),/* @__PURE__ */ _(`path`,{d:`M2 14h2M20 14h2M9 13h.01M15 13h.01M9.5 17h5`})]})}function uc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M4 14v-2a8 8 0 0 1 16 0v2`}),/* @__PURE__ */ _(`rect`,{x:`2`,y:`14`,width:`4`,height:`6`,rx:`1.5`}),/* @__PURE__ */ _(`rect`,{x:`18`,y:`14`,width:`4`,height:`6`,rx:`1.5`}),/* @__PURE__ */ _(`path`,{d:`M20 20v1a3 3 0 0 1-3 3h-5`})]})}function dc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`10`}),/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`4`}),/* @__PURE__ */ _(`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`})]})}function fc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`11`,cy:`11`,r:`7`}),/* @__PURE__ */ _(`path`,{d:`m21 21-4.3-4.3`})]})}function pc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`9`}),/* @__PURE__ */ _(`path`,{d:`m8.5 12 2.5 2.5 4.5-5`})]})}function mc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M3 9.5 12 3l9 6.5`}),/* @__PURE__ */ _(`path`,{d:`M5 9v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9`})]})}function hc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`m3 11 15-5v12L3 13z`}),/* @__PURE__ */ _(`path`,{d:`M3 11v2a2 2 0 0 0 2 2h1V9H5a2 2 0 0 0-2 2z`}),/* @__PURE__ */ _(`path`,{d:`M7 15v3a2 2 0 0 0 4 0v-2`}),/* @__PURE__ */ _(`path`,{d:`M21 10a3 3 0 0 1 0 4`})]})}function gc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z`}),/* @__PURE__ */ _(`path`,{d:`M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1`})]})}function _c(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`4`}),/* @__PURE__ */ _(`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`})]})}function vc(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z`})})}function yc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`9`}),/* @__PURE__ */ _(`path`,{d:`M12 3v18`}),/* @__PURE__ */ _(`path`,{d:`M12 3a9 9 0 0 1 0 18z`,fill:`currentColor`,stroke:`none`})]})}function bc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`10.5`,cy:`10.5`,r:`6.5`}),/* @__PURE__ */ _(`path`,{d:`M8 11a2.5 2.5 0 0 0 5 0`}),/* @__PURE__ */ _(`path`,{d:`m20 20-4.4-4.4`})]})}function xc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`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`}),/* @__PURE__ */ _(`path`,{d:`M18.5 4v3M20 5.5h-3M5.5 16v2.5M6.75 17.25h-2.5`})]})}function Sc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M4 18h16`}),/* @__PURE__ */ _(`path`,{d:`M5 18a7 7 0 0 1 14 0`}),/* @__PURE__ */ _(`path`,{d:`M12 8V6`}),/* @__PURE__ */ _(`path`,{d:`M10 6h4`})]})}function Cc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M7 11V6.5a1.5 1.5 0 0 1 3 0V10`}),/* @__PURE__ */ _(`path`,{d:`M10 10V5.5a1.5 1.5 0 0 1 3 0V10`}),/* @__PURE__ */ _(`path`,{d:`M13 10V6.5a1.5 1.5 0 0 1 3 0V12`}),/* @__PURE__ */ _(`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`})]})}function wc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`rect`,{x:`9`,y:`9`,width:`11`,height:`11`,rx:`2`}),/* @__PURE__ */ _(`path`,{d:`M5 15a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2`})]})}function Tc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M7 10v11H4a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z`}),/* @__PURE__ */ _(`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`})]})}function Ec(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`path`,{d:`M17 14V3h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1z`}),/* @__PURE__ */ _(`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`})]})}function Dc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`3.5`}),/* @__PURE__ */ _(`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`})]})}function Oc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`9`}),/* @__PURE__ */ _(`path`,{d:`M12 7v5l3 2`})]})}function kc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`9`}),/* @__PURE__ */ _(`path`,{d:`m8.5 12 2.5 2.5 4.5-5`})]})}function Ac(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`9`}),/* @__PURE__ */ _(`path`,{d:`m15 9-6 6M9 9l6 6`})]})}function jc(){return/* @__PURE__ */ _(`svg`,{...q,"aria-hidden":`true`,children:/* @__PURE__ */ _(`path`,{d:`M12 18V5M15 13a4.17 4.17 0 01-3-4 4.17 4.17 0 01-3 4M17.707 6.294A3 3 0 1012 5a3 3 0 10-5.707 1.294M17.996 5.125a4 4 0 012.526 5.77M18 18a4 4 0 002-7.465M19.967 17.482a4 4 0 11-7.967.517 4 4 0 11-7.967-.517M6 18a4 4 0 01-2-7.465M6.004 5.125a4 4 0 00-2.526 5.77`})})}function Mc(){return/* @__PURE__ */ v(`svg`,{...q,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`circle`,{cx:`12`,cy:`12`,r:`10`}),/* @__PURE__ */ _(`path`,{d:`M12 8v4M12 16h.01`})]})}const Nc={chat:As,message:oc,bubbles:gc,spark:ac,wand:cc,bot:lc,help:sc,lifebuoy:dc,headset:uc,search:bc,sparkles:xc,concierge:Sc,wave:Cc},J=N.cssPrefix,Y={launcher:`${J}-launcher`,callout:`${J}-callout`,calloutDismiss:`${J}-callout-dismiss`,panel:`${J}-panel`,panelHeader:`${J}-panel-header`,resizeGrip:`${J}-resize-grip`,scrollToBottom:`${J}-scroll-to-bottom`,loadPreviousMessages:`${J}-load-previous-messages`,actionHistory:`${J}-action-history`,actionClose:`${J}-action-close`,emailTranscriptSheet:`${J}-email-transcript-sheet`,emailTranscriptEmail:`${J}-email-transcript-email`,emailTranscriptSend:`${J}-email-transcript-send`,langSegment:`${J}-lang-segment`,composer:`${J}-composer`,composerInput:`${J}-composer-input`,composerCount:`${J}-composer-count`,composerSend:`${J}-composer-send`,composerStop:`${J}-composer-stop`,compactionStatus:`${J}-compaction-status`,messageQueue:`${J}-message-queue`,queuedMessage:`${J}-queued-message`,queuedMessageRemove:`${J}-queued-message-remove`,composerAttach:`${J}-composer-attach`,composerFileInput:`${J}-composer-file-input`,composerVoice:`${J}-composer-voice`,attachmentChip:`${J}-attachment-chip`,attachmentRemove:`${J}-attachment-remove`,attachmentRetry:`${J}-attachment-retry`,suggestion:`${J}-suggestion`,messageBubble:`${J}-message`,messageRetry:`${J}-message-retry`,messageFile:`${J}-message-file`,messageFeedback:`${J}-message-feedback`,feedbackUp:`${J}-feedback-up`,feedbackDown:`${J}-feedback-down`,messageCopy:`${J}-message-copy`,historyItem:`${J}-history-item`,historyLoadMore:`${J}-history-load-more`,sidebar:`${J}-sidebar`,sidebarToggle:`${J}-sidebar-toggle`,sidebarNewConversation:`${J}-sidebar-new-conversation`,messengerHome:`${J}-messenger-home`,panelNotice:`${J}-panel-notice`,tab:`${J}-tab`,tabBadge:`${J}-tab-badge`,homeView:`${J}-home-view`,homeGreeting:`${J}-home-greeting`,homeBrand:`${J}-home-brand`,backHeader:`${J}-back-header`,contentView:`${J}-content-view`,contentScroll:`${J}-content-scroll`,homeSearch:`${J}-home-search`,helpSearch:`${J}-help-search`,homeRecent:`${J}-home-recent`,homeAsk:`${J}-home-ask`,homeWhatsNew:`${J}-home-whats-new`,homeContentRow:`${J}-home-content-row`,helpArticle:`${J}-help-article`,newsItem:`${J}-news-item`,newsMore:`${J}-news-more`,formField:`${J}-form-field`,toolAskQuestions:`${J}-tool-ask-questions`,toolInputSubmit:`${J}-tool-input-submit`,toolInputSkip:`${J}-tool-input-skip`,toolApproval:`${J}-tool-approval`,toolPreview:`${J}-tool-preview`,toolApprove:`${J}-tool-approve`,toolDecline:`${J}-tool-decline`,toolEdit:`${J}-tool-edit`,toolDecision:`${J}-tool-decision`,typingDots:`${J}-typing-dots`,reasoning:`${J}-reasoning`,replyStopped:`${J}-reply-stopped`,toolAskSummary:`${J}-ask-questions-summary`,toolAskOptions:`${J}-ask-questions-options-toggle`,toolSteps:`${J}-tool-steps`,toolStep:`${J}-tool-step`,source:`${J}-source`,operatorRequest:`${J}-operator-request`,chatNotice:`${J}-chat-notice`,operatorBanner:`${J}-operator-banner`,cancelOperatorRequest:`${J}-cancel-operator-request`,loginBar:`${J}-login-bar`,loginBarAction:`${J}-login-bar-action`,loginBarHide:`${J}-login-bar-hide`,loginGate:`${J}-login-gate`,loginGateAction:`${J}-login-gate-action`,loginGateGuest:`${J}-login-gate-guest`,loggedIn:`${J}-logged-in`};function Pc(e,t){return`${e}-${t}`}const Fc=N.cssPrefix;function Ic({buttonRef:e,onToggle:t,launcher:n,strings:r,leaving:i,edgeTab:a}){let o=n.variant===`circle`?``:Lc(n,r);return/* @__PURE__ */ v(`button`,{ref:e,type:`button`,class:`${Fc}-fab`,part:`launcher`,"data-variant":n.variant,"data-size":n.size,"data-edge-tab":a?`true`:void 0,"data-leaving":i?`true`:void 0,"data-testid":Y.launcher,onClick:t,"aria-label":r.launcherOpen,children:[Rc(n.icon),o?/* @__PURE__ */ _(`span`,{class:`${Fc}-fab-label`,children:o}):null]})}function Lc(e,t){return e.label?M(t,e.label):e.personaName?t.launcherAsk.replace(`{name}`,M(t,e.personaName)):``}function Rc(e){let t=Nc[e];return t?/* @__PURE__ */ _(t,{}):/* @__PURE__ */ _(zc,{source:e})}function zc({source:e}){return/* @__PURE__ */ _(`span`,{ref:t=>{t&&Bc(t,e)},"aria-hidden":`true`})}function Bc(e,t){if(e.dataset.svgMounted!==t)try{let n=new DOMParser().parseFromString(t,`image/svg+xml`).documentElement;n.tagName.toLowerCase()===`svg`&&(e.replaceChildren(document.importNode(n,!0)),e.dataset.svgMounted=t)}catch{}}function Vc({callout:e,launcherPosition:t,strings:n,closeLabel:r,onDismiss:i}){let[a,o]=h(!1),s=m(null),[c,l]=h(!0);return f(()=>{let e=s.current?.parentElement;if(!e)return;let t=()=>l(window.innerWidth-e.getBoundingClientRect().width>=Hc);return t(),window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)}),u(()=>{let t=setTimeout(()=>o(!0),e.delayMs);return()=>clearTimeout(t)},[e.delayMs]),u(()=>{if(!a||e.autoDismissMs<=0)return;let t=setTimeout(i,e.autoDismissMs);return()=>clearTimeout(t)},[a,e.autoDismissMs,i]),a?/* @__PURE__ */ v(`div`,{ref:s,class:`${Fc}-callout`,role:`status`,"data-shape":e.shape,"data-position":Uc(e.position,t,c),"data-animated":e.animated?`true`:void 0,"data-testid":Y.callout,children:[/* @__PURE__ */ _(`span`,{children:M(n,e.text)}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Fc}-callout-close`,onClick:i,"aria-label":r,title:r,"data-testid":Y.calloutDismiss,children:/* @__PURE__ */ _(js,{})})]}):null}const Hc=200;function Uc(e,t,n=!0){let r=t.endsWith(`-right`),i=t.startsWith(`bottom-`);return e===`vertical`||e===`auto`&&!n?i?`top`:`bottom`:r?`left`:`right`}function Wc(e){function 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(),o=a instanceof ShadowRoot?a.activeElement:null;t.shiftKey&&o===r?(t.preventDefault(),i.focus()):!t.shiftKey&&o===i&&(t.preventDefault(),r.focus())}return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)}const Gc=N.cssPrefix;function Kc({title:e,actions:t}){return/* @__PURE__ */ v(`header`,{class:`${Gc}-back-header`,part:`header`,"data-variant":`title`,children:[/* @__PURE__ */ _(`span`,{class:`${Gc}-back-spacer`,"aria-hidden":`true`}),/* @__PURE__ */ _(`h1`,{class:`${Gc}-back-title`,children:e}),t??/* @__PURE__ */ _(`span`,{class:`${Gc}-back-spacer`,"aria-hidden":`true`})]})}function qc({title:e,backLabel:t,onBack:n,actions:r,testid:i}){return/* @__PURE__ */ v(`header`,{class:`${Gc}-back-header`,part:`header`,"data-testid":i,children:[/* @__PURE__ */ _(`button`,{type:`button`,class:`${Gc}-icon-btn`,onClick:n,"aria-label":t,title:t,children:/* @__PURE__ */ _(ec,{})}),/* @__PURE__ */ _(`h1`,{class:`${Gc}-back-title`,children:e}),r??/* @__PURE__ */ _(`span`,{class:`${Gc}-back-spacer`,"aria-hidden":`true`})]})}function Jc({textSig:e,doneSig:t,generativeUi:n=!1,strings:r=D,onCardAction:i}){let o=m(null),s=m(null);return f(()=>{let c=o.current;if(!c)return;c.classList.add(`${N.cssPrefix}-md`);let l=s.current,u={generativeUi:n,strings:r,onCardAction:i},d=()=>{s.current?.renderer?.dispose();let a=document.createElement(`div`),o=n?sa(a,{cssPrefix:N.cssPrefix,strings:r,onAction:i}):void 0,l=y.parser(Qc(rl(o??y.default_renderer(a)))),d=e.value,f=d.length;if(!t.value)for(;f>0&&d[f-1]===`_`;)f--;let p=Zc(d.slice(0,f));return p&&y.parser_write(l,p),t.value&&(y.parser_end(l),o?.finish()),c.replaceChildren(a),{settings:u,container:a,parser:l,renderer:o,lastLen:f,lastText:d.slice(0,f)}},f=l&&l.settings.generativeUi===n&&l.settings.strings===r&&l.settings.onCardAction===i&&e.value.startsWith(l.lastText)?l:d();s.current=f;let p=a(()=>{let n=e.value,r=t.value;if(n.length<f.lastLen){f=d(),s.current=f;return}let i=n.length;if(!r)for(;i>f.lastLen&&n[i-1]===`_`;)i--;let a=Math.max(f.lastLen-1,0),o=Zc(n.slice(a,i)).slice(f.lastLen-a);o&&y.parser_write(f.parser,o),f.lastLen=i,f.lastText=n.slice(0,i),r&&(y.parser_end(f.parser),f.renderer?.finish())}),m=new MutationObserver(()=>il(c));m.observe(c,{childList:!0,subtree:!0}),il(c);function h(e){let t=e.target instanceof Element?e.target.closest(`a`):null;if(!t||!(t instanceof HTMLAnchorElement))return;let n=t.getAttribute(`href`)??``;n&&!n.startsWith(`#`)&&(e.preventDefault(),window.open(n,`_blank`,`noopener,noreferrer`))}return c.addEventListener(`click`,h),()=>{p(),m.disconnect(),c.removeEventListener(`click`,h)}},[e,t,n,r,i]),u(()=>()=>{s.current?.renderer?.dispose(),s.current=null},[]),/* @__PURE__ */ _(`div`,{ref:o})}function Yc({text:e}){let t=p(()=>o(e),[e]),n=p(()=>o(!0),[]);return/* @__PURE__ */ _(Jc,{textSig:t,doneSig:n})}const Xc=/([\p{L}\p{N}])(_+)(?=[\p{L}\p{N}])/gu;function Zc(e){return e.replace(Xc,(e,t,n)=>t+``.repeat(n.length))}function Qc(e){return{...e,add_text:(t,n)=>e.add_text(t,n.replaceAll(``,`_`)),set_attr:(t,n,r)=>e.set_attr(t,n,r.replaceAll(``,`_`))}}const $c=/<(\/?)(?:(Note|Info|Tip|Warning|Danger|Check|Callout)|Tabs?|Steps?|AccordionGroup|Accordion|Expandable|Columns|CardGroup|Card|Frame|CodeGroup|Badge|Icon|Video|Embed|ParamField|ResponseField)\b((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>|(^|\n)([ \t]*)(```[^]*?(?:\n[ \t]*```|$))?/g;function el(e){let t=0,n=``;return e.replace($c,(e,r,i,a,o,s,c,l)=>{if(r===void 0)return t?s+(l?.split(`\n${c}`).join(`
35
- `)??n):e;if(r)return t--,i&&(n=n.slice(2)),i?`\n${n}`:``;o||(t++,i&&(n+=`> `));let u={};a.replace(/(\w+)=(["'])(.*?)\2/g,(e,t,n,r)=>u[t]=r);let d=u.href??u.src,f=u.title??u.path??u.query??u.body??u.header??u.name??d;return(i?`> `:``)+(f?`**${d?`[${f}](${d})`:f}**${u.type?` \`${u.type}\``:``}\n${n}`:``)})}const tl=/* @__PURE__ */ new Set([`http:`,`https:`,`mailto:`,`tel:`]),nl=/* @__PURE__ */ new Set([`http:`,`https:`]);function rl(e){let t=document.createElement(`a`);return{...e,set_attr:(n,r,i)=>{if(r!==y.HREF&&r!==y.SRC||(t.href=i,(r===y.HREF?tl:nl).has(t.protocol)))return e.set_attr(n,r,i);let a=r===y.SRC?n.nodes[n.index]:void 0;a?.replaceWith(...a.childNodes)}}}function il(e){for(let t of e.querySelectorAll(`a`)){let e=t.getAttribute(`href`)??``;e&&!e.startsWith(`#`)&&(t.target=`_blank`,t.rel=`noopener noreferrer`)}}const al=/* @__PURE__ */ new Set([y.CODE_INLINE,y.ITALIC_AST,y.ITALIC_UND,y.STRONG_AST,y.STRONG_UND,y.STRIKE,y.LINK,y.RAW_URL,y.IMAGE,y.EQUATION_INLINE]);function ol(e){let t=``,n=[],r=y.parser({data:void 0,add_token:(e,r)=>{n.push(r),al.has(r)||(t+=` `)},end_token:()=>{let e=n.pop();e!==void 0&&!al.has(e)&&(t+=` `)},add_text:(e,n)=>void(t+=n),set_attr:()=>void 0});return y.parser_write(r,Zc(e)),y.parser_end(r),t.replaceAll(``,`_`).replace(/\s+/g,` `).trim()}const sl=N.cssPrefix;function cl({tone:e=`info`,message:t,onRetry:n,strings:r}){return/* @__PURE__ */ v(`div`,{class:`${sl}-module-empty`,role:e===`error`?`alert`:`status`,"aria-live":`polite`,children:[/* @__PURE__ */ _(`span`,{children:t}),n?/* @__PURE__ */ _(`button`,{type:`button`,class:`${sl}-module-retry`,onClick:n,children:r.errorRetry}):null]})}const ll=N.cssPrefix,ul=R.scope(`content`);function dl({id:e,title:t,transport:n,strings:r,bus:i,onBack:a,actions:o}){let[s,c]=h(null),[d,f]=h(!1),[p,m]=h(!1),[y,b]=h(0),[x,S]=h(null),C=l(()=>{m(!1),c(null),b(e=>e+1)},[]);u(()=>{let t=!1,r=n.listContentCollections([]).catch(()=>void 0);return Promise.all([n.listContent({ids:[e],limit:1}),r]).then(([n,r])=>{if(t)return;let a=n.items[0];a?(c(a),f(r?.items.find(e=>e.id===a.contentCollectionId)?.settings?.voteAccess===`portal`),i.emit(`contentOpen`,{contentId:e,contentCollectionId:a.contentCollectionId})):m(!0)}).catch(e=>{t||(ul.warn(`listContent (reader) failed`,{err:e}),m(!0))}),()=>{t=!0}},[n,e,y,i]),u(()=>{if(!s)return;let t=setTimeout(()=>i.emit(`contentRead`,{contentId:e}),5e3);return()=>clearTimeout(t)},[s,e,i]);let w=l(t=>{let n=(t.target instanceof HTMLElement?t.target.closest(`a`):null)?.getAttribute(`href`)??``;n&&!n.startsWith(`#`)&&i.emit(`contentLinkClick`,{contentId:e})},[i,e]);function T(t){S(e),n.setContentVote({contentId:e,value:t})}function E(){return p?/* @__PURE__ */ _(cl,{tone:`error`,message:r.errorGeneric,onRetry:C,strings:r}):s===null?/* @__PURE__ */ _(cl,{message:r.contentLoading,strings:r}):/* @__PURE__ */ v(`article`,{class:`${ll}-content`,"data-testid":Y.contentView,onClick:w,children:[s.image?/* @__PURE__ */ _(`img`,{class:`${ll}-content-hero`,src:s.image,alt:``,loading:`lazy`}):null,s.description?/* @__PURE__ */ _(`p`,{class:`${ll}-content-subtitle`,children:s.description}):null,/* @__PURE__ */ _(Yc,{text:el(s.content??``)}),d?/* @__PURE__ */ _(`div`,{class:`${ll}-content-vote`,"aria-live":`polite`,children:x===e?r.feedbackThanks:/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`span`,{children:r.contentHelpful}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${ll}-module-retry`,onClick:()=>T(1),children:r.confirmYes}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${ll}-module-retry`,onClick:()=>T(0),children:r.confirmNo})]})}):null]})}return/* @__PURE__ */ v(`div`,{class:`${ll}-module`,children:[/* @__PURE__ */ _(qc,{title:s?.title||t||r.moduleBack,backLabel:r.moduleBack,onBack:a,actions:o,testid:Y.backHeader}),/* @__PURE__ */ _(`div`,{class:`${ll}-module-scroll`,"data-testid":Y.contentScroll,children:E()})]})}function fl({itemCount:e,initialFocusIndex:t}){let[n,r]=h(!1),i=m(null),a=m(null),[o,s]=h(-1),c=l(()=>{r(!1),s(-1),i.current?.focus()},[]),d=l(()=>r(e=>!e),[]);return u(()=>{if(!n)return;function e(e){let t=a.current,n=i.current;if(!t||!n)return;let o=e.composedPath();o.includes(t)||o.includes(n)||(r(!1),s(-1))}return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[n]),u(()=>{if(!n||e===0)return;let r=t?.()??0;s(r<0||r>=e?0:r)},[n,e,t]),u(()=>{!n||o<0||(a.current?.querySelectorAll(`[role='menuitem']`))?.[o]?.focus()},[n,o]),{open:n,focusIndex:o,triggerRef:i,menuRef:a,toggle:d,close:c,onTriggerKey:l(e=>{(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r(!0))},[]),onMenuKey:l(t=>{if(e!==0)switch(t.key){case`Escape`:t.preventDefault(),t.stopPropagation(),c();return;case`ArrowDown`:t.preventDefault(),s(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),s(t=>(t-1+e)%e);return;case`Home`:t.preventDefault(),s(0);return;case`End`:t.preventDefault(),s(e-1)}},[e,c])}}function pl({items:e,triggerLabel:t}){let n=N.cssPrefix,r=fl({itemCount:e.length});function i(e){e.disabled||(e.onSelect?.(),e.keepOpen||r.close())}function a(e,t){return e.onSelectValue?.(t)}function 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;let o=n[i];o&&(e.preventDefault(),e.stopPropagation(),a(t,o.value))}return/* @__PURE__ */ v(`div`,{class:`${n}-menu-wrap`,children:[/* @__PURE__ */ _(`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:/* @__PURE__ */ _(qs,{})}),r.open?/* @__PURE__ */ _(`div`,{ref:r.menuRef,class:`${n}-menu`,role:`menu`,"aria-label":t,onKeyDown:r.onMenuKey,tabIndex:-1,children:e.map(e=>e.segments?/* @__PURE__ */ v(`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?/* @__PURE__ */ _(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,/* @__PURE__ */ _(`span`,{class:`${n}-menu-label`,children:e.label}),/* @__PURE__ */ _(`span`,{class:`${n}-segmented`,role:`group`,"aria-label":e.label,children:e.segments.map(t=>{let r=t.value===e.value;return/* @__PURE__ */ _(`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":`${Y.langSegment}-${t.value}`,onClick:()=>a(e,t.value),children:t.label},t.value)})})]},e.id):/* @__PURE__ */ v(`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?/* @__PURE__ */ _(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,/* @__PURE__ */ _(`span`,{class:`${n}-menu-label`,children:e.label}),e.type===`switch`&&e.on?/* @__PURE__ */ _(`span`,{class:`${n}-menu-check`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Zs,{})}):null]},e.id))}):null]})}const ml=N.cssPrefix;function hl(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 gl={normal:`large`,large:`small`,small:`normal`};function _l(e){return _(e===`light`?_c:e===`dark`?vc:yc,{})}function vl(e,t){let n=e.split(`-`)[0];return(t.some(t=>t!==e&&t.split(`-`)[0]===n)?e:n??e).toUpperCase()}function yl(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 bl({panelProps:e,variant:t,onEmailTranscript:n,onLogIn:r}){let{options:i,panelSize:a,feedback:o,onClose:c,onClear:l,onExpand:u,onFullscreen:d,onSoundToggle:f}=e,{onToggleHistory:p,onLocaleChange:m,onThemeChange:h,onTextSizeChange:g}=e,y=i.strings,b=i.mode,x=t===`chat`,S=s(()=>o.mutedSig.value).value,C=new Set(i.actions);function w(e){return C.has(e)}let T=typeof matchMedia==`function`&&matchMedia(`(max-width: 640px)`).matches;function E(e){return!T&&ms(e,b,a)}let D=i.themeMode,O={auto:y.themeAuto,light:y.themeLight,dark:y.themeDark},k=i.textSize,A={small:y.textSizeSmall,normal:y.textSizeNormal,large:y.textSizeLarge},j=[];if(x&&w(`clear`)&&j.push({id:`clear`,icon:/* @__PURE__ */ _(tc,{}),label:y.newConversation,onSelect:l}),x&&n&&j.push({id:`emailTranscript`,icon:/* @__PURE__ */ _(nc,{}),label:y.emailTranscript,onSelect:n}),x&&r&&j.push({id:`logIn`,icon:/* @__PURE__ */ _(Bs,{}),label:y.loginAction,onSelect:r}),w(`expand`)&&E(`expand`)){let e=a===`expanded`;j.push({id:`expand`,icon:_(e?Hs:Vs,{}),label:e?y.collapse:y.expand,type:`switch`,on:e,onSelect:u})}if(w(`fullscreen`)&&E(`fullscreen`)){let e=a===`fullscreen`;j.push({id:`fullscreen`,icon:_(e?Ws:Us,{}),label:e?y.exitFullscreen:y.fullscreen,type:`switch`,on:e,onSelect:d})}let ee=i.popOutUrl,M=i.aiAgentDeploymentId;w(`popOut`)&&ee&&M&&ms(`popOut`,b,a)&&j.push({id:`popOut`,icon:/* @__PURE__ */ _(Gs,{}),label:y.popOut,onSelect:()=>{let t=yl(ee,{conversationId:e.conversationId,widgetId:i.widgetId,publicKey:i.publicKey,aiAgentDeploymentId:M});t&&window.open(t,`_blank`,`noopener,noreferrer`)}}),x&&w(`sound`)&&j.push({id:`sound`,icon:_(S?Ys:Js,{}),label:S?y.soundOff:y.soundOn,type:`switch`,on:!S,onSelect:f}),w(`theme`)&&D!==`host`&&j.push({id:`theme`,icon:_l(D),label:`${y.theme}: ${O[D]}`,onSelect:()=>h(hl(D)),keepOpen:!0}),w(`textSize`)&&j.push({id:`textSize`,icon:/* @__PURE__ */ _(Xs,{}),label:`${y.textSize}: ${A[k]}`,onSelect:()=>g(gl[k]),keepOpen:!0}),w(`language`)&&i.availableLocales.length>1&&j.push({id:`language`,icon:/* @__PURE__ */ _($s,{}),label:y.language,segments:i.availableLocales.map(e=>({value:e,label:vl(e,i.availableLocales),lang:e})),value:i.locale,onSelectValue:m});let te=!!c&&hs(b,a,i.actions),N=x&&w(`history`);return/* @__PURE__ */ v(`div`,{class:`${ml}-header-actions`,children:[N?/* @__PURE__ */ _(`button`,{type:`button`,class:`${ml}-icon-btn`,onClick:p,"aria-label":y.history,title:y.history,"data-testid":Y.actionHistory,children:/* @__PURE__ */ _(Qs,{})}):null,j.length>0?/* @__PURE__ */ _(pl,{items:j,triggerLabel:y.moreActions}):null,te?/* @__PURE__ */ _(`button`,{type:`button`,class:`${ml}-icon-btn`,onClick:c,"aria-label":y.close,title:y.close,"data-testid":Y.actionClose,children:/* @__PURE__ */ _(js,{})}):null]})}const xl={Icon:gc};function Sl(e,t){return e instanceof Oo?e.status===429?e.retryAfterSeconds?t.errorRateLimitedIn.replace(`{seconds}`,String(e.retryAfterSeconds)):t.errorRateLimited:e.code===`network`?t.errorOffline:e.status===403?t.errorOriginNotAllowed:e.errorCode===`MESSAGE_TOO_LONG`?t.errorMessageTooLong:e.status!==void 0&&e.status>=500?t.errorServer:t.errorGeneric:t.errorGeneric}const Cl=N.cssPrefix;function wl({placeholder:e,onActivate:t}){return/* @__PURE__ */ v(`button`,{type:`button`,class:`${Cl}-home-search`,onClick:t,"data-testid":Y.homeSearch,children:[/* @__PURE__ */ _(`span`,{class:`${Cl}-home-search-text`,children:e}),/* @__PURE__ */ _(`span`,{class:`${Cl}-home-search-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(fc,{})})]})}function Tl({placeholder:e,value:t,onInput:n}){return/* @__PURE__ */ v(`div`,{class:`${Cl}-home-search`,"data-input":`true`,children:[/* @__PURE__ */ _(`input`,{type:`search`,class:`${Cl}-home-search-input`,placeholder:e,value:t,maxLength:200,onInput:e=>n(e.currentTarget.value),"data-testid":Y.helpSearch}),/* @__PURE__ */ _(`span`,{class:`${Cl}-home-search-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(fc,{})})]})}const El=N.cssPrefix;function Dl({title:e,subtitle:t,onClick:n,testid:r}){return/* @__PURE__ */ v(`button`,{type:`button`,class:`${El}-list-row`,onClick:n,"data-testid":r,children:[/* @__PURE__ */ v(`span`,{class:`${El}-list-row-body`,children:[/* @__PURE__ */ _(`span`,{class:`${El}-list-row-title`,children:e}),t?/* @__PURE__ */ _(`span`,{class:`${El}-list-row-sub`,children:t}):null]}),/* @__PURE__ */ _(`span`,{class:`${El}-list-row-chevron`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Is,{})})]})}const Ol=N.cssPrefix,kl=R.scope(`help`);function Al(e,t,n){let r=new Map(n.map(e=>[e.id,e.title]));return t.map(t=>({id:t,title:r.get(t),rows:e.filter(e=>e.contentCollectionId===t)})).filter(e=>e.rows.length>0)}function jl({transport:e,strings:t,bus:n},r,i){let[a,o]=h(),s=m(void 0),c=r?.join(`,`);function l(a){if(!r?.length)return;let c={};s.current=c,o(e=>({search:i,items:[],collections:[],...e,pagination:a>1?e?.pagination:void 0,loading:!0,error:void 0})),Promise.all([e.listContent({contentCollectionIds:r,sortBy:`order`,page:a,limit:20,search:i}),a>1?void 0:e.listContentCollections(r)]).then(([e,t])=>{s.current===c&&(o(n=>({search:i,items:[...a>1?n?.items??[]:[],...e.items],collections:t?.items??n?.collections??[],pagination:e.pagination,loading:!1})),a>1||(i?n.emit(`contentSearch`,{queryLength:i.length,hitCount:e.pagination.total}):n.emit(`contentView`,{section:`help`,count:e.items.length})))}).catch(e=>{s.current===c&&(kl.warn(`listContent (help) failed`,{err:e,page:a}),o(n=>n&&{...n,loading:!1,error:Sl(e,t)}))})}return u(()=>{if(!r?.length)o(void 0);else return l(1),()=>{s.current=void 0}},[e,c,i]),[a,()=>!a?.loading&&l((a?.pagination?.page??0)+1)]}function Ml(e){let{strings:t,config:n,nav:r,panelProps:i}=e,a=n.contentCollectionIds,[o,s]=h(``),[c,l]=h(``),d=jl(e,a),f=jl(e,c?a:void 0,c),[p,m]=o.trim()?f:d;u(()=>{let e=setTimeout(()=>l(o.trim()),300);return()=>clearTimeout(e)},[o]);function y(){if(!a?.length)return/* @__PURE__ */ _(cl,{message:t.helpEmpty,strings:t});let e=p?.error?/* @__PURE__ */ _(cl,{tone:`error`,message:p.error,onRetry:m,strings:t}):null;return e&&!p?.pagination?e:!p||!p.pagination&&!p.items.length?/* @__PURE__ */ _(cl,{message:t.helpLoading,strings:t}):p.items.length?/* @__PURE__ */ v(g,{children:[Al(p.items,a,p.collections).map(e=>/* @__PURE__ */ v(`section`,{class:`${Ol}-help-group`,children:[e.title?/* @__PURE__ */ _(`h2`,{class:`${Ol}-help-section-title`,children:e.title}):null,/* @__PURE__ */ _(`div`,{class:`${Ol}-help-card`,children:e.rows.map(e=>/* @__PURE__ */ _(Dl,{title:e.title,subtitle:e.description,onClick:()=>e.url?ws(e.url):r.push({kind:`content`,id:e.id,title:e.title}),testid:Pc(Y.helpArticle,e.id)},e.id))})]},e.id)),e,p.pagination?.hasNext&&!e?/* @__PURE__ */ _(`div`,{children:/* @__PURE__ */ _(`div`,{class:`${Ol}-help-card`,children:/* @__PURE__ */ v(`button`,{type:`button`,class:`${Ol}-list-row ${Ol}-help-more`,onClick:m,"aria-busy":p.loading,children:[p.loading?/* @__PURE__ */ _(`span`,{class:`${Ol}-loading-spinner`,"aria-hidden":`true`}):null,t.helpShowMore]})})}):null]}):/* @__PURE__ */ _(cl,{message:p.search?t.helpSearchEmpty.replace(`{query}`,p.search):t.helpEmpty,strings:t})}return/* @__PURE__ */ v(`div`,{class:`${Ol}-module`,children:[/* @__PURE__ */ _(Kc,{title:t.helpTitle,actions:/* @__PURE__ */ _(bl,{panelProps:i,variant:`plain`})}),/* @__PURE__ */ _(`div`,{class:`${Ol}-module-pad`,children:/* @__PURE__ */ _(Tl,{placeholder:t.helpSearchPlaceholder,value:o,onInput:s})}),/* @__PURE__ */ _(`div`,{class:`${Ol}-help-list`,children:y()})]})}const Nl={Icon:sc,Root:e=>/* @__PURE__ */ _(Ml,{...e})},Pl=R.scope(`attachments`);function Fl(e,t,n){let r=Bl(e),i=[],a=[],o=Gl(n.accept),s=t.reduce((e,t)=>e+t.size,0),c=t.length;for(let e of r){let t=zl(e,c,s,n,o);t?a.push({file:e,reason:t}):(i.push(Wl(e)),s+=e.size,c+=1)}return(i.length||a.length)&&Pl.debug(`ingest`,{accepted:i.length,rejected:a.map(e=>({name:e.file.name,reason:e.reason}))}),{accepted:i,rejected:a}}function Il(e){let t=Math.min(Math.floor(Math.log10(Math.max(e,1))/3),2);return new Intl.NumberFormat(void 0,{style:`unit`,unit:[`byte`,`kilobyte`,`megabyte`][t],unitDisplay:`narrow`,maximumFractionDigits:1}).format(e/1e3**t)}function Ll(e,t){let n=Gl(t);return!e||n.length===0||n.some(t=>t.kind===`ext`||Kl(new File([],``,{type:e}),[t]))}function Rl(e){try{URL.revokeObjectURL(e.previewUrl)}catch(e){Pl.debug(`revokeObjectURL failed`,{error:e})}}function zl(e,t,n,r,i){return t>=r.maxCount?`count`:n+e.size>r.maxBytes?`bytes`:Kl(e,i)?null:`mime`}function Bl(e){return e?Array.isArray(e)?e.filter(e=>e instanceof File):[...e].map(e=>e instanceof File?e:Vl(e)).filter(e=>e!==null):[]}function Vl(e){let t=Hl(e)?e:null;return!t?.getAsFile||t.kind!==`file`?null:t.getAsFile()}function Hl(e){return Ul(e)&&(e.getAsFile===void 0||typeof e.getAsFile==`function`)}function Ul(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wl(e){return{file:e,id:Ut(),mediaType:e.type||`application/octet-stream`,name:e.name||`pasted-file`,previewUrl:URL.createObjectURL(e),size:e.size}}function Gl(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 Kl(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===`image`&&e.subtype===`*`&&/\.(heic|heif|avif|bmp|tif|tiff)$/.test(i)?!0:(e.type===`*`||e.type===n)&&(e.subtype===`*`||e.subtype===r))}const ql=N.cssPrefix,Jl={error:Mc,done:Zs};function Yl({attachment:e,upload:t,strings:n,onRemove:r,disabled:i=!1}){let a=/^image\/(jpeg|png|gif|webp|avif|bmp|x-ms-bmp|svg\+xml)$/i.test(e.mediaType),o=Math.round((t?.fraction??0)*100),s=Il(e.size),c=t?.status===`error`||t?.status===`done`?Jl[t.status]:void 0;return/* @__PURE__ */ v(`span`,{class:`${ql}-attachment-chip`,"data-upload":t?.status,title:e.name,"data-testid":Pc(Y.attachmentChip,e.id),children:[a?/* @__PURE__ */ _(`img`,{class:`${ql}-attachment-thumb`,src:e.previewUrl,alt:``}):/* @__PURE__ */ _(`span`,{class:`${ql}-attachment-thumb`,"aria-hidden":`true`,children:/* @__PURE__ */ _(ic,{})}),/* @__PURE__ */ v(`span`,{class:`${ql}-attachment-text`,children:[/* @__PURE__ */ _(`span`,{class:`${ql}-attachment-name`,children:e.name}),/* @__PURE__ */ v(`span`,{class:`${ql}-attachment-meta`,children:[c?/* @__PURE__ */ _(c,{}):null,t?.status===`uploading`?`${o}% · ${s}`:s]})]}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${ql}-attachment-remove`,onClick:r,disabled:i,"aria-label":n.removeAttachment.replace(`{name}`,e.name),"data-testid":Pc(Y.attachmentRemove,e.id),children:/* @__PURE__ */ _(js,{})}),t?.status===`uploading`?/* @__PURE__ */ _(`span`,{class:`${ql}-attachment-progress`,role:`progressbar`,"aria-label":e.name,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":o,children:/* @__PURE__ */ _(`span`,{style:{width:`${o}%`}})}):null]})}const Xl=/* @__PURE__ */ new WeakMap;function Zl(e){e.currentTarget&&Xl.set(e.currentTarget,e.timeStamp)}function Ql(e){let t=e.currentTarget?Xl.get(e.currentTarget):void 0;return e.isComposing||t!==void 0&&e.timeStamp-t<100}const $l=N.cssPrefix;function eu({text:e,retryLabel:t,onRetry:n,retryTestId:r}){return/* @__PURE__ */ v(`div`,{class:`${$l}-error`,role:`alert`,children:[/* @__PURE__ */ _(`span`,{class:`${$l}-error-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Mc,{})}),/* @__PURE__ */ _(`span`,{class:`${$l}-error-text`,children:e}),n&&t?/* @__PURE__ */ _(`button`,{type:`button`,class:`${$l}-error-retry`,onClick:n,"data-testid":r,children:t}):null]})}const tu={isSupported:!1,start:()=>void 0,stop:()=>void 0,cancel:()=>void 0};function nu(e,t,n){return e===`disabled`?tu:e===`server`?ou(n):ru(t)}function ru(e){let t=iu();if(!t)return tu;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)});function u(e){l||r!==s||n!==c||(l=!0,n=null,a(e))}c.addEventListener(`end`,()=>u(!1)),c.addEventListener(`error`,e=>u(`error`in e&&(e.error===`not-allowed`||e.error===`service-not-allowed`)));try{c.start()}catch{u(!1)}},stop(){n?.stop()},cancel(){r++;let e=n;n=null,e?.abort()}}}function iu(){return window.SpeechRecognition??window.webkitSpeechRecognition}const au=[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/mp4`];function ou(e){if(typeof MediaRecorder>`u`||!navigator?.mediaDevices?.getUserMedia)return tu;let t=0,n=null;function r(e){for(let t of e.stream?.getTracks()??[])t.stop();e.stream=null}function i(){t++;let e=n;n=null,e&&(r(e),e.recorder?.state!==`inactive`&&e.recorder?.stop())}async function a(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(!1))}}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=su(),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(e){r(s),n===s&&t===s.generation&&(n=null,o(e instanceof DOMException&&e.name===`NotAllowedError`))}},stop(){let e=n;e&&(e.recorder?e.recorder.state!==`inactive`&&e.recorder.stop():i())},cancel(){i()}}}function su(){for(let e of au)if(MediaRecorder.isTypeSupported(e))return e}function cu(e,{file:t,reason:n},r){return n===`count`?e.attachmentTooMany.replace(`{count}`,String(r.maxCount)):n===`bytes`?e.attachmentTooLarge.replace(`{name}`,t.name).replace(`{max}`,Il(r.maxBytes)):e.attachmentMimeRejected.replace(`{name}`,t.name)}const lu=N.cssPrefix,uu=R.scope(`composer`);function du(e){return e.reduce((e,t)=>e+t.size,0)}const fu={arrowUp:Ps,paperPlane:Ns,send:Fs,chevron:Is};function pu(e){return`activeElement`in e}function mu(e){return`host`in e&&`activeElement`in e}function hu(e){return`clipboardData`in e}function gu({options:e,transport:t,feedback:n,bus:r,persistence:i,conversationId:a,maxMessageCharacters:o,isStreaming:s,pageToolRunning:c=!1,isMemoryCompacting:d=!1,canReleaseQueuedMessages:p=!0,queueManualMessages:g=!1,replyAwaitsCard:y=!1,active:b=!0,isPreparing:x=!1,attachmentUploadsSig:S,operatorRequestEnabled:C,canRequestOperator:w=!1,controlMode:T=`ai-agent`,onRequestOperator:E,onSend:D,onStop:O,apiRef:k}){let A=e.strings,[j,ee]=h(()=>i.loadDraft(a)),[M,te]=h([]),[N,ne]=h(),[re,ie]=h(()=>i.loadMessageQueue(a).map(e=>({id:e.id,text:e.text,attachments:[]}))),P=m(re),ae=m(!1),oe=m(void 0),[F,se]=h(!1),[ce,le]=h(!1),[ue,de]=h(!1),[I,fe]=h(!1),pe=m(!1),me=m(null),he=m(null),ge=m(null),_e=m(0),ve=m(a);ve.current=a;let L=m(b);L.current=b;let ye=m(x);ye.current=x;let be=I||x||!b,xe=s&&T===`ai-agent`,Se=xe||d&&T===`ai-agent`,Ce=T===`ai-agent`&&(Se||g||re.length>0),we=l(e=>{ie(t=>{let n=e(t);return i.saveMessageQueue(ve.current,n.filter(e=>e.attachments.length===0).map(({id:e,text:t})=>({id:e,text:t}))),P.current=n,n})},[i]),Te=l(e=>{we(t=>(t.find(t=>t.id===e)?.attachments.forEach(Rl),t.filter(t=>t.id!==e)))},[we]),Ee=l(e=>{ee(t=>{let n=(typeof e==`function`?e(t):e).slice(0,o);return n===t?t:(i.saveDraft(ve.current,n),n)})},[i,o]),De=e.features.fileUpload,Oe=e.features.voice,[ke,Ae]=h(()=>nu(Oe,e.locale,(e,n)=>t.transcribe(e,n))),je=m(ke);je.current=ke;let Me=m({mode:Oe,locale:e.locale,transport:t});u(()=>{let n=Me.current;(n.mode!==Oe||n.locale!==e.locale||n.transport!==t)&&(Me.current={mode:Oe,locale:e.locale,transport:t},_e.current++,je.current.cancel(),ge.current=null,le(!1),Ae(nu(Oe,e.locale,(e,n)=>t.transcribe(e,n))))},[e.locale,Oe,t]),f(()=>()=>{_e.current++,ke.cancel()},[ke]);let Ne=l(e=>{let t=ge.current;if(t===null)return!1;let n=Math.round(performance.now()-t);return uu[e](`voiceStop`,{durationMs:n}),r.emit(`voiceStop`,{durationMs:n}),ge.current=null,!0},[r]),Pe=l(()=>{ge.current!==null&&(ke.stop(),le(!1),Ne(`info`)&&n.play(`voiceStop`))},[Ne,n,ke]),Fe=l(()=>{_e.current++,ke.cancel(),le(!1),Ne(`info`)&&n.play(`voiceStop`)},[Ne,n,ke]);u(()=>{(x||!b)&&Fe()},[b,Fe,x]),u(()=>{let e=me.current;if(!e)return;let t=e.getRootNode(),n=pu(t)?t.activeElement:null;n&&e.closest(`.${lu}-panel`)?.contains(n)||e.focus({preventScroll:!0})},[]),u(()=>{let e=me.current;if(!e)return;if(j.length===0){e.style.height=``;return}e.style.height=`auto`;let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--${lu}-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`},[j]);let Ie=m(M);Ie.current=M,u(()=>()=>{Ie.current.forEach(Rl);for(let e of P.current)e.attachments.forEach(Rl)},[]),f(()=>{if(k)return k.current={attachFromDrop:t=>{if(!De||!L.current||pe.current||ye.current)return;let n=Fl(t,Ie.current,e.attachments);ne(n.rejected[0]),n.accepted.length!==0&&(uu.info(`attach (drop)`,{count:n.accepted.length,totalBytes:du(n.accepted)}),r.emit(`attach`,{count:n.accepted.length,totalBytes:du(n.accepted)}),te(e=>[...e,...n.accepted]))},fill:e=>{if(!L.current||pe.current||ye.current)return;Ee(e);let t=me.current;t&&(t.focus({preventScroll:!0}),requestAnimationFrame(()=>t.setSelectionRange(t.value.length,t.value.length)))},acceptQueuedMessage:Te},()=>{k.current&&(k.current=null)}},[k,De,x,e.attachments,Te,Ee]),u(()=>{let t=me.current;if(!t)return;let n=t.closest(`.${lu}-panel`);if(!n)return;let i=n=>{if(!L.current||pe.current||ye.current)return;let i=n.clipboardData;if(!i)return;let a=n.target instanceof HTMLElement?n.target.closest(`input, textarea, [contenteditable]:not([contenteditable='false'])`):null;if(a&&a!==t)return;if(De){let t=Fl(i.items,Ie.current,e.attachments);if(ne(t.rejected[0]),t.accepted.length>0){n.preventDefault(),uu.info(`attach (paste)`,{count:t.accepted.length,totalBytes:du(t.accepted)}),r.emit(`attach`,{count:t.accepted.length,totalBytes:du(t.accepted)}),te(e=>[...e,...t.accepted]);return}}if(a===t)return;let o=i.getData(`text/plain`);o&&(n.preventDefault(),Ee(e=>e+o),t.focus())};function a(e){hu(e)&&i(e)}return n.addEventListener(`paste`,a),()=>n.removeEventListener(`paste`,a)},[De,e.attachments,Ee]);async function Le(){let e=j.trim();if(!e&&M.length===0||!b||xe||pe.current||x)return;Fe(),pe.current=!0,fe(!0);let t=j,n=M;try{await D(e,n)&&(ne(void 0),Ee(e=>e===t?``:e),te(e=>e===n?(n.forEach(Rl),Ie.current=[],[]):e))}finally{pe.current=!1,fe(!1),requestAnimationFrame(()=>{let e=me.current;if(!e||e.disabled||!L.current)return;let t=e.getRootNode(),n=pu(t)?t.activeElement:null,r=n?.getAttribute(`data-testid`);if(!(n&&n!==e&&r!==Y.composerSend&&r!==Y.composerStop)){if(mu(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})}})}}function Re(){let e=j.trim();if(!e&&M.length===0||!b||!Ce||pe.current||x)return;Fe();let t=M;we(n=>[...n,{id:Ut(),text:e,attachments:t}]),Se||se(!0),Ee(``),te(e=>e===t?(Ie.current=[],[]):e),me.current?.focus({preventScroll:!0})}u(()=>{Se&&(ae.current=!1,oe.current=void 0,se(!1))},[Se]),u(()=>{let t=re[0];if(!t||!p||Se||ae.current||I||x||!b)return;let n=y&&!F?(oe.current??(oe.current=performance.now()+e.cardAnswerWaitSeconds*1e3))-performance.now():0,r=setTimeout(()=>{ae.current=!0,D(t.text,t.attachments,t.id).then(e=>{e?Te(t.id):ae.current=!1})},Math.max(n,300));return()=>clearTimeout(r)},[b,p,F,x,D,e.cardAnswerWaitSeconds,Se,re,Te,y,I]);function ze(e){e.key!==`Enter`||e.shiftKey||Ql(e)||(e.preventDefault(),Ce&&(j.trim()||M.length>0)?Re():xe?O():Le())}function Be(t){if(!(t.target instanceof HTMLInputElement))return;let n=t.target;if(!b||pe.current||x){n.value=``;return}let i=Fl(n.files,M,e.attachments);ne(i.rejected[0]),i.accepted.length>0&&(uu.info(`attach (file picker)`,{count:i.accepted.length,totalBytes:du(i.accepted)}),r.emit(`attach`,{count:i.accepted.length,totalBytes:du(i.accepted)}),te(e=>[...e,...i.accepted])),n.value=``}function Ve(e){!b||pe.current||x||(uu.info(`removeAttachment`,{id:e}),r.emit(`removeAttachment`,{id:e}),ne(void 0),te(t=>{let n=t.find(t=>t.id===e);return n&&Rl(n),t.filter(t=>t.id!==e)}))}function He(){if(ce){Pe();return}if(!b||!ke.isSupported||pe.current||x)return;let e=++_e.current;ge.current=performance.now(),uu.info(`voiceStart`),r.emit(`voiceStart`,void 0),de(!1),le(!0),n.play(`voiceStart`),ke.start((t,n)=>{_e.current===e&&L.current&&!ye.current&&!pe.current&&n&&Ee(e=>`${e}${t} `)},t=>{_e.current===e&&L.current&&(le(!1),de(t),Ne(`debug`))})}let Ue=fu[e.composer.sendButton.icon],We=!!(j.trim()||M.length>0),Ge=S?.value,Ke=M.some(e=>Ge?.get(e.id)?.status===`uploading`),qe=M.filter(e=>Ge?.get(e.id)?.status===`error`),Je=qe.find(e=>Ge?.get(e.id)?.refusal),R=Je&&(Ge?.get(Je.id)?.refusal===`INVALID_FILE_TYPE`?A.attachmentMimeRejected:A.attachmentUploadFailed).replace(`{name}`,Je.name),Ye=xe||Ke||c&&!We;return/* @__PURE__ */ v(`div`,{class:`${lu}-composer`,part:`composer`,"data-testid":Y.composer,children:[re.length>0?/* @__PURE__ */ _(`div`,{class:`${lu}-message-queue`,"aria-label":A.queueMessage,"data-testid":Y.messageQueue,children:re.map(e=>/* @__PURE__ */ v(`div`,{class:`${lu}-attachment-chip ${lu}-queued-message`,"data-testid":`${Y.queuedMessage}-${e.id}`,children:[/* @__PURE__ */ _(`span`,{class:`${lu}-attachment-name ${lu}-queued-text`,children:e.text||e.attachments.map(e=>e.name).join(`, `)}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-attachment-remove`,onClick:()=>Te(e.id),"aria-label":A.removeQueuedMessage,title:A.removeQueuedMessage,"data-testid":`${Y.queuedMessageRemove}-${e.id}`,children:/* @__PURE__ */ _(js,{})})]},e.id))}):null,M.length>0?/* @__PURE__ */ _(`div`,{class:`${lu}-attachments`,children:M.map(e=>/* @__PURE__ */ _(Yl,{attachment:e,upload:Ge?.get(e.id),strings:A,onRemove:()=>Ve(e.id),disabled:be},e.id))}):null,qe.length>0&&!be?/* @__PURE__ */ _(eu,{text:R??A.attachmentUploadFailed.replace(`{name}`,qe.map(e=>e.name).join(`, `)),retryLabel:A.errorRetry,onRetry:Je?void 0:()=>void Le(),retryTestId:Y.attachmentRetry}):null,N?/* @__PURE__ */ _(`p`,{class:`${lu}-field-error`,role:`alert`,children:cu(A,N,e.attachments)}):null,ue?/* @__PURE__ */ _(`p`,{class:`${lu}-field-error`,role:`alert`,children:A.micBlocked}):null,o!==void 0&&j.length>=o*.9?/* @__PURE__ */ _(`p`,{class:`${lu}-field-${j.length<o?`hint`:`error`}`,"data-testid":Y.composerCount,children:`${j.length} / ${o}`}):null,/* @__PURE__ */ v(`div`,{class:`${lu}-composer-row`,children:[/* @__PURE__ */ v(`div`,{class:`${lu}-composer-actions`,children:[De?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-icon-btn`,onClick:()=>he.current?.click(),disabled:be,"aria-label":A.attach,title:A.attach,"data-testid":Y.composerAttach,children:/* @__PURE__ */ _(Rs,{})}):null,ke.isSupported?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-icon-btn`,onClick:He,disabled:be,"aria-label":ce?A.micStop:A.micStart,title:ce?A.micStop:A.micStart,"aria-pressed":ce,"data-recording":ce?`true`:void 0,"data-testid":Y.composerVoice,children:/* @__PURE__ */ _(zs,{})}):null,C&&T===`ai-agent`&&E?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-icon-btn`,onClick:E,disabled:be||!w,"aria-label":A.talkToOperator,title:A.talkToOperator,"data-testid":Y.operatorRequest,children:/* @__PURE__ */ _(Bs,{})}):null]}),/* @__PURE__ */ _(`textarea`,{ref:me,name:`message`,class:`${lu}-textarea`,rows:1,value:j,maxLength:o,placeholder:A.composerPlaceholder,onInput:e=>Ee(e.currentTarget.value),onKeyDown:ze,onCompositionEnd:Zl,disabled:be,"aria-label":A.composerPlaceholder,"data-testid":Y.composerInput}),Ce&&We?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:Re,disabled:be,"aria-label":A.queueMessage,title:A.queueMessage,"data-testid":Y.composerSend,children:/* @__PURE__ */ _(Ue,{})}):null,Ye?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-send`,onClick:O,disabled:be&&!Ke,"aria-label":A.stop,"data-testid":Y.composerStop,children:/* @__PURE__ */ _(Ls,{})}):null,!Ye&&(!Ce||!We)?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:()=>void Le(),disabled:be||!j.trim()&&M.length===0,"aria-label":A.send,"data-testid":Y.composerSend,children:/* @__PURE__ */ _(Ue,{})}):null]}),/* @__PURE__ */ _(`input`,{ref:he,name:`attachments`,type:`file`,multiple:!0,accept:e.attachments.accept,onChange:Be,disabled:be,class:`${lu}-sr-only`,"data-testid":Y.composerFileInput})]})}const _u=N.cssPrefix;function vu({onClick:e,children:t,testid:n}){return e?/* @__PURE__ */ _(`button`,{type:`button`,class:`${_u}-home-card`,"data-interactive":`true`,onClick:e,"data-testid":n,children:t}):/* @__PURE__ */ _(`div`,{class:`${_u}-home-card`,"data-testid":n,children:t})}function yu(e){return e.trim().split(/\s+/).slice(0,2).map(e=>e.charAt(0).toUpperCase()).join(``)}const bu=N.cssPrefix,xu=R.scope(`news`);function Su(e,t){let n=e?new Date(e):void 0;if(n&&!Number.isNaN(n.getTime()))return new Intl.DateTimeFormat(t,{dateStyle:`medium`}).format(n)}function Cu({options:e,transport:t,strings:n,config:r,nav:i,bus:a,panelProps:o,latestNews:s}){let c=r.contentCollectionIds,l=c?.join(`,`),[d,f]=h({items:[],loading:!0}),p=m(void 0);function g(e){if(!c?.length)return;let r={};p.current=r,f(e=>({...e,loading:!0,error:void 0})),t.listContent({contentCollectionIds:c,sortBy:`publishedAt`,sortOrder:`desc`,page:e,limit:10}).then(t=>{if(p.current!==r||(f(n=>({items:e>1?[...n.items,...t.items]:t.items,pagination:t.pagination,loading:!1})),e>1))return;a.emit(`contentView`,{section:`news`,count:t.items.length});let n=t.items[0];n&&s.markSeen(n.id)}).catch(t=>{p.current===r&&(xu.warn(`listContent (news) failed`,{err:t,page:e}),f(e=>({...e,loading:!1,error:Sl(t,n)})))})}function y(){d.loading||g((d.pagination?.page??0)+1)}u(()=>(f({items:[],loading:!0}),g(1),()=>{p.current=void 0}),[t,l]);function b(t){let n=Su(t.publishedAt,e.locale);return/* @__PURE__ */ v(`button`,{type:`button`,class:`${bu}-news-card`,onClick:()=>i.push({kind:`content`,id:t.id,title:t.title}),"data-testid":Pc(Y.newsItem,t.id),children:[t.image?/* @__PURE__ */ _(`img`,{class:`${bu}-news-hero`,src:t.image,alt:``,loading:`lazy`}):null,/* @__PURE__ */ v(`span`,{class:`${bu}-news-body`,children:[/* @__PURE__ */ _(`span`,{class:`${bu}-news-title`,children:t.title}),n||t.tags?.length?/* @__PURE__ */ v(`span`,{class:`${bu}-news-meta`,children:[n?/* @__PURE__ */ _(`time`,{dateTime:t.publishedAt,children:n}):null,t.tags?.map(e=>/* @__PURE__ */ _(`span`,{class:`${bu}-news-tag`,children:e},e))]}):null,t.description?/* @__PURE__ */ _(`span`,{class:`${bu}-news-summary`,children:t.description}):null]})]},t.id)}function x(){if(!c?.length)return/* @__PURE__ */ _(cl,{message:n.newsEmpty,strings:n});let e=d.error?/* @__PURE__ */ _(cl,{tone:`error`,message:d.error,onRetry:y,strings:n}):null;return e&&!d.pagination?e:d.pagination?d.items.length?/* @__PURE__ */ v(`div`,{class:`${bu}-news-list`,children:[d.items.map(b),e,d.pagination.hasNext&&!e?/* @__PURE__ */ v(`button`,{type:`button`,class:`${bu}-news-more`,onClick:y,"aria-busy":d.loading,"data-testid":Y.newsMore,children:[d.loading?/* @__PURE__ */ _(`span`,{class:`${bu}-loading-spinner`,"aria-hidden":`true`}):null,n.newsShowMore]}):null]}):/* @__PURE__ */ _(cl,{message:n.newsEmpty,strings:n}):/* @__PURE__ */ _(cl,{message:n.newsLoading,strings:n})}return/* @__PURE__ */ v(`div`,{class:`${bu}-module`,children:[/* @__PURE__ */ _(Kc,{title:n.newsTitle,actions:/* @__PURE__ */ _(bl,{panelProps:o,variant:`plain`})}),/* @__PURE__ */ _(`div`,{class:`${bu}-module-scroll`,children:x()})]})}const wu={Icon:hc,Root:e=>/* @__PURE__ */ _(Cu,{...e})},X=N.cssPrefix,Tu=R.scope(`home`);function Eu(e){let t=e.options.userContext?.name,n=e.config.greetingText?M(e.strings,e.config.greetingText):void 0;if(n){let r=t?n.replace(`{name}`,t):n.replace(/\s*\{name\}\s*/,` `).trim(),i=e.strings.homeGreetingLead;return{title:r,subtitle:r.toLowerCase()===i.toLowerCase()?void 0:i}}return t?{title:e.strings.homeGreetingNamed.replace(`{name}`,t),subtitle:e.strings.homeGreetingLead}:{title:e.strings.homeGreeting}}function Du(e,t){return t.url?ws(t.url):e.push({kind:`content`,id:t.id,title:t.title})}function Ou({options:e,onAsk:t}){let[n,r]=h(``),{sendButton:i}=e.composer,a=fu[i.icon];function o(e){e.preventDefault();let i=n.trim();i&&(r(``),t(i))}return/* @__PURE__ */ v(`form`,{class:`${X}-home-search ${X}-home-ask`,"data-input":`true`,onSubmit:o,"data-testid":Y.homeAsk,children:[/* @__PURE__ */ _(`input`,{type:`text`,class:`${X}-home-search-input`,placeholder:e.strings.homeAskPlaceholder,"aria-label":e.strings.homeAskPlaceholder,value:n,enterKeyHint:`send`,onInput:e=>r(e.currentTarget.value)}),/* @__PURE__ */ _(`button`,{type:`submit`,class:`${X}-send`,"data-shape":i.shape,"data-variant":i.variant,disabled:!n.trim(),"aria-label":e.strings.send,children:/* @__PURE__ */ _(a,{})})]})}function ku(e,t){return Go(e,t,t.type!==`upsert`||t.activity===!0)}function Au(e){let{transport:t,strings:n,config:r,nav:i,bus:a,panelProps:o,latestNews:s}=e,[c,l]=h(null),[d,f]=h([]),p=r.contentCollectionIds?.join(`,`),m=e.options.modules.list.some(e=>e.layout===`chat`);u(()=>{if(r.showRecentConversations===!1)return;let e=!1,n=!0,i=[],a=t.subscribeConversationChanges(e=>{n&&i.push(e),l(t=>ku(t?[t]:[],e)[0]??null)});return t.listConversations({limit:m?50:1}).then(t=>{if(e)return;let r=i.reduce(ku,t.conversations);i=[],n=!1,l(r[0]??null)}).catch(t=>{e||(i=[],n=!1,Tu.warn(`listConversations (home) failed`,{err:t}))}),()=>{e=!0,a()}},[t,r.showRecentConversations,m]),u(()=>{if(!r.contentCollectionIds?.length)return;let e=!1;return t.listContent({contentCollectionIds:r.contentCollectionIds,pinned:!0,limit:6}).then(t=>{e||(f(t.items),a.emit(`contentView`,{section:`home`,count:t.items.length}))}).catch(t=>!e&&Tu.warn(`listContent (home) failed`,{err:t})),()=>{e=!0}},[t,p,a]);let y=Eu(e),b=r.userAvatars??[],x=r.status,S=x?.text?M(n,x.text):n.homeStatus,C=x?.url,w=r.contentBlockTitle?M(n,r.contentBlockTitle):n.homeContentTitle,T=s.item,E=Su(T?.publishedAt,e.options.locale);return/* @__PURE__ */ _(`div`,{class:`${X}-module ${X}-home`,"data-testid":Y.homeView,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-scroll`,children:[/* @__PURE__ */ v(`div`,{class:`${X}-home-hero`,children:[/* @__PURE__ */ v(`div`,{class:`${X}-home-hero-top`,children:[r.brandName?/* @__PURE__ */ _(`span`,{class:`${X}-home-brand`,"data-testid":Y.homeBrand,children:r.brandName}):/* @__PURE__ */ _(`span`,{class:`${X}-home-brand-spacer`,"aria-hidden":`true`}),/* @__PURE__ */ v(`div`,{class:`${X}-home-hero-actions`,children:[b.length>0?/* @__PURE__ */ _(`div`,{class:`${X}-home-avatars`,children:b.map(e=>/* @__PURE__ */ _(`span`,{class:`${X}-home-avatar`,title:e.role?`${e.name} · ${e.role}`:e.name,children:e.avatar?/* @__PURE__ */ _(`img`,{src:e.avatar,alt:``,loading:`lazy`}):/* @__PURE__ */ _(`span`,{children:yu(e.name)})},e.name))}):null,/* @__PURE__ */ _(bl,{panelProps:o,variant:`plain`})]})]}),r.showGreeting===!1?null:/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`h1`,{class:`${X}-home-greeting`,"data-testid":Y.homeGreeting,children:y.title}),y.subtitle?/* @__PURE__ */ _(`p`,{class:`${X}-home-lead`,children:y.subtitle}):null]})]}),/* @__PURE__ */ v(`div`,{class:`${X}-home-cards`,children:[m?/* @__PURE__ */ _(Ou,{options:e.options,onAsk:e=>i.startNewConversation(e)}):null,r.showSearchBar===!1?null:/* @__PURE__ */ _(wl,{placeholder:n.homeSearchPlaceholder,onActivate:()=>i.switchToLayout(`help`)}),T?/* @__PURE__ */ _(vu,{onClick:()=>{s.markSeen(T.id),i.push({kind:`content`,id:T.id,title:T.title})},testid:Y.homeWhatsNew,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-recent-row`,"data-unread":s.unseen?`true`:void 0,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-avatar`,"aria-hidden":`true`,children:/* @__PURE__ */ _(hc,{})}),/* @__PURE__ */ v(`span`,{class:`${X}-home-recent-body`,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-title`,children:n.homeWhatsNew}),/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-preview`,children:E?`${T.title} · ${E}`:T.title})]}),s.unseen?/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-dot`,role:`img`,"aria-label":n.newsUnseen}):null]})}):null,c?/* @__PURE__ */ _(vu,{onClick:()=>i.selectConversation(c),testid:Y.homeRecent,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-recent-row`,"data-unread":c.hasUnread?`true`:void 0,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-avatar`,"aria-hidden":`true`,children:/* @__PURE__ */ _(gc,{})}),/* @__PURE__ */ v(`span`,{class:`${X}-home-recent-body`,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-title`,children:c.title}),c.preview?/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-preview`,children:ol(c.preview)}):null]}),c.hasUnread?/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-dot`,role:`img`,"aria-label":n.unread}):null]})}):null,x?/* @__PURE__ */ _(vu,{onClick:C?()=>ws(C):void 0,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-status`,"data-level":x.level??`operational`,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-status-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(pc,{})}),/* @__PURE__ */ _(`span`,{class:`${X}-home-status-text`,children:S})]})}):null,d.length>0?/* @__PURE__ */ v(`section`,{class:`${X}-home-content`,children:[/* @__PURE__ */ _(`div`,{class:`${X}-home-content-title`,children:w}),/* @__PURE__ */ _(`div`,{class:`${X}-home-content-list`,children:d.map(e=>/* @__PURE__ */ _(Dl,{title:e.title,subtitle:e.description,onClick:()=>Du(i,e),testid:Pc(Y.homeContentRow,e.id)},e.id))})]}):null]})]})})}const ju={chat:xl,home:{Icon:mc,Root:e=>/* @__PURE__ */ _(Au,{...e})},help:Nl,news:wu},Mu=N.cssPrefix;function Nu({modules:e,activeTab:t,strings:n,hasUnread:r,onSelect:i}){return/* @__PURE__ */ _(`nav`,{class:`${Mu}-tabbar`,role:`tablist`,"aria-label":n.panelTitle,children:e.map(e=>{let a=ju[e.layout].Icon,o=e.id===t,s=e.layout===`chat`&&r;return/* @__PURE__ */ v(`button`,{type:`button`,role:`tab`,"aria-selected":o,class:`${Mu}-tab`,onClick:()=>i(e.id),"data-testid":Pc(Y.tab,e.id),children:[/* @__PURE__ */ v(`span`,{class:`${Mu}-tab-icon`,children:[/* @__PURE__ */ _(a,{}),s?/* @__PURE__ */ _(`span`,{class:`${Mu}-tab-badge`,"data-testid":Y.tabBadge,role:`img`,"aria-label":n.unread}):null]}),/* @__PURE__ */ _(`span`,{class:`${Mu}-tab-label`,children:M(n,e.label)})]},e.id)})})}const Pu=N.cssPrefix;function Fu({agent:e,strings:t,ticketReference:n,person:r=!1}){let i=e.status??`online`,a=M(t,e.name),o=e.title?M(t,e.title):null,s=r?/* @__PURE__ */ _(Bs,{}):/* @__PURE__ */ _(`span`,{children:yu(a)});return/* @__PURE__ */ v(`div`,{class:`${Pu}-agent`,children:[/* @__PURE__ */ _(`div`,{class:`${Pu}-agent-avatar`,"data-status":i,children:e.avatar?/* @__PURE__ */ _(`img`,{src:e.avatar,alt:``}):s}),/* @__PURE__ */ v(`div`,{class:`${Pu}-agent-meta`,children:[/* @__PURE__ */ _(`strong`,{children:a}),o||n?/* @__PURE__ */ v(`div`,{class:`${Pu}-agent-sub`,children:[n?/* @__PURE__ */ _(Iu,{reference:n,strings:t}):null,o?/* @__PURE__ */ _(`span`,{children:o}):null]}):null]})]})}function Iu({reference:e,strings:t}){let[n,r]=h(!1);function i(){navigator.clipboard?.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})}return/* @__PURE__ */ _(`button`,{type:`button`,class:`${Pu}-agent-ticket`,onClick:i,title:t.copy,"aria-label":n?t.copied:t.copyTicketReference.replace(`{reference}`,e),children:n?t.copied:e})}const Lu=[`today`,`yesterday`,`lastWeek`,`older`];function Ru(e,t){let n=Date.parse(t);if(!Number.isFinite(n))return`older`;let r=Math.round((Bu(e)-Bu(n))/864e5);return r<=0?`today`:r===1?`yesterday`:r<7?`lastWeek`:`older`}function zu(e,t){let n=/* @__PURE__ */ new Map;for(let r of t){let t=Ru(e,r.lastMessageAt),i=n.get(t);i?i.push(r):n.set(t,[r])}return Lu.flatMap(e=>{let t=n.get(e);return t?[{bucket:e,conversations:t}]:[]})}function Bu(e){return new Date(e).setHours(0,0,0,0)}const Vu=R.scope(`history`),Hu={today:`dateToday`,yesterday:`dateYesterday`,lastWeek:`dateLastWeek`,older:`dateOlder`};function Uu(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=Go(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=Go(e.conversations,t,n);return r===e.conversations?e:{...t.type===`snapshot`?t.result:e,conversations:r}}function Wu(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<6048e5?new Intl.DateTimeFormat(n,{weekday:`short`}).format(r):new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`}).format(r):``}function Gu({transport:e,strings:t,locale:n,persistence:r,onSelect:i,onNewConversation:a}){let o=N.cssPrefix,s=e.peekConversations({limit:50}),[c,l]=h(s?`loaded`:`loading`),[d,f]=h(0),[p,y]=h(s),[b,x]=h(!1),S=m(void 0),C=p?.conversations??[],w=p?.pagination;u(()=>{let n=!1,i=!0,a=[],o=e.subscribeConversationChanges(e=>{i&&a.push(e),y(t=>t&&Uu(t,e))});S.current=void 0,x(!1);let s=e.peekConversations({limit:50});return y(s),l(s?`loaded`:`loading`),e.listConversations({limit:50}).then(e=>{if(n)return;let t=e;for(let e of a)t=Uu(t,e);a=[],i=!1,y(t),l(`loaded`),r.saveHistoryCount(t.conversations.length)}).catch(e=>{n||(a=[],i=!1,Vu.warn(`listConversations failed`,{err:e}),l({failure:Sl(e,t)}))}),()=>{n=!0,o(),S.current=void 0}},[e,r,n,d]);async function T(){if(S.current||!w?.hasNext)return;let t={};S.current=t,x(!0);try{let n=await e.listConversations({page:w.page+1,limit:w.limit});if(S.current!==t)return;y(e=>{if(!e)return e;let t=new Set(e.conversations.map(e=>e.conversationId)),i=n.conversations.filter(e=>!t.has(e.conversationId)&&(t.add(e.conversationId),!0)),a={conversations:[...e.conversations,...i],pagination:n.pagination};return r.saveHistoryCount(a.conversations.length),a})}catch(e){if(S.current!==t)return;Vu.warn(`listConversations page failed`,{err:e,page:w.page+1})}finally{S.current===t&&(S.current=void 0,x(!1))}}let E=a?/* @__PURE__ */ _(`div`,{class:`${o}-history-footer`,children:/* @__PURE__ */ v(`button`,{type:`button`,class:`${o}-history-new`,onClick:a,"data-testid":Y.sidebarNewConversation,children:[/* @__PURE__ */ _(Ms,{}),t.newConversation]})}):null;if(c===`loading`){let e=Math.min(r.loadHistoryCount()??3,6);return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`div`,{class:`${o}-history`,"aria-busy":`true`,"aria-label":t.historyLoading,children:/* @__PURE__ */ v(`div`,{class:`${o}-history-group`,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`div`,{class:`${o}-history-heading`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-heading`})}),/* @__PURE__ */ _(`div`,{class:`${o}-history-card`,children:Array.from({length:Math.max(1,e)},(e,t)=>/* @__PURE__ */ v(`div`,{class:`${o}-history-item ${o}-history-item-skeleton`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-avatar ${o}-skeleton`}),/* @__PURE__ */ v(`span`,{class:`${o}-history-body`,children:[/* @__PURE__ */ v(`span`,{class:`${o}-history-row`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-title`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-title`})}),/* @__PURE__ */ _(`span`,{class:`${o}-history-time`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-time`})})]}),/* @__PURE__ */ _(`span`,{class:`${o}-history-row`,children:/* @__PURE__ */ _(`span`,{class:`${o}-history-preview`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-preview`})})})]})]},t))})]})}),E]})}if(typeof c==`object`)return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(cl,{tone:`error`,message:c.failure,onRetry:()=>f(e=>e+1),strings:t}),E]});if(C.length===0)return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`div`,{class:`${o}-history-empty`,children:t.historyEmpty}),E]});let D=Date.now(),O=zu(D,C);return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ v(`div`,{class:`${o}-history`,role:`list`,children:[O.map(e=>/* @__PURE__ */ v(`div`,{class:`${o}-history-group`,children:[/* @__PURE__ */ _(`div`,{class:`${o}-history-heading`,children:t[Hu[e.bucket]]}),/* @__PURE__ */ _(`div`,{class:`${o}-history-card`,children:e.conversations.map(e=>/* @__PURE__ */ _(`div`,{role:`listitem`,children:/* @__PURE__ */ v(`button`,{type:`button`,class:`${o}-history-item`,onClick:()=>i(e),"data-unread":e.hasUnread?`true`:void 0,"data-testid":Pc(Y.historyItem,e.conversationId),children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-avatar`,"aria-hidden":`true`,children:/* @__PURE__ */ _(oc,{})}),/* @__PURE__ */ v(`span`,{class:`${o}-history-body`,children:[/* @__PURE__ */ v(`span`,{class:`${o}-history-row`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-title`,children:e.title}),/* @__PURE__ */ v(`span`,{class:`${o}-history-time`,children:[e.ticketReference&&`${e.ticketReference} · `,Wu(e.lastMessageAt,D,n)]})]}),/* @__PURE__ */ v(`span`,{class:`${o}-history-row`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-preview`,children:e.preview&&ol(e.preview)||t.historyContinue}),e.hasUnread?/* @__PURE__ */ _(`span`,{class:`${o}-history-dot`,role:`img`,"aria-label":t.unread}):null]})]})]})},e.conversationId))})]},e.bucket)),w?.hasNext?/* @__PURE__ */ _(`div`,{class:`${o}-history-more`,children:/* @__PURE__ */ _(`button`,{type:`button`,onClick:T,disabled:b,"aria-busy":b,"data-testid":Y.historyLoadMore,children:t.loadMoreConversations})}):null]}),E]})}const Ku=N.cssPrefix;function qu({state:e,strings:t}){return e?/* @__PURE__ */ v(`div`,{class:`${Ku}-dropzone`,"data-state":e,role:`status`,"aria-live":`polite`,children:[/* @__PURE__ */ _(`span`,{class:`${Ku}-dropzone-icon`,"aria-hidden":`true`,children:_(e===`reject`?Mc:Rs,{})}),e===`reject`?t.dropZoneRejected:t.dropZone]}):null}const Ju=new RegExp(String.raw`^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$`),Yu=/^[+]?[\d\s().-]{6,}$/;function Xu(e,t,n){let r=Array.isArray(t)?t.join(``):t?.trim()??``;if(!r)return e.required?n.formRequired:void 0;if(e.type===`email`&&!Ju.test(r))return n.formInvalidEmail;if(e.type===`tel`&&!Yu.test(r))return n.formInvalidTel;if(e.type===`number`&&!Number.isFinite(Number(r)))return n.formInvalidNumber}function Zu(e,t,n){return Object.fromEntries(e.flatMap(e=>{let r=Xu(e,t[e.name],n);return r?[[e.name,r]]:[]}))}const Qu=N.cssPrefix;function $u(e){return e.tokenEmail||e.userContext?.email?.trim()}function ed(e,t){let n=e instanceof Oo?e.status:void 0;return n===400?t.formInvalidEmail:n===409?t.emailTranscriptAlreadySent:n===422?t.emailTranscriptNotDelivered:n===429?t.emailTranscriptLimited:t.emailTranscriptFailed}function td(e){return`host`in e&&`activeElement`in e}function nd({transport:e,strings:t,knownEmail:n,onClose:r}){let[i,a]=h(n??``),[o,s]=h(!1),[c,l]=h({status:`idle`}),u=m(null),p=d(),y=`${p}-title`,b=`${p}-error`,x=c.status===`sending`,S=c.status===`sent`;f(()=>{let e=u.current;if(!e)return;let t=e.getRootNode(),n=td(t)?t.activeElement:null,r=Wc(e);return()=>{r(),n instanceof HTMLElement&&n.isConnected&&n.focus({preventScroll:!0})}},[]),f(()=>{u.current?.querySelector(`[data-autofocus]`)?.focus({preventScroll:!0})},[S]);async function C(n){if(n.preventDefault(),x)return;let r=i.trim();if(!Ju.test(r)){s(!0),u.current?.querySelector(`input`)?.focus();return}s(!1),l({status:`sending`});let a=await e.emailTranscript(r).then(e=>({status:`sent`,to:e.to}),e=>({status:`failed`,message:ed(e,t)}));l(a)}function w(e){e.key===`Tab`&&e.stopPropagation(),e.key===`Escape`&&(e.stopPropagation(),r())}return/* @__PURE__ */ v(`div`,{class:`${Qu}-transcript-layer`,children:[/* @__PURE__ */ _(`div`,{class:`${Qu}-transcript-backdrop`,"aria-hidden":`true`,onClick:r}),/* @__PURE__ */ v(`section`,{ref:u,class:`${Qu}-transcript-sheet`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":y,onKeyDown:w,"data-testid":Y.emailTranscriptSheet,children:[/* @__PURE__ */ v(`header`,{class:`${Qu}-transcript-sheet-head`,children:[/* @__PURE__ */ _(`span`,{class:`${Qu}-transcript-sheet-icon`,children:/* @__PURE__ */ _(nc,{})}),/* @__PURE__ */ _(`h2`,{id:y,class:`${Qu}-transcript-sheet-title`,children:t.emailTranscript}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Qu}-icon-btn`,onClick:r,"aria-label":t.emailTranscriptCancel,title:t.emailTranscriptCancel,children:/* @__PURE__ */ _(js,{})})]}),c.status===`sent`?/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ v(`p`,{class:`${Qu}-transcript-sheet-text ${Qu}-transcript-sheet-sent`,role:`status`,children:[/* @__PURE__ */ _(kc,{}),/* @__PURE__ */ _(`span`,{children:t.emailTranscriptSent.replace(`{email}`,c.to)})]}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Qu}-form-submit ${Qu}-transcript-sheet-action`,onClick:r,"data-autofocus":!0,children:t.emailTranscriptDone})]}):/* @__PURE__ */ v(`form`,{class:`${Qu}-transcript-sheet-form`,onSubmit:e=>void C(e),noValidate:!0,children:[/* @__PURE__ */ _(`p`,{class:`${Qu}-transcript-sheet-text`,children:t.emailTranscriptPrompt}),/* @__PURE__ */ v(`label`,{class:`${Qu}-field`,"data-invalid":o?`true`:void 0,children:[/* @__PURE__ */ _(`span`,{class:`${Qu}-field-label`,children:t.emailTranscriptEmailLabel}),/* @__PURE__ */ _(`input`,{class:`${Qu}-field-input`,type:`email`,name:`email`,autocomplete:`email`,inputMode:`email`,autocapitalize:`off`,spellcheck:!1,value:i,readOnly:x,"aria-invalid":o,"aria-describedby":o?b:void 0,onInput:e=>{a(e.currentTarget.value),s(!1)},"data-autofocus":!0,"data-testid":Y.emailTranscriptEmail}),o?/* @__PURE__ */ _(`span`,{id:b,class:`${Qu}-field-error`,role:`alert`,children:t.formInvalidEmail}):null]}),/* @__PURE__ */ _(`button`,{type:`submit`,class:`${Qu}-form-submit ${Qu}-transcript-sheet-action`,disabled:x,"aria-busy":x,"data-testid":Y.emailTranscriptSend,children:x?t.emailTranscriptSending:t.emailTranscriptSend}),c.status===`failed`?/* @__PURE__ */ _(`p`,{class:`${Qu}-field-error`,role:`alert`,children:c.message}):null]})]})]})}const rd=/* @__PURE__ */ new Set([`hidden`,`submit`,`button`,`reset`,`image`,`file`,`password`]);function id(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function ad(e){return!id(e)||e.name===``||e.disabled?!1:!(e instanceof HTMLInputElement&&rd.has(e.type))}function od(e){let t=e.labels?.[0]?.textContent?.trim();return e.getAttribute(`toolparamdescription`)??(t||e.getAttribute(`aria-description`))??void 0}function sd(e,t){let n=od(e),r=n?{description:n}:{};return e instanceof HTMLSelectElement?{...r,type:`string`,enum:[...e.options].map(e=>e.value)}:e instanceof HTMLTextAreaElement?{...r,type:`string`}:e.type===`checkbox`?{...r,type:`boolean`}:e.type===`radio`?{...r,type:`string`,enum:t}:e.type===`number`||e.type===`range`?{...r,type:`number`}:{...r,type:`string`}}function cd(e,t){Object.getOwnPropertyDescriptor(Reflect.getPrototypeOf(e)??e,`value`)?.set?.call(e,t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function ld(e){return e==null?``:typeof e==`string`?e:JSON.stringify(e)}function ud(e,t){e instanceof HTMLInputElement&&e.type===`checkbox`?e.checked!==(t===!0||t===`true`)&&e.click():e instanceof HTMLInputElement&&e.type===`radio`?e.value===ld(t)&&!e.checked&&e.click():cd(e,ld(t))}function dd(e,t,n){let r=[...e.elements].filter(ad),i={},a=/* @__PURE__ */ new Set;for(let e of r){var o;let t=r.flatMap(t=>t instanceof HTMLInputElement&&t.type===`radio`&&t.name===e.name?[t.value]:[]);i[o=e.name]??(i[o]=sd(e,t)),e.required&&a.add(e.name)}return{name:t,description:n,inputSchema:{type:`object`,properties:i,...a.size>0?{required:[...a]}:{}},execute(t){let n=typeof t==`object`&&t?Object.entries(t):[];for(let[e,t]of n)for(let n of r)n.name===e&&ud(n,t);if(!e.hasAttribute(`toolautosubmit`))return`Filled in the form. The visitor still needs to check it and press its submit button.`;let i=[...new Set([...e.elements].flatMap(e=>id(e)&&e.name&&!e.checkValidity()?[e.name]:[]))];return i.length>0?`Filled in the form, but it can't be submitted yet: ${i.join(`, `)} still needs the visitor. Ask them to complete it and press the submit button.`:(setTimeout(()=>e.requestSubmit(),0),`Filled in the form and submitted it.`)}}}function fd(){return[...document.querySelectorAll(`form[toolname][tooldescription]`)].flatMap(e=>{let t=e.getAttribute(`toolname`)?.trim()??``,n=e.getAttribute(`tooldescription`)?.trim()??``;return t&&n?[dd(e,t,n)]:[]})}const pd=`${N.cssPrefix}.page-tools`;function md(e){return typeof e==`object`&&!!e}function hd(e){return md(e)&&(e.state===`running`||e.state===`stopped`||e.state===`finished`&&md(e.outcome))}function gd(e){let t=e?JSON.parse(e):void 0;return md(t)?{sent:Array.isArray(t.sent)?t.sent.filter(e=>typeof e==`string`):[],calls:Object.fromEntries(Object.entries(md(t.calls)?t.calls:{}).filter(e=>hd(e[1])))}:{sent:[],calls:{}}}let _d={sent:[],calls:{}};function vd(){try{_d=gd(sessionStorage.getItem(pd))}catch{}return _d}function yd(e){_d=e;try{sessionStorage.setItem(pd,JSON.stringify(e))}catch{}}const bd={markSent(e){let t=vd();yd({...t,sent:[...t.sent.filter(t=>t!==e),e].slice(-20)})},sentHere(e){return vd().sent.includes(e)},get(e){return vd().calls[e]},set(e,t){let n=vd(),r=Object.entries(n.calls).filter(([t])=>t!==e);yd({...n,calls:Object.fromEntries([...r,[e,t]].slice(-50))})},clear(e){let t=vd();e.some(e=>e in t.calls)&&yd({...t,calls:Object.fromEntries(Object.entries(t.calls).filter(([t])=>!e.includes(t)))})}},xd=R.scope(`page-tools`),Sd=3e4,Cd=Symbol.for(`${N.cssPrefix}.page-tools`),wd={state:`output-error`,errorText:`The page reloaded before this finished, so it may or may not have taken effect. Check with the visitor before trying it again.`},Td=`The visitor stopped this before it finished.`;function Ed(e){return typeof e==`object`&&!!e}function Dd(e){return Ed(e)&&Array.isArray(e.registered)&&e.runs instanceof Map}function Od(){let e=Reflect.get(globalThis,Cd);if(Dd(e))return e;let t={registered:[],runs:/* @__PURE__ */ new Map};return Reflect.set(globalThis,Cd,t),t}function kd(e,t){let n=Ed(t)&&t.signal instanceof AbortSignal?t.signal:void 0;if(n?.aborted)return;let r=Od().registered;r.push(e);function i(){let t=r.indexOf(e);t>=0&&r.splice(t,1)}n?.addEventListener(`abort`,i,{once:!0})}function Ad(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,58)}function jd(e){if(!Ed(e)||typeof e.name!=`string`||!Ad(e.name))return;let t=typeof e.title==`string`&&e.title.trim()!==``?e.title.trim().slice(0,120):void 0,n=[e.description,t].find(e=>typeof e==`string`&&e.trim()!==``)??e.name,r=e.preview;return{name:Ad(e.name),...t?{title:t}:{},...typeof r==`function`?{preview:t=>Reflect.apply(r,e,[t])}:{},description:n.trim().slice(0,1024),inputSchema:{properties:{},...Ed(e.inputSchema)?e.inputSchema:{},type:`object`},consequential:Ed(e.annotations)&&e.annotations.consequentialHint===!0}}function Md(e){return e.flatMap(e=>{let t=jd(e),n=Ed(e)?e.execute:void 0;return!t||typeof n!=`function`?(xd.warn(`skipped a tool without a name or an execute function`,e),[]):[{...t,run:(t,r)=>Reflect.apply(n,e,[t,{signal:r}])}]})}async function Nd(){let e=Reflect.get(document,`modelContext`)??Reflect.get(navigator,`modelContext`);if(!Ed(e)||typeof e.getTools!=`function`||typeof e.executeTool!=`function`)return[];let t=e.getTools,n=e.executeTool,r=await Promise.race([Promise.resolve().then(()=>Reflect.apply(t,e,[])),wo(1e3).then(()=>[])]).catch(()=>[]);return(Array.isArray(r)?r:[]).flatMap(t=>{let r=jd(t);return r?[{...r,run:(r,i)=>Reflect.apply(n,e,[t,r,{signal:i}])}]:[]})}async function Pd(e=[]){let t=Md(fd()),n=new Set(t.map(e=>e.name)),r=[...(await Nd()).filter(e=>!n.has(e.name)),...t,...Md(e),...Md(Od().registered)];return new Map(r.map(e=>[e.name,e]))}function Fd(e){return[...e.values()].map(({name:e,title:t,description:n,inputSchema:r,consequential:i})=>{let a={name:e,description:n,inputSchema:r};return t&&(a.title=t),i&&(a.annotations={consequentialHint:!0}),a})}function Id(e){return e?.execution===`client`}function Ld(e){return e.startsWith(`site__`)?e.slice(6):e}function Rd(e){if(e===void 0||typeof e==`function`||typeof e==`symbol`)return null;let t=/* @__PURE__ */ new WeakSet,n=JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n!=`function`&&typeof n!=`symbol`)return n instanceof Node?`[${n.nodeName.toLowerCase()}]`:Ed(n)?t.has(n)?`[circular]`:(t.add(n),n):n});return n.length>Sd?{truncated:!0,preview:n.slice(0,Sd)}:JSON.parse(n)}async function zd(e){let t=(await Pd(e.optionTools)).get(Ld(e.toolName));if(!t?.preview)return;let n=t.preview;return Promise.resolve().then(()=>n(e.input)).catch(e=>{xd.warn(`a page tool preview failed`,{name:t.name,error:e})})}async function Bd(e){let t=Ld(e.toolName),n=(await Pd(e.optionTools)).get(t);return n?Promise.resolve().then(()=>n.run(e.input,e.signal)).then(e=>({state:`output-available`,output:Rd(e)})).catch(e=>(xd.warn(`a page tool failed`,{name:t,error:e}),{state:`output-error`,errorText:(e instanceof Error?e.message:String(e)).slice(0,1e3)||`The page tool failed.`})):{state:`output-error`,errorText:`This page doesn't offer "${t}" right now; the visitor may have moved on. Tell them, or continue without it.`}}function Vd(e){let{toolCallId:t}=e,n=bd.get(t);if(n?.state===`finished`)return Promise.resolve(n.outcome);let{runs:r}=Od(),i=r.get(t);if(i)return i.outcome;if(n?.state===`running`)return bd.set(t,{state:`finished`,outcome:wd}),e.onSettled(`interrupted`,0),Promise.resolve(wd);let a=new AbortController,o=performance.now();bd.set(t,{state:`running`});let s=Bd({...e,signal:a.signal}).then(n=>(r.delete(t),bd.get(t)?.state===`running`&&(bd.set(t,{state:`finished`,outcome:n}),e.onSettled(n.state===`output-available`?`completed`:`failed`,Math.round(performance.now()-o))),n));return r.set(t,{outcome:s,controller:a}),s}function Hd(e){return e===wd.errorText||e===Td}function Ud(e){return bd.set(e,{state:`stopped`}),Od().runs.get(e)?.controller.abort(),Td}function Wd(e){bd.clear([e]),Od().runs.get(e)?.controller.abort()}const Gd=N.cssPrefix;function Kd({messageId:e,initial:t,strings:n,onFeedback:r}){let[i,a]=h(t);u(()=>a(t),[e,t]);function o(t){let n=i===t?null:t;a(n),r(e,n)}return/* @__PURE__ */ v(`div`,{class:`${Gd}-feedback`,role:`group`,"data-testid":Y.messageFeedback,children:[/* @__PURE__ */ _(`button`,{type:`button`,class:`${Gd}-msg-action`,"data-active":i===`up`?`true`:void 0,"aria-pressed":i===`up`,"aria-label":n.feedbackUp,title:n.feedbackUp,onClick:()=>o(`up`),"data-testid":Y.feedbackUp,children:/* @__PURE__ */ _(Tc,{})}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Gd}-msg-action`,"data-active":i===`down`?`true`:void 0,"aria-pressed":i===`down`,"aria-label":n.feedbackDown,title:n.feedbackDown,onClick:()=>o(`down`),"data-testid":Y.feedbackDown,children:/* @__PURE__ */ _(Ec,{})}),/* @__PURE__ */ _(`span`,{class:`${Gd}-sr-only`,role:`status`,"aria-live":`polite`,children:i?n.feedbackThanks:``})]})}function qd(e){return e.partsSig.value.some(e=>e.kind===`text`&&e.textSig.value.length>0)}function Jd(e){return e.partsSig.value.some(e=>e.kind===`reasoning`)}function Yd(e){return e.streaming&&!e.bufferedHold&&!(e.reasoningVisible&&e.working)}function Xd(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:Yd({streaming:t,bufferedHold:a,reasoningVisible:n,working:o}),emptyReply:r,hidden:i}}const Zd=N.cssPrefix;function Qd({part:e,strings:t}){let n=e.title||e.filename||e.url||t.sources;return e.url?/* @__PURE__ */ v(`a`,{class:`${Zd}-source`,href:e.url,target:`_blank`,rel:`noreferrer noopener`,"data-testid":Y.source,children:[/* @__PURE__ */ _(`span`,{class:`${Zd}-source-icon`,"aria-hidden":`true`,children:`🔗`}),/* @__PURE__ */ _(`span`,{class:`${Zd}-source-label`,children:n})]}):/* @__PURE__ */ v(`span`,{class:`${Zd}-source`,"data-testid":Y.source,children:[/* @__PURE__ */ _(`span`,{class:`${Zd}-source-icon`,"aria-hidden":`true`,children:`📄`}),/* @__PURE__ */ _(`span`,{class:`${Zd}-source-label`,children:n})]})}const $d=N.cssPrefix;function ef(e){return{toolCallId:e.toolCallId,toolName:e.toolName,...e.title?{title:e.title}:{},state:e.stateSig.value,input:e.inputSig.value,output:e.outputSig.value,...e.errorSig.value?{errorText:e.errorSig.value}:{},...e.approvalSig.value?{approval:e.approvalSig.value}:{},...e.toolMetadata?{toolMetadata:e.toolMetadata}:{}}}function tf(e,t){if(t?.replacedByMessageId)return{terminal:!1,responded:!1,decided:!1};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 nf({status:e,label:t,icon:n}){return/* @__PURE__ */ v(`span`,{class:`${$d}-toolui-badge ${$d}-toolui-status`,"data-status":e,children:[/* @__PURE__ */ _(`span`,{class:`${$d}-toolui-status-icon`,children:n??/* @__PURE__ */ _(rf,{status:e})}),t]})}function rf({status:e}){return e===`running`?/* @__PURE__ */ _(`span`,{class:`${$d}-loading-spinner`}):_(e===`stopped`?Ls:e===`waiting`||e===`submitted`?Oc:e===`failed`||e===`declined`||e===`replaced`?Ac:kc,{})}function af(e){return e===`approved`||e===`declined`||e===`done`}function of({decision:e}){return/* @__PURE__ */ v(`span`,{class:`${$d}-steps-decision`,"data-approved":e.approved?`true`:`false`,children:[e.approved?/* @__PURE__ */ _(kc,{}):/* @__PURE__ */ _(Ac,{}),e.label]})}function sf({view:e,strings:t}){let n=e.raw;return/* @__PURE__ */ v(g,{children:[e.reason?/* @__PURE__ */ _(`p`,{class:`${$d}-steps-row-reason`,children:e.reason}):null,e.error?/* @__PURE__ */ _(`p`,{class:`${$d}-steps-row-error`,children:e.error}):null,e.fields.length>0?/* @__PURE__ */ _(cf,{fields:e.fields,label:n?t.stepInput:void 0}):null,e.resultFields?/* @__PURE__ */ _(cf,{fields:e.resultFields,label:t.toolResult}):null,n?.input||n?.output?/* @__PURE__ */ v(`details`,{class:`${$d}-toolui-raw`,children:[/* @__PURE__ */ _(`summary`,{children:t.stepRawData}),n.input?/* @__PURE__ */ _(lf,{label:t.stepInput,text:n.input}):null,n.output?/* @__PURE__ */ _(lf,{label:t.toolResult,text:n.output}):null]}):null]})}function cf({fields:e,label:t}){let n=/* @__PURE__ */ _(`div`,{class:`${$d}-toolui-fields`,children:/* @__PURE__ */ _(`table`,{children:/* @__PURE__ */ _(`tbody`,{children:e.map(({label:e,value:t},n)=>/* @__PURE__ */ v(`tr`,{children:[/* @__PURE__ */ _(`th`,{scope:`row`,children:e}),/* @__PURE__ */ _(`td`,{children:t})]},`${e}#${n}`))})})});return t?/* @__PURE__ */ v(`div`,{class:`${$d}-toolui-section`,children:[/* @__PURE__ */ _(`span`,{class:`${$d}-toolui-label`,children:t}),n]}):n}function lf({label:e,text:t}){return/* @__PURE__ */ v(`div`,{class:`${$d}-toolui-section`,children:[/* @__PURE__ */ _(`span`,{class:`${$d}-toolui-label`,children:e}),/* @__PURE__ */ _(`pre`,{class:`${$d}-toolui-code`,children:t})]})}const uf=N.cssPrefix;function df({part:e,view:t,strings:n,locale:r,canAct:i,onDecision:a,onEdit:o,preview:s}){let c=t.approval,l=t.status===`waiting`||t.status===`submitted`||t.status===`approved`,u=e.toolCallId;return/* @__PURE__ */ v(`details`,{class:`${uf}-toolui ${uf}-toolui-collapsible`,open:l||c?.buttons===`change`||void 0,"data-testid":t.status===`waiting`?Y.toolApproval:Y.toolDecision,"data-status":t.status,children:[/* @__PURE__ */ v(`summary`,{class:`${uf}-toolui-head`,children:[/* @__PURE__ */ _(`span`,{class:`${uf}-toolui-prompt`,children:l&&c?c.ask:t.name}),t.system?/* @__PURE__ */ _(`span`,{class:`${uf}-toolui-system`,children:t.system}):null,/* @__PURE__ */ v(`span`,{class:`${uf}-toolui-head-end`,children:[t.decision?/* @__PURE__ */ _(of,{decision:t.decision}):null,t.statusLabel&&!(t.decision&&af(t.status))?/* @__PURE__ */ _(nf,{status:t.status,label:t.statusLabel}):null,/* @__PURE__ */ _(`span`,{class:`${uf}-toolui-chevron`,children:/* @__PURE__ */ _(rc,{})})]})]}),/* @__PURE__ */ v(`div`,{class:`${uf}-toolui-collapse-body`,children:[l&&s&&Id(e.toolMetadata)?/* @__PURE__ */ _(pf,{toolName:e.toolName,input:e.inputSig.value,preview:s,strings:n,locale:r}):null,/* @__PURE__ */ _(sf,{view:t,strings:n}),c?.note?/* @__PURE__ */ _(`p`,{class:`${uf}-toolui-subtle`,children:c.note}):null,c?.buttons===`decide`?/* @__PURE__ */ v(`div`,{class:`${uf}-toolui-actions`,children:[/* @__PURE__ */ _(`button`,{type:`button`,class:`${uf}-form-skip`,disabled:!i,onClick:()=>a(u,!1),"data-testid":Y.toolDecline,children:n.decline}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${uf}-form-submit`,disabled:!i,onClick:()=>a(u,!0),"data-testid":Y.toolApprove,children:n.approve})]}):null,c?.buttons===`change`?/* @__PURE__ */ _(`div`,{class:`${uf}-toolui-actions`,children:/* @__PURE__ */ _(`button`,{type:`button`,class:`${uf}-form-skip`,onClick:()=>o(u),"data-testid":Y.toolEdit,children:n.changeAnswer})}):null]})]})}function ff(e){if(typeof e==`object`&&e&&`totals`in e)return`number`in e&&`items`in e?`root = Root([preview])\npreview = Order(${JSON.stringify(e)})`:`lines`in e?`root = Root([preview])\npreview = Cart(${JSON.stringify(e)})`:void 0}function pf({toolName:e,input:t,preview:n,strings:r,locale:i}){let[a,s]=h();u(()=>{let r=!0;return n(e,t).then(e=>{r&&s(ff(e))}),()=>{r=!1}},[e,t,n]);let c=p(()=>a?{textSig:o(a),doneSig:o(!0),replyDoneSig:o(!0)}:void 0,[a]);return c?/* @__PURE__ */ _(`div`,{class:`${uf}-toolui-preview`,"data-testid":Y.toolPreview,children:/* @__PURE__ */ _(ca,{cssPrefix:uf,textSig:c.textSig,doneSig:c.doneSig,replyDoneSig:c.replyDoneSig,strings:r,locale:i})}):null}const mf=[`text`,`email`,`phone`,`number`,`date`,`single-select`,`multi-select`,`boolean`];function hf(e){return typeof e==`object`&&!!e}function gf(e,t){let n=hf(e)?e:{},r=(Array.isArray(n.questions)?n.questions:[]).map((e,n)=>_f(e,n,t)).filter(e=>e!==null);return{intro:bf(n.intro),questions:r}}function _f(e,t,n){if(!hf(e))return null;let r=mf.find(t=>t===e.type)??`text`;return{key:bf(e.key)??`q${t+1}`,question:bf(e.question)??n,type:r,options:Array.isArray(e.options)?e.options.filter(e=>typeof e==`string`&&e.trim().length>0):void 0,required:typeof e.required==`boolean`?e.required:void 0,helpText:bf(e.helpText)}}function vf(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 yf(e,t,n){return e.questions.map(e=>{let r=vf(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 bf(e){return typeof e==`string`&&e.trim()?e.trim():void 0}const xf=N.cssPrefix;function Sf({fields:e,strings:t,submitLabel:n,onSubmit:r,skipLabel:i,onSkip:a,footerHint:o,submitOnEnter:s,disabled:c,initialValues:l,hideActions:u,fieldTypeLabels:d,rootTestId:f,submitTestId:p,skipTestId:m}){let[g,y]=h(()=>l??{}),[b,x]=h({}),[S,C]=h({});function w(e){S[e]&&C(t=>({...t,[e]:``}))}function T(e,t){y(n=>({...n,[e]:t})),w(e)}function E(e,t){x(n=>({...n,[e]:t})),w(e)}function D(n){if(n.preventDefault(),c)return;let i=Ef(e,g,b),a=Zu(e,i,t);Object.keys(a).length>0?C(a):r(i)}function O(e){!s||e.key!==`Enter`||e.shiftKey||Ql(e)||e.target&&`tagName`in e.target&&e.target.tagName===`TEXTAREA`&&D(e)}return/* @__PURE__ */ v(`form`,{class:`${xf}-form`,onSubmit:D,onKeyDown:O,onCompositionEnd:Zl,"data-testid":f,noValidate:!0,children:[e.map(e=>/* @__PURE__ */ _(Cf,{field:e,value:g[e.name],otherText:b[e.name]??``,error:S[e.name],disabled:c,typeLabel:d?.[e.name],strings:t,onChange:t=>T(e.name,t),onOtherChange:t=>E(e.name,t)},e.name)),u?null:/* @__PURE__ */ v(`div`,{class:`${xf}-form-actions`,children:[o?/* @__PURE__ */ _(`span`,{class:`${xf}-form-hint`,children:o}):null,i&&a?/* @__PURE__ */ _(`button`,{type:`button`,class:`${xf}-form-skip`,onClick:a,disabled:c,"data-testid":m,children:i}):null,/* @__PURE__ */ _(`button`,{type:`submit`,class:`${xf}-form-submit`,disabled:c,"data-testid":p,children:n})]})]})}function Cf({field:e,value:t,otherText:n,error:r,disabled:i,typeLabel:a,strings:o,onChange:s,onOtherChange:c}){let l=Pc(Y.formField,e.name),u=d(),f=wf({field:e,value:t,otherText:n,disabled:i,strings:o,onChange:s,onOtherChange:c,fieldTid:l,labelId:u}),p=e.type===`radio`||e.type===`multiselect`?`div`:`label`;return/* @__PURE__ */ v(p,{class:`${xf}-field`,"data-field":e.name,"data-invalid":r?`true`:void 0,children:[/* @__PURE__ */ v(`span`,{class:`${xf}-field-head`,children:[/* @__PURE__ */ v(`span`,{class:`${xf}-field-label`,id:u,children:[e.label,e.required?/* @__PURE__ */ _(`span`,{class:`${xf}-field-req`,"aria-hidden":`true`,children:` *`}):null]}),a?/* @__PURE__ */ _(`span`,{class:`${xf}-field-type`,children:a}):null]}),f,e.validationHint&&!r?/* @__PURE__ */ _(`span`,{class:`${xf}-field-hint`,children:e.validationHint}):null,r?/* @__PURE__ */ _(`span`,{class:`${xf}-field-error`,role:`alert`,children:r}):null]})}function wf(e){let{field:t,value:n,otherText:r,disabled:i,strings:a,onChange:o,onOtherChange:s,fieldTid:c,labelId:l}=e,u=typeof n==`string`?n:``;switch(t.type){case`textarea`:return/* @__PURE__ */ _(`textarea`,{class:`${xf}-field-input`,rows:3,value:u,disabled:i,onInput:e=>o(e.currentTarget.value),"data-testid":c});case`radio`:return/* @__PURE__ */ _(`div`,{class:`${xf}-field-choices`,role:`radiogroup`,"aria-labelledby":l,"data-testid":c,children:(t.options??[]).map(e=>/* @__PURE__ */ v(`label`,{class:`${xf}-choice`,children:[/* @__PURE__ */ _(`input`,{type:`radio`,name:`${xf}-${t.name}`,checked:u===e.value,disabled:i,onChange:()=>o(e.value)}),/* @__PURE__ */ _(`span`,{children:e.label})]},e.value))});case`multiselect`:{let e=Array.isArray(n)?n:[];function u(t,n){return o(n?[...e,t]:e.filter(e=>e!==t))}return/* @__PURE__ */ v(`div`,{class:`${xf}-field-choices`,role:`group`,"aria-labelledby":l,"data-testid":c,children:[(t.options??[]).map(t=>/* @__PURE__ */ v(`label`,{class:`${xf}-choice`,children:[/* @__PURE__ */ _(`input`,{type:`checkbox`,checked:e.includes(t.value),disabled:i,onChange:e=>u(t.value,e.currentTarget.checked)}),/* @__PURE__ */ _(`span`,{children:t.label})]},t.value)),(t.options??[]).length===0?/* @__PURE__ */ _(`textarea`,{class:`${xf}-field-input`,rows:2,value:r,placeholder:a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.currentTarget.value)}):null]})}default:return/* @__PURE__ */ _(`input`,{...Tf(t.type),class:`${xf}-field-input`,value:u,disabled:i,onInput:e=>o(e.currentTarget.value),"data-testid":c})}}function Tf(e){switch(e){case`number`:return{type:e};case`email`:return{type:e};case`tel`:return{type:e};case`date`:return{type:e};default:return{type:`text`}}}function Ef(e,t,n){let r={...t};for(let i of e){let e=n[i.name]?.trim();if(i.type===`multiselect`&&e){let n=e.split(/[,\n;]+/).map(e=>e.trim()).filter(Boolean),a=t[i.name];r[i.name]=[...Array.isArray(a)?a:[],...n]}}return r}const Df=N.cssPrefix;function Of({skipped:e,submitted:t,strings:n}){return e?{status:`replaced`,statusLabel:n.inputSkipped}:t?{status:`submitted`,statusLabel:n.stepWorkingOnIt}:{status:`done`,statusLabel:n.inputAnswered}}const kf={text:`qtypeText`,email:`qtypeEmail`,phone:`qtypePhone`,number:`qtypeNumber`,date:`qtypeDate`,"single-select":`qtypeChooseOne`,"multi-select":`qtypeChooseAny`,boolean:`qtypeBoolean`};function Af(e,t){let n={};for(let r of e)n[r.key]=t[kf[r.type]];return n}function jf({part:e,strings:t,active:n,superseded:r=!1,continuationStreaming:a=!1,onDecision:o,onEdit:s}){let c=p(()=>i(()=>e.stateSig.value),[e]).value,l=p(()=>i(()=>e.approvalSig.value),[e]).value,u=p(()=>i(()=>gf(e.inputSig.value,t.askFallbackQuestion)),[e,t]).value,{terminal:d,decided:f}=tf(c,l),m=f&&l?.approved===!0,g=a&&!f,y=!f&&!r&&!g,b=!y&&!m&&!g,x=m&&n&&!d,S=u.questions,[C,w]=h(null),T=C??(y||m||g),[E,D]=h(!1),O=S.length>1?As:sc,k=y?t.inputRequired:t.inputBadge,A=g?/* @__PURE__ */ _(`p`,{class:`${Df}-toolui-subtle`,children:t.stepWorkingOnIt}):y?/* @__PURE__ */ _(Mf,{req:u,strings:t,active:n,resolve:(t,n)=>o(e.toolCallId,n,t)}):E?/* @__PURE__ */ _(Sf,{fields:yf(u,t.confirmYes,t.confirmNo),strings:t,submitLabel:t.inputSubmit,onSubmit:()=>{},disabled:!0,hideActions:!0,fieldTypeLabels:Af(S,t),initialValues:m?zf(S,l?.reason):void 0}):/* @__PURE__ */ _(Nf,{questions:S,answers:m?Rf(l?.reason):{},strings:t}),{status:j,statusLabel:ee}=Of({skipped:b,submitted:g,strings:t});return/* @__PURE__ */ v(`details`,{class:`${Df}-toolui ${Df}-toolui-collapsible${r?` ${Df}-toolui-stale`:``}`,open:T,onToggle:e=>{let t=e.currentTarget.open;t!==T&&w(t)},"data-testid":y?Y.toolAskQuestions:Y.toolDecision,children:[/* @__PURE__ */ v(`summary`,{class:`${Df}-toolui-head`,children:[/* @__PURE__ */ v(`span`,{class:`${Df}-toolui-q-pill`,children:[/* @__PURE__ */ _(O,{}),k]}),/* @__PURE__ */ v(`span`,{class:`${Df}-toolui-head-end`,children:[y?null:/* @__PURE__ */ _(nf,{status:j,icon:_(b?Ac:kc,{}),label:ee}),/* @__PURE__ */ _(`span`,{class:`${Df}-toolui-chevron`,children:/* @__PURE__ */ _(rc,{})})]})]}),/* @__PURE__ */ v(`div`,{class:`${Df}-toolui-collapse-body`,children:[u.intro?/* @__PURE__ */ _(`div`,{class:`${Df}-toolui-desc`,children:u.intro}):null,A,y||g?null:/* @__PURE__ */ v(`div`,{class:`${Df}-toolui-footer`,children:[/* @__PURE__ */ v(`button`,{type:`button`,class:`${Df}-toolui-options-toggle`,onClick:()=>D(e=>!e),"data-testid":Y.toolAskOptions,children:[/* @__PURE__ */ _(`span`,{class:`${Df}-toolui-options-chevron${E?` ${Df}-open`:``}`,children:/* @__PURE__ */ _(rc,{})}),E?t.hideOptions:t.showOptions]}),x?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Df}-form-skip`,onClick:()=>s(e.toolCallId),"data-testid":Y.toolEdit,children:t.edit}):null]})]})]})}function Mf({req:e,strings:t,active:n,resolve:r}){let i=yf(e,t.confirmYes,t.confirmNo),a=e.questions.length===1&&e.questions[0]?.type===`text`;return/* @__PURE__ */ _(Sf,{fields:i,strings:t,disabled:!n,submitLabel:t.inputSubmit,footerHint:a?t.inputSubmitHint:void 0,onSubmit:t=>r(Ff(e.questions,t),!0),skipLabel:t.inputSkip,onSkip:()=>r(void 0,!1),submitOnEnter:a,fieldTypeLabels:Af(e.questions,t),submitTestId:Y.toolInputSubmit,skipTestId:Y.toolInputSkip})}function Nf({questions:e,answers:t,strings:n}){return/* @__PURE__ */ _(`div`,{class:`${Df}-toolui-summary`,"data-testid":Y.toolAskSummary,children:e.map(e=>/* @__PURE__ */ v(`div`,{class:`${Df}-field`,children:[/* @__PURE__ */ _(`span`,{class:`${Df}-field-head`,children:/* @__PURE__ */ v(`span`,{class:`${Df}-field-label`,children:[e.question,e.required?/* @__PURE__ */ _(`span`,{class:`${Df}-field-req`,"aria-hidden":`true`,children:` *`}):null]})}),/* @__PURE__ */ _(`p`,{class:`${Df}-toolui-answer`,children:Pf(e,t[e.key],n)||`—`})]},e.key))})}function Pf(e,t,n){return e.type===`boolean`?t===`yes`?n.confirmYes:t===`no`?n.confirmNo:t??``:t??``}function Ff(e,t){let n=e.flatMap(e=>{let n=t[e.key],r=typeof n==`string`?n.trim():n;return r?.length?[{key:e.key,value:r}]:[]});return JSON.stringify({answers:n})}function If(e){if(!e)return{};let t=(()=>{try{return JSON.parse(e)}catch{return}})(),n=Lf(t)?t.answers:void 0;if(!Array.isArray(n))return{};let r={};for(let e of n)if(Lf(e)){let{key:t,value:n}=e;if(typeof t!=`string`)continue;typeof n==`string`?r[t]=n:Array.isArray(n)&&(r[t]=n.filter(e=>typeof e==`string`))}return r}function Lf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rf(e){let t=If(e),n={};for(let[e,r]of Object.entries(t))n[e]=Array.isArray(r)?r.join(`, `):r;return n}function zf(e,t){let n=If(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}const Z=N.cssPrefix;function Bf(e,t){let n=[];for(let[r,i]of e.entries()){let e=n.at(-1),a=i.kind===`tool`?t.viewOf(i):void 0,o=Vf(i,a,t.showReasoning);o?e?.kind===`steps`?(e.rows.push(o),e.indices.push(r)):n.push({kind:`steps`,rows:[o],indices:[r]}):i.kind===`step-start`||i.kind===`reasoning`||i.kind===`source`&&!t.showSources||a?.placement===`hidden`||n.push({kind:`part`,part:i,index:r})}return n}function Vf(e,t,n){return e.kind===`reasoning`?n?{kind:`thought`,part:e}:void 0:e.kind===`tool`&&t?.placement===`step`?{kind:`tool`,part:e,view:t}:void 0}function Hf(e,t){let n=[...new Set(t)];if(e&&n.length!==0&&!n.some(t=>t<0||t>=e.length))return n.reduce((t,n)=>t+(e[n]?.durationMs??0),0)}function Uf(e){let t=[];for(let n of e)t.push((t.at(-1)??-1)+ +(n.kind===`step-start`));return t}function Wf(e,t){return e.streaming?t.thinking:e.reasoningMs===void 0?t.thought:t.thoughtFor.replace(`{time}`,Gf(e.reasoningMs))}function Gf(e){if(e<1e4)return`${Number((e/1e3).toFixed(1))} s`;let t=Math.round(e/1e3);return t<60?`${t} s`:`${Math.floor(t/60)} m ${t%60} s`}function Kf(e){return e.split(`
35
+ `)??n):e;if(r)return t--,i&&(n=n.slice(2)),i?`\n${n}`:``;o||(t++,i&&(n+=`> `));let u={};a.replace(/(\w+)=(["'])(.*?)\2/g,(e,t,n,r)=>u[t]=r);let d=u.href??u.src,f=u.title??u.path??u.query??u.body??u.header??u.name??d;return(i?`> `:``)+(f?`**${d?`[${f}](${d})`:f}**${u.type?` \`${u.type}\``:``}\n${n}`:``)})}const tl=/* @__PURE__ */ new Set([`http:`,`https:`,`mailto:`,`tel:`]),nl=/* @__PURE__ */ new Set([`http:`,`https:`]);function rl(e){let t=document.createElement(`a`);return{...e,set_attr:(n,r,i)=>{if(r!==y.HREF&&r!==y.SRC||(t.href=i,(r===y.HREF?tl:nl).has(t.protocol)))return e.set_attr(n,r,i);let a=r===y.SRC?n.nodes[n.index]:void 0;a?.replaceWith(...a.childNodes)}}}function il(e){for(let t of e.querySelectorAll(`a`)){let e=t.getAttribute(`href`)??``;e&&!e.startsWith(`#`)&&(t.target=`_blank`,t.rel=`noopener noreferrer`)}}const al=/* @__PURE__ */ new Set([y.CODE_INLINE,y.ITALIC_AST,y.ITALIC_UND,y.STRONG_AST,y.STRONG_UND,y.STRIKE,y.LINK,y.RAW_URL,y.IMAGE,y.EQUATION_INLINE]);function ol(e){let t=``,n=[],r=y.parser({data:void 0,add_token:(e,r)=>{n.push(r),al.has(r)||(t+=` `)},end_token:()=>{let e=n.pop();e!==void 0&&!al.has(e)&&(t+=` `)},add_text:(e,n)=>void(t+=n),set_attr:()=>void 0});return y.parser_write(r,Zc(e)),y.parser_end(r),t.replaceAll(``,`_`).replace(/\s+/g,` `).trim()}const sl=N.cssPrefix;function cl({tone:e=`info`,message:t,onRetry:n,strings:r}){return/* @__PURE__ */ v(`div`,{class:`${sl}-module-empty`,role:e===`error`?`alert`:`status`,"aria-live":`polite`,children:[/* @__PURE__ */ _(`span`,{children:t}),n?/* @__PURE__ */ _(`button`,{type:`button`,class:`${sl}-module-retry`,onClick:n,children:r.errorRetry}):null]})}const ll=N.cssPrefix,ul=R.scope(`content`);function dl({id:e,title:t,transport:n,strings:r,bus:i,onBack:a,actions:o}){let[s,c]=h(null),[d,f]=h(!1),[p,m]=h(!1),[y,b]=h(0),[x,S]=h(null),C=l(()=>{m(!1),c(null),b(e=>e+1)},[]);u(()=>{let t=!1,r=n.listContentCollections([]).catch(()=>void 0);return Promise.all([n.listContent({ids:[e],limit:1}),r]).then(([n,r])=>{if(t)return;let a=n.items[0];a?(c(a),f(r?.items.find(e=>e.id===a.contentCollectionId)?.settings?.voteAccess===`portal`),i.emit(`contentOpen`,{contentId:e,contentCollectionId:a.contentCollectionId})):m(!0)}).catch(e=>{t||(ul.warn(`listContent (reader) failed`,{err:e}),m(!0))}),()=>{t=!0}},[n,e,y,i]),u(()=>{if(!s)return;let t=setTimeout(()=>i.emit(`contentRead`,{contentId:e}),5e3);return()=>clearTimeout(t)},[s,e,i]);let w=l(t=>{let n=(t.target instanceof HTMLElement?t.target.closest(`a`):null)?.getAttribute(`href`)??``;n&&!n.startsWith(`#`)&&i.emit(`contentLinkClick`,{contentId:e})},[i,e]);function T(t){S(e),n.setContentVote({contentId:e,value:t})}function E(){return p?/* @__PURE__ */ _(cl,{tone:`error`,message:r.errorGeneric,onRetry:C,strings:r}):s===null?/* @__PURE__ */ _(cl,{message:r.contentLoading,strings:r}):/* @__PURE__ */ v(`article`,{class:`${ll}-content`,"data-testid":Y.contentView,onClick:w,children:[s.image?/* @__PURE__ */ _(`img`,{class:`${ll}-content-hero`,src:s.image,alt:``,loading:`lazy`}):null,s.description?/* @__PURE__ */ _(`p`,{class:`${ll}-content-subtitle`,children:s.description}):null,/* @__PURE__ */ _(Yc,{text:el(s.content??``)}),d?/* @__PURE__ */ _(`div`,{class:`${ll}-content-vote`,"aria-live":`polite`,children:x===e?r.feedbackThanks:/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`span`,{children:r.contentHelpful}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${ll}-module-retry`,onClick:()=>T(1),children:r.confirmYes}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${ll}-module-retry`,onClick:()=>T(0),children:r.confirmNo})]})}):null]})}return/* @__PURE__ */ v(`div`,{class:`${ll}-module`,children:[/* @__PURE__ */ _(qc,{title:s?.title||t||r.moduleBack,backLabel:r.moduleBack,onBack:a,actions:o,testid:Y.backHeader}),/* @__PURE__ */ _(`div`,{class:`${ll}-module-scroll`,"data-testid":Y.contentScroll,children:E()})]})}function fl({itemCount:e,initialFocusIndex:t}){let[n,r]=h(!1),i=m(null),a=m(null),[o,s]=h(-1),c=l(()=>{r(!1),s(-1),i.current?.focus()},[]),d=l(()=>r(e=>!e),[]);return u(()=>{if(!n)return;function e(e){let t=a.current,n=i.current;if(!t||!n)return;let o=e.composedPath();o.includes(t)||o.includes(n)||(r(!1),s(-1))}return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[n]),u(()=>{if(!n||e===0)return;let r=t?.()??0;s(r<0||r>=e?0:r)},[n,e,t]),u(()=>{!n||o<0||(a.current?.querySelectorAll(`[role='menuitem']`))?.[o]?.focus()},[n,o]),{open:n,focusIndex:o,triggerRef:i,menuRef:a,toggle:d,close:c,onTriggerKey:l(e=>{(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r(!0))},[]),onMenuKey:l(t=>{if(e!==0)switch(t.key){case`Escape`:t.preventDefault(),t.stopPropagation(),c();return;case`ArrowDown`:t.preventDefault(),s(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),s(t=>(t-1+e)%e);return;case`Home`:t.preventDefault(),s(0);return;case`End`:t.preventDefault(),s(e-1)}},[e,c])}}function pl({items:e,triggerLabel:t}){let n=N.cssPrefix,r=fl({itemCount:e.length});function i(e){e.disabled||(e.onSelect?.(),e.keepOpen||r.close())}function a(e,t){return e.onSelectValue?.(t)}function 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;let o=n[i];o&&(e.preventDefault(),e.stopPropagation(),a(t,o.value))}return/* @__PURE__ */ v(`div`,{class:`${n}-menu-wrap`,children:[/* @__PURE__ */ _(`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:/* @__PURE__ */ _(qs,{})}),r.open?/* @__PURE__ */ _(`div`,{ref:r.menuRef,class:`${n}-menu`,role:`menu`,"aria-label":t,onKeyDown:r.onMenuKey,tabIndex:-1,children:e.map(e=>e.segments?/* @__PURE__ */ v(`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?/* @__PURE__ */ _(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,/* @__PURE__ */ _(`span`,{class:`${n}-menu-label`,children:e.label}),/* @__PURE__ */ _(`span`,{class:`${n}-segmented`,role:`group`,"aria-label":e.label,children:e.segments.map(t=>{let r=t.value===e.value;return/* @__PURE__ */ _(`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":`${Y.langSegment}-${t.value}`,onClick:()=>a(e,t.value),children:t.label},t.value)})})]},e.id):/* @__PURE__ */ v(`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?/* @__PURE__ */ _(`span`,{class:`${n}-menu-icon`,children:e.icon}):null,/* @__PURE__ */ _(`span`,{class:`${n}-menu-label`,children:e.label}),e.type===`switch`&&e.on?/* @__PURE__ */ _(`span`,{class:`${n}-menu-check`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Zs,{})}):null]},e.id))}):null]})}const ml=N.cssPrefix;function hl(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 gl={normal:`large`,large:`small`,small:`normal`};function _l(e){return _(e===`light`?_c:e===`dark`?vc:yc,{})}function vl(e,t){let n=e.split(`-`)[0];return(t.some(t=>t!==e&&t.split(`-`)[0]===n)?e:n??e).toUpperCase()}function yl(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 bl({panelProps:e,variant:t,onEmailTranscript:n,onLogIn:r}){let{options:i,panelSize:a,feedback:o,onClose:c,onClear:l,onExpand:u,onFullscreen:d,onSoundToggle:f}=e,{onToggleHistory:p,onLocaleChange:m,onThemeChange:h,onTextSizeChange:g}=e,y=i.strings,b=i.mode,x=t===`chat`,S=s(()=>o.mutedSig.value).value,C=new Set(i.actions);function w(e){return C.has(e)}let T=typeof matchMedia==`function`&&matchMedia(`(max-width: 640px)`).matches;function E(e){return!T&&ms(e,b,a)}let D=i.themeMode,O={auto:y.themeAuto,light:y.themeLight,dark:y.themeDark},k=i.textSize,A={small:y.textSizeSmall,normal:y.textSizeNormal,large:y.textSizeLarge},j=[];if(x&&w(`clear`)&&j.push({id:`clear`,icon:/* @__PURE__ */ _(tc,{}),label:y.newConversation,onSelect:l}),x&&n&&j.push({id:`emailTranscript`,icon:/* @__PURE__ */ _(nc,{}),label:y.emailTranscript,onSelect:n}),x&&r&&j.push({id:`logIn`,icon:/* @__PURE__ */ _(Bs,{}),label:y.loginAction,onSelect:r}),w(`expand`)&&E(`expand`)){let e=a===`expanded`;j.push({id:`expand`,icon:_(e?Hs:Vs,{}),label:e?y.collapse:y.expand,type:`switch`,on:e,onSelect:u})}if(w(`fullscreen`)&&E(`fullscreen`)){let e=a===`fullscreen`;j.push({id:`fullscreen`,icon:_(e?Ws:Us,{}),label:e?y.exitFullscreen:y.fullscreen,type:`switch`,on:e,onSelect:d})}let ee=i.popOutUrl,M=i.aiAgentDeploymentId;w(`popOut`)&&ee&&M&&ms(`popOut`,b,a)&&j.push({id:`popOut`,icon:/* @__PURE__ */ _(Gs,{}),label:y.popOut,onSelect:()=>{let t=yl(ee,{conversationId:e.conversationId,widgetId:i.widgetId,publicKey:i.publicKey,aiAgentDeploymentId:M});t&&window.open(t,`_blank`,`noopener,noreferrer`)}}),x&&w(`sound`)&&j.push({id:`sound`,icon:_(S?Ys:Js,{}),label:S?y.soundOff:y.soundOn,type:`switch`,on:!S,onSelect:f}),w(`theme`)&&D!==`host`&&j.push({id:`theme`,icon:_l(D),label:`${y.theme}: ${O[D]}`,onSelect:()=>h(hl(D)),keepOpen:!0}),w(`textSize`)&&j.push({id:`textSize`,icon:/* @__PURE__ */ _(Xs,{}),label:`${y.textSize}: ${A[k]}`,onSelect:()=>g(gl[k]),keepOpen:!0}),w(`language`)&&i.availableLocales.length>1&&j.push({id:`language`,icon:/* @__PURE__ */ _($s,{}),label:y.language,segments:i.availableLocales.map(e=>({value:e,label:vl(e,i.availableLocales),lang:e})),value:i.locale,onSelectValue:m});let te=!!c&&hs(b,a,i.actions),N=x&&w(`history`);return/* @__PURE__ */ v(`div`,{class:`${ml}-header-actions`,children:[N?/* @__PURE__ */ _(`button`,{type:`button`,class:`${ml}-icon-btn`,onClick:p,"aria-label":y.history,title:y.history,"data-testid":Y.actionHistory,children:/* @__PURE__ */ _(Qs,{})}):null,j.length>0?/* @__PURE__ */ _(pl,{items:j,triggerLabel:y.moreActions}):null,te?/* @__PURE__ */ _(`button`,{type:`button`,class:`${ml}-icon-btn`,onClick:c,"aria-label":y.close,title:y.close,"data-testid":Y.actionClose,children:/* @__PURE__ */ _(js,{})}):null]})}const xl={Icon:gc};function Sl(e,t){return e instanceof Oo?e.status===429?e.retryAfterSeconds?t.errorRateLimitedIn.replace(`{seconds}`,String(e.retryAfterSeconds)):t.errorRateLimited:e.code===`network`?t.errorOffline:e.status===403?t.errorOriginNotAllowed:e.errorCode===`MESSAGE_TOO_LONG`?t.errorMessageTooLong:e.status!==void 0&&e.status>=500?t.errorServer:t.errorGeneric:t.errorGeneric}const Cl=N.cssPrefix;function wl({placeholder:e,onActivate:t}){return/* @__PURE__ */ v(`button`,{type:`button`,class:`${Cl}-home-search`,onClick:t,"data-testid":Y.homeSearch,children:[/* @__PURE__ */ _(`span`,{class:`${Cl}-home-search-text`,children:e}),/* @__PURE__ */ _(`span`,{class:`${Cl}-home-search-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(fc,{})})]})}function Tl({placeholder:e,value:t,onInput:n}){return/* @__PURE__ */ v(`div`,{class:`${Cl}-home-search`,"data-input":`true`,children:[/* @__PURE__ */ _(`input`,{type:`search`,class:`${Cl}-home-search-input`,placeholder:e,value:t,maxLength:200,onInput:e=>n(e.currentTarget.value),"data-testid":Y.helpSearch}),/* @__PURE__ */ _(`span`,{class:`${Cl}-home-search-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(fc,{})})]})}const El=N.cssPrefix;function Dl({title:e,subtitle:t,onClick:n,testid:r}){return/* @__PURE__ */ v(`button`,{type:`button`,class:`${El}-list-row`,onClick:n,"data-testid":r,children:[/* @__PURE__ */ v(`span`,{class:`${El}-list-row-body`,children:[/* @__PURE__ */ _(`span`,{class:`${El}-list-row-title`,children:e}),t?/* @__PURE__ */ _(`span`,{class:`${El}-list-row-sub`,children:t}):null]}),/* @__PURE__ */ _(`span`,{class:`${El}-list-row-chevron`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Is,{})})]})}const Ol=N.cssPrefix,kl=R.scope(`help`);function Al(e,t,n){let r=new Map(n.map(e=>[e.id,e.title]));return t.map(t=>({id:t,title:r.get(t),rows:e.filter(e=>e.contentCollectionId===t)})).filter(e=>e.rows.length>0)}function jl({transport:e,strings:t,bus:n},r,i){let[a,o]=h(),s=m(void 0),c=r?.join(`,`);function l(a){if(!r?.length)return;let c={};s.current=c,o(e=>({search:i,items:[],collections:[],...e,pagination:a>1?e?.pagination:void 0,loading:!0,error:void 0})),Promise.all([e.listContent({contentCollectionIds:r,sortBy:`order`,page:a,limit:20,search:i}),a>1?void 0:e.listContentCollections(r)]).then(([e,t])=>{s.current===c&&(o(n=>({search:i,items:[...a>1?n?.items??[]:[],...e.items],collections:t?.items??n?.collections??[],pagination:e.pagination,loading:!1})),a>1||(i?n.emit(`contentSearch`,{queryLength:i.length,hitCount:e.pagination.total}):n.emit(`contentView`,{section:`help`,count:e.items.length})))}).catch(e=>{s.current===c&&(kl.warn(`listContent (help) failed`,{err:e,page:a}),o(n=>n&&{...n,loading:!1,error:Sl(e,t)}))})}return u(()=>{if(!r?.length)o(void 0);else return l(1),()=>{s.current=void 0}},[e,c,i]),[a,()=>!a?.loading&&l((a?.pagination?.page??0)+1)]}function Ml(e){let{strings:t,config:n,nav:r,panelProps:i}=e,a=n.contentCollectionIds,[o,s]=h(``),[c,l]=h(``),d=jl(e,a),f=jl(e,c?a:void 0,c),[p,m]=o.trim()?f:d;u(()=>{let e=setTimeout(()=>l(o.trim()),300);return()=>clearTimeout(e)},[o]);function y(){if(!a?.length)return/* @__PURE__ */ _(cl,{message:t.helpEmpty,strings:t});let e=p?.error?/* @__PURE__ */ _(cl,{tone:`error`,message:p.error,onRetry:m,strings:t}):null;return e&&!p?.pagination?e:!p||!p.pagination&&!p.items.length?/* @__PURE__ */ _(cl,{message:t.helpLoading,strings:t}):p.items.length?/* @__PURE__ */ v(g,{children:[Al(p.items,a,p.collections).map(e=>/* @__PURE__ */ v(`section`,{class:`${Ol}-help-group`,children:[e.title?/* @__PURE__ */ _(`h2`,{class:`${Ol}-help-section-title`,children:e.title}):null,/* @__PURE__ */ _(`div`,{class:`${Ol}-help-card`,children:e.rows.map(e=>/* @__PURE__ */ _(Dl,{title:e.title,subtitle:e.description,onClick:()=>e.url?ws(e.url):r.push({kind:`content`,id:e.id,title:e.title}),testid:Pc(Y.helpArticle,e.id)},e.id))})]},e.id)),e,p.pagination?.hasNext&&!e?/* @__PURE__ */ _(`div`,{children:/* @__PURE__ */ _(`div`,{class:`${Ol}-help-card`,children:/* @__PURE__ */ v(`button`,{type:`button`,class:`${Ol}-list-row ${Ol}-help-more`,onClick:m,"aria-busy":p.loading,children:[p.loading?/* @__PURE__ */ _(`span`,{class:`${Ol}-loading-spinner`,"aria-hidden":`true`}):null,t.helpShowMore]})})}):null]}):/* @__PURE__ */ _(cl,{message:p.search?t.helpSearchEmpty.replace(`{query}`,p.search):t.helpEmpty,strings:t})}return/* @__PURE__ */ v(`div`,{class:`${Ol}-module`,children:[/* @__PURE__ */ _(Kc,{title:t.helpTitle,actions:/* @__PURE__ */ _(bl,{panelProps:i,variant:`plain`})}),/* @__PURE__ */ _(`div`,{class:`${Ol}-module-pad`,children:/* @__PURE__ */ _(Tl,{placeholder:t.helpSearchPlaceholder,value:o,onInput:s})}),/* @__PURE__ */ _(`div`,{class:`${Ol}-help-list`,children:y()})]})}const Nl={Icon:sc,Root:e=>/* @__PURE__ */ _(Ml,{...e})},Pl=R.scope(`attachments`);function Fl(e,t,n){let r=Bl(e),i=[],a=[],o=Gl(n.accept),s=t.reduce((e,t)=>e+t.size,0),c=t.length;for(let e of r){let t=zl(e,c,s,n,o);t?a.push({file:e,reason:t}):(i.push(Wl(e)),s+=e.size,c+=1)}return(i.length||a.length)&&Pl.debug(`ingest`,{accepted:i.length,rejected:a.map(e=>({name:e.file.name,reason:e.reason}))}),{accepted:i,rejected:a}}function Il(e){let t=Math.min(Math.floor(Math.log10(Math.max(e,1))/3),2);return new Intl.NumberFormat(void 0,{style:`unit`,unit:[`byte`,`kilobyte`,`megabyte`][t],unitDisplay:`narrow`,maximumFractionDigits:1}).format(e/1e3**t)}function Ll(e,t){let n=Gl(t);return!e||n.length===0||n.some(t=>t.kind===`ext`||Kl(new File([],``,{type:e}),[t]))}function Rl(e){try{URL.revokeObjectURL(e.previewUrl)}catch(e){Pl.debug(`revokeObjectURL failed`,{error:e})}}function zl(e,t,n,r,i){return t>=r.maxCount?`count`:n+e.size>r.maxBytes?`bytes`:Kl(e,i)?null:`mime`}function Bl(e){return e?Array.isArray(e)?e.filter(e=>e instanceof File):[...e].map(e=>e instanceof File?e:Vl(e)).filter(e=>e!==null):[]}function Vl(e){let t=Hl(e)?e:null;return!t?.getAsFile||t.kind!==`file`?null:t.getAsFile()}function Hl(e){return Ul(e)&&(e.getAsFile===void 0||typeof e.getAsFile==`function`)}function Ul(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wl(e){return{file:e,id:Ut(),mediaType:e.type||`application/octet-stream`,name:e.name||`pasted-file`,previewUrl:URL.createObjectURL(e),size:e.size}}function Gl(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 Kl(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===`image`&&e.subtype===`*`&&/\.(heic|heif|avif|bmp|tif|tiff)$/.test(i)?!0:(e.type===`*`||e.type===n)&&(e.subtype===`*`||e.subtype===r))}const ql=N.cssPrefix,Jl={error:Mc,done:Zs};function Yl({attachment:e,upload:t,strings:n,onRemove:r,disabled:i=!1}){let a=/^image\/(jpeg|png|gif|webp|avif|bmp|x-ms-bmp|svg\+xml)$/i.test(e.mediaType),o=Math.round((t?.fraction??0)*100),s=Il(e.size),c=t?.status===`error`||t?.status===`done`?Jl[t.status]:void 0;return/* @__PURE__ */ v(`span`,{class:`${ql}-attachment-chip`,"data-upload":t?.status,title:e.name,"data-testid":Pc(Y.attachmentChip,e.id),children:[a?/* @__PURE__ */ _(`img`,{class:`${ql}-attachment-thumb`,src:e.previewUrl,alt:``}):/* @__PURE__ */ _(`span`,{class:`${ql}-attachment-thumb`,"aria-hidden":`true`,children:/* @__PURE__ */ _(ic,{})}),/* @__PURE__ */ v(`span`,{class:`${ql}-attachment-text`,children:[/* @__PURE__ */ _(`span`,{class:`${ql}-attachment-name`,children:e.name}),/* @__PURE__ */ v(`span`,{class:`${ql}-attachment-meta`,children:[c?/* @__PURE__ */ _(c,{}):null,t?.status===`uploading`?`${o}% · ${s}`:s]})]}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${ql}-attachment-remove`,onClick:r,disabled:i,"aria-label":n.removeAttachment.replace(`{name}`,e.name),"data-testid":Pc(Y.attachmentRemove,e.id),children:/* @__PURE__ */ _(js,{})}),t?.status===`uploading`?/* @__PURE__ */ _(`span`,{class:`${ql}-attachment-progress`,role:`progressbar`,"aria-label":e.name,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":o,children:/* @__PURE__ */ _(`span`,{style:{width:`${o}%`}})}):null]})}const Xl=/* @__PURE__ */ new WeakMap;function Zl(e){e.currentTarget&&Xl.set(e.currentTarget,e.timeStamp)}function Ql(e){let t=e.currentTarget?Xl.get(e.currentTarget):void 0;return e.isComposing||t!==void 0&&e.timeStamp-t<100}const $l=N.cssPrefix;function eu({text:e,retryLabel:t,onRetry:n,retryTestId:r}){return/* @__PURE__ */ v(`div`,{class:`${$l}-error`,role:`alert`,children:[/* @__PURE__ */ _(`span`,{class:`${$l}-error-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Mc,{})}),/* @__PURE__ */ _(`span`,{class:`${$l}-error-text`,children:e}),n&&t?/* @__PURE__ */ _(`button`,{type:`button`,class:`${$l}-error-retry`,onClick:n,"data-testid":r,children:t}):null]})}const tu={isSupported:!1,start:()=>void 0,stop:()=>void 0,cancel:()=>void 0};function nu(e,t,n){return e===`disabled`?tu:e===`server`?ou(n):ru(t)}function ru(e){let t=iu();if(!t)return tu;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)});function u(e){l||r!==s||n!==c||(l=!0,n=null,a(e))}c.addEventListener(`end`,()=>u(!1)),c.addEventListener(`error`,e=>u(`error`in e&&(e.error===`not-allowed`||e.error===`service-not-allowed`)));try{c.start()}catch{u(!1)}},stop(){n?.stop()},cancel(){r++;let e=n;n=null,e?.abort()}}}function iu(){return window.SpeechRecognition??window.webkitSpeechRecognition}const au=[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/mp4`];function ou(e){if(typeof MediaRecorder>`u`||!navigator?.mediaDevices?.getUserMedia)return tu;let t=0,n=null;function r(e){for(let t of e.stream?.getTracks()??[])t.stop();e.stream=null}function i(){t++;let e=n;n=null,e&&(r(e),e.recorder?.state!==`inactive`&&e.recorder?.stop())}async function a(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(!1))}}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=su(),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(e){r(s),n===s&&t===s.generation&&(n=null,o(e instanceof DOMException&&e.name===`NotAllowedError`))}},stop(){let e=n;e&&(e.recorder?e.recorder.state!==`inactive`&&e.recorder.stop():i())},cancel(){i()}}}function su(){for(let e of au)if(MediaRecorder.isTypeSupported(e))return e}function cu(e,{file:t,reason:n},r){return n===`count`?e.attachmentTooMany.replace(`{count}`,String(r.maxCount)):n===`bytes`?e.attachmentTooLarge.replace(`{name}`,t.name).replace(`{max}`,Il(r.maxBytes)):e.attachmentMimeRejected.replace(`{name}`,t.name)}const lu=N.cssPrefix,uu=R.scope(`composer`);function du(e){return e.reduce((e,t)=>e+t.size,0)}const fu={arrowUp:Ps,paperPlane:Ns,send:Fs,chevron:Is};function pu(e){return`activeElement`in e}function mu(e){return`host`in e&&`activeElement`in e}function hu(e){return`clipboardData`in e}function gu({options:e,transport:t,feedback:n,bus:r,persistence:i,conversationId:a,maxMessageCharacters:o,isStreaming:s,pageToolRunning:c=!1,isMemoryCompacting:d=!1,canReleaseQueuedMessages:p=!0,queueManualMessages:g=!1,replyAwaitsCard:y=!1,active:b=!0,isPreparing:x=!1,attachmentUploadsSig:S,operatorRequestEnabled:C,canRequestOperator:w=!1,controlMode:T=`ai-agent`,onRequestOperator:E,onSend:D,onStop:O,apiRef:k}){let A=e.strings,[j,ee]=h(()=>i.loadDraft(a)),[M,te]=h([]),[N,ne]=h(),[re,ie]=h(()=>i.loadMessageQueue(a).map(e=>({id:e.id,text:e.text,attachments:[]}))),P=m(re),ae=m(!1),oe=m(void 0),[F,se]=h(!1),[ce,le]=h(!1),[ue,de]=h(!1),[I,fe]=h(!1),pe=m(!1),me=m(null),he=m(null),ge=m(null),_e=m(0),ve=m(a);ve.current=a;let L=m(b);L.current=b;let ye=m(x);ye.current=x;let be=I||x||!b,xe=s&&T===`ai-agent`,Se=xe||d&&T===`ai-agent`,Ce=T===`ai-agent`&&(Se||g||re.length>0),we=l(e=>{ie(t=>{let n=e(t);return i.saveMessageQueue(ve.current,n.filter(e=>e.attachments.length===0).map(({id:e,text:t})=>({id:e,text:t}))),P.current=n,n})},[i]),Te=l(e=>{we(t=>(t.find(t=>t.id===e)?.attachments.forEach(Rl),t.filter(t=>t.id!==e)))},[we]),Ee=l(e=>{ee(t=>{let n=(typeof e==`function`?e(t):e).slice(0,o);return n===t?t:(i.saveDraft(ve.current,n),n)})},[i,o]),De=e.features.fileUpload,Oe=e.features.voice,[ke,Ae]=h(()=>nu(Oe,e.locale,(e,n)=>t.transcribe(e,n))),je=m(ke);je.current=ke;let Me=m({mode:Oe,locale:e.locale,transport:t});u(()=>{let n=Me.current;(n.mode!==Oe||n.locale!==e.locale||n.transport!==t)&&(Me.current={mode:Oe,locale:e.locale,transport:t},_e.current++,je.current.cancel(),ge.current=null,le(!1),Ae(nu(Oe,e.locale,(e,n)=>t.transcribe(e,n))))},[e.locale,Oe,t]),f(()=>()=>{_e.current++,ke.cancel()},[ke]);let Ne=l(e=>{let t=ge.current;if(t===null)return!1;let n=Math.round(performance.now()-t);return uu[e](`voiceStop`,{durationMs:n}),r.emit(`voiceStop`,{durationMs:n}),ge.current=null,!0},[r]),Pe=l(()=>{ge.current!==null&&(ke.stop(),le(!1),Ne(`info`)&&n.play(`voiceStop`))},[Ne,n,ke]),Fe=l(()=>{_e.current++,ke.cancel(),le(!1),Ne(`info`)&&n.play(`voiceStop`)},[Ne,n,ke]);u(()=>{(x||!b)&&Fe()},[b,Fe,x]),u(()=>{let e=me.current;if(!e)return;let t=e.getRootNode(),n=pu(t)?t.activeElement:null;n&&e.closest(`.${lu}-panel`)?.contains(n)||e.focus({preventScroll:!0})},[]),u(()=>{let e=me.current;if(!e)return;if(j.length===0){e.style.height=``;return}e.style.height=`auto`;let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--${lu}-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`},[j]);let Ie=m(M);Ie.current=M,u(()=>()=>{Ie.current.forEach(Rl);for(let e of P.current)e.attachments.forEach(Rl)},[]),f(()=>{if(k)return k.current={attachFromDrop:t=>{if(!De||!L.current||pe.current||ye.current)return;let n=Fl(t,Ie.current,e.attachments);ne(n.rejected[0]),n.accepted.length!==0&&(uu.info(`attach (drop)`,{count:n.accepted.length,totalBytes:du(n.accepted)}),r.emit(`attach`,{count:n.accepted.length,totalBytes:du(n.accepted)}),te(e=>[...e,...n.accepted]))},fill:e=>{if(!L.current||pe.current||ye.current)return;Ee(e);let t=me.current;t&&(t.focus({preventScroll:!0}),requestAnimationFrame(()=>t.setSelectionRange(t.value.length,t.value.length)))},acceptQueuedMessage:Te},()=>{k.current&&(k.current=null)}},[k,De,x,e.attachments,Te,Ee]),u(()=>{let t=me.current;if(!t)return;let n=t.closest(`.${lu}-panel`);if(!n)return;let i=n=>{if(!L.current||pe.current||ye.current)return;let i=n.clipboardData;if(!i)return;let a=n.target instanceof HTMLElement?n.target.closest(`input, textarea, [contenteditable]:not([contenteditable='false'])`):null;if(a&&a!==t)return;if(De){let t=Fl(i.items,Ie.current,e.attachments);if(ne(t.rejected[0]),t.accepted.length>0){n.preventDefault(),uu.info(`attach (paste)`,{count:t.accepted.length,totalBytes:du(t.accepted)}),r.emit(`attach`,{count:t.accepted.length,totalBytes:du(t.accepted)}),te(e=>[...e,...t.accepted]);return}}if(a===t)return;let o=i.getData(`text/plain`);o&&(n.preventDefault(),Ee(e=>e+o),t.focus())};function a(e){hu(e)&&i(e)}return n.addEventListener(`paste`,a),()=>n.removeEventListener(`paste`,a)},[De,e.attachments,Ee]);async function Le(){let e=j.trim();if(!e&&M.length===0||!b||xe||pe.current||x)return;Fe(),pe.current=!0,fe(!0);let t=j,n=M;try{await D(e,n)&&(ne(void 0),Ee(e=>e===t?``:e),te(e=>e===n?(n.forEach(Rl),Ie.current=[],[]):e))}finally{pe.current=!1,fe(!1),requestAnimationFrame(()=>{let e=me.current;if(!e||e.disabled||!L.current)return;let t=e.getRootNode(),n=pu(t)?t.activeElement:null,r=n?.getAttribute(`data-testid`);if(!(n&&n!==e&&r!==Y.composerSend&&r!==Y.composerStop)){if(mu(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})}})}}function Re(){let e=j.trim();if(!e&&M.length===0||!b||!Ce||pe.current||x)return;Fe();let t=M;we(n=>[...n,{id:Ut(),text:e,attachments:t}]),Se||se(!0),Ee(``),te(e=>e===t?(Ie.current=[],[]):e),me.current?.focus({preventScroll:!0})}u(()=>{Se&&(ae.current=!1,oe.current=void 0,se(!1))},[Se]),u(()=>{let t=re[0];if(!t||!p||Se||ae.current||I||x||!b)return;let n=y&&!F?(oe.current??(oe.current=performance.now()+e.cardAnswerWaitSeconds*1e3))-performance.now():0,r=setTimeout(()=>{ae.current=!0,D(t.text,t.attachments,t.id).then(e=>{e?Te(t.id):ae.current=!1})},Math.max(n,300));return()=>clearTimeout(r)},[b,p,F,x,D,e.cardAnswerWaitSeconds,Se,re,Te,y,I]);function ze(e){e.key!==`Enter`||e.shiftKey||Ql(e)||(e.preventDefault(),Ce&&(j.trim()||M.length>0)?Re():xe?O():Le())}function Be(t){if(!(t.target instanceof HTMLInputElement))return;let n=t.target;if(!b||pe.current||x){n.value=``;return}let i=Fl(n.files,M,e.attachments);ne(i.rejected[0]),i.accepted.length>0&&(uu.info(`attach (file picker)`,{count:i.accepted.length,totalBytes:du(i.accepted)}),r.emit(`attach`,{count:i.accepted.length,totalBytes:du(i.accepted)}),te(e=>[...e,...i.accepted])),n.value=``}function Ve(e){!b||pe.current||x||(uu.info(`removeAttachment`,{id:e}),r.emit(`removeAttachment`,{id:e}),ne(void 0),te(t=>{let n=t.find(t=>t.id===e);return n&&Rl(n),t.filter(t=>t.id!==e)}))}function He(){if(ce){Pe();return}if(!b||!ke.isSupported||pe.current||x)return;let e=++_e.current;ge.current=performance.now(),uu.info(`voiceStart`),r.emit(`voiceStart`,void 0),de(!1),le(!0),n.play(`voiceStart`),ke.start((t,n)=>{_e.current===e&&L.current&&!ye.current&&!pe.current&&n&&Ee(e=>`${e}${t} `)},t=>{_e.current===e&&L.current&&(le(!1),de(t),Ne(`debug`))})}let Ue=fu[e.composer.sendButton.icon],We=!!(j.trim()||M.length>0),Ge=S?.value,Ke=M.some(e=>Ge?.get(e.id)?.status===`uploading`),qe=M.filter(e=>Ge?.get(e.id)?.status===`error`),Je=qe.find(e=>Ge?.get(e.id)?.refusal),R=Je&&(Ge?.get(Je.id)?.refusal===`INVALID_FILE_TYPE`?A.attachmentMimeRejected:A.attachmentUploadFailed).replace(`{name}`,Je.name),Ye=xe||Ke||c&&!We;return/* @__PURE__ */ v(`div`,{class:`${lu}-composer`,part:`composer`,"data-testid":Y.composer,children:[re.length>0?/* @__PURE__ */ _(`div`,{class:`${lu}-message-queue`,"aria-label":A.queueMessage,"data-testid":Y.messageQueue,children:re.map(e=>/* @__PURE__ */ v(`div`,{class:`${lu}-attachment-chip ${lu}-queued-message`,"data-testid":`${Y.queuedMessage}-${e.id}`,children:[/* @__PURE__ */ _(`span`,{class:`${lu}-attachment-name ${lu}-queued-text`,children:e.text||e.attachments.map(e=>e.name).join(`, `)}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-attachment-remove`,onClick:()=>Te(e.id),"aria-label":A.removeQueuedMessage,title:A.removeQueuedMessage,"data-testid":`${Y.queuedMessageRemove}-${e.id}`,children:/* @__PURE__ */ _(js,{})})]},e.id))}):null,M.length>0?/* @__PURE__ */ _(`div`,{class:`${lu}-attachments`,children:M.map(e=>/* @__PURE__ */ _(Yl,{attachment:e,upload:Ge?.get(e.id),strings:A,onRemove:()=>Ve(e.id),disabled:be},e.id))}):null,qe.length>0&&!be?/* @__PURE__ */ _(eu,{text:R??A.attachmentUploadFailed.replace(`{name}`,qe.map(e=>e.name).join(`, `)),retryLabel:A.errorRetry,onRetry:Je?void 0:()=>void Le(),retryTestId:Y.attachmentRetry}):null,N?/* @__PURE__ */ _(`p`,{class:`${lu}-field-error`,role:`alert`,children:cu(A,N,e.attachments)}):null,ue?/* @__PURE__ */ _(`p`,{class:`${lu}-field-error`,role:`alert`,children:A.micBlocked}):null,o!==void 0&&j.length>=o*.9?/* @__PURE__ */ _(`p`,{class:`${lu}-field-${j.length<o?`hint`:`error`}`,"data-testid":Y.composerCount,children:`${j.length} / ${o}`}):null,/* @__PURE__ */ v(`div`,{class:`${lu}-composer-row`,children:[/* @__PURE__ */ v(`div`,{class:`${lu}-composer-actions`,children:[De?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-icon-btn`,onClick:()=>he.current?.click(),disabled:be,"aria-label":A.attach,title:A.attach,"data-testid":Y.composerAttach,children:/* @__PURE__ */ _(Rs,{})}):null,ke.isSupported?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-icon-btn`,onClick:He,disabled:be,"aria-label":ce?A.micStop:A.micStart,title:ce?A.micStop:A.micStart,"aria-pressed":ce,"data-recording":ce?`true`:void 0,"data-testid":Y.composerVoice,children:/* @__PURE__ */ _(zs,{})}):null,C&&T===`ai-agent`&&E?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-icon-btn`,onClick:E,disabled:be||!w,"aria-label":A.talkToOperator,title:A.talkToOperator,"data-testid":Y.operatorRequest,children:/* @__PURE__ */ _(Bs,{})}):null]}),/* @__PURE__ */ _(`textarea`,{ref:me,name:`message`,class:`${lu}-textarea`,rows:1,value:j,maxLength:o,placeholder:A.composerPlaceholder,onInput:e=>Ee(e.currentTarget.value),onKeyDown:ze,onCompositionEnd:Zl,disabled:be,"aria-label":A.composerPlaceholder,"data-testid":Y.composerInput}),Ce&&We?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:Re,disabled:be,"aria-label":A.queueMessage,title:A.queueMessage,"data-testid":Y.composerSend,children:/* @__PURE__ */ _(Ue,{})}):null,Ye?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-send`,onClick:O,disabled:be&&!Ke,"aria-label":A.stop,"data-testid":Y.composerStop,children:/* @__PURE__ */ _(Ls,{})}):null,!Ye&&(!Ce||!We)?/* @__PURE__ */ _(`button`,{type:`button`,class:`${lu}-send`,"data-shape":e.composer.sendButton.shape,"data-variant":e.composer.sendButton.variant,onClick:()=>void Le(),disabled:be||!j.trim()&&M.length===0,"aria-label":A.send,"data-testid":Y.composerSend,children:/* @__PURE__ */ _(Ue,{})}):null]}),/* @__PURE__ */ _(`input`,{ref:he,name:`attachments`,type:`file`,multiple:!0,accept:e.attachments.accept,onChange:Be,disabled:be,class:`${lu}-sr-only`,"data-testid":Y.composerFileInput})]})}const _u=N.cssPrefix;function vu({onClick:e,children:t,testid:n}){return e?/* @__PURE__ */ _(`button`,{type:`button`,class:`${_u}-home-card`,"data-interactive":`true`,onClick:e,"data-testid":n,children:t}):/* @__PURE__ */ _(`div`,{class:`${_u}-home-card`,"data-testid":n,children:t})}function yu(e){return e.trim().split(/\s+/).slice(0,2).map(e=>e.charAt(0).toUpperCase()).join(``)}const bu=N.cssPrefix,xu=R.scope(`news`);function Su(e,t){let n=e?new Date(e):void 0;if(n&&!Number.isNaN(n.getTime()))return new Intl.DateTimeFormat(t,{dateStyle:`medium`}).format(n)}function Cu({options:e,transport:t,strings:n,config:r,nav:i,bus:a,panelProps:o,latestNews:s}){let c=r.contentCollectionIds,l=c?.join(`,`),[d,f]=h({items:[],loading:!0}),p=m(void 0);function g(e){if(!c?.length)return;let r={};p.current=r,f(e=>({...e,loading:!0,error:void 0})),t.listContent({contentCollectionIds:c,sortBy:`publishedAt`,sortOrder:`desc`,page:e,limit:10}).then(t=>{if(p.current!==r||(f(n=>({items:e>1?[...n.items,...t.items]:t.items,pagination:t.pagination,loading:!1})),e>1))return;a.emit(`contentView`,{section:`news`,count:t.items.length});let n=t.items[0];n&&s.markSeen(n.id)}).catch(t=>{p.current===r&&(xu.warn(`listContent (news) failed`,{err:t,page:e}),f(e=>({...e,loading:!1,error:Sl(t,n)})))})}function y(){d.loading||g((d.pagination?.page??0)+1)}u(()=>(f({items:[],loading:!0}),g(1),()=>{p.current=void 0}),[t,l]);function b(t){let n=Su(t.publishedAt,e.locale);return/* @__PURE__ */ v(`button`,{type:`button`,class:`${bu}-news-card`,onClick:()=>i.push({kind:`content`,id:t.id,title:t.title}),"data-testid":Pc(Y.newsItem,t.id),children:[t.image?/* @__PURE__ */ _(`img`,{class:`${bu}-news-hero`,src:t.image,alt:``,loading:`lazy`}):null,/* @__PURE__ */ v(`span`,{class:`${bu}-news-body`,children:[/* @__PURE__ */ _(`span`,{class:`${bu}-news-title`,children:t.title}),n||t.tags?.length?/* @__PURE__ */ v(`span`,{class:`${bu}-news-meta`,children:[n?/* @__PURE__ */ _(`time`,{dateTime:t.publishedAt,children:n}):null,t.tags?.map(e=>/* @__PURE__ */ _(`span`,{class:`${bu}-news-tag`,children:e},e))]}):null,t.description?/* @__PURE__ */ _(`span`,{class:`${bu}-news-summary`,children:t.description}):null]})]},t.id)}function x(){if(!c?.length)return/* @__PURE__ */ _(cl,{message:n.newsEmpty,strings:n});let e=d.error?/* @__PURE__ */ _(cl,{tone:`error`,message:d.error,onRetry:y,strings:n}):null;return e&&!d.pagination?e:d.pagination?d.items.length?/* @__PURE__ */ v(`div`,{class:`${bu}-news-list`,children:[d.items.map(b),e,d.pagination.hasNext&&!e?/* @__PURE__ */ v(`button`,{type:`button`,class:`${bu}-news-more`,onClick:y,"aria-busy":d.loading,"data-testid":Y.newsMore,children:[d.loading?/* @__PURE__ */ _(`span`,{class:`${bu}-loading-spinner`,"aria-hidden":`true`}):null,n.newsShowMore]}):null]}):/* @__PURE__ */ _(cl,{message:n.newsEmpty,strings:n}):/* @__PURE__ */ _(cl,{message:n.newsLoading,strings:n})}return/* @__PURE__ */ v(`div`,{class:`${bu}-module`,children:[/* @__PURE__ */ _(Kc,{title:n.newsTitle,actions:/* @__PURE__ */ _(bl,{panelProps:o,variant:`plain`})}),/* @__PURE__ */ _(`div`,{class:`${bu}-module-scroll`,children:x()})]})}const wu={Icon:hc,Root:e=>/* @__PURE__ */ _(Cu,{...e})},X=N.cssPrefix,Tu=R.scope(`home`);function Eu(e){let t=e.options.userContext?.name,n=e.config.greetingText?M(e.strings,e.config.greetingText):void 0;if(n){let r=t?n.replace(`{name}`,t):n.replace(/\s*\{name\}\s*/,` `).trim(),i=e.strings.homeGreetingLead;return{title:r,subtitle:r.toLowerCase()===i.toLowerCase()?void 0:i}}return t?{title:e.strings.homeGreetingNamed.replace(`{name}`,t),subtitle:e.strings.homeGreetingLead}:{title:e.strings.homeGreeting}}function Du(e,t){return t.url?ws(t.url):e.push({kind:`content`,id:t.id,title:t.title})}function Ou({options:e,onAsk:t}){let[n,r]=h(``),{sendButton:i}=e.composer,a=fu[i.icon];function o(e){e.preventDefault();let i=n.trim();i&&(r(``),t(i))}return/* @__PURE__ */ v(`form`,{class:`${X}-home-search ${X}-home-ask`,"data-input":`true`,onSubmit:o,"data-testid":Y.homeAsk,children:[/* @__PURE__ */ _(`input`,{type:`text`,class:`${X}-home-search-input`,placeholder:e.strings.homeAskPlaceholder,"aria-label":e.strings.homeAskPlaceholder,value:n,enterKeyHint:`send`,onInput:e=>r(e.currentTarget.value)}),/* @__PURE__ */ _(`button`,{type:`submit`,class:`${X}-send`,"data-shape":i.shape,"data-variant":i.variant,disabled:!n.trim(),"aria-label":e.strings.send,children:/* @__PURE__ */ _(a,{})})]})}function ku(e,t){return Go(e,t,t.type!==`upsert`||t.activity===!0)}function Au(e){let{transport:t,strings:n,config:r,nav:i,bus:a,panelProps:o,latestNews:s}=e,[c,l]=h(null),[d,f]=h([]),p=r.contentCollectionIds?.join(`,`),m=e.options.modules.list.some(e=>e.layout===`chat`);u(()=>{if(r.showRecentConversations===!1)return;let e=!1,n=!0,i=[],a=t.subscribeConversationChanges(e=>{n&&i.push(e),l(t=>ku(t?[t]:[],e)[0]??null)});return t.listConversations({limit:m?50:1}).then(t=>{if(e)return;let r=i.reduce(ku,t.conversations);i=[],n=!1,l(r[0]??null)}).catch(t=>{e||(i=[],n=!1,Tu.warn(`listConversations (home) failed`,{err:t}))}),()=>{e=!0,a()}},[t,r.showRecentConversations,m]),u(()=>{if(!r.contentCollectionIds?.length)return;let e=!1;return t.listContent({contentCollectionIds:r.contentCollectionIds,pinned:!0,limit:6}).then(t=>{e||(f(t.items),a.emit(`contentView`,{section:`home`,count:t.items.length}))}).catch(t=>!e&&Tu.warn(`listContent (home) failed`,{err:t})),()=>{e=!0}},[t,p,a]);let y=Eu(e),b=r.userAvatars??[],x=r.status,S=x?.text?M(n,x.text):n.homeStatus,C=x?.url,w=r.contentBlockTitle?M(n,r.contentBlockTitle):n.homeContentTitle,T=s.item,E=Su(T?.publishedAt,e.options.locale);return/* @__PURE__ */ _(`div`,{class:`${X}-module ${X}-home`,"data-testid":Y.homeView,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-scroll`,children:[/* @__PURE__ */ v(`div`,{class:`${X}-home-hero`,children:[/* @__PURE__ */ v(`div`,{class:`${X}-home-hero-top`,children:[r.brandName?/* @__PURE__ */ _(`span`,{class:`${X}-home-brand`,"data-testid":Y.homeBrand,children:r.brandName}):/* @__PURE__ */ _(`span`,{class:`${X}-home-brand-spacer`,"aria-hidden":`true`}),/* @__PURE__ */ v(`div`,{class:`${X}-home-hero-actions`,children:[b.length>0?/* @__PURE__ */ _(`div`,{class:`${X}-home-avatars`,children:b.map(e=>/* @__PURE__ */ _(`span`,{class:`${X}-home-avatar`,title:e.role?`${e.name} · ${e.role}`:e.name,children:e.avatar?/* @__PURE__ */ _(`img`,{src:e.avatar,alt:``,loading:`lazy`}):/* @__PURE__ */ _(`span`,{children:yu(e.name)})},e.name))}):null,/* @__PURE__ */ _(bl,{panelProps:o,variant:`plain`})]})]}),r.showGreeting===!1?null:/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`h1`,{class:`${X}-home-greeting`,"data-testid":Y.homeGreeting,children:y.title}),y.subtitle?/* @__PURE__ */ _(`p`,{class:`${X}-home-lead`,children:y.subtitle}):null]})]}),/* @__PURE__ */ v(`div`,{class:`${X}-home-cards`,children:[m?/* @__PURE__ */ _(Ou,{options:e.options,onAsk:e=>i.startNewConversation(e)}):null,r.showSearchBar===!1?null:/* @__PURE__ */ _(wl,{placeholder:n.homeSearchPlaceholder,onActivate:()=>i.switchToLayout(`help`)}),T?/* @__PURE__ */ _(vu,{onClick:()=>{s.markSeen(T.id),i.push({kind:`content`,id:T.id,title:T.title})},testid:Y.homeWhatsNew,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-recent-row`,"data-unread":s.unseen?`true`:void 0,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-avatar`,"aria-hidden":`true`,children:/* @__PURE__ */ _(hc,{})}),/* @__PURE__ */ v(`span`,{class:`${X}-home-recent-body`,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-title`,children:n.homeWhatsNew}),/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-preview`,children:E?`${T.title} · ${E}`:T.title})]}),s.unseen?/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-dot`,role:`img`,"aria-label":n.newsUnseen}):null]})}):null,c?/* @__PURE__ */ _(vu,{onClick:()=>i.selectConversation(c),testid:Y.homeRecent,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-recent-row`,"data-unread":c.hasUnread?`true`:void 0,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-avatar`,"aria-hidden":`true`,children:/* @__PURE__ */ _(gc,{})}),/* @__PURE__ */ v(`span`,{class:`${X}-home-recent-body`,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-title`,children:c.title}),c.preview?/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-preview`,children:ol(c.preview)}):null]}),c.hasUnread?/* @__PURE__ */ _(`span`,{class:`${X}-home-recent-dot`,role:`img`,"aria-label":n.unread}):null]})}):null,x?/* @__PURE__ */ _(vu,{onClick:C?()=>ws(C):void 0,children:/* @__PURE__ */ v(`div`,{class:`${X}-home-status`,"data-level":x.level??`operational`,children:[/* @__PURE__ */ _(`span`,{class:`${X}-home-status-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(pc,{})}),/* @__PURE__ */ _(`span`,{class:`${X}-home-status-text`,children:S})]})}):null,d.length>0?/* @__PURE__ */ v(`section`,{class:`${X}-home-content`,children:[/* @__PURE__ */ _(`div`,{class:`${X}-home-content-title`,children:w}),/* @__PURE__ */ _(`div`,{class:`${X}-home-content-list`,children:d.map(e=>/* @__PURE__ */ _(Dl,{title:e.title,subtitle:e.description,onClick:()=>Du(i,e),testid:Pc(Y.homeContentRow,e.id)},e.id))})]}):null]})]})})}const ju={chat:xl,home:{Icon:mc,Root:e=>/* @__PURE__ */ _(Au,{...e})},help:Nl,news:wu},Mu=N.cssPrefix;function Nu({modules:e,activeTab:t,strings:n,hasUnread:r,onSelect:i}){return/* @__PURE__ */ _(`nav`,{class:`${Mu}-tabbar`,role:`tablist`,"aria-label":n.panelTitle,children:e.map(e=>{let a=ju[e.layout].Icon,o=e.id===t,s=e.layout===`chat`&&r;return/* @__PURE__ */ v(`button`,{type:`button`,role:`tab`,"aria-selected":o,class:`${Mu}-tab`,onClick:()=>i(e.id),"data-testid":Pc(Y.tab,e.id),children:[/* @__PURE__ */ v(`span`,{class:`${Mu}-tab-icon`,children:[/* @__PURE__ */ _(a,{}),s?/* @__PURE__ */ _(`span`,{class:`${Mu}-tab-badge`,"data-testid":Y.tabBadge,role:`img`,"aria-label":n.unread}):null]}),/* @__PURE__ */ _(`span`,{class:`${Mu}-tab-label`,children:M(n,e.label)})]},e.id)})})}const Pu=N.cssPrefix;function Fu({agent:e,strings:t,ticketReference:n,person:r=!1}){let i=e.status??`online`,a=M(t,e.name),o=e.title?M(t,e.title):null,s=r?/* @__PURE__ */ _(Bs,{}):/* @__PURE__ */ _(`span`,{children:yu(a)});return/* @__PURE__ */ v(`div`,{class:`${Pu}-agent`,children:[/* @__PURE__ */ _(`div`,{class:`${Pu}-agent-avatar`,"data-status":i,children:e.avatar?/* @__PURE__ */ _(`img`,{src:e.avatar,alt:``}):s}),/* @__PURE__ */ v(`div`,{class:`${Pu}-agent-meta`,children:[/* @__PURE__ */ _(`strong`,{children:a}),o||n?/* @__PURE__ */ v(`div`,{class:`${Pu}-agent-sub`,children:[n?/* @__PURE__ */ _(Iu,{reference:n,strings:t}):null,o?/* @__PURE__ */ _(`span`,{children:o}):null]}):null]})]})}function Iu({reference:e,strings:t}){let[n,r]=h(!1);function i(){navigator.clipboard?.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})}return/* @__PURE__ */ _(`button`,{type:`button`,class:`${Pu}-agent-ticket`,onClick:i,title:t.copy,"aria-label":n?t.copied:t.copyTicketReference.replace(`{reference}`,e),children:n?t.copied:e})}const Lu=[`today`,`yesterday`,`lastWeek`,`older`];function Ru(e,t){let n=Date.parse(t);if(!Number.isFinite(n))return`older`;let r=Math.round((Bu(e)-Bu(n))/864e5);return r<=0?`today`:r===1?`yesterday`:r<7?`lastWeek`:`older`}function zu(e,t){let n=/* @__PURE__ */ new Map;for(let r of t){let t=Ru(e,r.lastMessageAt),i=n.get(t);i?i.push(r):n.set(t,[r])}return Lu.flatMap(e=>{let t=n.get(e);return t?[{bucket:e,conversations:t}]:[]})}function Bu(e){return new Date(e).setHours(0,0,0,0)}const Vu=R.scope(`history`),Hu={today:`dateToday`,yesterday:`dateYesterday`,lastWeek:`dateLastWeek`,older:`dateOlder`};function Uu(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=Go(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=Go(e.conversations,t,n);return r===e.conversations?e:{...t.type===`snapshot`?t.result:e,conversations:r}}function Wu(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<6048e5?new Intl.DateTimeFormat(n,{weekday:`short`}).format(r):new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`}).format(r):``}function Gu({transport:e,strings:t,locale:n,persistence:r,onSelect:i,onNewConversation:a}){let o=N.cssPrefix,s=e.peekConversations({limit:50}),[c,l]=h(s?`loaded`:`loading`),[d,f]=h(0),[p,y]=h(s),[b,x]=h(!1),S=m(void 0),C=p?.conversations??[],w=p?.pagination;u(()=>{let n=!1,i=!0,a=[],o=e.subscribeConversationChanges(e=>{i&&a.push(e),y(t=>t&&Uu(t,e))});S.current=void 0,x(!1);let s=e.peekConversations({limit:50});return y(s),l(s?`loaded`:`loading`),e.listConversations({limit:50}).then(e=>{if(n)return;let t=e;for(let e of a)t=Uu(t,e);a=[],i=!1,y(t),l(`loaded`),r.saveHistoryCount(t.conversations.length)}).catch(e=>{n||(a=[],i=!1,Vu.warn(`listConversations failed`,{err:e}),l({failure:Sl(e,t)}))}),()=>{n=!0,o(),S.current=void 0}},[e,r,n,d]);async function T(){if(S.current||!w?.hasNext)return;let t={};S.current=t,x(!0);try{let n=await e.listConversations({page:w.page+1,limit:w.limit});if(S.current!==t)return;y(e=>{if(!e)return e;let t=new Set(e.conversations.map(e=>e.conversationId)),i=n.conversations.filter(e=>!t.has(e.conversationId)&&(t.add(e.conversationId),!0)),a={conversations:[...e.conversations,...i],pagination:n.pagination};return r.saveHistoryCount(a.conversations.length),a})}catch(e){if(S.current!==t)return;Vu.warn(`listConversations page failed`,{err:e,page:w.page+1})}finally{S.current===t&&(S.current=void 0,x(!1))}}let E=a?/* @__PURE__ */ _(`div`,{class:`${o}-history-footer`,children:/* @__PURE__ */ v(`button`,{type:`button`,class:`${o}-history-new`,onClick:a,"data-testid":Y.sidebarNewConversation,children:[/* @__PURE__ */ _(Ms,{}),t.newConversation]})}):null;if(c===`loading`){let e=Math.min(r.loadHistoryCount()??3,6);return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`div`,{class:`${o}-history`,"aria-busy":`true`,"aria-label":t.historyLoading,children:/* @__PURE__ */ v(`div`,{class:`${o}-history-group`,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`div`,{class:`${o}-history-heading`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-heading`})}),/* @__PURE__ */ _(`div`,{class:`${o}-history-card`,children:Array.from({length:Math.max(1,e)},(e,t)=>/* @__PURE__ */ v(`div`,{class:`${o}-history-item ${o}-history-item-skeleton`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-avatar ${o}-skeleton`}),/* @__PURE__ */ v(`span`,{class:`${o}-history-body`,children:[/* @__PURE__ */ v(`span`,{class:`${o}-history-row`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-title`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-title`})}),/* @__PURE__ */ _(`span`,{class:`${o}-history-time`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-time`})})]}),/* @__PURE__ */ _(`span`,{class:`${o}-history-row`,children:/* @__PURE__ */ _(`span`,{class:`${o}-history-preview`,children:/* @__PURE__ */ _(`span`,{class:`${o}-skeleton ${o}-skeleton-preview`})})})]})]},t))})]})}),E]})}if(typeof c==`object`)return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(cl,{tone:`error`,message:c.failure,onRetry:()=>f(e=>e+1),strings:t}),E]});if(C.length===0)return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`div`,{class:`${o}-history-empty`,children:t.historyEmpty}),E]});let D=Date.now(),O=zu(D,C);return/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ v(`div`,{class:`${o}-history`,role:`list`,children:[O.map(e=>/* @__PURE__ */ v(`div`,{class:`${o}-history-group`,children:[/* @__PURE__ */ _(`div`,{class:`${o}-history-heading`,children:t[Hu[e.bucket]]}),/* @__PURE__ */ _(`div`,{class:`${o}-history-card`,children:e.conversations.map(e=>/* @__PURE__ */ _(`div`,{role:`listitem`,children:/* @__PURE__ */ v(`button`,{type:`button`,class:`${o}-history-item`,onClick:()=>i(e),"data-unread":e.hasUnread?`true`:void 0,"data-testid":Pc(Y.historyItem,e.conversationId),children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-avatar`,"aria-hidden":`true`,children:/* @__PURE__ */ _(oc,{})}),/* @__PURE__ */ v(`span`,{class:`${o}-history-body`,children:[/* @__PURE__ */ v(`span`,{class:`${o}-history-row`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-title`,children:e.title}),/* @__PURE__ */ v(`span`,{class:`${o}-history-time`,children:[e.ticketReference&&`${e.ticketReference} · `,Wu(e.lastMessageAt,D,n)]})]}),/* @__PURE__ */ v(`span`,{class:`${o}-history-row`,children:[/* @__PURE__ */ _(`span`,{class:`${o}-history-preview`,children:e.preview&&ol(e.preview)||t.historyContinue}),e.hasUnread?/* @__PURE__ */ _(`span`,{class:`${o}-history-dot`,role:`img`,"aria-label":t.unread}):null]})]})]})},e.conversationId))})]},e.bucket)),w?.hasNext?/* @__PURE__ */ _(`div`,{class:`${o}-history-more`,children:/* @__PURE__ */ _(`button`,{type:`button`,onClick:T,disabled:b,"aria-busy":b,"data-testid":Y.historyLoadMore,children:t.loadMoreConversations})}):null]}),E]})}const Ku=N.cssPrefix;function qu({state:e,strings:t}){return e?/* @__PURE__ */ v(`div`,{class:`${Ku}-dropzone`,"data-state":e,role:`status`,"aria-live":`polite`,children:[/* @__PURE__ */ _(`span`,{class:`${Ku}-dropzone-icon`,"aria-hidden":`true`,children:_(e===`reject`?Mc:Rs,{})}),e===`reject`?t.dropZoneRejected:t.dropZone]}):null}const Ju=new RegExp(String.raw`^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$`),Yu=/^[+]?[\d\s().-]{6,}$/;function Xu(e,t,n){let r=Array.isArray(t)?t.join(``):t?.trim()??``;if(!r)return e.required?n.formRequired:void 0;if(e.type===`email`&&!Ju.test(r))return n.formInvalidEmail;if(e.type===`tel`&&!Yu.test(r))return n.formInvalidTel;if(e.type===`number`&&!Number.isFinite(Number(r)))return n.formInvalidNumber}function Zu(e,t,n){return Object.fromEntries(e.flatMap(e=>{let r=Xu(e,t[e.name],n);return r?[[e.name,r]]:[]}))}const Qu=N.cssPrefix;function $u(e){return e.tokenEmail||e.userContext?.email?.trim()}function ed(e,t){let n=e instanceof Oo?e.status:void 0;return n===400?t.formInvalidEmail:n===409?t.emailTranscriptAlreadySent:n===422?t.emailTranscriptNotDelivered:n===429?t.emailTranscriptLimited:t.emailTranscriptFailed}function td(e){return`host`in e&&`activeElement`in e}function nd({transport:e,strings:t,knownEmail:n,onClose:r}){let[i,a]=h(n??``),[o,s]=h(!1),[c,l]=h({status:`idle`}),u=m(null),p=d(),y=`${p}-title`,b=`${p}-error`,x=c.status===`sending`,S=c.status===`sent`;f(()=>{let e=u.current;if(!e)return;let t=e.getRootNode(),n=td(t)?t.activeElement:null,r=Wc(e);return()=>{r(),n instanceof HTMLElement&&n.isConnected&&n.focus({preventScroll:!0})}},[]),f(()=>{u.current?.querySelector(`[data-autofocus]`)?.focus({preventScroll:!0})},[S]);async function C(n){if(n.preventDefault(),x)return;let r=i.trim();if(!Ju.test(r)){s(!0),u.current?.querySelector(`input`)?.focus();return}s(!1),l({status:`sending`});let a=await e.emailTranscript(r).then(e=>({status:`sent`,to:e.to}),e=>({status:`failed`,message:ed(e,t)}));l(a)}function w(e){e.key===`Tab`&&e.stopPropagation(),e.key===`Escape`&&(e.stopPropagation(),r())}return/* @__PURE__ */ v(`div`,{class:`${Qu}-transcript-layer`,children:[/* @__PURE__ */ _(`div`,{class:`${Qu}-transcript-backdrop`,"aria-hidden":`true`,onClick:r}),/* @__PURE__ */ v(`section`,{ref:u,class:`${Qu}-transcript-sheet`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":y,onKeyDown:w,"data-testid":Y.emailTranscriptSheet,children:[/* @__PURE__ */ v(`header`,{class:`${Qu}-transcript-sheet-head`,children:[/* @__PURE__ */ _(`span`,{class:`${Qu}-transcript-sheet-icon`,children:/* @__PURE__ */ _(nc,{})}),/* @__PURE__ */ _(`h2`,{id:y,class:`${Qu}-transcript-sheet-title`,children:t.emailTranscript}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Qu}-icon-btn`,onClick:r,"aria-label":t.emailTranscriptCancel,title:t.emailTranscriptCancel,children:/* @__PURE__ */ _(js,{})})]}),c.status===`sent`?/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ v(`p`,{class:`${Qu}-transcript-sheet-text ${Qu}-transcript-sheet-sent`,role:`status`,children:[/* @__PURE__ */ _(kc,{}),/* @__PURE__ */ _(`span`,{children:t.emailTranscriptSent.replace(`{email}`,c.to)})]}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Qu}-form-submit ${Qu}-transcript-sheet-action`,onClick:r,"data-autofocus":!0,children:t.emailTranscriptDone})]}):/* @__PURE__ */ v(`form`,{class:`${Qu}-transcript-sheet-form`,onSubmit:e=>void C(e),noValidate:!0,children:[/* @__PURE__ */ _(`p`,{class:`${Qu}-transcript-sheet-text`,children:t.emailTranscriptPrompt}),/* @__PURE__ */ v(`label`,{class:`${Qu}-field`,"data-invalid":o?`true`:void 0,children:[/* @__PURE__ */ _(`span`,{class:`${Qu}-field-label`,children:t.emailTranscriptEmailLabel}),/* @__PURE__ */ _(`input`,{class:`${Qu}-field-input`,type:`email`,name:`email`,autocomplete:`email`,inputMode:`email`,autocapitalize:`off`,spellcheck:!1,value:i,readOnly:x,"aria-invalid":o,"aria-describedby":o?b:void 0,onInput:e=>{a(e.currentTarget.value),s(!1)},"data-autofocus":!0,"data-testid":Y.emailTranscriptEmail}),o?/* @__PURE__ */ _(`span`,{id:b,class:`${Qu}-field-error`,role:`alert`,children:t.formInvalidEmail}):null]}),/* @__PURE__ */ _(`button`,{type:`submit`,class:`${Qu}-form-submit ${Qu}-transcript-sheet-action`,disabled:x,"aria-busy":x,"data-testid":Y.emailTranscriptSend,children:x?t.emailTranscriptSending:t.emailTranscriptSend}),c.status===`failed`?/* @__PURE__ */ _(`p`,{class:`${Qu}-field-error`,role:`alert`,children:c.message}):null]})]})]})}const rd=/* @__PURE__ */ new Set([`hidden`,`submit`,`button`,`reset`,`image`,`file`,`password`]);function id(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function ad(e){return!id(e)||e.name===``||e.disabled?!1:!(e instanceof HTMLInputElement&&rd.has(e.type))}function od(e){let t=e.labels?.[0]?.textContent?.trim();return e.getAttribute(`toolparamdescription`)??(t||e.getAttribute(`aria-description`))??void 0}function sd(e,t){let n=od(e),r=n?{description:n}:{};return e instanceof HTMLSelectElement?{...r,type:`string`,enum:[...e.options].map(e=>e.value)}:e instanceof HTMLTextAreaElement?{...r,type:`string`}:e.type===`checkbox`?{...r,type:`boolean`}:e.type===`radio`?{...r,type:`string`,enum:t}:e.type===`number`||e.type===`range`?{...r,type:`number`}:{...r,type:`string`}}function cd(e,t){Object.getOwnPropertyDescriptor(Reflect.getPrototypeOf(e)??e,`value`)?.set?.call(e,t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function ld(e){return e==null?``:typeof e==`string`?e:JSON.stringify(e)}function ud(e,t){e instanceof HTMLInputElement&&e.type===`checkbox`?e.checked!==(t===!0||t===`true`)&&e.click():e instanceof HTMLInputElement&&e.type===`radio`?e.value===ld(t)&&!e.checked&&e.click():cd(e,ld(t))}function dd(e,t,n){let r=[...e.elements].filter(ad),i={},a=/* @__PURE__ */ new Set;for(let e of r){var o;let t=r.flatMap(t=>t instanceof HTMLInputElement&&t.type===`radio`&&t.name===e.name?[t.value]:[]);i[o=e.name]??(i[o]=sd(e,t)),e.required&&a.add(e.name)}return{name:t,description:n,inputSchema:{type:`object`,properties:i,...a.size>0?{required:[...a]}:{}},execute(t){let n=typeof t==`object`&&t?Object.entries(t):[];for(let[e,t]of n)for(let n of r)n.name===e&&ud(n,t);if(!e.hasAttribute(`toolautosubmit`))return`Filled in the form. The visitor still needs to check it and press its submit button.`;let i=[...new Set([...e.elements].flatMap(e=>id(e)&&e.name&&!e.checkValidity()?[e.name]:[]))];return i.length>0?`Filled in the form, but it can't be submitted yet: ${i.join(`, `)} still needs the visitor. Ask them to complete it and press the submit button.`:(setTimeout(()=>e.requestSubmit(),0),`Filled in the form and submitted it.`)}}}function fd(){return[...document.querySelectorAll(`form[toolname][tooldescription]`)].flatMap(e=>{let t=e.getAttribute(`toolname`)?.trim()??``,n=e.getAttribute(`tooldescription`)?.trim()??``;return t&&n?[dd(e,t,n)]:[]})}const pd=`${N.cssPrefix}.page-tools`;function md(e){return typeof e==`object`&&!!e}function hd(e){return md(e)&&(e.state===`running`||e.state===`stopped`||e.state===`finished`&&md(e.outcome))}function gd(e){let t=e?JSON.parse(e):void 0;return md(t)?{sent:Array.isArray(t.sent)?t.sent.filter(e=>typeof e==`string`):[],calls:Object.fromEntries(Object.entries(md(t.calls)?t.calls:{}).filter(e=>hd(e[1])))}:{sent:[],calls:{}}}let _d={sent:[],calls:{}};function vd(){try{_d=gd(sessionStorage.getItem(pd))}catch{}return _d}function yd(e){_d=e;try{sessionStorage.setItem(pd,JSON.stringify(e))}catch{}}const bd={markSent(e){let t=vd();yd({...t,sent:[...t.sent.filter(t=>t!==e),e].slice(-20)})},sentHere(e){return vd().sent.includes(e)},get(e){return vd().calls[e]},set(e,t){let n=vd(),r=Object.entries(n.calls).filter(([t])=>t!==e);yd({...n,calls:Object.fromEntries([...r,[e,t]].slice(-50))})},clear(e){let t=vd();e.some(e=>e in t.calls)&&yd({...t,calls:Object.fromEntries(Object.entries(t.calls).filter(([t])=>!e.includes(t)))})}},xd=R.scope(`page-tools`),Sd=3e4,Cd=Symbol.for(`${N.cssPrefix}.page-tools`),wd={state:`output-error`,errorText:`The page reloaded before this finished, so it may or may not have taken effect. Check with the visitor before trying it again.`},Td=`The visitor stopped this before it finished.`;function Ed(e){return typeof e==`object`&&!!e}function Dd(e){return Ed(e)&&Array.isArray(e.registered)&&e.runs instanceof Map}function Od(){let e=Reflect.get(globalThis,Cd);if(Dd(e))return e;let t={registered:[],runs:/* @__PURE__ */ new Map};return Reflect.set(globalThis,Cd,t),t}function kd(e,t){let n=Ed(t)&&t.signal instanceof AbortSignal?t.signal:void 0;if(n?.aborted)return;let r=Od().registered;r.push(e);function i(){let t=r.indexOf(e);t>=0&&r.splice(t,1)}n?.addEventListener(`abort`,i,{once:!0})}function Ad(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,58)}function jd(e){if(!Ed(e)||typeof e.name!=`string`||!Ad(e.name))return;let t=typeof e.title==`string`&&e.title.trim()!==``?e.title.trim().slice(0,120):void 0,n=[e.description,t].find(e=>typeof e==`string`&&e.trim()!==``)??e.name,r=e.preview;return{name:Ad(e.name),...t?{title:t}:{},...typeof r==`function`?{preview:t=>Reflect.apply(r,e,[t])}:{},description:n.trim().slice(0,1024),inputSchema:{properties:{},...Ed(e.inputSchema)?e.inputSchema:{},type:`object`},consequential:Ed(e.annotations)&&e.annotations.consequentialHint===!0}}function Md(e){return e.flatMap(e=>{let t=jd(e),n=Ed(e)?e.execute:void 0;return!t||typeof n!=`function`?(xd.warn(`skipped a tool without a name or an execute function`,e),[]):[{...t,run:(t,r)=>Reflect.apply(n,e,[t,{signal:r}])}]})}async function Nd(){let e=Reflect.get(document,`modelContext`)??Reflect.get(navigator,`modelContext`);if(!Ed(e)||typeof e.getTools!=`function`||typeof e.executeTool!=`function`)return[];let t=e.getTools,n=e.executeTool,r=await Promise.race([Promise.resolve().then(()=>Reflect.apply(t,e,[])),wo(1e3).then(()=>[])]).catch(()=>[]);return(Array.isArray(r)?r:[]).flatMap(t=>{let r=jd(t);return r?[{...r,run:(r,i)=>Reflect.apply(n,e,[t,r,{signal:i}])}]:[]})}async function Pd(e=[]){let t=Md(fd()),n=new Set(t.map(e=>e.name)),r=[...(await Nd()).filter(e=>!n.has(e.name)),...t,...Md(e),...Md(Od().registered)];return new Map(r.map(e=>[e.name,e]))}function Fd(e){return[...e.values()].map(({name:e,title:t,description:n,inputSchema:r,consequential:i})=>{let a={name:e,description:n,inputSchema:r};return t&&(a.title=t),i&&(a.annotations={consequentialHint:!0}),a})}function Id(e){return e?.execution===`client`}function Ld(e){return e.startsWith(`site__`)?e.slice(6):e}function Rd(e){if(e===void 0||typeof e==`function`||typeof e==`symbol`)return null;let t=/* @__PURE__ */ new WeakSet,n=JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n!=`function`&&typeof n!=`symbol`)return n instanceof Node?`[${n.nodeName.toLowerCase()}]`:Ed(n)?t.has(n)?`[circular]`:(t.add(n),n):n});return n.length>Sd?{truncated:!0,preview:n.slice(0,Sd)}:JSON.parse(n)}async function zd(e){let t=(await Pd(e.optionTools)).get(Ld(e.toolName));if(!t?.preview)return;let n=t.preview;return Promise.resolve().then(()=>n(e.input)).catch(e=>{xd.warn(`a page tool preview failed`,{name:t.name,error:e})})}async function Bd(e){let t=Ld(e.toolName),n=(await Pd(e.optionTools)).get(t);return n?Promise.resolve().then(()=>n.run(e.input,e.signal)).then(e=>({state:`output-available`,output:Rd(e)})).catch(e=>(xd.warn(`a page tool failed`,{name:t,error:e}),{state:`output-error`,errorText:(e instanceof Error?e.message:String(e)).slice(0,1e3)||`The page tool failed.`})):{state:`output-error`,errorText:`This page doesn't offer "${t}" right now; the visitor may have moved on. Tell them, or continue without it.`}}function Vd(e){let{toolCallId:t}=e,n=bd.get(t);if(n?.state===`finished`)return Promise.resolve(n.outcome);let{runs:r}=Od(),i=r.get(t);if(i)return i.outcome;if(n?.state===`running`)return bd.set(t,{state:`finished`,outcome:wd}),e.onSettled(`interrupted`,0),Promise.resolve(wd);let a=new AbortController,o=performance.now();bd.set(t,{state:`running`});let s=Bd({...e,signal:a.signal}).then(n=>(r.delete(t),bd.get(t)?.state===`running`&&(bd.set(t,{state:`finished`,outcome:n}),e.onSettled(n.state===`output-available`?`completed`:`failed`,Math.round(performance.now()-o))),n));return r.set(t,{outcome:s,controller:a}),s}function Hd(e){return e===wd.errorText||e===Td}function Ud(e){return bd.set(e,{state:`stopped`}),Od().runs.get(e)?.controller.abort(),Td}function Wd(e){bd.clear([e]),Od().runs.get(e)?.controller.abort()}const Gd=N.cssPrefix;function Kd({messageId:e,initial:t,strings:n,onFeedback:r}){let[i,a]=h(t);u(()=>a(t),[e,t]);function o(t){let n=i===t?null:t;a(n),r(e,n)}return/* @__PURE__ */ v(`div`,{class:`${Gd}-feedback`,role:`group`,"data-testid":Y.messageFeedback,children:[/* @__PURE__ */ _(`button`,{type:`button`,class:`${Gd}-msg-action`,"data-active":i===`up`?`true`:void 0,"aria-pressed":i===`up`,"aria-label":n.feedbackUp,title:n.feedbackUp,onClick:()=>o(`up`),"data-testid":Y.feedbackUp,children:/* @__PURE__ */ _(Tc,{})}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Gd}-msg-action`,"data-active":i===`down`?`true`:void 0,"aria-pressed":i===`down`,"aria-label":n.feedbackDown,title:n.feedbackDown,onClick:()=>o(`down`),"data-testid":Y.feedbackDown,children:/* @__PURE__ */ _(Ec,{})}),/* @__PURE__ */ _(`span`,{class:`${Gd}-sr-only`,role:`status`,"aria-live":`polite`,children:i?n.feedbackThanks:``})]})}function qd(e){return e.partsSig.value.some(e=>e.kind===`text`&&e.textSig.value.length>0)}function Jd(e){return e.partsSig.value.some(e=>e.kind===`reasoning`)}function Yd(e){return e.streaming&&!e.bufferedHold&&!(e.reasoningVisible&&e.working)}function Xd(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:Yd({streaming:t,bufferedHold:a,reasoningVisible:n,working:o}),emptyReply:r,hidden:i}}const Zd=N.cssPrefix;function Qd({part:e,strings:t}){let n=e.title||e.filename||e.url||t.sources;return e.url?/* @__PURE__ */ v(`a`,{class:`${Zd}-source`,href:e.url,target:`_blank`,rel:`noreferrer noopener`,"data-testid":Y.source,children:[/* @__PURE__ */ _(`span`,{class:`${Zd}-source-icon`,"aria-hidden":`true`,children:`🔗`}),/* @__PURE__ */ _(`span`,{class:`${Zd}-source-label`,children:n})]}):/* @__PURE__ */ v(`span`,{class:`${Zd}-source`,"data-testid":Y.source,children:[/* @__PURE__ */ _(`span`,{class:`${Zd}-source-icon`,"aria-hidden":`true`,children:`📄`}),/* @__PURE__ */ _(`span`,{class:`${Zd}-source-label`,children:n})]})}const $d=N.cssPrefix;function ef(e){return{toolCallId:e.toolCallId,toolName:e.toolName,...e.title?{title:e.title}:{},state:e.stateSig.value,input:e.inputSig.value,output:e.outputSig.value,...e.errorSig.value?{errorText:e.errorSig.value}:{},...e.approvalSig.value?{approval:e.approvalSig.value}:{},...e.toolMetadata?{toolMetadata:e.toolMetadata}:{}}}function tf(e,t){if(t?.replacedByMessageId)return{terminal:!1,responded:!1,decided:!1};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 nf({status:e,label:t,icon:n}){return/* @__PURE__ */ v(`span`,{class:`${$d}-toolui-badge ${$d}-toolui-status`,"data-status":e,children:[/* @__PURE__ */ _(`span`,{class:`${$d}-toolui-status-icon`,children:n??/* @__PURE__ */ _(rf,{status:e})}),t]})}function rf({status:e}){return e===`running`?/* @__PURE__ */ _(`span`,{class:`${$d}-loading-spinner`}):_(e===`stopped`?Ls:e===`waiting`||e===`submitted`?Oc:e===`failed`||e===`declined`||e===`replaced`?Ac:kc,{})}function af(e){return e===`approved`||e===`declined`||e===`done`}function of({decision:e}){return/* @__PURE__ */ v(`span`,{class:`${$d}-steps-decision`,"data-approved":e.approved?`true`:`false`,title:e.title,children:[e.approved?/* @__PURE__ */ _(kc,{}):/* @__PURE__ */ _(Ac,{}),e.label]})}function sf({view:e,strings:t}){let n=e.raw;return/* @__PURE__ */ v(g,{children:[e.reason?/* @__PURE__ */ _(`p`,{class:`${$d}-steps-row-reason`,children:e.reason}):null,e.error?/* @__PURE__ */ _(`p`,{class:`${$d}-steps-row-error`,children:e.error}):null,e.fields.length>0?/* @__PURE__ */ _(cf,{fields:e.fields,label:n?t.stepInput:void 0}):null,e.resultFields?/* @__PURE__ */ _(cf,{fields:e.resultFields,label:t.toolResult}):null,n?.input||n?.output?/* @__PURE__ */ v(`details`,{class:`${$d}-toolui-raw`,children:[/* @__PURE__ */ _(`summary`,{children:t.stepRawData}),n.input?/* @__PURE__ */ _(lf,{label:t.stepInput,text:n.input}):null,n.output?/* @__PURE__ */ _(lf,{label:t.toolResult,text:n.output}):null]}):null]})}function cf({fields:e,label:t}){let n=/* @__PURE__ */ _(`div`,{class:`${$d}-toolui-fields`,children:/* @__PURE__ */ _(`table`,{children:/* @__PURE__ */ _(`tbody`,{children:e.map(({label:e,value:t},n)=>/* @__PURE__ */ v(`tr`,{children:[/* @__PURE__ */ _(`th`,{scope:`row`,children:e}),/* @__PURE__ */ _(`td`,{children:t})]},`${e}#${n}`))})})});return t?/* @__PURE__ */ v(`div`,{class:`${$d}-toolui-section`,children:[/* @__PURE__ */ _(`span`,{class:`${$d}-toolui-label`,children:t}),n]}):n}function lf({label:e,text:t}){return/* @__PURE__ */ v(`div`,{class:`${$d}-toolui-section`,children:[/* @__PURE__ */ _(`span`,{class:`${$d}-toolui-label`,children:e}),/* @__PURE__ */ _(`pre`,{class:`${$d}-toolui-code`,children:t})]})}const uf=N.cssPrefix;function df({part:e,view:t,strings:n,locale:r,canAct:i,onDecision:a,onEdit:o,preview:s}){let c=t.approval,l=t.status===`waiting`||t.status===`submitted`||t.status===`approved`,u=e.toolCallId;return/* @__PURE__ */ v(`details`,{class:`${uf}-toolui ${uf}-toolui-collapsible`,open:l||c?.buttons===`change`||void 0,"data-testid":t.status===`waiting`?Y.toolApproval:Y.toolDecision,"data-status":t.status,children:[/* @__PURE__ */ v(`summary`,{class:`${uf}-toolui-head`,children:[/* @__PURE__ */ _(`span`,{class:`${uf}-toolui-prompt`,children:l&&c?c.ask:t.name}),t.system?/* @__PURE__ */ _(`span`,{class:`${uf}-toolui-system`,children:t.system}):null,/* @__PURE__ */ v(`span`,{class:`${uf}-toolui-head-end`,children:[t.decision?/* @__PURE__ */ _(of,{decision:t.decision}):null,t.statusLabel&&!(t.decision&&af(t.status))?/* @__PURE__ */ _(nf,{status:t.status,label:t.statusLabel}):null,/* @__PURE__ */ _(`span`,{class:`${uf}-toolui-chevron`,children:/* @__PURE__ */ _(rc,{})})]})]}),/* @__PURE__ */ v(`div`,{class:`${uf}-toolui-collapse-body`,children:[l&&s&&Id(e.toolMetadata)?/* @__PURE__ */ _(pf,{toolName:e.toolName,input:e.inputSig.value,preview:s,strings:n,locale:r}):null,/* @__PURE__ */ _(sf,{view:t,strings:n}),c?.note?/* @__PURE__ */ _(`p`,{class:`${uf}-toolui-subtle`,children:c.note}):null,c?.buttons===`decide`?/* @__PURE__ */ v(`div`,{class:`${uf}-toolui-actions`,children:[/* @__PURE__ */ _(`button`,{type:`button`,class:`${uf}-form-skip`,disabled:!i,onClick:()=>a(u,!1),"data-testid":Y.toolDecline,children:n.decline}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${uf}-form-submit`,disabled:!i,onClick:()=>a(u,!0),"data-testid":Y.toolApprove,children:n.approve})]}):null,c?.buttons===`change`?/* @__PURE__ */ _(`div`,{class:`${uf}-toolui-actions`,children:/* @__PURE__ */ _(`button`,{type:`button`,class:`${uf}-form-skip`,onClick:()=>o(u),"data-testid":Y.toolEdit,children:n.changeAnswer})}):null]})]})}function ff(e){if(typeof e==`object`&&e&&`totals`in e)return`number`in e&&`items`in e?`root = Root([preview])\npreview = Order(${JSON.stringify(e)})`:`lines`in e?`root = Root([preview])\npreview = Cart(${JSON.stringify(e)})`:void 0}function pf({toolName:e,input:t,preview:n,strings:r,locale:i}){let[a,s]=h();u(()=>{let r=!0;return n(e,t).then(e=>{r&&s(ff(e))}),()=>{r=!1}},[e,t,n]);let c=p(()=>a?{textSig:o(a),doneSig:o(!0),replyDoneSig:o(!0)}:void 0,[a]);return c?/* @__PURE__ */ _(`div`,{class:`${uf}-toolui-preview`,"data-testid":Y.toolPreview,children:/* @__PURE__ */ _(ca,{cssPrefix:uf,textSig:c.textSig,doneSig:c.doneSig,replyDoneSig:c.replyDoneSig,strings:r,locale:i})}):null}const mf=[`text`,`email`,`phone`,`number`,`date`,`single-select`,`multi-select`,`boolean`];function hf(e){return typeof e==`object`&&!!e}function gf(e,t){let n=hf(e)?e:{},r=(Array.isArray(n.questions)?n.questions:[]).map((e,n)=>_f(e,n,t)).filter(e=>e!==null);return{intro:bf(n.intro),questions:r}}function _f(e,t,n){if(!hf(e))return null;let r=mf.find(t=>t===e.type)??`text`;return{key:bf(e.key)??`q${t+1}`,question:bf(e.question)??n,type:r,options:Array.isArray(e.options)?e.options.filter(e=>typeof e==`string`&&e.trim().length>0):void 0,required:typeof e.required==`boolean`?e.required:void 0,helpText:bf(e.helpText)}}function vf(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 yf(e,t,n){return e.questions.map(e=>{let r=vf(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 bf(e){return typeof e==`string`&&e.trim()?e.trim():void 0}const xf=N.cssPrefix;function Sf({fields:e,strings:t,submitLabel:n,onSubmit:r,skipLabel:i,onSkip:a,footerHint:o,submitOnEnter:s,disabled:c,initialValues:l,hideActions:u,fieldTypeLabels:d,rootTestId:f,submitTestId:p,skipTestId:m}){let[g,y]=h(()=>l??{}),[b,x]=h({}),[S,C]=h({});function w(e){S[e]&&C(t=>({...t,[e]:``}))}function T(e,t){y(n=>({...n,[e]:t})),w(e)}function E(e,t){x(n=>({...n,[e]:t})),w(e)}function D(n){if(n.preventDefault(),c)return;let i=Ef(e,g,b),a=Zu(e,i,t);Object.keys(a).length>0?C(a):r(i)}function O(e){!s||e.key!==`Enter`||e.shiftKey||Ql(e)||e.target&&`tagName`in e.target&&e.target.tagName===`TEXTAREA`&&D(e)}return/* @__PURE__ */ v(`form`,{class:`${xf}-form`,onSubmit:D,onKeyDown:O,onCompositionEnd:Zl,"data-testid":f,noValidate:!0,children:[e.map(e=>/* @__PURE__ */ _(Cf,{field:e,value:g[e.name],otherText:b[e.name]??``,error:S[e.name],disabled:c,typeLabel:d?.[e.name],strings:t,onChange:t=>T(e.name,t),onOtherChange:t=>E(e.name,t)},e.name)),u?null:/* @__PURE__ */ v(`div`,{class:`${xf}-form-actions`,children:[o?/* @__PURE__ */ _(`span`,{class:`${xf}-form-hint`,children:o}):null,i&&a?/* @__PURE__ */ _(`button`,{type:`button`,class:`${xf}-form-skip`,onClick:a,disabled:c,"data-testid":m,children:i}):null,/* @__PURE__ */ _(`button`,{type:`submit`,class:`${xf}-form-submit`,disabled:c,"data-testid":p,children:n})]})]})}function Cf({field:e,value:t,otherText:n,error:r,disabled:i,typeLabel:a,strings:o,onChange:s,onOtherChange:c}){let l=Pc(Y.formField,e.name),u=d(),f=wf({field:e,value:t,otherText:n,disabled:i,strings:o,onChange:s,onOtherChange:c,fieldTid:l,labelId:u}),p=e.type===`radio`||e.type===`multiselect`?`div`:`label`;return/* @__PURE__ */ v(p,{class:`${xf}-field`,"data-field":e.name,"data-invalid":r?`true`:void 0,children:[/* @__PURE__ */ v(`span`,{class:`${xf}-field-head`,children:[/* @__PURE__ */ v(`span`,{class:`${xf}-field-label`,id:u,children:[e.label,e.required?/* @__PURE__ */ _(`span`,{class:`${xf}-field-req`,"aria-hidden":`true`,children:` *`}):null]}),a?/* @__PURE__ */ _(`span`,{class:`${xf}-field-type`,children:a}):null]}),f,e.validationHint&&!r?/* @__PURE__ */ _(`span`,{class:`${xf}-field-hint`,children:e.validationHint}):null,r?/* @__PURE__ */ _(`span`,{class:`${xf}-field-error`,role:`alert`,children:r}):null]})}function wf(e){let{field:t,value:n,otherText:r,disabled:i,strings:a,onChange:o,onOtherChange:s,fieldTid:c,labelId:l}=e,u=typeof n==`string`?n:``;switch(t.type){case`textarea`:return/* @__PURE__ */ _(`textarea`,{class:`${xf}-field-input`,rows:3,value:u,disabled:i,onInput:e=>o(e.currentTarget.value),"data-testid":c});case`radio`:return/* @__PURE__ */ _(`div`,{class:`${xf}-field-choices`,role:`radiogroup`,"aria-labelledby":l,"data-testid":c,children:(t.options??[]).map(e=>/* @__PURE__ */ v(`label`,{class:`${xf}-choice`,children:[/* @__PURE__ */ _(`input`,{type:`radio`,name:`${xf}-${t.name}`,checked:u===e.value,disabled:i,onChange:()=>o(e.value)}),/* @__PURE__ */ _(`span`,{children:e.label})]},e.value))});case`multiselect`:{let e=Array.isArray(n)?n:[];function u(t,n){return o(n?[...e,t]:e.filter(e=>e!==t))}return/* @__PURE__ */ v(`div`,{class:`${xf}-field-choices`,role:`group`,"aria-labelledby":l,"data-testid":c,children:[(t.options??[]).map(t=>/* @__PURE__ */ v(`label`,{class:`${xf}-choice`,children:[/* @__PURE__ */ _(`input`,{type:`checkbox`,checked:e.includes(t.value),disabled:i,onChange:e=>u(t.value,e.currentTarget.checked)}),/* @__PURE__ */ _(`span`,{children:t.label})]},t.value)),(t.options??[]).length===0?/* @__PURE__ */ _(`textarea`,{class:`${xf}-field-input`,rows:2,value:r,placeholder:a.formOtherPlaceholder,disabled:i,onInput:e=>s(e.currentTarget.value)}):null]})}default:return/* @__PURE__ */ _(`input`,{...Tf(t.type),class:`${xf}-field-input`,value:u,disabled:i,onInput:e=>o(e.currentTarget.value),"data-testid":c})}}function Tf(e){switch(e){case`number`:return{type:e};case`email`:return{type:e};case`tel`:return{type:e};case`date`:return{type:e};default:return{type:`text`}}}function Ef(e,t,n){let r={...t};for(let i of e){let e=n[i.name]?.trim();if(i.type===`multiselect`&&e){let n=e.split(/[,\n;]+/).map(e=>e.trim()).filter(Boolean),a=t[i.name];r[i.name]=[...Array.isArray(a)?a:[],...n]}}return r}const Df=N.cssPrefix;function Of({skipped:e,submitted:t,strings:n}){return e?{status:`replaced`,statusLabel:n.inputSkipped}:t?{status:`submitted`,statusLabel:n.stepWorkingOnIt}:{status:`done`,statusLabel:n.inputAnswered}}const kf={text:`qtypeText`,email:`qtypeEmail`,phone:`qtypePhone`,number:`qtypeNumber`,date:`qtypeDate`,"single-select":`qtypeChooseOne`,"multi-select":`qtypeChooseAny`,boolean:`qtypeBoolean`};function Af(e,t){let n={};for(let r of e)n[r.key]=t[kf[r.type]];return n}function jf({part:e,strings:t,active:n,superseded:r=!1,continuationStreaming:a=!1,onDecision:o,onEdit:s}){let c=p(()=>i(()=>e.stateSig.value),[e]).value,l=p(()=>i(()=>e.approvalSig.value),[e]).value,u=p(()=>i(()=>gf(e.inputSig.value,t.askFallbackQuestion)),[e,t]).value,{terminal:d,decided:f}=tf(c,l),m=f&&l?.approved===!0,g=a&&!f,y=!f&&!r&&!g,b=!y&&!m&&!g,x=m&&n&&!d,S=u.questions,[C,w]=h(null),T=C??(y||m||g),[E,D]=h(!1),O=S.length>1?As:sc,k=y?t.inputRequired:t.inputBadge,A=g?/* @__PURE__ */ _(`p`,{class:`${Df}-toolui-subtle`,children:t.stepWorkingOnIt}):y?/* @__PURE__ */ _(Mf,{req:u,strings:t,active:n,resolve:(t,n)=>o(e.toolCallId,n,t)}):E?/* @__PURE__ */ _(Sf,{fields:yf(u,t.confirmYes,t.confirmNo),strings:t,submitLabel:t.inputSubmit,onSubmit:()=>{},disabled:!0,hideActions:!0,fieldTypeLabels:Af(S,t),initialValues:m?zf(S,l?.reason):void 0}):/* @__PURE__ */ _(Nf,{questions:S,answers:m?Rf(l?.reason):{},strings:t}),{status:j,statusLabel:ee}=Of({skipped:b,submitted:g,strings:t});return/* @__PURE__ */ v(`details`,{class:`${Df}-toolui ${Df}-toolui-collapsible${r?` ${Df}-toolui-stale`:``}`,open:T,onToggle:e=>{let t=e.currentTarget.open;t!==T&&w(t)},"data-testid":y?Y.toolAskQuestions:Y.toolDecision,children:[/* @__PURE__ */ v(`summary`,{class:`${Df}-toolui-head`,children:[/* @__PURE__ */ v(`span`,{class:`${Df}-toolui-q-pill`,children:[/* @__PURE__ */ _(O,{}),k]}),/* @__PURE__ */ v(`span`,{class:`${Df}-toolui-head-end`,children:[y?null:/* @__PURE__ */ _(nf,{status:j,icon:_(b?Ac:kc,{}),label:ee}),/* @__PURE__ */ _(`span`,{class:`${Df}-toolui-chevron`,children:/* @__PURE__ */ _(rc,{})})]})]}),/* @__PURE__ */ v(`div`,{class:`${Df}-toolui-collapse-body`,children:[u.intro?/* @__PURE__ */ _(`div`,{class:`${Df}-toolui-desc`,children:u.intro}):null,A,y||g?null:/* @__PURE__ */ v(`div`,{class:`${Df}-toolui-footer`,children:[/* @__PURE__ */ v(`button`,{type:`button`,class:`${Df}-toolui-options-toggle`,onClick:()=>D(e=>!e),"data-testid":Y.toolAskOptions,children:[/* @__PURE__ */ _(`span`,{class:`${Df}-toolui-options-chevron${E?` ${Df}-open`:``}`,children:/* @__PURE__ */ _(rc,{})}),E?t.hideOptions:t.showOptions]}),x?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Df}-form-skip`,onClick:()=>s(e.toolCallId),"data-testid":Y.toolEdit,children:t.edit}):null]})]})]})}function Mf({req:e,strings:t,active:n,resolve:r}){let i=yf(e,t.confirmYes,t.confirmNo),a=e.questions.length===1&&e.questions[0]?.type===`text`;return/* @__PURE__ */ _(Sf,{fields:i,strings:t,disabled:!n,submitLabel:t.inputSubmit,footerHint:a?t.inputSubmitHint:void 0,onSubmit:t=>r(Ff(e.questions,t),!0),skipLabel:t.inputSkip,onSkip:()=>r(void 0,!1),submitOnEnter:a,fieldTypeLabels:Af(e.questions,t),submitTestId:Y.toolInputSubmit,skipTestId:Y.toolInputSkip})}function Nf({questions:e,answers:t,strings:n}){return/* @__PURE__ */ _(`div`,{class:`${Df}-toolui-summary`,"data-testid":Y.toolAskSummary,children:e.map(e=>/* @__PURE__ */ v(`div`,{class:`${Df}-field`,children:[/* @__PURE__ */ _(`span`,{class:`${Df}-field-head`,children:/* @__PURE__ */ v(`span`,{class:`${Df}-field-label`,children:[e.question,e.required?/* @__PURE__ */ _(`span`,{class:`${Df}-field-req`,"aria-hidden":`true`,children:` *`}):null]})}),/* @__PURE__ */ _(`p`,{class:`${Df}-toolui-answer`,children:Pf(e,t[e.key],n)||`—`})]},e.key))})}function Pf(e,t,n){return e.type===`boolean`?t===`yes`?n.confirmYes:t===`no`?n.confirmNo:t??``:t??``}function Ff(e,t){let n=e.flatMap(e=>{let n=t[e.key],r=typeof n==`string`?n.trim():n;return r?.length?[{key:e.key,value:r}]:[]});return JSON.stringify({answers:n})}function If(e){if(!e)return{};let t=(()=>{try{return JSON.parse(e)}catch{return}})(),n=Lf(t)?t.answers:void 0;if(!Array.isArray(n))return{};let r={};for(let e of n)if(Lf(e)){let{key:t,value:n}=e;if(typeof t!=`string`)continue;typeof n==`string`?r[t]=n:Array.isArray(n)&&(r[t]=n.filter(e=>typeof e==`string`))}return r}function Lf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rf(e){let t=If(e),n={};for(let[e,r]of Object.entries(t))n[e]=Array.isArray(r)?r.join(`, `):r;return n}function zf(e,t){let n=If(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}const Z=N.cssPrefix;function Bf(e,t){let n=[];for(let[r,i]of e.entries()){let e=n.at(-1),a=i.kind===`tool`?t.viewOf(i):void 0,o=Vf(i,a,t.showReasoning);o?e?.kind===`steps`?(e.rows.push(o),e.indices.push(r)):n.push({kind:`steps`,rows:[o],indices:[r]}):i.kind===`step-start`||i.kind===`reasoning`||i.kind===`source`&&!t.showSources||a?.placement===`hidden`||n.push({kind:`part`,part:i,index:r})}return n}function Vf(e,t,n){return e.kind===`reasoning`?n?{kind:`thought`,part:e}:void 0:e.kind===`tool`&&t?.placement===`step`?{kind:`tool`,part:e,view:t}:void 0}function Hf(e,t){let n=[...new Set(t)];if(e&&n.length!==0&&!n.some(t=>t<0||t>=e.length))return n.reduce((t,n)=>t+(e[n]?.durationMs??0),0)}function Uf(e){let t=[];for(let n of e)t.push((t.at(-1)??-1)+ +(n.kind===`step-start`));return t}function Wf(e,t){return e.streaming?t.thinking:e.reasoningMs===void 0?t.thought:t.thoughtFor.replace(`{time}`,Gf(e.reasoningMs))}function Gf(e){if(e<1e4)return`${Number((e/1e3).toFixed(1))} s`;let t=Math.round(e/1e3);return t<60?`${t} s`:`${Math.floor(t/60)} m ${t%60} s`}function Kf(e){return e.split(`
36
36
  `).map(e=>e.trim()).findLast(e=>/^\*\*[^*].*\*\*$/.test(e))?.slice(2,-2).trim()}function qf(e,t){return e?.kind===`tool`?`${e.view.name}…`:(e&&Kf(e.part.textSig.value))??t.thinking}function Jf({rows:e,steps:t=[],stepTimings:n,timed:r=!0,strings:a,running:o,runStartedAt:s}){let[c,l]=h(!1),[u,d]=h(!1),f=Ce(e.flatMap(e=>e.kind===`tool`?[e.view]:[])),m=e.at(-1),g=p(()=>i(()=>qf(m,a)),[m,a]).value,y=r?Hf(n,t):void 0;function b(){l(!c),d(!0)}let[x]=e;return!o&&e.length===1&&x?.kind===`tool`?/* @__PURE__ */ _(`div`,{class:`${Z}-steps`,"data-testid":Y.toolSteps,"data-stopped":f.stopped?`true`:void 0,children:/* @__PURE__ */ _($f,{view:x.view,strings:a,durationMs:y,standalone:!0})}):/* @__PURE__ */ v(`div`,{class:`${Z}-steps`,"data-testid":Y.toolSteps,"data-running":o?`true`:void 0,"data-stopped":f.stopped?`true`:void 0,children:[/* @__PURE__ */ v(`button`,{type:`button`,class:`${Z}-steps-head`,"aria-expanded":c,onClick:b,children:[/* @__PURE__ */ _(`span`,{class:`${Z}-steps-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Xf,{running:o,stopped:f.stopped!==void 0})}),/* @__PURE__ */ _(`span`,{class:`${Z}-steps-label`,children:o?/* @__PURE__ */ _(`span`,{class:`${Z}-steps-live`,children:g}):/* @__PURE__ */ _(Zf,{line:f,strings:a})}),!o&&f.failed>0?/* @__PURE__ */ _(`span`,{class:`${Z}-steps-failed`,children:a.toolStepsFailed.replace(`{count}`,String(f.failed))}):null,o?null:f.marks.map(e=>/* @__PURE__ */ _(of,{decision:e},e.label)),o&&s?/* @__PURE__ */ _(Yf,{since:s}):null,!o&&y!==void 0?/* @__PURE__ */ _(`span`,{class:`${Z}-steps-time`,children:Gf(y)}):null,/* @__PURE__ */ _(`span`,{class:`${Z}-steps-chevron`,"data-open":c?`true`:void 0,children:/* @__PURE__ */ _(rc,{})})]}),/* @__PURE__ */ _(`span`,{class:`${Z}-sr-only`,role:`status`,children:o?g:``}),/* @__PURE__ */ _(`div`,{class:`${Z}-steps-body`,"data-open":c?`true`:void 0,inert:!c,children:/* @__PURE__ */ _(`div`,{class:`${Z}-steps-body-inner`,children:u?/* @__PURE__ */ _(`ol`,{class:`${Z}-steps-list`,children:e.map((r,i)=>r.kind===`tool`?/* @__PURE__ */ _($f,{view:r.view,strings:a},r.part.toolCallId):/* @__PURE__ */ _(ep,{part:r.part,current:o&&i===e.length-1,reasoningMs:n?.[t[i]??-1]?.reasoningMs,strings:a},`${r.part.id}#${i}`))}):null})})]})}function Yf({since:e}){let[t,n]=h(()=>Date.now());u(()=>{let e=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(e)},[]);let r=Math.max(0,Math.floor((t-Date.parse(e))/1e3));return/* @__PURE__ */ _(`span`,{class:`${Z}-steps-time`,children:r<60?`${r} s`:`${Math.floor(r/60)} m ${r%60} s`})}function Xf({running:e,stopped:t}){return e?/* @__PURE__ */ _(`span`,{class:`${Z}-loading-spinner`}):_(t?Ls:Dc,{})}function Zf({line:e,strings:t}){return e.stopped?/* @__PURE__ */ _(g,{children:Te(e.stopped.finished,t)}):e.single?/* @__PURE__ */ v(g,{children:[e.single.name,e.single.summary?/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`span`,{class:`${Z}-steps-sep`,"aria-hidden":`true`,children:`·`}),/* @__PURE__ */ _(`span`,{class:`${Z}-steps-summary`,children:e.single.summary})]}):null,e.single.outcome?/* @__PURE__ */ _(`span`,{class:`${Z}-steps-denied`,children:e.single.outcome}):null]}):/* @__PURE__ */ _(g,{children:e.tools.map(({name:e,count:t},n)=>/* @__PURE__ */ v(`span`,{class:`${Z}-steps-name`,children:[n>0?/* @__PURE__ */ _(`span`,{class:`${Z}-steps-sep`,"aria-hidden":`true`,children:`·`}):null,e,t>1?/* @__PURE__ */ v(`span`,{class:`${Z}-steps-count`,children:[`×`,t]}):null]},e))})}function Qf({view:e}){let t=e.statusLabel&&e.status!==`running`&&!(e.decision&&af(e.status))?/* @__PURE__ */ _(`span`,{class:e.status===`failed`?`${Z}-steps-failed`:`${Z}-steps-denied`,children:e.statusLabel}):null;return/* @__PURE__ */ v(g,{children:[e.decision?/* @__PURE__ */ _(of,{decision:e.decision}):null,t]})}function $f({view:e,strings:t,durationMs:n,standalone:r=!1}){let[i,a]=h(!1);return/* @__PURE__ */ v(r?`div`:`li`,{class:`${Z}-steps-row`,"data-testid":Y.toolStep,"data-status":e.status,children:[/* @__PURE__ */ _(`span`,{class:`${Z}-steps-row-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(rf,{status:e.status})}),/* @__PURE__ */ v(`div`,{class:`${Z}-steps-row-main`,children:[/* @__PURE__ */ v(`button`,{type:`button`,class:`${Z}-steps-row-head`,"aria-expanded":i,onClick:()=>a(!i),children:[/* @__PURE__ */ v(`span`,{class:`${Z}-steps-row-label`,children:[/* @__PURE__ */ _(`span`,{class:`${Z}-steps-row-name`,children:e.name}),e.system?/* @__PURE__ */ _(`span`,{class:`${Z}-steps-row-system`,children:e.system}):null,e.summary?/* @__PURE__ */ _(`span`,{class:`${Z}-steps-row-summary`,children:e.summary}):null]}),/* @__PURE__ */ _(Qf,{view:e}),n===void 0?null:/* @__PURE__ */ _(`span`,{class:`${Z}-steps-time`,children:Gf(n)}),/* @__PURE__ */ _(`span`,{class:`${Z}-steps-chevron`,"data-open":i?`true`:void 0,children:/* @__PURE__ */ _(rc,{})})]}),i?/* @__PURE__ */ _(`div`,{class:`${Z}-steps-row-body`,children:/* @__PURE__ */ _(sf,{view:e,strings:t})}):null]})]})}function ep({part:e,current:t,reasoningMs:n,strings:r,standalone:a=!1}){let[o,s]=h(!1),c=p(()=>i(()=>e.textSig.value.trim()===``),[e]).value,l=/* @__PURE__ */ _(`span`,{class:t?`${Z}-steps-thought-label ${Z}-steps-live`:`${Z}-steps-thought-label`,children:Wf({streaming:t,reasoningMs:n},r)});return/* @__PURE__ */ v(a?`div`:`li`,{class:`${Z}-steps-row ${Z}-steps-thought`,"data-status":`thought`,"data-testid":a?Y.reasoning:void 0,children:[/* @__PURE__ */ _(`span`,{class:`${Z}-steps-row-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(jc,{})}),/* @__PURE__ */ v(`div`,{class:`${Z}-steps-row-main`,children:[c?l:/* @__PURE__ */ v(`button`,{type:`button`,class:`${Z}-steps-row-head`,"aria-expanded":o,onClick:()=>s(!o),children:[l,/* @__PURE__ */ _(`span`,{class:`${Z}-steps-chevron`,"data-open":o?`true`:void 0,children:/* @__PURE__ */ _(rc,{})})]}),o&&!c?/* @__PURE__ */ _(`div`,{class:`${Z}-steps-thought-text ${Z}-reasoning-body`,children:/* @__PURE__ */ _(Jc,{textSig:e.textSig,doneSig:e.doneSig})}):null]})]})}const tp=N.cssPrefix,np=b(rp);function rp({message:e,status:t,createdAt:n,strings:r,locale:a,responseMode:o,showReasoning:s,stepDisplay:c,showSources:l,interactive:u=!1,superseded:d=!1,tool:f,onRetry:m,enableMessageFeedback:h=!1,onFeedback:g,reconnecting:y=!1,clientToolRunning:b=!1,onCardAction:x}){let S=[...p(()=>i(()=>e.partsSig.value),[e]).value];for(let t of e.attachments??[])t.url&&!S.some(e=>e.kind===`file`&&e.url===t.url)&&S.push({kind:`file`,url:t.url,mediaType:t.mediaType,filename:t.name,fileId:t.id,fileSize:t.size});let C=p(()=>i(()=>vo(e)),[e,t,e.canceled]),w=p(()=>i(()=>qd(e)),[e]),T=p(()=>i(()=>s&&Jd(e)),[e,s]),E=p(()=>i(()=>bo(e,T.value)),[e,T,t,e.canceled]),D=p(()=>i(()=>!Ja(e)),[e]),O=t===`streaming`,k=e.role===`assistant`&&b,A=e.role===`assistant`&&(O||k),j=O||k,ee=Xd({streaming:A,responseMode:o,reasoningVisible:T.value,hasAnswerText:w.value,emptyReply:C.value,hidden:E.value}),{bufferedHold:M,showStreamDots:te}=ee;if(ee.hidden)return null;let N=ap(n,a),ne=e.role===`assistant`||e.role===`operator`,re=h&&!!g&&!!e.serverMessageId&&ne&&!j&&t!==`error`&&!C.value,ie=j?``:S.filter(e=>e.kind===`text`).map(t=>e.role===`assistant`?va(t.textSig.peek()):t.textSig.peek()).join(`
37
37
 
38
38
  `).trim(),P=!j&&t!==`error`&&!C.value&&ie.length>0,ae=e.canceled===!0||t===`error`,oe=/* @__PURE__ */ new Map;for(let[n,i]of S.entries()){if(i.kind!==`tool`)continue;let a=Id(i.toolMetadata),o=xe(ef(i),{turn:{live:A||a&&!d,cutOff:ae,superseded:d,submitted:e.continuationStreaming===!0&&i.approvalSig.value?.approved===void 0,canAct:u&&t===`complete`&&to(e,n),interrupted:a&&Hd(i.errorSig.value)},reader:{decides:!0},display:c,strings:r});oe.set(i.toolCallId,o.placement===`card`&&!f?.humanInLoop?{...o,placement:`hidden`}:o)}function F(e){let t=oe.get(e.toolCallId);if(!t)throw Error(`no step view for ${e.toolCallId}`);return t}let se=Bf(S,{showReasoning:s,showSources:l,viewOf:F}),ce=Uf(S),le=e.canceled===!0&&!O&&D.value&&T.value,ue=se.at(-1),de=ue?.kind===`steps`?ue.indices.at(-1):ue?.index;function I(n,i){return/* @__PURE__ */ _(op,{part:n,generativeUi:e.role===`assistant`,onCardAction:x,current:A&&i===de,reasoningMs:e.stepTimings?.[ce[i]??-1]?.reasoningMs,strings:r,locale:a,showReasoning:s,showSources:l,view:n.kind===`tool`?oe.get(n.toolCallId):void 0,canAct:u&&t===`complete`&&(n.kind!==`tool`||to(e,i)),superseded:d,continuationStreaming:e.continuationStreaming===!0,tool:f},`${lp(n)}#${i}`)}let fe=re||P;return/* @__PURE__ */ _(`div`,{class:`${tp}-bubble-row`,"data-role":e.role,"aria-busy":A?`true`:void 0,"data-testid":Pc(Y.messageBubble,e.serverMessageId??e.id),children:/* @__PURE__ */ v(`div`,{class:`${tp}-bubble-col`,children:[/* @__PURE__ */ v(`div`,{class:`${tp}-bubble`,children:[e.role===`operator`&&e.operatorInitials?/* @__PURE__ */ _(`span`,{class:`${tp}-bubble-author`,children:e.operatorInitials}):null,/* @__PURE__ */ v(`div`,{class:`${tp}-bubble-body`,children:[M?/* @__PURE__ */ _(dp,{label:r.loading}):se.flatMap((t,n)=>t.kind===`part`?[I(t.part,t.index)]:t.rows.some(e=>e.kind===`tool`)?[/* @__PURE__ */ _(Jf,{rows:t.rows,steps:t.indices.map(e=>ce[e]??-1),stepTimings:e.stepTimings,timed:!ae,strings:r,running:A&&n===se.length-1,runStartedAt:e.runStartedAt},`steps#${t.indices[0]}`)]:t.rows.map((e,n)=>I(e.part,t.indices[n]??n))),le?/* @__PURE__ */ v(`div`,{class:`${tp}-steps-row`,"data-status":`stopped`,"data-testid":Y.replyStopped,children:[/* @__PURE__ */ _(`span`,{class:`${tp}-steps-row-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Ls,{})}),/* @__PURE__ */ _(`div`,{class:`${tp}-steps-row-main`,children:/* @__PURE__ */ _(`span`,{class:`${tp}-steps-stopped-label`,children:r.statusStopped})})]}):null,te&&!y?/* @__PURE__ */ _(up,{}):null,t===`error`||C.value?/* @__PURE__ */ _(eu,{text:cp(e,t,r),retryLabel:r.errorRetry,onRetry:m?()=>m(e):void 0,retryTestId:Y.messageRetry}):null,y&&A?/* @__PURE__ */ _(eu,{text:r.errorReconnecting,retryTestId:Y.messageRetry}):null]})]}),N||fe?/* @__PURE__ */ v(`div`,{class:`${tp}-bubble-meta`,children:[N?/* @__PURE__ */ _(`time`,{class:`${tp}-bubble-time`,dateTime:N.iso,title:N.full,children:N.short}):null,fe?/* @__PURE__ */ v(`div`,{class:`${tp}-bubble-actions`,children:[re&&e.serverMessageId?/* @__PURE__ */ _(Kd,{messageId:e.serverMessageId,initial:e.feedback??null,strings:r,onFeedback:g}):null,P?/* @__PURE__ */ _(ip,{text:ie,strings:r}):null]}):null]}):null]})})}function ip({text:e,strings:t}){let[n,r]=h(!1);function i(){navigator.clipboard?.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})}let a=n?t.copied:t.copy;return/* @__PURE__ */ _(`button`,{type:`button`,class:`${tp}-msg-action`,"data-active":n?`true`:void 0,"aria-label":a,title:a,onClick:i,"data-testid":Y.messageCopy,children:_(n?Zs:wc,{})})}function ap(e,t){if(typeof e!=`number`||!Number.isFinite(e))return null;try{let n=new Date(e);return{short:n.toLocaleTimeString(t,{hour:`numeric`,minute:`2-digit`}),full:n.toLocaleString(t,{dateStyle:`full`,timeStyle:`short`}),iso:n.toISOString()}}catch{return null}}function op({part:e,generativeUi:t,onCardAction:n,current:r,reasoningMs:i,strings:a,locale:o,showReasoning:s,showSources:c,view:l,canAct:u,superseded:d,continuationStreaming:f,tool:p}){switch(e.kind){case`step-start`:return null;case`text`:return/* @__PURE__ */ _(Jc,{textSig:e.textSig,doneSig:e.doneSig,generativeUi:t,strings:a,onCardAction:n});case`reasoning`:return s?/* @__PURE__ */ _(ep,{part:e,current:r,reasoningMs:i,strings:a,standalone:!0}):null;case`tool`:return l?.placement!==`card`||!p?null:l.card===`questions`?/* @__PURE__ */ _(jf,{part:e,strings:a,active:u,superseded:d,continuationStreaming:f,onDecision:p.onDecision,onEdit:p.onEdit}):/* @__PURE__ */ _(df,{part:e,view:l,strings:a,locale:o,canAct:u,onDecision:p.onDecision,onEdit:p.onEdit,preview:p.preview});case`file`:return/* @__PURE__ */ _(sp,{part:e,strings:a});case`source`:return c?/* @__PURE__ */ _(Qd,{part:e,strings:a}):null}}function sp({part:e,strings:t}){let n=e.filename??t.file;if(e.mediaType.startsWith(`image/`))return/* @__PURE__ */ _(`a`,{class:`${tp}-file-image`,href:e.url,target:`_blank`,rel:`noreferrer noopener`,title:n,"data-testid":Y.messageFile,children:/* @__PURE__ */ _(`img`,{src:e.url,alt:n,loading:`lazy`})});let r=(n.includes(`.`)?n.split(`.`).pop():e.mediaType.split(`/`).pop())?.toUpperCase(),i=e.fileSize===void 0?void 0:Il(e.fileSize);return/* @__PURE__ */ v(`a`,{class:`${tp}-file-chip`,href:e.url,target:`_blank`,rel:`noreferrer noopener`,title:n,"data-testid":Y.messageFile,children:[/* @__PURE__ */ _(`span`,{class:`${tp}-file-chip-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(ic,{})}),/* @__PURE__ */ v(`span`,{class:`${tp}-file-chip-text`,children:[/* @__PURE__ */ _(`span`,{class:`${tp}-file-chip-name`,children:n}),/* @__PURE__ */ _(`span`,{class:`${tp}-file-chip-meta`,children:[r,i].filter(Boolean).join(` · `)})]})]})}function cp(e,t,n){return e.errorText?e.errorText:t===`error`&&e.role===`assistant`?n.errorServer:n.errorGeneric}function lp(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 up(){return/* @__PURE__ */ v(`span`,{class:`${tp}-typing`,"data-testid":Y.typingDots,"aria-hidden":`true`,children:[/* @__PURE__ */ _(`span`,{}),/* @__PURE__ */ _(`span`,{}),/* @__PURE__ */ _(`span`,{})]})}function dp({label:e}){return/* @__PURE__ */ v(`span`,{class:`${tp}-loading`,role:`status`,children:[/* @__PURE__ */ _(`span`,{class:`${tp}-loading-spinner`,"aria-hidden":`true`}),/* @__PURE__ */ _(`span`,{class:`${tp}-loading-label`,children:e})]})}const fp=N.cssPrefix;function pp({messagesSig:e,reconnectingSig:t,pageToolRunning:n,strings:r,notice:i,locale:a,responseMode:o,showReasoning:c,stepDisplay:l,showSources:d,enableMessageFeedback:p,onFeedback:g,loading:y,onLoadPreviousMessages:b,idle:x,controlMode:S=`ai-agent`,tool:C,onRetry:w,onCardAction:T}){let E=m(null),D=s(()=>e.value),O=mp(a),[k,A]=h(!1),[j,ee]=h(!1),M=m(!1),te=m(!1),[N,ne]=h(),re=m(!1),ie=m(!1),P=m(!1),ae=m(0);function oe(){return P.current||performance.now()-ae.current<350}let F=m(0);function se(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`}function ce(e){return A(e.scrollHeight-e.scrollTop-e.clientHeight>240)}function le(e){F.current=performance.now(),e.scrollTop=e.scrollHeight,se(e)}function ue(e,t){le(e);let n=t,r=0;function i(){ie.current||oe()||(le(e),--n>0&&(r=requestAnimationFrame(i)))}return t>0&&(r=requestAnimationFrame(i)),()=>cancelAnimationFrame(r)}function de(e,t){let n,r,i,a=-1;function o(){n.disconnect(),r.disconnect(),clearTimeout(i)}function s(){if(ie.current||oe()||a>=0&&e.scrollTop<a-4)return o();le(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}let I=D.value[0]?.id;f(()=>{let e=E.current;if(e&&D.value.length!==0&&!te.current&&(re.current=!0,D.value.some(e=>e.role===`user`)))return de(e,300)},[I]);let fe=m(0);u(()=>{let e=E.current,t=D.value,n=fe.current;if(fe.current=t.length,e&&re.current&&!te.current){if(t.slice(n).some(e=>e.role===`user`))return ie.current=!1,ue(e,3);t.some(e=>e.role===`user`)&&(ie.current||oe()||e.scrollHeight-e.scrollTop-e.clientHeight<120&&le(e))}},[D.value.length]);let pe=m(null);u(()=>{let e=E.current,t=D.value.at(-1),n=pe.current;if(pe.current=t?{id:t.id,streaming:t.status===`streaming`}:null,e&&re.current&&t&&t.id===n?.id&&!n.streaming&&t.status===`streaming`)return ie.current=!1,ue(e,3)},[D.value]),u(()=>{let e=E.current;if(!e)return;let t=D.value.at(-1);if(!t||t.status!==`streaming`&&!D.value.some(e=>e.role===`user`))return;let n=()=>{ie.current||oe()||e.scrollHeight-e.scrollTop-e.clientHeight<240&&le(e)};if(t.status!==`streaming`)return de(e,300);n();let r=new MutationObserver(n);return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>r.disconnect()},[D.value]),u(()=>{let e=E.current;if(!e)return;let t=()=>{ce(e),se(e),performance.now()-F.current>150&&(ie.current=e.scrollHeight-e.scrollTop-e.clientHeight>8)};function n(){ie.current=!0}function r(e){e.deltaY<0&&n()}let i=0;function a(e){i=e.touches[0]?.clientY??0,P.current=!0}function o(e){(e.touches[0]?.clientY??0)>i+4&&n()}function s(){P.current=!1,ae.current=performance.now()}function c(){P.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}),ce(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)}},[]),u(()=>{let e=E.current;if(!e)return;let t=e.clientHeight,n=new ResizeObserver(()=>{if(e.clientHeight===t)return;let n=e.scrollHeight-e.scrollTop-t<=120;t=e.clientHeight,n&&!te.current&&D.value.some(e=>e.role===`user`)&&(ie.current=!1,le(e))});return n.observe(e),()=>n.disconnect()},[]);function me(){let e=E.current;e&&(ie.current=!1,le(e))}let he=D.value.filter(e=>!e.ephemeral),ge=he[0],_e=ge?.serverMessageId??ge?.id,ve=!!(b&&he.length>=50&&_e!==N);async function L(){if(!b||M.current)return;let e=E.current,t=e?.scrollHeight??0,n=e?.scrollTop??0;M.current=!0,te.current=!0,ee(!0);try{let r=await b();r===!1&&_e&&ne(_e),r&&e&&(await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),e.scrollTop=n+e.scrollHeight-t,se(e),ce(e))}finally{te.current=!1,M.current=!1,ee(!1)}}let ye=[],be=``,xe=D.value.at(-1)?.id,Se=t?.value===!0,Ce=n===!0;for(let e of D.value){if(e.role===`assistant`&&e.id!==xe&&vo(e))continue;let t=hp(e.createdAt);t&&t!==be&&(ye.push(/* @__PURE__ */ _(`div`,{class:`${fp}-date-divider`,children:/* @__PURE__ */ _(`span`,{class:`${fp}-date-pill`,title:gp(e.createdAt,O),children:_p(e.createdAt,r,O)})},`day:${t}`)),be=t);let n=e.retryAction!==void 0||e.role===`assistant`&&e.id===xe?yo(D.value,e):void 0,i=n!==void 0&&(n.kind!==`continue-assistant`||S===`ai-agent`);ye.push(/* @__PURE__ */ _(np,{message:e,status:e.status,createdAt:e.createdAt,strings:r,locale:O,responseMode:o,showReasoning:c,stepDisplay:l,showSources:d,interactive:!!x&&S===`ai-agent`&&e.id===xe,superseded:e.id!==xe,tool:C,onRetry:x&&i&&(e.role===`user`||e.id===xe)?w:void 0,enableMessageFeedback:p,onFeedback:g,reconnecting:Se&&e.id===xe,clientToolRunning:Ce&&e.id===xe&&e.role===`assistant`,onCardAction:T},e.id))}return/* @__PURE__ */ v(`div`,{class:`${fp}-list-wrap`,children:[/* @__PURE__ */ v(`div`,{ref:E,class:`${fp}-list ${fp}-list--fade`,part:`messages`,role:`log`,"aria-live":`polite`,"aria-relevant":`additions text`,children:[y&&D.value.length===0?/* @__PURE__ */ _(`div`,{class:`${fp}-list-loading`,role:`status`,children:r.conversationLoading}):null,i&&!ve?/* @__PURE__ */ _(`div`,{class:`${fp}-chat-notice`,role:`note`,"data-testid":Y.chatNotice,children:/* @__PURE__ */ _(Yc,{text:i})}):null,ve?/* @__PURE__ */ _(`div`,{class:`${fp}-load-previous`,children:/* @__PURE__ */ _(`button`,{type:`button`,onClick:L,disabled:j,"aria-busy":j,"data-testid":Y.loadPreviousMessages,children:r.loadPreviousMessages})}):null,ye]}),k?/* @__PURE__ */ _(`button`,{type:`button`,class:`${fp}-jump`,onClick:me,"aria-label":r.scrollToBottom,title:r.scrollToBottom,"data-testid":Y.scrollToBottom,children:/* @__PURE__ */ _(rc,{})}):null]})}function mp(e){try{return Intl.getCanonicalLocales(e)[0]}catch{return}}function hp(e){if(typeof e!=`number`||!Number.isFinite(e))return``;let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`}function gp(e,t){if(typeof e!=`number`||!Number.isFinite(e))return``;try{return new Date(e).toLocaleDateString(t,{dateStyle:`full`})}catch{return``}}function _p(e,t,n){let r=new Date(e);function i(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}let a=Math.round((i(/* @__PURE__ */ new Date)-i(r))/864e5);return a<=0?t.dateToday:a===1?t.dateYesterday:a<7?r.toLocaleDateString(n,{weekday:`long`}):r.toLocaleDateString(n,{month:`long`,day:`numeric`,year:`numeric`})}function vp({panelEl:e,resize:t,position:n,edge:r,initialSize:i,onSizeChange:a,onResizeStart:o,strings:s}){let c=N.cssPrefix,l=m(null),[d,f]=h(null),p=i?.width,g=i?.height;if(u(()=>{if(!e)return;let n=e.style;n.setProperty(`--${c}-resize-min-w`,t.minWidth??`320px`),n.setProperty(`--${c}-resize-min-h`,t.minHeight??`400px`),t.maxWidth&&n.setProperty(`--${c}-resize-max-w`,t.maxWidth),t.maxHeight&&n.setProperty(`--${c}-resize-max-h`,t.maxHeight),p!==void 0&&g!==void 0&&(n.setProperty(`--${c}-widget-w`,`${p}px`),n.setProperty(`--${c}-widget-h`,`${g}px`)),f(Math.round(e.getBoundingClientRect().width/window.innerWidth*100))},[e,t.minWidth,t.maxWidth,t.minHeight,t.maxHeight,c,p,g]),!e)return null;let v=n.startsWith(`top-`),y=n.endsWith(`-right`),b=y?-1:1,x=v?1:-1,S=`${c}-resize-grip--${r?`edge`:`${v?`bottom`:`top`}-${y?`left`:`right`}`}`;function C(e){e.setAttribute(`data-resizing`,``),o?.()}function w(e,t,n){e.style.setProperty(`--${c}-widget-w`,`${t}px`),r||e.style.setProperty(`--${c}-widget-h`,`${n}px`)}function T(e){let t=e.getBoundingClientRect(),n={width:Math.round(t.width),height:Math.round(t.height)};e.style.setProperty(`--${c}-widget-w`,`${n.width}px`),r||e.style.setProperty(`--${c}-widget-h`,`${n.height}px`),f(Math.round(n.width/window.innerWidth*100)),a(n)}function E(t){if(!e)return;let n=e.getBoundingClientRect();l.current={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,startW:n.width,startH:n.height,moved:!1},t.currentTarget.setPointerCapture(t.pointerId),t.preventDefault()}function D(t){let n=l.current;if(!n||t.pointerId!==n.pointerId||!e)return;let i=(t.clientX-n.startX)*b,a=r?0:(t.clientY-n.startY)*x;(n.moved||i!==0||a!==0)&&(n.moved||C(e),n.moved=!0,w(e,n.startW+i,n.startH+a))}function O(t){let n=l.current;n&&t.pointerId===n.pointerId&&e&&(t.currentTarget.releasePointerCapture(t.pointerId),l.current=null,n.moved&&(e.removeAttribute(`data-resizing`),T(e)))}function k(e){return e===`ArrowLeft`?[-1,0]:e===`ArrowRight`?[1,0]:r?null:e===`ArrowUp`?[0,-1]:e===`ArrowDown`?[0,1]:null}function A(t){let n=k(t.key);if(!n||!e)return;t.preventDefault();let r=t.shiftKey?64:16;t.repeat||C(e);let i=e.getBoundingClientRect();w(e,i.width+n[0]*r*b,i.height+n[1]*r*x)}function j(t){k(t.key)&&e&&(e.removeAttribute(`data-resizing`),T(e))}return/* @__PURE__ */ _(`div`,{class:`${c}-resize-grip ${S}`,role:`separator`,"aria-orientation":`vertical`,"aria-label":s.resizeHandle,"aria-valuenow":d??void 0,tabIndex:0,title:s.resizeHandle,onPointerDown:E,onPointerMove:D,onPointerUp:O,onPointerCancel:O,onKeyDown:A,onKeyUp:j,"data-testid":Y.resizeGrip,children:r?null:/* @__PURE__ */ _(Ks,{})})}const yp=N.cssPrefix;function bp({suggestions:e,strings:t,onPick:n,disabled:r=!1}){let i=m(null),[a,o]=h({start:!1,end:!1});return u(()=>{let e=i.current;if(!e)return;function t(){if(!e)return;let t=Math.abs(e.scrollLeft),n=t>1,r=t<e.scrollWidth-e.clientWidth-1;o(e=>e.start===n&&e.end===r?e:{start:n,end:r})}t(),e.addEventListener(`scroll`,t,{passive:!0});let n=typeof ResizeObserver>`u`?void 0:new ResizeObserver(t);return n?.observe(e),()=>{e.removeEventListener(`scroll`,t),n?.disconnect()}},[e]),e.length===0?null:/* @__PURE__ */ _(`div`,{ref:i,class:`${yp}-suggestions`,role:`group`,"aria-label":t.suggestedReplies,"data-cut-start":a.start?`true`:void 0,"data-cut-end":a.end?`true`:void 0,children:e.map((e,t)=>/* @__PURE__ */ _(`button`,{type:`button`,class:`${yp}-suggestion`,onClick:()=>n(e),disabled:r,"data-testid":Pc(Y.suggestion,t),children:e.label},e.id))})}const xp=N.cssPrefix,Sp=`.${xp}-header, .${xp}-back-header, .${xp}-home-hero`;function Cp(e,t){u(()=>{if(!t||!e)return;function n(e){return Number.parseFloat(e)||0}function r(e,t){return Math.min(t,Math.max(-t,e))}let i=null,a=t=>{let r=t.target;if(!(r instanceof Element)||!r.closest(Sp)||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(`--${xp}-modal-dx`)),dy:n(e.style.getPropertyValue(`--${xp}-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(`--${xp}-modal-dx`,`${n}px`),e.style.setProperty(`--${xp}-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 wp({containerRef:e,onDrop:t,accept:n,disabled:r=!1}){let[i,a]=h();return u(()=>{if(r){a(void 0);return}let i=e.current;if(!i)return;let o=0;function s(e){o+=1,e.dataTransfer?.types.includes(`Files`)&&(e.preventDefault(),a([...e.dataTransfer.items].every(e=>e.kind!==`file`||Ll(e.type,n))?`accept`:`reject`))}function c(){--o,o>0||(o=0,a(void 0))}function l(e){e.dataTransfer?.types.includes(`Files`)&&e.preventDefault()}function u(e){o=0,a(void 0),e.dataTransfer&&(e.preventDefault(),t(e.dataTransfer.items))}return i.addEventListener(`dragenter`,s),i.addEventListener(`dragleave`,c),i.addEventListener(`dragover`,l),i.addEventListener(`drop`,u),()=>{i.removeEventListener(`dragenter`,s),i.removeEventListener(`dragleave`,c),i.removeEventListener(`dragover`,l),i.removeEventListener(`drop`,u)}},[n,e,r,t]),r?void 0:i}const Q=N.cssPrefix;function Tp(e){let{options:t,onClose:n}=e,r=t.strings,i=m(null);u(()=>{let e=i.current;if(!e||!n)return;let t=Wc(e);function r(e){e.key===`Escape`&&n?.()}return e.addEventListener(`keydown`,r),()=>{t(),e.removeEventListener(`keydown`,r)}},[n]);let a=e.composerApiRef,o=e.composerActive&&e.view===`chat`&&!e.sendPreparing&&e.options.features.fileUpload,s=wp({containerRef:i,onDrop:l(e=>{o&&a.current?.attachFromDrop(e)},[a,o]),accept:e.options.attachments.accept,disabled:!o});return Cp(i.current,t.mode===`modal`),/* @__PURE__ */ v(`div`,{ref:i,class:`${Q}-panel`,part:`panel`,role:`dialog`,"aria-modal":`false`,"aria-label":r.panelTitle,style:{position:`relative`},"data-testid":Y.panel,children:[/* @__PURE__ */ _(Ep,{...e,containerEl:i.current,dragOver:s}),/* @__PURE__ */ _(Pp,{poweredBy:e.options.poweredBy,strings:e.options.strings})]})}function Ep(e){let{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,composerKey:c,panelSize:l,view:u,isStreaming:d,isMemoryCompacting:f,canReleaseQueuedMessages:p,queueManualMessages:m,replyAwaitsCard:y,sendPreparing:b,attachmentUploadsSig:x,controlMode:S,assignedOperator:C,operatorAvailable:w,operatorRequestEnabled:T,onRequestOperator:E,onCancelOperatorRequest:D,loadingMessages:O,onLoadPreviousMessages:k,messagesSig:A,reconnectingSig:j,agent:ee,ticketReference:te,login:N,onStartAsGuest:ne,suggestions:re,initialWidgetSize:ie,onClose:P,onBack:ae,onExpand:oe,onToggleHistory:F,onSelectHistoryConversation:se,onNewConversation:ce,onWidgetSizeChange:le,onSend:ue,onStop:de,onSuggestion:I,tool:fe,onRetry:pe,onMessageFeedback:me,onCardAction:he,containerEl:ge,dragOver:_e,composerApiRef:ve}=e,L=t.strings,ye=S===`operator`?C:void 0,be=ye?{name:ye.name??ye.initials,avatar:ye.avatar,title:L.operatorBadgeTitle,status:`online`}:ee,xe=t.header.showNotice?M(L,t.header.notice||`chatNotice`):void 0,Se=s(()=>A.value.some(e=>!e.ephemeral&&e.role!==`system`)).value,Ce=s(()=>A.value.length>0).value,[we,Te]=h(),Ee=we===o,De=t.features.emailTranscript&&Se?()=>Te(o):void 0,Oe=N.gate?/* @__PURE__ */ _(Np,{login:{...N,gate:N.gate},alone:!Ce,onStartAsGuest:ne,strings:L}):/* @__PURE__ */ v(g,{children:[S&&S!==`ai-agent`?/* @__PURE__ */ _(Op,{controlMode:S,operatorName:C?.name??C?.initials,operatorAvailable:w,onCancelOperatorRequest:D,strings:L}):null,f&&S===`ai-agent`?/* @__PURE__ */ v(`div`,{class:`${Q}-loading ${Q}-compaction-status`,role:`status`,"data-testid":Y.compactionStatus,children:[/* @__PURE__ */ _(`span`,{class:`${Q}-loading-spinner`,"aria-hidden":`true`}),L.compactingContext]}):null,!d&&!f&&S===`ai-agent`&&/* @__PURE__ */ _(bp,{suggestions:re,strings:L,onPick:I,disabled:b}),/* @__PURE__ */ _(gu,{options:t,transport:n,feedback:r,bus:i,persistence:a,conversationId:o,maxMessageCharacters:e.maxMessageCharacters,isStreaming:d,pageToolRunning:e.pageToolRunning,isMemoryCompacting:f,canReleaseQueuedMessages:p,queueManualMessages:m,replyAwaitsCard:y,active:e.composerActive&&u===`chat`,isPreparing:b,attachmentUploadsSig:x,operatorRequestEnabled:T,canRequestOperator:Se,controlMode:S,onRequestOperator:E,onSend:ue,onStop:de,apiRef:ve},c)]});return/* @__PURE__ */ v(g,{children:[u===`history`?/* @__PURE__ */ _(Dp,{strings:L,onBack:F,onClose:P,showClose:hs(t.mode,l,t.actions)}):/* @__PURE__ */ v(`header`,{class:`${Q}-header`,part:`header`,"data-variant":t.header.variant,"data-testid":Y.panelHeader,children:[ae?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-icon-btn`,onClick:ae,"aria-label":L.moduleBack,title:L.moduleBack,children:/* @__PURE__ */ _(ec,{})}):null,be?/* @__PURE__ */ _(Fu,{agent:be,strings:L,ticketReference:te,person:!!ye}):/* @__PURE__ */ _(`h1`,{children:L.panelTitle}),/* @__PURE__ */ _(bl,{panelProps:N.gate?{...e,options:{...t,actions:t.actions.filter(e=>e!==`history`)}}:e,variant:`chat`,onEmailTranscript:De,onLogIn:N.menuLogIn})]}),u===`history`?/* @__PURE__ */ _(Gu,{transport:n,strings:L,locale:t.locale,persistence:a,onSelect:se,onNewConversation:ce}):/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(qu,{state:_e,strings:L}),N.strip?/* @__PURE__ */ _(jp,{strip:N.strip,onLogIn:N.onLogIn,onHide:N.onHidePrompt,strings:L}):null,N.gate&&!Ce?null:/* @__PURE__ */ _(pp,{messagesSig:A,reconnectingSig:j,pageToolRunning:e.pageToolRunning,strings:L,notice:xe,locale:t.locale,responseMode:t.responseMode,showReasoning:t.showReasoning,stepDisplay:t.stepDisplay,showSources:t.showSources,enableMessageFeedback:t.enableMessageFeedback,onFeedback:me,loading:O,onLoadPreviousMessages:k,idle:!d&&!b,controlMode:S,tool:fe,onRetry:pe,onCardAction:he}),Oe,/* @__PURE__ */ _(Ap,{disclaimer:t.composerDisclaimer}),Ee?/* @__PURE__ */ _(nd,{transport:n,strings:L,knownEmail:$u({tokenEmail:N.email,userContext:t.userContext}),onClose:()=>Te(void 0)}):null]}),t.size.resize?.enabled?/* @__PURE__ */ _(vp,{panelEl:ge,resize:t.size.resize,position:t.position,edge:t.mode===`drawer`,initialSize:ie,onSizeChange:le,onResizeStart:t.mode===`floating`&&l===`expanded`?oe:void 0,strings:L}):null]})}function Dp({strings:e,onBack:t,onClose:n,showClose:r}){return/* @__PURE__ */ v(`header`,{class:`${Q}-header`,part:`header`,children:[/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-icon-btn`,onClick:t,"aria-label":e.historyBack,title:e.historyBack,children:/* @__PURE__ */ _(ec,{})}),/* @__PURE__ */ _(`h1`,{children:e.historyTitle}),r?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-icon-btn`,onClick:n,"aria-label":e.close,title:e.close,children:/* @__PURE__ */ _(js,{})}):null]})}function Op({controlMode:e,operatorName:t,operatorAvailable:n,onCancelOperatorRequest:r,strings:i}){let[a,o]=h(!1),s=kp(e,t,n,i);function c(){r&&(o(!0),r().finally(()=>o(!1)))}return/* @__PURE__ */ v(`div`,{class:`${Q}-operator-banner`,"data-mode":e,"data-available":n===!1?`false`:void 0,"data-testid":Y.operatorBanner,children:[/* @__PURE__ */ _(`span`,{class:`${Q}-operator-pulse`,"aria-hidden":`true`}),/* @__PURE__ */ _(`span`,{class:`${Q}-operator-label`,role:`status`,children:s}),e===`awaiting-operator`&&r?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-icon-btn ${Q}-operator-dismiss`,onClick:c,disabled:a,"aria-label":i.cancelOperatorRequest,title:i.cancelOperatorRequest,"data-testid":Y.cancelOperatorRequest,children:/* @__PURE__ */ _(js,{})}):null]})}function kp(e,t,n,r){return e===`operator`?r.chattingWithOperator.replace(`{operator}`,t??``):n===!1?r.noOperatorAvailable:r.connectingOperator}function Ap({disclaimer:e}){return e?/* @__PURE__ */ _(`div`,{class:`${Q}-composer-footer`,children:/* @__PURE__ */ _(`div`,{class:`${Q}-disclaimer`,children:e})}):null}function jp({strip:e,onLogIn:t,onHide:n,strings:r}){let i=e.kind===`user`;return/* @__PURE__ */ v(`div`,{class:`${Q}-login-bar`,"data-kind":e.kind,role:i?`status`:`note`,"data-testid":i?Y.loggedIn:Y.loginBar,children:[/* @__PURE__ */ _(`span`,{class:`${Q}-login-bar-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Bs,{})}),i?/* @__PURE__ */ _(`span`,{class:`${Q}-login-bar-text`,children:e.who?r.loggedInAs.replace(`{name}`,e.who):r.loggedIn}):/* @__PURE__ */ v(g,{children:[/* @__PURE__ */ _(`span`,{class:`${Q}-login-bar-text`,children:r.loginPrompt}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-login-bar-action`,onClick:t,"data-testid":Y.loginBarAction,children:r.loginAction}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-icon-btn ${Q}-login-bar-hide`,onClick:n,"aria-label":r.dismissLoginPrompt,title:r.dismissLoginPrompt,"data-testid":Y.loginBarHide,children:/* @__PURE__ */ _(js,{})})]})]})}function Mp(e,t){return e.gate===`required`?t.loginRequired:e.canStartAsGuest?t.loginExpiredGuest:t.loginExpired}function Np({login:e,alone:t,onStartAsGuest:n,strings:r}){return/* @__PURE__ */ v(`div`,{class:`${Q}-login-gate`,"data-gate":e.gate,"data-alone":t?``:void 0,"data-testid":Y.loginGate,children:[/* @__PURE__ */ _(`span`,{class:`${Q}-login-gate-icon`,"aria-hidden":`true`,children:/* @__PURE__ */ _(Bs,{})}),/* @__PURE__ */ _(`p`,{class:`${Q}-login-gate-title`,role:`status`,children:Mp(e,r)}),e.canLogIn||e.canStartAsGuest?/* @__PURE__ */ v(`div`,{class:`${Q}-form-actions ${Q}-login-gate-actions`,children:[e.canStartAsGuest?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-form-skip`,onClick:n,"data-testid":Y.loginGateGuest,children:r.startAsGuest}):null,e.canLogIn?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Q}-form-submit`,onClick:e.onLogIn,"data-testid":Y.loginGateAction,children:r.loginAction}):null]}):null]})}function Pp({poweredBy:e,strings:t}){return e?/* @__PURE__ */ _(`div`,{class:`${Q}-poweredby-bar`,children:/* @__PURE__ */ _(Fp,{logoUrl:e.logoUrl,text:e.text??t.poweredBy.replace(`{name}`,N.displayName),href:e.href})}):null}function Fp({logoUrl:e,text:t,href:n}){let r=/* @__PURE__ */ v(g,{children:[e?/* @__PURE__ */ _(`img`,{class:`${Q}-poweredby-logo`,src:e,alt:``,loading:`lazy`}):null,t?/* @__PURE__ */ _(`span`,{children:t}):null]});return n?/* @__PURE__ */ _(`a`,{class:`${Q}-poweredby`,href:n,target:`_blank`,rel:`noopener noreferrer`,children:r}):/* @__PURE__ */ _(`span`,{class:`${Q}-poweredby`,children:r})}const Ip=N.cssPrefix;function Lp({panelProps:e,enabledModules:t,nav:n,bus:r,hasUnread:i,latestNews:a,onSelectConversation:o,onStartNewConversation:c,onSetPanelSize:d}){let f=e.options,p=f.strings,h=m(null),g=m(/* @__PURE__ */ new Set);u(()=>{let t=h.current;if(!t||!e.onClose)return;let n=Wc(t);function r(t){t.key===`Escape`&&e.onClose?.()}return t.addEventListener(`keydown`,r),()=>{n(),t.removeEventListener(`keydown`,r)}},[e.onClose]);let y=s(()=>n.sig.value).value,b=Ss(y),x=f.modules.byId[y.activeTab],S=e.composerActive&&x?.layout===`chat`&&b===void 0,C=e.composerApiRef,w=S&&e.view===`chat`&&!e.sendPreparing&&e.options.features.fileUpload,T=wp({containerRef:h,onDrop:l(e=>{w&&C.current?.attachFromDrop(e)},[C,w]),accept:e.options.attachments.accept,disabled:!w});Cp(h.current,f.mode===`modal`);let E=b?.kind===`content`,D=t.length>1&&Cs(y),O=m(null);u(()=>{if(E&&O.current===null)O.current=e.panelSize,e.panelSize===`normal`&&d(`expanded`);else if(!E&&O.current!==null){let e=O.current;O.current=null,d(e)}},[E]);let k={push:e=>n.push(e),pop:()=>n.pop(),switchTab:e=>n.switchTab(e),switchToLayout:e=>{let r=t.find(t=>t.layout===e);r&&n.switchTab(r.id)},selectConversation:o,startNewConversation:c};function A(t){return{options:f,transport:e.transport,strings:p,config:t,nav:k,bus:r,panelProps:e,latestNews:a}}let j=/* @__PURE__ */ _(bl,{panelProps:e,variant:`plain`});x&&g.current.add(x.id);let ee=t.filter(e=>g.current.has(e.id));function M(t){if(t.layout===`chat`)return/* @__PURE__ */ _(Ep,{...e,composerActive:S,containerEl:h.current,dragOver:T});let n=ju[t.layout].Root;return n?/* @__PURE__ */ _(n,{...A(t)}):null}function te(){return b?.kind===`content`?/* @__PURE__ */ _(dl,{id:b.id,title:b.title,transport:e.transport,strings:p,bus:r,onBack:()=>n.pop(),actions:j}):null}return/* @__PURE__ */ v(`div`,{ref:h,class:`${Ip}-panel ${Ip}-messenger`,part:`panel`,role:`dialog`,"aria-modal":`false`,"aria-label":p.panelTitle,style:{position:`relative`},"data-testid":Y.messengerHome,children:[/* @__PURE__ */ v(`div`,{class:`${Ip}-messenger-body`,children:[ee.map(e=>/* @__PURE__ */ _(`div`,{class:`${Ip}-messenger-pane`,hidden:E||e.id!==x?.id,children:M(e)},e.id)),te()]}),D?/* @__PURE__ */ _(Nu,{modules:t,activeTab:y.activeTab,strings:p,hasUnread:i,onSelect:e=>n.switchTab(e)}):null,/* @__PURE__ */ _(Pp,{poweredBy:f.poweredBy,strings:f.strings}),f.size.resize?.enabled&&(x?.layout!==`chat`||b)?/* @__PURE__ */ _(vp,{panelEl:h.current,resize:f.size.resize,position:f.position,edge:f.mode===`drawer`,initialSize:e.initialWidgetSize,onSizeChange:e.onWidgetSizeChange,onResizeStart:f.mode===`floating`&&e.panelSize===`expanded`?e.onExpand:void 0,strings:p}):null]})}function Rp(e){let t=N.cssPrefix,{site:n,blocks:r,strings:i,collapsed:a}=e,o=r?.navigation??[],s=r?.linkCards??[],c=a?i.expandSidebar:i.collapseSidebar;return/* @__PURE__ */ v(`aside`,{class:`${t}-sidebar`,"data-collapsed":a?`true`:`false`,"data-testid":Y.sidebar,children:[/* @__PURE__ */ v(`div`,{class:`${t}-sidebar-header`,children:[/* @__PURE__ */ _(zp,{site:n}),/* @__PURE__ */ _(`button`,{type:`button`,class:`${t}-sidebar-toggle`,"aria-label":c,"aria-expanded":a?`false`:`true`,title:c,onClick:e.onToggleCollapsed,"data-testid":Y.sidebarToggle,children:/* @__PURE__ */ _(Bp,{collapsed:a})})]}),a?null:/* @__PURE__ */ v(g,{children:[o.length>0?/* @__PURE__ */ _(`nav`,{class:`${t}-sidebar-section`,"data-section":`navigation`,children:/* @__PURE__ */ _(Vp,{items:o})}):null,s.length>0?/* @__PURE__ */ _(`div`,{class:`${t}-sidebar-section`,"data-section":`link-cards`,children:/* @__PURE__ */ _(Hp,{items:s})}):null,e.showConversations?/* @__PURE__ */ _(`div`,{class:`${t}-sidebar-conversations`,children:/* @__PURE__ */ _(Gu,{transport:e.transport,strings:e.strings,locale:e.locale,persistence:e.persistence,onSelect:e.onSelectConversation,onNewConversation:e.onNewConversation})}):null]})]})}function zp({site:e}){let t=N.cssPrefix;if(e?.logo?.url){let n=e.logo.alt??e.title??`Logo`;return/* @__PURE__ */ v(`picture`,{children:[e.logoDark?.url?/* @__PURE__ */ _(`source`,{srcset:e.logoDark.url,media:`(prefers-color-scheme: dark)`}):null,/* @__PURE__ */ _(`img`,{class:`${t}-sidebar-logo`,src:e.logo.url,alt:n})]})}return/* @__PURE__ */ _(`div`,{class:`${t}-sidebar-title`,children:e?.title??N.name})}function Bp({collapsed:e}){return/* @__PURE__ */ _(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`,"aria-hidden":`true`,children:e?/* @__PURE__ */ _(`polyline`,{points:`9 6 15 12 9 18`}):/* @__PURE__ */ _(`polyline`,{points:`15 6 9 12 15 18`})})}function Vp({items:e}){let t=N.cssPrefix;return/* @__PURE__ */ _(`ul`,{class:`${t}-sidebar-nav`,children:e.map(e=>/* @__PURE__ */ _(`li`,{children:/* @__PURE__ */ v(`a`,{class:`${t}-sidebar-nav-item`,href:e.href,target:e.href?`_blank`:void 0,rel:e.href?`noreferrer`:void 0,children:[e.icon?/* @__PURE__ */ _(`span`,{class:`${t}-sidebar-nav-icon`,"data-icon":e.icon}):null,/* @__PURE__ */ _(`span`,{class:`${t}-sidebar-nav-label`,children:e.label})]})},e.id??e.label))})}function Hp({items:e}){let t=N.cssPrefix;return/* @__PURE__ */ _(`div`,{class:`${t}-sidebar-cards`,children:e.map(e=>/* @__PURE__ */ v(`a`,{class:`${t}-sidebar-card`,href:e.href,target:e.href?`_blank`:void 0,rel:e.href?`noreferrer`:void 0,children:[/* @__PURE__ */ _(`div`,{class:`${t}-sidebar-card-label`,children:e.label}),e.description?/* @__PURE__ */ _(`div`,{class:`${t}-sidebar-card-desc`,children:e.description}):null]},e.id??e.label))})}const Up=N.cssPrefix;function Wp(e){return/* @__PURE__ */ v(`main`,{class:`${Up}-page-shell`,"data-sidebar-collapsed":e.sidebarCollapsed?`true`:`false`,children:[/* @__PURE__ */ _(Rp,{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}),/* @__PURE__ */ _(`section`,{class:`${Up}-page-chat`,"aria-label":e.strings.panelTitle,children:e.children})]})}const Gp=N.cssPrefix;function Kp({strings:e,text:t,onClose:n}){return/* @__PURE__ */ v(`div`,{class:`${Gp}-panel ${Gp}-panel-notice`,part:`panel`,role:`dialog`,"aria-label":e.panelTitle,"data-testid":Y.panelNotice,children:[n?/* @__PURE__ */ _(`button`,{type:`button`,class:`${Gp}-icon-btn ${Gp}-panel-notice-close`,onClick:n,"aria-label":e.close,title:e.close,children:/* @__PURE__ */ _(js,{})}):null,/* @__PURE__ */ _(`p`,{class:`${Gp}-panel-notice-text`,children:t})]})}const qp=R.scope(`hitl`);function Jp(e){return e.kind===`tool`&&Id(e.toolMetadata)&&(e.stateSig.value===`input-available`||e.stateSig.value===`approval-responded`&&e.approvalSig.value?.approved===!0)}function Yp(e,t){t.errorSig.value=Ud(t.toolCallId),t.stateSig.value=`output-error`,e.partsSig.value=[...e.partsSig.value]}function Xp(e,t){let n=e.slice(0,e.indexOf(t)).findLast(e=>e.role===`user`);return n!==void 0&&bd.sentHere(n.id)}function Zp(e){let{streaming:t,controlModeSig:n,messagesSig:r,sendAiTurn:i,bus:a,humanInLoop:o,tools:c}=e,d=m(t);d.current=t;let f=m(c);f.current=c;let h=m(/* @__PURE__ */ new Map),g=s(()=>{let e=r.value,t=e.at(-1);return n.value!==`ai-agent`||t?.role!==`assistant`||t.status!==`complete`?!1:t.partsSig.value.some(e=>Jp(e)&&bd.get(e.toolCallId)?.state!==`stopped`)&&Xp(e,t)}).value,_=l((e,t,a)=>{if(d.current||n.value!==`ai-agent`)return!1;let o=r.value.at(-1),s=o?.partsSig.value.findIndex(t=>t.kind===`tool`&&t.toolCallId===e)??-1,c=o?.partsSig.value[s];if(!o||c?.kind!==`tool`)return qp.warn(`decideTool: tool part not found`,{toolCallId:e}),!1;if(o.status!==`complete`||!to(o,s)||!t(c))return!1;if(a(c),o.partsSig.value=[...o.partsSig.value],!$a(o)||o.partsSig.value.some(Jp))return!0;o.status=`streaming`,o.retryAction={kind:`continue-assistant`,messageId:o.serverMessageId??o.id},o.awaitingContinuation=!0,r.value=[...r.value];let l=o.partsSig.value.flatMap(e=>e.kind===`tool`?[e.toolCallId]:[]);return i({continueExisting:!0}).then(e=>e&&bd.clear(l)),!0},[n,r,i]),v=l((e,t)=>{let{toolCallId:n,toolName:r}=t;h.current.has(n)||(h.current.set(n,e),Vd({toolCallId:n,toolName:r,input:t.inputSig.value,optionTools:f.current??[],onSettled:(e,t)=>{qp.info(`toolResult`,{toolCallId:n,status:e}),a.emit(`toolResult`,{toolCallId:n,name:Ld(r),status:e,durationMs:t})}}).then(e=>{h.current.delete(n)&&_(n,Jp,t=>{e.state===`output-available`?t.outputSig.value=e.output:t.errorSig.value=e.errorText,t.stateSig.value=e.state})}))},[a,_]),y=l(()=>{let e=r.value;for(let[t,n]of h.current){let r=e.findIndex(e=>e.id===n);r<0||r===e.length-1||(h.current.delete(t),Wd(t))}let t=e.at(-1);if(d.current||t?.role!==`assistant`||t.status!==`complete`)return;let n=t.partsSig.value.filter(Jp);if(n.length!==0&&Xp(e,t))for(let e of n)bd.get(e.toolCallId)?.state===`stopped`?Yp(t,e):v(t.id,e)},[r,v]);u(()=>y(),[t,y]),u(()=>r.subscribe(()=>y()),[r,y]);let b=l((e,t,n)=>{let i=!1,o;if(!_(e,e=>e.stateSig.value===`approval-requested`,r=>{Id(r.toolMetadata)&&(o=r),i=r.toolMetadata?.card===`questions`;let a=r.approvalSig.value?.id??e;r.approvalSig.value={id:a,approved:t,reason:n},r.stateSig.value=`approval-responded`}))return;let s=r.value.at(-1);o&&t&&s&&v(s.id,o),o&&!t&&a.emit(`toolResult`,{toolCallId:e,name:Ld(o.toolName),status:`declined`,durationMs:0}),i?(qp.info(`toolResult`,{toolCallId:e}),a.emit(`toolResult`,{toolCallId:e})):(qp.info(`toolDecision`,{toolCallId:e,approved:t}),a.emit(`toolDecision`,{toolCallId:e,approved:t}))},[a,_,r,v]),x=l(e=>{_(e,e=>e.stateSig.value===`approval-responded`&&e.approvalSig.value?.approved!==void 0&&!Jp(e),t=>{let n=t.approvalSig.value?.id??e;t.approvalSig.value={id:n},t.stateSig.value=`approval-requested`})},[_]);return{toolInteraction:p(()=>({humanInLoop:o,onDecision:b,onEdit:x,preview:(e,t)=>zd({toolName:e,input:t,optionTools:f.current??[]})}),[o,b,x]),pageToolsRunning:g,stopPageTools:l(()=>{let e=r.value.at(-1);for(let t of h.current.keys()){let n=e?.partsSig.value.find(e=>e.kind===`tool`&&e.toolCallId===t);e&&n?Yp(e,n):Ud(t),qp.info(`toolResult`,{toolCallId:t,status:`stopped`}),a.emit(`toolResult`,{toolCallId:t,name:n?Ld(n.toolName):void 0,status:`stopped`,durationMs:0})}h.current.clear()},[a,r])}}const Qp=R.scope(`latest-news`);function $p({transport:e,options:t,persistence:n,enabled:r}){let i=t.modules.list.find(e=>e.layout===`news`)?.contentCollectionIds,a=i?.join(`,`),[o,s]=h(),[c,d]=h(()=>n.loadSeenNewsId());u(()=>{if(!r||!i?.length)return;let t=!1;return e.listContent({contentCollectionIds:i,sortBy:`publishedAt`,sortOrder:`desc`,limit:1}).then(e=>{t||s(e.items[0])}).catch(e=>Qp.debug(`listContent (latest news) failed (non-fatal)`,{err:e})),()=>{t=!0}},[e,r,a]);let f=l(e=>{n.saveSeenNewsId(e),d(e)},[n]);return{item:o,unseen:o!==void 0&&o.id!==c,markSeen:f}}function em({callout:e,persistence:t}){let n=e?.text??``,r=e?.persistent??!0,[i,a]=h(()=>!r&&t.loadCalloutDismissed(n));return u(()=>{a(!r&&t.loadCalloutDismissed(n))},[n,r,t]),{dismissed:i,dismissCallout:l(()=>{a(!0),r||t.saveCalloutDismissed(n)},[t,n,r])}}const tm=R.scope(`login`);function nm(e,t){switch(e.status){case`required`:return`required`;case`expired`:return`expired`;case`anonymous`:return t?`required`:void 0;case`pending`:case`loggedIn`:return;default:return e}}function rm(e,t,n){if(e.status===`loggedIn`)return t.hideUser?void 0:{kind:`user`,who:e.name??e.email};if(!(e.status!==`anonymous`||!t.url||t.hidePrompt||n))return{kind:`prompt`}}function im(e){let{state:t,deployment:n,bus:r,persistence:i,conversationIdSig:a}=e,[o,c]=h(()=>i.loadLoginPromptDismissedIn()),u=s(()=>a.value).value,d=o!==void 0&&o===u,f=(t.status===`required`?t.loginUrl:void 0)??n.url,p=nm(t,n.required),m=l(()=>{let e=or(),t=r.listensTo(`loginRequested`);if(tm.info(`loginRequested`,{pageLogsIn:t}),r.emit(`loginRequested`,{returnTo:e}),t||!f)return;let n=a.value;n&&i.saveLoginReturn({conversationId:n,draft:i.loadDraft(n)}),i.savePanelOpen(!1),sr(tr(f,e))},[r,a,f,i]),g=l(()=>{let e=a.value;e&&(i.dismissLoginPromptIn(e),c(e))},[a,i]),_=!!f||r.listensTo(`loginRequested`);return{strip:rm(t,n,!!p||d),gate:p,canStartAsGuest:p===`expired`&&!n.required,email:t.status===`loggedIn`?t.email:void 0,canLogIn:_,onLogIn:m,menuLogIn:t.status===`anonymous`&&!p&&_?m:void 0,onHidePrompt:g}}function am(e){let{transport:t,conversationIdSig:n}=e,r=c(`ai-agent`),i=c(void 0),a=c(void 0),o=m(void 0),s=l(e=>{let t=e.controlRevision,s=o.current;if(s&&s.conversationId===n.value&&t<s.revision)return;o.current={conversationId:n.value,revision:t},r.value=e.controlMode;let c=e.assignedOperatorInitials;i.value=c?{initials:c,name:e.assignedOperatorName,avatar:e.assignedOperatorAvatar}:void 0,e.controlMode===`awaiting-operator`?e.operatorAvailable!==void 0&&(a.value=e.operatorAvailable):a.value=void 0},[n,r,i,a]);return{controlModeSig:r,assignedOperatorSig:i,operatorAvailableSig:a,applyControlState:s,adoptControlStateChunk:l(e=>{if(e.type!==`data-control-state`)return;let t=Ea(e.data);t&&s(t)},[s]),requestOperator:l(async()=>{let e=n.value,r=await t.requestOperator();r&&n.value===e&&s(r)},[t,n,s]),cancelOperatorRequest:l(async()=>{let e=n.value,r=await t.cancelOperatorRequest();r&&n.value===e&&s(r)},[t,n,s])}}const om=N.cssPrefix,sm=`--${om}-visual-viewport-height`,cm=`--${om}-visual-viewport-top`;function lm(e){let{hostElement:t,mode:n,panelSize:r,isOpen:i,surfaceReady:a,onClose:o}=e;f(()=>{bn(t,Ts(n,r,i))},[t,i,r,n]),f(()=>{if(!i||!a)return;let e=t.ownerDocument.defaultView,n=e?.visualViewport,r=t.shadowRoot?.querySelector(`.${om}-anchor`);if(!e||!n||!r)return;let o=()=>{r.style.setProperty(sm,`${n.height}px`),r.style.setProperty(cm,`${n.offsetTop}px`)},s=0,c=()=>{e.cancelAnimationFrame(s),s=e.requestAnimationFrame(()=>{s=e.requestAnimationFrame(o)})};return o(),n.addEventListener(`resize`,c),n.addEventListener(`scroll`,c),()=>{e.cancelAnimationFrame(s),n.removeEventListener(`resize`,c),n.removeEventListener(`scroll`,c),r.style.removeProperty(sm),r.style.removeProperty(cm)}},[t,i,a]),u(()=>{if(n!==`modal`||!i)return;function e(e){e.composedPath().some(e=>e instanceof HTMLElement&&e.classList.contains(`${om}-panel`))||o()}return t.addEventListener(`click`,e),()=>t.removeEventListener(`click`,e)},[t,i,n,o]),u(()=>{if(n!==`drawer`||!i)return;function e(e){e.key===`Escape`&&!e.composedPath().includes(t)&&o()}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,i,n,o])}const um=R.scope(`reducer`);var dm=class{constructor(e,t){this.messagesSig=e,this.onReconcileNeeded=t,B(this,`active`,null),B(this,`openTextParts`,/* @__PURE__ */ new Map),B(this,`partSeq`,0),B(this,`replay`,null),B(this,`turnChunks`,[]),B(this,`turnRow`,null)}attach(e){this.active=e,this.openTextParts.clear()}detach(){this.active=null,this.replay=null,this.openTextParts.clear()}beginReplay(e,t){let n=Na();n.id=e.id;let r=fm(e)||eo(e)&&(e.status!==`streaming`||$a(e)),i=e.status===`streaming`&&$a(e)&&Qa(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,pm(a,i),e.liveCatchUp&&fm(e.shadow)&&(i.status===`streaming`||eo(i))?(e.probeContinuation=!1,e.continuationTailReplay=!1,e):(e.probeContinuation=fm(i)||eo(i)&&(i.status!==`streaming`||$a(i)),e.continuationTailReplay=i.status===`streaming`&&$a(i)&&Qa(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;pm(e,i);let a=fm(e)&&eo(i);return i.status!==`streaming`&&!a?(this.detach(),null):(this.replayTurn(),this.replay?this.replay.shadow:this.active)}replayTurn(){let[e,...t]=this.turnChunks;if(e?.type!==`start`)return;let n=this.messagesSig.value.find(t=>t.serverMessageId===e.messageId);if(n!==void 0&&n!==this.turnRow){this.detach();for(let n of[e,...t])this.applyResume(n)}}promoteReplay(e){let{baseline:t,shadow:n}=e;return r(()=>{t.role=n.role,t.serverMessageId=n.serverMessageId,t.operatorInitials=n.operatorInitials,t.status=n.status,n.canceled&&(t.canceled=!0),t.finishReason=n.finishReason,t.errorText=n.errorText,t.suggestions=n.suggestions??t.suggestions,t.runStartedAt=n.runStartedAt??t.runStartedAt,t.stepTimings=n.stepTimings??t.stepTimings,t.partsSig.value=n.partsSig.value,this.messagesSig.value=[...this.messagesSig.value]}),this.replay=null,this.active=t,t}promoteContinuation(e){let{baseline:t,chunks:n}=e,i=no(t);return this.replay=null,r(()=>{t.partsSig.value=t.partsSig.value.slice(0,mm(t,n)+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=i||void 0,this.messagesSig.value=[...this.messagesSig.value]}),t}settleOwnedContinuation(e,t){let{baseline:n}=e,i=no(n);return this.replay=null,r(()=>{n.awaitingContinuation=!1,n.status=`streaming`,n.finishReason=void 0,n.errorText=void 0,n.suggestions=void 0,this.attach(n),this.apply(t),n.continuationStreaming=i||void 0,this.messagesSig.value=[...this.messagesSig.value]}),n}applyResume(e){e.type===`start`&&(this.turnChunks=[]);let t=this.applyTurnChunk(e);return this.turnChunks.push(e),this.turnRow=t??this.replay?.baseline??this.active??this.turnRow,t}applyTurnChunk(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&&!qa(a))return this.attach(a),this.apply(e),null;let o=Na();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(!vm(n,r,e)){if(s){if(n.status===`streaming`&&n.awaitingContinuation!==!0){let n=this.settleOwnedContinuation(t,e);return this.detach(),n}Sm(n,r)&&(n.continuationStreaming=!0,this.messagesSig.value=[...this.messagesSig.value],this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id})),this.detach()}return null}let i=fm(n)&&s?this.settleOwnedContinuation(t,e):this.promoteContinuation(t);return s?(i.continuationStreaming&&(e.type===`finish`?this.onReconcileNeeded?.({messageId:i.serverMessageId??i.id}):i.continuationStreaming=!1),this.detach(),i):null}if(a&&gm(n,r)){let e=this.promoteContinuation(t);return s?(this.detach(),e):null}if(!o)return s&&this.detach(),null;if(s&&!qa(n)&&qa(r)){let e=this.promoteReplay(t);return this.detach(),e}if(!hm(n,r))return s&&(this.onReconcileNeeded?.({messageId:n.serverMessageId??n.id}),this.detach()),null;let c=this.promoteReplay(t);return s?(this.detach(),c):null}let t=this.refreshActive();if(!t)return null;if(this.replay)return this.applyTurnChunk(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:o(``),doneSig:o(!1)};return this.openTextParts.set(r,a),wm(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?.runStartedAt&&(t.runStartedAt=n.runStartedAt),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`:wm(t,{kind:`step-start`,id:`ss-${this.partSeq++}`});return;case`message-metadata`:t.stepTimings=Ra(e.messageMetadata?.steps)??t.stepTimings;return;case`finish`:um.debug(`finish`,{reason:e.finishReason}),t.stepTimings=Ra(e.messageMetadata?.steps)??t.stepTimings,t.status=`complete`,t.retryAction=void 0,e.finishReason&&(t.finishReason=e.finishReason),this.bumpDone(t);return;case`error`:um.warn(`stream error chunk`,{errorText:e.errorText}),t.status=`error`,t.errorText=void 0,this.bumpDone(t);return;case`abort`:um.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`:case`tool-approval-response`:Em(t,e);return;case`file`:wm(t,{kind:`file`,url:e.url,mediaType:e.mediaType,filename:e.filename,fileId:e.fileId,fileSize:e.fileSize});return;case`source-url`:Tm(t,{kind:`source`,sourceId:e.sourceId,url:e.url,title:e.title});return;case`source-document`:Tm(t,{kind:`source`,sourceId:e.sourceId,title:e.title,filename:e.filename,mediaType:e.mediaType});return;case`data-suggestions`:t.suggestions=Oa(e.data);return;case`data-control-state`:t.operatorRoutedTurn=e.data.controlMode!==`ai-agent`;return;case`data-memory-compaction-state`:return}}bumpDone(e){r(()=>{e.partsSig.value=[...e.partsSig.value],this.messagesSig.value.includes(e)&&(this.messagesSig.value=[...this.messagesSig.value])})}};function fm(e){return e.awaitingContinuation===!0||e.continuationStreaming===!0||e.retryAction?.kind===`continue-assistant`}function pm(e,t){e.canceled&&(t.canceled=!0),fm(e)&&(t.status===`streaming`||eo(t))&&(t.awaitingContinuation??(t.awaitingContinuation=e.awaitingContinuation),t.continuationStreaming??(t.continuationStreaming=e.continuationStreaming),t.retryAction===void 0&&(t.retryAction=e.retryAction))}function mm(e,t){let n=e.partsSig.value,r=t.findIndex(e=>e.type===`start-step`),i=new Set(t.slice(0,r<0?t.length:r).flatMap(e=>`toolCallId`in e&&e.type.startsWith(`tool-output`)?[e.toolCallId]:[])),a=n.findLastIndex(e=>e.kind===`tool`&&(e.stateSig.value===`approval-requested`||e.stateSig.value===`approval-responded`||i.has(e.toolCallId)));if(a>=0)return a;let o=new Set(t.flatMap(e=>e.type===`tool-input-start`||e.type===`tool-input-available`?[e.toolCallId]:[]));return n.some(e=>e.kind===`tool`&&o.has(e.toolCallId))?-1:n.findLastIndex(e=>e.kind===`tool`)}function hm(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)=>_m(e,r[t]))}function gm(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)=>_m(e,a[t]))}function _m(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||!ho(t.toolName,e.toolName)||go[t.stateSig.value]<go[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 vm(e,t,n){return ym(e,n)||!bm(e,t)?!0:n.type!==`finish`&&n.type!==`error`&&n.type!==`abort`?!1:Qa(t)||e.awaitingContinuation===!0&&n.type!==`finish`?!0:e.awaitingContinuation===!0&&t.partsSig.value.every(e=>e.kind===`step-start`)}function ym(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&&go[n.stateSig.value]<4}function bm(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)=>xm(r[t+n],e)))}function xm(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`||ho(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 Sm(e,t){if(fm(e)||!eo(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 Cm(e,t,n={}){let r=e.partsSig.value.find(e=>e.kind===`tool`&&e.toolCallId===t);if(r)return n.dynamic&&(r.dynamic=!0),r.toolMetadata??(r.toolMetadata=n.toolMetadata),r.title=n.title??r.title,r;let i={kind:`tool`,toolCallId:t,toolName:n.toolName??`tool`,title:n.title,dynamic:n.dynamic?!0:void 0,toolMetadata:n.toolMetadata,inputPartialSig:o(``),inputSig:o(void 0),outputSig:o(void 0),errorSig:o(void 0),stateSig:o(`input-streaming`),approvalSig:o(void 0)};return wm(e,i),i}function wm(e,t){e.partsSig.value=[...e.partsSig.value,t]}function Tm(e,t){e.partsSig.value.some(e=>e.kind===`source`&&e.sourceId===t.sourceId)||wm(e,t)}function Em(e,t){switch(t.type){case`tool-input-start`:Cm(e,t.toolCallId,t);return;case`tool-input-delta`:{let n=Cm(e,t.toolCallId);n.inputPartialSig.value+=t.inputTextDelta;return}case`tool-input-available`:{let n=Cm(e,t.toolCallId,t);n.inputSig.value=t.input,n.stateSig.value=`input-available`;return}case`tool-input-error`:{let n=Cm(e,t.toolCallId,t);n.inputSig.value=t.input,n.errorSig.value=t.errorText,n.stateSig.value=`output-error`;return}case`tool-approval-request`:{let n=Cm(e,t.toolCallId,t);if(t.isAutomatic){n.approvalSig.value={id:t.approvalId,isAutomatic:!0};return}n.approvalSig.value={id:t.approvalId},n.stateSig.value=`approval-requested`;return}case`tool-approval-response`:{let n=e.partsSig.value.find(e=>e.kind===`tool`&&e.approvalSig.value?.id===t.approvalId);n?.approvalSig.value&&(n.approvalSig.value={...n.approvalSig.value,approved:t.approved,reason:t.reason});return}case`tool-output-available`:{let n=Cm(e,t.toolCallId,t);n.outputSig.value=t.output,n.stateSig.value=`output-available`;return}case`tool-output-error`:{let n=Cm(e,t.toolCallId,t);n.errorSig.value=t.errorText,n.stateSig.value=`output-error`;return}case`tool-output-denied`:{let n=Cm(e,t.toolCallId);n.stateSig.value=`output-denied`;return}default:return}}const Dm=1e3;async function Om(e){let t=Dm,n=!1,r=!1,i=!1;function 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;e.onDropped?.(),o!==void 0&&e.now()-o>=1e3&&(t=Dm),await e.sleep(t),t=Math.min(t*2,15e3)}}function km(e){let{activated:t,conversationReady:n,paused:r,conversationIdSig:i,messagesSig:a,optionsRef:o,transport:s,visitorId:c,adoptControlStateChunk:l,adoptMemoryCompactionStateChunk:d,settleSuggestions:f,recordConversationReply:p,transcriptRecoverySig:h,beginConversationTranscript:g,commitConversationTranscript:_,runCancellation:v,feedback:y,bus:b,loadInitialThread:x,shouldReconcileOnConnect:S,reconnectingSig:C}=e,w=m(0);u(()=>{if(!t||!n||r||!i.value)return;let e=i.value,u=new AbortController,m=e=>{},T=new dm(a,e=>m(e));s.primeIdentity(c,e);let E=!1,D=!1,O,k=!1,A,j=0,ee,M,te=Date.now(),N,ne=!1,re=!1,ie=!1,P;function ae(t,n){if(!qa(t))return;let r=a.value.findLast(e=>!e.ephemeral),i=t.serverMessageId??t.id;if(!(r&&(r.serverMessageId??r.id)!==i)){if(N&&ne&&!a.value.some(e=>e.role===`user`&&!e.ephemeral))P={replyId:i,activityAt:n};else return Ka(a.value,t,e,o.current.strings.newConversation,n)}}function oe(e,t,n){let r=ae(e,n);if(!r)return;let i=`${e.serverMessageId??e.id}:${t}:${r.preview??``}`;i!==M&&(M=i,s.publishConversation({...r,hasUnread:!0},!0))}let F;function se(){F&&(clearTimeout(F.timer),F=void 0)}function ce(){let e=F;if(!e)return;clearTimeout(e.timer),F=void 0;let t=a.value.find(t=>(t.serverMessageId??t.id)===e.replyId);(t?.role===`assistant`||t?.role===`operator`)&&oe(t,e.generation,e.activityAt)}function le(e,t,n){se(),F={replyId:e.serverMessageId??e.id,generation:t,activityAt:n,timer:setTimeout(ce,120)}}function ue(e,t,n=Date.now(),r=!0){se();let i=ae(e,n);if(!i)return;let a=`${e.serverMessageId??e.id}:${t}`;a!==ee&&(ee=a,p(i),r&&N&&!ne&&(re=!0))}function de(e,t){(e||!v.localSendRef.current)&&v.settle(t)}function I(e,t=[],n=!1,r,i=j,s=Date.now(),c=!0){let l=o.current;if(e.canceled){ue(e,i,s,c),de(n,r);return}let u=!0,d=e.status===`error`;switch(xo(e,d)){case`drop`:a.value=a.value.filter(t=>t!==e),u=!1;break;case`complete-operator-routed`:e.status=`complete`,n&&(y.play(`messageReceived`),_s(b,l,`assistant`,Ga(e)));break;case`error`:if(e.status=`error`,n){y.play(`error`);let e=/* @__PURE__ */ Error(d?`stream error chunk`:`empty reply`);b.emit(`error`,e),l.onError?.(e)}break;case`complete`:e.status=`complete`,n&&(y.play(`messageReceived`),_s(b,l,`assistant`,Ga(e))),f(e,t)}u&&ue(e,i,s,c),de(n,r)}function fe(t){if(u.signal.aborted||i.value!==e)return;if(l(t),d?.(t),t.type===`start`){ce();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;A={messageId:t.messageId,senderRole:t.messageMetadata?.senderRole},j+=1,te=Date.now(),M=void 0,E=t.messageMetadata?.senderRole===void 0,D=!1,O=E?t.messageMetadata?.runId:void 0;let i=E?t.messageMetadata?.senderMessageId:void 0;function o(e){return e.role===`assistant`&&e.retryAction?.kind===`resend-user`&&e.retryAction.messageId===i}if(i&&a.value.some(o)&&(a.value=a.value.filter(e=>!o(e))),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=v.localSendRef.current&&(!n||o)&&i?.role===`assistant`&&i.status===`streaming`&&(o||i.serverMessageId===void 0&&i.partsSig.value.length===0);D=v.captureStart(e,t,s,r)}}let n=E&&(t.type===`finish`||t.type===`error`||t.type===`abort`),r=n?O:void 0,s=n&&(D||v.ownsLocalRun(r)),c=j,f=k;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,f=!1);let g=!k&&(h?.role===`assistant`||h?.role===`operator`);t.type===`text-delta`&&g&&le(h,j,te),t.type===`text-end`&&(se(),g&&oe(h,j,te)),p?p.role===`operator`?(f||(y.play(`messageReceived`),_s(b,o.current,`operator`,Ga(p))),ue(p,c,te),k=!1,n&&(s||!v.localSendRef.current)&&v.settle(r)):p.role===`assistant`&&(I(p,[],s,r,c,te),k=!1):n&&(s||!v.localSendRef.current)&&v.settle(r)}async function pe(t){let n=j,r=await s.loadConversation(e,t?{ids:[t]}:void 0).catch(()=>null);if(u.signal.aborted||i.value!==e||!r)return!1;r.controlState&&l({type:`data-control-state`,data:r.controlState});let o=a.value.at(-1),c=n===j&&(t===void 0||o!==void 0&&(o.serverMessageId===t||o.id===t));if(r.messages.length===0)return!0;let d=a.value,p=t===void 0?d.at(-1):d.find(e=>e.serverMessageId===t||e.id===t),m=fo(d,Ha(r.messages)),h=lo(r.messages),g=m.messages.filter(e=>!(e.role===`assistant`&&e.retryAction?.kind===`resend-user`&&h.has(e.retryAction.messageId)));if(!m.changed&&g.length===m.messages.length)return!0;a.value=g;let _=t===void 0?g.at(-1):g.find(e=>e.serverMessageId===t||e.id===t),y=p!==void 0&&_!==void 0&&(p.id===_.id||p.serverMessageId!==void 0&&p.serverMessageId===_.serverMessageId),b=_!==void 0&&_.status!==`streaming`&&(!y||p?.status===`streaming`),x=y&&p?.status===`streaming`?Date.now():_?.createdAt;return c&&b&&_.role===`assistant`?I(_,_.suggestions??[],v.localSendRef.current,void 0,n,x,!1):c&&b&&_.role===`operator`?ue(_,n,x,!1):c&&_?.role===`assistant`&&_.status!==`streaming`&&f(_,_.suggestions??[]),!0}let me=/* @__PURE__ */ new Set;m=({messageId:e})=>{if(me.has(e)||!a.value.some(t=>t.serverMessageId===e||t.id===e))return;me.add(e);function t(){return me.delete(e)}pe(e).then(t,t)};function he(){let e=P;P=void 0;let t=e&&a.value.find(t=>(t.serverMessageId??t.id)===e.replyId),n=t&&ae(t,e.activityAt);n&&p(n)}function ge(t=!1){if(u.signal.aborted||i.value!==e){re=!1;return}if(N){re=!0;return}let n=t?x(e):void 0,r=n??(!t||S()?pe():void 0);if(!r)return;g(e),N=r,ne=n!==void 0;function a(t=!1){N===r&&(N=void 0,T.replayTurn(),re?(re=!1,ge()):(he(),t&&_(e)))}r.then(a,()=>a(!1))}let _e=h.subscribe(e=>{e<=w.current||(w.current=e,ie&&ge())});return Om({signal:u.signal,now:()=>performance.now(),sleep:e=>wo(e,u.signal),connect:e=>s.connectResumeStream({signal:u.signal,onChunk:fe,onConnected:()=>{C.value=!1,e()}}),onDropped:()=>{C.value=!0},onInitialBoundaryReady:()=>{ie=!0,ge(!0)},backfill:()=>ge()}),()=>{u.abort(),C.value=!1,se(),_e(),T.detach()}},[t,n,r,i,i.value,c,s,l,d,f,p,h,g,_,v,a,b,y,x,S,C])}function Am(e){let{transport:t,setStreaming:n}=e,r=m(void 0),i=m(void 0),a=m(!1),o=m(void 0),s=m(!1),c=m(/* @__PURE__ */ new Map),u=m(/* @__PURE__ */ new Set),d=l((e,n)=>{let r=`${e}:${n}`;o.current!==r&&(o.current=r,t.cancelTurn(e,n))},[t]),f=l(e=>{r.current=void 0,i.current=e,a.current=!1,o.current=void 0,s.current=!0,n(!0)},[n]),h=l((e,t)=>{c.current.set(e,{messageId:t})},[]),g=l(e=>{if(e!==void 0){u.current.add(e);let t=u.current.values().next().value;u.current.size>32&&t!==void 0&&u.current.delete(t)}(e===void 0||r.current?.runId===e)&&(r.current=void 0,i.current=void 0,a.current=!1,s.current=!1,n(!1))},[n]),_=l((e,t)=>i.current===e?(i.current=void 0,t.runId?(r.current={conversationId:t.conversationId,runId:t.runId},n(!0),a.current&&d(t.conversationId,t.runId),!0):(g(),!0)):t.runId&&r.current?.runId===t.runId?(r.current={conversationId:t.conversationId,runId:t.runId},a.current&&d(t.conversationId,t.runId),!0):!1,[d,n,g]),v=l((e,t)=>{let l=c.current.get(e);return l?(c.current.delete(e),!t.runId||u.current.has(t.runId)?!0:l.runId===void 0?(s.current||i.current||(r.current={conversationId:t.conversationId,runId:t.runId},i.current=void 0,a.current=!1,o.current=void 0,s.current=!0,n(!0)),!0):(l.runId===t.runId&&r.current?.runId===t.runId&&(r.current={conversationId:t.conversationId,runId:t.runId},a.current&&d(t.conversationId,t.runId)),!0)):!1},[d,n]),y=l(e=>i.current===e&&(g(),!0),[g]),b=l(e=>{let t=c.current.get(e);return t?(c.current.delete(e),t.runId===void 0):!1},[]),x=l((e,t,l,f)=>{let p=t.messageMetadata?.runId;if(t.messageMetadata?.senderRole!==void 0||typeof p!=`string`||!p||u.current.has(p))return!1;if(r.current?.runId===p)return s.current;if(s.current)return r.current||!l?!1:(i.current=void 0,r.current={conversationId:e,runId:p},n(!0),a.current&&d(e,p),!0);let m=[...c.current.values()].filter(e=>e.runId===void 0).find(e=>e.messageId===f);return m?(m.runId=p,r.current={conversationId:e,runId:p},i.current=void 0,a.current=!1,o.current=void 0,s.current=!0,n(!0),!0):(i.current=void 0,r.current={conversationId:e,runId:p},n(!0),a.current&&d(e,p),s.current)},[d,n]),S=l(e=>typeof e==`string`&&r.current?.runId===e&&s.current,[]),C=l(()=>{let e=r.current;if(e)return a.current=!0,d(e.conversationId,e.runId),!0;let t=i.current;return t?(a.current=!0,t.then(e=>{e.runId&&d(e.conversationId,e.runId)}).catch(()=>void 0),!0):!1},[d]);return p(()=>({localSendRef:s,begin:f,beginRouted:h,acceptAck:_,acceptRoutedAck:v,reject:y,rejectRouted:b,captureStart:x,ownsLocalRun:S,settle:g,stop:C}),[_,v,f,h,x,S,y,b,g,C])}const jm=R.scope(`send`);function Mm(e,t,n,r,i){e.publishConversation({...Ka(t,n,r,i),hasUnread:!1},!0)}function Nm(e,t){return e.id===t.id||(e.serverMessageId??e.id)===(t.serverMessageId??t.id)}function Pm(e){return e.findLast(e=>!e.ephemeral&&e.role!==`system`&&(e.role===`user`||e.status!==`streaming`||qa(e)))}function Fm(e,t,n,r,i){let a=Pm(t);a?.role===`user`&&Nm(a,n)&&Mm(e,t,a,r,i)}function Im(e){return e instanceof Oo&&e.status===404&&e.errorCode===`CONVERSATION_NOT_FOUND`}function Lm(e){return!(e instanceof Oo)||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 Rm(e){let{transport:t,messagesSig:n,conversationIdSig:r,options:i,bus:a,feedback:o,persistence:s,visitorId:c,adoptConversationId:u,applyControlState:d,setTicket:f,settleSuggestions:p,runCancellation:m,onConversationNotFound:h}=e,g=l(()=>{let e=r.value??Ut();return r.value||(r.value=e,s.saveConversationId(e)),e},[r,s]);return{sendAiTurn:l(async({continueExisting:e,turn:l,movedFromConversation:_=!1})=>{let v=g(),y=n.value.at(-1),b=l?[l]:Ua(n.value,e),x=b[0];x?.role===`user`&&bd.markSent(x.id);let S=b.map(Wa),C=s.loadUserPrefs(),w=Pd(i.tools).then(n=>t.sendTurn(ka({messages:S,conversationId:v,visitorId:c,userPrefs:C,clientTools:Fd(n)}),{keepalive:e}));m.begin(w);try{let a=await w;if(r.value!==v||!m.acceptAck(w,a))return!1;if(u(a.conversationId),f({conversationId:a.conversationId,reference:a.ticketReference}),a.runId&&x?.role===`user`&&Fm(t,n.value,x,a.conversationId,i.strings.newConversation),!a.runId){let o=await t.loadConversation(a.conversationId).catch(()=>null);if(r.value!==a.conversationId)return!0;if(o){o.controlState&&d(o.controlState);let r=Ha(o.messages),{messages:s,changed:c}=fo(n.value,r);c&&(n.value=s);let l=r.findLast(e=>!e.ephemeral&&e.role!==`system`),u=Pm(n.value);u&&l&&Nm(u,l)&&Mm(t,n.value,u,a.conversationId,i.strings.newConversation);let f=y?n.value.find(e=>e.id===y.id&&e.role===`assistant`&&e.status!==`streaming`):void 0;f&&p(f,f.suggestions??[]),!e&&y?.role===`assistant`&&n.value.includes(y)&&y.serverMessageId===void 0&&!qa(y)&&(n.value=n.value.filter(e=>e!==y))}else y?.role===`assistant`&&n.value.includes(y)&&(y.status=`error`,y.errorText=i.strings.errorGeneric,y.retryAction=e?{kind:`continue-assistant`,messageId:y.serverMessageId??y.id}:x?.role===`user`?{kind:`resend-user`,messageId:x.id}:null,n.value=[...n.value])}return!0}catch(c){if(r.value!==v)return!1;if(!m.reject(w))return x?.role===`user`&&Fm(t,n.value,x,v,i.strings.newConversation),!0;if(!e&&!_&&x?.role===`user`&&Im(c))return h(x);if(!e&&x?.role===`user`&&c instanceof Oo&&c.status===401){let e=y?.role===`assistant`&&y.serverMessageId===void 0?y:void 0;return n.value=n.value.filter(t=>t!==x&&t!==e),s.saveDraft(v,Ga(x)),!1}let u=Sl(c,i.strings),f=Lm(c),g=l?.role===`assistant`?l:n.value.at(-1);if(e&&g?.role===`assistant`&&c instanceof Oo&&c.status===409){let e=g.serverMessageId??g.id,i=await t.loadConversation(v,{ids:[e]}).catch(()=>null);if(r.value!==v)return!1;if(i){i.controlState&&d(i.controlState);let t=Ha(i.messages),r=t.find(t=>(t.serverMessageId??t.id)===e);if(r&&po(g,r)){let{messages:r,changed:i}=fo(n.value,t),a=r.find(t=>(t.serverMessageId??t.id)===e);if(i&&a&&a!==g)return a.awaitingContinuation=!1,a.continuationStreaming=void 0,a.retryAction=null,n.value=r,a.status!==`streaming`&&p(a,a.suggestions??[]),!0}}if(!n.value.includes(g)||g.status!==`streaming`)return!1;g.continuationStreaming=!0}if(e&&g?.role===`assistant`)g.status=`error`,g.errorText=u,g.retryAction=f?{kind:`continue-assistant`,messageId:g.serverMessageId??g.id}:null,n.value=[...n.value];else if(y?.role===`assistant`&&n.value.includes(y)){y.status=`error`,y.errorText=u;let e=b[0];y.retryAction=f&&e?.role===`user`?{kind:`resend-user`,messageId:e.id}:null,n.value=[...n.value]}else{let e=Na();e.status=`error`,e.errorText=u;let t=b[0];e.retryAction=f&&t?.role===`user`?{kind:`resend-user`,messageId:t.id}:null,n.value=[...n.value,e]}return o.play(`error`),a.emit(`error`,c),i.onError?.(c),!1}},[t,n,i,a,o,s,c,u,d,f,p,g,m,h]),sendRoutedTurn:l(async e=>{let l=g();e.status=`pending`,e.errorText=void 0,e.retryAction=void 0,n.value.includes(e)&&(n.value=[...n.value]),bd.markSent(e.id);let d=[Wa(e)],p=s.loadUserPrefs(),_=Pd(i.tools).then(e=>t.sendTurn(ka({messages:d,conversationId:l,visitorId:c,userPrefs:p,clientTools:Fd(e)})));m.beginRouted(_,e.id);try{let a=await _;return r.value===l?m.acceptRoutedAck(_,a)?(u(a.conversationId),f({conversationId:a.conversationId,reference:a.ticketReference}),Fm(t,n.value,e,a.conversationId,i.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value])),!0):!1:(m.rejectRouted(_),!1)}catch(s){let c=m.rejectRouted(_);if(r.value!==l)return!1;if(!c)return Fm(t,n.value,e,l,i.strings.newConversation),e.status===`pending`&&(e.status=`complete`,n.value.includes(e)&&(n.value=[...n.value])),!0;if(e.status!==`pending`)return Fm(t,n.value,e,l,i.strings.newConversation),!0;if(Im(s))return h(e);jm.debug(`operator-routed send failed`,{error:s});let u=s instanceof Error?s:Error(String(s));return e.status=`error`,e.errorText=Sl(s,i.strings),e.retryAction=Lm(s)?{kind:`resend-user`,messageId:e.id}:null,n.value.includes(e)&&(n.value=[...n.value]),o.play(`error`),a.emit(`error`,u),i.onError?.(u),!1}},[t,n,i,a,o,s,c,u,f,g,m,h])}}const zm=R.scope(`unread`);function Bm(e){let{transport:t,options:n,conversationIdSig:r,isConversationVisibleRef:i,activated:a,conversationReady:o}=e,s=c(!1),d=c(0),f=c(0),p=m([]),h=m(void 0),g=m(!1),_=m(!1),v=l(()=>{let e=r.value,t=i.current()&&h.current===e?e:void 0,n=p.current.filter(e=>e.hasUnread&&e.conversationId!==t).length;d.value=n,s.value=n>0},[r,s,d,i]),y=l(e=>{let t=r.value,n=p.current.find(e=>e.conversationId===t),i=Go(p.current,e),a=i.find(e=>e.conversationId===t),o=e.type===`snapshot`&&t!==void 0&&a?.hasUnread===!0&&h.current===t&&n!==void 0&&n.lastMessageAt!==a.lastMessageAt;o&&(h.current=void 0),p.current=i,v(),o&&(f.value+=1)},[r,v,f]),b=l(()=>{if(v(),!i.current())return;let e=r.value;if(!e||h.current!==e)return;let n=p.current.find(t=>t.conversationId===e);n?.hasUnread&&t.markRead(e,n.lastMessageAt)},[r,i,v,t]),x=l(e=>{r.value===e&&(h.current=void 0,v())},[r,v]),S=l(e=>{r.value===e&&(h.current=e,b())},[r,b]),C=l(e=>h.current===e,[]),w=l((e=!1)=>{if(!n.history.enabled||!n.modules.list.some(e=>e.layout===`chat`))return;function r(e){g.current?e&&(_.current=!0):(g.current=!0,t.listConversations({limit:50},e).then(t=>{e||y({type:`snapshot`,result:t,requestedRevision:0}),b()}).catch(e=>zm.debug(`refreshUnread failed (non-fatal)`,{err:e})).finally(()=>{g.current=!1,_.current&&(_.current=!1,r(!0))}))}r(e)},[y,b,n.history.enabled,n.modules,t]),T=l(e=>{let n=e.conversationId,a=i.current()&&r.value===n&&h.current===n,o=p.current.find(e=>e.conversationId===n),s=a&&(o?.lastMessageAt!==e.lastMessageAt||o.hasUnread);t.publishConversation({...e,hasUnread:!a},!0),s&&t.markRead(n,e.lastMessageAt)},[r,i,t]);u(()=>t.subscribeConversationChanges(y),[y,t]);let E=m(!1);return u(()=>{a&&o&&!E.current&&(E.current=!0,w())},[a,o,w]),u(()=>{if(!a)return;function e(){document.visibilityState===`visible`&&(b(),w(!0))}return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[a,b,w]),{hasUnreadSig:s,unreadCountSig:d,transcriptRecoverySig:f,markVisibleConversationRead:b,beginConversationTranscript:x,commitConversationTranscript:S,isConversationTranscriptCommitted:C,recordConversationReply:T,refreshUnread:w}}const Vm=R.scope(`settings`);function Hm(e){let{options:t,persistence:n,transport:r,feedback:i,hostElement:a,bus:o}=e,s=n.loadUserPrefs(),[c,d]=h(()=>s.locale??t.locale),[f,p]=h(s.themeMode),m=gt(t.themeMode,f),[g,_]=h(()=>s.textSize??t.textSize),v=l(e=>{n.patchUserPrefs(e),r.saveUserPrefs(n.loadUserPrefs()).catch(e=>Vm.warn(`saveUserPrefs failed`,{err:e}))},[n,r]);u(()=>{s.soundMuted!==void 0&&i.setMuted(s.soundMuted)},[]),u(()=>{if(m!==`host`)a.dataset.theme=m;else return sn(e=>{a.dataset.theme=e})},[a,m,t]),u(()=>{a.dataset.textSize=g},[a,g,t]),u(()=>{let e=!0;return i.mutedSig.subscribe(t=>{e?e=!1:v({soundMuted:t})})},[i,v]);let y=st(c,t.availableLocales,t.defaultLocale);return u(()=>{r.setLocale(y)},[r,y]),u(()=>{a.dir=ee(y)?`rtl`:`ltr`},[a,y]),u(()=>{y!==c&&d(y)},[y,c]),{activeLocale:c,activeThemeMode:m,activeTextSize:g,setActiveLocale:d,setActiveThemeMode:p,setActiveTextSize:_,patchAndSync:v,handleLocaleChange:l(e=>{Vm.info(`localeChange`,{locale:e}),d(e),v({locale:e}),o.emit(`localeChange`,e)},[v,o]),handleThemeChange:l(e=>{Vm.info(`themeChange`,{mode:e}),p(e),a.dataset.theme=e,v({themeMode:e}),o.emit(`themeChange`,e)},[a,v,o]),handleTextSizeChange:l(e=>{Vm.info(`textSizeChange`,{size:e}),_(e),a.dataset.textSize=e,v({textSize:e}),o.emit(`textSizeChange`,e)},[a,v,o]),handleSoundToggle:l(()=>{i.toggleMuted();let e=i.mutedSig.value;Vm.info(`soundToggle`,{muted:e}),o.emit(`soundToggle`,{muted:e})},[i,o])}}const $=R.scope(`app`),Um=N.cssPrefix,Wm={home:`home`,chats:`chat`,help:`help`,news:`news`};function Gm({options:e,hostElement:t,bus:n,recentHostEvents:i,loginRevision:o=0,onPersonChanged:d,onStartAsGuest:g}){let y=e.aiAgentDeploymentId;if(!y)throw Error(`aiAgentDeploymentId is required`);let[b]=h(()=>Kt(e.widgetId,e.storage,e.aiAgentDeploymentId)),[x,S]=h(()=>b.getVisitorId()),C=b.loadUserPrefs(),w=c(b.loadConversationId()),T=m(w.value!==void 0),D=c(w.value??``),O=c([]),k=c(!1),[A,j]=h(!1),ee=m(void 0);function te(){let t=e.modules.list,n=new Set(t.map(e=>e.id)),r=b.loadActiveModule();return r&&n.has(r)?r:t[0]?.id??``}function ne(){return e.modules.list.find(e=>e.layout===`chat`)?.id}function re(){let t=ne();return t?e.modules.list.length===1||P.sig.value.activeTab===t:!1}let ie=m(void 0);if(!ie.current){let t=e.modules.list.map(e=>e.id),n=b.loadActiveModule()??t[0]??``;ie.current=bs(n,n?[...t,n]:t,e=>b.saveActiveModule(e))}let P=ie.current,ae=s(()=>P.sig.value.activeTab).value,oe=s(()=>w.value).value,[F,se]=h(!1),[ce,le]=h(!1),ue=e.mode===`standalone`||e.mode===`inline`,de=m(Ds(e,Os(),b.loadPanelOpen(),b.loadPanelSize())),[I,fe]=h(de.current.panelOpen),[pe,me]=h(de.current.panelOpen),he=m(void 0),ge=m(void 0),_e=m(!1),ve=m(void 0),L=m(e.strings),ye=m(void 0);u(()=>{I&&me(!0)},[I]);let be=m(!1),[xe,Se]=h(!1),Ce=m(null),we=m(!1),{dismissed:Te,dismissCallout:Ee}=em({callout:e.launcher.callout,persistence:b}),De=e.launcher.callout?.persistent??!0,Oe=l(()=>{$.info(`calloutDismiss`),n.emit(`calloutDismiss`,void 0),Ee()},[n,Ee]),[ke,Ae]=h(de.current.panelSize),je=m(!1),[Me,Ne]=h(`chat`),Pe=m(()=>!1);Pe.current=()=>I&&Me===`chat`&&!document.hidden&&re();let[Fe,Ie]=h(!1),Le=m(Fe);Le.current=Fe;let Re=m(null),[ze,Be]=h(!1),Ve=c(/* @__PURE__ */ new Map),He=l((e,t)=>{let n=new Map(Ve.value);t?n.set(e,t):n.delete(e),Ve.value=n},[Ve]),[Ue,We]=h(null),[Ge,Ke]=h(),[qe,Je]=h([]),R=m(e);R.current=e;let[Ye,Xe]=h(void 0),[Ze,Qe]=h(void 0),[$e,et]=h(()=>b.loadSidebarCollapsed()??!1),[tt,nt]=h({status:`anonymous`}),[rt,it]=h({}),[at,ot]=h(),[z]=h(()=>new Qo({agentApiBaseUrl:e.agentApiBaseUrl,dataApiBaseUrl:e.dataApiBaseUrl,auth:Sn({publicKey:e.publicKey,aiAgentDeploymentId:y,publicKeyHeader:`x-public-key`}),endpoints:e.endpoints,recentHostEvents:i,onLoginState:nt,continueLink:e.continueLink})),[st]=h(()=>new Xn(e.sound,e.haptics)),ct=Am({transport:z,setStreaming:Ie}),{activeLocale:lt,activeThemeMode:ut,activeTextSize:dt,setActiveLocale:ft,setActiveThemeMode:pt,setActiveTextSize:mt,patchAndSync:ht,handleLocaleChange:gt,handleThemeChange:vt,handleTextSizeChange:yt,handleSoundToggle:bt}=Hm({options:e,persistence:b,transport:z,feedback:st,hostElement:t,bus:n}),{controlModeSig:xt,assignedOperatorSig:St,operatorAvailableSig:Ct,applyControlState:wt,adoptControlStateChunk:Tt,requestOperator:Et,cancelOperatorRequest:Dt}=am({transport:z,conversationIdSig:w}),Ot=c(/* @__PURE__ */ new Map),kt=l(e=>{if(e.type!==`data-memory-compaction-state`)return;let t=w.value;if(!t)return;let n=Da(e.data);if(!n)return;let r=Ot.value.get(t);if(r&&(n.postFinishSequence<r.postFinishSequence||n.postFinishSequence===r.postFinishSequence&&(r.status===`ready`||r.status===n.status)))return;let i=new Map(Ot.value);i.set(t,n),Ot.value=i},[w,Ot]),{hasUnreadSig:At,unreadCountSig:jt,transcriptRecoverySig:Mt,markVisibleConversationRead:Nt,beginConversationTranscript:Pt,commitConversationTranscript:Ft,isConversationTranscriptCommitted:It,recordConversationReply:Lt,refreshUnread:Rt}=Bm({transport:z,options:e,conversationIdSig:w,isConversationVisibleRef:Pe,activated:pe,conversationReady:F}),zt=im({state:tt,deployment:rt,bus:n,persistence:b,conversationIdSig:w}),Bt=I&&e.modules.byId[ae]?.layout===`home`,Vt=$p({transport:z,options:e,persistence:b,enabled:F&&Bt});u(()=>{Nt()},[ae,I,Me,oe,Nt]),u(()=>{st.update(e.sound,e.haptics)},[st,e.sound,e.haptics]),u(()=>()=>st.destroy(),[st]),u(()=>{!je.current&&e.size.initialSize&&(je.current=!0,b.loadPanelSize()||Ae(Es(e.mode,e.size,Os())))},[e.mode,e.size,b]),u(()=>{if(!F||be.current)return;be.current=!0;let t=Ds(e,Os(),b.loadPanelOpen(),b.loadPanelSize());fe(t.panelOpen),Ae(t.panelSize)},[F,e,b]);let Ht=m(null);u(()=>{F&&P.reconcile(e.modules.list.map(e=>e.id),te())},[F,e.modules.list,P]);let Wt=l(e=>{e&&e.length!==0&&(O.value=e.map(e=>Pa({...e,text:M(L.current,e.text)})))},[O]),Gt=m(0),qt=m(0),Jt=l(e=>{if(e===w.value)return;let t=w.value;qt.current++,j(!1),t&&(b.saveDraft(e,b.loadDraft(t)),b.saveDraft(t,``),b.saveMessageQueue(e,b.loadMessageQueue(t)),b.saveMessageQueue(t,[])),w.value=e,b.saveConversationId(e),z.primeIdentity(void 0,e),$.info(`conversation rebound`,{previous:t,current:e}),t&&n.emit(`conversationRebound`,{previous:t,current:e})},[n,w,b,z]),Xt=l(e=>{let t=e.map(e=>e.createdAt).filter(e=>e!==void 0),n=(t.length?Math.min(...t):Date.now())-1;return[...(ve.current?.messages??[]).map(e=>{let t=Pa({...e,text:M(L.current,e.text)});return t.createdAt=n,t}),...e]},[]),Zt=l(async e=>{let t=qt.current;function r(){return t!==qt.current||w.value!==e}ge.current===e&&(ge.current=void 0),j(!0);try{let t=await z.loadConversation(e);if(r())return!1;let n=Ha(t.messages),i=Xt(uo(n,O.value));if(O.value=i,ge.current=i.some(e=>e.role===`user`)?void 0:e,n.length>0||t.controlState!==void 0){Ke({conversationId:e,reference:t.ticketReference}),t.controlState&&wt(t.controlState);let r=n.findLast(e=>e.role===`assistant`&&!e.ephemeral);Je(r?.suggestions??[])}return!0}catch(t){return r()||($.warn(`loadThread failed; keeping conversation active`,{err:t,conversationId:e}),n.emit(`error`,t),R.current.onError?.(t)),!1}finally{r()||j(!1)}},[z,O,w,Xt,n]),Qt=l(e=>{if(he.current===e)return he.current=void 0,Zt(e)},[Zt]),$t=l(()=>{if(ee.current)return Promise.resolve(void 0);let t=w.value,r=O.value.find(e=>e.serverMessageId!==void 0),i=r?.serverMessageId,a=r?new Date(r.createdAt).toISOString():void 0;if(!t||!i||!a)return Promise.resolve(void 0);let o=qt.current,s={};return ee.current=s,(async()=>{try{let e=await z.loadConversation(t,{beforeId:i,beforeCreatedAt:a});if(ee.current!==s||qt.current!==o||w.value!==t)return;if(e.messages.length===0)return!1;let n=e.messages.map(La),r=O.value,c=ro(r,n);if(c!==r){let e=Math.min(...n.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)}O.value=c}return!0}catch(r){if(ee.current!==s||qt.current!==o||w.value!==t)return;$.warn(`load previous messages failed`,{err:r,conversationId:t,beforeId:i}),n.emit(`error`,r),e.onError?.(r);return}finally{ee.current===s&&(ee.current=void 0)}})()},[n,w,O,e,z]),en=l(async({newConversation:t})=>{let i=++Gt.current;function a(){return i!==Gt.current}if(!t){let e=await z.userSub(),t=b.loadLastUserSub();if(a())return;if(t&&t!==e){d?.();return}e&&b.saveLastUserSub(e)}let o=w.value,s=t||!o?Ut():o;s!==o&&(qt.current++,j(!1),r(()=>{w.value=s,D.value=s}),b.saveConversationId(s)),z.primeIdentity(x,s);let c;try{c=await z.handshake({visitorId:x,conversationId:s,userPrefs:b.loadUserPrefs(),locale:lt})}catch(r){if(a())return;n.emit(`error`,r),e.onError?.(r);let i=r instanceof Oo&&r.errorCode?qm[r.errorCode]:void 0;if(i){$.warn(`the widget is not shown: ${i}`),(ue||e.mode===`page`)&&le(!0);return}t||se(!0);return}if(a())return;e.continueLink&&c.visitorId!==x&&S(c.visitorId),c.conversationId!==s&&Jt(c.conversationId),ye.current=c;let l=E(c,lt);We(l.agent),it(er(c.config?.login));let u=c.config?.maxMessageCharacters;ot(typeof u==`number`&&u>0?u:void 0),l.site&&Qn(l.site)?Xe(l.site):l.site&&$.warn(`invalid site config, using fallback`,{site:l.site}),l.blocks&&$n(l.blocks)?Qe(l.blocks):l.blocks&&$.warn(`invalid blocks config, using fallback`,{blocks:l.blocks});let f=Yt(c.userPrefs);if(Object.keys(f).length>0&&!t&&(b.saveUserPrefs(f),f.locale&&ft(f.locale),f.soundMuted!==void 0&&st.setMuted(f.soundMuted),f.themeMode&&pt(f.themeMode),f.textSize&&mt(f.textSize)),ve.current=l.welcome,t||n.emit(`handshake`,c),l.welcome?.suggestions){let e=L.current;Je(l.welcome.suggestions.map(t=>({...t,label:M(e,t.label),...t.text===void 0?{}:{text:M(e,t.text)}})))}let p=!t&&(c.conversationId===o||e.continueLink!==void 0);T.current=p,p?_e.current||(he.current=c.conversationId):(ge.current=c.conversationId,Wt(l.welcome?.messages),Ft(c.conversationId)),t||se(!0)},[z,x,b,e,n,w,D,st,Wt,lt,Jt,Ft,d]),tn=JSON.stringify(e.userContext??null),nn=JSON.stringify(e.pageContext??null);u(()=>{z.setContext(e.userContext,Km(e.pageContext))},[z,tn,nn]);let rn=m(!1);u(()=>{z.setUserToken(e.userToken),rn.current?en({newConversation:!1}).then(()=>{pe&&Rt(!0)}):rn.current=!0},[z,e.userToken,o]);let an=l((e,t=[])=>Je(e.suggestions??t),[]);u(()=>(z.primeIdentity(x,w.value),en({newConversation:!1}),()=>{Gt.current++,qt.current++}),[]),u(()=>{pe&&F&&!_e.current&&(_e.current=!0,he.current===w.value&&j(!0))},[pe,F]);let on=m(tn);u(()=>{F&&on.current!==tn&&(on.current=tn,en({newConversation:!1}))},[tn,F,en]);let sn=m(async()=>!1),{sendAiTurn:cn,sendRoutedTurn:ln}=Rm({onConversationNotFound:e=>sn.current(e),transport:z,messagesSig:O,conversationIdSig:w,options:e,bus:n,feedback:st,persistence:b,visitorId:x,adoptConversationId:Jt,applyControlState:wt,setTicket:Ke,settleSuggestions:an,runCancellation:ct}),{toolInteraction:un,pageToolsRunning:dn,stopPageTools:fn}=Zp({streaming:Fe,controlModeSig:xt,messagesSig:O,sendAiTurn:cn,bus:n,humanInLoop:e.features.humanInLoop,tools:e.tools}),pn=l((e,t)=>{let r=O.value.find(t=>t.serverMessageId===e);r&&(r.feedback=t),$.info(`messageFeedback`,{messageId:e,value:t}),n.emit(`messageFeedback`,{messageId:e,value:t}),z.submitFeedback({messageId:e,value:t})},[n,O,z]),mn=l(()=>T.current||O.value.some(e=>!e.ephemeral&&e.role===`user`),[O]);km({activated:pe,conversationReady:F,paused:tt.status===`pending`||tt.status===`expired`,conversationIdSig:w,messagesSig:O,optionsRef:R,transport:z,visitorId:x,adoptControlStateChunk:Tt,adoptMemoryCompactionStateChunk:kt,settleSuggestions:an,recordConversationReply:Lt,transcriptRecoverySig:Mt,beginConversationTranscript:Pt,commitConversationTranscript:Ft,runCancellation:ct,feedback:st,bus:n,loadInitialThread:Qt,shouldReconcileOnConnect:mn,reconnectingSig:k});let hn=l(async(t,r,i)=>{if(Re.current||zt.gate)return!1;let a=w.value,o=a?Ot.value.get(a):void 0,s=xt.value!==`ai-agent`;if(!s&&o?.status===`compacting`||($.info(`send`,{textLen:t.length,attachments:r.length,streaming:Le.current,routedToOperator:s}),Le.current&&!s))return!1;let c=new AbortController,l={conversationId:a,controller:c};Re.current=l,Be(!0);try{st.unlock(),Ve.value=/* @__PURE__ */ new Map;let o=await Xm(z,r,c.signal,He,t=>{c.signal.aborted||($.warn(`upload failed`,{err:t}),n.emit(`error`,t),e.onError?.(t))});if(c.signal.aborted||w.value!==a)return!1;let s=a?Ot.value.get(a):void 0,l=xt.value!==`ai-agent`;if(!l&&s?.status===`compacting`||Le.current&&!l||!i&&o.length<r.length||!t&&o.length===0)return!1;n.emit(`send`,{text:t,attachmentCount:r.length}),qe.length>0&&Je([]),st.play(`messageSent`);let u=Ma(t,o,i);return _s(n,e,`user`,t),l?(O.value=[...O.value,u],i?await ln(u):(ln(u),!0)):(O.value=[...O.value,u,Na()],i?await cn({continueExisting:!1}):(cn({continueExisting:!1}),!0))}finally{Re.current===l&&(Re.current=null,Be(!1))}},[z,n,e,qe.length,O,w,Ot,cn,ln,xt,Ve,He,zt.gate]),gn=m(hn);gn.current=hn;let _n=w.value,vn=(_n?Ot.value.get(_n):void 0)?.status===`compacting`,yn=xt.value===`ai-agent`,bn=s(()=>{let e=O.value.at(-1);return e?.role===`assistant`&&e.partsSig.value.some(e=>e.kind===`tool`&&(e.stateSig.value===`approval-requested`||e.stateSig.value===`approval-responded`))}),xn=s(()=>O.value.some(e=>e.retryAction?.kind===`resend-user`||e.retryAction?.kind===`continue-assistant`));f(()=>{let e=w.value;return()=>{let t=Re.current;t&&t.conversationId===e&&(Re.current=null,Be(!1),t.controller.abort())}},[w.value]);let Cn=l(()=>{if(Re.current){$.info(`stop uploads`),Re.current.controller.abort();return}if(dn){$.info(`stop page tools`),n.emit(`stop`,void 0),fn();return}if(!ct.stop())return;$.info(`stop`),n.emit(`stop`,void 0);let e=O.value.at(-1);e&&e.role!==`user`&&e.status===`streaming`&&(e.canceled=!0,O.value=[...O.value])},[ct,n,O,dn,fn]),On=l(e=>{$.info(`card action`,{text:e}),gn.current(e,[])},[]),jn=l(e=>{if(Fe)return;let t=O.value,n=yo(t,e);if(n)switch($.info(`retry`,{kind:n.kind,messageId:n.messageId}),n.kind){case`continue-assistant`:if(xt.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,O.value=[...t],cn({continueExisting:!0,turn:e});return;case`resend-user`:{let r=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!r)return;let i=e=>{e&&Ht.current?.acceptQueuedMessage(n.messageId)};if(r.status=`complete`,r.errorText=void 0,r.retryAction=void 0,xt.value!==`ai-agent`){O.value=e.role===`assistant`?t.filter(t=>t!==e):[...t],ln(r).then(i);return}let a=Na();O.value=e.role===`assistant`?t.map(t=>t===e?a:t):[...t,a],cn({continueExisting:!1,turn:r}).then(i);return}case`repeat-user`:{let e=t.find(e=>e.role===`user`&&e.id===n.messageId);if(!e)return;let r=Ma(Ga(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]),xt.value!==`ai-agent`){O.value=[...t,r],ln(r);return}O.value=[...t,r,Na()],cn({continueExisting:!1,turn:r});return}default:return n}},[Fe,O,xt,cn,ln]),Nn=l(()=>{gs(e.mode,ke)===`exit-fullscreen`?($.info(`close → exit-fullscreen`,{mode:e.mode}),Ae(`normal`),n.emit(`fullscreen`,!1)):($.info(`close → panel closed`,{mode:e.mode}),we.current=t.contains(t.ownerDocument.activeElement),fe(!1),b.savePanelOpen(!1),n.emit(`close`,void 0),e.onClose?.())},[n,e,b,ke,t]);lm({hostElement:t,mode:e.mode,panelSize:ke,isOpen:I,surfaceReady:F,onClose:Nn}),u(()=>{!I&&we.current&&(we.current=!1,Ce.current?.focus())},[I]);let Pn=l(()=>{$.info(`open`,{mode:e.mode}),st.unlock(),Se(!0),fe(!0),b.savePanelOpen(!0),!Te&&!De&&Oe(),setTimeout(()=>Se(!1),Jm),n.emit(`open`,void 0),e.onOpen?.()},[n,e,st,b,Te,De,Oe]),Fn=l(()=>{let e=O.value.some(e=>e.role===`user`);if(ge.current===w.value&&!e&&w.value)$.info(`clear → reusing empty conversation`,{conversationId:w.value}),O.value.length===0&&Wt(ve.current?.messages);else return $.info(`clear → new conversation`,{wasStreaming:Fe}),n.emit(`clear`,void 0),ct.settle(),T.current=!1,he.current=void 0,ge.current=void 0,r(()=>{O.value=[],w.value=void 0,wt({controlMode:`ai-agent`,controlRevision:0})}),b.clearConversation(),Je([]),en({newConversation:!0})},[Fe,O,w,b,en,n,Wt,ct,wt]);sn.current=async e=>($.info(`conversation not found → new conversation`,{messageId:e.id}),await Fn(),e.status=`complete`,e.errorText=void 0,e.retryAction=void 0,O.value=[...O.value,e,Na()],cn({continueExisting:!1,turn:e,movedFromConversation:!0}));let B=l(()=>{let t=Fn();Ne(`chat`);let n=e.modules.list.find(e=>e.layout===`chat`)?.id;return n&&P.switchTab(n),t},[Fn,P,e]),In=l(async e=>{await B(),await gn.current(e,[])||Ht.current?.fill(e)},[B]),Rn=l(()=>{let e=ke===`expanded`?`normal`:`expanded`;$.info(`expand`,{from:ke,expanded:e===`expanded`}),Ae(e),b.savePanelSize(e),n.emit(`expand`,e===`expanded`)},[n,ke,b]),zn=l(()=>{let e=ke===`fullscreen`?`normal`:`fullscreen`;$.info(`fullscreen`,{from:ke,fullscreen:e===`fullscreen`}),Ae(e),b.savePanelSize(e),n.emit(`fullscreen`,e===`fullscreen`)},[n,ke,b]),Bn=l(()=>{Ne(e=>{let t=e===`history`?`chat`:`history`;return $.info(`toggleHistory`,{view:t}),n.emit(`toggleHistory`,{view:t}),t})},[n]),Vn=l(()=>{et(e=>{let t=!e;return $.info(`sidebarToggle`,{collapsed:t}),b.saveSidebarCollapsed(t),n.emit(`sidebarToggle`,{collapsed:t}),t})},[b,n]),Hn=l(e=>{$.info(`resize`,e),ht({widgetSize:e}),n.emit(`resize`,e)},[ht,n]),Un=l(async t=>{let i=t.conversationId;if(i===w.value&&It(i)){$.info(`selectConversation`,{conversationId:i,cached:!0}),n.emit(`selectConversation`,{conversationId:i}),z.publishConversation(t),Ne(`chat`);let e=ne();e&&P.switchTab(e),Ft(i);return}let a=++Gt.current;qt.current++,j(!1);function o(){return a!==Gt.current}$.info(`selectConversation`,{conversationId:i,wasStreaming:Fe}),n.emit(`selectConversation`,{conversationId:i}),z.publishConversation(t);try{let e=await z.loadConversation(i);if(o())return;ct.settle(),T.current=!0,he.current=void 0;let t=Ha(e.messages),n=e.conversationId!==w.value,a=n?t:uo(t,O.value);ge.current=a.some(e=>e.role===`user`)?void 0:e.conversationId,r(()=>{O.value=Xt(a),n&&(D.value=e.conversationId),w.value=e.conversationId}),b.saveConversationId(e.conversationId),z.primeIdentity(x,e.conversationId),Ke({conversationId:e.conversationId,reference:e.ticketReference}),e.controlState&&wt(e.controlState);let s=a.findLast(e=>e.role===`assistant`&&!e.ephemeral);Je(s?.suggestions??[]),n?Pt(e.conversationId):Ft(e.conversationId),Ne(`chat`);let c=ne();c&&P.switchTab(c)}catch(t){if(o())return;n.emit(`error`,t),e.onError?.(t)}},[z,O,w,D,n,e,b,Xt,Fe,x,ct,Pt,Ft,It,P]),Wn=m(void 0),Gn=l(t=>{let n=e.modules.list.find(e=>e.layout===Wm[t.to]);if(!n){$.warn(`open: the widget has no such tab`,{to:t.to});return}let r=t.id&&(n.layout===`help`||n.layout===`news`)?{kind:`content`,id:t.id,title:``}:void 0;P.open(n.id,r)},[e.modules,P]),Kn=l(e=>{I||Pn(),e!=null&&(wn(e)?F?Gn(e):Wn.current=e:$.warn(`open: unknown target`,{detail:e}))},[I,Pn,F,Gn]);u(()=>{F&&Wn.current&&(Gn(Wn.current),Wn.current=void 0)},[F,Gn]);let qn=F&&!A&&(!yn||!xn.value),[Jn,Yn]=h(),Zn=l(e=>{let t=Dn(e);t?(I||Pn(),Yn(t)):$.warn(`ask: expected { text, send? } with non-empty text`,{detail:e})},[I,Pn]),tr=I&&F&&!A,nr=tr&&qn&&!ze&&!(yn&&(Fe||vn));u(()=>{if(Jn===void 0||!(Jn.send?nr:tr))return;let e=ne();e?Me!==`chat`||!re()?(Ne(`chat`),P.switchTab(e)):(Yn(void 0),Jn.send?hn(Jn.text,[]).then(e=>{e||Ht.current?.fill(Jn.text)}):Ht.current?.fill(Jn.text)):($.warn(`ask: the widget has no chat`),Yn(void 0))},[Jn,tr,nr,Me,ae,e.modules,P,hn]),u(()=>{if(e.widgetId!=="default")return;let n=`data-${N.cssPrefix}-`,r=[`ask`,`open`,`close`].map(e=>n+e);function i(e){let i=e.composedPath().find(e=>e instanceof Element&&r.some(t=>e.hasAttribute(t)));if(!(i instanceof Element))return;e.preventDefault();let a=i.getAttribute(`${n}ask`),o=i.getAttribute(`${n}open`);a===null?o===null?kn(t,`close`):kn(t,`open`,Tn(o)):kn(t,`ask`,En(a||(i.textContent??``),{send:i.hasAttribute(`${n}send`)}))}return document.addEventListener(`click`,i),()=>document.removeEventListener(`click`,i)},[e.widgetId,t]),u(()=>{if(e.widgetId!=="default")return;let n=Mn(location.href);n&&(history.replaceState(history.state,``,n.url),n.ask?kn(t,`ask`,En(n.ask)):kn(t,`open`,n.target))},[e.widgetId,t]);let rr=m(Ln),ir=e.mode===`page`||e.mode===`inline`||e.mode===`standalone`;u(()=>a(()=>{let e=w.value,t={open:ir||I,ready:F,unread:jt.value,...e?{conversationId:e}:{}},r=rr.current;(t.open!==r.open||t.ready!==r.ready||t.unread!==r.unread||t.conversationId!==r.conversationId)&&(rr.current=t,n.emit(`state`,t),t.unread!==r.unread&&n.emit(`unread`,t.unread))}),[n,ir,I,F,jt,w]);let ar=m({handleOpenCommand:Kn,handleClose:Nn,handleExpand:Rn,handleFullscreen:zn,handleAskCommand:Zn});ar.current={handleOpenCommand:Kn,handleClose:Nn,handleExpand:Rn,handleFullscreen:zn,handleAskCommand:Zn},f(()=>An(t,{open:e=>ar.current.handleOpenCommand(e),close:()=>ar.current.handleClose(),expand:()=>ar.current.handleExpand(),fullscreen:()=>ar.current.handleFullscreen(),ask:e=>ar.current.handleAskCommand(e)}),[t]);let or=p(()=>_t(e,lt,ut,dt),[e,lt,ut,dt]);L.current=or.strings,u(()=>{let e=ye.current;if(!e?.translations?.length)return;let t=E(e,lt);We(t.agent),t.site&&Qn(t.site)&&Xe(t.site),t.blocks&&$n(t.blocks)&&Qe(t.blocks)},[lt]);function sr(e){Un(e)}let cr={options:or,transport:z,feedback:st,bus:n,persistence:b,conversationId:w.value??``,composerKey:D.value,composerApiRef:Ht,view:Me,isStreaming:Fe,pageToolRunning:dn,isMemoryCompacting:vn,canReleaseQueuedMessages:qn,queueManualMessages:yn&&xn.value,replyAwaitsCard:yn&&bn.value,sendPreparing:ze,attachmentUploadsSig:Ve,composerActive:or.mode===`page`||or.mode===`inline`||or.mode===`standalone`||I,controlMode:xt.value,assignedOperator:St.value,operatorAvailable:Ct.value,operatorRequestEnabled:e.features.operatorRequest,onRequestOperator:Et,onCancelOperatorRequest:Dt,loadingMessages:A,onLoadPreviousMessages:$t,messagesSig:O,reconnectingSig:k,agent:Ue,ticketReference:Ge?.conversationId===w.value?Ge?.reference:void 0,login:zt,onStartAsGuest:g,maxMessageCharacters:at,suggestions:qe,initialWidgetSize:C.widgetSize??null,onClear:Fn,onExpand:Rn,onFullscreen:zn,onSoundToggle:bt,onToggleHistory:Bn,onSelectHistoryConversation:sr,onNewConversation:B,onLocaleChange:gt,onThemeChange:vt,onTextSizeChange:yt,onWidgetSizeChange:Hn,onSend:hn,onStop:Cn,onSuggestion:t=>{if(Re.current)return;let r=t.text??t.label;$.info(`suggestion`,{text:r,autoSend:e.autoSendSuggestions}),n.emit(`suggestion`,{text:r}),e.autoSendSuggestions?hn(r,[]):Ht.current?.fill(r)},tool:un,onRetry:jn,onMessageFeedback:pn,onCardAction:On};if(ce)return/* @__PURE__ */ _(`div`,{class:`${Um}-anchor`,children:/* @__PURE__ */ _(Kp,{strings:or.strings,text:or.strings.chatUnavailable})});if(!F)return null;let lr=or.modules.list;function ur(e){let t=ms(`close`,or.mode,e)?Nn:void 0;return lr.length===0?/* @__PURE__ */ _(Kp,{strings:or.strings,text:or.strings.modulesEmpty,onClose:t}):lr.length===1&&lr[0]?.layout===`chat`?/* @__PURE__ */ _(Tp,{...cr,panelSize:e,onClose:t}):/* @__PURE__ */ _(Lp,{panelProps:{...cr,panelSize:e,onClose:t},enabledModules:lr,nav:P,bus:n,hasUnread:At.value,latestNews:Vt,onSelectConversation:sr,onStartNewConversation:In,onSetPanelSize:Ae})}if(e.mode===`page`){let t=e.history.enabled&&lr.some(e=>e.layout===`chat`);return/* @__PURE__ */ _(`div`,{class:`${Um}-anchor`,children:/* @__PURE__ */ _(Wp,{site:Ye,blocks:Ze,transport:z,strings:or.strings,locale:or.locale,persistence:b,showConversations:t,onSelectConversation:sr,onNewConversation:B,sidebarCollapsed:$e,onToggleSidebarCollapsed:Vn,children:ur(`fullscreen`)})})}if(ue){let t=e.mode===`standalone`?`fullscreen`:ke;return/* @__PURE__ */ _(`div`,{class:`${Um}-anchor`,children:ur(t)})}let dr=e.mode===`drawer`,fr=e.mode!==`modal`&&!e.launcher.hidden&&(!I||xe),pr=fr&&!xe&&!Te&&!dr?or.launcher.callout:null;return/* @__PURE__ */ v(`div`,{class:`${Um}-anchor`,"data-launcher-size":or.launcher.size,children:[I||pe?/* @__PURE__ */ _(`div`,{class:`${Um}-surface`,hidden:!I,children:ur(ke)}):null,fr?/* @__PURE__ */ _(Ic,{buttonRef:Ce,onToggle:Pn,launcher:or.launcher,strings:or.strings,leaving:xe,edgeTab:dr}):null,pr?/* @__PURE__ */ _(Vc,{callout:pr,launcherPosition:or.position,strings:or.strings,closeLabel:or.strings.close,onDismiss:Oe}):null]})}function Km(e){let t=e?.url??(typeof location<`u`?location.href:void 0);if(e||t)return{...e,...t?{url:t}:{}}}const qm={AI_AGENT_PUBLIC_ACCESS_NOT_FOUND:`the deployment was not found or is turned off`,AI_AGENT_PUBLIC_ORIGIN_NOT_ALLOWED:`this website is not in the deployment's allowed origins`},Jm=120,Ym=/* @__PURE__ */ new WeakMap;async function Xm(e,t,n,r,i){return(await Promise.all(t.map(async t=>{try{r(t.id,{status:`uploading`});let i=Ym.get(t)??await e.uploadFile(t.file,n,e=>r(t.id,{status:`uploading`,fraction:e}));return Ym.set(t,i),r(t.id,{status:`done`}),{id:i.id,name:i.originalName,mediaType:i.mimeType,size:i.fileSize,url:i.url}}catch(e){r(t.id,n.aborted?void 0:{status:`error`,refusal:e instanceof Oo&&e.status===400?e.errorCode:void 0}),i(e);return}}))).filter(e=>e!==void 0)}const Zm=R.scope(`error-boundary`);var Qm=class extends e{constructor(...e){super(...e),B(this,`state`,{crashed:!(`toSorted`in Array.prototype)})}componentDidCatch(e,t){Zm.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}};function $m(e){let{bus:r,host:i,appRoot:a,persistence:o,reportError:s}=e,c=e.initialRaw,l,u,d=at(c),f=o.loadUserPrefs().locale??d.locale,p=!0,m=0,h=0,g=Ht(r);function _(){let e=l&&E({config:l,translations:u},f).config;d=at(e?bt(c,e):c)}function v(){dn(i,fn(d.mode)),xn(i,{...d,themeMode:gt(d.themeMode,o.loadUserPrefs().themeMode)}),p&&(bn(i,eh(d)),p=!1)}function y(){v(),n(t(Qm,{onError:s},t(Gm,{key:m,bus:r,hostElement:i,options:d,recentHostEvents:g,loginRevision:h,onPersonChanged:S,onStartAsGuest:C})),a)}r.on(`handshake`,e=>{e.config&&(e.config.storageVersion&&o.rememberStorageVersion(e.config.storageVersion),l=e.config,u=e.translations,_(),y())}),r.on(`localeChange`,e=>{f=e,u?.length&&(_(),y())});let b=tn(r,{getOptions:()=>d,getVisitorId:()=>o.getVisitorId(),getConversationId:()=>o.loadConversationId()});function x(){let e=o.takeLoginReturn();return e?(o.saveConversationId(e.conversationId),o.saveDraft(e.conversationId,e.draft),o.savePanelOpen(!0),!0):!1}c.userToken&&x();function S(){o.reset(),g.length=0,m+=1,p=!0,_(),y()}function C(){c={...c,userContext:void 0,userToken:void 0},S()}function w(e){`userToken`in e&&e.userToken&&!c.userToken&&x()&&(m+=1),c={...c,...e},_(),y()}return{getOptions:()=>d,getUserOptions:()=>c,render:y,setUserOptions:e=>{c=e,_(),y()},patchUserOptions:w,login:e=>{h+=1,w({userToken:e})},reset:()=>C(),destroy:()=>b()}}function eh(e){if(e.mode===`standalone`)return`standalone`;if(e.mode===`inline`)return`inline`;let t=Kt(e.widgetId,e.storage,e.aiAgentDeploymentId),{panelOpen:n,panelSize:r}=Ds(e,Os(),t.loadPanelOpen(),t.loadPanelSize());return Ts(e.mode,r,n)}const th=R.scope(`hooks`),nh=`*`,rh=/* @__PURE__ */ new Set;function ih(e,t,n){let r={widgetId:e,event:t,listener:n};return rh.add(r),()=>{rh.delete(r)}}function ah(e,t,n){let r=[...rh];for(let i of r)if(sh(i.widgetId,e.widgetId)&&(i.event===`*`||i.event===t))try{i.listener(e,t,n)}catch(e){th.warn(`hook listener threw`,{event:t,error:e})}}function oh(e,t){return t.tap({hear:(t,n)=>ah(e,t,n),listensTo:t=>[...rh].some(n=>n.event===t&&sh(n.widgetId,e.widgetId))})}function sh(e,t){return e===`*`||e===t}const ch=/* @__PURE__ */ new Map;function lh(e){if(!e.aiAgentDeploymentId)throw Error(`aiAgentDeploymentId is required`);e.debug!==void 0&&Ke(e.debug);let t=R.scope(`mount`);t.info(`mount`,{widgetId:e.widgetId,publicKey:e.publicKey,mode:e.presentation?.mode});let r=at(e),i=r.widgetId,a=ch.get(i);a&&(t.debug(`destroy existing instance at slot`,{widgetId:i}),a.destroy());let o=pn({position:fn(r.mode),target:e.target??null});o.hostElement.dataset.widgetId=i;let s=new Rn,c=Kt(i,r.storage,r.aiAgentDeploymentId);function l(e){s.emit(`error`,e),u.getOptions().onError?.(e)}let u=$m({bus:s,host:o.hostElement,appRoot:o.appRoot,persistence:c,initialRaw:e,reportError:l}),d=Ln,f=()=>{},p=new Promise(e=>{f=e});s.on(`state`,e=>{d=e,e.ready&&f()}),u.render();let m=o.hostElement,h=null;function g(e){e.debug!==void 0&&Ke(e.debug),u.patchUserOptions(e)}let _={widgetId:i,open:e=>kn(m,`open`,e),close:()=>kn(m,`close`),expand:()=>kn(m,`expand`),ask:(e,t)=>kn(m,`ask`,En(e,t)),on:(e,t)=>s.on(e,t),update:e=>{t.debug(`update`,{patch:e}),g(e)},setUserContext:e=>{t.debug(`setUserContext`,{keys:Object.keys(e)}),g({userContext:{...u.getUserOptions().userContext,...e}})},clearUserContext:()=>{t.debug(`clearUserContext`),g({userContext:void 0})},setPageContext:e=>{t.debug(`setPageContext`,{keys:Object.keys(e)}),g({pageContext:{...u.getUserOptions().pageContext,...e}})},clearPageContext:()=>{t.debug(`clearPageContext`),g({pageContext:void 0})},get state(){return d},ready:p,reset:()=>{t.info(`reset`,{widgetId:i}),u.reset()},login:e=>{t.info(`login`,{widgetId:i}),u.login(e)},track:(e,t)=>{let n=Vt(e,t);n&&s.emit(`hostEvent`,n)},registerTool:kd,setDebug:e=>{Ke(e),t.info(`debug level set`,{level:qe()})},debugLevel:()=>qe(),onLog:e=>Ye(e),destroy:()=>{t.info(`destroy`,{widgetId:i}),s.emit(`state`,Ln),h?.(),u.destroy(),s.clear(),n(null,o.appRoot),o.destroy(),ch.get(i)===_&&ch.delete(i)}};return h=oh(_,s),ch.set(i,_),_}function uh(e){if(!e.aiAgentDeploymentId)throw Error(`aiAgentDeploymentId is required`);let t=e.widgetId??`default`,n=ch.get(t);return n?(n.update(e),n):lh(e)}function dh(e){if(e!==void 0){ch.get(e)?.destroy();return}let t=[...ch.values()];for(let e of t)e.destroy()}function fh(e=`default`){return ch.get(e)??null}function ph(){return[...ch.values()]}const mh=Xt,hh=N;export{nh as HOOK_WILDCARD,hh as brand,dh as destroy,ph as getAllInstances,fh as getInstance,ih as hook,uh as init,lh as mount,eh as resolveInitialHostMode,mh as version};