@hsafa/ui-sdk 0.4.4 → 0.4.5

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 tt,{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 {createPortal}from'react-dom';import {Plus,History,ChevronRight,Pencil,Trash2,File as File$1,Eye,X as X$1,Download}from'lucide-react';var be={};var Mr=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:i,...p})=>{let c=[be.button,be[e],be[t],n&&be.loading,i].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:r||n,...p,children:[n&&jsx("span",{className:be.spinner}),jsx("span",{className:n?be.hiddenText:void 0,children:o})]})};function Wt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:r}){if(!e)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{i.currentTarget.style.borderColor=n.primaryColor,i.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:i=>{i.currentTarget.style.borderColor=n.borderColor,i.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function _t(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let r=t.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),t}function jt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var qt=createContext(void 0);function ro({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,i]=useState(new Map),[p,c]=useState(new Map),[b,T]=useState(new Map),[h,S]=useState(new Map),[x,k]=useState(void 0),a=useCallback((l,u)=>(i(w=>{let f=new Map(w);return f.set(String(l),u),f}),()=>{i(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});}),[]),v=useCallback((l,u)=>{i(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});},[]),s=useCallback((l,u)=>(c(w=>{let f=new Map(w);return f.set(String(l),u),f}),()=>{c(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});}),[]),d=useCallback((l,u)=>{c(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});},[]),g=useCallback((l,u)=>{T(w=>{let f=new Map(w);return u?f.set(l,true):f.delete(l),f});},[]),y=useCallback((l,u)=>{S(w=>{let f=new Map(w);return f.set(l,u),f});},[]),m=useMemo(()=>Array.from(b.values()).some(l=>l),[b]),I=useMemo(()=>Array.from(h.values()).some(l=>l),[h]),C=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:p,registerAction:a,unregisterAction:v,registerComponent:s,unregisterComponent:d,isAnyStreaming:m,setStreamingState:g,isAnyChatOpen:I,setChatOpenState:y,currentChatId:x,setCurrentChatId:k}),[e,t,n,o,p,a,v,s,d,m,g,I,y,x]);return jsx(qt.Provider,{value:C,children:r})}function re(){let e=useContext(qt);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{}}}var Ct=25*1024*1024;function Kt(e){let{baseUrl:t}=re(),n=e||t||"",[r,o]=useState([]),[i,p]=useState(false),c=useRef(null),b=useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let v=["B","KB","MB","GB","TB"],s=Math.min(v.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${v[s]}`},[]),T=useCallback(async a=>{let v=new FormData;v.append("file",a);let s=await fetch(jt(n,"/api/uploads"),{method:"POST",body:v});if(!s.ok){let g=await s.text().catch(()=>"");throw new Error(g||`Failed to upload ${a.name}`)}let d=await s.json();return {id:d.id,name:d.name||a.name,url:d.url,mimeType:d.mimeType||a.type||"application/octet-stream",size:typeof d.size=="number"?d.size:a.size}},[n]),h=useCallback(a=>{o(v=>v.filter(s=>s.id!==a));},[]),S=useCallback(async(a,v)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);v(null),p(true);let d=[];try{for(let g of s){if(g.size>Ct){v(`"${g.name}" exceeds the ${b(Ct)} limit.`);continue}try{let y=await T(g);d.push(y);}catch(y){console.error("Failed to upload attachment:",y),v(String(y?.message??`Failed to upload ${g.name}`));}}d.length&&o(g=>[...g,...d]);}finally{p(false);}},[T,b]),x=useCallback((a,v)=>{let s=[],d=(a||"").trim();d&&s.push({type:"text",text:d});for(let g of v||[]){let y=g.mimeType||"application/octet-stream";y.startsWith("image/")?s.push({type:"image",image:new URL(g.url),mediaType:y}):s.push({type:"file",data:g.url,mediaType:y,name:g.name});}return s},[]),k=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:i,fileInputRef:c,formatBytes:b,handleRemoveAttachment:h,handleFileSelection:S,buildUserContent:x,clearAttachments:k,setAttachments:o,MAX_UPLOAD_SIZE:Ct}}function Xt(e,t,n){return new DefaultChatTransport({api:`${e}/api/run/${t}`,fetch:async(r,o)=>{let p={...o?.body?JSON.parse(o.body):{},chatId:n};return fetch(r,{...o,body:JSON.stringify(p)})}})}function lo(e){if(!(e instanceof HTMLElement))return true;let t=window.getComputedStyle(e);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&e.offsetParent!==null}function co(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),r=n.querySelector("input, select, textarea");return r&&r.remove(),n.textContent?.trim()}}function vt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function kt(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function uo(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let i=n.className.split(" ").filter(p=>p.trim()).slice(0,2);i.length>0&&(r+="."+i.join("."));}let o=n.parentElement;if(o){let i=Array.from(o.children).filter(p=>p.tagName===n.tagName);if(i.length>1){let p=i.indexOf(n)+1;r+=`:nth-child(${p})`;}}t.unshift(r),n=o;}return t.slice(-3).join(" > ")}async function ze(e={}){try{let{includeHidden:t=!1,selector:n,what:r="content",limit:o}=e,i=document.querySelector(".hsafa-content-container");if(!i)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 p=n&&i.querySelector(n)||i,c=[],b=[];r==="inputs"?b=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:b=["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"],p.querySelectorAll(b.join(", ")).forEach(s=>{let d=lo(s);if(!d&&!t)return;let g={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:d,isInteractive:!0,selector:uo(s)};s instanceof HTMLInputElement?(g.type=s.type,g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=kt(s),g.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,g.disabled=s.disabled,g.required=s.required):s instanceof HTMLTextAreaElement?(g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=kt(s),g.disabled=s.disabled,g.required=s.required):s instanceof HTMLSelectElement?(g.name=s.name||void 0,g.value=kt(s),g.disabled=s.disabled,g.required=s.required,g.options=Array.from(s.options).map(y=>({value:y.value,label:y.text,selected:y.selected,disabled:y.disabled}))):s instanceof HTMLButtonElement?(g.type=s.type,g.disabled=s.disabled,g.text=vt(s)):s instanceof HTMLAnchorElement?(g.href=s.href,g.text=vt(s)):s instanceof HTMLImageElement?(g.text=s.alt||void 0,g.label=s.alt||g.label):g.text=vt(s),g.label=co(s),g.role=s.getAttribute("role")||void 0,g.ariaLabel=s.getAttribute("aria-label")||void 0,c.push(g);});let h=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,d)=>h(d)-h(s));let S=c.length,k=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=S>k,v=a?c.slice(0,k):c;return {ok:!0,components:v,count:v.length,total:S,truncated:a,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=ze);async function Ce(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(r){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:r?.message||String(r)}]}}}typeof window<"u"&&(window.guideCursor=Ce);function Yt(e){return !!e&&e.nodeType===1}function ae(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Jt(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ae(e,"input");}function po(e,t){e.checked!==t&&e.click();}function mo(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(r=>r.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);ae(e,"input"),ae(e,"change");}function go(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(r=>{r.selected=n.has(r.value)||n.has(r.text);}),ae(e,"input"),ae(e,"change");}function fo(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function yo(e,t){let n=Array.isArray(t)?t:[t],r=new DataTransfer;for(let o of n)r.items.add(o);Object.defineProperty(e,"files",{value:r.files,configurable:true}),ae(e,"input"),ae(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&Yt(n)){let r=n.closest('[contenteditable="true"], [contenteditable=""]');r&&(n=r);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let r=n.tagName.toLowerCase();if(r==="input"){let o=n,i=(o.type||"text").toLowerCase();if(i==="checkbox")po(o,!!e);else if(i==="radio"){let p=o.name;if(p&&e!=null&&String(o.value)!==String(e)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(p)}"][value="${CSS.escape(String(e))}"]`);c?c.click():o.click();}else o.click();}else if(i==="file")if(e instanceof File||Array.isArray(e)&&e.every(p=>p instanceof File))yo(o,e);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let p=i==="date"?fo(e):String(e??"");Jt(o,p),ae(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,i=String(e??"");return Jt(o,i),ae(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?go(o,Array.isArray(e)?e:[e]):mo(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(Yt(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(e??""),ae(o,"input"),ae(o,"change"),o.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${r}`}],errors:[`Unsupported active element: ${r}`]}}catch(r){return {ok:false,filled:[{key:"active",status:"error",message:r?.message??String(r)}],errors:[r?.message??String(r)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var We=null,Xe={},Qt=false,Ae=null,Je=false;function wt(e){e.classList.add("visible");}function an(){Je=true,Ae!=null&&(clearTimeout(Ae),Ae=null);}function xo(e,t=1500){Je||(Ae!=null&&clearTimeout(Ae),Ae=window.setTimeout(()=>{Je||e.classList.remove("visible");},t));}function bo(e,t=1200){Je=false,xo(e,t);}function Co(e){let t=[],n=e?.parentElement;for(;n;){let r=getComputedStyle(n),o=r.overflow+r.overflowY+r.overflowX;/(auto|scroll)/.test(o)&&t.push(n),n=n.parentElement;}return t}async function vo(e,t=1500,n=160){let r=performance.now(),o=e?Co(e):[],i=()=>{let h=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(S=>{h.push(S.scrollLeft,S.scrollTop);}),h},p=()=>{if(!e)return {x:0,y:0};let h=e.getBoundingClientRect();return {x:h.left,y:h.top}},c=i(),b=p(),T=performance.now();return new Promise(h=>{function S(x){let k=i(),a=p(),v=false;for(let s=0;s<k.length;s++)if(k[s]!==c[s]){v=true;break}if(!v&&e&&(a.x!==b.x||a.y!==b.y)&&(v=true),v&&(c=k,b=a,T=x),x-T>=n||x-r>=t){h();return}requestAnimationFrame(S);}requestAnimationFrame(S);})}var ko='<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>',wo='<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 To(){if(!Xe.arrow)try{Xe.arrow=ko,Xe.pointer=wo;}catch(e){console.warn("Failed to set cursor SVGs",e);}return Xe}function en({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function Io(){let e="demo-fake-cursor",t=document.getElementById(e),n=await To();if(!Qt){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
1
+ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import nt,{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 {createPortal}from'react-dom';import {Plus,History,ChevronRight,Pencil,Trash2,File as File$1,Eye,X,Download}from'lucide-react';var Ce={};var Er=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:i,...p})=>{let c=[Ce.button,Ce[e],Ce[t],n&&Ce.loading,i].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:r||n,...p,children:[n&&jsx("span",{className:Ce.spinner}),jsx("span",{className:n?Ce.hiddenText:void 0,children:o})]})};function Ot({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:r}){if(!e)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{i.currentTarget.style.borderColor=n.primaryColor,i.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:i=>{i.currentTarget.style.borderColor=n.borderColor,i.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 jt(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let r=t.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),t}function qt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var Vt=createContext(void 0);function so({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,i]=useState(new Map),[p,c]=useState(new Map),[b,T]=useState(new Map),[y,M]=useState(new Map),[x,k]=useState(void 0),a=useCallback((l,u)=>(i(w=>{let f=new Map(w);return f.set(String(l),u),f}),()=>{i(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});}),[]),v=useCallback((l,u)=>{i(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});},[]),s=useCallback((l,u)=>(c(w=>{let f=new Map(w);return f.set(String(l),u),f}),()=>{c(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});}),[]),d=useCallback((l,u)=>{c(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});},[]),g=useCallback((l,u)=>{T(w=>{let f=new Map(w);return u?f.set(l,true):f.delete(l),f});},[]),h=useCallback((l,u)=>{M(w=>{let f=new Map(w);return f.set(l,u),f});},[]),m=useMemo(()=>Array.from(b.values()).some(l=>l),[b]),I=useMemo(()=>Array.from(y.values()).some(l=>l),[y]),C=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:p,registerAction:a,unregisterAction:v,registerComponent:s,unregisterComponent:d,isAnyStreaming:m,setStreamingState:g,isAnyChatOpen:I,setChatOpenState:h,currentChatId:x,setCurrentChatId:k}),[e,t,n,o,p,a,v,s,d,m,g,I,h,x]);return jsx(Vt.Provider,{value:C,children:r})}function re(){let e=useContext(Vt);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{}}}var Ct=25*1024*1024;function Xt(e){let{baseUrl:t}=re(),n=e||t||"",[r,o]=useState([]),[i,p]=useState(false),c=useRef(null),b=useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let v=["B","KB","MB","GB","TB"],s=Math.min(v.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${v[s]}`},[]),T=useCallback(async a=>{let v=new FormData;v.append("file",a);let s=await fetch(qt(n,"/api/uploads"),{method:"POST",body:v});if(!s.ok){let g=await s.text().catch(()=>"");throw new Error(g||`Failed to upload ${a.name}`)}let d=await s.json();return {id:d.id,name:d.name||a.name,url:d.url,mimeType:d.mimeType||a.type||"application/octet-stream",size:typeof d.size=="number"?d.size:a.size}},[n]),y=useCallback(a=>{o(v=>v.filter(s=>s.id!==a));},[]),M=useCallback(async(a,v)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);v(null),p(true);let d=[];try{for(let g of s){if(g.size>Ct){v(`"${g.name}" exceeds the ${b(Ct)} limit.`);continue}try{let h=await T(g);d.push(h);}catch(h){console.error("Failed to upload attachment:",h),v(String(h?.message??`Failed to upload ${g.name}`));}}d.length&&o(g=>[...g,...d]);}finally{p(false);}},[T,b]),x=useCallback((a,v)=>{let s=[],d=(a||"").trim();d&&s.push({type:"text",text:d});for(let g of v||[]){let h=g.mimeType||"application/octet-stream";h.startsWith("image/")?s.push({type:"image",image:new URL(g.url),mediaType:h}):s.push({type:"file",data:g.url,mediaType:h,name:g.name});}return s},[]),k=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:i,fileInputRef:c,formatBytes:b,handleRemoveAttachment:y,handleFileSelection:M,buildUserContent:x,clearAttachments:k,setAttachments:o,MAX_UPLOAD_SIZE:Ct}}function Yt(e,t,n){return new DefaultChatTransport({api:`${e}/api/run/${t}`,fetch:async(r,o)=>{let p={...o?.body?JSON.parse(o.body):{},chatId:n};return fetch(r,{...o,body:JSON.stringify(p)})}})}function uo(e){if(!(e instanceof HTMLElement))return true;let t=window.getComputedStyle(e);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&e.offsetParent!==null}function po(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),r=n.querySelector("input, select, textarea");return r&&r.remove(),n.textContent?.trim()}}function vt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function kt(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function mo(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let i=n.className.split(" ").filter(p=>p.trim()).slice(0,2);i.length>0&&(r+="."+i.join("."));}let o=n.parentElement;if(o){let i=Array.from(o.children).filter(p=>p.tagName===n.tagName);if(i.length>1){let p=i.indexOf(n)+1;r+=`:nth-child(${p})`;}}t.unshift(r),n=o;}return t.slice(-3).join(" > ")}async function Ue(e={}){try{let{includeHidden:t=!1,selector:n,what:r="content",limit:o}=e,i=document.querySelector(".hsafa-content-container");if(!i)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 p=n&&i.querySelector(n)||i,c=[],b=[];r==="inputs"?b=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:b=["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"],p.querySelectorAll(b.join(", ")).forEach(s=>{let d=uo(s);if(!d&&!t)return;let g={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:d,isInteractive:!0,selector:mo(s)};s instanceof HTMLInputElement?(g.type=s.type,g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=kt(s),g.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,g.disabled=s.disabled,g.required=s.required):s instanceof HTMLTextAreaElement?(g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=kt(s),g.disabled=s.disabled,g.required=s.required):s instanceof HTMLSelectElement?(g.name=s.name||void 0,g.value=kt(s),g.disabled=s.disabled,g.required=s.required,g.options=Array.from(s.options).map(h=>({value:h.value,label:h.text,selected:h.selected,disabled:h.disabled}))):s instanceof HTMLButtonElement?(g.type=s.type,g.disabled=s.disabled,g.text=vt(s)):s instanceof HTMLAnchorElement?(g.href=s.href,g.text=vt(s)):s instanceof HTMLImageElement?(g.text=s.alt||void 0,g.label=s.alt||g.label):g.text=vt(s),g.label=po(s),g.role=s.getAttribute("role")||void 0,g.ariaLabel=s.getAttribute("aria-label")||void 0,c.push(g);});let y=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,d)=>y(d)-y(s));let M=c.length,k=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=M>k,v=a?c.slice(0,k):c;return {ok:!0,components:v,count:v.length,total:M,truncated:a,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=Ue);async function ve(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(r){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:r?.message||String(r)}]}}}typeof window<"u"&&(window.guideCursor=ve);function Jt(e){return !!e&&e.nodeType===1}function ae(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Zt(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ae(e,"input");}function go(e,t){e.checked!==t&&e.click();}function fo(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(r=>r.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);ae(e,"input"),ae(e,"change");}function ho(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(r=>{r.selected=n.has(r.value)||n.has(r.text);}),ae(e,"input"),ae(e,"change");}function yo(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function xo(e,t){let n=Array.isArray(t)?t:[t],r=new DataTransfer;for(let o of n)r.items.add(o);Object.defineProperty(e,"files",{value:r.files,configurable:true}),ae(e,"input"),ae(e,"change");}async function We(e,t={}){let n=document.activeElement||null;if(n&&Jt(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,i=(o.type||"text").toLowerCase();if(i==="checkbox")go(o,!!e);else if(i==="radio"){let p=o.name;if(p&&e!=null&&String(o.value)!==String(e)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(p)}"][value="${CSS.escape(String(e))}"]`);c?c.click():o.click();}else o.click();}else if(i==="file")if(e instanceof File||Array.isArray(e)&&e.every(p=>p instanceof File))xo(o,e);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let p=i==="date"?yo(e):String(e??"");Zt(o,p),ae(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,i=String(e??"");return Zt(o,i),ae(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?ho(o,Array.isArray(e)?e:[e]):fo(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(Jt(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(e??""),ae(o,"input"),ae(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=We);var Oe=null,Ye={},en=false,Re=null,Ze=false;function wt(e){e.classList.add("visible");}function sn(){Ze=true,Re!=null&&(clearTimeout(Re),Re=null);}function Co(e,t=1500){Ze||(Re!=null&&clearTimeout(Re),Re=window.setTimeout(()=>{Ze||e.classList.remove("visible");},t));}function vo(e,t=1200){Ze=false,Co(e,t);}function ko(e){let t=[],n=e?.parentElement;for(;n;){let r=getComputedStyle(n),o=r.overflow+r.overflowY+r.overflowX;/(auto|scroll)/.test(o)&&t.push(n),n=n.parentElement;}return t}async function wo(e,t=1500,n=160){let r=performance.now(),o=e?ko(e):[],i=()=>{let y=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(M=>{y.push(M.scrollLeft,M.scrollTop);}),y},p=()=>{if(!e)return {x:0,y:0};let y=e.getBoundingClientRect();return {x:y.left,y:y.top}},c=i(),b=p(),T=performance.now();return new Promise(y=>{function M(x){let k=i(),a=p(),v=false;for(let s=0;s<k.length;s++)if(k[s]!==c[s]){v=true;break}if(!v&&e&&(a.x!==b.x||a.y!==b.y)&&(v=true),v&&(c=k,b=a,T=x),x-T>=n||x-r>=t){y();return}requestAnimationFrame(M);}requestAnimationFrame(M);})}var To='<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>',Io='<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 Mo(){if(!Ye.arrow)try{Ye.arrow=To,Ye.pointer=Io;}catch(e){console.warn("Failed to set cursor SVGs",e);}return Ye}function tn({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function So(){let e="demo-fake-cursor",t=document.getElementById(e),n=await Mo();if(!en){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,19 +8,19 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import tt,{createContext,useRe
8
8
  .fake-cursor.as-pointer .arrow { display: none; }
9
9
  .fake-cursor.as-pointer .pointer { display: block; }
10
10
  .fake-cursor.pressing .pointer svg path { filter: brightness(0.9); }
11
- `,document.head.appendChild(o);}Qt=true;}return t?(t.classList.add("as-arrow"),We||(We=createRoot(t),We.render(jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),We=createRoot(t),We.render(jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Re(e,t,n){return Math.max(t,Math.min(n,e))}function Mo(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function sn(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let r=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!r)return null;let o=r[1].split(/\s*,\s*/).map(Number),[i,p,c,b=1]=o;return {r:i,g:p,b:c,a:b}}function So({r:e,g:t,b:n}){let r=[e,t,n].map(o=>o/255).map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*r[0]+.7152*r[1]+.0722*r[2]}function Eo(e){let t=e?sn(e):null;return !t||t.a===0?false:So(t)<.5}function Ao(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let p=getComputedStyle(n).backgroundColor,c=sn(p);if(c&&c.a>0)return p;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Tt(e,t,n){let r=Ao(t,n),o=Eo(r),i=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=i,c.style.strokeWidth="1";}),e.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function Ye(e,t,n,r,o="ease-in-out",i="curve",p=.25,c="auto",b){an(),wt(e);let T=performance.now(),h=o==="linear"?k=>k:Mo,S=i!=="straight",x={x:0,y:0};if(S){let k=n.x-t.x,a=n.y-t.y,v=Math.hypot(k,a)||1,s=(t.x+n.x)/2,d=(t.y+n.y)/2,g=-a/v,y=k/v,m=1;c==="left"?m=-1:c==="right"?m=1:m=Math.random()<.5?-1:1;let I=Re(p,0,1)*v;x={x:s+m*g*I,y:d+m*y*I};}return new Promise(k=>{function a(v){let s=Re((v-T)/r,0,1),d=h(s),g,y;if(S){let u=1-d;g=u*u*t.x+2*u*d*x.x+d*d*n.x,y=u*u*t.y+2*u*d*x.y+d*d*n.y;}else g=t.x+(n.x-t.x)*d,y=t.y+(n.y-t.y)*d;let I=.35*(1-d),C=Math.sin(v*.02)*I,l=Math.cos(v*.018)*I;e.style.left=`${g+C}px`,e.style.top=`${y+l}px`,Tt(e,g+C,y+l),b&&b({x:g+C,y:y+l,t:s,now:v}),s<1?requestAnimationFrame(a):k();}requestAnimationFrame(a);})}function tn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function de(e,t,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let i=t==="pointerdown"||t==="mousedown",p=t==="pointerup"||t==="mouseup",c={button:0,buttons:i?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let b=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...c});e.dispatchEvent(b);}else {let b=new MouseEvent(t,c);e.dispatchEvent(b);}}catch{let i=new MouseEvent(t,o);e.dispatchEvent(i);}}function ln(e){return e&&typeof e=="object"&&e.nodeType===1}function Ro(e){if(!e)return document;if(ln(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function nn(e){if(ln(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Ro(e.within??null).querySelectorAll(e.selector),r=Math.max(0,Math.min(n.length-1,e.nth??0)),o=n[r]??null;return {kind:o?"element":"position",element:o}}return {kind:"position",point:{x:0,y:0}}}function on(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let r=Re(t.x,0,1),o=Re(t.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function rn(e){return {x:Re(e.x,0,window.innerWidth),y:Re(e.y,0,window.innerHeight)}}function Fo(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await Io();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),wt(o),an();let i=parseFloat(o.style.left||"20")||20,p=parseFloat(o.style.top||"20")||20;Tt(o,i,p);for(let c of n){let{durationMs:b=800,easing:T="ease-in-out",offset:h,highlight:S=true,path:x="curve",curveStrength:k=.25,curveDirection:a="auto",anchor:v,cursorHotspot:s,dragTo:d}=c.options??{},g=c.action??c.options?.action??"none",y=performance.now(),m=nn(c.target),I=null,C=null;if(m.kind==="element"&&m.element?(C=m.element,o.classList.remove("visible"),C.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await vo(C,1500,180),wt(o),I=on(C,v)):m.kind==="position"&&m.point&&(I=m.point),!I){r.push({ok:false,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-y),error:"Target not found"});continue}let l={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},u=rn(tn(I,h));await Ye(o,l,u,b,T,x,k,a);let w=u.x-l.x,f=u.y-l.y,A=Math.hypot(w,f)||1,B=w/A,H=f/A,K=Math.min(6,Math.max(3,A*.02)),R={x:u.x+B*K,y:u.y+H*K};await Ye(o,u,R,Math.max(70,b*.1),"ease-out","straight",0,"right"),await Ye(o,R,u,120,"ease-out","straight",0,"left"),S&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let O=null;try{if(g==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let F={x:s?.x??0,y:s?.y??0},L={x:u.x+F.x,y:u.y+F.y};o.style.left=`${L.x}px`,o.style.top=`${L.y}px`,Tt(o,L.x,L.y);let N=C??document.elementFromPoint(L.x,L.y)??document.body;de(N,"pointerdown",L),de(N,"mousedown",L),await new Promise(G=>setTimeout(G,90)),o.classList.remove("pressing"),de(N,"mouseup",L),de(N,"click",L),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),N instanceof HTMLElement&&N.focus?.(),O=N?.id??null;}else if(g==="drag"){if(!d)throw new Error("dragTo is required for action 'drag'");let F=nn(d),L=null;if(F.kind==="element"&&F.element&&(L=on(F.element,v)),F.kind==="position"&&F.point&&(L=F.point),!L)throw new Error("dragTo target not found");let N=rn(tn(L,h)),G={x:u.x,y:u.y},D=C??document.elementFromPoint(G.x,G.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),de(D,"pointerdown",G),de(D,"mousedown",G),await Ye(o,G,N,Math.max(200,b),T,x,k,a,({x:pe,y:ue})=>{let we=document.elementFromPoint(pe,ue)??document.body,J={x:pe,y:ue};de(we,"pointermove",J),de(we,"mousemove",J);});let Y=document.elementFromPoint(N.x,N.y)??document.body;o.classList.remove("pressing"),de(Y,"pointerup",N),de(Y,"mouseup",N);}r.push({ok:!0,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-y),clickedElementId:O});}catch(F){r.push({ok:false,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-y),error:F?.message??String(F)});}}return bo(o,2e3),{ok:r.every(c=>c.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var Qe=Fo;function cn(){return {getDomComponents:{tool:async({includeHidden:e,selector:t})=>await ze({includeHidden:e,selector:t}),executeEachToken:false},controlCursor:{tool:async({target:e,action:t,anchor:n,durationMs:r,dragTo:o})=>{let i=await Ce(e,{action:t,anchor:n,durationMs:r,dragTo:o});if(i&&i.ok){let p=Array.isArray(i.steps)&&i.steps.length?i.steps[i.steps.length-1]:void 0,c=p?.clickedElementId?` (clicked element id: ${p.clickedElementId})`:"",b=t||p?.action||"none";return {success:true,message:b==="click"?`Cursor moved and clicked successfully${c}`:b==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:i}}return {success:false,message:"Cursor action failed",details:i}},executeEachToken:false},fillActiveInput:{tool:async({value:e})=>{let t=await Ue(e);return {success:!!t?.ok,message:t?.ok?"Active input filled successfully":t?.errors?.[0]||"Failed to fill active input",details:t}},executeEachToken:true},requestInput:{tool:async e=>({ok:true}),executeEachToken:true}}}function pn({chart:e,theme:t}){let n=useRef(null),[r,o]=useState(null),[i,p]=useState(true);useEffect(()=>{let x=true;return (async()=>{try{p(!0),o(null);let a;try{a=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!x)return;if(a.default?.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:{darkMode:t==="dark",primaryColor:t==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:t==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:t==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),n.current&&x){let v=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:s}=await a.default.render(v,e);if(n.current&&x){n.current.innerHTML=s;let d=n.current.querySelector("svg");d&&(d.style.maxWidth="100%",d.style.height="auto",d.style.display="block");}}}catch(a){x&&o(a instanceof Error?a.message:"Failed to render diagram");}finally{x&&p(false);}})(),()=>{x=false;}},[e,t]);let c=t==="dark"?"#374151":"#D1D5DB",b=t==="dark"?"#1F2937":"#F9FAFB",T=t==="dark"?"#7F1D1D":"#FEF2F2",h=t==="dark"?"#FCA5A5":"#DC2626",S=t==="dark"?"#9CA3AF":"#6B7280";return r?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:T,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:h,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:h,opacity:.8},children:r})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:b,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[i&&jsx("div",{style:{fontSize:"14px",color:S,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:i?"none":"block",textAlign:"center",minHeight:i?"0":"50px"}})]})}function se(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fe(e){return e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),e=e.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),e=e.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),e}function Po(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
11
+ `,document.head.appendChild(o);}en=true;}return t?(t.classList.add("as-arrow"),Oe||(Oe=createRoot(t),Oe.render(jsx(tn,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),Oe=createRoot(t),Oe.render(jsx(tn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Fe(e,t,n){return Math.max(t,Math.min(n,e))}function Eo(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function ln(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let r=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!r)return null;let o=r[1].split(/\s*,\s*/).map(Number),[i,p,c,b=1]=o;return {r:i,g:p,b:c,a:b}}function Ao({r:e,g:t,b:n}){let r=[e,t,n].map(o=>o/255).map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*r[0]+.7152*r[1]+.0722*r[2]}function Ro(e){let t=e?ln(e):null;return !t||t.a===0?false:Ao(t)<.5}function Fo(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let p=getComputedStyle(n).backgroundColor,c=ln(p);if(c&&c.a>0)return p;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Tt(e,t,n){let r=Fo(t,n),o=Ro(r),i=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=i,c.style.strokeWidth="1";}),e.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function Je(e,t,n,r,o="ease-in-out",i="curve",p=.25,c="auto",b){sn(),wt(e);let T=performance.now(),y=o==="linear"?k=>k:Eo,M=i!=="straight",x={x:0,y:0};if(M){let k=n.x-t.x,a=n.y-t.y,v=Math.hypot(k,a)||1,s=(t.x+n.x)/2,d=(t.y+n.y)/2,g=-a/v,h=k/v,m=1;c==="left"?m=-1:c==="right"?m=1:m=Math.random()<.5?-1:1;let I=Fe(p,0,1)*v;x={x:s+m*g*I,y:d+m*h*I};}return new Promise(k=>{function a(v){let s=Fe((v-T)/r,0,1),d=y(s),g,h;if(M){let u=1-d;g=u*u*t.x+2*u*d*x.x+d*d*n.x,h=u*u*t.y+2*u*d*x.y+d*d*n.y;}else g=t.x+(n.x-t.x)*d,h=t.y+(n.y-t.y)*d;let I=.35*(1-d),C=Math.sin(v*.02)*I,l=Math.cos(v*.018)*I;e.style.left=`${g+C}px`,e.style.top=`${h+l}px`,Tt(e,g+C,h+l),b&&b({x:g+C,y:h+l,t:s,now:v}),s<1?requestAnimationFrame(a):k();}requestAnimationFrame(a);})}function nn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function de(e,t,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let i=t==="pointerdown"||t==="mousedown",p=t==="pointerup"||t==="mouseup",c={button:0,buttons:i?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let b=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...c});e.dispatchEvent(b);}else {let b=new MouseEvent(t,c);e.dispatchEvent(b);}}catch{let i=new MouseEvent(t,o);e.dispatchEvent(i);}}function cn(e){return e&&typeof e=="object"&&e.nodeType===1}function Lo(e){if(!e)return document;if(cn(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function on(e){if(cn(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Lo(e.within??null).querySelectorAll(e.selector),r=Math.max(0,Math.min(n.length-1,e.nth??0)),o=n[r]??null;return {kind:o?"element":"position",element:o}}return {kind:"position",point:{x:0,y:0}}}function rn(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let r=Fe(t.x,0,1),o=Fe(t.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function an(e){return {x:Fe(e.x,0,window.innerWidth),y:Fe(e.y,0,window.innerHeight)}}function Ho(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await So();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),wt(o),sn();let i=parseFloat(o.style.left||"20")||20,p=parseFloat(o.style.top||"20")||20;Tt(o,i,p);for(let c of n){let{durationMs:b=800,easing:T="ease-in-out",offset:y,highlight:M=true,path:x="curve",curveStrength:k=.25,curveDirection:a="auto",anchor:v,cursorHotspot:s,dragTo:d}=c.options??{},g=c.action??c.options?.action??"none",h=performance.now(),m=on(c.target),I=null,C=null;if(m.kind==="element"&&m.element?(C=m.element,o.classList.remove("visible"),C.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await wo(C,1500,180),wt(o),I=rn(C,v)):m.kind==="position"&&m.point&&(I=m.point),!I){r.push({ok:false,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-h),error:"Target not found"});continue}let l={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},u=an(nn(I,y));await Je(o,l,u,b,T,x,k,a);let w=u.x-l.x,f=u.y-l.y,A=Math.hypot(w,f)||1,B=w/A,H=f/A,j=Math.min(6,Math.max(3,A*.02)),R={x:u.x+B*j,y:u.y+H*j};await Je(o,u,R,Math.max(70,b*.1),"ease-out","straight",0,"right"),await Je(o,R,u,120,"ease-out","straight",0,"left"),M&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let W=null;try{if(g==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let F={x:s?.x??0,y:s?.y??0},L={x:u.x+F.x,y:u.y+F.y};o.style.left=`${L.x}px`,o.style.top=`${L.y}px`,Tt(o,L.x,L.y);let N=C??document.elementFromPoint(L.x,L.y)??document.body;de(N,"pointerdown",L),de(N,"mousedown",L),await new Promise(O=>setTimeout(O,90)),o.classList.remove("pressing"),de(N,"mouseup",L),de(N,"click",L),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),N instanceof HTMLElement&&N.focus?.(),W=N?.id??null;}else if(g==="drag"){if(!d)throw new Error("dragTo is required for action 'drag'");let F=on(d),L=null;if(F.kind==="element"&&F.element&&(L=rn(F.element,v)),F.kind==="position"&&F.point&&(L=F.point),!L)throw new Error("dragTo target not found");let N=an(nn(L,y)),O={x:u.x,y:u.y},D=C??document.elementFromPoint(O.x,O.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),de(D,"pointerdown",O),de(D,"mousedown",O),await Je(o,O,N,Math.max(200,b),T,x,k,a,({x:me,y:ue})=>{let Te=document.elementFromPoint(me,ue)??document.body,Y={x:me,y:ue};de(Te,"pointermove",Y),de(Te,"mousemove",Y);});let K=document.elementFromPoint(N.x,N.y)??document.body;o.classList.remove("pressing"),de(K,"pointerup",N),de(K,"mouseup",N);}r.push({ok:!0,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-h),clickedElementId:W});}catch(F){r.push({ok:false,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-h),error:F?.message??String(F)});}}return vo(o,2e3),{ok:r.every(c=>c.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var et=Ho;function dn(){return {getDomComponents:{tool:async({includeHidden:e,selector:t})=>await Ue({includeHidden:e,selector:t}),executeEachToken:false},controlCursor:{tool:async({target:e,action:t,anchor:n,durationMs:r,dragTo:o})=>{let i=await ve(e,{action:t,anchor:n,durationMs:r,dragTo:o});if(i&&i.ok){let p=Array.isArray(i.steps)&&i.steps.length?i.steps[i.steps.length-1]:void 0,c=p?.clickedElementId?` (clicked element id: ${p.clickedElementId})`:"",b=t||p?.action||"none";return {success:true,message:b==="click"?`Cursor moved and clicked successfully${c}`:b==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:i}}return {success:false,message:"Cursor action failed",details:i}},executeEachToken:false},fillActiveInput:{tool:async({value:e})=>{let t=await We(e);return {success:!!t?.ok,message:t?.ok?"Active input filled successfully":t?.errors?.[0]||"Failed to fill active input",details:t}},executeEachToken:true},requestInput:{tool:async e=>({ok:true}),executeEachToken:true}}}function mn({chart:e,theme:t}){let n=useRef(null),[r,o]=useState(null),[i,p]=useState(true);useEffect(()=>{let x=true;return (async()=>{try{p(!0),o(null);let a;try{a=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!x)return;if(a.default?.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:{darkMode:t==="dark",primaryColor:t==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:t==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:t==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),n.current&&x){let v=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:s}=await a.default.render(v,e);if(n.current&&x){n.current.innerHTML=s;let d=n.current.querySelector("svg");d&&(d.style.maxWidth="100%",d.style.height="auto",d.style.display="block");}}}catch(a){x&&o(a instanceof Error?a.message:"Failed to render diagram");}finally{x&&p(false);}})(),()=>{x=false;}},[e,t]);let c=t==="dark"?"#374151":"#D1D5DB",b=t==="dark"?"#1F2937":"#F9FAFB",T=t==="dark"?"#7F1D1D":"#FEF2F2",y=t==="dark"?"#FCA5A5":"#DC2626",M=t==="dark"?"#9CA3AF":"#6B7280";return r?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:T,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:y,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:y,opacity:.8},children:r})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:b,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[i&&jsx("div",{style:{fontSize:"14px",color:M,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:i?"none":"block",textAlign:"center",minHeight:i?"0":"50px"}})]})}function se(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Le(e){return e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),e=e.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),e=e.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),e}function zo(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
12
12
  `).split(`
13
- `),r="",o=false,i="",p=[],c=false,b=false,T=false,h=t==="dark"?"#374151":"#D1D5DB",x=t==="dark"?"#111827":"#F3F4F6",k=t==="dark"?"#E5E7EB":"#374151",a=t==="dark"?"#374151":"#F3F4F6",v=t==="dark"?"#F9FAFB":"#111827",s=()=>{c&&(r+="</ul>",c=false),b&&(r+="</ol>",b=false);},d=l=>{for(let u=l;u<n.length;u++)if(n[u].trim().length>0)return u;return -1},g=l=>{let u=l.trim(),w=u.startsWith("|")?u.slice(1):u;return (w.endsWith("|")?w.slice(0,-1):w).split("|").map(A=>A.trim())},y=l=>{let u=l.trim();if(!u.startsWith("|"))return false;let w=g(u);return w.length>=2&&w.some(f=>f.length>0)},m=l=>{let u=g(l);return u.length===0?false:u.every(w=>/^:?-{3,}:?$/.test(w))},I=l=>{let u=l.startsWith(":"),w=l.endsWith(":");return u&&w?"center":!u&&w?"right":"left"},C=l=>{let u=l,w=d(u+1);if(w===-1)return {tableHtml:"",endIndex:l};let f=g(n[u]),A=g(n[w]),B=Math.max(f.length,A.length),H=[];for(let F=0;F<B;F++){let L=A[F]||"---";H.push(I(L));}let K=[],R=w+1;for(;R<n.length;){let F=n[R].trim();if(F.length===0){R++;continue}if(!F.startsWith("|"))break;let L=g(n[R]),N=[];for(let G=0;G<B;G++)N.push(L[G]??"");K.push(N),R++;}let O=`<div style="overflow: auto; max-width: 100%; max-height: 60vh; border-radius: 10px; margin: 8px 0;">
14
- <table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;">`;O+="<thead><tr>";for(let F=0;F<B;F++){let L=Fe(se(f[F]??"")),N=H[F],G=F===0,D=F===B-1;O+=`<th style="text-align: ${N}; padding: 10px 12px; border-bottom: 1px solid ${h}; background-color: ${a}; color: ${v}; position: sticky; top: 0; z-index: 1; ${`${G?"border-top-left-radius: 10px;":""}${D?"border-top-right-radius: 10px;":""}`}">${L}</th>`;}O+="</tr></thead>",O+="<tbody>";for(let F of K){O+="<tr>";for(let L=0;L<B;L++){let N=Fe(se(F[L]??"")),G=H[L],D=L===0;O+=`<td style="text-align: ${G}; padding: 10px 12px; border-bottom: 1px solid ${h}; ${D?`border-left: 1px solid ${h};`:""} border-right: 1px solid ${h};">${N}</td>`;}O+="</tr>";}return O+="</tbody></table></div>",{tableHtml:O,endIndex:R-1}};for(let l=0;l<n.length;l++){let u=n[l],w=u.match(/^```\s*(\w+)?\s*$/);if(w){if(!o)s(),o=true,i=w[1]?String(w[1]):"",p=[];else {if(i==="mermaid"){T=true;let H=p.join(`
13
+ `),r="",o=false,i="",p=[],c=false,b=false,T=false,y=t==="dark"?"#374151":"#D1D5DB",x=t==="dark"?"#111827":"#F3F4F6",k=t==="dark"?"#E5E7EB":"#374151",a=t==="dark"?"#374151":"#F3F4F6",v=t==="dark"?"#F9FAFB":"#111827",s=()=>{c&&(r+="</ul>",c=false),b&&(r+="</ol>",b=false);},d=l=>{for(let u=l;u<n.length;u++)if(n[u].trim().length>0)return u;return -1},g=l=>{let u=l.trim(),w=u.startsWith("|")?u.slice(1):u;return (w.endsWith("|")?w.slice(0,-1):w).split("|").map(A=>A.trim())},h=l=>{let u=l.trim();if(!u.startsWith("|"))return false;let w=g(u);return w.length>=2&&w.some(f=>f.length>0)},m=l=>{let u=g(l);return u.length===0?false:u.every(w=>/^:?-{3,}:?$/.test(w))},I=l=>{let u=l.startsWith(":"),w=l.endsWith(":");return u&&w?"center":!u&&w?"right":"left"},C=l=>{let u=l,w=d(u+1);if(w===-1)return {tableHtml:"",endIndex:l};let f=g(n[u]),A=g(n[w]),B=Math.max(f.length,A.length),H=[];for(let F=0;F<B;F++){let L=A[F]||"---";H.push(I(L));}let j=[],R=w+1;for(;R<n.length;){let F=n[R].trim();if(F.length===0){R++;continue}if(!F.startsWith("|"))break;let L=g(n[R]),N=[];for(let O=0;O<B;O++)N.push(L[O]??"");j.push(N),R++;}let W=`<div style="overflow: auto; max-width: 100%; max-height: 60vh; border-radius: 10px; margin: 8px 0;">
14
+ <table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;">`;W+="<thead><tr>";for(let F=0;F<B;F++){let L=Le(se(f[F]??"")),N=H[F],O=F===0,D=F===B-1;W+=`<th style="text-align: ${N}; padding: 10px 12px; border-bottom: 1px solid ${y}; background-color: ${a}; color: ${v}; position: sticky; top: 0; z-index: 1; ${`${O?"border-top-left-radius: 10px;":""}${D?"border-top-right-radius: 10px;":""}`}">${L}</th>`;}W+="</tr></thead>",W+="<tbody>";for(let F of j){W+="<tr>";for(let L=0;L<B;L++){let N=Le(se(F[L]??"")),O=H[L],D=L===0;W+=`<td style="text-align: ${O}; padding: 10px 12px; border-bottom: 1px solid ${y}; ${D?`border-left: 1px solid ${y};`:""} border-right: 1px solid ${y};">${N}</td>`;}W+="</tr>";}return W+="</tbody></table></div>",{tableHtml:W,endIndex:R-1}};for(let l=0;l<n.length;l++){let u=n[l],w=u.match(/^```\s*(\w+)?\s*$/);if(w){if(!o)s(),o=true,i=w[1]?String(w[1]):"",p=[];else {if(i==="mermaid"){T=true;let H=p.join(`
15
15
  `);r+=`<div class="mermaid-placeholder" data-mermaid="${se(H)}"></div>`;}else {let H=se(p.join(`
16
- `)),K=i?`language-${i}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${x}; color: ${k}; border: 1px solid ${h}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${K}">${H}</code></pre>`;}o=false,i="",p=[];}continue}if(o){p.push(u);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(u)){s(),r+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let f=u.match(/^(#{1,6})\s+(.+)$/);if(f){s();let H=f[1].length,K=Fe(se(f[2].trim())),R=H<=2?"18px":H===3?"16px":"14px";r+=`<h${H} style="font-size: ${R}; font-weight: 600; margin: 8px 0 4px 0;">${K}</h${H}>`;continue}if(y(u)){let H=d(l+1);if(H!==-1&&m(n[H])){s();let{tableHtml:K,endIndex:R}=C(l);if(K){r+=K,l=R;continue}}}let A=u.match(/^\s*[-*]\s+(.+)$/),B=u.match(/^\s*\d+\.\s+(.+)$/);if(A){c||(s(),r+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',c=true);let H=Fe(se(A[1]));r+=`<li style="margin: 2px 0;">${H}</li>`;continue}if(B){b||(s(),r+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',b=true);let H=Fe(se(B[1]));r+=`<li style="margin: 2px 0;">${H}</li>`;continue}if(u.trim().length===0)s(),r+='<div style="height: 8px;"></div>';else {s();let H=Fe(se(u));r+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${H}</p>`;}}if(o)if(i==="mermaid"){T=true;let l=p.join(`
16
+ `)),j=i?`language-${i}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${x}; color: ${k}; border: 1px solid ${y}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${j}">${H}</code></pre>`;}o=false,i="",p=[];}continue}if(o){p.push(u);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(u)){s(),r+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let f=u.match(/^(#{1,6})\s+(.+)$/);if(f){s();let H=f[1].length,j=Le(se(f[2].trim())),R=H<=2?"18px":H===3?"16px":"14px";r+=`<h${H} style="font-size: ${R}; font-weight: 600; margin: 8px 0 4px 0;">${j}</h${H}>`;continue}if(h(u)){let H=d(l+1);if(H!==-1&&m(n[H])){s();let{tableHtml:j,endIndex:R}=C(l);if(j){r+=j,l=R;continue}}}let A=u.match(/^\s*[-*]\s+(.+)$/),B=u.match(/^\s*\d+\.\s+(.+)$/);if(A){c||(s(),r+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',c=true);let H=Le(se(A[1]));r+=`<li style="margin: 2px 0;">${H}</li>`;continue}if(B){b||(s(),r+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',b=true);let H=Le(se(B[1]));r+=`<li style="margin: 2px 0;">${H}</li>`;continue}if(u.trim().length===0)s(),r+='<div style="height: 8px;"></div>';else {s();let H=Le(se(u));r+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${H}</p>`;}}if(o)if(i==="mermaid"){T=true;let l=p.join(`
17
17
  `);r+=`<div class="mermaid-placeholder" data-mermaid="${se(l)}"></div>`;}else {let l=se(p.join(`
18
- `)),u=i?`language-${i}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${x}; color: ${k}; border: 1px solid ${h}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${u}">${l}</code></pre>`;}return c&&(r+="</ul>"),b&&(r+="</ol>"),{html:r,hasMermaid:T}}function Oe({content:e,theme:t}){let{html:n,hasMermaid:r}=useMemo(()=>Po(e,t),[e,t]);if(!r)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let o=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),i=[];return o.forEach((p,c)=>{if(p.includes("mermaid-placeholder")){let b=p.match(/data-mermaid="([^"]*)"/);if(b){let T=b[1].replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");i.push(tt.createElement(pn,{key:`mermaid-${c}`,chart:T,theme:t}));}}else p.trim()&&i.push(tt.createElement("div",{key:`html-${c}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:p}}));}),tt.createElement(tt.Fragment,{},...i)}function zo({input:e}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(Oe,{content:e?.text||"",theme:"dark"})})}function gn(){return {plainText:zo}}function fn(e,t,n,r,o,i){let p=n.get(t);if(p){let m=p.parentElement,I=document.querySelector(`[data-get-from-user-host="${t}"]`);if(I&&m!==I){try{m?.removeChild(p);}catch{}I.innerHTML="",I.appendChild(p);}}else {p=document.createElement("div"),p.className="hsafa-inline-form";let m=document.querySelector(`[data-get-from-user-host="${t}"]`);m?(m.innerHTML="",m.appendChild(p)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(p),n.set(t,p);}let c=e?.title||"Provide input",b=e?.description||"",T=e?.submitLabel||"Submit",h=e?.skipLabel||"Skip",S=Array.isArray(e?.fields)?e.fields:e?.label||e?.placeholder?[{id:"value",label:e?.label||"Value",type:"text",placeholder:e?.placeholder||""}]:[],x=r.get(t)||{submitted:false,skipped:false,values:void 0};p.innerHTML="";let k=document.createElement("form");k.style.margin="12px 0",k.style.padding="14px",k.style.border="1px solid var(--hsafa-border, #2A2C33)",k.style.borderRadius="12px",k.style.background="var(--hsafa-card, #121318)",k.style.color="var(--hsafa-text, #EDEEF0)",k.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,k.appendChild(a),b){let m=document.createElement("div");m.style.fontSize="12px",m.style.opacity="0.8",m.style.marginBottom="10px",m.textContent=b,k.appendChild(m);}S.forEach(m=>{let I=document.createElement("div");if(I.style.margin="10px 0",m.label){let f=document.createElement("label");f.style.display="block",f.style.fontSize="12px",f.style.marginBottom="6px",f.style.opacity="0.9",f.textContent=m.label,I.appendChild(f);}let C,l=(m.type||"text").toLowerCase();if(l==="textarea"){let f=document.createElement("textarea");f.placeholder=m.placeholder||"",f.value=m.value??"",f.style.width="100%",f.style.minHeight="72px",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",C=f;}else if(l==="select"&&Array.isArray(m.options)){let f=document.createElement("select");f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",m.options.forEach(A=>{let B=document.createElement("option");B.value=String(A.value),B.text=String(A.label??A.value),f.appendChild(B);}),f.value=m.value??"",C=f;}else if(l==="checkbox"){let f=document.createElement("input");f.type="checkbox",f.checked=!!m.value,f.style.transform="scale(1.1)",C=f;}else {let f=document.createElement("input");f.type=l,f.placeholder=m.placeholder||"",f.value=m.value??"",f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",C=f;}let u=m.id||"value";C.dataset.fieldId=u;let w=x.values&&Object.prototype.hasOwnProperty.call(x.values,u)?x.values[u]:void 0;typeof w<"u"&&(C.type==="checkbox"?C.checked=!!w:C.value=String(w)),(x.submitted||x.skipped)&&(C.setAttribute("disabled","true"),C.style.opacity="0.7"),I.appendChild(C),k.appendChild(I);});let v=String(T).trim(),s=String(h).trim(),d=!!(v||s),g=null,y=null;if(d){let m=document.createElement("div");m.style.display="flex",m.style.gap="8px",m.style.marginTop="10px",g=document.createElement("button"),g.type="submit",g.textContent=v||"Submit",g.style.padding="6px 10px",g.style.borderRadius="8px",g.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",g.style.color="#000000",y=document.createElement("button"),y.type="button",y.textContent=s||"Skip",y.style.padding="6px 10px",y.style.borderRadius="8px",y.style.background="transparent",y.style.border="1px solid var(--hsafa-border, #2A2C33)",y.style.color="inherit",m.appendChild(g),m.appendChild(y),k.appendChild(m);}if(k.onsubmit=m=>{m.preventDefault();let I={};k.querySelectorAll("[data-field-id]").forEach(C=>{let l=C.dataset.fieldId||"value";C.type==="checkbox"?I[l]=C.checked:I[l]=C.value??"";}),r.set(t,{submitted:true,skipped:false,values:I}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:I}}),k.querySelectorAll("[data-field-id]").forEach(C=>{C.disabled=true,C.style.opacity="0.7";}),g&&(g.textContent=`${v||"Submit"} \u2713`,g.style.opacity="0.8",g.disabled=true),y&&(y.disabled=true);},y&&(y.onclick=()=>{r.set(t,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:false,skipped:true}}),k.querySelectorAll("[data-field-id]").forEach(m=>{m.disabled=true,m.style.opacity="0.7";}),y&&(y.textContent=`${s||"Skip"} \u2713`,y.style.opacity="0.8",y.disabled=true),g&&(g.disabled=true);}),x.submitted||x.skipped){let m=document.createElement("div");m.style.marginTop="10px",m.style.fontSize="12px",m.style.display="flex",m.style.alignItems="center",m.style.gap="8px";let I=document.createElement("span");I.style.display="inline-flex",I.style.alignItems="center",I.style.padding="2px 8px",I.style.borderRadius="999px",I.style.fontWeight="600",I.style.fontSize="11px",x.submitted?(I.style.background="rgba(16,185,129,0.15)",I.style.color="#10b981",I.textContent="Submitted"):(I.style.background="rgba(234,179,8,0.15)",I.style.color="#eab308",I.textContent="Skipped"),m.appendChild(I),k.appendChild(m);try{g&&(g.disabled=!0,g.style.opacity="0.8",x.submitted&&(g.textContent=`${v||"Submit"} \u2713`)),y&&(y.disabled=!0,y.style.opacity="0.8",x.skipped&&(y.textContent=`${s||"Skip"} \u2713`));}catch{}}p.appendChild(k);}function yn(e,t,n){let r=useRef(new Map),o=useRef(new Map),i=useRef(t),p=useRef(n);i.current=t,p.current=n,useEffect(()=>{e.forEach(c=>{c.role==="assistant"&&c.parts?.forEach(b=>{if(!b.toolCallId)return;let T=b.toolName;if(!T&&b.type?.startsWith("tool-")&&(T=b.type.replace(/^tool-/,"")),!T)return;let h=i.current[T];if(h&&typeof h=="object"&&h.executeEachToken&&h.tool){let S=b.input||b.args||{},x=JSON.stringify(S),k=r.current.get(b.toolCallId);if(x!==k&&x!=="{}"){r.current.set(b.toolCallId,x);try{if(T==="requestInput")p.current(S,b.toolCallId);else {let v=(o.current.get(b.toolCallId)||0)+1;o.current.set(b.toolCallId,v),v>1&&h.tool({...S,toolCallNumber:v-1});}}catch{}}}});});},[e]);}function Mt(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:i,onFinish:p,onError:c,initialMessages:b=[],onMessagesChange:T,controlledChatId:h,onChatIdChange:S}=e,{baseUrl:x,setCurrentChatId:k}=re(),a=n&&n.length>0?n:x||"",[v,s]=useState(""),[d,g]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),y=h??d,m=useCallback(E=>{h===void 0&&g(E),S&&S(E);},[h,S]);useEffect(()=>{try{k(y);}catch{}return ()=>{try{k(void 0);}catch{}}},[y,k]);let I=useMemo(()=>Xt(a,t,y),[a,t,y]),C=useCallback(E=>{console.log("Message finished:",E);let P=E?.message?.id;if(!P&&Array.isArray(E?.messages))for(let _=E.messages.length-1;_>=0;_--){let z=E.messages[_];if(z&&z.role==="assistant"&&z.id){P=z.id;break}}p?.({...E,chatId:y,assistantMessageId:P});},[p,y]),l=useCallback(E=>{console.error("Chat error:",E),c?.(E);},[c]),u=useMemo(()=>cn(),[]),w=useMemo(()=>({...u,...r}),[u,r]),f=useMemo(()=>gn(),[]),A=useMemo(()=>({...f,...o}),[f,o]),B=useRef(new Map),H=useRef(new Map),K=useCallback(()=>{try{B.current.forEach(E=>{try{E.remove();}catch{}}),B.current.clear(),H.current.clear();}catch{}},[]),R=useCallback((E,P)=>{fn(E,P,B.current,H.current,_=>O.current.addToolResult(_));},[]),O=useRef(null),F=useRef(new Set),L=useCallback((E,P,_)=>{console.error(`UI Error [${P}]:`,_),O.current&&F.current.has(E)&&(F.current.delete(E),O.current.addToolResult({tool:P,toolCallId:E,state:"output-error",errorText:_?.message||String(_)}));},[]),N=useCallback((E,P)=>{O.current&&F.current.has(E)&&(F.current.delete(E),O.current.addToolResult({tool:P,toolCallId:E,output:{status:"ok",rendered:true,component:P,logs:[]}}));},[]),G=useCallback(E=>{let P=w[E];return P?typeof P=="object"&&"tool"in P?P.tool:typeof P=="function"?P:null:null},[w]),D=useChat({transport:I,onFinish:C,onError:l,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:E}){let P=G(E.toolName);if(E.toolName==="requestInput"){try{R(E.input,E.toolCallId);}catch(ee){console.error("requestInput render error",ee);}return}let _=E.toolName==="ui";E?.input;let Q=A&&E.toolName in A;if(_||Q){F.current.add(E.toolCallId);return}if(P)try{let ee=await P(E.input);D.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,output:ee});}catch(ee){D.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,state:"output-error",errorText:ee?.message||String(ee)});}}}),{messages:Y,sendMessage:pe,status:ue,stop:we,error:J}=D;O.current=D,yn(Y,w,R),useEffect(()=>{try{let E=new Set,P=[];if(Y.forEach(_=>{_.role==="assistant"&&(_.parts||[]).forEach(z=>{if((z?.toolName||(typeof z?.type=="string"&&z.type.startsWith("tool-")?String(z.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let ee=z?.toolCallId||"";if(!ee)return;E.add(ee);let q=z?.output;if(q&&(q.submitted||q.skipped||q.values)){let Ie={submitted:!!q.submitted,skipped:!!q.skipped,values:q.values||void 0};H.current.set(ee,Ie);}let xe=z?.input||z?.args||{};P.push({input:xe,toolCallId:ee});});}),B.current.forEach((_,z)=>{if(!E.has(z)){let Q=B.current.get(z);try{Q?.remove();}catch{}B.current.delete(z),H.current.delete(z);}}),P.length>0){let _=requestAnimationFrame(()=>{P.forEach(({input:z,toolCallId:Q})=>{try{R(z,Q);}catch{}});});return ()=>cancelAnimationFrame(_)}}catch{}},[Y,R]),useEffect(()=>{b&&b.length>0&&Y.length===0&&console.log("Initial messages:",b);},[b,Y.length]);let me=ue==="submitted"||ue==="streaming",$e=useCallback(()=>{T&&T(Y,y);},[T,Y,y]),Te=useCallback(async E=>{let P=E?.text!==void 0?E.text:v,_=E?.files||[],z=P.trim();if(!(!z&&_.length===0)&&!me){E?.text===void 0&&s("");try{if(i){let Q={role:"user",content:z,createdAt:Date.now(),chatId:y};i(Q);}await pe({text:z,files:_});}catch(Q){throw console.error("Failed to send message:",Q),Q}}},[v,me,pe,i,y]),Lt=useCallback(()=>{if(me)return;K(),s("");try{D?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;m(E);},[me,D,K,m]),mt=useCallback(E=>{try{D?.setMessages?.(E);}catch{}},[D]);return {input:v,setInput:s,messages:Y,isLoading:me,status:ue,error:J,sendMessage:Te,stop:we,newChat:Lt,setMessages:mt,notifyMessagesChange:$e,chatApi:D,chatId:y,setChatId:m,tools:w,uiComponents:A,formHostRef:B,formStateRef:H,cleanupForms:K,onUISuccess:N,onUIError:L}}function rt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=y=>`${t}.chat.${y}`,o=`${t}.currentChatId`,i=`${t}.showChat`,p=()=>{try{let y=localStorage.getItem(n);return y?JSON.parse(y):[]}catch{return []}},c=y=>{try{localStorage.setItem(n,JSON.stringify(y));}catch{}},b=y=>{try{let m=localStorage.getItem(r(y));return m?JSON.parse(m):null}catch{return null}},T=y=>{try{localStorage.setItem(r(y.id),JSON.stringify(y));}catch{}},h=y=>{let m=p(),I=m.findIndex(C=>C.id===y.id);I>=0?m[I]=y:m.unshift(y),c(m);},S=y=>{let I=p().filter(C=>C.id!==y);c(I);},x=y=>{try{localStorage.removeItem(r(y));}catch{}};return {loadChatsIndex:p,saveChatsIndex:c,loadChat:b,saveChat:T,upsertChatMeta:h,deleteChatMeta:S,deleteChatData:x,deleteChat:y=>{x(y),S(y);},loadShowChatPreference:y=>{try{let m=localStorage.getItem(i);return m!==null?m==="true":y}catch{return y}},saveShowChatPreference:y=>{try{localStorage.setItem(i,String(y));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:y=>{try{localStorage.setItem(o,y);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Et(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:i=true,autoRestore:p=true}=e,c=useMemo(()=>rt(t),[t]),[b,T]=useState([]),[h,S]=useState(null),x=useRef(false),k=useRef(false),a=useCallback(()=>{try{let C=c.loadChatsIndex();T(C);let l=C.find(u=>u.id===n);S(l||null);}catch(C){console.error("Failed to refresh chat list:",C);}},[c,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!p||k.current)){try{c.loadCurrentChatId()&&(x.current=!0);}catch(C){console.error("Failed to restore chat:",C);}k.current=true;}},[c,p]),useEffect(()=>{if(!(!i||r.length===0))if(x.current){if(!o){let C=Date.now();try{c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(l){console.error("Failed to save chat:",l);}}}else {let C=r.find(l=>l.role==="user");if(C){let l="";if(Array.isArray(C.parts)){let f=C.parts.find(A=>A&&A.type==="text");l=f&&typeof f.text=="string"?f.text:"";}let u=(l||"New chat").slice(0,80),w=Date.now();try{c.upsertChatMeta({id:n,title:u,createdAt:w,updatedAt:w}),c.saveChat({id:n,messages:r,agentId:t}),c.saveCurrentChatId(n),x.current=!0,a();}catch(f){console.error("Failed to create chat:",f);}}}},[r,t,n,c,o,i,a]);let v=useRef(false);useEffect(()=>{if(o){v.current=true;return}if(v.current&&i){v.current=false;try{let C=Date.now();c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(C){console.error("Failed to save chat on completion:",C);}}},[o,r,n,t,c,i,a]);let s=useCallback(C=>{try{let l=c.loadChat(C);return l?{id:l.id,messages:l.messages,agentId:l.agentId||t}:null}catch(l){return console.error("Failed to load chat:",l),null}},[c,t]),d=useCallback(()=>{if(r.length!==0)try{let C=Date.now();c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(C){console.error("Failed to save chat:",C);}},[c,n,r,t,a]),g=useCallback(C=>{try{c.deleteChat(C),a();}catch(l){console.error("Failed to delete chat:",l);}},[c,a]),y=useCallback((C,l)=>{if(C!==n)try{x.current=!0,c.saveCurrentChatId(C);let u=c.loadChat(C),w=u&&Array.isArray(u.messages)?u.messages:[];l(w),a();}catch(u){console.error("Failed to switch chat:",u);}},[c,n,a]),m=useCallback(C=>{x.current=false,C();},[]),I=useCallback(C=>{if(!C.trim())return b;let l=C.toLowerCase();return b.filter(u=>u.title.toLowerCase().includes(l))},[b]);return {chatList:b,currentChatMeta:h,refreshChatList:a,loadChat:s,saveCurrentChat:d,deleteChat:g,switchToChat:y,createNewChat:m,searchChats:I,storage:c}}function _o(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:i}=e,{baseUrl:p}=re(),c=i||p||"",[b,T]=useState(null),[h,S]=useState(""),[x,k]=useState([]),[a,v]=useState(false),s=useCallback((C,l,u=[])=>{T(C),S(l),k(u);},[]),d=useCallback(()=>{T(null),S(""),k([]);},[]),g=useCallback(async C=>{if(!n)try{let l=t.findIndex(w=>w.id===C);if(l===-1)return;let u=t.slice(0,l);o(u),await r({text:h.trim(),files:x.map(w=>({type:"file",url:w.url,mediaType:w.mimeType||"application/octet-stream",...w.name?{name:w.name}:{},...w.size?{size:w.size}:{}}))}),d();}catch(l){throw console.error("Failed to save edit:",l),l}},[n,t,r,h,x,o,d]),y=useCallback(C=>b===C,[b]),m=useCallback(async C=>{if(!c){console.warn("baseUrl not provided, cannot upload attachments");return}v(true);try{let l=Array.from(C).map(async w=>{if(w.size>26214400)throw new Error(`${w.name} is too large (max 25MB)`);let f=new FormData;f.append("file",w);let A=await fetch(`${c}/api/upload`,{method:"POST",body:f});if(!A.ok)throw new Error(`Upload failed: ${A.statusText}`);let B=await A.json();return {id:B.url||`${Date.now()}-${Math.random()}`,name:w.name,url:B.url,mimeType:w.type,size:w.size}}),u=await Promise.all(l);k(w=>[...w,...u]);}catch(l){throw console.error("Failed to upload files:",l),l}finally{v(false);}},[c]),I=useCallback(C=>{k(l=>l.filter(u=>u.id!==C));},[]);return {editingMessageId:b,editingText:h,setEditingText:S,editAttachments:x,setEditAttachments:k,editUploading:a,startEdit:s,cancelEdit:d,saveEdit:g,isEditing:y,addEditAttachments:m,removeEditAttachment:I}}function X({IconComponent:e,...t}){return tt.createElement(e,t)}function At({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:i}){return jsx("button",{"aria-label":n,title:i,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:p=>{o||(p.currentTarget.style.backgroundColor=r.hoverBackground,p.currentTarget.style.color=r.textColor);},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function Cn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:i,onToggleHistory:p,onClose:c,historyBtnRef:b,t:T}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsx(At,{icon:jsx(X,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||i();},ariaLabel:T("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:b,"aria-label":T("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:h=>{h.currentTarget.style.backgroundColor=o.hoverBackground,h.currentTarget.style.color=o.textColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=o.mutedTextColor;},onClick:p,children:jsx(X,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(At,{icon:jsx(X,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:T("header.close"),resolvedColors:o})]})]})}var ct=class extends Component{constructor(t){super(t),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(t){return {hasError:true,error:t,errorInfo:null}}componentDidMount(){let{toolCallId:t,toolName:n,onSuccess:r}=this.props;t&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(t,n);},0);}componentDidCatch(t,n){console.error(`UI Component Error (${this.props.componentName}):`,t,n),this.setState({error:t,errorInfo:n});let{toolCallId:r,toolName:o,onError:i}=this.props;r&&o&&i&&i(r,o,t);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:t,componentName:n}=this.props;return jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var Jo=e=>{let t={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return t[e||"output-available"]||t["output-available"]},Zo=e=>{let t=/^(.+?)_([a-f0-9]{6})_(.+)$/,n=e.match(t);if(n){let[,r,,o]=n;return {isMCP:true,mcpName:r.replace(/_/g," "),toolName:o.replace(/_/g," ")}}return {isMCP:false,toolName:e}},Qo=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function vn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:p,onUISuccess:c,addToolResult:b}){let T=[],h=[],S,x,k=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){h.push(a.text),S||(S=a.startDate),x=a.endDate,a.state==="done"&&(k=true);continue}if(a.type==="text"&&typeof a.text=="string"){h.length&&(T.push({type:"reasoning",texts:h,startDate:S,endDate:x,isCompleted:k}),h=[],S=void 0,x=void 0,k=false),T.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let v=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(v||s||a.type==="tool-call"){h.length&&(T.push({type:"reasoning",texts:h,startDate:S,endDate:x,isCompleted:k}),h=[],S=void 0,x=void 0,k=false);let d=String(v?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");d==="requestInput"?T.push({type:"tool",toolName:d,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):T.push({type:"tool",toolName:d,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return h.length&&T.push({type:"reasoning",texts:h,startDate:S,endDate:x,isCompleted:k}),T.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[T.map((a,v)=>{let s=`${t}-${v}`,d=n.has(s);if(a.type==="reasoning"){let l=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",u=a.texts&&a.texts.length>0&&a.texts.some(f=>f.trim().length>0),w=()=>{u&&r(s);};return l&&!u?null:jsx("div",{onClick:w,style:{cursor:u?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:d?"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:[!l&&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:l?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:l?"auto":"200% 100%",backgroundClip:l?"unset":"text",WebkitBackgroundClip:l?"unset":"text",WebkitTextFillColor:l?o.mutedTextColor:"transparent",animation:l?void 0:"shimmer 2s ease-in-out infinite"},children:l?"Finish Thinking":"Thinking"})]}),u&&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:d?"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:d||!l?"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:(!l&&d?a.texts:l?d?a.texts:[]:[a.texts[a.texts.length-1]]).map((f,A)=>jsx("div",{style:{marginBottom:"6px"},children:jsx(Oe,{content:f,theme:"dark"})},`rg-line-${v}-${A}`))}):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")return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(Oe,{content:a.text,theme:"dark"})},s);let{color:g,text:y}=Jo(a.status),m=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 I=i?.[a.toolName||""];if(I)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(ct,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:p,onSuccess:c,children:jsx(I,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:b})})},s);let C=Zo(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:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:g,animation:m?"pulse 1.5s ease-in-out infinite":void 0}}),y]}),C.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:C.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:C.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:Qo(C.toolName)})]})})},s)}),jsx("style",{children:`
18
+ `)),u=i?`language-${i}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${x}; color: ${k}; border: 1px solid ${y}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${u}">${l}</code></pre>`;}return c&&(r+="</ul>"),b&&(r+="</ol>"),{html:r,hasMermaid:T}}function Ge({content:e,theme:t}){let{html:n,hasMermaid:r}=useMemo(()=>zo(e,t),[e,t]);if(!r)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let o=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),i=[];return o.forEach((p,c)=>{if(p.includes("mermaid-placeholder")){let b=p.match(/data-mermaid="([^"]*)"/);if(b){let T=b[1].replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");i.push(nt.createElement(mn,{key:`mermaid-${c}`,chart:T,theme:t}));}}else p.trim()&&i.push(nt.createElement("div",{key:`html-${c}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:p}}));}),nt.createElement(nt.Fragment,{},...i)}function Wo({input:e}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(Ge,{content:e?.text||"",theme:"dark"})})}function fn(){return {plainText:Wo}}function hn(e,t,n,r,o,i){let p=n.get(t);if(p){let m=p.parentElement,I=document.querySelector(`[data-get-from-user-host="${t}"]`);if(I&&m!==I){try{m?.removeChild(p);}catch{}I.innerHTML="",I.appendChild(p);}}else {p=document.createElement("div"),p.className="hsafa-inline-form";let m=document.querySelector(`[data-get-from-user-host="${t}"]`);m?(m.innerHTML="",m.appendChild(p)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(p),n.set(t,p);}let c=e?.title||"Provide input",b=e?.description||"",T=e?.submitLabel||"Submit",y=e?.skipLabel||"Skip",M=Array.isArray(e?.fields)?e.fields:e?.label||e?.placeholder?[{id:"value",label:e?.label||"Value",type:"text",placeholder:e?.placeholder||""}]:[],x=r.get(t)||{submitted:false,skipped:false,values:void 0};p.innerHTML="";let k=document.createElement("form");k.style.margin="12px 0",k.style.padding="14px",k.style.border="1px solid var(--hsafa-border, #2A2C33)",k.style.borderRadius="12px",k.style.background="var(--hsafa-card, #121318)",k.style.color="var(--hsafa-text, #EDEEF0)",k.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,k.appendChild(a),b){let m=document.createElement("div");m.style.fontSize="12px",m.style.opacity="0.8",m.style.marginBottom="10px",m.textContent=b,k.appendChild(m);}M.forEach(m=>{let I=document.createElement("div");if(I.style.margin="10px 0",m.label){let f=document.createElement("label");f.style.display="block",f.style.fontSize="12px",f.style.marginBottom="6px",f.style.opacity="0.9",f.textContent=m.label,I.appendChild(f);}let C,l=(m.type||"text").toLowerCase();if(l==="textarea"){let f=document.createElement("textarea");f.placeholder=m.placeholder||"",f.value=m.value??"",f.style.width="100%",f.style.minHeight="72px",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",C=f;}else if(l==="select"&&Array.isArray(m.options)){let f=document.createElement("select");f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",m.options.forEach(A=>{let B=document.createElement("option");B.value=String(A.value),B.text=String(A.label??A.value),f.appendChild(B);}),f.value=m.value??"",C=f;}else if(l==="checkbox"){let f=document.createElement("input");f.type="checkbox",f.checked=!!m.value,f.style.transform="scale(1.1)",C=f;}else {let f=document.createElement("input");f.type=l,f.placeholder=m.placeholder||"",f.value=m.value??"",f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",C=f;}let u=m.id||"value";C.dataset.fieldId=u;let w=x.values&&Object.prototype.hasOwnProperty.call(x.values,u)?x.values[u]:void 0;typeof w<"u"&&(C.type==="checkbox"?C.checked=!!w:C.value=String(w)),(x.submitted||x.skipped)&&(C.setAttribute("disabled","true"),C.style.opacity="0.7"),I.appendChild(C),k.appendChild(I);});let v=String(T).trim(),s=String(y).trim(),d=!!(v||s),g=null,h=null;if(d){let m=document.createElement("div");m.style.display="flex",m.style.gap="8px",m.style.marginTop="10px",g=document.createElement("button"),g.type="submit",g.textContent=v||"Submit",g.style.padding="6px 10px",g.style.borderRadius="8px",g.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",g.style.color="#000000",h=document.createElement("button"),h.type="button",h.textContent=s||"Skip",h.style.padding="6px 10px",h.style.borderRadius="8px",h.style.background="transparent",h.style.border="1px solid var(--hsafa-border, #2A2C33)",h.style.color="inherit",m.appendChild(g),m.appendChild(h),k.appendChild(m);}if(k.onsubmit=m=>{m.preventDefault();let I={};k.querySelectorAll("[data-field-id]").forEach(C=>{let l=C.dataset.fieldId||"value";C.type==="checkbox"?I[l]=C.checked:I[l]=C.value??"";}),r.set(t,{submitted:true,skipped:false,values:I}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:I}}),k.querySelectorAll("[data-field-id]").forEach(C=>{C.disabled=true,C.style.opacity="0.7";}),g&&(g.textContent=`${v||"Submit"} \u2713`,g.style.opacity="0.8",g.disabled=true),h&&(h.disabled=true);},h&&(h.onclick=()=>{r.set(t,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:false,skipped:true}}),k.querySelectorAll("[data-field-id]").forEach(m=>{m.disabled=true,m.style.opacity="0.7";}),h&&(h.textContent=`${s||"Skip"} \u2713`,h.style.opacity="0.8",h.disabled=true),g&&(g.disabled=true);}),x.submitted||x.skipped){let m=document.createElement("div");m.style.marginTop="10px",m.style.fontSize="12px",m.style.display="flex",m.style.alignItems="center",m.style.gap="8px";let I=document.createElement("span");I.style.display="inline-flex",I.style.alignItems="center",I.style.padding="2px 8px",I.style.borderRadius="999px",I.style.fontWeight="600",I.style.fontSize="11px",x.submitted?(I.style.background="rgba(16,185,129,0.15)",I.style.color="#10b981",I.textContent="Submitted"):(I.style.background="rgba(234,179,8,0.15)",I.style.color="#eab308",I.textContent="Skipped"),m.appendChild(I),k.appendChild(m);try{g&&(g.disabled=!0,g.style.opacity="0.8",x.submitted&&(g.textContent=`${v||"Submit"} \u2713`)),h&&(h.disabled=!0,h.style.opacity="0.8",x.skipped&&(h.textContent=`${s||"Skip"} \u2713`));}catch{}}p.appendChild(k);}function yn(e,t,n){let r=useRef(new Map),o=useRef(new Map),i=useRef(t),p=useRef(n);i.current=t,p.current=n,useEffect(()=>{e.forEach(c=>{c.role==="assistant"&&c.parts?.forEach(b=>{if(!b.toolCallId)return;let T=b.toolName;if(!T&&b.type?.startsWith("tool-")&&(T=b.type.replace(/^tool-/,"")),!T)return;let y=i.current[T];if(y&&typeof y=="object"&&y.executeEachToken&&y.tool){let M=b.input||b.args||{},x=JSON.stringify(M),k=r.current.get(b.toolCallId);if(x!==k&&x!=="{}"){r.current.set(b.toolCallId,x);try{if(T==="requestInput")p.current(M,b.toolCallId);else {let v=(o.current.get(b.toolCallId)||0)+1;o.current.set(b.toolCallId,v),v>1&&y.tool({...M,toolCallNumber:v-1});}}catch{}}}});});},[e]);}function Mt(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:i,onFinish:p,onError:c,initialMessages:b=[],onMessagesChange:T,controlledChatId:y,onChatIdChange:M}=e,{baseUrl:x,setCurrentChatId:k}=re(),a=n&&n.length>0?n:x||"",[v,s]=useState(""),[d,g]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),h=y??d,m=useCallback(E=>{y===void 0&&g(E),M&&M(E);},[y,M]);useEffect(()=>{try{k(h);}catch{}return ()=>{try{k(void 0);}catch{}}},[h,k]);let I=useMemo(()=>Yt(a,t,h),[a,t,h]),C=useCallback(E=>{console.log("Message finished:",E);let P=E?.message?.id;if(!P&&Array.isArray(E?.messages))for(let G=E.messages.length-1;G>=0;G--){let z=E.messages[G];if(z&&z.role==="assistant"&&z.id){P=z.id;break}}p?.({...E,chatId:h,assistantMessageId:P});},[p,h]),l=useCallback(E=>{console.error("Chat error:",E),c?.(E);},[c]),u=useMemo(()=>dn(),[]),w=useMemo(()=>({...u,...r}),[u,r]),f=useMemo(()=>fn(),[]),A=useMemo(()=>({...f,...o}),[f,o]),B=useRef(new Map),H=useRef(new Map),j=useCallback(()=>{try{B.current.forEach(E=>{try{E.remove();}catch{}}),B.current.clear(),H.current.clear();}catch{}},[]),R=useCallback((E,P)=>{hn(E,P,B.current,H.current,G=>W.current.addToolResult(G));},[]),W=useRef(null),F=useRef(new Set),L=useCallback((E,P,G)=>{console.error(`UI Error [${P}]:`,G),W.current&&F.current.has(E)&&(F.current.delete(E),W.current.addToolResult({tool:P,toolCallId:E,state:"output-error",errorText:G?.message||String(G)}));},[]),N=useCallback((E,P)=>{W.current&&F.current.has(E)&&(F.current.delete(E),W.current.addToolResult({tool:P,toolCallId:E,output:{status:"ok",rendered:true,component:P,logs:[]}}));},[]),O=useCallback(E=>{let P=w[E];return P?typeof P=="object"&&"tool"in P?P.tool:typeof P=="function"?P:null:null},[w]),D=useChat({transport:I,onFinish:C,onError:l,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:E}){let P=O(E.toolName);if(E.toolName==="requestInput"){try{R(E.input,E.toolCallId);}catch(ee){console.error("requestInput render error",ee);}return}let G=E.toolName==="ui";E?.input;let Q=A&&E.toolName in A;if(G||Q){F.current.add(E.toolCallId);return}if(P)try{let ee=await P(E.input);D.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,output:ee});}catch(ee){D.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,state:"output-error",errorText:ee?.message||String(ee)});}}}),{messages:K,sendMessage:me,status:ue,stop:Te,error:Y}=D;W.current=D,yn(K,w,R),useEffect(()=>{try{let E=new Set,P=[];if(K.forEach(G=>{G.role==="assistant"&&(G.parts||[]).forEach(z=>{if((z?.toolName||(typeof z?.type=="string"&&z.type.startsWith("tool-")?String(z.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let ee=z?.toolCallId||"";if(!ee)return;E.add(ee);let _=z?.output;if(_&&(_.submitted||_.skipped||_.values)){let Me={submitted:!!_.submitted,skipped:!!_.skipped,values:_.values||void 0};H.current.set(ee,Me);}let be=z?.input||z?.args||{};P.push({input:be,toolCallId:ee});});}),B.current.forEach((G,z)=>{if(!E.has(z)){let Q=B.current.get(z);try{Q?.remove();}catch{}B.current.delete(z),H.current.delete(z);}}),P.length>0){let G=requestAnimationFrame(()=>{P.forEach(({input:z,toolCallId:Q})=>{try{R(z,Q);}catch{}});});return ()=>cancelAnimationFrame(G)}}catch{}},[K,R]),useEffect(()=>{b&&b.length>0&&K.length===0&&console.log("Initial messages:",b);},[b,K.length]);let ge=ue==="submitted"||ue==="streaming",Be=useCallback(()=>{T&&T(K,h);},[T,K,h]),Ie=useCallback(async E=>{let P=E?.text!==void 0?E.text:v,G=E?.files||[],z=P.trim();if(!(!z&&G.length===0)&&!ge){E?.text===void 0&&s("");try{if(i){let Q={role:"user",content:z,createdAt:Date.now(),chatId:h};i(Q);}await me({text:z,files:G});}catch(Q){throw console.error("Failed to send message:",Q),Q}}},[v,ge,me,i,h]),Lt=useCallback(()=>{if(ge)return;j(),s("");try{D?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;m(E);},[ge,D,j,m]),gt=useCallback(E=>{try{D?.setMessages?.(E);}catch{}},[D]);return {input:v,setInput:s,messages:K,isLoading:ge,status:ue,error:Y,sendMessage:Ie,stop:Te,newChat:Lt,setMessages:gt,notifyMessagesChange:Be,chatApi:D,chatId:h,setChatId:m,tools:w,uiComponents:A,formHostRef:B,formStateRef:H,cleanupForms:j,onUISuccess:N,onUIError:L}}function at(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=h=>`${t}.chat.${h}`,o=`${t}.currentChatId`,i=`${t}.showChat`,p=()=>{try{let h=localStorage.getItem(n);return h?JSON.parse(h):[]}catch{return []}},c=h=>{try{localStorage.setItem(n,JSON.stringify(h));}catch{}},b=h=>{try{let m=localStorage.getItem(r(h));return m?JSON.parse(m):null}catch{return null}},T=h=>{try{localStorage.setItem(r(h.id),JSON.stringify(h));}catch{}},y=h=>{let m=p(),I=m.findIndex(C=>C.id===h.id);I>=0?m[I]=h:m.unshift(h),c(m);},M=h=>{let I=p().filter(C=>C.id!==h);c(I);},x=h=>{try{localStorage.removeItem(r(h));}catch{}};return {loadChatsIndex:p,saveChatsIndex:c,loadChat:b,saveChat:T,upsertChatMeta:y,deleteChatMeta:M,deleteChatData:x,deleteChat:h=>{x(h),M(h);},loadShowChatPreference:h=>{try{let m=localStorage.getItem(i);return m!==null?m==="true":h}catch{return h}},saveShowChatPreference:h=>{try{localStorage.setItem(i,String(h));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:h=>{try{localStorage.setItem(o,h);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Et(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:i=true,autoRestore:p=true}=e,c=useMemo(()=>at(t),[t]),[b,T]=useState([]),[y,M]=useState(null),x=useRef(false),k=useRef(false),a=useCallback(()=>{try{let C=c.loadChatsIndex();T(C);let l=C.find(u=>u.id===n);M(l||null);}catch(C){console.error("Failed to refresh chat list:",C);}},[c,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!p||k.current)){try{c.loadCurrentChatId()&&(x.current=!0);}catch(C){console.error("Failed to restore chat:",C);}k.current=true;}},[c,p]),useEffect(()=>{if(!(!i||r.length===0))if(x.current){if(!o){let C=Date.now();try{c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(l){console.error("Failed to save chat:",l);}}}else {let C=r.find(l=>l.role==="user");if(C){let l="";if(Array.isArray(C.parts)){let f=C.parts.find(A=>A&&A.type==="text");l=f&&typeof f.text=="string"?f.text:"";}let u=(l||"New chat").slice(0,80),w=Date.now();try{c.upsertChatMeta({id:n,title:u,createdAt:w,updatedAt:w}),c.saveChat({id:n,messages:r,agentId:t}),c.saveCurrentChatId(n),x.current=!0,a();}catch(f){console.error("Failed to create chat:",f);}}}},[r,t,n,c,o,i,a]);let v=useRef(false);useEffect(()=>{if(o){v.current=true;return}if(v.current&&i){v.current=false;try{let C=Date.now();c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(C){console.error("Failed to save chat on completion:",C);}}},[o,r,n,t,c,i,a]);let s=useCallback(C=>{try{let l=c.loadChat(C);return l?{id:l.id,messages:l.messages,agentId:l.agentId||t}:null}catch(l){return console.error("Failed to load chat:",l),null}},[c,t]),d=useCallback(()=>{if(r.length!==0)try{let C=Date.now();c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(C){console.error("Failed to save chat:",C);}},[c,n,r,t,a]),g=useCallback(C=>{try{c.deleteChat(C),a();}catch(l){console.error("Failed to delete chat:",l);}},[c,a]),h=useCallback((C,l)=>{if(C!==n)try{x.current=!0,c.saveCurrentChatId(C);let u=c.loadChat(C),w=u&&Array.isArray(u.messages)?u.messages:[];l(w),a();}catch(u){console.error("Failed to switch chat:",u);}},[c,n,a]),m=useCallback(C=>{x.current=false,C();},[]),I=useCallback(C=>{if(!C.trim())return b;let l=C.toLowerCase();return b.filter(u=>u.title.toLowerCase().includes(l))},[b]);return {chatList:b,currentChatMeta:y,refreshChatList:a,loadChat:s,saveCurrentChat:d,deleteChat:g,switchToChat:h,createNewChat:m,searchChats:I,storage:c}}function qo(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:i}=e,{baseUrl:p}=re(),c=i||p||"",[b,T]=useState(null),[y,M]=useState(""),[x,k]=useState([]),[a,v]=useState(false),s=useCallback((C,l,u=[])=>{T(C),M(l),k(u);},[]),d=useCallback(()=>{T(null),M(""),k([]);},[]),g=useCallback(async C=>{if(!n)try{let l=t.findIndex(w=>w.id===C);if(l===-1)return;let u=t.slice(0,l);o(u),await r({text:y.trim(),files:x.map(w=>({type:"file",url:w.url,mediaType:w.mimeType||"application/octet-stream",...w.name?{name:w.name}:{},...w.size?{size:w.size}:{}}))}),d();}catch(l){throw console.error("Failed to save edit:",l),l}},[n,t,r,y,x,o,d]),h=useCallback(C=>b===C,[b]),m=useCallback(async C=>{if(!c){console.warn("baseUrl not provided, cannot upload attachments");return}v(true);try{let l=Array.from(C).map(async w=>{if(w.size>26214400)throw new Error(`${w.name} is too large (max 25MB)`);let f=new FormData;f.append("file",w);let A=await fetch(`${c}/api/upload`,{method:"POST",body:f});if(!A.ok)throw new Error(`Upload failed: ${A.statusText}`);let B=await A.json();return {id:B.url||`${Date.now()}-${Math.random()}`,name:w.name,url:B.url,mimeType:w.type,size:w.size}}),u=await Promise.all(l);k(w=>[...w,...u]);}catch(l){throw console.error("Failed to upload files:",l),l}finally{v(false);}},[c]),I=useCallback(C=>{k(l=>l.filter(u=>u.id!==C));},[]);return {editingMessageId:b,editingText:y,setEditingText:M,editAttachments:x,setEditAttachments:k,editUploading:a,startEdit:s,cancelEdit:d,saveEdit:g,isEditing:h,addEditAttachments:m,removeEditAttachment:I}}function V({IconComponent:e,...t}){return nt.createElement(e,t)}function At({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:i}){return jsx("button",{"aria-label":n,title:i,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:p=>{o||(p.currentTarget.style.backgroundColor=r.hoverBackground,p.currentTarget.style.color=r.textColor);},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function vn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:i,onToggleHistory:p,onClose:c,historyBtnRef:b,t:T}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsx(At,{icon:jsx(V,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||i();},ariaLabel:T("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:b,"aria-label":T("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:y=>{y.currentTarget.style.backgroundColor=o.hoverBackground,y.currentTarget.style.color=o.textColor;},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color=o.mutedTextColor;},onClick:p,children:jsx(V,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(At,{icon:jsx(V,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:T("header.close"),resolvedColors:o})]})]})}var dt=class extends Component{constructor(t){super(t),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(t){return {hasError:true,error:t,errorInfo:null}}componentDidMount(){let{toolCallId:t,toolName:n,onSuccess:r}=this.props;t&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(t,n);},0);}componentDidCatch(t,n){console.error(`UI Component Error (${this.props.componentName}):`,t,n),this.setState({error:t,errorInfo:n});let{toolCallId:r,toolName:o,onError:i}=this.props;r&&o&&i&&i(r,o,t);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:t,componentName:n}=this.props;return jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var Qo=e=>{let t={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return t[e||"output-available"]||t["output-available"]},er=e=>{let t=/^(.+?)_([a-f0-9]{6})_(.+)$/,n=e.match(t);if(n){let[,r,,o]=n;return {isMCP:true,mcpName:r.replace(/_/g," "),toolName:o.replace(/_/g," ")}}return {isMCP:false,toolName:e}},tr=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function kn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:p,onUISuccess:c,addToolResult:b}){let T=[],y=[],M,x,k=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){y.push(a.text),M||(M=a.startDate),x=a.endDate,a.state==="done"&&(k=true);continue}if(a.type==="text"&&typeof a.text=="string"){y.length&&(T.push({type:"reasoning",texts:y,startDate:M,endDate:x,isCompleted:k}),y=[],M=void 0,x=void 0,k=false),T.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let v=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(v||s||a.type==="tool-call"){y.length&&(T.push({type:"reasoning",texts:y,startDate:M,endDate:x,isCompleted:k}),y=[],M=void 0,x=void 0,k=false);let d=String(v?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");d==="requestInput"?T.push({type:"tool",toolName:d,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):T.push({type:"tool",toolName:d,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return y.length&&T.push({type:"reasoning",texts:y,startDate:M,endDate:x,isCompleted:k}),T.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[T.map((a,v)=>{let s=`${t}-${v}`,d=n.has(s);if(a.type==="reasoning"){let l=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",u=a.texts&&a.texts.length>0&&a.texts.some(f=>f.trim().length>0),w=()=>{u&&r(s);};return l&&!u?null:jsx("div",{onClick:w,style:{cursor:u?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:d?"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:[!l&&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:l?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:l?"auto":"200% 100%",backgroundClip:l?"unset":"text",WebkitBackgroundClip:l?"unset":"text",WebkitTextFillColor:l?o.mutedTextColor:"transparent",animation:l?void 0:"shimmer 2s ease-in-out infinite"},children:l?"Finish Thinking":"Thinking"})]}),u&&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:d?"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:d||!l?"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:(!l&&d?a.texts:l?d?a.texts:[]:[a.texts[a.texts.length-1]]).map((f,A)=>jsx("div",{style:{marginBottom:"6px"},children:jsx(Ge,{content:f,theme:"dark"})},`rg-line-${v}-${A}`))}):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")return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(Ge,{content:a.text,theme:"dark"})},s);let{color:g,text:h}=Qo(a.status),m=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 I=i?.[a.toolName||""];if(I)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(dt,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:p,onSuccess:c,children:jsx(I,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:b})})},s);let C=er(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:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:g,animation:m?"pulse 1.5s ease-in-out infinite":void 0}}),h]}),C.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:C.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:C.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:tr(C.toolName)})]})})},s)}),jsx("style",{children:`
19
19
  @keyframes shimmer {
20
20
  0% { background-position: -200% 0; }
21
21
  100% { background-position: 200% 0; }
22
22
  }
23
- `})]}):null}function kn(e){if(!e||Number.isNaN(e))return "0 B";let t=["B","KB","MB","GB","TB"],n=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return `${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function wn({attachment:e,resolvedColors:t,mode:n,onRemove:r,maxWidth:o="200px"}){let i=e.mimeType?.startsWith("image/"),p=n==="editable"||n==="input",c=n==="viewable",b={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:c?"pointer":"default",maxWidth:n==="input"?"140px":o,position:"relative"},T=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:i?"transparent":t.accentColor,flexShrink:0},children:[i?jsx("img",{src:e.url,alt:e.name,style:{width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",objectFit:"cover"},onError:h=>{h.target.style.display="none";let S=h.target.nextElementSibling;S&&(S.style.display="block");}}):null,jsx(X,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:i?"none":"block",color:t.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:kn(e.size)})]}),n==="input"&&i&&jsx("button",{onClick:h=>{h.stopPropagation(),window.open(e.url,"_blank");},style:{background:"none",border:"none",color:t.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:h=>{h.currentTarget.style.backgroundColor=t.hoverBackground,h.currentTarget.style.color=t.textColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=t.mutedTextColor;},children:jsx(X,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),p&&r&&jsx("button",{onClick:h=>{h.stopPropagation(),r(e.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:t.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="#ef444420",h.currentTarget.style.color="#ef4444";},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=t.mutedTextColor;},children:jsx(X,{IconComponent:X$1,size:"12",strokeWidth:"2"})}),c&&jsx(X,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...b,textDecoration:"none"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor=t.hoverBackground,h.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor=t.inputBackground,h.currentTarget.style.borderColor=t.borderColor;},children:T}):jsx("div",{style:b,children:T})}function In({attachments:e,resolvedColors:t,onRemove:n}){if(!Array.isArray(e)||e.length===0)return null;let r=typeof n=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(o=>jsx(wn,{attachment:o,resolvedColors:t,mode:r,onRemove:n},o.id))})}function Mn({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:i,onUserMessageClick:p,HsafaUI:c,onUIError:b,onUISuccess:T,addToolResult:h,editableMessageIcon:S}){return jsxs(Fragment,{children:[jsx("style",{children:`
23
+ `})]}):null}function wn(e){if(!e||Number.isNaN(e))return "0 B";let t=["B","KB","MB","GB","TB"],n=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return `${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function Tn({attachment:e,resolvedColors:t,mode:n,onRemove:r,maxWidth:o="200px"}){let i=e.mimeType?.startsWith("image/"),p=n==="editable"||n==="input",c=n==="viewable",b={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:c?"pointer":"default",maxWidth:n==="input"?"140px":o,position:"relative"},T=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:i?"transparent":t.accentColor,flexShrink:0},children:[i?jsx("img",{src:e.url,alt:e.name,style:{width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",objectFit:"cover"},onError:y=>{y.target.style.display="none";let M=y.target.nextElementSibling;M&&(M.style.display="block");}}):null,jsx(V,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:i?"none":"block",color:t.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:wn(e.size)})]}),n==="input"&&i&&jsx("button",{onClick:y=>{y.stopPropagation(),window.open(e.url,"_blank");},style:{background:"none",border:"none",color:t.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:y=>{y.currentTarget.style.backgroundColor=t.hoverBackground,y.currentTarget.style.color=t.textColor;},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color=t.mutedTextColor;},children:jsx(V,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),p&&r&&jsx("button",{onClick:y=>{y.stopPropagation(),r(e.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:t.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="#ef444420",y.currentTarget.style.color="#ef4444";},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color=t.mutedTextColor;},children:jsx(V,{IconComponent:X,size:"12",strokeWidth:"2"})}),c&&jsx(V,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...b,textDecoration:"none"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor=t.hoverBackground,y.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:y=>{y.currentTarget.style.backgroundColor=t.inputBackground,y.currentTarget.style.borderColor=t.borderColor;},children:T}):jsx("div",{style:b,children:T})}function Mn({attachments:e,resolvedColors:t,onRemove:n}){if(!Array.isArray(e)||e.length===0)return null;let r=typeof n=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(o=>jsx(Tn,{attachment:o,resolvedColors:t,mode:r,onRemove:n},o.id))})}function Sn({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:i,onUserMessageClick:p,HsafaUI:c,onUIError:b,onUISuccess:T,addToolResult:y,editableMessageIcon:M}){return jsxs(Fragment,{children:[jsx("style",{children:`
24
24
  @keyframes jumpingDots {
25
25
  0%, 80%, 100% {
26
26
  transform: translateY(0);
@@ -30,14 +30,14 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import tt,{createContext,useRe
30
30
  }
31
31
  }
32
32
  `}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((x,k)=>{let a=Array.isArray(x.parts)?x.parts:[],v=a.filter(d=>d.type==="text").map(d=>d&&typeof d.text=="string"?d.text:"").join(`
33
- `),s=a.filter(d=>d.type==="file"||d.type==="image").map(d=>{if(d.type==="image"){let g=typeof d.image=="string"?d.image:d.image?.toString?.()||"";return {id:g||`${x.id}-img-${Date.now()}`,name:d.name||"image",url:g,mimeType:d.mediaType||"image/jpeg",size:d.size||0}}else return {id:d.url||`${x.id}-file-${Date.now()}`,name:d.name||"file",url:d.url||"",mimeType:d.mediaType||"application/octet-stream",size:d.size||0}});return jsx("div",{style:{padding:"0 4px"},children:x.role==="user"?jsx("div",{children:jsx("div",{title:i("editor.clickToEdit"),onClick:()=>p(x,x.id,v,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:d=>d.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor=o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[v,s.length>0&&jsx(In,{attachments:s,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(X,{IconComponent:S||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(vn,{parts:a,messageId:x.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:b,onUISuccess:T,addToolResult:h})},x.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function Sn({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:i,attachments:p,formatBytes:c,handleRemoveAttachment:b,onFileInputChange:T,onSend:h,onStop:S,status:x,t:k,resolvedColors:a}){let v=x==="streaming"||x==="submitted",s=p.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[p.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:p.map(d=>{let g=d.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:g?"transparent":a.cardBackground},children:g?jsx("img",{src:d.url,alt:d.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:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:d.name}),jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(d.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[g&&jsx("a",{href:d.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:k("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:()=>b(d.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:k("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"})]})})]})]},d.id)})}),i&&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:k("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:k("input.placeholder"),value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),h());},disabled:o||i,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:T,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||i,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||i?.5:1},"aria-label":k("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:S,disabled:!v,"aria-label":k("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:v?1:.4,cursor:v?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{v&&(d.currentTarget.style.backgroundColor="#ef444430",d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ef444420",d.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:h,disabled:!s||i,"aria-label":k("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||i?a.mutedTextColor:a.primaryColor,cursor:!s||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||i?.5:1},onMouseEnter:d=>{s&&!i&&(d.currentTarget.style.borderColor=a.primaryColor,d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.borderColor=a.borderColor,d.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 En(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let r=Math.floor(n/60);if(r<60)return `${r}m`;let o=Math.floor(r/60);if(o<24)return `${o}h`;let i=Math.floor(o/24);if(i<7)return `${i}d`;let p=Math.floor(i/7);if(p<4)return `${p}w`;let c=Math.floor(i/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function An({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:i,onSearchChange:p,onChatSelect:c,onChatDelete:b,loadChatsIndex:T,historyPopupRef:h}){if(!e)return null;let S=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:i}),jsxs("div",{ref:h,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:x=>p(x.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:x=>x.currentTarget.style.borderColor=o.primaryColor,onBlur:x=>x.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let x=t.toLowerCase().trim(),k=T();return x&&(k=k.filter(a=>(a.title||"").toLowerCase().includes(x))),!k||k.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:k.map((a,v)=>jsx("div",{style:{borderTop:v>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:En(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(),b(a.id);},children:jsx(X,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(S,document.body):S}function Rn({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let i=o?.title||"Edit Message",p=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",b=o?.cancel_button_label||"Cancel",T=o?.icon,h=typeof p=="function",S=h?p:null,x=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[T?jsx("div",{style:{flexShrink:0},children:jsx(X,{IconComponent:T,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsx(X,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:i})]}),jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:h&&S?jsx(S,{}):jsx("p",{style:{margin:0},children:p})}),jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${t.borderColor}`,justifyContent:"flex-end"},children:[jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${t.borderColor}`,backgroundColor:"transparent",color:t.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:k=>{k.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:k=>{k.currentTarget.style.backgroundColor="transparent";},children:b}),jsx("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:"none",backgroundColor:t.primaryColor,color:t.backgroundColor,cursor:"pointer",transition:"all 0.2s",opacity:1},onMouseEnter:k=>{k.currentTarget.style.opacity="0.9";},onMouseLeave:k=>{k.currentTarget.style.opacity="1";},children:c})]})]})]});return typeof document<"u"&&document.body?createPortal(x,document.body):x}function fr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:i,borderColor:p,textColor:c,accentColor:b,baseUrl:T="",initialMessages:h=[],onMessagesChange:S,defaultOpen:x=true,floatingButtonPosition:k={bottom:24,right:24},HsafaTools:a={},HsafaUI:v={},componentAboveInput:s,editProcessContent:d,onStart:g,onFinish:y,currentChat:m,onChatChanged:I}){let{dir:C,theme:l,baseUrl:u,setStreamingState:w,setChatOpenState:f}=re(),A=t||l||"dark",B=T&&T.length>0?T:u||"",R={primaryColor:A==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:i||(A==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:p||(A==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(A==="dark"?"#EDEEF0":"#111827"),accentColor:b||(A==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:A==="dark"?"#6f7276":"#6B7280",inputBackground:A==="dark"?"#17181C":"#F3F4F6",cardBackground:A==="dark"?"#121318":"#FFFFFF",hoverBackground:A==="dark"?"#1c1e25":"#F3F4F6"},O=M=>({"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"})[M]||M,F=Mt({agentId:e,baseUrl:B,tools:a,uiComponents:v,controlledChatId:m,onChatIdChange:m===void 0?M=>{I&&I(M);}:void 0,onStart:useCallback(M=>{g&&g(M);},[g]),onFinish:useCallback(M=>{y&&y(M);},[y]),onError:useCallback(M=>{console.error("Chat error:",M);},[]),initialMessages:h,onMessagesChange:S}),{input:L,setInput:N,messages:G,isLoading:D,status:Y,error:pe,sendMessage:ue,stop:we,setMessages:J,notifyMessagesChange:me,chatId:$e,setChatId:Te,tools:Lt,uiComponents:mt,formHostRef:E,formStateRef:P,cleanupForms:_,onUISuccess:z,onUIError:Q,chatApi:ee}=F,q=m!==void 0?m:$e,xe=useCallback(M=>{m===void 0&&Te(M),I&&I(M);},[m,Te,I]);useEffect(()=>{m!==void 0&&m!==$e&&Te(m);},[m,$e,Te]);let{attachments:Ie,uploading:Ln,fileInputRef:qe,formatBytes:Hn,handleRemoveAttachment:$n,handleFileSelection:Ht,clearAttachments:Ve,setAttachments:$t}=Kt(B),[Bt,Me]=useState(null),[Ke,Dt]=useState(()=>{try{return rt(e).loadShowChatPreference(!!x)}catch{return !!x}}),[Bn,gt]=useState(false),[Dn,Pn]=useState(""),[Nn,zn]=useState(0),Un=useRef(null),Wn=useRef(null),[On,Gn]=useState(new Set),[_n,ft]=useState(false),[Be,yt]=useState(null),Pt=useRef(null),jn=_t(D),ht=Et({agentId:e,chatId:q,messages:G,isLoading:D,autoSave:true,autoRestore:false}),V=ht.storage,De=useRef(false),Pe=useRef(null);useEffect(()=>{if(!De.current){if(m!==void 0){try{let M=V.loadChat(m),U=M&&Array.isArray(M.messages)?M.messages:[];if(U.length>0)try{J(U);}catch{}Pe.current=m;}catch{}try{V.saveCurrentChatId(m);}catch{}De.current=true;return}try{let M=V.loadCurrentChatId();if(M){xe(M);let U=V.loadChat(M),j=U&&Array.isArray(U.messages)?U.messages:[];try{J(j);}catch{}Pe.current=M;}}catch{}De.current=true;}},[m]),useEffect(()=>{if(De.current&&m!==void 0&&m!==Pe.current)try{let M=V.loadChat(m),U=M&&Array.isArray(M.messages)?M.messages:[];try{J(U);}catch{}Pe.current=m;try{V.saveCurrentChatId(m);}catch{}}catch{}},[m,V,J]),useEffect(()=>{if(De.current)try{V.saveCurrentChatId(q);}catch{}},[q,V]),useEffect(()=>{try{w(q,D);}catch{}return ()=>{try{w(q,!1);}catch{}}},[q,D,w]),useEffect(()=>{try{f(q,Ke);}catch{}return ()=>{try{f(q,!1);}catch{}}},[q,Ke,f]);let qn=useCallback(async()=>{let M=L.trim();if(!M&&Ie.length===0||D)return;let U=[...Ie];N(""),Ve(),Me(null);try{await ue({text:M,files:U.map(j=>({type:"file",url:j.url,mediaType:j.mimeType||"application/octet-stream",...j.name?{name:j.name}:{},...j.size?{size:j.size}:{}}))});}catch(j){console.error("Failed to send message:",j),Me("Failed to send message. Please try again.");}},[L,Ie,D,ue,Ve]),Nt=useCallback(()=>{if(D)return;_(),N(""),Ve(),Me(null);try{J([]);}catch{}let M=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Pe.current=M;try{ht.createNewChat(()=>{xe(M);try{V.saveCurrentChatId(M);}catch{}});}catch{xe(M);try{V.saveCurrentChatId(M);}catch{}}},[D,Ve,V,J,xe,_,ht]),Vn=useCallback(()=>{gt(M=>!M);},[]),Kn=useCallback(()=>{Dt(false);try{V.saveShowChatPreference(!1);}catch{}},[V]),Xn=useCallback(async M=>{let U=M.target.files;U&&await Ht(U,Me),qe.current&&(qe.current.value="");},[Ht,qe]);useEffect(()=>{let M=Pt.current;if(!M)return;M.style.height="24px",M.offsetHeight,M.style.height="auto";let U=Math.min(M.scrollHeight,200);M.style.height=`${U}px`;},[L]);let Yn=useCallback((M,U,j,Qn)=>{yt({id:U,text:j,attachments:Qn||[]}),ft(true);},[]),Jn=useCallback(()=>{if(!(!Be||D))try{let M=G.findIndex(j=>j.id===Be.id);if(M===-1)return;let U=G.slice(0,M);try{J(U);}catch{}N(Be.text),$t(Be.attachments),ft(!1),yt(null),me();}catch(M){console.error("Failed to edit message:",M),Me("Failed to edit message. Please try again.");}},[Be,D,G,J,$t,me]),Zn=useCallback(()=>{ft(false),yt(null);},[]),zt=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:R.textColor,gap:"16px",zIndex:1e3,transform:Ke?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(Cn,{title:O("general.agent"),alwaysOpen:false,streaming:D,dir:C||"ltr",resolvedColors:R,onNew:Nt,onToggleHistory:Vn,onClose:Kn,historyBtnRef:Un,t:O}),jsx("div",{ref:jn,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":R.primaryColor,"--hsafa-border":R.borderColor,"--hsafa-card":R.cardBackground,"--hsafa-text":R.textColor,"--hsafa-muted":R.mutedTextColor,"--hsafa-bg":R.backgroundColor,"--hsafa-hover":R.hoverBackground,"--hsafa-input-bg":R.inputBackground,"--hsafa-accent":R.accentColor},children:G.length===0?jsx("div",{style:{padding:"32px",textAlign:"center",color:R.mutedTextColor,fontSize:"14px"},children:O("messages.empty")}):jsx(Mn,{chatMessages:G,isLoading:D,openReasoningIds:On,toggleReasoning:M=>Gn(U=>{let j=new Set(U);return j.has(M)?j.delete(M):j.add(M),j}),resolvedColors:R,t:O,onUserMessageClick:Yn,HsafaUI:mt,onUIError:Q,onUISuccess:z,addToolResult:M=>ee?.addToolResult?.(M),editableMessageIcon:d?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&tt.createElement(s,{}),Bt&&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:Bt}),jsx("button",{onClick:()=>Me(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),pe&&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: ",pe.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(Sn,{input:L,setInput:N,textareaRef:Pt,fileInputRef:qe,isLoading:D,uploading:Ln,attachments:Ie,formatBytes:Hn,handleRemoveAttachment:$n,onFileInputChange:Xn,onSend:qn,onStop:()=>we(),status:Y,t:O,resolvedColors:R})]}),jsx(An,{historyOpen:Bn,historySearch:Dn,currentChatId:q,refreshKey:Nn,resolvedColors:R,onClose:()=>gt(false),onSearchChange:Pn,onChatSelect:M=>{if(gt(false),M&&M!==q&&(_(),xe(M),m===void 0)){try{V.saveCurrentChatId(M);}catch{}try{let U=V.loadChat(M),j=U&&Array.isArray(U.messages)?U.messages:[];try{J(j);}catch{}}catch{}}},onChatDelete:M=>{try{V.deleteChat(M),zn(U=>U+1),M===q&&Nt();}catch{}},loadChatsIndex:()=>V.loadChatsIndex(),historyPopupRef:Wn}),jsx(Rn,{isOpen:_n,resolvedColors:R,onConfirm:Jn,onCancel:Zn,editProcessContent:d}),jsx("style",{children:`
33
+ `),s=a.filter(d=>d.type==="file"||d.type==="image").map(d=>{if(d.type==="image"){let g=typeof d.image=="string"?d.image:d.image?.toString?.()||"";return {id:g||`${x.id}-img-${Date.now()}`,name:d.name||"image",url:g,mimeType:d.mediaType||"image/jpeg",size:d.size||0}}else return {id:d.url||`${x.id}-file-${Date.now()}`,name:d.name||"file",url:d.url||"",mimeType:d.mediaType||"application/octet-stream",size:d.size||0}});return jsx("div",{style:{padding:"0 4px"},children:x.role==="user"?jsx("div",{children:jsx("div",{title:i("editor.clickToEdit"),onClick:()=>p(x,x.id,v,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:d=>d.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor=o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[v,s.length>0&&jsx(Mn,{attachments:s,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(V,{IconComponent:M||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(kn,{parts:a,messageId:x.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:b,onUISuccess:T,addToolResult:y})},x.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function En({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:i,attachments:p,formatBytes:c,handleRemoveAttachment:b,onFileInputChange:T,onSend:y,onStop:M,status:x,t:k,resolvedColors:a}){let v=x==="streaming"||x==="submitted",s=p.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[p.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:p.map(d=>{let g=d.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:g?"transparent":a.cardBackground},children:g?jsx("img",{src:d.url,alt:d.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:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:d.name}),jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(d.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[g&&jsx("a",{href:d.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:k("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:()=>b(d.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:k("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"})]})})]})]},d.id)})}),i&&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:k("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:k("input.placeholder"),value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),y());},disabled:o||i,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:T,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||i,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||i?.5:1},"aria-label":k("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:M,disabled:!v,"aria-label":k("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:v?1:.4,cursor:v?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{v&&(d.currentTarget.style.backgroundColor="#ef444430",d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ef444420",d.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:y,disabled:!s||i,"aria-label":k("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||i?a.mutedTextColor:a.primaryColor,cursor:!s||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||i?.5:1},onMouseEnter:d=>{s&&!i&&(d.currentTarget.style.borderColor=a.primaryColor,d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.borderColor=a.borderColor,d.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 An(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let r=Math.floor(n/60);if(r<60)return `${r}m`;let o=Math.floor(r/60);if(o<24)return `${o}h`;let i=Math.floor(o/24);if(i<7)return `${i}d`;let p=Math.floor(i/7);if(p<4)return `${p}w`;let c=Math.floor(i/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function Rn({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:i,onSearchChange:p,onChatSelect:c,onChatDelete:b,loadChatsIndex:T,historyPopupRef:y}){if(!e)return null;let M=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:i}),jsxs("div",{ref:y,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:x=>p(x.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:x=>x.currentTarget.style.borderColor=o.primaryColor,onBlur:x=>x.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let x=t.toLowerCase().trim(),k=T();return x&&(k=k.filter(a=>(a.title||"").toLowerCase().includes(x))),!k||k.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:k.map((a,v)=>jsx("div",{style:{borderTop:v>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:An(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(),b(a.id);},children:jsx(V,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(M,document.body):M}function Fn({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let i=o?.title||"Edit Message",p=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",b=o?.cancel_button_label||"Cancel",T=o?.icon,y=typeof p=="function",M=y?p:null,x=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[T?jsx("div",{style:{flexShrink:0},children:jsx(V,{IconComponent:T,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsx(V,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:i})]}),jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:y&&M?jsx(M,{}):jsx("p",{style:{margin:0},children:p})}),jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${t.borderColor}`,justifyContent:"flex-end"},children:[jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${t.borderColor}`,backgroundColor:"transparent",color:t.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:k=>{k.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:k=>{k.currentTarget.style.backgroundColor="transparent";},children:b}),jsx("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:"none",backgroundColor:t.primaryColor,color:t.backgroundColor,cursor:"pointer",transition:"all 0.2s",opacity:1},onMouseEnter:k=>{k.currentTarget.style.opacity="0.9";},onMouseLeave:k=>{k.currentTarget.style.opacity="1";},children:c})]})]})]});return typeof document<"u"&&document.body?createPortal(x,document.body):x}function yr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:i,borderColor:p,textColor:c,accentColor:b,baseUrl:T="",initialMessages:y=[],onMessagesChange:M,defaultOpen:x=true,floatingButtonPosition:k={bottom:24,right:24},HsafaTools:a={},HsafaUI:v={},componentAboveInput:s,editProcessContent:d,onStart:g,onFinish:h,currentChat:m,onChatChanged:I}){let{dir:C,theme:l,baseUrl:u,setStreamingState:w,setChatOpenState:f}=re(),A=t||l||"dark",B=T&&T.length>0?T:u||"",R={primaryColor:A==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:i||(A==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:p||(A==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(A==="dark"?"#EDEEF0":"#111827"),accentColor:b||(A==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:A==="dark"?"#6f7276":"#6B7280",inputBackground:A==="dark"?"#17181C":"#F3F4F6",cardBackground:A==="dark"?"#121318":"#FFFFFF",hoverBackground:A==="dark"?"#1c1e25":"#F3F4F6"},W=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,F=Mt({agentId:e,baseUrl:B,tools:a,uiComponents:v,controlledChatId:m,onChatIdChange:m===void 0?S=>{I&&I(S);}:void 0,onStart:useCallback(S=>{g&&g(S);},[g]),onFinish:useCallback(S=>{h&&h(S);},[h]),onError:useCallback(S=>{console.error("Chat error:",S);},[]),initialMessages:y,onMessagesChange:M}),{input:L,setInput:N,messages:O,isLoading:D,status:K,error:me,sendMessage:ue,stop:Te,setMessages:Y,notifyMessagesChange:ge,chatId:Be,setChatId:Ie,tools:Lt,uiComponents:gt,formHostRef:E,formStateRef:P,cleanupForms:G,onUISuccess:z,onUIError:Q,chatApi:ee}=F,_=m!==void 0?m:Be,be=useCallback(S=>{m===void 0&&Ie(S),I&&I(S);},[m,Ie,I]);useEffect(()=>{m!==void 0&&m!==Be&&Ie(m);},[m,Be,Ie]);let{attachments:Me,uploading:Hn,fileInputRef:Ve,formatBytes:$n,handleRemoveAttachment:Bn,handleFileSelection:Ht,clearAttachments:Ke,setAttachments:$t}=Xt(B),[Bt,Se]=useState(null),[Xe,Dt]=useState(()=>{try{return at(e).loadShowChatPreference(!!x)}catch{return !!x}}),[Dn,ft]=useState(false),[Pn,Nn]=useState(""),[zn,Un]=useState(0),Wn=useRef(null),On=useRef(null),[Gn,_n]=useState(new Set),[jn,ht]=useState(false),[De,yt]=useState(null),Pt=useRef(null),qn=jt(D),[Vn,Nt]=useState(m!==void 0),fe=Et({agentId:e,chatId:_,messages:O,isLoading:D,autoSave:Vn,autoRestore:false}),X=fe.storage,Pe=useRef(false),Ne=useRef(null);useEffect(()=>{if(!Pe.current){if(m!==void 0){try{fe.switchToChat(m,Y),Ne.current=m;}catch{}try{X.saveCurrentChatId(m);}catch{}Pe.current=true,Nt(true);return}try{let S=X.loadCurrentChatId();S&&(be(S),fe.switchToChat(S,Y),Ne.current=S);}catch{}Pe.current=true,Nt(true);}},[m]),useEffect(()=>{if(Pe.current&&m!==void 0&&m!==Ne.current)try{fe.switchToChat(m,Y),Ne.current=m;try{X.saveCurrentChatId(m);}catch{}}catch{}},[m,X,Y,fe]),useEffect(()=>{if(Pe.current)try{X.saveCurrentChatId(_);}catch{}},[_,X]),useEffect(()=>{try{w(_,D);}catch{}return ()=>{try{w(_,!1);}catch{}}},[_,D,w]),useEffect(()=>{try{f(_,Xe);}catch{}return ()=>{try{f(_,!1);}catch{}}},[_,Xe,f]);let Kn=useCallback(async()=>{let S=L.trim();if(!S&&Me.length===0||D)return;let J=[...Me];N(""),Ke(),Se(null);try{await ue({text:S,files:J.map(q=>({type:"file",url:q.url,mediaType:q.mimeType||"application/octet-stream",...q.name?{name:q.name}:{},...q.size?{size:q.size}:{}}))});}catch(q){console.error("Failed to send message:",q),Se("Failed to send message. Please try again.");}},[L,Me,D,ue,Ke]),zt=useCallback(()=>{if(D)return;G(),N(""),Ke(),Se(null);try{Y([]);}catch{}let S=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Ne.current=S;try{fe.createNewChat(()=>{be(S);try{X.saveCurrentChatId(S);}catch{}});}catch{be(S);try{X.saveCurrentChatId(S);}catch{}}},[D,Ke,X,Y,be,G,fe]),Xn=useCallback(()=>{ft(S=>!S);},[]),Yn=useCallback(()=>{Dt(false);try{X.saveShowChatPreference(!1);}catch{}},[X]),Jn=useCallback(async S=>{let J=S.target.files;J&&await Ht(J,Se),Ve.current&&(Ve.current.value="");},[Ht,Ve]);useEffect(()=>{let S=Pt.current;if(!S)return;S.style.height="24px",S.offsetHeight,S.style.height="auto";let J=Math.min(S.scrollHeight,200);S.style.height=`${J}px`;},[L]);let Zn=useCallback((S,J,q,to)=>{yt({id:J,text:q,attachments:to||[]}),ht(true);},[]),Qn=useCallback(()=>{if(!(!De||D))try{let S=O.findIndex(q=>q.id===De.id);if(S===-1)return;let J=O.slice(0,S);try{Y(J);}catch{}N(De.text),$t(De.attachments),ht(!1),yt(null),ge();}catch(S){console.error("Failed to edit message:",S),Se("Failed to edit message. Please try again.");}},[De,D,O,Y,$t,ge]),eo=useCallback(()=>{ht(false),yt(null);},[]),Ut=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:R.textColor,gap:"16px",zIndex:1e3,transform:Xe?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(vn,{title:W("general.agent"),alwaysOpen:false,streaming:D,dir:C||"ltr",resolvedColors:R,onNew:zt,onToggleHistory:Xn,onClose:Yn,historyBtnRef:Wn,t:W}),jsx("div",{ref:qn,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":R.primaryColor,"--hsafa-border":R.borderColor,"--hsafa-card":R.cardBackground,"--hsafa-text":R.textColor,"--hsafa-muted":R.mutedTextColor,"--hsafa-bg":R.backgroundColor,"--hsafa-hover":R.hoverBackground,"--hsafa-input-bg":R.inputBackground,"--hsafa-accent":R.accentColor},children:O.length===0?jsx("div",{style:{padding:"32px",textAlign:"center",color:R.mutedTextColor,fontSize:"14px"},children:W("messages.empty")}):jsx(Sn,{chatMessages:O,isLoading:D,openReasoningIds:Gn,toggleReasoning:S=>_n(J=>{let q=new Set(J);return q.has(S)?q.delete(S):q.add(S),q}),resolvedColors:R,t:W,onUserMessageClick:Zn,HsafaUI:gt,onUIError:Q,onUISuccess:z,addToolResult:S=>ee?.addToolResult?.(S),editableMessageIcon:d?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&nt.createElement(s,{}),Bt&&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:Bt}),jsx("button",{onClick:()=>Se(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),me&&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: ",me.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(En,{input:L,setInput:N,textareaRef:Pt,fileInputRef:Ve,isLoading:D,uploading:Hn,attachments:Me,formatBytes:$n,handleRemoveAttachment:Bn,onFileInputChange:Jn,onSend:Kn,onStop:()=>Te(),status:K,t:W,resolvedColors:R})]}),jsx(Rn,{historyOpen:Dn,historySearch:Pn,currentChatId:_,refreshKey:zn,resolvedColors:R,onClose:()=>ft(false),onSearchChange:Nn,onChatSelect:S=>{if(ft(false),S&&S!==_&&(G(),be(S),m===void 0)){try{X.saveCurrentChatId(S);}catch{}try{fe.switchToChat(S,Y);}catch{}}},onChatDelete:S=>{try{X.deleteChat(S),Un(J=>J+1),S===_&&zt();}catch{}},loadChatsIndex:()=>X.loadChatsIndex(),historyPopupRef:On}),jsx(Fn,{isOpen:jn,resolvedColors:R,onConfirm:Qn,onCancel:eo,editProcessContent:d}),jsx("style",{children:`
34
34
  @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
35
35
  @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
36
- `})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(Qe,{}),createPortal(zt,document.body),jsx(Wt,{show:!Ke,onClick:()=>{Dt(true);try{V.saveShowChatPreference(!0);}catch{}},resolvedColors:R,floatingButtonPosition:k})]}):zt}var Fn={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 Cr({children:e,theme:t="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:i,mutedTextColor:p,enableBorderAnimation:c=true,borderRadius:b=16,enableContentBorder:T=true,className:h="",enableMargin:S=true,chatWidth:x=420,dir:k="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:v,dir:s,theme:d}=re(),g=(k??s)||"ltr",y=(t??d)||"dark",m=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[I,C]=useState(false);useEffect(()=>{let H=setTimeout(()=>C(true),50);return ()=>clearTimeout(H)},[]);let l=Fn[y],u={primaryColor:n||l.primaryColor,backgroundColor:r||l.backgroundColor,borderColor:o||l.borderColor,textColor:i||l.textColor,accentColor:l.accentColor,mutedTextColor:p||l.mutedTextColor,inputBackground:l.inputBackground,cardBackground:l.cardBackground,hoverBackground:l.hoverBackground},w=typeof b=="number"?`${b}px`:b,f=typeof x=="number"?`${x}px`:x,A=S&&v?g==="rtl"?{marginLeft:f}:{marginRight:f}:{},B=S&&v?`calc(100% - ${f})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:h,style:{width:B,height:"100%",transition:I?"all 0.2s ease-out":"none",padding:v&&T?"16px":"0",...A},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:I?"all 0.2s ease-out":"none",borderRadius:v?w:"0",border:v&&a&&c?"none":v?`1px solid ${u.borderColor}`:"none",padding:v&&a&&c?"1.5px":"0",background:v&&a&&c?`linear-gradient(120deg, ${u.primaryColor}dd 0%, ${u.primaryColor}88 25%, ${u.primaryColor}00 50%, ${u.primaryColor}88 75%, ${u.primaryColor}dd 100%)`:"transparent",backgroundSize:v&&a&&c?"300% 300%":"auto",animation:v&&a&&c?`${m.current}-border-flow 3s ease-in-out infinite`:"none",filter:v&&a&&c?`drop-shadow(0 0 10px ${u.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:v&&T?w:"0",backgroundColor:v&&T?u.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${u.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`
36
+ `})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(et,{}),createPortal(Ut,document.body),jsx(Ot,{show:!Xe,onClick:()=>{Dt(true);try{X.saveShowChatPreference(!0);}catch{}},resolvedColors:R,floatingButtonPosition:k})]}):Ut}var Ln={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 kr({children:e,theme:t="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:i,mutedTextColor:p,enableBorderAnimation:c=true,borderRadius:b=16,enableContentBorder:T=true,className:y="",enableMargin:M=true,chatWidth:x=420,dir:k="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:v,dir:s,theme:d}=re(),g=(k??s)||"ltr",h=(t??d)||"dark",m=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[I,C]=useState(false);useEffect(()=>{let H=setTimeout(()=>C(true),50);return ()=>clearTimeout(H)},[]);let l=Ln[h],u={primaryColor:n||l.primaryColor,backgroundColor:r||l.backgroundColor,borderColor:o||l.borderColor,textColor:i||l.textColor,accentColor:l.accentColor,mutedTextColor:p||l.mutedTextColor,inputBackground:l.inputBackground,cardBackground:l.cardBackground,hoverBackground:l.hoverBackground},w=typeof b=="number"?`${b}px`:b,f=typeof x=="number"?`${x}px`:x,A=M&&v?g==="rtl"?{marginLeft:f}:{marginRight:f}:{},B=M&&v?`calc(100% - ${f})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:y,style:{width:B,height:"100%",transition:I?"all 0.2s ease-out":"none",padding:v&&T?"16px":"0",...A},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:I?"all 0.2s ease-out":"none",borderRadius:v?w:"0",border:v&&a&&c?"none":v?`1px solid ${u.borderColor}`:"none",padding:v&&a&&c?"1.5px":"0",background:v&&a&&c?`linear-gradient(120deg, ${u.primaryColor}dd 0%, ${u.primaryColor}88 25%, ${u.primaryColor}00 50%, ${u.primaryColor}88 75%, ${u.primaryColor}dd 100%)`:"transparent",backgroundSize:v&&a&&c?"300% 300%":"auto",animation:v&&a&&c?`${m.current}-border-flow 3s ease-in-out infinite`:"none",filter:v&&a&&c?`drop-shadow(0 0 10px ${u.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:v&&T?w:"0",backgroundColor:v&&T?u.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${u.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`
37
37
  @keyframes ${m.current}-border-flow {
38
38
  0% { background-position: 0% 50%; }
39
39
  50% { background-position: 100% 50%; }
40
40
  100% { background-position: 0% 50%; }
41
41
  }
42
- `})," "]})}var Ft=class{constructor(){this.components=new Map;}register(t,n){this.components.set(t,n);}unregister(t){this.components.delete(t);}get(t){return this.components.get(t)}has(t){return this.components.has(t)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},wr=new Ft;export{Mr as Button,Cr as ContentContainer,Qe as CursorController,Ue as FillActiveInput,Wt as FloatingChatButton,fr as HsafaChat,ro as HsafaProvider,wr as componentRegistry,Ce as controlCursor,ze as getDomComponents,Ce as guideCursor,_t as useAutoScroll,Et as useChatStorage,Kt as useFileUpload,re as useHsafa,Mt as useHsafaAgent,_o as useMessageEditor};//# sourceMappingURL=index.js.map
42
+ `})," "]})}var Ft=class{constructor(){this.components=new Map;}register(t,n){this.components.set(t,n);}unregister(t){this.components.delete(t);}get(t){return this.components.get(t)}has(t){return this.components.has(t)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},Ir=new Ft;export{Er as Button,kr as ContentContainer,et as CursorController,We as FillActiveInput,Ot as FloatingChatButton,yr as HsafaChat,so as HsafaProvider,Ir as componentRegistry,ve as controlCursor,Ue as getDomComponents,ve as guideCursor,jt as useAutoScroll,Et as useChatStorage,Xt as useFileUpload,re as useHsafa,Mt as useHsafaAgent,qo as useMessageEditor};//# sourceMappingURL=index.js.map
43
43
  //# sourceMappingURL=index.js.map