@hsafa/ui-sdk 0.4.3 → 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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var jsxRuntime=require('react/jsx-runtime'),st=require('react'),react=require('@ai-sdk/react'),ai=require('ai'),client=require('react-dom/client'),dt=require('fast-json-patch'),reactDom=require('react-dom'),lucideReact=require('lucide-react');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var st__default=/*#__PURE__*/_interopDefault(st);var dt__namespace=/*#__PURE__*/_interopNamespace(dt);var we={};var Zo=({variant:n="primary",size:e="md",loading:t=false,disabled:o,children:r,className:i,...d})=>{let u=[we.button,we[n],we[e],t&&we.loading,i].filter(Boolean).join(" ");return jsxRuntime.jsxs("button",{className:u,disabled:o||t,...d,children:[t&&jsxRuntime.jsx("span",{className:we.spinner}),jsxRuntime.jsx("span",{className:t?we.hiddenText:void 0,children:r})]})};function nn({show:n,onClick:e,resolvedColors:t,floatingButtonPosition:o}){if(!n)return null;let r={position:"fixed",bottom:typeof o.bottom=="number"?`${o.bottom}px`:o.bottom,right:o.right?typeof o.right=="number"?`${o.right}px`:o.right:void 0,top:o.top?typeof o.top=="number"?`${o.top}px`:o.top:void 0,left:o.left?typeof o.left=="number"?`${o.left}px`:o.left:void 0,zIndex:1e3};return jsxRuntime.jsx("button",{"aria-label":"Open chat",onClick:e,style:{...r,borderColor:t.borderColor,backgroundColor:t.accentColor,color:t.textColor,borderRadius:"50%",border:`1px solid ${t.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=t.primaryColor,i.currentTarget.style.backgroundColor=`${t.accentColor}dd`;},onMouseLeave:i=>{i.currentTarget.style.borderColor=t.borderColor,i.currentTarget.style.backgroundColor=t.accentColor;},children:jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.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 an(n=true){let e=st.useRef(null),t=st.useRef(n);return st.useEffect(()=>{t.current=n;},[n]),st.useEffect(()=>{let o=e.current;if(!o)return;let r=new MutationObserver(()=>{t.current&&(o.scrollTop=o.scrollHeight);});return r.observe(o,{childList:true,subtree:true}),t.current&&(o.scrollTop=o.scrollHeight),()=>r.disconnect()},[]),e}function sn(n,e){if(!n)return e;let t=n.endsWith("/")?n.slice(0,-1):n,o=e.startsWith("/")?e:`/${e}`;return `${t}${o}`}var ln=st.createContext(void 0);function Cr({baseUrl:n,dir:e="ltr",theme:t="dark",children:o}){let[r,i]=st.useState(new Map),[d,u]=st.useState(new Map),[c,k]=st.useState(new Map),[g,T]=st.useState(new Map),[y,C]=st.useState(void 0),[a,p]=st.useState(new Map),s=y?a.get(y)||[]:[],l=st.useCallback((S,A)=>(i(F=>{let M=new Map(F);return M.set(String(S),A),M}),()=>{i(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});}),[]),m=st.useCallback((S,A)=>{i(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});},[]),f=st.useCallback((S,A)=>(u(F=>{let M=new Map(F);return M.set(String(S),A),M}),()=>{u(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});}),[]),x=st.useCallback((S,A)=>{u(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});},[]),I=st.useCallback((S,A)=>{k(F=>{let M=new Map(F);return A?M.set(S,true):M.delete(S),M});},[]),v=st.useCallback((S,A)=>{T(F=>{let M=new Map(F);return M.set(S,A),M});},[]),b=st.useCallback((S,A)=>{p(F=>{let M=new Map(F);return M.set(S,A),M});},[]),h=st.useCallback(S=>{p(A=>{let F=new Map(A);return F.delete(S),F});},[]),E=st.useMemo(()=>Array.from(c.values()).some(S=>S),[c]),w=st.useMemo(()=>Array.from(g.values()).some(S=>S),[g]),P=st.useMemo(()=>({baseUrl:n,dir:e,theme:t,actions:r,components:d,registerAction:l,unregisterAction:m,registerComponent:f,unregisterComponent:x,isAnyStreaming:E,setStreamingState:I,isAnyChatOpen:w,setChatOpenState:v,currentChatId:y,setCurrentChatId:C,dynamicPageTypes:s,registerDynamicPageTypes:b,unregisterDynamicPageTypes:h}),[n,e,t,r,d,l,m,f,x,E,I,w,v,y,s,b,h]);return jsxRuntime.jsx(ln.Provider,{value:P,children:o})}function ne(){let n=st.useContext(ln);return n||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{},dynamicPageTypes:[],registerDynamicPageTypes:()=>{},unregisterDynamicPageTypes:()=>{}}}var _t=25*1024*1024;function dn(n){let{baseUrl:e}=ne(),t=n||e||"",[o,r]=st.useState([]),[i,d]=st.useState(false),u=st.useRef(null),c=st.useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let p=["B","KB","MB","GB","TB"],s=Math.min(p.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${p[s]}`},[]),k=st.useCallback(async a=>{let p=new FormData;p.append("file",a);let s=await fetch(sn(t,"/api/uploads"),{method:"POST",body:p});if(!s.ok){let m=await s.text().catch(()=>"");throw new Error(m||`Failed to upload ${a.name}`)}let l=await s.json();return {id:l.id,name:l.name||a.name,url:l.url,mimeType:l.mimeType||a.type||"application/octet-stream",size:typeof l.size=="number"?l.size:a.size}},[t]),g=st.useCallback(a=>{r(p=>p.filter(s=>s.id!==a));},[]),T=st.useCallback(async(a,p)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);p(null),d(true);let l=[];try{for(let m of s){if(m.size>_t){p(`"${m.name}" exceeds the ${c(_t)} limit.`);continue}try{let f=await k(m);l.push(f);}catch(f){console.error("Failed to upload attachment:",f),p(String(f?.message??`Failed to upload ${m.name}`));}}l.length&&r(m=>[...m,...l]);}finally{d(false);}},[k,c]),y=st.useCallback((a,p)=>{let s=[],l=(a||"").trim();l&&s.push({type:"text",text:l});for(let m of p||[]){let f=m.mimeType||"application/octet-stream";f.startsWith("image/")?s.push({type:"image",image:new URL(m.url),mediaType:f}):s.push({type:"file",data:m.url,mediaType:f,name:m.name});}return s},[]),C=st.useCallback(()=>{r([]);},[]);return {attachments:o,uploading:i,fileInputRef:u,formatBytes:c,handleRemoveAttachment:g,handleFileSelection:T,buildUserContent:y,clearAttachments:C,setAttachments:r,MAX_UPLOAD_SIZE:_t}}function un(n,e,t){return new ai.DefaultChatTransport({api:`${n}/api/run/${e}`,fetch:async(o,r)=>{let d={...r?.body?JSON.parse(r.body):{},chatId:t};return fetch(o,{...r,body:JSON.stringify(d)})}})}function Tr(n){if(!(n instanceof HTMLElement))return true;let e=window.getComputedStyle(n);return e.display!=="none"&&e.visibility!=="hidden"&&e.opacity!=="0"&&n.offsetParent!==null}function Sr(n){if(n.id){let t=document.querySelector(`label[for="${n.id}"]`);if(t)return t.textContent?.trim()}let e=n.closest("label");if(e){let t=e.cloneNode(true),o=t.querySelector("input, select, textarea");return o&&o.remove(),t.textContent?.trim()}}function jt(n){if(n.textContent&&n.textContent.trim())return n.textContent.trim().slice(0,100)}function Dt(n){if(n instanceof HTMLInputElement){let e=n.type.toLowerCase();return e==="checkbox"||e==="radio"?n.checked:n.value}if(n instanceof HTMLTextAreaElement)return n.value;if(n instanceof HTMLSelectElement)return n.multiple?Array.from(n.selectedOptions).map(e=>e.value):n.value;if(n instanceof HTMLElement&&n.isContentEditable)return n.textContent||void 0}function Er(n){if(n.id)return `#${n.id}`;let e=[],t=n;for(;t&&t!==document.body;){let o=t.tagName.toLowerCase();if(t.className&&typeof t.className=="string"){let i=t.className.split(" ").filter(d=>d.trim()).slice(0,2);i.length>0&&(o+="."+i.join("."));}let r=t.parentElement;if(r){let i=Array.from(r.children).filter(d=>d.tagName===t.tagName);if(i.length>1){let d=i.indexOf(t)+1;o+=`:nth-child(${d})`;}}e.unshift(o),t=r;}return e.slice(-3).join(" > ")}async function Ue(n={}){try{let{includeHidden:e=!1,selector:t,what:o="content",limit:r}=n,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 d=t&&i.querySelector(t)||i,u=[],c=[];o==="inputs"?c=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:c=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],d.querySelectorAll(c.join(", ")).forEach(s=>{let l=Tr(s);if(!l&&!e)return;let m={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:l,isInteractive:!0,selector:Er(s)};s instanceof HTMLInputElement?(m.type=s.type,m.name=s.name||void 0,m.placeholder=s.placeholder||void 0,m.value=Dt(s),m.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,m.disabled=s.disabled,m.required=s.required):s instanceof HTMLTextAreaElement?(m.name=s.name||void 0,m.placeholder=s.placeholder||void 0,m.value=Dt(s),m.disabled=s.disabled,m.required=s.required):s instanceof HTMLSelectElement?(m.name=s.name||void 0,m.value=Dt(s),m.disabled=s.disabled,m.required=s.required,m.options=Array.from(s.options).map(f=>({value:f.value,label:f.text,selected:f.selected,disabled:f.disabled}))):s instanceof HTMLButtonElement?(m.type=s.type,m.disabled=s.disabled,m.text=jt(s)):s instanceof HTMLAnchorElement?(m.href=s.href,m.text=jt(s)):s instanceof HTMLImageElement?(m.text=s.alt||void 0,m.label=s.alt||m.label):m.text=jt(s),m.label=Sr(s),m.role=s.getAttribute("role")||void 0,m.ariaLabel=s.getAttribute("aria-label")||void 0,u.push(m);});let g=s=>s.isVisible?o==="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;u.sort((s,l)=>g(l)-g(s));let T=u.length,C=Math.max(1,Math.min(200,typeof r=="number"?Math.floor(r):o==="inputs"?100:150)),a=T>C,p=a?u.slice(0,C):u;return {ok:!0,components:p,count:p.length,total:T,truncated:a,containerFound:!0}}catch(e){return {ok:false,components:[],count:0,total:0,containerFound:false,error:e?.message||String(e)}}}typeof window<"u"&&(window.getDomComponents=Ue);async function Te(n,e={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let t=window.__cursorGuide;if(!t)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 t(n,e)}catch(o){return {ok:false,steps:[{ok:false,action:e.action||"none",targetKind:"position",durationMs:0,error:o?.message||String(o)}]}}}typeof window<"u"&&(window.guideCursor=Te);function pn(n){return !!n&&n.nodeType===1}function le(n,e){n.dispatchEvent(new Event(e,{bubbles:true}));}function mn(n,e){let t=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(n),"value")?.set;t?t.call(n,e):n.value=e,le(n,"input");}function Ir(n,e){n.checked!==e&&n.click();}function Mr(n,e){if(typeof e=="object"&&e&&"index"in e&&typeof e.index=="number")n.selectedIndex=Math.max(0,Math.min(n.options.length-1,e.index));else if(typeof e=="object"&&e&&"label"in e&&typeof e.label=="string"){let t=Array.from(n.options).findIndex(o=>o.text===e.label);n.selectedIndex=t>=0?t:0;}else n.value=String(e);le(n,"input"),le(n,"change");}function Ar(n,e){let t=new Set(e.map(String));Array.from(n.options).forEach(o=>{o.selected=t.has(o.value)||t.has(o.text);}),le(n,"input"),le(n,"change");}function Rr(n){return n?n instanceof Date?n.toISOString().slice(0,10):String(n):""}function _r(n,e){let t=Array.isArray(e)?e:[e],o=new DataTransfer;for(let r of t)o.items.add(r);Object.defineProperty(n,"files",{value:o.files,configurable:true}),le(n,"input"),le(n,"change");}async function Ge(n,e={}){let t=document.activeElement||null;if(t&&pn(t)){let o=t.closest('[contenteditable="true"], [contenteditable=""]');o&&(t=o);}if(!t||t===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let o=t.tagName.toLowerCase();if(o==="input"){let r=t,i=(r.type||"text").toLowerCase();if(i==="checkbox")Ir(r,!!n);else if(i==="radio"){let d=r.name;if(d&&n!=null&&String(r.value)!==String(n)){let u=document.querySelector(`input[type="radio"][name="${CSS.escape(d)}"][value="${CSS.escape(String(n))}"]`);u?u.click():r.click();}else r.click();}else if(i==="file")if(n instanceof File||Array.isArray(n)&&n.every(d=>d instanceof File))_r(r,n);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 d=i==="date"?Rr(n):String(n??"");mn(r,d),le(r,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="textarea"){let r=t,i=String(n??"");return mn(r,i),le(r,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="select"){let r=t;return r.multiple?Ar(r,Array.isArray(n)?n:[n]):Mr(r,n),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(pn(t)&&t.isContentEditable){let r=t;return r.focus(),r.textContent=String(n??""),le(r,"input"),le(r,"change"),r.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${o}`}],errors:[`Unsupported active element: ${o}`]}}catch(o){return {ok:false,filled:[{key:"active",status:"error",message:o?.message??String(o)}],errors:[o?.message??String(o)]}}}typeof window<"u"&&(window.FillActiveInput=Ge);var qe=null,et={},fn=false,De=null,nt=false;function $t(n){n.classList.add("visible");}function vn(){nt=true,De!=null&&(clearTimeout(De),De=null);}function Dr(n,e=1500){nt||(De!=null&&clearTimeout(De),De=window.setTimeout(()=>{nt||n.classList.remove("visible");},e));}function $r(n,e=1200){nt=false,Dr(n,e);}function Fr(n){let e=[],t=n?.parentElement;for(;t;){let o=getComputedStyle(t),r=o.overflow+o.overflowY+o.overflowX;/(auto|scroll)/.test(r)&&e.push(t),t=t.parentElement;}return e}async function Pr(n,e=1500,t=160){let o=performance.now(),r=n?Fr(n):[],i=()=>{let g=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return r.forEach(T=>{g.push(T.scrollLeft,T.scrollTop);}),g},d=()=>{if(!n)return {x:0,y:0};let g=n.getBoundingClientRect();return {x:g.left,y:g.top}},u=i(),c=d(),k=performance.now();return new Promise(g=>{function T(y){let C=i(),a=d(),p=false;for(let s=0;s<C.length;s++)if(C[s]!==u[s]){p=true;break}if(!p&&n&&(a.x!==c.x||a.y!==c.y)&&(p=true),p&&(u=C,c=a,k=y),y-k>=t||y-o>=e){g();return}requestAnimationFrame(T);}requestAnimationFrame(T);})}var Lr='<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>',Hr='<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 Br(){if(!et.arrow)try{et.arrow=Lr,et.pointer=Hr;}catch(n){console.warn("Failed to set cursor SVGs",n);}return et}function yn({arrowSvg:n,pointerSvg:e}){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[n&&jsxRuntime.jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:n}}),e&&jsxRuntime.jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:e}})]})}async function Or(){let n="demo-fake-cursor",e=document.getElementById(n),t=await Br();if(!fn){let o="cursor-controller-styles";if(!document.getElementById(o)){let r=document.createElement("style");r.id=o,r.textContent=`
1
+ 'use strict';var jsxRuntime=require('react/jsx-runtime'),nt=require('react'),react=require('@ai-sdk/react'),ai=require('ai'),client=require('react-dom/client'),reactDom=require('react-dom'),lucideReact=require('lucide-react');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var nt__default=/*#__PURE__*/_interopDefault(nt);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 jsxRuntime.jsxs("button",{className:c,disabled:r||n,...p,children:[n&&jsxRuntime.jsx("span",{className:Ce.spinner}),jsxRuntime.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 jsxRuntime.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:jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.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=nt.useRef(null),n=nt.useRef(e);return nt.useEffect(()=>{n.current=e;},[e]),nt.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=nt.createContext(void 0);function so({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,i]=nt.useState(new Map),[p,c]=nt.useState(new Map),[b,T]=nt.useState(new Map),[y,M]=nt.useState(new Map),[x,k]=nt.useState(void 0),a=nt.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=nt.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=nt.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=nt.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=nt.useCallback((l,u)=>{T(w=>{let f=new Map(w);return u?f.set(l,true):f.delete(l),f});},[]),h=nt.useCallback((l,u)=>{M(w=>{let f=new Map(w);return f.set(l,u),f});},[]),m=nt.useMemo(()=>Array.from(b.values()).some(l=>l),[b]),I=nt.useMemo(()=>Array.from(y.values()).some(l=>l),[y]),C=nt.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 jsxRuntime.jsx(Vt.Provider,{value:C,children:r})}function re(){let e=nt.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]=nt.useState([]),[i,p]=nt.useState(false),c=nt.useRef(null),b=nt.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=nt.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=nt.useCallback(a=>{o(v=>v.filter(s=>s.id!==a));},[]),M=nt.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=nt.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=nt.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 ai.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 jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[e&&jsxRuntime.jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsxRuntime.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 @@
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(r);}fn=true;}return e?(e.classList.add("as-arrow"),qe||(qe=client.createRoot(e),qe.render(jsxRuntime.jsx(yn,{arrowSvg:t.arrow,pointerSvg:t.pointer})))):(e=document.createElement("div"),e.id=n,e.className="fake-cursor as-arrow",e.style.position="fixed",e.style.left="20px",e.style.top="20px",document.body.appendChild(e),qe=client.createRoot(e),qe.render(jsxRuntime.jsx(yn,{arrowSvg:t.arrow,pointerSvg:t.pointer}))),e}function $e(n,e,t){return Math.max(e,Math.min(t,n))}function zr(n){return n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2}function kn(n){if(!n)return null;let e=document.createElement("canvas").getContext("2d");if(!e)return null;e.fillStyle="#000",e.fillStyle=n;let o=e.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!o)return null;let r=o[1].split(/\s*,\s*/).map(Number),[i,d,u,c=1]=r;return {r:i,g:d,b:u,a:c}}function Nr({r:n,g:e,b:t}){let o=[n,e,t].map(r=>r/255).map(r=>r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4));return .2126*o[0]+.7152*o[1]+.0722*o[2]}function Wr(n){let e=n?kn(n):null;return !e||e.a===0?false:Nr(e)<.5}function Ur(n,e){let t=document.elementFromPoint(n,e),o=new Set;for(;t&&!o.has(t);){o.add(t);let d=getComputedStyle(t).backgroundColor,u=kn(d);if(u&&u.a>0)return d;t=t.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Ft(n,e,t){let o=Ur(e,t),r=Wr(o),i=r?"#ffffff":"#000000";n.querySelectorAll("svg path").forEach(u=>{u.style.fill="white",u.style.stroke=i,u.style.strokeWidth="1";}),n.style.filter=r?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function tt(n,e,t,o,r="ease-in-out",i="curve",d=.25,u="auto",c){vn(),$t(n);let k=performance.now(),g=r==="linear"?C=>C:zr,T=i!=="straight",y={x:0,y:0};if(T){let C=t.x-e.x,a=t.y-e.y,p=Math.hypot(C,a)||1,s=(e.x+t.x)/2,l=(e.y+t.y)/2,m=-a/p,f=C/p,x=1;u==="left"?x=-1:u==="right"?x=1:x=Math.random()<.5?-1:1;let I=$e(d,0,1)*p;y={x:s+x*m*I,y:l+x*f*I};}return new Promise(C=>{function a(p){let s=$e((p-k)/o,0,1),l=g(s),m,f;if(T){let h=1-l;m=h*h*e.x+2*h*l*y.x+l*l*t.x,f=h*h*e.y+2*h*l*y.y+l*l*t.y;}else m=e.x+(t.x-e.x)*l,f=e.y+(t.y-e.y)*l;let I=.35*(1-l),v=Math.sin(p*.02)*I,b=Math.cos(p*.018)*I;n.style.left=`${m+v}px`,n.style.top=`${f+b}px`,Ft(n,m+v,f+b),c&&c({x:m+v,y:f+b,t:s,now:p}),s<1?requestAnimationFrame(a):C();}requestAnimationFrame(a);})}function hn(n,e){return {x:n.x+(e?.x??0),y:n.y+(e?.y??0)}}function me(n,e,t,o){let r={bubbles:true,cancelable:true,view:window,clientX:t.x,clientY:t.y,...o};try{let i=e==="pointerdown"||e==="mousedown",d=e==="pointerup"||e==="mouseup",u={button:0,buttons:i?1:0,isPrimary:!0,...r};if("PointerEvent"in window){let c=new PointerEvent(e,{pointerId:1,pointerType:"mouse",...u});n.dispatchEvent(c);}else {let c=new MouseEvent(e,u);n.dispatchEvent(c);}}catch{let i=new MouseEvent(e,r);n.dispatchEvent(i);}}function wn(n){return n&&typeof n=="object"&&n.nodeType===1}function Gr(n){if(!n)return document;if(wn(n))return n;if(typeof n=="string"){let e=document.getElementById(n);if(e)return e;let t=document.querySelector(n);if(t)return t}return document}function bn(n){if(wn(n))return {kind:"element",element:n};if(typeof n=="string"){let e=document.getElementById(n);if(e)return {kind:"element",element:e};let t=document.querySelector(n);return {kind:t?"element":"position",element:t??null}}if(typeof n=="object"&&"position"in n)return {kind:"position",point:n.position};if(typeof n=="object"&&"selector"in n){let t=Gr(n.within??null).querySelectorAll(n.selector),o=Math.max(0,Math.min(t.length-1,n.nth??0)),r=t[o]??null;return {kind:r?"element":"position",element:r}}return {kind:"position",point:{x:0,y:0}}}function xn(n,e){let t=n.getBoundingClientRect();if(!e||e==="center")return {x:t.left+t.width/2,y:t.top+t.height/2};if(e==="top-left")return {x:t.left,y:t.top};if(e==="bottom-right")return {x:t.right,y:t.bottom};let o=$e(e.x,0,1),r=$e(e.y,0,1);return {x:t.left+t.width*o,y:t.top+t.height*r}}function Cn(n){return {x:$e(n.x,0,window.innerWidth),y:$e(n.y,0,window.innerHeight)}}function qr(){return st.useEffect(()=>(window.__cursorGuide=async(n,e={})=>{let t=Array.isArray(n)?n:[{target:n,action:e.action??"none",options:e}],o=[],r=await Or();r.classList.add("visible","as-arrow"),r.classList.remove("as-pointer","pressing"),$t(r),vn();let i=parseFloat(r.style.left||"20")||20,d=parseFloat(r.style.top||"20")||20;Ft(r,i,d);for(let u of t){let{durationMs:c=800,easing:k="ease-in-out",offset:g,highlight:T=true,path:y="curve",curveStrength:C=.25,curveDirection:a="auto",anchor:p,cursorHotspot:s,dragTo:l}=u.options??{},m=u.action??u.options?.action??"none",f=performance.now(),x=bn(u.target),I=null,v=null;if(x.kind==="element"&&x.element?(v=x.element,r.classList.remove("visible"),v.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Pr(v,1500,180),$t(r),I=xn(v,p)):x.kind==="position"&&x.point&&(I=x.point),!I){o.push({ok:false,action:m,targetKind:x.kind,durationMs:Math.round(performance.now()-f),error:"Target not found"});continue}let b={x:parseFloat(r.style.left||"20")||20,y:parseFloat(r.style.top||"20")||20},h=Cn(hn(I,g));await tt(r,b,h,c,k,y,C,a);let E=h.x-b.x,w=h.y-b.y,P=Math.hypot(E,w)||1,S=E/P,A=w/P,F=Math.min(6,Math.max(3,P*.02)),M={x:h.x+S*F,y:h.y+A*F};await tt(r,h,M,Math.max(70,c*.1),"ease-out","straight",0,"right"),await tt(r,M,h,120,"ease-out","straight",0,"left"),T&&(r.classList?.add("click"),setTimeout(()=>r.classList?.remove("click"),180));let $=null;try{if(m==="click"){r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing");let D={x:s?.x??0,y:s?.y??0},R={x:h.x+D.x,y:h.y+D.y};r.style.left=`${R.x}px`,r.style.top=`${R.y}px`,Ft(r,R.x,R.y);let O=v??document.elementFromPoint(R.x,R.y)??document.body;me(O,"pointerdown",R),me(O,"mousedown",R),await new Promise(N=>setTimeout(N,90)),r.classList.remove("pressing"),me(O,"mouseup",R),me(O,"click",R),setTimeout(()=>{r.classList.remove("as-pointer"),r.classList.add("as-arrow");},140),O instanceof HTMLElement&&O.focus?.(),$=O?.id??null;}else if(m==="drag"){if(!l)throw new Error("dragTo is required for action 'drag'");let D=bn(l),R=null;if(D.kind==="element"&&D.element&&(R=xn(D.element,p)),D.kind==="position"&&D.point&&(R=D.point),!R)throw new Error("dragTo target not found");let O=Cn(hn(R,g)),N={x:h.x,y:h.y},J=v??document.elementFromPoint(N.x,N.y)??document.body;r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing"),me(J,"pointerdown",N),me(J,"mousedown",N),await tt(r,N,O,Math.max(200,c),k,y,C,a,({x:H,y:K})=>{let ae=document.elementFromPoint(H,K)??document.body,Ne={x:H,y:K};me(ae,"pointermove",Ne),me(ae,"mousemove",Ne);});let V=document.elementFromPoint(O.x,O.y)??document.body;r.classList.remove("pressing"),me(V,"pointerup",O),me(V,"mouseup",O);}o.push({ok:!0,action:m,targetKind:x.kind,durationMs:Math.round(performance.now()-f),clickedElementId:$});}catch(D){o.push({ok:false,action:m,targetKind:x.kind,durationMs:Math.round(performance.now()-f),error:D?.message??String(D)});}}return $r(r,2e3),{ok:o.every(u=>u.ok),steps:o}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var ot=qr;function Tn(){return {getDomComponents:{tool:async({includeHidden:n,selector:e})=>await Ue({includeHidden:n,selector:e}),executeEachToken:false},controlCursor:{tool:async({target:n,action:e,anchor:t,durationMs:o,dragTo:r})=>{let i=await Te(n,{action:e,anchor:t,durationMs:o,dragTo:r});if(i&&i.ok){let d=Array.isArray(i.steps)&&i.steps.length?i.steps[i.steps.length-1]:void 0,u=d?.clickedElementId?` (clicked element id: ${d.clickedElementId})`:"",c=e||d?.action||"none";return {success:true,message:c==="click"?`Cursor moved and clicked successfully${u}`:c==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:i}}return {success:false,message:"Cursor action failed",details:i}},executeEachToken:false},fillActiveInput:{tool:async({value:n})=>{let e=await Ge(n);return {success:!!e?.ok,message:e?.ok?"Active input filled successfully":e?.errors?.[0]||"Failed to fill active input",details:e}},executeEachToken:true},requestInput:{tool:async n=>({ok:true}),executeEachToken:true}}}function In({chart:n,theme:e}){let t=st.useRef(null),[o,r]=st.useState(null),[i,d]=st.useState(true);st.useEffect(()=>{let y=true;return (async()=>{try{d(!0),r(null);let a;try{a=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!y)return;if(a.default?.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:{darkMode:e==="dark",primaryColor:e==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:e==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:e==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),t.current&&y){let p=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:s}=await a.default.render(p,n);if(t.current&&y){t.current.innerHTML=s;let l=t.current.querySelector("svg");l&&(l.style.maxWidth="100%",l.style.height="auto",l.style.display="block");}}}catch(a){y&&r(a instanceof Error?a.message:"Failed to render diagram");}finally{y&&d(false);}})(),()=>{y=false;}},[n,e]);let u=e==="dark"?"#374151":"#D1D5DB",c=e==="dark"?"#1F2937":"#F9FAFB",k=e==="dark"?"#7F1D1D":"#FEF2F2",g=e==="dark"?"#FCA5A5":"#DC2626",T=e==="dark"?"#9CA3AF":"#6B7280";return o?jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${u}`,backgroundColor:k,padding:"16px",margin:"8px 0"},children:[jsxRuntime.jsx("div",{style:{fontSize:"14px",color:g,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:g,opacity:.8},children:o})]}):jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${u}`,backgroundColor:c,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[i&&jsxRuntime.jsx("div",{style:{fontSize:"14px",color:T,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsxRuntime.jsx("div",{ref:t,style:{display:i?"none":"block",textAlign:"center",minHeight:i?"0":"50px"}})]})}function ce(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fe(n){return n=n.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),n=n.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),n=n.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),n=n.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),n}function Zr(n,e="dark"){let t=(n||"").replace(/\r\n/g,`
11
+ `,document.head.appendChild(o);}en=true;}return t?(t.classList.add("as-arrow"),Oe||(Oe=client.createRoot(t),Oe.render(jsxRuntime.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=client.createRoot(t),Oe.render(jsxRuntime.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 nt.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=nt.useRef(null),[r,o]=nt.useState(null),[i,p]=nt.useState(true);nt.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?jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:T,padding:"16px",margin:"8px 0"},children:[jsxRuntime.jsx("div",{style:{fontSize:"14px",color:y,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:y,opacity:.8},children:r})]}):jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:b,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[i&&jsxRuntime.jsx("div",{style:{fontSize:"14px",color:M,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsxRuntime.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
- `),o="",r=false,i="",d=[],u=false,c=false,k=false,g=e==="dark"?"#374151":"#D1D5DB",y=e==="dark"?"#111827":"#F3F4F6",C=e==="dark"?"#E5E7EB":"#374151",a=e==="dark"?"#374151":"#F3F4F6",p=e==="dark"?"#F9FAFB":"#111827",s=()=>{u&&(o+="</ul>",u=false),c&&(o+="</ol>",c=false);},l=b=>{for(let h=b;h<t.length;h++)if(t[h].trim().length>0)return h;return -1},m=b=>{let h=b.trim(),E=h.startsWith("|")?h.slice(1):h;return (E.endsWith("|")?E.slice(0,-1):E).split("|").map(P=>P.trim())},f=b=>{let h=b.trim();if(!h.startsWith("|"))return false;let E=m(h);return E.length>=2&&E.some(w=>w.length>0)},x=b=>{let h=m(b);return h.length===0?false:h.every(E=>/^:?-{3,}:?$/.test(E))},I=b=>{let h=b.startsWith(":"),E=b.endsWith(":");return h&&E?"center":!h&&E?"right":"left"},v=b=>{let h=b,E=l(h+1);if(E===-1)return {tableHtml:"",endIndex:b};let w=m(t[h]),P=m(t[E]),S=Math.max(w.length,P.length),A=[];for(let D=0;D<S;D++){let R=P[D]||"---";A.push(I(R));}let F=[],M=E+1;for(;M<t.length;){let D=t[M].trim();if(D.length===0){M++;continue}if(!D.startsWith("|"))break;let R=m(t[M]),O=[];for(let N=0;N<S;N++)O.push(R[N]??"");F.push(O),M++;}let $=`<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;">`;$+="<thead><tr>";for(let D=0;D<S;D++){let R=Fe(ce(w[D]??"")),O=A[D],N=D===0,J=D===S-1;$+=`<th style="text-align: ${O}; padding: 10px 12px; border-bottom: 1px solid ${g}; background-color: ${a}; color: ${p}; position: sticky; top: 0; z-index: 1; ${`${N?"border-top-left-radius: 10px;":""}${J?"border-top-right-radius: 10px;":""}`}">${R}</th>`;}$+="</tr></thead>",$+="<tbody>";for(let D of F){$+="<tr>";for(let R=0;R<S;R++){let O=Fe(ce(D[R]??"")),N=A[R],J=R===0;$+=`<td style="text-align: ${N}; padding: 10px 12px; border-bottom: 1px solid ${g}; ${J?`border-left: 1px solid ${g};`:""} border-right: 1px solid ${g};">${O}</td>`;}$+="</tr>";}return $+="</tbody></table></div>",{tableHtml:$,endIndex:M-1}};for(let b=0;b<t.length;b++){let h=t[b],E=h.match(/^```\s*(\w+)?\s*$/);if(E){if(!r)s(),r=true,i=E[1]?String(E[1]):"",d=[];else {if(i==="mermaid"){k=true;let A=d.join(`
15
- `);o+=`<div class="mermaid-placeholder" data-mermaid="${ce(A)}"></div>`;}else {let A=ce(d.join(`
16
- `)),F=i?`language-${i}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${y}; color: ${C}; border: 1px solid ${g}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${F}">${A}</code></pre>`;}r=false,i="",d=[];}continue}if(r){d.push(h);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(h)){s(),o+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let w=h.match(/^(#{1,6})\s+(.+)$/);if(w){s();let A=w[1].length,F=Fe(ce(w[2].trim())),M=A<=2?"18px":A===3?"16px":"14px";o+=`<h${A} style="font-size: ${M}; font-weight: 600; margin: 8px 0 4px 0;">${F}</h${A}>`;continue}if(f(h)){let A=l(b+1);if(A!==-1&&x(t[A])){s();let{tableHtml:F,endIndex:M}=v(b);if(F){o+=F,b=M;continue}}}let P=h.match(/^\s*[-*]\s+(.+)$/),S=h.match(/^\s*\d+\.\s+(.+)$/);if(P){u||(s(),o+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',u=true);let A=Fe(ce(P[1]));o+=`<li style="margin: 2px 0;">${A}</li>`;continue}if(S){c||(s(),o+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',c=true);let A=Fe(ce(S[1]));o+=`<li style="margin: 2px 0;">${A}</li>`;continue}if(h.trim().length===0)s(),o+='<div style="height: 8px;"></div>';else {s();let A=Fe(ce(h));o+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${A}</p>`;}}if(r)if(i==="mermaid"){k=true;let b=d.join(`
17
- `);o+=`<div class="mermaid-placeholder" data-mermaid="${ce(b)}"></div>`;}else {let b=ce(d.join(`
18
- `)),h=i?`language-${i}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${y}; color: ${C}; border: 1px solid ${g}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${h}">${b}</code></pre>`;}return u&&(o+="</ul>"),c&&(o+="</ol>"),{html:o,hasMermaid:k}}function Ve({content:n,theme:e}){let{html:t,hasMermaid:o}=st.useMemo(()=>Zr(n,e),[n,e]);if(!o)return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:t}});let r=t.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),i=[];return r.forEach((d,u)=>{if(d.includes("mermaid-placeholder")){let c=d.match(/data-mermaid="([^"]*)"/);if(c){let k=c[1].replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");i.push(st__default.default.createElement(In,{key:`mermaid-${u}`,chart:k,theme:e}));}}else d.trim()&&i.push(st__default.default.createElement("div",{key:`html-${u}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:d}}));}),st__default.default.createElement(st__default.default.Fragment,{},...i)}function eo({input:n}){return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsxRuntime.jsx(Ve,{content:n?.text||"",theme:"dark"})})}function An(){return {plainText:eo}}function Rn(n,e,t,o,r,i){let d=t.get(e);if(d){let x=d.parentElement,I=document.querySelector(`[data-get-from-user-host="${e}"]`);if(I&&x!==I){try{x?.removeChild(d);}catch{}I.innerHTML="",I.appendChild(d);}}else {d=document.createElement("div"),d.className="hsafa-inline-form";let x=document.querySelector(`[data-get-from-user-host="${e}"]`);x?(x.innerHTML="",x.appendChild(d)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(d),t.set(e,d);}let u=n?.title||"Provide input",c=n?.description||"",k=n?.submitLabel||"Submit",g=n?.skipLabel||"Skip",T=Array.isArray(n?.fields)?n.fields:n?.label||n?.placeholder?[{id:"value",label:n?.label||"Value",type:"text",placeholder:n?.placeholder||""}]:[],y=o.get(e)||{submitted:false,skipped:false,values:void 0};d.innerHTML="";let C=document.createElement("form");C.style.margin="12px 0",C.style.padding="14px",C.style.border="1px solid var(--hsafa-border, #2A2C33)",C.style.borderRadius="12px",C.style.background="var(--hsafa-card, #121318)",C.style.color="var(--hsafa-text, #EDEEF0)",C.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let a=document.createElement("div");if(a.style.fontWeight="600",a.style.marginBottom="6px",a.textContent=u,C.appendChild(a),c){let x=document.createElement("div");x.style.fontSize="12px",x.style.opacity="0.8",x.style.marginBottom="10px",x.textContent=c,C.appendChild(x);}T.forEach(x=>{let I=document.createElement("div");if(I.style.margin="10px 0",x.label){let w=document.createElement("label");w.style.display="block",w.style.fontSize="12px",w.style.marginBottom="6px",w.style.opacity="0.9",w.textContent=x.label,I.appendChild(w);}let v,b=(x.type||"text").toLowerCase();if(b==="textarea"){let w=document.createElement("textarea");w.placeholder=x.placeholder||"",w.value=x.value??"",w.style.width="100%",w.style.minHeight="72px",w.style.padding="10px 12px",w.style.border="1px solid var(--hsafa-border, #2A2C33)",w.style.borderRadius="10px",w.style.background="var(--hsafa-input-bg, #17181C)",w.style.color="inherit",v=w;}else if(b==="select"&&Array.isArray(x.options)){let w=document.createElement("select");w.style.width="100%",w.style.padding="10px 12px",w.style.border="1px solid var(--hsafa-border, #2A2C33)",w.style.borderRadius="10px",w.style.background="var(--hsafa-input-bg, #17181C)",w.style.color="inherit",x.options.forEach(P=>{let S=document.createElement("option");S.value=String(P.value),S.text=String(P.label??P.value),w.appendChild(S);}),w.value=x.value??"",v=w;}else if(b==="checkbox"){let w=document.createElement("input");w.type="checkbox",w.checked=!!x.value,w.style.transform="scale(1.1)",v=w;}else {let w=document.createElement("input");w.type=b,w.placeholder=x.placeholder||"",w.value=x.value??"",w.style.width="100%",w.style.padding="10px 12px",w.style.border="1px solid var(--hsafa-border, #2A2C33)",w.style.borderRadius="10px",w.style.background="var(--hsafa-input-bg, #17181C)",w.style.color="inherit",v=w;}let h=x.id||"value";v.dataset.fieldId=h;let E=y.values&&Object.prototype.hasOwnProperty.call(y.values,h)?y.values[h]:void 0;typeof E<"u"&&(v.type==="checkbox"?v.checked=!!E:v.value=String(E)),(y.submitted||y.skipped)&&(v.setAttribute("disabled","true"),v.style.opacity="0.7"),I.appendChild(v),C.appendChild(I);});let p=String(k).trim(),s=String(g).trim(),l=!!(p||s),m=null,f=null;if(l){let x=document.createElement("div");x.style.display="flex",x.style.gap="8px",x.style.marginTop="10px",m=document.createElement("button"),m.type="submit",m.textContent=p||"Submit",m.style.padding="6px 10px",m.style.borderRadius="8px",m.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",m.style.color="#000000",f=document.createElement("button"),f.type="button",f.textContent=s||"Skip",f.style.padding="6px 10px",f.style.borderRadius="8px",f.style.background="transparent",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.color="inherit",x.appendChild(m),x.appendChild(f),C.appendChild(x);}if(C.onsubmit=x=>{x.preventDefault();let I={};C.querySelectorAll("[data-field-id]").forEach(v=>{let b=v.dataset.fieldId||"value";v.type==="checkbox"?I[b]=v.checked:I[b]=v.value??"";}),o.set(e,{submitted:true,skipped:false,values:I}),r({tool:"requestInput",toolCallId:e,output:{success:true,submitted:true,values:I}}),C.querySelectorAll("[data-field-id]").forEach(v=>{v.disabled=true,v.style.opacity="0.7";}),m&&(m.textContent=`${p||"Submit"} \u2713`,m.style.opacity="0.8",m.disabled=true),f&&(f.disabled=true);},f&&(f.onclick=()=>{o.set(e,{submitted:false,skipped:true,values:void 0}),r({tool:"requestInput",toolCallId:e,output:{success:true,submitted:false,skipped:true}}),C.querySelectorAll("[data-field-id]").forEach(x=>{x.disabled=true,x.style.opacity="0.7";}),f&&(f.textContent=`${s||"Skip"} \u2713`,f.style.opacity="0.8",f.disabled=true),m&&(m.disabled=true);}),y.submitted||y.skipped){let x=document.createElement("div");x.style.marginTop="10px",x.style.fontSize="12px",x.style.display="flex",x.style.alignItems="center",x.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",y.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"),x.appendChild(I),C.appendChild(x);try{m&&(m.disabled=!0,m.style.opacity="0.8",y.submitted&&(m.textContent=`${p||"Submit"} \u2713`)),f&&(f.disabled=!0,f.style.opacity="0.8",y.skipped&&(f.textContent=`${s||"Skip"} \u2713`));}catch{}}d.appendChild(C);}function _n(n,e,t){let o=st.useRef(new Map),r=st.useRef(new Map),i=st.useRef(e),d=st.useRef(t);i.current=e,d.current=t,st.useEffect(()=>{n.forEach(u=>{u.role==="assistant"&&u.parts?.forEach(c=>{if(!c.toolCallId)return;let k=c.toolName;if(!k&&c.type?.startsWith("tool-")&&(k=c.type.replace(/^tool-/,"")),!k)return;let g=i.current[k];if(g&&typeof g=="object"&&g.executeEachToken&&g.tool){let T=c.input||c.args||{},y=JSON.stringify(T),C=o.current.get(c.toolCallId);if(y!==C&&y!=="{}"){o.current.set(c.toolCallId,y);try{if(k==="requestInput")d.current(T,c.toolCallId);else {let p=(r.current.get(c.toolCallId)||0)+1;r.current.set(c.toolCallId,p),p>1&&g.tool({...T,toolCallNumber:p-1});}}catch{}}}});});},[n]);}var no="hsafa_dynamic_page_";function lt(n){return `${no}${n}`}function Se(n,e){try{let t=lt(n);localStorage.setItem(t,JSON.stringify(e));}catch(t){console.error("Failed to save dynamic page state:",t);}}function Ee(n){try{let e=lt(n),t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return console.error("Failed to load dynamic page state:",e),null}}function ro(n){try{let e=lt(n);localStorage.removeItem(e);}catch(e){console.error("Failed to delete dynamic page state:",e);}}function Pt(n){try{let e=lt(n);return localStorage.getItem(e)!==null}catch{return false}}function Z(n,e={}){return {success:true,message:n,...e}}function oo(n){if(n){if(n&&typeof n=="object"&&"_def"in n)try{let e=n._def,t=e.typeName||"unknown",o=e.description||void 0;return {type:"zod",zodType:t,description:o,schemaString:String(n)}}catch{return {type:"schema",note:"Schema provided but not serializable",raw:String(n)}}return typeof n=="object"?n:{type:"unknown",raw:String(n)}}}function ao(n){if(!n)return;let e=String(n).trim();if(e.length===0)return;if(e.includes('"'))return e;let t=e.split(/\r?\n+/).filter(Boolean);return (t.length>0?t:[e]).map(i=>i.trim().replace(/\s+/g," ")).map(i=>`"${i}"`).join(" ")}function X(n,e={}){return {success:false,message:n,...e}}function ct(n){let e=new Set;if(!n)return e;let t=/"([^"]+)"/g,o;for(;(o=t.exec(n))!==null;){let r=o[1].trim();r&&r.split(/\s+/).forEach(i=>{i&&i!=="."&&e.add(i);});}return e.size===0&&n.split(/\s+/).map(r=>r.replace(/"/g,"")).filter(r=>r&&r!==".").forEach(r=>e.add(r)),e}function so(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function Lt(n,e){if(e===""||e==="/")return n;if(!e.startsWith("/"))throw new Error(`Invalid pointer: ${e}`);let t=e.split("/").slice(1).map(so),o=n;for(let r of t){if(o==null||typeof o!="object")throw new Error(`Invalid pointer path at ${r}`);o=o[r];}return o}function io(n,e){try{if(e.endsWith("/-")){let t=e.slice(0,-2)||"/",o=Lt(n,t);return Array.isArray(o)}return Lt(n,e),!0}catch{return false}}function jn(n,e){if(e===null)return null;if(typeof e!="object"||Array.isArray(e))return e;let t=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};for(let o of Object.keys(e)){let r=e[o];r===null?delete t[o]:t[o]=jn(t[o],r);}return t}var Pe=class{constructor(e,t,o,r){this.chatId=e;this.state=t;this.availableTypes=o;this.onStateChange=r;}updateState(e){this.state=e,this.onStateChange(e),Se(this.chatId,e);}setGrid(e){let t={gridTemplateColumns:e.gridTemplateColumns,gridTemplateRows:e.gridTemplateRows,gap:e.gap||"0px 0px",gridTemplateAreas:ao(e.gridTemplateAreas)};this.updateState({...this.state,grid:t});let o=ct(t.gridTemplateAreas),r=Array.from(o);return Z(`Grid configured successfully with ${r.length} named area(s). When adding objects, use these area names: [${r.join(", ")}]`,{config:t,areas:r,area_count:r.length})}readGrid(){return this.state.grid?Z("Grid configuration retrieved",{grid:this.state.grid}):X("No grid configuration found. Use setGrid to create one.",{grid:null})}readAvailableTypes(){let e=this.availableTypes.map(t=>{let o={type:t.type,description:t.description,variants:t.variants};return t.schema?(o.schema=oo(t.schema),o.has_schema=true):o.has_schema=false,t.examples&&t.examples.length>0&&(o.examples=t.examples,o.example_count=t.examples.length),o});return Z(`Found ${e.length} registered component type(s). IMPORTANT: Only use these types when creating objects with setObject, or the component will not render correctly.`,{types:e,available_types:e.map(t=>t.type),total_count:e.length,types_with_schema:e.filter(t=>t.has_schema).length})}setObject(e){if(!e.object_name||typeof e.object_name!="string"||e.object_name.trim().length===0)return X("object_name is required and must be a non-empty string",{received_object_name:e.object_name,streaming_hint:"Waiting for complete object_name..."});if(e.type!==void 0&&(typeof e.type!="string"||e.type.trim().length===0))return X("type must be a non-empty string when provided",{object_name:e.object_name,received_type:e.type,streaming_hint:"Waiting for complete type..."});if(e.data===void 0)return X("data is required and cannot be undefined",{object_name:e.object_name,streaming_hint:"Waiting for data field to arrive..."});if(e.data===null)return X("Object data cannot be null",{object_name:e.object_name});let t=this.state.objects[e.object_name],o=!!t,r=[],i=[];if(e.type&&!this.availableTypes.some(a=>a.type===e.type)){let a=this.availableTypes.map(p=>p.type).join(", ");i.push(`TYPE MISMATCH: Type "${e.type}" is NOT registered. Available types: [${a}]. The object will render as raw JSON until you use a valid type. Call readAvailableTypes to see all registered types.`);}let d={object_name:e.object_name,area:e.area||e.object_name,data:e.data,type:e.type,meta:e.meta,version:o?(t.version||1)+1:1,updatedAt:new Date().toISOString()};if(this.state.grid?.gridTemplateAreas){let a=ct(this.state.grid.gridTemplateAreas),p=d.area||d.object_name;if(!a.has(p)){let s=Array.from(a).join(", ");r.push(`AREA WARNING: Area "${p}" is not defined in gridTemplateAreas. Available areas: [${s}]. The object may not be visible.`);}}this.updateState({...this.state,objects:{...this.state.objects,[e.object_name]:d}});let u=i.length>0||r.length>0,c=o?"reset":"added",k=u?`Object "${e.object_name}" ${c} with ${i.length} error(s) and ${r.length} warning(s). Review the issues below.`:`Object "${e.object_name}" ${c} successfully to area "${d.area}".`,g=(this.state.componentErrors||[]).filter(a=>a.object_name===e.object_name),T=new Date().getTime(),y=g.filter(a=>{let p=new Date(a.timestamp).getTime();return T-p<5e3}),C=y.length>0?{component_has_errors:true,component_error_count:g.length,recent_component_errors:y.slice(-3),latest_component_error:g[g.length-1],warning:`\u26A0\uFE0F This object has ${y.length} recent rendering error(s). Check component_errors field for details.`}:g.length>0?{component_has_errors:true,component_error_count:g.length,component_errors_note:`Object has ${g.length} past rendering error(s). Call readComponentErrors for details.`}:{component_has_errors:false};return {success:true,message:k,object:d,warnings:r,errors:i,has_issues:u||y.length>0,type_valid:i.length===0,area_valid:r.length===0,was_updated:o,previous_type:o?t.type:void 0,...C}}editObject(e){if(!e.object_name||typeof e.object_name!="string"||e.object_name.trim().length===0)return X("object_name is required and must be a non-empty string",{received_object_name:e.object_name,streaming_hint:"Waiting for complete object_name..."});let t=Array.isArray(e.json_patch)&&e.json_patch.length>0,o=e.merge_patch!==void 0&&e.merge_patch!==null,r=e.replace_entire_data===true&&e.new_data!==void 0;if(!t&&!o&&!r)return X("No complete edit operation provided. Waiting for json_patch, merge_patch, or replace_entire_data with new_data.",{object_name:e.object_name,has_json_patch:!!e.json_patch,has_merge_patch:e.merge_patch!==void 0,has_replace_data:!!e.replace_entire_data,streaming_hint:"Waiting for complete operation parameters..."});if(t){let u=e.json_patch.filter(c=>!c||typeof c!="object"||!c.op||typeof c.op!="string");if(u.length>0)return X('json_patch contains incomplete operations. Each operation must have an "op" field.',{object_name:e.object_name,incomplete_ops_count:u.length,total_ops:e.json_patch.length,streaming_hint:"Waiting for complete json_patch operations..."})}if(o&&typeof e.merge_patch!="object")return X("merge_patch must be an object",{object_name:e.object_name,received_type:typeof e.merge_patch,streaming_hint:"Waiting for complete merge_patch object..."});let i=this.state.objects[e.object_name];if(!i)return X(`Object "${e.object_name}" not found. Cannot edit non-existent object.`);let d=e.options?.expected_version;if(typeof d=="number"&&d!==i.version)return X(`Version conflict: expected ${d}, current ${i.version}.`,{current_version:i.version});try{let u=e.options?.patch_target==="object"?"object":"data",c={...i,data:i.data};if(e.replace_entire_data&&e.new_data!==void 0)c.data=e.new_data;else if(e.json_patch&&e.json_patch.length>0){let a=!!e.options?.strict_paths,p=e.json_patch.map(s=>{let l=s.path||"/",m=l;return u==="data"&&!l.startsWith("/data")&&(m=l==="/"?"/data":`/data${l}`),{...s,path:m}});if(a)p.forEach(l=>{if(["replace","remove","move","copy"].includes(l.op)){let m=u==="data"?{data:c.data}:c;if(!io(m,l.path))throw new Error(`Path does not exist for strict ${l.op}: ${l.path}`)}}),c=dt__namespace.applyPatch(c,p,!0).newDocument;else {let s=[],l=[],m=c;for(let f of p)try{m=dt__namespace.applyOperation(m,f,!1).newDocument,s.push({op:f,note:"applied"});}catch(x){l.push({op:f,error:x?.message||String(x)});}c=m,c.__edit_diagnostics={applied_ops_count:s.length,failed_ops_count:l.length,failed_ops:l};}}else if(e.merge_patch){let a=e.merge_patch?.data??e.merge_patch;c.data=jn(c.data,a);}c.version=(i.version||1)+1,c.updatedAt=new Date().toISOString();let k=!!e.options?.dry_run;k||this.updateState({...this.state,objects:{...this.state.objects,[e.object_name]:c}});let g=(this.state.componentErrors||[]).filter(a=>a.object_name===e.object_name),T=new Date().getTime(),y=g.filter(a=>{let p=new Date(a.timestamp).getTime();return T-p<5e3}),C=y.length>0?{component_has_errors:!0,recent_component_errors:y.slice(-3),warning:`\u26A0\uFE0F This object has ${y.length} recent rendering error(s) after edit.`}:g.length>0?{component_has_errors:!0,component_error_count:g.length}:{component_has_errors:!1};return Z(k?"Dry run completed":`Object "${e.object_name}" updated successfully`,{updated_object:e.options?.return_updated_object?c:void 0,applied_patch:e.options?.return_applied_patch?e.json_patch:void 0,dry_run:k,...C})}catch(u){return X(`Failed to edit object "${e.object_name}": ${u.message}`,{error:u.message})}}deleteObject(e){if(!this.state.objects[e.object_name])return X(`Object "${e.object_name}" not found. There is no object to delete with this name.`);let{[e.object_name]:o,...r}=this.state.objects;return this.updateState({...this.state,objects:r}),Z(`Object "${e.object_name}" deleted successfully`,{deleted:e.object_name})}readAllObjects(){let e=Object.values(this.state.objects);if(e.length===0)return Z("No objects found in the grid. Use setObject to add objects.",{objects:[],...this.getRecentErrorsSummary()});let t=this.getRecentErrorsSummary(),o=t.has_errors?`Found ${e.length} object(s) in the grid. Warning: ${t.total_error_count} component rendering error(s) detected.`:`Found ${e.length} object(s) in the grid`;return Z(o,{objects:e,...t})}readObject(e){let t=this.state.objects[e.object_name];if(!t)return X(`Object "${e.object_name}" not found. Use readAllObjects to see available objects.`);let o=(this.state.componentErrors||[]).filter(d=>d.object_name===e.object_name),r=o.length>0?{component_has_errors:true,component_errors:o.slice(-3).reverse(),component_error_count:o.length}:{component_has_errors:false},i=r.component_has_errors?`Object "${e.object_name}" retrieved. Warning: This component has ${o.length} rendering error(s).`:`Object "${e.object_name}" retrieved successfully`;return Z(i,{object:t,version:t.version,updatedAt:t.updatedAt,...r})}readAtPointer(e){let t=this.state.objects[e.object_name];if(!t)return {success:false,message:`Object "${e.object_name}" not found.`};let o=e.pointer||"/";try{let r=t.data,d=Lt(r,o==="/"?"/":o);return Z(`Value at pointer "${o}" retrieved successfully`,{value:d,pointer:o})}catch(r){return X(`Failed to read at pointer "${o}": ${r.message}`)}}renameObject(e){if(!this.state.objects[e.current_name])return X(`Object "${e.current_name}" not found. Cannot rename non-existent object.`);if(this.state.objects[e.new_name])return X(`Object "${e.new_name}" already exists. Choose a different name.`);let{[e.current_name]:o,...r}=this.state.objects,i={...o,object_name:e.new_name,area:e.new_area||e.new_name,version:o.version+1,updatedAt:new Date().toISOString()};return this.updateState({...this.state,objects:{...r,[e.new_name]:i}}),Z(`Object renamed from "${e.current_name}" to "${e.new_name}"`,{old_name:e.current_name,new_name:e.new_name})}moveObject(e){let t=this.state.objects[e.object_name];if(!t)return X(`Object "${e.object_name}" not found. Cannot move non-existent object.`);let o={...t,area:e.target_area,version:t.version+1,updatedAt:new Date().toISOString()};this.updateState({...this.state,objects:{...this.state.objects,[e.object_name]:o}});let r=[];return this.state.grid?.gridTemplateAreas&&(ct(this.state.grid.gridTemplateAreas).has(e.target_area)||r.push(`Area "${e.target_area}" is not defined in gridTemplateAreas`)),Z(`Object "${e.object_name}" moved to area "${e.target_area}"`,{object_name:e.object_name,target_area:e.target_area,warnings:r})}validateGrid(){if(!this.state.grid||!this.state.grid.gridTemplateAreas)return Z("No grid template areas defined. Validation skipped.",{valid:true,orphaned_objects:[],unused_areas:[],conflicts:[],warnings:[]});let e=ct(this.state.grid.gridTemplateAreas),t=[],o=new Set;Object.values(this.state.objects).forEach(c=>{let k=c.area||c.object_name;o.add(k),e.has(k)||t.push(c.object_name);});let r=[];e.forEach(c=>{o.has(c)||r.push(c);});let i=[];t.length>0&&i.push(`${t.length} object(s) reference non-existent grid areas`),r.length>0&&i.push(`${r.length} grid area(s) have no objects`);let d={};Object.values(this.state.objects).forEach(c=>{let k=c.area||c.object_name;d[k]=d[k]||[],d[k].push(c.object_name);});let u=[];for(let[c,k]of Object.entries(d))k.length>1&&u.push({area:c,objects:k});return Z(i.length>0?i.join(". "):"Grid is valid",{valid:t.length===0&&u.length===0,orphaned_objects:t,unused_areas:r,conflicts:u,warnings:i})}readComponentErrors(e){let t=this.state.componentErrors||[],o=e?.limit||10,r=Math.min(Math.max(1,o),50);if(t.length===0)return Z("No component errors found. All components are rendering successfully.",{errors:[],total_count:0,returned_count:0});let i=t.slice(-r).reverse();return Z(`Found ${t.length} component error(s). Returning ${i.length} most recent error(s).`,{errors:i,total_count:t.length,returned_count:i.length,limit:r,has_more:t.length>r})}clearComponentErrors(){let e=(this.state.componentErrors||[]).length;return this.updateState({...this.state,componentErrors:[]}),Z(e>0?`Cleared ${e} component error(s)`:"No component errors to clear",{cleared_count:e})}getRecentErrorsSummary(e=3){let t=this.state.componentErrors||[];return t.length===0?{has_errors:false}:{has_errors:true,recent_errors:t.slice(-e).reverse(),total_error_count:t.length}}};function Bt(n,e){let{currentChatId:t}=ne(),o=t||n,r=!!(o&&e&&e.length>0),[i,d]=st.useState(()=>!r||!o?{grid:null,objects:{},componentErrors:[]}:Ee(o)||{grid:null,objects:{},componentErrors:[]}),[u,c]=st.useState(()=>Pt(o)),k=st.useRef(null);st.useEffect(()=>{if(!r||!o){k.current=null;return}k.current=new Pe(o,i,e,a=>{d(a),c(true);});},[o,e,r]),st.useEffect(()=>{!r||!o||k.current&&(k.current=new Pe(o,i,e,a=>{d(a),c(true);}));},[i,o,e,r]),st.useEffect(()=>{if(!r||!o){d({grid:null,objects:{},componentErrors:[]}),c(false);return}let a=Ee(o);a?(d(a),c(true)):(d({grid:null,objects:{},componentErrors:[]}),c(false));},[o,r]);let g=st.useCallback(()=>k.current,[]),T=st.useCallback(()=>{c(false);},[]),y=st.useCallback(()=>{c(true);},[]),C=st.useCallback(a=>{!r||!o||d(p=>{let l=[...p.componentErrors||[],a].slice(-50),m={...p,componentErrors:l};return Se(o,m),m});},[o,r]);return {state:i,isDynamicPageOpen:u,getOperations:g,closeDynamicPage:T,openDynamicPage:y,handleError:C}}function he(n){return n&&typeof n=="object"&&"input"in n?{input:n.input,toolCallId:n.toolCallId}:{input:n}}function Ot(n,e){return {setGrid:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.setGrid(r)},readGrid:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");return o.readGrid()},readAvailableTypes:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.readAvailableTypes()},setObject:{executeEachToken:true,tool:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.setObject(r)}},editObject:{executeEachToken:true,tool:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t),i=r?.options||{},d={...r,options:{return_updated_object:i.return_updated_object??true,return_applied_patch:i.return_applied_patch??true,strict_paths:i.strict_paths??false,...i}};return o.editObject(d)}},deleteObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.deleteObject(r)},readAllObjects:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.readAllObjects()},readObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.readObject(r)},readAtPointer:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.readAtPointer(r)},renameObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.renameObject(r)},moveObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.moveObject(r)},validateGrid:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.validateGrid()},readComponentErrors:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.readComponentErrors(r)},clearComponentErrors:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.clearComponentErrors()}}}function zt(n){let{agentId:e,baseUrl:t="",tools:o={},uiComponents:r={},dynamicPageTypes:i=[],onFinish:d,onError:u,initialMessages:c=[],onMessagesChange:k}=n,{baseUrl:g,setCurrentChatId:T,registerDynamicPageTypes:y,unregisterDynamicPageTypes:C}=ne(),a=t&&t.length>0?t:g||"",[p,s]=st.useState(""),[l,m]=st.useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`);st.useEffect(()=>{try{T(l);}catch{}return ()=>{try{T(void 0);}catch{}}},[l,T]);let f=!!(i&&i.length>0);st.useEffect(()=>{if(f)return y(l,i),()=>{C(l);}},[l,f,i,y,C]);let x=Bt(f?l:"",f?i:[]),I=st.useMemo(()=>f?Ot(x.getOperations):{},[f,x.getOperations]),v=st.useMemo(()=>un(a,e,l),[a,e,l]),b=st.useCallback(_=>{console.log("Message finished:",_),d?.(_);},[d]),h=st.useCallback(_=>{console.error("Chat error:",_),u?.(_);},[u]),E=st.useMemo(()=>Tn(),[]),w=st.useMemo(()=>({...E,...I,...o}),[E,I,o]),P=st.useMemo(()=>An(),[]),S=st.useMemo(()=>({...P,...r}),[P,r]),A=st.useRef(new Map),F=st.useRef(new Map),M=st.useCallback(()=>{try{A.current.forEach(_=>{try{_.remove();}catch{}}),A.current.clear(),F.current.clear();}catch{}},[]),$=st.useCallback((_,z)=>{Rn(_,z,A.current,F.current,U=>D.current.addToolResult(U));},[]),D=st.useRef(null),R=st.useRef(new Set),O=st.useCallback((_,z,U)=>{console.error(`UI Error [${z}]:`,U),D.current&&R.current.has(_)&&(R.current.delete(_),D.current.addToolResult({tool:z,toolCallId:_,state:"output-error",errorText:U?.message||String(U)}));},[]),N=st.useCallback((_,z)=>{D.current&&R.current.has(_)&&(R.current.delete(_),D.current.addToolResult({tool:z,toolCallId:_,output:{status:"ok",rendered:true,component:z,logs:[]}}));},[]),J=st.useCallback(_=>{let z=w[_];return z?typeof z=="object"&&"tool"in z?z.tool:typeof z=="function"?z:null:null},[w]),V=react.useChat({transport:v,onFinish:b,onError:h,experimental_throttle:10,sendAutomaticallyWhen:ai.lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:_}){let z=J(_.toolName);if(_.toolName==="requestInput"){try{$(_.input,_.toolCallId);}catch(ee){console.error("requestInput render error",ee);}return}let U=_.toolName==="ui";_?.input;let se=S&&_.toolName in S;if(U||se){R.current.add(_.toolCallId);return}if(z)try{let ee=await z(_.input);V.addToolResult({tool:_.toolName,toolCallId:_.toolCallId,output:ee});}catch(ee){V.addToolResult({tool:_.toolName,toolCallId:_.toolCallId,state:"output-error",errorText:ee?.message||String(ee)});}}}),{messages:H,sendMessage:K,status:ae,stop:Ne,error:kt}=V;D.current=V,_n(H,w,$),st.useEffect(()=>{try{let _=new Set,z=[];if(H.forEach(U=>{U.role==="assistant"&&(U.parts||[]).forEach(G=>{if((G?.toolName||(typeof G?.type=="string"&&G.type.startsWith("tool-")?String(G.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let ee=G?.toolCallId||"";if(!ee)return;_.add(ee);let oe=G?.output;if(oe&&(oe.submitted||oe.skipped||oe.values)){let Ze={submitted:!!oe.submitted,skipped:!!oe.skipped,values:oe.values||void 0};F.current.set(ee,Ze);}let Ye=G?.input||G?.args||{};z.push({input:Ye,toolCallId:ee});});}),A.current.forEach((U,G)=>{if(!_.has(G)){let se=A.current.get(G);try{se?.remove();}catch{}A.current.delete(G),F.current.delete(G);}}),z.length>0){let U=requestAnimationFrame(()=>{z.forEach(({input:G,toolCallId:se})=>{try{$(G,se);}catch{}});});return ()=>cancelAnimationFrame(U)}}catch{}},[H,$]),st.useEffect(()=>{c&&c.length>0&&H.length===0&&console.log("Initial messages:",c);},[c,H.length]);let Xe=st.useRef(k);st.useEffect(()=>{Xe.current=k;},[k]);let Ae=st.useRef([]);st.useEffect(()=>{(H.length!==Ae.current.length||H.length>0&&Ae.current.length>0&&H[H.length-1]?.id!==Ae.current[Ae.current.length-1]?.id)&&Xe.current&&(Ae.current=H,Xe.current(H));},[H]);let ye=ae==="submitted"||ae==="streaming",wt=st.useCallback(async _=>{let z=_?.text!==void 0?_.text:p,U=_?.files||[],G=z.trim();if(!(!G&&U.length===0)&&!ye){_?.text===void 0&&s("");try{await K({text:G,files:U});}catch(se){throw console.error("Failed to send message:",se),se}}},[p,ye,K]),Tt=st.useCallback(()=>{if(ye)return;M(),s("");try{V?.setMessages?.([]);}catch{}let _=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;m(_);},[ye,V,M]),St=st.useCallback(_=>{try{V?.setMessages?.(_);}catch{}},[V]);return {input:p,setInput:s,messages:H,isLoading:ye,status:ae,error:kt,sendMessage:wt,stop:Ne,newChat:Tt,setMessages:St,chatApi:V,chatId:l,setChatId:m,tools:w,uiComponents:S,dynamicPage:f?x:null,formHostRef:A,formStateRef:F,cleanupForms:M,onUISuccess:N,onUIError:O}}function pt(n){let e=`hsafaChat_${n}`,t=`${e}.chats`,o=f=>`${e}.chat.${f}`,r=`${e}.currentChatId`,i=`${e}.showChat`,d=()=>{try{let f=localStorage.getItem(t);return f?JSON.parse(f):[]}catch{return []}},u=f=>{try{localStorage.setItem(t,JSON.stringify(f));}catch{}},c=f=>{try{let x=localStorage.getItem(o(f));return x?JSON.parse(x):null}catch{return null}},k=f=>{try{localStorage.setItem(o(f.id),JSON.stringify(f));}catch{}},g=f=>{let x=d(),I=x.findIndex(v=>v.id===f.id);I>=0?x[I]=f:x.unshift(f),u(x);},T=f=>{let I=d().filter(v=>v.id!==f);u(I);},y=f=>{try{localStorage.removeItem(o(f));}catch{}};return {loadChatsIndex:d,saveChatsIndex:u,loadChat:c,saveChat:k,upsertChatMeta:g,deleteChatMeta:T,deleteChatData:y,deleteChat:f=>{y(f),T(f);},loadShowChatPreference:f=>{try{let x=localStorage.getItem(i);return x!==null?x==="true":f}catch{return f}},saveShowChatPreference:f=>{try{localStorage.setItem(i,String(f));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(r)}catch{return null}},saveCurrentChatId:f=>{try{localStorage.setItem(r,f);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(r);}catch{}}}}function Wt(n){let{agentId:e,chatId:t,messages:o,isLoading:r=false,autoSave:i=true,autoRestore:d=true}=n,u=st.useMemo(()=>pt(e),[e]),[c,k]=st.useState([]),[g,T]=st.useState(null),y=st.useRef(false),C=st.useRef(false),a=st.useCallback(()=>{try{let v=u.loadChatsIndex();k(v);let b=v.find(h=>h.id===t);T(b||null);}catch(v){console.error("Failed to refresh chat list:",v);}},[u,t]);st.useEffect(()=>{a();},[a]),st.useEffect(()=>{if(!(!d||C.current)){try{u.loadCurrentChatId()&&(y.current=!0);}catch(v){console.error("Failed to restore chat:",v);}C.current=true;}},[u,d]),st.useEffect(()=>{if(!(!i||o.length===0))if(y.current){if(!r){let v=Date.now();try{u.saveChat({id:t,messages:o,agentId:e});let h=u.loadChatsIndex().find(E=>E.id===t);h&&(u.upsertChatMeta({...h,updatedAt:v}),a());}catch(b){console.error("Failed to save chat:",b);}}}else {let v=o.find(b=>b.role==="user");if(v){let b="";if(Array.isArray(v.parts)){let w=v.parts.find(P=>P&&P.type==="text");b=w&&typeof w.text=="string"?w.text:"";}let h=(b||"New chat").slice(0,80),E=Date.now();try{u.upsertChatMeta({id:t,title:h,createdAt:E,updatedAt:E}),u.saveChat({id:t,messages:o,agentId:e}),u.saveCurrentChatId(t),y.current=!0,a();}catch(w){console.error("Failed to create chat:",w);}}}},[o,e,t,u,r,i,a]);let p=st.useRef(false);st.useEffect(()=>{if(r){p.current=true;return}if(p.current&&i){p.current=false;try{let v=Date.now();u.saveChat({id:t,messages:o,agentId:e});let h=u.loadChatsIndex().find(E=>E.id===t);h&&(u.upsertChatMeta({...h,updatedAt:v}),a());}catch(v){console.error("Failed to save chat on completion:",v);}}},[r,o,t,e,u,i,a]);let s=st.useCallback(v=>{try{let b=u.loadChat(v);return b?{id:b.id,messages:b.messages,agentId:b.agentId||e}:null}catch(b){return console.error("Failed to load chat:",b),null}},[u,e]),l=st.useCallback(()=>{if(o.length!==0)try{let v=Date.now();u.saveChat({id:t,messages:o,agentId:e});let h=u.loadChatsIndex().find(E=>E.id===t);h&&(u.upsertChatMeta({...h,updatedAt:v}),a());}catch(v){console.error("Failed to save chat:",v);}},[u,t,o,e,a]),m=st.useCallback(v=>{try{u.deleteChat(v),a();}catch(b){console.error("Failed to delete chat:",b);}},[u,a]),f=st.useCallback((v,b)=>{if(v!==t)try{y.current=!0,u.saveCurrentChatId(v);let h=u.loadChat(v),E=h&&Array.isArray(h.messages)?h.messages:[];b(E),a();}catch(h){console.error("Failed to switch chat:",h);}},[u,t,a]),x=st.useCallback(v=>{y.current=false,v();},[]),I=st.useCallback(v=>{if(!v.trim())return c;let b=v.toLowerCase();return c.filter(h=>h.title.toLowerCase().includes(b))},[c]);return {chatList:c,currentChatMeta:g,refreshChatList:a,loadChat:s,saveCurrentChat:l,deleteChat:m,switchToChat:f,createNewChat:x,searchChats:I,storage:u}}function mo(n){let{messages:e,isLoading:t,sendMessage:o,setMessages:r,baseUrl:i}=n,{baseUrl:d}=ne(),u=i||d||"",[c,k]=st.useState(null),[g,T]=st.useState(""),[y,C]=st.useState([]),[a,p]=st.useState(false),s=st.useCallback((v,b,h=[])=>{k(v),T(b),C(h);},[]),l=st.useCallback(()=>{k(null),T(""),C([]);},[]),m=st.useCallback(async v=>{if(!t)try{let b=e.findIndex(E=>E.id===v);if(b===-1)return;let h=e.slice(0,b);r(h),await o({text:g.trim(),files:y.map(E=>({type:"file",url:E.url,mediaType:E.mimeType||"application/octet-stream",...E.name?{name:E.name}:{},...E.size?{size:E.size}:{}}))}),l();}catch(b){throw console.error("Failed to save edit:",b),b}},[t,e,o,g,y,r,l]),f=st.useCallback(v=>c===v,[c]),x=st.useCallback(async v=>{if(!u){console.warn("baseUrl not provided, cannot upload attachments");return}p(true);try{let b=Array.from(v).map(async E=>{if(E.size>26214400)throw new Error(`${E.name} is too large (max 25MB)`);let w=new FormData;w.append("file",E);let P=await fetch(`${u}/api/upload`,{method:"POST",body:w});if(!P.ok)throw new Error(`Upload failed: ${P.statusText}`);let S=await P.json();return {id:S.url||`${Date.now()}-${Math.random()}`,name:E.name,url:S.url,mimeType:E.type,size:E.size}}),h=await Promise.all(b);C(E=>[...E,...h]);}catch(b){throw console.error("Failed to upload files:",b),b}finally{p(false);}},[u]),I=st.useCallback(v=>{C(b=>b.filter(h=>h.id!==v));},[]);return {editingMessageId:c,editingText:g,setEditingText:T,editAttachments:y,setEditAttachments:C,editUploading:a,startEdit:s,cancelEdit:l,saveEdit:m,isEditing:f,addEditAttachments:x,removeEditAttachment:I}}function Q({IconComponent:n,...e}){return st__default.default.createElement(n,e)}function Ut({icon:n,onClick:e,ariaLabel:t,resolvedColors:o,disabled:r=false,title:i}){return jsxRuntime.jsx("button",{"aria-label":t,title:i,disabled:r,style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{r||(d.currentTarget.style.backgroundColor=o.hoverBackground,d.currentTarget.style.color=o.textColor);},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=o.mutedTextColor;},onClick:e,children:n})}function Ln({title:n,alwaysOpen:e,streaming:t,dir:o,resolvedColors:r,onNew:i,onToggleHistory:d,onClose:u,historyBtnRef:c,t:k}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:o==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:n,style:{color:r.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:n})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:r.mutedTextColor},children:[jsxRuntime.jsx(Ut,{icon:jsxRuntime.jsx(Q,{IconComponent:lucideReact.Plus,size:"20",strokeWidth:"2"}),onClick:()=>{t||i();},ariaLabel:k("header.new"),resolvedColors:r,disabled:t}),jsxRuntime.jsx("button",{ref:c,"aria-label":k("header.history"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor=r.hoverBackground,g.currentTarget.style.color=r.textColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=r.mutedTextColor;},onClick:d,children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.History,size:"20",strokeWidth:"2"})}),!e&&jsxRuntime.jsx(Ut,{icon:jsxRuntime.jsx(Q,{IconComponent:lucideReact.ChevronRight,size:"20",strokeWidth:"2",style:{transform:o==="rtl"?"rotate(180deg)":"none"}}),onClick:u,ariaLabel:k("header.close"),resolvedColors:r})]})]})}var ht=class extends st.Component{constructor(e){super(e),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(e){return {hasError:true,error:e,errorInfo:null}}componentDidMount(){let{toolCallId:e,toolName:t,onSuccess:o}=this.props;e&&t&&o&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||o(e,t);},0);}componentDidCatch(e,t){console.error(`UI Component Error (${this.props.componentName}):`,e,t),this.setState({error:e,errorInfo:t});let{toolCallId:o,toolName:r,onError:i}=this.props;o&&r&&i&&i(o,r,e);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:e,componentName:t}=this.props;return jsxRuntime.jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxRuntime.jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",t]})]}),jsxRuntime.jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxRuntime.jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsxRuntime.jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsxRuntime.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 Co=n=>{let e={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return e[n||"output-available"]||e["output-available"]},vo=n=>{let e=/^(.+?)_([a-f0-9]{6})_(.+)$/,t=n.match(e);if(t){let[,o,,r]=t;return {isMCP:true,mcpName:o.replace(/_/g," "),toolName:r.replace(/_/g," ")}}return {isMCP:false,toolName:n}},ko=n=>n.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase());function Hn({parts:n,messageId:e,openReasoningIds:t,toggleReasoning:o,resolvedColors:r,HsafaUI:i,onUIError:d,onUISuccess:u,addToolResult:c}){let k=[],g=[],T,y,C=false;for(let a of Array.isArray(n)?n:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){g.push(a.text),T||(T=a.startDate),y=a.endDate,a.state==="done"&&(C=true);continue}if(a.type==="text"&&typeof a.text=="string"){g.length&&(k.push({type:"reasoning",texts:g,startDate:T,endDate:y,isCompleted:C}),g=[],T=void 0,y=void 0,C=false),k.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let p=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(p||s||a.type==="tool-call"){g.length&&(k.push({type:"reasoning",texts:g,startDate:T,endDate:y,isCompleted:C}),g=[],T=void 0,y=void 0,C=false);let l=String(p?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");l==="requestInput"?k.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):k.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return g.length&&k.push({type:"reasoning",texts:g,startDate:T,endDate:y,isCompleted:C}),k.length?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[k.map((a,p)=>{let s=`${e}-${p}`,l=t.has(s);if(a.type==="reasoning"){let b=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",h=a.texts&&a.texts.length>0&&a.texts.some(w=>w.trim().length>0),E=()=>{h&&o(s);};return b&&!h?null:jsxRuntime.jsx("div",{onClick:E,style:{cursor:h?"pointer":"default",padding:"0"},children:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l?"4px":"0px"},children:[jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxRuntime.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!b&&jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.jsx("span",{style:{color:r.textColor,fontWeight:600,opacity:.9,background:b?"none":`linear-gradient(90deg, ${r.textColor}, ${r.mutedTextColor}, ${r.mutedTextColor})`,backgroundSize:b?"auto":"200% 100%",backgroundClip:b?"unset":"text",WebkitBackgroundClip:b?"unset":"text",WebkitTextFillColor:b?r.mutedTextColor:"transparent",animation:b?void 0:"shimmer 2s ease-in-out infinite"},children:b?"Finish Thinking":"Thinking"})]}),h&&jsxRuntime.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:l?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsxRuntime.jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsxRuntime.jsx("div",{style:{display:"grid",gridTemplateRows:l||!b?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsxRuntime.jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsxRuntime.jsx("div",{style:{fontSize:"13px",color:r.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!b&&l?a.texts:b?l?a.texts:[]:[a.texts[a.texts.length-1]]).map((w,P)=>jsxRuntime.jsx("div",{style:{marginBottom:"6px"},children:jsxRuntime.jsx(Ve,{content:w,theme:"dark"})},`rg-line-${p}-${P}`))}):jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:r.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text")return jsxRuntime.jsx("div",{style:{fontSize:"15px",color:r.textColor,lineHeight:"1.6"},children:jsxRuntime.jsx(Ve,{content:a.text,theme:"dark"})},s);let{color:m,text:f}=Co(a.status),x=a.status==="input-streaming"||a.status==="input-available";if(a.toolName==="requestInput")return jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx("div",{"data-get-from-user-host":a.toolCallId||s,style:{width:"100%"}})},s);let I=i?.[a.toolName||""];if(I)return jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx(ht,{componentName:a.toolName||"Unknown",resolvedColors:r,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:d,onSuccess:u,children:jsxRuntime.jsx(I,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:c})})},s);let v=vo(a.toolName||"tool");return jsxRuntime.jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsxs("span",{style:{fontWeight:600,color:m,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:m,animation:x?"pulse 1.5s ease-in-out infinite":void 0}}),f]}),v.isMCP?jsxRuntime.jsxs("span",{style:{fontWeight:500,color:r.textColor},children:[jsxRuntime.jsx("span",{style:{fontWeight:600},children:v.toolName}),jsxRuntime.jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsxRuntime.jsx("span",{style:{fontWeight:600,opacity:.85},children:v.mcpName})]}):jsxRuntime.jsx("span",{style:{fontWeight:500,color:r.textColor},children:ko(v.toolName)})]})})},s)}),jsxRuntime.jsx("style",{children:`
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
+ `);r+=`<div class="mermaid-placeholder" data-mermaid="${se(H)}"></div>`;}else {let H=se(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
+ `);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 ${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}=nt.useMemo(()=>zo(e,t),[e,t]);if(!r)return jsxRuntime.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__default.default.createElement(mn,{key:`mermaid-${c}`,chart:T,theme:t}));}}else p.trim()&&i.push(nt__default.default.createElement("div",{key:`html-${c}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:p}}));}),nt__default.default.createElement(nt__default.default.Fragment,{},...i)}function Wo({input:e}){return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsxRuntime.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=nt.useRef(new Map),o=nt.useRef(new Map),i=nt.useRef(t),p=nt.useRef(n);i.current=t,p.current=n,nt.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]=nt.useState(""),[d,g]=nt.useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),h=y??d,m=nt.useCallback(E=>{y===void 0&&g(E),M&&M(E);},[y,M]);nt.useEffect(()=>{try{k(h);}catch{}return ()=>{try{k(void 0);}catch{}}},[h,k]);let I=nt.useMemo(()=>Yt(a,t,h),[a,t,h]),C=nt.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=nt.useCallback(E=>{console.error("Chat error:",E),c?.(E);},[c]),u=nt.useMemo(()=>dn(),[]),w=nt.useMemo(()=>({...u,...r}),[u,r]),f=nt.useMemo(()=>fn(),[]),A=nt.useMemo(()=>({...f,...o}),[f,o]),B=nt.useRef(new Map),H=nt.useRef(new Map),j=nt.useCallback(()=>{try{B.current.forEach(E=>{try{E.remove();}catch{}}),B.current.clear(),H.current.clear();}catch{}},[]),R=nt.useCallback((E,P)=>{hn(E,P,B.current,H.current,G=>W.current.addToolResult(G));},[]),W=nt.useRef(null),F=nt.useRef(new Set),L=nt.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=nt.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=nt.useCallback(E=>{let P=w[E];return P?typeof P=="object"&&"tool"in P?P.tool:typeof P=="function"?P:null:null},[w]),D=react.useChat({transport:I,onFinish:C,onError:l,experimental_throttle:10,sendAutomaticallyWhen:ai.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),nt.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]),nt.useEffect(()=>{b&&b.length>0&&K.length===0&&console.log("Initial messages:",b);},[b,K.length]);let ge=ue==="submitted"||ue==="streaming",Be=nt.useCallback(()=>{T&&T(K,h);},[T,K,h]),Ie=nt.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=nt.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=nt.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=nt.useMemo(()=>at(t),[t]),[b,T]=nt.useState([]),[y,M]=nt.useState(null),x=nt.useRef(false),k=nt.useRef(false),a=nt.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]);nt.useEffect(()=>{a();},[a]),nt.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]),nt.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=nt.useRef(false);nt.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=nt.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=nt.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=nt.useCallback(C=>{try{c.deleteChat(C),a();}catch(l){console.error("Failed to delete chat:",l);}},[c,a]),h=nt.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=nt.useCallback(C=>{x.current=false,C();},[]),I=nt.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]=nt.useState(null),[y,M]=nt.useState(""),[x,k]=nt.useState([]),[a,v]=nt.useState(false),s=nt.useCallback((C,l,u=[])=>{T(C),M(l),k(u);},[]),d=nt.useCallback(()=>{T(null),M(""),k([]);},[]),g=nt.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=nt.useCallback(C=>b===C,[b]),m=nt.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=nt.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__default.default.createElement(e,t)}function At({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:i}){return jsxRuntime.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 jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:e,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsxRuntime.jsx(At,{icon:jsxRuntime.jsx(V,{IconComponent:lucideReact.Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||i();},ariaLabel:T("header.new"),resolvedColors:o,disabled:n}),jsxRuntime.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:jsxRuntime.jsx(V,{IconComponent:lucideReact.History,size:"20",strokeWidth:"2"})}),!t&&jsxRuntime.jsx(At,{icon:jsxRuntime.jsx(V,{IconComponent:lucideReact.ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:T("header.close"),resolvedColors:o})]})]})}var dt=class extends nt.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 jsxRuntime.jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxRuntime.jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsxRuntime.jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxRuntime.jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsxRuntime.jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsxRuntime.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?jsxRuntime.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:jsxRuntime.jsx("div",{onClick:w,style:{cursor:u?"pointer":"default",padding:"0"},children:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:d?"4px":"0px"},children:[jsxRuntime.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:[jsxRuntime.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!l&&jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.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&&jsxRuntime.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:jsxRuntime.jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsxRuntime.jsx("div",{style:{display:"grid",gridTemplateRows:d||!l?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsxRuntime.jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsxRuntime.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)=>jsxRuntime.jsx("div",{style:{marginBottom:"6px"},children:jsxRuntime.jsx(Ge,{content:f,theme:"dark"})},`rg-line-${v}-${A}`))}):jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text")return jsxRuntime.jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsxRuntime.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 jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx("div",{"data-get-from-user-host":a.toolCallId||s,style:{width:"100%"}})},s);let I=i?.[a.toolName||""];if(I)return jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx(dt,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:p,onSuccess:c,children:jsxRuntime.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 jsxRuntime.jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsxs("span",{style:{fontWeight:600,color:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.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?jsxRuntime.jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsxRuntime.jsx("span",{style:{fontWeight:600},children:C.toolName}),jsxRuntime.jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsxRuntime.jsx("span",{style:{fontWeight:600,opacity:.85},children:C.mcpName})]}):jsxRuntime.jsx("span",{style:{fontWeight:500,color:o.textColor},children:tr(C.toolName)})]})})},s)}),jsxRuntime.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 Bn(n){if(!n||Number.isNaN(n))return "0 B";let e=["B","KB","MB","GB","TB"],t=Math.min(e.length-1,Math.floor(Math.log(n)/Math.log(1024)));return `${(n/Math.pow(1024,t)).toFixed(t===0?0:1)} ${e[t]}`}function On({attachment:n,resolvedColors:e,mode:t,onRemove:o,maxWidth:r="200px"}){let i=n.mimeType?.startsWith("image/"),d=t==="editable"||t==="input",u=t==="viewable",c={display:"flex",alignItems:"center",gap:t==="input"?"8px":"6px",padding:t==="input"?"8px 12px":"6px 10px",backgroundColor:e.inputBackground,borderRadius:t==="input"?"10px":"8px",border:`1px solid ${e.borderColor}`,fontSize:t==="input"?"12px":"11px",color:e.textColor,transition:"all 0.2s ease-out",cursor:u?"pointer":"default",maxWidth:t==="input"?"140px":r,position:"relative"},k=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:t==="input"?"20px":"16px",height:t==="input"?"20px":"16px",borderRadius:t==="input"?"4px":"3px",backgroundColor:i?"transparent":e.accentColor,flexShrink:0},children:[i?jsxRuntime.jsx("img",{src:n.url,alt:n.name,style:{width:t==="input"?"20px":"16px",height:t==="input"?"20px":"16px",borderRadius:t==="input"?"4px":"3px",objectFit:"cover"},onError:g=>{g.target.style.display="none";let T=g.target.nextElementSibling;T&&(T.style.display="block");}}):null,jsxRuntime.jsx(Q,{IconComponent:lucideReact.File,size:t==="input"?14:10,strokeWidth:"2",style:{display:i?"none":"block",color:e.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsxRuntime.jsx("span",{title:n.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:n.name}),jsxRuntime.jsx("span",{style:{fontSize:t==="input"?"10px":"9px",color:e.mutedTextColor,marginTop:t==="input"?"2px":"1px"},children:Bn(n.size)})]}),t==="input"&&i&&jsxRuntime.jsx("button",{onClick:g=>{g.stopPropagation(),window.open(n.url,"_blank");},style:{background:"none",border:"none",color:e.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:g=>{g.currentTarget.style.backgroundColor=e.hoverBackground,g.currentTarget.style.color=e.textColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=e.mutedTextColor;},children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.Eye,size:"12",strokeWidth:"2"})}),d&&o&&jsxRuntime.jsx("button",{onClick:g=>{g.stopPropagation(),o(n.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:t==="input"?"auto":"16px",height:t==="input"?"auto":"16px",padding:t==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:e.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:g=>{g.currentTarget.style.backgroundColor="#ef444420",g.currentTarget.style.color="#ef4444";},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=e.mutedTextColor;},children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.X,size:"12",strokeWidth:"2"})}),u&&jsxRuntime.jsx(Q,{IconComponent:lucideReact.Download,size:"10",strokeWidth:"2",style:{color:e.mutedTextColor,flexShrink:0}})]});return u?jsxRuntime.jsx("a",{href:n.url,target:"_blank",rel:"noreferrer",style:{...c,textDecoration:"none"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor=e.hoverBackground,g.currentTarget.style.borderColor=e.primaryColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor=e.inputBackground,g.currentTarget.style.borderColor=e.borderColor;},children:k}):jsxRuntime.jsx("div",{style:c,children:k})}function Nn({attachments:n,resolvedColors:e,onRemove:t}){if(!Array.isArray(n)||n.length===0)return null;let o=typeof t=="function"?"editable":"viewable";return jsxRuntime.jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:n.map(r=>jsxRuntime.jsx(On,{attachment:r,resolvedColors:e,mode:o,onRemove:t},r.id))})}function Wn({chatMessages:n,isLoading:e,openReasoningIds:t,toggleReasoning:o,resolvedColors:r,t:i,onUserMessageClick:d,HsafaUI:u,onUIError:c,onUISuccess:k,addToolResult:g,editableMessageIcon:T}){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.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=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.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?jsxRuntime.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,jsxRuntime.jsx(V,{IconComponent:lucideReact.File,size:n==="input"?14:10,strokeWidth:"2",style:{display:i?"none":"block",color:t.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsxRuntime.jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsxRuntime.jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:wn(e.size)})]}),n==="input"&&i&&jsxRuntime.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:jsxRuntime.jsx(V,{IconComponent:lucideReact.Eye,size:"12",strokeWidth:"2"})}),p&&r&&jsxRuntime.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:jsxRuntime.jsx(V,{IconComponent:lucideReact.X,size:"12",strokeWidth:"2"})}),c&&jsxRuntime.jsx(V,{IconComponent:lucideReact.Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return c?jsxRuntime.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}):jsxRuntime.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 jsxRuntime.jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(o=>jsxRuntime.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 jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("style",{children:`
24
24
  @keyframes jumpingDots {
25
25
  0%, 80%, 100% {
26
26
  transform: translateY(0);
@@ -29,15 +29,15 @@
29
29
  transform: translateY(-5px);
30
30
  }
31
31
  }
32
- `}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[n.map((y,C)=>{let a=Array.isArray(y.parts)?y.parts:[],p=a.filter(l=>l.type==="text").map(l=>l&&typeof l.text=="string"?l.text:"").join(`
33
- `),s=a.filter(l=>l.type==="file"||l.type==="image").map(l=>{if(l.type==="image"){let m=typeof l.image=="string"?l.image:l.image?.toString?.()||"";return {id:m||`${y.id}-img-${Date.now()}`,name:l.name||"image",url:m,mimeType:l.mediaType||"image/jpeg",size:l.size||0}}else return {id:l.url||`${y.id}-file-${Date.now()}`,name:l.name||"file",url:l.url||"",mimeType:l.mediaType||"application/octet-stream",size:l.size||0}});return jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:y.role==="user"?jsxRuntime.jsx("div",{children:jsxRuntime.jsx("div",{title:i("editor.clickToEdit"),onClick:()=>d(y,y.id,p,s),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:r.accentColor,color:r.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:l=>l.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:l=>l.currentTarget.style.backgroundColor=r.accentColor,children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxRuntime.jsxs("div",{style:{flex:1},children:[p,s.length>0&&jsxRuntime.jsx(Nn,{attachments:s,resolvedColors:r})]}),jsxRuntime.jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsxRuntime.jsx(Q,{IconComponent:T||lucideReact.Pencil,size:"14",strokeWidth:"2"})})]})})}):jsxRuntime.jsx(Hn,{parts:a,messageId:y.id,openReasoningIds:t,toggleReasoning:o,resolvedColors:r,HsafaUI:u,onUIError:c,onUISuccess:k,addToolResult:g})},y.id)}),e&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function Un({input:n,setInput:e,textareaRef:t,fileInputRef:o,isLoading:r,uploading:i,attachments:d,formatBytes:u,handleRemoveAttachment:c,onFileInputChange:k,onSend:g,onStop:T,status:y,t:C,resolvedColors:a}){let p=y==="streaming"||y==="submitted",s=d.length>0||n.trim().length>0;return jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:1},children:jsxRuntime.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[d.length>0&&jsxRuntime.jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:d.map(l=>{let m=l.mimeType.startsWith("image/");return jsxRuntime.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:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:m?"transparent":a.cardBackground},children:m?jsxRuntime.jsx("img",{src:l.url,alt:l.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsxRuntime.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsxRuntime.jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsxRuntime.jsx("span",{title:l.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:l.name}),jsxRuntime.jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:u(l.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[m&&jsxRuntime.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:C("input.previewImage"),children:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsxRuntime.jsx("button",{onClick:()=>c(l.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:C("input.removeFile"),children:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntime.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},l.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsxRuntime.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:jsxRuntime.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsxRuntime.jsx("span",{children:C("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.jsx("textarea",{ref:t,"aria-label":"Prompt",rows:1,placeholder:C("input.placeholder"),value:n,onChange:l=>e(l.target.value),onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),g());},disabled:r||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"}})}),jsxRuntime.jsx("input",{ref:o,type:"file",multiple:true,onChange:k,style:{display:"none"},accept:"*/*"}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:a.mutedTextColor},children:jsxRuntime.jsx("button",{onClick:()=>o.current?.click(),disabled:r||i,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:r||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:r||i?.5:1},"aria-label":C("input.attachFiles"),children:jsxRuntime.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.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"})})})}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:r?jsxRuntime.jsx("button",{onClick:T,disabled:!p,"aria-label":C("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:p?1:.4,cursor:p?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{p&&(l.currentTarget.style.backgroundColor="#ef444430",l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="#ef444420",l.currentTarget.style.transform="scale(1)";},children:jsxRuntime.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:jsxRuntime.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsxRuntime.jsx("button",{onClick:g,disabled:!s||i,"aria-label":C("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground,color:!s||i?a.mutedTextColor:a.primaryColor,cursor:!s||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||i?.5:1},onMouseEnter:l=>{s&&!i&&(l.currentTarget.style.borderColor=a.primaryColor,l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.borderColor=a.borderColor,l.currentTarget.style.transform="scale(1)";},children:jsxRuntime.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:[jsxRuntime.jsx("path",{d:"m5 12 7-7 7 7"}),jsxRuntime.jsx("path",{d:"M12 19V5"})]})})})]})})})}function Gn(n){let e=Date.now()-n,t=Math.max(1,Math.floor(e/1e3));if(t<60)return `${t}s`;let o=Math.floor(t/60);if(o<60)return `${o}m`;let r=Math.floor(o/60);if(r<24)return `${r}h`;let i=Math.floor(r/24);if(i<7)return `${i}d`;let d=Math.floor(i/7);if(d<4)return `${d}w`;let u=Math.floor(i/30);return u<12?`${u}mo`:`${Math.floor(u/12)}y`}function qn({historyOpen:n,historySearch:e,currentChatId:t,refreshKey:o,resolvedColors:r,onClose:i,onSearchChange:d,onChatSelect:u,onChatDelete:c,loadChatsIndex:k,historyPopupRef:g}){if(!n)return null;let T=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:i}),jsxRuntime.jsxs("div",{ref:g,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${r.borderColor}`,backgroundColor:`${r.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${r.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.jsx("input",{autoFocus:true,value:e,onChange:y=>d(y.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:r.inputBackground,padding:"8px 12px",fontSize:"14px",color:r.textColor,border:`1px solid ${r.borderColor}`,outline:"none"},onFocus:y=>y.currentTarget.style.borderColor=r.primaryColor,onBlur:y=>y.currentTarget.style.borderColor=r.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let y=e.toLowerCase().trim(),C=k();return y&&(C=C.filter(a=>(a.title||"").toLowerCase().includes(y))),!C||C.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:r.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsxRuntime.jsx("div",{children:C.map((a,p)=>jsxRuntime.jsx("div",{style:{borderTop:p>0?`1px solid ${r.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===t?r.cardBackground:"transparent"},children:[jsxRuntime.jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:r.textColor},onMouseEnter:s=>s.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor="transparent",onClick:()=>u(a.id),children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:r.textColor},children:a.title||"Untitled chat"})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:r.mutedTextColor},children:Gn(a.updatedAt)})]})}),jsxRuntime.jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:r.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=r.mutedTextColor,s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.borderColor="transparent";},onClick:s=>{s.stopPropagation(),c(a.id);},children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(T,document.body):T}function Vn({isOpen:n,resolvedColors:e,onConfirm:t,onCancel:o,editProcessContent:r}){if(!n)return null;let i=r?.title||"Edit Message",d=r?.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?",u=r?.submit_button_label||"Edit",c=r?.cancel_button_label||"Cancel",k=r?.icon,g=typeof d=="function",T=g?d:null,y=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:o}),jsxRuntime.jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${e.borderColor}`,backgroundColor:e.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${e.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[k?jsxRuntime.jsx("div",{style:{flexShrink:0},children:jsxRuntime.jsx(Q,{IconComponent:k,size:"20",strokeWidth:"2"})}):jsxRuntime.jsx("div",{style:{flexShrink:0,color:e.mutedTextColor},children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.Pencil,size:"20",strokeWidth:"2"})}),jsxRuntime.jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:e.textColor,flex:1},children:i})]}),jsxRuntime.jsx("div",{style:{padding:"24px",color:e.textColor,fontSize:"14px",lineHeight:"1.6"},children:g&&T?jsxRuntime.jsx(T,{}):jsxRuntime.jsx("p",{style:{margin:0},children:d})}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${e.borderColor}`,justifyContent:"flex-end"},children:[jsxRuntime.jsx("button",{onClick:o,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${e.borderColor}`,backgroundColor:"transparent",color:e.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:C=>{C.currentTarget.style.backgroundColor=e.hoverBackground;},onMouseLeave:C=>{C.currentTarget.style.backgroundColor="transparent";},children:c}),jsxRuntime.jsx("button",{onClick:t,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:"none",backgroundColor:e.primaryColor,color:e.backgroundColor,cursor:"pointer",transition:"all 0.2s",opacity:1},onMouseEnter:C=>{C.currentTarget.style.opacity="0.9";},onMouseLeave:C=>{C.currentTarget.style.opacity="1";},children:u})]})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(y,document.body):y}function Ho({agentId:n,theme:e,primaryColor:t,primaryColorDark:o,primaryColorLight:r,backgroundColor:i,borderColor:d,textColor:u,accentColor:c,baseUrl:k="",initialMessages:g=[],onMessagesChange:T,defaultOpen:y=true,floatingButtonPosition:C={bottom:24,right:24},HsafaTools:a={},HsafaUI:p={},dynamicPageTypes:s=[],componentAboveInput:l,editProcessContent:m}){let{dir:f,theme:x,baseUrl:I,setStreamingState:v,setChatOpenState:b}=ne(),h=e||x||"dark",E=k&&k.length>0?k:I||"",S={primaryColor:h==="dark"?o||t||"#ffffff":r||t||"#000000",backgroundColor:i||(h==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:d||(h==="dark"?"#2A2C33":"#E5E7EB"),textColor:u||(h==="dark"?"#EDEEF0":"#111827"),accentColor:c||(h==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:h==="dark"?"#6f7276":"#6B7280",inputBackground:h==="dark"?"#17181C":"#F3F4F6",cardBackground:h==="dark"?"#121318":"#FFFFFF",hoverBackground:h==="dark"?"#1c1e25":"#F3F4F6"},A=j=>({"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"})[j]||j,F=zt({agentId:n,baseUrl:E,tools:a,uiComponents:p,dynamicPageTypes:s,onFinish:st.useCallback(j=>{console.log("Message finished:",j);},[]),onError:st.useCallback(j=>{console.error("Chat error:",j);},[]),initialMessages:g,onMessagesChange:T}),{input:M,setInput:$,messages:D,isLoading:R,status:O,error:N,sendMessage:J,stop:V,setMessages:H,chatId:K,setChatId:ae,tools:Ne,uiComponents:kt,formHostRef:Xe,formStateRef:Ae,cleanupForms:ye,onUISuccess:wt,onUIError:Tt,chatApi:St}=F,{attachments:_,uploading:z,fileInputRef:U,formatBytes:G,handleRemoveAttachment:se,handleFileSelection:ee,clearAttachments:oe,setAttachments:Ye}=dn(E),[Ze,Re]=st.useState(null),[Qe,Xt]=st.useState(()=>{try{return pt(n).loadShowChatPreference(!!y)}catch{return !!y}}),[Yn,Et]=st.useState(false),[Zn,Qn]=st.useState(""),[er,tr]=st.useState(0),nr=st.useRef(null),rr=st.useRef(null),[or,ar]=st.useState(new Set),[sr,It]=st.useState(false),[We,Mt]=st.useState(null),Yt=st.useRef(null),ir=an(R),ie=Wt({agentId:n,chatId:K,messages:D,isLoading:R,autoSave:true,autoRestore:false}).storage,Zt=st.useRef(false);st.useEffect(()=>{if(!Zt.current){try{let j=ie.loadCurrentChatId();if(j){ae(j);let W=ie.loadChat(j),q=W&&Array.isArray(W.messages)?W.messages:[];try{H(q);}catch{}}}catch{}Zt.current=true;}},[]),st.useEffect(()=>{try{v(K,R);}catch{}return ()=>{try{v(K,!1);}catch{}}},[K,R,v]),st.useEffect(()=>{try{b(K,Qe);}catch{}return ()=>{try{b(K,!1);}catch{}}},[K,Qe,b]);let lr=st.useCallback(async()=>{let j=M.trim();if(!j&&_.length===0||R)return;let W=[..._];$(""),oe(),Re(null);try{await J({text:j,files:W.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),Re("Failed to send message. Please try again.");}},[M,_,R,J,oe]),Qt=st.useCallback(()=>{if(R)return;ye(),$(""),oe(),Re(null);try{H([]);}catch{}let j=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;ae(j);try{ie.saveCurrentChatId(j);}catch{}},[R,oe,ie,H,ae,ye]),cr=st.useCallback(()=>{Et(j=>!j);},[]),dr=st.useCallback(()=>{Xt(false);try{ie.saveShowChatPreference(!1);}catch{}},[ie]),ur=st.useCallback(async j=>{let W=j.target.files;W&&await ee(W,Re),U.current&&(U.current.value="");},[ee,U]);st.useEffect(()=>{let j=Yt.current;if(!j)return;j.style.height="24px",j.offsetHeight,j.style.height="auto";let W=Math.min(j.scrollHeight,200);j.style.height=`${W}px`;},[M]);let pr=st.useCallback((j,W,q,fr)=>{Mt({id:W,text:q,attachments:fr||[]}),It(true);},[]),mr=st.useCallback(()=>{if(!(!We||R))try{let j=D.findIndex(q=>q.id===We.id);if(j===-1)return;let W=D.slice(0,j);try{H(W);}catch{}$(We.text),Ye(We.attachments),It(!1),Mt(null);}catch(j){console.error("Failed to edit message:",j),Re("Failed to edit message. Please try again.");}},[We,R,D,H,Ye]),gr=st.useCallback(()=>{It(false),Mt(null);},[]),en=jsxRuntime.jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:S.textColor,gap:"16px",zIndex:1e3,transform:Qe?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsxRuntime.jsx(Ln,{title:A("general.agent"),alwaysOpen:false,streaming:R,dir:f||"ltr",resolvedColors:S,onNew:Qt,onToggleHistory:cr,onClose:dr,historyBtnRef:nr,t:A}),jsxRuntime.jsx("div",{ref:ir,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":S.primaryColor,"--hsafa-border":S.borderColor,"--hsafa-card":S.cardBackground,"--hsafa-text":S.textColor,"--hsafa-muted":S.mutedTextColor,"--hsafa-bg":S.backgroundColor,"--hsafa-hover":S.hoverBackground,"--hsafa-input-bg":S.inputBackground,"--hsafa-accent":S.accentColor},children:D.length===0?jsxRuntime.jsx("div",{style:{padding:"32px",textAlign:"center",color:S.mutedTextColor,fontSize:"14px"},children:A("messages.empty")}):jsxRuntime.jsx(Wn,{chatMessages:D,isLoading:R,openReasoningIds:or,toggleReasoning:j=>ar(W=>{let q=new Set(W);return q.has(j)?q.delete(j):q.add(j),q}),resolvedColors:S,t:A,onUserMessageClick:pr,HsafaUI:kt,onUIError:Tt,onUISuccess:wt,addToolResult:j=>St?.addToolResult?.(j),editableMessageIcon:m?.message_icon})}),jsxRuntime.jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[l&&st__default.default.createElement(l,{}),Ze&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsx("span",{children:Ze}),jsxRuntime.jsx("button",{onClick:()=>Re(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),N&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsxs("span",{children:["An error occurred: ",N.message||"Please try again."]}),jsxRuntime.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"})]}),jsxRuntime.jsx(Un,{input:M,setInput:$,textareaRef:Yt,fileInputRef:U,isLoading:R,uploading:z,attachments:_,formatBytes:G,handleRemoveAttachment:se,onFileInputChange:ur,onSend:lr,onStop:()=>V(),status:O,t:A,resolvedColors:S})]}),jsxRuntime.jsx(qn,{historyOpen:Yn,historySearch:Zn,currentChatId:K,refreshKey:er,resolvedColors:S,onClose:()=>Et(false),onSearchChange:Qn,onChatSelect:j=>{if(Et(false),j&&j!==K){ye(),ae(j);try{ie.saveCurrentChatId(j);}catch{}try{let W=ie.loadChat(j),q=W&&Array.isArray(W.messages)?W.messages:[];try{H(q);}catch{}}catch{}}},onChatDelete:j=>{try{ie.deleteChat(j),tr(W=>W+1),j===K&&Qt();}catch{}},loadChatsIndex:()=>ie.loadChatsIndex(),historyPopupRef:rr}),jsxRuntime.jsx(Vn,{isOpen:sr,resolvedColors:S,onConfirm:mr,onCancel:gr,editProcessContent:m}),jsxRuntime.jsx("style",{children:`
32
+ `}),jsxRuntime.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 jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:x.role==="user"?jsxRuntime.jsx("div",{children:jsxRuntime.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:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxRuntime.jsxs("div",{style:{flex:1},children:[v,s.length>0&&jsxRuntime.jsx(Mn,{attachments:s,resolvedColors:o})]}),jsxRuntime.jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsxRuntime.jsx(V,{IconComponent:M||lucideReact.Pencil,size:"14",strokeWidth:"2"})})]})})}):jsxRuntime.jsx(kn,{parts:a,messageId:x.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:b,onUISuccess:T,addToolResult:y})},x.id)}),t&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsxRuntime.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"}}),jsxRuntime.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 jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:1},children:jsxRuntime.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&&jsxRuntime.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 jsxRuntime.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:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:g?"transparent":a.cardBackground},children:g?jsxRuntime.jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsxRuntime.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsxRuntime.jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsxRuntime.jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:d.name}),jsxRuntime.jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(d.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[g&&jsxRuntime.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:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsxRuntime.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:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntime.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},d.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsxRuntime.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:jsxRuntime.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsxRuntime.jsx("span",{children:k("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.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"}})}),jsxRuntime.jsx("input",{ref:r,type:"file",multiple:true,onChange:T,style:{display:"none"},accept:"*/*"}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:a.mutedTextColor},children:jsxRuntime.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:jsxRuntime.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.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"})})})}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:o?jsxRuntime.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:jsxRuntime.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:jsxRuntime.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsxRuntime.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:jsxRuntime.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:[jsxRuntime.jsx("path",{d:"m5 12 7-7 7 7"}),jsxRuntime.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=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:i}),jsxRuntime.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:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.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})})}),jsxRuntime.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?jsxRuntime.jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsxRuntime.jsx("div",{children:k.map((a,v)=>jsxRuntime.jsx("div",{style:{borderTop:v>0?`1px solid ${o.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===n?o.cardBackground:"transparent"},children:[jsxRuntime.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:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:o.textColor},children:a.title||"Untitled chat"})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:An(a.updatedAt)})]})}),jsxRuntime.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:jsxRuntime.jsx(V,{IconComponent:lucideReact.Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?reactDom.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=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxRuntime.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:[jsxRuntime.jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[T?jsxRuntime.jsx("div",{style:{flexShrink:0},children:jsxRuntime.jsx(V,{IconComponent:T,size:"20",strokeWidth:"2"})}):jsxRuntime.jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsxRuntime.jsx(V,{IconComponent:lucideReact.Pencil,size:"20",strokeWidth:"2"})}),jsxRuntime.jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:i})]}),jsxRuntime.jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:y&&M?jsxRuntime.jsx(M,{}):jsxRuntime.jsx("p",{style:{margin:0},children:p})}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${t.borderColor}`,justifyContent:"flex-end"},children:[jsxRuntime.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}),jsxRuntime.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?reactDom.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:nt.useCallback(S=>{g&&g(S);},[g]),onFinish:nt.useCallback(S=>{h&&h(S);},[h]),onError:nt.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=nt.useCallback(S=>{m===void 0&&Ie(S),I&&I(S);},[m,Ie,I]);nt.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]=nt.useState(null),[Xe,Dt]=nt.useState(()=>{try{return at(e).loadShowChatPreference(!!x)}catch{return !!x}}),[Dn,ft]=nt.useState(false),[Pn,Nn]=nt.useState(""),[zn,Un]=nt.useState(0),Wn=nt.useRef(null),On=nt.useRef(null),[Gn,_n]=nt.useState(new Set),[jn,ht]=nt.useState(false),[De,yt]=nt.useState(null),Pt=nt.useRef(null),qn=jt(D),[Vn,Nt]=nt.useState(m!==void 0),fe=Et({agentId:e,chatId:_,messages:O,isLoading:D,autoSave:Vn,autoRestore:false}),X=fe.storage,Pe=nt.useRef(false),Ne=nt.useRef(null);nt.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]),nt.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]),nt.useEffect(()=>{if(Pe.current)try{X.saveCurrentChatId(_);}catch{}},[_,X]),nt.useEffect(()=>{try{w(_,D);}catch{}return ()=>{try{w(_,!1);}catch{}}},[_,D,w]),nt.useEffect(()=>{try{f(_,Xe);}catch{}return ()=>{try{f(_,!1);}catch{}}},[_,Xe,f]);let Kn=nt.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=nt.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=nt.useCallback(()=>{ft(S=>!S);},[]),Yn=nt.useCallback(()=>{Dt(false);try{X.saveShowChatPreference(!1);}catch{}},[X]),Jn=nt.useCallback(async S=>{let J=S.target.files;J&&await Ht(J,Se),Ve.current&&(Ve.current.value="");},[Ht,Ve]);nt.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=nt.useCallback((S,J,q,to)=>{yt({id:J,text:q,attachments:to||[]}),ht(true);},[]),Qn=nt.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=nt.useCallback(()=>{ht(false),yt(null);},[]),Ut=jsxRuntime.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:[jsxRuntime.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}),jsxRuntime.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?jsxRuntime.jsx("div",{style:{padding:"32px",textAlign:"center",color:R.mutedTextColor,fontSize:"14px"},children:W("messages.empty")}):jsxRuntime.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})}),jsxRuntime.jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&nt__default.default.createElement(s,{}),Bt&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsx("span",{children:Bt}),jsxRuntime.jsx("button",{onClick:()=>Se(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),me&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsxs("span",{children:["An error occurred: ",me.message||"Please try again."]}),jsxRuntime.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"})]}),jsxRuntime.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})]}),jsxRuntime.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}),jsxRuntime.jsx(Fn,{isOpen:jn,resolvedColors:R,onConfirm:Qn,onCancel:eo,editProcessContent:d}),jsxRuntime.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?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(ot,{}),reactDom.createPortal(en,document.body),jsxRuntime.jsx(nn,{show:!Qe,onClick:()=>{Xt(true);try{ie.saveShowChatPreference(!0);}catch{}},resolvedColors:S,floatingButtonPosition:C})]}):en}var Kn={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"}};var Vt=class extends st__default.default.Component{constructor(e){super(e),this.state={error:null,errorInfo:null};}static getDerivedStateFromError(e){return {error:e}}componentDidCatch(e,t){console.error("Component render error:",e,t),this.setState({errorInfo:t}),this.props.onError&&this.props.onError({object_name:this.props.objectName,area:this.props.area,type:this.props.type,error:e?.message||String(e),errorStack:t?.componentStack,timestamp:new Date().toISOString()});}render(){let{error:e}=this.state,{data:t,resolvedColors:o}=this.props;return e?jsxRuntime.jsxs("div",{style:{padding:"12px",color:o.mutedTextColor,fontSize:"13px"},children:[jsxRuntime.jsx("div",{style:{color:"#ef4444",marginBottom:"8px",fontWeight:600},children:"\u26A0 Component Error"}),jsxRuntime.jsx("div",{style:{fontSize:"12px",opacity:.8},children:e?.message||String(e)}),jsxRuntime.jsxs("details",{style:{marginTop:"8px",fontSize:"11px",opacity:.6},children:[jsxRuntime.jsx("summary",{style:{cursor:"pointer"},children:"Data"}),jsxRuntime.jsx("pre",{style:{marginTop:"4px",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:JSON.stringify(t,null,2)})]})]}):this.props.children}};function zo({Component:n,data:e,resolvedColors:t,objectName:o,area:r,type:i,onError:d}){return jsxRuntime.jsx(Vt,{data:e,resolvedColors:t,objectName:o,area:r,type:i,onError:d,children:jsxRuntime.jsx(n,{data:e,...e})})}function No(n){if(!n)return [];let e=new Set,t=/"([^"]+)"/g,o;for(;(o=t.exec(n))!==null;){let r=o[1].trim();r&&r.split(/\s+/).forEach(i=>{i&&i!=="."&&e.add(i);});}return e.size===0&&n.split(/\s+/).map(r=>r.replace(/"/g,"")).filter(r=>r&&r!==".").forEach(r=>e.add(r)),Array.from(e)}function Kt({state:n,typeConfigs:e,theme:t="dark",primaryColor:o,backgroundColor:r,borderColor:i,textColor:d,onError:u}){let c={primaryColor:o||(t==="dark"?"#ffffff":"#000000"),backgroundColor:r||(t==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:i||(t==="dark"?"#2A2C33":"#E5E7EB"),textColor:d||(t==="dark"?"#EDEEF0":"#111827"),mutedTextColor:t==="dark"?"#6f7276":"#6B7280",cardBackground:t==="dark"?"#121318":"#FFFFFF"},k=st.useMemo(()=>{let p={};return e.forEach(s=>{p[s.type]=s.component;}),p},[e]),g=Object.values(n.objects),T=st.useMemo(()=>No(n.grid?.gridTemplateAreas),[n.grid?.gridTemplateAreas]),y=st.useMemo(()=>{let p=new Set;return g.forEach(s=>{let l=s.area||s.object_name;l&&p.add(l);}),p},[g]),C=T.filter(p=>!y.has(p));if(!n.grid)return jsxRuntime.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:c.mutedTextColor,fontSize:"14px",padding:"32px",textAlign:"center"},children:"No grid configuration found. The agent needs to use setGrid to create a dynamic page."});let a={display:"grid",gridTemplateColumns:n.grid.gridTemplateColumns,gridTemplateRows:n.grid.gridTemplateRows,gap:n.grid.gap||"0px 0px",gridTemplateAreas:n.grid.gridTemplateAreas||void 0,width:"100%",height:"100%",padding:"16px"};return jsxRuntime.jsxs("div",{style:a,children:[g.map(p=>{let s=p.area||p.object_name,l=p.type?k[p.type]:null,m={gridArea:s,backgroundColor:c.cardBackground,border:`1px solid ${c.borderColor}`,borderRadius:"8px",padding:"16px",overflow:"auto",display:"flex",flexDirection:"column",gap:"8px"};return jsxRuntime.jsxs("div",{style:m,children:[p.meta?.title&&jsxRuntime.jsx("h3",{style:{margin:0,fontSize:"16px",fontWeight:600,color:c.textColor},children:p.meta.title}),p.meta?.description&&jsxRuntime.jsx("p",{style:{margin:0,fontSize:"13px",color:c.mutedTextColor},children:p.meta.description}),jsxRuntime.jsx("div",{style:{flex:1},children:l?jsxRuntime.jsx(zo,{Component:l,data:p.data,resolvedColors:c,objectName:p.object_name,area:s,type:p.type,onError:u}):jsxRuntime.jsx("div",{children:p.type?jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("div",{style:{color:"#f59e0b",fontSize:"13px",marginBottom:"8px",fontWeight:600},children:['\u26A0 Unknown type: "',p.type,'"']}),jsxRuntime.jsx("div",{style:{color:c.mutedTextColor,fontSize:"12px",marginBottom:"8px"},children:"No renderer registered. Showing raw data:"}),jsxRuntime.jsx("pre",{style:{margin:0,fontSize:"11px",color:c.textColor,whiteSpace:"pre-wrap",wordBreak:"break-word",backgroundColor:c.backgroundColor,padding:"8px",borderRadius:"4px",border:`1px solid ${c.borderColor}`},children:JSON.stringify(p.data,null,2)})]}):jsxRuntime.jsx("pre",{style:{margin:0,fontSize:"12px",color:c.textColor,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:JSON.stringify(p.data,null,2)})})}),p.meta?.tags&&p.meta.tags.length>0&&jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap"},children:p.meta.tags.map((f,x)=>jsxRuntime.jsx("span",{style:{fontSize:"11px",padding:"2px 8px",borderRadius:"12px",backgroundColor:`${c.primaryColor}20`,color:c.primaryColor},children:f},x))})]},p.object_name)}),C.map(p=>jsxRuntime.jsxs("div",{style:{gridArea:p,backgroundColor:"transparent",border:`2px dashed ${c.borderColor}`,borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"center",color:c.mutedTextColor,fontSize:"12px",padding:"8px"},children:["Empty area: ",p]},`placeholder-${p}`))]})}function Go({children:n,theme:e="dark",primaryColor:t,backgroundColor:o,borderColor:r,textColor:i,mutedTextColor:d,enableBorderAnimation:u=true,borderRadius:c=16,enableContentBorder:k=true,className:g="",enableMargin:T=true,chatWidth:y=420,dir:C="ltr",onDynamicPageError:a}){let{isAnyStreaming:p,isAnyChatOpen:s,dir:l,theme:m,currentChatId:f,dynamicPageTypes:x}=ne(),I=(C??l)||"ltr",v=(e??m)||"dark",b=st.useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[h,E]=st.useState(false);st.useEffect(()=>{let J=setTimeout(()=>E(true),50);return ()=>clearTimeout(J)},[]);let[w,P]=st.useState(null),S=!!(f&&x&&x.length>0);st.useEffect(()=>{if(!S||!f){P(null);return}let J=Ee(f);P(J);let V=setInterval(()=>{let H=Ee(f);P(H);},500);return ()=>clearInterval(V)},[f,S]);let A=st__default.default.useCallback(J=>{if(f&&w){let H=[...w.componentErrors||[],J].slice(-50),K={...w,componentErrors:H};Se(f,K),P(K);}a?.(J);},[f,w,a]),F=w!==null&&w.grid!==null,M=Kn[v],$={primaryColor:t||M.primaryColor,backgroundColor:o||M.backgroundColor,borderColor:r||M.borderColor,textColor:i||M.textColor,accentColor:M.accentColor,mutedTextColor:d||M.mutedTextColor,inputBackground:M.inputBackground,cardBackground:M.cardBackground,hoverBackground:M.hoverBackground},D=typeof c=="number"?`${c}px`:c,R=typeof y=="number"?`${y}px`:y,O=T&&s?I==="rtl"?{marginLeft:R}:{marginRight:R}:{},N=T&&s?`calc(100% - ${R})`:"100%";return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:g,style:{width:N,height:"100%",transition:h?"all 0.2s ease-out":"none",padding:s&&k?"16px":"0",...O},children:jsxRuntime.jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:h?"all 0.2s ease-out":"none",borderRadius:s?D:"0",border:s&&p&&u?"none":s?`1px solid ${$.borderColor}`:"none",padding:s&&p&&u?"1.5px":"0",background:s&&p&&u?`linear-gradient(120deg, ${$.primaryColor}dd 0%, ${$.primaryColor}88 25%, ${$.primaryColor}00 50%, ${$.primaryColor}88 75%, ${$.primaryColor}dd 100%)`:"transparent",backgroundSize:s&&p&&u?"300% 300%":"auto",animation:s&&p&&u?`${b.current}-border-flow 3s ease-in-out infinite`:"none",filter:s&&p&&u?`drop-shadow(0 0 10px ${$.primaryColor}40)`:"none"},children:jsxRuntime.jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:s&&k?D:"0",backgroundColor:s&&k?$.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${$.mutedTextColor}40 transparent`},children:F?jsxRuntime.jsx(Kt,{state:w,typeConfigs:x,theme:v,primaryColor:$.primaryColor,backgroundColor:$.backgroundColor,borderColor:$.borderColor,textColor:$.textColor,onError:A}):n})})}),jsxRuntime.jsx("style",{children:`
37
- @keyframes ${b.current}-border-flow {
36
+ `})]});return typeof document<"u"&&document.body?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(et,{}),reactDom.createPortal(Ut,document.body),jsxRuntime.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=nt.useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[I,C]=nt.useState(false);nt.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 jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:y,style:{width:B,height:"100%",transition:I?"all 0.2s ease-out":"none",padding:v&&T?"16px":"0",...A},children:jsxRuntime.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:jsxRuntime.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})})}),jsxRuntime.jsx("style",{children:`
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 Jt=class{constructor(){this.components=new Map;}register(e,t){this.components.set(e,t);}unregister(e){this.components.delete(e);}get(e){return this.components.get(e)}has(e){return this.components.has(e)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},Ko=new Jt;exports.Button=Zo;exports.ContentContainer=Go;exports.CursorController=ot;exports.DynamicPage=Kt;exports.DynamicPageOperations=Pe;exports.FillActiveInput=Ge;exports.FloatingChatButton=nn;exports.HsafaChat=Ho;exports.HsafaProvider=Cr;exports.componentRegistry=Ko;exports.controlCursor=Te;exports.createDynamicPageTools=Ot;exports.deleteDynamicPageState=ro;exports.dynamicPageExists=Pt;exports.getDomComponents=Ue;exports.guideCursor=Te;exports.loadDynamicPageState=Ee;exports.saveDynamicPageState=Se;exports.useAutoScroll=an;exports.useChatStorage=Wt;exports.useDynamicPage=Bt;exports.useFileUpload=dn;exports.useHsafa=ne;exports.useHsafaAgent=zt;exports.useMessageEditor=mo;//# sourceMappingURL=index.cjs.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;exports.Button=Er;exports.ContentContainer=kr;exports.CursorController=et;exports.FillActiveInput=We;exports.FloatingChatButton=Ot;exports.HsafaChat=yr;exports.HsafaProvider=so;exports.componentRegistry=Ir;exports.controlCursor=ve;exports.getDomComponents=Ue;exports.guideCursor=ve;exports.useAutoScroll=jt;exports.useChatStorage=Et;exports.useFileUpload=Xt;exports.useHsafa=re;exports.useHsafaAgent=Mt;exports.useMessageEditor=qo;//# sourceMappingURL=index.cjs.map
43
43
  //# sourceMappingURL=index.cjs.map