@hsafa/ui-sdk 5.5.7 → 5.5.8

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,4 +1,4 @@
1
- import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Wo,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext,Component}from'react';import {useChat}from'@ai-sdk/react';import {lastAssistantMessageIsCompleteWithToolCalls,DefaultChatTransport}from'ai';import {createRoot}from'react-dom/client';import {XMarkdown}from'@ant-design/x-markdown';import'@ant-design/x-markdown/themes/light.css';import'@ant-design/x-markdown/themes/dark.css';import {createPortal}from'react-dom';import {Plus,History,ChevronRight,Pencil,Trash2,File as File$1,Eye,X,Download}from'lucide-react';var Ce={};var wr=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:c,...m})=>{let i=[Ce.button,Ce[e],Ce[t],n&&Ce.loading,c].filter(Boolean).join(" ");return jsxs("button",{className:i,disabled:r||n,...m,children:[n&&jsx("span",{className:Ce.spinner}),jsx("span",{className:n?Ce.hiddenText:void 0,children:o})]})};function Wt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:r}){if(!e)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:c=>{c.currentTarget.style.borderColor=n.primaryColor,c.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:c=>{c.currentTarget.style.borderColor=n.borderColor,c.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function _t(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let r=t.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),t}function jt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var qt=createContext(void 0);function oo({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,c]=useState(new Map),[m,i]=useState(new Map),[w,S]=useState(new Map),[d,T]=useState(new Map),[v,x]=useState(void 0),a=useCallback((p,C)=>(c(M=>{let g=new Map(M);return g.set(String(p),C),g}),()=>{c(M=>{let g=new Map(M),R=g.get(String(p));return (!C||R===C)&&g.delete(String(p)),g});}),[]),b=useCallback((p,C)=>{c(M=>{let g=new Map(M),R=g.get(String(p));return (!C||R===C)&&g.delete(String(p)),g});},[]),s=useCallback((p,C)=>(i(M=>{let g=new Map(M);return g.set(String(p),C),g}),()=>{i(M=>{let g=new Map(M),R=g.get(String(p));return (!C||R===C)&&g.delete(String(p)),g});}),[]),l=useCallback((p,C)=>{i(M=>{let g=new Map(M),R=g.get(String(p));return (!C||R===C)&&g.delete(String(p)),g});},[]),u=useCallback((p,C)=>{S(M=>{let g=new Map(M);return C?g.set(p,true):g.delete(p),g});},[]),h=useCallback((p,C)=>{T(M=>{let g=new Map(M);return g.set(p,C),g});},[]),f=useMemo(()=>Array.from(w.values()).some(p=>p),[w]),k=useMemo(()=>Array.from(d.values()).some(p=>p),[d]),y=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:m,registerAction:a,unregisterAction:b,registerComponent:s,unregisterComponent:l,isAnyStreaming:f,setStreamingState:u,isAnyChatOpen:k,setChatOpenState:h,currentChatId:v,setCurrentChatId:x}),[e,t,n,o,m,a,b,s,l,f,u,k,h,v]);return jsx(qt.Provider,{value:y,children:r})}function ne(){let e=useContext(qt);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{}}}var Ct=25*1024*1024;function Vt(e){let{baseUrl:t}=ne(),n=e||t||"",[r,o]=useState([]),[c,m]=useState(false),i=useRef(null),w=useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let b=["B","KB","MB","GB","TB"],s=Math.min(b.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${b[s]}`},[]),S=useCallback(async a=>{let b=new FormData;b.append("file",a);let s=await fetch(jt(n,"/api/uploads"),{method:"POST",body:b});if(!s.ok){let u=await s.text().catch(()=>"");throw new Error(u||`Failed to upload ${a.name}`)}let l=await s.json();return {id:l.id,name:l.name||a.name,url:l.url,mimeType:l.mimeType||a.type||"application/octet-stream",size:typeof l.size=="number"?l.size:a.size}},[n]),d=useCallback(a=>{o(b=>b.filter(s=>s.id!==a));},[]),T=useCallback(async(a,b)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);b(null),m(true);let l=[];try{for(let u of s){if(u.size>Ct){b(`"${u.name}" exceeds the ${w(Ct)} limit.`);continue}try{let h=await S(u);l.push(h);}catch(h){console.error("Failed to upload attachment:",h),b(String(h?.message??`Failed to upload ${u.name}`));}}l.length&&o(u=>[...u,...l]);}finally{m(false);}},[S,w]),v=useCallback((a,b)=>{let s=[],l=(a||"").trim();l&&s.push({type:"text",text:l});for(let u of b||[]){let h=u.mimeType||"application/octet-stream";h.startsWith("image/")?s.push({type:"image",image:new URL(u.url),mediaType:h}):s.push({type:"file",data:u.url,mediaType:h,name:u.name});}return s},[]),x=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:c,fileInputRef:i,formatBytes:w,handleRemoveAttachment:d,handleFileSelection:T,buildUserContent:v,clearAttachments:x,setAttachments:o,MAX_UPLOAD_SIZE:Ct}}function Xt(e,t,n,r){return console.log("\u{1F680} [SDK] createHsafaTransport called with templateParams:",r),new DefaultChatTransport({api:`${e}/api/run/${t}`,fetch:async(o,c)=>{let m=c||{},i=m?.body?JSON.parse(m.body):{},w=r&&typeof r=="object"?r:{};console.log("\u{1F680} [SDK] Before merge - body:",i),console.log("\u{1F680} [SDK] Before merge - mergedParams:",w);let S={...w,...i,chatId:n};return console.log("\u{1F680} [SDK] After merge - enhancedBody:",S),fetch(o,{...c,body:JSON.stringify(S)})}})}function io(e){if(!(e instanceof HTMLElement))return true;let t=window.getComputedStyle(e);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&e.offsetParent!==null}function lo(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),r=n.querySelector("input, select, textarea");return r&&r.remove(),n.textContent?.trim()}}function vt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function kt(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function co(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let c=n.className.split(" ").filter(m=>m.trim()).slice(0,2);c.length>0&&(r+="."+c.join("."));}let o=n.parentElement;if(o){let c=Array.from(o.children).filter(m=>m.tagName===n.tagName);if(c.length>1){let m=c.indexOf(n)+1;r+=`:nth-child(${m})`;}}t.unshift(r),n=o;}return t.slice(-3).join(" > ")}async function Ne(e={}){try{let{includeHidden:t=!1,selector:n,what:r="content",limit:o}=e,c=document.querySelector(".hsafa-content-container");if(!c)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let m=n&&c.querySelector(n)||c,i=[],w=[];r==="inputs"?w=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:w=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],m.querySelectorAll(w.join(", ")).forEach(s=>{let l=io(s);if(!l&&!t)return;let u={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:l,isInteractive:!0,selector:co(s)};s instanceof HTMLInputElement?(u.type=s.type,u.name=s.name||void 0,u.placeholder=s.placeholder||void 0,u.value=kt(s),u.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,u.disabled=s.disabled,u.required=s.required):s instanceof HTMLTextAreaElement?(u.name=s.name||void 0,u.placeholder=s.placeholder||void 0,u.value=kt(s),u.disabled=s.disabled,u.required=s.required):s instanceof HTMLSelectElement?(u.name=s.name||void 0,u.value=kt(s),u.disabled=s.disabled,u.required=s.required,u.options=Array.from(s.options).map(h=>({value:h.value,label:h.text,selected:h.selected,disabled:h.disabled}))):s instanceof HTMLButtonElement?(u.type=s.type,u.disabled=s.disabled,u.text=vt(s)):s instanceof HTMLAnchorElement?(u.href=s.href,u.text=vt(s)):s instanceof HTMLImageElement?(u.text=s.alt||void 0,u.label=s.alt||u.label):u.text=vt(s),u.label=lo(s),u.role=s.getAttribute("role")||void 0,u.ariaLabel=s.getAttribute("aria-label")||void 0,i.push(u);});let d=s=>s.isVisible?r==="inputs"?s.tag==="input"||s.tag==="textarea"||s.tag==="select"||s.role==="textbox"?3:s.tag==="button"||s.tag==="a"?2:1:["header","nav","main","footer"].includes(s.tag)?5:["section","article","aside"].includes(s.tag)||["h1","h2","h3"].includes(s.tag)?4:["h4","h5","h6"].includes(s.tag)?3:s.tag==="form"?4:s.tag==="label"?3:s.tag==="input"||s.tag==="textarea"||s.tag==="select"?4:s.tag==="p"||s.tag==="img"||s.tag==="button"||s.tag==="a"?3:1:0;i.sort((s,l)=>d(l)-d(s));let T=i.length,x=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=T>x,b=a?i.slice(0,x):i;return {ok:!0,components:b,count:b.length,total:T,truncated:a,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=Ne);async function ve(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(r){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:r?.message||String(r)}]}}}typeof window<"u"&&(window.guideCursor=ve);function Yt(e){return !!e&&e.nodeType===1}function oe(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Jt(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,oe(e,"input");}function uo(e,t){e.checked!==t&&e.click();}function po(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(r=>r.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);oe(e,"input"),oe(e,"change");}function mo(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(r=>{r.selected=n.has(r.value)||n.has(r.text);}),oe(e,"input"),oe(e,"change");}function go(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function fo(e,t){let n=Array.isArray(t)?t:[t],r=new DataTransfer;for(let o of n)r.items.add(o);Object.defineProperty(e,"files",{value:r.files,configurable:true}),oe(e,"input"),oe(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&Yt(n)){let r=n.closest('[contenteditable="true"], [contenteditable=""]');r&&(n=r);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let r=n.tagName.toLowerCase();if(r==="input"){let o=n,c=(o.type||"text").toLowerCase();if(c==="checkbox")uo(o,!!e);else if(c==="radio"){let m=o.name;if(m&&e!=null&&String(o.value)!==String(e)){let i=document.querySelector(`input[type="radio"][name="${CSS.escape(m)}"][value="${CSS.escape(String(e))}"]`);i?i.click():o.click();}else o.click();}else if(c==="file")if(e instanceof File||Array.isArray(e)&&e.every(m=>m instanceof File))fo(o,e);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let m=c==="date"?go(e):String(e??"");Jt(o,m),oe(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,c=String(e??"");return Jt(o,c),oe(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?mo(o,Array.isArray(e)?e:[e]):po(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(Yt(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(e??""),oe(o,"input"),oe(o,"change"),o.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${r}`}],errors:[`Unsupported active element: ${r}`]}}catch(r){return {ok:false,filled:[{key:"active",status:"error",message:r?.message??String(r)}],errors:[r?.message??String(r)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var ze=null,Ze={},Qt=false,Ae=null,et=false;function wt(e){e.classList.add("visible");}function an(){et=true,Ae!=null&&(clearTimeout(Ae),Ae=null);}function ho(e,t=1500){et||(Ae!=null&&clearTimeout(Ae),Ae=window.setTimeout(()=>{et||e.classList.remove("visible");},t));}function xo(e,t=1200){et=false,ho(e,t);}function bo(e){let t=[],n=e?.parentElement;for(;n;){let r=getComputedStyle(n),o=r.overflow+r.overflowY+r.overflowX;/(auto|scroll)/.test(o)&&t.push(n),n=n.parentElement;}return t}async function Co(e,t=1500,n=160){let r=performance.now(),o=e?bo(e):[],c=()=>{let d=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(T=>{d.push(T.scrollLeft,T.scrollTop);}),d},m=()=>{if(!e)return {x:0,y:0};let d=e.getBoundingClientRect();return {x:d.left,y:d.top}},i=c(),w=m(),S=performance.now();return new Promise(d=>{function T(v){let x=c(),a=m(),b=false;for(let s=0;s<x.length;s++)if(x[s]!==i[s]){b=true;break}if(!b&&e&&(a.x!==w.x||a.y!==w.y)&&(b=true),b&&(i=x,w=a,S=v),v-S>=n||v-r>=t){d();return}requestAnimationFrame(T);}requestAnimationFrame(T);})}var vo='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32px" height="32px"><path d="M 7.2304688 4.9863281 C 5.9215232 4.8276681 4.8053213 6.0177722 5.0234375 7.3066406 A 1.0001 1.0001 0 0 0 5.0253906 7.3085938 C 5.9996339 12.981516 7.7205826 18.716222 10 24.515625 A 1.0001 1.0001 0 0 0 10 24.517578 C 10.26886 25.199332 10.914322 25.653844 11.5625 25.738281 C 12.210678 25.822721 12.879213 25.592031 13.359375 25.09375 C 14.505165 23.921134 15.214424 22.695429 15.90625 21.498047 C 17.56565 23.217848 19.256845 24.909775 21.0625 26.484375 L 21.060547 26.480469 C 21.799528 27.12933 22.841378 27.205969 23.673828 26.78125 A 1.0001 1.0001 0 0 0 23.691406 26.771484 C 24.987999 26.077693 26.028685 25.052256 26.71875 23.746094 L 26.71875 23.744141 C 27.174557 22.900924 27.06954 21.854242 26.439453 21.119141 A 1.0001 1.0001 0 0 0 26.433594 21.113281 C 24.867416 19.313474 23.193611 17.633865 21.488281 15.986328 C 22.714141 15.237691 23.933938 14.51508 25.158203 13.414062 A 1.0001 1.0001 0 0 0 25.162109 13.410156 C 26.052979 12.600274 25.977319 11.169141 25.101562 10.404297 A 1.0001 1.0001 0 0 0 24.669922 10.042969 C 18.793373 7.4738953 12.973806 5.6931843 7.2324219 4.9882812 A 1.0001 1.0001 0 0 0 7.2304688 4.9863281 z M 6.9960938 6.9746094 C 12.468883 7.6474978 18.081513 9.3573116 23.796875 11.849609 A 1.0001 1.0001 0 0 0 23.867188 11.884766 C 23.901248 11.899796 23.884276 11.867987 23.816406 11.929688 C 22.403891 13.198979 20.999383 14.076858 19.457031 14.976562 A 1.0001 1.0001 0 0 0 19.275391 16.568359 C 21.250864 18.425305 23.134972 20.36916 24.919922 22.419922 C 25.009402 22.524309 25.024026 22.676488 24.960938 22.792969 A 1.0001 1.0001 0 0 0 24.955078 22.804688 C 24.446951 23.770198 23.730542 24.476149 22.755859 25 C 22.611605 25.06851 22.457885 25.047856 22.378906 24.978516 A 1.0001 1.0001 0 0 0 22.376953 24.976562 C 20.293628 23.159824 18.307991 21.233373 16.419922 19.216797 A 1.0001 1.0001 0 0 0 14.835938 19.378906 C 13.841812 21.004716 13.152668 22.447221 11.925781 23.701172 A 1.0001 1.0001 0 0 0 11.919922 23.707031 C 11.883822 23.744501 11.865156 23.739957 11.847656 23.742188 C 9.6161121 18.057657 7.9395914 12.46667 6.9960938 6.9746094 z"/></svg>',ko='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function wo(){if(!Ze.arrow)try{Ze.arrow=vo,Ze.pointer=ko;}catch(e){console.warn("Failed to set cursor SVGs",e);}return Ze}function en({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function To(){let e="demo-fake-cursor",t=document.getElementById(e),n=await wo();if(!Qt){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
1
+ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import br,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext,Component}from'react';import {useChat}from'@ai-sdk/react';import {lastAssistantMessageIsCompleteWithToolCalls,DefaultChatTransport}from'ai';import {createRoot}from'react-dom/client';import {XMarkdown}from'@ant-design/x-markdown';import'@ant-design/x-markdown/themes/light.css';import'@ant-design/x-markdown/themes/dark.css';import {createPortal}from'react-dom';import {Plus,History,ChevronRight,Pencil,Trash2,File as File$1,Eye,X,Download}from'lucide-react';var Ie={};var sa=({variant:t="primary",size:e="md",loading:n=false,disabled:r,children:o,className:p,...f})=>{let c=[Ie.button,Ie[t],Ie[e],n&&Ie.loading,p].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:r||n,...f,children:[n&&jsx("span",{className:Ie.spinner}),jsx("span",{className:n?Ie.hiddenText:void 0,children:o})]})};function en({show:t,onClick:e,resolvedColors:n,floatingButtonPosition:r}){if(!t)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:e,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{p.currentTarget.style.borderColor=n.primaryColor,p.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:p=>{p.currentTarget.style.borderColor=n.borderColor,p.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function on(t=true){let e=useRef(null),n=useRef(t);return useEffect(()=>{n.current=t;},[t]),useEffect(()=>{let r=e.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),e}function rn(t,e){if(!t)return e;let n=t.endsWith("/")?t.slice(0,-1):t,r=e.startsWith("/")?e:`/${e}`;return `${n}${r}`}var an=createContext(void 0);function So({baseUrl:t,dir:e="ltr",theme:n="dark",children:r,tools:o,uiComponents:p}){let[f,c]=useState(new Map),[C,I]=useState(new Map),[m,w]=useState(()=>new Map(Object.entries(o||{}))),[v,h]=useState(()=>new Map(Object.entries(p||{}))),[s,u]=useState(new Map),[a,i]=useState(new Map),[l,g]=useState(void 0),d=useCallback((R,H)=>(c(A=>{let M=new Map(A);return M.set(String(R),H),M}),()=>{c(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});}),[]),x=useCallback((R,H)=>{c(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});},[]),y=useCallback((R,H)=>(I(A=>{let M=new Map(A);return M.set(String(R),H),M}),()=>{I(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});}),[]),b=useCallback((R,H)=>{I(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});},[]),k=useCallback((R,H)=>(w(A=>{let M=new Map(A);return M.set(String(R),H),M}),()=>{w(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});}),[]),E=useCallback((R,H)=>{w(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});},[]),T=useCallback((R,H)=>(h(A=>{let M=new Map(A);return M.set(String(R),H),M}),()=>{h(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});}),[]),P=useCallback((R,H)=>{h(A=>{let M=new Map(A),W=M.get(String(R));return (!H||W===H)&&M.delete(String(R)),M});},[]),B=useCallback((R,H)=>{u(A=>{let M=new Map(A);return H?M.set(R,true):M.delete(R),M});},[]),z=useCallback((R,H)=>{i(A=>{let M=new Map(A);return M.set(R,H),M});},[]),_=useMemo(()=>Array.from(s.values()).some(R=>R),[s]),j=useMemo(()=>Array.from(a.values()).some(R=>R),[a]),te=useMemo(()=>({baseUrl:t,dir:e,theme:n,actions:f,components:C,tools:m,uiComponents:v,registerAction:d,unregisterAction:x,registerComponent:y,unregisterComponent:b,registerTool:k,unregisterTool:E,registerUIComponent:T,unregisterUIComponent:P,isAnyStreaming:_,setStreamingState:B,isAnyChatOpen:j,setChatOpenState:z,currentChatId:l,setCurrentChatId:g}),[t,e,n,f,C,m,v,d,x,y,b,k,E,T,P,_,B,j,z,l]);return jsx(an.Provider,{value:te,children:r})}function ee(){let t=useContext(an);return t||{baseUrl:void 0,actions:new Map,components:new Map,tools:new Map,uiComponents:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},registerTool:()=>()=>{},unregisterTool:()=>{},registerUIComponent:()=>()=>{},unregisterUIComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{}}}var At=25*1024*1024;function ln(t){let{baseUrl:e}=ee(),n=t||e||"",[r,o]=useState([]),[p,f]=useState(false),c=useRef(null),C=useCallback(s=>{if(!s||Number.isNaN(s))return "0 B";let u=["B","KB","MB","GB","TB"],a=Math.min(u.length-1,Math.floor(Math.log(s)/Math.log(1024)));return `${(s/Math.pow(1024,a)).toFixed(a===0?0:1)} ${u[a]}`},[]),I=useCallback(async s=>{let u=new FormData;u.append("file",s);let a=await fetch(rn(n,"/api/uploads"),{method:"POST",body:u});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(l||`Failed to upload ${s.name}`)}let i=await a.json();return {id:i.id,name:i.name||s.name,url:i.url,mimeType:i.mimeType||s.type||"application/octet-stream",size:typeof i.size=="number"?i.size:s.size}},[n]),m=useCallback(s=>{o(u=>u.filter(a=>a.id!==s));},[]),w=useCallback(async(s,u)=>{if(!s)return;let a=Array.isArray(s)?s:Array.from(s);u(null),f(true);let i=[];try{for(let l of a){if(l.size>At){u(`"${l.name}" exceeds the ${C(At)} limit.`);continue}try{let g=await I(l);i.push(g);}catch(g){console.error("Failed to upload attachment:",g),u(String(g?.message??`Failed to upload ${l.name}`));}}i.length&&o(l=>[...l,...i]);}finally{f(false);}},[I,C]),v=useCallback((s,u)=>{let a=[],i=(s||"").trim();i&&a.push({type:"text",text:i});for(let l of u||[]){let g=l.mimeType||"application/octet-stream";g.startsWith("image/")?a.push({type:"image",image:new URL(l.url),mediaType:g}):a.push({type:"file",data:l.url,mediaType:g,name:l.name});}return a},[]),h=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:p,fileInputRef:c,formatBytes:C,handleRemoveAttachment:m,handleFileSelection:w,buildUserContent:v,clearAttachments:h,setAttachments:o,MAX_UPLOAD_SIZE:At}}function cn(t,e,n,r){return console.log("\u{1F680} [SDK] createHsafaTransport called with templateParams:",r),new DefaultChatTransport({api:`${t}/api/run/${e}`,fetch:async(o,p)=>{let f=p||{},c=f?.body?JSON.parse(f.body):{},C=r&&typeof r=="object"?r:{};console.log("\u{1F680} [SDK] Before merge - body:",c),console.log("\u{1F680} [SDK] Before merge - mergedParams:",C);let I={...C,...c,chatId:n};return console.log("\u{1F680} [SDK] After merge - enhancedBody:",I),fetch(o,{...p,body:JSON.stringify(I)})}})}function Ro(t){if(!(t instanceof HTMLElement))return true;let e=window.getComputedStyle(t);return e.display!=="none"&&e.visibility!=="hidden"&&e.opacity!=="0"&&t.offsetParent!==null}function Ho(t){if(t.id){let n=document.querySelector(`label[for="${t.id}"]`);if(n)return n.textContent?.trim()}let e=t.closest("label");if(e){let n=e.cloneNode(true),r=n.querySelector("input, select, textarea");return r&&r.remove(),n.textContent?.trim()}}function Et(t){if(t.textContent&&t.textContent.trim())return t.textContent.trim().slice(0,100)}function Rt(t){if(t instanceof HTMLInputElement){let e=t.type.toLowerCase();return e==="checkbox"||e==="radio"?t.checked:t.value}if(t instanceof HTMLTextAreaElement)return t.value;if(t instanceof HTMLSelectElement)return t.multiple?Array.from(t.selectedOptions).map(e=>e.value):t.value;if(t instanceof HTMLElement&&t.isContentEditable)return t.textContent||void 0}function Fo(t){if(t.id)return `#${t.id}`;let e=[],n=t;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let p=n.className.split(" ").filter(f=>f.trim()).slice(0,2);p.length>0&&(r+="."+p.join("."));}let o=n.parentElement;if(o){let p=Array.from(o.children).filter(f=>f.tagName===n.tagName);if(p.length>1){let f=p.indexOf(n)+1;r+=`:nth-child(${f})`;}}e.unshift(r),n=o;}return e.slice(-3).join(" > ")}async function Ge(t={}){try{let{includeHidden:e=!1,selector:n,what:r="content",limit:o}=t,p=document.querySelector(".hsafa-content-container");if(!p)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let f=n&&p.querySelector(n)||p,c=[],C=[];r==="inputs"?C=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:C=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],f.querySelectorAll(C.join(", ")).forEach(a=>{let i=Ro(a);if(!i&&!e)return;let l={id:a.id||null,tag:a.tagName.toLowerCase(),className:a.className&&typeof a.className=="string"?a.className:void 0,isVisible:i,isInteractive:!0,selector:Fo(a)};a instanceof HTMLInputElement?(l.type=a.type,l.name=a.name||void 0,l.placeholder=a.placeholder||void 0,l.value=Rt(a),l.checked=a.type==="checkbox"||a.type==="radio"?a.checked:void 0,l.disabled=a.disabled,l.required=a.required):a instanceof HTMLTextAreaElement?(l.name=a.name||void 0,l.placeholder=a.placeholder||void 0,l.value=Rt(a),l.disabled=a.disabled,l.required=a.required):a instanceof HTMLSelectElement?(l.name=a.name||void 0,l.value=Rt(a),l.disabled=a.disabled,l.required=a.required,l.options=Array.from(a.options).map(g=>({value:g.value,label:g.text,selected:g.selected,disabled:g.disabled}))):a instanceof HTMLButtonElement?(l.type=a.type,l.disabled=a.disabled,l.text=Et(a)):a instanceof HTMLAnchorElement?(l.href=a.href,l.text=Et(a)):a instanceof HTMLImageElement?(l.text=a.alt||void 0,l.label=a.alt||l.label):l.text=Et(a),l.label=Ho(a),l.role=a.getAttribute("role")||void 0,l.ariaLabel=a.getAttribute("aria-label")||void 0,c.push(l);});let m=a=>a.isVisible?r==="inputs"?a.tag==="input"||a.tag==="textarea"||a.tag==="select"||a.role==="textbox"?3:a.tag==="button"||a.tag==="a"?2:1:["header","nav","main","footer"].includes(a.tag)?5:["section","article","aside"].includes(a.tag)||["h1","h2","h3"].includes(a.tag)?4:["h4","h5","h6"].includes(a.tag)?3:a.tag==="form"?4:a.tag==="label"?3:a.tag==="input"||a.tag==="textarea"||a.tag==="select"?4:a.tag==="p"||a.tag==="img"||a.tag==="button"||a.tag==="a"?3:1:0;c.sort((a,i)=>m(i)-m(a));let w=c.length,h=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),s=w>h,u=s?c.slice(0,h):c;return {ok:!0,components:u,count:u.length,total:w,truncated:s,containerFound:!0}}catch(e){return {ok:false,components:[],count:0,total:0,containerFound:false,error:e?.message||String(e)}}}typeof window<"u"&&(window.getDomComponents=Ge);async function Se(t,e={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(t,e)}catch(r){return {ok:false,steps:[{ok:false,action:e.action||"none",targetKind:"position",durationMs:0,error:r?.message||String(r)}]}}}typeof window<"u"&&(window.guideCursor=Se);function dn(t){return !!t&&t.nodeType===1}function de(t,e){t.dispatchEvent(new Event(e,{bubbles:true}));}function un(t,e){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value")?.set;n?n.call(t,e):t.value=e,de(t,"input");}function Lo(t,e){t.checked!==e&&t.click();}function Do(t,e){if(typeof e=="object"&&e&&"index"in e&&typeof e.index=="number")t.selectedIndex=Math.max(0,Math.min(t.options.length-1,e.index));else if(typeof e=="object"&&e&&"label"in e&&typeof e.label=="string"){let n=Array.from(t.options).findIndex(r=>r.text===e.label);t.selectedIndex=n>=0?n:0;}else t.value=String(e);de(t,"input"),de(t,"change");}function Po(t,e){let n=new Set(e.map(String));Array.from(t.options).forEach(r=>{r.selected=n.has(r.value)||n.has(r.text);}),de(t,"input"),de(t,"change");}function Bo(t){return t?t instanceof Date?t.toISOString().slice(0,10):String(t):""}function $o(t,e){let n=Array.isArray(e)?e:[e],r=new DataTransfer;for(let o of n)r.items.add(o);Object.defineProperty(t,"files",{value:r.files,configurable:true}),de(t,"input"),de(t,"change");}async function je(t,e={}){let n=document.activeElement||null;if(n&&dn(n)){let r=n.closest('[contenteditable="true"], [contenteditable=""]');r&&(n=r);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let r=n.tagName.toLowerCase();if(r==="input"){let o=n,p=(o.type||"text").toLowerCase();if(p==="checkbox")Lo(o,!!t);else if(p==="radio"){let f=o.name;if(f&&t!=null&&String(o.value)!==String(t)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(f)}"][value="${CSS.escape(String(t))}"]`);c?c.click():o.click();}else o.click();}else if(p==="file")if(t instanceof File||Array.isArray(t)&&t.every(f=>f instanceof File))$o(o,t);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let f=p==="date"?Bo(t):String(t??"");un(o,f),de(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,p=String(t??"");return un(o,p),de(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?Po(o,Array.isArray(t)?t:[t]):Do(o,t),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(dn(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(t??""),de(o,"input"),de(o,"change"),o.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${r}`}],errors:[`Unsupported active element: ${r}`]}}catch(r){return {ok:false,filled:[{key:"active",status:"error",message:r?.message??String(r)}],errors:[r?.message??String(r)]}}}typeof window<"u"&&(window.FillActiveInput=je);var Ve=null,rt={},fn=false,Le=null,st=false;function Ht(t){t.classList.add("visible");}function Cn(){st=true,Le!=null&&(clearTimeout(Le),Le=null);}function Uo(t,e=1500){st||(Le!=null&&clearTimeout(Le),Le=window.setTimeout(()=>{st||t.classList.remove("visible");},e));}function Oo(t,e=1200){st=false,Uo(t,e);}function zo(t){let e=[],n=t?.parentElement;for(;n;){let r=getComputedStyle(n),o=r.overflow+r.overflowY+r.overflowX;/(auto|scroll)/.test(o)&&e.push(n),n=n.parentElement;}return e}async function Wo(t,e=1500,n=160){let r=performance.now(),o=t?zo(t):[],p=()=>{let m=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(w=>{m.push(w.scrollLeft,w.scrollTop);}),m},f=()=>{if(!t)return {x:0,y:0};let m=t.getBoundingClientRect();return {x:m.left,y:m.top}},c=p(),C=f(),I=performance.now();return new Promise(m=>{function w(v){let h=p(),s=f(),u=false;for(let a=0;a<h.length;a++)if(h[a]!==c[a]){u=true;break}if(!u&&t&&(s.x!==C.x||s.y!==C.y)&&(u=true),u&&(c=h,C=s,I=v),v-I>=n||v-r>=e){m();return}requestAnimationFrame(w);}requestAnimationFrame(w);})}var Go='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32px" height="32px"><path d="M 7.2304688 4.9863281 C 5.9215232 4.8276681 4.8053213 6.0177722 5.0234375 7.3066406 A 1.0001 1.0001 0 0 0 5.0253906 7.3085938 C 5.9996339 12.981516 7.7205826 18.716222 10 24.515625 A 1.0001 1.0001 0 0 0 10 24.517578 C 10.26886 25.199332 10.914322 25.653844 11.5625 25.738281 C 12.210678 25.822721 12.879213 25.592031 13.359375 25.09375 C 14.505165 23.921134 15.214424 22.695429 15.90625 21.498047 C 17.56565 23.217848 19.256845 24.909775 21.0625 26.484375 L 21.060547 26.480469 C 21.799528 27.12933 22.841378 27.205969 23.673828 26.78125 A 1.0001 1.0001 0 0 0 23.691406 26.771484 C 24.987999 26.077693 26.028685 25.052256 26.71875 23.746094 L 26.71875 23.744141 C 27.174557 22.900924 27.06954 21.854242 26.439453 21.119141 A 1.0001 1.0001 0 0 0 26.433594 21.113281 C 24.867416 19.313474 23.193611 17.633865 21.488281 15.986328 C 22.714141 15.237691 23.933938 14.51508 25.158203 13.414062 A 1.0001 1.0001 0 0 0 25.162109 13.410156 C 26.052979 12.600274 25.977319 11.169141 25.101562 10.404297 A 1.0001 1.0001 0 0 0 24.669922 10.042969 C 18.793373 7.4738953 12.973806 5.6931843 7.2324219 4.9882812 A 1.0001 1.0001 0 0 0 7.2304688 4.9863281 z M 6.9960938 6.9746094 C 12.468883 7.6474978 18.081513 9.3573116 23.796875 11.849609 A 1.0001 1.0001 0 0 0 23.867188 11.884766 C 23.901248 11.899796 23.884276 11.867987 23.816406 11.929688 C 22.403891 13.198979 20.999383 14.076858 19.457031 14.976562 A 1.0001 1.0001 0 0 0 19.275391 16.568359 C 21.250864 18.425305 23.134972 20.36916 24.919922 22.419922 C 25.009402 22.524309 25.024026 22.676488 24.960938 22.792969 A 1.0001 1.0001 0 0 0 24.955078 22.804688 C 24.446951 23.770198 23.730542 24.476149 22.755859 25 C 22.611605 25.06851 22.457885 25.047856 22.378906 24.978516 A 1.0001 1.0001 0 0 0 22.376953 24.976562 C 20.293628 23.159824 18.307991 21.233373 16.419922 19.216797 A 1.0001 1.0001 0 0 0 14.835938 19.378906 C 13.841812 21.004716 13.152668 22.447221 11.925781 23.701172 A 1.0001 1.0001 0 0 0 11.919922 23.707031 C 11.883822 23.744501 11.865156 23.739957 11.847656 23.742188 C 9.6161121 18.057657 7.9395914 12.46667 6.9960938 6.9746094 z"/></svg>',jo='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function Vo(){if(!rt.arrow)try{rt.arrow=Go,rt.pointer=jo;}catch(t){console.warn("Failed to set cursor SVGs",t);}return rt}function mn({arrowSvg:t,pointerSvg:e}){return jsxs(Fragment,{children:[t&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:t}}),e&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:e}})]})}async function _o(){let t="demo-fake-cursor",e=document.getElementById(t),n=await Vo();if(!fn){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
2
2
  .fake-cursor { pointer-events: none; opacity: 0; transition: opacity 0.2s ease; z-index: 2147483647; }
3
3
  .fake-cursor.visible { opacity: 1; }
4
4
  .fake-cursor .arrow { display: none; }
@@ -8,12 +8,12 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Wo,{createContext,useRe
8
8
  .fake-cursor.as-pointer .arrow { display: none; }
9
9
  .fake-cursor.as-pointer .pointer { display: block; }
10
10
  .fake-cursor.pressing .pointer svg path { filter: brightness(0.9); }
11
- `,document.head.appendChild(o);}Qt=true;}return t?(t.classList.add("as-arrow"),ze||(ze=createRoot(t),ze.render(jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),ze=createRoot(t),ze.render(jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Re(e,t,n){return Math.max(t,Math.min(n,e))}function Io(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function sn(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let r=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!r)return null;let o=r[1].split(/\s*,\s*/).map(Number),[c,m,i,w=1]=o;return {r:c,g:m,b:i,a:w}}function So({r:e,g:t,b:n}){let r=[e,t,n].map(o=>o/255).map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*r[0]+.7152*r[1]+.0722*r[2]}function Mo(e){let t=e?sn(e):null;return !t||t.a===0?false:So(t)<.5}function Eo(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let m=getComputedStyle(n).backgroundColor,i=sn(m);if(i&&i.a>0)return m;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Tt(e,t,n){let r=Eo(t,n),o=Mo(r),c=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(i=>{i.style.fill="white",i.style.stroke=c,i.style.strokeWidth="1";}),e.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function Qe(e,t,n,r,o="ease-in-out",c="curve",m=.25,i="auto",w){an(),wt(e);let S=performance.now(),d=o==="linear"?x=>x:Io,T=c!=="straight",v={x:0,y:0};if(T){let x=n.x-t.x,a=n.y-t.y,b=Math.hypot(x,a)||1,s=(t.x+n.x)/2,l=(t.y+n.y)/2,u=-a/b,h=x/b,f=1;i==="left"?f=-1:i==="right"?f=1:f=Math.random()<.5?-1:1;let k=Re(m,0,1)*b;v={x:s+f*u*k,y:l+f*h*k};}return new Promise(x=>{function a(b){let s=Re((b-S)/r,0,1),l=d(s),u,h;if(T){let C=1-l;u=C*C*t.x+2*C*l*v.x+l*l*n.x,h=C*C*t.y+2*C*l*v.y+l*l*n.y;}else u=t.x+(n.x-t.x)*l,h=t.y+(n.y-t.y)*l;let k=.35*(1-l),y=Math.sin(b*.02)*k,p=Math.cos(b*.018)*k;e.style.left=`${u+y}px`,e.style.top=`${h+p}px`,Tt(e,u+y,h+p),w&&w({x:u+y,y:h+p,t:s,now:b}),s<1?requestAnimationFrame(a):x();}requestAnimationFrame(a);})}function tn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function le(e,t,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let c=t==="pointerdown"||t==="mousedown",m=t==="pointerup"||t==="mouseup",i={button:0,buttons:c?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let w=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...i});e.dispatchEvent(w);}else {let w=new MouseEvent(t,i);e.dispatchEvent(w);}}catch{let c=new MouseEvent(t,o);e.dispatchEvent(c);}}function ln(e){return e&&typeof e=="object"&&e.nodeType===1}function Ao(e){if(!e)return document;if(ln(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function nn(e){if(ln(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Ao(e.within??null).querySelectorAll(e.selector),r=Math.max(0,Math.min(n.length-1,e.nth??0)),o=n[r]??null;return {kind:o?"element":"position",element:o}}return {kind:"position",point:{x:0,y:0}}}function on(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let r=Re(t.x,0,1),o=Re(t.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function rn(e){return {x:Re(e.x,0,window.innerWidth),y:Re(e.y,0,window.innerHeight)}}function Ro(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await To();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),wt(o),an();let c=parseFloat(o.style.left||"20")||20,m=parseFloat(o.style.top||"20")||20;Tt(o,c,m);for(let i of n){let{durationMs:w=800,easing:S="ease-in-out",offset:d,highlight:T=true,path:v="curve",curveStrength:x=.25,curveDirection:a="auto",anchor:b,cursorHotspot:s,dragTo:l}=i.options??{},u=i.action??i.options?.action??"none",h=performance.now(),f=nn(i.target),k=null,y=null;if(f.kind==="element"&&f.element?(y=f.element,o.classList.remove("visible"),y.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Co(y,1500,180),wt(o),k=on(y,b)):f.kind==="position"&&f.point&&(k=f.point),!k){r.push({ok:false,action:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),error:"Target not found"});continue}let p={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},C=rn(tn(k,d));await Qe(o,p,C,w,S,v,x,a);let M=C.x-p.x,g=C.y-p.y,R=Math.hypot(M,g)||1,N=M/R,U=g/R,te=Math.min(6,Math.max(3,R*.02)),ye={x:C.x+N*te,y:C.y+U*te};await Qe(o,C,ye,Math.max(70,w*.1),"ease-out","straight",0,"right"),await Qe(o,ye,C,120,"ease-out","straight",0,"left"),T&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let ue=null;try{if(u==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let A={x:s?.x??0,y:s?.y??0},B={x:C.x+A.x,y:C.y+A.y};o.style.left=`${B.x}px`,o.style.top=`${B.y}px`,Tt(o,B.x,B.y);let _=y??document.elementFromPoint(B.x,B.y)??document.body;le(_,"pointerdown",B),le(_,"mousedown",B),await new Promise(V=>setTimeout(V,90)),o.classList.remove("pressing"),le(_,"mouseup",B),le(_,"click",B),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),_ instanceof HTMLElement&&_.focus?.(),ue=_?.id??null;}else if(u==="drag"){if(!l)throw new Error("dragTo is required for action 'drag'");let A=nn(l),B=null;if(A.kind==="element"&&A.element&&(B=on(A.element,b)),A.kind==="position"&&A.point&&(B=A.point),!B)throw new Error("dragTo target not found");let _=rn(tn(B,d)),V={x:C.x,y:C.y},ie=y??document.elementFromPoint(V.x,V.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),le(ie,"pointerdown",V),le(ie,"mousedown",V),await Qe(o,V,_,Math.max(200,w),S,v,x,a,({x:$,y:he})=>{let ce=document.elementFromPoint($,he)??document.body,xe={x:$,y:he};le(ce,"pointermove",xe),le(ce,"mousemove",xe);});let O=document.elementFromPoint(_.x,_.y)??document.body;o.classList.remove("pressing"),le(O,"pointerup",_),le(O,"mouseup",_);}r.push({ok:!0,action:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),clickedElementId:ue});}catch(A){r.push({ok:false,action:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),error:A?.message??String(A)});}}return xo(o,2e3),{ok:r.every(i=>i.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var nt=Ro;function cn(){return {getDomComponents:{tool:async({includeHidden:e,selector:t})=>await Ne({includeHidden:e,selector:t}),executeEachToken:false},controlCursor:{tool:async({target:e,action:t,anchor:n,durationMs:r,dragTo:o})=>{let c=await ve(e,{action:t,anchor:n,durationMs:r,dragTo:o});if(c&&c.ok){let m=Array.isArray(c.steps)&&c.steps.length?c.steps[c.steps.length-1]:void 0,i=m?.clickedElementId?` (clicked element id: ${m.clickedElementId})`:"",w=t||m?.action||"none";return {success:true,message:w==="click"?`Cursor moved and clicked successfully${i}`:w==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:c}}return {success:false,message:"Cursor action failed",details:c}},executeEachToken:false},fillActiveInput:{tool:async({value:e})=>{let t=await Ue(e);return {success:!!t?.ok,message:t?.ok?"Active input filled successfully":t?.errors?.[0]||"Failed to fill active input",details:t}},executeEachToken:true},requestInput:{tool:async e=>({ok:true}),executeEachToken:true}}}function We({content:e,theme:t="dark",streaming:n=false}){return jsx(XMarkdown,{content:e,className:t==="dark"?"x-markdown-dark":"x-markdown-light",streaming:{hasNextChunk:n,enableAnimation:true,animationConfig:{fadeDuration:200},incompleteMarkdownComponentMap:{html:"IncompleteBlock",link:"IncompleteBlock",image:"IncompleteBlock"}},openLinksInNewTab:true,config:{gfm:true},dompurifyConfig:{ADD_TAGS:["data-chart","welcome","user-card","mermaid"],ADD_ATTR:["data-source","data-spec","data-icon","data-description","data-raw"]},style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"}})}function Do({input:e}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(We,{content:e?.text||"",theme:"dark"})})}function un(){return {plainText:Do}}function pn(e,t,n,r,o,c){let m=n.get(t);if(m){let f=m.parentElement,k=document.querySelector(`[data-get-from-user-host="${t}"]`);if(k&&f!==k){try{f?.removeChild(m);}catch{}k.innerHTML="",k.appendChild(m);}}else {m=document.createElement("div"),m.className="hsafa-inline-form";let f=document.querySelector(`[data-get-from-user-host="${t}"]`);f?(f.innerHTML="",f.appendChild(m)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(m),n.set(t,m);}let i=e?.title||"Provide input",w=e?.description||"",S=e?.submitLabel||"Submit",d=e?.skipLabel||"Skip",T=Array.isArray(e?.fields)?e.fields:e?.label||e?.placeholder?[{id:"value",label:e?.label||"Value",type:"text",placeholder:e?.placeholder||""}]:[],v=r.get(t)||{submitted:false,skipped:false,values:void 0};m.innerHTML="";let x=document.createElement("form");x.style.margin="12px 0",x.style.padding="14px",x.style.border="1px solid var(--hsafa-border, #2A2C33)",x.style.borderRadius="12px",x.style.background="var(--hsafa-card, #121318)",x.style.color="var(--hsafa-text, #EDEEF0)",x.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let a=document.createElement("div");if(a.style.fontWeight="600",a.style.marginBottom="6px",a.textContent=i,x.appendChild(a),w){let f=document.createElement("div");f.style.fontSize="12px",f.style.opacity="0.8",f.style.marginBottom="10px",f.textContent=w,x.appendChild(f);}T.forEach(f=>{let k=document.createElement("div");if(k.style.margin="10px 0",f.label){let g=document.createElement("label");g.style.display="block",g.style.fontSize="12px",g.style.marginBottom="6px",g.style.opacity="0.9",g.textContent=f.label,k.appendChild(g);}let y,p=(f.type||"text").toLowerCase();if(p==="textarea"){let g=document.createElement("textarea");g.placeholder=f.placeholder||"",g.value=f.value??"",g.style.width="100%",g.style.minHeight="72px",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",y=g;}else if(p==="select"&&Array.isArray(f.options)){let g=document.createElement("select");g.style.width="100%",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",f.options.forEach(R=>{let N=document.createElement("option");N.value=String(R.value),N.text=String(R.label??R.value),g.appendChild(N);}),g.value=f.value??"",y=g;}else if(p==="checkbox"){let g=document.createElement("input");g.type="checkbox",g.checked=!!f.value,g.style.transform="scale(1.1)",y=g;}else {let g=document.createElement("input");g.type=p,g.placeholder=f.placeholder||"",g.value=f.value??"",g.style.width="100%",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",y=g;}let C=f.id||"value";y.dataset.fieldId=C;let M=v.values&&Object.prototype.hasOwnProperty.call(v.values,C)?v.values[C]:void 0;typeof M<"u"&&(y.type==="checkbox"?y.checked=!!M:y.value=String(M)),(v.submitted||v.skipped)&&(y.setAttribute("disabled","true"),y.style.opacity="0.7"),k.appendChild(y),x.appendChild(k);});let b=String(S).trim(),s=String(d).trim(),l=!!(b||s),u=null,h=null;if(l){let f=document.createElement("div");f.style.display="flex",f.style.gap="8px",f.style.marginTop="10px",u=document.createElement("button"),u.type="submit",u.textContent=b||"Submit",u.style.padding="6px 10px",u.style.borderRadius="8px",u.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",u.style.color="#000000",h=document.createElement("button"),h.type="button",h.textContent=s||"Skip",h.style.padding="6px 10px",h.style.borderRadius="8px",h.style.background="transparent",h.style.border="1px solid var(--hsafa-border, #2A2C33)",h.style.color="inherit",f.appendChild(u),f.appendChild(h),x.appendChild(f);}if(x.onsubmit=f=>{f.preventDefault();let k={};x.querySelectorAll("[data-field-id]").forEach(y=>{let p=y.dataset.fieldId||"value";y.type==="checkbox"?k[p]=y.checked:k[p]=y.value??"";}),r.set(t,{submitted:true,skipped:false,values:k}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:k}}),x.querySelectorAll("[data-field-id]").forEach(y=>{y.disabled=true,y.style.opacity="0.7";}),u&&(u.textContent=`${b||"Submit"} \u2713`,u.style.opacity="0.8",u.disabled=true),h&&(h.disabled=true);},h&&(h.onclick=()=>{r.set(t,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:false,skipped:true}}),x.querySelectorAll("[data-field-id]").forEach(f=>{f.disabled=true,f.style.opacity="0.7";}),h&&(h.textContent=`${s||"Skip"} \u2713`,h.style.opacity="0.8",h.disabled=true),u&&(u.disabled=true);}),v.submitted||v.skipped){let f=document.createElement("div");f.style.marginTop="10px",f.style.fontSize="12px",f.style.display="flex",f.style.alignItems="center",f.style.gap="8px";let k=document.createElement("span");k.style.display="inline-flex",k.style.alignItems="center",k.style.padding="2px 8px",k.style.borderRadius="999px",k.style.fontWeight="600",k.style.fontSize="11px",v.submitted?(k.style.background="rgba(16,185,129,0.15)",k.style.color="#10b981",k.textContent="Submitted"):(k.style.background="rgba(234,179,8,0.15)",k.style.color="#eab308",k.textContent="Skipped"),f.appendChild(k),x.appendChild(f);try{u&&(u.disabled=!0,u.style.opacity="0.8",v.submitted&&(u.textContent=`${b||"Submit"} \u2713`)),h&&(h.disabled=!0,h.style.opacity="0.8",v.skipped&&(h.textContent=`${s||"Skip"} \u2713`));}catch{}}m.appendChild(x);}function mn(e){return !!e&&typeof e=="object"}function gn(e,t,n){let r=useRef(new Map),o=useRef(new Map),c=useRef(new Map),m=useRef(t),i=useRef(n);m.current=t,i.current=n,useEffect(()=>{e.forEach(w=>{if(!mn(w)||w.role!=="assistant")return;(Array.isArray(w.parts)?w.parts:[]).forEach(d=>{if(!mn(d)||typeof d.toolCallId!="string"||!d.toolCallId)return;let T=typeof d.toolName=="string"?d.toolName:void 0,v=typeof d.type=="string"?d.type:"";if(!T&&v.startsWith("tool-")&&(T=v.replace(/^tool-/,"")),!T)return;let x=m.current[T];try{let a=String(d.state||d.status||""),b=o.current.get(d.toolCallId);if(a&&a!==b&&x&&typeof x=="object"){o.current.set(d.toolCallId,a);let s=d.input??d.args??{},l={toolCallId:d.toolCallId,toolName:T},u=x;a==="input-streaming"&&typeof u.inputting_start=="function"&&u.inputting_start(s,l),a==="input-available"&&typeof u.running_start=="function"&&u.running_start(s,l);}}catch{}if(x&&typeof x=="object"&&x.executeEachToken&&x.tool){let a=d.input??d.args??{},b=JSON.stringify(a),s=r.current.get(d.toolCallId);if(b!==s&&b!=="{}"){r.current.set(d.toolCallId,b);try{if(T==="requestInput")i.current(a,d.toolCallId);else {let u=(c.current.get(d.toolCallId)||0)+1;c.current.set(d.toolCallId,u),u>1&&x.tool({...a,toolCallNumber:u-1});}}catch{}}}});});},[e]);}function St(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:c,onFinish:m,onError:i,initialMessages:w=[],onMessagesChange:S,controlledChatId:d,onChatIdChange:T,templateParams:v}=e,{baseUrl:x,setCurrentChatId:a}=ne(),b=n&&n.length>0?n:x||"",[s,l]=useState(""),[u,h]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),f=d??u,k=useCallback(E=>{d===void 0&&h(E),T&&T(E);},[d,T]);useEffect(()=>{try{a(f);}catch{}return ()=>{try{a(void 0);}catch{}}},[f,a]);let y=useMemo(()=>Xt(b,t,f,v),[b,t,f,v]),p=useCallback(E=>{console.log("Message finished:",E);let F=E?.message?.id;if(!F&&Array.isArray(E?.messages))for(let z=E.messages.length-1;z>=0;z--){let H=E.messages[z];if(H&&H.role==="assistant"&&H.id){F=H.id;break}}m?.({...E,chatId:f,assistantMessageId:F});},[m,f]),C=useCallback(E=>{console.error("Chat error:",E),i?.(E);},[i]),M=useMemo(()=>cn(),[]),g=useMemo(()=>({...M,...r}),[M,r]),R=useMemo(()=>un(),[]),N=useMemo(()=>({...R,...o}),[R,o]),U=useRef(new Map),te=useRef(new Map),ye=useCallback(()=>{try{U.current.forEach(E=>{try{E.remove();}catch{}}),U.current.clear(),te.current.clear();}catch{}},[]),ue=useCallback((E,F)=>{pn(E,F,U.current,te.current,z=>A.current.addToolResult(z));},[]),A=useRef(null),B=useRef(new Set),_=useCallback((E,F,z)=>{console.error(`UI Error [${F}]:`,z),A.current&&B.current.has(E)&&(B.current.delete(E),A.current.addToolResult({tool:F,toolCallId:E,state:"output-error",errorText:z?.message||String(z)}));},[]),V=useCallback((E,F)=>{A.current&&B.current.has(E)&&(B.current.delete(E),A.current.addToolResult({tool:F,toolCallId:E,output:{status:"ok",rendered:true,component:F,logs:[]}}));},[]),ie=useCallback(E=>{let F=g[E];return F?typeof F=="object"&&"tool"in F?F.tool:typeof F=="function"?F:null:null},[g]),O=useChat({transport:y,onFinish:p,onError:C,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:E}){let F=ie(E.toolName);if(E.toolName==="requestInput"){try{ue(E.input,E.toolCallId);}catch(J){console.error("requestInput render error",J);}return}let z=E.toolName==="ui",H=N&&E.toolName in N;if((z||H)&&!F){B.current.add(E.toolCallId);return}if(F)try{let J=await F(E.input);O.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,output:J});}catch(J){O.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,state:"output-error",errorText:J?.message||String(J)});}}}),{messages:$,sendMessage:he,status:ce,stop:xe,error:mt}=O;A.current=O,gn($,g,ue),useEffect(()=>{try{let E=new Set,F=[];if($.forEach(z=>{z.role==="assistant"&&(z.parts||[]).forEach(H=>{if((H?.toolName||(typeof H?.type=="string"&&H.type.startsWith("tool-")?String(H.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let J=H?.toolCallId||"";if(!J)return;E.add(J);let de=H?.output;if(de&&(de.submitted||de.skipped||de.values)){let be={submitted:!!de.submitted,skipped:!!de.skipped,values:de.values||void 0};te.current.set(J,be);}let X=H?.input||H?.args||{};F.push({input:X,toolCallId:J});});}),U.current.forEach((z,H)=>{if(!E.has(H)){let Z=U.current.get(H);try{Z?.remove();}catch{}U.current.delete(H),te.current.delete(H);}}),F.length>0){let z=requestAnimationFrame(()=>{F.forEach(({input:H,toolCallId:Z})=>{try{ue(H,Z);}catch{}});});return ()=>cancelAnimationFrame(z)}}catch{}},[$,ue]),useEffect(()=>{w&&w.length>0&&$.length===0&&console.log("Initial messages:",w);},[w,$.length]);let q=ce==="submitted"||ce==="streaming",Ke=useCallback(()=>{S&&S($,f);},[S,$,f]),Fe=useCallback(async E=>{let F=E?.text!==void 0?E.text:s,z=E?.files||[],H=F.trim();if(!(!H&&z.length===0)&&!q){E?.text===void 0&&l("");try{if(c){let Z={role:"user",content:H,createdAt:Date.now(),chatId:f};c(Z);}await he({text:H,files:z});}catch(Z){throw console.error("Failed to send message:",Z),Z}}},[s,q,he,c,f]),Ie=useCallback(()=>{if(q)return;ye(),l("");try{O?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;k(E);},[q,O,ye,k]),Ht=useCallback(E=>{try{O?.setMessages?.(E);}catch{}},[O]);return {input:s,setInput:l,messages:$,isLoading:q,status:ce,error:mt,sendMessage:Fe,stop:xe,newChat:Ie,setMessages:Ht,notifyMessagesChange:Ke,chatApi:O,chatId:f,setChatId:k,tools:g,uiComponents:N,formHostRef:U,formStateRef:te,cleanupForms:ye,onUISuccess:V,onUIError:_}}function rt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=h=>`${t}.chat.${h}`,o=`${t}.currentChatId`,c=`${t}.showChat`,m=()=>{try{let h=localStorage.getItem(n);return h?JSON.parse(h):[]}catch{return []}},i=h=>{try{localStorage.setItem(n,JSON.stringify(h));}catch{}},w=h=>{try{let f=localStorage.getItem(r(h));return f?JSON.parse(f):null}catch{return null}},S=h=>{try{localStorage.setItem(r(h.id),JSON.stringify(h));}catch{}},d=h=>{let f=m(),k=f.findIndex(y=>y.id===h.id);k>=0?f[k]=h:f.unshift(h),i(f);},T=h=>{let k=m().filter(y=>y.id!==h);i(k);},v=h=>{try{localStorage.removeItem(r(h));}catch{}};return {loadChatsIndex:m,saveChatsIndex:i,loadChat:w,saveChat:S,upsertChatMeta:d,deleteChatMeta:T,deleteChatData:v,deleteChat:h=>{v(h),T(h);},loadShowChatPreference:h=>{try{let f=localStorage.getItem(c);return f!==null?f==="true":h}catch{return h}},saveShowChatPreference:h=>{try{localStorage.setItem(c,String(h));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:h=>{try{localStorage.setItem(o,h);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Et(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:c=true,autoRestore:m=true}=e,i=useMemo(()=>rt(t),[t]),[w,S]=useState([]),[d,T]=useState(null),v=useRef(false),x=useRef(false),a=useCallback(()=>{try{let y=i.loadChatsIndex();S(y);let p=y.find(C=>C.id===n);T(p||null);}catch(y){console.error("Failed to refresh chat list:",y);}},[i,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!m||x.current)){try{i.loadCurrentChatId()&&(v.current=!0);}catch(y){console.error("Failed to restore chat:",y);}x.current=true;}},[i,m]),useEffect(()=>{if(!(!c||r.length===0))if(v.current){if(!o){let y=Date.now();try{i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);C&&(i.upsertChatMeta({...C,updatedAt:y}),a());}catch(p){console.error("Failed to save chat:",p);}}}else {let y=r.find(p=>p.role==="user");if(y){let p="";if(Array.isArray(y.parts)){let g=y.parts.find(R=>R&&R.type==="text");p=g&&typeof g.text=="string"?g.text:"";}let C=(p||"New chat").slice(0,80),M=Date.now();try{i.upsertChatMeta({id:n,title:C,createdAt:M,updatedAt:M}),i.saveChat({id:n,messages:r,agentId:t}),i.saveCurrentChatId(n),v.current=!0,a();}catch(g){console.error("Failed to create chat:",g);}}}},[]);let b=useRef(false);useEffect(()=>{if(o){b.current=true;return}if(b.current&&c){b.current=false;try{let y=Date.now();i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);if(C)i.upsertChatMeta({...C,updatedAt:y});else {let M="",g=Array.isArray(r)?r.find(N=>N&&N.role==="user"):void 0;if(g&&Array.isArray(g.parts)){let N=g.parts.find(U=>U&&U.type==="text");M=N&&typeof N.text=="string"?N.text:"";}let R=(M||"New chat").slice(0,80);i.upsertChatMeta({id:n,title:R,createdAt:y,updatedAt:y});try{i.saveCurrentChatId(n);}catch{}v.current=!0;}a();}catch(y){console.error("Failed to save chat on completion:",y);}}},[o,r,n,t,i,c,a]);let s=useCallback(y=>{try{let p=i.loadChat(y);return p?{id:p.id,messages:p.messages,agentId:p.agentId||t}:null}catch(p){return console.error("Failed to load chat:",p),null}},[i,t]),l=useCallback(()=>{if(r.length!==0)try{let y=Date.now();i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);C&&(i.upsertChatMeta({...C,updatedAt:y}),a());}catch(y){console.error("Failed to save chat:",y);}},[i,n,r,t,a]),u=useCallback(y=>{try{i.deleteChat(y),a();}catch(p){console.error("Failed to delete chat:",p);}},[i,a]),h=useCallback((y,p)=>{if(y!==n)try{v.current=!0,i.saveCurrentChatId(y);let C=i.loadChat(y),M=C&&Array.isArray(C.messages)?C.messages:[];p(M),a();}catch(C){console.error("Failed to switch chat:",C);}},[i,n,a]),f=useCallback(y=>{v.current=false,y();},[]),k=useCallback(y=>{if(!y.trim())return w;let p=y.toLowerCase();return w.filter(C=>C.title.toLowerCase().includes(p))},[w]);return {chatList:w,currentChatMeta:d,refreshChatList:a,loadChat:s,saveCurrentChat:l,deleteChat:u,switchToChat:h,createNewChat:f,searchChats:k,storage:i}}function zo(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:c}=e,{baseUrl:m}=ne(),i=c||m||"",[w,S]=useState(null),[d,T]=useState(""),[v,x]=useState([]),[a,b]=useState(false),s=useCallback((y,p,C=[])=>{S(y),T(p),x(C);},[]),l=useCallback(()=>{S(null),T(""),x([]);},[]),u=useCallback(async y=>{if(!n)try{let p=t.findIndex(M=>M.id===y);if(p===-1)return;let C=t.slice(0,p);o(C),await r({text:d.trim(),files:v.map(M=>({type:"file",url:M.url,mediaType:M.mimeType||"application/octet-stream",...M.name?{name:M.name}:{},...M.size?{size:M.size}:{}}))}),l();}catch(p){throw console.error("Failed to save edit:",p),p}},[n,t,r,d,v,o,l]),h=useCallback(y=>w===y,[w]),f=useCallback(async y=>{if(!i){console.warn("baseUrl not provided, cannot upload attachments");return}b(true);try{let p=Array.from(y).map(async M=>{if(M.size>26214400)throw new Error(`${M.name} is too large (max 25MB)`);let g=new FormData;g.append("file",M);let R=await fetch(`${i}/api/upload`,{method:"POST",body:g});if(!R.ok)throw new Error(`Upload failed: ${R.statusText}`);let N=await R.json();return {id:N.url||`${Date.now()}-${Math.random()}`,name:M.name,url:N.url,mimeType:M.type,size:M.size}}),C=await Promise.all(p);x(M=>[...M,...C]);}catch(p){throw console.error("Failed to upload files:",p),p}finally{b(false);}},[i]),k=useCallback(y=>{x(p=>p.filter(C=>C.id!==y));},[]);return {editingMessageId:w,editingText:d,setEditingText:T,editAttachments:v,setEditAttachments:x,editUploading:a,startEdit:s,cancelEdit:l,saveEdit:u,isEditing:h,addEditAttachments:f,removeEditAttachment:k}}function j({IconComponent:e,...t}){return Wo.createElement(e,t)}function At({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:c}){return jsx("button",{"aria-label":n,title:c,disabled:o,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:o?"not-allowed":"pointer",opacity:o?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:m=>{o||(m.currentTarget.style.backgroundColor=r.hoverBackground,m.currentTarget.style.color=r.textColor);},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function xn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:c,onToggleHistory:m,onClose:i,historyBtnRef:w,t:S}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsx(At,{icon:jsx(j,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||c();},ariaLabel:S("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:w,"aria-label":S("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=o.hoverBackground,d.currentTarget.style.color=o.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=o.mutedTextColor;},onClick:m,children:jsx(j,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(At,{icon:jsx(j,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:i,ariaLabel:S("header.close"),resolvedColors:o})]})]})}var ct=class extends Component{constructor(t){super(t),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(t){return {hasError:true,error:t,errorInfo:null}}componentDidMount(){let{toolCallId:t,toolName:n,onSuccess:r}=this.props;t&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(t,n);},0);}componentDidCatch(t,n){console.error(`UI Component Error (${this.props.componentName}):`,t,n),this.setState({error:t,errorInfo:n});let{toolCallId:r,toolName:o,onError:c}=this.props;r&&o&&c&&c(r,o,t);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:t,componentName:n}=this.props;return jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var Ko=e=>{let t={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return t[e||"output-available"]||t["output-available"]},Vo=e=>{let t=/^(.+?)_([a-f0-9]{6})_(.+)$/,n=e.match(t);if(n){let[,r,,o]=n;return {isMCP:true,mcpName:r.replace(/_/g," "),toolName:o.replace(/_/g," ")}}return {isMCP:false,toolName:e}},Xo=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function bn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:m,onUISuccess:i,addToolResult:w}){let S=[],d=[],T,v,x=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){d.push(a.text),T||(T=a.startDate),v=a.endDate,a.state==="done"&&(x=true);continue}if(a.type==="text"&&typeof a.text=="string"){d.length&&(S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),d=[],T=void 0,v=void 0,x=false),S.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let b=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(b||s||a.type==="tool-call"){d.length&&(S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),d=[],T=void 0,v=void 0,x=false);let l=String(b?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");l==="requestInput"?S.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):S.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return d.length&&S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),S.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[S.map((a,b)=>{let s=`${t}-${b}`,l=n.has(s);if(a.type==="reasoning"){let p=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",C=a.texts&&a.texts.length>0&&a.texts.some(g=>g.trim().length>0),M=()=>{C&&r(s);};return p&&!C?null:jsx("div",{onClick:M,style:{cursor:C?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l?"4px":"0px"},children:[jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!p&&jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{color:o.textColor,fontWeight:600,opacity:.9,background:p?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:p?"auto":"200% 100%",backgroundClip:p?"unset":"text",WebkitBackgroundClip:p?"unset":"text",WebkitTextFillColor:p?o.mutedTextColor:"transparent",animation:p?void 0:"shimmer 2s ease-in-out infinite"},children:p?"Finish Thinking":"Thinking"})]}),C&&jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:l?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsx("div",{style:{display:"grid",gridTemplateRows:l||!p?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsx("div",{style:{fontSize:"13px",color:o.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!p&&l?a.texts:p?l?a.texts:[]:[a.texts[a.texts.length-1]]).map((g,R)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(We,{content:g,theme:"dark",streaming:!p})},`rg-line-${b}-${R}`))}):jsxs("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text"){let p=typeof a.endDate!="number";return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(We,{content:a.text,theme:"dark",streaming:p})},s)}let{color:u,text:h}=Ko(a.status),f=a.status==="input-streaming"||a.status==="input-available";if(a.toolName==="requestInput")return jsx("div",{style:{display:"block",position:"relative"},children:jsx("div",{"data-get-from-user-host":a.toolCallId||s,style:{width:"100%"}})},s);let k=c?.[a.toolName||""];if(k)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(ct,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:m,onSuccess:i,children:jsx(k,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:w})})},s);let y=Vo(a.toolName||"tool");return jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsx("div",{style:{flex:1,minWidth:0},children:jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxs("span",{style:{fontWeight:600,color:u,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:u,animation:f?"pulse 1.5s ease-in-out infinite":void 0}}),h]}),y.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:y.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:y.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:Xo(y.toolName)})]})})},s)}),jsx("style",{children:`
11
+ `,document.head.appendChild(o);}fn=true;}return e?(e.classList.add("as-arrow"),Ve||(Ve=createRoot(e),Ve.render(jsx(mn,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(e=document.createElement("div"),e.id=t,e.className="fake-cursor as-arrow",e.style.position="fixed",e.style.left="20px",e.style.top="20px",document.body.appendChild(e),Ve=createRoot(e),Ve.render(jsx(mn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),e}function De(t,e,n){return Math.max(e,Math.min(n,t))}function qo(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}function bn(t){if(!t)return null;let e=document.createElement("canvas").getContext("2d");if(!e)return null;e.fillStyle="#000",e.fillStyle=t;let r=e.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!r)return null;let o=r[1].split(/\s*,\s*/).map(Number),[p,f,c,C=1]=o;return {r:p,g:f,b:c,a:C}}function Ko({r:t,g:e,b:n}){let r=[t,e,n].map(o=>o/255).map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*r[0]+.7152*r[1]+.0722*r[2]}function Xo(t){let e=t?bn(t):null;return !e||e.a===0?false:Ko(e)<.5}function Jo(t,e){let n=document.elementFromPoint(t,e),r=new Set;for(;n&&!r.has(n);){r.add(n);let f=getComputedStyle(n).backgroundColor,c=bn(f);if(c&&c.a>0)return f;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Ft(t,e,n){let r=Jo(e,n),o=Xo(r),p=o?"#ffffff":"#000000";t.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=p,c.style.strokeWidth="1";}),t.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function at(t,e,n,r,o="ease-in-out",p="curve",f=.25,c="auto",C){Cn(),Ht(t);let I=performance.now(),m=o==="linear"?h=>h:qo,w=p!=="straight",v={x:0,y:0};if(w){let h=n.x-e.x,s=n.y-e.y,u=Math.hypot(h,s)||1,a=(e.x+n.x)/2,i=(e.y+n.y)/2,l=-s/u,g=h/u,d=1;c==="left"?d=-1:c==="right"?d=1:d=Math.random()<.5?-1:1;let x=De(f,0,1)*u;v={x:a+d*l*x,y:i+d*g*x};}return new Promise(h=>{function s(u){let a=De((u-I)/r,0,1),i=m(a),l,g;if(w){let k=1-i;l=k*k*e.x+2*k*i*v.x+i*i*n.x,g=k*k*e.y+2*k*i*v.y+i*i*n.y;}else l=e.x+(n.x-e.x)*i,g=e.y+(n.y-e.y)*i;let x=.35*(1-i),y=Math.sin(u*.02)*x,b=Math.cos(u*.018)*x;t.style.left=`${l+y}px`,t.style.top=`${g+b}px`,Ft(t,l+y,g+b),C&&C({x:l+y,y:g+b,t:a,now:u}),a<1?requestAnimationFrame(s):h();}requestAnimationFrame(s);})}function gn(t,e){return {x:t.x+(e?.x??0),y:t.y+(e?.y??0)}}function ye(t,e,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let p=e==="pointerdown"||e==="mousedown",f=e==="pointerup"||e==="mouseup",c={button:0,buttons:p?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let C=new PointerEvent(e,{pointerId:1,pointerType:"mouse",...c});t.dispatchEvent(C);}else {let C=new MouseEvent(e,c);t.dispatchEvent(C);}}catch{let p=new MouseEvent(e,o);t.dispatchEvent(p);}}function vn(t){return t&&typeof t=="object"&&t.nodeType===1}function Yo(t){if(!t)return document;if(vn(t))return t;if(typeof t=="string"){let e=document.getElementById(t);if(e)return e;let n=document.querySelector(t);if(n)return n}return document}function yn(t){if(vn(t))return {kind:"element",element:t};if(typeof t=="string"){let e=document.getElementById(t);if(e)return {kind:"element",element:e};let n=document.querySelector(t);return {kind:n?"element":"position",element:n??null}}if(typeof t=="object"&&"position"in t)return {kind:"position",point:t.position};if(typeof t=="object"&&"selector"in t){let n=Yo(t.within??null).querySelectorAll(t.selector),r=Math.max(0,Math.min(n.length-1,t.nth??0)),o=n[r]??null;return {kind:o?"element":"position",element:o}}return {kind:"position",point:{x:0,y:0}}}function hn(t,e){let n=t.getBoundingClientRect();if(!e||e==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(e==="top-left")return {x:n.left,y:n.top};if(e==="bottom-right")return {x:n.right,y:n.bottom};let r=De(e.x,0,1),o=De(e.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function xn(t){return {x:De(t.x,0,window.innerWidth),y:De(t.y,0,window.innerHeight)}}function Zo(){return useEffect(()=>(window.__cursorGuide=async(t,e={})=>{let n=Array.isArray(t)?t:[{target:t,action:e.action??"none",options:e}],r=[],o=await _o();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),Ht(o),Cn();let p=parseFloat(o.style.left||"20")||20,f=parseFloat(o.style.top||"20")||20;Ft(o,p,f);for(let c of n){let{durationMs:C=800,easing:I="ease-in-out",offset:m,highlight:w=true,path:v="curve",curveStrength:h=.25,curveDirection:s="auto",anchor:u,cursorHotspot:a,dragTo:i}=c.options??{},l=c.action??c.options?.action??"none",g=performance.now(),d=yn(c.target),x=null,y=null;if(d.kind==="element"&&d.element?(y=d.element,o.classList.remove("visible"),y.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Wo(y,1500,180),Ht(o),x=hn(y,u)):d.kind==="position"&&d.point&&(x=d.point),!x){r.push({ok:false,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),error:"Target not found"});continue}let b={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},k=xn(gn(x,m));await at(o,b,k,C,I,v,h,s);let E=k.x-b.x,T=k.y-b.y,P=Math.hypot(E,T)||1,B=E/P,z=T/P,_=Math.min(6,Math.max(3,P*.02)),j={x:k.x+B*_,y:k.y+z*_};await at(o,k,j,Math.max(70,C*.1),"ease-out","straight",0,"right"),await at(o,j,k,120,"ease-out","straight",0,"left"),w&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let te=null;try{if(l==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let R={x:a?.x??0,y:a?.y??0},H={x:k.x+R.x,y:k.y+R.y};o.style.left=`${H.x}px`,o.style.top=`${H.y}px`,Ft(o,H.x,H.y);let A=y??document.elementFromPoint(H.x,H.y)??document.body;ye(A,"pointerdown",H),ye(A,"mousedown",H),await new Promise(M=>setTimeout(M,90)),o.classList.remove("pressing"),ye(A,"mouseup",H),ye(A,"click",H),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),A instanceof HTMLElement&&A.focus?.(),te=A?.id??null;}else if(l==="drag"){if(!i)throw new Error("dragTo is required for action 'drag'");let R=yn(i),H=null;if(R.kind==="element"&&R.element&&(H=hn(R.element,u)),R.kind==="position"&&R.point&&(H=R.point),!H)throw new Error("dragTo target not found");let A=xn(gn(H,m)),M={x:k.x,y:k.y},W=y??document.elementFromPoint(M.x,M.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),ye(W,"pointerdown",M),ye(W,"mousedown",M),await at(o,M,A,Math.max(200,C),I,v,h,s,({x:Q,y:me})=>{let ne=document.elementFromPoint(Q,me)??document.body,le={x:Q,y:me};ye(ne,"pointermove",le),ye(ne,"mousemove",le);});let J=document.elementFromPoint(A.x,A.y)??document.body;o.classList.remove("pressing"),ye(J,"pointerup",A),ye(J,"mouseup",A);}r.push({ok:!0,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),clickedElementId:te});}catch(R){r.push({ok:false,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),error:R?.message??String(R)});}}return Oo(o,2e3),{ok:r.every(c=>c.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var lt=Zo;function kn(){return {getDomComponents:{tool:async({includeHidden:t,selector:e})=>await Ge({includeHidden:t,selector:e}),executeEachToken:false},controlCursor:{tool:async({target:t,action:e,anchor:n,durationMs:r,dragTo:o})=>{let p=await Se(t,{action:e,anchor:n,durationMs:r,dragTo:o});if(p&&p.ok){let f=Array.isArray(p.steps)&&p.steps.length?p.steps[p.steps.length-1]:void 0,c=f?.clickedElementId?` (clicked element id: ${f.clickedElementId})`:"",C=e||f?.action||"none";return {success:true,message:C==="click"?`Cursor moved and clicked successfully${c}`:C==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:p}}return {success:false,message:"Cursor action failed",details:p}},executeEachToken:false},fillActiveInput:{tool:async({value:t})=>{let e=await je(t);return {success:!!e?.ok,message:e?.ok?"Active input filled successfully":e?.errors?.[0]||"Failed to fill active input",details:e}},executeEachToken:true},requestInput:{tool:async t=>({ok:true}),executeEachToken:true}}}function _e({content:t,theme:e="dark",streaming:n=false}){return jsx(XMarkdown,{content:t,className:e==="dark"?"x-markdown-dark":"x-markdown-light",streaming:{hasNextChunk:n,enableAnimation:true,animationConfig:{fadeDuration:200},incompleteMarkdownComponentMap:{html:"IncompleteBlock",link:"IncompleteBlock",image:"IncompleteBlock"}},openLinksInNewTab:true,config:{gfm:true},dompurifyConfig:{ADD_TAGS:["data-chart","welcome","user-card","mermaid"],ADD_ATTR:["data-source","data-spec","data-icon","data-description","data-raw"]},style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"}})}function or({input:t}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(_e,{content:t?.text||"",theme:"dark"})})}function In(){return {plainText:or}}function Tn(t,e,n,r,o,p){let f=n.get(e);if(f){let d=f.parentElement,x=document.querySelector(`[data-get-from-user-host="${e}"]`);if(x&&d!==x){try{d?.removeChild(f);}catch{}x.innerHTML="",x.appendChild(f);}}else {f=document.createElement("div"),f.className="hsafa-inline-form";let d=document.querySelector(`[data-get-from-user-host="${e}"]`);d?(d.innerHTML="",d.appendChild(f)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(f),n.set(e,f);}let c=t?.title||"Provide input",C=t?.description||"",I=t?.submitLabel||"Submit",m=t?.skipLabel||"Skip",w=Array.isArray(t?.fields)?t.fields:t?.label||t?.placeholder?[{id:"value",label:t?.label||"Value",type:"text",placeholder:t?.placeholder||""}]:[],v=r.get(e)||{submitted:false,skipped:false,values:void 0};f.innerHTML="";let h=document.createElement("form");h.style.margin="12px 0",h.style.padding="14px",h.style.border="1px solid var(--hsafa-border, #2A2C33)",h.style.borderRadius="12px",h.style.background="var(--hsafa-card, #121318)",h.style.color="var(--hsafa-text, #EDEEF0)",h.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let s=document.createElement("div");if(s.style.fontWeight="600",s.style.marginBottom="6px",s.textContent=c,h.appendChild(s),C){let d=document.createElement("div");d.style.fontSize="12px",d.style.opacity="0.8",d.style.marginBottom="10px",d.textContent=C,h.appendChild(d);}w.forEach(d=>{let x=document.createElement("div");if(x.style.margin="10px 0",d.label){let T=document.createElement("label");T.style.display="block",T.style.fontSize="12px",T.style.marginBottom="6px",T.style.opacity="0.9",T.textContent=d.label,x.appendChild(T);}let y,b=(d.type||"text").toLowerCase();if(b==="textarea"){let T=document.createElement("textarea");T.placeholder=d.placeholder||"",T.value=d.value??"",T.style.width="100%",T.style.minHeight="72px",T.style.padding="10px 12px",T.style.border="1px solid var(--hsafa-border, #2A2C33)",T.style.borderRadius="10px",T.style.background="var(--hsafa-input-bg, #17181C)",T.style.color="inherit",y=T;}else if(b==="select"&&Array.isArray(d.options)){let T=document.createElement("select");T.style.width="100%",T.style.padding="10px 12px",T.style.border="1px solid var(--hsafa-border, #2A2C33)",T.style.borderRadius="10px",T.style.background="var(--hsafa-input-bg, #17181C)",T.style.color="inherit",d.options.forEach(P=>{let B=document.createElement("option");B.value=String(P.value),B.text=String(P.label??P.value),T.appendChild(B);}),T.value=d.value??"",y=T;}else if(b==="checkbox"){let T=document.createElement("input");T.type="checkbox",T.checked=!!d.value,T.style.transform="scale(1.1)",y=T;}else {let T=document.createElement("input");T.type=b,T.placeholder=d.placeholder||"",T.value=d.value??"",T.style.width="100%",T.style.padding="10px 12px",T.style.border="1px solid var(--hsafa-border, #2A2C33)",T.style.borderRadius="10px",T.style.background="var(--hsafa-input-bg, #17181C)",T.style.color="inherit",y=T;}let k=d.id||"value";y.dataset.fieldId=k;let E=v.values&&Object.prototype.hasOwnProperty.call(v.values,k)?v.values[k]:void 0;typeof E<"u"&&(y.type==="checkbox"?y.checked=!!E:y.value=String(E)),(v.submitted||v.skipped)&&(y.setAttribute("disabled","true"),y.style.opacity="0.7"),x.appendChild(y),h.appendChild(x);});let u=String(I).trim(),a=String(m).trim(),i=!!(u||a),l=null,g=null;if(i){let d=document.createElement("div");d.style.display="flex",d.style.gap="8px",d.style.marginTop="10px",l=document.createElement("button"),l.type="submit",l.textContent=u||"Submit",l.style.padding="6px 10px",l.style.borderRadius="8px",l.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",l.style.color="#000000",g=document.createElement("button"),g.type="button",g.textContent=a||"Skip",g.style.padding="6px 10px",g.style.borderRadius="8px",g.style.background="transparent",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.color="inherit",d.appendChild(l),d.appendChild(g),h.appendChild(d);}if(h.onsubmit=d=>{d.preventDefault();let x={};h.querySelectorAll("[data-field-id]").forEach(y=>{let b=y.dataset.fieldId||"value";y.type==="checkbox"?x[b]=y.checked:x[b]=y.value??"";}),r.set(e,{submitted:true,skipped:false,values:x}),o({tool:"requestInput",toolCallId:e,output:{success:true,submitted:true,values:x}}),h.querySelectorAll("[data-field-id]").forEach(y=>{y.disabled=true,y.style.opacity="0.7";}),l&&(l.textContent=`${u||"Submit"} \u2713`,l.style.opacity="0.8",l.disabled=true),g&&(g.disabled=true);},g&&(g.onclick=()=>{r.set(e,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:e,output:{success:true,submitted:false,skipped:true}}),h.querySelectorAll("[data-field-id]").forEach(d=>{d.disabled=true,d.style.opacity="0.7";}),g&&(g.textContent=`${a||"Skip"} \u2713`,g.style.opacity="0.8",g.disabled=true),l&&(l.disabled=true);}),v.submitted||v.skipped){let d=document.createElement("div");d.style.marginTop="10px",d.style.fontSize="12px",d.style.display="flex",d.style.alignItems="center",d.style.gap="8px";let x=document.createElement("span");x.style.display="inline-flex",x.style.alignItems="center",x.style.padding="2px 8px",x.style.borderRadius="999px",x.style.fontWeight="600",x.style.fontSize="11px",v.submitted?(x.style.background="rgba(16,185,129,0.15)",x.style.color="#10b981",x.textContent="Submitted"):(x.style.background="rgba(234,179,8,0.15)",x.style.color="#eab308",x.textContent="Skipped"),d.appendChild(x),h.appendChild(d);try{l&&(l.disabled=!0,l.style.opacity="0.8",v.submitted&&(l.textContent=`${u||"Submit"} \u2713`)),g&&(g.disabled=!0,g.style.opacity="0.8",v.skipped&&(g.textContent=`${a||"Skip"} \u2713`));}catch{}}f.appendChild(h);}function Sn(t){return !!t&&typeof t=="object"}function Mn(t,e,n){let r=useRef(new Map),o=useRef(new Map),p=useRef(new Map),f=useRef(e),c=useRef(n);f.current=e,c.current=n,useEffect(()=>{t.forEach(C=>{if(!Sn(C)||C.role!=="assistant")return;(Array.isArray(C.parts)?C.parts:[]).forEach(m=>{if(!Sn(m)||typeof m.toolCallId!="string"||!m.toolCallId)return;let w=typeof m.toolName=="string"?m.toolName:void 0,v=typeof m.type=="string"?m.type:"";if(!w&&v.startsWith("tool-")&&(w=v.replace(/^tool-/,"")),!w)return;let h=f.current[w];try{let s=String(m.state||m.status||""),u=o.current.get(m.toolCallId);if(s&&s!==u&&h&&typeof h=="object"){o.current.set(m.toolCallId,s);let a=m.input??m.args??{},i={toolCallId:m.toolCallId,toolName:w},l=h;s==="input-streaming"&&typeof l.inputting_start=="function"&&l.inputting_start(a,i),s==="input-available"&&typeof l.running_start=="function"&&l.running_start(a,i);}}catch{}if(h&&typeof h=="object"&&h.executeEachToken&&h.tool){let s=m.input??m.args??{},u=JSON.stringify(s),a=r.current.get(m.toolCallId);if(u!==a&&u!=="{}"){r.current.set(m.toolCallId,u);try{if(w==="requestInput")c.current(s,m.toolCallId);else {let l=(p.current.get(m.toolCallId)||0)+1;p.current.set(m.toolCallId,l),l>1&&h.tool({...s,toolCallNumber:l-1});}}catch{}}}});});},[t]);}function Dt(t){let{agentId:e,baseUrl:n="",tools:r={},uiComponents:o={},onStart:p,onFinish:f,onError:c,initialMessages:C=[],onMessagesChange:I,controlledChatId:m,onChatIdChange:w,templateParams:v}=t,{baseUrl:h,setCurrentChatId:s}=ee(),u=n&&n.length>0?n:h||"",[a,i]=useState(""),[l,g]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),d=m??l,x=useCallback(F=>{m===void 0&&g(F),w&&w(F);},[m,w]);useEffect(()=>{try{s(d);}catch{}return ()=>{try{s(void 0);}catch{}}},[d,s]);let y=useMemo(()=>cn(u,e,d,v),[u,e,d,v]),b=useCallback(F=>{console.log("Message finished:",F);let L=F?.message?.id;if(!L&&Array.isArray(F?.messages))for(let O=F.messages.length-1;O>=0;O--){let $=F.messages[O];if($&&$.role==="assistant"&&$.id){L=$.id;break}}f?.({...F,chatId:d,assistantMessageId:L});},[f,d]),k=useCallback(F=>{console.error("Chat error:",F),c?.(F);},[c]),E=useMemo(()=>kn(),[]),T=useMemo(()=>({...E,...r}),[E,r]),P=useMemo(()=>In(),[]),B=useMemo(()=>({...P,...o}),[P,o]),z=useRef(new Map),_=useRef(new Map),j=useCallback(()=>{try{z.current.forEach(F=>{try{F.remove();}catch{}}),z.current.clear(),_.current.clear();}catch{}},[]),te=useCallback((F,L)=>{Tn(F,L,z.current,_.current,O=>R.current.addToolResult(O));},[]),R=useRef(null),H=useRef(new Set),A=useCallback((F,L,O)=>{console.error(`UI Error [${L}]:`,O),R.current&&H.current.has(F)&&(H.current.delete(F),R.current.addToolResult({tool:L,toolCallId:F,state:"output-error",errorText:O?.message||String(O)}));},[]),M=useCallback((F,L)=>{R.current&&H.current.has(F)&&(H.current.delete(F),R.current.addToolResult({tool:L,toolCallId:F,output:{status:"ok",rendered:true,component:L,logs:[]}}));},[]),W=useCallback(F=>{let L=T[F];return L?typeof L=="object"&&"tool"in L?L.tool:typeof L=="function"?L:null:null},[T]),J=useChat({transport:y,onFinish:b,onError:k,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:F}){let L=W(F.toolName);if(F.toolName==="requestInput"){try{te(F.input,F.toolCallId);}catch(re){console.error("requestInput render error",re);}return}let O=F.toolName==="ui",$=B&&F.toolName in B;if((O||$)&&!L){H.current.add(F.toolCallId);return}if(L)try{let re=await L(F.input);J.addToolResult({tool:F.toolName,toolCallId:F.toolCallId,output:re});}catch(re){J.addToolResult({tool:F.toolName,toolCallId:F.toolCallId,state:"output-error",errorText:re?.message||String(re)});}}}),{messages:Q,sendMessage:me,status:ne,stop:le,error:q}=J;R.current=J,Mn(Q,T,te),useEffect(()=>{try{let F=new Set,L=[];if(Q.forEach(O=>{O.role==="assistant"&&(O.parts||[]).forEach($=>{if(($?.toolName||(typeof $?.type=="string"&&$.type.startsWith("tool-")?String($.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let re=$?.toolCallId||"";if(!re)return;F.add(re);let he=$?.output;if(he&&(he.submitted||he.skipped||he.values)){let vt={submitted:!!he.submitted,skipped:!!he.skipped,values:he.values||void 0};_.current.set(re,vt);}let Ne=$?.input||$?.args||{};L.push({input:Ne,toolCallId:re});});}),z.current.forEach((O,$)=>{if(!F.has($)){let oe=z.current.get($);try{oe?.remove();}catch{}z.current.delete($),_.current.delete($);}}),L.length>0){let O=requestAnimationFrame(()=>{L.forEach(({input:$,toolCallId:oe})=>{try{te($,oe);}catch{}});});return ()=>cancelAnimationFrame(O)}}catch{}},[Q,te]),useEffect(()=>{C&&C.length>0&&Q.length===0&&console.log("Initial messages:",C);},[C,Q.length]);let we=ne==="submitted"||ne==="streaming",Ze=useCallback(()=>{I&&I(Q,d);},[I,Q,d]),Qe=useCallback(async F=>{let L=F?.text!==void 0?F.text:a,O=F?.files||[],$=L.trim();if(!(!$&&O.length===0)&&!we){F?.text===void 0&&i("");try{if(p){let oe={role:"user",content:$,createdAt:Date.now(),chatId:d};p(oe);}await me({text:$,files:O});}catch(oe){throw console.error("Failed to send message:",oe),oe}}},[a,we,me,p,d]),bt=useCallback(()=>{if(we)return;j(),i("");try{J?.setMessages?.([]);}catch{}let F=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;x(F);},[we,J,j,x]),ce=useCallback(F=>{try{J?.setMessages?.(F);}catch{}},[J]);return {input:a,setInput:i,messages:Q,isLoading:we,status:ne,error:q,sendMessage:Qe,stop:le,newChat:bt,setMessages:ce,notifyMessagesChange:Ze,chatApi:J,chatId:d,setChatId:x,tools:T,uiComponents:B,formHostRef:z,formStateRef:_,cleanupForms:j,onUISuccess:M,onUIError:A}}function Pe(t){let e=`hsafaChat_${t}`,n=`${e}.chats`,r=g=>`${e}.chat.${g}`,o=`${e}.currentChatId`,p=`${e}.showChat`,f=()=>{try{let g=localStorage.getItem(n);return g?JSON.parse(g):[]}catch{return []}},c=g=>{try{localStorage.setItem(n,JSON.stringify(g));}catch{}},C=g=>{try{let d=localStorage.getItem(r(g));return d?JSON.parse(d):null}catch{return null}},I=g=>{try{localStorage.setItem(r(g.id),JSON.stringify(g));}catch{}},m=g=>{let d=f(),x=d.findIndex(y=>y.id===g.id);x>=0?d[x]=g:d.unshift(g),c(d);},w=g=>{let x=f().filter(y=>y.id!==g);c(x);},v=g=>{try{localStorage.removeItem(r(g));}catch{}};return {loadChatsIndex:f,saveChatsIndex:c,loadChat:C,saveChat:I,upsertChatMeta:m,deleteChatMeta:w,deleteChatData:v,deleteChat:g=>{v(g),w(g);},loadShowChatPreference:g=>{try{let d=localStorage.getItem(p);return d!==null?d==="true":g}catch{return g}},saveShowChatPreference:g=>{try{localStorage.setItem(p,String(g));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:g=>{try{localStorage.setItem(o,g);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Bt(t){let{agentId:e,chatId:n,messages:r,isLoading:o=false,autoSave:p=true,autoRestore:f=true}=t,c=useMemo(()=>Pe(e),[e]),[C,I]=useState([]),[m,w]=useState(null),v=useRef(false),h=useRef(false),s=useCallback(()=>{try{let y=c.loadChatsIndex();I(y);let b=y.find(k=>k.id===n);w(b||null);}catch(y){console.error("Failed to refresh chat list:",y);}},[c,n]);useEffect(()=>{s();},[s]),useEffect(()=>{if(!(!f||h.current)){try{c.loadCurrentChatId()&&(v.current=!0);}catch(y){console.error("Failed to restore chat:",y);}h.current=true;}},[c,f]),useEffect(()=>{if(!(!p||r.length===0))if(v.current){if(!o){let y=Date.now();try{c.saveChat({id:n,messages:r,agentId:e});let k=c.loadChatsIndex().find(E=>E.id===n);k&&(c.upsertChatMeta({...k,updatedAt:y}),s());}catch(b){console.error("Failed to save chat:",b);}}}else {let y=r.find(b=>b.role==="user");if(y){let b="";if(Array.isArray(y.parts)){let T=y.parts.find(P=>P&&P.type==="text");b=T&&typeof T.text=="string"?T.text:"";}let k=(b||"New chat").slice(0,80),E=Date.now();try{c.upsertChatMeta({id:n,title:k,createdAt:E,updatedAt:E}),c.saveChat({id:n,messages:r,agentId:e}),c.saveCurrentChatId(n),v.current=!0,s();}catch(T){console.error("Failed to create chat:",T);}}}},[]);let u=useRef(false);useEffect(()=>{if(o){u.current=true;return}if(u.current&&p){u.current=false;try{let y=Date.now();c.saveChat({id:n,messages:r,agentId:e});let k=c.loadChatsIndex().find(E=>E.id===n);if(k)c.upsertChatMeta({...k,updatedAt:y});else {let E="",T=Array.isArray(r)?r.find(B=>B&&B.role==="user"):void 0;if(T&&Array.isArray(T.parts)){let B=T.parts.find(z=>z&&z.type==="text");E=B&&typeof B.text=="string"?B.text:"";}let P=(E||"New chat").slice(0,80);c.upsertChatMeta({id:n,title:P,createdAt:y,updatedAt:y});try{c.saveCurrentChatId(n);}catch{}v.current=!0;}s();}catch(y){console.error("Failed to save chat on completion:",y);}}},[o,r,n,e,c,p,s]);let a=useCallback(y=>{try{let b=c.loadChat(y);return b?{id:b.id,messages:b.messages,agentId:b.agentId||e}:null}catch(b){return console.error("Failed to load chat:",b),null}},[c,e]),i=useCallback(()=>{if(r.length!==0)try{let y=Date.now();c.saveChat({id:n,messages:r,agentId:e});let k=c.loadChatsIndex().find(E=>E.id===n);k&&(c.upsertChatMeta({...k,updatedAt:y}),s());}catch(y){console.error("Failed to save chat:",y);}},[c,n,r,e,s]),l=useCallback(y=>{try{c.deleteChat(y),s();}catch(b){console.error("Failed to delete chat:",b);}},[c,s]),g=useCallback((y,b)=>{if(y!==n)try{v.current=!0,c.saveCurrentChatId(y);let k=c.loadChat(y),E=k&&Array.isArray(k.messages)?k.messages:[];b(E),s();}catch(k){console.error("Failed to switch chat:",k);}},[c,n,s]),d=useCallback(y=>{v.current=false,y();},[]),x=useCallback(y=>{if(!y.trim())return C;let b=y.toLowerCase();return C.filter(k=>k.title.toLowerCase().includes(b))},[C]);return {chatList:C,currentChatMeta:m,refreshChatList:s,loadChat:a,saveCurrentChat:i,deleteChat:l,switchToChat:g,createNewChat:d,searchChats:x,storage:c}}function lr(t){let{messages:e,isLoading:n,sendMessage:r,setMessages:o,baseUrl:p}=t,{baseUrl:f}=ee(),c=p||f||"",[C,I]=useState(null),[m,w]=useState(""),[v,h]=useState([]),[s,u]=useState(false),a=useCallback((y,b,k=[])=>{I(y),w(b),h(k);},[]),i=useCallback(()=>{I(null),w(""),h([]);},[]),l=useCallback(async y=>{if(!n)try{let b=e.findIndex(E=>E.id===y);if(b===-1)return;let k=e.slice(0,b);o(k),await r({text:m.trim(),files:v.map(E=>({type:"file",url:E.url,mediaType:E.mimeType||"application/octet-stream",...E.name?{name:E.name}:{},...E.size?{size:E.size}:{}}))}),i();}catch(b){throw console.error("Failed to save edit:",b),b}},[n,e,r,m,v,o,i]),g=useCallback(y=>C===y,[C]),d=useCallback(async y=>{if(!c){console.warn("baseUrl not provided, cannot upload attachments");return}u(true);try{let b=Array.from(y).map(async E=>{if(E.size>26214400)throw new Error(`${E.name} is too large (max 25MB)`);let T=new FormData;T.append("file",E);let P=await fetch(`${c}/api/upload`,{method:"POST",body:T});if(!P.ok)throw new Error(`Upload failed: ${P.statusText}`);let B=await P.json();return {id:B.url||`${Date.now()}-${Math.random()}`,name:E.name,url:B.url,mimeType:E.type,size:E.size}}),k=await Promise.all(b);h(E=>[...E,...k]);}catch(b){throw console.error("Failed to upload files:",b),b}finally{u(false);}},[c]),x=useCallback(y=>{h(b=>b.filter(k=>k.id!==y));},[]);return {editingMessageId:C,editingText:m,setEditingText:w,editAttachments:v,setEditAttachments:h,editUploading:s,startEdit:a,cancelEdit:i,saveEdit:l,isEditing:g,addEditAttachments:d,removeEditAttachment:x}}function ur(t){if(!(typeof window>"u"))try{return Pe(t).loadCurrentChatId()||void 0}catch{return}}function $t(t){let{agentId:e,prefer:n="context"}=t,{currentChatId:r}=ee(),[o,p]=useState(void 0),[f,c]=useState(false);return useEffect(()=>{c(false);let C=ur(e);p(C),c(true);},[e]),useMemo(()=>{let C=r||void 0,I=n==="context"?C:o,m=n==="context"?"context":"storage";return I?{chatId:I,isReady:n==="storage"?f:true,source:m}:C?{chatId:C,isReady:true,source:"context"}:o?{chatId:o,isReady:f,source:"storage"}:{chatId:void 0,isReady:f,source:"none"}},[r,n,o,f])}function fr(t){let{agentId:e,chatId:n,initial:r,store:o,autoLoad:p=true,autoSave:f=true,saveDebounceMs:c=800}=t,C=$t({agentId:e}),I=n??C.chatId,[m,w]=useState(r),[v,h]=useState("idle"),[s,u]=useState(void 0),a=useRef(false),i=useRef(void 0),l=useRef(void 0),g=useRef(null),d=useCallback(()=>{typeof window>"u"||l.current&&(window.clearTimeout(l.current),l.current=void 0);},[]),x=useCallback(async()=>{if(I)try{await o.saveLatest(I,m);}catch(k){u(k);}},[I,o,m]),y=useCallback(async()=>{d();let k=x();g.current=k,await k;},[d,x]),b=useCallback(async()=>{if(I){h("loading"),u(void 0);try{let k=p?await o.loadLatest(I):null;w(k??r),h("ready"),a.current=!0,i.current=I;}catch(k){u(k),h("error");}}},[p,r,I,o]);return useEffect(()=>{if(!C.isReady&&!n)return;if(!I){a.current=false,i.current=void 0,h("idle"),u(void 0),w(r),d();return}if(i.current===I&&a.current)return;a.current=false,i.current=I;let k=false;return (async()=>{h(p?"loading":"ready"),u(void 0);try{let E=p?await o.loadLatest(I):null;if(k)return;w(E??r),h("ready"),a.current=!0;}catch(E){if(k)return;u(E),h("error");}})(),()=>{k=true;}},[C.isReady,p,d,n,r,I,o]),useEffect(()=>{if(f&&I&&a.current&&!(typeof window>"u"))return d(),l.current=window.setTimeout(()=>{let k=x();g.current=k;},c),()=>{d();}},[f,d,x,I,c,m]),useMemo(()=>({value:m,setValue:w,status:v,error:s,reload:b,flushSave:y}),[s,y,b,v,m])}function yr(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.assistantMessageId=="string"&&e.assistantMessageId.length>0)return e.assistantMessageId;if(typeof e.message?.id=="string"&&e.message.id.length>0)return e.message.id;let n=e.messages;if(Array.isArray(n))for(let r=n.length-1;r>=0;r--){let o=n[r];if(o&&o.role==="assistant"&&typeof o.id=="string"&&o.id.length>0)return o.id}}function hr(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.chatId=="string"&&e.chatId.length>0)return e.chatId}function xr(t){let e=[];for(let n=t.length-1;n>=0;n--){let r=t[n];r&&r.role==="assistant"&&(typeof r.id!="string"||r.id.length===0||e.push(r.id));}return e}function Cr(t){let{chatId:e,store:n,value:r,setValue:o,initial:p}=t,f=useRef(r);useEffect(()=>{f.current=r;},[r]);let c=useRef(void 0),C=useRef(null),I=useCallback(async w=>{let v=hr(w)??e;if(!v)return;let h=yr(w);h&&await n.saveVersion(v,h,f.current);},[e,n]),m=useCallback(async(w,v)=>{let h=v??e;if(c.current!==h){c.current=h,C.current=Array.isArray(w)?w:[];return}let s=C.current,u=Array.isArray(w)?w:[],a=Array.isArray(s)&&u.length<s.length;if(!h){C.current=u;return}if(a){let i=xr(u);for(let l of i)try{if(!await n.hasVersion(h,l))continue;let d=await n.loadVersion(h,l);if(d){o(d),C.current=u;return}}catch{continue}o(p);}C.current=u;},[e,p,o,n]);return useMemo(()=>({onFinish:I,onMessagesChange:m}),[I,m])}function K({IconComponent:t,...e}){return br.createElement(t,e)}function Ot({icon:t,onClick:e,ariaLabel:n,resolvedColors:r,disabled:o=false,title:p}){return jsx("button",{"aria-label":n,title:p,disabled:o,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:o?"not-allowed":"pointer",opacity:o?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:f=>{o||(f.currentTarget.style.backgroundColor=r.hoverBackground,f.currentTarget.style.color=r.textColor);},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=r.mutedTextColor;},onClick:e,children:t})}function Dn({title:t,alwaysOpen:e,streaming:n,dir:r,resolvedColors:o,onNew:p,onToggleHistory:f,onClose:c,historyBtnRef:C,t:I}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:t,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:t})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsx(Ot,{icon:jsx(K,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||p();},ariaLabel:I("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:C,"aria-label":I("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor=o.hoverBackground,m.currentTarget.style.color=o.textColor;},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=o.mutedTextColor;},onClick:f,children:jsx(K,{IconComponent:History,size:"20",strokeWidth:"2"})}),!e&&jsx(Ot,{icon:jsx(K,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:I("header.close"),resolvedColors:o})]})]})}var yt=class extends Component{constructor(e){super(e),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(e){return {hasError:true,error:e,errorInfo:null}}componentDidMount(){let{toolCallId:e,toolName:n,onSuccess:r}=this.props;e&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(e,n);},0);}componentDidCatch(e,n){console.error(`UI Component Error (${this.props.componentName}):`,e,n),this.setState({error:e,errorInfo:n});let{toolCallId:r,toolName:o,onError:p}=this.props;r&&o&&p&&p(r,o,e);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:e,componentName:n}=this.props;return jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var Sr=t=>{let e={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return e[t||"output-available"]||e["output-available"]},Mr=t=>{let e=/^(.+?)_([a-f0-9]{6})_(.+)$/,n=t.match(e);if(n){let[,r,,o]=n;return {isMCP:true,mcpName:r.replace(/_/g," "),toolName:o.replace(/_/g," ")}}return {isMCP:false,toolName:t}},Ar=t=>t.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase());function Pn({parts:t,messageId:e,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:p,onUIError:f,onUISuccess:c,addToolResult:C}){let I=[],m=[],w,v,h=false;for(let s of Array.isArray(t)?t:[]){if(!s)continue;if(s.type==="reasoning"&&typeof s.text=="string"){m.push(s.text),w||(w=s.startDate),v=s.endDate,s.state==="done"&&(h=true);continue}if(s.type==="text"&&typeof s.text=="string"){m.length&&(I.push({type:"reasoning",texts:m,startDate:w,endDate:v,isCompleted:h}),m=[],w=void 0,v=void 0,h=false),I.push({type:"text",text:s.text,startDate:s.startDate,endDate:s.endDate});continue}let u=s.type==="dynamic-tool",a=typeof s.type=="string"&&s.type.startsWith("tool-");if(u||a||s.type==="tool-call"){m.length&&(I.push({type:"reasoning",texts:m,startDate:w,endDate:v,isCompleted:h}),m=[],w=void 0,v=void 0,h=false);let i=String(u?s.toolName||"dynamic-tool":a?s.type?.slice(5)||"tool":s.toolName||"tool");i==="requestInput"?I.push({type:"tool",toolName:i,status:s.state||s.status,input:s.input,output:s.output,startDate:s.startDate,endDate:s.endDate,toolCallId:s.toolCallId}):I.push({type:"tool",toolName:i,status:s.state||s.status,input:s.input,output:s.output,startDate:s.startDate,endDate:s.endDate,toolCallId:s.toolCallId});continue}}return m.length&&I.push({type:"reasoning",texts:m,startDate:w,endDate:v,isCompleted:h}),I.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[I.map((s,u)=>{let a=`${e}-${u}`,i=n.has(a);if(s.type==="reasoning"){let b=s.isCompleted||typeof s.startDate=="number"&&typeof s.endDate=="number",k=s.texts&&s.texts.length>0&&s.texts.some(T=>T.trim().length>0),E=()=>{k&&r(a);};return b&&!k?null:jsx("div",{onClick:E,style:{cursor:k?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:i?"4px":"0px"},children:[jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!b&&jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{color:o.textColor,fontWeight:600,opacity:.9,background:b?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:b?"auto":"200% 100%",backgroundClip:b?"unset":"text",WebkitBackgroundClip:b?"unset":"text",WebkitTextFillColor:b?o.mutedTextColor:"transparent",animation:b?void 0:"shimmer 2s ease-in-out infinite"},children:b?"Finish Thinking":"Thinking"})]}),k&&jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:i?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsx("div",{style:{display:"grid",gridTemplateRows:i||!b?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsx("div",{style:{minHeight:0},children:s.texts&&s.texts.length>0?jsx("div",{style:{fontSize:"13px",color:o.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!b&&i?s.texts:b?i?s.texts:[]:[s.texts[s.texts.length-1]]).map((T,P)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(_e,{content:T,theme:"dark",streaming:!b})},`rg-line-${u}-${P}`))}):jsxs("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},a)}if(s.type==="text"){let b=typeof s.endDate!="number";return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(_e,{content:s.text,theme:"dark",streaming:b})},a)}let{color:l,text:g}=Sr(s.status),d=s.status==="input-streaming"||s.status==="input-available";if(s.toolName==="requestInput")return jsx("div",{style:{display:"block",position:"relative"},children:jsx("div",{"data-get-from-user-host":s.toolCallId||a,style:{width:"100%"}})},a);let x=p?.[s.toolName||""];if(x)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(yt,{componentName:s.toolName||"Unknown",resolvedColors:o,toolCallId:s.toolCallId,toolName:s.toolName||"unknown",onError:f,onSuccess:c,children:jsx(x,{toolName:s.toolName||"",toolCallId:s.toolCallId||"",input:s.input,output:s.output,status:s.status,addToolResult:C})})},a);let y=Mr(s.toolName||"tool");return jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsx("div",{style:{flex:1,minWidth:0},children:jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxs("span",{style:{fontWeight:600,color:l,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:l,animation:d?"pulse 1.5s ease-in-out infinite":void 0}}),g]}),y.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:y.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:y.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:Ar(y.toolName)})]})})},a)}),jsx("style",{children:`
12
12
  @keyframes shimmer {
13
13
  0% { background-position: -200% 0; }
14
14
  100% { background-position: 200% 0; }
15
15
  }
16
- `})]}):null}function Cn(e){if(!e||Number.isNaN(e))return "0 B";let t=["B","KB","MB","GB","TB"],n=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return `${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function vn({attachment:e,resolvedColors:t,mode:n,onRemove:r,maxWidth:o="200px"}){let c=e.mimeType?.startsWith("image/"),m=n==="editable"||n==="input",i=n==="viewable",w={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:i?"pointer":"default",maxWidth:n==="input"?"140px":o,position:"relative"},S=jsxs(Fragment,{children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",backgroundColor:c?"transparent":t.accentColor,flexShrink:0},children:[c?jsx("img",{src:e.url,alt:e.name,style:{width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",objectFit:"cover"},onError:d=>{d.target.style.display="none";let T=d.target.nextElementSibling;T&&(T.style.display="block");}}):null,jsx(j,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:c?"none":"block",color:t.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:Cn(e.size)})]}),n==="input"&&c&&jsx("button",{onClick:d=>{d.stopPropagation(),window.open(e.url,"_blank");},style:{background:"none",border:"none",color:t.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:d=>{d.currentTarget.style.backgroundColor=t.hoverBackground,d.currentTarget.style.color=t.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=t.mutedTextColor;},children:jsx(j,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),m&&r&&jsx("button",{onClick:d=>{d.stopPropagation(),r(e.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:t.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.color="#ef4444";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=t.mutedTextColor;},children:jsx(j,{IconComponent:X,size:"12",strokeWidth:"2"})}),i&&jsx(j,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return i?jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...w,textDecoration:"none"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=t.hoverBackground,d.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor=t.inputBackground,d.currentTarget.style.borderColor=t.borderColor;},children:S}):jsx("div",{style:w,children:S})}function wn({attachments:e,resolvedColors:t,onRemove:n}){if(!Array.isArray(e)||e.length===0)return null;let r=typeof n=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(o=>jsx(vn,{attachment:o,resolvedColors:t,mode:r,onRemove:n},o.id))})}function Tn({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:c,onUserMessageClick:m,HsafaUI:i,onUIError:w,onUISuccess:S,addToolResult:d,editableMessageIcon:T}){return jsxs(Fragment,{children:[jsx("style",{children:`
16
+ `})]}):null}function Bn(t){if(!t||Number.isNaN(t))return "0 B";let e=["B","KB","MB","GB","TB"],n=Math.min(e.length-1,Math.floor(Math.log(t)/Math.log(1024)));return `${(t/Math.pow(1024,n)).toFixed(n===0?0:1)} ${e[n]}`}function $n({attachment:t,resolvedColors:e,mode:n,onRemove:r,maxWidth:o="200px"}){let p=t.mimeType?.startsWith("image/"),f=n==="editable"||n==="input",c=n==="viewable",C={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:e.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${e.borderColor}`,fontSize:n==="input"?"12px":"11px",color:e.textColor,transition:"all 0.2s ease-out",cursor:c?"pointer":"default",maxWidth:n==="input"?"140px":o,position:"relative"},I=jsxs(Fragment,{children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",backgroundColor:p?"transparent":e.accentColor,flexShrink:0},children:[p?jsx("img",{src:t.url,alt:t.name,style:{width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",objectFit:"cover"},onError:m=>{m.target.style.display="none";let w=m.target.nextElementSibling;w&&(w.style.display="block");}}):null,jsx(K,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:p?"none":"block",color:e.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:t.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:t.name}),jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:e.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:Bn(t.size)})]}),n==="input"&&p&&jsx("button",{onClick:m=>{m.stopPropagation(),window.open(t.url,"_blank");},style:{background:"none",border:"none",color:e.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:m=>{m.currentTarget.style.backgroundColor=e.hoverBackground,m.currentTarget.style.color=e.textColor;},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=e.mutedTextColor;},children:jsx(K,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),f&&r&&jsx("button",{onClick:m=>{m.stopPropagation(),r(t.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:e.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#ef444420",m.currentTarget.style.color="#ef4444";},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=e.mutedTextColor;},children:jsx(K,{IconComponent:X,size:"12",strokeWidth:"2"})}),c&&jsx(K,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:e.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",style:{...C,textDecoration:"none"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor=e.hoverBackground,m.currentTarget.style.borderColor=e.primaryColor;},onMouseLeave:m=>{m.currentTarget.style.backgroundColor=e.inputBackground,m.currentTarget.style.borderColor=e.borderColor;},children:I}):jsx("div",{style:C,children:I})}function Un({attachments:t,resolvedColors:e,onRemove:n}){if(!Array.isArray(t)||t.length===0)return null;let r=typeof n=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:t.map(o=>jsx($n,{attachment:o,resolvedColors:e,mode:r,onRemove:n},o.id))})}function On({chatMessages:t,isLoading:e,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:p,onUserMessageClick:f,HsafaUI:c,onUIError:C,onUISuccess:I,addToolResult:m,editableMessageIcon:w}){return jsxs(Fragment,{children:[jsx("style",{children:`
17
17
  @keyframes jumpingDots {
18
18
  0%, 80%, 100% {
19
19
  transform: translateY(0);
@@ -22,15 +22,15 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Wo,{createContext,useRe
22
22
  transform: translateY(-5px);
23
23
  }
24
24
  }
25
- `}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((v,x)=>{let a=Array.isArray(v.parts)?v.parts:[],b=a.filter(l=>l.type==="text").map(l=>l&&typeof l.text=="string"?l.text:"").join(`
26
- `),s=a.filter(l=>l.type==="file"||l.type==="image").map(l=>{if(l.type==="image"){let u=typeof l.image=="string"?l.image:l.image?.toString?.()||"";return {id:u||`${v.id}-img-${Date.now()}`,name:l.name||"image",url:u,mimeType:l.mediaType||"image/jpeg",size:l.size||0}}else return {id:l.url||`${v.id}-file-${Date.now()}`,name:l.name||"file",url:l.url||"",mimeType:l.mediaType||"application/octet-stream",size:l.size||0}});return jsx("div",{style:{padding:"0 4px"},children:v.role==="user"?jsx("div",{children:jsx("div",{title:c("editor.clickToEdit"),onClick:()=>m(v,v.id,b,s),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:o.accentColor,color:o.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:l=>l.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:l=>l.currentTarget.style.backgroundColor=o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[b,s.length>0&&jsx(wn,{attachments:s,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(j,{IconComponent:T||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(bn,{parts:a,messageId:v.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:w,onUISuccess:S,addToolResult:d})},v.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function In({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:c,attachments:m,formatBytes:i,handleRemoveAttachment:w,onFileInputChange:S,onSend:d,onStop:T,status:v,t:x,resolvedColors:a}){let b=v==="streaming"||v==="submitted",s=m.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[m.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:m.map(l=>{let u=l.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:a.inputBackground,borderRadius:"10px",border:`1px solid ${a.borderColor}`,fontSize:"12px",color:a.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:u?"transparent":a.cardBackground},children:u?jsx("img",{src:l.url,alt:l.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:l.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:l.name}),jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:i(l.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[u&&jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:x("input.previewImage"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsx("button",{onClick:()=>w(l.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:x("input.removeFile"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},l.id)})}),c&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:x("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:x("input.placeholder"),value:e,onChange:l=>t(l.target.value),onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),d());},disabled:o||c,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:a.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:r,type:"file",multiple:true,onChange:S,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:a.mutedTextColor},children:jsx("button",{onClick:()=>r.current?.click(),disabled:o||c,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||c?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||c?.5:1},"aria-label":x("input.attachFiles"),children:jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:o?jsx("button",{onClick:T,disabled:!b,"aria-label":x("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:b?1:.4,cursor:b?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{b&&(l.currentTarget.style.backgroundColor="#ef444430",l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="#ef444420",l.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:d,disabled:!s||c,"aria-label":x("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground,color:!s||c?a.mutedTextColor:a.primaryColor,cursor:!s||c?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||c?.5:1},onMouseEnter:l=>{s&&!c&&(l.currentTarget.style.borderColor=a.primaryColor,l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.borderColor=a.borderColor,l.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function Sn({prompts:e,onSelect:t,resolvedColors:n,disabled:r=false}){let[o,c]=useState(null);return !e||e.length===0?null:jsxs("div",{style:{padding:"12px 0",display:"flex",flexDirection:"column",gap:"8px"},children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:n.mutedTextColor,paddingLeft:"4px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Suggested Prompts"}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.map((m,i)=>{let w=o===i,S=m.prompt.length>80,d=S&&!w?m.prompt.slice(0,80)+"...":m.prompt;return jsxs("button",{onClick:()=>{r||t(m.prompt);},disabled:r,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,borderRadius:"12px",cursor:r?"not-allowed":"pointer",transition:"all 0.2s ease",textAlign:"left",opacity:r?.5:1,position:"relative",overflow:"hidden"},onMouseEnter:T=>{r||(T.currentTarget.style.backgroundColor=n.hoverBackground,T.currentTarget.style.borderColor=n.primaryColor,T.currentTarget.style.transform="translateX(2px)");},onMouseLeave:T=>{T.currentTarget.style.backgroundColor=n.cardBackground,T.currentTarget.style.borderColor=n.borderColor,T.currentTarget.style.transform="translateX(0)";},children:[jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:n.textColor,marginBottom:"6px",display:"flex",alignItems:"center",gap:"6px"},children:[jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n.primaryColor,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[jsx("path",{d:"M12 20h9"}),jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),m.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:d}),S&&jsxs("button",{onClick:T=>{T.stopPropagation(),c(w?null:i);},style:{marginTop:"8px",padding:"4px 8px",fontSize:"11px",color:n.primaryColor,backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:"4px",fontWeight:500},children:[w?"Show less":"Show more",jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},i)})})]})}function Mn(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let r=Math.floor(n/60);if(r<60)return `${r}m`;let o=Math.floor(r/60);if(o<24)return `${o}h`;let c=Math.floor(o/24);if(c<7)return `${c}d`;let m=Math.floor(c/7);if(m<4)return `${m}w`;let i=Math.floor(c/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function En({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:c,onSearchChange:m,onChatSelect:i,onChatDelete:w,loadChatsIndex:S,historyPopupRef:d}){if(!e)return null;let T=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:c}),jsxs("div",{ref:d,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:v=>m(v.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:o.inputBackground,padding:"8px 12px",fontSize:"14px",color:o.textColor,border:`1px solid ${o.borderColor}`,outline:"none"},onFocus:v=>v.currentTarget.style.borderColor=o.primaryColor,onBlur:v=>v.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let v=t.toLowerCase().trim(),x=S();return v&&(x=x.filter(a=>(a.title||"").toLowerCase().includes(v))),!x||x.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:x.map((a,b)=>jsx("div",{style:{borderTop:b>0?`1px solid ${o.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===n?o.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:o.textColor},onMouseEnter:s=>s.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor="transparent",onClick:()=>i(a.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:o.textColor},children:a.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:Mn(a.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:o.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:s=>{s.currentTarget.style.color="#ef4444",s.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",s.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:s=>{s.currentTarget.style.color=o.mutedTextColor,s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.borderColor="transparent";},onClick:s=>{s.stopPropagation(),w(a.id);},children:jsx(j,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(T,document.body):T}function An({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let c=o?.title||"Edit Message",m=o?.content||"This will remove this message and all messages after it, and place its content in the input field for editing. Do you want to continue?",i=o?.submit_button_label||"Edit",w=o?.cancel_button_label||"Cancel",S=o?.icon,d=typeof m=="function",T=d?m:null,v=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[S?jsx("div",{style:{flexShrink:0},children:jsx(j,{IconComponent:S,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsx(j,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:c})]}),jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:d&&T?jsx(T,{}):jsx("p",{style:{margin:0},children:m})}),jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${t.borderColor}`,justifyContent:"flex-end"},children:[jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${t.borderColor}`,backgroundColor:"transparent",color:t.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent";},children:w}),jsx("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:"none",backgroundColor:t.primaryColor,color:t.backgroundColor,cursor:"pointer",transition:"all 0.2s",opacity:1},onMouseEnter:x=>{x.currentTarget.style.opacity="0.9";},onMouseLeave:x=>{x.currentTarget.style.opacity="1";},children:i})]})]})]});return typeof document<"u"&&document.body?createPortal(v,document.body):v}function pr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:c,borderColor:m,textColor:i,accentColor:w,baseUrl:S="",initialMessages:d=[],onMessagesChange:T,defaultOpen:v=true,floatingButtonPosition:x={bottom:24,right:24},HsafaTools:a={},HsafaUI:b={},componentAboveInput:s,editProcessContent:l,presetPrompts:u,onStart:h,onFinish:f,currentChat:k,onChatChanged:y,templateParams:p}){let{dir:C,theme:M,baseUrl:g,setStreamingState:R,setChatOpenState:N}=ne(),U=t||M||"dark",te=S&&S.length>0?S:g||"",A={primaryColor:U==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:c||(U==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:m||(U==="dark"?"#2A2C33":"#E5E7EB"),textColor:i||(U==="dark"?"#EDEEF0":"#111827"),accentColor:w||(U==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:U==="dark"?"#6f7276":"#6B7280",inputBackground:U==="dark"?"#17181C":"#F3F4F6",cardBackground:U==="dark"?"#121318":"#FFFFFF",hoverBackground:U==="dark"?"#1c1e25":"#F3F4F6"},B=I=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[I]||I,_=St({agentId:e,baseUrl:te,tools:a,uiComponents:b,templateParams:p,controlledChatId:k,onChatIdChange:k===void 0?I=>{y&&y(I);}:void 0,onStart:useCallback(I=>{h&&h(I);},[h]),onFinish:useCallback(I=>{f&&f(I);},[f]),onError:useCallback(I=>{console.error("Chat error:",I);},[]),initialMessages:d,onMessagesChange:T}),{input:V,setInput:ie,messages:O,isLoading:$,status:he,error:ce,sendMessage:xe,stop:mt,setMessages:q,notifyMessagesChange:Ke,chatId:Fe,setChatId:Ie,tools:Ht,uiComponents:E,formHostRef:F,formStateRef:z,cleanupForms:H,onUISuccess:Z,onUIError:J,chatApi:de}=_,X=k!==void 0?k:Fe,be=useCallback(I=>{k===void 0&&Ie(I),y&&y(I);},[k,Ie,y]);useEffect(()=>{k!==void 0&&k!==Fe&&Ie(k);},[k,Fe,Ie]);let{attachments:Ve,uploading:Ln,fileInputRef:Xe,formatBytes:Hn,handleRemoveAttachment:Fn,handleFileSelection:Ft,clearAttachments:Ye,setAttachments:Bt}=Vt(te),[Dt,Se]=useState(null),[Je,Pt]=useState(()=>{try{return rt(e).loadShowChatPreference(!!v)}catch{return !!v}}),[Bn,gt]=useState(false),[Dn,Pn]=useState(""),[$n,Nn]=useState(0),Un=useRef(null),zn=useRef(null),[Wn,On]=useState(new Set),[Gn,ft]=useState(false),[Be,yt]=useState(null),$t=useRef(null),_n=_t($),ht=Et({agentId:e,chatId:X,messages:O,isLoading:$,autoSave:true,autoRestore:false}),G=ht.storage,De=useRef(false),Pe=useRef(null);useEffect(()=>{if(!De.current){if(k!==void 0){try{let I=G.loadChat(k),D=I&&Array.isArray(I.messages)?I.messages:[];if(D.length>0)try{q(D);}catch{}Pe.current=k;}catch{}try{G.saveCurrentChatId(k);}catch{}De.current=true;return}try{let I=G.loadCurrentChatId();if(I){be(I);let D=G.loadChat(I),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}Pe.current=I;}}catch{}De.current=true;}},[k]),useEffect(()=>{if(De.current&&k!==void 0&&k!==Pe.current)try{let I=G.loadChat(k),D=I&&Array.isArray(I.messages)?I.messages:[];try{q(D);}catch{}Pe.current=k;try{G.saveCurrentChatId(k);}catch{}}catch{}},[k,G,q]),useEffect(()=>{if(De.current)try{G.saveCurrentChatId(X);}catch{}},[X,G]),useEffect(()=>{try{R(X,$);}catch{}return ()=>{try{R(X,!1);}catch{}}},[X,$,R]),useEffect(()=>{try{N(X,Je);}catch{}return ()=>{try{N(X,!1);}catch{}}},[X,Je,N]);let jn=useCallback(async()=>{let I=V.trim();if(!I&&Ve.length===0||$)return;let D=[...Ve];ie(""),Ye(),Se(null);try{await xe({text:I,files:D.map(W=>({type:"file",url:W.url,mediaType:W.mimeType||"application/octet-stream",...W.name?{name:W.name}:{},...W.size?{size:W.size}:{}}))});}catch(W){console.error("Failed to send message:",W),Se("Failed to send message. Please try again.");}},[V,Ve,$,xe,Ye]),Nt=useCallback(()=>{if($)return;H(),ie(""),Ye(),Se(null);try{q([]);}catch{}let I=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Pe.current=I;try{ht.createNewChat(()=>{be(I);try{G.saveCurrentChatId(I);}catch{}});}catch{be(I);try{G.saveCurrentChatId(I);}catch{}}},[$,Ye,G,q,be,H,ht]),qn=useCallback(()=>{gt(I=>!I);},[]),Kn=useCallback(()=>{Pt(false);try{G.saveShowChatPreference(!1);}catch{}},[G]),Vn=useCallback(async I=>{let D=I.target.files;D&&await Ft(D,Se),Xe.current&&(Xe.current.value="");},[Ft,Xe]);useEffect(()=>{let I=$t.current;if(!I)return;I.style.height="24px",I.offsetHeight,I.style.height="auto";let D=Math.min(I.scrollHeight,200);I.style.height=`${D}px`;},[V]);let Xn=useCallback((I,D,W,Zn)=>{yt({id:D,text:W,attachments:Zn||[]}),ft(true);},[]),Yn=useCallback(()=>{if(!(!Be||$))try{let I=O.findIndex(W=>W.id===Be.id);if(I===-1)return;let D=O.slice(0,I);try{q(D);}catch{}ie(Be.text),Bt(Be.attachments),ft(!1),yt(null),Ke();}catch(I){console.error("Failed to edit message:",I),Se("Failed to edit message. Please try again.");}},[Be,$,O,q,Bt,Ke]),Jn=useCallback(()=>{ft(false),yt(null);},[]),Ut=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:A.textColor,gap:"16px",zIndex:1e3,transform:Je?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(xn,{title:B("general.agent")+2,alwaysOpen:false,streaming:$,dir:C||"ltr",resolvedColors:A,onNew:Nt,onToggleHistory:qn,onClose:Kn,historyBtnRef:Un,t:B}),jsx("div",{ref:_n,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":A.primaryColor,"--hsafa-border":A.borderColor,"--hsafa-card":A.cardBackground,"--hsafa-text":A.textColor,"--hsafa-muted":A.mutedTextColor,"--hsafa-bg":A.backgroundColor,"--hsafa-hover":A.hoverBackground,"--hsafa-input-bg":A.inputBackground,"--hsafa-accent":A.accentColor},children:O.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:u&&u.length>0?jsx(Sn,{prompts:u,onSelect:I=>ie(I),resolvedColors:A,disabled:$}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:B("messages.empty")})}):jsx(Tn,{chatMessages:O,isLoading:$,openReasoningIds:Wn,toggleReasoning:I=>On(D=>{let W=new Set(D);return W.has(I)?W.delete(I):W.add(I),W}),resolvedColors:A,t:B,onUserMessageClick:Xn,HsafaUI:E,onUIError:J,onUISuccess:Z,addToolResult:I=>de?.addToolResult?.(I),editableMessageIcon:l?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&Wo.createElement(s,{}),Dt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:Dt}),jsx("button",{onClick:()=>Se(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),ce&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",ce.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(In,{input:V,setInput:ie,textareaRef:$t,fileInputRef:Xe,isLoading:$,uploading:Ln,attachments:Ve,formatBytes:Hn,handleRemoveAttachment:Fn,onFileInputChange:Vn,onSend:jn,onStop:()=>mt(),status:he,t:B,resolvedColors:A})]}),jsx(En,{historyOpen:Bn,historySearch:Dn,currentChatId:X,refreshKey:$n,resolvedColors:A,onClose:()=>gt(false),onSearchChange:Pn,onChatSelect:I=>{if(gt(false),I&&I!==X&&(H(),be(I),k===void 0)){try{G.saveCurrentChatId(I);}catch{}try{let D=G.loadChat(I),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}}catch{}}},onChatDelete:I=>{try{G.deleteChat(I),Nn(D=>D+1),I===X&&Nt();}catch{}},loadChatsIndex:()=>G.loadChatsIndex(),historyPopupRef:zn}),jsx(An,{isOpen:Gn,resolvedColors:A,onConfirm:Yn,onCancel:Jn,editProcessContent:l}),jsx("style",{children:`
25
+ `}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[t.map((v,h)=>{let s=Array.isArray(v.parts)?v.parts:[],u=s.filter(i=>i.type==="text").map(i=>i&&typeof i.text=="string"?i.text:"").join(`
26
+ `),a=s.filter(i=>i.type==="file"||i.type==="image").map(i=>{if(i.type==="image"){let l=typeof i.image=="string"?i.image:i.image?.toString?.()||"";return {id:l||`${v.id}-img-${Date.now()}`,name:i.name||"image",url:l,mimeType:i.mediaType||"image/jpeg",size:i.size||0}}else return {id:i.url||`${v.id}-file-${Date.now()}`,name:i.name||"file",url:i.url||"",mimeType:i.mediaType||"application/octet-stream",size:i.size||0}});return jsx("div",{style:{padding:"0 4px"},children:v.role==="user"?jsx("div",{children:jsx("div",{title:p("editor.clickToEdit"),onClick:()=>f(v,v.id,u,a),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:o.accentColor,color:o.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:i=>i.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:i=>i.currentTarget.style.backgroundColor=o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[u,a.length>0&&jsx(Un,{attachments:a,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(K,{IconComponent:w||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(Pn,{parts:s,messageId:v.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:C,onUISuccess:I,addToolResult:m})},v.id)}),e&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function zn({input:t,setInput:e,textareaRef:n,fileInputRef:r,isLoading:o,uploading:p,attachments:f,formatBytes:c,handleRemoveAttachment:C,onFileInputChange:I,onSend:m,onStop:w,status:v,t:h,resolvedColors:s}){let u=v==="streaming"||v==="submitted",a=f.length>0||t.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${s.borderColor}`,backgroundColor:s.cardBackground},children:[f.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:f.map(i=>{let l=i.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:s.inputBackground,borderRadius:"10px",border:`1px solid ${s.borderColor}`,fontSize:"12px",color:s.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:l?"transparent":s.cardBackground},children:l?jsx("img",{src:i.url,alt:i.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:i.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:i.name}),jsx("span",{style:{color:s.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(i.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[l&&jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:s.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:h("input.previewImage"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsx("button",{onClick:()=>C(i.id),style:{background:"none",border:"none",color:s.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:h("input.removeFile"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},i.id)})}),p&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:s.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:h("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:h("input.placeholder"),value:t,onChange:i=>e(i.target.value),onKeyDown:i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),m());},disabled:o||p,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:s.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:r,type:"file",multiple:true,onChange:I,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:s.mutedTextColor},children:jsx("button",{onClick:()=>r.current?.click(),disabled:o||p,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||p?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||p?.5:1},"aria-label":h("input.attachFiles"),children:jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:o?jsx("button",{onClick:w,disabled:!u,"aria-label":h("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:u?1:.4,cursor:u?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{u&&(i.currentTarget.style.backgroundColor="#ef444430",i.currentTarget.style.transform="scale(1.02)");},onMouseLeave:i=>{i.currentTarget.style.backgroundColor="#ef444420",i.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:m,disabled:!a||p,"aria-label":h("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${s.borderColor}`,backgroundColor:s.cardBackground,color:!a||p?s.mutedTextColor:s.primaryColor,cursor:!a||p?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!a||p?.5:1},onMouseEnter:i=>{a&&!p&&(i.currentTarget.style.borderColor=s.primaryColor,i.currentTarget.style.transform="scale(1.02)");},onMouseLeave:i=>{i.currentTarget.style.borderColor=s.borderColor,i.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function Wn({prompts:t,onSelect:e,resolvedColors:n,disabled:r=false}){let[o,p]=useState(null);return !t||t.length===0?null:jsxs("div",{style:{padding:"12px 0",display:"flex",flexDirection:"column",gap:"8px"},children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:n.mutedTextColor,paddingLeft:"4px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Suggested Prompts"}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:t.map((f,c)=>{let C=o===c,I=f.prompt.length>80,m=I&&!C?f.prompt.slice(0,80)+"...":f.prompt;return jsxs("button",{onClick:()=>{r||e(f.prompt);},disabled:r,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,borderRadius:"12px",cursor:r?"not-allowed":"pointer",transition:"all 0.2s ease",textAlign:"left",opacity:r?.5:1,position:"relative",overflow:"hidden"},onMouseEnter:w=>{r||(w.currentTarget.style.backgroundColor=n.hoverBackground,w.currentTarget.style.borderColor=n.primaryColor,w.currentTarget.style.transform="translateX(2px)");},onMouseLeave:w=>{w.currentTarget.style.backgroundColor=n.cardBackground,w.currentTarget.style.borderColor=n.borderColor,w.currentTarget.style.transform="translateX(0)";},children:[jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:n.textColor,marginBottom:"6px",display:"flex",alignItems:"center",gap:"6px"},children:[jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n.primaryColor,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[jsx("path",{d:"M12 20h9"}),jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),f.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:m}),I&&jsxs("button",{onClick:w=>{w.stopPropagation(),p(C?null:c);},style:{marginTop:"8px",padding:"4px 8px",fontSize:"11px",color:n.primaryColor,backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:"4px",fontWeight:500},children:[C?"Show less":"Show more",jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:C?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},c)})})]})}function Gn(t){let e=Date.now()-t,n=Math.max(1,Math.floor(e/1e3));if(n<60)return `${n}s`;let r=Math.floor(n/60);if(r<60)return `${r}m`;let o=Math.floor(r/60);if(o<24)return `${o}h`;let p=Math.floor(o/24);if(p<7)return `${p}d`;let f=Math.floor(p/7);if(f<4)return `${f}w`;let c=Math.floor(p/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function jn({historyOpen:t,historySearch:e,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:p,onSearchChange:f,onChatSelect:c,onChatDelete:C,loadChatsIndex:I,historyPopupRef:m}){if(!t)return null;let w=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:p}),jsxs("div",{ref:m,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:e,onChange:v=>f(v.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:o.inputBackground,padding:"8px 12px",fontSize:"14px",color:o.textColor,border:`1px solid ${o.borderColor}`,outline:"none"},onFocus:v=>v.currentTarget.style.borderColor=o.primaryColor,onBlur:v=>v.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let v=e.toLowerCase().trim(),h=I();return v&&(h=h.filter(s=>(s.title||"").toLowerCase().includes(v))),!h||h.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:h.map((s,u)=>jsx("div",{style:{borderTop:u>0?`1px solid ${o.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:s.id===n?o.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:o.textColor},onMouseEnter:a=>a.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:a=>a.currentTarget.style.backgroundColor="transparent",onClick:()=>c(s.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:o.textColor},children:s.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:Gn(s.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:o.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:a=>{a.currentTarget.style.color="#ef4444",a.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",a.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:a=>{a.currentTarget.style.color=o.mutedTextColor,a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.borderColor="transparent";},onClick:a=>{a.stopPropagation(),C(s.id);},children:jsx(K,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},s.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(w,document.body):w}function Vn({isOpen:t,resolvedColors:e,onConfirm:n,onCancel:r,editProcessContent:o}){if(!t)return null;let p=o?.title||"Edit Message",f=o?.content||"This will remove this message and all messages after it, and place its content in the input field for editing. Do you want to continue?",c=o?.submit_button_label||"Edit",C=o?.cancel_button_label||"Cancel",I=o?.icon,m=typeof f=="function",w=m?f:null,v=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${e.borderColor}`,backgroundColor:e.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${e.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[I?jsx("div",{style:{flexShrink:0},children:jsx(K,{IconComponent:I,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:e.mutedTextColor},children:jsx(K,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:e.textColor,flex:1},children:p})]}),jsx("div",{style:{padding:"24px",color:e.textColor,fontSize:"14px",lineHeight:"1.6"},children:m&&w?jsx(w,{}):jsx("p",{style:{margin:0},children:f})}),jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${e.borderColor}`,justifyContent:"flex-end"},children:[jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${e.borderColor}`,backgroundColor:"transparent",color:e.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor=e.hoverBackground;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent";},children:C}),jsx("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:"none",backgroundColor:e.primaryColor,color:e.backgroundColor,cursor:"pointer",transition:"all 0.2s",opacity:1},onMouseEnter:h=>{h.currentTarget.style.opacity="0.9";},onMouseLeave:h=>{h.currentTarget.style.opacity="1";},children:c})]})]})]});return typeof document<"u"&&document.body?createPortal(v,document.body):v}function Vr({agentId:t,theme:e,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:p,borderColor:f,textColor:c,accentColor:C,baseUrl:I="",initialMessages:m=[],onMessagesChange:w,defaultOpen:v=true,floatingButtonPosition:h={bottom:24,right:24},HsafaTools:s={},HsafaUI:u={},componentAboveInput:a,editProcessContent:i,presetPrompts:l,onStart:g,onFinish:d,currentChat:x,onChatChanged:y,templateParams:b}){let{dir:k,theme:E,baseUrl:T,setStreamingState:P,setChatOpenState:B,tools:z,uiComponents:_}=ee(),j=e||E||"dark",te=I&&I.length>0?I:T||"",A={primaryColor:j==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:p||(j==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:f||(j==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(j==="dark"?"#EDEEF0":"#111827"),accentColor:C||(j==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:j==="dark"?"#6f7276":"#6B7280",inputBackground:j==="dark"?"#17181C":"#F3F4F6",cardBackground:j==="dark"?"#121318":"#FFFFFF",hoverBackground:j==="dark"?"#1c1e25":"#F3F4F6"},M=S=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[S]||S,W=useMemo(()=>({...z&&z.size>0?Object.fromEntries(z.entries()):{},...s||{}}),[s,z]),J=useMemo(()=>({..._&&_.size>0?Object.fromEntries(_.entries()):{},...u||{}}),[u,_]),Q=Dt({agentId:t,baseUrl:te,tools:W,uiComponents:J,templateParams:b,controlledChatId:x,onChatIdChange:x===void 0?S=>{y&&y(S);}:void 0,onStart:useCallback(S=>{g&&g(S);},[g]),onFinish:useCallback(S=>{d&&d(S);},[d]),onError:useCallback(S=>{console.error("Chat error:",S);},[]),initialMessages:m,onMessagesChange:w}),{input:me,setInput:ne,messages:le,isLoading:q,status:we,error:Ze,sendMessage:Qe,stop:bt,setMessages:ce,notifyMessagesChange:F,chatId:L,setChatId:O,tools:$,uiComponents:oe,formHostRef:re,formStateRef:he,cleanupForms:Ne,onUISuccess:vt,onUIError:Yn,chatApi:Zn}=Q,ae=x!==void 0?x:L,Ue=useCallback(S=>{x===void 0&&O(S),y&&y(S);},[x,O,y]);useEffect(()=>{x!==void 0&&x!==L&&O(x);},[x,L,O]);let{attachments:et,uploading:Qn,fileInputRef:tt,formatBytes:eo,handleRemoveAttachment:to,handleFileSelection:_t,clearAttachments:nt,setAttachments:qt}=ln(te),[Kt,He]=useState(null),[ot,Xt]=useState(()=>{try{return Pe(t).loadShowChatPreference(!!v)}catch{return !!v}}),[no,kt]=useState(false),[oo,ro]=useState(""),[ao,so]=useState(0),io=useRef(null),lo=useRef(null),[co,uo]=useState(new Set),[po,wt]=useState(false),[Oe,It]=useState(null),Jt=useRef(null),fo=on(q),Tt=Bt({agentId:t,chatId:ae,messages:le,isLoading:q,autoSave:true,autoRestore:false}),V=Tt.storage,ze=useRef(false),We=useRef(null);useEffect(()=>{if(!ze.current){if(x!==void 0){try{let S=V.loadChat(x),N=S&&Array.isArray(S.messages)?S.messages:[];if(N.length>0)try{ce(N);}catch{}We.current=x;}catch{}try{V.saveCurrentChatId(x);}catch{}ze.current=true;return}try{let S=V.loadCurrentChatId();if(S){Ue(S);let N=V.loadChat(S),G=N&&Array.isArray(N.messages)?N.messages:[];try{ce(G);}catch{}We.current=S;}}catch{}ze.current=true;}},[x]),useEffect(()=>{if(ze.current&&x!==void 0&&x!==We.current)try{let S=V.loadChat(x),N=S&&Array.isArray(S.messages)?S.messages:[];try{ce(N);}catch{}We.current=x;try{V.saveCurrentChatId(x);}catch{}}catch{}},[x,V,ce]),useEffect(()=>{if(ze.current)try{V.saveCurrentChatId(ae);}catch{}},[ae,V]),useEffect(()=>{try{P(ae,q);}catch{}return ()=>{try{P(ae,!1);}catch{}}},[ae,q,P]),useEffect(()=>{try{B(ae,ot);}catch{}return ()=>{try{B(ae,!1);}catch{}}},[ae,ot,B]);let mo=useCallback(async()=>{let S=me.trim();if(!S&&et.length===0||q)return;let N=[...et];ne(""),nt(),He(null);try{await Qe({text:S,files:N.map(G=>({type:"file",url:G.url,mediaType:G.mimeType||"application/octet-stream",...G.name?{name:G.name}:{},...G.size?{size:G.size}:{}}))});}catch(G){console.error("Failed to send message:",G),He("Failed to send message. Please try again.");}},[me,et,q,Qe,nt]),Yt=useCallback(()=>{if(q)return;Ne(),ne(""),nt(),He(null);try{ce([]);}catch{}let S=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;We.current=S;try{Tt.createNewChat(()=>{Ue(S);try{V.saveCurrentChatId(S);}catch{}});}catch{Ue(S);try{V.saveCurrentChatId(S);}catch{}}},[q,nt,V,ce,Ue,Ne,Tt]),go=useCallback(()=>{kt(S=>!S);},[]),yo=useCallback(()=>{Xt(false);try{V.saveShowChatPreference(!1);}catch{}},[V]),ho=useCallback(async S=>{let N=S.target.files;N&&await _t(N,He),tt.current&&(tt.current.value="");},[_t,tt]);useEffect(()=>{let S=Jt.current;if(!S)return;S.style.height="24px",S.offsetHeight,S.style.height="auto";let N=Math.min(S.scrollHeight,200);S.style.height=`${N}px`;},[me]);let xo=useCallback((S,N,G,vo)=>{It({id:N,text:G,attachments:vo||[]}),wt(true);},[]),Co=useCallback(()=>{if(!(!Oe||q))try{let S=le.findIndex(G=>G.id===Oe.id);if(S===-1)return;let N=le.slice(0,S);try{ce(N);}catch{}ne(Oe.text),qt(Oe.attachments),wt(!1),It(null),F();}catch(S){console.error("Failed to edit message:",S),He("Failed to edit message. Please try again.");}},[Oe,q,le,ce,qt,F]),bo=useCallback(()=>{wt(false),It(null);},[]),Zt=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:A.textColor,gap:"16px",zIndex:1e3,transform:ot?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(Dn,{title:M("general.agent")+2,alwaysOpen:false,streaming:q,dir:k||"ltr",resolvedColors:A,onNew:Yt,onToggleHistory:go,onClose:yo,historyBtnRef:io,t:M}),jsx("div",{ref:fo,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":A.primaryColor,"--hsafa-border":A.borderColor,"--hsafa-card":A.cardBackground,"--hsafa-text":A.textColor,"--hsafa-muted":A.mutedTextColor,"--hsafa-bg":A.backgroundColor,"--hsafa-hover":A.hoverBackground,"--hsafa-input-bg":A.inputBackground,"--hsafa-accent":A.accentColor},children:le.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:l&&l.length>0?jsx(Wn,{prompts:l,onSelect:S=>ne(S),resolvedColors:A,disabled:q}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:M("messages.empty")})}):jsx(On,{chatMessages:le,isLoading:q,openReasoningIds:co,toggleReasoning:S=>uo(N=>{let G=new Set(N);return G.has(S)?G.delete(S):G.add(S),G}),resolvedColors:A,t:M,onUserMessageClick:xo,HsafaUI:oe,onUIError:Yn,onUISuccess:vt,addToolResult:S=>Zn?.addToolResult?.(S),editableMessageIcon:i?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[a&&br.createElement(a,{}),Kt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:Kt}),jsx("button",{onClick:()=>He(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),Ze&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",Ze.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(zn,{input:me,setInput:ne,textareaRef:Jt,fileInputRef:tt,isLoading:q,uploading:Qn,attachments:et,formatBytes:eo,handleRemoveAttachment:to,onFileInputChange:ho,onSend:mo,onStop:()=>bt(),status:we,t:M,resolvedColors:A})]}),jsx(jn,{historyOpen:no,historySearch:oo,currentChatId:ae,refreshKey:ao,resolvedColors:A,onClose:()=>kt(false),onSearchChange:ro,onChatSelect:S=>{if(kt(false),S&&S!==ae&&(Ne(),Ue(S),x===void 0)){try{V.saveCurrentChatId(S);}catch{}try{let N=V.loadChat(S),G=N&&Array.isArray(N.messages)?N.messages:[];try{ce(G);}catch{}}catch{}}},onChatDelete:S=>{try{V.deleteChat(S),so(N=>N+1),S===ae&&Yt();}catch{}},loadChatsIndex:()=>V.loadChatsIndex(),historyPopupRef:lo}),jsx(Vn,{isOpen:po,resolvedColors:A,onConfirm:Co,onCancel:bo,editProcessContent:i}),jsx("style",{children:`
27
27
  @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
28
28
  @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
29
- `})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(nt,{}),createPortal(Ut,document.body),jsx(Wt,{show:!Je,onClick:()=>{Pt(true);try{G.saveShowChatPreference(!0);}catch{}},resolvedColors:A,floatingButtonPosition:x})]}):Ut}var Rn={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};function hr({children:e,theme:t="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:c,mutedTextColor:m,enableBorderAnimation:i=true,borderRadius:w=16,enableContentBorder:S=true,className:d="",enableMargin:T=true,chatWidth:v=420,dir:x="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:b,dir:s,theme:l}=ne(),u=(x??s)||"ltr",h=(t??l)||"dark",f=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[k,y]=useState(false);useEffect(()=>{let U=setTimeout(()=>y(true),50);return ()=>clearTimeout(U)},[]);let p=Rn[h],C={primaryColor:n||p.primaryColor,backgroundColor:r||p.backgroundColor,borderColor:o||p.borderColor,textColor:c||p.textColor,accentColor:p.accentColor,mutedTextColor:m||p.mutedTextColor,inputBackground:p.inputBackground,cardBackground:p.cardBackground,hoverBackground:p.hoverBackground},M=typeof w=="number"?`${w}px`:w,g=typeof v=="number"?`${v}px`:v,R=T&&b?u==="rtl"?{marginLeft:g}:{marginRight:g}:{},N=T&&b?`calc(100% - ${g})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:d,style:{width:N,height:"100%",transition:k?"all 0.2s ease-out":"none",padding:b&&S?"16px":"0",...R},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:k?"all 0.2s ease-out":"none",borderRadius:b?M:"0",border:b&&a&&i?"none":b?`1px solid ${C.borderColor}`:"none",padding:b&&a&&i?"1.5px":"0",background:b&&a&&i?`linear-gradient(120deg, ${C.primaryColor}dd 0%, ${C.primaryColor}88 25%, ${C.primaryColor}00 50%, ${C.primaryColor}88 75%, ${C.primaryColor}dd 100%)`:"transparent",backgroundSize:b&&a&&i?"300% 300%":"auto",animation:b&&a&&i?`${f.current}-border-flow 3s ease-in-out infinite`:"none",filter:b&&a&&i?`drop-shadow(0 0 10px ${C.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:b&&S?M:"0",backgroundColor:b&&S?C.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${C.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`
30
- @keyframes ${f.current}-border-flow {
29
+ `})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(lt,{}),createPortal(Zt,document.body),jsx(en,{show:!ot,onClick:()=>{Xt(true);try{V.saveShowChatPreference(!0);}catch{}},resolvedColors:A,floatingButtonPosition:h})]}):Zt}var qn={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};function Jr({children:t,theme:e="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:p,mutedTextColor:f,enableBorderAnimation:c=true,borderRadius:C=16,enableContentBorder:I=true,className:m="",enableMargin:w=true,chatWidth:v=420,dir:h="ltr"}){let{isAnyStreaming:s,isAnyChatOpen:u,dir:a,theme:i}=ee(),l=(h??a)||"ltr",g=(e??i)||"dark",d=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[x,y]=useState(false);useEffect(()=>{let z=setTimeout(()=>y(true),50);return ()=>clearTimeout(z)},[]);let b=qn[g],k={primaryColor:n||b.primaryColor,backgroundColor:r||b.backgroundColor,borderColor:o||b.borderColor,textColor:p||b.textColor,accentColor:b.accentColor,mutedTextColor:f||b.mutedTextColor,inputBackground:b.inputBackground,cardBackground:b.cardBackground,hoverBackground:b.hoverBackground},E=typeof C=="number"?`${C}px`:C,T=typeof v=="number"?`${v}px`:v,P=w&&u?l==="rtl"?{marginLeft:T}:{marginRight:T}:{},B=w&&u?`calc(100% - ${T})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:m,style:{width:B,height:"100%",transition:x?"all 0.2s ease-out":"none",padding:u&&I?"16px":"0",...P},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:x?"all 0.2s ease-out":"none",borderRadius:u?E:"0",border:u&&s&&c?"none":u?`1px solid ${k.borderColor}`:"none",padding:u&&s&&c?"1.5px":"0",background:u&&s&&c?`linear-gradient(120deg, ${k.primaryColor}dd 0%, ${k.primaryColor}88 25%, ${k.primaryColor}00 50%, ${k.primaryColor}88 75%, ${k.primaryColor}dd 100%)`:"transparent",backgroundSize:u&&s&&c?"300% 300%":"auto",animation:u&&s&&c?`${d.current}-border-flow 3s ease-in-out infinite`:"none",filter:u&&s&&c?`drop-shadow(0 0 10px ${k.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:u&&I?E:"0",backgroundColor:u&&I?k.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${k.mutedTextColor}40 transparent`},children:t})})}),jsx("style",{children:`
30
+ @keyframes ${d.current}-border-flow {
31
31
  0% { background-position: 0% 50%; }
32
32
  50% { background-position: 100% 50%; }
33
33
  100% { background-position: 0% 50%; }
34
34
  }
35
- `})," "]})}var Lt=class{constructor(){this.components=new Map;}register(t,n){this.components.set(t,n);}unregister(t){this.components.delete(t);}get(t){return this.components.get(t)}has(t){return this.components.has(t)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},Cr=new Lt;export{wr as Button,hr as ContentContainer,nt as CursorController,Ue as FillActiveInput,Wt as FloatingChatButton,pr as HsafaChat,oo as HsafaProvider,Cr as componentRegistry,ve as controlCursor,Ne as getDomComponents,ve as guideCursor,_t as useAutoScroll,Et as useChatStorage,Vt as useFileUpload,ne as useHsafa,St as useHsafaAgent,zo as useMessageEditor};//# sourceMappingURL=index.js.map
35
+ `})," "]})}var Wt=typeof navigator<"u"?navigator:void 0;function ke(){return !!Wt?.storage?.getDirectory}async function Re(){if(!ke()||!Wt?.storage?.getDirectory)return null;try{return await Wt.storage.getDirectory()}catch{return null}}async function Kn(t,e){try{return await t.getFileHandle(e,{create:!1}),!0}catch{return false}}async function Xn(t,e){let n=await t.createWritable();await n.write(new Blob([e],{type:"application/json"})),await n.close();}async function Jn(t){return await(await t.getFile()).text()}function Qr(t){return t.kind==="directory"}function ea(t){try{return JSON.parse(t)}catch{return null}}function ta(t){let e=`hsafa:${t}`;return {latest:n=>`${e}:${n}:latest`,version:(n,r)=>`${e}:${n}:versions:${r}`,latestPrefix:`${e}:`}}async function Z(t,e,n){try{return await t.getDirectoryHandle(e,{create:n})}catch{return null}}async function Gt(t,e){try{let n=await t.getFileHandle(e,{create:!1});return await Jn(n)}catch{return null}}async function jt(t,e,n){try{let r=await t.getFileHandle(e,{create:!0});return await Xn(r,n),!0}catch{return false}}function na(t){let{namespace:e,serialize:n=u=>JSON.stringify(u),deserialize:r=u=>JSON.parse(u),storageOrder:o=["opfs","localStorage"],legacyDecode:p}=t,f=ta(e),c=(u,a,i)=>{let l={chatId:u,versionId:a,updatedAt:new Date().toISOString(),data:n(i)};return JSON.stringify(l)},C=u=>{let a=ea(u);if(a&&typeof a.chatId=="string"&&typeof a.versionId=="string"){if(typeof a.updatedAt!="string"||typeof a.data!="string")return null;try{return {value:r(a.data),record:a}}catch{return null}}if(p)try{let i=p(u);if(!i||typeof i.chatId!="string"||typeof i.versionId!="string")return null;let l={chatId:i.chatId,versionId:i.versionId,updatedAt:typeof i.updatedAt=="string"?i.updatedAt:new Date().toISOString(),data:n(i.value)};return {value:i.value,record:l}}catch{return null}return null};return {saveLatest:async(u,a)=>{let i=c(u,"__latest",a);for(let l of o){if(l==="opfs"){if(!ke())continue;let g=await Re();if(!g)continue;let d=await Z(g,e,true);if(!d)continue;let x=await Z(d,u,true);if(!x)continue;if(await jt(x,"latest.json",i))return}if(l==="localStorage")try{localStorage.setItem(f.latest(u),i);return}catch{continue}}},loadLatest:async u=>{for(let a of o){if(a==="opfs"){if(!ke())continue;let i=await Re();if(!i)continue;let l=await Z(i,e,false);if(!l)continue;let g=await Z(l,u,false);if(!g)continue;let d=await Gt(g,"latest.json");if(!d)continue;let x=C(d);if(!x)continue;return x.value}if(a==="localStorage")try{let i=localStorage.getItem(f.latest(u));if(!i)continue;let l=C(i);if(!l)continue;return l.value}catch{continue}}return null},saveVersion:async(u,a,i)=>{let l=c(u,a,i);for(let g of o){if(g==="opfs"){if(!ke())continue;let d=await Re();if(!d)continue;let x=await Z(d,e,true);if(!x)continue;let y=await Z(x,u,true);if(!y)continue;let b=await Z(y,"versions",true);if(!b||!await jt(b,`${a}.json`,l))continue;if(await jt(y,"latest.json",l))return}if(g==="localStorage")try{localStorage.setItem(f.version(u,a),l),localStorage.setItem(f.latest(u),l);return}catch{continue}}},loadVersion:async(u,a)=>{for(let i of o){if(i==="opfs"){if(!ke())continue;let l=await Re();if(!l)continue;let g=await Z(l,e,false);if(!g)continue;let d=await Z(g,u,false);if(!d)continue;let x=await Z(d,"versions",false);if(!x)continue;let y=await Gt(x,`${a}.json`);if(!y)continue;let b=C(y);if(!b)continue;return b.value}if(i==="localStorage")try{let l=localStorage.getItem(f.version(u,a));if(!l)continue;let g=C(l);if(!g)continue;return g.value}catch{continue}}return null},hasVersion:async(u,a)=>{for(let i of o){if(i==="opfs"){if(!ke())continue;let l=await Re();if(!l)continue;let g=await Z(l,e,false);if(!g)continue;let d=await Z(g,u,false);if(!d)continue;let x=await Z(d,"versions",false);if(!x)continue;if(await Kn(x,`${a}.json`))return true}if(i==="localStorage")try{if(localStorage.getItem(f.version(u,a))!=null)return !0}catch{continue}}return false},findMostRecentChatId:async()=>{for(let u of o){if(u==="opfs"){if(!ke())continue;let a=await Re();if(!a)continue;let i=await Z(a,e,false);if(!i)continue;let l=null,g=0;try{let d=i.entries?.();if(!d)continue;for await(let[x,y]of d){if(!Qr(y))continue;let k=await Gt(y,"latest.json");if(!k)continue;let E=C(k);if(!E)continue;let T=Date.parse(E.record.updatedAt);!Number.isNaN(T)&&T>g&&(g=T,l=E.record.chatId||x);}if(l)return l}catch{continue}}if(u==="localStorage")try{let a=null,i=0;for(let l=0;l<localStorage.length;l++){let g=localStorage.key(l);if(!g||!g.startsWith(f.latestPrefix)||!g.endsWith(":latest"))continue;let d=localStorage.getItem(g);if(!d)continue;let x=C(d);if(!x)continue;let y=Date.parse(x.record.updatedAt);!Number.isNaN(y)&&y>i&&(i=y,a=x.record.chatId);}if(a)return a}catch{continue}}return null}}}var Vt=class{constructor(){this.components=new Map;}register(e,n){this.components.set(e,n);}unregister(e){this.components.delete(e);}get(e){return this.components.get(e)}has(e){return this.components.has(e)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},oa=new Vt;export{sa as Button,Jr as ContentContainer,lt as CursorController,je as FillActiveInput,en as FloatingChatButton,Vr as HsafaChat,So as HsafaProvider,oa as componentRegistry,Se as controlCursor,na as createHsafaArtifactStore,Ge as getDomComponents,Se as guideCursor,on as useAutoScroll,fr as useChatArtifact,Cr as useChatArtifactVersioning,Bt as useChatStorage,ln as useFileUpload,ee as useHsafa,$t as useHsafaActiveChatId,Dt as useHsafaAgent,lr as useMessageEditor};//# sourceMappingURL=index.js.map
36
36
  //# sourceMappingURL=index.js.map