@filigran/chatbot 3.15.2 → 3.16.0
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/CHANGELOG.md +17 -1
- package/README.md +39 -0
- package/dist/index.d.ts +46 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{createContext as r,useContext as a,useState as o,useRef as s,useEffect as i,useCallback as l,useInsertionEffect as c,useLayoutEffect as d,useMemo as u,useId as p,Component as h,memo as g,forwardRef as m,useImperativeHandle as f}from"react";import v from"remark-gfm";import w from"remark-parse";import{unified as y}from"unified";import{createPortal as b}from"react-dom";import x from"react-markdown";import k from"remark-breaks";function N(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}function C(e){return function(e){if(!e)return e;const t=e.split("\n"),n=/^(\s*)(`{3,})(.*)$/,r=/^(markdown|md|mdx|markup)\b/i;let a=-1;for(let e=0;e<t.length;e++){const o=t[e].match(n);if(o&&3===o[2].length&&r.test(o[3].trim())){a=e;break}}if(-1===a)return e;const o=[];for(let e=a+1;e<t.length;e++){const r=t[e].match(n);r&&o.push({idx:e,run:r[2].length,bare:""===r[3].trim()})}const s=(e,n)=>{for(let r=e+1;r<n;r++)if(""!==t[r].trim())return!1;return!0};let i=0,l=3,c=0,d=-1;for(let e=0;e<o.length;e++){const t=o[e];if(t.bare&&0===i){const n=o[e+1];if(!n||!n.bare||s(t.idx,n.idx)){d=t.idx;break}i++}else i=t.bare?Math.max(0,i-1):i+1;c++,l=Math.max(l,t.run)}if(-1===d||0===c)return e;const u="`".repeat(Math.max(l+1,4)),p=t[a].match(n);t[a]=`${p[1]}${u}${p[3]}`;const h=t[d].match(n);return t[d]=`${h[1]}${u}`,t.join("\n")}(function(e){if(!e||-1===e.indexOf("|"))return e;const t=e.split("\n"),n=e=>{let t=e.trim();t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=[];let r="";for(let e=0;e<t.length;e++){const a=t[e];"\\"===a&&e+1<t.length?(r+=a+t[e+1],e++):"|"===a?(n.push(r),r=""):r+=a}return n.push(r),n},r=e=>e.includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e),a=e=>{const t=e.trim(),n=t.startsWith(":"),r=t.endsWith(":");return n&&r?":---:":r?"---:":n?":---":"---"},o=/^\s*(?:(?:>\s?)|(?:[-*+]\s+)|(?:\d{1,9}[.)]\s+))*(`{3,}|~{3,})(.*)$/;let s=null,i=0;const l=/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/;for(let e=0;e<t.length-1;e++){const c=t[e].match(o);if(c){const e=c[1];null===s?(s=e[0],i=e.length):e[0]===s&&e.length>=i&&""===c[2].trim()&&(s=null,i=0);continue}if(null!==s)continue;const d=t[e],u=t[e+1];if(!d.includes("|")||r(d)||!r(u))continue;const p=d.match(l),h=p?p[0].length:d.length-d.trimStart().length,g=p?" ".repeat(h):d.slice(0,h),m=n(d.slice(h)).length,f=n(u);if(m<2||f.length===m)continue;const v=[];for(let e=0;e<m;e++)v.push(f[e]?a(f[e]):"---");t[e+1]=`${g}| ${v.join(" | ")} |`}return t.join("\n")}(function(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("[")||t.startsWith("```"))return e;try{return JSON.parse(t),"```json\n"+t+"\n```"}catch{return e}}((t=e).includes("![")?t.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>``):t)));var t}const S=new Set(["http","https","mailto","tel"]);function I(e){const t=e.indexOf(":");if(t<0)return e;const n=e.indexOf("/"),r=e.indexOf("?"),a=e.indexOf("#");if(n>-1&&t>n||r>-1&&t>r||a>-1&&t>a)return e;const o=e.slice(0,t).toLowerCase();return S.has(o)||"data"===o&&/^data:image\//i.test(e)?e:""}const T=e=>e;function A(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function _(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function E(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}M`}function M(e,t){if(!e)return"";const n=new Date(e).getTime();if(Number.isNaN(n))return"";const r=Date.now()-n,a=Math.floor(r/6e4);if(a<1)return t("just now");if(a<60)return A(t,"{count}m ago",{count:a});const o=Math.floor(a/60);if(o<24)return A(t,"{count}h ago",{count:o});const s=Math.floor(o/24);return s<7?A(t,"{count}d ago",{count:s}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const L=["FILE","PRESENTATION","REPORT","VIDEO"],R=`(${L.join("|")}):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?`,$=/^[A-Z][A-Z0-9_]*$/;const D=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new Map;function z(e){const t=e.filter(e=>!L.includes(e)),n=t.join(","),r=j.get(n);if(r)return r;const a=[...L,...t].map(D).join("|"),o=t.length>0?`|(${t.map(D).join("|")}):([^\\]]+)`:"",s=[...L,...t].map(e=>`[[${e}:`),i={complete:new RegExp(`\\[\\[(?:${R}${o})\\]\\]`,"gi"),partial:new RegExp(`\\[\\[(?:${a})(?::[^\\]]*)?\\]?$`,"i"),heads:s,longestHead:Math.max(...s.map(e=>e.length))};return j.size>=32&&j.delete(j.keys().next().value),j.set(n,i),i}function O(e,t=!1,n=[]){if(!e)return[];const r=z(n),a=[];let o=0;for(const t of e.matchAll(r.complete)){if(t.index>o&&a.push({type:"text",value:e.slice(o,t.index)}),t[1]){const e=t[1].toUpperCase();n.includes(e)?a.push({type:"marker",kind:e,args:t[3]?`${t[2]}#/${t[3]}`:t[2]}):"FILE"===e?a.push({type:"file",fileId:t[2]}):a.push({type:"artifact",kind:e.toLowerCase(),id:t[2].toLowerCase(),slideRef:t[3]||void 0})}else a.push({type:"marker",kind:t[4].toUpperCase(),args:t[5]});o=t.index+t[0].length}const s=e.slice(o).replace(r.partial,""),i=t?function(e,t){for(let n=Math.max(0,e.length-t.longestHead);n<e.length;n++){if("["!==e[n])continue;const r=e.slice(n).toUpperCase();if(t.heads.some(e=>e.startsWith(r)))return e.slice(0,n)}return e}(s,r):s;return i&&a.push({type:"text",value:i}),a}function P(e,t=[]){const n=[];for(const r of O(e,!1,t))"text"===r.type&&r.value.trim()&&n.push(C(r.value));return n}const U=(e,t)=>`${e}:${t.toLowerCase()}`;function H(e,t){const n=[];if("presentation"===e.kind&&void 0!==e.slideCount&&n.push(A(t,"{count} slides",{count:e.slideCount})),"report"===e.kind&&void 0!==e.sectionCount&&n.push(A(t,"{count} sections",{count:e.sectionCount})),"video"===e.kind){void 0!==e.sceneCount&&n.push(A(t,"{count} scenes",{count:e.sceneCount}));const r=function(e){if(!e||e<=0)return;const t=Math.round(e/1e3);return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}(e.durationMs);r&&n.push(r)}return n.join(" · ")}function W(e){const t=new Map;for(const n of e){const e=n.group?.trim()||null;t.has(e)||t.set(e,[]),t.get(e).push(n)}const n=t.get(null);return t.delete(null),[...n?[{group:null,agents:n}]:[],...[...t].map(([e,t])=>({group:e,agents:t}))]}const q=y().use(w).use(v).freeze(),B=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function F(e){if(B.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(F).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function V(e,t){if(!B.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(F(e));case"tableRow":return void t.push((e.children??[]).map(F).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])V(n,t)}}function K(e){const t=[];for(const n of e)n.trim()&&V(q.parse(n),t);return t.map(e=>e.replace(/\s+/g," ").replace(/ ([.,!?;:])/g,"$1").trim()).filter(e=>/[\p{L}\p{N}]/u.test(e)).map(e=>/[.!?;:\u3002\uff01\uff1f]$/.test(e)?e:`${e}.`).join("\n")}const G=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;function J(e,t=220){const n=e.split(/\n+|(?<=[.!?;:\u3002\uff01\uff1f])\s+/).map(e=>e.trim()).filter(Boolean),r=[];for(const e of n){if(e.length<=t){r.push(e);continue}let n="";for(const a of e.split(" "))for(let e=0;e<a.length;e+=t){const o=a.slice(e,e+t);n?n.length+1+o.length<=t?n=`${n} ${o}`:(r.push(n),n=o):n=o}n&&r.push(n)}const a=[];for(const e of r){const n=a.length-1;n>=0&&a[n].length+1+e.length<=t?a[n]=`${a[n]} ${e}`:a.push(e)}return a}async function*Y(e,t,n,r){const a=a=>async function(e,t,n,r){const a=await e(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.requestHeaders??{}},body:JSON.stringify({text:n,format:"mp3"}),signal:r});if(!a.ok)throw new Error(`TTS failed: ${a.status}`);return a.blob()}(e,t,n[a],r).catch(()=>null);let o=n.length>0?a(0):null;for(let e=0;o;e+=1){const t=await o;o=e+1<n.length&&!r.aborted?a(e+1):null,yield t}}function X(e,t,n,r){const a=t?.[r];return"rest"!==n||t?.singleEndpoint||"string"!=typeof a||!a?null:`${e}${a}`}const Z={es:{"(no output)":"(sin salida)","1 tool call":"1 llamada a una herramienta","1 transfer":"1 transferencia","A file failed to upload: remove it, or send once the answer ends":"Un archivo no se pudo subir: quítelo, o envíe cuando termine la respuesta","A message references at most {count} conversations":"Un mensaje puede hacer referencia a {count} conversaciones como máximo","Acting on the page…":"Actuando en la página…","Agent switching is not available here":"El cambio de agente no está disponible aquí","Almost there":"Ya casi estamos","Also applies to your scheduled runs, until you revoke it":"También se aplica a sus ejecuciones programadas, hasta que lo revoque","Always allowed":"Siempre permitido","Analyzing results…":"Analizando los resultados…","Analyzing the details":"Analizando los detalles",Approved:"Aprobado","Ask Assistant":"Preguntar al asistente","Ask a question...":"Haga una pregunta...",Assistant:"Asistente","Attach files":"Adjuntar archivos","Attached files":"Archivos adjuntos","Attachments wait for the current response":"Los archivos adjuntos esperan la respuesta actual",Back:"Volver","Bad response":"Respuesta incorrecta","Browse agents":"Explorar agentes",Cancel:"Cancelar","Cancel question":"Cancelar la pregunta","Clear all conversations":"Borrar todas las conversaciones",Close:"Cerrar","Collecting results from one task…":"Recopilando los resultados de una tarea…","Collecting results from {count} tasks…":"Recopilando los resultados de {count} tareas…","Composing answer…":"Redactando la respuesta…",Confirm:"Confirmar","Connecting the dots":"Atando cabos","Consulting the sources":"Consultando las fuentes","Consulting {agent}…":"Consultando a {agent}…","Context full — older turns are being dropped":"Contexto completo: se están eliminando los turnos más antiguos","Context nearly full — older turns are being summarized":"El contexto está casi lleno: se están resumiendo los turnos más antiguos","Context used":"Contexto utilizado","Continue now":"Continuar ahora",Conversation:"Conversación","Conversation history":"Historial de conversaciones","Conversation title":"Título de la conversación","Conversation transcript":"Hilo de la conversación",Copied:"Copiado","Copied!":"¡Copiado!","Copy code":"Copiar código","Copy message":"Copiar mensaje","Copy response":"Copiar respuesta","Could not reach the assistant service. Check the connection and try again.":"No se ha podido conectar con el servicio del asistente. Compruebe la conexión e inténtelo de nuevo.","Could not send your decision. Please try again.":"No se ha podido enviar su decisión. Inténtelo de nuevo.","Create agent":"Crear agente","Crunching the data":"Procesando los datos","Decline this call":"Rechazar esta llamada",Declined:"Rechazado","Delegating one task…":"Delegando una tarea…","Delegating {count} tasks…":"Delegando {count} tareas…","Delete all conversations":"Eliminar todas las conversaciones","Delete all conversations?":"¿Eliminar todas las conversaciones?","Delete conversation":"Eliminar conversación","Delete workspace":"Eliminar espacio de trabajo","Delete?":"¿Eliminar?","Dictate a message":"Dictar un mensaje","Did not answer":"No respondió",Download:"Descargar","Download {format}":"Descargar en {format}","Drop a conversation here, or start one with +.":"Suelte aquí una conversación o inicie una con +.","Drop files to attach them":"Suelte los archivos para adjuntarlos","End voice call":"Finalizar la llamada de voz","Enter to send now · Esc to stop":"Pulse Intro para enviar ahora · Esc para detener","Enter to send when the answer ends · Esc to stop":"Pulse Intro para enviar cuando termine la respuesta · Esc para detener","Every conversation is in a workspace.":"Todas las conversaciones están en un espacio de trabajo.","Expand image":"Ampliar imagen","Failed to get a response. Resuming…":"No se obtuvo respuesta. Reanudando…","Feedback already submitted":"Valoración ya enviada","Files uploading...":"Cargando archivos...",Floating:"Flotante","Full screen":"Pantalla completa","Good response":"Buena respuesta","Help me create a new simulation scenario":"Ayúdame a crear un nuevo escenario de simulación","Hide conversations":"Ocultar conversaciones","How can I help you, {name}?":"¿En qué puedo ayudarle, {name}?","How can {agent} help you, {name}?":"¿En qué puede ayudarle {agent}, {name}?","How do I configure detection rules?":"¿Cómo configuro las reglas de detección?","Image could not be loaded":"No se ha podido cargar la imagen","Image preview":"Vista previa de la imagen","Incorporating your message…":"Incorporando su mensaje…",Input:"Entrada","Insert prompt template":"Insertar plantilla de prompt","Listening...":"Escuchando...","Load earlier messages":"Cargar mensajes anteriores","Loading image…":"Cargando imagen…","MCP & dynamic tools":"MCP y herramientas dinámicas","Mention an agent":"Mencionar un agente","Model reasoning":"Razonamiento del modelo","Move to workspace":"Mover a un espacio de trabajo","Mute microphone":"Silenciar el micrófono",Muted:"Silenciado","New chat":"Nuevo chat","New conversation":"Nueva conversación","New conversation in this workspace":"Nueva conversación en este espacio de trabajo","New conversation — send a message to start it":"Nueva conversación: envíe un mensaje para iniciarla","New workspace":"Nuevo espacio de trabajo",No:"No","No agent matches":"No hay ningún agente que coincida","No conversation matches":"No hay conversaciones que coincidan","No conversations yet":"Aún no hay conversaciones","No prompt matches":"No hay ningún prompt que coincida","No response.":"Sin respuesta.","Not in a workspace":"Sin espacio de trabajo","Not rendered yet":"Renderizado no iniciado",Open:"Abrir","Open conversation":"Abrir conversación","Open in XTM One":"Abrir en XTM One","Other workspaces":"Otros espacios de trabajo",Output:"Salida","Play Space Invaders":"Jugar a Space Invaders","Play Space Invaders in XTM One":"Jugar a Space Invaders en XTM One","Polishing the answer":"Puliendo la respuesta",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (editable)",Presentation:"Presentación","Putting it together":"Juntando las piezas",Quota:"Cuota","Quota reached":"Cuota alcanzada","Read aloud":"Leer en voz alta","Reasoning details":"Detalles del razonamiento","Reasoning details — turn limit reached":"Detalles del razonamiento: se ha alcanzado el límite de turnos","Reconnecting…":"Reconectando…","Reference a conversation":"Hacer referencia a una conversación","Remove from workspace":"Quitar del espacio de trabajo","Rename conversation":"Cambiar el nombre de la conversación","Rename workspace":"Cambiar el nombre del espacio de trabajo","Rendering {progress}%":"Renderizando {progress} %",Report:"Informe","Response ready":"Respuesta lista","Reticulating splines":"Reticulando splines",Retry:"Reintentar",Save:"Guardar","Search agents...":"Buscar agentes...","Search conversations...":"Buscar conversaciones...","Search prompts...":"Buscar prompts...",Send:"Enviar","Send now":"Enviar ahora","Send when the answer ends":"Enviar cuando termine la respuesta","Sending…":"Enviando…","Sends when the answer ends:":"Se enviará cuando termine la respuesta:","Shared with you":"Compartido con usted","Show conversations":"Mostrar conversaciones",Sidebar:"Barra lateral",Skip:"Omitir","Skip response":"Omitir la respuesta","Sorry, an error occurred. Please try again.":"Lo sentimos, se ha producido un error. Inténtelo de nuevo.","Speak or tap to interrupt":"Habla o toca para interrumpir","Speaking…":"Hablando…","Stop dictation":"Detener el dictado","Stop generating":"Detener la generación","Stop reading":"Detener la lectura",Stopped:"Detenido","Stopping…":"Deteniendo…",Suggestions:"Sugerencias","Summarize my recent findings":"Resume mis hallazgos recientes","Summarized conversation":"Conversación resumida","Switch to":"Cambiar a","Switch to another agent":"Cambiar a otro agente","Switch view":"Cambiar de vista","System prompt":"Prompt del sistema","Tap to cancel":"Toca para cancelar","Tell us what went wrong (optional)":"Indíquenos qué ha fallado (opcional)","The agent needs your approval to run a tool:":"El agente necesita su aprobación para ejecutar una herramienta:","The agent needs your approval to run these tools:":"El agente necesita su aprobación para ejecutar estas herramientas:","The conversation could not be moved":"No se ha podido mover la conversación","The render did not finish":"El renderizado no ha finalizado","The workspace could not be created":"No se ha podido crear el espacio de trabajo","The workspace could not be deleted":"No se ha podido eliminar el espacio de trabajo","The workspace could not be renamed":"No se ha podido cambiar el nombre del espacio de trabajo","Thinking it through":"Reflexionando sobre ello","Thinking...":"Pensando...","This conversation could not be loaded.":"No se ha podido cargar esta conversación.","This decision could not be sent. Reload the chat and try again.":"No se ha podido enviar esta decisión. Actualice el chat e inténtelo de nuevo.","This message waits for the current response":"Este mensaje espera la respuesta actual","This message will be read with your next one.":"Este mensaje se leerá con su próximo mensaje.","This item could not be loaded.":"No se ha podido cargar este elemento.","The response could not be stopped. Try again.":"No se ha podido detener la respuesta. Inténtelo de nuevo.","This turn is no longer waiting for a decision.":"Este turno ya no está a la espera de una decisión.","Tool definitions":"Definiciones de herramientas","Tool results":"Resultados de las herramientas","Transfer chain":"Cadena de transferencia","Transferred from {agent}":"Transferido desde {agent}","Transferring to {agent}…":"Transfiriendo a {agent}…","Turn limit reached.":"Se ha alcanzado el límite de turnos.","Unable to connect. Please check the configuration.":"No se puede establecer conexión. Compruebe la configuración.","Unmute microphone":"Activar el micrófono","Untitled conversation":"Conversación sin título",Usage:"Uso","Usage · {period}":"Uso · {period}","Uses AI. Verify results.":"Utiliza IA. Verifique los resultados.","Using tools…":"Usando herramientas…",Video:"Vídeo","Voice call":"Llamada de voz","Waiting before continuing…":"Esperando antes de continuar…","Waiting for one background task…":"Esperando una tarea en segundo plano…","Waiting for your approval…":"Esperando su aprobación…","Waiting for {count} background tasks…":"Esperando {count} tareas en segundo plano…","Waiting to render":"Esperando el renderizado","What are the latest attack patterns?":"¿Cuáles son los últimos patrones de ataque?","What could be improved?":"¿Qué se podría mejorar?","Why not? The agent sees this and can adapt (optional)":"¿Por qué no? El agente ve esto y puede adaptarse (opcional)","Workspace name":"Nombre del espacio de trabajo",Workspaces:"Espacios de trabajo","Wrapping things up":"Finalizando",Yes:"Sí","Yes, always":"Sí, siempre","Your answer is ready":"Su respuesta está lista",default:"predeterminado","e.g. wrong environment — use staging instead":"Por ejemplo, entorno incorrecto: utilice el entorno de pruebas en su lugar","just now":"hace un momento","the agent":"el agente","this month":"este mes","this year":"este año",today:"hoy","unknown tool":"herramienta desconocida","{agent} has finished":"{agent} ha finalizado","{counts} tokens":"{counts} tokens","{count} iterations":"{count} iteraciones","{count} scenes":"{count} escenas","{count} sections":"{count} secciones","{count} slides":"{count} diapositivas","{count} tool calls":"{count} llamadas a herramientas","{count} transfers":"{count} transferencias","{count}d ago":"hace {count} d","{count}h ago":"hace {count} h","{count}m ago":"hace {count} min","{decided}/{total} decided":"{decided}/{total} decididos","{percent}% full":"{percent} % completo","{quota} (shared across all users)":"{quota} (compartido entre todos los usuarios)","{summary} — click for details":"{summary} — haga clic para ver más detalles","{tool} (+{count} more)…":"{tool} (+{count} más)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Se agotó el presupuesto de iteraciones del agente: la ejecución se detuvo antes de completar todos los pasos previstos. La respuesta final es un resumen aproximado del trabajo realizado hasta ahora.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Sí, siempre» guarda una preferencia para ti. Esa herramienta se ejecutará entonces sin preguntar, incluso en ejecuciones programadas que nadie supervisa, hasta que la revoques."},fr:{"(no output)":"(pas de sortie)","1 tool call":"1 appel d’outil","1 transfer":"1 transfert","A file failed to upload: remove it, or send once the answer ends":"Un fichier n’a pas pu être envoyé : retirez-le, ou envoyez une fois la réponse terminée","A message references at most {count} conversations":"Un message fait référence à {count} conversations au maximum","Acting on the page…":"Action sur la page…","Agent switching is not available here":"Le changement d’agent n’est pas disponible ici","Almost there":"On y est presque","Also applies to your scheduled runs, until you revoke it":"S’applique également à vos exécutions planifiées, jusqu’à ce que vous la révoquiez","Always allowed":"Toujours autorisé","Analyzing results…":"Analyse des résultats…","Analyzing the details":"Analyse des détails",Approved:"Approuvé","Ask Assistant":"Demander à l’assistant","Ask a question...":"Poser une question...",Assistant:"Assistant","Attach files":"Joindre des fichiers","Attached files":"Fichiers joints","Attachments wait for the current response":"Les pièces jointes attendent la réponse en cours",Back:"Retour","Bad response":"Réponse incorrecte","Browse agents":"Parcourir les agents",Cancel:"Annuler","Cancel question":"Annuler la question","Clear all conversations":"Effacer toutes les conversations",Close:"Fermer","Collecting results from one task…":"Collecte des résultats d’une tâche…","Collecting results from {count} tasks…":"Collecte des résultats de {count} tâches…","Composing answer…":"Rédaction de la réponse…",Confirm:"Confirmer","Connecting the dots":"Relier les points","Consulting the sources":"Consulter les sources","Consulting {agent}…":"Consultation de {agent}…","Context full — older turns are being dropped":"Contexte complet — les tours plus anciens sont supprimés","Context nearly full — older turns are being summarized":"Contexte presque plein — les tours plus anciens sont en cours de synthèse","Context used":"Contexte utilisé","Continue now":"Continuer maintenant",Conversation:"Conversation","Conversation history":"Historique des conversations","Conversation title":"Titre de la conversation","Conversation transcript":"Fil de la conversation",Copied:"Copié","Copied!":"Copié !","Copy code":"Copier le code","Copy message":"Copier le message","Copy response":"Copier la réponse","Could not reach the assistant service. Check the connection and try again.":"Impossible d’accéder au service d’assistant. Vérifiez la connexion et réessayez.","Could not send your decision. Please try again.":"Impossible d’envoyer votre décision. Veuillez réessayer.","Create agent":"Créer un agent","Crunching the data":"Traitement des données","Decline this call":"Refuser cet appel",Declined:"Refusé","Delegating one task…":"Délégation d’une tâche…","Delegating {count} tasks…":"Délégation de {count} tâches…","Delete all conversations":"Supprimer toutes les conversations","Delete all conversations?":"Supprimer toutes les conversations ?","Delete conversation":"Supprimer la conversation","Delete workspace":"Supprimer l’espace de travail","Delete?":"Supprimer ?","Dictate a message":"Dicter un message","Did not answer":"N’a pas répondu",Download:"Télécharger","Download {format}":"Télécharger en {format}","Drop a conversation here, or start one with +.":"Déposez une conversation ici ou démarrez-en une avec +.","Drop files to attach them":"Déposez des fichiers pour les joindre","End voice call":"Terminer l’appel vocal","Enter to send now · Esc to stop":"Appuyez sur Entrée pour envoyer maintenant · Appuyez sur Échap pour arrêter","Enter to send when the answer ends · Esc to stop":"Appuyez sur Entrée pour envoyer à la fin de la réponse · Appuyez sur Échap pour arrêter","Every conversation is in a workspace.":"Toutes les conversations sont dans un espace de travail.","Expand image":"Agrandir l’image","Failed to get a response. Resuming…":"Aucune réponse reçue. Reprise…","Feedback already submitted":"Avis déjà envoyé","Files uploading...":"Envoi des fichiers en cours...",Floating:"Flottant","Full screen":"Plein écran","Good response":"Bonne réponse","Help me create a new simulation scenario":"Aidez-moi à créer un nouveau scénario de simulation","Hide conversations":"Masquer les conversations","How can I help you, {name}?":"Comment puis-je vous aider, {name} ?","How can {agent} help you, {name}?":"Comment {agent} peut-il vous aider, {name} ?","How do I configure detection rules?":"Comment configurer les règles de détection ?","Image could not be loaded":"Impossible de charger l’image","Image preview":"Aperçu de l’image","Incorporating your message…":"Intégration de votre message…",Input:"Entrée","Insert prompt template":"Insérer un modèle de prompt","Listening...":"Écoute en cours...","Load earlier messages":"Charger les messages précédents","Loading image…":"Chargement de l’image…","MCP & dynamic tools":"MCP et outils dynamiques","Mention an agent":"Mentionner un agent","Model reasoning":"Raisonnement du modèle","Move to workspace":"Déplacer vers un espace de travail","Mute microphone":"Couper le micro",Muted:"Micro coupé","New chat":"Nouveau chat","New conversation":"Nouvelle conversation","New conversation in this workspace":"Nouvelle conversation dans cet espace de travail","New conversation — send a message to start it":"Nouvelle conversation — envoyez un message pour la démarrer","New workspace":"Nouvel espace de travail",No:"Non","No agent matches":"Aucun agent ne correspond","No conversation matches":"Aucune conversation ne correspond","No conversations yet":"Aucune conversation pour l’instant","No prompt matches":"Aucun prompt ne correspond","No response.":"Pas de réponse.","Not in a workspace":"Hors espace de travail","Not rendered yet":"Rendu non lancé",Open:"Ouvrir","Open conversation":"Ouvrir la conversation","Open in XTM One":"Ouvrir dans XTM One","Other workspaces":"Autres espaces de travail",Output:"Sortie","Play Space Invaders":"Jouer à Space Invaders","Play Space Invaders in XTM One":"Jouer à Space Invaders dans XTM One","Polishing the answer":"Peaufiner la réponse",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (modifiable)",Presentation:"Présentation","Putting it together":"Assemblage des éléments",Quota:"Quota","Quota reached":"Quota atteint","Read aloud":"Lire à voix haute","Reasoning details":"Détails du raisonnement","Reasoning details — turn limit reached":"Détails du raisonnement — limite de tours atteinte","Reconnecting…":"Reconnexion…","Reference a conversation":"Faire référence à une conversation","Remove from workspace":"Retirer de l’espace de travail","Rename conversation":"Renommer la conversation","Rename workspace":"Renommer l’espace de travail","Rendering {progress}%":"Rendu en cours : {progress} %",Report:"Rapport","Response ready":"Réponse prête","Reticulating splines":"Réticulation des splines",Retry:"Réessayer",Save:"Sauvegarder","Search agents...":"Rechercher des agents...","Search conversations...":"Rechercher des conversations...","Search prompts...":"Rechercher des prompts...",Send:"Envoyer","Send now":"Envoyer maintenant","Send when the answer ends":"Envoyer à la fin de la réponse","Sending…":"Envoi en cours…","Sends when the answer ends:":"Envoi à la fin de la réponse :","Shared with you":"Partagé avec vous","Show conversations":"Afficher les conversations",Sidebar:"Barre latérale",Skip:"Passer","Skip response":"Passer la réponse","Sorry, an error occurred. Please try again.":"Désolé, une erreur s’est produite. Veuillez réessayer.","Speak or tap to interrupt":"Parlez ou touchez pour interrompre","Speaking…":"Réponse en cours…","Stop dictation":"Arrêter la dictée","Stop generating":"Arrêter la génération","Stop reading":"Arrêter la lecture",Stopped:"Arrêté","Stopping…":"Arrêt en cours…",Suggestions:"Suggestions","Summarize my recent findings":"Résumez mes dernières découvertes","Summarized conversation":"Résumé de la conversation","Switch to":"Basculer vers","Switch to another agent":"Passer à un autre agent","Switch view":"Changer de vue","System prompt":"Prompt système","Tap to cancel":"Touchez pour annuler","Tell us what went wrong (optional)":"Dites-nous ce qui n’a pas fonctionné (facultatif)","The agent needs your approval to run a tool:":"L’agent a besoin de votre accord pour exécuter un outil :","The agent needs your approval to run these tools:":"L’agent a besoin de votre accord pour exécuter ces outils :","The conversation could not be moved":"Impossible de déplacer la conversation","The render did not finish":"Le rendu n’a pas abouti","The workspace could not be created":"Impossible de créer l’espace de travail","The workspace could not be deleted":"Impossible de supprimer l’espace de travail","The workspace could not be renamed":"Impossible de renommer l’espace de travail","Thinking it through":"Réfléchir à la question","Thinking...":"Je réfléchis...","This conversation could not be loaded.":"Impossible de charger cette conversation.","This decision could not be sent. Reload the chat and try again.":"Cette décision n’a pas pu être envoyée. Actualisez le chat et réessayez.","This message waits for the current response":"Ce message attend la réponse en cours","This message will be read with your next one.":"Ce message sera lu avec votre prochain message.","This item could not be loaded.":"Impossible de charger cet élément.","The response could not be stopped. Try again.":"La réponse n’a pas pu être arrêtée. Réessayez.","This turn is no longer waiting for a decision.":"Ce tour n’attend plus de décision.","Tool definitions":"Définitions des outils","Tool results":"Résultats des outils","Transfer chain":"Chaîne de transfert","Transferred from {agent}":"Transféré depuis {agent}","Transferring to {agent}…":"Transfert vers {agent}…","Turn limit reached.":"Limite de tours atteinte.","Unable to connect. Please check the configuration.":"Impossible de se connecter. Veuillez vérifier la configuration.","Unmute microphone":"Réactiver le micro","Untitled conversation":"Conversation sans titre",Usage:"Utilisation","Usage · {period}":"Utilisation · {period}","Uses AI. Verify results.":"Utilise l’IA. Vérifiez les résultats.","Using tools…":"Utilisation des outils…",Video:"Vidéo","Voice call":"Appel vocal","Waiting before continuing…":"En attente avant de continuer…","Waiting for one background task…":"En attente d’une tâche en arrière-plan…","Waiting for your approval…":"En attente de votre accord…","Waiting for {count} background tasks…":"En attente de {count} tâches en arrière-plan…","Waiting to render":"En attente du rendu","What are the latest attack patterns?":"Quels sont les derniers schémas d’attaque ?","What could be improved?":"Qu’est-ce qui pourrait être amélioré ?","Why not? The agent sees this and can adapt (optional)":"Pourquoi pas ? L’agent en prend connaissance et peut s’adapter (facultatif)","Workspace name":"Nom de l’espace de travail",Workspaces:"Espaces de travail","Wrapping things up":"Pour conclure",Yes:"Oui","Yes, always":"Oui, toujours","Your answer is ready":"Votre réponse est prête",default:"par défaut","e.g. wrong environment — use staging instead":"Par exemple : environnement incorrect — utilisez plutôt l’environnement de préproduction","just now":"à l’instant","the agent":"l’agent","this month":"ce mois-ci","this year":"cette année",today:"aujourd’hui","unknown tool":"outil inconnu","{agent} has finished":"{agent} a terminé","{counts} tokens":"{counts} tokens","{count} iterations":"{count} itérations","{count} scenes":"{count} scènes","{count} sections":"{count} sections","{count} slides":"{count} diapositives","{count} tool calls":"{count} appels d’outils","{count} transfers":"{count} transferts","{count}d ago":"il y a {count} j","{count}h ago":"il y a {count} h","{count}m ago":"il y a {count} min","{decided}/{total} decided":"{decided}/{total} décidés","{percent}% full":"{percent} % rempli","{quota} (shared across all users)":"{quota} (partagé entre tous les utilisateurs)","{summary} — click for details":"{summary} — cliquez pour plus de détails","{tool} (+{count} more)…":"{tool} (+{count} autres)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Le budget d’itérations de l’agent est épuisé : l’exécution s’est arrêtée avant la fin de toutes les étapes prévues. La réponse finale résume au mieux le travail accompli jusqu’ici.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"« Oui, toujours » enregistre une préférence pour vous. Cet outil s’exécutera alors sans demander, y compris lors des exécutions planifiées que personne ne surveille, jusqu’à ce que vous la révoquiez."},ja:{"(no output)":"(出力なし)","1 tool call":"ツール呼び出し 1 件","1 transfer":"転送 1 件","A file failed to upload: remove it, or send once the answer ends":"ファイルのアップロードに失敗しました。削除するか、応答の終了後に送信してください","A message references at most {count} conversations":"1 つのメッセージで参照できる会話は最大 {count} 件です","Acting on the page…":"ページを操作中…","Agent switching is not available here":"ここではエージェントの切り替えは利用できません","Almost there":"もうすぐ完了します","Also applies to your scheduled runs, until you revoke it":"予定された実行についても、取り消すまでは同様に適用されます","Always allowed":"常に許可","Analyzing results…":"結果を分析中…","Analyzing the details":"詳細を分析しています",Approved:"承認済み","Ask Assistant":"アシスタントに質問","Ask a question...":"質問する...",Assistant:"アシスタント","Attach files":"ファイルを添付","Attached files":"添付ファイル","Attachments wait for the current response":"添付ファイルは、現在の応答を待機します",Back:"戻る","Bad response":"不適切な回答","Browse agents":"エージェントを閲覧する",Cancel:"キャンセル","Cancel question":"質問をキャンセル","Clear all conversations":"すべての会話を消去",Close:"閉じる","Collecting results from one task…":"1 件のタスクの結果を収集中…","Collecting results from {count} tasks…":"{count} 件のタスクの結果を収集中…","Composing answer…":"回答を作成中…",Confirm:"確認する","Connecting the dots":"情報を関連付けています","Consulting the sources":"情報源を確認しています","Consulting {agent}…":"{agent} に問い合わせ中…","Context full — older turns are being dropped":"コンテキストが満杯 — 古いターンが削除されています","Context nearly full — older turns are being summarized":"コンテキストがほぼ満杯です — 古いターンが要約されています","Context used":"使用されたコンテキスト","Continue now":"今すぐ続行",Conversation:"会話","Conversation history":"会話履歴","Conversation title":"会話のタイトル","Conversation transcript":"会話の履歴",Copied:"コピーしました","Copied!":"コピー完了!","Copy code":"コードをコピー","Copy message":"メッセージをコピー","Copy response":"応答をコピー","Could not reach the assistant service. Check the connection and try again.":"アシスタントサービスに接続できませんでした。接続状態を確認して、もう一度お試しください。","Could not send your decision. Please try again.":"決定内容を送信できませんでした。もう一度お試しください。","Create agent":"エージェントを作成する","Crunching the data":"データを処理しています","Decline this call":"この呼び出しを拒否",Declined:"拒否済み","Delegating one task…":"1 件のタスクを委任中…","Delegating {count} tasks…":"{count} 件のタスクを委任中…","Delete all conversations":"すべての会話を削除","Delete all conversations?":"すべての会話を削除しますか?","Delete conversation":"会話を削除","Delete workspace":"ワークスペースを削除","Delete?":"削除しますか?","Dictate a message":"メッセージを音声入力する","Did not answer":"回答なし",Download:"ダウンロード","Download {format}":"{format} をダウンロード","Drop a conversation here, or start one with +.":"ここに会話をドロップするか、+ で新しく開始してください。","Drop files to attach them":"ファイルをドロップして添付","End voice call":"音声通話を終了","Enter to send now · Esc to stop":"Enterキーで今すぐ送信 · Escキーで停止","Enter to send when the answer ends · Esc to stop":"Enterキーで回答の終了後に送信 · Escキーで停止","Every conversation is in a workspace.":"すべての会話がワークスペースに含まれています。","Expand image":"画像を拡大","Failed to get a response. Resuming…":"応答を取得できませんでした。再開しています…","Feedback already submitted":"フィードバックは送信済みです","Files uploading...":"ファイルのアップロード中...",Floating:"フローティング","Full screen":"全画面表示","Good response":"適切な回答","Help me create a new simulation scenario":"新しいシミュレーションシナリオの作成を手伝ってください","Hide conversations":"会話を非表示にする","How can I help you, {name}?":"{name} さん、何かお手伝いできることはありますか?","How can {agent} help you, {name}?":"{name} さん、{agent} がお手伝いできることはありますか?","How do I configure detection rules?":"検出ルールはどのように設定すればよいですか?","Image could not be loaded":"画像を読み込めませんでした","Image preview":"画像プレビュー","Incorporating your message…":"メッセージを組み込んでいます…",Input:"入力","Insert prompt template":"プロンプトテンプレートを挿入","Listening...":"聞き取り中...","Load earlier messages":"以前のメッセージを読み込む","Loading image…":"画像を読み込み中…","MCP & dynamic tools":"MCPと動的ツール","Mention an agent":"エージェントをメンション","Model reasoning":"モデルの推論","Move to workspace":"ワークスペースに移動","Mute microphone":"マイクをミュート",Muted:"ミュート中","New chat":"新しいチャット","New conversation":"新しい会話","New conversation in this workspace":"このワークスペースで新しい会話","New conversation — send a message to start it":"新しい会話 — メッセージを送信すると開始されます","New workspace":"新しいワークスペース",No:"いいえ","No agent matches":"該当するエージェントはありません","No conversation matches":"一致する会話はありません","No conversations yet":"まだ会話はありません","No prompt matches":"一致するプロンプトはありません","No response.":"応答なし。","Not in a workspace":"ワークスペースなし","Not rendered yet":"まだレンダリングされていません",Open:"開く","Open conversation":"会話を開く","Open in XTM One":"XTM One で開く","Other workspaces":"その他のワークスペース",Output:"出力","Play Space Invaders":"Space Invaders をプレイ","Play Space Invaders in XTM One":"XTM One で Space Invaders をプレイ","Polishing the answer":"回答を仕上げています",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint(編集可能)",Presentation:"プレゼンテーション","Putting it together":"内容をまとめています",Quota:"クォータ","Quota reached":"クォータに達しました","Read aloud":"読み上げ","Reasoning details":"推論の詳細","Reasoning details — turn limit reached":"推論の詳細 — ターン制限に達しました","Reconnecting…":"再接続中…","Reference a conversation":"会話を参照","Remove from workspace":"ワークスペースから外す","Rename conversation":"会話の名前を変更","Rename workspace":"ワークスペースの名前を変更","Rendering {progress}%":"レンダリング中 {progress}%",Report:"レポート","Response ready":"応答準備完了","Reticulating splines":"スプラインを網状化しています",Retry:"再試行",Save:"保存","Search agents...":"エージェントを検索...","Search conversations...":"会話を検索...","Search prompts...":"プロンプトを検索...",Send:"送信","Send now":"今すぐ送信","Send when the answer ends":"回答の終了後に送信","Sending…":"送信中…","Sends when the answer ends:":"回答の終了後に送信:","Shared with you":"他のユーザーから共有","Show conversations":"会話を表示",Sidebar:"サイドバー",Skip:"スキップ","Skip response":"応答をスキップ","Sorry, an error occurred. Please try again.":"申し訳ありません。エラーが発生しました。もう一度お試しください。","Speak or tap to interrupt":"話すかタップして中断","Speaking…":"読み上げ中…","Stop dictation":"ディクテーションを停止","Stop generating":"生成を停止","Stop reading":"読み上げを停止",Stopped:"停止","Stopping…":"停止中…",Suggestions:"提案","Summarize my recent findings":"私の最近の発見を要約してください","Summarized conversation":"会話の要約","Switch to":"切り替え先","Switch to another agent":"別のエージェントに切り替える","Switch view":"ビューを切り替える","System prompt":"システムプロンプト","Tap to cancel":"タップしてキャンセル","Tell us what went wrong (optional)":"問題があった点をお聞かせください(任意)","The agent needs your approval to run a tool:":"エージェントがツールを実行するには、あなたの承認が必要です:","The agent needs your approval to run these tools:":"エージェントがこれらのツールを実行するには、あなたの承認が必要です:","The conversation could not be moved":"会話を移動できませんでした","The render did not finish":"レンダリングが完了しませんでした","The workspace could not be created":"ワークスペースを作成できませんでした","The workspace could not be deleted":"ワークスペースを削除できませんでした","The workspace could not be renamed":"ワークスペースの名前を変更できませんでした","Thinking it through":"じっくり考えています","Thinking...":"考え中...","This conversation could not be loaded.":"この会話を読み込めませんでした。","This decision could not be sent. Reload the chat and try again.":"この決定を送信できませんでした。チャットを再読み込みして、もう一度お試しください。","This message waits for the current response":"このメッセージは、現在の応答を待機します","This message will be read with your next one.":"このメッセージは次のメッセージと一緒に読まれます。","This item could not be loaded.":"この項目を読み込めませんでした。","The response could not be stopped. Try again.":"応答を停止できませんでした。もう一度お試しください。","This turn is no longer waiting for a decision.":"このターンでは、決定を待つ必要がなくなりました。","Tool definitions":"ツールの定義","Tool results":"ツールの結果","Transfer chain":"転送チェーン","Transferred from {agent}":"{agent} から転送されました","Transferring to {agent}…":"{agent} に転送中…","Turn limit reached.":"ターン制限に達しました。","Unable to connect. Please check the configuration.":"接続できません。設定を確認してください。","Unmute microphone":"マイクのミュートを解除","Untitled conversation":"タイトルのない会話",Usage:"使用状況","Usage · {period}":"使用状況 · {period}","Uses AI. Verify results.":"AIを使用しています。結果を確認してください。","Using tools…":"ツールを使用中…",Video:"動画","Voice call":"音声通話","Waiting before continuing…":"続行する前に待機中…","Waiting for one background task…":"バックグラウンドタスク 1 件を待機中…","Waiting for your approval…":"承認をお待ちしています…","Waiting for {count} background tasks…":"バックグラウンドタスク {count} 件を待機中…","Waiting to render":"レンダリング待ち","What are the latest attack patterns?":"最新の攻撃パターンにはどのようなものがありますか?","What could be improved?":"改善できる点はありますか?","Why not? The agent sees this and can adapt (optional)":"なぜですか? エージェントはこれを確認し、対応を調整できます(任意)","Workspace name":"ワークスペース名",Workspaces:"ワークスペース","Wrapping things up":"仕上げをしています",Yes:"はい","Yes, always":"はい、常に","Your answer is ready":"回答の準備が整いました",default:"デフォルト","e.g. wrong environment — use staging instead":"例:環境が間違っている — 代わりにステージング環境を使用してください","just now":"たった今","the agent":"エージェント","this month":"今月","this year":"今年",today:"今日","unknown tool":"不明なツール","{agent} has finished":"{agent} が完了しました","{counts} tokens":"{counts} トークン","{count} iterations":"{count} 回の反復","{count} scenes":"{count} シーン","{count} sections":"{count} セクション","{count} slides":"{count} スライド","{count} tool calls":"ツール呼び出し {count} 件","{count} transfers":"転送 {count} 件","{count}d ago":"{count} 日前","{count}h ago":"{count} 時間前","{count}m ago":"{count} 分前","{decided}/{total} decided":"{decided}/{total} 件が決定済み","{percent}% full":"{percent} % 使用中","{quota} (shared across all users)":"{quota}(全ユーザーで共有)","{summary} — click for details":"{summary} — クリックで詳細を表示","{tool} (+{count} more)…":"{tool}(他 {count} 件)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"エージェントの反復回数の上限に達したため、予定されたすべてのステップを完了する前に実行が停止しました。最終的な回答は、これまでに行った作業をできる限りまとめたものです。","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"「はい、常に」を選ぶと、あなたの設定として保存されます。以後、そのツールは確認なしで実行されます(誰も見ていない定期実行を含む)。取り消すまでこの設定は有効です。"}};function Q(e,t){const n=t||!e?function(e){const t=e??("undefined"!=typeof navigator?navigator.language:void 0),n=t?.toLowerCase().split(/[-_]/)[0];return n?Z[n]:void 0}(t):void 0;return t=>{const r=e?.(t);return r&&r!==t?r:n?.[t]??t}}const ee=e=>"up"===e?"positive":"negative";function te(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function ne(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function re(e,t,n){return X(e,t,n,"feedback")}async function ae(e,t,n,r,a,o){const{url:s,init:i}=function(e,t,n,r,a){const o=`${e}/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}/feedback`;return r?{url:o,init:{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...a},body:JSON.stringify({rating:r.rating,comment:ne(r.comment)})}}:{url:o,init:{method:"DELETE",credentials:"include",headers:{...a}}}}(t,n,r,a,o);try{return(await e(s,i)).ok}catch{return!1}}const oe=e=>void 0!==e&&/[\w-]/.test(e),se=/^[\w-]+$/;function ie(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const a=r[1].toLowerCase();oe(e[r.index-1])||t.includes(a)||t.push(a),r=n.exec(e)}return t}function le(e,t){if(0===e.length)return e;const n=new Set(ie(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function ce(e,t){if(0===e.length)return[];const n=[];for(const r of ie(t))for(const t of e)t.key.toLowerCase()!==r||n.some(e=>e.conversationId===t.conversationId)||n.push(t);return n.slice(0,5)}function de(e){const t=Array.isArray(e)?e:Array.isArray(e?.conversations)?e.conversations:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.id&&t.id&&"string"==typeof t.key&&se.test(t.key)&&(n.some(e=>e.id===t.id)||n.push({id:t.id,title:"string"==typeof t.title?t.title.trim():"",key:t.key,updatedAt:"string"==typeof t.updated_at?t.updated_at:void 0,isOwn:!1!==t.is_own}))}return n}function ue(e,t,n){return X(e,t,n,"conversationReferences")}const pe={query:null,items:[],failed:!1};function he(e,t){const n=e.toLowerCase();if(!n||t.key.toLowerCase().startsWith(n))return!0;const r=t.title.toLowerCase(),a=n.split(/[\s_-]+/).filter(Boolean);return a.length>0&&a.every(e=>r.includes(e))}function ge(e,t){if(t.every(t=>e.some(e=>{return r=t,(n=e).id===r.id&&n.key===r.key&&n.title===r.title&&n.isOwn===r.isOwn&&n.updatedAt===r.updatedAt;var n,r})))return e;const n=new Set(t.map(e=>e.id)),r=[...e.filter(e=>!n.has(e.id)),...t];return r.length>200?r.slice(r.length-200):r}function me(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function fe(e,t={}){const n=Array.isArray(e)?e:Array.isArray(e?.workspaces)?e.workspaces:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const n=e;"string"==typeof n.id&&n.id&&"string"==typeof n.name&&(!0!==n.is_archived&&r.push({id:n.id,name:n.name,isOwn:"boolean"==typeof n.is_own?n.is_own:!!t.userId&&n.user_id===t.userId,isDefault:!0===n.is_default,canManage:!0===n.can_manage}))}return r}function ve(e){const t=e=>e.isDefault&&e.isOwn;return[...e].sort((e,n)=>t(e)!==t(n)?t(e)?-1:1:e.name.localeCompare(n.name))}function we(e,t,n,r,a){return!!a||(!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e))}function ye(e,t,n){return!n&&!(t&&e.conversations.some(e=>e.conversationId===t))}const be=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&t.length<=500?t:null};async function xe(e){try{return function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;return be(e.message)??be(e.detail)}return be(t)}(await e.json())}catch{return null}}function ke(e){return e?JSON.stringify(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0)):""}function Ne(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}const Ce=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function Se(e){const t=e.context_tokens,n=e.context_window;if("number"!=typeof t||"number"!=typeof n)return;if(!Number.isFinite(t)||!Number.isFinite(n)||n<=0||t<0)return;const r=function(e){if(!e||"object"!=typeof e)return;const t=e,n={};let r=!1;for(const[e,a]of Ce){const o=t[e];"number"==typeof o&&Number.isFinite(o)&&o>0&&(n[a]=o,r=!0)}return r?n:void 0}(e.context_breakdown);return r?{used:t,limit:n,breakdown:r}:{used:t,limit:n}}function Ie(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.file_id;"string"==typeof r&&r&&t.push({fileId:r,filename:"string"==typeof e.filename?e.filename:"file",type:"string"==typeof e.type?e.type:void 0,size:"number"==typeof e.size?e.size:void 0,contentType:"string"==typeof e.content_type?e.content_type:void 0,fileTag:"working_file"===e.file_tag?"working_file":"download_file"})}return t.length>0?t:void 0}const Te=["presentation","report","video"],Ae=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function _e(e){if(!e||"object"!=typeof e)return;const t=e,n=Te.find(e=>e===t.kind);return n&&"string"==typeof t.id&&t.id?{kind:n,id:t.id,title:"string"==typeof t.title?t.title:"",url:"string"==typeof t.url&&t.url?t.url:void 0,slideRef:"string"==typeof t.slide_ref&&t.slide_ref?t.slide_ref:void 0,slideCount:Ae(t.slide_count),sectionCount:Ae(t.section_count),sceneCount:Ae(t.scene_count),durationMs:Ae(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:Ae(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function Ee(e){if(!Array.isArray(e))return;const t=e.map(_e).filter(e=>!!e);return t.length>0?t:void 0}function Me(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.name&&e.name&&t.push({name:e.name,input:"string"==typeof e.input?e.input:void 0,output:"string"==typeof e.output?e.output:void 0,success:"boolean"!=typeof e.success||e.success})}return t.length>0?t:void 0}function Le(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.conversation_id&&e.conversation_id&&(t.some(t=>t.conversationId===e.conversation_id)||t.push({conversationId:e.conversation_id,title:"string"==typeof e.title?e.title.trim():"",key:"string"==typeof e.key?e.key:""}))}return t.length>0?t:void 0}function Re(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.agent_name&&e.agent_name&&t.push({agentId:"string"==typeof e.agent_id?e.agent_id:"",agentName:e.agent_name})}return t.length>0?t:void 0}function $e(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.tool_call_id;if("string"!=typeof r||!r)continue;const a=e.arguments,o=e.input_schema;t.push({toolCallId:r,toolName:"string"==typeof e.tool_name&&e.tool_name?e.tool_name:"",toolDescription:"string"==typeof e.tool_description?e.tool_description:void 0,arguments:a&&"object"==typeof a&&!Array.isArray(a)?a:{},inputSchema:o&&"object"==typeof o&&!Array.isArray(o)?o:void 0,source:"string"==typeof e.source?e.source:void 0})}return t.length>0?t:void 0}const De=e=>"string"==typeof e&&e?e:void 0;function je(e){if("string"==typeof e)return e?{agentName:e}:void 0;if(!e||"object"!=typeof e)return;const t=e,n={agentId:De(t.agent_id),agentName:De(t.agent_name)??De(t.name),agentIcon:De(t.agent_icon)};return n.agentId||n.agentName?Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)):void 0}function ze(e,t){const n=e.type;if("error"===n||"cancelled"===n){const t=De(e.message_id),r=!0===e.provisional||void 0,a={...t?{messageId:t,raw:{...e}}:{},...r?{provisional:r}:{}};return"error"===n?{action:"error",content:e.content||"",...a}:{action:"cancelled",...a}}if("session_expired"===n)return{action:"session_ended",reason:De(e.reason)};if("approval_resolved"===n)return{action:"approval_resolved"};if("folded_into_active_turn"===n)return{action:"folded",turnId:De(e.turn_id)};if("conversation_title"===n){const t=De(e.title);return t?{action:"conversation_title",conversationId:De(e.conversation_id),title:t}:{action:"noop"}}if("user_message"===n){const[t]=Ue([e.message]);return t&&"user"===t.role?{action:"user_message",message:{...t,id:Oe(t.serverId)}}:{action:"noop"}}if("thinking"===n)return{action:"status",status:"thinking",resumed:!0===e.resumed||void 0,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};if("status"===n){const n=e.status;if("tool_done"===n||"wind_down"===n)return{action:"noop"};if("streaming"===n)return{action:"status",status:"streaming"};if("thinking_text"===n)return{action:"status",status:"thinking_text",thinkingContent:e.content};if("tool_start"===n)return t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:e.tools};if("tool_progress"===n&&"page_action_required"===e.event){if("string"!=typeof e.action_id||!e.action_id)return{action:"noop"};const t=function(e){if(!e||"object"!=typeof e)return{type:"unsupported",requested:"malformed"};const t=e,n=e=>"string"==typeof e&&e.length>0;return"snapshot"===t.type?{type:"snapshot"}:"navigate"===t.type&&n(t.path)?{type:"navigate",path:t.path}:"click"===t.type&&n(t.ref)?{type:"click",ref:t.ref}:"open"===t.type&&n(t.ref)?{type:"open",ref:t.ref}:"type"===t.type&&n(t.ref)&&"string"==typeof t.text?{type:"type",ref:t.ref,text:t.text}:{type:"unsupported",requested:"string"==typeof t.type?t.type.slice(0,64):"unknown"}}(e.action);return{action:"page_action_required",actionId:e.action_id,pageAction:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}}if("wait_start"===n)return{action:"status",status:"wait_start",waitSeconds:"number"==typeof e.seconds&&e.seconds>0?e.seconds:void 0,waitReason:De(e.reason)};if("tool_heartbeat"===n)return{action:"status",status:"tool_heartbeat",tools:e.tools,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};const r=Se(e);return"thinking"===n&&t.hasUsedTools?{action:"status",status:"analyzing",contextUsage:r}:{action:"status",status:n,tools:e.tools,contextUsage:r}}if("approval_required"===n){const t=$e(e.proposals);return t?{action:"approval_required",proposals:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}:{action:"noop"}}return"stream"===n?{action:"stream",content:e.content}:"done"===n?{action:"done",content:e.content,conversationId:e.conversation_id,toolNames:e.tool_names,toolCallCount:e.tool_call_count,iterations:e.iterations,transferAgentId:e.transfer_agent_id,transferAgentName:e.transfer_agent_name,attachments:Ie(e.attachments),artifacts:Ee(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:Me(e.tool_call_trace),transferChain:Re(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:Se(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0,intermediate:!0===e.intermediate||void 0,answeredBy:je(e.answered_by),mentionFailed:!0===e.mention_failed||void 0,raw:{...e}}:{action:"noop"}}function Oe(e,t=Ne()){return e?`msg-${e}`:t}function Pe(e){if(!e||"object"!=typeof e)return;const{rating:t,comment:n}=e;return"positive"===t||"negative"===t?{rating:t,comment:"string"==typeof n&&n.trim()?n:null}:void 0}function Ue(e){if(!Array.isArray(e))return[];const t=[];return e.forEach((e,n)=>{if(!e||"object"!=typeof e)return;const r=e;if("user"!==r.role&&"assistant"!==r.role)return;const a="string"==typeof r.created_at?new Date(r.created_at):null,o=a&&!Number.isNaN(a.getTime())?a:null,s="assistant"===r.role?je(r.answered_by):void 0,i="string"==typeof r.id&&r.id?r.id:void 0;t.push({id:Oe(i,`restored-${n}`),serverId:i,role:r.role,content:"string"==typeof r.content?r.content:"",timestamp:o??new Date,timestampUnknown:!o||void 0,feedback:"assistant"===r.role?Pe(r.feedback):void 0,agentName:s?.agentName??("string"==typeof r.agent_name?r.agent_name:void 0),answeredBy:s,mentionFailed:"assistant"===r.role&&!0===r.mention_failed||void 0,attachments:Ie(r.attachments),artifacts:"assistant"===r.role?Ee(r.artifacts):void 0,conversationRefs:"user"===r.role?Le(r.conversation_refs):void 0,toolNames:Array.isArray(r.tool_names)?r.tool_names:void 0,toolCallCount:"number"==typeof r.tool_call_count?r.tool_call_count:void 0,iterations:"number"==typeof r.iterations?r.iterations:void 0,reasoning:"string"==typeof r.reasoning?r.reasoning:void 0,toolCallTrace:Me(r.tool_call_trace),transferChain:Re(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0,raw:{...r}})}),t}function He(e,t){const n=e.event;if("nextAgentFlow"===n){const n=e.data,r=n?.nodeId;return"INPROGRESS"===n?.status&&r&&(t.activeNodeId=r),{action:"noop"}}if("start"===n)return{action:"noop"};if("token"===n){return{action:"stream",content:(e.data??"").replace(/<br\s*\/?>/g,"\n")}}if("agentReasoning"===n){const n=e.data,r=n?.usedTools;return r?.length?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:r.map(e=>e.tool)}):t.hasUsedTools?{action:"status",status:"analyzing"}:{action:"status",status:"thinking"}}if("usedTools"===n){t.hasUsedTools=!0;const n=e.data;return{action:"status",status:"tool_start",tools:Array.isArray(n)?n.map(e=>e.tool):[]}}if("metadata"===n){const t=e.data,n=t?.chatId;return n?{action:"set_chat_id",chatId:n}:{action:"noop"}}return"error"===n?{action:"error",content:e.data||""}:"end"===n?{action:"done",content:""}:{action:"noop"}}function We(e,t){const n=e.type;if("RUN_STARTED"===n)return{action:"status",status:"thinking"};if("RUN_FINISHED"===n)return{action:"done",content:""};if("RUN_ERROR"===n)return{action:"error",content:"string"==typeof e.message?e.message:""};if("STEP_STARTED"===n){return{action:"status",status:e.stepName||"thinking"}}if("STEP_FINISHED"===n)return{action:"noop"};if("TEXT_MESSAGE_START"===n)return{action:"status",status:"streaming"};if("TEXT_MESSAGE_CONTENT"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TEXT_MESSAGE_END"===n)return{action:"noop"};if("TEXT_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TOOL_CALL_START"===n){t.hasUsedTools=!0;const n=e.toolCallName;return{action:"status",status:"tool_start",tools:n?[n]:[]}}if("TOOL_CALL_ARGS"===n)return{action:"noop"};if("TOOL_CALL_END"===n)return{action:"status",status:"analyzing"};if("TOOL_CALL_RESULT"===n)return{action:"noop"};if("TOOL_CALL_CHUNK"===n){const n=e.toolCallName;return n?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:[n]}):{action:"noop"}}if("REASONING_START"===n||"REASONING_MESSAGE_START"===n)return{action:"status",status:"thinking"};if("REASONING_MESSAGE_CONTENT"===n||"REASONING_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"status",status:"thinking_text",thinkingContent:t}:{action:"status",status:"thinking"}}return{action:"noop"}}function qe(){let e=0,t=null,n=null;return{get generation(){return e},get pending(){return t},run(r){if(t)return t;const a=e,o=new AbortController;n=o;const s=r(()=>a===e,o.signal).catch(()=>null);return t=s,s.finally(()=>{t===s&&(t=null),n===o&&(n=null)}),s},abandon(){e+=1,t=null,n?.abort(),n=null}}}function Be(e,t){return null!==e&&"function"==typeof t}function Fe(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const Ve=(e,t)=>{const n=t??Fe();if(!e||!n)return null;try{const t=new URL(e,n);if("http:"!==t.protocol&&"https:"!==t.protocol)return null;if(t.origin!==new URL(n).origin)return null;const r=`${t.pathname}${t.search}${t.hash}`||"/";return r.startsWith("//")?null:r}catch{return null}};function Ke(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const Ge=/^(current-password|new-password|one-time-code|cc-)/;function Je(e){const t=e.ownerDocument.defaultView,n={bubbles:!0,cancelable:!0,view:t??void 0,pointerType:"mouse"},r=t?.PointerEvent??t?.MouseEvent??MouseEvent,a=t?.MouseEvent??MouseEvent;e.dispatchEvent(new r("pointerover",n)),e.dispatchEvent(new r("pointerenter",{...n,bubbles:!1})),e.dispatchEvent(new a("mouseover",n)),e.dispatchEvent(new a("mouseenter",{...n,bubbles:!1}))}function Ye(e,t,n){const r=e=>e.preventDefault();for(const n of t)e.addEventListener(n,r,!0);try{n()}finally{for(const n of t)e.removeEventListener(n,r,!0)}}function Xe(e,t,n){if(e.matches?.("a[href]")){const r=e.getAttribute("target");if(r&&"_self"!==r)return{ok:!1,error:"opens_new_tab"};const a=e.getAttribute("href")??"";if(a&&!a.startsWith("#")){const e=Ve(a,n);if(!e)return{ok:!1,error:"external_link"};if(t)return t(e),{ok:!0}}}e.focus?.();const r=e.closest?.("a[href]"),a=!!r&&!(r.getAttribute("href")??"").startsWith("#"),o=a?["submit","click"]:["submit"],s=e.matches?.('input[type="checkbox"], input[type="radio"]')??!1,i=e.checked;if(Ye(e.ownerDocument,o,()=>e.click()),s&&a&&e.checked===i){const t=e;t.checked="radio"===t.type||!i,t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("input",{bubbles:!0})),t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("change",{bubbles:!0}))}return{ok:!0}}function Ze(e){const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!1}for(let t=e;t;t=t.parentElement){if(t.hidden||t.hasAttribute("inert"))return!1;if("true"===t.getAttribute("aria-hidden"))return!1;const e=t.ownerDocument.defaultView?.getComputedStyle(t);if("none"===e?.display||"hidden"===e?.visibility)return!1}return!0}function Qe(e){const t=e.getAttribute("aria-expanded");if("true"===t)return!0;if("false"===t)return!1;const n=e.getAttribute("aria-controls");if(!n)return!1;const r=e.ownerDocument.getElementById(n);return!!r&&Ze(r)}async function et(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(Qe(e))return{ok:!0};if(r){if(Je(e),await(a=()=>Qe(e),o=300,new Promise(e=>{const t=Date.now(),n=()=>a()?e(!0):Date.now()-t>=o?e(!1):void setTimeout(n,30);n()})))return{ok:!0}}else if(await function(e,t,n=300){const r=e.defaultView,a=r?.MutationObserver??globalThis.MutationObserver;return a?new Promise(r=>{const o=new a(e=>{e.some(e=>e.addedNodes.length>0&&!Ke(e.target)&&Array.from(e.addedNodes).some(e=>!Ke(e)))&&(o.disconnect(),clearTimeout(s),r(!0))});o.observe(e.body??e.documentElement,{subtree:!0,childList:!0}),t();const s=setTimeout(()=>{o.disconnect(),r(!1)},n)}):(t(),Promise.resolve(!0))}(e.ownerDocument,()=>Je(e)))return{ok:!0};var a,o;return n?.aborted?{ok:!1,error:"aborted"}:Xe(e,void 0,t)}const tt=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function nt(e,t,n,r,a){try{if(a?.aborted)return{ok:!1,error:"aborted"};if("snapshot"===e.type)return{ok:!0};if("unsupported"===e.type)return{ok:!1,error:`unsupported_action: ${e.requested}`.slice(0,500)};if("navigate"===e.type){if(!n)return{ok:!1,error:"navigation_unavailable"};const t=Ve(e.path,Fe(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const o=t.get(e.ref);return o&&o.isConnected?Ze(o)?function(e){if(e.hasAttribute("disabled"))return!0;if("true"===e.getAttribute("aria-disabled"))return!0;if(e.matches?.(":disabled"))return!0;if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(o)?{ok:!1,error:"disabled"}:o.matches?.('input[type="file"]')?{ok:!1,error:"opens_file_dialog"}:"open"===e.type?await et(o,Fe(r??o.ownerDocument),a):"click"===e.type?Xe(o,n,Fe(r??o.ownerDocument)):function(e){return e.matches?.('textarea, [contenteditable="true"], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="number"]')??!1}(o)?function(e){return!0===e.readOnly||"true"===e.getAttribute("aria-readonly")}(o)?{ok:!1,error:"read_only"}:function(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>Ge.test(e))}(o)?{ok:!1,error:"secret_field"}:(o.focus?.(),function(e,t){const n=e.ownerDocument.defaultView;if(n&&(e instanceof n.HTMLInputElement||e instanceof n.HTMLTextAreaElement)){const r=e instanceof n.HTMLInputElement?n.HTMLInputElement.prototype:n.HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(r,"value")?.set?.call(e,t)}else e.textContent=t;e.dispatchEvent(new(n?.Event??Event)("input",{bubbles:!0})),e.dispatchEvent(new(n?.Event??Event)("change",{bubbles:!0}))}(o,e.text),function(e){if("searchbox"===e.getAttribute("role"))return!0;if("search"===e.type)return!0;if(null!==e.closest('[role="search"]'))return!0;if(!["name","id","placeholder","aria-label","title"].some(t=>tt.test(e.getAttribute(t)??"")))return!1;const t=e.form;return!t||1===t.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]), select, textarea, [contenteditable="true"]').length}(o)&&function(e){const t=e.ownerDocument.defaultView,n=t?.KeyboardEvent??KeyboardEvent,r={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:!0,cancelable:!0},a=new n("keydown",r);e.dispatchEvent(a),e.dispatchEvent(new n("keyup",r));const o=e.form;o&&!a.defaultPrevented&&Ye(e.ownerDocument,["submit"],()=>o.requestSubmit?.())}(o),{ok:!0}):{ok:!1,error:"not_a_text_field"}:{ok:!1,error:"not_visible"}:{ok:!1,error:"unknown_ref"}}catch(e){return{ok:!1,error:`failed: ${e instanceof Error?e.message:String(e)}`.slice(0,500)}}}const rt="[truncated]",at=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function ot(e){if("select"===e.tagName.toLowerCase())return!1;for(const t of Array.from(e.querySelectorAll('a[href], button, summary, select, textarea, input, [contenteditable="true"], [role]')))if(st(t))return!0;return!1}function st(e){const t=e.getAttribute("role");if(t&&at.has(t))return t;const n=e.tagName.toLowerCase();if("a"===n&&e.hasAttribute("href"))return"link";if("button"===n||"summary"===n)return"button";if("select"===n)return"combobox";if("textarea"===n)return"textbox";if("input"===n){const t=(e.getAttribute("type")||"text").toLowerCase();return"hidden"===t?null:["button","submit","reset","image"].includes(t)?"button":"checkbox"===t||"radio"===t?t:"search"===t?"searchbox":"file"===t?"button":"textbox"}return"true"===e.getAttribute("contenteditable")?"textbox":null}function it(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function lt(e){const t=e.ownerDocument.defaultView;let n="";for(const r of Array.from(e.childNodes))if(3===r.nodeType)n+=r.textContent??"";else if(1===r.nodeType){if(wt(r)||mt(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?lt(r):` ${lt(r)} `}return n}function ct(e){return(e??"").replace(/\s+/g," ").trim()}const dt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function ut(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=ct(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const a=ct(e.getAttribute("aria-label"));if(a)return a;const o=e.getAttribute("id"),s=o&&Array.from(n.getElementsByTagName("label")).find(e=>e.htmlFor===o)||e.closest("label");if(s){const e=ct(Array.from(s.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||ct(s.textContent))return e||ct(s.textContent)}const i=e.tagName.toLowerCase(),l=(e.getAttribute("type")||"").toLowerCase();if("input"===i&&["submit","reset","button"].includes(l)){const t=ct(e.getAttribute("value"));if(t)return t;if("button"!==l)return"submit"===l?"Submit":"Reset"}const c=ct(e.getAttribute("alt"))||ct(e.querySelector("img[alt]")?.getAttribute("alt"));if(c)return c;const d=mt(e)?"":ct(lt(e));if(dt.has(t)&&d)return d;const u=ct(e.getAttribute("placeholder"));if(u)return u;const p=ct(e.getAttribute("title"));return p||d}function pt(e){return JSON.stringify(e.slice(0,80))}function ht(e){const t=[];(e.hasAttribute("disabled")||function(e){if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(e)||"true"===e.getAttribute("aria-disabled"))&&t.push("disabled"),"true"===e.getAttribute("aria-selected")&&t.push("selected"),(e.checked||"true"===e.getAttribute("aria-checked"))&&t.push("checked"),"true"===e.getAttribute("aria-expanded")?t.push("expanded"):"false"!==(e.getAttribute("aria-haspopup")??"false")?t.push("menu"):"false"===e.getAttribute("aria-expanded")&&t.push("collapsed"),"true"===e.getAttribute("aria-pressed")&&t.push("pressed");const n=e.getAttribute("aria-current");return n&&"false"!==n&&t.push("current"),t}const gt=/^(current-password|new-password|one-time-code|cc-)/;function mt(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>gt.test(e))}function ft(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(mt(e))return null;const n="value"in e?String(e.value??""):ct(lt(e));return n||null}function vt(e){const t=e.getAttribute("href"),n=e.ownerDocument.defaultView?.location;if(!t||!n)return"";try{const e=new URL(t,n.href);return e.origin===n.origin?` -> ${e.pathname}${e.search}`:""}catch{return""}}function wt(e){if(e.classList.contains("filigran-chatbot"))return!0;const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!0}if(e.hidden||e.hasAttribute("inert"))return!0;if("true"===e.getAttribute("aria-hidden"))return!0;const n=e.ownerDocument.defaultView?.getComputedStyle(e);return"none"===n?.display||"hidden"===n?.visibility}const yt="filigranChatConversationId",bt="filigranChatLegacyChatId",xt="filigranChatAgentSlug",kt="filigranChatSidebarWidth",Nt="filigran-chat-collapsed-workspaces",Ct="filigranChatDraft:",St="filigranChatDraftRefs:";function It(e,t){return e?`${e}:${t}`:t}function Tt(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch{return null}}function At(e,t){try{return Tt(e)?.getItem(t)??null}catch{return null}}function _t(e,t,n){try{const r=Tt(e);if(!r)return;n?r.setItem(t,n):r.removeItem(t)}catch{}}class Et extends Error{constructor(){super("the event stream fell silent"),this.name="SseStreamSilentError"}}async function Mt(e,t,{idleTimeoutMs:n}={}){const r=e.getReader(),a=new TextDecoder;let o="",s=null,i=!1,l=!1,c=null;const d=()=>{null!==c&&clearTimeout(c),c=null;const e="function"==typeof n?n():n;i&&void 0!==e&&(c=setTimeout(()=>{l=!0,r.cancel().catch(()=>{})},e))},u=e=>{const r=e.replace(/\r$/,"");if(r.startsWith(":")){const e=Date.now();null===s&&(s=e);const t="function"==typeof n?n():n;void 0!==t&&e-s>=t/3&&(i=!0)}if(!r.startsWith("data:"))return!0;const a=r.startsWith("data: ")?r.slice(6):r.slice(5);let o;try{o=JSON.parse(a)}catch{return!0}return!(o&&"object"==typeof o&&!Array.isArray(o))||!1!==t(o)};try{for(;;){const{done:e,value:t}=await r.read();if(l)throw new Et;if(e)break;o+=a.decode(t,{stream:!0});const n=o.split("\n");o=n.pop()??"";for(const e of n)if(!u(e))return void await r.cancel().catch(()=>{});d()}o+=a.decode(),o&&u(o)}finally{null!==c&&clearTimeout(c),r.releaseLock()}}function Lt(e,...t){if(e)try{return e(...t)}catch(e){return void console.error("A chat panel host callback threw",e)}}const Rt=e=>e.some(e=>"error"===e.uploadStatus);function $t(e){if(e.slug&&/^[\w-]+$/.test(e.slug))return e.slug;return e.name.toLowerCase().replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")||null}function Dt(e,t){const n=[];for(const r of ie(t))for(const t of e)t.key.toLowerCase()!==r||n.includes(t.agentId)||n.push(t.agentId);return n}const jt=r({fetch:(e,t)=>globalThis.fetch(e,t),sessionEnded:()=>{}}),zt=jt.Provider;function Ot(){return a(jt).fetch}const Pt=(e,t)=>It(e,`${Ct}${t??"new"}`),Ut=(e,t)=>It(e,`${St}${t??"new"}`);function Ht(e,t){try{const n=JSON.parse(At("session",Ut(e,t))??"[]");return Array.isArray(n)?n.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.conversationId&&"string"==typeof e.key&&"string"==typeof e.title):[]}catch{return[]}}function Wt(e,t,n,r){_t("session",Pt(e,t),n),_t("session",Ut(e,t),r.length>0?JSON.stringify(r):null)}function qt(e,t){const n=At("session",Pt(e,t))??"";return{text:n,refs:le(Ht(e,t),n)}}const Bt=9e5,Ft=Bt,Vt=new Set(["wait_status","tool_progress","consult_progress"]),Kt=new Set(["status","stream","done","approval_required","error","cancelled"]),Gt=new Set(["mentioned_agent_ids","content","conversation_id","agent_slug","supports_tool_approval","supports_page_actions","supports_artifacts","referenced_conversation_ids","file_ids","context"]);function Jt(e,t,n,r){return{...e,content:n,timestamp:r,toolNames:t.toolNames,toolCallCount:t.toolCallCount,iterations:t.iterations,attachments:t.attachments,artifacts:t.artifacts,reasoning:t.reasoning,toolCallTrace:t.toolCallTrace,transferChain:t.transferChain,isTruncated:t.isTruncated,agentName:t.answeredBy?.agentName??e.agentName,answeredBy:t.answeredBy,mentionFailed:t.mentionFailed,serverId:t.messageId??e.serverId,raw:t.raw??e.raw}}const Yt=["toolNames","toolCallCount","iterations","attachments","artifacts","reasoning","toolCallTrace","transferChain","isTruncated","agentName","answeredBy","mentionFailed","feedback"],Xt=Symbol("sentText");function Zt(e,t){return t===e.content?e:{...e,[Xt]:t}}function Qt(e){return e[Xt]??e.content}const en=e=>`${e.role}\0${"user"===e.role?Qt(e):e.content}`,tn=e=>`${e.role}\0${e.content}`;function nn(e,t){const n={...e,serverId:t.serverId??e.serverId,raw:t.raw??e.raw};if("assistant"!==e.role)return n;const r=n;for(const e of Yt)void 0!==t[e]&&(r[e]=t[e]);return n}function rn(e,t,n){const r=null===n?-1:e.findIndex(e=>e.id===n);return r<0?[...e,t]:[...e.slice(0,r),t,...e.slice(r)]}const an=(e,t)=>[e,t].filter(Boolean).join("\n\n"),on=(e,t)=>void 0!==e.displayText||void 0!==t.displayText?an(e.displayText??e.text,t.displayText??t.text):void 0;function sn(e,t){const n=new Set(e.refs.map(e=>e.conversationId)),r=new Set(e.mentions.map(e=>e.agentId));return{text:an(e.text,t.text),draft:an(e.draft,t.draft),files:[...e.files,...t.files],refs:[...e.refs,...t.refs.filter(e=>!n.has(e.conversationId))],mentions:[...e.mentions,...t.mentions.filter(e=>!r.has(e.agentId))],extras:e.extras||t.extras?{...e.extras,...t.extras}:void 0,displayText:on(e,t)}}const ln={text:"",draft:"",files:[],refs:[],mentions:[]};function cn(e){return{...e.reduce(sn,ln),parts:e}}function dn(e,t){return cn([...e?.parts??[],t])}function un(e){for(const t of e)Lt(t.onNotSent)}function pn(e,t,n){if(!1===t)return null;const r=t&&"object"==typeof t?t:void 0,a=("string"==typeof r?.text?r.text:e).trim(),o="string"==typeof r?.displayText?r.displayText.trim():"",s="string"==typeof n?n.trim():"";return{text:a,displayText:o||s||a,extras:r?.extras}}function hn(e){return"error"===e.action||"cancelled"===e.action||"done"===e.action&&!e.intermediate?e:null}function gn(e){return("error"===e.action||"cancelled"===e.action)&&!!e.provisional}function mn(e){const t=Lt(e);return t&&"object"==typeof t?t:{}}const fn=52428800;function vn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t].serverId;if(n)return n}return null}function wn(e,t){const n=null===t?0:e.findIndex(e=>e.serverId===t)+1;return null!==t&&0===n?"stopped":e.slice(n).some(e=>"assistant"===e.role)?"answered":"stopped"}function yn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:r,requestHeaders:a,pageContext:c,onRelativeLinkClick:d,t:u,maxFileCount:p=10,maxTotalSize:h=52428800,storageKeyPrefix:g,controlledConversationId:m,onConversationIdChange:f,getRequestExtras:v,onStreamEvent:w,onSessionEnded:y,onConversationTitle:b,historySettledFor:x=null,steerAttachments:k=!1,holdSends:N=!1,agentMentionsEnabled:C=!1,onBeforeSend:S,onHeldSendSettled:I}){const T=Ot(),A="legacy"===n,[_,E]=o([]),[M,L]=o(!1),[R,$]=o(null),[D,j]=o(null),z=void 0!==m,O=It(g,yt),P=It(g,bt),[U,H]=o(()=>z?m??null:At("local",O)),[W]=o(()=>qt(g,U)),[q,B]=o(W.text),[F,V]=o(W.refs),[K,G]=o([]),[J,Y]=o([]),[Z,Q]=o(null),[ee,te]=o(null),[ne,re]=o(null),[ae,oe]=o(!1),[se,de]=o(null),[pe,he]=o(!1),[ge,me]=o(0),[fe,ve]=o(0),[we,ye]=o(()=>At("local",P)),be=s(!1),Ce=s(null),Se=s(null),Ie=s(null),Te=s(!1),Ae=s(null),_e=s(null),Ee=s(null),Me=s(null),Le=s(null),Re=s(!1),[De,je]=o(null),Pe=s(De);Pe.current=De;const[Ue,Fe]=o(null),Ve=s(!1),Ge=s(new Map),Je=s(null),[Ye,Xe]=o(!1),Ze=s(null),Qe=s(!1),et=s("off"),tt=s(0),at=s(null),dt=s(null),gt=s(null),mt=s(null),[xt,kt]=o(!1),Nt=e=>{const t=mt.current?.readBack;t&&e!==mt.current&&window.clearTimeout(t.timer),mt.current=e,kt(null!==e)},Ct=s(_);Ct.current=_;const St=s(0),[Tt,Et]=o(()=>Ne()),$t=s(null),jt=s(null),zt=s(!1),Pt=s(0),Ut=s(null),Ht=s(null),Yt=s(null),Xt=()=>{null!==$t.current&&window.clearTimeout($t.current),$t.current=null,jt.current=null,zt.current=!1,Yt.current&&window.clearTimeout(Yt.current.timer),Yt.current=null;const e=Ht.current;Ht.current=null,null!==e&&E(t=>t.filter(t=>t.id!==e||t.content))},an=e=>{Je.current&&window.clearTimeout(Je.current.timer);const t={timer:0,relayed:e};return t.timer=window.setTimeout(()=>on(t),5e3),Je.current=t,Xe(!0),t},on=e=>{const t=Je.current;!t||e&&e!==t||(window.clearTimeout(t.timer),Je.current=null,Xe(!1))},sn=()=>{Je.current?.relayed&&on()},ln=s(v);ln.current=v;const yn=s(w);yn.current=w;const bn=s(y);bn.current=y;const xn=s(b);xn.current=b;const kn=s(S);kn.current=S;const Nn=s(I);Nn.current=I;const Cn=s(U),Sn=s(M);Sn.current=M;const In=e=>{Sn.current&&$(e),Sn.current=!1,L(!1),Ve.current||Fe(null)},Tn=s(c);Tn.current=c;const An=s(new Map),_n=s(d);_n.current=d;const En=s(a);En.current=a;const Mn=s(null),Ln=s(!1),Rn=s(null),$n=s(0),[Dn]=o(qe),jn=s(null),[zn,On]=o(null),Pn=s(new AbortController),Un=Number.isFinite(p)&&p>0?Math.floor(p):10,Hn=Number.isFinite(h)&&h>0?h:fn;i(()=>{V(e=>le(e,q)),G(e=>function(e,t){if(0===e.length)return e;const n=new Set(ie(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}(e,q))},[q]);const Wn=l(e=>{G(t=>{return r=e,(n=t).some(e=>e.agentId===r.agentId)?n:[...n,r];var n,r})},[]),qn=l(e=>{V(t=>{return r=e,(n=t).some(e=>e.conversationId===r.conversationId)?n:[...n,r];var n,r})},[]),Bn=({draft:e,files:t,refs:n,mentions:r},{before:a})=>{e&&B(t=>t?a?`${e}\n${t}`:`${t}\n\n${e}`:e),t.length>0&&Y(e=>a?[...t,...e]:[...e,...t]),n.length>0&&V(e=>{const t=n.filter(t=>!e.some(e=>e.conversationId===t.conversationId));return a?[...t,...e]:[...e,...t]}),r.length>0&&G(e=>{const t=r.filter(t=>!e.some(e=>e.agentId===t.agentId));return a?[...t,...e]:[...e,...t]})},Fn=()=>A||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,Vn=()=>X(e,t,n,"approve"),Kn=s(Vn);Kn.current=Vn;const Gn=async e=>{const t=cr(e);if(!t)return null;try{const e=await T(t,{headers:{...a??{}}});if(!e.ok)return null;const n=await e.json();return{proposals:$e(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Jn=l(()=>{be.current=!1,St.current+=1,me(St.current)},[]),Yn=()=>{if(null===jt.current)return;const e=vn(Ct.current);if(Xt(),!pr())return void Sr("stopped");Jn();const t=window.setTimeout(()=>{Yt.current?.timer===t&&(Yt.current=null,Sr("stopped"))},1e4);Yt.current={from:St.current,shownUpTo:e,timer:t}},Xn=s(Yn);Xn.current=Yn;const Zn=()=>{null!==$t.current&&window.clearTimeout($t.current),zt.current=!1,$t.current=window.setTimeout(()=>{$t.current=null,_e.current||Xn.current()},Math.max(0,Pt.current-Date.now()))},Qn=()=>{null===jt.current||_e.current||zt.current||(zt.current=!0,null!==$t.current&&window.clearTimeout($t.current),$t.current=window.setTimeout(()=>{$t.current=null,_e.current||Xn.current()},5e3))},er=s(Qn);er.current=Qn;const tr=()=>{null!==jt.current&&!_e.current&&zt.current&&Zn()},nr=s(tr);nr.current=tr;const rr=()=>A||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,ar=()=>X(e,t,n,"cancel"),or=()=>X(e,t,n,"skipWait"),sr=X(e,t,n,"events"),ir=!!sr,lr=X(e,t,n,"pendingApprovals"),cr=e=>lr?`${lr}/${encodeURIComponent(e)}/pending-approvals`:null,dr=()=>ir?{"X-Chat-Client-Id":Tt}:{},ur=(e,t,n)=>T(e,{method:"POST",headers:{"Content-Type":"application/json",...En.current??{},...dr()},body:JSON.stringify({conversation_id:t,...n})}),pr=()=>A||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`,hr=s(f);hr.current=f;const gr=l((e,{notify:t=!0}={})=>{const n=Cn.current!==e;Cn.current=e,H(e),z||_t("local",O,e),n&&t&&hr.current?.(e)},[z,O]),mr=async e=>{if(Cn.current)return Cn.current;if(Dn.pending)return Dn.pending;const t=pr();return t?Dn.run(async(n,r)=>{const o=jn.current,s=await T(t,{method:"POST",headers:{"Content-Type":"application/json",...a??{}},body:JSON.stringify(o?{agent_slug:e,workspace_id:o}:{agent_slug:e}),signal:r});if(!s.ok||!n())return null;const i=await s.json();if(!n())return null;const l=i?.conversation_id??null;return l&&(be.current=!0,gr(l),jn.current=null,On(null)),l}):null},fr=async(e,t,n)=>{const r=rr(),o=new FormData;o.append("conversation_id",t),o.append("file",e,e.name);const s=a?Object.fromEntries(Object.entries(a).filter(([e])=>"content-type"!==e.toLowerCase())):void 0,i=await T(r,{method:"POST",headers:s,body:o,signal:n});if(!i.ok)throw new Error(`File upload failed: ${i.status}`);const l=(await i.json()).file_ids??[];if(0===l.length)throw new Error("No file_id returned");return l[0]},vr=e=>{if(!e||0===e.length||!rr())return;const t=Array.from(e).map(e=>({file:e,tempId:Ne()}));let n=[];Y(e=>{const r=e.length,a=e.reduce((e,t)=>e+t.size,0),o=Un-r;if(o<=0)return e;let s=Hn-a;const i=[];for(const e of t.slice(0,o))e.file.size<=s&&(i.push(e),s-=e.file.size);if(0===i.length)return e;n=i;const l=i.map(({file:e,tempId:t})=>({name:e.name,type:e.type,size:e.size,rawFile:e,uploadStatus:"pending",fileId:t}));return[...e,...l]}),setTimeout(()=>{const e=Pn.current.signal;for(const{file:t,tempId:a}of n)(async()=>{try{const n=await mr(r);if(!n)return void Y(e=>e.map(e=>e.fileId===a?{...e,uploadStatus:"error"}:e));const o=await fr(t,n,e);Y(e=>e.map(e=>e.fileId===a?{...e,fileId:o,uploadStatus:"done"}:e))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;Y(e=>e.map(e=>e.fileId===a?{...e,uploadStatus:"error"}:e))}})()},0)},wr=async(e,t,n)=>{const r=Kn.current(),a=n??Cn.current;if(!r||!a||"undefined"==typeof document)return;const o=Se.current?.signal,s=async t=>{try{await T(r,{method:"POST",headers:{"Content-Type":"application/json",...En.current??{},...dr()},body:JSON.stringify({conversation_id:a,page_action:{action_id:e,ok:!1,error:t,url:"",title:"",snapshot:""}})})}catch{}};if(o?.aborted)return s("panel_closed");if(!Be(r,_n.current))return s("page_actions_not_supported");j(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await nt(t,An.current,_n.current,document,o);if(o?.aborted)return s("panel_closed");if("snapshot"!==t.type&&await function(e,{quietMs:t=300,maxMs:n=3e3,signal:r}={}){return new Promise(a=>{if(r?.aborted)return a();const o=e.defaultView,s=o?.MutationObserver??globalThis.MutationObserver;let i;const l=()=>{clearTimeout(i),clearTimeout(d),c?.disconnect(),r?.removeEventListener("abort",l),a()},c=s?new s(e=>{e.some(e=>!Ke(e.target))&&(clearTimeout(i),i=setTimeout(l,t))}):null;c?.observe(e.body??e.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),i=setTimeout(l,t);const d=setTimeout(l,n);r?.addEventListener("abort",l)})}(document,{signal:o}),o?.aborted)return s("panel_closed");let i={text:"",url:"",title:""},l=null;try{const e=function(e,t=2e4){const n=e.defaultView?.location,r=(n?`${n.pathname}${n.search}`:"").slice(0,500),a=ct(e.title).slice(0,80),o=Math.max(0,t-12);let s=!1,i=`# ${a} — ${r}`;i.length>o&&(i=i.slice(0,o),s=!0);const l=[i];let c=i.length;const d=new Map,u=e=>{for(const t of Array.from(e.children)){if(wt(t))continue;const e=st(t),n=it(t);let r=null;if(e){const n=`e${d.size+1}`,a=ft(t,e),i=ht(t);if(r=`[${n}] ${e} ${pt(ut(t,e))}${i.length?` (${i.join(", ")})`:""}${a?` = ${pt(a)}`:""}${vt(t)}`,c+r.length+1>o)return s=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${pt(ct(lt(t)))} (level ${n})`,c+r.length+1>o))return s=!0,!1;if(r&&(l.push(r),c+=r.length+1),(!e||ot(t))&&!u(t))return!1}return!0};return e.body&&!s&&u(e.body),s&&l.push(rt),{text:l.join("\n"),url:r,title:a,refs:d}}(document);An.current=e.refs,i={text:e.text,url:e.url,title:e.title}}catch(e){An.current=new Map,l=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await T(r,{method:"POST",headers:{"Content-Type":"application/json",...En.current??{},...dr()},signal:o,body:JSON.stringify({conversation_id:a,page_action:{action_id:e,ok:n.ok,error:n.error??(null===l?null:`snapshot_failed: ${l}`),url:i.url,title:i.title,snapshot:i.text}})})}catch{}finally{o?.aborted||j(e=>"acting_on_page"===e?.status?{...e,status:"thinking"}:e)}},yr=(e,t)=>{let n=e;const r=[e];let a="",o=!1,s=!1,i=null;const l=function(e){let t=!1,n="",r=null,a=!1;const o=()=>{null!==r&&cancelAnimationFrame(r),r=null},s=()=>{if(o(),!t&&!n)return;const r=t,a=n;t=!1,n="",e(r,a)},i=()=>{null===r&&("function"==typeof requestAnimationFrame?r=requestAnimationFrame(()=>{r=null,s()}):s())};return{text:()=>{a||(t=!0,i())},thinking:e=>{a||(n+=e,i())},flush:s,close:()=>{a=!0,o(),t=!1,n=""}}}((e,t)=>{if(e){const e=n,t=a;j(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),E(n=>n.map(n=>n.id===e?{...n,content:t}:n))}t&&j(e=>({...e,status:e?.status??"thinking",thinkingContent:(e?.thinkingContent??"")+t}))}),c=()=>{if(!o)return;l.flush(),o=!1,s=!1,a="",n=Ne(),r.push(n);const e=n;E(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),j({status:"thinking"})};return{ctx:{hasUsedTools:!1,activeNodeId:""},deltas:l,apply:e=>{switch(tt.current+=1,e.action){case"status":return(e=>{c();const t=n;if(e.contextUsage&&te(e.contextUsage),"thinking_text"===e.status)return void l.thinking(e.thinkingContent??"");l.flush();const r="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;e.resumed?(a="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),j({status:"thinking",elapsedS:e.elapsedS,elapsedStartMs:r})):"stream_retract"===e.status?(a="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),j(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}))):"tool_heartbeat"===e.status?j(t=>t?{...t,elapsedS:e.elapsedS,elapsedStartMs:r}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:r}):"wait_start"===e.status?j(t=>({status:"wait_start",thinkingContent:t?.thinkingContent,waitSeconds:e.waitSeconds,waitReason:e.waitReason,waitStartMs:Date.now()})):j(t=>"wait_start"===t?.status&&Vt.has(e.status)?t:{status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent})})(e),"continue";case"stream":return c(),a+=e.content,l.text(),"continue";case"done":return(e=>{l.flush(),o=!0,e.intermediate||(s=!0),re(null),de(null),br(e,t);const r=n,i=e.content||a,c=new Date;xr(r,e.messageId,t=>Jt(t,e,i,c))})(e),t&&!e.intermediate?"end":"continue";case"approval_required":return l.flush(),Mn.current=e.conversationId??Cn.current,Ln.current=!1,de(null),re(e.proposals),j(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"}),"continue";case"error":{c(),l.flush();const t=n;return i="error",E(n=>n.map(n=>n.id===t?{...n,content:e.content||u("Sorry, an error occurred. Please try again.")}:n)),"end"}case"cancelled":{l.flush(),i="cancelled";const e=n;return E(t=>t.map(t=>t.id===e?{...t,stopped:!0}:t)),"end"}case"session_ended":{l.flush(),i="session";const e=n;return E(t=>t.filter(t=>!(t.id===e&&!t.content))),"end"}default:return"continue"}},currentAssistantId:()=>n,openAnswerId:()=>o?null:n,accumulated:()=>a,doneReceived:()=>o,segmentIds:()=>r,ended:()=>i,outcome:()=>"error"===i?"failed":null===i&&s?"answered":"stopped"}},br=(e,t)=>{e.conversationId&&!t&&gr(e.conversationId),e.contextUsage&&te(e.contextUsage),e.transferAgentId&&e.transferAgentName&&Q({id:e.transferAgentId,name:e.transferAgentName})},xr=(e,t,n)=>{E(r=>t&&r.some(n=>n.id!==e&&n.serverId===t)?r.filter(t=>t.id!==e):r.map(t=>t.id===e?n(t):t))},kr=(e,t,n)=>{const r=hn(t),a=r?.messageId;if(!r||!a)return!1;"done"!==r.action||Sn.current||br(r,n);const o=new Date;return xr(e,a,e=>"done"===r.action?Jt(e,r,r.content||e.content,o):{...e,serverId:a,raw:r.raw??e.raw}),!0},Nr=(e,t,n,r)=>{let a;try{a=e(t,n)}catch{a=void 0}return Lt(yn.current,t,function(e,t){const n={relayed:e};if(!t)return n;const r=hn(t);return r&&gn(r)?n.end="provisional":r?.messageId&&(n.end="stored"),"status"===t.action&&t.resumed&&(n.replayed=!0),n}(r,a)),"session_ended"===a?.action&&Lt(bn.current,a.reason),a},Cr=e=>{switch(e.action){case"user_message":{const t=e.message,n=Me.current?.openAnswerId()??Ht.current;return E(e=>{if(t.serverId&&e.some(e=>e.serverId===t.serverId))return e;let r=e.length-1;for(;r>=0&&("user"!==e[r].role||e[r].serverId||Qt(e[r])!==t.content);)r-=1;return r>=0&&e.length-r<=3?e.map((e,n)=>n===r?{...e,serverId:t.serverId,raw:t.raw}:e):rn(e,t,n)}),!0}case"conversation_title":return xn.current?.(e.conversationId??Cn.current,e.title),!0;case"approval_resolved":return re(null),de(null),!0;default:return!1}},Sr=e=>{qr(),In(e),j(null),re(null),de(null),Mn.current=null,Ln.current=!1,Rn.current=Cn.current},Ir=async o=>{const s=!o,i=o?o.text:q,l=s?q:o?.draft??"",c=s?J:o?.files??[];if(!i.trim()&&0===c.length)return"dropped";const d=s?"composer":o?.source??"host",p=!Sn.current&&(null!==Je.current||null!==mt.current),h=Sn.current||null!==mt.current,g=!o?.decided&&h&&kn.current?{text:i,source:d,extras:o?.extras,displayText:o?.displayText}:void 0,m=pn(i,o?.decided?void 0:Lt(kn.current,{text:i,source:d,turnRunning:h}),o?.displayText);if(!m)return"dropped";Ve.current=!1,Fe(null);const f=m.extras,v=o?.extras||f?{...o?.extras,...f}:void 0,w=m.text,y=o?.decided?o.displayText?.trim()||w:m.displayText,b=y!==w?y:void 0,x=s?ue(e,t,n)?ce(F,q):[]:o?.refs??[],S=s?C?K:[]:o?.mentions??[],I=Dt(S,w);if(!w&&0===c.length)return"dropped";const _=()=>{s&&(B(""),V([]),G([]),Y([]))};if(Sn.current||p){if(Rt(c))return"dropped";const e=c.every(e=>"done"===e.uploadStatus);if(!p&&!!Fn()&&!!Cn.current&&0===x.length&&0===I.length&&0===Object.keys(v??{}).length&&(0===c.length||k&&e)){_();const e=await(async(e,t,n,o=e)=>{const s=Fn(),i=Cn.current;if(!s||!i)return{result:"failed"};const l=Zt({id:Ne(),role:"user",content:o,timestamp:new Date,files:t.length>0?t:void 0},e),c=Me.current?.openAnswerId()??Ht.current;E(e=>rn(e,l,c));const d=t.filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId);let u=null;try{const t=await T(s,{method:"POST",headers:{"Content-Type":"application/json",...a??{},...dr()},body:JSON.stringify({conversation_id:i,content:e,agent_slug:r,...d.length>0?{file_ids:d}:{}})});if(t.ok){const e=await t.json().catch(()=>null),n=e&&"object"==typeof e?e:{},r=n.turn_id;return{result:"ok",turnId:"string"==typeof r&&r?r:null,unanswered:!1===n.answered}}if(E(e=>e.filter(e=>e.id!==l.id)),409===t.status&&N)return{result:"ended"};409!==t.status&&(u=await xe(t))}catch{E(e=>e.filter(e=>e.id!==l.id))}return null!==n&&Bn({draft:n,files:t,refs:[],mentions:[]},{before:!0}),{result:"failed",detail:u}})(w,c,s?l:null,y);return"ended"===e.result?(je(e=>dn(e,{text:w,draft:l,files:c,refs:[],mentions:[],extras:v,displayText:b,asked:g,onSent:o?.onSent,onNotSent:o?.onNotSent})),"held"):"ok"===e.result?(e.unanswered&&(Ve.current=!0,Fe(u("This message will be read with your next one."))),o?.onSteered?.(e.turnId,e.unanswered),"steered"):(e.detail&&Fe(e.detail),"failed")}return(N||p)&&e?(_(),je(e=>dn(e,{text:w,draft:l,files:c,refs:x,mentions:S,extras:v,displayText:b,asked:g,onSent:o?.onSent,onNotSent:o?.onNotSent})),"held"):"dropped"}const M=Zt({id:Ne(),role:"user",content:y,timestamp:new Date,files:c.length>0?[...c]:void 0,conversationRefs:x.length>0?x:void 0},w),R=Ne();E(e=>[...e,M,{id:R,role:"assistant",content:"",timestamp:new Date}]),_(),Sn.current=!0,L(!0),j({status:"thinking"});const $=Dn.generation,D=yr(R,!1);Ie.current=D.deltas,Me.current=D,Re.current=!1,Te.current=!0,Ae.current=null,Qe.current=!1;let z=!1,O=!1,U=!1,H=!1,W=!1,X=!1,Z=null;const Q=()=>{if(!ir||!Cn.current||!Ae.current||D.ended())return!1;z=!0;const e=D.doneReceived()?Ne():D.currentAssistantId();return E(t=>[...t.filter(t=>t.id!==e),{id:e,role:"assistant",content:"",timestamp:new Date}]),Ht.current=e,jt.current=Ae.current,Ae.current=null,Et(Ne()),j(e=>"cancelling"===e?.status?e:{status:"reconnecting"}),Pt.current=Date.now()+(Ut.current?Ft:15e3),Zn(),!0},ee=new AbortController;Se.current?.abort();const te=new AbortController,ne=()=>{X||(X=!0,D.deltas.close(),Ie.current===D.deltas&&(Ie.current=null),Me.current===D&&(Me.current=null),Te.current=!1,Se.current===te&&te.abort(),Ce.current===ee&&(Ce.current=null),Dn.generation!==$||z||Sr(U?"failed":D.outcome()))};try{Ce.current=ee,Se.current=te;const s=(M.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),i=!!(ar()||or()||ir);if(!Cn.current&&(jn.current||i)){const e=Dn.generation,t=await mr(r);if(Dn.generation!==e)return"dropped";t||(jn.current=null,On(null))}const l=function(e,t,n){switch(e){case"legacy":return{question:t,chatId:n.legacyChatId??void 0,streaming:!0};case"ag-ui":return{threadId:n.conversationId??Ne(),runId:Ne(),messages:[{id:Ne(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={...Object.fromEntries(Object.entries(n.extras??{}).filter(([e])=>!Gt.has(e))),content:t,conversation_id:n.conversationId,agent_slug:n.agentSlug};if(n.supportsToolApproval&&(e.supports_tool_approval=!0),n.referencedConversationIds&&n.referencedConversationIds.length>0&&(e.referenced_conversation_ids=n.referencedConversationIds),n.supportsPageActions&&(e.supports_page_actions=!0),e.supports_artifacts=!0,n.pageContext&&Object.keys(n.pageContext).length>0)try{const t=JSON.stringify(n.pageContext);t&&"{}"!==t&&(e.context=n.pageContext)}catch{}return e}}}(n,w,{legacyChatId:we,conversationId:Cn.current,agentSlug:r,pageContext:Tn.current,supportsToolApproval:null!==Vn(),referencedConversationIds:x.map(e=>e.conversationId),supportsPageActions:Be(Vn(),_n.current),extras:{...mn(ln.current),...v??{}}});s.length>0&&(l.file_ids=s),I.length>0&&(l.mentioned_agent_ids=I);const c=await T(A||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...a??{},...dr()},body:JSON.stringify(l),signal:ee.signal});if(!c.ok||!c.body){const e=c.ok?null:await xe(c);return U=!0,E(t=>t.map(t=>t.id===R?{...t,content:e??u("Unable to connect. Please check the configuration.")}:t)),"failed"}O=!0,o?.onSent?.();const d=function(e){switch(e){case"legacy":return He;case"ag-ui":return We;default:return ze}}(n);if(await Mt(c.body,e=>{const t=Nr(d,e,D.ctx,!1);if(!t)return!0;try{return W?Dn.generation===$&&(!!Cr(t)||!kr(D.currentAssistantId(),t,!1)):(Qe.current||Me.current!==D||(Qe.current=!0,"resend"===et.current&&(et.current="off",null!==Ee.current&&Fr(Ee.current))),!Ae.current&&"string"==typeof e.turn_id&&e.turn_id&&(Ae.current=e.turn_id),"folded"===t.action?(t.turnId&&(Ae.current=t.turnId),!0):!!Cr(t)||("set_chat_id"===t.action?(ye(t.chatId),_t("local",P,t.chatId),!0):"page_action_required"===t.action?(D.deltas.flush(),wr(t.actionId,t.pageAction,t.conversationId),!0):(("session_ended"===t.action||hn(t))&&(H=!0),"end"!==D.apply(t)||!!gn(t)&&(D.deltas.flush(),W=!0,i&&(Z=an(!1)),Ze.current=ee,ne(),!0))))}catch{return!0}},{idleTimeoutMs:()=>ir&&Cn.current&&Ae.current?45e3:void 0}),D.deltas.flush(),!z&&!H&&Q())return"sent";if(!z&&!D.ended()&&D.accumulated()&&!D.doneReceived()){const e=D.currentAssistantId(),t=D.accumulated();E(n=>n.map(n=>n.id===e?{...n,content:t||u("No response.")}:n))}}catch(e){if(D.deltas.close(),X)return"sent";if(e instanceof DOMException&&"AbortError"===e.name)return O?"sent":"dropped";const t=D.currentAssistantId();if(Q())return"sent";O||(U=!0),E(e=>e.map(e=>e.id===t?{...e,content:u("Sorry, an error occurred. Please try again.")}:e))}finally{ne(),Z&&on(Z),Ze.current===ee&&(Ze.current=null)}return O?"sent":"failed"},Tr=()=>{const e=_e.current;if(!e)return;_e.current=null,e.renderer.deltas.flush(),e.renderer.deltas.close(),Ie.current===e.renderer.deltas&&(Ie.current=null),Me.current===e.renderer&&(Me.current=null);const t=e.renderer.currentAssistantId();E(e=>e.filter(e=>!(e.id===t&&!e.content&&!e.stopped))),Sr(e.renderer.outcome())},Ar=s(Tr);Ar.current=Tr;const _r=()=>{const e=_e.current;if(!e)return;const t=e.renderer.doneReceived()?null:e.renderer.currentAssistantId();Tr(),Nt({turnId:e.turnId,shownUpTo:vn(Ct.current)}),t&&E(e=>e.filter(e=>e.id!==t))},Er=s(_r);Er.current=_r;const Mr=e=>{mt.current&&(Nt(null),e&&$(e))},Lr=s(Mr);Lr.current=Mr;const Rr=()=>{dt.current&&window.clearTimeout(dt.current.timer),dt.current=null},$r=()=>{Rr();const e=_e.current;if(e){const t=vn(Ct.current);Tr(),Nt({turnId:e.turnId,shownUpTo:t})}const t=mt.current;if(!t||t.readBack)return;if(!pr())return void Mr("stopped");Jn();const n=window.setTimeout(()=>{mt.current===t&&Mr("stopped")},1e4);t.readBack={from:St.current,timer:n}},Dr=s($r);Dr.current=$r;const jr=()=>{const e=_e.current,t=mt.current;if(!e&&t&&(t.readBack||dt.current?.turn===t))return;Rr();const n=e??t;if(!n)return;const r=window.setTimeout(()=>{dt.current=null,(e?_e.current===e:mt.current===t)&&$r()},5e3);dt.current={turn:n,timer:r}},zr=s(jr);zr.current=jr;const Or=s(new Set),Pr=e=>{let t=_e.current;const n=Nr(ze,e,t?.renderer.ctx??{hasUsedTools:!1,activeNodeId:""},!0);if(!n)return;if(Cr(n))return;if("session_ended"===n.action)return Tr(),Mr("stopped"),void(null===jt.current&&null===Yt.current||Te.current||(Xt(),Sr("stopped")));if(!Kt.has(n.action))return;const r="string"==typeof e.turn_id&&e.turn_id?e.turn_id:null;if(!r)return a=String(e.type),void(Or.current.has(a)||(Or.current.add(a),console.warn(`A "${a}" frame of the event stream names no turn and is not read: the events route needs \`turn_id\` on every turn frame (see "Turns that outlive their stream" in the README)`)));var a;const o=Ge.current.get(r);if(void 0!==o)return void(kr(o,n,!0)&&(Ge.current.delete(r),sn()));if(Te.current||r===Ae.current)return;if(r===Le.current)return;const s=dt.current;if(s)if(Rr(),t&&t===s.turn&&r!==t.turnId){const e=t.renderer.doneReceived()?null:t.renderer.currentAssistantId();Tr(),e&&E(t=>t.filter(t=>t.id!==e)),Jn(),t=null}else t&&t===s.turn&&(gt.current=t.renderer,Jn());let i=t;if(i&&i.turnId!==r&&(Tr(),i=null),!i){const t=mt.current,a=t?.turnId===r,o=r===jt.current;if(!("cancelled"!==n.action&&"error"!==n.action||a||o))return void(t&&$r());t&&!a&&(Mr(),Jn());const s=Ne();E(e=>[...e,{id:s,role:"assistant",content:"",timestamp:new Date}]),i={turnId:r,renderer:yr(s,!0)},_e.current=i,sn(),Ie.current=i.renderer.deltas,Me.current=i.renderer,Nt(null);const l=o||a;!0===e.resumed&&l?(gt.current=i.renderer,Jn()):!o||"cancelled"!==n.action&&"error"!==n.action||Jn(),Xt(),Re.current=!1,Sn.current=!0,L(!0),j({status:"thinking"})}if("end"===i.renderer.apply(n)){if(gn(n)){const e=Ge.current;for(e.set(i.turnId,i.renderer.currentAssistantId());e.size>20;)e.delete(e.keys().next().value);an(!0)}Tr()}},Ur=s(Pr);Ur.current=Pr;const Hr=()=>{const e=Pe.current;e&&(Nn.current?.(e.text,"cancelled"),un(e.parts)),je(null)},Wr=(e,t)=>{const n="string"==typeof e&&e?e:null;jn.current=n,On(n),Ie.current?.close(),Ie.current=null,Ce.current?.abort(),Ce.current=null,Se.current?.abort(),Se.current=null,Pn.current.abort(),Pn.current=new AbortController,Dn.abandon(),_e.current?.renderer.deltas.close(),_e.current=null,Rr(),gt.current=null,Nt(null),Ge.current.clear(),Ze.current?.abort(),Ze.current=null,on(),Te.current=!1,Hr(),qr(),Xt(),Ve.current=!1,In("stopped"),E([]),B(""),V([]),G([]),Y([]),j(null),Q(null),te(null),re(null),de(null),he(!1),Mn.current=null,Ln.current=!1,Rn.current=null,be.current=!1,A?(ye(null),_t("local",P,null)):gr(null,{notify:t})},qr=()=>{null!==Ee.current&&window.clearTimeout(Ee.current),Ee.current=null,et.current="off",at.current=null},Br=(e=!0)=>{qr();const t=Me.current;Me.current=null;const n=_e.current,r=n?.turnId??jt.current;r&&(Le.current=r),Xt(),Ie.current?.flush(),Ie.current?.close(),Ie.current=null,Ce.current?.abort(),Ce.current=null,Se.current?.abort(),Se.current=null,_e.current=null,In("stopped"),j(null),re(null),de(null),he(!1),Mn.current=null,Ln.current=!1,An.current=new Map;const a=e?t?.currentAssistantId():void 0;E(e=>e.map(e=>e.id===a?{...e,stopped:!0}:e).filter(e=>!("assistant"===e.role&&!e.content&&!e.stopped)))},Fr=e=>{const t=ar(),n=Cn.current;if(!t||!n)return;const r=Te.current&&!Qe.current;r&&(et.current="asked");const a=()=>Ee.current===e;ur(t,n,r?{awaiting_send:!0}:void 0).then(async t=>{if(t.ok){const n=await t.json().catch(()=>null);if(!a())return;const o=!!n&&"object"==typeof n&&"none"===n.turn;if(r)return void(o?Qe.current?(et.current="off",Fr(e)):et.current="resend":et.current="off");if(!o)return;return Br(),void Jn()}const n=await xe(t);if(!a())return;const o=at.current;qr(),Re.current=!1,j(e=>"cancelling"!==e?.status?e:o&&tt.current===o.frameSeq?o.statusBefore:{...e,status:o?.statusBefore?.status??"thinking"}),o?.approvalsBefore&&re(e=>e??o.approvalsBefore),Fe(n??u("The response could not be stopped. Try again."))}).catch(()=>{a()&&Br()})},Vr=or(),Kr=U&&x===U?(Gr=U,sr?`${sr}/${encodeURIComponent(Gr)}/events?client_id=${encodeURIComponent(Tt)}`:null):null;var Gr;Ut.current=Kr;const Jr=ke(a),Yr=s(Jr);Yr.current=Jr;const[Xr,Zr]=o(null),[Qr,ea]=o(0);i(()=>{Xr&&Xr.url===Kr&&Xr.headersKey!==Jr&&(Zr(null),ea(e=>e+1))},[Xr,Kr,Jr]),i(()=>{if(!Kr)return;let e=!1,t=!1,n=0,r=null,a=null,o=null,s=!1,i=!1;const l=async()=>{if(r=null,e||t)return;if("hidden"===document.visibilityState)return void(s&&(i=!0));t=!0,a=new AbortController;let o=!1,c=null;try{const t=Yr.current,r=await T(Kr,{headers:{...En.current??{},"X-Chat-Client-Id":Tt},signal:a.signal});if([401,403,404,405].includes(r.status))return o=!0,401!==r.status&&403!==r.status||e||Zr({url:Kr,headersKey:t}),void(e||(Dr.current(),Xn.current()));if(!r.ok||!r.body)return void(e||[502,503,504].includes(r.status)||Xn.current());s&&zr.current(),er.current(),s=!0,c=Date.now(),await Mt(r.body,e=>{n=0;try{Ur.current(e)}catch{}},{idleTimeoutMs:45e3})}catch{}finally{if(t=!1,null===c||e||nr.current(),null!==c&&Date.now()-c>=5e3&&(n=0),!e&&!o&&!i){const e=Math.min(3e4,1e3*2**n);n+=1,r=window.setTimeout(()=>{l()},e*(.5+Math.random()/2))}}},c=()=>{o=null,e||"hidden"!==document.visibilityState||(i=!0,null!==r&&window.clearTimeout(r),r=null,a?.abort(),Er.current())},d=()=>{"hidden"!==document.visibilityState?(null!==o&&window.clearTimeout(o),o=null,"visible"===document.visibilityState&&(mt.current&&zr.current(),t||(null!==r&&window.clearTimeout(r),n=0,i&&(i=!1,Jn()),l()))):null===o&&(o=window.setTimeout(c,6e4))};return l(),document.addEventListener("visibilitychange",d),()=>{e=!0,null!==r&&window.clearTimeout(r),null!==o&&window.clearTimeout(o),a?.abort(),document.removeEventListener("visibilitychange",d),Ar.current(),Lr.current()}},[Kr,Tt,Qr,Jn]);const ta=s([]),[na,ra]=o(0),aa=e=>{ta.current.push(e),ra(e=>e+1)};i(()=>{for(const e of ta.current.splice(0))Nn.current?.(e,"returned")},[na]),i(()=>{if(M||xt)return;if(Re.current&&(Re.current=!1,De))return je(null),un(De.parts),De.draft||0!==De.files.length?(aa(De.text),void Bn(De,{before:!0})):void Nn.current?.(De.text,"dropped");if(Ye||!De)return;je(null);let e=!1;const t=t=>{e||(e=!0,Nn.current?.(De.text,t))},n=[],r=[];for(const e of De.parts){const{asked:t}=e;if(!t){n.push(e);continue}const a=pn(t.text,Lt(kn.current,{text:t.text,source:t.source,turnRunning:!1,held:!0}),t.displayText);a?n.push({...e,text:a.text,displayText:a.displayText!==a.text?a.displayText:void 0,extras:t.extras||a.extras?{...t.extras,...a.extras}:void 0,asked:void 0}):r.push(e)}un(r);const a=r.filter(e=>e.draft||e.files.length>0);for(const e of a)Bn(e,{before:!1});if(0===n.length)return void(a.length>0?aa(De.text):t("dropped"));const{text:o,draft:s,files:i,refs:l,mentions:c,extras:d,displayText:u}=cn(n);oa.current({text:o,draft:s,files:i,refs:l,mentions:c,extras:d,displayText:u,decided:!0,onSent:()=>{t("sent");for(const e of n)Lt(e.onSent)},onNotSent:()=>un(n)}).then(e=>{if("held"===e)return;const r="sent"===e||"steered"===e;t(r?"sent":"failed"===e?"failed":"dropped"),r||un(n)},()=>{t("failed"),un(n)})},[M,xt,Ye,De]);const oa=s(Ir);oa.current=Ir,i(()=>{const e=window.setTimeout(()=>{Wt(g,U,q,F)},300);return()=>window.clearTimeout(e)},[q,U,F,g]),i(()=>()=>{Ie.current?.close(),Se.current?.abort(),Ze.current?.abort(),Je.current&&window.clearTimeout(Je.current.timer),null!==$t.current&&window.clearTimeout($t.current),Yt.current&&window.clearTimeout(Yt.current.timer),dt.current&&window.clearTimeout(dt.current.timer),Hr()},[]);const sa=s({conversationId:U,inputValue:q,conversationRefs:F});sa.current={conversationId:U,inputValue:q,conversationRefs:F},i(()=>()=>{const{conversationId:e,inputValue:t,conversationRefs:n}=sa.current;Wt(g,e,t,n)},[]),i(()=>{const e=U;if(!e||M)return;if(Rn.current===e)return;cr(e)&&Vn()&&(Rn.current=e,(async()=>{const t=await Gn(e);t?.proposals&&(Cn.current!==e||Sn.current||(Mn.current=e,Ln.current=!0,de(null),re(t.proposals)))})())},[U,M]),i(()=>{if(!ne?.length||!Ln.current)return;const e=Mn.current,t=e?cr(e):null;if(!t)return;const n=window.setInterval(()=>{T(t,{headers:{...a??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[ne]),i(()=>{if(!pe)return;const e=Mn.current;if(!e)return void he(!1);if(Date.now()>=$n.current)return he(!1),void Jn();let t=!1;const n=window.setTimeout(async()=>{const n=await Gn(e);if(!t){if(n)return n.proposals?(Ln.current=!0,de(null),re(n.proposals),void he(!1)):n.turnRunning?void ve(e=>e+1):(he(!1),void Jn());ve(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[pe,fe,Jn]);const ia=M&&null!==Fn()&&null!==U;return{messages:_,inputValue:q,setInputValue:B,isLoading:M,turnRunning:M||xt,sendsHeld:!M&&(Ye||xt),turnEnd:R,agentStatus:D,attachedFiles:J,conversationId:U,contextUsage:ee,transferredAgent:Z,canSteer:ia,pendingApprovals:ne,isSubmittingApproval:ae,approvalError:se,submitApprovalDecisions:async e=>{const t=Vn(),n=Mn.current??Cn.current;if(0!==e.length)if(t&&n){de(null),oe(!0);try{const r=await T(t,{method:"POST",headers:{"Content-Type":"application/json",...a??{},...dr()},body:JSON.stringify({conversation_id:n,decisions:e.map(e=>({tool_call_id:e.toolCallId,decision:e.verdict,..."reject"===e.verdict&&e.rejectionReason?{rejection_reason:e.rejectionReason}:{}}))})});if(r.ok)return re(null),Ln.current&&!_e.current?(Ln.current=!1,$n.current=Date.now()+Bt,void he(!0)):void j(e=>e?{...e,status:"thinking"}:{status:"thinking"});de(409===r.status?u("This turn is no longer waiting for a decision."):u("Could not send your decision. Please try again."))}catch{de(u("Could not send your decision. Please try again."))}finally{oe(!1)}}else de(u("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:pe,historyReloadNonce:ge,historyLoadedRef:be,conversationIdRef:Cn,handleFileAdd:vr,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),vr(t))},handleSendMessage:Ir,skipWait:Vr?async()=>{const e=or(),t=Cn.current;if(e&&t)try{(await ur(e,t)).ok&&j(e=>"wait_start"===e?.status?{status:"thinking",thinkingContent:e.thinkingContent}:e)}catch{}}:null,readPendingApprovals:lr?Gn:null,heldMessage:De,notice:Ue,cancelHeldMessage:Hr,reloadHistory:Jn,mergeTurnHistory:e=>{const t=gt.current;if(gt.current=null,!t||Te.current)return!1;const n=new Set(t.segmentIds()),r=t.currentAssistantId();return E(t=>function(e,t,n,r){const a=e.findIndex(e=>n.has(e.id));if(a<0)return e;const o=e.slice(0,a),s=e.slice(a),i=new Set(o.map(e=>e.serverId).filter(Boolean));let l=-1;t.forEach((e,t)=>{e.serverId&&i.has(e.serverId)&&(l=t)});const c=new Map;for(const e of o)e.serverId||c.set(en(e),(c.get(en(e))??0)+1);const d=t.slice(l+1).filter(e=>{if(e.serverId&&i.has(e.serverId))return!1;const t=c.get(tn(e))??0;return 0===t||(c.set(tn(e),t-1),!1)});if(0===d.length)return e;const u=new Set,p=d.map(e=>{const t=s.find(t=>!u.has(t.id)&&!!e.serverId&&t.serverId===e.serverId)??s.find(t=>!u.has(t.id)&&t.id!==r&&!t.serverId&&en(t)===tn(e));return t?(u.add(t.id),nn(t,e)):{...e,id:Oe(e.serverId)}});return[...o,...p,...s.filter(e=>!u.has(e.id))]}(t,e,n,r)),!0},settleUnseenEnd:(e,t)=>{const n=Yt.current;n&&e>=n.from&&(window.clearTimeout(n.timer),Yt.current=null,Sr(t?wn(t,n.shownUpTo):"stopped"));const r=mt.current;!r?.readBack||e<r.readBack.from||Mr(t?wn(t,r.shownUpTo):"stopped")},agentMentions:K,addAgentMention:Wn,handleNewChat:e=>Wr(e,!0),pendingWorkspaceId:zn,clearPendingWorkspace:e=>{jn.current===e&&(jn.current=null,On(null))},handleStopGenerating:()=>{const e=mt.current;if(!Sn.current&&e){const t=ar(),n=Cn.current;return t&&n&&ur(t,n).catch(()=>{}),Le.current=e.turnId,Re.current=!0,Rr(),void Mr("stopped")}if(!Sn.current)return void Br(!1);Re.current=!0;const t=ar(),n=Cn.current,r=null!==jt.current&&!_e.current;if(!t||!n||r)return t&&n&&ur(t,n).catch(()=>{}),void Br();if(null!==Ee.current)return;Ve.current=!1,Fe(null),re(null),de(null),j(e=>({...e,status:"cancelling"}));const a=window.setTimeout(()=>Br(),1e4);Ee.current=a,at.current={statusBefore:D,approvalsBefore:ne,frameSeq:tt.current},Fr(a)},conversationRefs:F,addConversationRef:qn,setAttachedFiles:Y,setMessages:E,setContextUsage:te,updateConversationId:gr,handleSwitchConversation:e=>{if((A||e!==Cn.current)&&(Wr(void 0,!1),!A)){gr(e);const t=qt(g,e);B(t.text),V(t.refs)}}}}function bn(e,t){if(t)return e.find(e=>e.id===t)??e.find(e=>e.slug===t)}function xn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,storageKeyPrefix:a,initialAgent:c,onAgentChange:d}){const u=Ot(),p=null===t?.agents||!!t?.singleEndpoint||"legacy"===n,h=It(a,xt),[g,m]=o([]),[f,v]=o(!1),[w,y]=o(!1),[b,x]=o(p),[k,N]=o(0),C=l(()=>N(e=>e+1),[]),[S,I]=o(null),[T,A]=o(!1),_=s(0);i(()=>{if(p)return void x(!0);const n=`${e}${t?.agents??"/chat/agents"}`,a=++_.current,o=()=>a===_.current;v(!0),u(n,{headers:r}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}).then(e=>{if(!o())return;const t=function(e){return(Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]).filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id)}(e);if(m(t),y(!1),0===t.length)return void I(null);const n=()=>{const e=At("local",h);return bn(t,c)??(e?t.find(t=>t.slug===e):void 0)??t[0]};I(e=>e?t.find(t=>t.id===e.id)??n():n())}).catch(()=>{o()&&(y(!0),0===k&&m([]))}).finally(()=>{o()&&(v(!1),x(!0))})},[e,t,n,r,p,k]);return{agents:g,agentsLoading:f,agentsError:w,agentsSettled:b,agentsDisabled:p,selectedAgent:S,setSelectedAgent:I,agentMenuOpen:T,setAgentMenuOpen:A,handleSwitchAgent:(e,t)=>{e.id!==S?.id?(I(e),e.slug&&_t("local",h,e.slug),A(!1),d?.(e),t?.()):A(!1)},reloadAgents:C}}function kn(e){if(!e||"object"!=typeof e)return null;const t=e,n=t.conversation_id??t.id;if("string"!=typeof n||!n)return null;return{conversationId:n,title:"string"==typeof t.title?t.title.trim():"",updatedAt:"string"==typeof t.updated_at?t.updated_at:"string"==typeof t.created_at?t.created_at:void 0,messageCount:"number"==typeof t.message_count?t.message_count:void 0,agentName:"string"==typeof t.agent_name&&t.agent_name?t.agent_name:void 0,workspaceId:"string"==typeof t.workspace_id&&t.workspace_id?t.workspace_id:null===t.workspace_id?null:void 0}}const Nn=400;let Cn=null,Sn=null,In=0;function Tn(){null!==Cn&&(window.clearInterval(Cn),Cn=null),null!==Sn&&(document.title=Sn,Sn=null)}function An({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:a,isViewingChat:o}){const l=s(!1),c=s(0);i(()=>{if(!r||"undefined"==typeof document)return;In+=1;const e=()=>{!document.hidden&&document.hasFocus()&&Tn()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),In=Math.max(0,In-1),0===In&&Tn()}},[r]),i(()=>{const s=l.current;if(l.current=e,!e||s){if(!e&&s&&r){if(Date.now()-c.current<4e3)return;const e="undefined"!=typeof document&&document.hidden,r="undefined"!=typeof document&&!document.hasFocus(),s=e||r,i=!o||o();if(!s&&i)return;const l=n("Response ready"),d=t?A(n,"{agent} has finished",{agent:t}):n("Your answer is ready");s&&(function(e){if("undefined"==typeof document)return;null===Sn&&(Sn=document.title),null!==Cn&&window.clearInterval(Cn);let t=!0;document.title=e,Cn=window.setInterval(()=>{t=!t,document.title=t?e:Sn??e},1200)}(l),function(e,t){try{if("undefined"==typeof Notification||"granted"!==Notification.permission)return;new Notification(e,{body:t,tag:"filigran-chat-complete"})}catch{}}(l,d)),a?.(l,d)}}else c.current=Date.now()},[e,r,t,n,a,o])}function _n({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=Ot(),[s,c]=o(null),[d,u]=o(null),p="rest"===n&&!t?.singleEndpoint,h=void 0===t?.prompts?"/chat/prompts":t.prompts,g=void 0===t?.quota?"/chat/quota":t.quota,m=p&&h?`${e}${h}`:null,f=p&&g?`${e}${g}`:null;i(()=>{if(!m)return void c(null);let e=!1;return a(m,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){const t=Array.isArray(e)?e:Array.isArray(e?.prompts)?e.prompts:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,r="string"==typeof t.id?t.id:"",a="string"==typeof t.content?t.content:"";r&&a&&n.push({id:r,title:"string"==typeof t.title&&t.title?t.title:r,content:a,description:"string"==typeof t.description?t.description:void 0})}return n}(t);c(n.length>0?n:null)}).catch(()=>{e||c(null)}),()=>{e=!0}},[m,r]);const[v,w]=o(0),y=l(()=>w(e=>e+1),[]);return i(()=>{if(!f)return void u(null);let e=!1;return a(f,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{e||u(function(e){if(!e||"object"!=typeof e)return null;const t=e;return"number"!=typeof t.used?null:{used:t.used,limit:"number"==typeof t.limit?t.limit:null,period:"string"==typeof t.period?t.period:"",..."global"===t.scope||"user"===t.scope?{scope:t.scope}:{}}}(t))}).catch(()=>{e||u(null)}),()=>{e=!0}},[f,r,v]),{prompts:s,quota:d,refreshQuota:y}}function En({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,agentSlug:a}){const s=Ot(),[l,c]=o(null),[d,u]=o(!1),p="rest"===n&&!t?.singleEndpoint,h=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,g=p&&h?`${e}${h}`:null;return i(()=>{if(!g)return void c(null);let e=!1;u(!0);const t=a?`${g}?agent_slug=${encodeURIComponent(a)}`:g;return s(t,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){return(Array.isArray(e)?e:Array.isArray(e?.suggestions)?e.suggestions:[]).map(e=>{if("string"==typeof e)return e.trim();if(e&&"object"==typeof e){const t=e,n=t.prompt??t.label??t.text;if("string"==typeof n)return n.trim()}return""}).filter(e=>e.length>0)}(t);c(n.length>0?n:null)}).catch(()=>{e||c(null)}).finally(()=>{e||u(!1)}),()=>{e=!0}},[g,a,r]),{suggestions:l,loading:d}}function Mn(e){const t=s(e);return function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||"object"!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}(t.current,e)||(t.current=e),t.current}function Ln(e){const t=s(e);c(()=>{t.current=e});const n=l((...e)=>t.current?.(...e),[]);return e?n:void 0}function Rn(e,t){let n="idle",r=!1,a=!1,o=!1;const s=()=>"listening"===n||r,i=()=>{a||s()===o||(o=s(),t.onListeningChange(o))},l=()=>{try{return e.start(),!0}catch{return!1}};return e.onresult=e=>{if("listening"!==n&&"stopping"!==n)return;let r="",a="";for(let t=e.resultIndex;t<e.results.length;t++){const n=e.results[t];n.isFinal?r+=n[0].transcript:a+=n[0].transcript}const o=r.trim();o&&t.onFinal(o),"listening"===n&&t.onInterim(a.trim())},e.onerror=()=>{"listening"===n&&(n="stopping",t.onInterim("")),i()},e.onend=()=>{if(t.onInterim(""),"listening"===n){if(l())return;n="idle"}else r?(r=!1,n=l()?"listening":"idle"):n="idle";i()},{toggle:()=>{a||(s()?(()=>{if(r=!1,"listening"===n){n="stopping",t.onInterim("");try{e.stop()}catch{n="idle"}}i()})():(l()?n="listening":"idle"!==n&&(r=!0),i()))},cancel:()=>{if(!a){if(r=!1,"listening"===n||"stopping"===n){n="discarding",t.onInterim("");try{e.abort()}catch{n="idle"}}i()}},dispose:()=>{if(!a){if(a=!0,e.onresult=null,e.onerror=null,e.onend=null,"idle"!==n)try{e.abort()}catch{}n="idle",r=!1}}}}function $n(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const Dn=new Set(["thinking","status","stream","turn_started"]);function jn(e,t){const n="string"==typeof t.turn_id&&""!==t.turn_id?t.turn_id:null;if(!0===t.relayed){if(null===e.turnId||n!==e.turnId)return{kind:"ignore"}}else{if("folded_into_active_turn"===t.type){if(null!==n)e.turnId=n,e.folded=!0;else if(!1===t.folded)return{kind:"failed"};return{kind:"progress"}}null!==n&&null===e.turnId&&(e.turnId=n)}const r=t.type;if("status"!==r||"transfer_start"!==t.status||"string"!=typeof t.agent_id||!t.agent_id||null!==n&&n!==e.turnId||(e.agentId=t.agent_id),"string"==typeof r&&Dn.has(r))return{kind:"progress"};if("done"===r){const n=function(e){return"string"==typeof e?e:""}(t.content),r=!0!==t.intermediate,a=function(e){const t=je(e.answered_by);return t?.agentId&&t.agentName?.trim()?{agentId:t.agentId,agentName:t.agentName}:null}(t);if(null!==a&&a.agentId!==e.agentId)return n&&e.others.push({...a,failed:!0===t.mention_failed,text:n}),r?{kind:"answer",text:e.segments.join("\n\n"),others:e.others}:{kind:"progress"};if(!r)return n&&(e.segments=e.folded?[n]:[...e.segments,n]),{kind:"progress"};return{kind:"answer",text:(e.folded?[n]:[...e.segments,n]).filter(Boolean).join("\n\n"),others:e.others}}return"cancelled"===r||"error"===r?{kind:"failed"}:{kind:"ignore"}}function zn(e){return e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}const On=new Set(["no-speech","aborted"]);function Pn(e){const t=e.setTimer??((e,t)=>window.setTimeout(e,t)),n=e.clearTimer??(e=>window.clearTimeout(e)),r=e.recognition;let a="listening",o=!1,s="",i=[],l="",c=null,d=!1,u=0,p=null,h="",g=null,m=null,f=null,v=null,w=!1,y=!1,b=0;const x=()=>e.onChange({phase:a,muted:o,heard:s,lines:i}),k=e=>(null!==e&&n(e),null),N=()=>!o&&("listening"===a||"speaking"===a),C=()=>{if(N()){if(w||null!==v)return;try{r.start(),w=!0}catch{}}else if(w)try{r.stop()}catch{}},S=e=>{a=e,C(),x()},I=()=>{p?.abort(),p=null,h=""},T=()=>{g=k(g),f=k(f),l="",s="",S("listening")},A=()=>{m=k(m),c=null,d=!1},_=()=>{A(),S("error"),f=t(()=>{f=null,"error"===a&&T()},2e3)},E=()=>{m=k(m);const n=c;m=t(()=>{m=null,e.probe().then(e=>{c===n&&n&&("over"===e?_():E())})},12e4)},M=t=>{if(!c||!d)return;const n=jn(c,t);"ignore"!==n.kind&&("answer"===n.kind?((t,n)=>{A();const r=e.present(t),o=function(e){const t=e.text.trim()?[{content:e.text}]:[];for(const n of e.others)n.text.trim()&&t.push({content:n.text,agent:{name:n.agentName,failed:n.failed}});return t}({text:r,others:n.map(t=>({...t,text:e.present(t.text)}))});i=[...i,...o.map(e=>({role:"assistant",...e}))];const c=r.trim()?e.speakable(r):"";if(!c.trim())return void T();const d=new AbortController;p=d,h=c,s="",l="",S("speaking"),e.speak(c,d.signal).catch(()=>{}).then(()=>{p===d&&(p=null,h="","speaking"===a&&T())})})(n.text,n.others):"failed"===n.kind?_():E())},L=()=>{u+=1,A()};return r.continuous=!0,r.interimResults=!0,e.lang&&(r.lang=e.lang),r.onresult=n=>{if(b=0,o||"listening"!==a&&"speaking"!==a)return;let r="",p="";for(let e=n.resultIndex;e<n.results.length;e++){const t=n.results[e];t.isFinal?r+=t[0].transcript:p+=t[0].transcript}if("speaking"===a){if(!function(e,t){const n=zn(e);if(n.length<2)return!1;const r=new Set(zn(t));return n.filter(e=>r.has(e)).length/n.length<.6}(`${r} ${p}`,h))return;I(),l="",a="listening"}r.trim()&&(l=[l,r.trim()].filter(Boolean).join(" ")),s=[l,p.trim()].filter(Boolean).join(" "),g=k(g),l&&(g=t(()=>{g=null,"listening"===a&&!o&&l.trim()&&(t=>{const n=++u;g=k(g),l="",s="",i=[...i,{role:"user",content:t}],c=function(e=null){return{turnId:null,folded:!1,agentId:e,segments:[],others:[]}}(e.addressedAgentId()),d=!1,S("processing"),E();const r=()=>n===u&&null!==c;e.send(t,{onAccepted:()=>{r()&&(d=!0)},onNotSent:()=>{r()&&_()},onSteered:(e,t)=>{r()&&(d=!0,M(e?{type:"folded_into_active_turn",folded:!0,turn_id:e}:{type:"folded_into_active_turn",...t?{folded:!1}:{}}))}}).then(e=>{!r()||"dropped"!==e&&"failed"!==e||_()},()=>{r()&&_()})})(l.trim())},1e3)),x()},r.onerror=e=>{y=!0,On.has(e?.error??"")||(b+=1)},r.onend=()=>{w=!1;const e=y;if(y=!1,N())return b>=5?(b=0,o=!0,void x()):void(e?v=t(()=>{v=null,C()},300):C())},{start:T,end:()=>{if("ended"!==a){if(L(),I(),g=k(g),f=k(f),v=k(v),a="ended",r.onresult=null,r.onerror=null,r.onend=null,w)try{r.abort()}catch{}w=!1,x()}},frame:(e,t)=>M({...e,relayed:t||!0===e.relayed}),interrupt:()=>{"speaking"===a?(I(),T()):"processing"===a&&(L(),e.stopTurn(),T())},cancel:()=>{"processing"!==a&&"speaking"!==a||(L(),I(),T())},toggleMute:()=>{if("ended"!==a){if(o=!o,b=0,o)g=k(g),l="",s="";else if("speaking"===a)return I(),void T();C(),x()}}}}const Un=()=>null!==$n();function Hn(e,t){return new Promise(n=>{const r=URL.createObjectURL(e),a=new Audio(r),o=e=>{a.pause(),URL.revokeObjectURL(r),t.removeEventListener("abort",s),n(e)},s=()=>o(!0);a.onended=()=>o(!0),a.onerror=()=>o(!1),t.addEventListener("abort",s),a.play().catch(()=>o(!1))})}function Wn(e,t,n){return"undefined"!=typeof window&&window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance?new Promise(r=>{const a=new SpeechSynthesisUtterance(e);t&&(a.lang=t);const o=()=>{n.removeEventListener("abort",s),r()},s=()=>{window.speechSynthesis.cancel(),o()};a.onend=o,a.onerror=o,n.addEventListener("abort",s),window.speechSynthesis.speak(a)}):Promise.resolve()}const qn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),t("path",{d:"M12 9v4"}),t("path",{d:"M12 17h.01"})]}),Bn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m16 3 4 4-4 4"}),t("path",{d:"M20 7H4"}),t("path",{d:"m8 21-4-4 4-4"}),t("path",{d:"M4 17h16"})]}),Fn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),Vn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 8V4H8"}),t("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),t("path",{d:"M2 14h2"}),t("path",{d:"M20 14h2"}),t("path",{d:"M15 13v2"}),t("path",{d:"M9 13v2"})]}),Kn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),t("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),t("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),t("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),t("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),t("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),t("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),t("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),t("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),Gn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),Jn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 6 9 17l-5-5"})}),Yn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m6 9 6 6 6-6"})}),Xn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m9 18 6-6-6-6"})}),Zn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),Qn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),t("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),er=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),t("path",{d:"M3 5V19A9 3 0 0 0 21 19V5"}),t("path",{d:"M3 12A9 3 0 0 0 21 12"})]}),tr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),nr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),t("polyline",{points:"7 10 12 15 17 10"}),t("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]}),rr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 20h9"}),t("path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"})]}),ar=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M10 14 21 3"}),t("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),or=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),sr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7"}),t("rect",{width:"12",height:"12",x:"10",y:"10",rx:"2"})]}),ir=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}),lr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1"}),t("path",{d:"M2 13h10"}),t("path",{d:"m9 16 3-3-3-3"})]}),cr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 10v6"}),t("path",{d:"M9 13h6"}),t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})]}),dr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),t("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),t("path",{d:"M3 16h3a2 2 0 0 0 2 2v3"}),t("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"})]}),ur=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),t("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),t("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),t("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]}),pr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("line",{x1:"6",x2:"10",y1:"11",y2:"11"}),t("line",{x1:"8",x2:"8",y1:"9",y2:"13"}),t("line",{x1:"15",x2:"15.01",y1:"12",y2:"12"}),t("line",{x1:"18",x2:"18.01",y1:"10",y2:"10"}),t("path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"})]}),hr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),t("path",{d:"M2 12h20"})]}),gr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),t("path",{d:"M3 3v5h5"}),t("path",{d:"M12 7v5l4 2"})]}),mr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),t("circle",{cx:"9",cy:"9",r:"2"}),t("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]}),fr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),vr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),t("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),wr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),yr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),br=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]}),xr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-.11 1.23"}),t("path",{d:"M5 10v2a7 7 0 0 0 12 5"}),t("path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33"}),t("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12"}),t("path",{d:"m2 2 20 20"})]}),kr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}),t("path",{d:"m15 5 4 4"})]}),Nr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272"}),t("path",{d:"M22 2 2 22"}),t("path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473"})]}),Cr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),Sr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),Ir=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),Tr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),Ar=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),_r=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),Er=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M17 14V2"}),t("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),Mr=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M7 10v12"}),t("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),Lr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 6h18"}),t("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),t("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),t("line",{x1:"10",x2:"10",y1:"11",y2:"17"}),t("line",{x1:"14",x2:"14",y1:"11",y2:"17"})]}),Rr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t("circle",{cx:"9",cy:"7",r:"4"}),t("line",{x1:"19",x2:"19",y1:"8",y2:"14"}),t("line",{x1:"22",x2:"16",y1:"11",y2:"11"})]}),$r="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",Dr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:$r}),t("path",{d:"M16 9a5 5 0 0 1 0 6"}),t("path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"})]}),jr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:$r}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),zr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),Or=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]});function Pr({onClear:r,className:a,iconButtonClass:s,t:i}){const[l,c]=o(!1);return t("div",{className:`flex items-center gap-1 ${a}`,children:l?e(n,{children:[t("span",{className:"flex-1 text-[0.7rem] text-red-600 dark:text-red-400",children:i("Delete all conversations?")}),t("button",{type:"button",onClick:()=>{c(!1),r()},"aria-label":i("Delete all conversations"),className:`${s} hover:text-red-500`,children:t(Jn,{size:13})}),t("button",{type:"button",onClick:()=>c(!1),"aria-label":i("Cancel"),className:s,children:t(Zn,{size:13})})]}):e("button",{type:"button",onClick:()=>c(!0),className:"flex items-center gap-1.5 rounded-md px-1 py-0.5 text-[0.7rem] text-gray-400 dark:text-white/40 hover:text-red-500 dark:hover:text-red-400 transition-colors",children:[t(Lr,{size:12}),i("Clear all conversations")]})})}const Ur=({open:e,onClose:n,anchorRef:r,placement:a="bottom-start",width:c=280,children:u})=>{const p=s(null),[h,g]=o({top:0,left:0}),m=l(()=>n(),[n]);if(function(e,t,n=!0){i(()=>{if(!n)return;const r=n=>{e.current&&!e.current.contains(n.target)&&t()};return document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r)}},[e,t,n])}(p,m,e),d(()=>{if(!e||!r.current)return;const t=r.current.getBoundingClientRect(),n=p.current?.offsetHeight??0,o=window.innerHeight-t.bottom-8,s=t.top-8,i=n>0&&o<n&&s>o?Math.max(8,t.top-n-4):t.bottom+4,l="bottom-end"===a?t.right-c:t.left,d=Math.max(8,Math.min(l,window.innerWidth-c-8));g({top:i,left:d})},[e,r,a,c,u]),!e)return null;const f=_(r.current);return b(t("div",{ref:p,className:"fixed z-[10000] rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl",style:{top:h.top,left:h.left,width:c},children:u}),f)},Hr=({size:e=16,className:n=""})=>t("div",{className:`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${n}`,style:{width:e,height:e}});function Wr(e){return Math.max(e.maxRight-e.minLeft,0)}const qr=({title:n,children:r})=>{const a=s(null),i=s(null),[l,c]=o(null),[u,p]=o({below:!1,shift:0});if(d(()=>{if(!l||!i.current)return;const{width:e,height:t}=i.current.getBoundingClientRect();p(function(e,t){const n=e.center-t.width/2;let r=0;return n<e.minLeft?r=e.minLeft-n:n+t.width>e.maxRight&&(r=e.maxRight-(n+t.width)),{below:e.top-4-t.height<e.minTop,shift:r}}(l,{width:e,height:t}))},[l,n]),!n)return r;const h=()=>{if(!a.current)return;const e=_(a.current).getBoundingClientRect();c(function(e,t,n){return{top:e.top,bottom:e.bottom,center:(e.left+e.right)/2,minTop:Math.max(t.top,0),minLeft:Math.max(t.left,0)+4,maxRight:Math.min(t.right,n)-4}}(a.current.getBoundingClientRect(),e,window.innerWidth))};return e("span",{ref:a,className:"inline-flex",onMouseEnter:h,onMouseLeave:()=>c(null),onFocus:e=>{const t=e.target;"function"==typeof t.matches&&t.matches(":focus-visible")&&h()},onBlur:()=>c(null),children:[r,l&&b(t("span",{ref:i,className:`pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${u.below?"":"-translate-y-full"} whitespace-normal break-words rounded-md bg-gray-900 dark:bg-gray-100 px-2 py-1 text-xs text-white dark:text-gray-900 shadow-lg`,style:{top:u.below?l.bottom+4:l.top-4,left:l.center+u.shift,maxWidth:Wr(l)},role:"tooltip",children:n}),_(a.current))]})},Br=({icon:e,fallback:n})=>{const r=function(e){const t=e?.trim();return t?/^(https:\/\/|data:image\/)/i.test(t)?"image":t.length<=8&&!/[\p{L}\p{N}]/u.test(t)?"emoji":null:null}(e);return"image"===r?t("img",{src:e.trim(),alt:"",className:"w-4 h-4 rounded-sm object-cover"}):t("span","emoji"===r?{className:"text-sm leading-none",children:e.trim()}:{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:n})},Fr=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(sr,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(Ir,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(ur,{...e})}],Vr=({mode:r,agentName:a,agents:l,agentsLoading:c=!1,agentsError:d=!1,selectedAgent:p,transferredFrom:h,agentMenuOpen:g,onAgentMenuToggle:m,onAgentMenuClose:f,onSwitchAgent:v,modeMenuOpen:w,onModeMenuToggle:y,onModeMenuClose:b,onModeChange:x,onNewChat:k,onClose:N,logoIcon:C,agentDashboardUrl:S,historyEnabled:I=!1,historyMenuOpen:T=!1,onHistoryMenuToggle:_,onHistoryMenuClose:E,conversations:L=[],conversationsLoading:R=!1,activeConversationId:$=null,onSelectConversation:D,onDeleteConversation:j,onClearAll:z,actions:O,t:P})=>{const U=s(null),H=s(null),q=s(null),[B,F]=o("");i(()=>{g||F("")},[g]);const V=u(()=>{const e=B.trim().toLowerCase();return e?l.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):l},[l,B]),K=l.length>5,G="sidebar"===r?Ir:"fullscreen"===r?dr:sr;return e("div",{className:"flex items-center px-3 py-2 min-h-[48px] border-b border-gray-200 dark:border-white/10 bg-gradient-to-br from-[var(--chat-accent-dark)]/[0.13] to-[var(--chat-accent)]/[0.07] "+("floating"===r?"rounded-t-xl":""),children:[e("div",{className:"min-w-0",children:[e("button",{ref:U,type:"button",onClick:m,className:"flex max-w-full items-center gap-1.5 text-sm font-semibold text-gray-900 dark:text-white px-2 py-1 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t("span",{className:"flex shrink-0 items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:C}),t("span",{className:"min-w-0 truncate",children:a}),t(Yn,{size:16,className:"shrink-0 text-gray-400 dark:text-white/30"})]}),h&&t("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal text-gray-400 dark:text-white/30",children:A(P,"Transferred from {agent}",{agent:h})})]}),e(Ur,{open:g,onClose:f,anchorRef:U,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:P("Switch to another agent")}),0===l.length&&c&&t("div",{className:"px-4 py-2",children:t(Hr,{size:16})}),0===l.length&&!c&&d&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(qn,{size:14,className:"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400"}),t("span",{className:"text-[0.75rem] leading-5 text-gray-600 dark:text-white/60",children:P("Could not reach the assistant service. Check the connection and try again.")})]}),0===l.length&&!c&&!d&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:P("Agent switching is not available here")}),K&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(Cr,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40"}),t("input",{autoFocus:!0,type:"text",value:B,onChange:e=>F(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f()},placeholder:P("Search agents..."),"aria-label":P("Search agents..."),className:"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[l.length>0&&0===V.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:P("No agent matches")}),W(V).map(({group:n,agents:r})=>e("div",{role:"group","aria-label":n??void 0,children:[n&&t("span",{className:"block px-4 pt-2 pb-0.5 text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40",children:n}),r.map(n=>e("button",{type:"button",onClick:()=>v(n),className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(n.id===p?.id?"bg-[var(--chat-accent)]/10":""),children:[t("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t(Br,{icon:n.icon,fallback:C})}),e("div",{className:"min-w-0",children:[t("div",{className:"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate",children:n.name}),n.description&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:n.description})]})]},n.id))]},n??""))]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("div",{children:[S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/agents`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(ar,{size:18,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:P("Browse agents")})]}),S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/agents/new`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(Rr,{size:18,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:P("Create agent")})]})]})]}),t("div",{className:"flex-1"}),I&&e(n,{children:[t(qr,{title:P("Conversation history"),children:t("button",{ref:q,type:"button",onClick:_,"aria-label":P("Conversation history"),"aria-haspopup":"menu","aria-expanded":T,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(gr,{size:18})})}),e(Ur,{open:T,onClose:()=>E?.(),anchorRef:q,placement:"bottom-end",width:300,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:P("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[R&&0===L.length&&t("div",{className:"px-4 py-2",children:t(Hr,{size:16})}),!R&&0===L.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:P("No conversations yet")}),L.map(n=>{const r=n.conversationId===$,a=M(n.updatedAt,P);return e("div",{className:"group flex items-center gap-2 px-4 py-1.5 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(r?"bg-[var(--chat-accent)]/10":""),children:[e("button",{type:"button",onClick:()=>D?.(n.conversationId),className:"flex-1 min-w-0 text-left",children:[t("div",{className:"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate",children:n.title||P("Untitled conversation")}),a&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:a})]}),j&&t("button",{type:"button",onClick:()=>j(n.conversationId),title:P("Delete conversation"),"aria-label":P("Delete conversation"),className:"shrink-0 p-1 rounded-md text-gray-400 dark:text-white/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all",children:t(Lr,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("button",{type:"button",onClick:()=>{E?.(),k()},className:"w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(rr,{size:16,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:P("New conversation")})]}),z&&L.length>0&&t(Pr,{onClear:()=>{E?.(),z()},className:"px-3 pb-2",iconButtonClass:"p-1 rounded-md text-gray-400 dark:text-white/40 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",t:P})]})]}),O,t(qr,{title:P("New chat"),children:t("button",{type:"button",onClick:k,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(rr,{size:18})})}),"inline"!==r&&x&&e(n,{children:[t(qr,{title:P("Switch view"),children:t("button",{ref:H,type:"button","aria-label":P("Switch view"),onClick:y,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(G,{size:18})})}),e(Ur,{open:w,onClose:b,anchorRef:H,placement:"bottom-end",width:180,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:P("Switch to")}),t("div",{className:"pb-1",children:Fr.map(n=>e("button",{type:"button",onClick:()=>{x(n.mode),b()},className:"w-full flex items-center gap-3 px-4 py-1 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(r===n.mode?"bg-[var(--chat-accent)]/10":""),children:[n.getIcon({size:18,className:"text-gray-400 dark:text-white/40"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:n.label(P)})]},n.mode))})]})]}),"inline"!==r&&N&&t(n,{children:t(qr,{title:P("Close"),children:t("button",{type:"button","aria-label":P("Close"),onClick:N,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(Zn,{size:18})})})})]})};function Kr({url:e,query:t,exclude:n,requestHeaders:r}){const a=Ot(),[s,l]=o(pe);return i(()=>{if(!e||null===t)return void l(pe);let o=!0;const s=new AbortController,i=window.setTimeout(async()=>{try{const i=await a(function(e,t,n){const r=new URLSearchParams({limit:String(8)});return t&&r.set("q",t),n&&r.set("exclude",n),`${e}${e.includes("?")?"&":"?"}${r.toString()}`}(e,t,n),{credentials:"include",headers:{...r??{}},signal:s.signal}),c=i.ok?await i.json():null;if(!o)return;l(i.ok?{query:t,items:de(c),failed:!1}:{query:t,items:[],failed:!0})}catch{o&&l({query:t,items:[],failed:!0})}},150);return()=>{o=!1,window.clearTimeout(i),s.abort()}},[e,t,n,r]),s}function Gr({url:e,requestHeaders:t,conversationId:n,text:r,onTextChange:a,textareaRef:c,refs:h,onPick:g,agentMentions:m}){const f=null!==e||!!m,[v,w]=o(null),[y,b]=o(null),[x,k]=o(0),N=s(null),C=p(),S=l(e=>`${C}-option-${e}`,[C]),I=l(()=>{const e=c.current,t=f&&e&&document.activeElement===e&&e.selectionStart===e.selectionEnd?function(e){const t=/@([\w-]*)$/.exec(e);return!t||oe(e[t.index-1])?null:{anchor:t.index,query:t[1]}}(e.value.slice(0,e.selectionStart)):null;w(e=>{return(n=e)===(r=t)||n&&r&&n.anchor===r.anchor&&n.query===r.query?e:t;var n,r})},[f,c]),T=l(()=>w(null),[]);d(()=>{const e=N.current;if(null===e)return;N.current=null;const t=c.current;t&&(t.focus(),t.setSelectionRange(e,e))},[r,c]),i(()=>{I()},[r,I]),i(()=>{v||b(null)},[v]);const A=Kr({url:e,query:v?.query??null,exclude:n,requestHeaders:t}),[_,E]=o([]);i(()=>{E([])},[n]),i(()=>{E(e=>function(e,t,n){if(null===t.query||t.failed)return e;const r=t.query,a=new Set(t.items.map(e=>e.id)),o=t.items.length<8,s=r.toLowerCase(),i=o?e.filter(e=>e.id===n||a.has(e.id)||!e.title.toLowerCase().includes(s)):e;return ge(i.length===e.length?e:i,t.items)}(e,A,n))},[A,n]);const M=u(()=>ge(h.map(me),_),[h,_]);i(()=>{k(0)},[A]);const L=function(e){const{trigger:t,dismissed:n,search:r,referenced:a,exclude:o,known:s=[]}=e;if(!t||n)return{kind:"closed"};if(a>=5)return{kind:"full"};if(r.failed)return{kind:"closed"};const i=t.query?s.filter(e=>he(t.query,e)&&!r.items.some(t=>t.id===e.id)):[],l=[...r.items,...i].slice(0,8),c=o?l.filter(e=>e.id!==o):l;return c.length>0?{kind:"results",items:c}:t.query&&r.query===t.query?{kind:"empty"}:{kind:"closed"}}({trigger:v,dismissed:null!==v&&v.anchor===y,search:A,referenced:ce(h,r).length,exclude:n,known:M}),R=null!==v&&v.anchor===y,$=[...u(()=>m&&v&&!R?function(e,t){const n=[];for(const r of e){const e=$t(r);if(e&&he(t,{key:e,title:r.name})&&(n.push({agentId:r.id,name:r.name,key:e}),n.length>=5))break}return n}(m.agents,v.query):[],[m,v,R]).map(e=>({type:"agent",mention:e})),...null!==e&&"results"===L.kind?L.items.map(e=>({type:"conversation",candidate:e})):[]],D=Math.min(x,Math.max($.length-1,0)),j=e=>{if(!v)return;const t="agent"===e.type?e.mention.key:e.candidate.key,n=function(e,t,n){const r=e.slice(0,t.anchor),a=e.slice(t.anchor+1+t.query.length),o=`@${n}`;return{text:`${r}${o}${/^\s/.test(a)?"":" "}${a}`,caret:r.length+o.length+1}}(r,v,t);"agent"===e.type?m?.onPick(e.mention):g({conversationId:e.candidate.id,title:e.candidate.title,key:t,isOwn:e.candidate.isOwn}),N.current=n.caret,a(n.text),w(null)},z=f?{"aria-autocomplete":"list","aria-controls":$.length>0?C:void 0,"aria-activedescendant":$.length>0?S(D):void 0}:{};return{view:null===e?{kind:"closed"}:L,items:$,activeIndex:D,setActiveIndex:k,listboxId:C,optionId:S,sync:I,close:T,pick:j,onKeyDown:e=>{if("closed"===L.kind&&0===$.length||!v||e.nativeEvent.isComposing)return!1;if("Escape"===e.key)return e.preventDefault(),b(v.anchor),!0;if(0===$.length)return!1;if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;return k((D+t+$.length)%$.length),!0}return!("Enter"!==e.key&&"Tab"!==e.key||e.shiftKey)&&(e.preventDefault(),j($[D]),!0)},textareaAria:z}}const Jr=14,Yr=2*Math.PI*6,Xr=[{field:"system",label:e=>e("System prompt"),color:"#9ca3af"},{field:"tools",label:e=>e("Tool definitions"),color:"#a78bfa"},{field:"dynamicTools",label:e=>e("MCP & dynamic tools"),color:"#f0abfc"},{field:"summary",label:e=>e("Summarized conversation"),color:"#fb7185"},{field:"toolResults",label:e=>e("Tool results"),color:"#34d399"},{field:"conversation",label:e=>e("Conversation"),color:"#a1a1aa"}],Zr=({usage:r,t:a})=>{const{used:i,limit:l,breakdown:c}=r,d=s(null),[u,p]=o(!1),h=Math.min(Math.max(i/l,0),1),g=h>=.95,m=h>=.8,f=g?"text-red-500":m?"text-amber-500":"text-[var(--chat-accent)]",v=g?"text-red-500 dark:text-red-400":m?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",w=Math.round(100*h),y=`${E(i)}/${E(l)}`,b=a(g?"Context full — older turns are being dropped":m?"Context nearly full — older turns are being summarized":"Context used"),x=A(a,"{counts} tokens",{counts:y}),k=`${b} · ${x}`,N=c?Xr.filter(e=>(c[e.field]??0)>0):[],C=N.length>0,S=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:Jr,height:Jr,viewBox:"0 0 14 14",className:f,"aria-hidden":"true",children:[t("circle",{cx:7,cy:7,r:6,fill:"none",strokeWidth:2,className:"stroke-gray-200 dark:stroke-white/15"}),t("circle",{cx:7,cy:7,r:6,fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeDasharray:Yr,strokeDashoffset:Yr*(1-h),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${v}`,children:[w,"%"]})]});return C?e(n,{children:[t(qr,{title:u?"":A(a,"{summary} — click for details",{summary:k}),children:t("button",{ref:d,type:"button",onClick:()=>p(e=>!e),"aria-label":`${k} (${w}%)`,"aria-haspopup":"dialog","aria-expanded":u,className:"flex items-center rounded-md px-1 -mx-1 py-0.5 transition-colors hover:bg-gray-100 dark:hover:bg-white/10",children:S})}),e(Ur,{open:u,onClose:()=>p(!1),anchorRef:d,placement:"bottom-end",width:296,children:[e("div",{className:"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3",children:[t("span",{className:`text-[0.8125rem] tabular-nums ${v}`,children:A(a,"{percent}% full",{percent:w})}),e("span",{className:"text-[0.7rem] tabular-nums text-gray-400 dark:text-white/40 shrink-0",children:["~",x]})]}),t("div",{className:"px-3.5 pb-2.5 pt-1.5",children:t("span",{className:"flex h-1.5 w-full gap-px rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:N.map(e=>t("span",{className:"h-full first:rounded-l-full",style:{width:(c?.[e.field]??0)/Math.max(i,1)*Math.min(i/l,1)*100+"%",backgroundColor:e.color}},e.field))})}),t("div",{className:"px-3.5 pb-1",children:N.map(n=>e("div",{className:"flex items-center gap-2 py-[3px]",children:[t("span",{className:"h-2 w-2 shrink-0",style:{backgroundColor:n.color,borderRadius:2},"aria-hidden":"true"}),t("span",{className:"text-[0.75rem] text-gray-700 dark:text-white/70 truncate",children:n.label(a)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0",children:E(c?.[n.field]??0)})]},n.field))}),m&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${v}`,children:b})]})]}):t(qr,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},Qr=({view:n,items:r,activeIndex:a,listboxId:o,optionId:i,onHover:l,onPick:c,t:u})=>{const p=s(null);if(d(()=>{p.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[a,n.kind]),"closed"===n.kind&&0===r.length)return null;const h=r.some(e=>"agent"===e.type),g=u(h?"Mention an agent":"Reference a conversation");return e("div",{className:"absolute left-0 right-0 bottom-full mb-1.5 z-20 rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl",children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:g}),r.length>0&&t("div",{ref:p,id:o,role:"listbox","aria-label":g,className:"max-h-[240px] overflow-y-auto pb-1 filigran-chat-scrollable",children:r.map((n,o)=>{const s=o===a,d="conversation"===n.type&&h&&"agent"===r[o-1]?.type;return e("div",{children:[d&&t("span",{className:"block px-4 pt-2 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:u("Reference a conversation")}),e("div",{id:i(o),role:"option","aria-selected":s,onMouseDown:e=>{e.preventDefault(),c(n)},onMouseMove:()=>{s||l(o)},className:"flex items-center gap-2.5 px-4 py-1.5 cursor-pointer transition-colors "+(s?"bg-gray-100 dark:bg-white/10":""),children:[t("span",{className:"shrink-0 text-[var(--chat-accent)]",children:"agent"===n.type?t(Vn,{size:14}):t(yr,{size:14})}),"agent"===n.type?e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] text-gray-900 dark:text-white truncate",children:n.mention.name}),e("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:["@",n.mention.key]})]}):e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] text-gray-900 dark:text-white truncate",children:n.candidate.title||u("Untitled conversation")}),e("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:["@",n.candidate.key,!n.candidate.isOwn&&` · ${u("Shared with you")}`]})]})]})]},"agent"===n.type?`agent-${n.mention.agentId}`:n.candidate.id)})}),"empty"===n.kind&&0===r.length&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:u("No conversation matches")}),"full"===n.kind&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:A(u,"A message references at most {count} conversations",{count:5})})]})},ea=({prompts:r,onPick:a,t:i})=>{const l=s(null),[c,d]=o(!1),[u,p]=o(""),h=()=>{d(!1),p("")},g=u.trim().toLowerCase(),m=g?r.filter(e=>e.title.toLowerCase().includes(g)||(e.description??"").toLowerCase().includes(g)):r;return e(n,{children:[t(qr,{title:i("Insert prompt template"),children:t("button",{ref:l,type:"button",onClick:()=>c?h():d(!0),"aria-label":i("Insert prompt template"),"aria-haspopup":"menu","aria-expanded":c,className:"w-7 h-7 flex items-center justify-center rounded-lg transition-colors "+(c?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10":"text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10"),children:t(Tr,{size:15})})}),e(Ur,{open:c,onClose:h,anchorRef:l,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:i("Insert prompt template")}),r.length>5&&t("div",{className:"px-3 pb-2 pt-1",children:t("input",{autoFocus:!0,type:"text",value:u,onChange:e=>p(e.target.value),onKeyDown:e=>{"Escape"===e.key&&h()},placeholder:i("Search prompts..."),"aria-label":i("Search prompts..."),className:"w-full h-7 px-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[0===m.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:i("No prompt matches")}),m.map(n=>e("button",{type:"button",onClick:()=>{a(n.content),h()},className:"w-full px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t("div",{className:"text-[0.8125rem] text-gray-900 dark:text-white truncate",children:n.title}),n.description&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:n.description})]},n.id))]})]})]})},ta=({quota:n,t:r})=>{const{used:a,limit:o}=n,s=function(e,t){switch(e){case"daily":return t("today");case"monthly":return t("this month");case"yearly":return t("this year");default:return e}}(n.period,r),i=e=>"global"===n.scope?A(r,"{quota} (shared across all users)",{quota:e}):e;if(null===o){const e=i(s?A(r,"Usage · {period}",{period:s}):r("Usage"));return t(qr,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30",role:"img","aria-label":`${e} ${E(a)}`,children:E(a)})})}const l=o>0?Math.min(a/o,1):1,c=!(o>0)||a>=o,d=l>=.75,u=c?"bg-red-500":d?"bg-amber-500":"bg-[var(--chat-accent)]/60",p=c?"text-red-500 dark:text-red-400":d?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",h=`${E(a)}/${E(o)}`,g=r(c?"Quota reached":"Quota"),m=i(s?`${g} · ${s}`:g);return t(qr,{title:m,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${m} ${h}`,children:[t("span",{className:"h-1 w-10 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:t("span",{className:`block h-full rounded-full transition-[width] duration-300 ${u}`,style:{width:100*l+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${p}`,children:h})]})})},na=[],ra=({header:r,steerAttachments:a=!1,canHold:c=!1,heldMessage:p,notice:h,onCancelHeld:g,inputValue:m,onInputChange:f,onSend:v,onStop:w,isLoading:y,sendsHeld:b=!1,canSteer:x=!1,attachedFiles:k=[],onFileAdd:N,onFileRemove:C,onPaste:S,t:I,mode:T,separatorColor:A,prompts:_,quota:E,contextUsage:M,composerToolbar:L,conversationReferences:R,agentMentions:$})=>{const D=s(null),j=s(null),z=$?.agents,O=$?.onPick,P=u(()=>z&&O?{agents:z,onPick:O}:void 0,[z,O]),U=Gr({url:R?.url??null,requestHeaders:R?.requestHeaders,conversationId:R?.conversationId,text:m,onTextChange:f,textareaRef:j,refs:R?.refs??na,onPick:e=>R?.onPick(e),agentMentions:P}),H=s(!1),W=function(e){const[t,n]=o(!1),[r,a]=o(""),c=s(null),d=s(e);d.current=e;const u=null!==$n();return i(()=>{const e=$n();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=Rn(t,{onFinal:e=>d.current(e),onInterim:a,onListeningChange:n});return c.current=r,()=>{c.current=null,r.dispose(),n(!1),a("")}},[]),{supported:u,listening:t,interim:r,toggle:l(()=>c.current?.toggle(),[]),cancel:l(()=>c.current?.cancel(),[])}}(e=>{H.current=!0,f(m.trim()?`${m.trimEnd()} ${e}`:e)});d(()=>{const e=j.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,H.current&&(H.current=!1,e.scrollTop=e.scrollHeight))},[m]);const q=Boolean(_&&_.length>0||E||M||L),B=Boolean(N&&C&&S),F=m.trim()||B&&k.length>0,V=B&&k.some(e=>"pending"===e.uploadStatus),K=B&&k.length>0,G=B&&(y||b)&&Rt(k),J=F&&!V&&!G,Y=Boolean(R)&&ce(R?.refs??na,m).length>0||Boolean($)&&Dt($?.mentions??[],m).length>0,X=y&&x&&!Y&&(!K||a),Z=X&&!V&&!G&&(K||Boolean(m.trim())),Q=y&&c&&!Z&&!p&&Boolean(J),ee=()=>{(y?Z||Q:J)&&(W.cancel(),v())},te=I(Q?"Enter to send when the answer ends · Esc to stop":G?"A file failed to upload: remove it, or send once the answer ends":X?"Enter to send now · Esc to stop":y&&K?"Attachments wait for the current response":y&&Y?"This message waits for the current response":"Uses AI. Verify results.");return e("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-white/10 "+("floating"===T?"rounded-b-xl":""),style:A?{borderTopColor:A,borderTopWidth:1}:void 0,"data-testid":"filigran-chat-composer",children:[r&&t("div",{className:"mb-2",children:r}),h&&t("div",{role:"alert","data-testid":"filigran-chat-composer-notice",className:"mb-2 text-[0.75rem] text-red-500 dark:text-red-400",children:h}),p&&e("div",{className:"mb-2 flex items-center gap-2 rounded-lg border border-dashed border-[var(--chat-accent-40)] px-2.5 py-1.5 text-[0.75rem]",children:[t("span",{className:"shrink-0 text-gray-500 dark:text-white/50",children:I("Sends when the answer ends:")}),t("span",{className:"min-w-0 flex-1 truncate text-gray-800 dark:text-white/80",children:p.displayText??(p.text||I("Attached files"))}),g&&t("button",{type:"button",onClick:g,className:"shrink-0 text-gray-400 dark:text-white/40 hover:text-red-500",children:I("Cancel")})]}),B&&k.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:k.map((n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] "+("error"===n.uploadStatus?"border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400":"pending"===n.uploadStatus?"border-gray-200 dark:border-white/10 text-gray-400 dark:text-white/40":"border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60"),children:["pending"===n.uploadStatus?t("span",{className:"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin"}):t(or,{size:14}),n.name,"error"===n.uploadStatus&&t("span",{className:"text-red-400 text-[0.6rem]",children:"✕"}),t("button",{type:"button",onClick:()=>C?.(r),className:"ml-0.5 text-gray-400 dark:text-white/30 hover:text-gray-600 dark:hover:text-white/60",children:"×"})]},r))}),e("div",{className:`relative flex items-end border rounded-xl px-2 py-1 transition-colors ${W.listening?"border-red-500/50":"border-gray-200 dark:border-white/10 focus-within:border-[var(--chat-accent)]"} ${y?"filigran-chat-active-border":""}`,children:[B&&e(n,{children:[t("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:e=>{N?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>D.current?.click(),"aria-label":I("Attach files"),className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 mr-0.5 transition-colors",children:t(Fn,{size:18})})]}),t("textarea",{ref:j,placeholder:W.listening?I("Listening..."):I("Ask a question..."),value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{U.onKeyDown(e)||("Enter"!==e.key||e.shiftKey||(e.preventDefault(),ee()),"Escape"===e.key&&y&&(e.preventDefault(),w()))},onKeyUp:U.sync,onClick:U.sync,onFocus:U.sync,onBlur:U.close,...U.textareaAria,onPaste:S,rows:1,className:"flex-1 bg-transparent border-none outline-hidden resize-none text-[0.8125rem] py-1.5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 filigran-chat-scrollable",style:{maxHeight:120}}),t(Qr,{view:U.view,items:U.items,activeIndex:U.activeIndex,listboxId:U.listboxId,optionId:U.optionId,onHover:U.setActiveIndex,onPick:U.pick,t:I}),W.supported&&t(qr,{title:W.listening?I("Stop dictation"):I("Dictate a message"),children:e("button",{type:"button",onClick:W.toggle,"aria-label":I("Dictate a message"),"aria-pressed":W.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors "+(W.listening?"text-red-500 bg-red-500/10 hover:bg-red-500/20":"text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10"),children:[W.listening?t(xr,{size:18}):t(br,{size:18}),W.listening&&t("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse"})]})}),Q&&t(qr,{title:I("Send when the answer ends"),children:t("button",{type:"button",onClick:ee,"aria-label":I("Send when the answer ends"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Sr,{size:18})})}),Z&&t(qr,{title:I("Send now"),children:t("button",{type:"button",onClick:ee,"aria-label":I("Send now"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Sr,{size:18})})}),t(qr,{title:y?I("Stop generating"):V?I("Files uploading..."):"",children:t("button",{type:"button",onClick:y?w:ee,"aria-label":I(y?"Stop generating":"Send"),disabled:!y&&!J,className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 "+(y?"text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5":J?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20":"text-gray-300 dark:text-white/20 cursor-not-allowed"),children:t(y?Ar:Sr,{size:18})})})]}),q&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[_&&_.length>0&&t(ea,{prompts:_,onPick:e=>{f(m.trim()?`${m.trimEnd()}\n\n${e}`:e),j.current?.focus()},t:I}),L,(M||E)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[M&&t(Zr,{usage:M,t:I}),E&&t(ta,{quota:E,t:I})]})]}),W.interim?e("p",{className:"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-red-500 dark:text-red-400 mt-1.5",children:[t("span",{className:"w-1.5 h-1.5 shrink-0 rounded-full bg-red-500 motion-safe:animate-pulse"}),t("span",{className:"truncate",children:W.interim})]}):t("p",{"data-testid":"filigran-chat-disclaimer",className:"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70",children:te})]})},aa=e=>e.serverId??e.id;const oa=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;const sa={time:{hour:"2-digit",minute:"2-digit"},date:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"},dateWithYear:{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"},full:{dateStyle:"full",timeStyle:"short"}},ia=new Map;function la(e,t){const n=`${e??""}|${t}`;let r=ia.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,sa[t])}catch{r=new Intl.DateTimeFormat(void 0,sa[t])}ia.set(n,r)}return r}const ca={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const da=new Set(["ArrowUp","PageUp","Home"]);function ua(e){return 1===e.length?e[0].clientY:null}const pa=new Set(["auto","scroll","overlay"]);const ha={presentation:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 3h20"}),t("path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"}),t("path",{d:"m7 21 5-5 5 5"})]}),report:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),t("path",{d:"M10 9H8"}),t("path",{d:"M16 13H8"}),t("path",{d:"M16 17H8"})]}),video:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z"}),t("path",{d:"m6.2 5.3 3.1 3.9"}),t("path",{d:"m12.4 3.4 3.1 4"}),t("path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})]})},ga="inline-flex items-center gap-1 rounded-md border border-gray-200 dark:border-white/10 px-2 py-1 text-[0.7rem] text-gray-700 dark:text-white/70 transition-colors hover:border-[var(--chat-accent)] hover:text-[var(--chat-accent)] disabled:opacity-50 disabled:cursor-default outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",ma=({artifact:n,t:r,onDownload:a,onRefresh:s,onOpen:l})=>{const[c,d]=o(n),[u,p]=o(null),[h,g]=o(!1);i(()=>d(n),[n]);const m=!!s&&!h&&(e=>"video"===e.kind&&("pending"===e.status||"running"===e.status))(c);i(()=>{if(!m||!s)return;let e=!1;const t=function(e,{intervalMs:t,forMs:n,onGiveUp:r}){let a,o=!1;const s=()=>{a=setTimeout(()=>{e().catch(()=>{}).finally(()=>{o||s()})},t)},i=setTimeout(()=>{o=!0,clearTimeout(a),r?.()},n);return s(),()=>{o=!0,clearTimeout(a),clearTimeout(i)}}(()=>s(c.kind,c.id).then(t=>{!e&&t&&d(t)}),{intervalMs:1e4,forMs:9e5,onGiveUp:()=>g(!0)});return()=>{e=!0,t()}},[m,s,c.kind,c.id]);const f=ha[c.kind],v=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(c.kind,r),w=c.title||v,y=H(c,r),b=function(e,t){if("video"===e.kind){if("running"===e.status)return A(t,"Rendering {progress}%",{progress:Math.round(e.progress??0)});if("pending"===e.status)return t("Waiting to render");if(!(e.downloads.length>0))return"failed"===e.status||"cancelled"===e.status?t("The render did not finish"):t("Not rendered yet")}}(c,r),x=l?null:function(e){if(e.url)try{const t=new URL(e.url);return"http:"===t.protocol||"https:"===t.protocol?t.toString():void 0}catch{return}}(c),k=a?c.downloads:[];return e("div",{role:"group","aria-label":`${v}: ${w}`,className:"flex flex-col gap-2 w-full max-w-[90%] rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] px-3 py-2.5",children:[e("div",{className:"flex items-start gap-2.5 min-w-0",children:[t("span",{className:"shrink-0 mt-0.5 text-[var(--chat-accent)]",children:t(f,{size:18})}),e("span",{className:"flex flex-col min-w-0 flex-1 gap-0.5",children:[t("span",{className:"truncate text-[0.8125rem] font-medium text-gray-900 dark:text-white",children:w}),y&&t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/50",children:y}),b&&e("span",{className:"flex items-center gap-1.5 text-[0.7rem] text-gray-500 dark:text-white/50","aria-live":"polite",children:[m&&t(Hr,{size:10}),b]})]})]}),(x||l||k.length>0)&&e("div",{className:"flex flex-wrap items-center gap-1.5 pl-[28px]",children:[l&&t("button",{type:"button",className:ga,onClick:()=>l(c),children:r("Open")}),x&&e("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:ga,children:[r("Open in XTM One"),t(ar,{size:12})]}),k.map(n=>{const o=function(e,t){return"pdf"===e?"PDF":"mp4"===e?"MP4":"pptx"===e?t("PowerPoint"):"pptx_native"===e?t("PowerPoint (editable)"):e.toUpperCase()}(n,r);return e("button",{type:"button",className:ga,disabled:null!==u,"aria-label":A(r,"Download {format}",{format:o}),onClick:()=>{(async e=>{if(a){p(e);try{await a(c,e)}finally{p(null)}}})(n)},children:[u===n?t(Hr,{size:11}):t(nr,{size:12}),o]},n)})]})]})};function fa(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function va(e){const t=s(null);return i(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const wa="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",ya=({proposal:n,decision:r,onDecide:a,disabled:s,t:i})=>{const[l,c]=o(!1),[d,u]=o(""),h=p(),g=va(l),m=r?.verdict,f=Object.keys(n.arguments??{}),v=e=>{a({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&d.trim()?{rejectionReason:d.trim()}:{}})};return e("div",{"data-testid":"filigran-chat-approval",className:"rounded-lg border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2",children:[e("div",{className:"flex items-start justify-between gap-2",children:[e("div",{className:"min-w-0 flex items-start gap-2",children:[t(zr,{size:13,className:"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400"}),e("div",{className:"min-w-0",children:[t("p",{className:"truncate font-mono text-xs text-gray-800 dark:text-white/85",children:n.toolName||i("unknown tool")}),n.toolDescription&&t("p",{className:"mt-0.5 text-[0.7rem] text-gray-600 dark:text-white/60",children:n.toolDescription}),n.source&&t("p",{className:"mt-0.5 text-[0.65rem] text-gray-400 dark:text-white/35",children:n.source})]})]}),m&&t("span",{className:"shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===m?"bg-red-500/15 text-red-600 dark:text-red-300":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"),children:i("reject"===m?"Declined":"approve_always"===m?"Always allowed":"Approved")})]}),f.length>0&&t("div",{className:"flex flex-col gap-1.5",children:f.map(r=>{const a=function(e,t){const n=e?.properties;if(!n||"object"!=typeof n)return{};const r=n[t];if(!r||"object"!=typeof r)return{};const a=r;return{description:"string"==typeof a.description?a.description:void 0,type:"string"==typeof a.type?a.type:void 0}}(n.inputSchema,r);return e("div",{className:"text-[0.7rem]",children:[e("div",{className:"flex flex-wrap items-baseline gap-1.5",children:[t("span",{className:"font-mono text-gray-700 dark:text-white/75",children:r}),a.description&&e("span",{className:"text-gray-500 dark:text-white/45",children:["— ",a.description]})]}),t("pre",{className:"mt-0.5 whitespace-pre-wrap break-all font-mono text-gray-600 dark:text-white/60",children:fa(n.arguments?.[r])})]},r)})}),!m&&l&&e("div",{ref:g,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:h,className:"text-[0.7rem] text-gray-500 dark:text-white/45",children:i("Why not? The agent sees this and can adapt (optional)")}),t("textarea",{id:h,autoFocus:!0,rows:2,value:d,onChange:e=>u(e.target.value),placeholder:i("e.g. wrong environment — use staging instead"),className:"w-full resize-none rounded-md border border-gray-200 bg-white px-2 py-1 text-[0.7rem] text-gray-800 outline-none focus:border-[var(--chat-accent)]/50 dark:border-white/10 dark:bg-white/[0.03] dark:text-white/85"}),e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>v("reject"),className:`${wa} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(Or,{size:13}),i("Decline this call")]}),t("button",{type:"button",disabled:s,onClick:()=>{c(!1),u("")},className:`${wa} text-gray-500 hover:bg-gray-100 dark:text-white/50 dark:hover:bg-white/5`,children:i("Back")})]})]}),!m&&!l&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>c(!0),className:`${wa} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(Or,{size:13}),i("No")]}),e("button",{type:"button",disabled:s,onClick:()=>v("approve"),className:`${wa} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(Jn,{size:13}),i("Yes")]}),t("button",{type:"button",disabled:s,onClick:()=>v("approve_always"),title:i("Also applies to your scheduled runs, until you revoke it"),className:`${wa} border border-gray-200 text-gray-700 hover:bg-gray-100 dark:border-white/15 dark:text-white/70 dark:hover:bg-white/5`,children:i("Yes, always")})]})]})},ba=({proposals:n,onSubmit:r,isSubmitting:a,error:l,t:c})=>{const[d,u]=o({}),p=s(!1),[h,g]=o(!1);i(()=>{l&&(p.current=!1,g(!1))},[l]);const m=a||h,f=e=>{p.current||a||(p.current=!0,g(!0),r(e))},v=n.filter(e=>d[e.toolCallId]).length,w=v===n.length&&n.length>0,y=Object.values(d).some(e=>"approve_always"===e.verdict),b=va(y),x=va(!0);return e("div",{ref:x,className:"flex flex-col gap-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.02] p-3",children:[e("p",{className:"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300",children:[t(qn,{size:13,className:"mt-0.5 shrink-0"}),1===n.length?c("The agent needs your approval to run a tool:"):c("The agent needs your approval to run these tools:")]}),n.map(e=>t(ya,{proposal:e,decision:d[e.toolCallId],disabled:m,t:c,onDecide:e=>{const t={...d,[e.toolCallId]:e};u(t);const r=n.map(e=>t[e.toolCallId]);r.every(Boolean)&&!r.some(e=>"approve_always"===e.verdict)&&f(r)}},e.toolCallId)),y&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(qn,{size:13,className:"mt-0.5 shrink-0"}),c("“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.")]}),l&&t("p",{className:"text-[0.7rem] text-red-600 dark:text-red-300",children:l}),e("div",{ref:b,className:"flex items-center justify-between gap-2",children:[t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40",children:n.length>1?A(c,"{decided}/{total} decided",{decided:v,total:n.length}):""}),t("button",{type:"button",disabled:!w||m,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${wa} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:c(m?"Sending…":"Confirm")})]})]})},xa=({src:n,alt:r,onClose:a,t:l})=>{const c=s(null),d=s(null),[u,p]=o(null);return i(()=>{p(_(c.current))},[]),i(()=>{const e=e=>{"Escape"===e.key&&a()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[a]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return d.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]),t("span",{ref:c,className:"hidden",children:u&&b(e("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4",onClick:a,role:"dialog","aria-modal":"true","aria-label":l("Image preview"),children:[t("button",{ref:d,type:"button",onClick:a,"aria-label":l("Close"),className:"absolute top-4 right-4 rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(Zn,{size:20})}),t("img",{src:n,alt:r,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},ka=({src:r,alt:a,requestHeaders:s,maxHeightClass:l="max-h-[400px]",t:c})=>{const d=!!s&&Object.keys(s).length>0&&(e=>!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(r),[u,p]=o(null),[h,g]=o(!1),[m,f]=o(!1),v=Ot();i(()=>{if(!d)return;let e=!1,t=null;return v(r,{credentials:"include",headers:{...s}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(n=>{e||(t=URL.createObjectURL(n),p(t))}).catch(()=>{e||g(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,r,s]);const w=d?u:r;return h?t("p",{className:"my-2 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:c("Image could not be loaded")}):w?e(n,{children:[e("span",{className:"group/img relative my-3 inline-block max-w-full rounded-lg border border-gray-200 p-1 transition-colors hover:border-[var(--chat-accent)]/40 dark:border-white/10",children:[t("img",{src:w,alt:a,loading:"lazy",onClick:()=>f(!0),onError:()=>g(!0),className:`max-w-full cursor-zoom-in rounded-md object-contain ${l}`}),t("button",{type:"button",onClick:()=>f(!0),"aria-label":c("Expand image"),className:"absolute top-2 right-2 rounded-md bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100",children:t(wr,{size:14})})]}),m&&t(xa,{src:w,alt:a,onClose:()=>f(!1),t:c})]}):e("span",{className:"my-3 inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 dark:border-white/10",children:[t(mr,{size:14,className:"shrink-0 animate-pulse text-[var(--chat-accent)]"}),t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40",children:c("Loading image…")})]})};const Na="inline-flex items-center gap-1.5 self-start rounded text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100",Ca=({t:n,enabled:r=!0,onPlay:a,playUrl:s,keepEndInView:l,messages:c,content:d})=>{const p=u(()=>c&&c.length>0?c:(e=>[e("Crunching the data"),e("Connecting the dots"),e("Consulting the sources"),e("Thinking it through"),e("Reticulating splines"),e("Analyzing the details"),e("Almost there"),e("Putting it together"),e("Polishing the answer"),e("Wrapping things up")])(n),[c,n]),h=function(){const[e,t]=o(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return i(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=()=>t(e.matches);return"function"==typeof e.addEventListener?(e.addEventListener("change",n),()=>e.removeEventListener("change",n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}(),[g,m]=o(0);if(i(()=>{r&&l()},[r,l]),i(()=>{if(!r||d)return;const e=window.setInterval(()=>m(e=>(e+1)%p.length),2600);return()=>window.clearInterval(e)},[r,p.length,!!d]),!r)return null;if(d)return t("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:d});const f=p[g%p.length];return e("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:f}),e("div",{className:"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5",style:h?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[e("span",{"aria-hidden":!0,className:"text-xs text-gray-500 dark:text-white/45",style:h?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[f,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(h?"":"animate-pulse")})]},f),a?e("button",{type:"button",onClick:a,className:Na,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(pr,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:Na,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(pr,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(ar,{size:11})})]}):null]})]})};function Sa(e,t){return e>1?A(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function Ia(e,t){return e>1?A(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function Ta(e,t){return e>1?A(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function Aa(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:Kn,showDots:!1};switch(e.status){case"tool_start":{const n=e.tools??[],r=n.map(e=>e.toLowerCase());if(r.some(e=>"spawn_background_task"===e)){return{label:Sa(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:Rr,showDots:!1}}if(r.some(e=>"check_task_status"===e)){return{label:Ia(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:Tr,showDots:!1}}if(r.some(e=>"get_task_result"===e)){return{label:Ta(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:Tr,showDots:!1}}let a,o=zr;if(r.some(e=>e.includes("search")||e.includes("list"))?o=Cr:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?o=er:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?o=vr:r.some(e=>e.includes("code")||e.includes("execute"))?o=_r:r.some(e=>e.includes("web")||e.includes("browse"))&&(o=hr),n.length>0){const e=n.map(e=>e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())),r=Array.from(new Set(e));a=1===r.length?`${r[0]}…`:A(t,"{tool} (+{count} more)…",{tool:r[0],count:r.length-1})}else a=t("Using tools…");return{label:a,StatusIcon:o,showDots:!1}}case"awaiting_approval":return{label:t("Waiting for your approval…"),StatusIcon:qn,showDots:!1};case"cancelling":return{label:t("Stopping…"),StatusIcon:Kn,showDots:!0};case"reconnecting":return{label:t("Reconnecting…"),StatusIcon:Kn,showDots:!0};case"wait_start":return{label:e.waitReason||t("Waiting before continuing…"),StatusIcon:Tr,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:Tr,showDots:!0};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:Tr,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:Tr,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:Kn,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Consulting {agent}…",{agent:n}),StatusIcon:Rr,showDots:!1}}case"delegating":return{label:Sa(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:Rr,showDots:!1};case"polling":return{label:Ia(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:Tr,showDots:!1};case"collecting":return{label:Ta(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:Tr,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Transferring to {agent}…",{agent:n}),StatusIcon:ar,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:Kn,showDots:!1}}}function _a(e,t,n){return e&&n?.(e)||Aa(e,t).label}function Ea(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/#{1,6}\s+/g,"").replace(/^[ \t]*[-*>]+[ \t]*/gm,"").replace(/[ \t]+/g," ").replace(/\n{3,}/g,"\n\n").trim()}function Ma({text:e}){const n=s(null),[r,a]=o(!1);return i(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight,a(e.scrollHeight>e.clientHeight+1))},[e]),t("div",{className:"filigran-chat-reasoning ml-11 mt-2.5 max-w-[75%] rounded-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3",children:t("div",{ref:n,className:"max-h-40 overflow-hidden"+(r?" [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)] [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]":""),children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-xs leading-5 text-gray-500 dark:text-white/45",children:e})})})}function La(e){const t=Math.floor(e);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Ra(e,t,n=0){const[r,a]=o(null);return i(()=>{if(a(null),!e)return;const r=window.setTimeout(()=>a(n),t);return()=>window.clearTimeout(r)},[e,t,n]),e&&r===n}const $a=({agentStatus:r,logoIcon:a,t:s,miniGameEnabled:l=!0,onPlayWaitingGame:c,waitingGameUrl:d,keepEndInView:p,onSkipWait:h,statusLabel:g,waitingMessages:m,renderWaitingPanel:f})=>{const v=Aa(r,s),{StatusIcon:w,showDots:y}=v,b=_a(r,s,g),x=r?.thinkingContent,k=r?.elapsedStartMs,N="wait_start"===r?.status?r.waitStartMs:void 0,C=k??N,[S,I]=o(()=>Date.now());i(()=>{if(null==C)return;I(Date.now());const e=window.setInterval(()=>I(Date.now()),1e3);return()=>window.clearInterval(e)},[C]);const T=r?.waitSeconds,A=null!=N&&null!=T?Math.max(0,T-(S-N)/1e3):void 0,_=null!=k?Math.max(0,(S-k)/1e3):r?.elapsedS,E="number"==typeof _&&_>=15,M=u(()=>function(e){if(e.length<=6e3)return Ea(e);const t=[];let n=0;for(let r=e.indexOf("```");-1!==r;r=e.indexOf("```",n)){const a=e.indexOf("```",r+3);if(-1===a)break;t.push([n,r]),n=a+3}t.push([n,e.length]);const r=[];let a=6e3;for(let n=t.length-1;n>=0&&a>0;n--){const[o,s]=t[n],i=Math.max(o,s-a);r.push(e.slice(i,s)),a-=s-i+1}let o=r.reverse().join(" ");if(a<=0){const e=o.indexOf("\n\n");-1!==e&&e<o.length/2&&(o=o.slice(e+2))}return Ea(o)}(x??""),[x]),L=M.length>=3,R=Ra(l&&!L,5e3),$=Ra(l&&L,1e4,x?.length??0),D=L?$:R;return e(n,{children:[e("div",{className:"flex gap-3 items-center justify-start",children:[t("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:a})}),e("div",{className:"filigran-chat-active-border rounded-lg bg-gray-50 dark:bg-white/[0.03] px-4 py-3 relative overflow-hidden",children:[t("div",{className:"absolute inset-0 bg-gradient-to-r from-[var(--chat-accent)]/[0.03] via-transparent to-[var(--chat-accent)]/[0.03] animate-pulse pointer-events-none"}),e("div",{className:"relative flex items-center gap-2.5",children:[y?t("div",{className:"flex gap-[3px] items-center h-3.5 w-3.5 justify-center",children:[0,.15,.3].map((e,n)=>t("span",{className:"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50",style:{animation:`chat-dot 1s ease-in-out infinite ${e}s`}},n))}):t(w,{size:14,className:"text-[var(--chat-accent)] animate-pulse transition-all duration-300"}),t("span",{className:"text-sm text-gray-500 dark:text-white/50 transition-all duration-300",children:b}),void 0!==A?t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:La(Math.ceil(A))}):E&&t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:La(_)}),"wait_start"===r?.status&&h&&t("button",{type:"button",onClick:h,className:"ml-1 shrink-0 rounded-md border border-[var(--chat-accent)]/40 px-2 py-0.5 text-xs text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors",children:s("Continue now")})]})]})]}),D?t(Ca,{t:s,enabled:l,onPlay:c,playUrl:d,keepEndInView:p,messages:m,content:f?.()}):L?t(Ma,{text:M}):null]})};class Da extends h{state={failed:!1,resetKey:this.props.resetKey};static getDerivedStateFromError(){return{failed:!0}}static getDerivedStateFromProps(e,t){return e.resetKey===t.resetKey?null:{failed:!1,resetKey:e.resetKey}}componentDidCatch(e,t){console.error(`${this.props.label} failed to render`,e,t.componentStack)}render(){return this.state.failed?this.props.fallback:this.props.children}}function ja({draw:e}){return t(n,{children:e()})}function za({t:e}){return t("p",{className:"pl-1 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:e("This item could not be loaded.")})}const Oa=y().use(w).use(v).freeze();function Pa(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(Pa);default:return!1}}function Ua(e,t){return e.lastIndexOf("\n",t-1)+1}function Ha(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Ua(e,t-1),t-1).trim()}function Wa(e,t,n){const r=e.slice(t,n).split("\n");for(let e=r.length-1;e>=0;e--)if(r[e].trim())return/^(?: {4}|\t)/.test(r[e]);return!1}class qa{last=null;split(e){return this.last?.source!==e&&(this.last=function(e,t){if(!e.trim())return function(e){return{source:e,blocks:e?[e]:[],starts:e?[0]:[],settled:0,firstDefinition:-1}}(e);const n=t&&t.settled>0&&e.startsWith(t.source)?t.settled:0,r=n?t.starts[n]:0,a=e.slice(r),o=t&&n?t.starts.slice(0,n):[];let s=t&&n&&t.firstDefinition<n?t.firstDefinition:-1;o.push(r);for(const t of Oa.parse(a).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Ua(a,n),s=o[o.length-1];t>s&&!Wa(e,s,t)&&o.push(t)}s<0&&Pa(t)&&(s=o.length-1)}let i=n;for(let t=o.length-1;t>n;t--)if(Ha(e,o[t])){i=t;break}const l=s<0?o.map((t,n)=>e.slice(t,o[n+1]??e.length)):[e];return{source:e,blocks:l,starts:o,settled:i,firstDefinition:s}}(e,this.last)),this.last.blocks}}const Ba=r({copiedBlock:null,onCopyCode:()=>{},streaming:!1,t:T});function Fa({draw:e,block:r}){const a=e();return null==a||!1===a?t(n,{children:r}):t("div",{className:"my-3",children:a})}const Va={p:({children:e})=>t("p",{className:"mb-3 last:mb-0 leading-7 break-words text-[0.8125rem] text-gray-900 dark:text-white/90",children:e}),pre:({children:e})=>t(n,{children:e}),code:({className:n,children:r})=>{const{copiedBlock:o,onCopyCode:s,codeBlockRenderers:i,streaming:l,t:c}=a(Ba),d=/(?:^|\s)language-(\S+)/.exec(n||""),u=String(r).replace(/\n$/,""),p=d?i?.[d[1].toLowerCase()]:void 0;if(d||u.includes("\n")){const n=e("div",{className:"my-3 rounded-lg border border-gray-200 dark:border-white/10 overflow-hidden bg-gray-50 dark:bg-white/[0.03]",children:[e("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-gray-200 dark:border-white/10 bg-gray-100 dark:bg-white/[0.03]",children:[t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 font-mono",children:d?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>s(u),"aria-label":c(o===u?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors",children:o===u?t(Jn,{size:14,className:"text-green-500"}):t(Qn,{size:14,className:"text-gray-400 dark:text-white/40"})})]}),t("pre",{className:"m-0 px-3 py-2 overflow-x-auto",children:t("code",{className:"font-mono text-xs leading-[1.7] text-gray-800 dark:text-white/90 whitespace-pre",children:u})})]});return p?t(Da,{label:"A chat code block renderer",resetKey:`${u}\0${l}`,fallback:t(za,{t:c}),children:t(Fa,{draw:()=>p(u,{streaming:l}),block:n})}):n}return t("code",{className:"bg-gray-100 dark:bg-white/[0.08] px-1.5 py-0.5 rounded-sm font-mono text-xs text-[var(--chat-accent)]",children:r})},ul:({children:e})=>t("ul",{className:"list-disc pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),ol:({children:e})=>t("ol",{className:"list-decimal pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),li:({children:e})=>t("li",{className:"leading-7 break-words",children:e}),strong:({children:e})=>t("strong",{className:"font-semibold text-gray-900 dark:text-white",children:e}),em:({children:e})=>t("em",{className:"italic",children:e}),hr:()=>t("hr",{className:"my-4 border-gray-200 dark:border-white/10"}),blockquote:({children:e})=>t("blockquote",{className:"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 rounded-r-md italic text-gray-500 dark:text-white/60",children:e}),a:({href:e,children:n})=>{const{onRelativeLinkClick:r}=a(Ba),o=Ve(e),s=null!==o&&!!r,i=!(s||(e=>!!e&&!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e)&&null!==o);return t("a",{href:e,onClick:e=>{s&&(e.preventDefault(),r(o))},target:i?"_blank":void 0,rel:i?"noopener noreferrer":void 0,className:"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125",children:n})},img:({src:e,alt:n})=>{const{requestHeaders:r,t:o}=a(Ba);return"string"==typeof e&&e?t(ka,{src:e,alt:n||"",requestHeaders:r,t:o},e):null},h1:({children:e})=>t("h1",{className:"mt-4 first:mt-0 mb-2 font-bold text-base text-gray-900 dark:text-white",children:e}),h2:({children:e})=>t("h2",{className:"mt-3 first:mt-0 mb-2 font-bold text-[0.9rem] text-gray-900 dark:text-white",children:e}),h3:({children:e})=>t("h3",{className:"mt-3 first:mt-0 mb-1.5 font-semibold text-[0.85rem] text-gray-900 dark:text-white",children:e}),table:({children:e})=>t("div",{className:"my-3 overflow-x-auto rounded-lg border border-gray-200 dark:border-white/10",children:t("table",{className:"w-full border-collapse text-xs",children:e})}),tr:({children:e})=>t("tr",{className:"transition-colors hover:bg-gray-50 dark:hover:bg-white/[0.02]",children:e}),th:({children:e})=>t("th",{className:"px-3 py-2 text-left font-semibold bg-gray-50 dark:bg-white/[0.04] border-b border-gray-200 dark:border-white/10 text-gray-900 dark:text-white",children:e}),td:({children:e})=>t("td",{className:"px-3 py-2 border-b border-gray-200 dark:border-white/10 text-gray-700 dark:text-white/80",children:e})},Ka=[v,k],Ga=g(({source:e})=>t(x,{remarkPlugins:Ka,urlTransform:I,components:Va,children:e}));Ga.displayName="MarkdownBody";const Ja=({source:e})=>{const[r]=o(()=>new qa),a=u(()=>r.split(e),[r,e]);return t(n,{children:a.map((e,n)=>t(Ga,{source:e},n))})},Ya=g(({codeBlockRenderers:e,...n})=>{const{content:r,streaming:a=!1,onRelativeLinkClick:s,requestHeaders:i,t:c=T}=n,[d,p]=o(null),[h,g]=o(a);a&&!h&&g(!0);const m=u(()=>C(r),[r]),f=l(e=>{navigator.clipboard.writeText(e),p(e),setTimeout(()=>p(null),2e3)},[]),v=u(()=>({copiedBlock:d,onCopyCode:f,onRelativeLinkClick:s,requestHeaders:i,codeBlockRenderers:e,streaming:a,t:c}),[d,f,s,i,e,a,c]);return t(Ba.Provider,{value:v,children:t(h?Ja:Ga,{source:m})})});Ya.displayName="MarkdownMessage";function Xa(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Za(e){return e.replace(/_/g," ")}const Qa=({entry:n,index:r,t:a})=>{const[s,i]=o(!1),l=u(()=>Xa(n.input),[n.input]),c=u(()=>Xa(n.output),[n.output]),d=!!l&&"{}"!==l;return e("div",{className:"border border-gray-200 dark:border-white/[0.06] rounded-md overflow-hidden",children:[e("button",{type:"button",onClick:()=>i(e=>!e),"aria-expanded":s,className:"w-full flex items-center gap-2.5 px-3 py-2 hover:bg-gray-50 dark:hover:bg-white/[0.03] transition-colors text-left",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),n.success?t(Gn,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(Or,{size:12,className:"shrink-0 text-red-500 dark:text-red-400"}),t("span",{className:"flex-1 min-w-0 text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono",children:Za(n.name)}),t(Yn,{size:14,className:"shrink-0 text-gray-400 dark:text-white/50 transition-transform duration-200 "+(s?"rotate-180":"")})]}),s&&e("div",{className:"border-t border-gray-200 dark:border-white/[0.06]",children:[d&&e("div",{className:"px-3 py-2 border-b border-gray-100 dark:border-white/[0.04] bg-gray-50/50 dark:bg-white/[0.01]",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium",children:a("Input")}),t("pre",{className:"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable",children:l})]}),e("div",{className:"px-3 py-2 bg-gray-50/50 dark:bg-white/[0.01]",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium",children:a("Output")}),t("pre",{className:"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable",children:c||a("(no output)")})]})]})]})},eo=({msg:n,onClose:r,t:a})=>{const l=s(null),c=s(null),d=s(null),[u,p]=o(null);i(()=>{p(_(l.current))},[]),i(()=>{const e=e=>{if("Escape"===e.key)return void r();if("Tab"!==e.key)return;const t=d.current;if(!t)return;const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const a=n[0],o=n[n.length-1],s=document.activeElement;e.shiftKey?s!==a&&t.contains(s)||(e.preventDefault(),o.focus()):s!==o&&t.contains(s)||(e.preventDefault(),a.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return c.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]);const h=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,g=n.toolNames??[],m=n.iterations??1,f=n.transferChain??[],v=n.toolCallTrace??[],w=(n.reasoning??"").trim(),y=[m>1?A(a,"{count} iterations",{count:m}):"",1===h?a("1 tool call"):A(a,"{count} tool calls",{count:h}),1===f.length?a("1 transfer"):f.length>1?A(a,"{count} transfers",{count:f.length}):""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:u&&b(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:r,role:"presentation",children:e("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":a("Reasoning details"),onClick:e=>e.stopPropagation(),className:"w-full max-w-md max-h-full flex flex-col rounded-xl border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1e1e2e] shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]",children:[e("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-gray-200 dark:border-white/10",children:[e("div",{className:"flex items-center gap-2",children:[t(zr,{size:15,className:"text-[var(--chat-accent)]"}),t("span",{className:"flex-1 text-[0.875rem] font-semibold text-gray-900 dark:text-white",children:a("Reasoning details")}),t("button",{ref:c,type:"button",onClick:r,"aria-label":a("Close"),className:"w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(Zn,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] text-gray-500 dark:text-white/40",children:y.join(" · ")})]}),e("div",{className:"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3",children:[n.isTruncated&&e("div",{className:"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90",children:[t(qn,{size:14,className:"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400"}),e("span",{children:[t("span",{className:"font-semibold",children:a("Turn limit reached.")})," ",a("The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.")]})]}),w&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Kn,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:a("Model reasoning")})]}),t("div",{className:"rounded-md border border-gray-200 dark:border-white/[0.06] bg-gray-50/50 dark:bg-white/[0.01] px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable",children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 text-gray-500 dark:text-white/45",children:Ea(w)})})]}),v.length>0?t("div",{className:"flex flex-col gap-1.5",children:v.map((e,n)=>t(Qa,{entry:e,index:n,t:a},`${e.name}-${n}`))}):g.length>0&&t("div",{children:g.map((n,r)=>e("div",{className:"flex items-center gap-3 py-2 border-b border-gray-100 dark:border-white/[0.04] last:border-0",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),t(zr,{size:12,className:"shrink-0 text-gray-400 dark:text-white/50"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono",children:Za(n)})]},`${n}-${r}`))}),f.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Bn,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:a("Transfer chain")})]}),t("div",{className:"flex items-center gap-1.5 flex-wrap",children:f.map((n,r)=>e("div",{className:"flex items-center gap-1.5",children:[r>0&&t("span",{className:"text-gray-300 dark:text-white/30 text-[0.72rem]",children:"→"}),e("span",{className:"inline-flex items-center gap-1 rounded-md bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]",children:[t(Vn,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},to=e=>e.parentElement,no=e=>getComputedStyle(e).overflowY;function ro(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function ao(e){const t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return;const n=e.slice(t+1);return n.length<=8?n.toUpperCase():void 0}const oo=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const so="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",io="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",lo="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",co=`opacity-0 ${so} ${lo}`,uo=`opacity-50 ${so} ${lo}`,po="opacity-100 text-[var(--chat-accent)]",ho=({timestamp:n,locale:r})=>{const a=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:la(t,(a=n,(r=e).getFullYear()===a.getFullYear()&&r.getMonth()===a.getMonth()&&r.getDate()===a.getDate()?"time":e.getFullYear()===n.getFullYear()?"date":"dateWithYear")).format(e),full:la(t,"full").format(e),iso:e.toISOString()}:null;var r,a}(n,r);return a?t(qr,{title:a.full,children:e("time",{dateTime:a.iso,className:"px-1 text-[0.65rem] tabular-nums text-gray-400 dark:text-white/40 select-none",children:[t("span",{"aria-hidden":"true",children:a.label}),t("span",{className:"sr-only",children:a.full})]})}):null},go=({text:e,label:n,t:r})=>{const[a,s]=o(!1),i=a?r("Copied!"):n;return t(qr,{title:i,children:t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),s(!0),setTimeout(()=>s(!1),2e3)}catch{}},"aria-label":i,className:`${io} ${a?"opacity-100 text-green-500 dark:text-green-400":co}`,children:t(a?Jn:Qn,{size:14})})})},mo=({value:r,locked:a,pending:o,onChange:s,downRef:i,t:l})=>{const c=p(),d=a||o,u=(e,n)=>{const o=r===e;if(a&&!o)return null;const u="up"===e?Mr:Er;return t(qr,{title:a?l("Feedback already submitted"):n,children:t("button",{ref:"down"===e?i:void 0,type:"button",onClick:()=>{d||s(o?null:e)},"aria-label":n,"aria-pressed":o,"aria-disabled":d||void 0,"aria-describedby":a?c:void 0,className:`${io} ${o?po:co} ${d?"cursor-default":""}`,children:t(u,{size:14,filled:o})})})};return e(n,{children:[u("up",l("Good response")),u("down",l("Bad response")),a&&t("span",{id:c,className:"sr-only",children:l("Feedback already submitted")})]})},fo=({pending:n,onSave:r,onSkip:a,t:s})=>{const[i,l]=o(""),c=p(),d=!n&&!!i.trim();return e("div",{className:"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] p-2",children:[t("label",{htmlFor:c,className:"text-[0.7rem] text-gray-600 dark:text-white/60",children:s("Tell us what went wrong (optional)")}),t("textarea",{id:c,autoFocus:!0,rows:2,maxLength:2e3,value:i,readOnly:n,onChange:e=>l(e.target.value),onKeyDown:e=>{"Escape"===e.key?(e.preventDefault(),e.stopPropagation(),n||a()):"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),d&&r(i))},placeholder:s("What could be improved?"),className:"w-full resize-y rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-transparent px-2 py-1 text-[0.75rem] leading-5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]"}),e("div",{className:"flex justify-end gap-1.5",children:[t("button",{type:"button",onClick:()=>{n||a()},"aria-disabled":n||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:s("Skip")}),t("button",{type:"button",onClick:()=>{d&&r(i)},"aria-disabled":!d||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] "+(d?"hover:opacity-90":"opacity-50 cursor-default"),children:s("Save")})]})]})},vo=({speaking:e,onToggle:n,t:r})=>{const a=r(e?"Stop reading":"Read aloud");return t(qr,{title:a,children:t("button",{type:"button",onClick:n,"aria-label":a,className:`${io} ${e?po:co}`,children:t(e?jr:Dr,{size:14})})})},wo=[],yo=new Set(["PRESENTATION","REPORT","VIDEO"]),bo=g(({msg:r,isStreaming:a,agentName:i,logoIcon:l,onRelativeLinkClick:c,onDownloadFile:p,resolveAttachmentUrl:h,onDownloadArtifact:g,onRefreshArtifact:m,requestHeaders:f,feedbackMode:v,feedback:w,onRate:y,onSaveComment:b,onSkipComment:x,locale:k,canSpeak:N,isSpeaking:C,onToggleSpeech:S,openableConversationIds:I,onOpenConversation:T,markerRenderers:A,markerKindList:_=wo,codeBlockRenderers:E,transformMessageText:M,onArtifactOpen:L,renderMessageExtras:R,messageFooterActions:$,t:D})=>{const[j,H]=o(!1),W="assistant"===r.role,q=u(()=>Lt(M,r.content,r)??r.content,[M,r]),B=u(()=>W?"":function(e){return e.trimEnd().replace(/^(?:[ \t]*\r?\n)+/,"")}(q),[W,q]),F=!q,V=s(null),K=!!w?.commentOpen,J=s(K);d(()=>{const e=J.current&&!K;J.current=K,!e||document.activeElement&&document.activeElement!==document.body||V.current?.focus()},[K]);const Y=(n,r)=>{const a=h&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&oo.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&oo.has(e.filename.slice(n+1).toLowerCase())}(n)?h(n):void 0;if(a)return t(ka,{src:a,alt:n.filename,requestHeaders:f,maxHeightClass:"max-h-[200px]",t:D},r);const o="working_file"===n.fileTag,s=!(i=n.size)||i<=0?"":i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(0)} KB`:`${(i/1048576).toFixed(1)} MB`;var i;return e("button",{type:"button",onClick:()=>p?.(n),title:D("Download"),className:"group flex items-center gap-2 text-left rounded-lg border px-2.5 py-1.5 transition-colors cursor-pointer max-w-[90%] "+(o?"border-gray-200 dark:border-white/10 bg-transparent":"border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5"),children:[t("span",{className:"shrink-0 "+(o?"text-gray-400 dark:text-white/40":"text-[var(--chat-accent)]"),children:t(or,{size:16})}),e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"truncate text-[0.75rem] text-gray-900 dark:text-white",children:n.filename}),(n.type||s)&&t("span",{className:"text-[0.65rem] text-gray-400 dark:text-white/40 uppercase",children:[n.type,s].filter(Boolean).join(" · ")})]}),t("span",{className:"shrink-0 text-gray-400 dark:text-white/30 group-hover:text-[var(--chat-accent)]",children:t(nr,{size:15})})]},r)},X=(n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.7rem] text-gray-600 dark:text-white/60",children:[t(or,{size:14}),n]},r),Z=(e,n)=>t(ma,{artifact:e,t:D,onDownload:g,onRefresh:m,onOpen:L},n),Q=(e,n,o)=>{const s=A?.[e];return!s||a&&!s.renderWhileStreaming?null:t("div",{className:s.fullWidth?"w-full":"w-full max-w-[90%]",children:t(Da,{label:"A chat marker card",resetKey:`${n}\0${a}`,fallback:t(za,{t:D}),children:t(ja,{draw:()=>s.render(n,{message:r,streaming:a})})})},o)},ee=r.toolNames&&r.toolNames.length>0||!!(r.reasoning??"").trim()||r.toolCallTrace&&r.toolCallTrace.length>0||r.transferChain&&r.transferChain.length>0||r.isTruncated,te=W&&!F&&!a,ne=function(e,t=[]){if(!e)return e;const n=z(t),r=e.replace(n.complete,"").replace(n.partial,"");return r===e?e:r.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}(q,_),re=u(()=>te&&N?P(q,_):null,[te,N,q,_]),ae=(oe=w,se=r.feedback,oe?{value:oe.value,locked:!1}:se?{value:(ie=se.rating,"positive"===ie?"up":"down"),locked:!0}:{value:null,locked:!1});var oe,se,ie;const le=aa(r);return e("div",{"data-message-id":r.serverId??r.id,className:"group/msg flex flex-col "+(W?"items-start":"items-end"),children:[W&&e("div",{className:"flex items-center gap-1.5 mb-1",children:[t("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3",children:l})}),t("span",{className:"font-semibold text-xs text-gray-900 dark:text-white",children:r.agentName??i})]}),!W&&((r.files?.length??0)>0||(r.attachments?.length??0)>0)&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end",children:(()=>{const e=[],t=new Set;return(r.files??[]).forEach((n,r)=>{!(!p||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(Y({fileId:n.fileId,filename:n.name,type:ao(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(X(n.name,`file-${r}`))}),(r.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(p?Y(n,`att-${n.fileId}-${r}`):X(n.filename,`att-${r}`)))}),e})()}),!W&&(r.conversationRefs?.length??0)>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end max-w-[90%]",children:r.conversationRefs.map((r,a)=>{const o=r.title||(r.key?`@${r.key}`:D("Untitled conversation")),s="inline-flex items-center gap-1 max-w-[240px] px-2 py-0.5 rounded-full border text-[0.7rem]",i=e(n,{children:[t(yr,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:o})]});return T&&I?.has(r.conversationId)?t(qr,{title:D("Open conversation"),children:t("button",{type:"button",onClick:()=>T(r.conversationId),className:`${s} border-[var(--chat-accent-40)] text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]`,children:i})},`ref-${r.conversationId}-${a}`):t(qr,{title:r.key?`@${r.key}`:"",children:t("span",{className:`${s} border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60`,children:i})},`ref-${r.conversationId}-${a}`)})}),W?e("div",{"data-testid":"filigran-chat-assistant-message",className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=O(q,a,_),n=new Map((r.attachments??[]).map(e=>[e.fileId,e])),o=new Map((r.artifacts??[]).map(e=>[U(e.kind,e.id),e])),s=new Set,i=new Set,l=[];return e.forEach((e,r)=>{if("text"===e.type)e.value.trim()&&l.push(t("div",{className:"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7",children:t(Ya,{content:e.value,streaming:a,onRelativeLinkClick:c,requestHeaders:f,codeBlockRenderers:E,t:D})},`t-${r}`));else if("marker"===e.type){"FILE"===e.kind?s.add(e.args):yo.has(e.kind)&&i.add(U(e.kind.toLowerCase(),e.args.split("#/")[0]));const t=Q(e.kind,e.args,`m-${e.kind}-${r}`);t&&l.push(t)}else if("artifact"===e.type){const t=U(e.kind,e.id),n=o.get(t);n&&!i.has(t)&&(i.add(t),l.push(Z(n,`a-${t}-${r}`)))}else if(p){const t=n.get(e.fileId);t&&(s.add(e.fileId),l.push(Y(t,`f-${e.fileId}-${r}`)))}}),(r.artifacts??[]).forEach(e=>{const t=U(e.kind,e.id);if(!i.has(t)){i.add(t);const n=e.kind.toUpperCase();if(A?.[n]){const r=Q(n,e.slideRef?`${e.id}#/${e.slideRef}`:e.id,`orphan-a-${t}`);r&&l.push(r)}else l.push(Z(e,`orphan-a-${t}`))}}),(r.attachments??[]).forEach(e=>{if(!s.has(e.fileId))if(A?.FILE){const t=Q("FILE",e.fileId,`orphan-${e.fileId}`);t&&l.push(t)}else p&&l.push(Y(e,`orphan-${e.fileId}`))}),0!==l.length||a||r.stopped||l.push(t("span",{className:"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic",children:"..."},"empty")),l})(),r.stopped&&!a&&t("p",{className:"pl-1 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:D("Stopped")}),!F&&a&&t("span",{className:"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse"})]}):t("div",{"data-testid":"filigran-chat-user-message",className:"max-w-[90%] px-3.5 py-2 rounded-[14px_14px_4px_14px] bg-[var(--chat-accent-dark)] text-white text-[0.8125rem] leading-6 whitespace-pre-wrap break-words",children:B}),R&&t("div",{className:"w-full "+(W?"":"flex justify-end"),children:R(r,{streaming:a})}),!W&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 text-gray-400 dark:text-white/40",children:[!!B&&t(go,{text:B,label:D("Copy message"),t:D}),!r.timestampUnknown&&t(ho,{timestamp:r.timestamp,locale:k})]}),te&&e("div",{className:"mt-0.5 flex flex-wrap items-center gap-0.5 text-gray-400 dark:text-white/40",children:[!r.timestampUnknown&&t(ho,{timestamp:r.timestamp,locale:k}),ee&&t(qr,{title:r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),children:t("button",{type:"button",onClick:()=>H(e=>!e),className:`${io} ${r.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":uo}`,"aria-label":r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":j,children:r.isTruncated?t(qn,{size:14}):t(fr,{size:14})})}),t(go,{text:ne,label:D("Copy response"),t:D}),v&&t(mo,{value:ae.value,locked:ae.locked,pending:!!w?.pending,onChange:e=>y(r,e,w),downRef:V,t:D}),re&&(ce=re,ce.some(e=>/[\p{L}\p{N}]/u.test(e.replace(G,""))))&&t(vo,{speaking:C,onToggle:()=>S(le,re),t:D}),$?.(r,{streaming:a})]}),te&&w?.commentOpen&&t(fo,{pending:w.pending,onSave:e=>b(r,e,w),onSkip:()=>x(r,w),t:D}),te&&w?.error&&t("p",{role:"alert",className:"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400",children:w.error}),j&&t(eo,{msg:r,onClose:()=>H(!1),t:D})]});var ce});bo.displayName="MessageRow";const xo=({messages:n,isLoading:r,agentStatus:a,agentName:p,logoIcon:h,onRelativeLinkClick:g,onDownloadFile:m,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,miniGameEnabled:b=!0,onPlayWaitingGame:x,waitingGameUrl:k,onMessageFeedback:N,isResumingAfterDecision:C,onSkipWait:S,pendingApprovals:I,onSubmitApprovalDecisions:T,isSubmittingApproval:A,approvalError:_,feedbackUrl:E,conversationId:M,locale:L,openableConversationIds:R,onOpenConversation:$,markerRenderers:D,markerKindList:j,codeBlockRenderers:z,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,transcriptFooter:W,onLoadEarlier:q,ttsRoute:B,thinking:F,t:V})=>{const G=s(null),[X,Z]=o(150),{entries:Q,rate:re,saveComment:oe,skipComment:se}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a}){const i=Ot(),[d,u]=o(()=>({scope:t,entries:{}}));let p=d.entries;d.scope!==t&&(p={},u({scope:t,entries:p}));const h=s({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a});c(()=>{h.current={feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a}});const g=s(0),m=l((e,t)=>u(n=>({...n,entries:{...n.entries,[e]:t}})),[]),f=l((e,t,n)=>u(r=>{const a=r.entries[e];return a&&a.seq===t?{...r,entries:{...r.entries,[e]:n(a)}}:r}),[]),v=l(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,onMessageFeedback:s,t:l}=h.current,c=aa(e),d=++g.current;if(!r)return m(c,{seq:d,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void s?.(c,t,e);if(a&&e.serverId){if(m(c,{seq:d,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await ae(i,r,a,e.serverId,t?{rating:ee(t),comment:null}:null,o)){const e=l(t?"Could not submit feedback.":"Could not retract feedback.");return void f(c,d,()=>n?{...n,seq:d,pending:!1,commentOpen:!1,error:e}:{seq:d,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}f(c,d,e=>({...e,pending:!1,commentOpen:"down"===t})),h.current.onMessageFeedback?.(c,t,e)}},[m,f]),w=l(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,t:s}=h.current,l=aa(e),c=ne(t);if(!(r&&a&&e.serverId&&c))return void m(l,{...n,commentOpen:!1,error:null});const d=++g.current;m(l,{...n,seq:d,pending:!0,error:null});const u=await ae(i,r,a,e.serverId,{rating:"negative",comment:c},o);f(l,d,e=>u?{...e,comment:c,pending:!1,commentOpen:!1}:{...e,pending:!1,error:s("Could not submit feedback.")})},[m,f]);return{entries:p,rate:v,saveComment:w,skipComment:l((e,t)=>m(aa(e),{...t,commentOpen:!1,error:null}),[m])}}({feedbackUrl:E,conversationId:M,requestHeaders:y,onMessageFeedback:N,t:V}),ie=function(e,t){const n=Ot(),[r]=o(oa),a=r||!!t,[d,u]=o(null),p=s(null),h=s(e),g=s(t);c(()=>{h.current=e,g.current=t});const m=s(null),f=l(()=>{const e=m.current;e&&(m.current=null,e.abort.abort(),e.audio?.pause(),e.url&&URL.revokeObjectURL(e.url),u(t=>t===e.id?null:t))},[]),v=l(()=>r?(p.current??=function(e,t,n){let r=0,a=null;const o=e=>{e===r&&null!==a&&(r+=1,a=null,n(null))},s=()=>{null!==a&&(r+=1,a=null,e.cancel(),n(null))};return{speak:(i,l,c)=>{s();const d=l.filter(e=>e.trim());if(!d.length)return!1;const u=r;return a=i,n(i),d.forEach((n,a)=>{const s=a===d.length-1,i=t(n,{lang:c,onEnd:()=>{s&&o(u)},onError:()=>{u===r&&(o(u),e.cancel())}});e.speak(i)}),!0},stop:s,get speakingId(){return a}}}(window.speechSynthesis,(e,{lang:t,onEnd:n,onError:r})=>{const a=new SpeechSynthesisUtterance(e);return t&&(a.lang=t),a.onend=n,a.onerror=r,a},u),p.current):null,[r]),w=l((e,t)=>v()?.speak(e,J(t),h.current),[v]),y=l(async(e,t,r)=>{const a=new AbortController,o={id:t,abort:a};m.current=o,u(t);const s=J(r,4096),i=new Audio;o.audio=i;let l=0;try{for await(const t of Y(n,e,s,a.signal)){if(m.current!==o)return;if(!t)throw new Error("TTS failed");o.url&&URL.revokeObjectURL(o.url),o.url=URL.createObjectURL(t);const e=new Promise(e=>{i.onended=()=>e(!0),i.onerror=()=>e(!1)});if(i.src=o.url,await i.play(),!await e)throw new Error("TTS playback failed");if(m.current!==o)return;l+=1}f()}catch(e){if(m.current!==o||e instanceof DOMException&&"AbortError"===e.name)return;f(),w(t,s.slice(l).join(" "))}},[w,f]),b=l((e,t)=>{const n=m.current?.id??p.current?.speakingId??null;if(f(),p.current?.stop(),n===e)return;const r=K(t),a=g.current;a?y(a,e,r):w(e,r)},[w,y,f]),x=l(()=>{f(),p.current?.stop()},[f]);return i(()=>()=>x(),[x]),{supported:a,speakingId:d,toggle:b,stop:x}}(L,B),[le]=o(()=>function(e,t=ca){let n=!0,r=0,a=null;const o=e=>{e.scrollTo({top:e.scrollHeight,behavior:"instant"}),r=e.scrollTop},s=()=>{a&&(t.clear(a.timer),a=null)},i=()=>{s();const t=e();t&&n&&o(t)};return{get following(){return n},reveal:()=>{const o=e();if(!o)return;n=!0,s();const l=Math.max(0,o.scrollHeight-o.clientHeight);o.scrollTo({top:o.scrollHeight,behavior:"smooth"}),r=o.scrollTop,r>=l-1||(a={target:l,timer:t.set(i,1e3)})},keepUp:()=>{const t=e();t&&n&&!a&&o(t)},onScroll:()=>{const t=e();if(!t)return;const o=t.scrollTop,s=o<r-1,l=o>r+1;(s||l)&&(r=o);const c=t.scrollHeight-o-t.clientHeight;s?n=c<=1:l&&c<=100&&(n=!0),a&&(s||o>=a.target-1||c<=1)&&i()},leave:()=>{const t=e();!t||t.scrollTop<=0||(n=!1,s())}}}(()=>G.current));i(()=>{const e=G.current;return e?function(e,t,n=globalThis){const{ResizeObserver:r,MutationObserver:a}=n;if(!r)return()=>{};const o=new r(()=>t());for(const t of Array.from(e.children))o.observe(t);const s=a?new a(e=>{for(const t of e)for(const e of Array.from(t.addedNodes))1===e.nodeType&&o.observe(e)}):null;return s?.observe(e,{childList:!0}),()=>{o.disconnect(),s?.disconnect()}}(e,le.keepUp):void 0},[le]);const ce=s(null),de=(e,t)=>{t instanceof Element&&e.contains(t)&&(function(e,t,n,r){for(let a=e;a&&a!==t;a=n(a))if(a.scrollTop>0&&a.scrollHeight>a.clientHeight&&pa.has(r(a)))return!0;return!1}(t,e,to,no)||le.leave())},ue=n[0]?.id,pe=s(null),[he,ge]=o(!1);d(()=>{const e=pe.current,t=e?n.findIndex(t=>t.id===e.firstId):-1;if(e&&t>0)return e.count=t,void Z(e.visible+e.count);Z(150)},[ue]),d(()=>{const e=pe.current;if(!e?.count||X!==e.visible+e.count)return;pe.current=null;const t=G.current;t&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))});let me=0;for(const e of n)"user"===e.role&&(me+=1);const fe=s(null);d(()=>{const e=fe.current;fe.current={firstMessageId:ue,userMessageCount:me},pe.current?.count||(!e||e.firstMessageId!==ue||me>e.userMessageCount?le.reveal():le.keepUp())},[n,ue,me,le]);const ve=a?.thinkingContent?.length??0;d(()=>{ve&&le.keepUp()},[ve,le]);const we=n.length>X,ye=u(()=>we?n.slice(n.length-X):n,[n,X,we]),{speakingId:be,stop:xe}=ie,ke=null===be||n.some(e=>aa(e)===be),Ne=s({conversationId:M,userMessageCount:me});i(()=>{const e=Ne.current;Ne.current={conversationId:M,userMessageCount:me},(e.conversationId!==M||me>e.userMessageCount||!ke)&&xe()},[M,me,ke,xe]);let Ce=null;if(r)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){Ce=n[e].id;break}const Se=!!I?.length&&!!T;return e("div",{ref:G,role:"region","aria-label":V("Conversation transcript"),tabIndex:0,onScroll:le.onScroll,onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&de(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(da.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&ro(e.target)||de(e.currentTarget,e.target))},onPointerDown:e=>{const t=e.currentTarget,n=t.getBoundingClientRect();(function(e){if(1===e.button)return!e.onControl;if(0!==e.button||!e.onContainer||e.x<e.clientWidth)return!1;const t=(e.scrollTop+e.clientHeight)/e.scrollHeight*e.clientHeight;return e.y<=t})({button:e.button,onContainer:e.target===t,onControl:ro(e.target),x:e.clientX-n.left-t.clientLeft,y:e.clientY-n.top-t.clientTop,clientWidth:t.clientWidth,clientHeight:t.clientHeight,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight})&&de(t,e.target)},onTouchStart:e=>{ce.current=ua(e.touches)},onTouchMove:e=>{const t=ua(e.touches),n=ce.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&de(e.currentTarget,e.target),ce.current=function(e,t){return null===t?null:null===e?t:Math.min(e,t)}(n,t)},"data-testid":"filigran-chat-transcript",className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]",children:[(we||q)&&t("div",{className:"flex justify-center",children:e("button",{type:"button",disabled:he,onClick:()=>{(async()=>{if(n.length>X)return void Z(e=>e+50);if(!q||he)return;const e=G.current;ge(!0),pe.current={firstId:n[0]?.id,visible:Math.min(n.length,X),count:0,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0};try{0===await q()&&(pe.current=null)}finally{ge(!1)}})()},className:"flex items-center gap-1.5 rounded-full border border-gray-200 dark:border-white/10 px-3 py-1 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]",children:[t(Yn,{size:13,className:"rotate-180"}),V("Load earlier messages")]})}),ye.map(e=>{const n=e.id===Ce;return"assistant"===e.role&&!e.content&&n?Se?null:t("div",{children:t($a,{agentStatus:a,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:le.keepUp,onSkipWait:S,...F})},e.id):t(bo,{msg:e,isStreaming:n,agentName:p,logoIcon:h,onRelativeLinkClick:g,onDownloadFile:m,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,feedbackMode:"assistant"===e.role?te(e.serverId,E,M,!!N):null,feedback:Q[aa(e)],onRate:re,onSaveComment:oe,onSkipComment:se,locale:L,canSpeak:ie.supported,isSpeaking:be===aa(e),onToggleSpeech:ie.toggle,openableConversationIds:e.conversationRefs?.length?R:void 0,onOpenConversation:e.conversationRefs?.length?$:void 0,markerRenderers:D,markerKindList:j,codeBlockRenderers:z,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,t:V},e.id)}),C&&!Se&&t($a,{agentStatus:a,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:le.keepUp,...F}),Se&&t(ba,{proposals:I,onSubmit:T,isSubmitting:A,error:_,t:V},I.map(e=>e.toolCallId).join("|")),W,t("div",{})]})};function ko(e){const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const No=({call:n,agentName:r,logoIcon:a,processingLabel:l,onInterrupt:c,onToggleMute:d,onEnd:u,t:p})=>{const[h,g]=o(0);i(()=>{const e=window.setInterval(()=>g(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);const m=s(null);i(()=>{m.current?.scrollIntoView?.({block:"end"})},[n.lines.length,n.heard]);const{phase:f,muted:v}=n,w="listening"===f?p(v?"Muted":"Listening..."):"processing"===f?l:"speaking"===f?p("Speaking…"):"error"===f?p("Failed to get a response. Resuming…"):"",y="speaking"===f||"processing"===f,b="speaking"===f||"listening"===f&&!v,x="w-12 h-12 rounded-full flex items-center justify-center border transition-colors disabled:opacity-40";return e("div",{role:"dialog","aria-label":p("Voice call"),"data-testid":"filigran-chat-voice-call",className:"absolute inset-0 z-40 flex flex-col rounded-[inherit] bg-white dark:bg-[#1e1e2e]",children:[e("div",{className:"flex items-center justify-between px-4 py-3 text-[0.7rem] uppercase tracking-[1px] text-gray-500 dark:text-white/50",children:[t("span",{children:p("Voice call")}),t("span",{className:"font-mono normal-case tracking-normal",children:ko(h)})]}),e("div",{className:"flex flex-1 min-h-0 flex-col items-center justify-center gap-1 px-4",children:[e("button",{type:"button",onClick:y?c:void 0,disabled:!y,"aria-label":"speaking"===f?p("Skip response"):"processing"===f?p("Cancel question"):r,className:`relative mb-4 flex h-28 w-28 items-center justify-center rounded-full border-2 transition-colors ${"error"===f?"border-amber-400/50":b?"border-[var(--chat-accent)]":"border-[var(--chat-accent-40)]"} ${y?"cursor-pointer":"cursor-default"}`,children:[b&&t("span",{className:"absolute inset-0 rounded-full border border-[var(--chat-accent-40)] animate-ping","aria-hidden":"true"}),"processing"===f&&t("span",{className:"absolute inset-3 rounded-full border-2 border-dashed border-[var(--chat-accent-40)] animate-spin","aria-hidden":"true"}),t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-10 [&>svg]:h-10",children:a})]}),t("h2",{className:"max-w-full truncate text-base font-semibold text-gray-900 dark:text-white",children:r}),t("p",{"aria-live":"polite",className:"text-center text-[0.8125rem] text-gray-500 dark:text-white/60",children:w}),"speaking"===f&&t("p",{className:"text-[0.7rem] text-gray-400 dark:text-white/40",children:p("Speak or tap to interrupt")}),"processing"===f&&t("p",{className:"text-[0.7rem] text-gray-400 dark:text-white/40",children:p("Tap to cancel")}),"listening"===f&&n.heard&&e("p",{className:"mt-3 max-w-md text-center text-[0.8125rem] italic text-gray-500 dark:text-white/50",children:["“",n.heard,"”"]})]}),n.lines.length>0&&t("div",{className:"max-h-[35%] overflow-y-auto filigran-chat-scrollable px-4 pb-2",children:e("div",{className:"flex flex-col gap-2",children:[n.lines.map((n,r)=>t("div",{className:"flex "+("user"===n.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[85%] rounded-lg px-3 py-1.5 text-[0.75rem] leading-5 "+("user"===n.role?"bg-[var(--chat-accent)]/10 text-gray-800 dark:text-white/80":"bg-gray-100 dark:bg-white/[0.06] text-gray-700 dark:text-white/70"),children:[n.agent&&e("div",{className:"mb-0.5 text-[0.7rem] font-medium text-[var(--chat-accent)]",children:[n.agent.name,n.agent.failed&&e("span",{className:"font-normal text-gray-500 dark:text-white/50",children:[" · ",p("Did not answer")]})]}),n.content.length>200?`${n.content.slice(0,200)}…`:n.content]})},r)),t("div",{ref:m})]})}),e("div",{className:"flex items-center justify-center gap-5 px-4 pb-5 pt-3",children:[t("button",{type:"button",onClick:d,"aria-label":p(v?"Unmute microphone":"Mute microphone"),"aria-pressed":v,className:`${x} ${v?"border-red-400/40 bg-red-500/10 text-red-500":"border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/70 hover:bg-gray-100 dark:hover:bg-white/[0.06]"}`,children:t(v?xr:br,{size:20})}),t("button",{type:"button",onClick:u,"aria-label":p("End voice call"),className:"w-14 h-14 rounded-full flex items-center justify-center bg-red-500 text-white hover:bg-red-600 transition-colors",children:t(Nr,{size:22})}),t("button",{type:"button",onClick:c,disabled:"speaking"!==f,"aria-label":p("Skip response"),className:`${x} border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/70 hover:bg-gray-100 dark:hover:bg-white/[0.06]`,children:t(jr,{size:20})})]})]})},Co=({firstName:r,agentName:a,t:o})=>{if(!a)return t(n,{children:A(o,"How can I help you, {name}?",{name:r})});const{before:s,after:i,hasSlot:l}=function(e,t,n,r={}){const a=A(e,t,r),o=`{${n}}`,s=a.indexOf(o);return-1===s?{before:a,after:"",hasSlot:!1}:{before:a.slice(0,s),after:a.slice(s+o.length),hasSlot:!0}}(o,"How can {agent} help you, {name}?","agent",{name:r});return e(n,{children:[s,l&&t("span",{className:"text-[var(--chat-accent)]",children:a}),i]})},So=({firstName:n,logoIcon:r,promptSuggestions:a,onPromptClick:o,agentName:s,agentDescription:i,suggestionsLoading:l=!1,t:c})=>e("div",{className:"flex-1 flex flex-col items-center justify-center px-6 pb-8",children:[t("span",{className:"text-[var(--chat-accent)] mb-4 [&>svg]:w-12 [&>svg]:h-12 drop-shadow-[0_0_12px_var(--chat-accent-40)]",children:r}),t("h2",{className:"text-xl font-medium mb-1 text-center text-gray-900 dark:text-white",style:{fontFamily:'"Geologica", sans-serif',animation:"chat-fade-in 0.35s ease-out"},children:t(Co,{firstName:n,agentName:s,t:c})},s??"default"),i&&t("p",{className:"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 text-gray-500 dark:text-white/40",children:i}),!i&&t("span",{className:"mb-5"}),(l||a.length>0)&&e("div",{className:"w-full max-w-[320px]",children:[t("span",{className:"block text-center mb-2 text-[0.65rem] tracking-[1.5px] uppercase text-[var(--chat-accent)] font-semibold",children:c("Suggestions")}),l?t("div",{"aria-hidden":!0,className:"space-y-1",children:[0,1,2].map(e=>t("div",{className:"h-8 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-100/50 dark:bg-white/[0.03] animate-pulse"},e))}):o&&a.map(e=>t("button",{type:"button",onClick:()=>o(e),className:"w-full text-left text-[0.8125rem] text-gray-800 dark:text-white py-1.5 px-3 mb-1 rounded-lg border border-gray-200 dark:border-white/10 bg-transparent transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)]",children:e},e))]})]}),Io="application/x-filigran-conversation";const To="p-1 rounded-md text-gray-400 dark:text-white/30 hover:bg-gray-200/60 dark:hover:bg-white/10 transition-colors disabled:opacity-40 disabled:pointer-events-none",Ao="text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40",_o=({conversations:r,loading:a,activeConversationId:l,collapsed:c,onToggleCollapsed:d,onSelect:p,onDelete:h,onRename:g,onNewChat:m,workspaces:f,storageKeyPrefix:v,rowActions:w,headerActions:y,sections:b,onClearAll:x,t:k})=>{const[N,C]=o(""),[S,I]=o(null),[T,A]=o(""),_=s(!1),E=It(v,Nt),[M,L]=o(()=>function(e){try{const t=JSON.parse(At("local",e)??"[]");return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e):[])}catch{return new Set}}(E)),[R,$]=o(!1),[D,j]=o(null);i(()=>{if(!D)return;const e=setTimeout(()=>j(null),6e3);return()=>clearTimeout(e)},[D]);const z=(e,t)=>{_.current=!1,I(e),A(t)},O=()=>{if(_.current)return;_.current=!0;const e=S,t=T.trim();I(null),e&&t&&g?.(e,t)},P=()=>{_.current=!0,I(null)},U=(e,t)=>j(e||k(t)),H=async(e,t)=>{if(!f||function(e,t,n){const r=e.find(e=>e.conversationId===t);return!!r&&(r.workspaceId??null)===n}(r,e,t))return;const n=await f.onMove(e,t);null!==n&&U(n,"The conversation could not be moved")},W=N.trim().toLowerCase(),q=u(()=>W?e=>(e.title||"").toLowerCase().includes(W):void 0,[W]),B=u(()=>q?r.filter(q):r,[r,q]),F=u(()=>f?function(e,t,n={}){const{matches:r}=n,a=r?e.filter(r):e,o=new Set(t.map(e=>e.id)),s=new Set(e.map(e=>e.workspaceId).filter(e=>!!e)),i=new Map,l=[],c=[];for(const e of a){const t=e.workspaceId??null;t?o.has(t)?i.set(t,[...i.get(t)??[],e]):l.push(e):c.push(e)}const d=[];for(const e of ve(t)){const t=i.get(e.id)??[];(e.canManage||s.has(e.id))&&(r&&0===t.length||d.push({workspace:e,key:e.id,conversations:t}))}return l.length>0&&d.push({workspace:null,key:"__elsewhere__",conversations:l}),{groups:d,unfiled:c}}(r,f.list,{matches:q}):null,[r,f,q]),V=f?function(e){return ve(e.filter(e=>e.canManage))}(f.list):[],K=F?function(e){const{total:t,unfiled:n,loading:r,searching:a}=e;return n>0||r||a?null:0===t?"none":"all-filed"}({total:r.length,unfiled:F.unfiled.length,loading:a,searching:!!W}):null;if(c)return e("div",{className:"flex flex-col items-center gap-1 border-r border-gray-200 dark:border-white/10 px-2 py-3 shrink-0",children:[t(qr,{title:k("Show conversations"),children:t("button",{type:"button",onClick:d,"aria-label":k("Show conversations"),"aria-expanded":!1,className:"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t(Ir,{size:17})})}),t(qr,{title:k("New conversation"),children:t("button",{type:"button",onClick:()=>m(),"aria-label":k("New conversation"),className:"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t(rr,{size:17})})})]});const G=e=>t(Ro,{conversation:e,isActive:e.conversationId===l,isEditing:e.conversationId===S,draftTitle:T,onDraftTitleChange:A,onCommitRename:O,onCancelRename:P,onStartRename:g?z:void 0,onSelect:p,onDelete:h,fileable:f?V:void 0,onMove:H,actions:w,t:k},e.conversationId);return e("div",{className:"w-64 shrink-0 flex flex-col border-r border-gray-200 dark:border-white/10",children:[e("div",{className:"flex items-center gap-1 px-3 py-3",children:[e("button",{type:"button",onClick:()=>m(),className:"flex-1 flex items-center gap-2 rounded-lg border border-gray-200 dark:border-white/10 px-3 py-1.5 text-[0.8125rem] text-gray-700 dark:text-white/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors",children:[t(rr,{size:15}),k("New conversation")]}),y,t(qr,{title:k("Hide conversations"),children:t("button",{type:"button",onClick:d,"aria-label":k("Hide conversations"),"aria-expanded":!0,className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t(Ir,{size:17})})})]}),r.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Cr,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40"}),t("input",{type:"text",value:N,onChange:e=>C(e.target.value),onKeyDown:e=>{"Escape"===e.key&&C("")},placeholder:k("Search conversations..."),"aria-label":k("Search conversations..."),className:"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable",children:[a&&0===r.length&&t("div",{className:"px-3 py-2",children:t(Hr,{size:16})}),e(n,F&&f?{children:[!W&&e("div",{className:"flex items-center justify-between px-2 pb-1 pt-1",children:[t("span",{className:Ao,children:k("Workspaces")}),t(qr,{title:k("New workspace"),children:t("button",{type:"button",onClick:()=>$(!0),"aria-label":k("New workspace"),className:To,children:t(cr,{size:14})})})]}),R&&t(Mo,{placeholder:k("Workspace name"),onSubmit:async e=>{if($(!1),!e)return;const t=await f.onCreate(e);t.ok||U(t.error,"The workspace could not be created")},onCancel:()=>$(!1)}),F.groups.map(e=>t(Lo,{workspace:e.workspace,count:e.conversations.length,open:we(e.key,M,e,l,!!W),toggleable:ye(e,l,!!W),pending:!!e.workspace&&f.pendingWorkspaceId===e.workspace.id&&!l,onToggle:()=>{return t=e.key,void L(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),_t("local",E,JSON.stringify([...n])),n});var t},onNewChat:f.onNewChat,onRename:async(e,t)=>{const n=await f.onRename(e,t);n.ok||U(n.error,"The workspace could not be renamed")},onDelete:async e=>{const t=await f.onDelete(e);t.ok||U(t.error,"The workspace could not be deleted")},onDropConversation:t=>e.workspace&&void H(t,e.workspace.id),t:k,children:e.conversations.length>0?e.conversations.map(G):t("p",{className:"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30",children:k("Drop a conversation here, or start one with +.")})},e.key)),e(Eo,{onDropConversation:e=>{H(e,null)},accepts:!0,children:[e("div",{className:"flex items-center justify-between px-2 pb-1 pt-3",children:[t("span",{className:Ao,children:k("Not in a workspace")}),t("span",{className:"text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30",children:F.unfiled.length})]}),F.unfiled.map(G),K&&t("p",{className:"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30",children:k("none"===K?"No conversations yet":"Every conversation is in a workspace.")})]}),W&&0===F.groups.length&&0===F.unfiled.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:k("No conversation matches")})]}:{children:[!a&&0===r.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:k("No conversations yet")}),r.length>0&&0===B.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:k("No conversation matches")}),B.map(G)]}),b,x&&r.length>0&&!W&&t(Pr,{onClear:x,className:"px-2 pt-3",iconButtonClass:To,t:k})]}),D&&t("p",{role:"alert",className:"mx-3 mb-3 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[0.7rem] text-red-600 dark:text-red-400",children:D})]})},Eo=({onDropConversation:e,accepts:n,children:r,className:a=""})=>{const[i,l]=o(!1),c=s(0),d=e=>e.dataTransfer.types.includes(Io);return t("div",{className:`rounded-lg transition-colors ${i?"bg-[var(--chat-accent)]/10 ring-1 ring-[var(--chat-accent)]/40":""} ${a}`,...n?{onDragEnter:e=>{d(e)&&(c.current+=1,l(!0))},onDragOver:e=>{d(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},onDragLeave:e=>{d(e)&&(c.current=Math.max(0,c.current-1),0===c.current&&l(!1))},onDrop:t=>{if(!d(t))return;t.preventDefault(),c.current=0,l(!1);const n=t.dataTransfer.getData(Io);n&&e(n)}}:{},children:r})},Mo=({initial:e="",placeholder:n,onSubmit:r,onCancel:a})=>{const[l,c]=o(e),d=s(!1),u=s(null);i(()=>{u.current?.focus(),u.current?.select()},[]);const p=()=>{d.current||(d.current=!0,r(l.trim()))};return t("input",{ref:u,value:l,maxLength:200,onChange:e=>c(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&p(),"Escape"===e.key&&(d.current=!0,a())},onBlur:p,placeholder:n,"aria-label":n,className:"mx-2 mb-1 w-[calc(100%-1rem)] rounded-md bg-white dark:bg-white/10 px-2 py-1 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]"})},Lo=({workspace:r,count:a,open:s,toggleable:i,pending:l,onToggle:c,onNewChat:d,onRename:u,onDelete:p,onDropConversation:h,t:g,children:m})=>{const[f,v]=o(!1),[w,y]=o(!1),b=!!r?.canManage,x=!!r&&r.isDefault&&r.isOwn;return e(Eo,{onDropConversation:h,accepts:b,className:"mb-0.5",children:[e("div",{className:"group/ws flex items-center gap-1 rounded-lg px-1.5 py-1 hover:bg-gray-100 dark:hover:bg-white/[0.06]",children:[f&&r?t(Mo,{initial:r.name,placeholder:g("Workspace name"),onSubmit:e=>{v(!1),e&&e!==r.name&&u(r.id,e)},onCancel:()=>v(!1)}):e("button",{type:"button",onClick:c,disabled:!i,"aria-expanded":s,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left disabled:cursor-default",children:[t(Xn,{size:12,className:"shrink-0 text-gray-400 dark:text-white/30 transition-transform "+(s?"rotate-90":"")}),t(ir,{size:14,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate text-[0.8125rem] font-medium text-gray-800 dark:text-white/80",children:r?r.name:g("Other workspaces")}),x&&t("span",{className:"shrink-0 rounded bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] text-[var(--chat-accent)]",children:g("default")}),t("span",{className:"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30",children:a})]}),r&&b&&!f&&t("span",{className:"flex shrink-0 items-center opacity-0 group-hover/ws:opacity-100 focus-within:opacity-100 transition-opacity",children:e(n,w?{children:[t("span",{className:"px-1 text-[0.65rem] text-red-600 dark:text-red-400",children:g("Delete?")}),t("button",{type:"button",onClick:()=>{y(!1),p(r.id)},"aria-label":g("Delete workspace"),className:`${To} hover:text-red-500`,children:t(Jn,{size:13})}),t("button",{type:"button",onClick:()=>y(!1),"aria-label":g("Cancel"),className:To,children:t(Zn,{size:13})})]}:{children:[t(qr,{title:g("New conversation in this workspace"),children:t("button",{type:"button",onClick:()=>d(r.id),"aria-label":g("New conversation in this workspace"),className:To,children:t(rr,{size:13})})}),t(qr,{title:g("Rename workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":g("Rename workspace"),className:To,children:t(kr,{size:13})})}),!r.isDefault&&t(qr,{title:g("Delete workspace"),children:t("button",{type:"button",onClick:()=>y(!0),"aria-label":g("Delete workspace"),className:`${To} hover:text-red-500`,children:t(Lr,{size:13})})})]})})]}),s&&e("div",{className:"space-y-0.5 pb-1 pl-3",children:[l&&e("div",{className:"flex items-center gap-2 rounded-lg bg-[var(--chat-accent)]/10 px-2.5 py-1.5 text-[0.75rem] text-[var(--chat-accent)]",children:[t(rr,{size:12}),g("New conversation — send a message to start it")]}),m]})]})},Ro=({conversation:r,isActive:a,isEditing:i,draftTitle:l,onDraftTitleChange:c,onCommitRename:d,onCancelRename:u,onStartRename:p,onSelect:h,onDelete:g,fileable:m,onMove:f,actions:v,t:w})=>{const[y,b]=o(!1),x=s(null),k=!!m&&!i;return e("div",{role:"button",tabIndex:0,"aria-current":a,draggable:k,onDragStart:k?e=>{e.dataTransfer.setData(Io,r.conversationId),e.dataTransfer.effectAllowed="move"}:void 0,onClick:()=>h(r.conversationId),onKeyDown:e=>{e.target===e.currentTarget&&("Enter"!==e.key&&" "!==e.key||(e.preventDefault(),h(r.conversationId)))},className:"group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors "+(a?"bg-[var(--chat-accent)]/10":"hover:bg-gray-100 dark:hover:bg-white/[0.06]"),children:[t("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg "+(a?"bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]":"bg-gray-100 dark:bg-white/[0.06] text-gray-400 dark:text-white/30"),children:t(Vn,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[i?t("input",{autoFocus:!0,value:l,onChange:e=>c(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&d(),"Escape"===e.key&&u()},onBlur:d,"aria-label":w("Conversation title"),className:"w-full rounded-md bg-white dark:bg-white/10 px-1.5 py-0.5 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]"}):t("span",{className:"block truncate text-[0.8125rem] "+(a?"text-gray-900 dark:text-white":"text-gray-700 dark:text-white/70"),children:r.title||w("Untitled conversation")}),(r.agentName||r.updatedAt)&&!i&&e("span",{className:"block text-[0.65rem] text-gray-400 dark:text-white/30 truncate",children:[r.agentName,r.agentName&&r.updatedAt?" · ":"",r.updatedAt?M(r.updatedAt,w):""]})]}),!i&&e("span",{className:"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[v&&t("span",{className:"flex",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:v(r)}),k&&e(n,{children:[t("button",{ref:x,type:"button",onClick:e=>{e.stopPropagation(),b(e=>!e)},"aria-label":w("Move to workspace"),title:w("Move to workspace"),"aria-expanded":y,className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(lr,{size:13})}),t(Ur,{open:y,onClose:()=>b(!1),anchorRef:x,placement:"bottom-end",width:220,children:e("div",{className:"py-1",onClick:e=>e.stopPropagation(),children:[t("p",{className:"px-3 pb-1 pt-1.5 text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40",children:w("Move to workspace")}),m.map(n=>e("button",{type:"button",disabled:n.id===r.workspaceId,onClick:()=>{b(!1),f(r.conversationId,n.id)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] text-gray-700 dark:text-white/80 hover:bg-gray-100 dark:hover:bg-white/10 disabled:opacity-40",children:[t(ir,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===r.workspaceId&&t(Jn,{size:12,className:"ml-auto shrink-0"})]},n.id)),t("div",{className:"my-1 h-px bg-gray-200 dark:bg-white/10"}),e("button",{type:"button",disabled:!r.workspaceId,onClick:()=>{b(!1),f(r.conversationId,null)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] text-gray-700 dark:text-white/80 hover:bg-gray-100 dark:hover:bg-white/10 disabled:opacity-40",children:[t(Zn,{size:13,className:"shrink-0"}),w("Remove from workspace")]})]})})]}),p&&t("button",{type:"button",onClick:e=>{e.stopPropagation(),p(r.conversationId,r.title||"")},"aria-label":w("Rename conversation"),title:w("Rename conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(rr,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),g(r.conversationId)},"aria-label":w("Delete conversation"),title:w("Delete conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-red-500 dark:hover:text-red-400",children:t(Lr,{size:13})})]})]})},$o=new Set([502,503,504]),Do=new Set([401,403]),jo=m(function(e,n){const r=s(e.onSessionEnded);r.current=e.onSessionEnded;const a=s("");a.current=ke(e.requestHeaders);const o=u(()=>{let e=null;const t=t=>{r.current&&e!==a.current&&(e=a.current,Lt(r.current,t))};return{sessionEnded:t,fetch:(n=()=>r.current?t:void 0,async(e,t)=>{const r=await globalThis.fetch(e,t),a=401===r.status?n():void 0;return a&&"function"==typeof r.clone&&r.clone().json().then(e=>{const t=function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(!t||"object"!=typeof t)return null;const{code:n,reason:r}=t;return"session_expired"!==n?null:{reason:"string"==typeof r&&r?r:void 0}}(e);t&&a(t.reason)}).catch(()=>{}),r})};var n},[]);return t(zt,{value:o,children:t(zo,{...e,ref:n})})}),zo=m(function({mode:n,onClose:r,onModeChange:d,topOffset:p=0,apiBaseUrl:h,apiEndpoints:g,agentDashboardUrl:m,waitingGameUrl:v,user:w,t:y,accentColor:b="#7b5cff",logoIcon:x,promptSuggestions:k,draftBorderColor:C,resizable:S=!1,onWidthChange:I,onResizeStart:T,onResizeEnd:A,disableFileManagement:_=!1,onRelativeLinkClick:E,onDownloadError:M,maxFileCount:L,maxTotalSize:R,requestHeaders:D,pageContext:j,pushContentSelector:z,backendType:O="rest",miniGameEnabled:U=!0,onPlayWaitingGame:H,notifyOnComplete:W=!0,onTaskComplete:q,onMessageFeedback:B,locale:F,disableImagePreviews:V=!1,contextUsageEnabled:G=!0,composerToolbar:Z,storageKeyPrefix:ee,conversationId:te,onConversationChange:ne,initialAgent:ae,onAgentChange:oe,readOnly:se=!1,readOnlyNotice:ie,getRequestExtras:le,onStreamEvent:ce,markerRenderers:de,codeBlockRenderers:pe,transformMessageText:he,onArtifactOpen:ge,headerActions:me,banner:ve,composerHeader:we,transcriptFooter:ye,welcome:be,renderMessageExtras:Ne,messageFooterActions:Ce,sidebarRowActions:Ie,sidebarHeaderActions:Te,sidebarSections:Ae,statusLabel:Ee,waitingMessages:Me,renderWaitingPanel:Le,fontFamily:Re,onReady:$e,onBeforeSend:De,onHeldSendSettled:je,onTurnRunningChange:ze,steerAttachments:Pe=!1,holdSendsDuringTurn:He=!1,agentMentions:We=!1,hideConversationList:qe=!1},Be){const Fe=Mn(g),Ve=Mn(D),Ke=Mn(j),Ge=Mn(k),Je=Ln(E),Ye=Ln(M),Xe=Ln(H),Ze=Ln(q),Qe=Ln(B),et=Ln(ne),tt=Ln(oe),nt=Ln(le),rt=Ln(De),at=Ln(je),ot=Ln(ce),st=Ln(ze),it=Ln(ge),lt=s(null),{fetch:ct,sessionEnded:dt}=a(jt),ut=u(()=>Q(y,F),[y,F]),pt=Mn(Me),ht=u(()=>de?Object.fromEntries(Object.entries(de).map(([e,t])=>[e.toUpperCase(),t])):void 0,[de]),gt=Mn(u(()=>pe?Object.fromEntries(Object.entries(pe).map(([e,t])=>[e.toLowerCase(),t])):void 0,[pe])),mt=Mn(u(()=>function(e){const t=new Set;for(const n of e??[]){const e=n.toUpperCase();$.test(e)&&t.add(e)}return[...t].sort()}(ht&&Object.keys(ht)),[ht])),ft=u(()=>({statusLabel:Ee,waitingMessages:pt,renderWaitingPanel:Le}),[Ee,pt,Le]),vt="fullscreen"===n||"inline"===n,[wt,yt]=o(!1),{agents:bt,agentsLoading:xt,agentsError:Nt,agentsSettled:Ct,agentsDisabled:St,selectedAgent:Tt,agentMenuOpen:Et,setAgentMenuOpen:Mt,handleSwitchAgent:Rt,reloadAgents:$t}=xn({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve,storageKeyPrefix:ee,initialAgent:ae,onAgentChange:oe?tt:void 0}),[Dt,zt]=o(null),Pt=s(null),[Ut,Ht]=o(null),[Wt,qt]=o(void 0),[Bt,Ft]=o(null),[Vt,Kt]=o(null),Gt=s(0),[Jt,Yt]=o(null),Xt=s(async()=>{}),Zt=s(()=>{}),Qt=l((e,t)=>{Lt(Zt.current,e,t.relayed),Lt(ot,e,t)},[ot]),{messages:rn,inputValue:an,setInputValue:on,isLoading:sn,turnRunning:ln,sendsHeld:cn,turnEnd:dn,agentStatus:un,attachedFiles:pn,conversationId:hn,contextUsage:gn,transferredAgent:mn,canSteer:fn,pendingApprovals:vn,isSubmittingApproval:wn,approvalError:Cn,submitApprovalDecisions:Sn,isResumingAfterDecision:In,historyReloadNonce:Tn,reloadHistory:Rn,mergeTurnHistory:Dn,settleUnseenEnd:jn,historyLoadedRef:zn,conversationIdRef:On,handleFileAdd:Un,handlePaste:Bn,handleSendMessage:Fn,skipWait:Vn,readPendingApprovals:Kn,heldMessage:Gn,notice:Jn,cancelHeldMessage:Yn,agentMentions:Xn,addAgentMention:Zn,handleNewChat:Qn,pendingWorkspaceId:er,clearPendingWorkspace:nr,handleStopGenerating:rr,conversationRefs:ar,addConversationRef:or,setAttachedFiles:sr,setMessages:ir,setContextUsage:lr,updateConversationId:cr,handleSwitchConversation:dr}=yn({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,agentSlug:Tt?.slug,requestHeaders:Ve,pageContext:Ke,onRelativeLinkClick:E?Je:void 0,t:ut,maxFileCount:L,maxTotalSize:R,storageKeyPrefix:ee,controlledConversationId:te,onConversationIdChange:ne?et:void 0,getRequestExtras:le?nt:void 0,onStreamEvent:Qt,onSessionEnded:dt,onConversationTitle:()=>{Xt.current()},historySettledFor:Ut,steerAttachments:Pe,holdSends:He,agentMentionsEnabled:We,onBeforeSend:De?rt:void 0,onHeldSendSettled:je?at:void 0});Wt!==hn&&(qt(hn),null!==Ut&&Ht(null)),i(()=>{void 0!==te&&te!==On.current&&(te?dr(te):Qn())},[te]);const{suggestions:ur,loading:pr}=En({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve,agentSlug:Tt?.slug}),hr=u(()=>(ur??Ge)?.map(e=>ut(e))??(e=>[e("Help me create a new simulation scenario"),e("What are the latest attack patterns?"),e("How do I configure detection rules?"),e("Summarize my recent findings")])(ut),[ur,Ge,ut]),{prompts:gr,quota:mr,refreshQuota:fr}=_n({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve}),{historyEnabled:vr,conversations:wr,conversationsLoading:yr,refreshConversations:br,deleteConversation:xr,renameConversation:kr,moveConversation:Nr,clearConversations:Cr}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=Ot(),[s,i]=o([]),[c,d]=o(!1),u="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,p=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,h=l(async()=>{if(u){d(!0);try{const e=await a(p,{method:"GET",headers:{...r??{}}});if(!e.ok)return void i([]);const t=await e.json(),n=Array.isArray(t)?t:Array.isArray(t?.conversations)?t.conversations:[];i(n.map(kn).filter(e=>null!==e))}catch{i([])}finally{d(!1)}}},[u,p,r]),g=l(async e=>{if(!u)return!1;try{return!!(await a(`${p}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...r??{}}})).ok&&(i(t=>t.filter(t=>t.conversationId!==e)),!0)}catch{return!1}},[u,p,r]),m=u&&t?.clearAll?`${e}${t.clearAll}`:null,f=l(async()=>{if(!m)return!1;try{return!!(await a(m,{method:"DELETE",headers:{...r??{}}})).ok&&(i([]),!0)}catch{return!1}},[m,r]),v=l(async(e,t)=>{const n=t.trim();if(!u||!n)return!1;const o=s;i(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{return!!(await a(`${p}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({title:n})})).ok||(i(o),!1)}catch{return i(o),!1}},[u,p,r,s]),w=l(async(e,t)=>{if(!u)return"";const n=s.find(t=>t.conversationId===e)?.workspaceId,o=()=>i(r=>function(e,t,n,r){const a=e.findIndex(e=>e.conversationId===t);if(a<0||(e[a].workspaceId??null)!==n)return e;const o=[...e];return o[a]={...e[a],workspaceId:r},o}(r,e,t,n));i(n=>n.map(n=>n.conversationId===e?{...n,workspaceId:t}:n));try{const n=await a(`${p}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({workspace_id:t})});return n.ok?null:(o(),await xe(n)??"")}catch{return o(),""}},[u,p,r,s]);return{historyEnabled:u,conversations:s,conversationsLoading:c,refreshConversations:h,deleteConversation:g,renameConversation:v,moveConversation:w,clearConversations:m?f:null}}({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve});Xt.current=br;const{workspacesEnabled:Sr,workspaces:Ir,refreshWorkspaces:Tr,createWorkspace:Ar,renameWorkspace:_r,deleteWorkspace:Er}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=Ot(),[i,c]=o([]),[d,u]=o(!1),p=s(0),h=t?.workspaces,g="rest"===n&&!t?.singleEndpoint&&"string"==typeof h&&h.length>0,m=g?`${e}${h}`:null,f=l(async()=>{if(!m)return;const e=++p.current;try{const n=await a(m,{method:"GET",headers:{...r??{}}});if(e!==p.current)return;if(!n.ok)return void(408===(t=n.status)||429===t||t>=500&&501!==t||(u(!1),c([])));const o=fe(await n.json());if(e!==p.current)return;c(o),u(!0)}catch{}var t},[m,r]),v=l(async(e,t,n)=>{try{const o=await a(t,{method:e,headers:{...n?{"Content-Type":"application/json"}:{},...r??{}},...n?{body:JSON.stringify(n)}:{}});if(!o.ok)return{ok:!1,error:await xe(o)};const s=204===o.status?[]:fe([await o.json().catch(()=>null)]);return await f(),{ok:!0,workspace:s[0]}}catch{return{ok:!1,error:null}}},[r,f]),w=l(async e=>m?v("POST",m,{name:e.trim()}):{ok:!1,error:null},[m,v]),y=l(async(e,t)=>m?v("PATCH",`${m}/${encodeURIComponent(e)}`,{name:t.trim()}):{ok:!1,error:null},[m,v]),b=l(async e=>m?v("DELETE",`${m}/${encodeURIComponent(e)}`):{ok:!1,error:null},[m,v]);return{workspacesEnabled:g&&d,workspaces:i,refreshWorkspaces:f,createWorkspace:w,renameWorkspace:y,deleteWorkspace:b}}({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve});i(()=>{Sr&&er&&!function(e,t){return t.some(t=>t.id===e&&t.canManage)}(er,Ir)&&nr(er)},[Sr,Ir,er,nr]);const[Mr,Lr]=o(!1),[Rr,$r]=o(!1),Dr=vt&&vr&&!qe;i(()=>{Dr&&br()},[Dr,hn,br]),i(()=>{Dr&&Tr()},[Dr,hn,Tr]);const jr=s(null);i(()=>{if(!Dr)return;const e=()=>{if("visible"!==document.visibilityState)return;const e=Date.now();(function(e,t){return null===t||e-t>=2e3})(e,jr.current)&&(jr.current=e,br(),Tr())};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[Dr,br,Tr]);const zr=s(!1);i(()=>{zr.current!==ln&&(zr.current=ln,ln?Lt(st,!0):Lt(st,!1,{ended:dn??"stopped"}))},[ln,dn,st]),i(()=>()=>{zr.current&&(zr.current=!1,Lt(st,!1,{ended:"stopped"}))},[st]);const Or=s(!1);i(()=>{Or.current&&!ln&&(fr(),Dr&&(br(),Tr())),Or.current=ln},[ln,fr,Dr,br,Tr]);const Pr=e=>{Lr(!1),dr(e)},Ur=ue(h,Fe,O),Hr=u(()=>new Set(wr.map(e=>e.conversationId)),[wr]),Wr=Ln(vr?Pr:void 0),qr=rn.some(e=>(e.conversationRefs?.length??0)>0);i(()=>{qr&&vr&&br()},[qr,vr,br,hn]);const Br=X(h,Fe,O,"messagesPage"),[Fr,Kr]=o(!1),Gr=X(h,Fe,O,"tts"),Jr=u(()=>Gr?{url:Gr,requestHeaders:Ve}:void 0,[Gr,Ve]),Yr=s(rn);Yr.current=rn,i(()=>Kr(!1),[hn]);const Xr=l(async()=>{const e=On.current,t=Yr.current.find(e=>e.serverId)?.serverId;if(!Br||!e||!t)return Kr(!1),0;try{const n=await ct(`${Br}/${encodeURIComponent(e)}/messages?before=${encodeURIComponent(t)}&limit=50&supports_artifacts=true`,{headers:{...Ve??{}}});if(!n.ok||On.current!==e)return 0;const r=await n.json();if(On.current!==e)return 0;const a=new Set(Yr.current.map(e=>e.serverId).filter(Boolean)),o=Ue(r?.messages).filter(e=>!e.serverId||!a.has(e.serverId)).map(e=>({...e,id:Oe(e.serverId)}));return ir(e=>[...o,...e]),Kr(!0===r?.has_more&&o.length>0),o.length}catch{return 0}},[Br,On,Ve,ir]),Zr=(e,t,n)=>{if(Ht(e),Kr(!!Br&&!0===t.has_more),!t.messages?.length)return;const r=Ue(t.messages);if(n)ir(e=>function(e,t){const n=[...e],r=new Map;n.forEach((e,t)=>{e.serverId&&r.set(e.serverId,t)});const a=new Set,o=new Map;let s=-1,i=!1;for(const e of t){let t=void 0!==e.serverId?r.get(e.serverId):void 0;if(void 0===t){const r=tn(e),o=n.findIndex((e,t)=>!a.has(t)&&!e.serverId&&en(e)===r);o>=0&&(t=o,n[o]=nn(n[o],e),i=!0)}if(void 0!==t){a.add(t),s=Math.max(s,t);continue}const l=o.get(s)??[];l.push({...e,id:Oe(e.serverId)}),o.set(s,l)}if(0===o.size)return i?n:e;const l=[...o.get(-1)??[]];return n.forEach((e,t)=>{l.push(e,...o.get(t)??[])}),l}(e,r));else{ir(r);for(let e=t.messages.length-1;e>=0;e-=1){const n=Se(t.messages[e]);if(n){lr(n);break}}}},Qr=s(sn);Qr.current=sn,i(()=>{Gt.current=0},[hn]),i(()=>{Bt&&!sn&&(Ft(null),Bt.conversationId===hn&&Zr(Bt.conversationId,Bt.data,!0))},[Bt,sn,hn]),i(()=>{if(!Vt||Vt!==hn||sn)return;const e=()=>{Qr.current||(Kt(null),Gt.current+=1,Rn())},t=Math.min(6e4,5e3*2**Gt.current),n=window.setTimeout(e,t),r=()=>{"visible"===document.visibilityState&&e()};return window.addEventListener("online",e),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(n),window.removeEventListener("online",e),document.removeEventListener("visibilitychange",r)}},[Vt,hn,sn,Rn]);const ea=ke(Ve),ta=l(()=>{Yt(null),Rn()},[Rn]);i(()=>{Jt&&Jt.conversationId===hn&&!sn&&Jt.headersKey!==ea&&ta()},[Jt,hn,sn,ea,ta]);const na=Jt&&Jt.conversationId===hn?Jt:null,aa="rest"===O&&!Fe?.singleEndpoint&&null!==Fe?.sessions&&!!hn&&Dt!==hn,oa=!se&&!_&&"rest"===O&&!Fe?.singleEndpoint&&null!==Fe?.upload,[sa,ia]=o(!1),la=s(0),ca=e=>e.dataTransfer.types.includes("Files"),da=oa?{onDragEnter:e=>{ca(e)&&(la.current+=1,ia(!0))},onDragOver:e=>{ca(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDragLeave:e=>{ca(e)&&(la.current=Math.max(0,la.current-1),0===la.current&&ia(!1))},onDrop:e=>{ca(e)&&(e.preventDefault(),e.stopPropagation(),la.current=0,ia(!1),Un(e.dataTransfer.files))}}:{},ua=async()=>{await(Cr?.())&&Qn()},pa=async e=>{await xr(e)&&e===On.current&&Qn()},{sidebarWidth:ha,handleResizeStart:ga,defaultWidth:ma,isResizing:fa}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:r,onResizeEnd:a,storageKeyPrefix:l}){const c=It(l,kt),[d,u]=o(()=>{const e=At("local",c);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=Nn)return t}return Nn}),[p,h]=o(!1),g=s(!1),m=s(d);m.current=d;const f=s(n);f.current=n;const v=s(a);return v.current=a,i(()=>{"sidebar"===e&&t&&f.current?.(m.current)},[e,t]),i(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!g.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,Nn),n);u(r),m.current=r,f.current?.(r)},r=()=>{g.current&&(g.current=!1,h(!1),document.body.style.cursor="",document.body.style.userSelect="",_t("local",c,String(m.current)),v.current?.())},a=()=>{const e=.4*window.innerWidth;if(m.current>e){const t=Math.max(e,Nn);u(t),m.current=t,f.current?.(t)}};return document.addEventListener("mousemove",n),document.addEventListener("mouseup",r),window.addEventListener("resize",a),()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",r),window.removeEventListener("resize",a)}},[e,t,c]),{sidebarWidth:d,handleResizeStart:e=>{e.preventDefault(),g.current=!0,h(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",r?.()},defaultWidth:Nn,isResizing:p}}({mode:n,resizable:S,onWidthChange:I,onResizeStart:T,onResizeEnd:A,storageKeyPrefix:ee});i(()=>{const e="sidebar"===n?S?ha:ma:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",fa?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),z){const e=document.querySelector(z);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=fa?"none":"padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)",()=>{e.style.paddingRight=n,e.style.transition=r,document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}}}return()=>{document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}},[z,n,ha,ma,S,fa]);const va=u(()=>x??t(tr,{size:24}),[x]),wa=u(()=>function(e,t){if(void 0!==t){const e=t.trim();return/^https?:\/\//i.test(e)||/^\/(?![/\\])/.test(e)?e:null}const n=e?.trim().replace(/\/+$/,"");return n&&/^https?:\/\//i.test(n)?`${n}/chat?arcade=play`:null}(m,v),[m,v]),ya=w.firstName,[ba,xa]=o(null),ka=mn?.name||ba||Tt?.name||ut("Assistant"),Na=l(()=>{const e=lt.current;return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);An({isLoading:ln,agentName:ka,t:ut,enabled:W,onComplete:Ze,isViewingChat:Na});const Ca=null!=Fe?.download,Sa="rest"===O&&null!==Fe?.download&&(!Fe?.singleEndpoint||Ca),Ia=l(e=>`${h}${Fe?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[h,Fe]),Ta=l(async e=>{const t=Ia(e);try{const n=await ct(t,{method:"GET",credentials:"include",headers:{...Ve??{}}});if(!n.ok)throw new Error(`Download failed: ${n.status}`);const r=await n.blob(),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=e.filename||"download",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a)}catch(t){Ye?.(t,e)}},[Ia,Ve,Ye]),Aa="rest"===O&&Fe?.artifacts?`${h}${Fe.artifacts}`:null,Ea=l((e,t)=>`${Aa}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,[Aa]),Ma=l(async(e,t)=>{const n=`${e.title||e.kind}.${function(e){return"pptx_native"===e?"pptx":e}(t)}`;try{const r=await ct(`${Ea(e.kind,e.id)}/download`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...Ve??{}},body:JSON.stringify({format:t})});if(!r.ok)throw new Error(`Download failed: ${r.status}`);const a=await r.blob(),o=URL.createObjectURL(a),s=document.createElement("a");s.href=o,s.download=function(e){if(!e)return;const t=/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(e);if(t)try{return decodeURIComponent(t[1].trim().replace(/^"|"$/g,""))||void 0}catch{}const n=/filename\s*=\s*("([^"]*)"|[^;]+)/.exec(e);return(n?(n[2]??n[1]).trim():"")||void 0}(r.headers.get("content-disposition"))??n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(o)}catch(r){Ye?.(r,{fileId:e.id,filename:n,type:t.toUpperCase()})}},[Ea,Ve,Ye]),La=l(async(e,t)=>{const n=await ct(Ea(e,t),{credentials:"include",headers:{...Ve??{}}});if(n.ok)return _e(await n.json())},[Ea,Ve]),Ra={"--chat-accent":b,"--chat-accent-10":N(b,.1),"--chat-accent-40":N(b,.25),"--chat-accent-50":N(b,.5),"--chat-accent-dark":b,...Re?{fontFamily:Re}:{}},$a=s(Dn);$a.current=Dn;const Da=s(jn);Da.current=jn;const ja=s(!0);i(()=>(ja.current=!0,()=>{ja.current=!1}),[]),i(()=>{if(null===Fe?.sessions||Fe?.singleEndpoint||"legacy"===O||"ag-ui"===O)return;if(!hn)return xa(null),void zt(null);if(zn.current)return Pt.current!==hn&&Dt!==hn&&zt(hn),void(Pt.current!==hn&&Ut!==hn&&Bt?.conversationId!==hn&&Ht(hn));if(!Tt&&!St)return void(Ct&&Dt!==hn&&zt(hn));zn.current=!0,Pt.current=hn,zt(null);const e=`${h}${Fe?.sessions??"/chat/sessions"}`,t=hn,n=()=>!ja.current||On.current!==t,r=ke(Ve),a=Tn;ct(e,{method:"POST",headers:{"Content-Type":"application/json",...Ve??{}},body:JSON.stringify({conversation_id:hn,agent_slug:Tt?.slug,supports_artifacts:!0})}).then(e=>n()?null:e.ok?(Gt.current=0,Kt(null),Yt(null),e.json()):(Da.current(a,null),Do.has(e.status)?xe(e).then(e=>(n()||Yt({conversationId:t,detail:e,headersKey:r}),null)):($o.has(e.status)?Kt(t):cr(null),null))).then(e=>{if(!e||n())return;"string"==typeof e.conversation_id&&e.conversation_id&&e.conversation_id!==t&&cr(e.conversation_id),xa("string"==typeof e.agent_name?e.agent_name:null);const r=Ue(e.messages);Da.current(a,r),$a.current(r)||(Qr.current?Ft({conversationId:t,data:e}):Zr(t,e,!1))}).catch(()=>{n()||(Da.current(a,null),Kt(t))}).finally(()=>{Pt.current===t&&(Pt.current=null),n()||zt(t)})},[hn,Tt,Ct,Dt,Br,h,Fe,O,Bt,Tn,zn,On,ja,Ve,ir,lr,cr]);const za=s(Fn);za.current=Fn;const Oa=s(Qn);Oa.current=Qn;const Pa=s(dr);Pa.current=dr;const Ua=s(bt);Ua.current=bt;const Ha=s(Tt);Ha.current=Tt;const Wa=Ct&&!aa,qa=Ln($e),Ba=s(!1);i(()=>{Wa&&!Ba.current&&(Ba.current=!0,qa?.())},[Wa,qa]);const Fa=s([]),[Va,Ka]=o(0),Ga=(e,t)=>{Fa.current.push({run:e,drop:t}),Ka(e=>e+1)};i(()=>{if(!Wa||0===Fa.current.length)return;Fa.current.shift().run(),Fa.current.length>0&&Ka(e=>e+1)},[Wa,Va]),i(()=>()=>{queueMicrotask(()=>{if(!ja.current)for(const e of Fa.current.splice(0))e.drop?.()})},[]);const Ja=s(Rt);Ja.current=Rt;const Ya=s(rr);Ya.current=rr;const Xa=s(se);Xa.current=se;const Za=s(an);Za.current=an;const Qa=mn?.id??(ba?bt.find(e=>e.name===ba)?.id:void 0)??Tt?.id??null,eo=function(e){const t=Ot(),n=s(e);c(()=>{n.current=e});const[r,a]=o(null),d=s(null),u=l(async(e,r)=>{const{tts:a,locale:o}=n.current,s=o||("undefined"!=typeof navigator?navigator.language:void 0),i=J(e,200),l=a?Y(t,a,i,r):null;for(const e of i){if(r.aborted)return;const t=l?(await l.next()).value??null:null;if(r.aborted)return;if(!t||!await Hn(t,r)){if(r.aborted)return;await Wn(e,s,r)}}},[]),p=l(()=>{if(d.current)return!0;const e=$n();if(!e)return!1;const t=Pn({recognition:new e,lang:n.current.locale||("undefined"!=typeof navigator?navigator.language:void 0),send:(e,t)=>n.current.send(e,t),speak:u,speakable:e=>Lt(n.current.speakable,e)??e,present:e=>Lt(n.current.present,e)??e,probe:()=>{const e=n.current.readTurnState;return e?async function(e){try{const t=await e();return t?t.running?"running":"over":"unknown"}catch{return"unknown"}}(e):Promise.resolve("over")},stopTurn:()=>n.current.stopTurn(),addressedAgentId:()=>n.current.addressedAgentId(),onChange:e=>{d.current===t&&a(e)}});return d.current=t,t.start(),!0},[u]),h=l(()=>{const e=d.current;d.current=null,e?.end(),a(null)},[]);return i(()=>h,[h]),{snapshot:r,start:p,end:h,onFrame:l((e,t)=>d.current?.frame(e,t),[]),interrupt:l(()=>d.current?.interrupt(),[]),cancel:l(()=>d.current?.cancel(),[]),toggleMute:l(()=>d.current?.toggleMute(),[])}}({send:(e,t)=>za.current({text:e,source:"voice",onSent:t.onAccepted,onNotSent:t.onNotSent,onSteered:t.onSteered}),stopTurn:()=>Ya.current(),readTurnState:Kn?async()=>{const e=On.current,t=e?await Kn(e):null;return t&&{running:t.turnRunning}}:void 0,addressedAgentId:()=>Qa,speakable:e=>K(P(e,mt)),present:e=>he?he(e,{id:"voice-call",role:"assistant",content:e,timestamp:new Date}):e,tts:Jr,locale:F});Zt.current=eo.onFrame;f(Be,()=>({send:(e,t)=>Xa.current?Promise.resolve("dropped"):new Promise(n=>Ga(()=>{Xa.current?n("dropped"):za.current({text:e,extras:t?.extras,displayText:t?.displayText,onSent:()=>n("sent")}).then(n,()=>n("failed"))},()=>n("dropped"))),newConversation:e=>Ga(()=>{const t=bn(Ua.current,e?.agent);t&&t.id!==Ha.current?.id&&Ja.current(t),Oa.current(e?.workspaceId)}),selectConversation:e=>Ga(()=>Pa.current(e)),setDraft:e=>{Za.current=e,on(e)},getDraft:()=>Za.current,focusComposer:()=>lt.current?.querySelector("textarea")?.focus(),stop:()=>{eo.cancel(),Ya.current()},startVoiceCall:()=>!Xa.current&&eo.start(),reloadAgents:$t,scrollToMessage:e=>{const t=[...lt.current?.querySelectorAll("[data-message-id]")??[]].find(t=>t.dataset.messageId===e);return!!t&&(t.scrollIntoView?.({block:"center",behavior:"smooth"}),t.classList.add("filigran-chat-highlight"),window.setTimeout(()=>t.classList.remove("filigran-chat-highlight"),2e3),!0)}}),[]);const to=(()=>{const e="filigran-chatbot";switch(n){case"sidebar":return`${e} fixed right-0 bottom-0 flex flex-col bg-white dark:bg-[#1e1e2e] border-l border-gray-200 dark:border-white/10 z-[1200]`;case"floating":return`${e} fixed bottom-5 right-5 flex flex-col bg-white dark:bg-[#1e1e2e] rounded-xl shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border border-gray-200 dark:border-white/10`;case"fullscreen":return`${e} fixed right-0 bottom-0 left-0 flex flex-col bg-gray-50 dark:bg-[#161622] z-[1400]`;case"inline":return`${e} relative flex flex-col h-full w-full min-h-0 bg-gray-50 dark:bg-[#161622]`;default:return e}})(),no={...Ra,..."sidebar"===n?{top:p,width:S?ha:ma}:"floating"===n?{width:380,height:560}:"inline"===n?{}:{top:p}};return e("div",{ref:lt,className:to,style:no,"data-testid":"filigran-chat-panel",children:["sidebar"===n&&S&&t("div",{onMouseDown:ga,className:"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group",children:t("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 rounded-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100"})}),t(Vr,{mode:n,agentName:ka,agents:bt,agentsLoading:xt,agentsError:Nt,selectedAgent:Tt,transferredFrom:mn?Tt?.name:void 0,agentMenuOpen:Et,onAgentMenuToggle:()=>Mt(e=>!e),onAgentMenuClose:()=>Mt(!1),onSwitchAgent:e=>{e&&Rt(e,()=>{Qn()})},modeMenuOpen:wt,onModeMenuToggle:()=>yt(e=>!e),onModeMenuClose:()=>yt(!1),onModeChange:d,onNewChat:Qn,onClose:r,logoIcon:va,actions:me,agentDashboardUrl:m,historyEnabled:vr&&!Dr,historyMenuOpen:Mr,onHistoryMenuToggle:()=>{const e=!Mr;e&&br(),Lr(e)},onHistoryMenuClose:()=>Lr(!1),conversations:wr,conversationsLoading:yr,activeConversationId:hn,onSelectConversation:Pr,onDeleteConversation:e=>{pa(e)},onClearAll:Cr?()=>{ua()}:void 0,t:ut}),e("div",{className:Dr?"flex flex-1 min-h-0":"contents",children:[Dr&&t(_o,{conversations:wr,loading:yr,activeConversationId:hn,collapsed:Rr,onToggleCollapsed:()=>$r(e=>!e),onSelect:Pr,onDelete:e=>{pa(e)},onRename:(e,t)=>{kr(e,t)},onNewChat:Qn,workspaces:Sr?{list:Ir,pendingWorkspaceId:er,onCreate:Ar,onRename:_r,onDelete:async e=>{const t=await Er(e);return t.ok&&(nr(e),br()),t},onMove:Nr,onNewChat:e=>{Qn(e),Tr()}}:void 0,storageKeyPrefix:ee,rowActions:Ie,headerActions:Te,sections:Ae,onClearAll:Cr?()=>{ua()}:void 0,t:ut}),e("div",{className:Dr?"relative flex flex-1 flex-col min-w-0":"contents",...da,children:[sa&&t("div",{className:"pointer-events-none absolute inset-2 z-30 flex items-center justify-center rounded-xl border-2 border-dashed border-[var(--chat-accent)] bg-[var(--chat-accent)]/10 text-sm font-medium text-[var(--chat-accent)]",children:ut("Drop files to attach them")}),ve&&t("div",{className:"shrink-0",children:ve}),0===rn.length&&aa?t("div",{"data-testid":"filigran-chat-loading",className:"flex-1 flex flex-col gap-4 px-4 py-6","aria-busy":"true",children:[0,1,2].map(e=>t("div",{className:"flex "+(e%2?"justify-end":"justify-start"),children:t("div",{className:"h-10 rounded-xl bg-gray-200/70 dark:bg-white/[0.06] animate-pulse "+(e%2?"w-1/3":"w-2/3")})},e))}):0===rn.length&&na?e("div",{"data-testid":"filigran-chat-restore-error",role:"alert",className:"flex-1 flex flex-col items-center justify-center gap-3 px-6 py-6 text-center",children:[t(qn,{size:18,className:"text-amber-500 dark:text-amber-400"}),t("p",{className:"max-w-sm text-[0.8125rem] leading-6 text-gray-600 dark:text-white/60",children:na.detail??ut("This conversation could not be loaded.")}),t("button",{type:"button",onClick:ta,className:"rounded-md border border-gray-200 dark:border-white/10 px-3 py-1 text-[0.75rem] font-medium text-gray-700 dark:text-white/80 transition-colors hover:bg-gray-100 dark:hover:bg-white/[0.06]",children:ut("Retry")})]}):0===rn.length?be?t("div",{className:"flex-1 min-h-0 overflow-y-auto filigran-chat-scrollable",children:be}):t(So,{firstName:ya,logoIcon:va,promptSuggestions:hr,suggestionsLoading:pr,agentName:Tt?.name,agentDescription:Tt?.description,onPromptClick:se?void 0:on,t:ut}):t(xo,{messages:rn,isLoading:sn,agentStatus:un,agentName:ka,logoIcon:va,onRelativeLinkClick:Je,onDownloadFile:Sa?Ta:void 0,resolveAttachmentUrl:Sa&&!V?Ia:void 0,onDownloadArtifact:Aa?Ma:void 0,onRefreshArtifact:Aa?La:void 0,requestHeaders:Ve,miniGameEnabled:U,onPlayWaitingGame:Xe,waitingGameUrl:wa,onMessageFeedback:Qe,feedbackUrl:re(h,Fe,O),conversationId:hn,locale:F,isResumingAfterDecision:In,onSkipWait:Vn??void 0,pendingApprovals:vn,onSubmitApprovalDecisions:Sn,isSubmittingApproval:wn,approvalError:Cn,openableConversationIds:Hr,onOpenConversation:Wr,markerRenderers:ht,markerKindList:mt,codeBlockRenderers:gt,transformMessageText:he,onArtifactOpen:it,renderMessageExtras:Ne,messageFooterActions:Ce,transcriptFooter:ye,onLoadEarlier:Fr?Xr:void 0,ttsRoute:Jr,thinking:ft,t:ut}),se?ie&&t("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-white/10 text-sm text-gray-500 dark:text-white/50",children:ie}):t(ra,{header:we,sendsHeld:cn,steerAttachments:Pe,canHold:He,heldMessage:Gn,notice:Jn,onCancelHeld:Yn,agentMentions:We&&bt.length>0?{agents:bt,mentions:Xn,onPick:Zn}:void 0,inputValue:an,onInputChange:on,onSend:Fn,onStop:rr,isLoading:sn,canSteer:fn,attachedFiles:_?[]:pn,onFileAdd:_?void 0:Un,onFileRemove:_?void 0:e=>sr(t=>t.filter((t,n)=>n!==e)),onPaste:_?void 0:Bn,t:ut,mode:n,separatorColor:C,prompts:gr,quota:mr,contextUsage:G?gn:null,composerToolbar:Z,conversationReferences:Ur?{url:Ur,requestHeaders:Ve,conversationId:hn,refs:ar,onPick:or}:void 0})]})]}),eo.snapshot&&t(No,{call:eo.snapshot,agentName:ka,logoIcon:va,processingLabel:_a(un,ut,Ee),onInterrupt:eo.interrupt,onToggleMute:eo.toggleMute,onEnd:eo.end,t:ut})]})}),Oo=({isOpen:n,onToggle:r,label:a,accentColor:o="#7b5cff",icon:s,t:i,locale:l})=>{const c=u(()=>Q(i,l),[i,l]),d=s??t(tr,{size:16});return e("button",{type:"button",onClick:r,className:"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap rounded-md border transition-colors",style:{borderColor:n?o:N(o,.5),color:o,backgroundColor:n?N(o,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=o,e.currentTarget.style.backgroundColor=N(o,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?o:N(o,.5),e.currentTarget.style.backgroundColor=n?N(o,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:d}),a??c("Ask Assistant")]})};export{jo as ChatPanel,Oo as ChatToggleButton,Un as voiceCallSupported};
|
|
1
|
+
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{createContext as r,useContext as o,useState as a,useRef as s,useEffect as i,useCallback as c,useInsertionEffect as l,useLayoutEffect as d,useMemo as u,useId as p,Component as h,memo as m,forwardRef as f,useImperativeHandle as g}from"react";import v from"remark-gfm";import w from"remark-parse";import{unified as y}from"unified";import{createPortal as b}from"react-dom";import x from"react-markdown";import k from"remark-breaks";function N(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}function C(e){return function(e){if(!e)return e;const t=e.split("\n"),n=/^(\s*)(`{3,})(.*)$/,r=/^(markdown|md|mdx|markup)\b/i;let o=-1;for(let e=0;e<t.length;e++){const a=t[e].match(n);if(a&&3===a[2].length&&r.test(a[3].trim())){o=e;break}}if(-1===o)return e;const a=[];for(let e=o+1;e<t.length;e++){const r=t[e].match(n);r&&a.push({idx:e,run:r[2].length,bare:""===r[3].trim()})}const s=(e,n)=>{for(let r=e+1;r<n;r++)if(""!==t[r].trim())return!1;return!0};let i=0,c=3,l=0,d=-1;for(let e=0;e<a.length;e++){const t=a[e];if(t.bare&&0===i){const n=a[e+1];if(!n||!n.bare||s(t.idx,n.idx)){d=t.idx;break}i++}else i=t.bare?Math.max(0,i-1):i+1;l++,c=Math.max(c,t.run)}if(-1===d||0===l)return e;const u="`".repeat(Math.max(c+1,4)),p=t[o].match(n);t[o]=`${p[1]}${u}${p[3]}`;const h=t[d].match(n);return t[d]=`${h[1]}${u}`,t.join("\n")}(function(e){if(!e||-1===e.indexOf("|"))return e;const t=e.split("\n"),n=e=>{let t=e.trim();t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=[];let r="";for(let e=0;e<t.length;e++){const o=t[e];"\\"===o&&e+1<t.length?(r+=o+t[e+1],e++):"|"===o?(n.push(r),r=""):r+=o}return n.push(r),n},r=e=>e.includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e),o=e=>{const t=e.trim(),n=t.startsWith(":"),r=t.endsWith(":");return n&&r?":---:":r?"---:":n?":---":"---"},a=/^\s*(?:(?:>\s?)|(?:[-*+]\s+)|(?:\d{1,9}[.)]\s+))*(`{3,}|~{3,})(.*)$/;let s=null,i=0;const c=/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/;for(let e=0;e<t.length-1;e++){const l=t[e].match(a);if(l){const e=l[1];null===s?(s=e[0],i=e.length):e[0]===s&&e.length>=i&&""===l[2].trim()&&(s=null,i=0);continue}if(null!==s)continue;const d=t[e],u=t[e+1];if(!d.includes("|")||r(d)||!r(u))continue;const p=d.match(c),h=p?p[0].length:d.length-d.trimStart().length,m=p?" ".repeat(h):d.slice(0,h),f=n(d.slice(h)).length,g=n(u);if(f<2||g.length===f)continue;const v=[];for(let e=0;e<f;e++)v.push(g[e]?o(g[e]):"---");t[e+1]=`${m}| ${v.join(" | ")} |`}return t.join("\n")}(function(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("[")||t.startsWith("```"))return e;try{return JSON.parse(t),"```json\n"+t+"\n```"}catch{return e}}((t=e).includes("![")?t.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>``):t)));var t}const S=new Set(["http","https","mailto","tel"]);function I(e){const t=e.indexOf(":");if(t<0)return e;const n=e.indexOf("/"),r=e.indexOf("?"),o=e.indexOf("#");if(n>-1&&t>n||r>-1&&t>r||o>-1&&t>o)return e;const a=e.slice(0,t).toLowerCase();return S.has(a)||"data"===a&&/^data:image\//i.test(e)?e:""}const T=e=>e;function A(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function _(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function E(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}M`}function M(e,t){if(!e)return"";const n=new Date(e).getTime();if(Number.isNaN(n))return"";const r=Date.now()-n,o=Math.floor(r/6e4);if(o<1)return t("just now");if(o<60)return A(t,"{count}m ago",{count:o});const a=Math.floor(o/60);if(a<24)return A(t,"{count}h ago",{count:a});const s=Math.floor(a/24);return s<7?A(t,"{count}d ago",{count:s}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const L=["FILE","PRESENTATION","REPORT","VIDEO"],R=`(${L.join("|")}):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?`,$=/^[A-Z][A-Z0-9_]*$/;const D=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),z=new Map;function j(e){const t=e.filter(e=>!L.includes(e)),n=t.join(","),r=z.get(n);if(r)return r;const o=[...L,...t].map(D).join("|"),a=t.length>0?`|(${t.map(D).join("|")}):([^\\]]+)`:"",s=[...L,...t].map(e=>`[[${e}:`),i={complete:new RegExp(`\\[\\[(?:${R}${a})\\]\\]`,"gi"),partial:new RegExp(`\\[\\[(?:${o})(?::[^\\]]*)?\\]?$`,"i"),heads:s,longestHead:Math.max(...s.map(e=>e.length))};return z.size>=32&&z.delete(z.keys().next().value),z.set(n,i),i}function O(e,t=!1,n=[]){if(!e)return[];const r=j(n),o=[];let a=0;for(const t of e.matchAll(r.complete)){if(t.index>a&&o.push({type:"text",value:e.slice(a,t.index)}),t[1]){const e=t[1].toUpperCase();n.includes(e)?o.push({type:"marker",kind:e,args:t[3]?`${t[2]}#/${t[3]}`:t[2]}):"FILE"===e?o.push({type:"file",fileId:t[2]}):o.push({type:"artifact",kind:e.toLowerCase(),id:t[2].toLowerCase(),slideRef:t[3]||void 0})}else o.push({type:"marker",kind:t[4].toUpperCase(),args:t[5]});a=t.index+t[0].length}const s=e.slice(a).replace(r.partial,""),i=t?function(e,t){for(let n=Math.max(0,e.length-t.longestHead);n<e.length;n++){if("["!==e[n])continue;const r=e.slice(n).toUpperCase();if(t.heads.some(e=>e.startsWith(r)))return e.slice(0,n)}return e}(s,r):s;return i&&o.push({type:"text",value:i}),o}function P(e,t=[]){const n=[];for(const r of O(e,!1,t))"text"===r.type&&r.value.trim()&&n.push(C(r.value));return n}const U=(e,t)=>`${e}:${t.toLowerCase()}`;function H(e,t){const n=[];if("presentation"===e.kind&&void 0!==e.slideCount&&n.push(A(t,"{count} slides",{count:e.slideCount})),"report"===e.kind&&void 0!==e.sectionCount&&n.push(A(t,"{count} sections",{count:e.sectionCount})),"video"===e.kind){void 0!==e.sceneCount&&n.push(A(t,"{count} scenes",{count:e.sceneCount}));const r=function(e){if(!e||e<=0)return;const t=Math.round(e/1e3);return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}(e.durationMs);r&&n.push(r)}return n.join(" · ")}function W(e){const t=new Map;for(const n of e){const e=n.group?.trim()||null;t.has(e)||t.set(e,[]),t.get(e).push(n)}const n=t.get(null);return t.delete(null),[...n?[{group:null,agents:n}]:[],...[...t].map(([e,t])=>({group:e,agents:t}))]}const q=y().use(w).use(v).freeze(),B=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function F(e){if(B.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(F).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function V(e,t){if(!B.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(F(e));case"tableRow":return void t.push((e.children??[]).map(F).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])V(n,t)}}function K(e){const t=[];for(const n of e)n.trim()&&V(q.parse(n),t);return t.map(e=>e.replace(/\s+/g," ").replace(/ ([.,!?;:])/g,"$1").trim()).filter(e=>/[\p{L}\p{N}]/u.test(e)).map(e=>/[.!?;:\u3002\uff01\uff1f]$/.test(e)?e:`${e}.`).join("\n")}const G=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;function J(e,t=220){const n=e.split(/\n+|(?<=[.!?;:\u3002\uff01\uff1f])\s+/).map(e=>e.trim()).filter(Boolean),r=[];for(const e of n){if(e.length<=t){r.push(e);continue}let n="";for(const o of e.split(" "))for(let e=0;e<o.length;e+=t){const a=o.slice(e,e+t);n?n.length+1+a.length<=t?n=`${n} ${a}`:(r.push(n),n=a):n=a}n&&r.push(n)}const o=[];for(const e of r){const n=o.length-1;n>=0&&o[n].length+1+e.length<=t?o[n]=`${o[n]} ${e}`:o.push(e)}return o}async function*Y(e,t,n,r){const o=o=>async function(e,t,n,r){const o=await e(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.requestHeaders??{}},body:JSON.stringify({text:n,format:"mp3"}),signal:r});if(!o.ok)throw new Error(`TTS failed: ${o.status}`);return o.blob()}(e,t,n[o],r).catch(()=>null);let a=n.length>0?o(0):null;for(let e=0;a;e+=1){const t=await a;a=e+1<n.length&&!r.aborted?o(e+1):null,yield t}}function X(e,t,n,r){const o=t?.[r];return"rest"!==n||t?.singleEndpoint||"string"!=typeof o||!o?null:`${e}${o}`}const Z={surface:"--filigran-chat-surface",surfaceRaised:"--filigran-chat-surface-raised",surfaceSubtle:"--filigran-chat-surface-subtle",surfaceHover:"--filigran-chat-surface-hover",inputSurface:"--filigran-chat-input-surface",headerBackground:"--filigran-chat-header-background",text:"--filigran-chat-text",textMuted:"--filigran-chat-text-muted",textSecondary:"--filigran-chat-text-secondary",border:"--filigran-chat-border",textSize:"--filigran-chat-text-size",userBackground:"--filigran-chat-user-background",userText:"--filigran-chat-user-text",userRadius:"--filigran-chat-user-radius",userPadding:"--filigran-chat-user-padding",userTextSize:"--filigran-chat-user-text-size",fontMono:"--filigran-chat-font-mono",codeSize:"--filigran-chat-code-size",codeSurface:"--filigran-chat-code-surface"};function Q(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(Z)){const o=e[n];"string"==typeof o&&o.trim()&&(t[r]=o)}return t}const ee={es:{"(no output)":"(sin salida)","1 tool call":"1 llamada a una herramienta","1 transfer":"1 transferencia","A file failed to upload: remove it, or send once the answer ends":"Un archivo no se pudo subir: quítelo, o envíe cuando termine la respuesta","A message references at most {count} conversations":"Un mensaje puede hacer referencia a {count} conversaciones como máximo","Acting on the page…":"Actuando en la página…","Agent switching is not available here":"El cambio de agente no está disponible aquí","Almost there":"Ya casi estamos","Also applies to your scheduled runs, until you revoke it":"También se aplica a sus ejecuciones programadas, hasta que lo revoque","Always allowed":"Siempre permitido","Analyzing results…":"Analizando los resultados…","Analyzing the details":"Analizando los detalles",Approved:"Aprobado","Ask Assistant":"Preguntar al asistente","Ask a question...":"Haga una pregunta...",Assistant:"Asistente","Attach files":"Adjuntar archivos","Attached files":"Archivos adjuntos","Attachments wait for the current response":"Los archivos adjuntos esperan la respuesta actual",Back:"Volver","Bad response":"Respuesta incorrecta","Browse agents":"Explorar agentes",Cancel:"Cancelar","Cancel question":"Cancelar la pregunta","Clear all conversations":"Borrar todas las conversaciones",Close:"Cerrar","Collecting results from one task…":"Recopilando los resultados de una tarea…","Collecting results from {count} tasks…":"Recopilando los resultados de {count} tareas…","Composing answer…":"Redactando la respuesta…",Confirm:"Confirmar","Connecting the dots":"Atando cabos","Consulting the sources":"Consultando las fuentes","Consulting {agent}…":"Consultando a {agent}…","Context full — older turns are being dropped":"Contexto completo: se están eliminando los turnos más antiguos","Context nearly full — older turns are being summarized":"El contexto está casi lleno: se están resumiendo los turnos más antiguos","Context used":"Contexto utilizado","Continue now":"Continuar ahora",Conversation:"Conversación","Conversation history":"Historial de conversaciones","Conversation title":"Título de la conversación","Conversation transcript":"Hilo de la conversación",Copied:"Copiado","Copied!":"¡Copiado!","Copy code":"Copiar código","Copy message":"Copiar mensaje","Copy response":"Copiar respuesta","Could not reach the assistant service. Check the connection and try again.":"No se ha podido conectar con el servicio del asistente. Compruebe la conexión e inténtelo de nuevo.","Could not send your decision. Please try again.":"No se ha podido enviar su decisión. Inténtelo de nuevo.","Create agent":"Crear agente","Crunching the data":"Procesando los datos","Decline this call":"Rechazar esta llamada",Declined:"Rechazado","Delegating one task…":"Delegando una tarea…","Delegating {count} tasks…":"Delegando {count} tareas…","Delete all conversations":"Eliminar todas las conversaciones","Delete all conversations?":"¿Eliminar todas las conversaciones?","Delete conversation":"Eliminar conversación","Delete workspace":"Eliminar espacio de trabajo","Delete?":"¿Eliminar?","Dictate a message":"Dictar un mensaje","Did not answer":"No respondió",Download:"Descargar","Download {format}":"Descargar en {format}","Drop a conversation here, or start one with +.":"Suelte aquí una conversación o inicie una con +.","Drop files to attach them":"Suelte los archivos para adjuntarlos","End voice call":"Finalizar la llamada de voz","Enter to send now · Esc to stop":"Pulse Intro para enviar ahora · Esc para detener","Enter to send when the answer ends · Esc to stop":"Pulse Intro para enviar cuando termine la respuesta · Esc para detener","Every conversation is in a workspace.":"Todas las conversaciones están en un espacio de trabajo.","Expand image":"Ampliar imagen","Failed to get a response. Resuming…":"No se obtuvo respuesta. Reanudando…","Feedback already submitted":"Valoración ya enviada","Files uploading...":"Cargando archivos...",Floating:"Flotante","Full screen":"Pantalla completa","Good response":"Buena respuesta","Help me create a new simulation scenario":"Ayúdame a crear un nuevo escenario de simulación","Hide conversations":"Ocultar conversaciones","How can I help you, {name}?":"¿En qué puedo ayudarle, {name}?","How can {agent} help you, {name}?":"¿En qué puede ayudarle {agent}, {name}?","How do I configure detection rules?":"¿Cómo configuro las reglas de detección?","Image could not be loaded":"No se ha podido cargar la imagen","Image preview":"Vista previa de la imagen","Incorporating your message…":"Incorporando su mensaje…",Input:"Entrada","Insert prompt template":"Insertar plantilla de prompt","Listening...":"Escuchando...","Load earlier messages":"Cargar mensajes anteriores","Loading image…":"Cargando imagen…","MCP & dynamic tools":"MCP y herramientas dinámicas","Mention an agent":"Mencionar un agente","Model reasoning":"Razonamiento del modelo","Move to workspace":"Mover a un espacio de trabajo","Mute microphone":"Silenciar el micrófono",Muted:"Silenciado","New chat":"Nuevo chat","New conversation":"Nueva conversación","New conversation in this workspace":"Nueva conversación en este espacio de trabajo","New conversation — send a message to start it":"Nueva conversación: envíe un mensaje para iniciarla","New workspace":"Nuevo espacio de trabajo",No:"No","No agent matches":"No hay ningún agente que coincida","No conversation matches":"No hay conversaciones que coincidan","No conversations yet":"Aún no hay conversaciones","No prompt matches":"No hay ningún prompt que coincida","No response.":"Sin respuesta.","Not in a workspace":"Sin espacio de trabajo","Not rendered yet":"Renderizado no iniciado",Open:"Abrir","Open conversation":"Abrir conversación","Open in XTM One":"Abrir en XTM One","Other workspaces":"Otros espacios de trabajo",Output:"Salida","Play Space Invaders":"Jugar a Space Invaders","Play Space Invaders in XTM One":"Jugar a Space Invaders en XTM One","Polishing the answer":"Puliendo la respuesta",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (editable)",Presentation:"Presentación","Putting it together":"Juntando las piezas",Quota:"Cuota","Quota reached":"Cuota alcanzada","Read aloud":"Leer en voz alta","Reasoning details":"Detalles del razonamiento","Reasoning details — turn limit reached":"Detalles del razonamiento: se ha alcanzado el límite de turnos","Reconnecting…":"Reconectando…","Reference a conversation":"Hacer referencia a una conversación","Remove from workspace":"Quitar del espacio de trabajo","Rename conversation":"Cambiar el nombre de la conversación","Rename workspace":"Cambiar el nombre del espacio de trabajo","Rendering {progress}%":"Renderizando {progress} %",Report:"Informe","Response ready":"Respuesta lista","Reticulating splines":"Reticulando splines",Retry:"Reintentar",Save:"Guardar","Search agents...":"Buscar agentes...","Search conversations...":"Buscar conversaciones...","Search prompts...":"Buscar prompts...",Send:"Enviar","Send now":"Enviar ahora","Send when the answer ends":"Enviar cuando termine la respuesta","Sending…":"Enviando…","Sends when the answer ends:":"Se enviará cuando termine la respuesta:","Shared with you":"Compartido con usted","Show conversations":"Mostrar conversaciones",Sidebar:"Barra lateral",Skip:"Omitir","Skip response":"Omitir la respuesta","Sorry, an error occurred. Please try again.":"Lo sentimos, se ha producido un error. Inténtelo de nuevo.","Speak or tap to interrupt":"Habla o toca para interrumpir","Speaking…":"Hablando…","Stop dictation":"Detener el dictado","Stop generating":"Detener la generación","Stop reading":"Detener la lectura",Stopped:"Detenido","Stopping…":"Deteniendo…",Suggestions:"Sugerencias","Summarize my recent findings":"Resume mis hallazgos recientes","Summarized conversation":"Conversación resumida","Switch to":"Cambiar a","Switch to another agent":"Cambiar a otro agente","Switch view":"Cambiar de vista","System prompt":"Prompt del sistema","Tap to cancel":"Toca para cancelar","Tell us what went wrong (optional)":"Indíquenos qué ha fallado (opcional)","The agent needs your approval to run a tool:":"El agente necesita su aprobación para ejecutar una herramienta:","The agent needs your approval to run these tools:":"El agente necesita su aprobación para ejecutar estas herramientas:","The conversation could not be moved":"No se ha podido mover la conversación","The render did not finish":"El renderizado no ha finalizado","The workspace could not be created":"No se ha podido crear el espacio de trabajo","The workspace could not be deleted":"No se ha podido eliminar el espacio de trabajo","The workspace could not be renamed":"No se ha podido cambiar el nombre del espacio de trabajo","Thinking it through":"Reflexionando sobre ello","Thinking...":"Pensando...","This conversation could not be loaded.":"No se ha podido cargar esta conversación.","This decision could not be sent. Reload the chat and try again.":"No se ha podido enviar esta decisión. Actualice el chat e inténtelo de nuevo.","This message waits for the current response":"Este mensaje espera la respuesta actual","This message will be read with your next one.":"Este mensaje se leerá con su próximo mensaje.","This item could not be loaded.":"No se ha podido cargar este elemento.","The response could not be stopped. Try again.":"No se ha podido detener la respuesta. Inténtelo de nuevo.","This turn is no longer waiting for a decision.":"Este turno ya no está a la espera de una decisión.","Tool definitions":"Definiciones de herramientas","Tool results":"Resultados de las herramientas","Transfer chain":"Cadena de transferencia","Transferred from {agent}":"Transferido desde {agent}","Transferring to {agent}…":"Transfiriendo a {agent}…","Turn limit reached.":"Se ha alcanzado el límite de turnos.","Unable to connect. Please check the configuration.":"No se puede establecer conexión. Compruebe la configuración.","Unmute microphone":"Activar el micrófono","Untitled conversation":"Conversación sin título",Usage:"Uso","Usage · {period}":"Uso · {period}","Uses AI. Verify results.":"Utiliza IA. Verifique los resultados.","Using tools…":"Usando herramientas…",Video:"Vídeo","Voice call":"Llamada de voz","Waiting before continuing…":"Esperando antes de continuar…","Waiting for one background task…":"Esperando una tarea en segundo plano…","Waiting for your approval…":"Esperando su aprobación…","Waiting for {count} background tasks…":"Esperando {count} tareas en segundo plano…","Waiting to render":"Esperando el renderizado","What are the latest attack patterns?":"¿Cuáles son los últimos patrones de ataque?","What could be improved?":"¿Qué se podría mejorar?","Why not? The agent sees this and can adapt (optional)":"¿Por qué no? El agente ve esto y puede adaptarse (opcional)","Workspace name":"Nombre del espacio de trabajo",Workspaces:"Espacios de trabajo","Wrapping things up":"Finalizando",Yes:"Sí","Yes, always":"Sí, siempre","Your answer is ready":"Su respuesta está lista",default:"predeterminado","e.g. wrong environment — use staging instead":"Por ejemplo, entorno incorrecto: utilice el entorno de pruebas en su lugar","just now":"hace un momento","the agent":"el agente","this month":"este mes","this year":"este año",today:"hoy","unknown tool":"herramienta desconocida","{agent} has finished":"{agent} ha finalizado","{counts} tokens":"{counts} tokens","{count} iterations":"{count} iteraciones","{count} scenes":"{count} escenas","{count} sections":"{count} secciones","{count} slides":"{count} diapositivas","{count} tool calls":"{count} llamadas a herramientas","{count} transfers":"{count} transferencias","{count}d ago":"hace {count} d","{count}h ago":"hace {count} h","{count}m ago":"hace {count} min","{decided}/{total} decided":"{decided}/{total} decididos","{percent}% full":"{percent} % completo","{quota} (shared across all users)":"{quota} (compartido entre todos los usuarios)","{summary} — click for details":"{summary} — haga clic para ver más detalles","{tool} (+{count} more)…":"{tool} (+{count} más)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Se agotó el presupuesto de iteraciones del agente: la ejecución se detuvo antes de completar todos los pasos previstos. La respuesta final es un resumen aproximado del trabajo realizado hasta ahora.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Sí, siempre» guarda una preferencia para ti. Esa herramienta se ejecutará entonces sin preguntar, incluso en ejecuciones programadas que nadie supervisa, hasta que la revoques."},fr:{"(no output)":"(pas de sortie)","1 tool call":"1 appel d’outil","1 transfer":"1 transfert","A file failed to upload: remove it, or send once the answer ends":"Un fichier n’a pas pu être envoyé : retirez-le, ou envoyez une fois la réponse terminée","A message references at most {count} conversations":"Un message fait référence à {count} conversations au maximum","Acting on the page…":"Action sur la page…","Agent switching is not available here":"Le changement d’agent n’est pas disponible ici","Almost there":"On y est presque","Also applies to your scheduled runs, until you revoke it":"S’applique également à vos exécutions planifiées, jusqu’à ce que vous la révoquiez","Always allowed":"Toujours autorisé","Analyzing results…":"Analyse des résultats…","Analyzing the details":"Analyse des détails",Approved:"Approuvé","Ask Assistant":"Demander à l’assistant","Ask a question...":"Poser une question...",Assistant:"Assistant","Attach files":"Joindre des fichiers","Attached files":"Fichiers joints","Attachments wait for the current response":"Les pièces jointes attendent la réponse en cours",Back:"Retour","Bad response":"Réponse incorrecte","Browse agents":"Parcourir les agents",Cancel:"Annuler","Cancel question":"Annuler la question","Clear all conversations":"Effacer toutes les conversations",Close:"Fermer","Collecting results from one task…":"Collecte des résultats d’une tâche…","Collecting results from {count} tasks…":"Collecte des résultats de {count} tâches…","Composing answer…":"Rédaction de la réponse…",Confirm:"Confirmer","Connecting the dots":"Relier les points","Consulting the sources":"Consulter les sources","Consulting {agent}…":"Consultation de {agent}…","Context full — older turns are being dropped":"Contexte complet — les tours plus anciens sont supprimés","Context nearly full — older turns are being summarized":"Contexte presque plein — les tours plus anciens sont en cours de synthèse","Context used":"Contexte utilisé","Continue now":"Continuer maintenant",Conversation:"Conversation","Conversation history":"Historique des conversations","Conversation title":"Titre de la conversation","Conversation transcript":"Fil de la conversation",Copied:"Copié","Copied!":"Copié !","Copy code":"Copier le code","Copy message":"Copier le message","Copy response":"Copier la réponse","Could not reach the assistant service. Check the connection and try again.":"Impossible d’accéder au service d’assistant. Vérifiez la connexion et réessayez.","Could not send your decision. Please try again.":"Impossible d’envoyer votre décision. Veuillez réessayer.","Create agent":"Créer un agent","Crunching the data":"Traitement des données","Decline this call":"Refuser cet appel",Declined:"Refusé","Delegating one task…":"Délégation d’une tâche…","Delegating {count} tasks…":"Délégation de {count} tâches…","Delete all conversations":"Supprimer toutes les conversations","Delete all conversations?":"Supprimer toutes les conversations ?","Delete conversation":"Supprimer la conversation","Delete workspace":"Supprimer l’espace de travail","Delete?":"Supprimer ?","Dictate a message":"Dicter un message","Did not answer":"N’a pas répondu",Download:"Télécharger","Download {format}":"Télécharger en {format}","Drop a conversation here, or start one with +.":"Déposez une conversation ici ou démarrez-en une avec +.","Drop files to attach them":"Déposez des fichiers pour les joindre","End voice call":"Terminer l’appel vocal","Enter to send now · Esc to stop":"Appuyez sur Entrée pour envoyer maintenant · Appuyez sur Échap pour arrêter","Enter to send when the answer ends · Esc to stop":"Appuyez sur Entrée pour envoyer à la fin de la réponse · Appuyez sur Échap pour arrêter","Every conversation is in a workspace.":"Toutes les conversations sont dans un espace de travail.","Expand image":"Agrandir l’image","Failed to get a response. Resuming…":"Aucune réponse reçue. Reprise…","Feedback already submitted":"Avis déjà envoyé","Files uploading...":"Envoi des fichiers en cours...",Floating:"Flottant","Full screen":"Plein écran","Good response":"Bonne réponse","Help me create a new simulation scenario":"Aidez-moi à créer un nouveau scénario de simulation","Hide conversations":"Masquer les conversations","How can I help you, {name}?":"Comment puis-je vous aider, {name} ?","How can {agent} help you, {name}?":"Comment {agent} peut-il vous aider, {name} ?","How do I configure detection rules?":"Comment configurer les règles de détection ?","Image could not be loaded":"Impossible de charger l’image","Image preview":"Aperçu de l’image","Incorporating your message…":"Intégration de votre message…",Input:"Entrée","Insert prompt template":"Insérer un modèle de prompt","Listening...":"Écoute en cours...","Load earlier messages":"Charger les messages précédents","Loading image…":"Chargement de l’image…","MCP & dynamic tools":"MCP et outils dynamiques","Mention an agent":"Mentionner un agent","Model reasoning":"Raisonnement du modèle","Move to workspace":"Déplacer vers un espace de travail","Mute microphone":"Couper le micro",Muted:"Micro coupé","New chat":"Nouveau chat","New conversation":"Nouvelle conversation","New conversation in this workspace":"Nouvelle conversation dans cet espace de travail","New conversation — send a message to start it":"Nouvelle conversation — envoyez un message pour la démarrer","New workspace":"Nouvel espace de travail",No:"Non","No agent matches":"Aucun agent ne correspond","No conversation matches":"Aucune conversation ne correspond","No conversations yet":"Aucune conversation pour l’instant","No prompt matches":"Aucun prompt ne correspond","No response.":"Pas de réponse.","Not in a workspace":"Hors espace de travail","Not rendered yet":"Rendu non lancé",Open:"Ouvrir","Open conversation":"Ouvrir la conversation","Open in XTM One":"Ouvrir dans XTM One","Other workspaces":"Autres espaces de travail",Output:"Sortie","Play Space Invaders":"Jouer à Space Invaders","Play Space Invaders in XTM One":"Jouer à Space Invaders dans XTM One","Polishing the answer":"Peaufiner la réponse",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (modifiable)",Presentation:"Présentation","Putting it together":"Assemblage des éléments",Quota:"Quota","Quota reached":"Quota atteint","Read aloud":"Lire à voix haute","Reasoning details":"Détails du raisonnement","Reasoning details — turn limit reached":"Détails du raisonnement — limite de tours atteinte","Reconnecting…":"Reconnexion…","Reference a conversation":"Faire référence à une conversation","Remove from workspace":"Retirer de l’espace de travail","Rename conversation":"Renommer la conversation","Rename workspace":"Renommer l’espace de travail","Rendering {progress}%":"Rendu en cours : {progress} %",Report:"Rapport","Response ready":"Réponse prête","Reticulating splines":"Réticulation des splines",Retry:"Réessayer",Save:"Sauvegarder","Search agents...":"Rechercher des agents...","Search conversations...":"Rechercher des conversations...","Search prompts...":"Rechercher des prompts...",Send:"Envoyer","Send now":"Envoyer maintenant","Send when the answer ends":"Envoyer à la fin de la réponse","Sending…":"Envoi en cours…","Sends when the answer ends:":"Envoi à la fin de la réponse :","Shared with you":"Partagé avec vous","Show conversations":"Afficher les conversations",Sidebar:"Barre latérale",Skip:"Passer","Skip response":"Passer la réponse","Sorry, an error occurred. Please try again.":"Désolé, une erreur s’est produite. Veuillez réessayer.","Speak or tap to interrupt":"Parlez ou touchez pour interrompre","Speaking…":"Réponse en cours…","Stop dictation":"Arrêter la dictée","Stop generating":"Arrêter la génération","Stop reading":"Arrêter la lecture",Stopped:"Arrêté","Stopping…":"Arrêt en cours…",Suggestions:"Suggestions","Summarize my recent findings":"Résumez mes dernières découvertes","Summarized conversation":"Résumé de la conversation","Switch to":"Basculer vers","Switch to another agent":"Passer à un autre agent","Switch view":"Changer de vue","System prompt":"Prompt système","Tap to cancel":"Touchez pour annuler","Tell us what went wrong (optional)":"Dites-nous ce qui n’a pas fonctionné (facultatif)","The agent needs your approval to run a tool:":"L’agent a besoin de votre accord pour exécuter un outil :","The agent needs your approval to run these tools:":"L’agent a besoin de votre accord pour exécuter ces outils :","The conversation could not be moved":"Impossible de déplacer la conversation","The render did not finish":"Le rendu n’a pas abouti","The workspace could not be created":"Impossible de créer l’espace de travail","The workspace could not be deleted":"Impossible de supprimer l’espace de travail","The workspace could not be renamed":"Impossible de renommer l’espace de travail","Thinking it through":"Réfléchir à la question","Thinking...":"Je réfléchis...","This conversation could not be loaded.":"Impossible de charger cette conversation.","This decision could not be sent. Reload the chat and try again.":"Cette décision n’a pas pu être envoyée. Actualisez le chat et réessayez.","This message waits for the current response":"Ce message attend la réponse en cours","This message will be read with your next one.":"Ce message sera lu avec votre prochain message.","This item could not be loaded.":"Impossible de charger cet élément.","The response could not be stopped. Try again.":"La réponse n’a pas pu être arrêtée. Réessayez.","This turn is no longer waiting for a decision.":"Ce tour n’attend plus de décision.","Tool definitions":"Définitions des outils","Tool results":"Résultats des outils","Transfer chain":"Chaîne de transfert","Transferred from {agent}":"Transféré depuis {agent}","Transferring to {agent}…":"Transfert vers {agent}…","Turn limit reached.":"Limite de tours atteinte.","Unable to connect. Please check the configuration.":"Impossible de se connecter. Veuillez vérifier la configuration.","Unmute microphone":"Réactiver le micro","Untitled conversation":"Conversation sans titre",Usage:"Utilisation","Usage · {period}":"Utilisation · {period}","Uses AI. Verify results.":"Utilise l’IA. Vérifiez les résultats.","Using tools…":"Utilisation des outils…",Video:"Vidéo","Voice call":"Appel vocal","Waiting before continuing…":"En attente avant de continuer…","Waiting for one background task…":"En attente d’une tâche en arrière-plan…","Waiting for your approval…":"En attente de votre accord…","Waiting for {count} background tasks…":"En attente de {count} tâches en arrière-plan…","Waiting to render":"En attente du rendu","What are the latest attack patterns?":"Quels sont les derniers schémas d’attaque ?","What could be improved?":"Qu’est-ce qui pourrait être amélioré ?","Why not? The agent sees this and can adapt (optional)":"Pourquoi pas ? L’agent en prend connaissance et peut s’adapter (facultatif)","Workspace name":"Nom de l’espace de travail",Workspaces:"Espaces de travail","Wrapping things up":"Pour conclure",Yes:"Oui","Yes, always":"Oui, toujours","Your answer is ready":"Votre réponse est prête",default:"par défaut","e.g. wrong environment — use staging instead":"Par exemple : environnement incorrect — utilisez plutôt l’environnement de préproduction","just now":"à l’instant","the agent":"l’agent","this month":"ce mois-ci","this year":"cette année",today:"aujourd’hui","unknown tool":"outil inconnu","{agent} has finished":"{agent} a terminé","{counts} tokens":"{counts} tokens","{count} iterations":"{count} itérations","{count} scenes":"{count} scènes","{count} sections":"{count} sections","{count} slides":"{count} diapositives","{count} tool calls":"{count} appels d’outils","{count} transfers":"{count} transferts","{count}d ago":"il y a {count} j","{count}h ago":"il y a {count} h","{count}m ago":"il y a {count} min","{decided}/{total} decided":"{decided}/{total} décidés","{percent}% full":"{percent} % rempli","{quota} (shared across all users)":"{quota} (partagé entre tous les utilisateurs)","{summary} — click for details":"{summary} — cliquez pour plus de détails","{tool} (+{count} more)…":"{tool} (+{count} autres)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Le budget d’itérations de l’agent est épuisé : l’exécution s’est arrêtée avant la fin de toutes les étapes prévues. La réponse finale résume au mieux le travail accompli jusqu’ici.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"« Oui, toujours » enregistre une préférence pour vous. Cet outil s’exécutera alors sans demander, y compris lors des exécutions planifiées que personne ne surveille, jusqu’à ce que vous la révoquiez."},ja:{"(no output)":"(出力なし)","1 tool call":"ツール呼び出し 1 件","1 transfer":"転送 1 件","A file failed to upload: remove it, or send once the answer ends":"ファイルのアップロードに失敗しました。削除するか、応答の終了後に送信してください","A message references at most {count} conversations":"1 つのメッセージで参照できる会話は最大 {count} 件です","Acting on the page…":"ページを操作中…","Agent switching is not available here":"ここではエージェントの切り替えは利用できません","Almost there":"もうすぐ完了します","Also applies to your scheduled runs, until you revoke it":"予定された実行についても、取り消すまでは同様に適用されます","Always allowed":"常に許可","Analyzing results…":"結果を分析中…","Analyzing the details":"詳細を分析しています",Approved:"承認済み","Ask Assistant":"アシスタントに質問","Ask a question...":"質問する...",Assistant:"アシスタント","Attach files":"ファイルを添付","Attached files":"添付ファイル","Attachments wait for the current response":"添付ファイルは、現在の応答を待機します",Back:"戻る","Bad response":"不適切な回答","Browse agents":"エージェントを閲覧する",Cancel:"キャンセル","Cancel question":"質問をキャンセル","Clear all conversations":"すべての会話を消去",Close:"閉じる","Collecting results from one task…":"1 件のタスクの結果を収集中…","Collecting results from {count} tasks…":"{count} 件のタスクの結果を収集中…","Composing answer…":"回答を作成中…",Confirm:"確認する","Connecting the dots":"情報を関連付けています","Consulting the sources":"情報源を確認しています","Consulting {agent}…":"{agent} に問い合わせ中…","Context full — older turns are being dropped":"コンテキストが満杯 — 古いターンが削除されています","Context nearly full — older turns are being summarized":"コンテキストがほぼ満杯です — 古いターンが要約されています","Context used":"使用されたコンテキスト","Continue now":"今すぐ続行",Conversation:"会話","Conversation history":"会話履歴","Conversation title":"会話のタイトル","Conversation transcript":"会話の履歴",Copied:"コピーしました","Copied!":"コピー完了!","Copy code":"コードをコピー","Copy message":"メッセージをコピー","Copy response":"応答をコピー","Could not reach the assistant service. Check the connection and try again.":"アシスタントサービスに接続できませんでした。接続状態を確認して、もう一度お試しください。","Could not send your decision. Please try again.":"決定内容を送信できませんでした。もう一度お試しください。","Create agent":"エージェントを作成する","Crunching the data":"データを処理しています","Decline this call":"この呼び出しを拒否",Declined:"拒否済み","Delegating one task…":"1 件のタスクを委任中…","Delegating {count} tasks…":"{count} 件のタスクを委任中…","Delete all conversations":"すべての会話を削除","Delete all conversations?":"すべての会話を削除しますか?","Delete conversation":"会話を削除","Delete workspace":"ワークスペースを削除","Delete?":"削除しますか?","Dictate a message":"メッセージを音声入力する","Did not answer":"回答なし",Download:"ダウンロード","Download {format}":"{format} をダウンロード","Drop a conversation here, or start one with +.":"ここに会話をドロップするか、+ で新しく開始してください。","Drop files to attach them":"ファイルをドロップして添付","End voice call":"音声通話を終了","Enter to send now · Esc to stop":"Enterキーで今すぐ送信 · Escキーで停止","Enter to send when the answer ends · Esc to stop":"Enterキーで回答の終了後に送信 · Escキーで停止","Every conversation is in a workspace.":"すべての会話がワークスペースに含まれています。","Expand image":"画像を拡大","Failed to get a response. Resuming…":"応答を取得できませんでした。再開しています…","Feedback already submitted":"フィードバックは送信済みです","Files uploading...":"ファイルのアップロード中...",Floating:"フローティング","Full screen":"全画面表示","Good response":"適切な回答","Help me create a new simulation scenario":"新しいシミュレーションシナリオの作成を手伝ってください","Hide conversations":"会話を非表示にする","How can I help you, {name}?":"{name} さん、何かお手伝いできることはありますか?","How can {agent} help you, {name}?":"{name} さん、{agent} がお手伝いできることはありますか?","How do I configure detection rules?":"検出ルールはどのように設定すればよいですか?","Image could not be loaded":"画像を読み込めませんでした","Image preview":"画像プレビュー","Incorporating your message…":"メッセージを組み込んでいます…",Input:"入力","Insert prompt template":"プロンプトテンプレートを挿入","Listening...":"聞き取り中...","Load earlier messages":"以前のメッセージを読み込む","Loading image…":"画像を読み込み中…","MCP & dynamic tools":"MCPと動的ツール","Mention an agent":"エージェントをメンション","Model reasoning":"モデルの推論","Move to workspace":"ワークスペースに移動","Mute microphone":"マイクをミュート",Muted:"ミュート中","New chat":"新しいチャット","New conversation":"新しい会話","New conversation in this workspace":"このワークスペースで新しい会話","New conversation — send a message to start it":"新しい会話 — メッセージを送信すると開始されます","New workspace":"新しいワークスペース",No:"いいえ","No agent matches":"該当するエージェントはありません","No conversation matches":"一致する会話はありません","No conversations yet":"まだ会話はありません","No prompt matches":"一致するプロンプトはありません","No response.":"応答なし。","Not in a workspace":"ワークスペースなし","Not rendered yet":"まだレンダリングされていません",Open:"開く","Open conversation":"会話を開く","Open in XTM One":"XTM One で開く","Other workspaces":"その他のワークスペース",Output:"出力","Play Space Invaders":"Space Invaders をプレイ","Play Space Invaders in XTM One":"XTM One で Space Invaders をプレイ","Polishing the answer":"回答を仕上げています",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint(編集可能)",Presentation:"プレゼンテーション","Putting it together":"内容をまとめています",Quota:"クォータ","Quota reached":"クォータに達しました","Read aloud":"読み上げ","Reasoning details":"推論の詳細","Reasoning details — turn limit reached":"推論の詳細 — ターン制限に達しました","Reconnecting…":"再接続中…","Reference a conversation":"会話を参照","Remove from workspace":"ワークスペースから外す","Rename conversation":"会話の名前を変更","Rename workspace":"ワークスペースの名前を変更","Rendering {progress}%":"レンダリング中 {progress}%",Report:"レポート","Response ready":"応答準備完了","Reticulating splines":"スプラインを網状化しています",Retry:"再試行",Save:"保存","Search agents...":"エージェントを検索...","Search conversations...":"会話を検索...","Search prompts...":"プロンプトを検索...",Send:"送信","Send now":"今すぐ送信","Send when the answer ends":"回答の終了後に送信","Sending…":"送信中…","Sends when the answer ends:":"回答の終了後に送信:","Shared with you":"他のユーザーから共有","Show conversations":"会話を表示",Sidebar:"サイドバー",Skip:"スキップ","Skip response":"応答をスキップ","Sorry, an error occurred. Please try again.":"申し訳ありません。エラーが発生しました。もう一度お試しください。","Speak or tap to interrupt":"話すかタップして中断","Speaking…":"読み上げ中…","Stop dictation":"ディクテーションを停止","Stop generating":"生成を停止","Stop reading":"読み上げを停止",Stopped:"停止","Stopping…":"停止中…",Suggestions:"提案","Summarize my recent findings":"私の最近の発見を要約してください","Summarized conversation":"会話の要約","Switch to":"切り替え先","Switch to another agent":"別のエージェントに切り替える","Switch view":"ビューを切り替える","System prompt":"システムプロンプト","Tap to cancel":"タップしてキャンセル","Tell us what went wrong (optional)":"問題があった点をお聞かせください(任意)","The agent needs your approval to run a tool:":"エージェントがツールを実行するには、あなたの承認が必要です:","The agent needs your approval to run these tools:":"エージェントがこれらのツールを実行するには、あなたの承認が必要です:","The conversation could not be moved":"会話を移動できませんでした","The render did not finish":"レンダリングが完了しませんでした","The workspace could not be created":"ワークスペースを作成できませんでした","The workspace could not be deleted":"ワークスペースを削除できませんでした","The workspace could not be renamed":"ワークスペースの名前を変更できませんでした","Thinking it through":"じっくり考えています","Thinking...":"考え中...","This conversation could not be loaded.":"この会話を読み込めませんでした。","This decision could not be sent. Reload the chat and try again.":"この決定を送信できませんでした。チャットを再読み込みして、もう一度お試しください。","This message waits for the current response":"このメッセージは、現在の応答を待機します","This message will be read with your next one.":"このメッセージは次のメッセージと一緒に読まれます。","This item could not be loaded.":"この項目を読み込めませんでした。","The response could not be stopped. Try again.":"応答を停止できませんでした。もう一度お試しください。","This turn is no longer waiting for a decision.":"このターンでは、決定を待つ必要がなくなりました。","Tool definitions":"ツールの定義","Tool results":"ツールの結果","Transfer chain":"転送チェーン","Transferred from {agent}":"{agent} から転送されました","Transferring to {agent}…":"{agent} に転送中…","Turn limit reached.":"ターン制限に達しました。","Unable to connect. Please check the configuration.":"接続できません。設定を確認してください。","Unmute microphone":"マイクのミュートを解除","Untitled conversation":"タイトルのない会話",Usage:"使用状況","Usage · {period}":"使用状況 · {period}","Uses AI. Verify results.":"AIを使用しています。結果を確認してください。","Using tools…":"ツールを使用中…",Video:"動画","Voice call":"音声通話","Waiting before continuing…":"続行する前に待機中…","Waiting for one background task…":"バックグラウンドタスク 1 件を待機中…","Waiting for your approval…":"承認をお待ちしています…","Waiting for {count} background tasks…":"バックグラウンドタスク {count} 件を待機中…","Waiting to render":"レンダリング待ち","What are the latest attack patterns?":"最新の攻撃パターンにはどのようなものがありますか?","What could be improved?":"改善できる点はありますか?","Why not? The agent sees this and can adapt (optional)":"なぜですか? エージェントはこれを確認し、対応を調整できます(任意)","Workspace name":"ワークスペース名",Workspaces:"ワークスペース","Wrapping things up":"仕上げをしています",Yes:"はい","Yes, always":"はい、常に","Your answer is ready":"回答の準備が整いました",default:"デフォルト","e.g. wrong environment — use staging instead":"例:環境が間違っている — 代わりにステージング環境を使用してください","just now":"たった今","the agent":"エージェント","this month":"今月","this year":"今年",today:"今日","unknown tool":"不明なツール","{agent} has finished":"{agent} が完了しました","{counts} tokens":"{counts} トークン","{count} iterations":"{count} 回の反復","{count} scenes":"{count} シーン","{count} sections":"{count} セクション","{count} slides":"{count} スライド","{count} tool calls":"ツール呼び出し {count} 件","{count} transfers":"転送 {count} 件","{count}d ago":"{count} 日前","{count}h ago":"{count} 時間前","{count}m ago":"{count} 分前","{decided}/{total} decided":"{decided}/{total} 件が決定済み","{percent}% full":"{percent} % 使用中","{quota} (shared across all users)":"{quota}(全ユーザーで共有)","{summary} — click for details":"{summary} — クリックで詳細を表示","{tool} (+{count} more)…":"{tool}(他 {count} 件)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"エージェントの反復回数の上限に達したため、予定されたすべてのステップを完了する前に実行が停止しました。最終的な回答は、これまでに行った作業をできる限りまとめたものです。","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"「はい、常に」を選ぶと、あなたの設定として保存されます。以後、そのツールは確認なしで実行されます(誰も見ていない定期実行を含む)。取り消すまでこの設定は有効です。"}};function te(e,t){const n=t||!e?function(e){const t=e??("undefined"!=typeof navigator?navigator.language:void 0),n=t?.toLowerCase().split(/[-_]/)[0];return n?ee[n]:void 0}(t):void 0;return t=>{const r=e?.(t);return r&&r!==t?r:n?.[t]??t}}const ne=e=>"up"===e?"positive":"negative";function re(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function oe(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function ae(e,t,n){return X(e,t,n,"feedback")}async function se(e,t,n,r,o,a){const{url:s,init:i}=function(e,t,n,r,o){const a=`${e}/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}/feedback`;return r?{url:a,init:{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...o},body:JSON.stringify({rating:r.rating,comment:oe(r.comment)})}}:{url:a,init:{method:"DELETE",credentials:"include",headers:{...o}}}}(t,n,r,o,a);try{return(await e(s,i)).ok}catch{return!1}}const ie=e=>void 0!==e&&/[\w-]/.test(e),ce=/^[\w-]+$/;function le(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const o=r[1].toLowerCase();ie(e[r.index-1])||t.includes(o)||t.push(o),r=n.exec(e)}return t}function de(e,t){if(0===e.length)return e;const n=new Set(le(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function ue(e,t){if(0===e.length)return[];const n=[];for(const r of le(t))for(const t of e)t.key.toLowerCase()!==r||n.some(e=>e.conversationId===t.conversationId)||n.push(t);return n.slice(0,5)}function pe(e){const t=Array.isArray(e)?e:Array.isArray(e?.conversations)?e.conversations:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.id&&t.id&&"string"==typeof t.key&&ce.test(t.key)&&(n.some(e=>e.id===t.id)||n.push({id:t.id,title:"string"==typeof t.title?t.title.trim():"",key:t.key,updatedAt:"string"==typeof t.updated_at?t.updated_at:void 0,isOwn:!1!==t.is_own}))}return n}function he(e,t,n){return X(e,t,n,"conversationReferences")}const me={query:null,items:[],failed:!1};function fe(e,t){const n=e.toLowerCase();if(!n||t.key.toLowerCase().startsWith(n))return!0;const r=t.title.toLowerCase(),o=n.split(/[\s_-]+/).filter(Boolean);return o.length>0&&o.every(e=>r.includes(e))}function ge(e,t){if(t.every(t=>e.some(e=>{return r=t,(n=e).id===r.id&&n.key===r.key&&n.title===r.title&&n.isOwn===r.isOwn&&n.updatedAt===r.updatedAt;var n,r})))return e;const n=new Set(t.map(e=>e.id)),r=[...e.filter(e=>!n.has(e.id)),...t];return r.length>200?r.slice(r.length-200):r}function ve(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function we(e,t={}){const n=Array.isArray(e)?e:Array.isArray(e?.workspaces)?e.workspaces:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const n=e;"string"==typeof n.id&&n.id&&"string"==typeof n.name&&(!0!==n.is_archived&&r.push({id:n.id,name:n.name,isOwn:"boolean"==typeof n.is_own?n.is_own:!!t.userId&&n.user_id===t.userId,isDefault:!0===n.is_default,canManage:!0===n.can_manage}))}return r}function ye(e){const t=e=>e.isDefault&&e.isOwn;return[...e].sort((e,n)=>t(e)!==t(n)?t(e)?-1:1:e.name.localeCompare(n.name))}function be(e,t,n,r,o){return!!o||(!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e))}function xe(e,t,n){return!n&&!(t&&e.conversations.some(e=>e.conversationId===t))}const ke=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&t.length<=500?t:null};async function Ne(e){try{return function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;return ke(e.message)??ke(e.detail)}return ke(t)}(await e.json())}catch{return null}}function Ce(e){return e?JSON.stringify(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0)):""}function Se(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}const Ie=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function Te(e){const t=e.context_tokens,n=e.context_window;if("number"!=typeof t||"number"!=typeof n)return;if(!Number.isFinite(t)||!Number.isFinite(n)||n<=0||t<0)return;const r=function(e){if(!e||"object"!=typeof e)return;const t=e,n={};let r=!1;for(const[e,o]of Ie){const a=t[e];"number"==typeof a&&Number.isFinite(a)&&a>0&&(n[o]=a,r=!0)}return r?n:void 0}(e.context_breakdown);return r?{used:t,limit:n,breakdown:r}:{used:t,limit:n}}function Ae(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.file_id;"string"==typeof r&&r&&t.push({fileId:r,filename:"string"==typeof e.filename?e.filename:"file",type:"string"==typeof e.type?e.type:void 0,size:"number"==typeof e.size?e.size:void 0,contentType:"string"==typeof e.content_type?e.content_type:void 0,fileTag:"working_file"===e.file_tag?"working_file":"download_file"})}return t.length>0?t:void 0}const _e=["presentation","report","video"],Ee=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function Me(e){if(!e||"object"!=typeof e)return;const t=e,n=_e.find(e=>e===t.kind);return n&&"string"==typeof t.id&&t.id?{kind:n,id:t.id,title:"string"==typeof t.title?t.title:"",url:"string"==typeof t.url&&t.url?t.url:void 0,slideRef:"string"==typeof t.slide_ref&&t.slide_ref?t.slide_ref:void 0,slideCount:Ee(t.slide_count),sectionCount:Ee(t.section_count),sceneCount:Ee(t.scene_count),durationMs:Ee(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:Ee(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function Le(e){if(!Array.isArray(e))return;const t=e.map(Me).filter(e=>!!e);return t.length>0?t:void 0}function Re(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.name&&e.name&&t.push({name:e.name,input:"string"==typeof e.input?e.input:void 0,output:"string"==typeof e.output?e.output:void 0,success:"boolean"!=typeof e.success||e.success})}return t.length>0?t:void 0}function $e(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.conversation_id&&e.conversation_id&&(t.some(t=>t.conversationId===e.conversation_id)||t.push({conversationId:e.conversation_id,title:"string"==typeof e.title?e.title.trim():"",key:"string"==typeof e.key?e.key:""}))}return t.length>0?t:void 0}function De(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.agent_name&&e.agent_name&&t.push({agentId:"string"==typeof e.agent_id?e.agent_id:"",agentName:e.agent_name})}return t.length>0?t:void 0}function ze(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.tool_call_id;if("string"!=typeof r||!r)continue;const o=e.arguments,a=e.input_schema;t.push({toolCallId:r,toolName:"string"==typeof e.tool_name&&e.tool_name?e.tool_name:"",toolDescription:"string"==typeof e.tool_description?e.tool_description:void 0,arguments:o&&"object"==typeof o&&!Array.isArray(o)?o:{},inputSchema:a&&"object"==typeof a&&!Array.isArray(a)?a:void 0,source:"string"==typeof e.source?e.source:void 0})}return t.length>0?t:void 0}const je=e=>"string"==typeof e&&e?e:void 0;function Oe(e){if("string"==typeof e)return e?{agentName:e}:void 0;if(!e||"object"!=typeof e)return;const t=e,n={agentId:je(t.agent_id),agentName:je(t.agent_name)??je(t.name),agentIcon:je(t.agent_icon)};return n.agentId||n.agentName?Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)):void 0}function Pe(e,t){const n=e.type;if("error"===n||"cancelled"===n){const t=je(e.message_id),r=!0===e.provisional||void 0,o={...t?{messageId:t,raw:{...e}}:{},...r?{provisional:r}:{}};return"error"===n?{action:"error",content:e.content||"",...o}:{action:"cancelled",...o}}if("session_expired"===n)return{action:"session_ended",reason:je(e.reason)};if("approval_resolved"===n)return{action:"approval_resolved"};if("folded_into_active_turn"===n)return{action:"folded",turnId:je(e.turn_id)};if("conversation_title"===n){const t=je(e.title);return t?{action:"conversation_title",conversationId:je(e.conversation_id),title:t}:{action:"noop"}}if("user_message"===n){const[t]=We([e.message]);return t&&"user"===t.role?{action:"user_message",message:{...t,id:Ue(t.serverId)}}:{action:"noop"}}if("thinking"===n)return{action:"status",status:"thinking",resumed:!0===e.resumed||void 0,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};if("status"===n){const n=e.status;if("tool_done"===n||"wind_down"===n)return{action:"noop"};if("streaming"===n)return{action:"status",status:"streaming"};if("thinking_text"===n)return{action:"status",status:"thinking_text",thinkingContent:e.content};if("tool_start"===n)return t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:e.tools};if("tool_progress"===n&&"page_action_required"===e.event){if("string"!=typeof e.action_id||!e.action_id)return{action:"noop"};const t=function(e){if(!e||"object"!=typeof e)return{type:"unsupported",requested:"malformed"};const t=e,n=e=>"string"==typeof e&&e.length>0;return"snapshot"===t.type?{type:"snapshot"}:"navigate"===t.type&&n(t.path)?{type:"navigate",path:t.path}:"click"===t.type&&n(t.ref)?{type:"click",ref:t.ref}:"open"===t.type&&n(t.ref)?{type:"open",ref:t.ref}:"type"===t.type&&n(t.ref)&&"string"==typeof t.text?{type:"type",ref:t.ref,text:t.text}:{type:"unsupported",requested:"string"==typeof t.type?t.type.slice(0,64):"unknown"}}(e.action);return{action:"page_action_required",actionId:e.action_id,pageAction:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}}if("wait_start"===n)return{action:"status",status:"wait_start",waitSeconds:"number"==typeof e.seconds&&e.seconds>0?e.seconds:void 0,waitReason:je(e.reason)};if("tool_heartbeat"===n)return{action:"status",status:"tool_heartbeat",tools:e.tools,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};const r=Te(e);return"thinking"===n&&t.hasUsedTools?{action:"status",status:"analyzing",contextUsage:r}:{action:"status",status:n,tools:e.tools,contextUsage:r}}if("approval_required"===n){const t=ze(e.proposals);return t?{action:"approval_required",proposals:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}:{action:"noop"}}return"stream"===n?{action:"stream",content:e.content}:"done"===n?{action:"done",content:e.content,conversationId:e.conversation_id,toolNames:e.tool_names,toolCallCount:e.tool_call_count,iterations:e.iterations,transferAgentId:e.transfer_agent_id,transferAgentName:e.transfer_agent_name,attachments:Ae(e.attachments),artifacts:Le(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:Re(e.tool_call_trace),transferChain:De(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:Te(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0,intermediate:!0===e.intermediate||void 0,answeredBy:Oe(e.answered_by),mentionFailed:!0===e.mention_failed||void 0,raw:{...e}}:{action:"noop"}}function Ue(e,t=Se()){return e?`msg-${e}`:t}function He(e){if(!e||"object"!=typeof e)return;const{rating:t,comment:n}=e;return"positive"===t||"negative"===t?{rating:t,comment:"string"==typeof n&&n.trim()?n:null}:void 0}function We(e){if(!Array.isArray(e))return[];const t=[];return e.forEach((e,n)=>{if(!e||"object"!=typeof e)return;const r=e;if("user"!==r.role&&"assistant"!==r.role)return;const o="string"==typeof r.created_at?new Date(r.created_at):null,a=o&&!Number.isNaN(o.getTime())?o:null,s="assistant"===r.role?Oe(r.answered_by):void 0,i="string"==typeof r.id&&r.id?r.id:void 0;t.push({id:Ue(i,`restored-${n}`),serverId:i,role:r.role,content:"string"==typeof r.content?r.content:"",timestamp:a??new Date,timestampUnknown:!a||void 0,feedback:"assistant"===r.role?He(r.feedback):void 0,agentName:s?.agentName??("string"==typeof r.agent_name?r.agent_name:void 0),answeredBy:s,mentionFailed:"assistant"===r.role&&!0===r.mention_failed||void 0,attachments:Ae(r.attachments),artifacts:"assistant"===r.role?Le(r.artifacts):void 0,conversationRefs:"user"===r.role?$e(r.conversation_refs):void 0,toolNames:Array.isArray(r.tool_names)?r.tool_names:void 0,toolCallCount:"number"==typeof r.tool_call_count?r.tool_call_count:void 0,iterations:"number"==typeof r.iterations?r.iterations:void 0,reasoning:"string"==typeof r.reasoning?r.reasoning:void 0,toolCallTrace:Re(r.tool_call_trace),transferChain:De(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0,raw:{...r}})}),t}function qe(e,t){const n=e.event;if("nextAgentFlow"===n){const n=e.data,r=n?.nodeId;return"INPROGRESS"===n?.status&&r&&(t.activeNodeId=r),{action:"noop"}}if("start"===n)return{action:"noop"};if("token"===n){return{action:"stream",content:(e.data??"").replace(/<br\s*\/?>/g,"\n")}}if("agentReasoning"===n){const n=e.data,r=n?.usedTools;return r?.length?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:r.map(e=>e.tool)}):t.hasUsedTools?{action:"status",status:"analyzing"}:{action:"status",status:"thinking"}}if("usedTools"===n){t.hasUsedTools=!0;const n=e.data;return{action:"status",status:"tool_start",tools:Array.isArray(n)?n.map(e=>e.tool):[]}}if("metadata"===n){const t=e.data,n=t?.chatId;return n?{action:"set_chat_id",chatId:n}:{action:"noop"}}return"error"===n?{action:"error",content:e.data||""}:"end"===n?{action:"done",content:""}:{action:"noop"}}function Be(e,t){const n=e.type;if("RUN_STARTED"===n)return{action:"status",status:"thinking"};if("RUN_FINISHED"===n)return{action:"done",content:""};if("RUN_ERROR"===n)return{action:"error",content:"string"==typeof e.message?e.message:""};if("STEP_STARTED"===n){return{action:"status",status:e.stepName||"thinking"}}if("STEP_FINISHED"===n)return{action:"noop"};if("TEXT_MESSAGE_START"===n)return{action:"status",status:"streaming"};if("TEXT_MESSAGE_CONTENT"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TEXT_MESSAGE_END"===n)return{action:"noop"};if("TEXT_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TOOL_CALL_START"===n){t.hasUsedTools=!0;const n=e.toolCallName;return{action:"status",status:"tool_start",tools:n?[n]:[]}}if("TOOL_CALL_ARGS"===n)return{action:"noop"};if("TOOL_CALL_END"===n)return{action:"status",status:"analyzing"};if("TOOL_CALL_RESULT"===n)return{action:"noop"};if("TOOL_CALL_CHUNK"===n){const n=e.toolCallName;return n?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:[n]}):{action:"noop"}}if("REASONING_START"===n||"REASONING_MESSAGE_START"===n)return{action:"status",status:"thinking"};if("REASONING_MESSAGE_CONTENT"===n||"REASONING_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"status",status:"thinking_text",thinkingContent:t}:{action:"status",status:"thinking"}}return{action:"noop"}}function Fe(){let e=0,t=null,n=null;return{get generation(){return e},get pending(){return t},run(r){if(t)return t;const o=e,a=new AbortController;n=a;const s=r(()=>o===e,a.signal).catch(()=>null);return t=s,s.finally(()=>{t===s&&(t=null),n===a&&(n=null)}),s},abandon(){e+=1,t=null,n?.abort(),n=null}}}function Ve(e,t){return null!==e&&"function"==typeof t}function Ke(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const Ge=(e,t)=>{const n=t??Ke();if(!e||!n)return null;try{const t=new URL(e,n);if("http:"!==t.protocol&&"https:"!==t.protocol)return null;if(t.origin!==new URL(n).origin)return null;const r=`${t.pathname}${t.search}${t.hash}`||"/";return r.startsWith("//")?null:r}catch{return null}};function Je(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const Ye=/^(current-password|new-password|one-time-code|cc-)/;function Xe(e){const t=e.ownerDocument.defaultView,n={bubbles:!0,cancelable:!0,view:t??void 0,pointerType:"mouse"},r=t?.PointerEvent??t?.MouseEvent??MouseEvent,o=t?.MouseEvent??MouseEvent;e.dispatchEvent(new r("pointerover",n)),e.dispatchEvent(new r("pointerenter",{...n,bubbles:!1})),e.dispatchEvent(new o("mouseover",n)),e.dispatchEvent(new o("mouseenter",{...n,bubbles:!1}))}function Ze(e,t,n){const r=e=>e.preventDefault();for(const n of t)e.addEventListener(n,r,!0);try{n()}finally{for(const n of t)e.removeEventListener(n,r,!0)}}function Qe(e,t,n){if(e.matches?.("a[href]")){const r=e.getAttribute("target");if(r&&"_self"!==r)return{ok:!1,error:"opens_new_tab"};const o=e.getAttribute("href")??"";if(o&&!o.startsWith("#")){const e=Ge(o,n);if(!e)return{ok:!1,error:"external_link"};if(t)return t(e),{ok:!0}}}e.focus?.();const r=e.closest?.("a[href]"),o=!!r&&!(r.getAttribute("href")??"").startsWith("#"),a=o?["submit","click"]:["submit"],s=e.matches?.('input[type="checkbox"], input[type="radio"]')??!1,i=e.checked;if(Ze(e.ownerDocument,a,()=>e.click()),s&&o&&e.checked===i){const t=e;t.checked="radio"===t.type||!i,t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("input",{bubbles:!0})),t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("change",{bubbles:!0}))}return{ok:!0}}function et(e){const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!1}for(let t=e;t;t=t.parentElement){if(t.hidden||t.hasAttribute("inert"))return!1;if("true"===t.getAttribute("aria-hidden"))return!1;const e=t.ownerDocument.defaultView?.getComputedStyle(t);if("none"===e?.display||"hidden"===e?.visibility)return!1}return!0}function tt(e){const t=e.getAttribute("aria-expanded");if("true"===t)return!0;if("false"===t)return!1;const n=e.getAttribute("aria-controls");if(!n)return!1;const r=e.ownerDocument.getElementById(n);return!!r&&et(r)}async function nt(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(tt(e))return{ok:!0};if(r){if(Xe(e),await(o=()=>tt(e),a=300,new Promise(e=>{const t=Date.now(),n=()=>o()?e(!0):Date.now()-t>=a?e(!1):void setTimeout(n,30);n()})))return{ok:!0}}else if(await function(e,t,n=300){const r=e.defaultView,o=r?.MutationObserver??globalThis.MutationObserver;return o?new Promise(r=>{const a=new o(e=>{e.some(e=>e.addedNodes.length>0&&!Je(e.target)&&Array.from(e.addedNodes).some(e=>!Je(e)))&&(a.disconnect(),clearTimeout(s),r(!0))});a.observe(e.body??e.documentElement,{subtree:!0,childList:!0}),t();const s=setTimeout(()=>{a.disconnect(),r(!1)},n)}):(t(),Promise.resolve(!0))}(e.ownerDocument,()=>Xe(e)))return{ok:!0};var o,a;return n?.aborted?{ok:!1,error:"aborted"}:Qe(e,void 0,t)}const rt=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function ot(e,t,n,r,o){try{if(o?.aborted)return{ok:!1,error:"aborted"};if("snapshot"===e.type)return{ok:!0};if("unsupported"===e.type)return{ok:!1,error:`unsupported_action: ${e.requested}`.slice(0,500)};if("navigate"===e.type){if(!n)return{ok:!1,error:"navigation_unavailable"};const t=Ge(e.path,Ke(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const a=t.get(e.ref);return a&&a.isConnected?et(a)?function(e){if(e.hasAttribute("disabled"))return!0;if("true"===e.getAttribute("aria-disabled"))return!0;if(e.matches?.(":disabled"))return!0;if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(a)?{ok:!1,error:"disabled"}:a.matches?.('input[type="file"]')?{ok:!1,error:"opens_file_dialog"}:"open"===e.type?await nt(a,Ke(r??a.ownerDocument),o):"click"===e.type?Qe(a,n,Ke(r??a.ownerDocument)):function(e){return e.matches?.('textarea, [contenteditable="true"], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="number"]')??!1}(a)?function(e){return!0===e.readOnly||"true"===e.getAttribute("aria-readonly")}(a)?{ok:!1,error:"read_only"}:function(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>Ye.test(e))}(a)?{ok:!1,error:"secret_field"}:(a.focus?.(),function(e,t){const n=e.ownerDocument.defaultView;if(n&&(e instanceof n.HTMLInputElement||e instanceof n.HTMLTextAreaElement)){const r=e instanceof n.HTMLInputElement?n.HTMLInputElement.prototype:n.HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(r,"value")?.set?.call(e,t)}else e.textContent=t;e.dispatchEvent(new(n?.Event??Event)("input",{bubbles:!0})),e.dispatchEvent(new(n?.Event??Event)("change",{bubbles:!0}))}(a,e.text),function(e){if("searchbox"===e.getAttribute("role"))return!0;if("search"===e.type)return!0;if(null!==e.closest('[role="search"]'))return!0;if(!["name","id","placeholder","aria-label","title"].some(t=>rt.test(e.getAttribute(t)??"")))return!1;const t=e.form;return!t||1===t.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]), select, textarea, [contenteditable="true"]').length}(a)&&function(e){const t=e.ownerDocument.defaultView,n=t?.KeyboardEvent??KeyboardEvent,r={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:!0,cancelable:!0},o=new n("keydown",r);e.dispatchEvent(o),e.dispatchEvent(new n("keyup",r));const a=e.form;a&&!o.defaultPrevented&&Ze(e.ownerDocument,["submit"],()=>a.requestSubmit?.())}(a),{ok:!0}):{ok:!1,error:"not_a_text_field"}:{ok:!1,error:"not_visible"}:{ok:!1,error:"unknown_ref"}}catch(e){return{ok:!1,error:`failed: ${e instanceof Error?e.message:String(e)}`.slice(0,500)}}}const at="[truncated]",st=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function it(e){if("select"===e.tagName.toLowerCase())return!1;for(const t of Array.from(e.querySelectorAll('a[href], button, summary, select, textarea, input, [contenteditable="true"], [role]')))if(ct(t))return!0;return!1}function ct(e){const t=e.getAttribute("role");if(t&&st.has(t))return t;const n=e.tagName.toLowerCase();if("a"===n&&e.hasAttribute("href"))return"link";if("button"===n||"summary"===n)return"button";if("select"===n)return"combobox";if("textarea"===n)return"textbox";if("input"===n){const t=(e.getAttribute("type")||"text").toLowerCase();return"hidden"===t?null:["button","submit","reset","image"].includes(t)?"button":"checkbox"===t||"radio"===t?t:"search"===t?"searchbox":"file"===t?"button":"textbox"}return"true"===e.getAttribute("contenteditable")?"textbox":null}function lt(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function dt(e){const t=e.ownerDocument.defaultView;let n="";for(const r of Array.from(e.childNodes))if(3===r.nodeType)n+=r.textContent??"";else if(1===r.nodeType){if(bt(r)||vt(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?dt(r):` ${dt(r)} `}return n}function ut(e){return(e??"").replace(/\s+/g," ").trim()}const pt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function ht(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=ut(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const o=ut(e.getAttribute("aria-label"));if(o)return o;const a=e.getAttribute("id"),s=a&&Array.from(n.getElementsByTagName("label")).find(e=>e.htmlFor===a)||e.closest("label");if(s){const e=ut(Array.from(s.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||ut(s.textContent))return e||ut(s.textContent)}const i=e.tagName.toLowerCase(),c=(e.getAttribute("type")||"").toLowerCase();if("input"===i&&["submit","reset","button"].includes(c)){const t=ut(e.getAttribute("value"));if(t)return t;if("button"!==c)return"submit"===c?"Submit":"Reset"}const l=ut(e.getAttribute("alt"))||ut(e.querySelector("img[alt]")?.getAttribute("alt"));if(l)return l;const d=vt(e)?"":ut(dt(e));if(pt.has(t)&&d)return d;const u=ut(e.getAttribute("placeholder"));if(u)return u;const p=ut(e.getAttribute("title"));return p||d}function mt(e){return JSON.stringify(e.slice(0,80))}function ft(e){const t=[];(e.hasAttribute("disabled")||function(e){if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(e)||"true"===e.getAttribute("aria-disabled"))&&t.push("disabled"),"true"===e.getAttribute("aria-selected")&&t.push("selected"),(e.checked||"true"===e.getAttribute("aria-checked"))&&t.push("checked"),"true"===e.getAttribute("aria-expanded")?t.push("expanded"):"false"!==(e.getAttribute("aria-haspopup")??"false")?t.push("menu"):"false"===e.getAttribute("aria-expanded")&&t.push("collapsed"),"true"===e.getAttribute("aria-pressed")&&t.push("pressed");const n=e.getAttribute("aria-current");return n&&"false"!==n&&t.push("current"),t}const gt=/^(current-password|new-password|one-time-code|cc-)/;function vt(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>gt.test(e))}function wt(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(vt(e))return null;const n="value"in e?String(e.value??""):ut(dt(e));return n||null}function yt(e){const t=e.getAttribute("href"),n=e.ownerDocument.defaultView?.location;if(!t||!n)return"";try{const e=new URL(t,n.href);return e.origin===n.origin?` -> ${e.pathname}${e.search}`:""}catch{return""}}function bt(e){if(e.classList.contains("filigran-chatbot"))return!0;const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!0}if(e.hidden||e.hasAttribute("inert"))return!0;if("true"===e.getAttribute("aria-hidden"))return!0;const n=e.ownerDocument.defaultView?.getComputedStyle(e);return"none"===n?.display||"hidden"===n?.visibility}const xt="filigranChatConversationId",kt="filigranChatLegacyChatId",Nt="filigranChatAgentSlug",Ct="filigranChatSidebarWidth",St="filigran-chat-collapsed-workspaces",It="filigranChatDraft:",Tt="filigranChatDraftRefs:";function At(e,t){return e?`${e}:${t}`:t}function _t(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch{return null}}function Et(e,t){try{return _t(e)?.getItem(t)??null}catch{return null}}function Mt(e,t,n){try{const r=_t(e);if(!r)return;n?r.setItem(t,n):r.removeItem(t)}catch{}}class Lt extends Error{constructor(){super("the event stream fell silent"),this.name="SseStreamSilentError"}}async function Rt(e,t,{idleTimeoutMs:n}={}){const r=e.getReader(),o=new TextDecoder;let a="",s=null,i=!1,c=!1,l=null;const d=()=>{null!==l&&clearTimeout(l),l=null;const e="function"==typeof n?n():n;i&&void 0!==e&&(l=setTimeout(()=>{c=!0,r.cancel().catch(()=>{})},e))},u=e=>{const r=e.replace(/\r$/,"");if(r.startsWith(":")){const e=Date.now();null===s&&(s=e);const t="function"==typeof n?n():n;void 0!==t&&e-s>=t/3&&(i=!0)}if(!r.startsWith("data:"))return!0;const o=r.startsWith("data: ")?r.slice(6):r.slice(5);let a;try{a=JSON.parse(o)}catch{return!0}return!(a&&"object"==typeof a&&!Array.isArray(a))||!1!==t(a)};try{for(;;){const{done:e,value:t}=await r.read();if(c)throw new Lt;if(e)break;a+=o.decode(t,{stream:!0});const n=a.split("\n");a=n.pop()??"";for(const e of n)if(!u(e))return void await r.cancel().catch(()=>{});d()}a+=o.decode(),a&&u(a)}finally{null!==l&&clearTimeout(l),r.releaseLock()}}function $t(e,...t){if(e)try{return e(...t)}catch(e){return void console.error("A chat panel host callback threw",e)}}const Dt=e=>e.some(e=>"error"===e.uploadStatus);function zt(e){if(e.slug&&/^[\w-]+$/.test(e.slug))return e.slug;return e.name.toLowerCase().replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")||null}function jt(e,t){const n=[];for(const r of le(t))for(const t of e)t.key.toLowerCase()!==r||n.includes(t.agentId)||n.push(t.agentId);return n}const Ot=r({fetch:(e,t)=>globalThis.fetch(e,t),sessionEnded:()=>{}}),Pt=Ot.Provider;function Ut(){return o(Ot).fetch}const Ht=(e,t)=>At(e,`${It}${t??"new"}`),Wt=(e,t)=>At(e,`${Tt}${t??"new"}`);function qt(e,t){try{const n=JSON.parse(Et("session",Wt(e,t))??"[]");return Array.isArray(n)?n.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.conversationId&&"string"==typeof e.key&&"string"==typeof e.title):[]}catch{return[]}}function Bt(e,t,n,r){Mt("session",Ht(e,t),n),Mt("session",Wt(e,t),r.length>0?JSON.stringify(r):null)}function Ft(e,t){const n=Et("session",Ht(e,t))??"";return{text:n,refs:de(qt(e,t),n)}}const Vt=9e5,Kt=Vt,Gt=new Set(["wait_status","tool_progress","consult_progress"]),Jt=new Set(["status","stream","done","approval_required","error","cancelled"]),Yt=new Set(["mentioned_agent_ids","content","conversation_id","agent_slug","supports_tool_approval","supports_page_actions","supports_artifacts","referenced_conversation_ids","file_ids","context"]);function Xt(e,t,n,r){return{...e,content:n,timestamp:r,toolNames:t.toolNames,toolCallCount:t.toolCallCount,iterations:t.iterations,attachments:t.attachments,artifacts:t.artifacts,reasoning:t.reasoning,toolCallTrace:t.toolCallTrace,transferChain:t.transferChain,isTruncated:t.isTruncated,agentName:t.answeredBy?.agentName??e.agentName,answeredBy:t.answeredBy,mentionFailed:t.mentionFailed,serverId:t.messageId??e.serverId,raw:t.raw??e.raw}}const Zt=["toolNames","toolCallCount","iterations","attachments","artifacts","reasoning","toolCallTrace","transferChain","isTruncated","agentName","answeredBy","mentionFailed","feedback"],Qt=Symbol("sentText");function en(e,t){return t===e.content?e:{...e,[Qt]:t}}function tn(e){return e[Qt]??e.content}const nn=e=>`${e.role}\0${"user"===e.role?tn(e):e.content}`,rn=e=>`${e.role}\0${e.content}`;function on(e,t){const n={...e,serverId:t.serverId??e.serverId,raw:t.raw??e.raw};if("assistant"!==e.role)return n;const r=n;for(const e of Zt)void 0!==t[e]&&(r[e]=t[e]);return n}function an(e,t,n){const r=null===n?-1:e.findIndex(e=>e.id===n);return r<0?[...e,t]:[...e.slice(0,r),t,...e.slice(r)]}const sn=(e,t)=>[e,t].filter(Boolean).join("\n\n"),cn=(e,t)=>void 0!==e.displayText||void 0!==t.displayText?sn(e.displayText??e.text,t.displayText??t.text):void 0;function ln(e,t){const n=new Set(e.refs.map(e=>e.conversationId)),r=new Set(e.mentions.map(e=>e.agentId));return{text:sn(e.text,t.text),draft:sn(e.draft,t.draft),files:[...e.files,...t.files],refs:[...e.refs,...t.refs.filter(e=>!n.has(e.conversationId))],mentions:[...e.mentions,...t.mentions.filter(e=>!r.has(e.agentId))],extras:e.extras||t.extras?{...e.extras,...t.extras}:void 0,displayText:cn(e,t)}}const dn={text:"",draft:"",files:[],refs:[],mentions:[]};function un(e){return{...e.reduce(ln,dn),parts:e}}function pn(e,t){return un([...e?.parts??[],t])}function hn(e){for(const t of e)$t(t.onNotSent)}function mn(e,t,n){if(!1===t)return null;const r=t&&"object"==typeof t?t:void 0,o=("string"==typeof r?.text?r.text:e).trim(),a="string"==typeof r?.displayText?r.displayText.trim():"",s="string"==typeof n?n.trim():"";return{text:o,displayText:a||s||o,extras:r?.extras}}function fn(e){return"error"===e.action||"cancelled"===e.action||"done"===e.action&&!e.intermediate?e:null}function gn(e){return("error"===e.action||"cancelled"===e.action)&&!!e.provisional}function vn(e){const t=$t(e);return t&&"object"==typeof t?t:{}}const wn=52428800;function yn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t].serverId;if(n)return n}return null}function bn(e,t){const n=null===t?0:e.findIndex(e=>e.serverId===t)+1;return null!==t&&0===n?"stopped":e.slice(n).some(e=>"assistant"===e.role)?"answered":"stopped"}function xn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:r,requestHeaders:o,pageContext:l,onRelativeLinkClick:d,t:u,maxFileCount:p=10,maxTotalSize:h=52428800,storageKeyPrefix:m,controlledConversationId:f,onConversationIdChange:g,getRequestExtras:v,onStreamEvent:w,onSessionEnded:y,onConversationTitle:b,historySettledFor:x=null,steerAttachments:k=!1,holdSends:N=!1,agentMentionsEnabled:C=!1,onBeforeSend:S,onHeldSendSettled:I}){const T=Ut(),A="legacy"===n,[_,E]=a([]),[M,L]=a(!1),[R,$]=a(null),[D,z]=a(null),j=void 0!==f,O=At(m,xt),P=At(m,kt),[U,H]=a(()=>j?f??null:Et("local",O)),[W]=a(()=>Ft(m,U)),[q,B]=a(W.text),[F,V]=a(W.refs),[K,G]=a([]),[J,Y]=a([]),[Z,Q]=a(null),[ee,te]=a(null),[ne,re]=a(null),[oe,ae]=a(!1),[se,ie]=a(null),[ce,pe]=a(!1),[me,fe]=a(0),[ge,ve]=a(0),[we,ye]=a(()=>Et("local",P)),be=s(!1),xe=s(null),ke=s(null),Ie=s(null),Te=s(!1),Ae=s(null),_e=s(null),Ee=s(null),Me=s(null),Le=s(null),Re=s(!1),[$e,De]=a(null),je=s($e);je.current=$e;const[Oe,He]=a(null),We=s(!1),Ke=s(new Map),Ge=s(null),[Ye,Xe]=a(!1),Ze=s(null),Qe=s(!1),et=s("off"),tt=s(0),nt=s(null),rt=s(null),st=s(null),pt=s(null),[gt,vt]=a(!1),Nt=e=>{const t=pt.current?.readBack;t&&e!==pt.current&&window.clearTimeout(t.timer),pt.current=e,vt(null!==e)},Ct=s(_);Ct.current=_;const St=s(0),[It,Tt]=a(()=>Se()),_t=s(null),Lt=s(null),zt=s(!1),Ot=s(0),Pt=s(null),Ht=s(null),Wt=s(null),qt=()=>{null!==_t.current&&window.clearTimeout(_t.current),_t.current=null,Lt.current=null,zt.current=!1,Wt.current&&window.clearTimeout(Wt.current.timer),Wt.current=null;const e=Ht.current;Ht.current=null,null!==e&&E(t=>t.filter(t=>t.id!==e||t.content))},Zt=e=>{Ge.current&&window.clearTimeout(Ge.current.timer);const t={timer:0,relayed:e};return t.timer=window.setTimeout(()=>Qt(t),5e3),Ge.current=t,Xe(!0),t},Qt=e=>{const t=Ge.current;!t||e&&e!==t||(window.clearTimeout(t.timer),Ge.current=null,Xe(!1))},sn=()=>{Ge.current?.relayed&&Qt()},cn=s(v);cn.current=v;const ln=s(w);ln.current=w;const dn=s(y);dn.current=y;const xn=s(b);xn.current=b;const kn=s(S);kn.current=S;const Nn=s(I);Nn.current=I;const Cn=s(U),Sn=s(M);Sn.current=M;const In=e=>{Sn.current&&$(e),Sn.current=!1,L(!1),We.current||He(null)},Tn=s(l);Tn.current=l;const An=s(new Map),_n=s(d);_n.current=d;const En=s(o);En.current=o;const Mn=s(null),Ln=s(!1),Rn=s(null),$n=s(0),[Dn]=a(Fe),zn=s(null),[jn,On]=a(null),Pn=s(new AbortController),Un=Number.isFinite(p)&&p>0?Math.floor(p):10,Hn=Number.isFinite(h)&&h>0?h:wn;i(()=>{V(e=>de(e,q)),G(e=>function(e,t){if(0===e.length)return e;const n=new Set(le(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}(e,q))},[q]);const Wn=c(e=>{G(t=>{return r=e,(n=t).some(e=>e.agentId===r.agentId)?n:[...n,r];var n,r})},[]),qn=c(e=>{V(t=>{return r=e,(n=t).some(e=>e.conversationId===r.conversationId)?n:[...n,r];var n,r})},[]),Bn=({draft:e,files:t,refs:n,mentions:r},{before:o})=>{e&&B(t=>t?o?`${e}\n${t}`:`${t}\n\n${e}`:e),t.length>0&&Y(e=>o?[...t,...e]:[...e,...t]),n.length>0&&V(e=>{const t=n.filter(t=>!e.some(e=>e.conversationId===t.conversationId));return o?[...t,...e]:[...e,...t]}),r.length>0&&G(e=>{const t=r.filter(t=>!e.some(e=>e.agentId===t.agentId));return o?[...t,...e]:[...e,...t]})},Fn=()=>A||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,Vn=()=>X(e,t,n,"approve"),Kn=s(Vn);Kn.current=Vn;const Gn=async e=>{const t=lr(e);if(!t)return null;try{const e=await T(t,{headers:{...o??{}}});if(!e.ok)return null;const n=await e.json();return{proposals:ze(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Jn=c(()=>{be.current=!1,St.current+=1,fe(St.current)},[]),Yn=()=>{if(null===Lt.current)return;const e=yn(Ct.current);if(qt(),!pr())return void Sr("stopped");Jn();const t=window.setTimeout(()=>{Wt.current?.timer===t&&(Wt.current=null,Sr("stopped"))},1e4);Wt.current={from:St.current,shownUpTo:e,timer:t}},Xn=s(Yn);Xn.current=Yn;const Zn=()=>{null!==_t.current&&window.clearTimeout(_t.current),zt.current=!1,_t.current=window.setTimeout(()=>{_t.current=null,_e.current||Xn.current()},Math.max(0,Ot.current-Date.now()))},Qn=()=>{null===Lt.current||_e.current||zt.current||(zt.current=!0,null!==_t.current&&window.clearTimeout(_t.current),_t.current=window.setTimeout(()=>{_t.current=null,_e.current||Xn.current()},5e3))},er=s(Qn);er.current=Qn;const tr=()=>{null!==Lt.current&&!_e.current&&zt.current&&Zn()},nr=s(tr);nr.current=tr;const rr=()=>A||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,or=()=>X(e,t,n,"cancel"),ar=()=>X(e,t,n,"skipWait"),sr=X(e,t,n,"events"),ir=!!sr,cr=X(e,t,n,"pendingApprovals"),lr=e=>cr?`${cr}/${encodeURIComponent(e)}/pending-approvals`:null,dr=()=>ir?{"X-Chat-Client-Id":It}:{},ur=(e,t,n)=>T(e,{method:"POST",headers:{"Content-Type":"application/json",...En.current??{},...dr()},body:JSON.stringify({conversation_id:t,...n})}),pr=()=>A||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`,hr=s(g);hr.current=g;const mr=c((e,{notify:t=!0}={})=>{const n=Cn.current!==e;Cn.current=e,H(e),j||Mt("local",O,e),n&&t&&hr.current?.(e)},[j,O]),fr=async e=>{if(Cn.current)return Cn.current;if(Dn.pending)return Dn.pending;const t=pr();return t?Dn.run(async(n,r)=>{const a=zn.current,s=await T(t,{method:"POST",headers:{"Content-Type":"application/json",...o??{}},body:JSON.stringify(a?{agent_slug:e,workspace_id:a}:{agent_slug:e}),signal:r});if(!s.ok||!n())return null;const i=await s.json();if(!n())return null;const c=i?.conversation_id??null;return c&&(be.current=!0,mr(c),zn.current=null,On(null)),c}):null},gr=async(e,t,n)=>{const r=rr(),a=new FormData;a.append("conversation_id",t),a.append("file",e,e.name);const s=o?Object.fromEntries(Object.entries(o).filter(([e])=>"content-type"!==e.toLowerCase())):void 0,i=await T(r,{method:"POST",headers:s,body:a,signal:n});if(!i.ok)throw new Error(`File upload failed: ${i.status}`);const c=(await i.json()).file_ids??[];if(0===c.length)throw new Error("No file_id returned");return c[0]},vr=e=>{if(!e||0===e.length||!rr())return;const t=Array.from(e).map(e=>({file:e,tempId:Se()}));let n=[];Y(e=>{const r=e.length,o=e.reduce((e,t)=>e+t.size,0),a=Un-r;if(a<=0)return e;let s=Hn-o;const i=[];for(const e of t.slice(0,a))e.file.size<=s&&(i.push(e),s-=e.file.size);if(0===i.length)return e;n=i;const c=i.map(({file:e,tempId:t})=>({name:e.name,type:e.type,size:e.size,rawFile:e,uploadStatus:"pending",fileId:t}));return[...e,...c]}),setTimeout(()=>{const e=Pn.current.signal;for(const{file:t,tempId:o}of n)(async()=>{try{const n=await fr(r);if(!n)return void Y(e=>e.map(e=>e.fileId===o?{...e,uploadStatus:"error"}:e));const a=await gr(t,n,e);Y(e=>e.map(e=>e.fileId===o?{...e,fileId:a,uploadStatus:"done"}:e))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;Y(e=>e.map(e=>e.fileId===o?{...e,uploadStatus:"error"}:e))}})()},0)},wr=async(e,t,n)=>{const r=Kn.current(),o=n??Cn.current;if(!r||!o||"undefined"==typeof document)return;const a=ke.current?.signal,s=async t=>{try{await T(r,{method:"POST",headers:{"Content-Type":"application/json",...En.current??{},...dr()},body:JSON.stringify({conversation_id:o,page_action:{action_id:e,ok:!1,error:t,url:"",title:"",snapshot:""}})})}catch{}};if(a?.aborted)return s("panel_closed");if(!Ve(r,_n.current))return s("page_actions_not_supported");z(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await ot(t,An.current,_n.current,document,a);if(a?.aborted)return s("panel_closed");if("snapshot"!==t.type&&await function(e,{quietMs:t=300,maxMs:n=3e3,signal:r}={}){return new Promise(o=>{if(r?.aborted)return o();const a=e.defaultView,s=a?.MutationObserver??globalThis.MutationObserver;let i;const c=()=>{clearTimeout(i),clearTimeout(d),l?.disconnect(),r?.removeEventListener("abort",c),o()},l=s?new s(e=>{e.some(e=>!Je(e.target))&&(clearTimeout(i),i=setTimeout(c,t))}):null;l?.observe(e.body??e.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),i=setTimeout(c,t);const d=setTimeout(c,n);r?.addEventListener("abort",c)})}(document,{signal:a}),a?.aborted)return s("panel_closed");let i={text:"",url:"",title:""},c=null;try{const e=function(e,t=2e4){const n=e.defaultView?.location,r=(n?`${n.pathname}${n.search}`:"").slice(0,500),o=ut(e.title).slice(0,80),a=Math.max(0,t-12);let s=!1,i=`# ${o} — ${r}`;i.length>a&&(i=i.slice(0,a),s=!0);const c=[i];let l=i.length;const d=new Map,u=e=>{for(const t of Array.from(e.children)){if(bt(t))continue;const e=ct(t),n=lt(t);let r=null;if(e){const n=`e${d.size+1}`,o=wt(t,e),i=ft(t);if(r=`[${n}] ${e} ${mt(ht(t,e))}${i.length?` (${i.join(", ")})`:""}${o?` = ${mt(o)}`:""}${yt(t)}`,l+r.length+1>a)return s=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${mt(ut(dt(t)))} (level ${n})`,l+r.length+1>a))return s=!0,!1;if(r&&(c.push(r),l+=r.length+1),(!e||it(t))&&!u(t))return!1}return!0};return e.body&&!s&&u(e.body),s&&c.push(at),{text:c.join("\n"),url:r,title:o,refs:d}}(document);An.current=e.refs,i={text:e.text,url:e.url,title:e.title}}catch(e){An.current=new Map,c=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await T(r,{method:"POST",headers:{"Content-Type":"application/json",...En.current??{},...dr()},signal:a,body:JSON.stringify({conversation_id:o,page_action:{action_id:e,ok:n.ok,error:n.error??(null===c?null:`snapshot_failed: ${c}`),url:i.url,title:i.title,snapshot:i.text}})})}catch{}finally{a?.aborted||z(e=>"acting_on_page"===e?.status?{...e,status:"thinking"}:e)}},yr=(e,t)=>{let n=e;const r=[e];let o="",a=!1,s=!1,i=null;const c=function(e){let t=!1,n="",r=null,o=!1;const a=()=>{null!==r&&cancelAnimationFrame(r),r=null},s=()=>{if(a(),!t&&!n)return;const r=t,o=n;t=!1,n="",e(r,o)},i=()=>{null===r&&("function"==typeof requestAnimationFrame?r=requestAnimationFrame(()=>{r=null,s()}):s())};return{text:()=>{o||(t=!0,i())},thinking:e=>{o||(n+=e,i())},flush:s,close:()=>{o=!0,a(),t=!1,n=""}}}((e,t)=>{if(e){const e=n,t=o;z(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),E(n=>n.map(n=>n.id===e?{...n,content:t}:n))}t&&z(e=>({...e,status:e?.status??"thinking",thinkingContent:(e?.thinkingContent??"")+t}))}),l=()=>{if(!a)return;c.flush(),a=!1,s=!1,o="",n=Se(),r.push(n);const e=n;E(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),z({status:"thinking"})};return{ctx:{hasUsedTools:!1,activeNodeId:""},deltas:c,apply:e=>{switch(tt.current+=1,e.action){case"status":return(e=>{l();const t=n;if(e.contextUsage&&te(e.contextUsage),"thinking_text"===e.status)return void c.thinking(e.thinkingContent??"");c.flush();const r="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;e.resumed?(o="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),z({status:"thinking",elapsedS:e.elapsedS,elapsedStartMs:r})):"stream_retract"===e.status?(o="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),z(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}))):"tool_heartbeat"===e.status?z(t=>t?{...t,elapsedS:e.elapsedS,elapsedStartMs:r}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:r}):"wait_start"===e.status?z(t=>({status:"wait_start",thinkingContent:t?.thinkingContent,waitSeconds:e.waitSeconds,waitReason:e.waitReason,waitStartMs:Date.now()})):z(t=>"wait_start"===t?.status&&Gt.has(e.status)?t:{status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent})})(e),"continue";case"stream":return l(),o+=e.content,c.text(),"continue";case"done":return(e=>{c.flush(),a=!0,e.intermediate||(s=!0),re(null),ie(null),br(e,t);const r=n,i=e.content||o,l=new Date;xr(r,e.messageId,t=>Xt(t,e,i,l))})(e),t&&!e.intermediate?"end":"continue";case"approval_required":return c.flush(),Mn.current=e.conversationId??Cn.current,Ln.current=!1,ie(null),re(e.proposals),z(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"}),"continue";case"error":{l(),c.flush();const t=n;return i="error",E(n=>n.map(n=>n.id===t?{...n,content:e.content||u("Sorry, an error occurred. Please try again.")}:n)),"end"}case"cancelled":{c.flush(),i="cancelled";const e=n;return E(t=>t.map(t=>t.id===e?{...t,stopped:!0}:t)),"end"}case"session_ended":{c.flush(),i="session";const e=n;return E(t=>t.filter(t=>!(t.id===e&&!t.content))),"end"}default:return"continue"}},currentAssistantId:()=>n,openAnswerId:()=>a?null:n,accumulated:()=>o,doneReceived:()=>a,segmentIds:()=>r,ended:()=>i,outcome:()=>"error"===i?"failed":null===i&&s?"answered":"stopped"}},br=(e,t)=>{e.conversationId&&!t&&mr(e.conversationId),e.contextUsage&&te(e.contextUsage),e.transferAgentId&&e.transferAgentName&&Q({id:e.transferAgentId,name:e.transferAgentName})},xr=(e,t,n)=>{E(r=>t&&r.some(n=>n.id!==e&&n.serverId===t)?r.filter(t=>t.id!==e):r.map(t=>t.id===e?n(t):t))},kr=(e,t,n)=>{const r=fn(t),o=r?.messageId;if(!r||!o)return!1;"done"!==r.action||Sn.current||br(r,n);const a=new Date;return xr(e,o,e=>"done"===r.action?Xt(e,r,r.content||e.content,a):{...e,serverId:o,raw:r.raw??e.raw}),!0},Nr=(e,t,n,r)=>{let o;try{o=e(t,n)}catch{o=void 0}return $t(ln.current,t,function(e,t){const n={relayed:e};if(!t)return n;const r=fn(t);return r&&gn(r)?n.end="provisional":r?.messageId&&(n.end="stored"),"status"===t.action&&t.resumed&&(n.replayed=!0),n}(r,o)),"session_ended"===o?.action&&$t(dn.current,o.reason),o},Cr=e=>{switch(e.action){case"user_message":{const t=e.message,n=Me.current?.openAnswerId()??Ht.current;return E(e=>{if(t.serverId&&e.some(e=>e.serverId===t.serverId))return e;let r=e.length-1;for(;r>=0&&("user"!==e[r].role||e[r].serverId||tn(e[r])!==t.content);)r-=1;return r>=0&&e.length-r<=3?e.map((e,n)=>n===r?{...e,serverId:t.serverId,raw:t.raw}:e):an(e,t,n)}),!0}case"conversation_title":return xn.current?.(e.conversationId??Cn.current,e.title),!0;case"approval_resolved":return re(null),ie(null),!0;default:return!1}},Sr=e=>{qr(),In(e),z(null),re(null),ie(null),Mn.current=null,Ln.current=!1,Rn.current=Cn.current},Ir=async a=>{const s=!a,i=a?a.text:q,c=s?q:a?.draft??"",l=s?J:a?.files??[];if(!i.trim()&&0===l.length)return"dropped";const d=s?"composer":a?.source??"host",p=!Sn.current&&(null!==Ge.current||null!==pt.current),h=Sn.current||null!==pt.current,m=!a?.decided&&h&&kn.current?{text:i,source:d,extras:a?.extras,displayText:a?.displayText}:void 0,f=mn(i,a?.decided?void 0:$t(kn.current,{text:i,source:d,turnRunning:h}),a?.displayText);if(!f)return"dropped";We.current=!1,He(null);const g=f.extras,v=a?.extras||g?{...a?.extras,...g}:void 0,w=f.text,y=a?.decided?a.displayText?.trim()||w:f.displayText,b=y!==w?y:void 0,x=s?he(e,t,n)?ue(F,q):[]:a?.refs??[],S=s?C?K:[]:a?.mentions??[],I=jt(S,w);if(!w&&0===l.length)return"dropped";const _=()=>{s&&(B(""),V([]),G([]),Y([]))};if(Sn.current||p){if(Dt(l))return"dropped";const e=l.every(e=>"done"===e.uploadStatus);if(!p&&!!Fn()&&!!Cn.current&&0===x.length&&0===I.length&&0===Object.keys(v??{}).length&&(0===l.length||k&&e)){_();const e=await(async(e,t,n,a=e)=>{const s=Fn(),i=Cn.current;if(!s||!i)return{result:"failed"};const c=en({id:Se(),role:"user",content:a,timestamp:new Date,files:t.length>0?t:void 0},e),l=Me.current?.openAnswerId()??Ht.current;E(e=>an(e,c,l));const d=t.filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId);let u=null;try{const t=await T(s,{method:"POST",headers:{"Content-Type":"application/json",...o??{},...dr()},body:JSON.stringify({conversation_id:i,content:e,agent_slug:r,...d.length>0?{file_ids:d}:{}})});if(t.ok){const e=await t.json().catch(()=>null),n=e&&"object"==typeof e?e:{},r=n.turn_id;return{result:"ok",turnId:"string"==typeof r&&r?r:null,unanswered:!1===n.answered}}if(E(e=>e.filter(e=>e.id!==c.id)),409===t.status&&N)return{result:"ended"};409!==t.status&&(u=await Ne(t))}catch{E(e=>e.filter(e=>e.id!==c.id))}return null!==n&&Bn({draft:n,files:t,refs:[],mentions:[]},{before:!0}),{result:"failed",detail:u}})(w,l,s?c:null,y);return"ended"===e.result?(De(e=>pn(e,{text:w,draft:c,files:l,refs:[],mentions:[],extras:v,displayText:b,asked:m,onSent:a?.onSent,onNotSent:a?.onNotSent})),"held"):"ok"===e.result?(e.unanswered&&(We.current=!0,He(u("This message will be read with your next one."))),a?.onSteered?.(e.turnId,e.unanswered),"steered"):(e.detail&&He(e.detail),"failed")}return(N||p)&&e?(_(),De(e=>pn(e,{text:w,draft:c,files:l,refs:x,mentions:S,extras:v,displayText:b,asked:m,onSent:a?.onSent,onNotSent:a?.onNotSent})),"held"):"dropped"}const M=en({id:Se(),role:"user",content:y,timestamp:new Date,files:l.length>0?[...l]:void 0,conversationRefs:x.length>0?x:void 0},w),R=Se();E(e=>[...e,M,{id:R,role:"assistant",content:"",timestamp:new Date}]),_(),Sn.current=!0,L(!0),z({status:"thinking"});const $=Dn.generation,D=yr(R,!1);Ie.current=D.deltas,Me.current=D,Re.current=!1,Te.current=!0,Ae.current=null,Qe.current=!1;let j=!1,O=!1,U=!1,H=!1,W=!1,X=!1,Z=null;const Q=()=>{if(!ir||!Cn.current||!Ae.current||D.ended())return!1;j=!0;const e=D.doneReceived()?Se():D.currentAssistantId();return E(t=>[...t.filter(t=>t.id!==e),{id:e,role:"assistant",content:"",timestamp:new Date}]),Ht.current=e,Lt.current=Ae.current,Ae.current=null,Tt(Se()),z(e=>"cancelling"===e?.status?e:{status:"reconnecting"}),Ot.current=Date.now()+(Pt.current?Kt:15e3),Zn(),!0},ee=new AbortController;ke.current?.abort();const te=new AbortController,ne=()=>{X||(X=!0,D.deltas.close(),Ie.current===D.deltas&&(Ie.current=null),Me.current===D&&(Me.current=null),Te.current=!1,ke.current===te&&te.abort(),xe.current===ee&&(xe.current=null),Dn.generation!==$||j||Sr(U?"failed":D.outcome()))};try{xe.current=ee,ke.current=te;const s=(M.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),i=!!(or()||ar()||ir);if(!Cn.current&&(zn.current||i)){const e=Dn.generation,t=await fr(r);if(Dn.generation!==e)return"dropped";t||(zn.current=null,On(null))}const c=function(e,t,n){switch(e){case"legacy":return{question:t,chatId:n.legacyChatId??void 0,streaming:!0};case"ag-ui":return{threadId:n.conversationId??Se(),runId:Se(),messages:[{id:Se(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={...Object.fromEntries(Object.entries(n.extras??{}).filter(([e])=>!Yt.has(e))),content:t,conversation_id:n.conversationId,agent_slug:n.agentSlug};if(n.supportsToolApproval&&(e.supports_tool_approval=!0),n.referencedConversationIds&&n.referencedConversationIds.length>0&&(e.referenced_conversation_ids=n.referencedConversationIds),n.supportsPageActions&&(e.supports_page_actions=!0),e.supports_artifacts=!0,n.pageContext&&Object.keys(n.pageContext).length>0)try{const t=JSON.stringify(n.pageContext);t&&"{}"!==t&&(e.context=n.pageContext)}catch{}return e}}}(n,w,{legacyChatId:we,conversationId:Cn.current,agentSlug:r,pageContext:Tn.current,supportsToolApproval:null!==Vn(),referencedConversationIds:x.map(e=>e.conversationId),supportsPageActions:Ve(Vn(),_n.current),extras:{...vn(cn.current),...v??{}}});s.length>0&&(c.file_ids=s),I.length>0&&(c.mentioned_agent_ids=I);const l=await T(A||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...o??{},...dr()},body:JSON.stringify(c),signal:ee.signal});if(!l.ok||!l.body){const e=l.ok?null:await Ne(l);return U=!0,E(t=>t.map(t=>t.id===R?{...t,content:e??u("Unable to connect. Please check the configuration.")}:t)),"failed"}O=!0,a?.onSent?.();const d=function(e){switch(e){case"legacy":return qe;case"ag-ui":return Be;default:return Pe}}(n);if(await Rt(l.body,e=>{const t=Nr(d,e,D.ctx,!1);if(!t)return!0;try{return W?Dn.generation===$&&(!!Cr(t)||!kr(D.currentAssistantId(),t,!1)):(Qe.current||Me.current!==D||(Qe.current=!0,"resend"===et.current&&(et.current="off",null!==Ee.current&&Fr(Ee.current))),!Ae.current&&"string"==typeof e.turn_id&&e.turn_id&&(Ae.current=e.turn_id),"folded"===t.action?(t.turnId&&(Ae.current=t.turnId),!0):!!Cr(t)||("set_chat_id"===t.action?(ye(t.chatId),Mt("local",P,t.chatId),!0):"page_action_required"===t.action?(D.deltas.flush(),wr(t.actionId,t.pageAction,t.conversationId),!0):(("session_ended"===t.action||fn(t))&&(H=!0),"end"!==D.apply(t)||!!gn(t)&&(D.deltas.flush(),W=!0,i&&(Z=Zt(!1)),Ze.current=ee,ne(),!0))))}catch{return!0}},{idleTimeoutMs:()=>ir&&Cn.current&&Ae.current?45e3:void 0}),D.deltas.flush(),!j&&!H&&Q())return"sent";if(!j&&!D.ended()&&D.accumulated()&&!D.doneReceived()){const e=D.currentAssistantId(),t=D.accumulated();E(n=>n.map(n=>n.id===e?{...n,content:t||u("No response.")}:n))}}catch(e){if(D.deltas.close(),X)return"sent";if(e instanceof DOMException&&"AbortError"===e.name)return O?"sent":"dropped";const t=D.currentAssistantId();if(Q())return"sent";O||(U=!0),E(e=>e.map(e=>e.id===t?{...e,content:u("Sorry, an error occurred. Please try again.")}:e))}finally{ne(),Z&&Qt(Z),Ze.current===ee&&(Ze.current=null)}return O?"sent":"failed"},Tr=()=>{const e=_e.current;if(!e)return;_e.current=null,e.renderer.deltas.flush(),e.renderer.deltas.close(),Ie.current===e.renderer.deltas&&(Ie.current=null),Me.current===e.renderer&&(Me.current=null);const t=e.renderer.currentAssistantId();E(e=>e.filter(e=>!(e.id===t&&!e.content&&!e.stopped))),Sr(e.renderer.outcome())},Ar=s(Tr);Ar.current=Tr;const _r=()=>{const e=_e.current;if(!e)return;const t=e.renderer.doneReceived()?null:e.renderer.currentAssistantId();Tr(),Nt({turnId:e.turnId,shownUpTo:yn(Ct.current)}),t&&E(e=>e.filter(e=>e.id!==t))},Er=s(_r);Er.current=_r;const Mr=e=>{pt.current&&(Nt(null),e&&$(e))},Lr=s(Mr);Lr.current=Mr;const Rr=()=>{rt.current&&window.clearTimeout(rt.current.timer),rt.current=null},$r=()=>{Rr();const e=_e.current;if(e){const t=yn(Ct.current);Tr(),Nt({turnId:e.turnId,shownUpTo:t})}const t=pt.current;if(!t||t.readBack)return;if(!pr())return void Mr("stopped");Jn();const n=window.setTimeout(()=>{pt.current===t&&Mr("stopped")},1e4);t.readBack={from:St.current,timer:n}},Dr=s($r);Dr.current=$r;const zr=()=>{const e=_e.current,t=pt.current;if(!e&&t&&(t.readBack||rt.current?.turn===t))return;Rr();const n=e??t;if(!n)return;const r=window.setTimeout(()=>{rt.current=null,(e?_e.current===e:pt.current===t)&&$r()},5e3);rt.current={turn:n,timer:r}},jr=s(zr);jr.current=zr;const Or=s(new Set),Pr=e=>{let t=_e.current;const n=Nr(Pe,e,t?.renderer.ctx??{hasUsedTools:!1,activeNodeId:""},!0);if(!n)return;if(Cr(n))return;if("session_ended"===n.action)return Tr(),Mr("stopped"),void(null===Lt.current&&null===Wt.current||Te.current||(qt(),Sr("stopped")));if(!Jt.has(n.action))return;const r="string"==typeof e.turn_id&&e.turn_id?e.turn_id:null;if(!r)return o=String(e.type),void(Or.current.has(o)||(Or.current.add(o),console.warn(`A "${o}" frame of the event stream names no turn and is not read: the events route needs \`turn_id\` on every turn frame (see "Turns that outlive their stream" in the README)`)));var o;const a=Ke.current.get(r);if(void 0!==a)return void(kr(a,n,!0)&&(Ke.current.delete(r),sn()));if(Te.current||r===Ae.current)return;if(r===Le.current)return;const s=rt.current;if(s)if(Rr(),t&&t===s.turn&&r!==t.turnId){const e=t.renderer.doneReceived()?null:t.renderer.currentAssistantId();Tr(),e&&E(t=>t.filter(t=>t.id!==e)),Jn(),t=null}else t&&t===s.turn&&(st.current=t.renderer,Jn());let i=t;if(i&&i.turnId!==r&&(Tr(),i=null),!i){const t=pt.current,o=t?.turnId===r,a=r===Lt.current;if(!("cancelled"!==n.action&&"error"!==n.action||o||a))return void(t&&$r());t&&!o&&(Mr(),Jn());const s=Se();E(e=>[...e,{id:s,role:"assistant",content:"",timestamp:new Date}]),i={turnId:r,renderer:yr(s,!0)},_e.current=i,sn(),Ie.current=i.renderer.deltas,Me.current=i.renderer,Nt(null);const c=a||o;!0===e.resumed&&c?(st.current=i.renderer,Jn()):!a||"cancelled"!==n.action&&"error"!==n.action||Jn(),qt(),Re.current=!1,Sn.current=!0,L(!0),z({status:"thinking"})}if("end"===i.renderer.apply(n)){if(gn(n)){const e=Ke.current;for(e.set(i.turnId,i.renderer.currentAssistantId());e.size>20;)e.delete(e.keys().next().value);Zt(!0)}Tr()}},Ur=s(Pr);Ur.current=Pr;const Hr=()=>{const e=je.current;e&&(Nn.current?.(e.text,"cancelled"),hn(e.parts)),De(null)},Wr=(e,t)=>{const n="string"==typeof e&&e?e:null;zn.current=n,On(n),Ie.current?.close(),Ie.current=null,xe.current?.abort(),xe.current=null,ke.current?.abort(),ke.current=null,Pn.current.abort(),Pn.current=new AbortController,Dn.abandon(),_e.current?.renderer.deltas.close(),_e.current=null,Rr(),st.current=null,Nt(null),Ke.current.clear(),Ze.current?.abort(),Ze.current=null,Qt(),Te.current=!1,Hr(),qr(),qt(),We.current=!1,In("stopped"),E([]),B(""),V([]),G([]),Y([]),z(null),Q(null),te(null),re(null),ie(null),pe(!1),Mn.current=null,Ln.current=!1,Rn.current=null,be.current=!1,A?(ye(null),Mt("local",P,null)):mr(null,{notify:t})},qr=()=>{null!==Ee.current&&window.clearTimeout(Ee.current),Ee.current=null,et.current="off",nt.current=null},Br=(e=!0)=>{qr();const t=Me.current;Me.current=null;const n=_e.current,r=n?.turnId??Lt.current;r&&(Le.current=r),qt(),Ie.current?.flush(),Ie.current?.close(),Ie.current=null,xe.current?.abort(),xe.current=null,ke.current?.abort(),ke.current=null,_e.current=null,In("stopped"),z(null),re(null),ie(null),pe(!1),Mn.current=null,Ln.current=!1,An.current=new Map;const o=e?t?.currentAssistantId():void 0;E(e=>e.map(e=>e.id===o?{...e,stopped:!0}:e).filter(e=>!("assistant"===e.role&&!e.content&&!e.stopped)))},Fr=e=>{const t=or(),n=Cn.current;if(!t||!n)return;const r=Te.current&&!Qe.current;r&&(et.current="asked");const o=()=>Ee.current===e;ur(t,n,r?{awaiting_send:!0}:void 0).then(async t=>{if(t.ok){const n=await t.json().catch(()=>null);if(!o())return;const a=!!n&&"object"==typeof n&&"none"===n.turn;if(r)return void(a?Qe.current?(et.current="off",Fr(e)):et.current="resend":et.current="off");if(!a)return;return Br(),void Jn()}const n=await Ne(t);if(!o())return;const a=nt.current;qr(),Re.current=!1,z(e=>"cancelling"!==e?.status?e:a&&tt.current===a.frameSeq?a.statusBefore:{...e,status:a?.statusBefore?.status??"thinking"}),a?.approvalsBefore&&re(e=>e??a.approvalsBefore),He(n??u("The response could not be stopped. Try again."))}).catch(()=>{o()&&Br()})},Vr=ar(),Kr=U&&x===U?(Gr=U,sr?`${sr}/${encodeURIComponent(Gr)}/events?client_id=${encodeURIComponent(It)}`:null):null;var Gr;Pt.current=Kr;const Jr=Ce(o),Yr=s(Jr);Yr.current=Jr;const[Xr,Zr]=a(null),[Qr,eo]=a(0);i(()=>{Xr&&Xr.url===Kr&&Xr.headersKey!==Jr&&(Zr(null),eo(e=>e+1))},[Xr,Kr,Jr]),i(()=>{if(!Kr)return;let e=!1,t=!1,n=0,r=null,o=null,a=null,s=!1,i=!1;const c=async()=>{if(r=null,e||t)return;if("hidden"===document.visibilityState)return void(s&&(i=!0));t=!0,o=new AbortController;let a=!1,l=null;try{const t=Yr.current,r=await T(Kr,{headers:{...En.current??{},"X-Chat-Client-Id":It},signal:o.signal});if([401,403,404,405].includes(r.status))return a=!0,401!==r.status&&403!==r.status||e||Zr({url:Kr,headersKey:t}),void(e||(Dr.current(),Xn.current()));if(!r.ok||!r.body)return void(e||[502,503,504].includes(r.status)||Xn.current());s&&jr.current(),er.current(),s=!0,l=Date.now(),await Rt(r.body,e=>{n=0;try{Ur.current(e)}catch{}},{idleTimeoutMs:45e3})}catch{}finally{if(t=!1,null===l||e||nr.current(),null!==l&&Date.now()-l>=5e3&&(n=0),!e&&!a&&!i){const e=Math.min(3e4,1e3*2**n);n+=1,r=window.setTimeout(()=>{c()},e*(.5+Math.random()/2))}}},l=()=>{a=null,e||"hidden"!==document.visibilityState||(i=!0,null!==r&&window.clearTimeout(r),r=null,o?.abort(),Er.current())},d=()=>{"hidden"!==document.visibilityState?(null!==a&&window.clearTimeout(a),a=null,"visible"===document.visibilityState&&(pt.current&&jr.current(),t||(null!==r&&window.clearTimeout(r),n=0,i&&(i=!1,Jn()),c()))):null===a&&(a=window.setTimeout(l,6e4))};return c(),document.addEventListener("visibilitychange",d),()=>{e=!0,null!==r&&window.clearTimeout(r),null!==a&&window.clearTimeout(a),o?.abort(),document.removeEventListener("visibilitychange",d),Ar.current(),Lr.current()}},[Kr,It,Qr,Jn]);const to=s([]),[no,ro]=a(0),oo=e=>{to.current.push(e),ro(e=>e+1)};i(()=>{for(const e of to.current.splice(0))Nn.current?.(e,"returned")},[no]),i(()=>{if(M||gt)return;if(Re.current&&(Re.current=!1,$e))return De(null),hn($e.parts),$e.draft||0!==$e.files.length?(oo($e.text),void Bn($e,{before:!0})):void Nn.current?.($e.text,"dropped");if(Ye||!$e)return;De(null);let e=!1;const t=t=>{e||(e=!0,Nn.current?.($e.text,t))},n=[],r=[];for(const e of $e.parts){const{asked:t}=e;if(!t){n.push(e);continue}const o=mn(t.text,$t(kn.current,{text:t.text,source:t.source,turnRunning:!1,held:!0}),t.displayText);o?n.push({...e,text:o.text,displayText:o.displayText!==o.text?o.displayText:void 0,extras:t.extras||o.extras?{...t.extras,...o.extras}:void 0,asked:void 0}):r.push(e)}hn(r);const o=r.filter(e=>e.draft||e.files.length>0);for(const e of o)Bn(e,{before:!1});if(0===n.length)return void(o.length>0?oo($e.text):t("dropped"));const{text:a,draft:s,files:i,refs:c,mentions:l,extras:d,displayText:u}=un(n);ao.current({text:a,draft:s,files:i,refs:c,mentions:l,extras:d,displayText:u,decided:!0,onSent:()=>{t("sent");for(const e of n)$t(e.onSent)},onNotSent:()=>hn(n)}).then(e=>{if("held"===e)return;const r="sent"===e||"steered"===e;t(r?"sent":"failed"===e?"failed":"dropped"),r||hn(n)},()=>{t("failed"),hn(n)})},[M,gt,Ye,$e]);const ao=s(Ir);ao.current=Ir,i(()=>{const e=window.setTimeout(()=>{Bt(m,U,q,F)},300);return()=>window.clearTimeout(e)},[q,U,F,m]),i(()=>()=>{Ie.current?.close(),ke.current?.abort(),Ze.current?.abort(),Ge.current&&window.clearTimeout(Ge.current.timer),null!==_t.current&&window.clearTimeout(_t.current),Wt.current&&window.clearTimeout(Wt.current.timer),rt.current&&window.clearTimeout(rt.current.timer),Hr()},[]);const so=s({conversationId:U,inputValue:q,conversationRefs:F});so.current={conversationId:U,inputValue:q,conversationRefs:F},i(()=>()=>{const{conversationId:e,inputValue:t,conversationRefs:n}=so.current;Bt(m,e,t,n)},[]),i(()=>{const e=U;if(!e||M)return;if(Rn.current===e)return;lr(e)&&Vn()&&(Rn.current=e,(async()=>{const t=await Gn(e);t?.proposals&&(Cn.current!==e||Sn.current||(Mn.current=e,Ln.current=!0,ie(null),re(t.proposals)))})())},[U,M]),i(()=>{if(!ne?.length||!Ln.current)return;const e=Mn.current,t=e?lr(e):null;if(!t)return;const n=window.setInterval(()=>{T(t,{headers:{...o??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[ne]),i(()=>{if(!ce)return;const e=Mn.current;if(!e)return void pe(!1);if(Date.now()>=$n.current)return pe(!1),void Jn();let t=!1;const n=window.setTimeout(async()=>{const n=await Gn(e);if(!t){if(n)return n.proposals?(Ln.current=!0,ie(null),re(n.proposals),void pe(!1)):n.turnRunning?void ve(e=>e+1):(pe(!1),void Jn());ve(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[ce,ge,Jn]);const io=M&&null!==Fn()&&null!==U;return{messages:_,inputValue:q,setInputValue:B,isLoading:M,turnRunning:M||gt,sendsHeld:!M&&(Ye||gt),turnEnd:R,agentStatus:D,attachedFiles:J,conversationId:U,contextUsage:ee,transferredAgent:Z,canSteer:io,pendingApprovals:ne,isSubmittingApproval:oe,approvalError:se,submitApprovalDecisions:async e=>{const t=Vn(),n=Mn.current??Cn.current;if(0!==e.length)if(t&&n){ie(null),ae(!0);try{const r=await T(t,{method:"POST",headers:{"Content-Type":"application/json",...o??{},...dr()},body:JSON.stringify({conversation_id:n,decisions:e.map(e=>({tool_call_id:e.toolCallId,decision:e.verdict,..."reject"===e.verdict&&e.rejectionReason?{rejection_reason:e.rejectionReason}:{}}))})});if(r.ok)return re(null),Ln.current&&!_e.current?(Ln.current=!1,$n.current=Date.now()+Vt,void pe(!0)):void z(e=>e?{...e,status:"thinking"}:{status:"thinking"});ie(409===r.status?u("This turn is no longer waiting for a decision."):u("Could not send your decision. Please try again."))}catch{ie(u("Could not send your decision. Please try again."))}finally{ae(!1)}}else ie(u("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:ce,historyReloadNonce:me,historyLoadedRef:be,conversationIdRef:Cn,handleFileAdd:vr,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),vr(t))},handleSendMessage:Ir,skipWait:Vr?async()=>{const e=ar(),t=Cn.current;if(e&&t)try{(await ur(e,t)).ok&&z(e=>"wait_start"===e?.status?{status:"thinking",thinkingContent:e.thinkingContent}:e)}catch{}}:null,readPendingApprovals:cr?Gn:null,heldMessage:$e,notice:Oe,cancelHeldMessage:Hr,reloadHistory:Jn,mergeTurnHistory:e=>{const t=st.current;if(st.current=null,!t||Te.current)return!1;const n=new Set(t.segmentIds()),r=t.currentAssistantId();return E(t=>function(e,t,n,r){const o=e.findIndex(e=>n.has(e.id));if(o<0)return e;const a=e.slice(0,o),s=e.slice(o),i=new Set(a.map(e=>e.serverId).filter(Boolean));let c=-1;t.forEach((e,t)=>{e.serverId&&i.has(e.serverId)&&(c=t)});const l=new Map;for(const e of a)e.serverId||l.set(nn(e),(l.get(nn(e))??0)+1);const d=t.slice(c+1).filter(e=>{if(e.serverId&&i.has(e.serverId))return!1;const t=l.get(rn(e))??0;return 0===t||(l.set(rn(e),t-1),!1)});if(0===d.length)return e;const u=new Set,p=d.map(e=>{const t=s.find(t=>!u.has(t.id)&&!!e.serverId&&t.serverId===e.serverId)??s.find(t=>!u.has(t.id)&&t.id!==r&&!t.serverId&&nn(t)===rn(e));return t?(u.add(t.id),on(t,e)):{...e,id:Ue(e.serverId)}});return[...a,...p,...s.filter(e=>!u.has(e.id))]}(t,e,n,r)),!0},settleUnseenEnd:(e,t)=>{const n=Wt.current;n&&e>=n.from&&(window.clearTimeout(n.timer),Wt.current=null,Sr(t?bn(t,n.shownUpTo):"stopped"));const r=pt.current;!r?.readBack||e<r.readBack.from||Mr(t?bn(t,r.shownUpTo):"stopped")},agentMentions:K,addAgentMention:Wn,handleNewChat:e=>Wr(e,!0),pendingWorkspaceId:jn,clearPendingWorkspace:e=>{zn.current===e&&(zn.current=null,On(null))},handleStopGenerating:()=>{const e=pt.current;if(!Sn.current&&e){const t=or(),n=Cn.current;return t&&n&&ur(t,n).catch(()=>{}),Le.current=e.turnId,Re.current=!0,Rr(),void Mr("stopped")}if(!Sn.current)return void Br(!1);Re.current=!0;const t=or(),n=Cn.current,r=null!==Lt.current&&!_e.current;if(!t||!n||r)return t&&n&&ur(t,n).catch(()=>{}),void Br();if(null!==Ee.current)return;We.current=!1,He(null),re(null),ie(null),z(e=>({...e,status:"cancelling"}));const o=window.setTimeout(()=>Br(),1e4);Ee.current=o,nt.current={statusBefore:D,approvalsBefore:ne,frameSeq:tt.current},Fr(o)},conversationRefs:F,addConversationRef:qn,setAttachedFiles:Y,setMessages:E,setContextUsage:te,updateConversationId:mr,handleSwitchConversation:e=>{if((A||e!==Cn.current)&&(Wr(void 0,!1),!A)){mr(e);const t=Ft(m,e);B(t.text),V(t.refs)}}}}function kn(e,t){if(t)return e.find(e=>e.id===t)??e.find(e=>e.slug===t)}function Nn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,storageKeyPrefix:o,initialAgent:l,onAgentChange:d}){const u=Ut(),p=null===t?.agents||!!t?.singleEndpoint||"legacy"===n,h=At(o,Nt),[m,f]=a([]),[g,v]=a(!1),[w,y]=a(!1),[b,x]=a(p),[k,N]=a(0),C=c(()=>N(e=>e+1),[]),[S,I]=a(null),[T,A]=a(!1),_=s(0);i(()=>{if(p)return void x(!0);const n=`${e}${t?.agents??"/chat/agents"}`,o=++_.current,a=()=>o===_.current;v(!0),u(n,{headers:r}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}).then(e=>{if(!a())return;const t=function(e){return(Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]).filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id)}(e);if(f(t),y(!1),0===t.length)return void I(null);const n=()=>{const e=Et("local",h);return kn(t,l)??(e?t.find(t=>t.slug===e):void 0)??t[0]};I(e=>e?t.find(t=>t.id===e.id)??n():n())}).catch(()=>{a()&&(y(!0),0===k&&f([]))}).finally(()=>{a()&&(v(!1),x(!0))})},[e,t,n,r,p,k]);return{agents:m,agentsLoading:g,agentsError:w,agentsSettled:b,agentsDisabled:p,selectedAgent:S,setSelectedAgent:I,agentMenuOpen:T,setAgentMenuOpen:A,handleSwitchAgent:(e,t)=>{e.id!==S?.id?(I(e),e.slug&&Mt("local",h,e.slug),A(!1),d?.(e),t?.()):A(!1)},reloadAgents:C}}function Cn(e){if(!e||"object"!=typeof e)return null;const t=e,n=t.conversation_id??t.id;if("string"!=typeof n||!n)return null;return{conversationId:n,title:"string"==typeof t.title?t.title.trim():"",updatedAt:"string"==typeof t.updated_at?t.updated_at:"string"==typeof t.created_at?t.created_at:void 0,messageCount:"number"==typeof t.message_count?t.message_count:void 0,agentName:"string"==typeof t.agent_name&&t.agent_name?t.agent_name:void 0,workspaceId:"string"==typeof t.workspace_id&&t.workspace_id?t.workspace_id:null===t.workspace_id?null:void 0}}const Sn=400;let In=null,Tn=null,An=0;function _n(){null!==In&&(window.clearInterval(In),In=null),null!==Tn&&(document.title=Tn,Tn=null)}function En({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:o,isViewingChat:a}){const c=s(!1),l=s(0);i(()=>{if(!r||"undefined"==typeof document)return;An+=1;const e=()=>{!document.hidden&&document.hasFocus()&&_n()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),An=Math.max(0,An-1),0===An&&_n()}},[r]),i(()=>{const s=c.current;if(c.current=e,!e||s){if(!e&&s&&r){if(Date.now()-l.current<4e3)return;const e="undefined"!=typeof document&&document.hidden,r="undefined"!=typeof document&&!document.hasFocus(),s=e||r,i=!a||a();if(!s&&i)return;const c=n("Response ready"),d=t?A(n,"{agent} has finished",{agent:t}):n("Your answer is ready");s&&(function(e){if("undefined"==typeof document)return;null===Tn&&(Tn=document.title),null!==In&&window.clearInterval(In);let t=!0;document.title=e,In=window.setInterval(()=>{t=!t,document.title=t?e:Tn??e},1200)}(c),function(e,t){try{if("undefined"==typeof Notification||"granted"!==Notification.permission)return;new Notification(e,{body:t,tag:"filigran-chat-complete"})}catch{}}(c,d)),o?.(c,d)}}else l.current=Date.now()},[e,r,t,n,o,a])}function Mn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=Ut(),[s,l]=a(null),[d,u]=a(null),p="rest"===n&&!t?.singleEndpoint,h=void 0===t?.prompts?"/chat/prompts":t.prompts,m=void 0===t?.quota?"/chat/quota":t.quota,f=p&&h?`${e}${h}`:null,g=p&&m?`${e}${m}`:null;i(()=>{if(!f)return void l(null);let e=!1;return o(f,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){const t=Array.isArray(e)?e:Array.isArray(e?.prompts)?e.prompts:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,r="string"==typeof t.id?t.id:"",o="string"==typeof t.content?t.content:"";r&&o&&n.push({id:r,title:"string"==typeof t.title&&t.title?t.title:r,content:o,description:"string"==typeof t.description?t.description:void 0})}return n}(t);l(n.length>0?n:null)}).catch(()=>{e||l(null)}),()=>{e=!0}},[f,r]);const[v,w]=a(0),y=c(()=>w(e=>e+1),[]);return i(()=>{if(!g)return void u(null);let e=!1;return o(g,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{e||u(function(e){if(!e||"object"!=typeof e)return null;const t=e;return"number"!=typeof t.used?null:{used:t.used,limit:"number"==typeof t.limit?t.limit:null,period:"string"==typeof t.period?t.period:"",..."global"===t.scope||"user"===t.scope?{scope:t.scope}:{}}}(t))}).catch(()=>{e||u(null)}),()=>{e=!0}},[g,r,v]),{prompts:s,quota:d,refreshQuota:y}}function Ln({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,agentSlug:o}){const s=Ut(),[c,l]=a(null),[d,u]=a(!1),p="rest"===n&&!t?.singleEndpoint,h=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,m=p&&h?`${e}${h}`:null;return i(()=>{if(!m)return void l(null);let e=!1;u(!0);const t=o?`${m}?agent_slug=${encodeURIComponent(o)}`:m;return s(t,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){return(Array.isArray(e)?e:Array.isArray(e?.suggestions)?e.suggestions:[]).map(e=>{if("string"==typeof e)return e.trim();if(e&&"object"==typeof e){const t=e,n=t.prompt??t.label??t.text;if("string"==typeof n)return n.trim()}return""}).filter(e=>e.length>0)}(t);l(n.length>0?n:null)}).catch(()=>{e||l(null)}).finally(()=>{e||u(!1)}),()=>{e=!0}},[m,o,r]),{suggestions:c,loading:d}}function Rn(e){const t=s(e);return function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||"object"!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}(t.current,e)||(t.current=e),t.current}function $n(e){const t=s(e);l(()=>{t.current=e});const n=c((...e)=>t.current?.(...e),[]);return e?n:void 0}function Dn(e,t){let n="idle",r=!1,o=!1,a=!1;const s=()=>"listening"===n||r,i=()=>{o||s()===a||(a=s(),t.onListeningChange(a))},c=()=>{try{return e.start(),!0}catch{return!1}};return e.onresult=e=>{if("listening"!==n&&"stopping"!==n)return;let r="",o="";for(let t=e.resultIndex;t<e.results.length;t++){const n=e.results[t];n.isFinal?r+=n[0].transcript:o+=n[0].transcript}const a=r.trim();a&&t.onFinal(a),"listening"===n&&t.onInterim(o.trim())},e.onerror=()=>{"listening"===n&&(n="stopping",t.onInterim("")),i()},e.onend=()=>{if(t.onInterim(""),"listening"===n){if(c())return;n="idle"}else r?(r=!1,n=c()?"listening":"idle"):n="idle";i()},{toggle:()=>{o||(s()?(()=>{if(r=!1,"listening"===n){n="stopping",t.onInterim("");try{e.stop()}catch{n="idle"}}i()})():(c()?n="listening":"idle"!==n&&(r=!0),i()))},cancel:()=>{if(!o){if(r=!1,"listening"===n||"stopping"===n){n="discarding",t.onInterim("");try{e.abort()}catch{n="idle"}}i()}},dispose:()=>{if(!o){if(o=!0,e.onresult=null,e.onerror=null,e.onend=null,"idle"!==n)try{e.abort()}catch{}n="idle",r=!1}}}}function zn(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const jn=new Set(["thinking","status","stream","turn_started"]);function On(e,t){const n="string"==typeof t.turn_id&&""!==t.turn_id?t.turn_id:null;if(!0===t.relayed){if(null===e.turnId||n!==e.turnId)return{kind:"ignore"}}else{if("folded_into_active_turn"===t.type){if(null!==n)e.turnId=n,e.folded=!0;else if(!1===t.folded)return{kind:"failed"};return{kind:"progress"}}null!==n&&null===e.turnId&&(e.turnId=n)}const r=t.type;if("status"!==r||"transfer_start"!==t.status||"string"!=typeof t.agent_id||!t.agent_id||null!==n&&n!==e.turnId||(e.agentId=t.agent_id),"string"==typeof r&&jn.has(r))return{kind:"progress"};if("done"===r){const n=function(e){return"string"==typeof e?e:""}(t.content),r=!0!==t.intermediate,o=function(e){const t=Oe(e.answered_by);return t?.agentId&&t.agentName?.trim()?{agentId:t.agentId,agentName:t.agentName}:null}(t);if(null!==o&&o.agentId!==e.agentId)return n&&e.others.push({...o,failed:!0===t.mention_failed,text:n}),r?{kind:"answer",text:e.segments.join("\n\n"),others:e.others}:{kind:"progress"};if(!r)return n&&(e.segments=e.folded?[n]:[...e.segments,n]),{kind:"progress"};return{kind:"answer",text:(e.folded?[n]:[...e.segments,n]).filter(Boolean).join("\n\n"),others:e.others}}return"cancelled"===r||"error"===r?{kind:"failed"}:{kind:"ignore"}}function Pn(e){return e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}const Un=new Set(["no-speech","aborted"]);function Hn(e){const t=e.setTimer??((e,t)=>window.setTimeout(e,t)),n=e.clearTimer??(e=>window.clearTimeout(e)),r=e.recognition;let o="listening",a=!1,s="",i=[],c="",l=null,d=!1,u=0,p=null,h="",m=null,f=null,g=null,v=null,w=!1,y=!1,b=0;const x=()=>e.onChange({phase:o,muted:a,heard:s,lines:i}),k=e=>(null!==e&&n(e),null),N=()=>!a&&("listening"===o||"speaking"===o),C=()=>{if(N()){if(w||null!==v)return;try{r.start(),w=!0}catch{}}else if(w)try{r.stop()}catch{}},S=e=>{o=e,C(),x()},I=()=>{p?.abort(),p=null,h=""},T=()=>{m=k(m),g=k(g),c="",s="",S("listening")},A=()=>{f=k(f),l=null,d=!1},_=()=>{A(),S("error"),g=t(()=>{g=null,"error"===o&&T()},2e3)},E=()=>{f=k(f);const n=l;f=t(()=>{f=null,e.probe().then(e=>{l===n&&n&&("over"===e?_():E())})},12e4)},M=t=>{if(!l||!d)return;const n=On(l,t);"ignore"!==n.kind&&("answer"===n.kind?((t,n)=>{A();const r=e.present(t),a=function(e){const t=e.text.trim()?[{content:e.text}]:[];for(const n of e.others)n.text.trim()&&t.push({content:n.text,agent:{name:n.agentName,failed:n.failed}});return t}({text:r,others:n.map(t=>({...t,text:e.present(t.text)}))});i=[...i,...a.map(e=>({role:"assistant",...e}))];const l=r.trim()?e.speakable(r):"";if(!l.trim())return void T();const d=new AbortController;p=d,h=l,s="",c="",S("speaking"),e.speak(l,d.signal).catch(()=>{}).then(()=>{p===d&&(p=null,h="","speaking"===o&&T())})})(n.text,n.others):"failed"===n.kind?_():E())},L=()=>{u+=1,A()};return r.continuous=!0,r.interimResults=!0,e.lang&&(r.lang=e.lang),r.onresult=n=>{if(b=0,a||"listening"!==o&&"speaking"!==o)return;let r="",p="";for(let e=n.resultIndex;e<n.results.length;e++){const t=n.results[e];t.isFinal?r+=t[0].transcript:p+=t[0].transcript}if("speaking"===o){if(!function(e,t){const n=Pn(e);if(n.length<2)return!1;const r=new Set(Pn(t));return n.filter(e=>r.has(e)).length/n.length<.6}(`${r} ${p}`,h))return;I(),c="",o="listening"}r.trim()&&(c=[c,r.trim()].filter(Boolean).join(" ")),s=[c,p.trim()].filter(Boolean).join(" "),m=k(m),c&&(m=t(()=>{m=null,"listening"===o&&!a&&c.trim()&&(t=>{const n=++u;m=k(m),c="",s="",i=[...i,{role:"user",content:t}],l=function(e=null){return{turnId:null,folded:!1,agentId:e,segments:[],others:[]}}(e.addressedAgentId()),d=!1,S("processing"),E();const r=()=>n===u&&null!==l;e.send(t,{onAccepted:()=>{r()&&(d=!0)},onNotSent:()=>{r()&&_()},onSteered:(e,t)=>{r()&&(d=!0,M(e?{type:"folded_into_active_turn",folded:!0,turn_id:e}:{type:"folded_into_active_turn",...t?{folded:!1}:{}}))}}).then(e=>{!r()||"dropped"!==e&&"failed"!==e||_()},()=>{r()&&_()})})(c.trim())},1e3)),x()},r.onerror=e=>{y=!0,Un.has(e?.error??"")||(b+=1)},r.onend=()=>{w=!1;const e=y;if(y=!1,N())return b>=5?(b=0,a=!0,void x()):void(e?v=t(()=>{v=null,C()},300):C())},{start:T,end:()=>{if("ended"!==o){if(L(),I(),m=k(m),g=k(g),v=k(v),o="ended",r.onresult=null,r.onerror=null,r.onend=null,w)try{r.abort()}catch{}w=!1,x()}},frame:(e,t)=>M({...e,relayed:t||!0===e.relayed}),interrupt:()=>{"speaking"===o?(I(),T()):"processing"===o&&(L(),e.stopTurn(),T())},cancel:()=>{"processing"!==o&&"speaking"!==o||(L(),I(),T())},toggleMute:()=>{if("ended"!==o){if(a=!a,b=0,a)m=k(m),c="",s="";else if("speaking"===o)return I(),void T();C(),x()}}}}const Wn=()=>null!==zn();function qn(e,t){return new Promise(n=>{const r=URL.createObjectURL(e),o=new Audio(r),a=e=>{o.pause(),URL.revokeObjectURL(r),t.removeEventListener("abort",s),n(e)},s=()=>a(!0);o.onended=()=>a(!0),o.onerror=()=>a(!1),t.addEventListener("abort",s),o.play().catch(()=>a(!1))})}function Bn(e,t,n){return"undefined"!=typeof window&&window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance?new Promise(r=>{const o=new SpeechSynthesisUtterance(e);t&&(o.lang=t);const a=()=>{n.removeEventListener("abort",s),r()},s=()=>{window.speechSynthesis.cancel(),a()};o.onend=a,o.onerror=a,n.addEventListener("abort",s),window.speechSynthesis.speak(o)}):Promise.resolve()}const Fn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),t("path",{d:"M12 9v4"}),t("path",{d:"M12 17h.01"})]}),Vn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m16 3 4 4-4 4"}),t("path",{d:"M20 7H4"}),t("path",{d:"m8 21-4-4 4-4"}),t("path",{d:"M4 17h16"})]}),Kn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),Gn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 8V4H8"}),t("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),t("path",{d:"M2 14h2"}),t("path",{d:"M20 14h2"}),t("path",{d:"M15 13v2"}),t("path",{d:"M9 13v2"})]}),Jn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),t("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),t("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),t("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),t("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),t("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),t("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),t("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),t("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),Yn=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),Xn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 6 9 17l-5-5"})}),Zn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m6 9 6 6 6-6"})}),Qn=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m9 18 6-6-6-6"})}),er=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),tr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),t("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),nr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),t("path",{d:"M3 5V19A9 3 0 0 0 21 19V5"}),t("path",{d:"M3 12A9 3 0 0 0 21 12"})]}),rr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),or=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),t("polyline",{points:"7 10 12 15 17 10"}),t("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]}),ar=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 20h9"}),t("path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"})]}),sr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M10 14 21 3"}),t("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),ir=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),cr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7"}),t("rect",{width:"12",height:"12",x:"10",y:"10",rx:"2"})]}),lr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}),dr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1"}),t("path",{d:"M2 13h10"}),t("path",{d:"m9 16 3-3-3-3"})]}),ur=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 10v6"}),t("path",{d:"M9 13h6"}),t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})]}),pr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),t("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),t("path",{d:"M3 16h3a2 2 0 0 0 2 2v3"}),t("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"})]}),hr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),t("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),t("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),t("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]}),mr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("line",{x1:"6",x2:"10",y1:"11",y2:"11"}),t("line",{x1:"8",x2:"8",y1:"9",y2:"13"}),t("line",{x1:"15",x2:"15.01",y1:"12",y2:"12"}),t("line",{x1:"18",x2:"18.01",y1:"10",y2:"10"}),t("path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"})]}),fr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),t("path",{d:"M2 12h20"})]}),gr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),t("path",{d:"M3 3v5h5"}),t("path",{d:"M12 7v5l4 2"})]}),vr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),t("circle",{cx:"9",cy:"9",r:"2"}),t("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]}),wr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),yr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),t("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),br=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),xr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),kr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]}),Nr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-.11 1.23"}),t("path",{d:"M5 10v2a7 7 0 0 0 12 5"}),t("path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33"}),t("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12"}),t("path",{d:"m2 2 20 20"})]}),Cr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}),t("path",{d:"m15 5 4 4"})]}),Sr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272"}),t("path",{d:"M22 2 2 22"}),t("path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473"})]}),Ir=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),Tr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),Ar=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),_r=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),Er=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),Mr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),Lr=({className:n,size:r=24,filled:o=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:o?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M17 14V2"}),t("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),Rr=({className:n,size:r=24,filled:o=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:o?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M7 10v12"}),t("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),$r=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 6h18"}),t("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),t("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),t("line",{x1:"10",x2:"10",y1:"11",y2:"17"}),t("line",{x1:"14",x2:"14",y1:"11",y2:"17"})]}),Dr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t("circle",{cx:"9",cy:"7",r:"4"}),t("line",{x1:"19",x2:"19",y1:"8",y2:"14"}),t("line",{x1:"22",x2:"16",y1:"11",y2:"11"})]}),zr="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",jr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:zr}),t("path",{d:"M16 9a5 5 0 0 1 0 6"}),t("path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"})]}),Or=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:zr}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),Pr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),Ur=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]});function Hr({onClear:r,className:o,iconButtonClass:s,t:i}){const[c,l]=a(!1);return t("div",{className:`flex items-center gap-1 ${o}`,children:c?e(n,{children:[t("span",{className:"flex-1 text-[0.7rem] text-red-600 dark:text-red-400",children:i("Delete all conversations?")}),t("button",{type:"button",onClick:()=>{l(!1),r()},"aria-label":i("Delete all conversations"),className:`${s} hover:text-red-500`,children:t(Xn,{size:13})}),t("button",{type:"button",onClick:()=>l(!1),"aria-label":i("Cancel"),className:s,children:t(er,{size:13})})]}):e("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1.5 rounded-md px-1 py-0.5 text-[0.7rem] chat-text-muted-400/40 hover:text-red-500 dark:hover:text-red-400 transition-colors",children:[t($r,{size:12}),i("Clear all conversations")]})})}const Wr=({open:e,onClose:n,anchorRef:r,placement:o="bottom-start",width:l=280,children:u})=>{const p=s(null),[h,m]=a({top:0,left:0}),f=c(()=>n(),[n]);if(function(e,t,n=!0){i(()=>{if(!n)return;const r=n=>{e.current&&!e.current.contains(n.target)&&t()};return document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r)}},[e,t,n])}(p,f,e),d(()=>{if(!e||!r.current)return;const t=r.current.getBoundingClientRect(),n=p.current?.offsetHeight??0,a=window.innerHeight-t.bottom-8,s=t.top-8,i=n>0&&a<n&&s>a?Math.max(8,t.top-n-4):t.bottom+4,c="bottom-end"===o?t.right-l:t.left,d=Math.max(8,Math.min(c,window.innerWidth-l-8));m({top:i,left:d})},[e,r,o,l,u]),!e)return null;const g=_(r.current);return b(t("div",{ref:p,className:"fixed z-[10000] rounded-[10px] overflow-hidden border chat-border-200/10 chat-menu-surface shadow-xl",style:{top:h.top,left:h.left,width:l},children:u}),g)},qr=({size:e=16,className:n=""})=>t("div",{className:`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${n}`,style:{width:e,height:e}});function Br(e){return Math.max(e.maxRight-e.minLeft,0)}const Fr=({title:n,children:r})=>{const o=s(null),i=s(null),[c,l]=a(null),[u,p]=a({below:!1,shift:0});if(d(()=>{if(!c||!i.current)return;const{width:e,height:t}=i.current.getBoundingClientRect();p(function(e,t){const n=e.center-t.width/2;let r=0;return n<e.minLeft?r=e.minLeft-n:n+t.width>e.maxRight&&(r=e.maxRight-(n+t.width)),{below:e.top-4-t.height<e.minTop,shift:r}}(c,{width:e,height:t}))},[c,n]),!n)return r;const h=()=>{if(!o.current)return;const e=_(o.current).getBoundingClientRect();l(function(e,t,n){return{top:e.top,bottom:e.bottom,center:(e.left+e.right)/2,minTop:Math.max(t.top,0),minLeft:Math.max(t.left,0)+4,maxRight:Math.min(t.right,n)-4}}(o.current.getBoundingClientRect(),e,window.innerWidth))};return e("span",{ref:o,className:"inline-flex",onMouseEnter:h,onMouseLeave:()=>l(null),onFocus:e=>{const t=e.target;"function"==typeof t.matches&&t.matches(":focus-visible")&&h()},onBlur:()=>l(null),children:[r,c&&b(t("span",{ref:i,className:`pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${u.below?"":"-translate-y-full"} whitespace-normal break-words rounded-md bg-gray-900 dark:bg-gray-100 px-2 py-1 text-xs text-white dark:text-gray-900 shadow-lg`,style:{top:u.below?c.bottom+4:c.top-4,left:c.center+u.shift,maxWidth:Br(c)},role:"tooltip",children:n}),_(o.current))]})},Vr=({icon:e,fallback:n})=>{const r=function(e){const t=e?.trim();return t?/^(https:\/\/|data:image\/)/i.test(t)?"image":t.length<=8&&!/[\p{L}\p{N}]/u.test(t)?"emoji":null:null}(e);return"image"===r?t("img",{src:e.trim(),alt:"",className:"w-4 h-4 rounded-sm object-cover"}):t("span","emoji"===r?{className:"text-sm leading-none",children:e.trim()}:{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:n})},Kr=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(cr,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(Ar,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(hr,{...e})}],Gr=({mode:r,agentName:o,agents:c,agentsLoading:l=!1,agentsError:d=!1,selectedAgent:p,transferredFrom:h,agentMenuOpen:m,onAgentMenuToggle:f,onAgentMenuClose:g,onSwitchAgent:v,modeMenuOpen:w,onModeMenuToggle:y,onModeMenuClose:b,onModeChange:x,onNewChat:k,onClose:N,logoIcon:C,agentDashboardUrl:S,historyEnabled:I=!1,historyMenuOpen:T=!1,onHistoryMenuToggle:_,onHistoryMenuClose:E,conversations:L=[],conversationsLoading:R=!1,activeConversationId:$=null,onSelectConversation:D,onDeleteConversation:z,onClearAll:j,actions:O,t:P})=>{const U=s(null),H=s(null),q=s(null),[B,F]=a("");i(()=>{m||F("")},[m]);const V=u(()=>{const e=B.trim().toLowerCase();return e?c.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):c},[c,B]),K=c.length>5,G="sidebar"===r?Ar:"fullscreen"===r?pr:cr;return e("div",{className:"flex items-center px-3 py-2 min-h-[48px] border-b chat-border-200/10 chat-header-surface "+("floating"===r?"rounded-t-xl":""),children:[e("div",{className:"min-w-0",children:[e("button",{ref:U,type:"button",onClick:f,className:"flex max-w-full items-center gap-1.5 text-sm font-semibold chat-text-900/100 px-2 py-1 rounded-lg hover:chat-surface-hover-100/10 transition-colors",children:[t("span",{className:"flex shrink-0 items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:C}),t("span",{className:"min-w-0 truncate",children:o}),t(Zn,{size:16,className:"shrink-0 chat-text-muted-400/30"})]}),h&&t("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal chat-text-muted-400/30",children:A(P,"Transferred from {agent}",{agent:h})})]}),e(Wr,{open:m,onClose:g,anchorRef:U,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:P("Switch to another agent")}),0===c.length&&l&&t("div",{className:"px-4 py-2",children:t(qr,{size:16})}),0===c.length&&!l&&d&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(Fn,{size:14,className:"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400"}),t("span",{className:"text-[0.75rem] leading-5 chat-text-secondary-600/60",children:P("Could not reach the assistant service. Check the connection and try again.")})]}),0===c.length&&!l&&!d&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:P("Agent switching is not available here")}),K&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(Ir,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 chat-text-muted-400/40"}),t("input",{autoFocus:!0,type:"text",value:B,onChange:e=>F(e.target.value),onKeyDown:e=>{"Escape"===e.key&&g()},placeholder:P("Search agents..."),"aria-label":P("Search agents..."),className:"w-full h-7 pl-7 pr-2 rounded-md chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[c.length>0&&0===V.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:P("No agent matches")}),W(V).map(({group:n,agents:r})=>e("div",{role:"group","aria-label":n??void 0,children:[n&&t("span",{className:"block px-4 pt-2 pb-0.5 text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",children:n}),r.map(n=>e("button",{type:"button",onClick:()=>v(n),className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors "+(n.id===p?.id?"bg-[var(--chat-accent)]/10":""),children:[t("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t(Vr,{icon:n.icon,fallback:C})}),e("div",{className:"min-w-0",children:[t("div",{className:"text-[0.8125rem] font-medium chat-text-900/100 truncate",children:n.name}),n.description&&t("div",{className:"text-[0.7rem] chat-text-secondary-500/40 truncate",children:n.description})]})]},n.id))]},n??""))]}),t("div",{className:"h-px chat-border-fill-200/10 mx-2"}),e("div",{children:[S&&e("button",{type:"button",onClick:()=>{g(),window.open(`${S}/agents`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(sr,{size:18,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:P("Browse agents")})]}),S&&e("button",{type:"button",onClick:()=>{g(),window.open(`${S}/agents/new`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(Dr,{size:18,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:P("Create agent")})]})]})]}),t("div",{className:"flex-1"}),I&&e(n,{children:[t(Fr,{title:P("Conversation history"),children:t("button",{ref:q,type:"button",onClick:_,"aria-label":P("Conversation history"),"aria-haspopup":"menu","aria-expanded":T,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(gr,{size:18})})}),e(Wr,{open:T,onClose:()=>E?.(),anchorRef:q,placement:"bottom-end",width:300,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:P("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[R&&0===L.length&&t("div",{className:"px-4 py-2",children:t(qr,{size:16})}),!R&&0===L.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:P("No conversations yet")}),L.map(n=>{const r=n.conversationId===$,o=M(n.updatedAt,P);return e("div",{className:"group flex items-center gap-2 px-4 py-1.5 hover:chat-surface-hover-100/10 transition-colors "+(r?"bg-[var(--chat-accent)]/10":""),children:[e("button",{type:"button",onClick:()=>D?.(n.conversationId),className:"flex-1 min-w-0 text-left",children:[t("div",{className:"text-[0.8125rem] font-medium chat-text-900/100 truncate",children:n.title||P("Untitled conversation")}),o&&t("div",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:o})]}),z&&t("button",{type:"button",onClick:()=>z(n.conversationId),title:P("Delete conversation"),"aria-label":P("Delete conversation"),className:"shrink-0 p-1 rounded-md chat-text-muted-400/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all",children:t($r,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px chat-border-fill-200/10 mx-2"}),e("button",{type:"button",onClick:()=>{E?.(),k()},className:"w-full flex items-center gap-2 px-4 py-2 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(ar,{size:16,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:P("New conversation")})]}),j&&L.length>0&&t(Hr,{onClear:()=>{E?.(),j()},className:"px-3 pb-2",iconButtonClass:"p-1 rounded-md chat-text-muted-400/40 hover:chat-surface-hover-100/10 transition-colors",t:P})]})]}),O,t(Fr,{title:P("New chat"),children:t("button",{type:"button",onClick:k,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(ar,{size:18})})}),"inline"!==r&&x&&e(n,{children:[t(Fr,{title:P("Switch view"),children:t("button",{ref:H,type:"button","aria-label":P("Switch view"),onClick:y,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(G,{size:18})})}),e(Wr,{open:w,onClose:b,anchorRef:H,placement:"bottom-end",width:180,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:P("Switch to")}),t("div",{className:"pb-1",children:Kr.map(n=>e("button",{type:"button",onClick:()=>{x(n.mode),b()},className:"w-full flex items-center gap-3 px-4 py-1 text-left hover:chat-surface-hover-100/10 transition-colors "+(r===n.mode?"bg-[var(--chat-accent)]/10":""),children:[n.getIcon({size:18,className:"chat-text-muted-400/40"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:n.label(P)})]},n.mode))})]})]}),"inline"!==r&&N&&t(n,{children:t(Fr,{title:P("Close"),children:t("button",{type:"button","aria-label":P("Close"),onClick:N,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(er,{size:18})})})})]})};function Jr({url:e,query:t,exclude:n,requestHeaders:r}){const o=Ut(),[s,c]=a(me);return i(()=>{if(!e||null===t)return void c(me);let a=!0;const s=new AbortController,i=window.setTimeout(async()=>{try{const i=await o(function(e,t,n){const r=new URLSearchParams({limit:String(8)});return t&&r.set("q",t),n&&r.set("exclude",n),`${e}${e.includes("?")?"&":"?"}${r.toString()}`}(e,t,n),{credentials:"include",headers:{...r??{}},signal:s.signal}),l=i.ok?await i.json():null;if(!a)return;c(i.ok?{query:t,items:pe(l),failed:!1}:{query:t,items:[],failed:!0})}catch{a&&c({query:t,items:[],failed:!0})}},150);return()=>{a=!1,window.clearTimeout(i),s.abort()}},[e,t,n,r]),s}function Yr({url:e,requestHeaders:t,conversationId:n,text:r,onTextChange:o,textareaRef:l,refs:h,onPick:m,agentMentions:f}){const g=null!==e||!!f,[v,w]=a(null),[y,b]=a(null),[x,k]=a(0),N=s(null),C=p(),S=c(e=>`${C}-option-${e}`,[C]),I=c(()=>{const e=l.current,t=g&&e&&document.activeElement===e&&e.selectionStart===e.selectionEnd?function(e){const t=/@([\w-]*)$/.exec(e);return!t||ie(e[t.index-1])?null:{anchor:t.index,query:t[1]}}(e.value.slice(0,e.selectionStart)):null;w(e=>{return(n=e)===(r=t)||n&&r&&n.anchor===r.anchor&&n.query===r.query?e:t;var n,r})},[g,l]),T=c(()=>w(null),[]);d(()=>{const e=N.current;if(null===e)return;N.current=null;const t=l.current;t&&(t.focus(),t.setSelectionRange(e,e))},[r,l]),i(()=>{I()},[r,I]),i(()=>{v||b(null)},[v]);const A=Jr({url:e,query:v?.query??null,exclude:n,requestHeaders:t}),[_,E]=a([]);i(()=>{E([])},[n]),i(()=>{E(e=>function(e,t,n){if(null===t.query||t.failed)return e;const r=t.query,o=new Set(t.items.map(e=>e.id)),a=t.items.length<8,s=r.toLowerCase(),i=a?e.filter(e=>e.id===n||o.has(e.id)||!e.title.toLowerCase().includes(s)):e;return ge(i.length===e.length?e:i,t.items)}(e,A,n))},[A,n]);const M=u(()=>ge(h.map(ve),_),[h,_]);i(()=>{k(0)},[A]);const L=function(e){const{trigger:t,dismissed:n,search:r,referenced:o,exclude:a,known:s=[]}=e;if(!t||n)return{kind:"closed"};if(o>=5)return{kind:"full"};if(r.failed)return{kind:"closed"};const i=t.query?s.filter(e=>fe(t.query,e)&&!r.items.some(t=>t.id===e.id)):[],c=[...r.items,...i].slice(0,8),l=a?c.filter(e=>e.id!==a):c;return l.length>0?{kind:"results",items:l}:t.query&&r.query===t.query?{kind:"empty"}:{kind:"closed"}}({trigger:v,dismissed:null!==v&&v.anchor===y,search:A,referenced:ue(h,r).length,exclude:n,known:M}),R=null!==v&&v.anchor===y,$=[...u(()=>f&&v&&!R?function(e,t){const n=[];for(const r of e){const e=zt(r);if(e&&fe(t,{key:e,title:r.name})&&(n.push({agentId:r.id,name:r.name,key:e}),n.length>=5))break}return n}(f.agents,v.query):[],[f,v,R]).map(e=>({type:"agent",mention:e})),...null!==e&&"results"===L.kind?L.items.map(e=>({type:"conversation",candidate:e})):[]],D=Math.min(x,Math.max($.length-1,0)),z=e=>{if(!v)return;const t="agent"===e.type?e.mention.key:e.candidate.key,n=function(e,t,n){const r=e.slice(0,t.anchor),o=e.slice(t.anchor+1+t.query.length),a=`@${n}`;return{text:`${r}${a}${/^\s/.test(o)?"":" "}${o}`,caret:r.length+a.length+1}}(r,v,t);"agent"===e.type?f?.onPick(e.mention):m({conversationId:e.candidate.id,title:e.candidate.title,key:t,isOwn:e.candidate.isOwn}),N.current=n.caret,o(n.text),w(null)},j=g?{"aria-autocomplete":"list","aria-controls":$.length>0?C:void 0,"aria-activedescendant":$.length>0?S(D):void 0}:{};return{view:null===e?{kind:"closed"}:L,items:$,activeIndex:D,setActiveIndex:k,listboxId:C,optionId:S,sync:I,close:T,pick:z,onKeyDown:e=>{if("closed"===L.kind&&0===$.length||!v||e.nativeEvent.isComposing)return!1;if("Escape"===e.key)return e.preventDefault(),b(v.anchor),!0;if(0===$.length)return!1;if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;return k((D+t+$.length)%$.length),!0}return!("Enter"!==e.key&&"Tab"!==e.key||e.shiftKey)&&(e.preventDefault(),z($[D]),!0)},textareaAria:j}}const Xr=14,Zr=2*Math.PI*6,Qr=[{field:"system",label:e=>e("System prompt"),color:"#9ca3af"},{field:"tools",label:e=>e("Tool definitions"),color:"#a78bfa"},{field:"dynamicTools",label:e=>e("MCP & dynamic tools"),color:"#f0abfc"},{field:"summary",label:e=>e("Summarized conversation"),color:"#fb7185"},{field:"toolResults",label:e=>e("Tool results"),color:"#34d399"},{field:"conversation",label:e=>e("Conversation"),color:"#a1a1aa"}],eo=({usage:r,t:o})=>{const{used:i,limit:c,breakdown:l}=r,d=s(null),[u,p]=a(!1),h=Math.min(Math.max(i/c,0),1),m=h>=.95,f=h>=.8,g=m?"text-red-500":f?"text-amber-500":"text-[var(--chat-accent)]",v=m?"text-red-500 dark:text-red-400":f?"text-amber-600 dark:text-amber-400":"chat-text-muted-400/30",w=Math.round(100*h),y=`${E(i)}/${E(c)}`,b=o(m?"Context full — older turns are being dropped":f?"Context nearly full — older turns are being summarized":"Context used"),x=A(o,"{counts} tokens",{counts:y}),k=`${b} · ${x}`,N=l?Qr.filter(e=>(l[e.field]??0)>0):[],C=N.length>0,S=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:Xr,height:Xr,viewBox:"0 0 14 14",className:g,"aria-hidden":"true",children:[t("circle",{cx:7,cy:7,r:6,fill:"none",strokeWidth:2,className:"stroke-gray-200 dark:stroke-white/15"}),t("circle",{cx:7,cy:7,r:6,fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeDasharray:Zr,strokeDashoffset:Zr*(1-h),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${v}`,children:[w,"%"]})]});return C?e(n,{children:[t(Fr,{title:u?"":A(o,"{summary} — click for details",{summary:k}),children:t("button",{ref:d,type:"button",onClick:()=>p(e=>!e),"aria-label":`${k} (${w}%)`,"aria-haspopup":"dialog","aria-expanded":u,className:"flex items-center rounded-md px-1 -mx-1 py-0.5 transition-colors hover:chat-surface-hover-100/10",children:S})}),e(Wr,{open:u,onClose:()=>p(!1),anchorRef:d,placement:"bottom-end",width:296,children:[e("div",{className:"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3",children:[t("span",{className:`text-[0.8125rem] tabular-nums ${v}`,children:A(o,"{percent}% full",{percent:w})}),e("span",{className:"text-[0.7rem] tabular-nums chat-text-muted-400/40 shrink-0",children:["~",x]})]}),t("div",{className:"px-3.5 pb-2.5 pt-1.5",children:t("span",{className:"flex h-1.5 w-full gap-px rounded-full chat-border-fill-200/10 overflow-hidden",children:N.map(e=>t("span",{className:"h-full first:rounded-l-full",style:{width:(l?.[e.field]??0)/Math.max(i,1)*Math.min(i/c,1)*100+"%",backgroundColor:e.color}},e.field))})}),t("div",{className:"px-3.5 pb-1",children:N.map(n=>e("div",{className:"flex items-center gap-2 py-[3px]",children:[t("span",{className:"h-2 w-2 shrink-0",style:{backgroundColor:n.color,borderRadius:2},"aria-hidden":"true"}),t("span",{className:"text-[0.75rem] chat-text-secondary-700/70 truncate",children:n.label(o)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums chat-text-muted-500/40 shrink-0",children:E(l?.[n.field]??0)})]},n.field))}),f&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${v}`,children:b})]})]}):t(Fr,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},to=({view:n,items:r,activeIndex:o,listboxId:a,optionId:i,onHover:c,onPick:l,t:u})=>{const p=s(null);if(d(()=>{p.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[o,n.kind]),"closed"===n.kind&&0===r.length)return null;const h=r.some(e=>"agent"===e.type),m=u(h?"Mention an agent":"Reference a conversation");return e("div",{className:"absolute left-0 right-0 bottom-full mb-1.5 z-20 rounded-[10px] overflow-hidden border chat-border-200/10 chat-menu-surface shadow-xl",children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:m}),r.length>0&&t("div",{ref:p,id:a,role:"listbox","aria-label":m,className:"max-h-[240px] overflow-y-auto pb-1 filigran-chat-scrollable",children:r.map((n,a)=>{const s=a===o,d="conversation"===n.type&&h&&"agent"===r[a-1]?.type;return e("div",{children:[d&&t("span",{className:"block px-4 pt-2 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:u("Reference a conversation")}),e("div",{id:i(a),role:"option","aria-selected":s,onMouseDown:e=>{e.preventDefault(),l(n)},onMouseMove:()=>{s||c(a)},className:"flex items-center gap-2.5 px-4 py-1.5 cursor-pointer transition-colors "+(s?"chat-surface-subtle-100/10":""),children:[t("span",{className:"shrink-0 text-[var(--chat-accent)]",children:"agent"===n.type?t(Gn,{size:14}):t(xr,{size:14})}),"agent"===n.type?e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.mention.name}),e("span",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:["@",n.mention.key]})]}):e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.candidate.title||u("Untitled conversation")}),e("span",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:["@",n.candidate.key,!n.candidate.isOwn&&` · ${u("Shared with you")}`]})]})]})]},"agent"===n.type?`agent-${n.mention.agentId}`:n.candidate.id)})}),"empty"===n.kind&&0===r.length&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] chat-text-muted-400/40",children:u("No conversation matches")}),"full"===n.kind&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] chat-text-muted-400/40",children:A(u,"A message references at most {count} conversations",{count:5})})]})},no=({prompts:r,onPick:o,t:i})=>{const c=s(null),[l,d]=a(!1),[u,p]=a(""),h=()=>{d(!1),p("")},m=u.trim().toLowerCase(),f=m?r.filter(e=>e.title.toLowerCase().includes(m)||(e.description??"").toLowerCase().includes(m)):r;return e(n,{children:[t(Fr,{title:i("Insert prompt template"),children:t("button",{ref:c,type:"button",onClick:()=>l?h():d(!0),"aria-label":i("Insert prompt template"),"aria-haspopup":"menu","aria-expanded":l,className:"w-7 h-7 flex items-center justify-center rounded-lg transition-colors "+(l?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10":"chat-text-muted-400/30 hover:chat-surface-hover-100/10"),children:t(_r,{size:15})})}),e(Wr,{open:l,onClose:h,anchorRef:c,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:i("Insert prompt template")}),r.length>5&&t("div",{className:"px-3 pb-2 pt-1",children:t("input",{autoFocus:!0,type:"text",value:u,onChange:e=>p(e.target.value),onKeyDown:e=>{"Escape"===e.key&&h()},placeholder:i("Search prompts..."),"aria-label":i("Search prompts..."),className:"w-full h-7 px-2 rounded-md chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[0===f.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:i("No prompt matches")}),f.map(n=>e("button",{type:"button",onClick:()=>{o(n.content),h()},className:"w-full px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t("div",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.title}),n.description&&t("div",{className:"text-[0.7rem] chat-text-secondary-500/40 truncate",children:n.description})]},n.id))]})]})]})},ro=({quota:n,t:r})=>{const{used:o,limit:a}=n,s=function(e,t){switch(e){case"daily":return t("today");case"monthly":return t("this month");case"yearly":return t("this year");default:return e}}(n.period,r),i=e=>"global"===n.scope?A(r,"{quota} (shared across all users)",{quota:e}):e;if(null===a){const e=i(s?A(r,"Usage · {period}",{period:s}):r("Usage"));return t(Fr,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums chat-text-muted-400/30",role:"img","aria-label":`${e} ${E(o)}`,children:E(o)})})}const c=a>0?Math.min(o/a,1):1,l=!(a>0)||o>=a,d=c>=.75,u=l?"bg-red-500":d?"bg-amber-500":"bg-[var(--chat-accent)]/60",p=l?"text-red-500 dark:text-red-400":d?"text-amber-600 dark:text-amber-400":"chat-text-muted-400/30",h=`${E(o)}/${E(a)}`,m=r(l?"Quota reached":"Quota"),f=i(s?`${m} · ${s}`:m);return t(Fr,{title:f,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${f} ${h}`,children:[t("span",{className:"h-1 w-10 rounded-full chat-border-fill-200/10 overflow-hidden",children:t("span",{className:`block h-full rounded-full transition-[width] duration-300 ${u}`,style:{width:100*c+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${p}`,children:h})]})})},oo=[],ao=({header:r,steerAttachments:o=!1,canHold:l=!1,heldMessage:p,notice:h,onCancelHeld:m,inputValue:f,onInputChange:g,onSend:v,onStop:w,isLoading:y,sendsHeld:b=!1,canSteer:x=!1,attachedFiles:k=[],onFileAdd:N,onFileRemove:C,onPaste:S,t:I,mode:T,separatorColor:A,prompts:_,quota:E,contextUsage:M,composerToolbar:L,conversationReferences:R,agentMentions:$})=>{const D=s(null),z=s(null),j=$?.agents,O=$?.onPick,P=u(()=>j&&O?{agents:j,onPick:O}:void 0,[j,O]),U=Yr({url:R?.url??null,requestHeaders:R?.requestHeaders,conversationId:R?.conversationId,text:f,onTextChange:g,textareaRef:z,refs:R?.refs??oo,onPick:e=>R?.onPick(e),agentMentions:P}),H=s(!1),W=function(e){const[t,n]=a(!1),[r,o]=a(""),l=s(null),d=s(e);d.current=e;const u=null!==zn();return i(()=>{const e=zn();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=Dn(t,{onFinal:e=>d.current(e),onInterim:o,onListeningChange:n});return l.current=r,()=>{l.current=null,r.dispose(),n(!1),o("")}},[]),{supported:u,listening:t,interim:r,toggle:c(()=>l.current?.toggle(),[]),cancel:c(()=>l.current?.cancel(),[])}}(e=>{H.current=!0,g(f.trim()?`${f.trimEnd()} ${e}`:e)});d(()=>{const e=z.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,H.current&&(H.current=!1,e.scrollTop=e.scrollHeight))},[f]);const q=Boolean(_&&_.length>0||E||M||L),B=Boolean(N&&C&&S),F=f.trim()||B&&k.length>0,V=B&&k.some(e=>"pending"===e.uploadStatus),K=B&&k.length>0,G=B&&(y||b)&&Dt(k),J=F&&!V&&!G,Y=Boolean(R)&&ue(R?.refs??oo,f).length>0||Boolean($)&&jt($?.mentions??[],f).length>0,X=y&&x&&!Y&&(!K||o),Z=X&&!V&&!G&&(K||Boolean(f.trim())),Q=y&&l&&!Z&&!p&&Boolean(J),ee=()=>{(y?Z||Q:J)&&(W.cancel(),v())},te=I(Q?"Enter to send when the answer ends · Esc to stop":G?"A file failed to upload: remove it, or send once the answer ends":X?"Enter to send now · Esc to stop":y&&K?"Attachments wait for the current response":y&&Y?"This message waits for the current response":"Uses AI. Verify results.");return e("div",{className:"px-4 py-3 border-t chat-border-200/10 "+("floating"===T?"rounded-b-xl":""),style:A?{borderTopColor:A,borderTopWidth:1}:void 0,"data-testid":"filigran-chat-composer",children:[r&&t("div",{className:"mb-2",children:r}),h&&t("div",{role:"alert","data-testid":"filigran-chat-composer-notice",className:"mb-2 text-[0.75rem] text-red-500 dark:text-red-400",children:h}),p&&e("div",{className:"mb-2 flex items-center gap-2 rounded-lg border border-dashed border-[var(--chat-accent-40)] px-2.5 py-1.5 text-[0.75rem]",children:[t("span",{className:"shrink-0 chat-text-secondary-500/50",children:I("Sends when the answer ends:")}),t("span",{className:"min-w-0 flex-1 truncate chat-text-800/80",children:p.displayText??(p.text||I("Attached files"))}),m&&t("button",{type:"button",onClick:m,className:"shrink-0 chat-text-muted-400/40 hover:text-red-500",children:I("Cancel")})]}),B&&k.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:k.map((n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] "+("error"===n.uploadStatus?"border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400":"pending"===n.uploadStatus?"chat-border-200/10 chat-text-muted-400/40":"chat-border-200/10 chat-text-secondary-600/60"),children:["pending"===n.uploadStatus?t("span",{className:"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin"}):t(ir,{size:14}),n.name,"error"===n.uploadStatus&&t("span",{className:"text-red-400 text-[0.6rem]",children:"✕"}),t("button",{type:"button",onClick:()=>C?.(r),className:"ml-0.5 chat-text-muted-400/30 hover:chat-text-secondary-600/60",children:"×"})]},r))}),e("div",{className:`relative flex items-end border rounded-xl chat-composer-surface px-2 py-1 transition-colors ${W.listening?"border-red-500/50":"chat-border-200/10 focus-within:border-[var(--chat-accent)]"} ${y?"filigran-chat-active-border":""}`,children:[B&&e(n,{children:[t("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:e=>{N?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>D.current?.click(),"aria-label":I("Attach files"),className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 mr-0.5 transition-colors",children:t(Kn,{size:18})})]}),t("textarea",{ref:z,placeholder:W.listening?I("Listening..."):I("Ask a question..."),value:f,onChange:e=>g(e.target.value),onKeyDown:e=>{U.onKeyDown(e)||("Enter"!==e.key||e.shiftKey||(e.preventDefault(),ee()),"Escape"===e.key&&y&&(e.preventDefault(),w()))},onKeyUp:U.sync,onClick:U.sync,onFocus:U.sync,onBlur:U.close,...U.textareaAria,onPaste:S,rows:1,className:"flex-1 bg-transparent border-none outline-hidden resize-none text-[0.8125rem] py-1.5 chat-text-900/100 placeholder:chat-text-muted-400/30 filigran-chat-scrollable",style:{maxHeight:120}}),t(to,{view:U.view,items:U.items,activeIndex:U.activeIndex,listboxId:U.listboxId,optionId:U.optionId,onHover:U.setActiveIndex,onPick:U.pick,t:I}),W.supported&&t(Fr,{title:W.listening?I("Stop dictation"):I("Dictate a message"),children:e("button",{type:"button",onClick:W.toggle,"aria-label":I("Dictate a message"),"aria-pressed":W.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors "+(W.listening?"text-red-500 bg-red-500/10 hover:bg-red-500/20":"chat-text-muted-400/30 hover:chat-surface-hover-100/10"),children:[W.listening?t(Nr,{size:18}):t(kr,{size:18}),W.listening&&t("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse"})]})}),Q&&t(Fr,{title:I("Send when the answer ends"),children:t("button",{type:"button",onClick:ee,"aria-label":I("Send when the answer ends"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Tr,{size:18})})}),Z&&t(Fr,{title:I("Send now"),children:t("button",{type:"button",onClick:ee,"aria-label":I("Send now"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Tr,{size:18})})}),t(Fr,{title:y?I("Stop generating"):V?I("Files uploading..."):"",children:t("button",{type:"button",onClick:y?w:ee,"aria-label":I(y?"Stop generating":"Send"),disabled:!y&&!J,className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 "+(y?"text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5":J?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20":"chat-text-muted-300/20 cursor-not-allowed"),children:t(y?Er:Tr,{size:18})})})]}),q&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[_&&_.length>0&&t(no,{prompts:_,onPick:e=>{g(f.trim()?`${f.trimEnd()}\n\n${e}`:e),z.current?.focus()},t:I}),L,(M||E)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[M&&t(eo,{usage:M,t:I}),E&&t(ro,{quota:E,t:I})]})]}),W.interim?e("p",{className:"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-red-500 dark:text-red-400 mt-1.5",children:[t("span",{className:"w-1.5 h-1.5 shrink-0 rounded-full bg-red-500 motion-safe:animate-pulse"}),t("span",{className:"truncate",children:W.interim})]}):t("p",{"data-testid":"filigran-chat-disclaimer",className:"text-center text-[0.65rem] chat-text-muted-400/30 mt-1.5 opacity-70",children:te})]})},so=e=>e.serverId??e.id;const io=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;const co={time:{hour:"2-digit",minute:"2-digit"},date:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"},dateWithYear:{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"},full:{dateStyle:"full",timeStyle:"short"}},lo=new Map;function uo(e,t){const n=`${e??""}|${t}`;let r=lo.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,co[t])}catch{r=new Intl.DateTimeFormat(void 0,co[t])}lo.set(n,r)}return r}const po={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const ho=new Set(["ArrowUp","PageUp","Home"]);function mo(e){return 1===e.length?e[0].clientY:null}const fo=new Set(["auto","scroll","overlay"]);const go={presentation:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 3h20"}),t("path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"}),t("path",{d:"m7 21 5-5 5 5"})]}),report:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),t("path",{d:"M10 9H8"}),t("path",{d:"M16 13H8"}),t("path",{d:"M16 17H8"})]}),video:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z"}),t("path",{d:"m6.2 5.3 3.1 3.9"}),t("path",{d:"m12.4 3.4 3.1 4"}),t("path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})]})},vo="inline-flex items-center gap-1 rounded-md border chat-border-200/10 px-2 py-1 text-[0.7rem] chat-text-secondary-700/70 transition-colors hover:border-[var(--chat-accent)] hover:text-[var(--chat-accent)] disabled:opacity-50 disabled:cursor-default outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",wo=({artifact:n,t:r,onDownload:o,onRefresh:s,onOpen:c})=>{const[l,d]=a(n),[u,p]=a(null),[h,m]=a(!1);i(()=>d(n),[n]);const f=!!s&&!h&&(e=>"video"===e.kind&&("pending"===e.status||"running"===e.status))(l);i(()=>{if(!f||!s)return;let e=!1;const t=function(e,{intervalMs:t,forMs:n,onGiveUp:r}){let o,a=!1;const s=()=>{o=setTimeout(()=>{e().catch(()=>{}).finally(()=>{a||s()})},t)},i=setTimeout(()=>{a=!0,clearTimeout(o),r?.()},n);return s(),()=>{a=!0,clearTimeout(o),clearTimeout(i)}}(()=>s(l.kind,l.id).then(t=>{!e&&t&&d(t)}),{intervalMs:1e4,forMs:9e5,onGiveUp:()=>m(!0)});return()=>{e=!0,t()}},[f,s,l.kind,l.id]);const g=go[l.kind],v=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(l.kind,r),w=l.title||v,y=H(l,r),b=function(e,t){if("video"===e.kind){if("running"===e.status)return A(t,"Rendering {progress}%",{progress:Math.round(e.progress??0)});if("pending"===e.status)return t("Waiting to render");if(!(e.downloads.length>0))return"failed"===e.status||"cancelled"===e.status?t("The render did not finish"):t("Not rendered yet")}}(l,r),x=c?null:function(e){if(e.url)try{const t=new URL(e.url);return"http:"===t.protocol||"https:"===t.protocol?t.toString():void 0}catch{return}}(l),k=o?l.downloads:[];return e("div",{role:"group","aria-label":`${v}: ${w}`,className:"flex flex-col gap-2 w-full max-w-[90%] rounded-lg border chat-border-200/10 chat-surface-subtle-50/4 px-3 py-2.5",children:[e("div",{className:"flex items-start gap-2.5 min-w-0",children:[t("span",{className:"shrink-0 mt-0.5 text-[var(--chat-accent)]",children:t(g,{size:18})}),e("span",{className:"flex flex-col min-w-0 flex-1 gap-0.5",children:[t("span",{className:"truncate text-[0.8125rem] font-medium chat-text-900/100",children:w}),y&&t("span",{className:"text-[0.7rem] chat-text-secondary-500/50",children:y}),b&&e("span",{className:"flex items-center gap-1.5 text-[0.7rem] chat-text-secondary-500/50","aria-live":"polite",children:[f&&t(qr,{size:10}),b]})]})]}),(x||c||k.length>0)&&e("div",{className:"flex flex-wrap items-center gap-1.5 pl-[28px]",children:[c&&t("button",{type:"button",className:vo,onClick:()=>c(l),children:r("Open")}),x&&e("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:vo,children:[r("Open in XTM One"),t(sr,{size:12})]}),k.map(n=>{const a=function(e,t){return"pdf"===e?"PDF":"mp4"===e?"MP4":"pptx"===e?t("PowerPoint"):"pptx_native"===e?t("PowerPoint (editable)"):e.toUpperCase()}(n,r);return e("button",{type:"button",className:vo,disabled:null!==u,"aria-label":A(r,"Download {format}",{format:a}),onClick:()=>{(async e=>{if(o){p(e);try{await o(l,e)}finally{p(null)}}})(n)},children:[u===n?t(qr,{size:11}):t(or,{size:12}),a]},n)})]})]})};function yo(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function bo(e){const t=s(null);return i(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const xo="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",ko=({proposal:n,decision:r,onDecide:o,disabled:s,t:i})=>{const[c,l]=a(!1),[d,u]=a(""),h=p(),m=bo(c),f=r?.verdict,g=Object.keys(n.arguments??{}),v=e=>{o({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&d.trim()?{rejectionReason:d.trim()}:{}})};return e("div",{"data-testid":"filigran-chat-approval",className:"rounded-lg border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2",children:[e("div",{className:"flex items-start justify-between gap-2",children:[e("div",{className:"min-w-0 flex items-start gap-2",children:[t(Pr,{size:13,className:"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400"}),e("div",{className:"min-w-0",children:[t("p",{className:"truncate font-mono text-xs chat-text-800/85",children:n.toolName||i("unknown tool")}),n.toolDescription&&t("p",{className:"mt-0.5 text-[0.7rem] chat-text-secondary-600/60",children:n.toolDescription}),n.source&&t("p",{className:"mt-0.5 text-[0.65rem] chat-text-muted-400/35",children:n.source})]})]}),f&&t("span",{className:"shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===f?"bg-red-500/15 text-red-600 dark:text-red-300":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"),children:i("reject"===f?"Declined":"approve_always"===f?"Always allowed":"Approved")})]}),g.length>0&&t("div",{className:"flex flex-col gap-1.5",children:g.map(r=>{const o=function(e,t){const n=e?.properties;if(!n||"object"!=typeof n)return{};const r=n[t];if(!r||"object"!=typeof r)return{};const o=r;return{description:"string"==typeof o.description?o.description:void 0,type:"string"==typeof o.type?o.type:void 0}}(n.inputSchema,r);return e("div",{className:"text-[0.7rem]",children:[e("div",{className:"flex flex-wrap items-baseline gap-1.5",children:[t("span",{className:"font-mono chat-text-secondary-700/75",children:r}),o.description&&e("span",{className:"chat-text-secondary-500/45",children:["— ",o.description]})]}),t("pre",{className:"mt-0.5 whitespace-pre-wrap break-all font-mono chat-text-secondary-600/60",children:yo(n.arguments?.[r])})]},r)})}),!f&&c&&e("div",{ref:m,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:h,className:"text-[0.7rem] chat-text-secondary-500/45",children:i("Why not? The agent sees this and can adapt (optional)")}),t("textarea",{id:h,autoFocus:!0,rows:2,value:d,onChange:e=>u(e.target.value),placeholder:i("e.g. wrong environment — use staging instead"),className:"w-full resize-none rounded-md border chat-border-200/10 chat-input-surface-white/3 px-2 py-1 text-[0.7rem] chat-text-800/85 outline-none focus:border-[var(--chat-accent)]/50"}),e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>v("reject"),className:`${xo} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(Ur,{size:13}),i("Decline this call")]}),t("button",{type:"button",disabled:s,onClick:()=>{l(!1),u("")},className:`${xo} chat-text-secondary-500/50 hover:chat-surface-hover-100/5`,children:i("Back")})]})]}),!f&&!c&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>l(!0),className:`${xo} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(Ur,{size:13}),i("No")]}),e("button",{type:"button",disabled:s,onClick:()=>v("approve"),className:`${xo} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(Xn,{size:13}),i("Yes")]}),t("button",{type:"button",disabled:s,onClick:()=>v("approve_always"),title:i("Also applies to your scheduled runs, until you revoke it"),className:`${xo} border chat-border-200/15 chat-text-secondary-700/70 hover:chat-surface-hover-100/5`,children:i("Yes, always")})]})]})},No=({proposals:n,onSubmit:r,isSubmitting:o,error:c,t:l})=>{const[d,u]=a({}),p=s(!1),[h,m]=a(!1);i(()=>{c&&(p.current=!1,m(!1))},[c]);const f=o||h,g=e=>{p.current||o||(p.current=!0,m(!0),r(e))},v=n.filter(e=>d[e.toolCallId]).length,w=v===n.length&&n.length>0,y=Object.values(d).some(e=>"approve_always"===e.verdict),b=bo(y),x=bo(!0);return e("div",{ref:x,className:"flex flex-col gap-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.02] p-3",children:[e("p",{className:"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300",children:[t(Fn,{size:13,className:"mt-0.5 shrink-0"}),1===n.length?l("The agent needs your approval to run a tool:"):l("The agent needs your approval to run these tools:")]}),n.map(e=>t(ko,{proposal:e,decision:d[e.toolCallId],disabled:f,t:l,onDecide:e=>{const t={...d,[e.toolCallId]:e};u(t);const r=n.map(e=>t[e.toolCallId]);r.every(Boolean)&&!r.some(e=>"approve_always"===e.verdict)&&g(r)}},e.toolCallId)),y&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(Fn,{size:13,className:"mt-0.5 shrink-0"}),l("“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.")]}),c&&t("p",{className:"text-[0.7rem] text-red-600 dark:text-red-300",children:c}),e("div",{ref:b,className:"flex items-center justify-between gap-2",children:[t("span",{className:"text-[0.7rem] chat-text-muted-500/40",children:n.length>1?A(l,"{decided}/{total} decided",{decided:v,total:n.length}):""}),t("button",{type:"button",disabled:!w||f,onClick:()=>g(n.map(e=>d[e.toolCallId])),className:`${xo} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:l(f?"Sending…":"Confirm")})]})]})},Co=({src:n,alt:r,onClose:o,t:c})=>{const l=s(null),d=s(null),[u,p]=a(null);return i(()=>{p(_(l.current))},[]),i(()=>{const e=e=>{"Escape"===e.key&&o()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return d.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]),t("span",{ref:l,className:"hidden",children:u&&b(e("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4",onClick:o,role:"dialog","aria-modal":"true","aria-label":c("Image preview"),children:[t("button",{ref:d,type:"button",onClick:o,"aria-label":c("Close"),className:"absolute top-4 right-4 rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(er,{size:20})}),t("img",{src:n,alt:r,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},So=({src:r,alt:o,requestHeaders:s,maxHeightClass:c="max-h-[400px]",t:l})=>{const d=!!s&&Object.keys(s).length>0&&(e=>!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(r),[u,p]=a(null),[h,m]=a(!1),[f,g]=a(!1),v=Ut();i(()=>{if(!d)return;let e=!1,t=null;return v(r,{credentials:"include",headers:{...s}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(n=>{e||(t=URL.createObjectURL(n),p(t))}).catch(()=>{e||m(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,r,s]);const w=d?u:r;return h?t("p",{className:"my-2 text-[0.75rem] italic chat-text-muted-400/40",children:l("Image could not be loaded")}):w?e(n,{children:[e("span",{className:"group/img relative my-3 inline-block max-w-full rounded-lg border chat-border-200/10 p-1 transition-colors hover:border-[var(--chat-accent)]/40",children:[t("img",{src:w,alt:o,loading:"lazy",onClick:()=>g(!0),onError:()=>m(!0),className:`max-w-full cursor-zoom-in rounded-md object-contain ${c}`}),t("button",{type:"button",onClick:()=>g(!0),"aria-label":l("Expand image"),className:"absolute top-2 right-2 rounded-md bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100",children:t(br,{size:14})})]}),f&&t(Co,{src:w,alt:o,onClose:()=>g(!1),t:l})]}):e("span",{className:"my-3 inline-flex items-center gap-2 rounded-lg border chat-border-200/10 px-3 py-2",children:[t(vr,{size:14,className:"shrink-0 animate-pulse text-[var(--chat-accent)]"}),t("span",{className:"text-[0.7rem] chat-text-muted-500/40",children:l("Loading image…")})]})};const Io="inline-flex items-center gap-1.5 self-start rounded text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100",To=({t:n,enabled:r=!0,onPlay:o,playUrl:s,keepEndInView:c,messages:l,content:d})=>{const p=u(()=>l&&l.length>0?l:(e=>[e("Crunching the data"),e("Connecting the dots"),e("Consulting the sources"),e("Thinking it through"),e("Reticulating splines"),e("Analyzing the details"),e("Almost there"),e("Putting it together"),e("Polishing the answer"),e("Wrapping things up")])(n),[l,n]),h=function(){const[e,t]=a(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return i(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=()=>t(e.matches);return"function"==typeof e.addEventListener?(e.addEventListener("change",n),()=>e.removeEventListener("change",n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}(),[m,f]=a(0);if(i(()=>{r&&c()},[r,c]),i(()=>{if(!r||d)return;const e=window.setInterval(()=>f(e=>(e+1)%p.length),2600);return()=>window.clearInterval(e)},[r,p.length,!!d]),!r)return null;if(d)return t("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:d});const g=p[m%p.length];return e("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:g}),e("div",{className:"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5",style:h?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[e("span",{"aria-hidden":!0,className:"text-xs chat-text-muted-500/45",style:h?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[g,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(h?"":"animate-pulse")})]},g),o?e("button",{type:"button",onClick:o,className:Io,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(mr,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:Io,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(mr,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(sr,{size:11})})]}):null]})]})};function Ao(e,t){return e>1?A(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function _o(e,t){return e>1?A(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function Eo(e,t){return e>1?A(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function Mo(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:Jn,showDots:!1};switch(e.status){case"tool_start":{const n=e.tools??[],r=n.map(e=>e.toLowerCase());if(r.some(e=>"spawn_background_task"===e)){return{label:Ao(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:Dr,showDots:!1}}if(r.some(e=>"check_task_status"===e)){return{label:_o(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:_r,showDots:!1}}if(r.some(e=>"get_task_result"===e)){return{label:Eo(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:_r,showDots:!1}}let o,a=Pr;if(r.some(e=>e.includes("search")||e.includes("list"))?a=Ir:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?a=nr:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?a=yr:r.some(e=>e.includes("code")||e.includes("execute"))?a=Mr:r.some(e=>e.includes("web")||e.includes("browse"))&&(a=fr),n.length>0){const e=n.map(e=>e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())),r=Array.from(new Set(e));o=1===r.length?`${r[0]}…`:A(t,"{tool} (+{count} more)…",{tool:r[0],count:r.length-1})}else o=t("Using tools…");return{label:o,StatusIcon:a,showDots:!1}}case"awaiting_approval":return{label:t("Waiting for your approval…"),StatusIcon:Fn,showDots:!1};case"cancelling":return{label:t("Stopping…"),StatusIcon:Jn,showDots:!0};case"reconnecting":return{label:t("Reconnecting…"),StatusIcon:Jn,showDots:!0};case"wait_start":return{label:e.waitReason||t("Waiting before continuing…"),StatusIcon:_r,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:_r,showDots:!0};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:_r,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:_r,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:Jn,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Consulting {agent}…",{agent:n}),StatusIcon:Dr,showDots:!1}}case"delegating":return{label:Ao(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:Dr,showDots:!1};case"polling":return{label:_o(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:_r,showDots:!1};case"collecting":return{label:Eo(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:_r,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Transferring to {agent}…",{agent:n}),StatusIcon:sr,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:Jn,showDots:!1}}}function Lo(e,t,n){return e&&n?.(e)||Mo(e,t).label}function Ro(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/#{1,6}\s+/g,"").replace(/^[ \t]*[-*>]+[ \t]*/gm,"").replace(/[ \t]+/g," ").replace(/\n{3,}/g,"\n\n").trim()}function $o({text:e}){const n=s(null),[r,o]=a(!1);return i(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight,o(e.scrollHeight>e.clientHeight+1))},[e]),t("div",{className:"filigran-chat-reasoning ml-11 mt-2.5 max-w-[75%] rounded-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3",children:t("div",{ref:n,className:"max-h-40 overflow-hidden"+(r?" [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)] [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]":""),children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-xs leading-5 chat-text-secondary-500/45",children:e})})})}function Do(e){const t=Math.floor(e);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function zo(e,t,n=0){const[r,o]=a(null);return i(()=>{if(o(null),!e)return;const r=window.setTimeout(()=>o(n),t);return()=>window.clearTimeout(r)},[e,t,n]),e&&r===n}const jo=({agentStatus:r,logoIcon:o,t:s,miniGameEnabled:c=!0,onPlayWaitingGame:l,waitingGameUrl:d,keepEndInView:p,onSkipWait:h,statusLabel:m,waitingMessages:f,renderWaitingPanel:g})=>{const v=Mo(r,s),{StatusIcon:w,showDots:y}=v,b=Lo(r,s,m),x=r?.thinkingContent,k=r?.elapsedStartMs,N="wait_start"===r?.status?r.waitStartMs:void 0,C=k??N,[S,I]=a(()=>Date.now());i(()=>{if(null==C)return;I(Date.now());const e=window.setInterval(()=>I(Date.now()),1e3);return()=>window.clearInterval(e)},[C]);const T=r?.waitSeconds,A=null!=N&&null!=T?Math.max(0,T-(S-N)/1e3):void 0,_=null!=k?Math.max(0,(S-k)/1e3):r?.elapsedS,E="number"==typeof _&&_>=15,M=u(()=>function(e){if(e.length<=6e3)return Ro(e);const t=[];let n=0;for(let r=e.indexOf("```");-1!==r;r=e.indexOf("```",n)){const o=e.indexOf("```",r+3);if(-1===o)break;t.push([n,r]),n=o+3}t.push([n,e.length]);const r=[];let o=6e3;for(let n=t.length-1;n>=0&&o>0;n--){const[a,s]=t[n],i=Math.max(a,s-o);r.push(e.slice(i,s)),o-=s-i+1}let a=r.reverse().join(" ");if(o<=0){const e=a.indexOf("\n\n");-1!==e&&e<a.length/2&&(a=a.slice(e+2))}return Ro(a)}(x??""),[x]),L=M.length>=3,R=zo(c&&!L,5e3),$=zo(c&&L,1e4,x?.length??0),D=L?$:R;return e(n,{children:[e("div",{className:"flex gap-3 items-center justify-start",children:[t("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:o})}),e("div",{className:"filigran-chat-active-border rounded-lg chat-surface-subtle-50/3 px-4 py-3 relative overflow-hidden",children:[t("div",{className:"absolute inset-0 bg-gradient-to-r from-[var(--chat-accent)]/[0.03] via-transparent to-[var(--chat-accent)]/[0.03] animate-pulse pointer-events-none"}),e("div",{className:"relative flex items-center gap-2.5",children:[y?t("div",{className:"flex gap-[3px] items-center h-3.5 w-3.5 justify-center",children:[0,.15,.3].map((e,n)=>t("span",{className:"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50",style:{animation:`chat-dot 1s ease-in-out infinite ${e}s`}},n))}):t(w,{size:14,className:"text-[var(--chat-accent)] animate-pulse transition-all duration-300"}),t("span",{className:"text-sm chat-text-secondary-500/50 transition-all duration-300",children:b}),void 0!==A?t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:Do(Math.ceil(A))}):E&&t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:Do(_)}),"wait_start"===r?.status&&h&&t("button",{type:"button",onClick:h,className:"ml-1 shrink-0 rounded-md border border-[var(--chat-accent)]/40 px-2 py-0.5 text-xs text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors",children:s("Continue now")})]})]})]}),D?t(To,{t:s,enabled:c,onPlay:l,playUrl:d,keepEndInView:p,messages:f,content:g?.()}):L?t($o,{text:M}):null]})};class Oo extends h{state={failed:!1,resetKey:this.props.resetKey};static getDerivedStateFromError(){return{failed:!0}}static getDerivedStateFromProps(e,t){return e.resetKey===t.resetKey?null:{failed:!1,resetKey:e.resetKey}}componentDidCatch(e,t){console.error(`${this.props.label} failed to render`,e,t.componentStack)}render(){return this.state.failed?this.props.fallback:this.props.children}}function Po({draw:e}){return t(n,{children:e()})}function Uo({t:e}){return t("p",{className:"pl-1 text-[0.75rem] italic chat-text-muted-400/40",children:e("This item could not be loaded.")})}const Ho=y().use(w).use(v).freeze();function Wo(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(Wo);default:return!1}}function qo(e,t){return e.lastIndexOf("\n",t-1)+1}function Bo(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(qo(e,t-1),t-1).trim()}function Fo(e,t,n){const r=e.slice(t,n).split("\n");for(let e=r.length-1;e>=0;e--)if(r[e].trim())return/^(?: {4}|\t)/.test(r[e]);return!1}class Vo{last=null;split(e){return this.last?.source!==e&&(this.last=function(e,t){if(!e.trim())return function(e){return{source:e,blocks:e?[e]:[],starts:e?[0]:[],settled:0,firstDefinition:-1}}(e);const n=t&&t.settled>0&&e.startsWith(t.source)?t.settled:0,r=n?t.starts[n]:0,o=e.slice(r),a=t&&n?t.starts.slice(0,n):[];let s=t&&n&&t.firstDefinition<n?t.firstDefinition:-1;a.push(r);for(const t of Ho.parse(o).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+qo(o,n),s=a[a.length-1];t>s&&!Fo(e,s,t)&&a.push(t)}s<0&&Wo(t)&&(s=a.length-1)}let i=n;for(let t=a.length-1;t>n;t--)if(Bo(e,a[t])){i=t;break}const c=s<0?a.map((t,n)=>e.slice(t,a[n+1]??e.length)):[e];return{source:e,blocks:c,starts:a,settled:i,firstDefinition:s}}(e,this.last)),this.last.blocks}}const Ko=r({copiedBlock:null,onCopyCode:()=>{},streaming:!1,t:T});function Go({draw:e,block:r}){const o=e();return null==o||!1===o?t(n,{children:r}):t("div",{className:"my-3",children:o})}const Jo={p:({children:e})=>t("p",{className:"mb-3 last:mb-0 leading-7 break-words chat-answer-text",children:e}),pre:({children:e})=>t(n,{children:e}),code:({className:n,children:r})=>{const{copiedBlock:a,onCopyCode:s,codeBlockRenderers:i,streaming:c,t:l}=o(Ko),d=/(?:^|\s)language-(\S+)/.exec(n||""),u=String(r).replace(/\n$/,""),p=d?i?.[d[1].toLowerCase()]:void 0;if(d||u.includes("\n")){const n=e("div",{className:"my-3 rounded-lg border chat-border-200/10 overflow-hidden chat-code-block",children:[e("div",{className:"flex items-center justify-between px-3 py-1.5 border-b chat-border-200/10 chat-surface-subtle-100/3",children:[t("span",{className:"text-[0.7rem] chat-text-muted-500/40 font-mono",children:d?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>s(u),"aria-label":l(a===u?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:chat-surface-hover-200/10 transition-colors",children:a===u?t(Xn,{size:14,className:"text-green-500"}):t(tr,{size:14,className:"chat-text-muted-400/40"})})]}),t("pre",{className:"m-0 px-3 py-2 overflow-x-auto",children:t("code",{className:"chat-code leading-[1.7] chat-text-800/90 whitespace-pre",children:u})})]});return p?t(Oo,{label:"A chat code block renderer",resetKey:`${u}\0${c}`,fallback:t(Uo,{t:l}),children:t(Go,{draw:()=>p(u,{streaming:c}),block:n})}):n}return t("code",{className:"chat-code-inline chat-code px-1.5 py-0.5 rounded-sm text-[var(--chat-accent)]",children:r})},ul:({children:e})=>t("ul",{className:"list-disc pl-5 mb-3 chat-answer-text [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),ol:({children:e})=>t("ol",{className:"list-decimal pl-5 mb-3 chat-answer-text [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),li:({children:e})=>t("li",{className:"leading-7 break-words",children:e}),strong:({children:e})=>t("strong",{className:"font-semibold chat-text-900/100",children:e}),em:({children:e})=>t("em",{className:"italic",children:e}),hr:()=>t("hr",{className:"my-4 chat-border-200/10"}),blockquote:({children:e})=>t("blockquote",{className:"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 rounded-r-md italic chat-text-secondary-500/60",children:e}),a:({href:e,children:n})=>{const{onRelativeLinkClick:r}=o(Ko),a=Ge(e),s=null!==a&&!!r,i=!(s||(e=>!!e&&!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e)&&null!==a);return t("a",{href:e,onClick:e=>{s&&(e.preventDefault(),r(a))},target:i?"_blank":void 0,rel:i?"noopener noreferrer":void 0,className:"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125",children:n})},img:({src:e,alt:n})=>{const{requestHeaders:r,t:a}=o(Ko);return"string"==typeof e&&e?t(So,{src:e,alt:n||"",requestHeaders:r,t:a},e):null},h1:({children:e})=>t("h1",{className:"mt-4 first:mt-0 mb-2 font-bold chat-answer-heading-1 chat-text-900/100",children:e}),h2:({children:e})=>t("h2",{className:"mt-3 first:mt-0 mb-2 font-bold chat-answer-heading-2 chat-text-900/100",children:e}),h3:({children:e})=>t("h3",{className:"mt-3 first:mt-0 mb-1.5 font-semibold chat-answer-heading-3 chat-text-900/100",children:e}),table:({children:e})=>t("div",{className:"my-3 overflow-x-auto rounded-lg border chat-border-200/10",children:t("table",{className:"w-full border-collapse text-xs",children:e})}),tr:({children:e})=>t("tr",{className:"transition-colors hover:chat-surface-hover-50/2",children:e}),th:({children:e})=>t("th",{className:"px-3 py-2 text-left font-semibold chat-surface-subtle-50/4 border-b chat-border-200/10 chat-text-900/100",children:e}),td:({children:e})=>t("td",{className:"px-3 py-2 border-b chat-border-200/10 chat-text-secondary-700/80",children:e})},Yo=[v,k],Xo=m(({source:e})=>t(x,{remarkPlugins:Yo,urlTransform:I,components:Jo,children:e}));Xo.displayName="MarkdownBody";const Zo=({source:e})=>{const[r]=a(()=>new Vo),o=u(()=>r.split(e),[r,e]);return t(n,{children:o.map((e,n)=>t(Xo,{source:e},n))})},Qo=m(({codeBlockRenderers:e,...n})=>{const{content:r,streaming:o=!1,onRelativeLinkClick:s,requestHeaders:i,t:l=T}=n,[d,p]=a(null),[h,m]=a(o);o&&!h&&m(!0);const f=u(()=>C(r),[r]),g=c(e=>{navigator.clipboard.writeText(e),p(e),setTimeout(()=>p(null),2e3)},[]),v=u(()=>({copiedBlock:d,onCopyCode:g,onRelativeLinkClick:s,requestHeaders:i,codeBlockRenderers:e,streaming:o,t:l}),[d,g,s,i,e,o,l]);return t(Ko.Provider,{value:v,children:t(h?Zo:Xo,{source:f})})});Qo.displayName="MarkdownMessage";function ea(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ta(e){return e.replace(/_/g," ")}const na=({entry:n,index:r,t:o})=>{const[s,i]=a(!1),c=u(()=>ea(n.input),[n.input]),l=u(()=>ea(n.output),[n.output]),d=!!c&&"{}"!==c;return e("div",{className:"border chat-border-200/6 rounded-md overflow-hidden",children:[e("button",{type:"button",onClick:()=>i(e=>!e),"aria-expanded":s,className:"w-full flex items-center gap-2.5 px-3 py-2 hover:chat-surface-hover-50/3 transition-colors text-left",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),n.success?t(Yn,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(Ur,{size:12,className:"shrink-0 text-red-500 dark:text-red-400"}),t("span",{className:"flex-1 min-w-0 text-[0.8125rem] chat-text-secondary-700/80 truncate font-mono",children:ta(n.name)}),t(Zn,{size:14,className:"shrink-0 chat-text-muted-400/50 transition-transform duration-200 "+(s?"rotate-180":"")})]}),s&&e("div",{className:"border-t chat-border-200/6",children:[d&&e("div",{className:"px-3 py-2 border-b chat-border-100/4 chat-detail-surface",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] chat-text-muted-500/40 uppercase tracking-wider font-medium",children:o("Input")}),t("pre",{className:"m-0 text-[0.7rem] chat-text-secondary-600/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable",children:c})]}),e("div",{className:"px-3 py-2 chat-detail-surface",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] chat-text-muted-500/40 uppercase tracking-wider font-medium",children:o("Output")}),t("pre",{className:"m-0 text-[0.7rem] chat-text-secondary-600/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable",children:l||o("(no output)")})]})]})]})},ra=({msg:n,onClose:r,t:o})=>{const c=s(null),l=s(null),d=s(null),[u,p]=a(null);i(()=>{p(_(c.current))},[]),i(()=>{const e=e=>{if("Escape"===e.key)return void r();if("Tab"!==e.key)return;const t=d.current;if(!t)return;const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const o=n[0],a=n[n.length-1],s=document.activeElement;e.shiftKey?s!==o&&t.contains(s)||(e.preventDefault(),a.focus()):s!==a&&t.contains(s)||(e.preventDefault(),o.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return l.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]);const h=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,m=n.toolNames??[],f=n.iterations??1,g=n.transferChain??[],v=n.toolCallTrace??[],w=(n.reasoning??"").trim(),y=[f>1?A(o,"{count} iterations",{count:f}):"",1===h?o("1 tool call"):A(o,"{count} tool calls",{count:h}),1===g.length?o("1 transfer"):g.length>1?A(o,"{count} transfers",{count:g.length}):""].filter(Boolean);return t("span",{ref:c,className:"hidden",children:u&&b(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:r,role:"presentation",children:e("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":o("Reasoning details"),onClick:e=>e.stopPropagation(),className:"w-full max-w-md max-h-full flex flex-col rounded-xl border chat-border-200/10 chat-surface-raised shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]",children:[e("div",{className:"px-4 pt-3.5 pb-2.5 border-b chat-border-200/10",children:[e("div",{className:"flex items-center gap-2",children:[t(Pr,{size:15,className:"text-[var(--chat-accent)]"}),t("span",{className:"flex-1 text-[0.875rem] font-semibold chat-text-900/100",children:o("Reasoning details")}),t("button",{ref:l,type:"button",onClick:r,"aria-label":o("Close"),className:"w-7 h-7 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(er,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] chat-text-muted-500/40",children:y.join(" · ")})]}),e("div",{className:"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3",children:[n.isTruncated&&e("div",{className:"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90",children:[t(Fn,{size:14,className:"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400"}),e("span",{children:[t("span",{className:"font-semibold",children:o("Turn limit reached.")})," ",o("The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.")]})]}),w&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Jn,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium chat-text-secondary-500/50",children:o("Model reasoning")})]}),t("div",{className:"rounded-md border chat-border-200/6 chat-detail-surface px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable",children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 chat-text-secondary-500/45",children:Ro(w)})})]}),v.length>0?t("div",{className:"flex flex-col gap-1.5",children:v.map((e,n)=>t(na,{entry:e,index:n,t:o},`${e.name}-${n}`))}):m.length>0&&t("div",{children:m.map((n,r)=>e("div",{className:"flex items-center gap-3 py-2 border-b chat-border-100/4 last:border-0",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),t(Pr,{size:12,className:"shrink-0 chat-text-muted-400/50"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/80 truncate font-mono",children:ta(n)})]},`${n}-${r}`))}),g.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Vn,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium chat-text-secondary-500/50",children:o("Transfer chain")})]}),t("div",{className:"flex items-center gap-1.5 flex-wrap",children:g.map((n,r)=>e("div",{className:"flex items-center gap-1.5",children:[r>0&&t("span",{className:"chat-text-muted-300/30 text-[0.72rem]",children:"→"}),e("span",{className:"inline-flex items-center gap-1 rounded-md bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]",children:[t(Gn,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},oa=e=>e.parentElement,aa=e=>getComputedStyle(e).overflowY;function sa(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function ia(e){const t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return;const n=e.slice(t+1);return n.length<=8?n.toUpperCase():void 0}const ca=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const la="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",da="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",ua="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",pa=`opacity-0 ${la} ${ua}`,ha=`opacity-50 ${la} ${ua}`,ma="opacity-100 text-[var(--chat-accent)]",fa=({timestamp:n,locale:r})=>{const o=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:uo(t,(o=n,(r=e).getFullYear()===o.getFullYear()&&r.getMonth()===o.getMonth()&&r.getDate()===o.getDate()?"time":e.getFullYear()===n.getFullYear()?"date":"dateWithYear")).format(e),full:uo(t,"full").format(e),iso:e.toISOString()}:null;var r,o}(n,r);return o?t(Fr,{title:o.full,children:e("time",{dateTime:o.iso,className:"px-1 text-[0.65rem] tabular-nums chat-text-muted-400/40 select-none",children:[t("span",{"aria-hidden":"true",children:o.label}),t("span",{className:"sr-only",children:o.full})]})}):null},ga=({text:e,label:n,t:r})=>{const[o,s]=a(!1),i=o?r("Copied!"):n;return t(Fr,{title:i,children:t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),s(!0),setTimeout(()=>s(!1),2e3)}catch{}},"aria-label":i,className:`${da} ${o?"opacity-100 text-green-500 dark:text-green-400":pa}`,children:t(o?Xn:tr,{size:14})})})},va=({value:r,locked:o,pending:a,onChange:s,downRef:i,t:c})=>{const l=p(),d=o||a,u=(e,n)=>{const a=r===e;if(o&&!a)return null;const u="up"===e?Rr:Lr;return t(Fr,{title:o?c("Feedback already submitted"):n,children:t("button",{ref:"down"===e?i:void 0,type:"button",onClick:()=>{d||s(a?null:e)},"aria-label":n,"aria-pressed":a,"aria-disabled":d||void 0,"aria-describedby":o?l:void 0,className:`${da} ${a?ma:pa} ${d?"cursor-default":""}`,children:t(u,{size:14,filled:a})})})};return e(n,{children:[u("up",c("Good response")),u("down",c("Bad response")),o&&t("span",{id:l,className:"sr-only",children:c("Feedback already submitted")})]})},wa=({pending:n,onSave:r,onSkip:o,t:s})=>{const[i,c]=a(""),l=p(),d=!n&&!!i.trim();return e("div",{className:"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 rounded-lg border chat-border-200/10 chat-surface-subtle-50/4 p-2",children:[t("label",{htmlFor:l,className:"text-[0.7rem] chat-text-secondary-600/60",children:s("Tell us what went wrong (optional)")}),t("textarea",{id:l,autoFocus:!0,rows:2,maxLength:2e3,value:i,readOnly:n,onChange:e=>c(e.target.value),onKeyDown:e=>{"Escape"===e.key?(e.preventDefault(),e.stopPropagation(),n||o()):"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),d&&r(i))},placeholder:s("What could be improved?"),className:"w-full resize-y rounded-md border chat-border-200/10 chat-input-surface-white/0 px-2 py-1 text-[0.75rem] leading-5 chat-text-900/100 placeholder:chat-text-muted-400/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]"}),e("div",{className:"flex justify-end gap-1.5",children:[t("button",{type:"button",onClick:()=>{n||o()},"aria-disabled":n||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] chat-text-secondary-500/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:s("Skip")}),t("button",{type:"button",onClick:()=>{d&&r(i)},"aria-disabled":!d||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] "+(d?"hover:opacity-90":"opacity-50 cursor-default"),children:s("Save")})]})]})},ya=({speaking:e,onToggle:n,t:r})=>{const o=r(e?"Stop reading":"Read aloud");return t(Fr,{title:o,children:t("button",{type:"button",onClick:n,"aria-label":o,className:`${da} ${e?ma:pa}`,children:t(e?Or:jr,{size:14})})})},ba=[],xa=new Set(["PRESENTATION","REPORT","VIDEO"]),ka=m(({msg:r,isStreaming:o,agentName:i,logoIcon:c,onRelativeLinkClick:l,onDownloadFile:p,resolveAttachmentUrl:h,onDownloadArtifact:m,onRefreshArtifact:f,requestHeaders:g,feedbackMode:v,feedback:w,onRate:y,onSaveComment:b,onSkipComment:x,locale:k,canSpeak:N,isSpeaking:C,onToggleSpeech:S,openableConversationIds:I,onOpenConversation:T,markerRenderers:A,markerKindList:_=ba,codeBlockRenderers:E,transformMessageText:M,onArtifactOpen:L,renderMessageExtras:R,messageFooterActions:$,t:D})=>{const[z,H]=a(!1),W="assistant"===r.role,q=u(()=>$t(M,r.content,r)??r.content,[M,r]),B=u(()=>W?"":function(e){return e.trimEnd().replace(/^(?:[ \t]*\r?\n)+/,"")}(q),[W,q]),F=!q,V=s(null),K=!!w?.commentOpen,J=s(K);d(()=>{const e=J.current&&!K;J.current=K,!e||document.activeElement&&document.activeElement!==document.body||V.current?.focus()},[K]);const Y=(n,r)=>{const o=h&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&ca.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&ca.has(e.filename.slice(n+1).toLowerCase())}(n)?h(n):void 0;if(o)return t(So,{src:o,alt:n.filename,requestHeaders:g,maxHeightClass:"max-h-[200px]",t:D},r);const a="working_file"===n.fileTag,s=!(i=n.size)||i<=0?"":i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(0)} KB`:`${(i/1048576).toFixed(1)} MB`;var i;return e("button",{type:"button",onClick:()=>p?.(n),title:D("Download"),className:"group flex items-center gap-2 text-left rounded-lg border px-2.5 py-1.5 transition-colors cursor-pointer max-w-[90%] "+(a?"chat-border-200/10 bg-transparent":"chat-border-200/10 chat-surface-subtle-50/4 hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5"),children:[t("span",{className:"shrink-0 "+(a?"chat-text-muted-400/40":"text-[var(--chat-accent)]"),children:t(ir,{size:16})}),e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"truncate text-[0.75rem] chat-text-900/100",children:n.filename}),(n.type||s)&&t("span",{className:"text-[0.65rem] chat-text-muted-400/40 uppercase",children:[n.type,s].filter(Boolean).join(" · ")})]}),t("span",{className:"shrink-0 chat-text-muted-400/30 group-hover:text-[var(--chat-accent)]",children:t(or,{size:15})})]},r)},X=(n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border chat-border-200/10 text-[0.7rem] chat-text-secondary-600/60",children:[t(ir,{size:14}),n]},r),Z=(e,n)=>t(wo,{artifact:e,t:D,onDownload:m,onRefresh:f,onOpen:L},n),Q=(e,n,a)=>{const s=A?.[e];return!s||o&&!s.renderWhileStreaming?null:t("div",{className:s.fullWidth?"w-full":"w-full max-w-[90%]",children:t(Oo,{label:"A chat marker card",resetKey:`${n}\0${o}`,fallback:t(Uo,{t:D}),children:t(Po,{draw:()=>s.render(n,{message:r,streaming:o})})})},a)},ee=r.toolNames&&r.toolNames.length>0||!!(r.reasoning??"").trim()||r.toolCallTrace&&r.toolCallTrace.length>0||r.transferChain&&r.transferChain.length>0||r.isTruncated,te=W&&!F&&!o,ne=function(e,t=[]){if(!e)return e;const n=j(t),r=e.replace(n.complete,"").replace(n.partial,"");return r===e?e:r.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}(q,_),re=u(()=>te&&N?P(q,_):null,[te,N,q,_]),oe=(ae=w,se=r.feedback,ae?{value:ae.value,locked:!1}:se?{value:(ie=se.rating,"positive"===ie?"up":"down"),locked:!0}:{value:null,locked:!1});var ae,se,ie;const ce=so(r);return e("div",{"data-message-id":r.serverId??r.id,className:"group/msg flex flex-col "+(W?"items-start":"items-end"),children:[W&&e("div",{className:"flex items-center gap-1.5 mb-1",children:[t("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3",children:c})}),t("span",{className:"font-semibold text-xs chat-text-900/100",children:r.agentName??i})]}),!W&&((r.files?.length??0)>0||(r.attachments?.length??0)>0)&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end",children:(()=>{const e=[],t=new Set;return(r.files??[]).forEach((n,r)=>{!(!p||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(Y({fileId:n.fileId,filename:n.name,type:ia(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(X(n.name,`file-${r}`))}),(r.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(p?Y(n,`att-${n.fileId}-${r}`):X(n.filename,`att-${r}`)))}),e})()}),!W&&(r.conversationRefs?.length??0)>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end max-w-[90%]",children:r.conversationRefs.map((r,o)=>{const a=r.title||(r.key?`@${r.key}`:D("Untitled conversation")),s="inline-flex items-center gap-1 max-w-[240px] px-2 py-0.5 rounded-full border text-[0.7rem]",i=e(n,{children:[t(xr,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:a})]});return T&&I?.has(r.conversationId)?t(Fr,{title:D("Open conversation"),children:t("button",{type:"button",onClick:()=>T(r.conversationId),className:`${s} border-[var(--chat-accent-40)] text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]`,children:i})},`ref-${r.conversationId}-${o}`):t(Fr,{title:r.key?`@${r.key}`:"",children:t("span",{className:`${s} chat-border-200/10 chat-text-secondary-600/60`,children:i})},`ref-${r.conversationId}-${o}`)})}),W?e("div",{"data-testid":"filigran-chat-assistant-message",className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=O(q,o,_),n=new Map((r.attachments??[]).map(e=>[e.fileId,e])),a=new Map((r.artifacts??[]).map(e=>[U(e.kind,e.id),e])),s=new Set,i=new Set,c=[];return e.forEach((e,r)=>{if("text"===e.type)e.value.trim()&&c.push(t("div",{className:"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7",children:t(Qo,{content:e.value,streaming:o,onRelativeLinkClick:l,requestHeaders:g,codeBlockRenderers:E,t:D})},`t-${r}`));else if("marker"===e.type){"FILE"===e.kind?s.add(e.args):xa.has(e.kind)&&i.add(U(e.kind.toLowerCase(),e.args.split("#/")[0]));const t=Q(e.kind,e.args,`m-${e.kind}-${r}`);t&&c.push(t)}else if("artifact"===e.type){const t=U(e.kind,e.id),n=a.get(t);n&&!i.has(t)&&(i.add(t),c.push(Z(n,`a-${t}-${r}`)))}else if(p){const t=n.get(e.fileId);t&&(s.add(e.fileId),c.push(Y(t,`f-${e.fileId}-${r}`)))}}),(r.artifacts??[]).forEach(e=>{const t=U(e.kind,e.id);if(!i.has(t)){i.add(t);const n=e.kind.toUpperCase();if(A?.[n]){const r=Q(n,e.slideRef?`${e.id}#/${e.slideRef}`:e.id,`orphan-a-${t}`);r&&c.push(r)}else c.push(Z(e,`orphan-a-${t}`))}}),(r.attachments??[]).forEach(e=>{if(!s.has(e.fileId))if(A?.FILE){const t=Q("FILE",e.fileId,`orphan-${e.fileId}`);t&&c.push(t)}else p&&c.push(Y(e,`orphan-${e.fileId}`))}),0!==c.length||o||r.stopped||c.push(t("span",{className:"pl-1 text-[0.8125rem] chat-text-muted-400/40 italic",children:"..."},"empty")),c})(),r.stopped&&!o&&t("p",{className:"pl-1 text-[0.75rem] italic chat-text-muted-400/40",children:D("Stopped")}),!F&&o&&t("span",{className:"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse"})]}):t("div",{"data-testid":"filigran-chat-user-message",className:"max-w-[90%] chat-user-bubble leading-6 whitespace-pre-wrap break-words",children:B}),R&&t("div",{className:"w-full "+(W?"":"flex justify-end"),children:R(r,{streaming:o})}),!W&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 chat-text-muted-400/40",children:[!!B&&t(ga,{text:B,label:D("Copy message"),t:D}),!r.timestampUnknown&&t(fa,{timestamp:r.timestamp,locale:k})]}),te&&e("div",{className:"mt-0.5 flex flex-wrap items-center gap-0.5 chat-text-muted-400/40",children:[!r.timestampUnknown&&t(fa,{timestamp:r.timestamp,locale:k}),ee&&t(Fr,{title:r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),children:t("button",{type:"button",onClick:()=>H(e=>!e),className:`${da} ${r.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":ha}`,"aria-label":r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":z,children:r.isTruncated?t(Fn,{size:14}):t(wr,{size:14})})}),t(ga,{text:ne,label:D("Copy response"),t:D}),v&&t(va,{value:oe.value,locked:oe.locked,pending:!!w?.pending,onChange:e=>y(r,e,w),downRef:V,t:D}),re&&(le=re,le.some(e=>/[\p{L}\p{N}]/u.test(e.replace(G,""))))&&t(ya,{speaking:C,onToggle:()=>S(ce,re),t:D}),$?.(r,{streaming:o})]}),te&&w?.commentOpen&&t(wa,{pending:w.pending,onSave:e=>b(r,e,w),onSkip:()=>x(r,w),t:D}),te&&w?.error&&t("p",{role:"alert",className:"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400",children:w.error}),z&&t(ra,{msg:r,onClose:()=>H(!1),t:D})]});var le});ka.displayName="MessageRow";const Na=({messages:n,isLoading:r,agentStatus:o,agentName:p,logoIcon:h,onRelativeLinkClick:m,onDownloadFile:f,resolveAttachmentUrl:g,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,miniGameEnabled:b=!0,onPlayWaitingGame:x,waitingGameUrl:k,onMessageFeedback:N,isResumingAfterDecision:C,onSkipWait:S,pendingApprovals:I,onSubmitApprovalDecisions:T,isSubmittingApproval:A,approvalError:_,feedbackUrl:E,conversationId:M,locale:L,openableConversationIds:R,onOpenConversation:$,markerRenderers:D,markerKindList:z,codeBlockRenderers:j,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,transcriptFooter:W,onLoadEarlier:q,ttsRoute:B,thinking:F,t:V})=>{const G=s(null),[X,Z]=a(150),{entries:Q,rate:ee,saveComment:te,skipComment:ae}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o}){const i=Ut(),[d,u]=a(()=>({scope:t,entries:{}}));let p=d.entries;d.scope!==t&&(p={},u({scope:t,entries:p}));const h=s({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o});l(()=>{h.current={feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o}});const m=s(0),f=c((e,t)=>u(n=>({...n,entries:{...n.entries,[e]:t}})),[]),g=c((e,t,n)=>u(r=>{const o=r.entries[e];return o&&o.seq===t?{...r,entries:{...r.entries,[e]:n(o)}}:r}),[]),v=c(async(e,t,n)=>{const{feedbackUrl:r,conversationId:o,requestHeaders:a,onMessageFeedback:s,t:c}=h.current,l=so(e),d=++m.current;if(!r)return f(l,{seq:d,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void s?.(l,t,e);if(o&&e.serverId){if(f(l,{seq:d,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await se(i,r,o,e.serverId,t?{rating:ne(t),comment:null}:null,a)){const e=c(t?"Could not submit feedback.":"Could not retract feedback.");return void g(l,d,()=>n?{...n,seq:d,pending:!1,commentOpen:!1,error:e}:{seq:d,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}g(l,d,e=>({...e,pending:!1,commentOpen:"down"===t})),h.current.onMessageFeedback?.(l,t,e)}},[f,g]),w=c(async(e,t,n)=>{const{feedbackUrl:r,conversationId:o,requestHeaders:a,t:s}=h.current,c=so(e),l=oe(t);if(!(r&&o&&e.serverId&&l))return void f(c,{...n,commentOpen:!1,error:null});const d=++m.current;f(c,{...n,seq:d,pending:!0,error:null});const u=await se(i,r,o,e.serverId,{rating:"negative",comment:l},a);g(c,d,e=>u?{...e,comment:l,pending:!1,commentOpen:!1}:{...e,pending:!1,error:s("Could not submit feedback.")})},[f,g]);return{entries:p,rate:v,saveComment:w,skipComment:c((e,t)=>f(so(e),{...t,commentOpen:!1,error:null}),[f])}}({feedbackUrl:E,conversationId:M,requestHeaders:y,onMessageFeedback:N,t:V}),ie=function(e,t){const n=Ut(),[r]=a(io),o=r||!!t,[d,u]=a(null),p=s(null),h=s(e),m=s(t);l(()=>{h.current=e,m.current=t});const f=s(null),g=c(()=>{const e=f.current;e&&(f.current=null,e.abort.abort(),e.audio?.pause(),e.url&&URL.revokeObjectURL(e.url),u(t=>t===e.id?null:t))},[]),v=c(()=>r?(p.current??=function(e,t,n){let r=0,o=null;const a=e=>{e===r&&null!==o&&(r+=1,o=null,n(null))},s=()=>{null!==o&&(r+=1,o=null,e.cancel(),n(null))};return{speak:(i,c,l)=>{s();const d=c.filter(e=>e.trim());if(!d.length)return!1;const u=r;return o=i,n(i),d.forEach((n,o)=>{const s=o===d.length-1,i=t(n,{lang:l,onEnd:()=>{s&&a(u)},onError:()=>{u===r&&(a(u),e.cancel())}});e.speak(i)}),!0},stop:s,get speakingId(){return o}}}(window.speechSynthesis,(e,{lang:t,onEnd:n,onError:r})=>{const o=new SpeechSynthesisUtterance(e);return t&&(o.lang=t),o.onend=n,o.onerror=r,o},u),p.current):null,[r]),w=c((e,t)=>v()?.speak(e,J(t),h.current),[v]),y=c(async(e,t,r)=>{const o=new AbortController,a={id:t,abort:o};f.current=a,u(t);const s=J(r,4096),i=new Audio;a.audio=i;let c=0;try{for await(const t of Y(n,e,s,o.signal)){if(f.current!==a)return;if(!t)throw new Error("TTS failed");a.url&&URL.revokeObjectURL(a.url),a.url=URL.createObjectURL(t);const e=new Promise(e=>{i.onended=()=>e(!0),i.onerror=()=>e(!1)});if(i.src=a.url,await i.play(),!await e)throw new Error("TTS playback failed");if(f.current!==a)return;c+=1}g()}catch(e){if(f.current!==a||e instanceof DOMException&&"AbortError"===e.name)return;g(),w(t,s.slice(c).join(" "))}},[w,g]),b=c((e,t)=>{const n=f.current?.id??p.current?.speakingId??null;if(g(),p.current?.stop(),n===e)return;const r=K(t),o=m.current;o?y(o,e,r):w(e,r)},[w,y,g]),x=c(()=>{g(),p.current?.stop()},[g]);return i(()=>()=>x(),[x]),{supported:o,speakingId:d,toggle:b,stop:x}}(L,B),[ce]=a(()=>function(e,t=po){let n=!0,r=0,o=null;const a=e=>{e.scrollTo({top:e.scrollHeight,behavior:"instant"}),r=e.scrollTop},s=()=>{o&&(t.clear(o.timer),o=null)},i=()=>{s();const t=e();t&&n&&a(t)};return{get following(){return n},reveal:()=>{const a=e();if(!a)return;n=!0,s();const c=Math.max(0,a.scrollHeight-a.clientHeight);a.scrollTo({top:a.scrollHeight,behavior:"smooth"}),r=a.scrollTop,r>=c-1||(o={target:c,timer:t.set(i,1e3)})},keepUp:()=>{const t=e();t&&n&&!o&&a(t)},onScroll:()=>{const t=e();if(!t)return;const a=t.scrollTop,s=a<r-1,c=a>r+1;(s||c)&&(r=a);const l=t.scrollHeight-a-t.clientHeight;s?n=l<=1:c&&l<=100&&(n=!0),o&&(s||a>=o.target-1||l<=1)&&i()},leave:()=>{const t=e();!t||t.scrollTop<=0||(n=!1,s())}}}(()=>G.current));i(()=>{const e=G.current;return e?function(e,t,n=globalThis){const{ResizeObserver:r,MutationObserver:o}=n;if(!r)return()=>{};const a=new r(()=>t());for(const t of Array.from(e.children))a.observe(t);const s=o?new o(e=>{for(const t of e)for(const e of Array.from(t.addedNodes))1===e.nodeType&&a.observe(e)}):null;return s?.observe(e,{childList:!0}),()=>{a.disconnect(),s?.disconnect()}}(e,ce.keepUp):void 0},[ce]);const le=s(null),de=(e,t)=>{t instanceof Element&&e.contains(t)&&(function(e,t,n,r){for(let o=e;o&&o!==t;o=n(o))if(o.scrollTop>0&&o.scrollHeight>o.clientHeight&&fo.has(r(o)))return!0;return!1}(t,e,oa,aa)||ce.leave())},ue=n[0]?.id,pe=s(null),[he,me]=a(!1);d(()=>{const e=pe.current,t=e?n.findIndex(t=>t.id===e.firstId):-1;if(e&&t>0)return e.count=t,void Z(e.visible+e.count);Z(150)},[ue]),d(()=>{const e=pe.current;if(!e?.count||X!==e.visible+e.count)return;pe.current=null;const t=G.current;t&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))});let fe=0;for(const e of n)"user"===e.role&&(fe+=1);const ge=s(null);d(()=>{const e=ge.current;ge.current={firstMessageId:ue,userMessageCount:fe},pe.current?.count||(!e||e.firstMessageId!==ue||fe>e.userMessageCount?ce.reveal():ce.keepUp())},[n,ue,fe,ce]);const ve=o?.thinkingContent?.length??0;d(()=>{ve&&ce.keepUp()},[ve,ce]);const we=n.length>X,ye=u(()=>we?n.slice(n.length-X):n,[n,X,we]),{speakingId:be,stop:xe}=ie,ke=null===be||n.some(e=>so(e)===be),Ne=s({conversationId:M,userMessageCount:fe});i(()=>{const e=Ne.current;Ne.current={conversationId:M,userMessageCount:fe},(e.conversationId!==M||fe>e.userMessageCount||!ke)&&xe()},[M,fe,ke,xe]);let Ce=null;if(r)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){Ce=n[e].id;break}const Se=!!I?.length&&!!T;return e("div",{ref:G,role:"region","aria-label":V("Conversation transcript"),tabIndex:0,onScroll:ce.onScroll,onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&de(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(ho.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&sa(e.target)||de(e.currentTarget,e.target))},onPointerDown:e=>{const t=e.currentTarget,n=t.getBoundingClientRect();(function(e){if(1===e.button)return!e.onControl;if(0!==e.button||!e.onContainer||e.x<e.clientWidth)return!1;const t=(e.scrollTop+e.clientHeight)/e.scrollHeight*e.clientHeight;return e.y<=t})({button:e.button,onContainer:e.target===t,onControl:sa(e.target),x:e.clientX-n.left-t.clientLeft,y:e.clientY-n.top-t.clientTop,clientWidth:t.clientWidth,clientHeight:t.clientHeight,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight})&&de(t,e.target)},onTouchStart:e=>{le.current=mo(e.touches)},onTouchMove:e=>{const t=mo(e.touches),n=le.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&de(e.currentTarget,e.target),le.current=function(e,t){return null===t?null:null===e?t:Math.min(e,t)}(n,t)},"data-testid":"filigran-chat-transcript",className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]",children:[(we||q)&&t("div",{className:"flex justify-center",children:e("button",{type:"button",disabled:he,onClick:()=>{(async()=>{if(n.length>X)return void Z(e=>e+50);if(!q||he)return;const e=G.current;me(!0),pe.current={firstId:n[0]?.id,visible:Math.min(n.length,X),count:0,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0};try{0===await q()&&(pe.current=null)}finally{me(!1)}})()},className:"flex items-center gap-1.5 rounded-full border chat-border-200/10 px-3 py-1 text-[0.7rem] chat-text-secondary-500/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]",children:[t(Zn,{size:13,className:"rotate-180"}),V("Load earlier messages")]})}),ye.map(e=>{const n=e.id===Ce;return"assistant"===e.role&&!e.content&&n?Se?null:t("div",{children:t(jo,{agentStatus:o,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,onSkipWait:S,...F})},e.id):t(ka,{msg:e,isStreaming:n,agentName:p,logoIcon:h,onRelativeLinkClick:m,onDownloadFile:f,resolveAttachmentUrl:g,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,feedbackMode:"assistant"===e.role?re(e.serverId,E,M,!!N):null,feedback:Q[so(e)],onRate:ee,onSaveComment:te,onSkipComment:ae,locale:L,canSpeak:ie.supported,isSpeaking:be===so(e),onToggleSpeech:ie.toggle,openableConversationIds:e.conversationRefs?.length?R:void 0,onOpenConversation:e.conversationRefs?.length?$:void 0,markerRenderers:D,markerKindList:z,codeBlockRenderers:j,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,t:V},e.id)}),C&&!Se&&t(jo,{agentStatus:o,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,...F}),Se&&t(No,{proposals:I,onSubmit:T,isSubmitting:A,error:_,t:V},I.map(e=>e.toolCallId).join("|")),W,t("div",{})]})};function Ca(e){const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const Sa=({call:n,agentName:r,logoIcon:o,processingLabel:c,onInterrupt:l,onToggleMute:d,onEnd:u,t:p})=>{const[h,m]=a(0);i(()=>{const e=window.setInterval(()=>m(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);const f=s(null);i(()=>{f.current?.scrollIntoView?.({block:"end"})},[n.lines.length,n.heard]);const{phase:g,muted:v}=n,w="listening"===g?p(v?"Muted":"Listening..."):"processing"===g?c:"speaking"===g?p("Speaking…"):"error"===g?p("Failed to get a response. Resuming…"):"",y="speaking"===g||"processing"===g,b="speaking"===g||"listening"===g&&!v,x="w-12 h-12 rounded-full flex items-center justify-center border transition-colors disabled:opacity-40";return e("div",{role:"dialog","aria-label":p("Voice call"),"data-testid":"filigran-chat-voice-call",className:"absolute inset-0 z-40 flex flex-col rounded-[inherit] chat-surface-raised",children:[e("div",{className:"flex items-center justify-between px-4 py-3 text-[0.7rem] uppercase tracking-[1px] chat-text-secondary-500/50",children:[t("span",{children:p("Voice call")}),t("span",{className:"font-mono normal-case tracking-normal",children:Ca(h)})]}),e("div",{className:"flex flex-1 min-h-0 flex-col items-center justify-center gap-1 px-4",children:[e("button",{type:"button",onClick:y?l:void 0,disabled:!y,"aria-label":"speaking"===g?p("Skip response"):"processing"===g?p("Cancel question"):r,className:`relative mb-4 flex h-28 w-28 items-center justify-center rounded-full border-2 transition-colors ${"error"===g?"border-amber-400/50":b?"border-[var(--chat-accent)]":"border-[var(--chat-accent-40)]"} ${y?"cursor-pointer":"cursor-default"}`,children:[b&&t("span",{className:"absolute inset-0 rounded-full border border-[var(--chat-accent-40)] animate-ping","aria-hidden":"true"}),"processing"===g&&t("span",{className:"absolute inset-3 rounded-full border-2 border-dashed border-[var(--chat-accent-40)] animate-spin","aria-hidden":"true"}),t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-10 [&>svg]:h-10",children:o})]}),t("h2",{className:"max-w-full truncate text-base font-semibold chat-text-900/100",children:r}),t("p",{"aria-live":"polite",className:"text-center text-[0.8125rem] chat-text-secondary-500/60",children:w}),"speaking"===g&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:p("Speak or tap to interrupt")}),"processing"===g&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:p("Tap to cancel")}),"listening"===g&&n.heard&&e("p",{className:"mt-3 max-w-md text-center text-[0.8125rem] italic chat-text-secondary-500/50",children:["“",n.heard,"”"]})]}),n.lines.length>0&&t("div",{className:"max-h-[35%] overflow-y-auto filigran-chat-scrollable px-4 pb-2",children:e("div",{className:"flex flex-col gap-2",children:[n.lines.map((n,r)=>t("div",{className:"flex "+("user"===n.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[85%] rounded-lg px-3 py-1.5 text-[0.75rem] leading-5 "+("user"===n.role?"bg-[var(--chat-accent)]/10 chat-text-800/80":"chat-surface-subtle-100/6 chat-text-secondary-700/70"),children:[n.agent&&e("div",{className:"mb-0.5 text-[0.7rem] font-medium text-[var(--chat-accent)]",children:[n.agent.name,n.agent.failed&&e("span",{className:"font-normal chat-text-secondary-500/50",children:[" · ",p("Did not answer")]})]}),n.content.length>200?`${n.content.slice(0,200)}…`:n.content]})},r)),t("div",{ref:f})]})}),e("div",{className:"flex items-center justify-center gap-5 px-4 pb-5 pt-3",children:[t("button",{type:"button",onClick:d,"aria-label":p(v?"Unmute microphone":"Mute microphone"),"aria-pressed":v,className:`${x} ${v?"border-red-400/40 bg-red-500/10 text-red-500":"chat-border-200/10 chat-text-secondary-600/70 hover:chat-surface-hover-100/6"}`,children:t(v?Nr:kr,{size:20})}),t("button",{type:"button",onClick:u,"aria-label":p("End voice call"),className:"w-14 h-14 rounded-full flex items-center justify-center bg-red-500 text-white hover:bg-red-600 transition-colors",children:t(Sr,{size:22})}),t("button",{type:"button",onClick:l,disabled:"speaking"!==g,"aria-label":p("Skip response"),className:`${x} chat-border-200/10 chat-text-secondary-600/70 hover:chat-surface-hover-100/6`,children:t(Or,{size:20})})]})]})},Ia=({firstName:r,agentName:o,t:a})=>{if(!o)return t(n,{children:A(a,"How can I help you, {name}?",{name:r})});const{before:s,after:i,hasSlot:c}=function(e,t,n,r={}){const o=A(e,t,r),a=`{${n}}`,s=o.indexOf(a);return-1===s?{before:o,after:"",hasSlot:!1}:{before:o.slice(0,s),after:o.slice(s+a.length),hasSlot:!0}}(a,"How can {agent} help you, {name}?","agent",{name:r});return e(n,{children:[s,c&&t("span",{className:"text-[var(--chat-accent)]",children:o}),i]})},Ta=({firstName:n,logoIcon:r,promptSuggestions:o,onPromptClick:a,agentName:s,agentDescription:i,suggestionsLoading:c=!1,t:l})=>e("div",{className:"flex-1 flex flex-col items-center justify-center px-6 pb-8",children:[t("span",{className:"text-[var(--chat-accent)] mb-4 [&>svg]:w-12 [&>svg]:h-12 drop-shadow-[0_0_12px_var(--chat-accent-40)]",children:r}),t("h2",{className:"text-xl font-medium mb-1 text-center chat-text-900/100",style:{fontFamily:'"Geologica", sans-serif',animation:"chat-fade-in 0.35s ease-out"},children:t(Ia,{firstName:n,agentName:s,t:l})},s??"default"),i&&t("p",{className:"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 chat-text-secondary-500/40",children:i}),!i&&t("span",{className:"mb-5"}),(c||o.length>0)&&e("div",{className:"w-full max-w-[320px]",children:[t("span",{className:"block text-center mb-2 text-[0.65rem] tracking-[1.5px] uppercase text-[var(--chat-accent)] font-semibold",children:l("Suggestions")}),c?t("div",{"aria-hidden":!0,className:"space-y-1",children:[0,1,2].map(e=>t("div",{className:"h-8 rounded-lg border chat-border-200/10 chat-skeleton-card animate-pulse"},e))}):a&&o.map(e=>t("button",{type:"button",onClick:()=>a(e),className:"w-full text-left text-[0.8125rem] chat-text-800/100 py-1.5 px-3 mb-1 rounded-lg border chat-border-200/10 bg-transparent transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)]",children:e},e))]})]}),Aa="application/x-filigran-conversation";const _a="p-1 rounded-md chat-text-muted-400/30 hover:chat-icon-hover transition-colors disabled:opacity-40 disabled:pointer-events-none",Ea="text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",Ma=({conversations:r,loading:o,activeConversationId:c,collapsed:l,onToggleCollapsed:d,onSelect:p,onDelete:h,onRename:m,onNewChat:f,workspaces:g,storageKeyPrefix:v,rowActions:w,headerActions:y,sections:b,onClearAll:x,t:k})=>{const[N,C]=a(""),[S,I]=a(null),[T,A]=a(""),_=s(!1),E=At(v,St),[M,L]=a(()=>function(e){try{const t=JSON.parse(Et("local",e)??"[]");return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e):[])}catch{return new Set}}(E)),[R,$]=a(!1),[D,z]=a(null);i(()=>{if(!D)return;const e=setTimeout(()=>z(null),6e3);return()=>clearTimeout(e)},[D]);const j=(e,t)=>{_.current=!1,I(e),A(t)},O=()=>{if(_.current)return;_.current=!0;const e=S,t=T.trim();I(null),e&&t&&m?.(e,t)},P=()=>{_.current=!0,I(null)},U=(e,t)=>z(e||k(t)),H=async(e,t)=>{if(!g||function(e,t,n){const r=e.find(e=>e.conversationId===t);return!!r&&(r.workspaceId??null)===n}(r,e,t))return;const n=await g.onMove(e,t);null!==n&&U(n,"The conversation could not be moved")},W=N.trim().toLowerCase(),q=u(()=>W?e=>(e.title||"").toLowerCase().includes(W):void 0,[W]),B=u(()=>q?r.filter(q):r,[r,q]),F=u(()=>g?function(e,t,n={}){const{matches:r}=n,o=r?e.filter(r):e,a=new Set(t.map(e=>e.id)),s=new Set(e.map(e=>e.workspaceId).filter(e=>!!e)),i=new Map,c=[],l=[];for(const e of o){const t=e.workspaceId??null;t?a.has(t)?i.set(t,[...i.get(t)??[],e]):c.push(e):l.push(e)}const d=[];for(const e of ye(t)){const t=i.get(e.id)??[];(e.canManage||s.has(e.id))&&(r&&0===t.length||d.push({workspace:e,key:e.id,conversations:t}))}return c.length>0&&d.push({workspace:null,key:"__elsewhere__",conversations:c}),{groups:d,unfiled:l}}(r,g.list,{matches:q}):null,[r,g,q]),V=g?function(e){return ye(e.filter(e=>e.canManage))}(g.list):[],K=F?function(e){const{total:t,unfiled:n,loading:r,searching:o}=e;return n>0||r||o?null:0===t?"none":"all-filed"}({total:r.length,unfiled:F.unfiled.length,loading:o,searching:!!W}):null;if(l)return e("div",{className:"flex flex-col items-center gap-1 border-r chat-border-200/10 px-2 py-3 shrink-0",children:[t(Fr,{title:k("Show conversations"),children:t("button",{type:"button",onClick:d,"aria-label":k("Show conversations"),"aria-expanded":!1,className:"w-8 h-8 flex items-center justify-center rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(Ar,{size:17})})}),t(Fr,{title:k("New conversation"),children:t("button",{type:"button",onClick:()=>f(),"aria-label":k("New conversation"),className:"w-8 h-8 flex items-center justify-center rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(ar,{size:17})})})]});const G=e=>t(Da,{conversation:e,isActive:e.conversationId===c,isEditing:e.conversationId===S,draftTitle:T,onDraftTitleChange:A,onCommitRename:O,onCancelRename:P,onStartRename:m?j:void 0,onSelect:p,onDelete:h,fileable:g?V:void 0,onMove:H,actions:w,t:k},e.conversationId);return e("div",{className:"w-64 shrink-0 flex flex-col border-r chat-border-200/10",children:[e("div",{className:"flex items-center gap-1 px-3 py-3",children:[e("button",{type:"button",onClick:()=>f(),className:"flex-1 flex items-center gap-2 rounded-lg border chat-border-200/10 px-3 py-1.5 text-[0.8125rem] chat-text-secondary-700/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors",children:[t(ar,{size:15}),k("New conversation")]}),y,t(Fr,{title:k("Hide conversations"),children:t("button",{type:"button",onClick:d,"aria-label":k("Hide conversations"),"aria-expanded":!0,className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(Ar,{size:17})})})]}),r.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Ir,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 chat-text-muted-400/40"}),t("input",{type:"text",value:N,onChange:e=>C(e.target.value),onKeyDown:e=>{"Escape"===e.key&&C("")},placeholder:k("Search conversations..."),"aria-label":k("Search conversations..."),className:"w-full h-7 pl-7 pr-2 rounded-md chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable",children:[o&&0===r.length&&t("div",{className:"px-3 py-2",children:t(qr,{size:16})}),e(n,F&&g?{children:[!W&&e("div",{className:"flex items-center justify-between px-2 pb-1 pt-1",children:[t("span",{className:Ea,children:k("Workspaces")}),t(Fr,{title:k("New workspace"),children:t("button",{type:"button",onClick:()=>$(!0),"aria-label":k("New workspace"),className:_a,children:t(ur,{size:14})})})]}),R&&t(Ra,{placeholder:k("Workspace name"),onSubmit:async e=>{if($(!1),!e)return;const t=await g.onCreate(e);t.ok||U(t.error,"The workspace could not be created")},onCancel:()=>$(!1)}),F.groups.map(e=>t($a,{workspace:e.workspace,count:e.conversations.length,open:be(e.key,M,e,c,!!W),toggleable:xe(e,c,!!W),pending:!!e.workspace&&g.pendingWorkspaceId===e.workspace.id&&!c,onToggle:()=>{return t=e.key,void L(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Mt("local",E,JSON.stringify([...n])),n});var t},onNewChat:g.onNewChat,onRename:async(e,t)=>{const n=await g.onRename(e,t);n.ok||U(n.error,"The workspace could not be renamed")},onDelete:async e=>{const t=await g.onDelete(e);t.ok||U(t.error,"The workspace could not be deleted")},onDropConversation:t=>e.workspace&&void H(t,e.workspace.id),t:k,children:e.conversations.length>0?e.conversations.map(G):t("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:k("Drop a conversation here, or start one with +.")})},e.key)),e(La,{onDropConversation:e=>{H(e,null)},accepts:!0,children:[e("div",{className:"flex items-center justify-between px-2 pb-1 pt-3",children:[t("span",{className:Ea,children:k("Not in a workspace")}),t("span",{className:"text-[0.625rem] tabular-nums chat-text-muted-400/30",children:F.unfiled.length})]}),F.unfiled.map(G),K&&t("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:k("none"===K?"No conversations yet":"Every conversation is in a workspace.")})]}),W&&0===F.groups.length&&0===F.unfiled.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:k("No conversation matches")})]}:{children:[!o&&0===r.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:k("No conversations yet")}),r.length>0&&0===B.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:k("No conversation matches")}),B.map(G)]}),b,x&&r.length>0&&!W&&t(Hr,{onClear:x,className:"px-2 pt-3",iconButtonClass:_a,t:k})]}),D&&t("p",{role:"alert",className:"mx-3 mb-3 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[0.7rem] text-red-600 dark:text-red-400",children:D})]})},La=({onDropConversation:e,accepts:n,children:r,className:o=""})=>{const[i,c]=a(!1),l=s(0),d=e=>e.dataTransfer.types.includes(Aa);return t("div",{className:`rounded-lg transition-colors ${i?"bg-[var(--chat-accent)]/10 ring-1 ring-[var(--chat-accent)]/40":""} ${o}`,...n?{onDragEnter:e=>{d(e)&&(l.current+=1,c(!0))},onDragOver:e=>{d(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},onDragLeave:e=>{d(e)&&(l.current=Math.max(0,l.current-1),0===l.current&&c(!1))},onDrop:t=>{if(!d(t))return;t.preventDefault(),l.current=0,c(!1);const n=t.dataTransfer.getData(Aa);n&&e(n)}}:{},children:r})},Ra=({initial:e="",placeholder:n,onSubmit:r,onCancel:o})=>{const[c,l]=a(e),d=s(!1),u=s(null);i(()=>{u.current?.focus(),u.current?.select()},[]);const p=()=>{d.current||(d.current=!0,r(c.trim()))};return t("input",{ref:u,value:c,maxLength:200,onChange:e=>l(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&p(),"Escape"===e.key&&(d.current=!0,o())},onBlur:p,placeholder:n,"aria-label":n,className:"mx-2 mb-1 w-[calc(100%-1rem)] rounded-md chat-input-surface-white/10 px-2 py-1 text-[0.8125rem] chat-text-900/100 outline-hidden ring-1 ring-[var(--chat-accent)]"})},$a=({workspace:r,count:o,open:s,toggleable:i,pending:c,onToggle:l,onNewChat:d,onRename:u,onDelete:p,onDropConversation:h,t:m,children:f})=>{const[g,v]=a(!1),[w,y]=a(!1),b=!!r?.canManage,x=!!r&&r.isDefault&&r.isOwn;return e(La,{onDropConversation:h,accepts:b,className:"mb-0.5",children:[e("div",{className:"group/ws flex items-center gap-1 rounded-lg px-1.5 py-1 hover:chat-surface-hover-100/6",children:[g&&r?t(Ra,{initial:r.name,placeholder:m("Workspace name"),onSubmit:e=>{v(!1),e&&e!==r.name&&u(r.id,e)},onCancel:()=>v(!1)}):e("button",{type:"button",onClick:l,disabled:!i,"aria-expanded":s,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left disabled:cursor-default",children:[t(Qn,{size:12,className:"shrink-0 chat-text-muted-400/30 transition-transform "+(s?"rotate-90":"")}),t(lr,{size:14,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate text-[0.8125rem] font-medium chat-text-800/80",children:r?r.name:m("Other workspaces")}),x&&t("span",{className:"shrink-0 rounded bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] text-[var(--chat-accent)]",children:m("default")}),t("span",{className:"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums chat-text-muted-400/30",children:o})]}),r&&b&&!g&&t("span",{className:"flex shrink-0 items-center opacity-0 group-hover/ws:opacity-100 focus-within:opacity-100 transition-opacity",children:e(n,w?{children:[t("span",{className:"px-1 text-[0.65rem] text-red-600 dark:text-red-400",children:m("Delete?")}),t("button",{type:"button",onClick:()=>{y(!1),p(r.id)},"aria-label":m("Delete workspace"),className:`${_a} hover:text-red-500`,children:t(Xn,{size:13})}),t("button",{type:"button",onClick:()=>y(!1),"aria-label":m("Cancel"),className:_a,children:t(er,{size:13})})]}:{children:[t(Fr,{title:m("New conversation in this workspace"),children:t("button",{type:"button",onClick:()=>d(r.id),"aria-label":m("New conversation in this workspace"),className:_a,children:t(ar,{size:13})})}),t(Fr,{title:m("Rename workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":m("Rename workspace"),className:_a,children:t(Cr,{size:13})})}),!r.isDefault&&t(Fr,{title:m("Delete workspace"),children:t("button",{type:"button",onClick:()=>y(!0),"aria-label":m("Delete workspace"),className:`${_a} hover:text-red-500`,children:t($r,{size:13})})})]})})]}),s&&e("div",{className:"space-y-0.5 pb-1 pl-3",children:[c&&e("div",{className:"flex items-center gap-2 rounded-lg bg-[var(--chat-accent)]/10 px-2.5 py-1.5 text-[0.75rem] text-[var(--chat-accent)]",children:[t(ar,{size:12}),m("New conversation — send a message to start it")]}),f]})]})},Da=({conversation:r,isActive:o,isEditing:i,draftTitle:c,onDraftTitleChange:l,onCommitRename:d,onCancelRename:u,onStartRename:p,onSelect:h,onDelete:m,fileable:f,onMove:g,actions:v,t:w})=>{const[y,b]=a(!1),x=s(null),k=!!f&&!i;return e("div",{role:"button",tabIndex:0,"aria-current":o,draggable:k,onDragStart:k?e=>{e.dataTransfer.setData(Aa,r.conversationId),e.dataTransfer.effectAllowed="move"}:void 0,onClick:()=>h(r.conversationId),onKeyDown:e=>{e.target===e.currentTarget&&("Enter"!==e.key&&" "!==e.key||(e.preventDefault(),h(r.conversationId)))},className:"group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors "+(o?"bg-[var(--chat-accent)]/10":"hover:chat-surface-hover-100/6"),children:[t("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg "+(o?"bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]":"chat-surface-subtle-100/6 chat-text-muted-400/30"),children:t(Gn,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[i?t("input",{autoFocus:!0,value:c,onChange:e=>l(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&d(),"Escape"===e.key&&u()},onBlur:d,"aria-label":w("Conversation title"),className:"w-full rounded-md chat-input-surface-white/10 px-1.5 py-0.5 text-[0.8125rem] chat-text-900/100 outline-hidden ring-1 ring-[var(--chat-accent)]"}):t("span",{className:"block truncate text-[0.8125rem] "+(o?"chat-text-900/100":"chat-text-secondary-700/70"),children:r.title||w("Untitled conversation")}),(r.agentName||r.updatedAt)&&!i&&e("span",{className:"block text-[0.65rem] chat-text-muted-400/30 truncate",children:[r.agentName,r.agentName&&r.updatedAt?" · ":"",r.updatedAt?M(r.updatedAt,w):""]})]}),!i&&e("span",{className:"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[v&&t("span",{className:"flex",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:v(r)}),k&&e(n,{children:[t("button",{ref:x,type:"button",onClick:e=>{e.stopPropagation(),b(e=>!e)},"aria-label":w("Move to workspace"),title:w("Move to workspace"),"aria-expanded":y,className:"p-1 rounded-md chat-text-muted-400/30 hover:text-[var(--chat-accent)]",children:t(dr,{size:13})}),t(Wr,{open:y,onClose:()=>b(!1),anchorRef:x,placement:"bottom-end",width:220,children:e("div",{className:"py-1",onClick:e=>e.stopPropagation(),children:[t("p",{className:"px-3 pb-1 pt-1.5 text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",children:w("Move to workspace")}),f.map(n=>e("button",{type:"button",disabled:n.id===r.workspaceId,onClick:()=>{b(!1),g(r.conversationId,n.id)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] chat-text-secondary-700/80 hover:chat-surface-hover-100/10 disabled:opacity-40",children:[t(lr,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===r.workspaceId&&t(Xn,{size:12,className:"ml-auto shrink-0"})]},n.id)),t("div",{className:"my-1 h-px chat-border-fill-200/10"}),e("button",{type:"button",disabled:!r.workspaceId,onClick:()=>{b(!1),g(r.conversationId,null)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] chat-text-secondary-700/80 hover:chat-surface-hover-100/10 disabled:opacity-40",children:[t(er,{size:13,className:"shrink-0"}),w("Remove from workspace")]})]})})]}),p&&t("button",{type:"button",onClick:e=>{e.stopPropagation(),p(r.conversationId,r.title||"")},"aria-label":w("Rename conversation"),title:w("Rename conversation"),className:"p-1 rounded-md chat-text-muted-400/30 hover:text-[var(--chat-accent)]",children:t(ar,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),m(r.conversationId)},"aria-label":w("Delete conversation"),title:w("Delete conversation"),className:"p-1 rounded-md chat-text-muted-400/30 hover:text-red-500 dark:hover:text-red-400",children:t($r,{size:13})})]})]})},za=new Set([502,503,504]),ja=new Set([401,403]),Oa=f(function(e,n){const r=s(e.onSessionEnded);r.current=e.onSessionEnded;const o=s("");o.current=Ce(e.requestHeaders);const a=u(()=>{let e=null;const t=t=>{r.current&&e!==o.current&&(e=o.current,$t(r.current,t))};return{sessionEnded:t,fetch:(n=()=>r.current?t:void 0,async(e,t)=>{const r=await globalThis.fetch(e,t),o=401===r.status?n():void 0;return o&&"function"==typeof r.clone&&r.clone().json().then(e=>{const t=function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(!t||"object"!=typeof t)return null;const{code:n,reason:r}=t;return"session_expired"!==n?null:{reason:"string"==typeof r&&r?r:void 0}}(e);t&&o(t.reason)}).catch(()=>{}),r})};var n},[]);return t(Pt,{value:a,children:t(Pa,{...e,ref:n})})}),Pa=f(function({mode:n,onClose:r,onModeChange:d,topOffset:p=0,apiBaseUrl:h,apiEndpoints:m,agentDashboardUrl:f,waitingGameUrl:v,user:w,t:y,accentColor:b="#7b5cff",logoIcon:x,promptSuggestions:k,draftBorderColor:C,resizable:S=!1,onWidthChange:I,onResizeStart:T,onResizeEnd:A,disableFileManagement:_=!1,onRelativeLinkClick:E,onDownloadError:M,maxFileCount:L,maxTotalSize:R,requestHeaders:D,pageContext:z,pushContentSelector:j,backendType:O="rest",miniGameEnabled:U=!0,onPlayWaitingGame:H,notifyOnComplete:W=!0,onTaskComplete:q,onMessageFeedback:B,locale:F,disableImagePreviews:V=!1,contextUsageEnabled:G=!0,composerToolbar:Z,storageKeyPrefix:ee,conversationId:ne,onConversationChange:re,initialAgent:oe,onAgentChange:se,readOnly:ie=!1,readOnlyNotice:ce,getRequestExtras:le,onStreamEvent:de,markerRenderers:ue,codeBlockRenderers:pe,transformMessageText:me,onArtifactOpen:fe,headerActions:ge,banner:ve,composerHeader:ye,transcriptFooter:be,welcome:xe,renderMessageExtras:ke,messageFooterActions:Se,sidebarRowActions:Ie,sidebarHeaderActions:Ae,sidebarSections:_e,statusLabel:Ee,waitingMessages:Le,renderWaitingPanel:Re,fontFamily:$e,theme:De,onReady:ze,onBeforeSend:je,onHeldSendSettled:Oe,onTurnRunningChange:Pe,steerAttachments:He=!1,holdSendsDuringTurn:qe=!1,agentMentions:Be=!1,hideConversationList:Fe=!1},Ve){const Ke=Rn(m),Ge=Rn(D),Je=Rn(z),Ye=Rn(k),Xe=$n(E),Ze=$n(M),Qe=$n(H),et=$n(q),tt=$n(B),nt=$n(re),rt=$n(se),ot=$n(le),at=$n(je),st=$n(Oe),it=$n(de),ct=$n(Pe),lt=$n(fe),dt=s(null),{fetch:ut,sessionEnded:pt}=o(Ot),ht=u(()=>te(y,F),[y,F]),mt=Rn(Le),ft=u(()=>ue?Object.fromEntries(Object.entries(ue).map(([e,t])=>[e.toUpperCase(),t])):void 0,[ue]),gt=Rn(u(()=>pe?Object.fromEntries(Object.entries(pe).map(([e,t])=>[e.toLowerCase(),t])):void 0,[pe])),vt=Rn(u(()=>function(e){const t=new Set;for(const n of e??[]){const e=n.toUpperCase();$.test(e)&&t.add(e)}return[...t].sort()}(ft&&Object.keys(ft)),[ft])),wt=u(()=>({statusLabel:Ee,waitingMessages:mt,renderWaitingPanel:Re}),[Ee,mt,Re]),yt="fullscreen"===n||"inline"===n,[bt,xt]=a(!1),{agents:kt,agentsLoading:Nt,agentsError:St,agentsSettled:It,agentsDisabled:Tt,selectedAgent:_t,agentMenuOpen:Lt,setAgentMenuOpen:Rt,handleSwitchAgent:Dt,reloadAgents:zt}=Nn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge,storageKeyPrefix:ee,initialAgent:oe,onAgentChange:se?rt:void 0}),[jt,Pt]=a(null),Ht=s(null),[Wt,qt]=a(null),[Bt,Ft]=a(void 0),[Vt,Kt]=a(null),[Gt,Jt]=a(null),Yt=s(0),[Xt,Zt]=a(null),Qt=s(async()=>{}),en=s(()=>{}),tn=c((e,t)=>{$t(en.current,e,t.relayed),$t(it,e,t)},[it]),{messages:an,inputValue:sn,setInputValue:cn,isLoading:ln,turnRunning:dn,sendsHeld:un,turnEnd:pn,agentStatus:hn,attachedFiles:mn,conversationId:fn,contextUsage:gn,transferredAgent:vn,canSteer:wn,pendingApprovals:yn,isSubmittingApproval:bn,approvalError:In,submitApprovalDecisions:Tn,isResumingAfterDecision:An,historyReloadNonce:_n,reloadHistory:Dn,mergeTurnHistory:jn,settleUnseenEnd:On,historyLoadedRef:Pn,conversationIdRef:Un,handleFileAdd:Wn,handlePaste:Vn,handleSendMessage:Kn,skipWait:Gn,readPendingApprovals:Jn,heldMessage:Yn,notice:Xn,cancelHeldMessage:Zn,agentMentions:Qn,addAgentMention:er,handleNewChat:tr,pendingWorkspaceId:nr,clearPendingWorkspace:or,handleStopGenerating:ar,conversationRefs:sr,addConversationRef:ir,setAttachedFiles:cr,setMessages:lr,setContextUsage:dr,updateConversationId:ur,handleSwitchConversation:pr}=xn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,agentSlug:_t?.slug,requestHeaders:Ge,pageContext:Je,onRelativeLinkClick:E?Xe:void 0,t:ht,maxFileCount:L,maxTotalSize:R,storageKeyPrefix:ee,controlledConversationId:ne,onConversationIdChange:re?nt:void 0,getRequestExtras:le?ot:void 0,onStreamEvent:tn,onSessionEnded:pt,onConversationTitle:()=>{Qt.current()},historySettledFor:Wt,steerAttachments:He,holdSends:qe,agentMentionsEnabled:Be,onBeforeSend:je?at:void 0,onHeldSendSettled:Oe?st:void 0});Bt!==fn&&(Ft(fn),null!==Wt&&qt(null)),i(()=>{void 0!==ne&&ne!==Un.current&&(ne?pr(ne):tr())},[ne]);const{suggestions:hr,loading:mr}=Ln({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge,agentSlug:_t?.slug}),fr=u(()=>(hr??Ye)?.map(e=>ht(e))??(e=>[e("Help me create a new simulation scenario"),e("What are the latest attack patterns?"),e("How do I configure detection rules?"),e("Summarize my recent findings")])(ht),[hr,Ye,ht]),{prompts:gr,quota:vr,refreshQuota:wr}=Mn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge}),{historyEnabled:yr,conversations:br,conversationsLoading:xr,refreshConversations:kr,deleteConversation:Nr,renameConversation:Cr,moveConversation:Sr,clearConversations:Ir}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=Ut(),[s,i]=a([]),[l,d]=a(!1),u="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,p=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,h=c(async()=>{if(u){d(!0);try{const e=await o(p,{method:"GET",headers:{...r??{}}});if(!e.ok)return void i([]);const t=await e.json(),n=Array.isArray(t)?t:Array.isArray(t?.conversations)?t.conversations:[];i(n.map(Cn).filter(e=>null!==e))}catch{i([])}finally{d(!1)}}},[u,p,r]),m=c(async e=>{if(!u)return!1;try{return!!(await o(`${p}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...r??{}}})).ok&&(i(t=>t.filter(t=>t.conversationId!==e)),!0)}catch{return!1}},[u,p,r]),f=u&&t?.clearAll?`${e}${t.clearAll}`:null,g=c(async()=>{if(!f)return!1;try{return!!(await o(f,{method:"DELETE",headers:{...r??{}}})).ok&&(i([]),!0)}catch{return!1}},[f,r]),v=c(async(e,t)=>{const n=t.trim();if(!u||!n)return!1;const a=s;i(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{return!!(await o(`${p}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({title:n})})).ok||(i(a),!1)}catch{return i(a),!1}},[u,p,r,s]),w=c(async(e,t)=>{if(!u)return"";const n=s.find(t=>t.conversationId===e)?.workspaceId,a=()=>i(r=>function(e,t,n,r){const o=e.findIndex(e=>e.conversationId===t);if(o<0||(e[o].workspaceId??null)!==n)return e;const a=[...e];return a[o]={...e[o],workspaceId:r},a}(r,e,t,n));i(n=>n.map(n=>n.conversationId===e?{...n,workspaceId:t}:n));try{const n=await o(`${p}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({workspace_id:t})});return n.ok?null:(a(),await Ne(n)??"")}catch{return a(),""}},[u,p,r,s]);return{historyEnabled:u,conversations:s,conversationsLoading:l,refreshConversations:h,deleteConversation:m,renameConversation:v,moveConversation:w,clearConversations:f?g:null}}({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge});Qt.current=kr;const{workspacesEnabled:Tr,workspaces:Ar,refreshWorkspaces:_r,createWorkspace:Er,renameWorkspace:Mr,deleteWorkspace:Lr}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=Ut(),[i,l]=a([]),[d,u]=a(!1),p=s(0),h=t?.workspaces,m="rest"===n&&!t?.singleEndpoint&&"string"==typeof h&&h.length>0,f=m?`${e}${h}`:null,g=c(async()=>{if(!f)return;const e=++p.current;try{const n=await o(f,{method:"GET",headers:{...r??{}}});if(e!==p.current)return;if(!n.ok)return void(408===(t=n.status)||429===t||t>=500&&501!==t||(u(!1),l([])));const a=we(await n.json());if(e!==p.current)return;l(a),u(!0)}catch{}var t},[f,r]),v=c(async(e,t,n)=>{try{const a=await o(t,{method:e,headers:{...n?{"Content-Type":"application/json"}:{},...r??{}},...n?{body:JSON.stringify(n)}:{}});if(!a.ok)return{ok:!1,error:await Ne(a)};const s=204===a.status?[]:we([await a.json().catch(()=>null)]);return await g(),{ok:!0,workspace:s[0]}}catch{return{ok:!1,error:null}}},[r,g]),w=c(async e=>f?v("POST",f,{name:e.trim()}):{ok:!1,error:null},[f,v]),y=c(async(e,t)=>f?v("PATCH",`${f}/${encodeURIComponent(e)}`,{name:t.trim()}):{ok:!1,error:null},[f,v]),b=c(async e=>f?v("DELETE",`${f}/${encodeURIComponent(e)}`):{ok:!1,error:null},[f,v]);return{workspacesEnabled:m&&d,workspaces:i,refreshWorkspaces:g,createWorkspace:w,renameWorkspace:y,deleteWorkspace:b}}({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge});i(()=>{Tr&&nr&&!function(e,t){return t.some(t=>t.id===e&&t.canManage)}(nr,Ar)&&or(nr)},[Tr,Ar,nr,or]);const[Rr,$r]=a(!1),[Dr,zr]=a(!1),jr=yt&&yr&&!Fe;i(()=>{jr&&kr()},[jr,fn,kr]),i(()=>{jr&&_r()},[jr,fn,_r]);const Or=s(null);i(()=>{if(!jr)return;const e=()=>{if("visible"!==document.visibilityState)return;const e=Date.now();(function(e,t){return null===t||e-t>=2e3})(e,Or.current)&&(Or.current=e,kr(),_r())};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[jr,kr,_r]);const Pr=s(!1);i(()=>{Pr.current!==dn&&(Pr.current=dn,dn?$t(ct,!0):$t(ct,!1,{ended:pn??"stopped"}))},[dn,pn,ct]),i(()=>()=>{Pr.current&&(Pr.current=!1,$t(ct,!1,{ended:"stopped"}))},[ct]);const Ur=s(!1);i(()=>{Ur.current&&!dn&&(wr(),jr&&(kr(),_r())),Ur.current=dn},[dn,wr,jr,kr,_r]);const Hr=e=>{$r(!1),pr(e)},Wr=he(h,Ke,O),qr=u(()=>new Set(br.map(e=>e.conversationId)),[br]),Br=$n(yr?Hr:void 0),Fr=an.some(e=>(e.conversationRefs?.length??0)>0);i(()=>{Fr&&yr&&kr()},[Fr,yr,kr,fn]);const Vr=X(h,Ke,O,"messagesPage"),[Kr,Jr]=a(!1),Yr=X(h,Ke,O,"tts"),Xr=u(()=>Yr?{url:Yr,requestHeaders:Ge}:void 0,[Yr,Ge]),Zr=s(an);Zr.current=an,i(()=>Jr(!1),[fn]);const Qr=c(async()=>{const e=Un.current,t=Zr.current.find(e=>e.serverId)?.serverId;if(!Vr||!e||!t)return Jr(!1),0;try{const n=await ut(`${Vr}/${encodeURIComponent(e)}/messages?before=${encodeURIComponent(t)}&limit=50&supports_artifacts=true`,{headers:{...Ge??{}}});if(!n.ok||Un.current!==e)return 0;const r=await n.json();if(Un.current!==e)return 0;const o=new Set(Zr.current.map(e=>e.serverId).filter(Boolean)),a=We(r?.messages).filter(e=>!e.serverId||!o.has(e.serverId)).map(e=>({...e,id:Ue(e.serverId)}));return lr(e=>[...a,...e]),Jr(!0===r?.has_more&&a.length>0),a.length}catch{return 0}},[Vr,Un,Ge,lr]),eo=(e,t,n)=>{if(qt(e),Jr(!!Vr&&!0===t.has_more),!t.messages?.length)return;const r=We(t.messages);if(n)lr(e=>function(e,t){const n=[...e],r=new Map;n.forEach((e,t)=>{e.serverId&&r.set(e.serverId,t)});const o=new Set,a=new Map;let s=-1,i=!1;for(const e of t){let t=void 0!==e.serverId?r.get(e.serverId):void 0;if(void 0===t){const r=rn(e),a=n.findIndex((e,t)=>!o.has(t)&&!e.serverId&&nn(e)===r);a>=0&&(t=a,n[a]=on(n[a],e),i=!0)}if(void 0!==t){o.add(t),s=Math.max(s,t);continue}const c=a.get(s)??[];c.push({...e,id:Ue(e.serverId)}),a.set(s,c)}if(0===a.size)return i?n:e;const c=[...a.get(-1)??[]];return n.forEach((e,t)=>{c.push(e,...a.get(t)??[])}),c}(e,r));else{lr(r);for(let e=t.messages.length-1;e>=0;e-=1){const n=Te(t.messages[e]);if(n){dr(n);break}}}},to=s(ln);to.current=ln,i(()=>{Yt.current=0},[fn]),i(()=>{Vt&&!ln&&(Kt(null),Vt.conversationId===fn&&eo(Vt.conversationId,Vt.data,!0))},[Vt,ln,fn]),i(()=>{if(!Gt||Gt!==fn||ln)return;const e=()=>{to.current||(Jt(null),Yt.current+=1,Dn())},t=Math.min(6e4,5e3*2**Yt.current),n=window.setTimeout(e,t),r=()=>{"visible"===document.visibilityState&&e()};return window.addEventListener("online",e),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(n),window.removeEventListener("online",e),document.removeEventListener("visibilitychange",r)}},[Gt,fn,ln,Dn]);const no=Ce(Ge),ro=c(()=>{Zt(null),Dn()},[Dn]);i(()=>{Xt&&Xt.conversationId===fn&&!ln&&Xt.headersKey!==no&&ro()},[Xt,fn,ln,no,ro]);const oo=Xt&&Xt.conversationId===fn?Xt:null,so="rest"===O&&!Ke?.singleEndpoint&&null!==Ke?.sessions&&!!fn&&jt!==fn,io=!ie&&!_&&"rest"===O&&!Ke?.singleEndpoint&&null!==Ke?.upload,[co,lo]=a(!1),uo=s(0),po=e=>e.dataTransfer.types.includes("Files"),ho=io?{onDragEnter:e=>{po(e)&&(uo.current+=1,lo(!0))},onDragOver:e=>{po(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDragLeave:e=>{po(e)&&(uo.current=Math.max(0,uo.current-1),0===uo.current&&lo(!1))},onDrop:e=>{po(e)&&(e.preventDefault(),e.stopPropagation(),uo.current=0,lo(!1),Wn(e.dataTransfer.files))}}:{},mo=async()=>{await(Ir?.())&&tr()},fo=async e=>{await Nr(e)&&e===Un.current&&tr()},{sidebarWidth:go,handleResizeStart:vo,defaultWidth:wo,isResizing:yo}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:r,onResizeEnd:o,storageKeyPrefix:c}){const l=At(c,Ct),[d,u]=a(()=>{const e=Et("local",l);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=Sn)return t}return Sn}),[p,h]=a(!1),m=s(!1),f=s(d);f.current=d;const g=s(n);g.current=n;const v=s(o);return v.current=o,i(()=>{"sidebar"===e&&t&&g.current?.(f.current)},[e,t]),i(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!m.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,Sn),n);u(r),f.current=r,g.current?.(r)},r=()=>{m.current&&(m.current=!1,h(!1),document.body.style.cursor="",document.body.style.userSelect="",Mt("local",l,String(f.current)),v.current?.())},o=()=>{const e=.4*window.innerWidth;if(f.current>e){const t=Math.max(e,Sn);u(t),f.current=t,g.current?.(t)}};return document.addEventListener("mousemove",n),document.addEventListener("mouseup",r),window.addEventListener("resize",o),()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",r),window.removeEventListener("resize",o)}},[e,t,l]),{sidebarWidth:d,handleResizeStart:e=>{e.preventDefault(),m.current=!0,h(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",r?.()},defaultWidth:Sn,isResizing:p}}({mode:n,resizable:S,onWidthChange:I,onResizeStart:T,onResizeEnd:A,storageKeyPrefix:ee});i(()=>{const e="sidebar"===n?S?go:wo:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",yo?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),j){const e=document.querySelector(j);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=yo?"none":"padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)",()=>{e.style.paddingRight=n,e.style.transition=r,document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}}}return()=>{document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}},[j,n,go,wo,S,yo]);const bo=u(()=>x??t(rr,{size:24}),[x]),xo=u(()=>function(e,t){if(void 0!==t){const e=t.trim();return/^https?:\/\//i.test(e)||/^\/(?![/\\])/.test(e)?e:null}const n=e?.trim().replace(/\/+$/,"");return n&&/^https?:\/\//i.test(n)?`${n}/chat?arcade=play`:null}(f,v),[f,v]),ko=w.firstName,[No,Co]=a(null),So=vn?.name||No||_t?.name||ht("Assistant"),Io=c(()=>{const e=dt.current;return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);En({isLoading:dn,agentName:So,t:ht,enabled:W,onComplete:et,isViewingChat:Io});const To=null!=Ke?.download,Ao="rest"===O&&null!==Ke?.download&&(!Ke?.singleEndpoint||To),_o=c(e=>`${h}${Ke?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[h,Ke]),Eo=c(async e=>{const t=_o(e);try{const n=await ut(t,{method:"GET",credentials:"include",headers:{...Ge??{}}});if(!n.ok)throw new Error(`Download failed: ${n.status}`);const r=await n.blob(),o=URL.createObjectURL(r),a=document.createElement("a");a.href=o,a.download=e.filename||"download",document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(o)}catch(t){Ze?.(t,e)}},[_o,Ge,Ze]),Mo="rest"===O&&Ke?.artifacts?`${h}${Ke.artifacts}`:null,Ro=c((e,t)=>`${Mo}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,[Mo]),$o=c(async(e,t)=>{const n=`${e.title||e.kind}.${function(e){return"pptx_native"===e?"pptx":e}(t)}`;try{const r=await ut(`${Ro(e.kind,e.id)}/download`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...Ge??{}},body:JSON.stringify({format:t})});if(!r.ok)throw new Error(`Download failed: ${r.status}`);const o=await r.blob(),a=URL.createObjectURL(o),s=document.createElement("a");s.href=a,s.download=function(e){if(!e)return;const t=/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(e);if(t)try{return decodeURIComponent(t[1].trim().replace(/^"|"$/g,""))||void 0}catch{}const n=/filename\s*=\s*("([^"]*)"|[^;]+)/.exec(e);return(n?(n[2]??n[1]).trim():"")||void 0}(r.headers.get("content-disposition"))??n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(a)}catch(r){Ze?.(r,{fileId:e.id,filename:n,type:t.toUpperCase()})}},[Ro,Ge,Ze]),Do=c(async(e,t)=>{const n=await ut(Ro(e,t),{credentials:"include",headers:{...Ge??{}}});if(n.ok)return Me(await n.json())},[Ro,Ge]),zo={"--chat-accent":b,"--chat-accent-10":N(b,.1),"--chat-accent-40":N(b,.25),"--chat-accent-50":N(b,.5),"--chat-accent-dark":b,...$e?{fontFamily:$e}:{},...Q(De)},jo=s(jn);jo.current=jn;const Oo=s(On);Oo.current=On;const Po=s(!0);i(()=>(Po.current=!0,()=>{Po.current=!1}),[]),i(()=>{if(null===Ke?.sessions||Ke?.singleEndpoint||"legacy"===O||"ag-ui"===O)return;if(!fn)return Co(null),void Pt(null);if(Pn.current)return Ht.current!==fn&&jt!==fn&&Pt(fn),void(Ht.current!==fn&&Wt!==fn&&Vt?.conversationId!==fn&&qt(fn));if(!_t&&!Tt)return void(It&&jt!==fn&&Pt(fn));Pn.current=!0,Ht.current=fn,Pt(null);const e=`${h}${Ke?.sessions??"/chat/sessions"}`,t=fn,n=()=>!Po.current||Un.current!==t,r=Ce(Ge),o=_n;ut(e,{method:"POST",headers:{"Content-Type":"application/json",...Ge??{}},body:JSON.stringify({conversation_id:fn,agent_slug:_t?.slug,supports_artifacts:!0})}).then(e=>n()?null:e.ok?(Yt.current=0,Jt(null),Zt(null),e.json()):(Oo.current(o,null),ja.has(e.status)?Ne(e).then(e=>(n()||Zt({conversationId:t,detail:e,headersKey:r}),null)):(za.has(e.status)?Jt(t):ur(null),null))).then(e=>{if(!e||n())return;"string"==typeof e.conversation_id&&e.conversation_id&&e.conversation_id!==t&&ur(e.conversation_id),Co("string"==typeof e.agent_name?e.agent_name:null);const r=We(e.messages);Oo.current(o,r),jo.current(r)||(to.current?Kt({conversationId:t,data:e}):eo(t,e,!1))}).catch(()=>{n()||(Oo.current(o,null),Jt(t))}).finally(()=>{Ht.current===t&&(Ht.current=null),n()||Pt(t)})},[fn,_t,It,jt,Vr,h,Ke,O,Vt,_n,Pn,Un,Po,Ge,lr,dr,ur]);const Uo=s(Kn);Uo.current=Kn;const Ho=s(tr);Ho.current=tr;const Wo=s(pr);Wo.current=pr;const qo=s(kt);qo.current=kt;const Bo=s(_t);Bo.current=_t;const Fo=It&&!so,Vo=$n(ze),Ko=s(!1);i(()=>{Fo&&!Ko.current&&(Ko.current=!0,Vo?.())},[Fo,Vo]);const Go=s([]),[Jo,Yo]=a(0),Xo=(e,t)=>{Go.current.push({run:e,drop:t}),Yo(e=>e+1)};i(()=>{if(!Fo||0===Go.current.length)return;Go.current.shift().run(),Go.current.length>0&&Yo(e=>e+1)},[Fo,Jo]),i(()=>()=>{queueMicrotask(()=>{if(!Po.current)for(const e of Go.current.splice(0))e.drop?.()})},[]);const Zo=s(Dt);Zo.current=Dt;const Qo=s(ar);Qo.current=ar;const ea=s(ie);ea.current=ie;const ta=s(sn);ta.current=sn;const na=vn?.id??(No?kt.find(e=>e.name===No)?.id:void 0)??_t?.id??null,ra=function(e){const t=Ut(),n=s(e);l(()=>{n.current=e});const[r,o]=a(null),d=s(null),u=c(async(e,r)=>{const{tts:o,locale:a}=n.current,s=a||("undefined"!=typeof navigator?navigator.language:void 0),i=J(e,200),c=o?Y(t,o,i,r):null;for(const e of i){if(r.aborted)return;const t=c?(await c.next()).value??null:null;if(r.aborted)return;if(!t||!await qn(t,r)){if(r.aborted)return;await Bn(e,s,r)}}},[]),p=c(()=>{if(d.current)return!0;const e=zn();if(!e)return!1;const t=Hn({recognition:new e,lang:n.current.locale||("undefined"!=typeof navigator?navigator.language:void 0),send:(e,t)=>n.current.send(e,t),speak:u,speakable:e=>$t(n.current.speakable,e)??e,present:e=>$t(n.current.present,e)??e,probe:()=>{const e=n.current.readTurnState;return e?async function(e){try{const t=await e();return t?t.running?"running":"over":"unknown"}catch{return"unknown"}}(e):Promise.resolve("over")},stopTurn:()=>n.current.stopTurn(),addressedAgentId:()=>n.current.addressedAgentId(),onChange:e=>{d.current===t&&o(e)}});return d.current=t,t.start(),!0},[u]),h=c(()=>{const e=d.current;d.current=null,e?.end(),o(null)},[]);return i(()=>h,[h]),{snapshot:r,start:p,end:h,onFrame:c((e,t)=>d.current?.frame(e,t),[]),interrupt:c(()=>d.current?.interrupt(),[]),cancel:c(()=>d.current?.cancel(),[]),toggleMute:c(()=>d.current?.toggleMute(),[])}}({send:(e,t)=>Uo.current({text:e,source:"voice",onSent:t.onAccepted,onNotSent:t.onNotSent,onSteered:t.onSteered}),stopTurn:()=>Qo.current(),readTurnState:Jn?async()=>{const e=Un.current,t=e?await Jn(e):null;return t&&{running:t.turnRunning}}:void 0,addressedAgentId:()=>na,speakable:e=>K(P(e,vt)),present:e=>me?me(e,{id:"voice-call",role:"assistant",content:e,timestamp:new Date}):e,tts:Xr,locale:F});en.current=ra.onFrame;g(Ve,()=>({send:(e,t)=>ea.current?Promise.resolve("dropped"):new Promise(n=>Xo(()=>{ea.current?n("dropped"):Uo.current({text:e,extras:t?.extras,displayText:t?.displayText,onSent:()=>n("sent")}).then(n,()=>n("failed"))},()=>n("dropped"))),newConversation:e=>Xo(()=>{const t=kn(qo.current,e?.agent);t&&t.id!==Bo.current?.id&&Zo.current(t),Ho.current(e?.workspaceId)}),selectConversation:e=>Xo(()=>Wo.current(e)),setDraft:e=>{ta.current=e,cn(e)},getDraft:()=>ta.current,focusComposer:()=>dt.current?.querySelector("textarea")?.focus(),stop:()=>{ra.cancel(),Qo.current()},startVoiceCall:()=>!ea.current&&ra.start(),reloadAgents:zt,scrollToMessage:e=>{const t=[...dt.current?.querySelectorAll("[data-message-id]")??[]].find(t=>t.dataset.messageId===e);return!!t&&(t.scrollIntoView?.({block:"center",behavior:"smooth"}),t.classList.add("filigran-chat-highlight"),window.setTimeout(()=>t.classList.remove("filigran-chat-highlight"),2e3),!0)}}),[]);const oa=(()=>{const e="filigran-chatbot";switch(n){case"sidebar":return`${e} fixed right-0 bottom-0 flex flex-col chat-surface-raised border-l chat-border-200/10 z-[1200]`;case"floating":return`${e} fixed bottom-5 right-5 flex flex-col chat-surface-raised rounded-xl shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border chat-border-200/10`;case"fullscreen":return`${e} fixed right-0 bottom-0 left-0 flex flex-col chat-surface z-[1400]`;case"inline":return`${e} relative flex flex-col h-full w-full min-h-0 chat-surface`;default:return e}})(),aa={...zo,..."sidebar"===n?{top:p,width:S?go:wo}:"floating"===n?{width:380,height:560}:"inline"===n?{}:{top:p}};return e("div",{ref:dt,className:oa,style:aa,"data-testid":"filigran-chat-panel",children:["sidebar"===n&&S&&t("div",{onMouseDown:vo,className:"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group",children:t("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 rounded-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100"})}),t(Gr,{mode:n,agentName:So,agents:kt,agentsLoading:Nt,agentsError:St,selectedAgent:_t,transferredFrom:vn?_t?.name:void 0,agentMenuOpen:Lt,onAgentMenuToggle:()=>Rt(e=>!e),onAgentMenuClose:()=>Rt(!1),onSwitchAgent:e=>{e&&Dt(e,()=>{tr()})},modeMenuOpen:bt,onModeMenuToggle:()=>xt(e=>!e),onModeMenuClose:()=>xt(!1),onModeChange:d,onNewChat:tr,onClose:r,logoIcon:bo,actions:ge,agentDashboardUrl:f,historyEnabled:yr&&!jr,historyMenuOpen:Rr,onHistoryMenuToggle:()=>{const e=!Rr;e&&kr(),$r(e)},onHistoryMenuClose:()=>$r(!1),conversations:br,conversationsLoading:xr,activeConversationId:fn,onSelectConversation:Hr,onDeleteConversation:e=>{fo(e)},onClearAll:Ir?()=>{mo()}:void 0,t:ht}),e("div",{className:jr?"flex flex-1 min-h-0":"contents",children:[jr&&t(Ma,{conversations:br,loading:xr,activeConversationId:fn,collapsed:Dr,onToggleCollapsed:()=>zr(e=>!e),onSelect:Hr,onDelete:e=>{fo(e)},onRename:(e,t)=>{Cr(e,t)},onNewChat:tr,workspaces:Tr?{list:Ar,pendingWorkspaceId:nr,onCreate:Er,onRename:Mr,onDelete:async e=>{const t=await Lr(e);return t.ok&&(or(e),kr()),t},onMove:Sr,onNewChat:e=>{tr(e),_r()}}:void 0,storageKeyPrefix:ee,rowActions:Ie,headerActions:Ae,sections:_e,onClearAll:Ir?()=>{mo()}:void 0,t:ht}),e("div",{className:jr?"relative flex flex-1 flex-col min-w-0":"contents",...ho,children:[co&&t("div",{className:"pointer-events-none absolute inset-2 z-30 flex items-center justify-center rounded-xl border-2 border-dashed border-[var(--chat-accent)] bg-[var(--chat-accent)]/10 text-sm font-medium text-[var(--chat-accent)]",children:ht("Drop files to attach them")}),ve&&t("div",{className:"shrink-0",children:ve}),0===an.length&&so?t("div",{"data-testid":"filigran-chat-loading",className:"flex-1 flex flex-col gap-4 px-4 py-6","aria-busy":"true",children:[0,1,2].map(e=>t("div",{className:"flex "+(e%2?"justify-end":"justify-start"),children:t("div",{className:"h-10 rounded-xl chat-skeleton-fill animate-pulse "+(e%2?"w-1/3":"w-2/3")})},e))}):0===an.length&&oo?e("div",{"data-testid":"filigran-chat-restore-error",role:"alert",className:"flex-1 flex flex-col items-center justify-center gap-3 px-6 py-6 text-center",children:[t(Fn,{size:18,className:"text-amber-500 dark:text-amber-400"}),t("p",{className:"max-w-sm text-[0.8125rem] leading-6 chat-text-secondary-600/60",children:oo.detail??ht("This conversation could not be loaded.")}),t("button",{type:"button",onClick:ro,className:"rounded-md border chat-border-200/10 px-3 py-1 text-[0.75rem] font-medium chat-text-secondary-700/80 transition-colors hover:chat-surface-hover-100/6",children:ht("Retry")})]}):0===an.length?xe?t("div",{className:"flex-1 min-h-0 overflow-y-auto filigran-chat-scrollable",children:xe}):t(Ta,{firstName:ko,logoIcon:bo,promptSuggestions:fr,suggestionsLoading:mr,agentName:_t?.name,agentDescription:_t?.description,onPromptClick:ie?void 0:cn,t:ht}):t(Na,{messages:an,isLoading:ln,agentStatus:hn,agentName:So,logoIcon:bo,onRelativeLinkClick:Xe,onDownloadFile:Ao?Eo:void 0,resolveAttachmentUrl:Ao&&!V?_o:void 0,onDownloadArtifact:Mo?$o:void 0,onRefreshArtifact:Mo?Do:void 0,requestHeaders:Ge,miniGameEnabled:U,onPlayWaitingGame:Qe,waitingGameUrl:xo,onMessageFeedback:tt,feedbackUrl:ae(h,Ke,O),conversationId:fn,locale:F,isResumingAfterDecision:An,onSkipWait:Gn??void 0,pendingApprovals:yn,onSubmitApprovalDecisions:Tn,isSubmittingApproval:bn,approvalError:In,openableConversationIds:qr,onOpenConversation:Br,markerRenderers:ft,markerKindList:vt,codeBlockRenderers:gt,transformMessageText:me,onArtifactOpen:lt,renderMessageExtras:ke,messageFooterActions:Se,transcriptFooter:be,onLoadEarlier:Kr?Qr:void 0,ttsRoute:Xr,thinking:wt,t:ht}),ie?ce&&t("div",{className:"px-4 py-3 border-t chat-border-200/10 text-sm chat-text-secondary-500/50",children:ce}):t(ao,{header:ye,sendsHeld:un,steerAttachments:He,canHold:qe,heldMessage:Yn,notice:Xn,onCancelHeld:Zn,agentMentions:Be&&kt.length>0?{agents:kt,mentions:Qn,onPick:er}:void 0,inputValue:sn,onInputChange:cn,onSend:Kn,onStop:ar,isLoading:ln,canSteer:wn,attachedFiles:_?[]:mn,onFileAdd:_?void 0:Wn,onFileRemove:_?void 0:e=>cr(t=>t.filter((t,n)=>n!==e)),onPaste:_?void 0:Vn,t:ht,mode:n,separatorColor:C,prompts:gr,quota:vr,contextUsage:G?gn:null,composerToolbar:Z,conversationReferences:Wr?{url:Wr,requestHeaders:Ge,conversationId:fn,refs:sr,onPick:ir}:void 0})]})]}),ra.snapshot&&t(Sa,{call:ra.snapshot,agentName:So,logoIcon:bo,processingLabel:Lo(hn,ht,Ee),onInterrupt:ra.interrupt,onToggleMute:ra.toggleMute,onEnd:ra.end,t:ht})]})}),Ua=({isOpen:n,onToggle:r,label:o,accentColor:a="#7b5cff",icon:s,t:i,locale:c})=>{const l=u(()=>te(i,c),[i,c]),d=s??t(rr,{size:16});return e("button",{type:"button",onClick:r,className:"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap rounded-md border transition-colors",style:{borderColor:n?a:N(a,.5),color:a,backgroundColor:n?N(a,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=a,e.currentTarget.style.backgroundColor=N(a,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?a:N(a,.5),e.currentTarget.style.backgroundColor=n?N(a,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:d}),o??l("Ask Assistant")]})};export{Oa as ChatPanel,Ua as ChatToggleButton,Wn as voiceCallSupported};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|