@hsafa/ui-sdk 5.5.9 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {jsxs,jsx,Fragment}from'react/jsx-runtime';import*as At from'react';import At__default,{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 as X$1,Download}from'lucide-react';var Tt={};var da=({variant:t="primary",size:e="md",loading:n=false,disabled:r,children:o,className:u,...f})=>{let c=[Tt.button,Tt[t],Tt[e],n&&Tt.loading,u].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:r||n,...f,children:[n&&jsx("span",{className:Tt.spinner}),jsx("span",{className:n?Tt.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:u=>{u.currentTarget.style.borderColor=n.primaryColor,u.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:u=>{u.currentTarget.style.borderColor=n.borderColor,u.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 rn(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 an(t,e){if(!t)return e;let n=t.endsWith("/")?t.slice(0,-1):t,r=e.startsWith("/")?e:`/${e}`;return `${n}${r}`}var sn=createContext(void 0);function Ro({baseUrl:t,dir:e="ltr",theme:n="dark",children:r,tools:o,uiComponents:u}){let[f,c]=useState(new Map),[x,k]=useState(new Map),[m,T]=useState(()=>new Map(Object.entries(o||{}))),[v,C]=useState(()=>new Map(Object.entries(u||{}))),[s,p]=useState(new Map),[a,i]=useState(new Map),[l,g]=useState(void 0),d=useCallback((E,H)=>(c(A=>{let M=new Map(A);return M.set(String(E),H),M}),()=>{c(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});}),[]),h=useCallback((E,H)=>{c(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});},[]),y=useCallback((E,H)=>(k(A=>{let M=new Map(A);return M.set(String(E),H),M}),()=>{k(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});}),[]),b=useCallback((E,H)=>{k(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});},[]),w=useCallback((E,H)=>(T(A=>{let M=new Map(A);return M.set(String(E),H),M}),()=>{T(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});}),[]),R=useCallback((E,H)=>{T(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});},[]),I=useCallback((E,H)=>(C(A=>{let M=new Map(A);return M.set(String(E),H),M}),()=>{C(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});}),[]),B=useCallback((E,H)=>{C(A=>{let M=new Map(A),j=M.get(String(E));return (!H||j===H)&&M.delete(String(E)),M});},[]),L=useCallback((E,H)=>{p(A=>{let M=new Map(A);return H?M.set(E,true):M.delete(E),M});},[]),D=useCallback((E,H)=>{i(A=>{let M=new Map(A);return M.set(E,H),M});},[]),P=useMemo(()=>Array.from(s.values()).some(E=>E),[s]),G=useMemo(()=>Array.from(a.values()).some(E=>E),[a]),_=useMemo(()=>({baseUrl:t,dir:e,theme:n,actions:f,components:x,tools:m,uiComponents:v,registerAction:d,unregisterAction:h,registerComponent:y,unregisterComponent:b,registerTool:w,unregisterTool:R,registerUIComponent:I,unregisterUIComponent:B,isAnyStreaming:P,setStreamingState:L,isAnyChatOpen:G,setChatOpenState:D,currentChatId:l,setCurrentChatId:g}),[t,e,n,f,x,m,v,d,h,y,b,w,R,I,B,P,L,G,D,l]);return jsx(sn.Provider,{value:_,children:r})}function et(){let t=useContext(sn);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 Ee=25*1024*1024;function cn(t){let{baseUrl:e}=et(),n=t||e||"",[r,o]=useState([]),[u,f]=useState(false),c=useRef(null),x=useCallback(s=>{if(!s||Number.isNaN(s))return "0 B";let p=["B","KB","MB","GB","TB"],a=Math.min(p.length-1,Math.floor(Math.log(s)/Math.log(1024)));return `${(s/Math.pow(1024,a)).toFixed(a===0?0:1)} ${p[a]}`},[]),k=useCallback(async s=>{let p=new FormData;p.append("file",s);let a=await fetch(an(n,"/api/uploads"),{method:"POST",body:p});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(p=>p.filter(a=>a.id!==s));},[]),T=useCallback(async(s,p)=>{if(!s)return;let a=Array.isArray(s)?s:Array.from(s);p(null),f(true);let i=[];try{for(let l of a){if(l.size>Ee){p(`"${l.name}" exceeds the ${x(Ee)} limit.`);continue}try{let g=await k(l);i.push(g);}catch(g){console.error("Failed to upload attachment:",g),p(String(g?.message??`Failed to upload ${l.name}`));}}i.length&&o(l=>[...l,...i]);}finally{f(false);}},[k,x]),v=useCallback((s,p)=>{let a=[],i=(s||"").trim();i&&a.push({type:"text",text:i});for(let l of p||[]){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},[]),C=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:u,fileInputRef:c,formatBytes:x,handleRemoveAttachment:m,handleFileSelection:T,buildUserContent:v,clearAttachments:C,setAttachments:o,MAX_UPLOAD_SIZE:Ee}}function dn(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,u)=>{let f=u||{},c=f?.body?JSON.parse(f.body):{},x=r&&typeof r=="object"?r:{};console.log("\u{1F680} [SDK] Before merge - body:",c),console.log("\u{1F680} [SDK] Before merge - mergedParams:",x);let k={...x,...c,chatId:n};return console.log("\u{1F680} [SDK] After merge - enhancedBody:",k),fetch(o,{...u,body:JSON.stringify(k)})}})}function Lo(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 Do(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 He(t){if(t.textContent&&t.textContent.trim())return t.textContent.trim().slice(0,100)}function Fe(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 Po(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 u=n.className.split(" ").filter(f=>f.trim()).slice(0,2);u.length>0&&(r+="."+u.join("."));}let o=n.parentElement;if(o){let u=Array.from(o.children).filter(f=>f.tagName===n.tagName);if(u.length>1){let f=u.indexOf(n)+1;r+=`:nth-child(${f})`;}}e.unshift(r),n=o;}return e.slice(-3).join(" > ")}async function jt(t={}){try{let{includeHidden:e=!1,selector:n,what:r="content",limit:o}=t,u=document.querySelector(".hsafa-content-container");if(!u)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&&u.querySelector(n)||u,c=[],x=[];r==="inputs"?x=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:x=["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(x.join(", ")).forEach(a=>{let i=Lo(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:Po(a)};a instanceof HTMLInputElement?(l.type=a.type,l.name=a.name||void 0,l.placeholder=a.placeholder||void 0,l.value=Fe(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=Fe(a),l.disabled=a.disabled,l.required=a.required):a instanceof HTMLSelectElement?(l.name=a.name||void 0,l.value=Fe(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=He(a)):a instanceof HTMLAnchorElement?(l.href=a.href,l.text=He(a)):a instanceof HTMLImageElement?(l.text=a.alt||void 0,l.label=a.alt||l.label):l.text=He(a),l.label=Do(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 T=c.length,C=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),s=T>C,p=s?c.slice(0,C):c;return {ok:!0,components:p,count:p.length,total:T,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=jt);async function St(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=St);function un(t){return !!t&&t.nodeType===1}function dt(t,e){t.dispatchEvent(new Event(e,{bubbles:true}));}function pn(t,e){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value")?.set;n?n.call(t,e):t.value=e,dt(t,"input");}function Bo(t,e){t.checked!==e&&t.click();}function No(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);dt(t,"input"),dt(t,"change");}function $o(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);}),dt(t,"input"),dt(t,"change");}function Oo(t){return t?t instanceof Date?t.toISOString().slice(0,10):String(t):""}function Uo(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}),dt(t,"input"),dt(t,"change");}async function Vt(t,e={}){let n=document.activeElement||null;if(n&&un(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,u=(o.type||"text").toLowerCase();if(u==="checkbox")Bo(o,!!t);else if(u==="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(u==="file")if(t instanceof File||Array.isArray(t)&&t.every(f=>f instanceof File))Uo(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=u==="date"?Oo(t):String(t??"");pn(o,f),dt(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,u=String(t??"");return pn(o,u),dt(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?$o(o,Array.isArray(t)?t:[t]):No(o,t),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(un(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(t??""),dt(o,"input"),dt(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=Vt);var _t=null,ae={},mn=false,Dt=null,ie=false;function Le(t){t.classList.add("visible");}function bn(){ie=true,Dt!=null&&(clearTimeout(Dt),Dt=null);}function Wo(t,e=1500){ie||(Dt!=null&&clearTimeout(Dt),Dt=window.setTimeout(()=>{ie||t.classList.remove("visible");},e));}function Go(t,e=1200){ie=false,Wo(t,e);}function jo(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 Vo(t,e=1500,n=160){let r=performance.now(),o=t?jo(t):[],u=()=>{let m=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(T=>{m.push(T.scrollLeft,T.scrollTop);}),m},f=()=>{if(!t)return {x:0,y:0};let m=t.getBoundingClientRect();return {x:m.left,y:m.top}},c=u(),x=f(),k=performance.now();return new Promise(m=>{function T(v){let C=u(),s=f(),p=false;for(let a=0;a<C.length;a++)if(C[a]!==c[a]){p=true;break}if(!p&&t&&(s.x!==x.x||s.y!==x.y)&&(p=true),p&&(c=C,x=s,k=v),v-k>=n||v-r>=e){m();return}requestAnimationFrame(T);}requestAnimationFrame(T);})}var _o='<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>',qo='<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 Ko(){if(!ae.arrow)try{ae.arrow=_o,ae.pointer=qo;}catch(t){console.warn("Failed to set cursor SVGs",t);}return ae}function gn({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 Xo(){let t="demo-fake-cursor",e=document.getElementById(t),n=await Ko();if(!mn){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*as Ae from'react';import Ae__default,{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 gs=({variant:t="primary",size:e="md",loading:n=false,disabled:r,children:o,className:u,...f})=>{let c=[Ie.button,Ie[t],Ie[e],n&&Ie.loading,u].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 rn({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:u=>{u.currentTarget.style.borderColor=n.primaryColor,u.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:u=>{u.currentTarget.style.borderColor=n.borderColor,u.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 ln(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 cn(t,e){if(!t)return e;let n=t.endsWith("/")?t.slice(0,-1):t,r=e.startsWith("/")?e:`/${e}`;return `${n}${r}`}var dn=createContext(void 0);function Lo({baseUrl:t,dir:e="ltr",theme:n="dark",children:r,tools:o,uiComponents:u}){let[f,c]=useState(new Map),[x,k]=useState(new Map),[m,I]=useState(()=>new Map(Object.entries(o||{}))),[b,C]=useState(()=>new Map(Object.entries(u||{}))),[a,p]=useState(new Map),[s,i]=useState(new Map),[l,g]=useState(void 0),d=useCallback((R,F)=>(c(A=>{let M=new Map(A);return M.set(String(R),F),M}),()=>{c(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});}),[]),h=useCallback((R,F)=>{c(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});},[]),y=useCallback((R,F)=>(k(A=>{let M=new Map(A);return M.set(String(R),F),M}),()=>{k(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});}),[]),v=useCallback((R,F)=>{k(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});},[]),w=useCallback((R,F)=>(I(A=>{let M=new Map(A);return M.set(String(R),F),M}),()=>{I(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});}),[]),E=useCallback((R,F)=>{I(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});},[]),T=useCallback((R,F)=>(C(A=>{let M=new Map(A);return M.set(String(R),F),M}),()=>{C(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});}),[]),N=useCallback((R,F)=>{C(A=>{let M=new Map(A),j=M.get(String(R));return (!F||j===F)&&M.delete(String(R)),M});},[]),$=useCallback((R,F)=>{p(A=>{let M=new Map(A);return F?M.set(R,true):M.delete(R),M});},[]),L=useCallback((R,F)=>{i(A=>{let M=new Map(A);return M.set(R,F),M});},[]),P=useMemo(()=>Array.from(a.values()).some(R=>R),[a]),D=useMemo(()=>Array.from(s.values()).some(R=>R),[s]),V=useMemo(()=>({baseUrl:t,dir:e,theme:n,actions:f,components:x,tools:m,uiComponents:b,registerAction:d,unregisterAction:h,registerComponent:y,unregisterComponent:v,registerTool:w,unregisterTool:E,registerUIComponent:T,unregisterUIComponent:N,isAnyStreaming:P,setStreamingState:$,isAnyChatOpen:D,setChatOpenState:L,currentChatId:l,setCurrentChatId:g}),[t,e,n,f,x,m,b,d,h,y,v,w,E,T,N,P,$,D,L,l]);return jsx(dn.Provider,{value:V,children:r})}function se(){let t=useContext(dn);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 Ft=25*1024*1024;function pn(t){let{baseUrl:e}=se(),n=t||e||"",[r,o]=useState([]),[u,f]=useState(false),c=useRef(null),x=useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let p=["B","KB","MB","GB","TB"],s=Math.min(p.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${p[s]}`},[]),k=useCallback(async a=>{let p=new FormData;p.append("file",a);let s=await fetch(cn(n,"/api/uploads"),{method:"POST",body:p});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(l||`Failed to upload ${a.name}`)}let i=await s.json();return {id:i.id,name:i.name||a.name,url:i.url,mimeType:i.mimeType||a.type||"application/octet-stream",size:typeof i.size=="number"?i.size:a.size}},[n]),m=useCallback(a=>{o(p=>p.filter(s=>s.id!==a));},[]),I=useCallback(async(a,p)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);p(null),f(true);let i=[];try{for(let l of s){if(l.size>Ft){p(`"${l.name}" exceeds the ${x(Ft)} limit.`);continue}try{let g=await k(l);i.push(g);}catch(g){console.error("Failed to upload attachment:",g),p(String(g?.message??`Failed to upload ${l.name}`));}}i.length&&o(l=>[...l,...i]);}finally{f(false);}},[k,x]),b=useCallback((a,p)=>{let s=[],i=(a||"").trim();i&&s.push({type:"text",text:i});for(let l of p||[]){let g=l.mimeType||"application/octet-stream";g.startsWith("image/")?s.push({type:"image",image:new URL(l.url),mediaType:g}):s.push({type:"file",data:l.url,mediaType:g,name:l.name});}return s},[]),C=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:u,fileInputRef:c,formatBytes:x,handleRemoveAttachment:m,handleFileSelection:I,buildUserContent:b,clearAttachments:C,setAttachments:o,MAX_UPLOAD_SIZE:Ft}}function fn(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,u)=>{let f=u||{},c=f?.body?JSON.parse(f.body):{},x=r&&typeof r=="object"?r:{};console.log("\u{1F680} [SDK] Before merge - body:",c),console.log("\u{1F680} [SDK] Before merge - mergedParams:",x);let k={...x,...c,chatId:n};return console.log("\u{1F680} [SDK] After merge - enhancedBody:",k),fetch(o,{...u,body:JSON.stringify(k)})}})}function No(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 $o(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 Lt(t){if(t.textContent&&t.textContent.trim())return t.textContent.trim().slice(0,100)}function Dt(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 Uo(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 u=n.className.split(" ").filter(f=>f.trim()).slice(0,2);u.length>0&&(r+="."+u.join("."));}let o=n.parentElement;if(o){let u=Array.from(o.children).filter(f=>f.tagName===n.tagName);if(u.length>1){let f=u.indexOf(n)+1;r+=`:nth-child(${f})`;}}e.unshift(r),n=o;}return e.slice(-3).join(" > ")}async function je(t={}){try{let{includeHidden:e=!1,selector:n,what:r="content",limit:o}=t,u=document.querySelector(".hsafa-content-container");if(!u)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&&u.querySelector(n)||u,c=[],x=[];r==="inputs"?x=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:x=["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(x.join(", ")).forEach(s=>{let i=No(s);if(!i&&!e)return;let l={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:i,isInteractive:!0,selector:Uo(s)};s instanceof HTMLInputElement?(l.type=s.type,l.name=s.name||void 0,l.placeholder=s.placeholder||void 0,l.value=Dt(s),l.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,l.disabled=s.disabled,l.required=s.required):s instanceof HTMLTextAreaElement?(l.name=s.name||void 0,l.placeholder=s.placeholder||void 0,l.value=Dt(s),l.disabled=s.disabled,l.required=s.required):s instanceof HTMLSelectElement?(l.name=s.name||void 0,l.value=Dt(s),l.disabled=s.disabled,l.required=s.required,l.options=Array.from(s.options).map(g=>({value:g.value,label:g.text,selected:g.selected,disabled:g.disabled}))):s instanceof HTMLButtonElement?(l.type=s.type,l.disabled=s.disabled,l.text=Lt(s)):s instanceof HTMLAnchorElement?(l.href=s.href,l.text=Lt(s)):s instanceof HTMLImageElement?(l.text=s.alt||void 0,l.label=s.alt||l.label):l.text=Lt(s),l.label=$o(s),l.role=s.getAttribute("role")||void 0,l.ariaLabel=s.getAttribute("aria-label")||void 0,c.push(l);});let m=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;c.sort((s,i)=>m(i)-m(s));let I=c.length,C=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=I>C,p=a?c.slice(0,C):c;return {ok:!0,components:p,count:p.length,total:I,truncated:a,containerFound:!0}}catch(e){return {ok:false,components:[],count:0,total:0,containerFound:false,error:e?.message||String(e)}}}typeof window<"u"&&(window.getDomComponents=je);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 gn(t){return !!t&&t.nodeType===1}function ue(t,e){t.dispatchEvent(new Event(e,{bubbles:true}));}function mn(t,e){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value")?.set;n?n.call(t,e):t.value=e,ue(t,"input");}function Oo(t,e){t.checked!==e&&t.click();}function zo(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);ue(t,"input"),ue(t,"change");}function Wo(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);}),ue(t,"input"),ue(t,"change");}function _o(t){return t?t instanceof Date?t.toISOString().slice(0,10):String(t):""}function Go(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}),ue(t,"input"),ue(t,"change");}async function Ve(t,e={}){let n=document.activeElement||null;if(n&&gn(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,u=(o.type||"text").toLowerCase();if(u==="checkbox")Oo(o,!!t);else if(u==="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(u==="file")if(t instanceof File||Array.isArray(t)&&t.every(f=>f instanceof File))Go(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=u==="date"?_o(t):String(t??"");mn(o,f),ue(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,u=String(t??"");return mn(o,u),ue(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?Wo(o,Array.isArray(t)?t:[t]):zo(o,t),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(gn(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(t??""),ue(o,"input"),ue(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=Ve);var qe=null,it={},hn=false,Pe=null,ct=false;function Pt(t){t.classList.add("visible");}function wn(){ct=true,Pe!=null&&(clearTimeout(Pe),Pe=null);}function Vo(t,e=1500){ct||(Pe!=null&&clearTimeout(Pe),Pe=window.setTimeout(()=>{ct||t.classList.remove("visible");},e));}function qo(t,e=1200){ct=false,Vo(t,e);}function Ko(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 Xo(t,e=1500,n=160){let r=performance.now(),o=t?Ko(t):[],u=()=>{let m=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(I=>{m.push(I.scrollLeft,I.scrollTop);}),m},f=()=>{if(!t)return {x:0,y:0};let m=t.getBoundingClientRect();return {x:m.left,y:m.top}},c=u(),x=f(),k=performance.now();return new Promise(m=>{function I(b){let C=u(),a=f(),p=false;for(let s=0;s<C.length;s++)if(C[s]!==c[s]){p=true;break}if(!p&&t&&(a.x!==x.x||a.y!==x.y)&&(p=true),p&&(c=C,x=a,k=b),b-k>=n||b-r>=e){m();return}requestAnimationFrame(I);}requestAnimationFrame(I);})}var Jo='<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>',Yo='<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 Zo(){if(!it.arrow)try{it.arrow=Jo,it.pointer=Yo;}catch(t){console.warn("Failed to set cursor SVGs",t);}return it}function xn({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 Qo(){let t="demo-fake-cursor",e=document.getElementById(t),n=await Zo();if(!hn){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*as At from'react';impor
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);}mn=true;}return e?(e.classList.add("as-arrow"),_t||(_t=createRoot(e),_t.render(jsx(gn,{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),_t=createRoot(e),_t.render(jsx(gn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),e}function Pt(t,e,n){return Math.max(e,Math.min(n,t))}function Jo(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}function vn(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),[u,f,c,x=1]=o;return {r:u,g:f,b:c,a:x}}function Yo({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 Zo(t){let e=t?vn(t):null;return !e||e.a===0?false:Yo(e)<.5}function Qo(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=vn(f);if(c&&c.a>0)return f;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function De(t,e,n){let r=Qo(e,n),o=Zo(r),u=o?"#ffffff":"#000000";t.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=u,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 se(t,e,n,r,o="ease-in-out",u="curve",f=.25,c="auto",x){bn(),Le(t);let k=performance.now(),m=o==="linear"?C=>C:Jo,T=u!=="straight",v={x:0,y:0};if(T){let C=n.x-e.x,s=n.y-e.y,p=Math.hypot(C,s)||1,a=(e.x+n.x)/2,i=(e.y+n.y)/2,l=-s/p,g=C/p,d=1;c==="left"?d=-1:c==="right"?d=1:d=Math.random()<.5?-1:1;let h=Pt(f,0,1)*p;v={x:a+d*l*h,y:i+d*g*h};}return new Promise(C=>{function s(p){let a=Pt((p-k)/r,0,1),i=m(a),l,g;if(T){let w=1-i;l=w*w*e.x+2*w*i*v.x+i*i*n.x,g=w*w*e.y+2*w*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 h=.35*(1-i),y=Math.sin(p*.02)*h,b=Math.cos(p*.018)*h;t.style.left=`${l+y}px`,t.style.top=`${g+b}px`,De(t,l+y,g+b),x&&x({x:l+y,y:g+b,t:a,now:p}),a<1?requestAnimationFrame(s):C();}requestAnimationFrame(s);})}function yn(t,e){return {x:t.x+(e?.x??0),y:t.y+(e?.y??0)}}function yt(t,e,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let u=e==="pointerdown"||e==="mousedown",f=e==="pointerup"||e==="mouseup",c={button:0,buttons:u?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let x=new PointerEvent(e,{pointerId:1,pointerType:"mouse",...c});t.dispatchEvent(x);}else {let x=new MouseEvent(e,c);t.dispatchEvent(x);}}catch{let u=new MouseEvent(e,o);t.dispatchEvent(u);}}function kn(t){return t&&typeof t=="object"&&t.nodeType===1}function tr(t){if(!t)return document;if(kn(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 hn(t){if(kn(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=tr(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 xn(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=Pt(e.x,0,1),o=Pt(e.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function Cn(t){return {x:Pt(t.x,0,window.innerWidth),y:Pt(t.y,0,window.innerHeight)}}function er(){return useEffect(()=>(window.__cursorGuide=async(t,e={})=>{let n=Array.isArray(t)?t:[{target:t,action:e.action??"none",options:e}],r=[],o=await Xo();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),Le(o),bn();let u=parseFloat(o.style.left||"20")||20,f=parseFloat(o.style.top||"20")||20;De(o,u,f);for(let c of n){let{durationMs:x=800,easing:k="ease-in-out",offset:m,highlight:T=true,path:v="curve",curveStrength:C=.25,curveDirection:s="auto",anchor:p,cursorHotspot:a,dragTo:i}=c.options??{},l=c.action??c.options?.action??"none",g=performance.now(),d=hn(c.target),h=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 Vo(y,1500,180),Le(o),h=xn(y,p)):d.kind==="position"&&d.point&&(h=d.point),!h){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},w=Cn(yn(h,m));await se(o,b,w,x,k,v,C,s);let R=w.x-b.x,I=w.y-b.y,B=Math.hypot(R,I)||1,L=R/B,D=I/B,P=Math.min(6,Math.max(3,B*.02)),G={x:w.x+L*P,y:w.y+D*P};await se(o,w,G,Math.max(70,x*.1),"ease-out","straight",0,"right"),await se(o,G,w,120,"ease-out","straight",0,"left"),T&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let _=null;try{if(l==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let E={x:a?.x??0,y:a?.y??0},H={x:w.x+E.x,y:w.y+E.y};o.style.left=`${H.x}px`,o.style.top=`${H.y}px`,De(o,H.x,H.y);let A=y??document.elementFromPoint(H.x,H.y)??document.body;yt(A,"pointerdown",H),yt(A,"mousedown",H),await new Promise(M=>setTimeout(M,90)),o.classList.remove("pressing"),yt(A,"mouseup",H),yt(A,"click",H),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),A instanceof HTMLElement&&A.focus?.(),_=A?.id??null;}else if(l==="drag"){if(!i)throw new Error("dragTo is required for action 'drag'");let E=hn(i),H=null;if(E.kind==="element"&&E.element&&(H=xn(E.element,p)),E.kind==="position"&&E.point&&(H=E.point),!H)throw new Error("dragTo target not found");let A=Cn(yn(H,m)),M={x:w.x,y:w.y},j=y??document.elementFromPoint(M.x,M.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),yt(j,"pointerdown",M),yt(j,"mousedown",M),await se(o,M,A,Math.max(200,x),k,v,C,s,({x:tt,y:mt})=>{let nt=document.elementFromPoint(tt,mt)??document.body,lt={x:tt,y:mt};yt(nt,"pointermove",lt),yt(nt,"mousemove",lt);});let J=document.elementFromPoint(A.x,A.y)??document.body;o.classList.remove("pressing"),yt(J,"pointerup",A),yt(J,"mouseup",A);}r.push({ok:!0,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),clickedElementId:_});}catch(E){r.push({ok:false,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),error:E?.message??String(E)});}}return Go(o,2e3),{ok:r.every(c=>c.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var ce=er;function wn(){return {getDomComponents:{tool:async({includeHidden:t,selector:e})=>await jt({includeHidden:t,selector:e}),executeEachToken:false},controlCursor:{tool:async({target:t,action:e,anchor:n,durationMs:r,dragTo:o})=>{let u=await St(t,{action:e,anchor:n,durationMs:r,dragTo:o});if(u&&u.ok){let f=Array.isArray(u.steps)&&u.steps.length?u.steps[u.steps.length-1]:void 0,c=f?.clickedElementId?` (clicked element id: ${f.clickedElementId})`:"",x=e||f?.action||"none";return {success:true,message:x==="click"?`Cursor moved and clicked successfully${c}`:x==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:u}}return {success:false,message:"Cursor action failed",details:u}},executeEachToken:false},fillActiveInput:{tool:async({value:t})=>{let e=await Vt(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 qt({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 sr({input:t}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(qt,{content:t?.text||"",theme:"dark"})})}function In(){return {plainText:sr}}function Sn(t,e,n,r,o,u){let f=n.get(e);if(f){let d=f.parentElement,h=document.querySelector(`[data-get-from-user-host="${e}"]`);if(h&&d!==h){try{d?.removeChild(f);}catch{}h.innerHTML="",h.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",x=t?.description||"",k=t?.submitLabel||"Submit",m=t?.skipLabel||"Skip",T=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 C=document.createElement("form");C.style.margin="12px 0",C.style.padding="14px",C.style.border="1px solid var(--hsafa-border, #2A2C33)",C.style.borderRadius="12px",C.style.background="var(--hsafa-card, #121318)",C.style.color="var(--hsafa-text, #EDEEF0)",C.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,C.appendChild(s),x){let d=document.createElement("div");d.style.fontSize="12px",d.style.opacity="0.8",d.style.marginBottom="10px",d.textContent=x,C.appendChild(d);}T.forEach(d=>{let h=document.createElement("div");if(h.style.margin="10px 0",d.label){let I=document.createElement("label");I.style.display="block",I.style.fontSize="12px",I.style.marginBottom="6px",I.style.opacity="0.9",I.textContent=d.label,h.appendChild(I);}let y,b=(d.type||"text").toLowerCase();if(b==="textarea"){let I=document.createElement("textarea");I.placeholder=d.placeholder||"",I.value=d.value??"",I.style.width="100%",I.style.minHeight="72px",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",y=I;}else if(b==="select"&&Array.isArray(d.options)){let I=document.createElement("select");I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",d.options.forEach(B=>{let L=document.createElement("option");L.value=String(B.value),L.text=String(B.label??B.value),I.appendChild(L);}),I.value=d.value??"",y=I;}else if(b==="checkbox"){let I=document.createElement("input");I.type="checkbox",I.checked=!!d.value,I.style.transform="scale(1.1)",y=I;}else {let I=document.createElement("input");I.type=b,I.placeholder=d.placeholder||"",I.value=d.value??"",I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",y=I;}let w=d.id||"value";y.dataset.fieldId=w;let R=v.values&&Object.prototype.hasOwnProperty.call(v.values,w)?v.values[w]:void 0;typeof R<"u"&&(y.type==="checkbox"?y.checked=!!R:y.value=String(R)),(v.submitted||v.skipped)&&(y.setAttribute("disabled","true"),y.style.opacity="0.7"),h.appendChild(y),C.appendChild(h);});let p=String(k).trim(),a=String(m).trim(),i=!!(p||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=p||"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),C.appendChild(d);}if(C.onsubmit=d=>{d.preventDefault();let h={};C.querySelectorAll("[data-field-id]").forEach(y=>{let b=y.dataset.fieldId||"value";y.type==="checkbox"?h[b]=y.checked:h[b]=y.value??"";}),r.set(e,{submitted:true,skipped:false,values:h}),o({tool:"requestInput",toolCallId:e,output:{success:true,submitted:true,values:h}}),C.querySelectorAll("[data-field-id]").forEach(y=>{y.disabled=true,y.style.opacity="0.7";}),l&&(l.textContent=`${p||"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}}),C.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 h=document.createElement("span");h.style.display="inline-flex",h.style.alignItems="center",h.style.padding="2px 8px",h.style.borderRadius="999px",h.style.fontWeight="600",h.style.fontSize="11px",v.submitted?(h.style.background="rgba(16,185,129,0.15)",h.style.color="#10b981",h.textContent="Submitted"):(h.style.background="rgba(234,179,8,0.15)",h.style.color="#eab308",h.textContent="Skipped"),d.appendChild(h),C.appendChild(d);try{l&&(l.disabled=!0,l.style.opacity="0.8",v.submitted&&(l.textContent=`${p||"Submit"} \u2713`)),g&&(g.disabled=!0,g.style.opacity="0.8",v.skipped&&(g.textContent=`${a||"Skip"} \u2713`));}catch{}}f.appendChild(C);}function Mn(t){return !!t&&typeof t=="object"}function An(t,e,n){let r=useRef(new Map),o=useRef(new Map),u=useRef(new Map),f=useRef(e),c=useRef(n);f.current=e,c.current=n,useEffect(()=>{t.forEach(x=>{if(!Mn(x)||x.role!=="assistant")return;(Array.isArray(x.parts)?x.parts:[]).forEach(m=>{if(!Mn(m)||typeof m.toolCallId!="string"||!m.toolCallId)return;let T=typeof m.toolName=="string"?m.toolName:void 0,v=typeof m.type=="string"?m.type:"";if(!T&&v.startsWith("tool-")&&(T=v.replace(/^tool-/,"")),!T)return;let C=f.current[T];try{let s=String(m.state||m.status||""),p=o.current.get(m.toolCallId);if(s&&s!==p&&C&&typeof C=="object"){o.current.set(m.toolCallId,s);let a=m.input??m.args??{},i={toolCallId:m.toolCallId,toolName:T},l=C;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(C&&typeof C=="object"&&C.executeEachToken&&C.tool){let s=m.input??m.args??{},p=JSON.stringify(s),a=r.current.get(m.toolCallId);if(p!==a&&p!=="{}"){r.current.set(m.toolCallId,p);try{if(T==="requestInput")c.current(s,m.toolCallId);else {let l=(u.current.get(m.toolCallId)||0)+1;u.current.set(m.toolCallId,l),l>1&&C.tool({...s,toolCallNumber:l-1});}}catch{}}}});});},[t]);}function Be(t){let{agentId:e,baseUrl:n="",tools:r={},uiComponents:o={},onStart:u,onFinish:f,onError:c,initialMessages:x=[],onMessagesChange:k,controlledChatId:m,onChatIdChange:T,templateParams:v}=t,{baseUrl:C,setCurrentChatId:s}=et(),p=n&&n.length>0?n:C||"",[a,i]=useState(""),[l,g]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),d=m??l,h=useCallback(F=>{m===void 0&&g(F),T&&T(F);},[m,T]);useEffect(()=>{try{s(d);}catch{}return ()=>{try{s(void 0);}catch{}}},[d,s]);let y=useMemo(()=>dn(p,e,d,v),[p,e,d,v]),b=useCallback(F=>{console.log("Message finished:",F);let N=F?.message?.id;if(!N&&Array.isArray(F?.messages))for(let W=F.messages.length-1;W>=0;W--){let O=F.messages[W];if(O&&O.role==="assistant"&&O.id){N=O.id;break}}f?.({...F,chatId:d,assistantMessageId:N});},[f,d]),w=useCallback(F=>{console.error("Chat error:",F),c?.(F);},[c]),R=useMemo(()=>wn(),[]),I=useMemo(()=>({...R,...r}),[R,r]),B=useMemo(()=>In(),[]),L=useMemo(()=>({...B,...o}),[B,o]),D=useRef(new Map),P=useRef(new Map),G=useCallback(()=>{try{D.current.forEach(F=>{try{F.remove();}catch{}}),D.current.clear(),P.current.clear();}catch{}},[]),_=useCallback((F,N)=>{Sn(F,N,D.current,P.current,W=>E.current.addToolResult(W));},[]),E=useRef(null),H=useRef(new Set),A=useCallback((F,N,W)=>{console.error(`UI Error [${N}]:`,W),E.current&&H.current.has(F)&&(H.current.delete(F),E.current.addToolResult({tool:N,toolCallId:F,state:"output-error",errorText:W?.message||String(W)}));},[]),M=useCallback((F,N)=>{E.current&&H.current.has(F)&&(H.current.delete(F),E.current.addToolResult({tool:N,toolCallId:F,output:{status:"ok",rendered:true,component:N,logs:[]}}));},[]),j=useCallback(F=>{let N=I[F];return N?typeof N=="object"&&"tool"in N?N.tool:typeof N=="function"?N:null:null},[I]),J=useChat({transport:y,onFinish:b,onError:w,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:F}){let N=j(F.toolName);if(F.toolName==="requestInput"){try{_(F.input,F.toolCallId);}catch(rt){console.error("requestInput render error",rt);}return}let W=F.toolName==="ui",O=L&&F.toolName in L;if((W||O)&&!N){H.current.add(F.toolCallId);return}if(N)try{let rt=await N(F.input);J.addToolResult({tool:F.toolName,toolCallId:F.toolCallId,output:rt});}catch(rt){J.addToolResult({tool:F.toolName,toolCallId:F.toolCallId,state:"output-error",errorText:rt?.message||String(rt)});}}}),{messages:tt,sendMessage:mt,status:nt,stop:lt,error:K}=J;E.current=J,An(tt,I,_),useEffect(()=>{try{let F=new Set,N=[];if(tt.forEach(W=>{W.role==="assistant"&&(W.parts||[]).forEach(O=>{if((O?.toolName||(typeof O?.type=="string"&&O.type.startsWith("tool-")?String(O.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let rt=O?.toolCallId||"";if(!rt)return;F.add(rt);let ht=O?.output;if(ht&&(ht.submitted||ht.skipped||ht.values)){let we={submitted:!!ht.submitted,skipped:!!ht.skipped,values:ht.values||void 0};P.current.set(rt,we);}let Ot=O?.input||O?.args||{};N.push({input:Ot,toolCallId:rt});});}),D.current.forEach((W,O)=>{if(!F.has(O)){let ot=D.current.get(O);try{ot?.remove();}catch{}D.current.delete(O),P.current.delete(O);}}),N.length>0){let W=requestAnimationFrame(()=>{N.forEach(({input:O,toolCallId:ot})=>{try{_(O,ot);}catch{}});});return ()=>cancelAnimationFrame(W)}}catch{}},[tt,_]),useEffect(()=>{x&&x.length>0&&tt.length===0&&console.log("Initial messages:",x);},[x,tt.length]);let wt=nt==="submitted"||nt==="streaming",Qt=useCallback(()=>{k&&k(tt,d);},[k,tt,d]),te=useCallback(async F=>{let N=F?.text!==void 0?F.text:a,W=F?.files||[],O=N.trim();if(!(!O&&W.length===0)&&!wt){F?.text===void 0&&i("");try{if(u){let ot={role:"user",content:O,createdAt:Date.now(),chatId:d};u(ot);}await mt({text:O,files:W});}catch(ot){throw console.error("Failed to send message:",ot),ot}}},[a,wt,mt,u,d]),ke=useCallback(()=>{if(wt)return;G(),i("");try{J?.setMessages?.([]);}catch{}let F=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;h(F);},[wt,J,G,h]),ct=useCallback(F=>{try{J?.setMessages?.(F);}catch{}},[J]);return {input:a,setInput:i,messages:tt,isLoading:wt,status:nt,error:K,sendMessage:te,stop:lt,newChat:ke,setMessages:ct,notifyMessagesChange:Qt,chatApi:J,chatId:d,setChatId:h,tools:I,uiComponents:L,formHostRef:D,formStateRef:P,cleanupForms:G,onUISuccess:M,onUIError:A}}function Bt(t){let e=`hsafaChat_${t}`,n=`${e}.chats`,r=g=>`${e}.chat.${g}`,o=`${e}.currentChatId`,u=`${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{}},x=g=>{try{let d=localStorage.getItem(r(g));return d?JSON.parse(d):null}catch{return null}},k=g=>{try{localStorage.setItem(r(g.id),JSON.stringify(g));}catch{}},m=g=>{let d=f(),h=d.findIndex(y=>y.id===g.id);h>=0?d[h]=g:d.unshift(g),c(d);},T=g=>{let h=f().filter(y=>y.id!==g);c(h);},v=g=>{try{localStorage.removeItem(r(g));}catch{}};return {loadChatsIndex:f,saveChatsIndex:c,loadChat:x,saveChat:k,upsertChatMeta:m,deleteChatMeta:T,deleteChatData:v,deleteChat:g=>{v(g),T(g);},loadShowChatPreference:g=>{try{let d=localStorage.getItem(u);return d!==null?d==="true":g}catch{return g}},saveShowChatPreference:g=>{try{localStorage.setItem(u,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 $e(t){let{agentId:e,chatId:n,messages:r,isLoading:o=false,autoSave:u=true,autoRestore:f=true}=t,c=useMemo(()=>Bt(e),[e]),[x,k]=useState([]),[m,T]=useState(null),v=useRef(false),C=useRef(false),s=useCallback(()=>{try{let y=c.loadChatsIndex();k(y);let b=y.find(w=>w.id===n);T(b||null);}catch(y){console.error("Failed to refresh chat list:",y);}},[c,n]);useEffect(()=>{s();},[s]),useEffect(()=>{if(!(!f||C.current)){try{c.loadCurrentChatId()&&(v.current=!0);}catch(y){console.error("Failed to restore chat:",y);}C.current=true;}},[c,f]),useEffect(()=>{if(!(!u||r.length===0))if(v.current){if(!o){let y=Date.now();try{c.saveChat({id:n,messages:r,agentId:e});let w=c.loadChatsIndex().find(R=>R.id===n);w&&(c.upsertChatMeta({...w,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 I=y.parts.find(B=>B&&B.type==="text");b=I&&typeof I.text=="string"?I.text:"";}let w=(b||"New chat").slice(0,80),R=Date.now();try{c.upsertChatMeta({id:n,title:w,createdAt:R,updatedAt:R}),c.saveChat({id:n,messages:r,agentId:e}),c.saveCurrentChatId(n),v.current=!0,s();}catch(I){console.error("Failed to create chat:",I);}}}},[]);let p=useRef(false);useEffect(()=>{if(o){p.current=true;return}if(p.current&&u){p.current=false;try{let y=Date.now();c.saveChat({id:n,messages:r,agentId:e});let w=c.loadChatsIndex().find(R=>R.id===n);if(w)c.upsertChatMeta({...w,updatedAt:y});else {let R="",I=Array.isArray(r)?r.find(L=>L&&L.role==="user"):void 0;if(I&&Array.isArray(I.parts)){let L=I.parts.find(D=>D&&D.type==="text");R=L&&typeof L.text=="string"?L.text:"";}let B=(R||"New chat").slice(0,80);c.upsertChatMeta({id:n,title:B,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,u,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 w=c.loadChatsIndex().find(R=>R.id===n);w&&(c.upsertChatMeta({...w,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 w=c.loadChat(y),R=w&&Array.isArray(w.messages)?w.messages:[];b(R),s();}catch(w){console.error("Failed to switch chat:",w);}},[c,n,s]),d=useCallback(y=>{v.current=false,y();},[]),h=useCallback(y=>{if(!y.trim())return x;let b=y.toLowerCase();return x.filter(w=>w.title.toLowerCase().includes(b))},[x]);return {chatList:x,currentChatMeta:m,refreshChatList:s,loadChat:a,saveCurrentChat:i,deleteChat:l,switchToChat:g,createNewChat:d,searchChats:h,storage:c}}function ur(t){let{messages:e,isLoading:n,sendMessage:r,setMessages:o,baseUrl:u}=t,{baseUrl:f}=et(),c=u||f||"",[x,k]=useState(null),[m,T]=useState(""),[v,C]=useState([]),[s,p]=useState(false),a=useCallback((y,b,w=[])=>{k(y),T(b),C(w);},[]),i=useCallback(()=>{k(null),T(""),C([]);},[]),l=useCallback(async y=>{if(!n)try{let b=e.findIndex(R=>R.id===y);if(b===-1)return;let w=e.slice(0,b);o(w),await r({text:m.trim(),files:v.map(R=>({type:"file",url:R.url,mediaType:R.mimeType||"application/octet-stream",...R.name?{name:R.name}:{},...R.size?{size:R.size}:{}}))}),i();}catch(b){throw console.error("Failed to save edit:",b),b}},[n,e,r,m,v,o,i]),g=useCallback(y=>x===y,[x]),d=useCallback(async y=>{if(!c){console.warn("baseUrl not provided, cannot upload attachments");return}p(true);try{let b=Array.from(y).map(async R=>{if(R.size>26214400)throw new Error(`${R.name} is too large (max 25MB)`);let I=new FormData;I.append("file",R);let B=await fetch(`${c}/api/upload`,{method:"POST",body:I});if(!B.ok)throw new Error(`Upload failed: ${B.statusText}`);let L=await B.json();return {id:L.url||`${Date.now()}-${Math.random()}`,name:R.name,url:L.url,mimeType:R.type,size:R.size}}),w=await Promise.all(b);C(R=>[...R,...w]);}catch(b){throw console.error("Failed to upload files:",b),b}finally{p(false);}},[c]),h=useCallback(y=>{C(b=>b.filter(w=>w.id!==y));},[]);return {editingMessageId:x,editingText:m,setEditingText:T,editAttachments:v,setEditAttachments:C,editUploading:s,startEdit:a,cancelEdit:i,saveEdit:l,isEditing:g,addEditAttachments:d,removeEditAttachment:h}}function mr(t){if(!(typeof window>"u"))try{return Bt(t).loadCurrentChatId()||void 0}catch{return}}function Oe(t){let{agentId:e,prefer:n="context"}=t,{currentChatId:r}=et(),[o,u]=useState(void 0),[f,c]=useState(false);return useEffect(()=>{c(false);let x=mr(e);u(x),c(true);},[e]),useMemo(()=>{let x=r||void 0,k=n==="context"?x:o,m=n==="context"?"context":"storage";return k?{chatId:k,isReady:n==="storage"?f:true,source:m}:x?{chatId:x,isReady:true,source:"context"}:o?{chatId:o,isReady:f,source:"storage"}:{chatId:void 0,isReady:f,source:"none"}},[r,n,o,f])}function yr(t){let{agentId:e,chatId:n,initial:r,store:o,autoLoad:u=true,autoSave:f=true,saveDebounceMs:c=800}=t,x=Oe({agentId:e}),k=n??x.chatId,[m,T]=useState(r),[v,C]=useState("idle"),[s,p]=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);},[]),h=useCallback(async()=>{if(k)try{await o.saveLatest(k,m);}catch(w){p(w);}},[k,o,m]),y=useCallback(async()=>{d();let w=h();g.current=w,await w;},[d,h]),b=useCallback(async()=>{if(k){C("loading"),p(void 0);try{let w=u?await o.loadLatest(k):null;T(w??r),C("ready"),a.current=!0,i.current=k;}catch(w){p(w),C("error");}}},[u,r,k,o]);return useEffect(()=>{if(!x.isReady&&!n)return;if(!k){a.current=false,i.current=void 0,C("idle"),p(void 0),T(r),d();return}if(i.current===k&&a.current)return;a.current=false,i.current=k;let w=false;return (async()=>{C(u?"loading":"ready"),p(void 0);try{let R=u?await o.loadLatest(k):null;if(w)return;T(R??r),C("ready"),a.current=!0;}catch(R){if(w)return;p(R),C("error");}})(),()=>{w=true;}},[x.isReady,u,d,n,r,k,o]),useEffect(()=>{if(f&&k&&a.current&&!(typeof window>"u"))return d(),l.current=window.setTimeout(()=>{let w=h();g.current=w;},c),()=>{d();}},[f,d,h,k,c,m]),useMemo(()=>({value:m,setValue:T,status:v,error:s,reload:b,flushSave:y}),[s,y,b,v,m])}function Cr(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 br(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.chatId=="string"&&e.chatId.length>0)return e.chatId}function vr(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 Dn(t){if(!t||typeof t!="object")return "";let e=t;return typeof e.role=="string"?e.role:""}function Pn(t){if(!t||typeof t!="object")return "";let e=t,n=e.content??e.text;if(typeof n=="string")return n.slice(0,2e3);if(n==null)return "";try{return JSON.stringify(n).slice(0,2e3)}catch{return ""}}function kr(t){let{chatId:e,store:n,value:r,setValue:o,initial:u}=t,f=useRef(r);useEffect(()=>{f.current=r;},[r]);let c=useRef(void 0),x=useRef(null),k=useRef(0),m=useCallback(async v=>{let C=br(v)??e;if(!C)return;let s=Cr(v);s&&await n.saveVersion(C,s,f.current);},[e,n]),T=useCallback(async(v,C)=>{let s=C??e;if(c.current!==s){c.current=s,x.current=Array.isArray(v)?v:[];return}let p=x.current,a=Array.isArray(v)?v:[],i=Array.isArray(p)?p:[],l=Math.min(i.length,a.length),g=0;for(let L=0;L<l;L++){let D=i[L],P=a[L],G=D&&typeof D.id=="string"?D.id:"",_=P&&typeof P.id=="string"?P.id:"",E=D&&typeof D.role=="string"?D.role:"",H=P&&typeof P.role=="string"?P.role:"";if(G===_&&E===H){g++;continue}break}let d=i.length>0&&g===i.length&&a.length>=i.length,h=i.length>0?Dn(i[i.length-1]):"",y=a.length>0?Dn(a[a.length-1]):"",w=(h==="assistant"||y==="assistant")&&i.length>0&&a.length===i.length&&g===Math.max(0,i.length-1),R=i.length>0&&a.length<i.length,I=i.length>0&&!d&&!w&&g<i.length,B=false;for(let L=0;L<l;L++){let D=i[L],P=a[L],G=D&&typeof D.id=="string"?D.id:"",_=P&&typeof P.id=="string"?P.id:"",E=D&&typeof D.role=="string"?D.role:"",H=P&&typeof P.role=="string"?P.role:"";if(G!==_||E!==H)break;let A=Pn(D),M=Pn(P);if(A===M)continue;L===l-1&&E==="assistant"&&H==="assistant"||(B=true);break}if(!s){x.current=a;return}if(R||I||B){let L=++k.current,D=vr(a);for(let P of D)try{if(!await n.hasVersion(s,P))continue;let _=await n.loadVersion(s,P);if(k.current!==L)return;if(_){o(_),x.current=a;return}}catch{continue}if(k.current!==L)return;o(u);}x.current=a;},[e,u,o,n]);return useMemo(()=>({onFinish:m,onMessagesChange:T}),[m,T])}function wr(t){let{state:e,setState:n,tools:r}=t,o=At.useRef(e);o.current=e;let u=At.useCallback(()=>o.current,[]),f=At.useCallback(k=>{n(m=>{let T=typeof k=="function"?k(m):k;return o.current=T,T});},[n]),c=At.useRef(null),x=At.useRef(r);return x.current=r,c.current||(c.current=x.current({get:u,set:f})),c.current}function X({IconComponent:t,...e}){return At__default.createElement(t,e)}function ze({icon:t,onClick:e,ariaLabel:n,resolvedColors:r,disabled:o=false,title:u}){return jsx("button",{"aria-label":n,title:u,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 Nn({title:t,alwaysOpen:e,streaming:n,dir:r,resolvedColors:o,onNew:u,onToggleHistory:f,onClose:c,historyBtnRef:x,t:k}){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(ze,{icon:jsx(X,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||u();},ariaLabel:k("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:x,"aria-label":k("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(X,{IconComponent:History,size:"20",strokeWidth:"2"})}),!e&&jsx(ze,{icon:jsx(X,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:k("header.close"),resolvedColors:o})]})]})}var xe=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:u}=this.props;r&&o&&u&&u(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 Er=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"]},Hr=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}},Fr=t=>t.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase());function $n({parts:t,messageId:e,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:u,onUIError:f,onUISuccess:c,addToolResult:x}){let k=[],m=[],T,v,C=false;for(let s of Array.isArray(t)?t:[]){if(!s)continue;if(s.type==="reasoning"&&typeof s.text=="string"){m.push(s.text),T||(T=s.startDate),v=s.endDate,s.state==="done"&&(C=true);continue}if(s.type==="text"&&typeof s.text=="string"){m.length&&(k.push({type:"reasoning",texts:m,startDate:T,endDate:v,isCompleted:C}),m=[],T=void 0,v=void 0,C=false),k.push({type:"text",text:s.text,startDate:s.startDate,endDate:s.endDate});continue}let p=s.type==="dynamic-tool",a=typeof s.type=="string"&&s.type.startsWith("tool-");if(p||a||s.type==="tool-call"){m.length&&(k.push({type:"reasoning",texts:m,startDate:T,endDate:v,isCompleted:C}),m=[],T=void 0,v=void 0,C=false);let i=String(p?s.toolName||"dynamic-tool":a?s.type?.slice(5)||"tool":s.toolName||"tool");i==="requestInput"?k.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}):k.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&&k.push({type:"reasoning",texts:m,startDate:T,endDate:v,isCompleted:C}),k.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[k.map((s,p)=>{let a=`${e}-${p}`,i=n.has(a);if(s.type==="reasoning"){let b=s.isCompleted||typeof s.startDate=="number"&&typeof s.endDate=="number",w=s.texts&&s.texts.length>0&&s.texts.some(I=>I.trim().length>0),R=()=>{w&&r(a);};return b&&!w?null:jsx("div",{onClick:R,style:{cursor:w?"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"})]}),w&&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((I,B)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(qt,{content:I,theme:"dark",streaming:!b})},`rg-line-${p}-${B}`))}):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(qt,{content:s.text,theme:"dark",streaming:b})},a)}let{color:l,text:g}=Er(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 h=u?.[s.toolName||""];if(h)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(xe,{componentName:s.toolName||"Unknown",resolvedColors:o,toolCallId:s.toolCallId,toolName:s.toolName||"unknown",onError:f,onSuccess:c,children:jsx(h,{toolName:s.toolName||"",toolCallId:s.toolCallId||"",input:s.input,output:s.output,status:s.status,addToolResult:x})})},a);let y=Hr(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:Fr(y.toolName)})]})})},a)}),jsx("style",{children:`
11
+ `,document.head.appendChild(o);}hn=true;}return e?(e.classList.add("as-arrow"),qe||(qe=createRoot(e),qe.render(jsx(xn,{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),qe=createRoot(e),qe.render(jsx(xn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),e}function Be(t,e,n){return Math.max(e,Math.min(n,t))}function er(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}function In(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),[u,f,c,x=1]=o;return {r:u,g:f,b:c,a:x}}function tr({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 nr(t){let e=t?In(t):null;return !e||e.a===0?false:tr(e)<.5}function or(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=In(f);if(c&&c.a>0)return f;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Bt(t,e,n){let r=or(e,n),o=nr(r),u=o?"#ffffff":"#000000";t.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=u,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 lt(t,e,n,r,o="ease-in-out",u="curve",f=.25,c="auto",x){wn(),Pt(t);let k=performance.now(),m=o==="linear"?C=>C:er,I=u!=="straight",b={x:0,y:0};if(I){let C=n.x-e.x,a=n.y-e.y,p=Math.hypot(C,a)||1,s=(e.x+n.x)/2,i=(e.y+n.y)/2,l=-a/p,g=C/p,d=1;c==="left"?d=-1:c==="right"?d=1:d=Math.random()<.5?-1:1;let h=Be(f,0,1)*p;b={x:s+d*l*h,y:i+d*g*h};}return new Promise(C=>{function a(p){let s=Be((p-k)/r,0,1),i=m(s),l,g;if(I){let w=1-i;l=w*w*e.x+2*w*i*b.x+i*i*n.x,g=w*w*e.y+2*w*i*b.y+i*i*n.y;}else l=e.x+(n.x-e.x)*i,g=e.y+(n.y-e.y)*i;let h=.35*(1-i),y=Math.sin(p*.02)*h,v=Math.cos(p*.018)*h;t.style.left=`${l+y}px`,t.style.top=`${g+v}px`,Bt(t,l+y,g+v),x&&x({x:l+y,y:g+v,t:s,now:p}),s<1?requestAnimationFrame(a):C();}requestAnimationFrame(a);})}function Cn(t,e){return {x:t.x+(e?.x??0),y:t.y+(e?.y??0)}}function he(t,e,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let u=e==="pointerdown"||e==="mousedown",f=e==="pointerup"||e==="mouseup",c={button:0,buttons:u?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let x=new PointerEvent(e,{pointerId:1,pointerType:"mouse",...c});t.dispatchEvent(x);}else {let x=new MouseEvent(e,c);t.dispatchEvent(x);}}catch{let u=new MouseEvent(e,o);t.dispatchEvent(u);}}function Tn(t){return t&&typeof t=="object"&&t.nodeType===1}function rr(t){if(!t)return document;if(Tn(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 bn(t){if(Tn(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=rr(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 vn(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=Be(e.x,0,1),o=Be(e.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function kn(t){return {x:Be(t.x,0,window.innerWidth),y:Be(t.y,0,window.innerHeight)}}function sr(){return useEffect(()=>(window.__cursorGuide=async(t,e={})=>{let n=Array.isArray(t)?t:[{target:t,action:e.action??"none",options:e}],r=[],o=await Qo();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),Pt(o),wn();let u=parseFloat(o.style.left||"20")||20,f=parseFloat(o.style.top||"20")||20;Bt(o,u,f);for(let c of n){let{durationMs:x=800,easing:k="ease-in-out",offset:m,highlight:I=true,path:b="curve",curveStrength:C=.25,curveDirection:a="auto",anchor:p,cursorHotspot:s,dragTo:i}=c.options??{},l=c.action??c.options?.action??"none",g=performance.now(),d=bn(c.target),h=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 Xo(y,1500,180),Pt(o),h=vn(y,p)):d.kind==="position"&&d.point&&(h=d.point),!h){r.push({ok:false,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),error:"Target not found"});continue}let v={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},w=kn(Cn(h,m));await lt(o,v,w,x,k,b,C,a);let E=w.x-v.x,T=w.y-v.y,N=Math.hypot(E,T)||1,$=E/N,L=T/N,P=Math.min(6,Math.max(3,N*.02)),D={x:w.x+$*P,y:w.y+L*P};await lt(o,w,D,Math.max(70,x*.1),"ease-out","straight",0,"right"),await lt(o,D,w,120,"ease-out","straight",0,"left"),I&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let V=null;try{if(l==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let R={x:s?.x??0,y:s?.y??0},F={x:w.x+R.x,y:w.y+R.y};o.style.left=`${F.x}px`,o.style.top=`${F.y}px`,Bt(o,F.x,F.y);let A=y??document.elementFromPoint(F.x,F.y)??document.body;he(A,"pointerdown",F),he(A,"mousedown",F),await new Promise(M=>setTimeout(M,90)),o.classList.remove("pressing"),he(A,"mouseup",F),he(A,"click",F),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),A instanceof HTMLElement&&A.focus?.(),V=A?.id??null;}else if(l==="drag"){if(!i)throw new Error("dragTo is required for action 'drag'");let R=bn(i),F=null;if(R.kind==="element"&&R.element&&(F=vn(R.element,p)),R.kind==="position"&&R.point&&(F=R.point),!F)throw new Error("dragTo target not found");let A=kn(Cn(F,m)),M={x:w.x,y:w.y},j=y??document.elementFromPoint(M.x,M.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),he(j,"pointerdown",M),he(j,"mousedown",M),await lt(o,M,A,Math.max(200,x),k,b,C,a,({x:Q,y:me})=>{let oe=document.elementFromPoint(Q,me)??document.body,ae={x:Q,y:me};he(oe,"pointermove",ae),he(oe,"mousemove",ae);});let Y=document.elementFromPoint(A.x,A.y)??document.body;o.classList.remove("pressing"),he(Y,"pointerup",A),he(Y,"mouseup",A);}r.push({ok:!0,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),clickedElementId:V});}catch(R){r.push({ok:false,action:l,targetKind:d.kind,durationMs:Math.round(performance.now()-g),error:R?.message??String(R)});}}return qo(o,2e3),{ok:r.every(c=>c.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var ut=sr;function Sn(){return {getDomComponents:{tool:async({includeHidden:t,selector:e})=>await je({includeHidden:t,selector:e}),executeEachToken:false},controlCursor:{tool:async({target:t,action:e,anchor:n,durationMs:r,dragTo:o})=>{let u=await Se(t,{action:e,anchor:n,durationMs:r,dragTo:o});if(u&&u.ok){let f=Array.isArray(u.steps)&&u.steps.length?u.steps[u.steps.length-1]:void 0,c=f?.clickedElementId?` (clicked element id: ${f.clickedElementId})`:"",x=e||f?.action||"none";return {success:true,message:x==="click"?`Cursor moved and clicked successfully${c}`:x==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:u}}return {success:false,message:"Cursor action failed",details:u}},executeEachToken:false},fillActiveInput:{tool:async({value:t})=>{let e=await Ve(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 Ke({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 dr({input:t}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(Ke,{content:t?.text||"",theme:"dark"})})}function An(){return {plainText:dr}}function Rn(t,e,n,r,o,u){let f=n.get(e);if(f){let d=f.parentElement,h=document.querySelector(`[data-get-from-user-host="${e}"]`);if(h&&d!==h){try{d?.removeChild(f);}catch{}h.innerHTML="",h.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",x=t?.description||"",k=t?.submitLabel||"Submit",m=t?.skipLabel||"Skip",I=Array.isArray(t?.fields)?t.fields:t?.label||t?.placeholder?[{id:"value",label:t?.label||"Value",type:"text",placeholder:t?.placeholder||""}]:[],b=r.get(e)||{submitted:false,skipped:false,values:void 0};f.innerHTML="";let C=document.createElement("form");C.style.margin="12px 0",C.style.padding="14px",C.style.border="1px solid var(--hsafa-border, #2A2C33)",C.style.borderRadius="12px",C.style.background="var(--hsafa-card, #121318)",C.style.color="var(--hsafa-text, #EDEEF0)",C.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=c,C.appendChild(a),x){let d=document.createElement("div");d.style.fontSize="12px",d.style.opacity="0.8",d.style.marginBottom="10px",d.textContent=x,C.appendChild(d);}I.forEach(d=>{let h=document.createElement("div");if(h.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,h.appendChild(T);}let y,v=(d.type||"text").toLowerCase();if(v==="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(v==="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(N=>{let $=document.createElement("option");$.value=String(N.value),$.text=String(N.label??N.value),T.appendChild($);}),T.value=d.value??"",y=T;}else if(v==="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=v,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 w=d.id||"value";y.dataset.fieldId=w;let E=b.values&&Object.prototype.hasOwnProperty.call(b.values,w)?b.values[w]:void 0;typeof E<"u"&&(y.type==="checkbox"?y.checked=!!E:y.value=String(E)),(b.submitted||b.skipped)&&(y.setAttribute("disabled","true"),y.style.opacity="0.7"),h.appendChild(y),C.appendChild(h);});let p=String(k).trim(),s=String(m).trim(),i=!!(p||s),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=p||"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=s||"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),C.appendChild(d);}if(C.onsubmit=d=>{d.preventDefault();let h={};C.querySelectorAll("[data-field-id]").forEach(y=>{let v=y.dataset.fieldId||"value";y.type==="checkbox"?h[v]=y.checked:h[v]=y.value??"";}),r.set(e,{submitted:true,skipped:false,values:h}),o({tool:"requestInput",toolCallId:e,output:{success:true,submitted:true,values:h}}),C.querySelectorAll("[data-field-id]").forEach(y=>{y.disabled=true,y.style.opacity="0.7";}),l&&(l.textContent=`${p||"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}}),C.querySelectorAll("[data-field-id]").forEach(d=>{d.disabled=true,d.style.opacity="0.7";}),g&&(g.textContent=`${s||"Skip"} \u2713`,g.style.opacity="0.8",g.disabled=true),l&&(l.disabled=true);}),b.submitted||b.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 h=document.createElement("span");h.style.display="inline-flex",h.style.alignItems="center",h.style.padding="2px 8px",h.style.borderRadius="999px",h.style.fontWeight="600",h.style.fontSize="11px",b.submitted?(h.style.background="rgba(16,185,129,0.15)",h.style.color="#10b981",h.textContent="Submitted"):(h.style.background="rgba(234,179,8,0.15)",h.style.color="#eab308",h.textContent="Skipped"),d.appendChild(h),C.appendChild(d);try{l&&(l.disabled=!0,l.style.opacity="0.8",b.submitted&&(l.textContent=`${p||"Submit"} \u2713`)),g&&(g.disabled=!0,g.style.opacity="0.8",b.skipped&&(g.textContent=`${s||"Skip"} \u2713`));}catch{}}f.appendChild(C);}function En(t){return !!t&&typeof t=="object"}function Hn(t,e,n){let r=useRef(new Map),o=useRef(new Map),u=useRef(new Map),f=useRef(e),c=useRef(n);f.current=e,c.current=n,useEffect(()=>{t.forEach(x=>{if(!En(x)||x.role!=="assistant")return;(Array.isArray(x.parts)?x.parts:[]).forEach(m=>{if(!En(m)||typeof m.toolCallId!="string"||!m.toolCallId)return;let I=typeof m.toolName=="string"?m.toolName:void 0,b=typeof m.type=="string"?m.type:"";if(!I&&b.startsWith("tool-")&&(I=b.replace(/^tool-/,"")),!I)return;let C=f.current[I];try{let a=String(m.state||m.status||""),p=o.current.get(m.toolCallId);if(a&&a!==p&&C&&typeof C=="object"){o.current.set(m.toolCallId,a);let s=m.input??m.args??{},i={toolCallId:m.toolCallId,toolName:I},l=C;a==="input-streaming"&&typeof l.inputting_start=="function"&&l.inputting_start(s,i),a==="input-available"&&typeof l.running_start=="function"&&l.running_start(s,i);}}catch{}if(C&&typeof C=="object"&&C.executeEachToken&&C.tool){let a=m.input??m.args??{},p=JSON.stringify(a),s=r.current.get(m.toolCallId);if(p!==s&&p!=="{}"){r.current.set(m.toolCallId,p);try{if(I==="requestInput")c.current(a,m.toolCallId);else {let l=(u.current.get(m.toolCallId)||0)+1;u.current.set(m.toolCallId,l),l>1&&C.tool({...a,toolCallNumber:l-1});}}catch{}}}});});},[t]);}function Ln(t){if(!t||typeof t!="object")return {};let e=t,n=typeof e.id=="string"?e.id:void 0,r=typeof e.role=="string"?e.role:void 0;return {id:n,role:r}}function $t(t){let{agentId:e,baseUrl:n="",tools:r={},uiComponents:o={},onStart:u,onFinish:f,onError:c,initialMessages:x=[],onMessagesChange:k,controlledChatId:m,onChatIdChange:I,templateParams:b}=t,{baseUrl:C,setCurrentChatId:a}=se(),p=n&&n.length>0?n:C||"",[s,i]=useState(""),[l,g]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),d=m??l,h=useCallback(H=>{m===void 0&&g(H),I&&I(H);},[m,I]);useEffect(()=>{try{a(d);}catch{}return ()=>{try{a(void 0);}catch{}}},[d,a]);let y=useMemo(()=>fn(p,e,d,b),[p,e,d,b]),v=useCallback(H=>{console.log("Message finished:",H);let B=H?.message?.id;if(!B&&Array.isArray(H?.messages))for(let U=H.messages.length-1;U>=0;U--){let O=H.messages[U];if(O&&O.role==="assistant"&&O.id){B=O.id;break}}f?.({...H,chatId:d,assistantMessageId:B});},[f,d]),w=useCallback(H=>{console.error("Chat error:",H),c?.(H);},[c]),E=useMemo(()=>Sn(),[]),T=useMemo(()=>({...E,...r}),[E,r]),N=useMemo(()=>An(),[]),$=useMemo(()=>({...N,...o}),[N,o]),L=useRef(new Map),P=useRef(new Map),D=useCallback(()=>{try{L.current.forEach(H=>{try{H.remove();}catch{}}),L.current.clear(),P.current.clear();}catch{}},[]),V=useCallback((H,B)=>{Rn(H,B,L.current,P.current,U=>R.current.addToolResult(U));},[]),R=useRef(null),F=useRef(new Set),A=useCallback((H,B,U)=>{console.error(`UI Error [${B}]:`,U),R.current&&F.current.has(H)&&(F.current.delete(H),R.current.addToolResult({tool:B,toolCallId:H,state:"output-error",errorText:U?.message||String(U)}));},[]),M=useCallback((H,B)=>{R.current&&F.current.has(H)&&(F.current.delete(H),R.current.addToolResult({tool:B,toolCallId:H,output:{status:"ok",rendered:true,component:B,logs:[]}}));},[]),j=useCallback(H=>{let B=T[H];return B?typeof B=="object"&&"tool"in B?B.tool:typeof B=="function"?B:null:null},[T]),Y=useChat({transport:y,onFinish:v,onError:w,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:H}){let B=j(H.toolName);if(H.toolName==="requestInput"){try{V(H.input,H.toolCallId);}catch(ee){console.error("requestInput render error",ee);}return}let U=H.toolName==="ui",O=$&&H.toolName in $;if((U||O)&&!B){F.current.add(H.toolCallId);return}if(B)try{let ee=await B(H.input);Y.addToolResult({tool:H.toolName,toolCallId:H.toolCallId,output:ee});}catch(ee){Y.addToolResult({tool:H.toolName,toolCallId:H.toolCallId,state:"output-error",errorText:ee?.message||String(ee)});}}}),{messages:Q,sendMessage:me,status:oe,stop:ae,error:X}=Y;R.current=Y,Hn(Q,T,V),useEffect(()=>{try{let H=new Set,B=[];if(Q.forEach(U=>{U.role==="assistant"&&(U.parts||[]).forEach(O=>{if((O?.toolName||(typeof O?.type=="string"&&O.type.startsWith("tool-")?String(O.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let ee=O?.toolCallId||"";if(!ee)return;H.add(ee);let de=O?.output;if(de&&(de.submitted||de.skipped||de.values)){let Tt={submitted:!!de.submitted,skipped:!!de.skipped,values:de.values||void 0};P.current.set(ee,Tt);}let Oe=O?.input||O?.args||{};B.push({input:Oe,toolCallId:ee});});}),L.current.forEach((U,O)=>{if(!H.has(O)){let re=L.current.get(O);try{re?.remove();}catch{}L.current.delete(O),P.current.delete(O);}}),B.length>0){let U=requestAnimationFrame(()=>{B.forEach(({input:O,toolCallId:re})=>{try{V(O,re);}catch{}});});return ()=>cancelAnimationFrame(U)}}catch{}},[Q,V]),useEffect(()=>{x&&x.length>0&&Q.length===0&&console.log("Initial messages:",x);},[x,Q.length]);let we=oe==="submitted"||oe==="streaming",et=useCallback((H,B)=>{if(k){let U=H??Q,O=B??d;if(!!globalThis.__HSAFA_DEBUG__){let ee=U.length>0?U[U.length-1]:void 0,de=Ln(ee);console.log("[hsafa-agent] notifyMessagesChange",{chatId:O,messagesOverrideUsed:H!==void 0,messagesLen:U.length,lastMessageId:de.id,lastMessageRole:de.role});}k(U,O);}},[k,Q,d]),tt=useCallback(async H=>{let B=H?.text!==void 0?H.text:s,U=H?.files||[],O=B.trim();if(!(!O&&U.length===0)&&!we){H?.text===void 0&&i("");try{if(u){let re={role:"user",content:O,createdAt:Date.now(),chatId:d};u(re);}await me({text:O,files:U});}catch(re){throw console.error("Failed to send message:",re),re}}},[s,we,me,u,d]),It=useCallback(()=>{if(we)return;D(),i("");try{Y?.setMessages?.([]);}catch{}let H=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;h(H);},[we,Y,D,h]),ce=useCallback(H=>{try{Y?.setMessages?.(H);}catch{}if(k){if(!!globalThis.__HSAFA_DEBUG__){let U=H.length>0?H[H.length-1]:void 0,O=Ln(U);console.log("[hsafa-agent] setMessages:emitOnMessagesChange",{chatId:d,messagesLen:H.length,lastMessageId:O.id,lastMessageRole:O.role});}k(H,d);}},[Y,k,d]);return {input:s,setInput:i,messages:Q,isLoading:we,status:oe,error:X,sendMessage:tt,stop:ae,newChat:It,setMessages:ce,notifyMessagesChange:et,chatApi:Y,chatId:d,setChatId:h,tools:T,uiComponents:$,formHostRef:L,formStateRef:P,cleanupForms:D,onUISuccess:M,onUIError:A}}function Ne(t){let e=`hsafaChat_${t}`,n=`${e}.chats`,r=g=>`${e}.chat.${g}`,o=`${e}.currentChatId`,u=`${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{}},x=g=>{try{let d=localStorage.getItem(r(g));return d?JSON.parse(d):null}catch{return null}},k=g=>{try{localStorage.setItem(r(g.id),JSON.stringify(g));}catch{}},m=g=>{let d=f(),h=d.findIndex(y=>y.id===g.id);h>=0?d[h]=g:d.unshift(g),c(d);},I=g=>{let h=f().filter(y=>y.id!==g);c(h);},b=g=>{try{localStorage.removeItem(r(g));}catch{}};return {loadChatsIndex:f,saveChatsIndex:c,loadChat:x,saveChat:k,upsertChatMeta:m,deleteChatMeta:I,deleteChatData:b,deleteChat:g=>{b(g),I(g);},loadShowChatPreference:g=>{try{let d=localStorage.getItem(u);return d!==null?d==="true":g}catch{return g}},saveShowChatPreference:g=>{try{localStorage.setItem(u,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 Ot(t){let{agentId:e,chatId:n,messages:r,isLoading:o=false,autoSave:u=true,autoRestore:f=true}=t,c=useMemo(()=>Ne(e),[e]),[x,k]=useState([]),[m,I]=useState(null),b=useRef(false),C=useRef(false),a=useCallback(()=>{try{let y=c.loadChatsIndex();k(y);let v=y.find(w=>w.id===n);I(v||null);}catch(y){console.error("Failed to refresh chat list:",y);}},[c,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!f||C.current)){try{c.loadCurrentChatId()&&(b.current=!0);}catch(y){console.error("Failed to restore chat:",y);}C.current=true;}},[c,f]),useEffect(()=>{if(!(!u||r.length===0))if(b.current){if(!o){let y=Date.now();try{c.saveChat({id:n,messages:r,agentId:e});let w=c.loadChatsIndex().find(E=>E.id===n);w&&(c.upsertChatMeta({...w,updatedAt:y}),a());}catch(v){console.error("Failed to save chat:",v);}}}else {let y=r.find(v=>v.role==="user");if(y){let v="";if(Array.isArray(y.parts)){let T=y.parts.find(N=>N&&N.type==="text");v=T&&typeof T.text=="string"?T.text:"";}let w=(v||"New chat").slice(0,80),E=Date.now();try{c.upsertChatMeta({id:n,title:w,createdAt:E,updatedAt:E}),c.saveChat({id:n,messages:r,agentId:e}),c.saveCurrentChatId(n),b.current=!0,a();}catch(T){console.error("Failed to create chat:",T);}}}},[]);let p=useRef(false);useEffect(()=>{if(o){p.current=true;return}if(p.current&&u){p.current=false;try{let y=Date.now();c.saveChat({id:n,messages:r,agentId:e});let w=c.loadChatsIndex().find(E=>E.id===n);if(w)c.upsertChatMeta({...w,updatedAt:y});else {let E="",T=Array.isArray(r)?r.find($=>$&&$.role==="user"):void 0;if(T&&Array.isArray(T.parts)){let $=T.parts.find(L=>L&&L.type==="text");E=$&&typeof $.text=="string"?$.text:"";}let N=(E||"New chat").slice(0,80);c.upsertChatMeta({id:n,title:N,createdAt:y,updatedAt:y});try{c.saveCurrentChatId(n);}catch{}b.current=!0;}a();}catch(y){console.error("Failed to save chat on completion:",y);}}},[o,r,n,e,c,u,a]);let s=useCallback(y=>{try{let v=c.loadChat(y);return v?{id:v.id,messages:v.messages,agentId:v.agentId||e}:null}catch(v){return console.error("Failed to load chat:",v),null}},[c,e]),i=useCallback(()=>{if(r.length!==0)try{let y=Date.now();c.saveChat({id:n,messages:r,agentId:e});let w=c.loadChatsIndex().find(E=>E.id===n);w&&(c.upsertChatMeta({...w,updatedAt:y}),a());}catch(y){console.error("Failed to save chat:",y);}},[c,n,r,e,a]),l=useCallback(y=>{try{c.deleteChat(y),a();}catch(v){console.error("Failed to delete chat:",v);}},[c,a]),g=useCallback((y,v)=>{if(y!==n)try{b.current=!0,c.saveCurrentChatId(y);let w=c.loadChat(y),E=w&&Array.isArray(w.messages)?w.messages:[];v(E),a();}catch(w){console.error("Failed to switch chat:",w);}},[c,n,a]),d=useCallback(y=>{b.current=false,y();},[]),h=useCallback(y=>{if(!y.trim())return x;let v=y.toLowerCase();return x.filter(w=>w.title.toLowerCase().includes(v))},[x]);return {chatList:x,currentChatMeta:m,refreshChatList:a,loadChat:s,saveCurrentChat:i,deleteChat:l,switchToChat:g,createNewChat:d,searchChats:h,storage:c}}function mr(t){let{messages:e,isLoading:n,sendMessage:r,setMessages:o,baseUrl:u}=t,{baseUrl:f}=se(),c=u||f||"",[x,k]=useState(null),[m,I]=useState(""),[b,C]=useState([]),[a,p]=useState(false),s=useCallback((y,v,w=[])=>{k(y),I(v),C(w);},[]),i=useCallback(()=>{k(null),I(""),C([]);},[]),l=useCallback(async y=>{if(!n)try{let v=e.findIndex(E=>E.id===y);if(v===-1)return;let w=e.slice(0,v);o(w),await r({text:m.trim(),files:b.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(v){throw console.error("Failed to save edit:",v),v}},[n,e,r,m,b,o,i]),g=useCallback(y=>x===y,[x]),d=useCallback(async y=>{if(!c){console.warn("baseUrl not provided, cannot upload attachments");return}p(true);try{let v=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 N=await fetch(`${c}/api/upload`,{method:"POST",body:T});if(!N.ok)throw new Error(`Upload failed: ${N.statusText}`);let $=await N.json();return {id:$.url||`${Date.now()}-${Math.random()}`,name:E.name,url:$.url,mimeType:E.type,size:E.size}}),w=await Promise.all(v);C(E=>[...E,...w]);}catch(v){throw console.error("Failed to upload files:",v),v}finally{p(false);}},[c]),h=useCallback(y=>{C(v=>v.filter(w=>w.id!==y));},[]);return {editingMessageId:x,editingText:m,setEditingText:I,editAttachments:b,setEditAttachments:C,editUploading:a,startEdit:s,cancelEdit:i,saveEdit:l,isEditing:g,addEditAttachments:d,removeEditAttachment:h}}function xr(t){if(!(typeof window>"u"))try{return Ne(t).loadCurrentChatId()||void 0}catch{return}}function zt(t){let{agentId:e,prefer:n="context"}=t,{currentChatId:r}=se(),[o,u]=useState(void 0),[f,c]=useState(false);return useEffect(()=>{c(false);let x=xr(e);u(x),c(true);},[e]),useMemo(()=>{let x=r||void 0,k=n==="context"?x:o,m=n==="context"?"context":"storage";return k?{chatId:k,isReady:n==="storage"?f:true,source:m}:x?{chatId:x,isReady:true,source:"context"}:o?{chatId:o,isReady:f,source:"storage"}:{chatId:void 0,isReady:f,source:"none"}},[r,n,o,f])}function br(t){let{agentId:e,chatId:n,initial:r,store:o,autoLoad:u=true,autoSave:f=true,saveDebounceMs:c=800}=t,x=zt({agentId:e}),k=n??x.chatId,[m,I]=useState(r),[b,C]=useState("idle"),[a,p]=useState(void 0),s=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);},[]),h=useCallback(async()=>{if(k)try{await o.saveLatest(k,m);}catch(w){p(w);}},[k,o,m]),y=useCallback(async()=>{d();let w=h();g.current=w,await w;},[d,h]),v=useCallback(async()=>{if(k){C("loading"),p(void 0);try{let w=u?await o.loadLatest(k):null;I(w??r),C("ready"),s.current=!0,i.current=k;}catch(w){p(w),C("error");}}},[u,r,k,o]);return useEffect(()=>{if(!x.isReady&&!n)return;if(!k){s.current=false,i.current=void 0,C("idle"),p(void 0),I(r),d();return}if(i.current===k&&s.current)return;s.current=false,i.current=k;let w=false;return (async()=>{C(u?"loading":"ready"),p(void 0);try{let E=u?await o.loadLatest(k):null;if(w)return;I(E??r),C("ready"),s.current=!0;}catch(E){if(w)return;p(E),C("error");}})(),()=>{w=true;}},[x.isReady,u,d,n,r,k,o]),useEffect(()=>{if(f&&k&&s.current&&!(typeof window>"u"))return d(),l.current=window.setTimeout(()=>{let w=h();g.current=w;},c),()=>{d();}},[f,d,h,k,c,m]),useMemo(()=>({value:m,setValue:I,status:b,error:a,reload:v,flushSave:y}),[a,y,v,b,m])}function _t(){return !!globalThis.__HSAFA_DEBUG__}function $n(t){if(!t||typeof t!="object")return {};let e=t,n=typeof e.id=="string"?e.id:void 0,r=typeof e.role=="string"?e.role:void 0;return {id:n,role:r}}function wr(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 Ir(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.chatId=="string"&&e.chatId.length>0)return e.chatId}function Tr(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 Un(t){if(!t||typeof t!="object")return "";let e=t;return typeof e.role=="string"?e.role:""}function On(t){if(!t||typeof t!="object")return "";let e=t,n=e.content??e.text;if(typeof n=="string")return n.slice(0,2e3);if(n==null)return "";try{return JSON.stringify(n).slice(0,2e3)}catch{return ""}}function Sr(t){let{chatId:e,store:n,value:r,setValue:o,initial:u}=t,f=useRef(r);useEffect(()=>{f.current=r;},[r]);let c=useRef(void 0),x=useRef(null),k=useRef(0),m=useCallback(async b=>{let C=Ir(b)??e;if(!C)return;let a=wr(b);a&&(_t()&&console.log("[hsafa-versioning] onFinish:saveVersion",{chatId:C,assistantMessageId:a}),await n.saveVersion(C,a,f.current));},[e,n]),I=useCallback(async(b,C)=>{let a=C??e;if(c.current!==a){_t()&&console.log("[hsafa-versioning] messagesChange:chatIdChanged",{prevChatId:c.current,nextChatId:a,nextMessagesLen:Array.isArray(b)?b.length:0}),c.current=a,x.current=Array.isArray(b)?b:[];return}let p=x.current,s=Array.isArray(b)?b:[],i=Array.isArray(p)?p:[],l=Math.min(i.length,s.length),g=0;for(let L=0;L<l;L++){let P=i[L],D=s[L],V=P&&typeof P.id=="string"?P.id:"",R=D&&typeof D.id=="string"?D.id:"",F=P&&typeof P.role=="string"?P.role:"",A=D&&typeof D.role=="string"?D.role:"";if(V===R&&F===A){g++;continue}break}let d=i.length>0&&g===i.length&&s.length>=i.length,h=i.length>0?Un(i[i.length-1]):"",y=s.length>0?Un(s[s.length-1]):"",w=(h==="assistant"||y==="assistant")&&i.length>0&&s.length===i.length&&g===Math.max(0,i.length-1),E=i.length>0&&s.length<i.length,T=i.length>0&&!d&&!w&&g<i.length,N=false;for(let L=0;L<l;L++){let P=i[L],D=s[L],V=P&&typeof P.id=="string"?P.id:"",R=D&&typeof D.id=="string"?D.id:"",F=P&&typeof P.role=="string"?P.role:"",A=D&&typeof D.role=="string"?D.role:"";if(V!==R||F!==A)break;let M=On(P),j=On(D);if(M===j)continue;L===l-1&&F==="assistant"&&A==="assistant"||(N=true);break}if(!a){x.current=s;return}let $=_t();if($){let L=i.length>0?i[i.length-1]:void 0,P=s.length>0?s[s.length-1]:void 0,D=$n(L),V=$n(P);console.log("[hsafa-versioning] messagesChange:evaluate",{chatId:a,prevLen:i.length,nextLen:s.length,commonPrefixLen:g,isAppend:d,isTailRewriteOnly:w,wasTruncated:E,wasRewritten:T,wasContentEdited:N,lastPrevId:D.id,lastPrevRole:D.role,lastNextId:V.id,lastNextRole:V.role});}if(E||T||N){let L=++k.current,P=Tr(s);$&&console.log("[hsafa-versioning] restore:start",{chatId:a,restoreSeq:L,assistantIds:P.slice(0,20)});for(let D of P)try{if(!await n.hasVersion(a,D))continue;let R=await n.loadVersion(a,D);if(k.current!==L)return;if(R){$&&console.log("[hsafa-versioning] restore:success",{chatId:a,restoreSeq:L,assistantMessageId:D}),o(R),x.current=s;return}}catch{continue}if(k.current!==L)return;$&&console.log("[hsafa-versioning] restore:fallbackInitial",{chatId:a,restoreSeq:L}),o(u);}x.current=s;},[e,u,o,n]);return useMemo(()=>({onFinish:m,onMessagesChange:I}),[m,I])}function Mr(t){let{state:e,setState:n,tools:r}=t,o=Ae.useRef(e);o.current=e;let u=Ae.useCallback(()=>o.current,[]),f=Ae.useCallback(k=>{n(m=>{let I=typeof k=="function"?k(m):k;return o.current=I,I});},[n]),c=Ae.useRef(null),x=Ae.useRef(r);return x.current=r,c.current||(c.current=x.current({get:u,set:f})),c.current}function J({IconComponent:t,...e}){return Ae__default.createElement(t,e)}function Gt({icon:t,onClick:e,ariaLabel:n,resolvedColors:r,disabled:o=false,title:u}){return jsx("button",{"aria-label":n,title:u,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 Wn({title:t,alwaysOpen:e,streaming:n,dir:r,resolvedColors:o,onNew:u,onToggleHistory:f,onClose:c,historyBtnRef:x,t:k}){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(Gt,{icon:jsx(J,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||u();},ariaLabel:k("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:x,"aria-label":k("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(J,{IconComponent:History,size:"20",strokeWidth:"2"})}),!e&&jsx(Gt,{icon:jsx(J,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:k("header.close"),resolvedColors:o})]})]})}var bt=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:u}=this.props;r&&o&&u&&u(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 Dr=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"]},Pr=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}},Br=t=>t.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase());function _n({parts:t,messageId:e,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:u,onUIError:f,onUISuccess:c,addToolResult:x}){let k=[],m=[],I,b,C=false;for(let a of Array.isArray(t)?t:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){m.push(a.text),I||(I=a.startDate),b=a.endDate,a.state==="done"&&(C=true);continue}if(a.type==="text"&&typeof a.text=="string"){m.length&&(k.push({type:"reasoning",texts:m,startDate:I,endDate:b,isCompleted:C}),m=[],I=void 0,b=void 0,C=false),k.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let p=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(p||s||a.type==="tool-call"){m.length&&(k.push({type:"reasoning",texts:m,startDate:I,endDate:b,isCompleted:C}),m=[],I=void 0,b=void 0,C=false);let i=String(p?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");i==="requestInput"?k.push({type:"tool",toolName:i,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):k.push({type:"tool",toolName:i,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return m.length&&k.push({type:"reasoning",texts:m,startDate:I,endDate:b,isCompleted:C}),k.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[k.map((a,p)=>{let s=`${e}-${p}`,i=n.has(s);if(a.type==="reasoning"){let v=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",w=a.texts&&a.texts.length>0&&a.texts.some(T=>T.trim().length>0),E=()=>{w&&r(s);};return v&&!w?null:jsx("div",{onClick:E,style:{cursor:w?"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:[!v&&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:v?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:v?"auto":"200% 100%",backgroundClip:v?"unset":"text",WebkitBackgroundClip:v?"unset":"text",WebkitTextFillColor:v?o.mutedTextColor:"transparent",animation:v?void 0:"shimmer 2s ease-in-out infinite"},children:v?"Finish Thinking":"Thinking"})]}),w&&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||!v?"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:(!v&&i?a.texts:v?i?a.texts:[]:[a.texts[a.texts.length-1]]).map((T,N)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(Ke,{content:T,theme:"dark",streaming:!v})},`rg-line-${p}-${N}`))}):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 v=typeof a.endDate!="number";return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(Ke,{content:a.text,theme:"dark",streaming:v})},s)}let{color:l,text:g}=Dr(a.status),d=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 h=u?.[a.toolName||""];if(h)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(bt,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:f,onSuccess:c,children:jsx(h,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:x})})},s);let y=Pr(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: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:Br(y.toolName)})]})})},s)}),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 On(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 Un({attachment:t,resolvedColors:e,mode:n,onRemove:r,maxWidth:o="200px"}){let u=t.mimeType?.startsWith("image/"),f=n==="editable"||n==="input",c=n==="viewable",x={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"},k=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:u?"transparent":e.accentColor,flexShrink:0},children:[u?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 T=m.target.nextElementSibling;T&&(T.style.display="block");}}):null,jsx(X,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:u?"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:On(t.size)})]}),n==="input"&&u&&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(X,{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(X,{IconComponent:X$1,size:"12",strokeWidth:"2"})}),c&&jsx(X,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:e.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",style:{...x,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:k}):jsx("div",{style:x,children:k})}function Wn({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(Un,{attachment:o,resolvedColors:e,mode:r,onRemove:n},o.id))})}function Gn({chatMessages:t,isLoading:e,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:u,onUserMessageClick:f,HsafaUI:c,onUIError:x,onUISuccess:k,addToolResult:m,editableMessageIcon:T}){return jsxs(Fragment,{children:[jsx("style",{children:`
16
+ `})]}):null}function Gn(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 jn({attachment:t,resolvedColors:e,mode:n,onRemove:r,maxWidth:o="200px"}){let u=t.mimeType?.startsWith("image/"),f=n==="editable"||n==="input",c=n==="viewable",x={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"},k=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:u?"transparent":e.accentColor,flexShrink:0},children:[u?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 I=m.target.nextElementSibling;I&&(I.style.display="block");}}):null,jsx(J,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:u?"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:Gn(t.size)})]}),n==="input"&&u&&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(J,{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(J,{IconComponent:X,size:"12",strokeWidth:"2"})}),c&&jsx(J,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:e.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",style:{...x,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:k}):jsx("div",{style:x,children:k})}function qn({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(jn,{attachment:o,resolvedColors:e,mode:r,onRemove:n},o.id))})}function Kn({chatMessages:t,isLoading:e,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:u,onUserMessageClick:f,HsafaUI:c,onUIError:x,onUISuccess:k,addToolResult:m,editableMessageIcon:I}){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*as At from'react';impor
22
22
  transform: translateY(-5px);
23
23
  }
24
24
  }
25
- `}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[t.map((v,C)=>{let s=Array.isArray(v.parts)?v.parts:[],p=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:u("editor.clickToEdit"),onClick:()=>f(v,v.id,p,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:[p,a.length>0&&jsx(Wn,{attachments:a,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(X,{IconComponent:T||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx($n,{parts:s,messageId:v.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:x,onUISuccess:k,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 jn({input:t,setInput:e,textareaRef:n,fileInputRef:r,isLoading:o,uploading:u,attachments:f,formatBytes:c,handleRemoveAttachment:x,onFileInputChange:k,onSend:m,onStop:T,status:v,t:C,resolvedColors:s}){let p=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:C("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:()=>x(i.id),style:{background:"none",border:"none",color:s.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:C("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)})}),u&&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:C("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:C("input.placeholder"),value:t,onChange:i=>e(i.target.value),onKeyDown:i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),m());},disabled:o||u,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:k,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||u,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||u?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||u?.5:1},"aria-label":C("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:!p,"aria-label":C("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:p?1:.4,cursor:p?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{p&&(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||u,"aria-label":C("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||u?s.mutedTextColor:s.primaryColor,cursor:!a||u?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!a||u?.5:1},onMouseEnter:i=>{a&&!u&&(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 Vn({prompts:t,onSelect:e,resolvedColors:n,disabled:r=false}){let[o,u]=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 x=o===c,k=f.prompt.length>80,m=k&&!x?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: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"})]}),f.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:m}),k&&jsxs("button",{onClick:T=>{T.stopPropagation(),u(x?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:[x?"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:x?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},c)})})]})}function _n(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 u=Math.floor(o/24);if(u<7)return `${u}d`;let f=Math.floor(u/7);if(f<4)return `${f}w`;let c=Math.floor(u/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function qn({historyOpen:t,historySearch:e,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:u,onSearchChange:f,onChatSelect:c,onChatDelete:x,loadChatsIndex:k,historyPopupRef:m}){if(!t)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:u}),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(),C=k();return v&&(C=C.filter(s=>(s.title||"").toLowerCase().includes(v))),!C||C.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:C.map((s,p)=>jsx("div",{style:{borderTop:p>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:_n(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(),x(s.id);},children:jsx(X,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},s.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(T,document.body):T}function Kn({isOpen:t,resolvedColors:e,onConfirm:n,onCancel:r,editProcessContent:o}){if(!t)return null;let u=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",x=o?.cancel_button_label||"Cancel",k=o?.icon,m=typeof f=="function",T=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:[k?jsx("div",{style:{flexShrink:0},children:jsx(X,{IconComponent:k,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:e.mutedTextColor},children:jsx(X,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:e.textColor,flex:1},children:u})]}),jsx("div",{style:{padding:"24px",color:e.textColor,fontSize:"14px",lineHeight:"1.6"},children:m&&T?jsx(T,{}):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:C=>{C.currentTarget.style.backgroundColor=e.hoverBackground;},onMouseLeave:C=>{C.currentTarget.style.backgroundColor="transparent";},children:x}),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:C=>{C.currentTarget.style.opacity="0.9";},onMouseLeave:C=>{C.currentTarget.style.opacity="1";},children:c})]})]})]});return typeof document<"u"&&document.body?createPortal(v,document.body):v}function Xr({agentId:t,theme:e,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:u,borderColor:f,textColor:c,accentColor:x,baseUrl:k="",initialMessages:m=[],onMessagesChange:T,defaultOpen:v=true,floatingButtonPosition:C={bottom:24,right:24},HsafaTools:s={},HsafaUI:p={},componentAboveInput:a,editProcessContent:i,presetPrompts:l,onStart:g,onFinish:d,currentChat:h,onChatChanged:y,templateParams:b}){let{dir:w,theme:R,baseUrl:I,setStreamingState:B,setChatOpenState:L,tools:D,uiComponents:P}=et(),G=e||R||"dark",_=k&&k.length>0?k:I||"",A={primaryColor:G==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:u||(G==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:f||(G==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(G==="dark"?"#EDEEF0":"#111827"),accentColor:x||(G==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:G==="dark"?"#6f7276":"#6B7280",inputBackground:G==="dark"?"#17181C":"#F3F4F6",cardBackground:G==="dark"?"#121318":"#FFFFFF",hoverBackground:G==="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,j=useMemo(()=>({...D&&D.size>0?Object.fromEntries(D.entries()):{},...s||{}}),[s,D]),J=useMemo(()=>({...P&&P.size>0?Object.fromEntries(P.entries()):{},...p||{}}),[p,P]),tt=Be({agentId:t,baseUrl:_,tools:j,uiComponents:J,templateParams:b,controlledChatId:h,onChatIdChange:h===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:T}),{input:mt,setInput:nt,messages:lt,isLoading:K,status:wt,error:Qt,sendMessage:te,stop:ke,setMessages:ct,notifyMessagesChange:F,chatId:N,setChatId:W,tools:O,uiComponents:ot,formHostRef:rt,formStateRef:ht,cleanupForms:Ot,onUISuccess:we,onUIError:to,chatApi:eo}=tt,at=h!==void 0?h:N,Ut=useCallback(S=>{h===void 0&&W(S),y&&y(S);},[h,W,y]);useEffect(()=>{h!==void 0&&h!==N&&W(h);},[h,N,W]);let{attachments:ee,uploading:no,fileInputRef:ne,formatBytes:oo,handleRemoveAttachment:ro,handleFileSelection:qe,clearAttachments:oe,setAttachments:Ke}=cn(_),[Xe,Ft]=useState(null),[re,Je]=useState(()=>{try{return Bt(t).loadShowChatPreference(!!v)}catch{return !!v}}),[ao,Te]=useState(false),[so,io]=useState(""),[lo,co]=useState(0),uo=useRef(null),po=useRef(null),[fo,mo]=useState(new Set),[go,Ie]=useState(false),[zt,Se]=useState(null),Ye=useRef(null),yo=rn(K),Me=$e({agentId:t,chatId:at,messages:lt,isLoading:K,autoSave:true,autoRestore:false}),q=Me.storage,Wt=useRef(false),Gt=useRef(null);useEffect(()=>{if(!Wt.current){if(h!==void 0){try{let S=q.loadChat(h),U=S&&Array.isArray(S.messages)?S.messages:[];if(U.length>0)try{ct(U);}catch{}Gt.current=h;}catch{}try{q.saveCurrentChatId(h);}catch{}Wt.current=true;return}try{let S=q.loadCurrentChatId();if(S){Ut(S);let U=q.loadChat(S),V=U&&Array.isArray(U.messages)?U.messages:[];try{ct(V);}catch{}Gt.current=S;}}catch{}Wt.current=true;}},[h]),useEffect(()=>{if(Wt.current&&h!==void 0&&h!==Gt.current)try{let S=q.loadChat(h),U=S&&Array.isArray(S.messages)?S.messages:[];try{ct(U);}catch{}Gt.current=h;try{q.saveCurrentChatId(h);}catch{}}catch{}},[h,q,ct]),useEffect(()=>{if(Wt.current)try{q.saveCurrentChatId(at);}catch{}},[at,q]),useEffect(()=>{try{B(at,K);}catch{}return ()=>{try{B(at,!1);}catch{}}},[at,K,B]),useEffect(()=>{try{L(at,re);}catch{}return ()=>{try{L(at,!1);}catch{}}},[at,re,L]);let ho=useCallback(async()=>{let S=mt.trim();if(!S&&ee.length===0||K)return;let U=[...ee];nt(""),oe(),Ft(null);try{await te({text:S,files:U.map(V=>({type:"file",url:V.url,mediaType:V.mimeType||"application/octet-stream",...V.name?{name:V.name}:{},...V.size?{size:V.size}:{}}))});}catch(V){console.error("Failed to send message:",V),Ft("Failed to send message. Please try again.");}},[mt,ee,K,te,oe]),Ze=useCallback(()=>{if(K)return;Ot(),nt(""),oe(),Ft(null);try{ct([]);}catch{}let S=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Gt.current=S;try{Me.createNewChat(()=>{Ut(S);try{q.saveCurrentChatId(S);}catch{}});}catch{Ut(S);try{q.saveCurrentChatId(S);}catch{}}},[K,oe,q,ct,Ut,Ot,Me]),xo=useCallback(()=>{Te(S=>!S);},[]),Co=useCallback(()=>{Je(false);try{q.saveShowChatPreference(!1);}catch{}},[q]),bo=useCallback(async S=>{let U=S.target.files;U&&await qe(U,Ft),ne.current&&(ne.current.value="");},[qe,ne]);useEffect(()=>{let S=Ye.current;if(!S)return;S.style.height="24px",S.offsetHeight,S.style.height="auto";let U=Math.min(S.scrollHeight,200);S.style.height=`${U}px`;},[mt]);let vo=useCallback((S,U,V,To)=>{Se({id:U,text:V,attachments:To||[]}),Ie(true);},[]),ko=useCallback(()=>{if(!(!zt||K))try{let S=lt.findIndex(V=>V.id===zt.id);if(S===-1)return;let U=lt.slice(0,S);try{ct(U);}catch{}nt(zt.text),Ke(zt.attachments),Ie(!1),Se(null),F();}catch(S){console.error("Failed to edit message:",S),Ft("Failed to edit message. Please try again.");}},[zt,K,lt,ct,Ke,F]),wo=useCallback(()=>{Ie(false),Se(null);},[]),Qe=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:re?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(Nn,{title:M("general.agent")+2,alwaysOpen:false,streaming:K,dir:w||"ltr",resolvedColors:A,onNew:Ze,onToggleHistory:xo,onClose:Co,historyBtnRef:uo,t:M}),jsx("div",{ref:yo,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:lt.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:l&&l.length>0?jsx(Vn,{prompts:l,onSelect:S=>nt(S),resolvedColors:A,disabled:K}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:M("messages.empty")})}):jsx(Gn,{chatMessages:lt,isLoading:K,openReasoningIds:fo,toggleReasoning:S=>mo(U=>{let V=new Set(U);return V.has(S)?V.delete(S):V.add(S),V}),resolvedColors:A,t:M,onUserMessageClick:vo,HsafaUI:ot,onUIError:to,onUISuccess:we,addToolResult:S=>eo?.addToolResult?.(S),editableMessageIcon:i?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[a&&At__default.createElement(a,{}),Xe&&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:Xe}),jsx("button",{onClick:()=>Ft(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),Qt&&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: ",Qt.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(jn,{input:mt,setInput:nt,textareaRef:Ye,fileInputRef:ne,isLoading:K,uploading:no,attachments:ee,formatBytes:oo,handleRemoveAttachment:ro,onFileInputChange:bo,onSend:ho,onStop:()=>ke(),status:wt,t:M,resolvedColors:A})]}),jsx(qn,{historyOpen:ao,historySearch:so,currentChatId:at,refreshKey:lo,resolvedColors:A,onClose:()=>Te(false),onSearchChange:io,onChatSelect:S=>{if(Te(false),S&&S!==at&&(Ot(),Ut(S),h===void 0)){try{q.saveCurrentChatId(S);}catch{}try{let U=q.loadChat(S),V=U&&Array.isArray(U.messages)?U.messages:[];try{ct(V);}catch{}}catch{}}},onChatDelete:S=>{try{q.deleteChat(S),co(U=>U+1),S===at&&Ze();}catch{}},loadChatsIndex:()=>q.loadChatsIndex(),historyPopupRef:po}),jsx(Kn,{isOpen:go,resolvedColors:A,onConfirm:ko,onCancel:wo,editProcessContent:i}),jsx("style",{children:`
25
+ `}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[t.map((b,C)=>{let a=Array.isArray(b.parts)?b.parts:[],p=a.filter(i=>i.type==="text").map(i=>i&&typeof i.text=="string"?i.text:"").join(`
26
+ `),s=a.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||`${b.id}-img-${Date.now()}`,name:i.name||"image",url:l,mimeType:i.mediaType||"image/jpeg",size:i.size||0}}else return {id:i.url||`${b.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:b.role==="user"?jsx("div",{children:jsx("div",{title:u("editor.clickToEdit"),onClick:()=>f(b,b.id,p,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: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:[p,s.length>0&&jsx(qn,{attachments:s,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(J,{IconComponent:I||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(_n,{parts:a,messageId:b.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:x,onUISuccess:k,addToolResult:m})},b.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 Xn({input:t,setInput:e,textareaRef:n,fileInputRef:r,isLoading:o,uploading:u,attachments:f,formatBytes:c,handleRemoveAttachment:x,onFileInputChange:k,onSend:m,onStop:I,status:b,t:C,resolvedColors:a}){let p=b==="streaming"||b==="submitted",s=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 ${a.borderColor}`,backgroundColor:a.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: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:l?"transparent":a.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:a.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:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:C("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:()=>x(i.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:C("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)})}),u&&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:C("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:C("input.placeholder"),value:t,onChange:i=>e(i.target.value),onKeyDown:i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),m());},disabled:o||u,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:k,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||u,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||u?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||u?.5:1},"aria-label":C("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:I,disabled:!p,"aria-label":C("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:p?1:.4,cursor:p?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{p&&(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:!s||u,"aria-label":C("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||u?a.mutedTextColor:a.primaryColor,cursor:!s||u?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||u?.5:1},onMouseEnter:i=>{s&&!u&&(i.currentTarget.style.borderColor=a.primaryColor,i.currentTarget.style.transform="scale(1.02)");},onMouseLeave:i=>{i.currentTarget.style.borderColor=a.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 Jn({prompts:t,onSelect:e,resolvedColors:n,disabled:r=false}){let[o,u]=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 x=o===c,k=f.prompt.length>80,m=k&&!x?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:I=>{r||(I.currentTarget.style.backgroundColor=n.hoverBackground,I.currentTarget.style.borderColor=n.primaryColor,I.currentTarget.style.transform="translateX(2px)");},onMouseLeave:I=>{I.currentTarget.style.backgroundColor=n.cardBackground,I.currentTarget.style.borderColor=n.borderColor,I.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}),k&&jsxs("button",{onClick:I=>{I.stopPropagation(),u(x?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:[x?"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:x?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},c)})})]})}function Yn(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 u=Math.floor(o/24);if(u<7)return `${u}d`;let f=Math.floor(u/7);if(f<4)return `${f}w`;let c=Math.floor(u/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function Zn({historyOpen:t,historySearch:e,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:u,onSearchChange:f,onChatSelect:c,onChatDelete:x,loadChatsIndex:k,historyPopupRef:m}){if(!t)return null;let I=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:u}),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:b=>f(b.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:b=>b.currentTarget.style.borderColor=o.primaryColor,onBlur:b=>b.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let b=e.toLowerCase().trim(),C=k();return b&&(C=C.filter(a=>(a.title||"").toLowerCase().includes(b))),!C||C.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:C.map((a,p)=>jsx("div",{style:{borderTop:p>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:()=>c(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:Yn(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(),x(a.id);},children:jsx(J,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(I,document.body):I}function Qn({isOpen:t,resolvedColors:e,onConfirm:n,onCancel:r,editProcessContent:o}){if(!t)return null;let u=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",x=o?.cancel_button_label||"Cancel",k=o?.icon,m=typeof f=="function",I=m?f:null,b=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:[k?jsx("div",{style:{flexShrink:0},children:jsx(J,{IconComponent:k,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:e.mutedTextColor},children:jsx(J,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:e.textColor,flex:1},children:u})]}),jsx("div",{style:{padding:"24px",color:e.textColor,fontSize:"14px",lineHeight:"1.6"},children:m&&I?jsx(I,{}):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:C=>{C.currentTarget.style.backgroundColor=e.hoverBackground;},onMouseLeave:C=>{C.currentTarget.style.backgroundColor="transparent";},children:x}),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:C=>{C.currentTarget.style.opacity="0.9";},onMouseLeave:C=>{C.currentTarget.style.opacity="1";},children:c})]})]})]});return typeof document<"u"&&document.body?createPortal(b,document.body):b}function Qr({agentId:t,theme:e,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:u,borderColor:f,textColor:c,accentColor:x,baseUrl:k="",initialMessages:m=[],onMessagesChange:I,defaultOpen:b=true,floatingButtonPosition:C={bottom:24,right:24},HsafaTools:a={},HsafaUI:p={},componentAboveInput:s,editProcessContent:i,presetPrompts:l,onStart:g,onFinish:d,currentChat:h,onChatChanged:y,templateParams:v}){let{dir:w,theme:E,baseUrl:T,setStreamingState:N,setChatOpenState:$,tools:L,uiComponents:P}=se(),D=e||E||"dark",V=k&&k.length>0?k:T||"",A={primaryColor:D==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:u||(D==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:f||(D==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(D==="dark"?"#EDEEF0":"#111827"),accentColor:x||(D==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:D==="dark"?"#6f7276":"#6B7280",inputBackground:D==="dark"?"#17181C":"#F3F4F6",cardBackground:D==="dark"?"#121318":"#FFFFFF",hoverBackground:D==="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,j=useMemo(()=>({...L&&L.size>0?Object.fromEntries(L.entries()):{},...a||{}}),[a,L]),Y=useMemo(()=>({...P&&P.size>0?Object.fromEntries(P.entries()):{},...p||{}}),[p,P]),Q=$t({agentId:t,baseUrl:V,tools:j,uiComponents:Y,templateParams:v,controlledChatId:h,onChatIdChange:h===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:I}),{input:me,setInput:oe,messages:ae,isLoading:X,status:we,error:et,sendMessage:tt,stop:It,setMessages:ce,notifyMessagesChange:H,chatId:B,setChatId:U,tools:O,uiComponents:re,formHostRef:ee,formStateRef:de,cleanupForms:Oe,onUISuccess:Tt,onUIError:so,chatApi:ao}=Q,K=h!==void 0?h:B,ze=useCallback(S=>{h===void 0&&U(S),y&&y(S);},[h,U,y]);useEffect(()=>{h!==void 0&&h!==B&&U(h);},[h,B,U]);let{attachments:nt,uploading:io,fileInputRef:ot,formatBytes:lo,handleRemoveAttachment:co,handleFileSelection:Jt,clearAttachments:rt,setAttachments:Yt}=pn(V),[Zt,Fe]=useState(null),[st,Qt]=useState(()=>{try{return Ne(t).loadShowChatPreference(!!b)}catch{return !!b}}),[uo,St]=useState(false),[po,fo]=useState(""),[go,mo]=useState(0),yo=useRef(null),ho=useRef(null),[xo,Co]=useState(new Set),[bo,Mt]=useState(false),[Le,At]=useState(null),en=useRef(null),vo=ln(X),Rt=Ot({agentId:t,chatId:K,messages:ae,isLoading:X,autoSave:true,autoRestore:false}),q=Rt.storage,We=useRef(false),_e=useRef(null);useEffect(()=>{if(!We.current){if(h!==void 0){try{let S=q.loadChat(h),W=S&&Array.isArray(S.messages)?S.messages:[];if(W.length>0)try{ce(W);}catch{}_e.current=h;}catch{}try{q.saveCurrentChatId(h);}catch{}We.current=true;return}try{let S=q.loadCurrentChatId();if(S){ze(S);let W=q.loadChat(S),_=W&&Array.isArray(W.messages)?W.messages:[];try{ce(_);}catch{}_e.current=S;}}catch{}We.current=true;}},[h]),useEffect(()=>{if(We.current&&h!==void 0&&h!==_e.current)try{let S=q.loadChat(h),W=S&&Array.isArray(S.messages)?S.messages:[];try{ce(W);}catch{}_e.current=h;try{q.saveCurrentChatId(h);}catch{}}catch{}},[h,q,ce]),useEffect(()=>{if(We.current)try{q.saveCurrentChatId(K);}catch{}},[K,q]),useEffect(()=>{try{N(K,X);}catch{}return ()=>{try{N(K,!1);}catch{}}},[K,X,N]),useEffect(()=>{try{$(K,st);}catch{}return ()=>{try{$(K,!1);}catch{}}},[K,st,$]);let ko=useCallback(async()=>{let S=me.trim();if(!S&&nt.length===0||X)return;let W=[...nt];oe(""),rt(),Fe(null);try{await tt({text:S,files:W.map(_=>({type:"file",url:_.url,mediaType:_.mimeType||"application/octet-stream",..._.name?{name:_.name}:{},..._.size?{size:_.size}:{}}))});}catch(_){console.error("Failed to send message:",_),Fe("Failed to send message. Please try again.");}},[me,nt,X,tt,rt]),tn=useCallback(()=>{if(X)return;Oe(),oe(""),rt(),Fe(null);try{ce([]);}catch{}let S=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;_e.current=S;try{Rt.createNewChat(()=>{ze(S);try{q.saveCurrentChatId(S);}catch{}});}catch{ze(S);try{q.saveCurrentChatId(S);}catch{}}},[X,rt,q,ce,ze,Oe,Rt]),wo=useCallback(()=>{St(S=>!S);},[]),Io=useCallback(()=>{Qt(false);try{q.saveShowChatPreference(!1);}catch{}},[q]),To=useCallback(async S=>{let W=S.target.files;W&&await Jt(W,Fe),ot.current&&(ot.current.value="");},[Jt,ot]);useEffect(()=>{let S=en.current;if(!S)return;S.style.height="24px",S.offsetHeight,S.style.height="auto";let W=Math.min(S.scrollHeight,200);S.style.height=`${W}px`;},[me]);let So=useCallback((S,W,_,at)=>{At({id:W,text:_,attachments:at||[]}),Mt(true);},[]),Mo=useCallback(()=>{if(!(!Le||X))try{let S=ae.findIndex(Ge=>Ge.id===Le.id);if(S===-1)return;let W=!!globalThis.__HSAFA_DEBUG__;W&&console.log("[hsafa-chat] confirmEdit:start",{chatId:K,messageId:Le.id,messageIndex:S,prevMessagesLen:ae.length});let _=ae.slice(0,S);try{ce(_);}catch(Ge){console.warn("[hsafa-chat] confirmEdit:setMessages failed",Ge);}let at=_.length>0?_[_.length-1]:void 0;W&&console.log("[hsafa-chat] confirmEdit:truncated",{chatId:K,nextMessagesLen:_.length,lastMessageId:at?.id,lastMessageRole:at?.role}),oe(Le.text),Yt(Le.attachments),Mt(!1),At(null);try{H(_,K);}catch(Ge){console.warn("[hsafa-chat] confirmEdit:notifyMessagesChange failed",Ge);}W&&console.log("[hsafa-chat] confirmEdit:notifiedMessagesChange",{chatId:K,nextMessagesLen:_.length});}catch(S){console.error("Failed to edit message:",S),Fe("Failed to edit message. Please try again.");}},[Le,X,ae,ce,oe,Yt,H,K]),Ao=useCallback(()=>{Mt(false),At(null);},[]),nn=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:st?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(Wn,{title:M("general.agent")+2,alwaysOpen:false,streaming:X,dir:w||"ltr",resolvedColors:A,onNew:tn,onToggleHistory:wo,onClose:Io,historyBtnRef:yo,t:M}),jsx("div",{ref:vo,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:ae.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:l&&l.length>0?jsx(Jn,{prompts:l,onSelect:S=>oe(S),resolvedColors:A,disabled:X}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:M("messages.empty")})}):jsx(Kn,{chatMessages:ae,isLoading:X,openReasoningIds:xo,toggleReasoning:S=>Co(W=>{let _=new Set(W);return _.has(S)?_.delete(S):_.add(S),_}),resolvedColors:A,t:M,onUserMessageClick:So,HsafaUI:re,onUIError:so,onUISuccess:Tt,addToolResult:S=>ao?.addToolResult?.(S),editableMessageIcon:i?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&Ae__default.createElement(s,{}),Zt&&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:Zt}),jsx("button",{onClick:()=>Fe(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),et&&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: ",et.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(Xn,{input:me,setInput:oe,textareaRef:en,fileInputRef:ot,isLoading:X,uploading:io,attachments:nt,formatBytes:lo,handleRemoveAttachment:co,onFileInputChange:To,onSend:ko,onStop:()=>It(),status:we,t:M,resolvedColors:A})]}),jsx(Zn,{historyOpen:uo,historySearch:po,currentChatId:K,refreshKey:go,resolvedColors:A,onClose:()=>St(false),onSearchChange:fo,onChatSelect:S=>{if(St(false),S&&S!==K&&(Oe(),ze(S),h===void 0)){try{q.saveCurrentChatId(S);}catch{}try{let W=q.loadChat(S),_=W&&Array.isArray(W.messages)?W.messages:[];try{ce(_);}catch{}}catch{}}},onChatDelete:S=>{try{q.deleteChat(S),mo(W=>W+1),S===K&&tn();}catch{}},loadChatsIndex:()=>q.loadChatsIndex(),historyPopupRef:ho}),jsx(Qn,{isOpen:bo,resolvedColors:A,onConfirm:Mo,onCancel:Ao,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(ce,{}),createPortal(Qe,document.body),jsx(en,{show:!re,onClick:()=>{Je(true);try{q.saveShowChatPreference(!0);}catch{}},resolvedColors:A,floatingButtonPosition:C})]}):Qe}var Jn={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 ta({children:t,theme:e="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:u,mutedTextColor:f,enableBorderAnimation:c=true,borderRadius:x=16,enableContentBorder:k=true,className:m="",enableMargin:T=true,chatWidth:v=420,dir:C="ltr"}){let{isAnyStreaming:s,isAnyChatOpen:p,dir:a,theme:i}=et(),l=(C??a)||"ltr",g=(e??i)||"dark",d=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[h,y]=useState(false);useEffect(()=>{let D=setTimeout(()=>y(true),50);return ()=>clearTimeout(D)},[]);let b=Jn[g],w={primaryColor:n||b.primaryColor,backgroundColor:r||b.backgroundColor,borderColor:o||b.borderColor,textColor:u||b.textColor,accentColor:b.accentColor,mutedTextColor:f||b.mutedTextColor,inputBackground:b.inputBackground,cardBackground:b.cardBackground,hoverBackground:b.hoverBackground},R=typeof x=="number"?`${x}px`:x,I=typeof v=="number"?`${v}px`:v,B=T&&p?l==="rtl"?{marginLeft:I}:{marginRight:I}:{},L=T&&p?`calc(100% - ${I})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:m,style:{width:L,height:"100%",transition:h?"all 0.2s ease-out":"none",padding:p&&k?"16px":"0",...B},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:h?"all 0.2s ease-out":"none",borderRadius:p?R:"0",border:p&&s&&c?"none":p?`1px solid ${w.borderColor}`:"none",padding:p&&s&&c?"1.5px":"0",background:p&&s&&c?`linear-gradient(120deg, ${w.primaryColor}dd 0%, ${w.primaryColor}88 25%, ${w.primaryColor}00 50%, ${w.primaryColor}88 75%, ${w.primaryColor}dd 100%)`:"transparent",backgroundSize:p&&s&&c?"300% 300%":"auto",animation:p&&s&&c?`${d.current}-border-flow 3s ease-in-out infinite`:"none",filter:p&&s&&c?`drop-shadow(0 0 10px ${w.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:p&&k?R:"0",backgroundColor:p&&k?w.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${w.mutedTextColor}40 transparent`},children:t})})}),jsx("style",{children:`
29
+ `})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(ut,{}),createPortal(nn,document.body),jsx(rn,{show:!st,onClick:()=>{Qt(true);try{q.saveShowChatPreference(!0);}catch{}},resolvedColors:A,floatingButtonPosition:C})]}):nn}var to={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 rs({children:t,theme:e="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:u,mutedTextColor:f,enableBorderAnimation:c=true,borderRadius:x=16,enableContentBorder:k=true,className:m="",enableMargin:I=true,chatWidth:b=420,dir:C="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:p,dir:s,theme:i}=se(),l=(C??s)||"ltr",g=(e??i)||"dark",d=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[h,y]=useState(false);useEffect(()=>{let L=setTimeout(()=>y(true),50);return ()=>clearTimeout(L)},[]);let v=to[g],w={primaryColor:n||v.primaryColor,backgroundColor:r||v.backgroundColor,borderColor:o||v.borderColor,textColor:u||v.textColor,accentColor:v.accentColor,mutedTextColor:f||v.mutedTextColor,inputBackground:v.inputBackground,cardBackground:v.cardBackground,hoverBackground:v.hoverBackground},E=typeof x=="number"?`${x}px`:x,T=typeof b=="number"?`${b}px`:b,N=I&&p?l==="rtl"?{marginLeft:T}:{marginRight:T}:{},$=I&&p?`calc(100% - ${T})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:m,style:{width:$,height:"100%",transition:h?"all 0.2s ease-out":"none",padding:p&&k?"16px":"0",...N},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:h?"all 0.2s ease-out":"none",borderRadius:p?E:"0",border:p&&a&&c?"none":p?`1px solid ${w.borderColor}`:"none",padding:p&&a&&c?"1.5px":"0",background:p&&a&&c?`linear-gradient(120deg, ${w.primaryColor}dd 0%, ${w.primaryColor}88 25%, ${w.primaryColor}00 50%, ${w.primaryColor}88 75%, ${w.primaryColor}dd 100%)`:"transparent",backgroundSize:p&&a&&c?"300% 300%":"auto",animation:p&&a&&c?`${d.current}-border-flow 3s ease-in-out infinite`:"none",filter:p&&a&&c?`drop-shadow(0 0 10px ${w.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:p&&k?E:"0",backgroundColor:p&&k?w.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${w.mutedTextColor}40 transparent`},children:t})})}),jsx("style",{children:`
30
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 Ge=typeof navigator<"u"?navigator:void 0;function kt(){return !!Ge?.storage?.getDirectory}async function Ht(){if(!kt()||!Ge?.storage?.getDirectory)return null;try{return await Ge.storage.getDirectory()}catch{return null}}async function Yn(t,e){try{return await t.getFileHandle(e,{create:!1}),!0}catch{return false}}async function Zn(t,e){let n=await t.createWritable();await n.write(new Blob([e],{type:"application/json"})),await n.close();}async function Qn(t){return await(await t.getFile()).text()}function oa(t){return t.kind==="directory"}function ra(t){try{return JSON.parse(t)}catch{return null}}function aa(t){let e=`hsafa:${t}`;return {latest:n=>`${e}:${n}:latest`,version:(n,r)=>`${e}:${n}:versions:${r}`,latestPrefix:`${e}:`}}async function Q(t,e,n){try{return await t.getDirectoryHandle(e,{create:n})}catch{return null}}async function je(t,e){try{let n=await t.getFileHandle(e,{create:!1});return await Qn(n)}catch{return null}}async function Ve(t,e,n){try{let r=await t.getFileHandle(e,{create:!0});return await Zn(r,n),!0}catch{return false}}function sa(t){let{namespace:e,serialize:n=p=>JSON.stringify(p),deserialize:r=p=>JSON.parse(p),storageOrder:o=["opfs","localStorage"],legacyDecode:u}=t,f=aa(e),c=(p,a,i)=>{let l={chatId:p,versionId:a,updatedAt:new Date().toISOString(),data:n(i)};return JSON.stringify(l)},x=p=>{let a=ra(p);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(u)try{let i=u(p);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(p,a)=>{let i=c(p,"__latest",a);for(let l of o){if(l==="opfs"){if(!kt())continue;let g=await Ht();if(!g)continue;let d=await Q(g,e,true);if(!d)continue;let h=await Q(d,p,true);if(!h)continue;if(await Ve(h,"latest.json",i))return}if(l==="localStorage")try{localStorage.setItem(f.latest(p),i);return}catch{continue}}},loadLatest:async p=>{for(let a of o){if(a==="opfs"){if(!kt())continue;let i=await Ht();if(!i)continue;let l=await Q(i,e,false);if(!l)continue;let g=await Q(l,p,false);if(!g)continue;let d=await je(g,"latest.json");if(!d)continue;let h=x(d);if(!h)continue;return h.value}if(a==="localStorage")try{let i=localStorage.getItem(f.latest(p));if(!i)continue;let l=x(i);if(!l)continue;return l.value}catch{continue}}return null},saveVersion:async(p,a,i)=>{let l=c(p,a,i);for(let g of o){if(g==="opfs"){if(!kt())continue;let d=await Ht();if(!d)continue;let h=await Q(d,e,true);if(!h)continue;let y=await Q(h,p,true);if(!y)continue;let b=await Q(y,"versions",true);if(!b||!await Ve(b,`${a}.json`,l))continue;if(await Ve(y,"latest.json",l))return}if(g==="localStorage")try{localStorage.setItem(f.version(p,a),l),localStorage.setItem(f.latest(p),l);return}catch{continue}}},loadVersion:async(p,a)=>{for(let i of o){if(i==="opfs"){if(!kt())continue;let l=await Ht();if(!l)continue;let g=await Q(l,e,false);if(!g)continue;let d=await Q(g,p,false);if(!d)continue;let h=await Q(d,"versions",false);if(!h)continue;let y=await je(h,`${a}.json`);if(!y)continue;let b=x(y);if(!b)continue;return b.value}if(i==="localStorage")try{let l=localStorage.getItem(f.version(p,a));if(!l)continue;let g=x(l);if(!g)continue;return g.value}catch{continue}}return null},hasVersion:async(p,a)=>{for(let i of o){if(i==="opfs"){if(!kt())continue;let l=await Ht();if(!l)continue;let g=await Q(l,e,false);if(!g)continue;let d=await Q(g,p,false);if(!d)continue;let h=await Q(d,"versions",false);if(!h)continue;if(await Yn(h,`${a}.json`))return true}if(i==="localStorage")try{if(localStorage.getItem(f.version(p,a))!=null)return !0}catch{continue}}return false},findMostRecentChatId:async()=>{for(let p of o){if(p==="opfs"){if(!kt())continue;let a=await Ht();if(!a)continue;let i=await Q(a,e,false);if(!i)continue;let l=null,g=0;try{let d=i.entries?.();if(!d)continue;for await(let[h,y]of d){if(!oa(y))continue;let w=await je(y,"latest.json");if(!w)continue;let R=x(w);if(!R)continue;let I=Date.parse(R.record.updatedAt);!Number.isNaN(I)&&I>g&&(g=I,l=R.record.chatId||h);}if(l)return l}catch{continue}}if(p==="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 h=x(d);if(!h)continue;let y=Date.parse(h.record.updatedAt);!Number.isNaN(y)&&y>i&&(i=y,a=h.record.chatId);}if(a)return a}catch{continue}}return null}}}var _e=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())}},ia=new _e;export{da as Button,ta as ContentContainer,ce as CursorController,Vt as FillActiveInput,en as FloatingChatButton,Xr as HsafaChat,Ro as HsafaProvider,ia as componentRegistry,St as controlCursor,sa as createHsafaArtifactStore,jt as getDomComponents,St as guideCursor,rn as useAutoScroll,yr as useChatArtifact,kr as useChatArtifactVersioning,$e as useChatStorage,cn as useFileUpload,et as useHsafa,Oe as useHsafaActiveChatId,Be as useHsafaAgent,wr as useHsafaTools,ur as useMessageEditor};//# sourceMappingURL=index.js.map
35
+ `})," "]})}var Vt=typeof navigator<"u"?navigator:void 0;function ke(){return !!Vt?.storage?.getDirectory}async function He(){if(!ke()||!Vt?.storage?.getDirectory)return null;try{return await Vt.storage.getDirectory()}catch{return null}}async function no(t,e){try{return await t.getFileHandle(e,{create:!1}),!0}catch{return false}}async function oo(t,e){let n=await t.createWritable();await n.write(new Blob([e],{type:"application/json"})),await n.close();}async function ro(t){return await(await t.getFile()).text()}function is(t){return t.kind==="directory"}function ls(t){try{return JSON.parse(t)}catch{return null}}function cs(t){let e=`hsafa:${t}`;return {latest:n=>`${e}:${n}:latest`,version:(n,r)=>`${e}:${n}:versions:${r}`,latestPrefix:`${e}:`}}async function ne(t,e,n){try{return await t.getDirectoryHandle(e,{create:n})}catch{return null}}async function qt(t,e){try{let n=await t.getFileHandle(e,{create:!1});return await ro(n)}catch{return null}}async function Kt(t,e,n){try{let r=await t.getFileHandle(e,{create:!0});return await oo(r,n),!0}catch{return false}}function ds(t){let{namespace:e,serialize:n=p=>JSON.stringify(p),deserialize:r=p=>JSON.parse(p),storageOrder:o=["opfs","localStorage"],legacyDecode:u}=t,f=cs(e),c=(p,s,i)=>{let l={chatId:p,versionId:s,updatedAt:new Date().toISOString(),data:n(i)};return JSON.stringify(l)},x=p=>{let s=ls(p);if(s&&typeof s.chatId=="string"&&typeof s.versionId=="string"){if(typeof s.updatedAt!="string"||typeof s.data!="string")return null;try{return {value:r(s.data),record:s}}catch{return null}}if(u)try{let i=u(p);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(p,s)=>{let i=c(p,"__latest",s);for(let l of o){if(l==="opfs"){if(!ke())continue;let g=await He();if(!g)continue;let d=await ne(g,e,true);if(!d)continue;let h=await ne(d,p,true);if(!h)continue;if(await Kt(h,"latest.json",i))return}if(l==="localStorage")try{localStorage.setItem(f.latest(p),i);return}catch{continue}}},loadLatest:async p=>{for(let s of o){if(s==="opfs"){if(!ke())continue;let i=await He();if(!i)continue;let l=await ne(i,e,false);if(!l)continue;let g=await ne(l,p,false);if(!g)continue;let d=await qt(g,"latest.json");if(!d)continue;let h=x(d);if(!h)continue;return h.value}if(s==="localStorage")try{let i=localStorage.getItem(f.latest(p));if(!i)continue;let l=x(i);if(!l)continue;return l.value}catch{continue}}return null},saveVersion:async(p,s,i)=>{let l=c(p,s,i);for(let g of o){if(g==="opfs"){if(!ke())continue;let d=await He();if(!d)continue;let h=await ne(d,e,true);if(!h)continue;let y=await ne(h,p,true);if(!y)continue;let v=await ne(y,"versions",true);if(!v||!await Kt(v,`${s}.json`,l))continue;if(await Kt(y,"latest.json",l))return}if(g==="localStorage")try{localStorage.setItem(f.version(p,s),l),localStorage.setItem(f.latest(p),l);return}catch{continue}}},loadVersion:async(p,s)=>{for(let i of o){if(i==="opfs"){if(!ke())continue;let l=await He();if(!l)continue;let g=await ne(l,e,false);if(!g)continue;let d=await ne(g,p,false);if(!d)continue;let h=await ne(d,"versions",false);if(!h)continue;let y=await qt(h,`${s}.json`);if(!y)continue;let v=x(y);if(!v)continue;return v.value}if(i==="localStorage")try{let l=localStorage.getItem(f.version(p,s));if(!l)continue;let g=x(l);if(!g)continue;return g.value}catch{continue}}return null},hasVersion:async(p,s)=>{for(let i of o){if(i==="opfs"){if(!ke())continue;let l=await He();if(!l)continue;let g=await ne(l,e,false);if(!g)continue;let d=await ne(g,p,false);if(!d)continue;let h=await ne(d,"versions",false);if(!h)continue;if(await no(h,`${s}.json`))return true}if(i==="localStorage")try{if(localStorage.getItem(f.version(p,s))!=null)return !0}catch{continue}}return false},findMostRecentChatId:async()=>{for(let p of o){if(p==="opfs"){if(!ke())continue;let s=await He();if(!s)continue;let i=await ne(s,e,false);if(!i)continue;let l=null,g=0;try{let d=i.entries?.();if(!d)continue;for await(let[h,y]of d){if(!is(y))continue;let w=await qt(y,"latest.json");if(!w)continue;let E=x(w);if(!E)continue;let T=Date.parse(E.record.updatedAt);!Number.isNaN(T)&&T>g&&(g=T,l=E.record.chatId||h);}if(l)return l}catch{continue}}if(p==="localStorage")try{let s=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 h=x(d);if(!h)continue;let y=Date.parse(h.record.updatedAt);!Number.isNaN(y)&&y>i&&(i=y,s=h.record.chatId);}if(s)return s}catch{continue}}return null}}}var Xt=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())}},us=new Xt;export{gs as Button,rs as ContentContainer,ut as CursorController,Ve as FillActiveInput,rn as FloatingChatButton,Qr as HsafaChat,Lo as HsafaProvider,us as componentRegistry,Se as controlCursor,ds as createHsafaArtifactStore,je as getDomComponents,Se as guideCursor,ln as useAutoScroll,br as useChatArtifact,Sr as useChatArtifactVersioning,Ot as useChatStorage,pn as useFileUpload,se as useHsafa,zt as useHsafaActiveChatId,$t as useHsafaAgent,Mr as useHsafaTools,mr as useMessageEditor};//# sourceMappingURL=index.js.map
36
36
  //# sourceMappingURL=index.js.map