@filigran/chatbot 3.16.1 → 3.18.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/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 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.replace(/\s+/g," ").trim()}](${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,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}}function E(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function M(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 L(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 R=["FILE","PRESENTATION","REPORT","VIDEO"],$=`(${R.join("|")}):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?`,D=/^[A-Z][A-Z0-9_]*$/;const z=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new Map;function O(e){const t=e.filter(e=>!R.includes(e)),n=t.join(","),r=j.get(n);if(r)return r;const o=[...R,...t].map(z).join("|"),a=t.length>0?`|(${t.map(z).join("|")}):([^\\]]+)`:"",s=[...R,...t].map(e=>`[[${e}:`),i={complete:new RegExp(`\\[\\[(?:${$}${a})\\]\\]`,"gi"),partial:new RegExp(`\\[\\[(?:${o})(?::[^\\]]*)?\\]?$`,"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 P(e,t=!1,n=[]){if(!e)return[];const r=O(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 U(e,t=[]){const n=[];for(const r of P(e,!1,t))"text"===r.type&&r.value.trim()&&n.push(C(r.value));return n}const H=(e,t)=>`${e}:${t.toLowerCase()}`;function W(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 q(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 B=y().use(w).use(v).freeze(),F=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function V(e){if(F.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(V).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function K(e,t){if(!F.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(V(e));case"tableRow":return void t.push((e.children??[]).map(V).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])K(n,t)}}function G(e){const t=[];for(const n of e)n.trim()&&K(B.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 J=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;function Y(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*X(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 Z(e,t,n,r){const o=t?.[r];return"rest"!==n||t?.singleEndpoint||"string"!=typeof o||!o?null:`${e}${o}`}const Q={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 ee(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(Q)){const o=e[n];"string"==typeof o&&o.trim()&&(t[r]=o)}return t}const te={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 {icon}.":"Suelte aquí una conversación o inicie una con {icon}.","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 {icon}.":"Déposez une conversation ici ou démarrez-en une avec {icon}.","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 {icon}.":"ここに会話をドロップするか、{icon} で新しく開始してください。","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 ne(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?te[n]:void 0}(t):void 0;return t=>{const r=e?.(t);return r&&r!==t?r:n?.[t]??t}}const re=e=>"up"===e?"positive":"negative";function oe(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function ae(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function se(e,t,n){return Z(e,t,n,"feedback")}async function ie(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:ae(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 ce=e=>void 0!==e&&/[\w-]/.test(e),le=/^[\w-]+$/;function de(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const o=r[1].toLowerCase();ce(e[r.index-1])||t.includes(o)||t.push(o),r=n.exec(e)}return t}function ue(e,t){if(0===e.length)return e;const n=new Set(de(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function pe(e,t){if(0===e.length)return[];const n=[];for(const r of de(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 he(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&&le.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 me(e,t,n){return Z(e,t,n,"conversationReferences")}const fe={query:null,items:[],failed:!1};function ge(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 ve(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 we(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function ye(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 be(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 xe(e,t,n,r,o){return!!o||(!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e))}function ke(e,t,n){return!n&&!(t&&e.conversations.some(e=>e.conversationId===t))}const Ne=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&t.length<=500?t:null};async function Ce(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 Ne(e.message)??Ne(e.detail)}return Ne(t)}(await e.json())}catch{return null}}function Se(e){return e?JSON.stringify(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0)):""}function Ie(){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 Te=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function Ae(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 Te){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 _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.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 Ee=["presentation","report","video"],Me=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function Le(e){if(!e||"object"!=typeof e)return;const t=e,n=Ee.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:Me(t.slide_count),sectionCount:Me(t.section_count),sceneCount:Me(t.scene_count),durationMs:Me(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:Me(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function Re(e){if(!Array.isArray(e))return;const t=e.map(Le).filter(e=>!!e);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.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 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.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 ze(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 je(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 Oe=e=>"string"==typeof e&&e?e:void 0;function Pe(e){if("string"==typeof e)return e?{agentName:e}:void 0;if(!e||"object"!=typeof e)return;const t=e,n={agentId:Oe(t.agent_id),agentName:Oe(t.agent_name)??Oe(t.name),agentIcon:Oe(t.agent_icon)};return n.agentId||n.agentName?Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)):void 0}function Ue(e,t){const n=e.type;if("error"===n||"cancelled"===n){const t=Oe(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:Oe(e.reason)};if("approval_resolved"===n)return{action:"approval_resolved"};if("folded_into_active_turn"===n)return{action:"folded",turnId:Oe(e.turn_id)};if("conversation_title"===n){const t=Oe(e.title);return t?{action:"conversation_title",conversationId:Oe(e.conversation_id),title:t}:{action:"noop"}}if("user_message"===n){const[t]=qe([e.message]);return t&&"user"===t.role?{action:"user_message",message:{...t,id:He(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:Oe(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=Ae(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=je(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:_e(e.attachments),artifacts:Re(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:$e(e.tool_call_trace),transferChain:ze(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:Ae(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0,intermediate:!0===e.intermediate||void 0,answeredBy:Pe(e.answered_by),mentionFailed:!0===e.mention_failed||void 0,raw:{...e}}:{action:"noop"}}function He(e,t=Ie()){return e?`msg-${e}`:t}function We(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 qe(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?Pe(r.answered_by):void 0,i="string"==typeof r.id&&r.id?r.id:void 0;t.push({id:He(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?We(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:_e(r.attachments),artifacts:"assistant"===r.role?Re(r.artifacts):void 0,conversationRefs:"user"===r.role?De(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:$e(r.tool_call_trace),transferChain:ze(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0,raw:{...r}})}),t}function Be(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 Fe(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 Ve(){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 Ke(e,t){return null!==e&&"function"==typeof t}function Ge(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const Je=(e,t)=>{const n=t??Ge();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 Ye(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const Xe=/^(current-password|new-password|one-time-code|cc-)/;function Ze(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 Qe(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 et(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=Je(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(Qe(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 tt(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 nt(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&&tt(r)}async function rt(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(nt(e))return{ok:!0};if(r){if(Ze(e),await(o=()=>nt(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&&!Ye(e.target)&&Array.from(e.addedNodes).some(e=>!Ye(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,()=>Ze(e)))return{ok:!0};var o,a;return n?.aborted?{ok:!1,error:"aborted"}:et(e,void 0,t)}const ot=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function at(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=Je(e.path,Ge(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const a=t.get(e.ref);return a&&a.isConnected?tt(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 rt(a,Ge(r??a.ownerDocument),o):"click"===e.type?et(a,n,Ge(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=>Xe.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=>ot.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&&Qe(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 st="[truncated]",it=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function ct(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(lt(t))return!0;return!1}function lt(e){const t=e.getAttribute("role");if(t&&it.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 dt(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function ut(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(xt(r)||wt(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?ut(r):` ${ut(r)} `}return n}function pt(e){return(e??"").replace(/\s+/g," ").trim()}const ht=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function mt(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=pt(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const o=pt(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=pt(Array.from(s.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||pt(s.textContent))return e||pt(s.textContent)}const i=e.tagName.toLowerCase(),c=(e.getAttribute("type")||"").toLowerCase();if("input"===i&&["submit","reset","button"].includes(c)){const t=pt(e.getAttribute("value"));if(t)return t;if("button"!==c)return"submit"===c?"Submit":"Reset"}const l=pt(e.getAttribute("alt"))||pt(e.querySelector("img[alt]")?.getAttribute("alt"));if(l)return l;const d=wt(e)?"":pt(ut(e));if(ht.has(t)&&d)return d;const u=pt(e.getAttribute("placeholder"));if(u)return u;const p=pt(e.getAttribute("title"));return p||d}function ft(e){return JSON.stringify(e.slice(0,80))}function gt(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 vt=/^(current-password|new-password|one-time-code|cc-)/;function wt(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>vt.test(e))}function yt(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(wt(e))return null;const n="value"in e?String(e.value??""):pt(ut(e));return n||null}function bt(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 xt(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 kt="filigranChatConversationId",Nt="filigranChatLegacyChatId",Ct="filigranChatAgentSlug",St="filigranChatSidebarWidth",It="filigran-chat-collapsed-workspaces",Tt="filigranChatDraft:",At="filigranChatDraftRefs:";function _t(e,t){return e?`${e}:${t}`:t}function Et(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch{return null}}function Mt(e,t){try{return Et(e)?.getItem(t)??null}catch{return null}}function Lt(e,t,n){try{const r=Et(e);if(!r)return;n?r.setItem(t,n):r.removeItem(t)}catch{}}class Rt extends Error{constructor(){super("the event stream fell silent"),this.name="SseStreamSilentError"}}async function $t(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 Rt;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 Dt(e,...t){if(e)try{return e(...t)}catch(e){return void console.error("A chat panel host callback threw",e)}}const zt=e=>e.some(e=>"error"===e.uploadStatus);function jt(e){if(e.slug&&/^[\w-]+$/.test(e.slug))return e.slug;return e.name.toLowerCase().replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")||null}function Ot(e,t){const n=[];for(const r of de(t))for(const t of e)t.key.toLowerCase()!==r||n.includes(t.agentId)||n.push(t.agentId);return n}const Pt=r({fetch:(e,t)=>globalThis.fetch(e,t),sessionEnded:()=>{}}),Ut=Pt.Provider;function Ht(){return o(Pt).fetch}const Wt=(e,t)=>_t(e,`${Tt}${t??"new"}`),qt=(e,t)=>_t(e,`${At}${t??"new"}`);function Bt(e,t){try{const n=JSON.parse(Mt("session",qt(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 Ft(e,t,n,r){Lt("session",Wt(e,t),n),Lt("session",qt(e,t),r.length>0?JSON.stringify(r):null)}function Vt(e,t){const n=Mt("session",Wt(e,t))??"";return{text:n,refs:ue(Bt(e,t),n)}}const Kt=9e5,Gt=Kt,Jt=new Set(["wait_status","tool_progress","consult_progress"]),Yt=new Set(["status","stream","done","approval_required","error","cancelled"]),Xt=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 Zt(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 Qt=["toolNames","toolCallCount","iterations","attachments","artifacts","reasoning","toolCallTrace","transferChain","isTruncated","agentName","answeredBy","mentionFailed","feedback"],en=Symbol("sentText");function tn(e,t){return t===e.content?e:{...e,[en]:t}}function nn(e){return e[en]??e.content}const rn=e=>`${e.role}\0${"user"===e.role?nn(e):e.content}`,on=e=>`${e.role}\0${e.content}`;function an(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 Qt)void 0!==t[e]&&(r[e]=t[e]);return n}function sn(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 cn=(e,t)=>[e,t].filter(Boolean).join("\n\n"),ln=(e,t)=>void 0!==e.displayText||void 0!==t.displayText?cn(e.displayText??e.text,t.displayText??t.text):void 0;function dn(e,t){const n=new Set(e.refs.map(e=>e.conversationId)),r=new Set(e.mentions.map(e=>e.agentId));return{text:cn(e.text,t.text),draft:cn(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:ln(e,t)}}const un={text:"",draft:"",files:[],refs:[],mentions:[]};function pn(e){return{...e.reduce(dn,un),parts:e}}function hn(e,t){return pn([...e?.parts??[],t])}function mn(e){for(const t of e)Dt(t.onNotSent)}function fn(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 gn(e){return"error"===e.action||"cancelled"===e.action||"done"===e.action&&!e.intermediate?e:null}function vn(e){return("error"===e.action||"cancelled"===e.action)&&!!e.provisional}function wn(e){const t=Dt(e);return t&&"object"==typeof t?t:{}}const yn=52428800;function bn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t].serverId;if(n)return n}return null}function xn(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 kn({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=Ht(),A="legacy"===n,[_,E]=a([]),[M,L]=a(!1),[R,$]=a(null),[D,z]=a(null),j=void 0!==f,O=_t(m,kt),P=_t(m,Nt),[U,H]=a(()=>j?f??null:Mt("local",O)),[W]=a(()=>Vt(m,U)),[q,B]=a(W.text),[F,V]=a(W.refs),[K,G]=a([]),[J,Y]=a([]),[X,Q]=a(null),[ee,te]=a(null),[ne,re]=a(null),[oe,ae]=a(!1),[se,ie]=a(null),[ce,le]=a(!1),[he,fe]=a(0),[ge,ve]=a(0),[we,ye]=a(()=>Mt("local",P)),be=s(!1),xe=s(null),ke=s(null),Ne=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),ze=s($e);ze.current=$e;const[Oe,Pe]=a(null),We=s(!1),qe=s(new Map),Ge=s(null),[Je,Xe]=a(!1),Ze=s(null),Qe=s(!1),et=s("off"),tt=s(0),nt=s(null),rt=s(null),ot=s(null),it=s(null),[ht,vt]=a(!1),wt=e=>{const t=it.current?.readBack;t&&e!==it.current&&window.clearTimeout(t.timer),it.current=e,vt(null!==e)},Ct=s(_);Ct.current=_;const St=s(0),[It,Tt]=a(()=>Ie()),At=s(null),Et=s(null),Rt=s(!1),jt=s(0),Pt=s(null),Ut=s(null),Wt=s(null),qt=()=>{null!==At.current&&window.clearTimeout(At.current),At.current=null,Et.current=null,Rt.current=!1,Wt.current&&window.clearTimeout(Wt.current.timer),Wt.current=null;const e=Ut.current;Ut.current=null,null!==e&&E(t=>t.filter(t=>t.id!==e||t.content))},Bt=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))},en=()=>{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 un=s(b);un.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||Pe(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(Ve),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:yn;i(()=>{V(e=>ue(e,q)),G(e=>function(e,t){if(0===e.length)return e;const n=new Set(de(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=()=>Z(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:je(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Jn=c(()=>{be.current=!1,St.current+=1,fe(St.current)},[]),Yn=()=>{if(null===Et.current)return;const e=bn(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!==At.current&&window.clearTimeout(At.current),Rt.current=!1,At.current=window.setTimeout(()=>{At.current=null,_e.current||Xn.current()},Math.max(0,jt.current-Date.now()))},Qn=()=>{null===Et.current||_e.current||Rt.current||(Rt.current=!0,null!==At.current&&window.clearTimeout(At.current),At.current=window.setTimeout(()=>{At.current=null,_e.current||Xn.current()},5e3))},er=s(Qn);er.current=Qn;const tr=()=>{null!==Et.current&&!_e.current&&Rt.current&&Zn()},nr=s(tr);nr.current=tr;const rr=()=>A||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,or=()=>Z(e,t,n,"cancel"),ar=()=>Z(e,t,n,"skipWait"),sr=Z(e,t,n,"events"),ir=!!sr,cr=Z(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||Lt("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:Ie()}));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(!Ke(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 at(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=>!Ye(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=pt(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(xt(t))continue;const e=lt(t),n=dt(t);let r=null;if(e){const n=`e${d.size+1}`,o=yt(t,e),i=gt(t);if(r=`[${n}] ${e} ${ft(mt(t,e))}${i.length?` (${i.join(", ")})`:""}${o?` = ${ft(o)}`:""}${bt(t)}`,l+r.length+1>a)return s=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${ft(pt(ut(t)))} (level ${n})`,l+r.length+1>a))return s=!0,!1;if(r&&(c.push(r),l+=r.length+1),(!e||ct(t))&&!u(t))return!1}return!0};return e.body&&!s&&u(e.body),s&&c.push(st),{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=Ie(),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&&Jt.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=>Zt(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=gn(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?Zt(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 Dt(ln.current,t,function(e,t){const n={relayed:e};if(!t)return n;const r=gn(t);return r&&vn(r)?n.end="provisional":r?.messageId&&(n.end="stored"),"status"===t.action&&t.resumed&&(n.replayed=!0),n}(r,o)),"session_ended"===o?.action&&Dt(dn.current,o.reason),o},Cr=e=>{switch(e.action){case"user_message":{const t=e.message,n=Me.current?.openAnswerId()??Ut.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||nn(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):sn(e,t,n)}),!0}case"conversation_title":return un.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!==it.current),h=Sn.current||null!==it.current,m=!a?.decided&&h&&kn.current?{text:i,source:d,extras:a?.extras,displayText:a?.displayText}:void 0,f=fn(i,a?.decided?void 0:Dt(kn.current,{text:i,source:d,turnRunning:h}),a?.displayText);if(!f)return"dropped";We.current=!1,Pe(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?me(e,t,n)?pe(F,q):[]:a?.refs??[],S=s?C?K:[]:a?.mentions??[],I=Ot(S,w);if(!w&&0===l.length)return"dropped";const _=()=>{s&&(B(""),V([]),G([]),Y([]))};if(Sn.current||p){if(zt(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=tn({id:Ie(),role:"user",content:a,timestamp:new Date,files:t.length>0?t:void 0},e),l=Me.current?.openAnswerId()??Ut.current;E(e=>sn(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 Ce(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=>hn(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,Pe(u("This message will be read with your next one."))),a?.onSteered?.(e.turnId,e.unanswered),"steered"):(e.detail&&Pe(e.detail),"failed")}return(N||p)&&e?(_(),De(e=>hn(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=tn({id:Ie(),role:"user",content:y,timestamp:new Date,files:l.length>0?[...l]:void 0,conversationRefs:x.length>0?x:void 0},w),R=Ie();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);Ne.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()?Ie():D.currentAssistantId();return E(t=>[...t.filter(t=>t.id!==e),{id:e,role:"assistant",content:"",timestamp:new Date}]),Ut.current=e,Et.current=Ae.current,Ae.current=null,Tt(Ie()),z(e=>"cancelling"===e?.status?e:{status:"reconnecting"}),jt.current=Date.now()+(Pt.current?Gt:15e3),Zn(),!0},ee=new AbortController;ke.current?.abort();const te=new AbortController,ne=()=>{X||(X=!0,D.deltas.close(),Ne.current===D.deltas&&(Ne.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??Ie(),runId:Ie(),messages:[{id:Ie(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={...Object.fromEntries(Object.entries(n.extras??{}).filter(([e])=>!Xt.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:Ke(Vn(),_n.current),extras:{...wn(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 Ce(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 Be;case"ag-ui":return Fe;default:return Ue}}(n);if(await $t(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),Lt("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||gn(t))&&(H=!0),"end"!==D.apply(t)||!!vn(t)&&(D.deltas.flush(),W=!0,i&&(Z=Bt(!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(),Ne.current===e.renderer.deltas&&(Ne.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(),wt({turnId:e.turnId,shownUpTo:bn(Ct.current)}),t&&E(e=>e.filter(e=>e.id!==t))},Er=s(_r);Er.current=_r;const Mr=e=>{it.current&&(wt(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=bn(Ct.current);Tr(),wt({turnId:e.turnId,shownUpTo:t})}const t=it.current;if(!t||t.readBack)return;if(!pr())return void Mr("stopped");Jn();const n=window.setTimeout(()=>{it.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=it.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:it.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(Ue,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===Et.current&&null===Wt.current||Te.current||(qt(),Sr("stopped")));if(!Yt.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=qe.current.get(r);if(void 0!==a)return void(kr(a,n,!0)&&(qe.current.delete(r),en()));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&&(ot.current=t.renderer,Jn());let i=t;if(i&&i.turnId!==r&&(Tr(),i=null),!i){const t=it.current,o=t?.turnId===r,a=r===Et.current;if(!("cancelled"!==n.action&&"error"!==n.action||o||a))return void(t&&$r());t&&!o&&(Mr(),Jn());const s=Ie();E(e=>[...e,{id:s,role:"assistant",content:"",timestamp:new Date}]),i={turnId:r,renderer:yr(s,!0)},_e.current=i,en(),Ne.current=i.renderer.deltas,Me.current=i.renderer,wt(null);const c=a||o;!0===e.resumed&&c?(ot.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(vn(n)){const e=qe.current;for(e.set(i.turnId,i.renderer.currentAssistantId());e.size>20;)e.delete(e.keys().next().value);Bt(!0)}Tr()}},Ur=s(Pr);Ur.current=Pr;const Hr=()=>{const e=ze.current;e&&(Nn.current?.(e.text,"cancelled"),mn(e.parts)),De(null)},Wr=(e,t)=>{const n="string"==typeof e&&e?e:null;zn.current=n,On(n),Ne.current?.close(),Ne.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(),ot.current=null,wt(null),qe.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),le(!1),Mn.current=null,Ln.current=!1,Rn.current=null,be.current=!1,A?(ye(null),Lt("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??Et.current;r&&(Le.current=r),qt(),Ne.current?.flush(),Ne.current?.close(),Ne.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),le(!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 Ce(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),Pe(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=Se(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 $t(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&&(it.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||ht)return;if(Re.current&&(Re.current=!1,$e))return De(null),mn($e.parts),$e.draft||0!==$e.files.length?(oo($e.text),void Bn($e,{before:!0})):void Nn.current?.($e.text,"dropped");if(Je||!$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=fn(t.text,Dt(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)}mn(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}=pn(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)Dt(e.onSent)},onNotSent:()=>mn(n)}).then(e=>{if("held"===e)return;const r="sent"===e||"steered"===e;t(r?"sent":"failed"===e?"failed":"dropped"),r||mn(n)},()=>{t("failed"),mn(n)})},[M,ht,Je,$e]);const ao=s(Ir);ao.current=Ir,i(()=>{const e=window.setTimeout(()=>{Ft(m,U,q,F)},300);return()=>window.clearTimeout(e)},[q,U,F,m]),i(()=>()=>{Ne.current?.close(),ke.current?.abort(),Ze.current?.abort(),Ge.current&&window.clearTimeout(Ge.current.timer),null!==At.current&&window.clearTimeout(At.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;Ft(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 le(!1);if(Date.now()>=$n.current)return le(!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 le(!1)):n.turnRunning?void ve(e=>e+1):(le(!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||ht,sendsHeld:!M&&(Je||ht),turnEnd:R,agentStatus:D,attachedFiles:J,conversationId:U,contextUsage:ee,transferredAgent:X,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()+Kt,void le(!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:he,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=ot.current;if(ot.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(rn(e),(l.get(rn(e))??0)+1);const d=t.slice(c+1).filter(e=>{if(e.serverId&&i.has(e.serverId))return!1;const t=l.get(on(e))??0;return 0===t||(l.set(on(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&&rn(t)===on(e));return t?(u.add(t.id),an(t,e)):{...e,id:He(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?xn(t,n.shownUpTo):"stopped"));const r=it.current;!r?.readBack||e<r.readBack.from||Mr(t?xn(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=it.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!==Et.current&&!_e.current;if(!t||!n||r)return t&&n&&ur(t,n).catch(()=>{}),void Br();if(null!==Ee.current)return;We.current=!1,Pe(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=Vt(m,e);B(t.text),V(t.refs)}}}}function Nn(e,t){if(t)return e.find(e=>e.id===t)??e.find(e=>e.slug===t)}function Cn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,storageKeyPrefix:o,initialAgent:l,onAgentChange:d}){const u=Ht(),p=null===t?.agents||!!t?.singleEndpoint||"legacy"===n,h=_t(o,Ct),[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=Mt("local",h);return Nn(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&&Lt("local",h,e.slug),A(!1),d?.(e),t?.()):A(!1)},reloadAgents:C}}function Sn(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 In=400;let Tn=null,An=null,_n=0;function En(){null!==Tn&&(window.clearInterval(Tn),Tn=null),null!==An&&(document.title=An,An=null)}function Mn({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;_n+=1;const e=()=>{!document.hidden&&document.hasFocus()&&En()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),_n=Math.max(0,_n-1),0===_n&&En()}},[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===An&&(An=document.title),null!==Tn&&window.clearInterval(Tn);let t=!0;document.title=e,Tn=window.setInterval(()=>{t=!t,document.title=t?e:An??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 Ln({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=Ht(),[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 Rn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,agentSlug:o}){const s=Ht(),[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 $n(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 Dn(e){const t=s(e);l(()=>{t.current=e});const n=c((...e)=>t.current?.(...e),[]);return e?n:void 0}function zn(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 jn(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const On=new Set(["thinking","status","stream","turn_started"]);function Pn(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&&On.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=Pe(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 Un(e){return e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}const Hn=new Set(["no-speech","aborted"]);function Wn(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=Pn(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=Un(e);if(n.length<2)return!1;const r=new Set(Un(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,Hn.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 qn=()=>null!==jn();function Bn(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 Fn(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 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:"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"})]}),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:"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"})]}),Gn=({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"})}),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 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"})]}),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("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"})]}),Xn=({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"})]}),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:"M20 6 9 17l-5-5"})}),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:"m6 9 6 6 6-6"})}),er=({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"})}),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:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),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("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"})]}),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("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"})]}),or=({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"})}),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:"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"})]}),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:"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"})]}),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 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"})]}),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:"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"})]}),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:"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"})]}),dr=({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"})}),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:"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"})]}),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:"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"})]}),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 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"})]}),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("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"})]}),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("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"})]}),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("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"})]}),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("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"})]}),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("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"})]}),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("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),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("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"})]}),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:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),kr=({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"})}),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-14 0v-2"}),t("rect",{x:"9",y:"2",width:"6",height:"13",rx:"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 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"})]}),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:"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"})]}),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:"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"})]}),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("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.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:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),_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("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),Er=({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"})}),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("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),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("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),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:"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"})]}),$r=({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"})]}),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:"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"})]}),zr=({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"})]}),jr="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",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:jr}),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"})]}),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:jr}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),Ur=({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"})}),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:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]});function Wr({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(Zn,{size:13})}),t("button",{type:"button",onClick:()=>l(!1),"aria-label":i("Cancel"),className:s,children:t(tr,{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(Dr,{size:12}),i("Clear all conversations")]})})}const qr=({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=E(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)},Br=({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 Fr(e){return Math.max(e.maxRight-e.minLeft,0)}const Vr=({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=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:Fr(c)},role:"tooltip",children:n}),E(o.current))]})},Kr=({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})},Gr=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(lr,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(_r,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(mr,{...e})}],Jr=({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:M=[],conversationsLoading:R=!1,activeConversationId:$=null,onSelectConversation:D,onDeleteConversation:z,onClearAll:j,actions:O,t:P})=>{const U=s(null),H=s(null),W=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?_r:"fullscreen"===r?hr:lr;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(Qn,{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(qr,{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(Br,{size:16})}),0===c.length&&!l&&d&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(Vn,{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(Tr,{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")}),q(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(Kr,{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(ir,{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(zr,{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(Vr,{title:P("Conversation history"),children:t("button",{ref:W,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(vr,{size:18})})}),e(qr,{open:T,onClose:()=>E?.(),anchorRef:W,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===M.length&&t("div",{className:"px-4 py-2",children:t(Br,{size:16})}),!R&&0===M.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:P("No conversations yet")}),M.map(n=>{const r=n.conversationId===$,o=L(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(Dr,{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(sr,{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&&M.length>0&&t(Wr,{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(Vr,{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(sr,{size:18})})}),"inline"!==r&&x&&e(n,{children:[t(Vr,{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(qr,{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:Gr.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(Vr,{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(tr,{size:18})})})})]})};function Yr({url:e,query:t,exclude:n,requestHeaders:r}){const o=Ht(),[s,c]=a(fe);return i(()=>{if(!e||null===t)return void c(fe);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:he(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 Xr({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||ce(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=Yr({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 ve(i.length===e.length?e:i,t.items)}(e,A,n))},[A,n]);const M=u(()=>ve(h.map(we),_),[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=>ge(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:pe(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=jt(r);if(e&&ge(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 Zr=14,Qr=2*Math.PI*6,eo=[{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"}],to=({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=`${M(i)}/${M(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?eo.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:Zr,height:Zr,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:Qr,strokeDashoffset:Qr*(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(Vr,{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(qr,{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:M(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(Vr,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},no=({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(Jn,{size:14}):t(kr,{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})})]})},ro=({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(Vr,{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(Er,{size:15})})}),e(qr,{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))]})]})]})},oo=({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(Vr,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums chat-text-muted-400/30",role:"img","aria-label":`${e} ${M(o)}`,children:M(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=`${M(o)}/${M(a)}`,m=r(l?"Quota reached":"Quota"),f=i(s?`${m} · ${s}`:m);return t(Vr,{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})]})})},ao=[],so=({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=Xr({url:R?.url??null,requestHeaders:R?.requestHeaders,conversationId:R?.conversationId,text:f,onTextChange:g,textareaRef:z,refs:R?.refs??ao,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!==jn();return i(()=>{const e=jn();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=zn(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)&&zt(k),J=F&&!V&&!G,Y=Boolean(R)&&pe(R?.refs??ao,f).length>0||Boolean($)&&Ot($?.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(cr,{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(Gn,{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(no,{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(Vr,{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(Cr,{size:18}):t(Nr,{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(Vr,{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(Ar,{size:18})})}),Z&&t(Vr,{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(Ar,{size:18})})}),t(Vr,{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?Mr:Ar,{size:18})})})]}),q&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[_&&_.length>0&&t(ro,{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(to,{usage:M,t:I}),E&&t(oo,{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})]})},io=e=>e.serverId??e.id;const co=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;const lo={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"}},uo=new Map;function po(e,t){const n=`${e??""}|${t}`;let r=uo.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,lo[t])}catch{r=new Intl.DateTimeFormat(void 0,lo[t])}uo.set(n,r)}return r}const ho={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const mo=new Set(["ArrowUp","PageUp","Home"]);function fo(e){return 1===e.length?e[0].clientY:null}const go=new Set(["auto","scroll","overlay"]);const vo={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"})]})},wo="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)]",yo=({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=vo[l.kind],v=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(l.kind,r),w=l.title||v,y=W(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(Br,{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:wo,onClick:()=>c(l),children:r("Open")}),x&&e("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:wo,children:[r("Open in XTM One"),t(ir,{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:wo,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(Br,{size:11}):t(ar,{size:12}),a]},n)})]})]})};function bo(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function xo(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 ko="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",No=({proposal:n,decision:r,onDecide:o,disabled:s,t:i})=>{const[c,l]=a(!1),[d,u]=a(""),h=p(),m=xo(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(Ur,{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:bo(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:`${ko} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(Hr,{size:13}),i("Decline this call")]}),t("button",{type:"button",disabled:s,onClick:()=>{l(!1),u("")},className:`${ko} 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:`${ko} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(Hr,{size:13}),i("No")]}),e("button",{type:"button",disabled:s,onClick:()=>v("approve"),className:`${ko} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(Zn,{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:`${ko} border chat-border-200/15 chat-text-secondary-700/70 hover:chat-surface-hover-100/5`,children:i("Yes, always")})]})]})},Co=({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=xo(y),x=xo(!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(Vn,{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(No,{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(Vn,{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:`${ko} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:l(f?"Sending…":"Confirm")})]})]})},So=({src:n,alt:r,onClose:o,t:c})=>{const l=s(null),d=s(null),[u,p]=a(null);return i(()=>{p(E(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(tr,{size:20})}),t("img",{src:n,alt:r,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},Io=({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=Ht();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(xr,{size:14})})]}),f&&t(So,{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(wr,{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 To="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",Ao=({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:To,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(fr,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:To,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(fr,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(ir,{size:11})})]}):null]})]})};function _o(e,t){return e>1?A(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function Eo(e,t){return e>1?A(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function Mo(e,t){return e>1?A(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function Lo(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:Yn,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:_o(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:zr,showDots:!1}}if(r.some(e=>"check_task_status"===e)){return{label:Eo(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:Er,showDots:!1}}if(r.some(e=>"get_task_result"===e)){return{label:Mo(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:Er,showDots:!1}}let o,a=Ur;if(r.some(e=>e.includes("search")||e.includes("list"))?a=Tr:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?a=rr:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?a=br:r.some(e=>e.includes("code")||e.includes("execute"))?a=Lr:r.some(e=>e.includes("web")||e.includes("browse"))&&(a=gr),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:Vn,showDots:!1};case"cancelling":return{label:t("Stopping…"),StatusIcon:Yn,showDots:!0};case"reconnecting":return{label:t("Reconnecting…"),StatusIcon:Yn,showDots:!0};case"wait_start":return{label:e.waitReason||t("Waiting before continuing…"),StatusIcon:Er,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:Er,showDots:!0};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:Er,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:Er,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:Yn,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Consulting {agent}…",{agent:n}),StatusIcon:zr,showDots:!1}}case"delegating":return{label:_o(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:zr,showDots:!1};case"polling":return{label:Eo(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:Er,showDots:!1};case"collecting":return{label:Mo(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:Er,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Transferring to {agent}…",{agent:n}),StatusIcon:ir,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:Yn,showDots:!1}}}function Ro(e,t,n){return e&&n?.(e)||Lo(e,t).label}function $o(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 Do({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 zo(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 jo(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 Oo=({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=Lo(r,s),{StatusIcon:w,showDots:y}=v,b=Ro(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 $o(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 $o(a)}(x??""),[x]),L=M.length>=3,R=jo(c&&!L,5e3),$=jo(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:zo(Math.ceil(A))}):E&&t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:zo(_)}),"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(Ao,{t:s,enabled:c,onPlay:l,playUrl:d,keepEndInView:p,messages:f,content:g?.()}):L?t(Do,{text:M}):null]})};class Po 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 Uo({draw:e}){return t(n,{children:e()})}function Ho({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 Wo=y().use(w).use(v).freeze();function qo(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(qo);default:return!1}}function Bo(e,t){return e.lastIndexOf("\n",t-1)+1}function Fo(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Bo(e,t-1),t-1).trim()}function Vo(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 Ko{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 Wo.parse(o).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Bo(o,n),s=a[a.length-1];t>s&&!Vo(e,s,t)&&a.push(t)}s<0&&qo(t)&&(s=a.length-1)}let i=n;for(let t=a.length-1;t>n;t--)if(Fo(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 Go=r({copiedBlock:null,onCopyCode:()=>{},streaming:!1,t:T});function Jo({draw:e,block:r}){const o=e();return null==o||!1===o?t(n,{children:r}):t("div",{className:"my-3",children:o})}const Yo={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(Go),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(Zn,{size:14,className:"text-green-500"}):t(nr,{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(Po,{label:"A chat code block renderer",resetKey:`${u}\0${c}`,fallback:t(Ho,{t:l}),children:t(Jo,{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(Go),a=Je(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(Go);return"string"==typeof e&&e?t(Io,{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})},Xo=[v,k],Zo=m(({source:e})=>t(x,{remarkPlugins:Xo,urlTransform:I,components:Yo,children:e}));Zo.displayName="MarkdownBody";const Qo=({source:e})=>{const[r]=a(()=>new Ko),o=u(()=>r.split(e),[r,e]);return t(n,{children:o.map((e,n)=>t(Zo,{source:e},n))})},ea=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(Go.Provider,{value:v,children:t(h?Qo:Zo,{source:f})})});ea.displayName="MarkdownMessage";function ta(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function na(e){return e.replace(/_/g," ")}const ra=({entry:n,index:r,t:o})=>{const[s,i]=a(!1),c=u(()=>ta(n.input),[n.input]),l=u(()=>ta(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(Xn,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(Hr,{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:na(n.name)}),t(Qn,{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)")})]})]})]})},oa=({msg:n,onClose:r,t:o})=>{const c=s(null),l=s(null),d=s(null),[u,p]=a(null);i(()=>{p(E(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(Ur,{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(tr,{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(Vn,{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(Yn,{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:$o(w)})})]}),v.length>0?t("div",{className:"flex flex-col gap-1.5",children:v.map((e,n)=>t(ra,{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(Ur,{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:na(n)})]},`${n}-${r}`))}),g.length>0&&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 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(Jn,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},aa=e=>e.parentElement,sa=e=>getComputedStyle(e).overflowY;function ia(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function ca(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 la=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const da="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",ua="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",pa="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",ha=`opacity-0 ${da} ${pa}`,ma=`opacity-50 ${da} ${pa}`,fa="opacity-100 text-[var(--chat-accent)]",ga=({timestamp:n,locale:r})=>{const o=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:po(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:po(t,"full").format(e),iso:e.toISOString()}:null;var r,o}(n,r);return o?t(Vr,{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},va=({text:e,label:n,t:r})=>{const[o,s]=a(!1),i=o?r("Copied!"):n;return t(Vr,{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:`${ua} ${o?"opacity-100 text-green-500 dark:text-green-400":ha}`,children:t(o?Zn:nr,{size:14})})})},wa=({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?$r:Rr;return t(Vr,{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:`${ua} ${a?fa:ha} ${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")})]})},ya=({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")})]})]})},ba=({speaking:e,onToggle:n,t:r})=>{const o=r(e?"Stop reading":"Read aloud");return t(Vr,{title:o,children:t("button",{type:"button",onClick:n,"aria-label":o,className:`${ua} ${e?fa:ha}`,children:t(e?Pr:Or,{size:14})})})},xa=[],ka=new Set(["PRESENTATION","REPORT","VIDEO"]),Na=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:_=xa,codeBlockRenderers:E,transformMessageText:M,onArtifactOpen:L,renderMessageExtras:R,messageFooterActions:$,t:D})=>{const[z,j]=a(!1),W="assistant"===r.role,q=u(()=>Dt(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,G=s(K);d(()=>{const e=G.current&&!K;G.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&&la.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&la.has(e.filename.slice(n+1).toLowerCase())}(n)?h(n):void 0;if(o)return t(Io,{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(cr,{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(ar,{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(cr,{size:14}),n]},r),Z=(e,n)=>t(yo,{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(Po,{label:"A chat marker card",resetKey:`${n}\0${o}`,fallback:t(Ho,{t:D}),children:t(Uo,{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=O(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?U(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=io(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:ca(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(kr,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:a})]});return T&&I?.has(r.conversationId)?t(Vr,{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(Vr,{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=P(q,o,_),n=new Map((r.attachments??[]).map(e=>[e.fileId,e])),a=new Map((r.artifacts??[]).map(e=>[H(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(ea,{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):ka.has(e.kind)&&i.add(H(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=H(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=H(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(va,{text:B,label:D("Copy message"),t:D}),!r.timestampUnknown&&t(ga,{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(ga,{timestamp:r.timestamp,locale:k}),ee&&t(Vr,{title:r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),children:t("button",{type:"button",onClick:()=>j(e=>!e),className:`${ua} ${r.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":ma}`,"aria-label":r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":z,children:r.isTruncated?t(Vn,{size:14}):t(yr,{size:14})})}),t(va,{text:ne,label:D("Copy response"),t:D}),v&&t(wa,{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(J,""))))&&t(ba,{speaking:C,onToggle:()=>S(ce,re),t:D}),$?.(r,{streaming:o})]}),te&&w?.commentOpen&&t(ya,{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(oa,{msg:r,onClose:()=>j(!1),t:D})]});var le});Na.displayName="MessageRow";const Ca=({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 K=s(null),[J,Z]=a(150),{entries:Q,rate:ee,saveComment:te,skipComment:ne}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o}){const i=Ht(),[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=io(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 ie(i,r,o,e.serverId,t?{rating:re(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=io(e),l=ae(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 ie(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(io(e),{...t,commentOpen:!1,error:null}),[f])}}({feedbackUrl:E,conversationId:M,requestHeaders:y,onMessageFeedback:N,t:V}),se=function(e,t){const n=Ht(),[r]=a(co),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,Y(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=Y(r,4096),i=new Audio;a.audio=i;let c=0;try{for await(const t of X(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=G(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=ho){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())}}}(()=>K.current));i(()=>{const e=K.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&&go.has(r(o)))return!0;return!1}(t,e,aa,sa)||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||J!==e.visible+e.count)return;pe.current=null;const t=K.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>J,ye=u(()=>we?n.slice(n.length-J):n,[n,J,we]),{speakingId:be,stop:xe}=se,ke=null===be||n.some(e=>io(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:K,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&&(mo.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&ia(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:ia(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=fo(e.touches)},onTouchMove:e=>{const t=fo(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:"relative 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>J)return void Z(e=>e+50);if(!q||he)return;const e=K.current;me(!0),pe.current={firstId:n[0]?.id,visible:Math.min(n.length,J),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(Qn,{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(Oo,{agentStatus:o,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,onSkipWait:S,...F})},e.id):t(Na,{msg:e,isStreaming:n,agentName:p,logoIcon:h,onRelativeLinkClick:m,onDownloadFile:f,resolveAttachmentUrl:g,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,feedbackMode:"assistant"===e.role?oe(e.serverId,E,M,!!N):null,feedback:Q[io(e)],onRate:ee,onSaveComment:te,onSkipComment:ne,locale:L,canSpeak:se.supported,isSpeaking:be===io(e),onToggleSpeech:se.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(Oo,{agentStatus:o,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,...F}),Se&&t(Co,{proposals:I,onSubmit:T,isSubmitting:A,error:_,t:V},I.map(e=>e.toolCallId).join("|")),W,t("div",{})]})};function Sa(e){const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const Ia=({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:Sa(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?Cr:Nr,{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(Ir,{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(Pr,{size:20})})]})]})},Ta=({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}=_(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]})},Aa=({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(Ta,{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))]})]}),_a="application/x-filigran-conversation";const Ea="p-1 rounded-md chat-text-muted-400/30 hover:chat-icon-hover transition-colors disabled:opacity-40 disabled:pointer-events-none",Ma="text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",La=({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=_t(v,It),[M,L]=a(()=>function(e){try{const t=JSON.parse(Mt("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 be(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 be(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(Vr,{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(_r,{size:17})})}),t(Vr,{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(sr,{size:17})})})]});const G=e=>t(ja,{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(sr,{size:15}),k("New conversation")]}),y,t(Vr,{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(_r,{size:17})})})]}),r.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Tr,{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(Br,{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:Ma,children:k("Workspaces")}),t(Vr,{title:k("New workspace"),children:t("button",{type:"button",onClick:()=>$(!0),"aria-label":k("New workspace"),className:Ea,children:t(pr,{size:14})})})]}),R&&t(Da,{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(za,{workspace:e.workspace,count:e.conversations.length,open:xe(e.key,M,e,c,!!W),toggleable:ke(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),Lt("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($a,{t:k})},e.key)),e(Ra,{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:Ma,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(Wr,{onClear:x,className:"px-2 pt-3",iconButtonClass:Ea,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})]})},Ra=({onDropConversation:e,accepts:n,children:r,className:o=""})=>{const[i,c]=a(!1),l=s(0),d=e=>e.dataTransfer.types.includes(_a);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(_a);n&&e(n)}}:{},children:r})},$a=({t:n})=>{const{before:r,after:o,hasSlot:a}=_(n,"Drop a conversation here, or start one with {icon}.","icon");return e("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:[r,a&&t("span",{role:"img","aria-label":n("New conversation in this workspace"),className:"inline-block align-[-1px]",children:t(sr,{size:11})}),o]})},Da=({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)]"})},za=({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(Ra,{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(Da,{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(er,{size:12,className:"shrink-0 chat-text-muted-400/30 transition-transform "+(s?"rotate-90":"")}),t(dr,{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:`${Ea} hover:text-red-500`,children:t(Zn,{size:13})}),t("button",{type:"button",onClick:()=>y(!1),"aria-label":m("Cancel"),className:Ea,children:t(tr,{size:13})})]}:{children:[t(Vr,{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:Ea,children:t(sr,{size:13})})}),t(Vr,{title:m("Rename workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":m("Rename workspace"),className:Ea,children:t(Sr,{size:13})})}),!r.isDefault&&t(Vr,{title:m("Delete workspace"),children:t("button",{type:"button",onClick:()=>y(!0),"aria-label":m("Delete workspace"),className:`${Ea} hover:text-red-500`,children:t(Dr,{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(sr,{size:12}),m("New conversation — send a message to start it")]}),f]})]})},ja=({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(_a,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(Jn,{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?L(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(ur,{size:13})}),t(qr,{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(dr,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===r.workspaceId&&t(Zn,{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(tr,{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(sr,{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(Dr,{size:13})})]})]})},Oa=new Set([502,503,504]),Pa=new Set([401,403]),Ua=f(function(e,n){const r=s(e.onSessionEnded);r.current=e.onSessionEnded;const o=s("");o.current=Se(e.requestHeaders);const a=u(()=>{let e=null;const t=t=>{r.current&&e!==o.current&&(e=o.current,Dt(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(Ut,{value:a,children:t(Ha,{...e,ref:n})})}),Ha=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:$,pageContext:z,pushContentSelector:j,backendType:O="rest",miniGameEnabled:P=!0,onPlayWaitingGame:H,notifyOnComplete:W=!0,onTaskComplete:q,onMessageFeedback:B,locale:F,disableImagePreviews:V=!1,contextUsageEnabled:K=!0,composerToolbar:J,storageKeyPrefix:Q,conversationId:te,onConversationChange:re,initialAgent:oe,onAgentChange:ae,readOnly:ie=!1,readOnlyNotice:ce,getRequestExtras:le,onStreamEvent:de,markerRenderers:ue,codeBlockRenderers:pe,transformMessageText:he,onArtifactOpen:fe,headerActions:ge,banner:ve,composerHeader:we,transcriptFooter:be,welcome:xe,renderMessageExtras:ke,messageFooterActions:Ne,sidebarRowActions:Ie,sidebarHeaderActions:Te,sidebarSections:_e,statusLabel:Ee,waitingMessages:Me,renderWaitingPanel:Re,fontFamily:$e,theme:De,onReady:ze,onBeforeSend:je,onHeldSendSettled:Oe,onTurnRunningChange:Pe,steerAttachments:Ue=!1,holdSendsDuringTurn:We=!1,agentMentions:Be=!1,hideConversationList:Fe=!1},Ve){const Ke=$n(m),Ge=$n($),Je=$n(z),Ye=$n(k),Xe=Dn(E),Ze=Dn(M),Qe=Dn(H),et=Dn(q),tt=Dn(B),nt=Dn(re),rt=Dn(ae),ot=Dn(le),at=Dn(je),st=Dn(Oe),it=Dn(de),ct=Dn(Pe),lt=Dn(fe),dt=s(null),{fetch:ut,sessionEnded:pt}=o(Pt),ht=u(()=>ne(y,F),[y,F]),mt=$n(Me),ft=u(()=>ue?Object.fromEntries(Object.entries(ue).map(([e,t])=>[e.toUpperCase(),t])):void 0,[ue]),gt=$n(u(()=>pe?Object.fromEntries(Object.entries(pe).map(([e,t])=>[e.toLowerCase(),t])):void 0,[pe])),vt=$n(u(()=>function(e){const t=new Set;for(const n of e??[]){const e=n.toUpperCase();D.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:Ct,agentsSettled:It,agentsDisabled:Tt,selectedAgent:At,agentMenuOpen:Et,setAgentMenuOpen:Rt,handleSwitchAgent:$t,reloadAgents:zt}=Cn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge,storageKeyPrefix:Q,initialAgent:oe,onAgentChange:ae?rt:void 0}),[jt,Ot]=a(null),Ut=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)=>{Dt(en.current,e,t.relayed),Dt(it,e,t)},[it]),{messages:nn,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:xn,submitApprovalDecisions:Tn,isResumingAfterDecision:An,historyReloadNonce:_n,reloadHistory:En,mergeTurnHistory:zn,settleUnseenEnd:On,historyLoadedRef:Pn,conversationIdRef:Un,handleFileAdd:Hn,handlePaste:qn,handleSendMessage:Kn,skipWait:Gn,readPendingApprovals:Jn,heldMessage:Yn,notice:Xn,cancelHeldMessage:Zn,agentMentions:Qn,addAgentMention:er,handleNewChat:tr,pendingWorkspaceId:nr,clearPendingWorkspace:rr,handleStopGenerating:ar,conversationRefs:sr,addConversationRef:ir,setAttachedFiles:cr,setMessages:lr,setContextUsage:dr,updateConversationId:ur,handleSwitchConversation:pr}=kn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,agentSlug:At?.slug,requestHeaders:Ge,pageContext:Je,onRelativeLinkClick:E?Xe:void 0,t:ht,maxFileCount:L,maxTotalSize:R,storageKeyPrefix:Q,controlledConversationId:te,onConversationIdChange:re?nt:void 0,getRequestExtras:le?ot:void 0,onStreamEvent:tn,onSessionEnded:pt,onConversationTitle:()=>{Qt.current()},historySettledFor:Wt,steerAttachments:Ue,holdSends:We,agentMentionsEnabled:Be,onBeforeSend:je?at:void 0,onHeldSendSettled:Oe?st:void 0});Bt!==fn&&(Ft(fn),null!==Wt&&qt(null)),i(()=>{void 0!==te&&te!==Un.current&&(te?pr(te):tr())},[te]);const{suggestions:hr,loading:mr}=Rn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge,agentSlug:At?.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}=Ln({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=Ht(),[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(Sn).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 Ce(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=Ht(),[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=ye(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 Ce(a)};const s=204===a.status?[]:ye([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)&&rr(nr)},[Tr,Ar,nr,rr]);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?Dt(ct,!0):Dt(ct,!1,{ended:pn??"stopped"}))},[dn,pn,ct]),i(()=>()=>{Pr.current&&(Pr.current=!1,Dt(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=me(h,Ke,O),qr=u(()=>new Set(br.map(e=>e.conversationId)),[br]),Br=Dn(yr?Hr:void 0),Fr=nn.some(e=>(e.conversationRefs?.length??0)>0);i(()=>{Fr&&yr&&kr()},[Fr,yr,kr,fn]);const Vr=Z(h,Ke,O,"messagesPage"),[Kr,Gr]=a(!1),Yr=Z(h,Ke,O,"tts"),Xr=u(()=>Yr?{url:Yr,requestHeaders:Ge}:void 0,[Yr,Ge]),Zr=s(nn);Zr.current=nn,i(()=>Gr(!1),[fn]);const Qr=c(async()=>{const e=Un.current,t=Zr.current.find(e=>e.serverId)?.serverId;if(!Vr||!e||!t)return Gr(!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=qe(r?.messages).filter(e=>!e.serverId||!o.has(e.serverId)).map(e=>({...e,id:He(e.serverId)}));return lr(e=>[...a,...e]),Gr(!0===r?.has_more&&a.length>0),a.length}catch{return 0}},[Vr,Un,Ge,lr]),eo=(e,t,n)=>{if(qt(e),Gr(!!Vr&&!0===t.has_more),!t.messages?.length)return;const r=qe(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=on(e),a=n.findIndex((e,t)=>!o.has(t)&&!e.serverId&&rn(e)===r);a>=0&&(t=a,n[a]=an(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:He(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=Ae(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,En())},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,En]);const no=Se(Ge),ro=c(()=>{Zt(null),En()},[En]);i(()=>{Xt&&Xt.conversationId===fn&&!ln&&Xt.headersKey!==no&&ro()},[Xt,fn,ln,no,ro]);const oo=Xt&&Xt.conversationId===fn?Xt:null,ao="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),Hn(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=_t(c,St),[d,u]=a(()=>{const e=Mt("local",l);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=In)return t}return In}),[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,In),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="",Lt("local",l,String(f.current)),v.current?.())},o=()=>{const e=.4*window.innerWidth;if(f.current>e){const t=Math.max(e,In);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:In,isResizing:p}}({mode:n,resizable:S,onWidthChange:I,onResizeStart:T,onResizeEnd:A,storageKeyPrefix:Q});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(or,{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||At?.name||ht("Assistant"),Io=c(()=>{const e=dt.current;return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);Mn({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,Lo=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(`${Lo(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()})}},[Lo,Ge,Ze]),Do=c(async(e,t)=>{const n=await ut(Lo(e,t),{credentials:"include",headers:{...Ge??{}}});if(n.ok)return Le(await n.json())},[Lo,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}:{},...ee(De)},jo=s(zn);jo.current=zn;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 Ot(null);if(Pn.current)return Ut.current!==fn&&jt!==fn&&Ot(fn),void(Ut.current!==fn&&Wt!==fn&&Vt?.conversationId!==fn&&qt(fn));if(!At&&!Tt)return void(It&&jt!==fn&&Ot(fn));Pn.current=!0,Ut.current=fn,Ot(null);const e=`${h}${Ke?.sessions??"/chat/sessions"}`,t=fn,n=()=>!Po.current||Un.current!==t,r=Se(Ge),o=_n;ut(e,{method:"POST",headers:{"Content-Type":"application/json",...Ge??{}},body:JSON.stringify({conversation_id:fn,agent_slug:At?.slug,supports_artifacts:!0})}).then(e=>n()?null:e.ok?(Yt.current=0,Jt(null),Zt(null),e.json()):(Oo.current(o,null),Pa.has(e.status)?Ce(e).then(e=>(n()||Zt({conversationId:t,detail:e,headersKey:r}),null)):(Oa.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=qe(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(()=>{Ut.current===t&&(Ut.current=null),n()||Ot(t)})},[fn,At,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(At);Bo.current=At;const Fo=It&&!ao,Vo=Dn(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($t);Zo.current=$t;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)??At?.id??null,ra=function(e){const t=Ht(),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=Y(e,200),c=o?X(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 Bn(t,r)){if(r.aborted)return;await Fn(e,s,r)}}},[]),p=c(()=>{if(d.current)return!0;const e=jn();if(!e)return!1;const t=Wn({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=>Dt(n.current.speakable,e)??e,present:e=>Dt(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=>G(U(e,vt)),present:e=>he?he(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=Nn(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(Jr,{mode:n,agentName:So,agents:kt,agentsLoading:Nt,agentsError:Ct,selectedAgent:At,transferredFrom:vn?At?.name:void 0,agentMenuOpen:Et,onAgentMenuToggle:()=>Rt(e=>!e),onAgentMenuClose:()=>Rt(!1),onSwitchAgent:e=>{e&&$t(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(La,{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&&(rr(e),kr()),t},onMove:Sr,onNewChat:e=>{tr(e),_r()}}:void 0,storageKeyPrefix:Q,rowActions:Ie,headerActions:Te,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===nn.length&&ao?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===nn.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(Vn,{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===nn.length?xe?t("div",{className:"flex-1 min-h-0 overflow-y-auto filigran-chat-scrollable",children:xe}):t(Aa,{firstName:ko,logoIcon:bo,promptSuggestions:fr,suggestionsLoading:mr,agentName:At?.name,agentDescription:At?.description,onPromptClick:ie?void 0:cn,t:ht}):t(Ca,{messages:nn,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:P,onPlayWaitingGame:Qe,waitingGameUrl:xo,onMessageFeedback:tt,feedbackUrl:se(h,Ke,O),conversationId:fn,locale:F,isResumingAfterDecision:An,onSkipWait:Gn??void 0,pendingApprovals:yn,onSubmitApprovalDecisions:Tn,isSubmittingApproval:bn,approvalError:xn,openableConversationIds:qr,onOpenConversation:Br,markerRenderers:ft,markerKindList:vt,codeBlockRenderers:gt,transformMessageText:he,onArtifactOpen:lt,renderMessageExtras:ke,messageFooterActions:Ne,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(so,{header:we,sendsHeld:un,steerAttachments:Ue,canHold:We,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:Hn,onFileRemove:_?void 0:e=>cr(t=>t.filter((t,n)=>n!==e)),onPaste:_?void 0:qn,t:ht,mode:n,separatorColor:C,prompts:gr,quota:vr,contextUsage:K?gn:null,composerToolbar:J,conversationReferences:Wr?{url:Wr,requestHeaders:Ge,conversationId:fn,refs:sr,onPick:ir}:void 0})]})]}),ra.snapshot&&t(Ia,{call:ra.snapshot,agentName:So,logoIcon:bo,processingLabel:Ro(hn,ht,Ee),onInterrupt:ra.interrupt,onToggleMute:ra.toggleMute,onEnd:ra.end,t:ht})]})}),Wa=({isOpen:n,onToggle:r,label:o,accentColor:a="#7b5cff",icon:s,t:i,locale:c})=>{const l=u(()=>ne(i,c),[i,c]),d=s??t(or,{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{Ua as ChatPanel,Wa as ChatToggleButton,qn 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 g,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 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),g=n(d.slice(h)).length,f=n(u);if(g<2||f.length===g)continue;const v=[];for(let e=0;e<g;e++)v.push(f[e]?o(f[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.replace(/\s+/g," ").trim()}](${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,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}}function E(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function M(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 L(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 R=["FILE","PRESENTATION","REPORT","VIDEO"],D=`(${R.join("|")}):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?`,$=/^[A-Z][A-Z0-9_]*$/;const z=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new Map;function O(e){const t=e.filter(e=>!R.includes(e)),n=t.join(","),r=j.get(n);if(r)return r;const o=[...R,...t].map(z).join("|"),a=t.length>0?`|(${t.map(z).join("|")}):([^\\]]+)`:"",s=[...R,...t].map(e=>`[[${e}:`),i={complete:new RegExp(`\\[\\[(?:${D}${a})\\]\\]`,"gi"),partial:new RegExp(`\\[\\[(?:${o})(?::[^\\]]*)?\\]?$`,"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 P(e,t=!1,n=[]){if(!e)return[];const r=O(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 U(e,t=[]){const n=[];for(const r of P(e,!1,t))"text"===r.type&&r.value.trim()&&n.push(C(r.value));return n}const H=(e,t)=>`${e}:${t.toLowerCase()}`;function q(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 B=y().use(w).use(v).freeze(),F=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function V(e){if(F.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(V).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function K(e,t){if(!F.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(V(e));case"tableRow":return void t.push((e.children??[]).map(V).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])K(n,t)}}function G(e){const t=[];for(const n of e)n.trim()&&K(B.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 J=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;function Y(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*X(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 Z(e,t,n,r){const o=t?.[r];return"rest"!==n||t?.singleEndpoint||"string"!=typeof o||!o?null:`${e}${o}`}const Q={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 ee(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(Q)){const o=e[n];"string"==typeof o&&o.trim()&&(t[r]=o)}return t}const te={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}…","Consulting {agent}: {count} questions…":"Consultando a {agent}: {count} preguntas…","Consulting {agent}: {tool} (+{count} more)…":"Consultando a {agent}: {tool} (+{count} más)…","Consulting {agent}: {tool}…":"Consultando a {agent}: {tool}…","Consulting {agent}: writing the answer…":"Consultando a {agent}: redactando la respuesta…","Consulting {count} agents…":"Consultando a {count} agentes…","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 {icon}.":"Suelte aquí una conversación o inicie una con {icon}.","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}…","Consulting {agent}: {count} questions…":"Consultation de {agent} : {count} questions…","Consulting {agent}: {tool} (+{count} more)…":"Consultation de {agent} : {tool} (+{count} autres)…","Consulting {agent}: {tool}…":"Consultation de {agent} : {tool}…","Consulting {agent}: writing the answer…":"Consultation de {agent} : rédaction de la réponse…","Consulting {count} agents…":"Consultation de {count} agents…","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 {icon}.":"Déposez une conversation ici ou démarrez-en une avec {icon}.","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} に問い合わせ中…","Consulting {agent}: {count} questions…":"{agent} に問い合わせ中: {count} 件の質問…","Consulting {agent}: {tool} (+{count} more)…":"{agent} に問い合わせ中: {tool}(他 {count} 件)…","Consulting {agent}: {tool}…":"{agent} に問い合わせ中: {tool}…","Consulting {agent}: writing the answer…":"{agent} に問い合わせ中: 回答を作成しています…","Consulting {count} agents…":"{count} 件のエージェントに問い合わせ中…","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 {icon}.":"ここに会話をドロップするか、{icon} で新しく開始してください。","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 ne(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?te[n]:void 0}(t):void 0;return t=>{const r=e?.(t);return r&&r!==t?r:n?.[t]??t}}const re=e=>"up"===e?"positive":"negative";function oe(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function ae(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function se(e,t,n){return Z(e,t,n,"feedback")}async function ie(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:ae(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 ce=e=>void 0!==e&&/[\w-]/.test(e),le=/^[\w-]+$/;function de(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const o=r[1].toLowerCase();ce(e[r.index-1])||t.includes(o)||t.push(o),r=n.exec(e)}return t}function ue(e,t){if(0===e.length)return e;const n=new Set(de(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function pe(e,t){if(0===e.length)return[];const n=[];for(const r of de(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 he(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&&le.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 me(e,t,n){return Z(e,t,n,"conversationReferences")}const ge={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 ve(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 we(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function ye(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 be(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 xe(e,t,n,r,o){return!!o||(!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e))}function ke(e,t,n){return!n&&!(t&&e.conversations.some(e=>e.conversationId===t))}const Ne=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&t.length<=500?t:null};async function Ce(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 Ne(e.message)??Ne(e.detail)}return Ne(t)}(await e.json())}catch{return null}}function Se(e){return e?JSON.stringify(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0)):""}function Ie(){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 Te=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function Ae(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 Te){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 _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.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 Ee=["presentation","report","video"],Me=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function Le(e){if(!e||"object"!=typeof e)return;const t=e,n=Ee.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:Me(t.slide_count),sectionCount:Me(t.section_count),sceneCount:Me(t.scene_count),durationMs:Me(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:Me(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function Re(e){if(!Array.isArray(e))return;const t=e.map(Le).filter(e=>!!e);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.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 ze(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 je(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 Oe=e=>"string"==typeof e&&e?e:void 0,Pe=e=>e&&"object"==typeof e&&!Array.isArray(e)?e:void 0;function Ue(e){const t=Oe(e.agent_name);if(!t)return;const n=Pe(e.inner);let r=n;for(let e=0;"consult_progress"===r?.status&&e<8;e+=1)r=Pe(r.inner);const o=Array.isArray(r?.tools)?r.tools.filter(e=>"string"==typeof e):void 0,a=Oe(e.agent_id)??t;return{consultId:Oe(e.consult_id)??a,agentId:a,agentName:t,status:Oe(r?.status),tools:o,answering:"streaming"===n?.status||"composing"===n?.status}}function He(e){if("string"==typeof e)return e?{agentName:e}:void 0;if(!e||"object"!=typeof e)return;const t=e,n={agentId:Oe(t.agent_id),agentName:Oe(t.agent_name)??Oe(t.name),agentIcon:Oe(t.agent_icon)};return n.agentId||n.agentName?Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)):void 0}function qe(e,t){const n=e.type;if("error"===n||"cancelled"===n){const t=Oe(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:Oe(e.reason)};if("approval_resolved"===n)return{action:"approval_resolved"};if("folded_into_active_turn"===n)return{action:"folded",turnId:Oe(e.turn_id)};if("conversation_title"===n){const t=Oe(e.title);return t?{action:"conversation_title",conversationId:Oe(e.conversation_id),title:t}:{action:"noop"}}if("user_message"===n){const[t]=Fe([e.message]);return t&&"user"===t.role?{action:"user_message",message:{...t,id:We(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("consult_progress"===n)return{action:"status",status:n,consult:Ue(e)};if("wait_start"===n)return{action:"status",status:"wait_start",waitSeconds:"number"==typeof e.seconds&&e.seconds>0?e.seconds:void 0,waitReason:Oe(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=Ae(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=je(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:_e(e.attachments),artifacts:Re(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:De(e.tool_call_trace),transferChain:ze(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:Ae(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0,intermediate:!0===e.intermediate||void 0,answeredBy:He(e.answered_by),mentionFailed:!0===e.mention_failed||void 0,raw:{...e}}:{action:"noop"}}function We(e,t=Ie()){return e?`msg-${e}`:t}function Be(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 Fe(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?He(r.answered_by):void 0,i="string"==typeof r.id&&r.id?r.id:void 0;t.push({id:We(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?Be(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:_e(r.attachments),artifacts:"assistant"===r.role?Re(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:De(r.tool_call_trace),transferChain:ze(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0,raw:{...r}})}),t}function Ve(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 Ke(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 Ge(){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 Je(e,t){return null!==e&&"function"==typeof t}function Ye(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const Xe=(e,t)=>{const n=t??Ye();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 Ze(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const Qe=/^(current-password|new-password|one-time-code|cc-)/;function et(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 tt(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 nt(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=Xe(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(tt(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 rt(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 ot(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&&rt(r)}async function at(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(ot(e))return{ok:!0};if(r){if(et(e),await(o=()=>ot(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&&!Ze(e.target)&&Array.from(e.addedNodes).some(e=>!Ze(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,()=>et(e)))return{ok:!0};var o,a;return n?.aborted?{ok:!1,error:"aborted"}:nt(e,void 0,t)}const st=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function it(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=Xe(e.path,Ye(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const a=t.get(e.ref);return a&&a.isConnected?rt(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 at(a,Ye(r??a.ownerDocument),o):"click"===e.type?nt(a,n,Ye(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=>Qe.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=>st.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&&tt(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 ct="[truncated]",lt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function dt(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(ut(t))return!0;return!1}function ut(e){const t=e.getAttribute("role");if(t&&lt.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 pt(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function ht(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(Nt(r)||bt(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?ht(r):` ${ht(r)} `}return n}function mt(e){return(e??"").replace(/\s+/g," ").trim()}const gt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function ft(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=mt(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const o=mt(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=mt(Array.from(s.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||mt(s.textContent))return e||mt(s.textContent)}const i=e.tagName.toLowerCase(),c=(e.getAttribute("type")||"").toLowerCase();if("input"===i&&["submit","reset","button"].includes(c)){const t=mt(e.getAttribute("value"));if(t)return t;if("button"!==c)return"submit"===c?"Submit":"Reset"}const l=mt(e.getAttribute("alt"))||mt(e.querySelector("img[alt]")?.getAttribute("alt"));if(l)return l;const d=bt(e)?"":mt(ht(e));if(gt.has(t)&&d)return d;const u=mt(e.getAttribute("placeholder"));if(u)return u;const p=mt(e.getAttribute("title"));return p||d}function vt(e){return JSON.stringify(e.slice(0,80))}function wt(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 yt=/^(current-password|new-password|one-time-code|cc-)/;function bt(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>yt.test(e))}function xt(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(bt(e))return null;const n="value"in e?String(e.value??""):mt(ht(e));return n||null}function kt(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 Nt(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 Ct="filigranChatConversationId",St="filigranChatLegacyChatId",It="filigranChatAgentSlug",Tt="filigranChatSidebarWidth",At="filigran-chat-collapsed-workspaces",_t="filigranChatDraft:",Et="filigranChatDraftRefs:";function Mt(e,t){return e?`${e}:${t}`:t}function Lt(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch{return null}}function Rt(e,t){try{return Lt(e)?.getItem(t)??null}catch{return null}}function Dt(e,t,n){try{const r=Lt(e);if(!r)return;n?r.setItem(t,n):r.removeItem(t)}catch{}}class $t extends Error{constructor(){super("the event stream fell silent"),this.name="SseStreamSilentError"}}async function zt(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 $t;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 jt(e,...t){if(e)try{return e(...t)}catch(e){return void console.error("A chat panel host callback threw",e)}}const Ot=e=>e.some(e=>"error"===e.uploadStatus);function Pt(e){if(e.slug&&/^[\w-]+$/.test(e.slug))return e.slug;return e.name.toLowerCase().replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")||null}function Ut(e,t){const n=[];for(const r of de(t))for(const t of e)t.key.toLowerCase()!==r||n.includes(t.agentId)||n.push(t.agentId);return n}const Ht=r({fetch:(e,t)=>globalThis.fetch(e,t),sessionEnded:()=>{}}),qt=Ht.Provider;function Wt(){return o(Ht).fetch}const Bt=(e,t)=>Mt(e,`${_t}${t??"new"}`),Ft=(e,t)=>Mt(e,`${Et}${t??"new"}`);function Vt(e,t){try{const n=JSON.parse(Rt("session",Ft(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 Kt(e,t,n,r){Dt("session",Bt(e,t),n),Dt("session",Ft(e,t),r.length>0?JSON.stringify(r):null)}function Gt(e,t){const n=Rt("session",Bt(e,t))??"";return{text:n,refs:ue(Vt(e,t),n)}}const Jt=9e5,Yt=Jt,Xt=new Set(["wait_status","tool_progress"]),Zt=new Set(["tool_progress","tool_heartbeat","wait_status","thinking_text"]),Qt=new Set(["thinking","analyzing","llm_step","tool_start","composing","streaming","stream_retract"]);const en=new Set(["status","stream","done","approval_required","error","cancelled"]),tn=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 nn(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 rn=["toolNames","toolCallCount","iterations","attachments","artifacts","reasoning","toolCallTrace","transferChain","isTruncated","agentName","answeredBy","mentionFailed","feedback"],on=Symbol("sentText");function an(e,t){return t===e.content?e:{...e,[on]:t}}function sn(e){return e[on]??e.content}const cn=e=>`${e.role}\0${"user"===e.role?sn(e):e.content}`,ln=e=>`${e.role}\0${e.content}`;function dn(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 rn)void 0!==t[e]&&(r[e]=t[e]);return n}function un(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 pn=(e,t)=>[e,t].filter(Boolean).join("\n\n"),hn=(e,t)=>void 0!==e.displayText||void 0!==t.displayText?pn(e.displayText??e.text,t.displayText??t.text):void 0;function mn(e,t){const n=new Set(e.refs.map(e=>e.conversationId)),r=new Set(e.mentions.map(e=>e.agentId));return{text:pn(e.text,t.text),draft:pn(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:hn(e,t)}}const gn={text:"",draft:"",files:[],refs:[],mentions:[]};function fn(e){return{...e.reduce(mn,gn),parts:e}}function vn(e,t){return fn([...e?.parts??[],t])}function wn(e){for(const t of e)jt(t.onNotSent)}function yn(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 bn(e){return"error"===e.action||"cancelled"===e.action||"done"===e.action&&!e.intermediate?e:null}function xn(e){return("error"===e.action||"cancelled"===e.action)&&!!e.provisional}function kn(e){const t=jt(e);return t&&"object"==typeof t?t:{}}const Nn=52428800;function Cn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t].serverId;if(n)return n}return null}function Sn(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 In({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:g,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=Wt(),A="legacy"===n,[_,E]=a([]),[M,L]=a(!1),[R,D]=a(null),[$,z]=a(null),j=void 0!==g,O=Mt(m,Ct),P=Mt(m,St),[U,H]=a(()=>j?g??null:Rt("local",O)),[q]=a(()=>Gt(m,U)),[W,B]=a(q.text),[F,V]=a(q.refs),[K,G]=a([]),[J,Y]=a([]),[X,Q]=a(null),[ee,te]=a(null),[ne,re]=a(null),[oe,ae]=a(!1),[se,ie]=a(null),[ce,le]=a(!1),[he,ge]=a(0),[fe,ve]=a(0),[we,ye]=a(()=>Rt("local",P)),be=s(!1),xe=s(null),ke=s(null),Ne=s(null),Te=s(!1),Ae=s(null),_e=s(null),Ee=s(null),Me=s(null),Le=s(null),Re=s(!1),[De,$e]=a(null),ze=s(De);ze.current=De;const[Oe,Pe]=a(null),Ue=s(!1),He=s(new Map),Be=s(null),[Fe,Ye]=a(!1),Xe=s(null),Qe=s(!1),et=s("off"),tt=s(0),nt=s(null),rt=s(null),ot=s(null),at=s(null),[st,lt]=a(!1),gt=e=>{const t=at.current?.readBack;t&&e!==at.current&&window.clearTimeout(t.timer),at.current=e,lt(null!==e)},yt=s(_);yt.current=_;const bt=s(0),[It,Tt]=a(()=>Ie()),At=s(null),_t=s(null),Et=s(!1),Lt=s(0),$t=s(null),Pt=s(null),Ht=s(null),qt=()=>{null!==At.current&&window.clearTimeout(At.current),At.current=null,_t.current=null,Et.current=!1,Ht.current&&window.clearTimeout(Ht.current.timer),Ht.current=null;const e=Pt.current;Pt.current=null,null!==e&&E(t=>t.filter(t=>t.id!==e||t.content))},Bt=e=>{Be.current&&window.clearTimeout(Be.current.timer);const t={timer:0,relayed:e};return t.timer=window.setTimeout(()=>Ft(t),5e3),Be.current=t,Ye(!0),t},Ft=e=>{const t=Be.current;!t||e&&e!==t||(window.clearTimeout(t.timer),Be.current=null,Ye(!1))},Vt=()=>{Be.current?.relayed&&Ft()},rn=s(v);rn.current=v;const on=s(w);on.current=w;const pn=s(y);pn.current=y;const hn=s(b);hn.current=b;const mn=s(S);mn.current=S;const gn=s(I);gn.current=I;const In=s(U),Tn=s(M);Tn.current=M;const An=e=>{Tn.current&&D(e),Tn.current=!1,L(!1),Ue.current||Pe(null)},_n=s(l);_n.current=l;const En=s(new Map),Mn=s(d);Mn.current=d;const Ln=s(o);Ln.current=o;const Rn=s(null),Dn=s(!1),$n=s(null),zn=s(0),[jn]=a(Ge),On=s(null),[Pn,Un]=a(null),Hn=s(new AbortController),qn=Number.isFinite(p)&&p>0?Math.floor(p):10,Wn=Number.isFinite(h)&&h>0?h:Nn;i(()=>{V(e=>ue(e,W)),G(e=>function(e,t){if(0===e.length)return e;const n=new Set(de(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}(e,W))},[W]);const Bn=c(e=>{G(t=>{return r=e,(n=t).some(e=>e.agentId===r.agentId)?n:[...n,r];var n,r})},[]),Fn=c(e=>{V(t=>{return r=e,(n=t).some(e=>e.conversationId===r.conversationId)?n:[...n,r];var n,r})},[]),Vn=({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]})},Kn=()=>A||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,Gn=()=>Z(e,t,n,"approve"),Jn=s(Gn);Jn.current=Gn;const Yn=async e=>{const t=ur(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:je(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Xn=c(()=>{be.current=!1,bt.current+=1,ge(bt.current)},[]),Zn=()=>{if(null===_t.current)return;const e=Cn(yt.current);if(qt(),!mr())return void Ar("stopped");Xn();const t=window.setTimeout(()=>{Ht.current?.timer===t&&(Ht.current=null,Ar("stopped"))},1e4);Ht.current={from:bt.current,shownUpTo:e,timer:t}},Qn=s(Zn);Qn.current=Zn;const er=()=>{null!==At.current&&window.clearTimeout(At.current),Et.current=!1,At.current=window.setTimeout(()=>{At.current=null,_e.current||Qn.current()},Math.max(0,Lt.current-Date.now()))},tr=()=>{null===_t.current||_e.current||Et.current||(Et.current=!0,null!==At.current&&window.clearTimeout(At.current),At.current=window.setTimeout(()=>{At.current=null,_e.current||Qn.current()},5e3))},nr=s(tr);nr.current=tr;const rr=()=>{null!==_t.current&&!_e.current&&Et.current&&er()},or=s(rr);or.current=rr;const ar=()=>A||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,sr=()=>Z(e,t,n,"cancel"),ir=()=>Z(e,t,n,"skipWait"),cr=Z(e,t,n,"events"),lr=!!cr,dr=Z(e,t,n,"pendingApprovals"),ur=e=>dr?`${dr}/${encodeURIComponent(e)}/pending-approvals`:null,pr=()=>lr?{"X-Chat-Client-Id":It}:{},hr=(e,t,n)=>T(e,{method:"POST",headers:{"Content-Type":"application/json",...Ln.current??{},...pr()},body:JSON.stringify({conversation_id:t,...n})}),mr=()=>A||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`,gr=s(f);gr.current=f;const fr=c((e,{notify:t=!0}={})=>{const n=In.current!==e;In.current=e,H(e),j||Dt("local",O,e),n&&t&&gr.current?.(e)},[j,O]),vr=async e=>{if(In.current)return In.current;if(jn.pending)return jn.pending;const t=mr();return t?jn.run(async(n,r)=>{const a=On.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,fr(c),On.current=null,Un(null)),c}):null},wr=async(e,t,n)=>{const r=ar(),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]},yr=e=>{if(!e||0===e.length||!ar())return;const t=Array.from(e).map(e=>({file:e,tempId:Ie()}));let n=[];Y(e=>{const r=e.length,o=e.reduce((e,t)=>e+t.size,0),a=qn-r;if(a<=0)return e;let s=Wn-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=Hn.current.signal;for(const{file:t,tempId:o}of n)(async()=>{try{const n=await vr(r);if(!n)return void Y(e=>e.map(e=>e.fileId===o?{...e,uploadStatus:"error"}:e));const a=await wr(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)},br=async(e,t,n)=>{const r=Jn.current(),o=n??In.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",...Ln.current??{},...pr()},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(!Je(r,Mn.current))return s("page_actions_not_supported");z(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await it(t,En.current,Mn.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=>!Ze(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=mt(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(Nt(t))continue;const e=ut(t),n=pt(t);let r=null;if(e){const n=`e${d.size+1}`,o=xt(t,e),i=wt(t);if(r=`[${n}] ${e} ${vt(ft(t,e))}${i.length?` (${i.join(", ")})`:""}${o?` = ${vt(o)}`:""}${kt(t)}`,l+r.length+1>a)return s=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${vt(mt(ht(t)))} (level ${n})`,l+r.length+1>a))return s=!0,!1;if(r&&(c.push(r),l+=r.length+1),(!e||dt(t))&&!u(t))return!1}return!0};return e.body&&!s&&u(e.body),s&&c.push(ct),{text:c.join("\n"),url:r,title:o,refs:d}}(document);En.current=e.refs,i={text:e.text,url:e.url,title:e.title}}catch(e){En.current=new Map,c=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await T(r,{method:"POST",headers:{"Content-Type":"application/json",...Ln.current??{},...pr()},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)}},xr=(e,t)=>{let n=e;const r=[e];let o="",a=!1,s=!1,i=null;const c=new Map,l=new Set,d=()=>{c.clear(),l.clear()};let p=!0;const h=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}))}),m=()=>{if(!a)return;h.flush(),a=!1,s=!1,o="",d(),n=Ie(),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:h,apply:e=>{switch(tt.current+=1,e.action){case"status":return(e=>{m();const t=n;if(e.contextUsage&&te(e.contextUsage),"thinking_text"===e.status)return void h.thinking(e.thinkingContent??"");h.flush();const r="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;if((e.resumed||Qt.has(e.status))&&(d(),p=!0===e.resumed||"tool_start"===e.status),e.resumed)o="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),z({status:"thinking",elapsedS:e.elapsedS,elapsedStartMs:r});else if("stream_retract"===e.status)o="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),z(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}));else if("tool_heartbeat"===e.status)z(t=>t?{...t,elapsedS:e.elapsedS,elapsedStartMs:r}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:r});else if("consult_progress"===e.status){const t=e.consult;if(!t||!p)return;const{consultId:n,agentId:r,agentName:o,status:a}=t;if(t.answering)c.delete(n),l.add(n);else if(a&&!Zt.has(a))l.delete(n),c.delete(n),c.set(n,{agentId:r,agentName:o,status:a,tools:t.tools});else if(!c.has(n)){if(l.has(n))return;c.set(n,{agentId:r,agentName:o,status:"thinking"})}let s={agentName:o,status:a??"thinking",answering:t.answering};const i=new Set;for(const e of c.values())s=e,i.add(e.agentId);const d={agentName:s.agentName,status:s.status,tools:s.tools,answering:s.answering,count:Math.max(c.size,1),agents:Math.max(i.size,1)};z(e=>{return"wait_start"===e?.status||"consulting"===e?.status&&(t=e.consult,n=d,t&&t.agentName===n.agentName&&t.status===n.status&&t.count===n.count&&t.agents===n.agents&&t.answering===n.answering&&(t.tools??[]).join("\n")===(n.tools??[]).join("\n"))?e:{status:"consulting",consult:d,thinkingContent:e?.thinkingContent,elapsedS:e?.elapsedS,elapsedStartMs:e?.elapsedStartMs};var t,n})}else"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&&Xt.has(e.status)?t:{status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent})})(e),"continue";case"stream":return m(),o+=e.content,h.text(),"continue";case"done":return(e=>{h.flush(),a=!0,e.intermediate||(s=!0),re(null),ie(null),Nr(e,t);const r=n,i=e.content||o,c=new Date;Cr(r,e.messageId,t=>nn(t,e,i,c))})(e),t&&!e.intermediate?"end":"continue";case"approval_required":return h.flush(),Rn.current=e.conversationId??In.current,Dn.current=!1,ie(null),re(e.proposals),z(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"}),"continue";case"error":{m(),h.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":{h.flush(),i="cancelled";const e=n;return E(t=>t.map(t=>t.id===e?{...t,stopped:!0}:t)),"end"}case"session_ended":{h.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"}},kr=c(()=>Q(null),[]),Nr=(e,t)=>{e.conversationId&&!t&&fr(e.conversationId),e.contextUsage&&te(e.contextUsage),e.transferAgentId&&e.transferAgentName&&Q({id:e.transferAgentId,name:e.transferAgentName})},Cr=(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))},Sr=(e,t,n)=>{const r=bn(t),o=r?.messageId;if(!r||!o)return!1;"done"!==r.action||Tn.current||Nr(r,n);const a=new Date;return Cr(e,o,e=>"done"===r.action?nn(e,r,r.content||e.content,a):{...e,serverId:o,raw:r.raw??e.raw}),!0},Ir=(e,t,n,r)=>{let o;try{o=e(t,n)}catch{o=void 0}return jt(on.current,t,function(e,t){const n={relayed:e};if(!t)return n;const r=bn(t);return r&&xn(r)?n.end="provisional":r?.messageId&&(n.end="stored"),"status"===t.action&&t.resumed&&(n.replayed=!0),n}(r,o)),"session_ended"===o?.action&&jt(pn.current,o.reason),o},Tr=e=>{switch(e.action){case"user_message":{const t=e.message,n=Me.current?.openAnswerId()??Pt.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||sn(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):un(e,t,n)}),!0}case"conversation_title":return hn.current?.(e.conversationId??In.current,e.title),!0;case"approval_resolved":return re(null),ie(null),!0;default:return!1}},Ar=e=>{Vr(),An(e),z(null),re(null),ie(null),Rn.current=null,Dn.current=!1,$n.current=In.current},_r=async a=>{const s=!a,i=a?a.text:W,c=s?W:a?.draft??"",l=s?J:a?.files??[];if(!i.trim()&&0===l.length)return"dropped";const d=s?"composer":a?.source??"host",p=!Tn.current&&(null!==Be.current||null!==at.current),h=Tn.current||null!==at.current,m=!a?.decided&&h&&mn.current?{text:i,source:d,extras:a?.extras,displayText:a?.displayText}:void 0,g=yn(i,a?.decided?void 0:jt(mn.current,{text:i,source:d,turnRunning:h}),a?.displayText);if(!g)return"dropped";Ue.current=!1,Pe(null);const f=g.extras,v=a?.extras||f?{...a?.extras,...f}:void 0,w=g.text,y=a?.decided?a.displayText?.trim()||w:g.displayText,b=y!==w?y:void 0,x=s?me(e,t,n)?pe(F,W):[]:a?.refs??[],S=s?C?K:[]:a?.mentions??[],I=Ut(S,w);if(!w&&0===l.length)return"dropped";const _=()=>{s&&(B(""),V([]),G([]),Y([]))};if(Tn.current||p){if(Ot(l))return"dropped";const e=l.every(e=>"done"===e.uploadStatus);if(!p&&!!Kn()&&!!In.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=Kn(),i=In.current;if(!s||!i)return{result:"failed"};const c=an({id:Ie(),role:"user",content:a,timestamp:new Date,files:t.length>0?t:void 0},e),l=Me.current?.openAnswerId()??Pt.current;E(e=>un(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??{},...pr()},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 Ce(t))}catch{E(e=>e.filter(e=>e.id!==c.id))}return null!==n&&Vn({draft:n,files:t,refs:[],mentions:[]},{before:!0}),{result:"failed",detail:u}})(w,l,s?c:null,y);return"ended"===e.result?($e(e=>vn(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&&(Ue.current=!0,Pe(u("This message will be read with your next one."))),a?.onSteered?.(e.turnId,e.unanswered),"steered"):(e.detail&&Pe(e.detail),"failed")}return(N||p)&&e?(_(),$e(e=>vn(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=an({id:Ie(),role:"user",content:y,timestamp:new Date,files:l.length>0?[...l]:void 0,conversationRefs:x.length>0?x:void 0},w),R=Ie();E(e=>[...e,M,{id:R,role:"assistant",content:"",timestamp:new Date}]),_(),Tn.current=!0,L(!0),z({status:"thinking"});const D=jn.generation,$=xr(R,!1);Ne.current=$.deltas,Me.current=$,Re.current=!1,Te.current=!0,Ae.current=null,Qe.current=!1;let j=!1,O=!1,U=!1,H=!1,q=!1,X=!1,Z=null;const Q=()=>{if(!lr||!In.current||!Ae.current||$.ended())return!1;j=!0;const e=$.doneReceived()?Ie():$.currentAssistantId();return E(t=>[...t.filter(t=>t.id!==e),{id:e,role:"assistant",content:"",timestamp:new Date}]),Pt.current=e,_t.current=Ae.current,Ae.current=null,Tt(Ie()),z(e=>"cancelling"===e?.status?e:{status:"reconnecting"}),Lt.current=Date.now()+($t.current?Yt:15e3),er(),!0},ee=new AbortController;ke.current?.abort();const te=new AbortController,ne=()=>{X||(X=!0,$.deltas.close(),Ne.current===$.deltas&&(Ne.current=null),Me.current===$&&(Me.current=null),Te.current=!1,ke.current===te&&te.abort(),xe.current===ee&&(xe.current=null),jn.generation!==D||j||Ar(U?"failed":$.outcome()))};try{xe.current=ee,ke.current=te;const s=(M.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),i=!!(sr()||ir()||lr);if(!In.current&&(On.current||i)){const e=jn.generation,t=await vr(r);if(jn.generation!==e)return"dropped";t||(On.current=null,Un(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??Ie(),runId:Ie(),messages:[{id:Ie(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={...Object.fromEntries(Object.entries(n.extras??{}).filter(([e])=>!tn.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:In.current,agentSlug:r,pageContext:_n.current,supportsToolApproval:null!==Gn(),referencedConversationIds:x.map(e=>e.conversationId),supportsPageActions:Je(Gn(),Mn.current),extras:{...kn(rn.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??{},...pr()},body:JSON.stringify(c),signal:ee.signal});if(!l.ok||!l.body){const e=l.ok?null:await Ce(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 Ve;case"ag-ui":return Ke;default:return qe}}(n);if(await zt(l.body,e=>{const t=Ir(d,e,$.ctx,!1);if(!t)return!0;try{return q?jn.generation===D&&(!!Tr(t)||!Sr($.currentAssistantId(),t,!1)):(Qe.current||Me.current!==$||(Qe.current=!0,"resend"===et.current&&(et.current="off",null!==Ee.current&&Gr(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):!!Tr(t)||("set_chat_id"===t.action?(ye(t.chatId),Dt("local",P,t.chatId),!0):"page_action_required"===t.action?($.deltas.flush(),br(t.actionId,t.pageAction,t.conversationId),!0):(("session_ended"===t.action||bn(t))&&(H=!0),"end"!==$.apply(t)||!!xn(t)&&($.deltas.flush(),q=!0,i&&(Z=Bt(!1)),Xe.current=ee,ne(),!0))))}catch{return!0}},{idleTimeoutMs:()=>lr&&In.current&&Ae.current?45e3:void 0}),$.deltas.flush(),!j&&!H&&Q())return"sent";if(!j&&!$.ended()&&$.accumulated()&&!$.doneReceived()){const e=$.currentAssistantId(),t=$.accumulated();E(n=>n.map(n=>n.id===e?{...n,content:t||u("No response.")}:n))}}catch(e){if($.deltas.close(),X)return"sent";if(e instanceof DOMException&&"AbortError"===e.name)return O?"sent":"dropped";const t=$.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&&Ft(Z),Xe.current===ee&&(Xe.current=null)}return O?"sent":"failed"},Er=()=>{const e=_e.current;if(!e)return;_e.current=null,e.renderer.deltas.flush(),e.renderer.deltas.close(),Ne.current===e.renderer.deltas&&(Ne.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))),Ar(e.renderer.outcome())},Mr=s(Er);Mr.current=Er;const Lr=()=>{const e=_e.current;if(!e)return;const t=e.renderer.doneReceived()?null:e.renderer.currentAssistantId();Er(),gt({turnId:e.turnId,shownUpTo:Cn(yt.current)}),t&&E(e=>e.filter(e=>e.id!==t))},Rr=s(Lr);Rr.current=Lr;const Dr=e=>{at.current&&(gt(null),e&&D(e))},$r=s(Dr);$r.current=Dr;const zr=()=>{rt.current&&window.clearTimeout(rt.current.timer),rt.current=null},jr=()=>{zr();const e=_e.current;if(e){const t=Cn(yt.current);Er(),gt({turnId:e.turnId,shownUpTo:t})}const t=at.current;if(!t||t.readBack)return;if(!mr())return void Dr("stopped");Xn();const n=window.setTimeout(()=>{at.current===t&&Dr("stopped")},1e4);t.readBack={from:bt.current,timer:n}},Or=s(jr);Or.current=jr;const Pr=()=>{const e=_e.current,t=at.current;if(!e&&t&&(t.readBack||rt.current?.turn===t))return;zr();const n=e??t;if(!n)return;const r=window.setTimeout(()=>{rt.current=null,(e?_e.current===e:at.current===t)&&jr()},5e3);rt.current={turn:n,timer:r}},Ur=s(Pr);Ur.current=Pr;const Hr=s(new Set),qr=e=>{let t=_e.current;const n=Ir(qe,e,t?.renderer.ctx??{hasUsedTools:!1,activeNodeId:""},!0);if(!n)return;if(Tr(n))return;if("session_ended"===n.action)return Er(),Dr("stopped"),void(null===_t.current&&null===Ht.current||Te.current||(qt(),Ar("stopped")));if(!en.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(Hr.current.has(o)||(Hr.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=He.current.get(r);if(void 0!==a)return void(Sr(a,n,!0)&&(He.current.delete(r),Vt()));if(Te.current||r===Ae.current)return;if(r===Le.current)return;const s=rt.current;if(s)if(zr(),t&&t===s.turn&&r!==t.turnId){const e=t.renderer.doneReceived()?null:t.renderer.currentAssistantId();Er(),e&&E(t=>t.filter(t=>t.id!==e)),Xn(),t=null}else t&&t===s.turn&&(ot.current=t.renderer,Xn());let i=t;if(i&&i.turnId!==r&&(Er(),i=null),!i){const t=at.current,o=t?.turnId===r,a=r===_t.current;if(!("cancelled"!==n.action&&"error"!==n.action||o||a))return void(t&&jr());t&&!o&&(Dr(),Xn());const s=Ie();E(e=>[...e,{id:s,role:"assistant",content:"",timestamp:new Date}]),i={turnId:r,renderer:xr(s,!0)},_e.current=i,Vt(),Ne.current=i.renderer.deltas,Me.current=i.renderer,gt(null);const c=a||o;!0===e.resumed&&c?(ot.current=i.renderer,Xn()):!a||"cancelled"!==n.action&&"error"!==n.action||Xn(),qt(),Re.current=!1,Tn.current=!0,L(!0),z({status:"thinking"})}if("end"===i.renderer.apply(n)){if(xn(n)){const e=He.current;for(e.set(i.turnId,i.renderer.currentAssistantId());e.size>20;)e.delete(e.keys().next().value);Bt(!0)}Er()}},Wr=s(qr);Wr.current=qr;const Br=()=>{const e=ze.current;e&&(gn.current?.(e.text,"cancelled"),wn(e.parts)),$e(null)},Fr=(e,t,n=!1)=>{const r="string"==typeof e&&e?e:null;On.current=r,Un(r),Ne.current?.close(),Ne.current=null,xe.current?.abort(),xe.current=null,ke.current?.abort(),ke.current=null,Hn.current.abort(),Hn.current=new AbortController,jn.abandon(),_e.current?.renderer.deltas.close(),_e.current=null,zr(),ot.current=null,gt(null),He.current.clear(),Xe.current?.abort(),Xe.current=null,Ft(),Te.current=!1,Br(),Vr(),qt(),Ue.current=!1,An("stopped"),E([]),n||(B(""),V([]),G([]),Y([])),z(null),Q(null),te(null),re(null),ie(null),le(!1),Rn.current=null,Dn.current=!1,$n.current=null,be.current=!1,A?(ye(null),Dt("local",P,null)):fr(null,{notify:t})},Vr=()=>{null!==Ee.current&&window.clearTimeout(Ee.current),Ee.current=null,et.current="off",nt.current=null},Kr=(e=!0)=>{Vr();const t=Me.current;Me.current=null;const n=_e.current,r=n?.turnId??_t.current;r&&(Le.current=r),qt(),Ne.current?.flush(),Ne.current?.close(),Ne.current=null,xe.current?.abort(),xe.current=null,ke.current?.abort(),ke.current=null,_e.current=null,An("stopped"),z(null),re(null),ie(null),le(!1),Rn.current=null,Dn.current=!1,En.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)))},Gr=e=>{const t=sr(),n=In.current;if(!t||!n)return;const r=Te.current&&!Qe.current;r&&(et.current="asked");const o=()=>Ee.current===e;hr(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",Gr(e)):et.current="resend":et.current="off");if(!a)return;return Kr(),void Xn()}const n=await Ce(t);if(!o())return;const a=nt.current;Vr(),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),Pe(n??u("The response could not be stopped. Try again."))}).catch(()=>{o()&&Kr()})},Jr=ir(),Yr=U&&x===U?(Xr=U,cr?`${cr}/${encodeURIComponent(Xr)}/events?client_id=${encodeURIComponent(It)}`:null):null;var Xr;$t.current=Yr;const Zr=Se(o),Qr=s(Zr);Qr.current=Zr;const[eo,to]=a(null),[no,ro]=a(0);i(()=>{eo&&eo.url===Yr&&eo.headersKey!==Zr&&(to(null),ro(e=>e+1))},[eo,Yr,Zr]),i(()=>{if(!Yr)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=Qr.current,r=await T(Yr,{headers:{...Ln.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||to({url:Yr,headersKey:t}),void(e||(Or.current(),Qn.current()));if(!r.ok||!r.body)return void(e||[502,503,504].includes(r.status)||Qn.current());s&&Ur.current(),nr.current(),s=!0,l=Date.now(),await zt(r.body,e=>{n=0;try{Wr.current(e)}catch{}},{idleTimeoutMs:45e3})}catch{}finally{if(t=!1,null===l||e||or.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(),Rr.current())},d=()=>{"hidden"!==document.visibilityState?(null!==a&&window.clearTimeout(a),a=null,"visible"===document.visibilityState&&(at.current&&Ur.current(),t||(null!==r&&window.clearTimeout(r),n=0,i&&(i=!1,Xn()),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),Mr.current(),$r.current()}},[Yr,It,no,Xn]);const oo=s([]),[ao,so]=a(0),io=e=>{oo.current.push(e),so(e=>e+1)};i(()=>{for(const e of oo.current.splice(0))gn.current?.(e,"returned")},[ao]),i(()=>{if(M||st)return;if(Re.current&&(Re.current=!1,De))return $e(null),wn(De.parts),De.draft||0!==De.files.length?(io(De.text),void Vn(De,{before:!0})):void gn.current?.(De.text,"dropped");if(Fe||!De)return;$e(null);let e=!1;const t=t=>{e||(e=!0,gn.current?.(De.text,t))},n=[],r=[];for(const e of De.parts){const{asked:t}=e;if(!t){n.push(e);continue}const o=yn(t.text,jt(mn.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)}wn(r);const o=r.filter(e=>e.draft||e.files.length>0);for(const e of o)Vn(e,{before:!1});if(0===n.length)return void(o.length>0?io(De.text):t("dropped"));const{text:a,draft:s,files:i,refs:c,mentions:l,extras:d,displayText:u}=fn(n);co.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)jt(e.onSent)},onNotSent:()=>wn(n)}).then(e=>{if("held"===e)return;const r="sent"===e||"steered"===e;t(r?"sent":"failed"===e?"failed":"dropped"),r||wn(n)},()=>{t("failed"),wn(n)})},[M,st,Fe,De]);const co=s(_r);co.current=_r,i(()=>{const e=window.setTimeout(()=>{Kt(m,U,W,F)},300);return()=>window.clearTimeout(e)},[W,U,F,m]),i(()=>()=>{Ne.current?.close(),ke.current?.abort(),Xe.current?.abort(),Be.current&&window.clearTimeout(Be.current.timer),null!==At.current&&window.clearTimeout(At.current),Ht.current&&window.clearTimeout(Ht.current.timer),rt.current&&window.clearTimeout(rt.current.timer),Br()},[]);const lo=s({conversationId:U,inputValue:W,conversationRefs:F});lo.current={conversationId:U,inputValue:W,conversationRefs:F},i(()=>()=>{const{conversationId:e,inputValue:t,conversationRefs:n}=lo.current;Kt(m,e,t,n)},[]),i(()=>{const e=U;if(!e||M)return;if($n.current===e)return;ur(e)&&Gn()&&($n.current=e,(async()=>{const t=await Yn(e);t?.proposals&&(In.current!==e||Tn.current||(Rn.current=e,Dn.current=!0,ie(null),re(t.proposals)))})())},[U,M]),i(()=>{if(!ne?.length||!Dn.current)return;const e=Rn.current,t=e?ur(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=Rn.current;if(!e)return void le(!1);if(Date.now()>=zn.current)return le(!1),void Xn();let t=!1;const n=window.setTimeout(async()=>{const n=await Yn(e);if(!t){if(n)return n.proposals?(Dn.current=!0,ie(null),re(n.proposals),void le(!1)):n.turnRunning?void ve(e=>e+1):(le(!1),void Xn());ve(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[ce,fe,Xn]);const uo=M&&null!==Kn()&&null!==U;return{messages:_,inputValue:W,setInputValue:B,isLoading:M,turnRunning:M||st,sendsHeld:!M&&(Fe||st),turnEnd:R,agentStatus:$,attachedFiles:J,conversationId:U,contextUsage:ee,transferredAgent:X,forgetTransfer:kr,canSteer:uo,pendingApprovals:ne,isSubmittingApproval:oe,approvalError:se,submitApprovalDecisions:async e=>{const t=Gn(),n=Rn.current??In.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??{},...pr()},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),Dn.current&&!_e.current?(Dn.current=!1,zn.current=Date.now()+Jt,void le(!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:he,historyLoadedRef:be,conversationIdRef:In,handleFileAdd:yr,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),yr(t))},handleSendMessage:_r,skipWait:Jr?async()=>{const e=ir(),t=In.current;if(e&&t)try{(await hr(e,t)).ok&&z(e=>"wait_start"===e?.status?{status:"thinking",thinkingContent:e.thinkingContent}:e)}catch{}}:null,readPendingApprovals:dr?Yn:null,heldMessage:De,notice:Oe,cancelHeldMessage:Br,reloadHistory:Xn,mergeTurnHistory:e=>{const t=ot.current;if(ot.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(cn(e),(l.get(cn(e))??0)+1);const d=t.slice(c+1).filter(e=>{if(e.serverId&&i.has(e.serverId))return!1;const t=l.get(ln(e))??0;return 0===t||(l.set(ln(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&&cn(t)===ln(e));return t?(u.add(t.id),dn(t,e)):{...e,id:We(e.serverId)}});return[...a,...p,...s.filter(e=>!u.has(e.id))]}(t,e,n,r)),!0},settleUnseenEnd:(e,t)=>{const n=Ht.current;n&&e>=n.from&&(window.clearTimeout(n.timer),Ht.current=null,Ar(t?Sn(t,n.shownUpTo):"stopped"));const r=at.current;!r?.readBack||e<r.readBack.from||Dr(t?Sn(t,r.shownUpTo):"stopped")},agentMentions:K,addAgentMention:Bn,handleNewChat:e=>Fr(e,!0),adoptRecreatedConversation:e=>{Fr(void 0,!1,!0),fr(e)},pendingWorkspaceId:Pn,clearPendingWorkspace:e=>{On.current===e&&(On.current=null,Un(null))},handleStopGenerating:()=>{const e=at.current;if(!Tn.current&&e){const t=sr(),n=In.current;return t&&n&&hr(t,n).catch(()=>{}),Le.current=e.turnId,Re.current=!0,zr(),void Dr("stopped")}if(!Tn.current)return void Kr(!1);Re.current=!0;const t=sr(),n=In.current,r=null!==_t.current&&!_e.current;if(!t||!n||r)return t&&n&&hr(t,n).catch(()=>{}),void Kr();if(null!==Ee.current)return;Ue.current=!1,Pe(null),re(null),ie(null),z(e=>({...e,status:"cancelling"}));const o=window.setTimeout(()=>Kr(),1e4);Ee.current=o,nt.current={statusBefore:$,approvalsBefore:ne,frameSeq:tt.current},Gr(o)},conversationRefs:F,addConversationRef:Fn,setAttachedFiles:Y,setMessages:E,setContextUsage:te,updateConversationId:fr,handleSwitchConversation:e=>{if((A||e!==In.current)&&(Fr(void 0,!1),!A)){fr(e);const t=Gt(m,e);B(t.text),V(t.refs)}}}}function Tn(e,t){if(t)return e.find(e=>e.id===t)??e.find(e=>e.slug===t)}function An({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,storageKeyPrefix:o,initialAgent:l,onAgentChange:d}){const u=Wt(),p=null===t?.agents||!!t?.singleEndpoint||"legacy"===n,h=Mt(o,It),[m,g]=a([]),[f,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(g(t),y(!1),0===t.length)return void I(null);const n=()=>{const e=Rt("local",h);return Tn(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&&g([]))}).finally(()=>{a()&&(v(!1),x(!0))})},[e,t,n,r,p,k]);return{agents:m,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&&Dt("local",h,e.slug),A(!1),d?.(e),t?.()):A(!1)},reloadAgents:C}}function _n(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 En=400;let Mn=null,Ln=null,Rn=0;function Dn(){null!==Mn&&(window.clearInterval(Mn),Mn=null),null!==Ln&&(document.title=Ln,Ln=null)}function $n({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;Rn+=1;const e=()=>{!document.hidden&&document.hasFocus()&&Dn()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),Rn=Math.max(0,Rn-1),0===Rn&&Dn()}},[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===Ln&&(Ln=document.title),null!==Mn&&window.clearInterval(Mn);let t=!0;document.title=e,Mn=window.setInterval(()=>{t=!t,document.title=t?e:Ln??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 zn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=Wt(),[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,g=p&&h?`${e}${h}`:null,f=p&&m?`${e}${m}`:null;i(()=>{if(!g)return void l(null);let e=!1;return o(g,{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}},[g,r]);const[v,w]=a(0),y=c(()=>w(e=>e+1),[]);return i(()=>{if(!f)return void u(null);let e=!1;return o(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 jn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,agentSlug:o}){const s=Wt(),[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 On(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 Pn(e){const t=s(e);l(()=>{t.current=e});const n=c((...e)=>t.current?.(...e),[]);return e?n:void 0}function Un(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 Hn(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const qn=new Set(["thinking","status","stream","turn_started"]);function Wn(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&&qn.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=He(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 Bn(e){return e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}const Fn=new Set(["no-speech","aborted"]);function Vn(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,g=null,f=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),f=k(f),c="",s="",S("listening")},A=()=>{g=k(g),l=null,d=!1},_=()=>{A(),S("error"),f=t(()=>{f=null,"error"===o&&T()},2e3)},E=()=>{g=k(g);const n=l;g=t(()=>{g=null,e.probe().then(e=>{l===n&&n&&("over"===e?_():E())})},12e4)},M=t=>{if(!l||!d)return;const n=Wn(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=Bn(e);if(n.length<2)return!1;const r=new Set(Bn(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,Fn.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),f=k(f),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 Kn=()=>null!==Hn();function Gn(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 Jn(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 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("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"})]}),Xn=({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"})]}),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:"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"})}),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:"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"})]}),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:"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"})]}),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("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),nr=({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"})}),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:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m6 9 6 6 6-6"})}),or=({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"})}),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:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),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("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"})]}),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("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"})]}),cr=({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"})}),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:"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"})]}),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:"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"})]}),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:"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"})]}),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:"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"})]}),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:"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"})]}),mr=({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"})}),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:"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"})]}),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("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"})]}),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("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"})]}),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:"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"})]}),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("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"})]}),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("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"})]}),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:"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"})]}),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("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"})]}),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("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),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("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"})]}),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:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),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:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),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:"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"})]}),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 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"})]}),_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:"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"})]}),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:"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"})]}),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("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),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:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),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("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),Dr=({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"})}),$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("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),zr=({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"})]}),jr=({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"})]}),Or=({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"})]}),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:"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"})]}),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:"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"})]}),Hr="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",qr=({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:Hr}),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"})]}),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:Hr}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),Br=({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"})}),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:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]});function Vr({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(nr,{size:13})}),t("button",{type:"button",onClick:()=>l(!1),"aria-label":i("Cancel"),className:s,children:t(ar,{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(Pr,{size:12}),i("Clear all conversations")]})})}const Kr=({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}),g=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,g,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 f=E(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}),f)},Gr=({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 Jr(e){return Math.max(e.maxRight-e.minLeft,0)}const Yr=({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=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:Jr(c)},role:"tooltip",children:n}),E(o.current))]})},Xr=({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})},Zr=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(hr,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(Rr,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(wr,{...e})}],Qr=({mode:r,agentName:o,agents:c,agentsLoading:l=!1,agentsError:d=!1,selectedAgent:p,transferredFrom:h,agentMenuOpen:m,onAgentMenuToggle:g,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:M=[],conversationsLoading:R=!1,activeConversationId:D=null,onSelectConversation:$,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?Rr:"fullscreen"===r?vr:hr;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:g,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(rr,{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(Kr,{open:m,onClose:f,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(Gr,{size:16})}),0===c.length&&!l&&d&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(Yn,{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(Mr,{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&&f()},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(Xr,{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:()=>{f(),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(ur,{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:()=>{f(),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(Ur,{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(Yr,{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(xr,{size:18})})}),e(Kr,{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===M.length&&t("div",{className:"px-4 py-2",children:t(Gr,{size:16})}),!R&&0===M.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:P("No conversations yet")}),M.map(n=>{const r=n.conversationId===D,o=L(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:()=>$?.(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(Pr,{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(dr,{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&&M.length>0&&t(Vr,{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(Yr,{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(dr,{size:18})})}),"inline"!==r&&x&&e(n,{children:[t(Yr,{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(Kr,{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:Zr.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(Yr,{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(ar,{size:18})})})})]})};function eo({url:e,query:t,exclude:n,requestHeaders:r}){const o=Wt(),[s,c]=a(ge);return i(()=>{if(!e||null===t)return void c(ge);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:he(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 to({url:e,requestHeaders:t,conversationId:n,text:r,onTextChange:o,textareaRef:l,refs:h,onPick:m,agentMentions:g}){const f=null!==e||!!g,[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=f&&e&&document.activeElement===e&&e.selectionStart===e.selectionEnd?function(e){const t=/@([\w-]*)$/.exec(e);return!t||ce(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,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=eo({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 ve(i.length===e.length?e:i,t.items)}(e,A,n))},[A,n]);const M=u(()=>ve(h.map(we),_),[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:pe(h,r).length,exclude:n,known:M}),R=null!==v&&v.anchor===y,D=[...u(()=>g&&v&&!R?function(e,t){const n=[];for(const r of e){const e=Pt(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}(g.agents,v.query):[],[g,v,R]).map(e=>({type:"agent",mention:e})),...null!==e&&"results"===L.kind?L.items.map(e=>({type:"conversation",candidate:e})):[]],$=Math.min(x,Math.max(D.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?g?.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=f?{"aria-autocomplete":"list","aria-controls":D.length>0?C:void 0,"aria-activedescendant":D.length>0?S($):void 0}:{};return{view:null===e?{kind:"closed"}:L,items:D,activeIndex:$,setActiveIndex:k,listboxId:C,optionId:S,sync:I,close:T,pick:z,onKeyDown:e=>{if("closed"===L.kind&&0===D.length||!v||e.nativeEvent.isComposing)return!1;if("Escape"===e.key)return e.preventDefault(),b(v.anchor),!0;if(0===D.length)return!1;if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;return k(($+t+D.length)%D.length),!0}return!("Enter"!==e.key&&"Tab"!==e.key||e.shiftKey)&&(e.preventDefault(),z(D[$]),!0)},textareaAria:j}}const no=14,ro=2*Math.PI*6,oo=[{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"}],ao=({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,g=h>=.8,f=m?"text-red-500":g?"text-amber-500":"text-[var(--chat-accent)]",v=m?"text-red-500 dark:text-red-400":g?"text-amber-600 dark:text-amber-400":"chat-text-muted-400/30",w=Math.round(100*h),y=`${M(i)}/${M(c)}`,b=o(m?"Context full — older turns are being dropped":g?"Context nearly full — older turns are being summarized":"Context used"),x=A(o,"{counts} tokens",{counts:y}),k=`${b} · ${x}`,N=l?oo.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:no,height:no,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:ro,strokeDashoffset:ro*(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(Yr,{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(Kr,{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:M(l?.[n.field]??0)})]},n.field))}),g&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${v}`,children:b})]})]}):t(Yr,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},so=({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(Qn,{size:14}):t(Ir,{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})})]})},io=({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(),g=m?r.filter(e=>e.title.toLowerCase().includes(m)||(e.description??"").toLowerCase().includes(m)):r;return e(n,{children:[t(Yr,{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(Dr,{size:15})})}),e(Kr,{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===g.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:i("No prompt matches")}),g.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))]})]})]})},co=({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(Yr,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums chat-text-muted-400/30",role:"img","aria-label":`${e} ${M(o)}`,children:M(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=`${M(o)}/${M(a)}`,m=r(l?"Quota reached":"Quota"),g=i(s?`${m} · ${s}`:m);return t(Yr,{title:g,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${g} ${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})]})})},lo=[],uo=({header:r,steerAttachments:o=!1,canHold:l=!1,heldMessage:p,notice:h,onCancelHeld:m,inputValue:g,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:D})=>{const $=s(null),z=s(null),j=D?.agents,O=D?.onPick,P=u(()=>j&&O?{agents:j,onPick:O}:void 0,[j,O]),U=to({url:R?.url??null,requestHeaders:R?.requestHeaders,conversationId:R?.conversationId,text:g,onTextChange:f,textareaRef:z,refs:R?.refs??lo,onPick:e=>R?.onPick(e),agentMentions:P}),H=s(!1),q=function(e){const[t,n]=a(!1),[r,o]=a(""),l=s(null),d=s(e);d.current=e;const u=null!==Hn();return i(()=>{const e=Hn();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=Un(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,f(g.trim()?`${g.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))},[g]);const W=Boolean(_&&_.length>0||E||M||L),B=Boolean(N&&C&&S),F=g.trim()||B&&k.length>0,V=B&&k.some(e=>"pending"===e.uploadStatus),K=B&&k.length>0,G=B&&(y||b)&&Ot(k),J=F&&!V&&!G,Y=Boolean(R)&&pe(R?.refs??lo,g).length>0||Boolean(D)&&Ut(D?.mentions??[],g).length>0,X=y&&x&&!Y&&(!K||o),Z=X&&!V&&!G&&(K||Boolean(g.trim())),Q=y&&l&&!Z&&!p&&Boolean(J),ee=()=>{(y?Z||Q:J)&&(q.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(pr,{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 ${q.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:$,type:"file",multiple:!0,hidden:!0,onChange:e=>{N?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>$.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(Zn,{size:18})})]}),t("textarea",{ref:z,placeholder:q.listening?I("Listening..."):I("Ask a question..."),value:g,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 chat-text-900/100 placeholder:chat-text-muted-400/30 filigran-chat-scrollable",style:{maxHeight:120}}),t(so,{view:U.view,items:U.items,activeIndex:U.activeIndex,listboxId:U.listboxId,optionId:U.optionId,onHover:U.setActiveIndex,onPick:U.pick,t:I}),q.supported&&t(Yr,{title:q.listening?I("Stop dictation"):I("Dictate a message"),children:e("button",{type:"button",onClick:q.toggle,"aria-label":I("Dictate a message"),"aria-pressed":q.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors "+(q.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:[q.listening?t(Ar,{size:18}):t(Tr,{size:18}),q.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(Yr,{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(Lr,{size:18})})}),Z&&t(Yr,{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(Lr,{size:18})})}),t(Yr,{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?$r:Lr,{size:18})})})]}),W&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[_&&_.length>0&&t(io,{prompts:_,onPick:e=>{f(g.trim()?`${g.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(ao,{usage:M,t:I}),E&&t(co,{quota:E,t:I})]})]}),q.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:q.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})]})},po=e=>e.serverId??e.id;const ho=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;const mo={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"}},go=new Map;function fo(e,t){const n=`${e??""}|${t}`;let r=go.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,mo[t])}catch{r=new Intl.DateTimeFormat(void 0,mo[t])}go.set(n,r)}return r}const vo={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const wo=new Set(["ArrowUp","PageUp","Home"]);function yo(e){return 1===e.length?e[0].clientY:null}const bo=new Set(["auto","scroll","overlay"]);const xo={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"})]})},ko="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)]",No=({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 g=!!s&&!h&&(e=>"video"===e.kind&&("pending"===e.status||"running"===e.status))(l);i(()=>{if(!g||!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()}},[g,s,l.kind,l.id]);const f=xo[l.kind],v=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(l.kind,r),w=l.title||v,y=q(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(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 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:[g&&t(Gr,{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:ko,onClick:()=>c(l),children:r("Open")}),x&&e("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:ko,children:[r("Open in XTM One"),t(ur,{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:ko,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(Gr,{size:11}):t(lr,{size:12}),a]},n)})]})]})};function Co(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function So(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 Io="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",To=({proposal:n,decision:r,onDecide:o,disabled:s,t:i})=>{const[c,l]=a(!1),[d,u]=a(""),h=p(),m=So(c),g=r?.verdict,f=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(Br,{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})]})]}),g&&t("span",{className:"shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===g?"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"===g?"Declined":"approve_always"===g?"Always allowed":"Approved")})]}),f.length>0&&t("div",{className:"flex flex-col gap-1.5",children:f.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:Co(n.arguments?.[r])})]},r)})}),!g&&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:`${Io} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(Fr,{size:13}),i("Decline this call")]}),t("button",{type:"button",disabled:s,onClick:()=>{l(!1),u("")},className:`${Io} chat-text-secondary-500/50 hover:chat-surface-hover-100/5`,children:i("Back")})]})]}),!g&&!c&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>l(!0),className:`${Io} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(Fr,{size:13}),i("No")]}),e("button",{type:"button",disabled:s,onClick:()=>v("approve"),className:`${Io} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(nr,{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:`${Io} border chat-border-200/15 chat-text-secondary-700/70 hover:chat-surface-hover-100/5`,children:i("Yes, always")})]})]})},Ao=({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 g=o||h,f=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=So(y),x=So(!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(Yn,{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(To,{proposal:e,decision:d[e.toolCallId],disabled:g,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)&&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(Yn,{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||g,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${Io} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:l(g?"Sending…":"Confirm")})]})]})},_o=({src:n,alt:r,onClose:o,t:c})=>{const l=s(null),d=s(null),[u,p]=a(null);return i(()=>{p(E(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(ar,{size:20})}),t("img",{src:n,alt:r,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},Eo=({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),[g,f]=a(!1),v=Wt();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:()=>f(!0),onError:()=>m(!0),className:`max-w-full cursor-zoom-in rounded-md object-contain ${c}`}),t("button",{type:"button",onClick:()=>f(!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(Sr,{size:14})})]}),g&&t(_o,{src:w,alt:o,onClose:()=>f(!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(kr,{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 Mo="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",Lo=({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,g]=a(0);if(i(()=>{r&&c()},[r,c]),i(()=>{if(!r||d)return;const e=window.setInterval(()=>g(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[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: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 chat-text-muted-500/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),o?e("button",{type:"button",onClick:o,className:Mo,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(yr,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:Mo,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(yr,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(ur,{size:11})})]}):null]})]})};function Ro(e,t){return e>1?A(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function Do(e,t){return e>1?A(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function $o(e,t){return e>1?A(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function zo(e){return Array.from(new Set(e.map(e=>e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))))}function jo(e,t){if(e.agents>1)return A(t,"Consulting {count} agents…",{count:e.agents});const n=e.agentName;if(e.count>1)return A(t,"Consulting {agent}: {count} questions…",{agent:n,count:e.count});const r="tool_start"===e.status?(e.tools??[]).filter(e=>"consult_agent"!==e):[];if(r.length>0){const[e,...o]=zo(r);return o.length>0?A(t,"Consulting {agent}: {tool} (+{count} more)…",{agent:n,tool:e,count:o.length}):A(t,"Consulting {agent}: {tool}…",{agent:n,tool:e})}return e.answering?A(t,"Consulting {agent}: writing the answer…",{agent:n}):A(t,"Consulting {agent}…",{agent:n})}function Oo(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:er,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:Ro(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:Ur,showDots:!1}}if(r.some(e=>"check_task_status"===e)){return{label:Do(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:Dr,showDots:!1}}if(r.some(e=>"get_task_result"===e)){return{label:$o(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:Dr,showDots:!1}}let o,a=Br;if(r.some(e=>e.includes("search")||e.includes("list"))?a=Mr:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?a=ir:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?a=Cr:r.some(e=>e.includes("code")||e.includes("execute"))?a=zr:r.some(e=>e.includes("web")||e.includes("browse"))&&(a=br),n.length>0){const e=zo(n);o=1===e.length?`${e[0]}…`:A(t,"{tool} (+{count} more)…",{tool:e[0],count:e.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:Yn,showDots:!1};case"cancelling":return{label:t("Stopping…"),StatusIcon:er,showDots:!0};case"reconnecting":return{label:t("Reconnecting…"),StatusIcon:er,showDots:!0};case"wait_start":return{label:e.waitReason||t("Waiting before continuing…"),StatusIcon:Dr,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:Dr,showDots:!0};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:Dr,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:Dr,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:er,showDots:!0};case"consulting":{if(e.consult)return{label:jo(e.consult,t),StatusIcon:Ur,showDots:!1};const n=e.tools?.[0]??t("the agent");return{label:A(t,"Consulting {agent}…",{agent:n}),StatusIcon:Ur,showDots:!1}}case"delegating":return{label:Ro(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:Ur,showDots:!1};case"polling":return{label:Do(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:Dr,showDots:!1};case"collecting":return{label:$o(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:Dr,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Transferring to {agent}…",{agent:n}),StatusIcon:ur,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:er,showDots:!1}}}function Po(e,t,n){return e&&n?.(e)||Oo(e,t).label}function Uo(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 Ho({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 qo(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 Wo(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 Bo=({agentStatus:r,logoIcon:o,t:s,miniGameEnabled:c=!0,onPlayWaitingGame:l,waitingGameUrl:d,keepEndInView:p,onSkipWait:h,statusLabel:m,waitingMessages:g,renderWaitingPanel:f})=>{const v=Oo(r,s),{StatusIcon:w,showDots:y}=v,b=Po(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 Uo(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 Uo(a)}(x??""),[x]),L=M.length>=3,R=Wo(c&&!L,5e3),D=Wo(c&&L,1e4,x?.length??0),$=L?D: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:qo(Math.ceil(A))}):E&&t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:qo(_)}),"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")})]})]})]}),$?t(Lo,{t:s,enabled:c,onPlay:l,playUrl:d,keepEndInView:p,messages:g,content:f?.()}):L?t(Ho,{text:M}):null]})};class Fo 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 Vo({draw:e}){return t(n,{children:e()})}function Ko({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 Go=y().use(w).use(v).freeze();function Jo(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(Jo);default:return!1}}function Yo(e,t){return e.lastIndexOf("\n",t-1)+1}function Xo(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Yo(e,t-1),t-1).trim()}function Zo(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 Qo{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 Go.parse(o).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Yo(o,n),s=a[a.length-1];t>s&&!Zo(e,s,t)&&a.push(t)}s<0&&Jo(t)&&(s=a.length-1)}let i=n;for(let t=a.length-1;t>n;t--)if(Xo(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 ea=r({copiedBlock:null,onCopyCode:()=>{},streaming:!1,t:T});function ta({draw:e,block:r}){const o=e();return null==o||!1===o?t(n,{children:r}):t("div",{className:"my-3",children:o})}const na={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(ea),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(nr,{size:14,className:"text-green-500"}):t(sr,{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(Fo,{label:"A chat code block renderer",resetKey:`${u}\0${c}`,fallback:t(Ko,{t:l}),children:t(ta,{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(ea),a=Xe(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(ea);return"string"==typeof e&&e?t(Eo,{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})},ra=[v,k],oa=m(({source:e})=>t(x,{remarkPlugins:ra,urlTransform:I,components:na,children:e}));oa.displayName="MarkdownBody";const aa=({source:e})=>{const[r]=a(()=>new Qo),o=u(()=>r.split(e),[r,e]);return t(n,{children:o.map((e,n)=>t(oa,{source:e},n))})},sa=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 g=u(()=>C(r),[r]),f=c(e=>{navigator.clipboard.writeText(e),p(e),setTimeout(()=>p(null),2e3)},[]),v=u(()=>({copiedBlock:d,onCopyCode:f,onRelativeLinkClick:s,requestHeaders:i,codeBlockRenderers:e,streaming:o,t:l}),[d,f,s,i,e,o,l]);return t(ea.Provider,{value:v,children:t(h?aa:oa,{source:g})})});sa.displayName="MarkdownMessage";function ia(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ca(e){return e.replace(/_/g," ")}const la=({entry:n,index:r,t:o})=>{const[s,i]=a(!1),c=u(()=>ia(n.input),[n.input]),l=u(()=>ia(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(tr,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(Fr,{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:ca(n.name)}),t(rr,{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)")})]})]})]})},da=({msg:n,onClose:r,t:o})=>{const c=s(null),l=s(null),d=s(null),[u,p]=a(null);i(()=>{p(E(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??[],g=n.iterations??1,f=n.transferChain??[],v=n.toolCallTrace??[],w=(n.reasoning??"").trim(),y=[g>1?A(o,"{count} iterations",{count:g}):"",1===h?o("1 tool call"):A(o,"{count} tool calls",{count:h}),1===f.length?o("1 transfer"):f.length>1?A(o,"{count} transfers",{count:f.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(Br,{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(ar,{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(Yn,{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(er,{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:Uo(w)})})]}),v.length>0?t("div",{className:"flex flex-col gap-1.5",children:v.map((e,n)=>t(la,{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(Br,{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:ca(n)})]},`${n}-${r}`))}),f.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Xn,{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:f.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(Qn,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},ua=e=>e.parentElement,pa=e=>getComputedStyle(e).overflowY;function ha(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function ma(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 ga=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const fa="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",va="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",wa="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",ya=`opacity-0 ${fa} ${wa}`,ba=`opacity-50 ${fa} ${wa}`,xa="opacity-100 text-[var(--chat-accent)]",ka=({timestamp:n,locale:r})=>{const o=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:fo(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:fo(t,"full").format(e),iso:e.toISOString()}:null;var r,o}(n,r);return o?t(Yr,{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},Na=({text:e,label:n,t:r})=>{const[o,s]=a(!1),i=o?r("Copied!"):n;return t(Yr,{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:`${va} ${o?"opacity-100 text-green-500 dark:text-green-400":ya}`,children:t(o?nr:sr,{size:14})})})},Ca=({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?Or:jr;return t(Yr,{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:`${va} ${a?xa:ya} ${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")})]})},Sa=({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")})]})]})},Ia=({speaking:e,onToggle:n,t:r})=>{const o=r(e?"Stop reading":"Read aloud");return t(Yr,{title:o,children:t("button",{type:"button",onClick:n,"aria-label":o,className:`${va} ${e?xa:ya}`,children:t(e?Wr:qr,{size:14})})})},Ta=[],Aa=new Set(["PRESENTATION","REPORT","VIDEO"]),_a=m(({msg:r,isStreaming:o,agentName:i,logoIcon:c,onRelativeLinkClick:l,onDownloadFile:p,resolveAttachmentUrl:h,onDownloadArtifact:m,onRefreshArtifact:g,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:_=Ta,codeBlockRenderers:E,transformMessageText:M,onArtifactOpen:L,renderMessageExtras:R,messageFooterActions:D,t:$})=>{const[z,j]=a(!1),q="assistant"===r.role,W=u(()=>jt(M,r.content,r)??r.content,[M,r]),B=u(()=>q?"":function(e){return e.trimEnd().replace(/^(?:[ \t]*\r?\n)+/,"")}(W),[q,W]),F=!W,V=s(null),K=!!w?.commentOpen,G=s(K);d(()=>{const e=G.current&&!K;G.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&&ga.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&ga.has(e.filename.slice(n+1).toLowerCase())}(n)?h(n):void 0;if(o)return t(Eo,{src:o,alt:n.filename,requestHeaders:f,maxHeightClass:"max-h-[200px]",t:$},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:$("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(pr,{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(lr,{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(pr,{size:14}),n]},r),Z=(e,n)=>t(No,{artifact:e,t:$,onDownload:m,onRefresh:g,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(Fo,{label:"A chat marker card",resetKey:`${n}\0${o}`,fallback:t(Ko,{t:$}),children:t(Vo,{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=q&&!F&&!o,ne=function(e,t=[]){if(!e)return e;const n=O(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()}(W,_),re=u(()=>te&&N?U(W,_):null,[te,N,W,_]),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=po(r);return e("div",{"data-message-id":r.serverId??r.id,className:"group/msg flex flex-col "+(q?"items-start":"items-end"),children:[q&&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})]}),!q&&((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:ma(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})()}),!q&&(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}`:$("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(Ir,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:a})]});return T&&I?.has(r.conversationId)?t(Yr,{title:$("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(Yr,{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}`)})}),q?e("div",{"data-testid":"filigran-chat-assistant-message",className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=P(W,o,_),n=new Map((r.attachments??[]).map(e=>[e.fileId,e])),a=new Map((r.artifacts??[]).map(e=>[H(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(sa,{content:e.value,streaming:o,onRelativeLinkClick:l,requestHeaders:f,codeBlockRenderers:E,t:$})},`t-${r}`));else if("marker"===e.type){"FILE"===e.kind?s.add(e.args):Aa.has(e.kind)&&i.add(H(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=H(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=H(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:$("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 "+(q?"":"flex justify-end"),children:R(r,{streaming:o})}),!q&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 chat-text-muted-400/40",children:[!!B&&t(Na,{text:B,label:$("Copy message"),t:$}),!r.timestampUnknown&&t(ka,{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(ka,{timestamp:r.timestamp,locale:k}),ee&&t(Yr,{title:r.isTruncated?$("Reasoning details — turn limit reached"):$("Reasoning details"),children:t("button",{type:"button",onClick:()=>j(e=>!e),className:`${va} ${r.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":ba}`,"aria-label":r.isTruncated?$("Reasoning details — turn limit reached"):$("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":z,children:r.isTruncated?t(Yn,{size:14}):t(Nr,{size:14})})}),t(Na,{text:ne,label:$("Copy response"),t:$}),v&&t(Ca,{value:oe.value,locked:oe.locked,pending:!!w?.pending,onChange:e=>y(r,e,w),downRef:V,t:$}),re&&(le=re,le.some(e=>/[\p{L}\p{N}]/u.test(e.replace(J,""))))&&t(Ia,{speaking:C,onToggle:()=>S(ce,re),t:$}),D?.(r,{streaming:o})]}),te&&w?.commentOpen&&t(Sa,{pending:w.pending,onSave:e=>b(r,e,w),onSkip:()=>x(r,w),t:$}),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(da,{msg:r,onClose:()=>j(!1),t:$})]});var le});_a.displayName="MessageRow";const Ea=({messages:n,isLoading:r,agentStatus:o,agentName:p,logoIcon:h,onRelativeLinkClick:m,onDownloadFile:g,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:D,markerRenderers:$,markerKindList:z,codeBlockRenderers:j,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,transcriptFooter:q,onLoadEarlier:W,ttsRoute:B,thinking:F,t:V})=>{const K=s(null),[J,Z]=a(150),{entries:Q,rate:ee,saveComment:te,skipComment:ne}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o}){const i=Wt(),[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),g=c((e,t)=>u(n=>({...n,entries:{...n.entries,[e]:t}})),[]),f=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=po(e),d=++m.current;if(!r)return g(l,{seq:d,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void s?.(l,t,e);if(o&&e.serverId){if(g(l,{seq:d,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await ie(i,r,o,e.serverId,t?{rating:re(t),comment:null}:null,a)){const e=c(t?"Could not submit feedback.":"Could not retract feedback.");return void f(l,d,()=>n?{...n,seq:d,pending:!1,commentOpen:!1,error:e}:{seq:d,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}f(l,d,e=>({...e,pending:!1,commentOpen:"down"===t})),h.current.onMessageFeedback?.(l,t,e)}},[g,f]),w=c(async(e,t,n)=>{const{feedbackUrl:r,conversationId:o,requestHeaders:a,t:s}=h.current,c=po(e),l=ae(t);if(!(r&&o&&e.serverId&&l))return void g(c,{...n,commentOpen:!1,error:null});const d=++m.current;g(c,{...n,seq:d,pending:!0,error:null});const u=await ie(i,r,o,e.serverId,{rating:"negative",comment:l},a);f(c,d,e=>u?{...e,comment:l,pending:!1,commentOpen:!1}:{...e,pending:!1,error:s("Could not submit feedback.")})},[g,f]);return{entries:p,rate:v,saveComment:w,skipComment:c((e,t)=>g(po(e),{...t,commentOpen:!1,error:null}),[g])}}({feedbackUrl:E,conversationId:M,requestHeaders:y,onMessageFeedback:N,t:V}),se=function(e,t){const n=Wt(),[r]=a(ho),o=r||!!t,[d,u]=a(null),p=s(null),h=s(e),m=s(t);l(()=>{h.current=e,m.current=t});const g=s(null),f=c(()=>{const e=g.current;e&&(g.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,Y(t),h.current),[v]),y=c(async(e,t,r)=>{const o=new AbortController,a={id:t,abort:o};g.current=a,u(t);const s=Y(r,4096),i=new Audio;a.audio=i;let c=0;try{for await(const t of X(n,e,s,o.signal)){if(g.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(g.current!==a)return;c+=1}f()}catch(e){if(g.current!==a||e instanceof DOMException&&"AbortError"===e.name)return;f(),w(t,s.slice(c).join(" "))}},[w,f]),b=c((e,t)=>{const n=g.current?.id??p.current?.speakingId??null;if(f(),p.current?.stop(),n===e)return;const r=G(t),o=m.current;o?y(o,e,r):w(e,r)},[w,y,f]),x=c(()=>{f(),p.current?.stop()},[f]);return i(()=>()=>x(),[x]),{supported:o,speakingId:d,toggle:b,stop:x}}(L,B),[ce]=a(()=>function(e,t=vo){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())}}}(()=>K.current));i(()=>{const e=K.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&&bo.has(r(o)))return!0;return!1}(t,e,ua,pa)||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||J!==e.visible+e.count)return;pe.current=null;const t=K.current;t&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))});let ge=0;for(const e of n)"user"===e.role&&(ge+=1);const fe=s(null);d(()=>{const e=fe.current;fe.current={firstMessageId:ue,userMessageCount:ge},pe.current?.count||(!e||e.firstMessageId!==ue||ge>e.userMessageCount?ce.reveal():ce.keepUp())},[n,ue,ge,ce]);const ve=o?.thinkingContent?.length??0;d(()=>{ve&&ce.keepUp()},[ve,ce]);const we=n.length>J,ye=u(()=>we?n.slice(n.length-J):n,[n,J,we]),{speakingId:be,stop:xe}=se,ke=null===be||n.some(e=>po(e)===be),Ne=s({conversationId:M,userMessageCount:ge});i(()=>{const e=Ne.current;Ne.current={conversationId:M,userMessageCount:ge},(e.conversationId!==M||ge>e.userMessageCount||!ke)&&xe()},[M,ge,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:K,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&&(wo.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&ha(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:ha(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=yo(e.touches)},onTouchMove:e=>{const t=yo(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:"relative 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||W)&&t("div",{className:"flex justify-center",children:e("button",{type:"button",disabled:he,onClick:()=>{(async()=>{if(n.length>J)return void Z(e=>e+50);if(!W||he)return;const e=K.current;me(!0),pe.current={firstId:n[0]?.id,visible:Math.min(n.length,J),count:0,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0};try{0===await W()&&(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(rr,{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(Bo,{agentStatus:o,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,onSkipWait:S,...F})},e.id):t(_a,{msg:e,isStreaming:n,agentName:p,logoIcon:h,onRelativeLinkClick:m,onDownloadFile:g,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,feedbackMode:"assistant"===e.role?oe(e.serverId,E,M,!!N):null,feedback:Q[po(e)],onRate:ee,onSaveComment:te,onSkipComment:ne,locale:L,canSpeak:se.supported,isSpeaking:be===po(e),onToggleSpeech:se.toggle,openableConversationIds:e.conversationRefs?.length?R:void 0,onOpenConversation:e.conversationRefs?.length?D:void 0,markerRenderers:$,markerKindList:z,codeBlockRenderers:j,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,t:V},e.id)}),C&&!Se&&t(Bo,{agentStatus:o,logoIcon:h,t:V,miniGameEnabled:b,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,...F}),Se&&t(Ao,{proposals:I,onSubmit:T,isSubmitting:A,error:_,t:V},I.map(e=>e.toolCallId).join("|")),q,t("div",{})]})};function Ma(e){const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const La=({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 g=s(null);i(()=>{g.current?.scrollIntoView?.({block:"end"})},[n.lines.length,n.heard]);const{phase:f,muted:v}=n,w="listening"===f?p(v?"Muted":"Listening..."):"processing"===f?c:"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] 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:Ma(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"===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: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"===f&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:p("Speak or tap to interrupt")}),"processing"===f&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:p("Tap to cancel")}),"listening"===f&&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:g})]})}),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?Ar:Tr,{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(Er,{size:22})}),t("button",{type:"button",onClick:l,disabled:"speaking"!==f,"aria-label":p("Skip response"),className:`${x} chat-border-200/10 chat-text-secondary-600/70 hover:chat-surface-hover-100/6`,children:t(Wr,{size:20})})]})]})},Ra=({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}=_(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]})},Da=({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(Ra,{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))]})]}),$a="application/x-filigran-conversation";const za="p-1 rounded-md chat-text-muted-400/30 hover:chat-icon-hover transition-colors disabled:opacity-40 disabled:pointer-events-none",ja="text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",Oa=({conversations:r,loading:o,activeConversationId:c,collapsed:l,onToggleCollapsed:d,onSelect:p,onDelete:h,onRename:m,onNewChat:g,workspaces:f,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=Mt(v,At),[M,L]=a(()=>function(e){try{const t=JSON.parse(Rt("local",e)??"[]");return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e):[])}catch{return new Set}}(E)),[R,D]=a(!1),[$,z]=a(null);i(()=>{if(!$)return;const e=setTimeout(()=>z(null),6e3);return()=>clearTimeout(e)},[$]);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(!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")},q=N.trim().toLowerCase(),W=u(()=>q?e=>(e.title||"").toLowerCase().includes(q):void 0,[q]),B=u(()=>W?r.filter(W):r,[r,W]),F=u(()=>f?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 be(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,f.list,{matches:W}):null,[r,f,W]),V=f?function(e){return be(e.filter(e=>e.canManage))}(f.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:!!q}):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(Yr,{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(Rr,{size:17})})}),t(Yr,{title:k("New conversation"),children:t("button",{type:"button",onClick:()=>g(),"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(dr,{size:17})})})]});const G=e=>t(Wa,{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: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 chat-border-200/10",children:[e("div",{className:"flex items-center gap-1 px-3 py-3",children:[e("button",{type:"button",onClick:()=>g(),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(dr,{size:15}),k("New conversation")]}),y,t(Yr,{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(Rr,{size:17})})})]}),r.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Mr,{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(Gr,{size:16})}),e(n,F&&f?{children:[!q&&e("div",{className:"flex items-center justify-between px-2 pb-1 pt-1",children:[t("span",{className:ja,children:k("Workspaces")}),t(Yr,{title:k("New workspace"),children:t("button",{type:"button",onClick:()=>D(!0),"aria-label":k("New workspace"),className:za,children:t(fr,{size:14})})})]}),R&&t(Ha,{placeholder:k("Workspace name"),onSubmit:async e=>{if(D(!1),!e)return;const t=await f.onCreate(e);t.ok||U(t.error,"The workspace could not be created")},onCancel:()=>D(!1)}),F.groups.map(e=>t(qa,{workspace:e.workspace,count:e.conversations.length,open:xe(e.key,M,e,c,!!q),toggleable:ke(e,c,!!q),pending:!!e.workspace&&f.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),Dt("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(Ua,{t:k})},e.key)),e(Pa,{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:ja,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.")})]}),q&&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&&!q&&t(Vr,{onClear:x,className:"px-2 pt-3",iconButtonClass:za,t:k})]}),$&&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:$})]})},Pa=({onDropConversation:e,accepts:n,children:r,className:o=""})=>{const[i,c]=a(!1),l=s(0),d=e=>e.dataTransfer.types.includes($a);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($a);n&&e(n)}}:{},children:r})},Ua=({t:n})=>{const{before:r,after:o,hasSlot:a}=_(n,"Drop a conversation here, or start one with {icon}.","icon");return e("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:[r,a&&t("span",{role:"img","aria-label":n("New conversation in this workspace"),className:"inline-block align-[-1px]",children:t(dr,{size:11})}),o]})},Ha=({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)]"})},qa=({workspace:r,count:o,open:s,toggleable:i,pending:c,onToggle:l,onNewChat:d,onRename:u,onDelete:p,onDropConversation:h,t:m,children:g})=>{const[f,v]=a(!1),[w,y]=a(!1),b=!!r?.canManage,x=!!r&&r.isDefault&&r.isOwn;return e(Pa,{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:[f&&r?t(Ha,{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(or,{size:12,className:"shrink-0 chat-text-muted-400/30 transition-transform "+(s?"rotate-90":"")}),t(mr,{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&&!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:m("Delete?")}),t("button",{type:"button",onClick:()=>{y(!1),p(r.id)},"aria-label":m("Delete workspace"),className:`${za} hover:text-red-500`,children:t(nr,{size:13})}),t("button",{type:"button",onClick:()=>y(!1),"aria-label":m("Cancel"),className:za,children:t(ar,{size:13})})]}:{children:[t(Yr,{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:za,children:t(dr,{size:13})})}),t(Yr,{title:m("Rename workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":m("Rename workspace"),className:za,children:t(_r,{size:13})})}),!r.isDefault&&t(Yr,{title:m("Delete workspace"),children:t("button",{type:"button",onClick:()=>y(!0),"aria-label":m("Delete workspace"),className:`${za} hover:text-red-500`,children:t(Pr,{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(dr,{size:12}),m("New conversation — send a message to start it")]}),g]})]})},Wa=({conversation:r,isActive:o,isEditing:i,draftTitle:c,onDraftTitleChange:l,onCommitRename:d,onCancelRename:u,onStartRename:p,onSelect:h,onDelete:m,fileable:g,onMove:f,actions:v,t:w})=>{const[y,b]=a(!1),x=s(null),k=!!g&&!i;return e("div",{role:"button",tabIndex:0,"aria-current":o,draggable:k,onDragStart:k?e=>{e.dataTransfer.setData($a,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(Qn,{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?L(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(gr,{size:13})}),t(Kr,{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")}),g.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] chat-text-secondary-700/80 hover:chat-surface-hover-100/10 disabled:opacity-40",children:[t(mr,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===r.workspaceId&&t(nr,{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),f(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(ar,{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(dr,{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(Pr,{size:13})})]})]})},Ba=new Set([502,503,504]),Fa=new Set([401,403]),Va=g(function(e,n){const r=s(e.onSessionEnded);r.current=e.onSessionEnded;const o=s("");o.current=Se(e.requestHeaders);const a=u(()=>{let e=null;const t=t=>{r.current&&e!==o.current&&(e=o.current,jt(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(qt,{value:a,children:t(Ka,{...e,ref:n})})}),Ka=g(function({mode:n,onClose:r,onModeChange:d,topOffset:p=0,apiBaseUrl:h,apiEndpoints:m,agentDashboardUrl:g,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:P=!0,onPlayWaitingGame:H,notifyOnComplete:q=!0,onTaskComplete:W,onMessageFeedback:B,locale:F,disableImagePreviews:V=!1,contextUsageEnabled:K=!0,composerToolbar:J,storageKeyPrefix:Q,conversationId:te,onConversationChange:re,initialAgent:oe,onAgentChange:ae,readOnly:ie=!1,readOnlyNotice:ce,getRequestExtras:le,onStreamEvent:de,markerRenderers:ue,codeBlockRenderers:pe,transformMessageText:he,onArtifactOpen:ge,headerActions:fe,banner:ve,composerHeader:we,transcriptFooter:be,welcome:xe,renderMessageExtras:ke,messageFooterActions:Ne,sidebarRowActions:Ie,sidebarHeaderActions:Te,sidebarSections:_e,statusLabel:Ee,waitingMessages:Me,renderWaitingPanel:Re,fontFamily:De,theme:$e,onReady:ze,onBeforeSend:je,onHeldSendSettled:Oe,onTurnRunningChange:Pe,steerAttachments:Ue=!1,holdSendsDuringTurn:He=!1,agentMentions:qe=!1,hideConversationList:Be=!1},Ve){const Ke=On(m),Ge=On(D),Je=On(z),Ye=On(k),Xe=Pn(E),Ze=Pn(M),Qe=Pn(H),et=Pn(W),tt=Pn(B),nt=Pn(re),rt=Pn(ae),ot=Pn(le),at=Pn(je),st=Pn(Oe),it=Pn(de),ct=Pn(Pe),lt=Pn(ge),dt=s(null),{fetch:ut,sessionEnded:pt}=o(Ht),ht=u(()=>ne(y,F),[y,F]),mt=On(Me),gt=u(()=>ue?Object.fromEntries(Object.entries(ue).map(([e,t])=>[e.toUpperCase(),t])):void 0,[ue]),ft=On(u(()=>pe?Object.fromEntries(Object.entries(pe).map(([e,t])=>[e.toLowerCase(),t])):void 0,[pe])),vt=On(u(()=>function(e){const t=new Set;for(const n of e??[]){const e=n.toUpperCase();$.test(e)&&t.add(e)}return[...t].sort()}(gt&&Object.keys(gt)),[gt])),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:Ct,agentsSettled:St,agentsDisabled:It,selectedAgent:At,agentMenuOpen:_t,setAgentMenuOpen:Et,handleSwitchAgent:Lt,reloadAgents:$t}=An({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge,storageKeyPrefix:Q,initialAgent:oe,onAgentChange:ae?rt:void 0}),[zt,Ot]=a(null),Pt=s(null),[Ut,qt]=a(null),[Bt,Ft]=a(void 0),[Vt,Kt]=a(null),[Gt,Jt]=a(null),[Yt,Xt]=a(null),Zt=s(0),[Qt,en]=a(null),tn=s(null),nn=s(async()=>{}),rn=s(()=>{}),on=c((e,t)=>{jt(rn.current,e,t.relayed),jt(it,e,t)},[it]),{messages:an,inputValue:sn,setInputValue:un,isLoading:pn,turnRunning:hn,sendsHeld:mn,turnEnd:gn,agentStatus:fn,attachedFiles:vn,conversationId:wn,contextUsage:yn,transferredAgent:bn,forgetTransfer:xn,adoptRecreatedConversation:kn,canSteer:Nn,pendingApprovals:Cn,isSubmittingApproval:Sn,approvalError:Mn,submitApprovalDecisions:Ln,isResumingAfterDecision:Rn,historyReloadNonce:Dn,reloadHistory:Un,mergeTurnHistory:qn,settleUnseenEnd:Wn,historyLoadedRef:Bn,conversationIdRef:Fn,handleFileAdd:Kn,handlePaste:Xn,handleSendMessage:Zn,skipWait:Qn,readPendingApprovals:er,heldMessage:tr,notice:nr,cancelHeldMessage:rr,agentMentions:or,addAgentMention:ar,handleNewChat:sr,pendingWorkspaceId:ir,clearPendingWorkspace:lr,handleStopGenerating:dr,conversationRefs:ur,addConversationRef:pr,setAttachedFiles:hr,setMessages:mr,setContextUsage:gr,updateConversationId:fr,handleSwitchConversation:vr}=In({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,agentSlug:At?.slug,requestHeaders:Ge,pageContext:Je,onRelativeLinkClick:E?Xe:void 0,t:ht,maxFileCount:L,maxTotalSize:R,storageKeyPrefix:Q,controlledConversationId:te,onConversationIdChange:re?nt:void 0,getRequestExtras:le?ot:void 0,onStreamEvent:on,onSessionEnded:pt,onConversationTitle:()=>{nn.current()},historySettledFor:Ut,steerAttachments:Ue,holdSends:He,agentMentionsEnabled:qe,onBeforeSend:je?at:void 0,onHeldSendSettled:Oe?st:void 0});Bt!==wn&&(Ft(wn),null!==Ut&&qt(null),null!==Vt&&Vt!==wn&&Kt(null)),i(()=>{void 0!==te&&te!==Fn.current&&(te?vr(te):sr())},[te]);const{suggestions:wr,loading:yr}=jn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge,agentSlug:At?.slug}),br=u(()=>(wr??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),[wr,Ye,ht]),{prompts:xr,quota:kr,refreshQuota:Nr}=zn({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge}),{historyEnabled:Cr,conversations:Sr,conversationsLoading:Ir,refreshConversations:Tr,deleteConversation:Ar,renameConversation:_r,moveConversation:Er,clearConversations:Mr}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=Wt(),[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(_n).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]),g=u&&t?.clearAll?`${e}${t.clearAll}`:null,f=c(async()=>{if(!g)return!1;try{return!!(await o(g,{method:"DELETE",headers:{...r??{}}})).ok&&(i([]),!0)}catch{return!1}},[g,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 Ce(n)??"")}catch{return a(),""}},[u,p,r,s]);return{historyEnabled:u,conversations:s,conversationsLoading:l,refreshConversations:h,deleteConversation:m,renameConversation:v,moveConversation:w,clearConversations:g?f:null}}({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge});nn.current=Tr;const{workspacesEnabled:Lr,workspaces:Rr,refreshWorkspaces:Dr,createWorkspace:$r,renameWorkspace:zr,deleteWorkspace:jr}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=Wt(),[i,l]=a([]),[d,u]=a(!1),p=s(0),h=t?.workspaces,m="rest"===n&&!t?.singleEndpoint&&"string"==typeof h&&h.length>0,g=m?`${e}${h}`:null,f=c(async()=>{if(!g)return;const e=++p.current;try{const n=await o(g,{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=ye(await n.json());if(e!==p.current)return;l(a),u(!0)}catch{}var t},[g,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 Ce(a)};const s=204===a.status?[]:ye([await a.json().catch(()=>null)]);return await f(),{ok:!0,workspace:s[0]}}catch{return{ok:!1,error:null}}},[r,f]),w=c(async e=>g?v("POST",g,{name:e.trim()}):{ok:!1,error:null},[g,v]),y=c(async(e,t)=>g?v("PATCH",`${g}/${encodeURIComponent(e)}`,{name:t.trim()}):{ok:!1,error:null},[g,v]),b=c(async e=>g?v("DELETE",`${g}/${encodeURIComponent(e)}`):{ok:!1,error:null},[g,v]);return{workspacesEnabled:m&&d,workspaces:i,refreshWorkspaces:f,createWorkspace:w,renameWorkspace:y,deleteWorkspace:b}}({apiBaseUrl:h,apiEndpoints:Ke,backendType:O,requestHeaders:Ge});i(()=>{Lr&&ir&&!function(e,t){return t.some(t=>t.id===e&&t.canManage)}(ir,Rr)&&lr(ir)},[Lr,Rr,ir,lr]);const[Or,Pr]=a(!1),[Ur,Hr]=a(!1),qr=yt&&Cr&&!Be;i(()=>{qr&&Tr()},[qr,wn,Tr]),i(()=>{qr&&Dr()},[qr,wn,Dr]);const Wr=s(null);i(()=>{if(!qr)return;const e=()=>{if("visible"!==document.visibilityState)return;const e=Date.now();(function(e,t){return null===t||e-t>=2e3})(e,Wr.current)&&(Wr.current=e,Tr(),Dr())};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[qr,Tr,Dr]);const Br=s(!1);i(()=>{Br.current!==hn&&(Br.current=hn,hn?jt(ct,!0):jt(ct,!1,{ended:gn??"stopped"}))},[hn,gn,ct]),i(()=>()=>{Br.current&&(Br.current=!1,jt(ct,!1,{ended:"stopped"}))},[ct]);const Fr=s(!1);i(()=>{Fr.current&&!hn&&(Nr(),qr&&(Tr(),Dr())),Fr.current=hn},[hn,Nr,qr,Tr,Dr]);const Vr=e=>{Pr(!1),vr(e)},Kr=me(h,Ke,O),Gr=u(()=>new Set(Sr.map(e=>e.conversationId)),[Sr]),Jr=Pn(Cr?Vr:void 0),Yr=an.some(e=>(e.conversationRefs?.length??0)>0);i(()=>{Yr&&Cr&&Tr()},[Yr,Cr,Tr,wn]);const Xr=Z(h,Ke,O,"messagesPage"),[Zr,eo]=a(!1),to=Z(h,Ke,O,"tts"),no=u(()=>to?{url:to,requestHeaders:Ge}:void 0,[to,Ge]),ro=s(an);ro.current=an,i(()=>eo(!1),[wn]);const oo=c(async()=>{const e=Fn.current,t=ro.current.find(e=>e.serverId)?.serverId;if(!Xr||!e||!t)return eo(!1),0;try{const n=await ut(`${Xr}/${encodeURIComponent(e)}/messages?before=${encodeURIComponent(t)}&limit=50&supports_artifacts=true`,{headers:{...Ge??{}}});if(!n.ok||Fn.current!==e)return 0;const r=await n.json();if(Fn.current!==e)return 0;const o=new Set(ro.current.map(e=>e.serverId).filter(Boolean)),a=Fe(r?.messages).filter(e=>!e.serverId||!o.has(e.serverId)).map(e=>({...e,id:We(e.serverId)}));return mr(e=>[...a,...e]),eo(!0===r?.has_more&&a.length>0),a.length}catch{return 0}},[Xr,Fn,Ge,mr]),ao=(e,t,{merge:n,afterTurn:r,keepEarlierOffer:o})=>{if(qt(e),Kt(e),o||eo(!!Xr&&!0===t.has_more),!t.messages?.length)return;const a=Fe(t.messages);if(mr(n?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=ln(e),a=n.findIndex((e,t)=>!o.has(t)&&!e.serverId&&cn(e)===r);a>=0&&(t=a,n[a]=dn(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:We(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,a):a),!r)for(let e=t.messages.length-1;e>=0;e-=1){const n=Ae(t.messages[e]);if(n){gr(n);break}}},so=s(pn);so.current=pn,i(()=>{Zt.current=0},[wn]),i(()=>{Gt&&!pn&&(Jt(null),Gt.conversationId===wn&&ao(Gt.conversationId,Gt.data,{merge:!0,afterTurn:!0,keepEarlierOffer:Gt.host}))},[Gt,pn,wn]),i(()=>{if(!Yt||Yt.conversationId!==wn||pn)return;const e=()=>{so.current||(Xt(null),Zt.current+=1,tn.current=Yt.host?Yt.conversationId:null,Un())},t=Math.min(6e4,5e3*2**Zt.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)}},[Yt,wn,pn,Un]);const[io,co]=a(null),lo=Se(Ge),po=c(()=>{en(null),tn.current=Qt?.host?Qt.conversationId:null,Un()},[Qt,Un]);i(()=>{Qt&&Qt.conversationId===wn&&!pn&&Qt.headersKey!==lo&&po()},[Qt,wn,pn,lo,po]);const ho=Qt&&Qt.conversationId===wn?Qt:null,mo="rest"===O&&!Ke?.singleEndpoint&&null!==Ke?.sessions&&!!wn&&zt!==wn,go=!ie&&!_&&"rest"===O&&!Ke?.singleEndpoint&&null!==Ke?.upload,[fo,vo]=a(!1),wo=s(0),yo=e=>e.dataTransfer.types.includes("Files"),bo=go?{onDragEnter:e=>{yo(e)&&(wo.current+=1,vo(!0))},onDragOver:e=>{yo(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDragLeave:e=>{yo(e)&&(wo.current=Math.max(0,wo.current-1),0===wo.current&&vo(!1))},onDrop:e=>{yo(e)&&(e.preventDefault(),e.stopPropagation(),wo.current=0,vo(!1),Kn(e.dataTransfer.files))}}:{},xo=async()=>{await(Mr?.())&&sr()},ko=async e=>{await Ar(e)&&e===Fn.current&&sr()},{sidebarWidth:No,handleResizeStart:Co,defaultWidth:So,isResizing:Io}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:r,onResizeEnd:o,storageKeyPrefix:c}){const l=Mt(c,Tt),[d,u]=a(()=>{const e=Rt("local",l);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=En)return t}return En}),[p,h]=a(!1),m=s(!1),g=s(d);g.current=d;const f=s(n);f.current=n;const v=s(o);return v.current=o,i(()=>{"sidebar"===e&&t&&f.current?.(g.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,En),n);u(r),g.current=r,f.current?.(r)},r=()=>{m.current&&(m.current=!1,h(!1),document.body.style.cursor="",document.body.style.userSelect="",Dt("local",l,String(g.current)),v.current?.())},o=()=>{const e=.4*window.innerWidth;if(g.current>e){const t=Math.max(e,En);u(t),g.current=t,f.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:En,isResizing:p}}({mode:n,resizable:S,onWidthChange:I,onResizeStart:T,onResizeEnd:A,storageKeyPrefix:Q});i(()=>{const e="sidebar"===n?S?No:So:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",Io?"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=Io?"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,No,So,S,Io]);const To=u(()=>x??t(cr,{size:24}),[x]),Ao=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}(g,v),[g,v]),_o=w.firstName,[Eo,Mo]=a(null),Lo=bn?.name||Eo||At?.name||ht("Assistant"),Ro=c(()=>{const e=dt.current;return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);$n({isLoading:hn,agentName:Lo,t:ht,enabled:q,onComplete:et,isViewingChat:Ro});const Do=null!=Ke?.download,$o="rest"===O&&null!==Ke?.download&&(!Ke?.singleEndpoint||Do),zo=c(e=>`${h}${Ke?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[h,Ke]),jo=c(async e=>{const t=zo(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)}},[zo,Ge,Ze]),Oo="rest"===O&&Ke?.artifacts?`${h}${Ke.artifacts}`:null,Uo=c((e,t)=>`${Oo}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,[Oo]),Ho=c(async(e,t)=>{const n=`${e.title||e.kind}.${function(e){return"pptx_native"===e?"pptx":e}(t)}`;try{const r=await ut(`${Uo(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()})}},[Uo,Ge,Ze]),qo=c(async(e,t)=>{const n=await ut(Uo(e,t),{credentials:"include",headers:{...Ge??{}}});if(n.ok)return Le(await n.json())},[Uo,Ge]),Wo={"--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,...De?{fontFamily:De}:{},...ee($e)},Bo=s(qn);Bo.current=qn;const Fo=s(Wn);Fo.current=Wn;const Vo=s(kn);Vo.current=kn;const Ko=s(!0);i(()=>(Ko.current=!0,()=>{Ko.current=!1}),[]),i(()=>{const e=tn.current;if(tn.current=null,null===Ke?.sessions||Ke?.singleEndpoint||"legacy"===O||"ag-ui"===O)return;if(!wn)return Mo(null),void Ot(null);if(Bn.current)return Pt.current!==wn&&zt!==wn&&Ot(wn),void(Pt.current!==wn&&Ut!==wn&&Gt?.conversationId!==wn&&qt(wn));if(!At&&!It)return void(St&&zt!==wn&&Ot(wn));Bn.current=!0,Pt.current=wn,Ot(null);const t=`${h}${Ke?.sessions??"/chat/sessions"}`,n=wn,r=()=>!Ko.current||Fn.current!==n,o=e===n,a=Se(Ge),s=Dn;ut(t,{method:"POST",headers:{"Content-Type":"application/json",...Ge??{}},body:JSON.stringify({conversation_id:wn,agent_slug:At?.slug,supports_artifacts:!0})}).then(e=>r()?null:e.ok?(Zt.current=0,Xt(null),en(null),e.json()):(Fo.current(s,null),Fa.has(e.status)?Ce(e).then(e=>(r()||en({conversationId:n,detail:e,headersKey:a,host:o}),null)):(Ba.has(e.status)?Xt({conversationId:n,host:o}):o||fr(null),null))).then(e=>{if(!e||r())return;const t="string"==typeof e.conversation_id&&!!e.conversation_id&&e.conversation_id!==n;Mo("string"==typeof e.agent_name?e.agent_name:null);const a=Fe(e.messages);if(Fo.current(s,a),t)return Vo.current(e.conversation_id),Bn.current=!0,void ao(e.conversation_id,e,{merge:!1,afterTurn:!1,keepEarlierOffer:!1});o&&xn(),Bo.current(a)||(so.current?Jt({conversationId:n,data:e,host:o}):ao(n,e,{merge:o,afterTurn:!1,keepEarlierOffer:o}))}).catch(()=>{r()||(Fo.current(s,null),Xt({conversationId:n,host:o}))}).finally(()=>{Pt.current===n&&(Pt.current=null),r()||Ot(n)})},[wn,At,St,zt,Xr,h,Ke,O,Gt,Dn,Bn,Fn,Ko,Ge,mr,gr,fr,xn]);const Go=s(Zn);Go.current=Zn;const Jo=s(sr);Jo.current=sr;const Yo=s(vr);Yo.current=vr;const Xo=s(kt);Xo.current=kt;const Zo=s(At);Zo.current=At;const Qo=St&&!mo;i(()=>{if(null===io)return;if(io!==wn)return void co(null);if(!Qo||hn)return;co(null);const e=Vt===wn||an.length>0;Xt(null),en(null),tn.current=e?wn:null,Un()},[io,wn,Qo,hn,Vt,an.length,Un]);const ea=Pn(ze),ta=s(!1);i(()=>{Qo&&!ta.current&&(ta.current=!0,ea?.())},[Qo,ea]);const na=s([]),[ra,oa]=a(0),aa=(e,t)=>{na.current.push({run:e,drop:t}),oa(e=>e+1)};i(()=>{if(!Qo||0===na.current.length)return;na.current.shift().run(),na.current.length>0&&oa(e=>e+1)},[Qo,ra]),i(()=>()=>{queueMicrotask(()=>{if(!Ko.current)for(const e of na.current.splice(0))e.drop?.()})},[]);const sa=s(Lt);sa.current=Lt;const ia=s(dr);ia.current=dr;const ca=s(ie);ca.current=ie;const la=s(sn);la.current=sn;const da=bn?.id??(Eo?kt.find(e=>e.name===Eo)?.id:void 0)??At?.id??null,ua=function(e){const t=Wt(),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=Y(e,200),c=o?X(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 Gn(t,r)){if(r.aborted)return;await Jn(e,s,r)}}},[]),p=c(()=>{if(d.current)return!0;const e=Hn();if(!e)return!1;const t=Vn({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=>jt(n.current.speakable,e)??e,present:e=>jt(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)=>Go.current({text:e,source:"voice",onSent:t.onAccepted,onNotSent:t.onNotSent,onSteered:t.onSteered}),stopTurn:()=>ia.current(),readTurnState:er?async()=>{const e=Fn.current,t=e?await er(e):null;return t&&{running:t.turnRunning}}:void 0,addressedAgentId:()=>da,speakable:e=>G(U(e,vt)),present:e=>he?he(e,{id:"voice-call",role:"assistant",content:e,timestamp:new Date}):e,tts:no,locale:F});rn.current=ua.onFrame;f(Ve,()=>({send:(e,t)=>ca.current?Promise.resolve("dropped"):new Promise(n=>aa(()=>{ca.current?n("dropped"):Go.current({text:e,extras:t?.extras,displayText:t?.displayText,onSent:()=>n("sent")}).then(n,()=>n("failed"))},()=>n("dropped"))),newConversation:e=>aa(()=>{const t=Tn(Xo.current,e?.agent);t&&t.id!==Zo.current?.id&&sa.current(t),Jo.current(e?.workspaceId)}),selectConversation:e=>aa(()=>Yo.current(e)),setDraft:e=>{la.current=e,un(e)},getDraft:()=>la.current,focusComposer:()=>dt.current?.querySelector("textarea")?.focus(),stop:()=>{ua.cancel(),ia.current()},startVoiceCall:()=>!ca.current&&ua.start(),reloadAgents:$t,reloadConversation:()=>{const e=Fn.current;e&&co(e)},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 pa=(()=>{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}})(),ha={...Wo,..."sidebar"===n?{top:p,width:S?No:So}:"floating"===n?{width:380,height:560}:"inline"===n?{}:{top:p}};return e("div",{ref:dt,className:pa,style:ha,"data-testid":"filigran-chat-panel",children:["sidebar"===n&&S&&t("div",{onMouseDown:Co,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(Qr,{mode:n,agentName:Lo,agents:kt,agentsLoading:Nt,agentsError:Ct,selectedAgent:At,transferredFrom:bn?At?.name:void 0,agentMenuOpen:_t,onAgentMenuToggle:()=>Et(e=>!e),onAgentMenuClose:()=>Et(!1),onSwitchAgent:e=>{e&&Lt(e,()=>{sr()})},modeMenuOpen:bt,onModeMenuToggle:()=>xt(e=>!e),onModeMenuClose:()=>xt(!1),onModeChange:d,onNewChat:sr,onClose:r,logoIcon:To,actions:fe,agentDashboardUrl:g,historyEnabled:Cr&&!qr,historyMenuOpen:Or,onHistoryMenuToggle:()=>{const e=!Or;e&&Tr(),Pr(e)},onHistoryMenuClose:()=>Pr(!1),conversations:Sr,conversationsLoading:Ir,activeConversationId:wn,onSelectConversation:Vr,onDeleteConversation:e=>{ko(e)},onClearAll:Mr?()=>{xo()}:void 0,t:ht}),e("div",{className:qr?"flex flex-1 min-h-0":"contents",children:[qr&&t(Oa,{conversations:Sr,loading:Ir,activeConversationId:wn,collapsed:Ur,onToggleCollapsed:()=>Hr(e=>!e),onSelect:Vr,onDelete:e=>{ko(e)},onRename:(e,t)=>{_r(e,t)},onNewChat:sr,workspaces:Lr?{list:Rr,pendingWorkspaceId:ir,onCreate:$r,onRename:zr,onDelete:async e=>{const t=await jr(e);return t.ok&&(lr(e),Tr()),t},onMove:Er,onNewChat:e=>{sr(e),Dr()}}:void 0,storageKeyPrefix:Q,rowActions:Ie,headerActions:Te,sections:_e,onClearAll:Mr?()=>{xo()}:void 0,t:ht}),e("div",{className:qr?"relative flex flex-1 flex-col min-w-0":"contents",...bo,children:[fo&&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&&mo?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&&ho?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(Yn,{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:ho.detail??ht("This conversation could not be loaded.")}),t("button",{type:"button",onClick:po,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(Da,{firstName:_o,logoIcon:To,promptSuggestions:br,suggestionsLoading:yr,agentName:At?.name,agentDescription:At?.description,onPromptClick:ie?void 0:un,t:ht}):t(Ea,{messages:an,isLoading:pn,agentStatus:fn,agentName:Lo,logoIcon:To,onRelativeLinkClick:Xe,onDownloadFile:$o?jo:void 0,resolveAttachmentUrl:$o&&!V?zo:void 0,onDownloadArtifact:Oo?Ho:void 0,onRefreshArtifact:Oo?qo:void 0,requestHeaders:Ge,miniGameEnabled:P,onPlayWaitingGame:Qe,waitingGameUrl:Ao,onMessageFeedback:tt,feedbackUrl:se(h,Ke,O),conversationId:wn,locale:F,isResumingAfterDecision:Rn,onSkipWait:Qn??void 0,pendingApprovals:Cn,onSubmitApprovalDecisions:Ln,isSubmittingApproval:Sn,approvalError:Mn,openableConversationIds:Gr,onOpenConversation:Jr,markerRenderers:gt,markerKindList:vt,codeBlockRenderers:ft,transformMessageText:he,onArtifactOpen:lt,renderMessageExtras:ke,messageFooterActions:Ne,transcriptFooter:be,onLoadEarlier:Zr?oo:void 0,ttsRoute:no,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(uo,{header:we,sendsHeld:mn,steerAttachments:Ue,canHold:He,heldMessage:tr,notice:nr,onCancelHeld:rr,agentMentions:qe&&kt.length>0?{agents:kt,mentions:or,onPick:ar}:void 0,inputValue:sn,onInputChange:un,onSend:Zn,onStop:dr,isLoading:pn,canSteer:Nn,attachedFiles:_?[]:vn,onFileAdd:_?void 0:Kn,onFileRemove:_?void 0:e=>hr(t=>t.filter((t,n)=>n!==e)),onPaste:_?void 0:Xn,t:ht,mode:n,separatorColor:C,prompts:xr,quota:kr,contextUsage:K?yn:null,composerToolbar:J,conversationReferences:Kr?{url:Kr,requestHeaders:Ge,conversationId:wn,refs:ur,onPick:pr}:void 0})]})]}),ua.snapshot&&t(La,{call:ua.snapshot,agentName:Lo,logoIcon:To,processingLabel:Po(fn,ht,Ee),onInterrupt:ua.interrupt,onToggleMute:ua.toggleMute,onEnd:ua.end,t:ht})]})}),Ga=({isOpen:n,onToggle:r,label:o,accentColor:a="#7b5cff",icon:s,t:i,locale:c})=>{const l=u(()=>ne(i,c),[i,c]),d=s??t(cr,{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{Va as ChatPanel,Ga as ChatToggleButton,Kn as voiceCallSupported};
2
2
  //# sourceMappingURL=index.js.map