@hsafa/ui-sdk 0.4.9 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +13 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +13 -13
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {jsxs,jsx,Fragment}from'react/jsx-runtime';import at,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext,Component}from'react';import {useChat}from'@ai-sdk/react';import {lastAssistantMessageIsCompleteWithToolCalls,DefaultChatTransport}from'ai';import {createRoot}from'react-dom/client';import {createPortal}from'react-dom';import {Plus,History,ChevronRight,Pencil,Trash2,File as File$1,Eye,X as X$1,Download}from'lucide-react';var Ce={};var Fr=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:i,...u})=>{let l=[Ce.button,Ce[e],Ce[t],n&&Ce.loading,i].filter(Boolean).join(" ");return jsxs("button",{className:l,disabled:r||n,...u,children:[n&&jsx("span",{className:Ce.spinner}),jsx("span",{className:n?Ce.hiddenText:void 0,children:o})]})};function _t({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:r}){if(!e)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{i.currentTarget.style.borderColor=n.primaryColor,i.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:i=>{i.currentTarget.style.borderColor=n.borderColor,i.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function Vt(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let r=t.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),t}function Kt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var Xt=createContext(void 0);function lo({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,i]=useState(new Map),[u,l]=useState(new Map),[x,I]=useState(new Map),[f,M]=useState(new Map),[b,k]=useState(void 0),a=useCallback((c,p)=>(i(w=>{let m=new Map(w);return m.set(String(c),p),m}),()=>{i(w=>{let m=new Map(w),R=m.get(String(c));return (!p||R===p)&&m.delete(String(c)),m});}),[]),v=useCallback((c,p)=>{i(w=>{let m=new Map(w),R=m.get(String(c));return (!p||R===p)&&m.delete(String(c)),m});},[]),s=useCallback((c,p)=>(l(w=>{let m=new Map(w);return m.set(String(c),p),m}),()=>{l(w=>{let m=new Map(w),R=m.get(String(c));return (!p||R===p)&&m.delete(String(c)),m});}),[]),d=useCallback((c,p)=>{l(w=>{let m=new Map(w),R=m.get(String(c));return (!p||R===p)&&m.delete(String(c)),m});},[]),g=useCallback((c,p)=>{I(w=>{let m=new Map(w);return p?m.set(c,true):m.delete(c),m});},[]),y=useCallback((c,p)=>{M(w=>{let m=new Map(w);return m.set(c,p),m});},[]),C=useMemo(()=>Array.from(x.values()).some(c=>c),[x]),T=useMemo(()=>Array.from(f.values()).some(c=>c),[f]),h=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:u,registerAction:a,unregisterAction:v,registerComponent:s,unregisterComponent:d,isAnyStreaming:C,setStreamingState:g,isAnyChatOpen:T,setChatOpenState:y,currentChatId:b,setCurrentChatId:k}),[e,t,n,o,u,a,v,s,d,C,g,T,y,b]);return jsx(Xt.Provider,{value:h,children:r})}function re(){let e=useContext(Xt);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 wt=25*1024*1024;function Jt(e){let{baseUrl:t}=re(),n=e||t||"",[r,o]=useState([]),[i,u]=useState(false),l=useRef(null),x=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]}`},[]),I=useCallback(async a=>{let v=new FormData;v.append("file",a);let s=await fetch(Kt(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]),f=useCallback(a=>{o(v=>v.filter(s=>s.id!==a));},[]),M=useCallback(async(a,v)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);v(null),u(true);let d=[];try{for(let g of s){if(g.size>wt){v(`"${g.name}" exceeds the ${x(wt)} limit.`);continue}try{let y=await I(g);d.push(y);}catch(y){console.error("Failed to upload attachment:",y),v(String(y?.message??`Failed to upload ${g.name}`));}}d.length&&o(g=>[...g,...d]);}finally{u(false);}},[I,x]),b=useCallback((a,v)=>{let s=[],d=(a||"").trim();d&&s.push({type:"text",text:d});for(let g of v||[]){let y=g.mimeType||"application/octet-stream";y.startsWith("image/")?s.push({type:"image",image:new URL(g.url),mediaType:y}):s.push({type:"file",data:g.url,mediaType:y,name:g.name});}return s},[]),k=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:i,fileInputRef:l,formatBytes:x,handleRemoveAttachment:f,handleFileSelection:M,buildUserContent:b,clearAttachments:k,setAttachments:o,MAX_UPLOAD_SIZE:wt}}function Zt(e,t,n){return new DefaultChatTransport({api:`${e}/api/run/${t}`,fetch:async(r,o)=>{let u={...o?.body?JSON.parse(o.body):{},chatId:n};return fetch(r,{...o,body:JSON.stringify(u)})}})}function mo(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 go(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 Tt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function It(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 fo(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(u=>u.trim()).slice(0,2);i.length>0&&(r+="."+i.join("."));}let o=n.parentElement;if(o){let i=Array.from(o.children).filter(u=>u.tagName===n.tagName);if(i.length>1){let u=i.indexOf(n)+1;r+=`:nth-child(${u})`;}}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 u=n&&i.querySelector(n)||i,l=[],x=[];r==="inputs"?x=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:x=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],u.querySelectorAll(x.join(", ")).forEach(s=>{let d=mo(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:fo(s)};s instanceof HTMLInputElement?(g.type=s.type,g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=It(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=It(s),g.disabled=s.disabled,g.required=s.required):s instanceof HTMLSelectElement?(g.name=s.name||void 0,g.value=It(s),g.disabled=s.disabled,g.required=s.required,g.options=Array.from(s.options).map(y=>({value:y.value,label:y.text,selected:y.selected,disabled:y.disabled}))):s instanceof HTMLButtonElement?(g.type=s.type,g.disabled=s.disabled,g.text=Tt(s)):s instanceof HTMLAnchorElement?(g.href=s.href,g.text=Tt(s)):s instanceof HTMLImageElement?(g.text=s.alt||void 0,g.label=s.alt||g.label):g.text=Tt(s),g.label=go(s),g.role=s.getAttribute("role")||void 0,g.ariaLabel=s.getAttribute("aria-label")||void 0,l.push(g);});let f=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;l.sort((s,d)=>f(d)-f(s));let M=l.length,k=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=M>k,v=a?l.slice(0,k):l;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 Qt(e){return !!e&&e.nodeType===1}function ae(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function en(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ae(e,"input");}function yo(e,t){e.checked!==t&&e.click();}function ho(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 xo(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 bo(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function Co(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&&Qt(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")yo(o,!!e);else if(i==="radio"){let u=o.name;if(u&&e!=null&&String(o.value)!==String(e)){let l=document.querySelector(`input[type="radio"][name="${CSS.escape(u)}"][value="${CSS.escape(String(e))}"]`);l?l.click():o.click();}else o.click();}else if(i==="file")if(e instanceof File||Array.isArray(e)&&e.every(u=>u instanceof File))Co(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 u=i==="date"?bo(e):String(e??"");en(o,u),ae(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,i=String(e??"");return en(o,i),ae(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?xo(o,Array.isArray(e)?e:[e]):ho(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(Qt(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,Qe={},nn=false,Re=null,tt=false;function Mt(e){e.classList.add("visible");}function cn(){tt=true,Re!=null&&(clearTimeout(Re),Re=null);}function ko(e,t=1500){tt||(Re!=null&&clearTimeout(Re),Re=window.setTimeout(()=>{tt||e.classList.remove("visible");},t));}function wo(e,t=1200){tt=false,ko(e,t);}function To(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 Io(e,t=1500,n=160){let r=performance.now(),o=e?To(e):[],i=()=>{let f=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(M=>{f.push(M.scrollLeft,M.scrollTop);}),f},u=()=>{if(!e)return {x:0,y:0};let f=e.getBoundingClientRect();return {x:f.left,y:f.top}},l=i(),x=u(),I=performance.now();return new Promise(f=>{function M(b){let k=i(),a=u(),v=false;for(let s=0;s<k.length;s++)if(k[s]!==l[s]){v=true;break}if(!v&&e&&(a.x!==x.x||a.y!==x.y)&&(v=true),v&&(l=k,x=a,I=b),b-I>=n||b-r>=t){f();return}requestAnimationFrame(M);}requestAnimationFrame(M);})}var Mo='<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>',So='<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 Eo(){if(!Qe.arrow)try{Qe.arrow=Mo,Qe.pointer=So;}catch(e){console.warn("Failed to set cursor SVGs",e);}return Qe}function on({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function Ao(){let e="demo-fake-cursor",t=document.getElementById(e),n=await Eo();if(!nn){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
|
|
1
|
+
import {jsxs,jsx,Fragment}from'react/jsx-runtime';import at,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext,Component}from'react';import {useChat}from'@ai-sdk/react';import {lastAssistantMessageIsCompleteWithToolCalls,DefaultChatTransport}from'ai';import {createRoot}from'react-dom/client';import {createPortal}from'react-dom';import {Plus,History,ChevronRight,Pencil,Trash2,File as File$1,Eye,X as X$1,Download}from'lucide-react';var ve={};var Lr=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:l,...u})=>{let i=[ve.button,ve[e],ve[t],n&&ve.loading,l].filter(Boolean).join(" ");return jsxs("button",{className:i,disabled:r||n,...u,children:[n&&jsx("span",{className:ve.spinner}),jsx("span",{className:n?ve.hiddenText:void 0,children:o})]})};function jt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:r}){if(!e)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{l.currentTarget.style.borderColor=n.primaryColor,l.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:l=>{l.currentTarget.style.borderColor=n.borderColor,l.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function Kt(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let r=t.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),t}function Xt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var Yt=createContext(void 0);function co({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,l]=useState(new Map),[u,i]=useState(new Map),[h,I]=useState(new Map),[f,S]=useState(new Map),[b,k]=useState(void 0),a=useCallback((c,p)=>(l(T=>{let m=new Map(T);return m.set(String(c),p),m}),()=>{l(T=>{let m=new Map(T),F=m.get(String(c));return (!p||F===p)&&m.delete(String(c)),m});}),[]),v=useCallback((c,p)=>{l(T=>{let m=new Map(T),F=m.get(String(c));return (!p||F===p)&&m.delete(String(c)),m});},[]),s=useCallback((c,p)=>(i(T=>{let m=new Map(T);return m.set(String(c),p),m}),()=>{i(T=>{let m=new Map(T),F=m.get(String(c));return (!p||F===p)&&m.delete(String(c)),m});}),[]),d=useCallback((c,p)=>{i(T=>{let m=new Map(T),F=m.get(String(c));return (!p||F===p)&&m.delete(String(c)),m});},[]),g=useCallback((c,p)=>{I(T=>{let m=new Map(T);return p?m.set(c,true):m.delete(c),m});},[]),C=useCallback((c,p)=>{S(T=>{let m=new Map(T);return m.set(c,p),m});},[]),y=useMemo(()=>Array.from(h.values()).some(c=>c),[h]),w=useMemo(()=>Array.from(f.values()).some(c=>c),[f]),x=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:u,registerAction:a,unregisterAction:v,registerComponent:s,unregisterComponent:d,isAnyStreaming:y,setStreamingState:g,isAnyChatOpen:w,setChatOpenState:C,currentChatId:b,setCurrentChatId:k}),[e,t,n,o,u,a,v,s,d,y,g,w,C,b]);return jsx(Yt.Provider,{value:x,children:r})}function ae(){let e=useContext(Yt);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 Tt=25*1024*1024;function Zt(e){let{baseUrl:t}=ae(),n=e||t||"",[r,o]=useState([]),[l,u]=useState(false),i=useRef(null),h=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]}`},[]),I=useCallback(async a=>{let v=new FormData;v.append("file",a);let s=await fetch(Xt(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]),f=useCallback(a=>{o(v=>v.filter(s=>s.id!==a));},[]),S=useCallback(async(a,v)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);v(null),u(true);let d=[];try{for(let g of s){if(g.size>Tt){v(`"${g.name}" exceeds the ${h(Tt)} limit.`);continue}try{let C=await I(g);d.push(C);}catch(C){console.error("Failed to upload attachment:",C),v(String(C?.message??`Failed to upload ${g.name}`));}}d.length&&o(g=>[...g,...d]);}finally{u(false);}},[I,h]),b=useCallback((a,v)=>{let s=[],d=(a||"").trim();d&&s.push({type:"text",text:d});for(let g of v||[]){let C=g.mimeType||"application/octet-stream";C.startsWith("image/")?s.push({type:"image",image:new URL(g.url),mediaType:C}):s.push({type:"file",data:g.url,mediaType:C,name:g.name});}return s},[]),k=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:l,fileInputRef:i,formatBytes:h,handleRemoveAttachment:f,handleFileSelection:S,buildUserContent:b,clearAttachments:k,setAttachments:o,MAX_UPLOAD_SIZE:Tt}}function Qt(e,t,n,r){return console.log("\u{1F680} [SDK] createHsafaTransport called with templateParams:",r),new DefaultChatTransport({api:`${e}/api/run/${t}`,fetch:async(o,l)=>{let u=l||{},i=u?.body?JSON.parse(u.body):{},h=r&&typeof r=="object"?r:{};console.log("\u{1F680} [SDK] Before merge - body:",i),console.log("\u{1F680} [SDK] Before merge - mergedParams:",h);let I={...h,...i,chatId:n};return console.log("\u{1F680} [SDK] After merge - enhancedBody:",I),fetch(o,{...l,body:JSON.stringify(I)})}})}function go(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 fo(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 It(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function St(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 yo(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 l=n.className.split(" ").filter(u=>u.trim()).slice(0,2);l.length>0&&(r+="."+l.join("."));}let o=n.parentElement;if(o){let l=Array.from(o.children).filter(u=>u.tagName===n.tagName);if(l.length>1){let u=l.indexOf(n)+1;r+=`:nth-child(${u})`;}}t.unshift(r),n=o;}return t.slice(-3).join(" > ")}async function We(e={}){try{let{includeHidden:t=!1,selector:n,what:r="content",limit:o}=e,l=document.querySelector(".hsafa-content-container");if(!l)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 u=n&&l.querySelector(n)||l,i=[],h=[];r==="inputs"?h=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:h=["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"],u.querySelectorAll(h.join(", ")).forEach(s=>{let d=go(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:yo(s)};s instanceof HTMLInputElement?(g.type=s.type,g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=St(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=St(s),g.disabled=s.disabled,g.required=s.required):s instanceof HTMLSelectElement?(g.name=s.name||void 0,g.value=St(s),g.disabled=s.disabled,g.required=s.required,g.options=Array.from(s.options).map(C=>({value:C.value,label:C.text,selected:C.selected,disabled:C.disabled}))):s instanceof HTMLButtonElement?(g.type=s.type,g.disabled=s.disabled,g.text=It(s)):s instanceof HTMLAnchorElement?(g.href=s.href,g.text=It(s)):s instanceof HTMLImageElement?(g.text=s.alt||void 0,g.label=s.alt||g.label):g.text=It(s),g.label=fo(s),g.role=s.getAttribute("role")||void 0,g.ariaLabel=s.getAttribute("aria-label")||void 0,i.push(g);});let f=s=>s.isVisible?r==="inputs"?s.tag==="input"||s.tag==="textarea"||s.tag==="select"||s.role==="textbox"?3:s.tag==="button"||s.tag==="a"?2:1:["header","nav","main","footer"].includes(s.tag)?5:["section","article","aside"].includes(s.tag)||["h1","h2","h3"].includes(s.tag)?4:["h4","h5","h6"].includes(s.tag)?3:s.tag==="form"?4:s.tag==="label"?3:s.tag==="input"||s.tag==="textarea"||s.tag==="select"?4:s.tag==="p"||s.tag==="img"||s.tag==="button"||s.tag==="a"?3:1:0;i.sort((s,d)=>f(d)-f(s));let S=i.length,k=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=S>k,v=a?i.slice(0,k):i;return {ok:!0,components:v,count:v.length,total:S,truncated:a,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=We);async function ke(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=ke);function en(e){return !!e&&e.nodeType===1}function se(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function tn(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,se(e,"input");}function ho(e,t){e.checked!==t&&e.click();}function xo(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);se(e,"input"),se(e,"change");}function bo(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);}),se(e,"input"),se(e,"change");}function Co(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function vo(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}),se(e,"input"),se(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&en(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,l=(o.type||"text").toLowerCase();if(l==="checkbox")ho(o,!!e);else if(l==="radio"){let u=o.name;if(u&&e!=null&&String(o.value)!==String(e)){let i=document.querySelector(`input[type="radio"][name="${CSS.escape(u)}"][value="${CSS.escape(String(e))}"]`);i?i.click():o.click();}else o.click();}else if(l==="file")if(e instanceof File||Array.isArray(e)&&e.every(u=>u instanceof File))vo(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 u=l==="date"?Co(e):String(e??"");tn(o,u),se(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,l=String(e??"");return tn(o,l),se(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?bo(o,Array.isArray(e)?e:[e]):xo(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(en(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(e??""),se(o,"input"),se(o,"change"),o.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${r}`}],errors:[`Unsupported active element: ${r}`]}}catch(r){return {ok:false,filled:[{key:"active",status:"error",message:r?.message??String(r)}],errors:[r?.message??String(r)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var Oe=null,Qe={},on=false,Re=null,tt=false;function Mt(e){e.classList.add("visible");}function dn(){tt=true,Re!=null&&(clearTimeout(Re),Re=null);}function wo(e,t=1500){tt||(Re!=null&&clearTimeout(Re),Re=window.setTimeout(()=>{tt||e.classList.remove("visible");},t));}function To(e,t=1200){tt=false,wo(e,t);}function Io(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 So(e,t=1500,n=160){let r=performance.now(),o=e?Io(e):[],l=()=>{let f=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(S=>{f.push(S.scrollLeft,S.scrollTop);}),f},u=()=>{if(!e)return {x:0,y:0};let f=e.getBoundingClientRect();return {x:f.left,y:f.top}},i=l(),h=u(),I=performance.now();return new Promise(f=>{function S(b){let k=l(),a=u(),v=false;for(let s=0;s<k.length;s++)if(k[s]!==i[s]){v=true;break}if(!v&&e&&(a.x!==h.x||a.y!==h.y)&&(v=true),v&&(i=k,h=a,I=b),b-I>=n||b-r>=t){f();return}requestAnimationFrame(S);}requestAnimationFrame(S);})}var Mo='<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>',Eo='<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 Ao(){if(!Qe.arrow)try{Qe.arrow=Mo,Qe.pointer=Eo;}catch(e){console.warn("Failed to set cursor SVGs",e);}return Qe}function rn({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function Ro(){let e="demo-fake-cursor",t=document.getElementById(e),n=await Ao();if(!on){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
|
|
2
2
|
.fake-cursor { pointer-events: none; opacity: 0; transition: opacity 0.2s ease; z-index: 2147483647; }
|
|
3
3
|
.fake-cursor.visible { opacity: 1; }
|
|
4
4
|
.fake-cursor .arrow { display: none; }
|
|
@@ -8,19 +8,19 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import at,{createContext,useRe
|
|
|
8
8
|
.fake-cursor.as-pointer .arrow { display: none; }
|
|
9
9
|
.fake-cursor.as-pointer .pointer { display: block; }
|
|
10
10
|
.fake-cursor.pressing .pointer svg path { filter: brightness(0.9); }
|
|
11
|
-
`,document.head.appendChild(o);}nn=true;}return t?(t.classList.add("as-arrow"),Oe||(Oe=createRoot(t),Oe.render(jsx(on,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),Oe=createRoot(t),Oe.render(jsx(on,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Fe(e,t,n){return Math.max(t,Math.min(n,e))}function Ro(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function dn(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,u,l,x=1]=o;return {r:i,g:u,b:l,a:x}}function Fo({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 Lo(e){let t=e?dn(e):null;return !t||t.a===0?false:Fo(t)<.5}function Ho(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let u=getComputedStyle(n).backgroundColor,l=dn(u);if(l&&l.a>0)return u;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function St(e,t,n){let r=Ho(t,n),o=Lo(r),i=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(l=>{l.style.fill="white",l.style.stroke=i,l.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 et(e,t,n,r,o="ease-in-out",i="curve",u=.25,l="auto",x){cn(),Mt(e);let I=performance.now(),f=o==="linear"?k=>k:Ro,M=i!=="straight",b={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,y=k/v,C=1;l==="left"?C=-1:l==="right"?C=1:C=Math.random()<.5?-1:1;let T=Fe(u,0,1)*v;b={x:s+C*g*T,y:d+C*y*T};}return new Promise(k=>{function a(v){let s=Fe((v-I)/r,0,1),d=f(s),g,y;if(M){let p=1-d;g=p*p*t.x+2*p*d*b.x+d*d*n.x,y=p*p*t.y+2*p*d*b.y+d*d*n.y;}else g=t.x+(n.x-t.x)*d,y=t.y+(n.y-t.y)*d;let T=.35*(1-d),h=Math.sin(v*.02)*T,c=Math.cos(v*.018)*T;e.style.left=`${g+h}px`,e.style.top=`${y+c}px`,St(e,g+h,y+c),x&&x({x:g+h,y:y+c,t:s,now:v}),s<1?requestAnimationFrame(a):k();}requestAnimationFrame(a);})}function rn(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",u=t==="pointerup"||t==="mouseup",l={button:0,buttons:i?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let x=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...l});e.dispatchEvent(x);}else {let x=new MouseEvent(t,l);e.dispatchEvent(x);}}catch{let i=new MouseEvent(t,o);e.dispatchEvent(i);}}function un(e){return e&&typeof e=="object"&&e.nodeType===1}function $o(e){if(!e)return document;if(un(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 an(e){if(un(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=$o(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 sn(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 ln(e){return {x:Fe(e.x,0,window.innerWidth),y:Fe(e.y,0,window.innerHeight)}}function Bo(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await Ao();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),Mt(o),cn();let i=parseFloat(o.style.left||"20")||20,u=parseFloat(o.style.top||"20")||20;St(o,i,u);for(let l of n){let{durationMs:x=800,easing:I="ease-in-out",offset:f,highlight:M=true,path:b="curve",curveStrength:k=.25,curveDirection:a="auto",anchor:v,cursorHotspot:s,dragTo:d}=l.options??{},g=l.action??l.options?.action??"none",y=performance.now(),C=an(l.target),T=null,h=null;if(C.kind==="element"&&C.element?(h=C.element,o.classList.remove("visible"),h.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Io(h,1500,180),Mt(o),T=sn(h,v)):C.kind==="position"&&C.point&&(T=C.point),!T){r.push({ok:false,action:g,targetKind:C.kind,durationMs:Math.round(performance.now()-y),error:"Target not found"});continue}let c={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},p=ln(rn(T,f));await et(o,c,p,x,I,b,k,a);let w=p.x-c.x,m=p.y-c.y,R=Math.hypot(w,m)||1,A=w/R,H=m/R,K=Math.min(6,Math.max(3,R*.02)),q={x:p.x+A*K,y:p.y+H*K};await et(o,p,q,Math.max(70,x*.1),"ease-out","straight",0,"right"),await et(o,q,p,120,"ease-out","straight",0,"left"),M&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let L=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},$={x:p.x+F.x,y:p.y+F.y};o.style.left=`${$.x}px`,o.style.top=`${$.y}px`,St(o,$.x,$.y);let N=h??document.elementFromPoint($.x,$.y)??document.body;de(N,"pointerdown",$),de(N,"mousedown",$),await new Promise(O=>setTimeout(O,90)),o.classList.remove("pressing"),de(N,"mouseup",$),de(N,"click",$),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),N instanceof HTMLElement&&N.focus?.(),L=N?.id??null;}else if(g==="drag"){if(!d)throw new Error("dragTo is required for action 'drag'");let F=an(d),$=null;if(F.kind==="element"&&F.element&&($=sn(F.element,v)),F.kind==="position"&&F.point&&($=F.point),!$)throw new Error("dragTo target not found");let N=ln(rn($,f)),O={x:p.x,y:p.y},G=h??document.elementFromPoint(O.x,O.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),de(G,"pointerdown",O),de(G,"mousedown",O),await et(o,O,N,Math.max(200,x),I,b,k,a,({x:he,y:ue})=>{let xe=document.elementFromPoint(he,ue)??document.body,Ie={x:he,y:ue};de(xe,"pointermove",Ie),de(xe,"mousemove",Ie);});let P=document.elementFromPoint(N.x,N.y)??document.body;o.classList.remove("pressing"),de(P,"pointerup",N),de(P,"mouseup",N);}r.push({ok:!0,action:g,targetKind:C.kind,durationMs:Math.round(performance.now()-y),clickedElementId:L});}catch(F){r.push({ok:false,action:g,targetKind:C.kind,durationMs:Math.round(performance.now()-y),error:F?.message??String(F)});}}return wo(o,2e3),{ok:r.every(l=>l.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var ot=Bo;function pn(){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 u=Array.isArray(i.steps)&&i.steps.length?i.steps[i.steps.length-1]:void 0,l=u?.clickedElementId?` (clicked element id: ${u.clickedElementId})`:"",x=t||u?.action||"none";return {success:true,message:x==="click"?`Cursor moved and clicked successfully${l}`:x==="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 fn({chart:e,theme:t}){let n=useRef(null),[r,o]=useState(null),[i,u]=useState(true);useEffect(()=>{let b=true;return (async()=>{try{u(!0),o(null);let a;try{a=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!b)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&&b){let v=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:s}=await a.default.render(v,e);if(n.current&&b){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){b&&o(a instanceof Error?a.message:"Failed to render diagram");}finally{b&&u(false);}})(),()=>{b=false;}},[e,t]);let l=t==="dark"?"#374151":"#D1D5DB",x=t==="dark"?"#1F2937":"#F9FAFB",I=t==="dark"?"#7F1D1D":"#FEF2F2",f=t==="dark"?"#FCA5A5":"#DC2626",M=t==="dark"?"#9CA3AF":"#6B7280";return r?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${l}`,backgroundColor:I,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:f,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:f,opacity:.8},children:r})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${l}`,backgroundColor:x,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[i&&jsx("div",{style:{fontSize:"14px",color:M,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:i?"none":"block",textAlign:"center",minHeight:i?"0":"50px"}})]})}function se(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 Wo(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
|
|
11
|
+
`,document.head.appendChild(o);}on=true;}return t?(t.classList.add("as-arrow"),Oe||(Oe=createRoot(t),Oe.render(jsx(rn,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),Oe=createRoot(t),Oe.render(jsx(rn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Fe(e,t,n){return Math.max(t,Math.min(n,e))}function Fo(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function un(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),[l,u,i,h=1]=o;return {r:l,g:u,b:i,a:h}}function Lo({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 Ho(e){let t=e?un(e):null;return !t||t.a===0?false:Lo(t)<.5}function $o(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let u=getComputedStyle(n).backgroundColor,i=un(u);if(i&&i.a>0)return u;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Et(e,t,n){let r=$o(t,n),o=Ho(r),l=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(i=>{i.style.fill="white",i.style.stroke=l,i.style.strokeWidth="1";}),e.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function et(e,t,n,r,o="ease-in-out",l="curve",u=.25,i="auto",h){dn(),Mt(e);let I=performance.now(),f=o==="linear"?k=>k:Fo,S=l!=="straight",b={x:0,y:0};if(S){let k=n.x-t.x,a=n.y-t.y,v=Math.hypot(k,a)||1,s=(t.x+n.x)/2,d=(t.y+n.y)/2,g=-a/v,C=k/v,y=1;i==="left"?y=-1:i==="right"?y=1:y=Math.random()<.5?-1:1;let w=Fe(u,0,1)*v;b={x:s+y*g*w,y:d+y*C*w};}return new Promise(k=>{function a(v){let s=Fe((v-I)/r,0,1),d=f(s),g,C;if(S){let p=1-d;g=p*p*t.x+2*p*d*b.x+d*d*n.x,C=p*p*t.y+2*p*d*b.y+d*d*n.y;}else g=t.x+(n.x-t.x)*d,C=t.y+(n.y-t.y)*d;let w=.35*(1-d),x=Math.sin(v*.02)*w,c=Math.cos(v*.018)*w;e.style.left=`${g+x}px`,e.style.top=`${C+c}px`,Et(e,g+x,C+c),h&&h({x:g+x,y:C+c,t:s,now:v}),s<1?requestAnimationFrame(a):k();}requestAnimationFrame(a);})}function an(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function ue(e,t,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let l=t==="pointerdown"||t==="mousedown",u=t==="pointerup"||t==="mouseup",i={button:0,buttons:l?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let h=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...i});e.dispatchEvent(h);}else {let h=new MouseEvent(t,i);e.dispatchEvent(h);}}catch{let l=new MouseEvent(t,o);e.dispatchEvent(l);}}function pn(e){return e&&typeof e=="object"&&e.nodeType===1}function Bo(e){if(!e)return document;if(pn(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 sn(e){if(pn(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=Bo(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 ln(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 cn(e){return {x:Fe(e.x,0,window.innerWidth),y:Fe(e.y,0,window.innerHeight)}}function Do(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await Ro();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),Mt(o),dn();let l=parseFloat(o.style.left||"20")||20,u=parseFloat(o.style.top||"20")||20;Et(o,l,u);for(let i of n){let{durationMs:h=800,easing:I="ease-in-out",offset:f,highlight:S=true,path:b="curve",curveStrength:k=.25,curveDirection:a="auto",anchor:v,cursorHotspot:s,dragTo:d}=i.options??{},g=i.action??i.options?.action??"none",C=performance.now(),y=sn(i.target),w=null,x=null;if(y.kind==="element"&&y.element?(x=y.element,o.classList.remove("visible"),x.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await So(x,1500,180),Mt(o),w=ln(x,v)):y.kind==="position"&&y.point&&(w=y.point),!w){r.push({ok:false,action:g,targetKind:y.kind,durationMs:Math.round(performance.now()-C),error:"Target not found"});continue}let c={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},p=cn(an(w,f));await et(o,c,p,h,I,b,k,a);let T=p.x-c.x,m=p.y-c.y,F=Math.hypot(T,m)||1,H=T/F,R=m/F,O=Math.min(6,Math.max(3,F*.02)),V={x:p.x+H*O,y:p.y+R*O};await et(o,p,V,Math.max(70,h*.1),"ease-out","straight",0,"right"),await et(o,V,p,120,"ease-out","straight",0,"left"),S&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let K=null;try{if(g==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let E={x:s?.x??0,y:s?.y??0},L={x:p.x+E.x,y:p.y+E.y};o.style.left=`${L.x}px`,o.style.top=`${L.y}px`,Et(o,L.x,L.y);let W=x??document.elementFromPoint(L.x,L.y)??document.body;ue(W,"pointerdown",L),ue(W,"mousedown",L),await new Promise(U=>setTimeout(U,90)),o.classList.remove("pressing"),ue(W,"mouseup",L),ue(W,"click",L),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),W instanceof HTMLElement&&W.focus?.(),K=W?.id??null;}else if(g==="drag"){if(!d)throw new Error("dragTo is required for action 'drag'");let E=sn(d),L=null;if(E.kind==="element"&&E.element&&(L=ln(E.element,v)),E.kind==="position"&&E.point&&(L=E.point),!L)throw new Error("dragTo target not found");let W=cn(an(L,f)),U={x:p.x,y:p.y},Z=x??document.elementFromPoint(U.x,U.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),ue(Z,"pointerdown",U),ue(Z,"mousedown",U),await et(o,U,W,Math.max(200,h),I,b,k,a,({x:N,y:xe})=>{let pe=document.elementFromPoint(N,xe)??document.body,be={x:N,y:xe};ue(pe,"pointermove",be),ue(pe,"mousemove",be);});let G=document.elementFromPoint(W.x,W.y)??document.body;o.classList.remove("pressing"),ue(G,"pointerup",W),ue(G,"mouseup",W);}r.push({ok:!0,action:g,targetKind:y.kind,durationMs:Math.round(performance.now()-C),clickedElementId:K});}catch(E){r.push({ok:false,action:g,targetKind:y.kind,durationMs:Math.round(performance.now()-C),error:E?.message??String(E)});}}return To(o,2e3),{ok:r.every(i=>i.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var ot=Do;function mn(){return {getDomComponents:{tool:async({includeHidden:e,selector:t})=>await We({includeHidden:e,selector:t}),executeEachToken:false},controlCursor:{tool:async({target:e,action:t,anchor:n,durationMs:r,dragTo:o})=>{let l=await ke(e,{action:t,anchor:n,durationMs:r,dragTo:o});if(l&&l.ok){let u=Array.isArray(l.steps)&&l.steps.length?l.steps[l.steps.length-1]:void 0,i=u?.clickedElementId?` (clicked element id: ${u.clickedElementId})`:"",h=t||u?.action||"none";return {success:true,message:h==="click"?`Cursor moved and clicked successfully${i}`:h==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:l}}return {success:false,message:"Cursor action failed",details:l}},executeEachToken:false},fillActiveInput:{tool:async({value:e})=>{let t=await Ue(e);return {success:!!t?.ok,message:t?.ok?"Active input filled successfully":t?.errors?.[0]||"Failed to fill active input",details:t}},executeEachToken:true},requestInput:{tool:async e=>({ok:true}),executeEachToken:true}}}function yn({chart:e,theme:t}){let n=useRef(null),[r,o]=useState(null),[l,u]=useState(true);useEffect(()=>{let b=true;return (async()=>{try{u(!0),o(null);let a;try{a=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!b)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&&b){let v=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:s}=await a.default.render(v,e);if(n.current&&b){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){b&&o(a instanceof Error?a.message:"Failed to render diagram");}finally{b&&u(false);}})(),()=>{b=false;}},[e,t]);let i=t==="dark"?"#374151":"#D1D5DB",h=t==="dark"?"#1F2937":"#F9FAFB",I=t==="dark"?"#7F1D1D":"#FEF2F2",f=t==="dark"?"#FCA5A5":"#DC2626",S=t==="dark"?"#9CA3AF":"#6B7280";return r?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${i}`,backgroundColor:I,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:f,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:f,opacity:.8},children:r})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${i}`,backgroundColor:h,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[l&&jsx("div",{style:{fontSize:"14px",color:S,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:l?"none":"block",textAlign:"center",minHeight:l?"0":"50px"}})]})}function ie(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 Oo(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
|
|
12
12
|
`).split(`
|
|
13
|
-
`),r="",o=false,
|
|
14
|
-
<table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;">`;
|
|
15
|
-
`);r+=`<div class="mermaid-placeholder" data-mermaid="${
|
|
16
|
-
`)),
|
|
17
|
-
`);r+=`<div class="mermaid-placeholder" data-mermaid="${
|
|
18
|
-
`)),p=i?`language-${i}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${b}; color: ${k}; border: 1px solid ${f}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${p}">${c}</code></pre>`;}return l&&(r+="</ul>"),x&&(r+="</ol>"),{html:r,hasMermaid:I}}function Ge({content:e,theme:t}){let{html:n,hasMermaid:r}=useMemo(()=>Wo(e,t),[e,t]);if(!r)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let o=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),i=[];return o.forEach((u,l)=>{if(u.includes("mermaid-placeholder")){let x=u.match(/data-mermaid="([^"]*)"/);if(x){let I=x[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");i.push(at.createElement(fn,{key:`mermaid-${l}`,chart:I,theme:t}));}}else u.trim()&&i.push(at.createElement("div",{key:`html-${l}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:u}}));}),at.createElement(at.Fragment,{},...i)}function Go({input:e}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(Ge,{content:e?.text||"",theme:"dark"})})}function hn(){return {plainText:Go}}function xn(e,t,n,r,o,i){let u=n.get(t);if(u){let C=u.parentElement,T=document.querySelector(`[data-get-from-user-host="${t}"]`);if(T&&C!==T){try{C?.removeChild(u);}catch{}T.innerHTML="",T.appendChild(u);}}else {u=document.createElement("div"),u.className="hsafa-inline-form";let C=document.querySelector(`[data-get-from-user-host="${t}"]`);C?(C.innerHTML="",C.appendChild(u)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(u),n.set(t,u);}let l=e?.title||"Provide input",x=e?.description||"",I=e?.submitLabel||"Submit",f=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||""}]:[],b=r.get(t)||{submitted:false,skipped:false,values:void 0};u.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=l,k.appendChild(a),x){let C=document.createElement("div");C.style.fontSize="12px",C.style.opacity="0.8",C.style.marginBottom="10px",C.textContent=x,k.appendChild(C);}M.forEach(C=>{let T=document.createElement("div");if(T.style.margin="10px 0",C.label){let m=document.createElement("label");m.style.display="block",m.style.fontSize="12px",m.style.marginBottom="6px",m.style.opacity="0.9",m.textContent=C.label,T.appendChild(m);}let h,c=(C.type||"text").toLowerCase();if(c==="textarea"){let m=document.createElement("textarea");m.placeholder=C.placeholder||"",m.value=C.value??"",m.style.width="100%",m.style.minHeight="72px",m.style.padding="10px 12px",m.style.border="1px solid var(--hsafa-border, #2A2C33)",m.style.borderRadius="10px",m.style.background="var(--hsafa-input-bg, #17181C)",m.style.color="inherit",h=m;}else if(c==="select"&&Array.isArray(C.options)){let m=document.createElement("select");m.style.width="100%",m.style.padding="10px 12px",m.style.border="1px solid var(--hsafa-border, #2A2C33)",m.style.borderRadius="10px",m.style.background="var(--hsafa-input-bg, #17181C)",m.style.color="inherit",C.options.forEach(R=>{let A=document.createElement("option");A.value=String(R.value),A.text=String(R.label??R.value),m.appendChild(A);}),m.value=C.value??"",h=m;}else if(c==="checkbox"){let m=document.createElement("input");m.type="checkbox",m.checked=!!C.value,m.style.transform="scale(1.1)",h=m;}else {let m=document.createElement("input");m.type=c,m.placeholder=C.placeholder||"",m.value=C.value??"",m.style.width="100%",m.style.padding="10px 12px",m.style.border="1px solid var(--hsafa-border, #2A2C33)",m.style.borderRadius="10px",m.style.background="var(--hsafa-input-bg, #17181C)",m.style.color="inherit",h=m;}let p=C.id||"value";h.dataset.fieldId=p;let w=b.values&&Object.prototype.hasOwnProperty.call(b.values,p)?b.values[p]:void 0;typeof w<"u"&&(h.type==="checkbox"?h.checked=!!w:h.value=String(w)),(b.submitted||b.skipped)&&(h.setAttribute("disabled","true"),h.style.opacity="0.7"),T.appendChild(h),k.appendChild(T);});let v=String(I).trim(),s=String(f).trim(),d=!!(v||s),g=null,y=null;if(d){let C=document.createElement("div");C.style.display="flex",C.style.gap="8px",C.style.marginTop="10px",g=document.createElement("button"),g.type="submit",g.textContent=v||"Submit",g.style.padding="6px 10px",g.style.borderRadius="8px",g.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",g.style.color="#000000",y=document.createElement("button"),y.type="button",y.textContent=s||"Skip",y.style.padding="6px 10px",y.style.borderRadius="8px",y.style.background="transparent",y.style.border="1px solid var(--hsafa-border, #2A2C33)",y.style.color="inherit",C.appendChild(g),C.appendChild(y),k.appendChild(C);}if(k.onsubmit=C=>{C.preventDefault();let T={};k.querySelectorAll("[data-field-id]").forEach(h=>{let c=h.dataset.fieldId||"value";h.type==="checkbox"?T[c]=h.checked:T[c]=h.value??"";}),r.set(t,{submitted:true,skipped:false,values:T}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:T}}),k.querySelectorAll("[data-field-id]").forEach(h=>{h.disabled=true,h.style.opacity="0.7";}),g&&(g.textContent=`${v||"Submit"} \u2713`,g.style.opacity="0.8",g.disabled=true),y&&(y.disabled=true);},y&&(y.onclick=()=>{r.set(t,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:false,skipped:true}}),k.querySelectorAll("[data-field-id]").forEach(C=>{C.disabled=true,C.style.opacity="0.7";}),y&&(y.textContent=`${s||"Skip"} \u2713`,y.style.opacity="0.8",y.disabled=true),g&&(g.disabled=true);}),b.submitted||b.skipped){let C=document.createElement("div");C.style.marginTop="10px",C.style.fontSize="12px",C.style.display="flex",C.style.alignItems="center",C.style.gap="8px";let T=document.createElement("span");T.style.display="inline-flex",T.style.alignItems="center",T.style.padding="2px 8px",T.style.borderRadius="999px",T.style.fontWeight="600",T.style.fontSize="11px",b.submitted?(T.style.background="rgba(16,185,129,0.15)",T.style.color="#10b981",T.textContent="Submitted"):(T.style.background="rgba(234,179,8,0.15)",T.style.color="#eab308",T.textContent="Skipped"),C.appendChild(T),k.appendChild(C);try{g&&(g.disabled=!0,g.style.opacity="0.8",b.submitted&&(g.textContent=`${v||"Submit"} \u2713`)),y&&(y.disabled=!0,y.style.opacity="0.8",b.skipped&&(y.textContent=`${s||"Skip"} \u2713`));}catch{}}u.appendChild(k);}function bn(e,t,n){let r=useRef(new Map),o=useRef(new Map),i=useRef(t),u=useRef(n);i.current=t,u.current=n,useEffect(()=>{e.forEach(l=>{l.role==="assistant"&&l.parts?.forEach(x=>{if(!x.toolCallId)return;let I=x.toolName;if(!I&&x.type?.startsWith("tool-")&&(I=x.type.replace(/^tool-/,"")),!I)return;let f=i.current[I];if(f&&typeof f=="object"&&f.executeEachToken&&f.tool){let M=x.input||x.args||{},b=JSON.stringify(M),k=r.current.get(x.toolCallId);if(b!==k&&b!=="{}"){r.current.set(x.toolCallId,b);try{if(I==="requestInput")u.current(M,x.toolCallId);else {let v=(o.current.get(x.toolCallId)||0)+1;o.current.set(x.toolCallId,v),v>1&&f.tool({...M,toolCallNumber:v-1});}}catch{}}}});});},[e]);}function At(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:i,onFinish:u,onError:l,initialMessages:x=[],onMessagesChange:I,controlledChatId:f,onChatIdChange:M}=e,{baseUrl:b,setCurrentChatId:k}=re(),a=n&&n.length>0?n:b||"",[v,s]=useState(""),[d,g]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),y=f??d,C=useCallback(E=>{f===void 0&&g(E),M&&M(E);},[f,M]);useEffect(()=>{try{k(y);}catch{}return ()=>{try{k(void 0);}catch{}}},[y,k]);let T=useMemo(()=>Zt(a,t,y),[a,t,y]),h=useCallback(E=>{console.log("Message finished:",E);let z=E?.message?.id;if(!z&&Array.isArray(E?.messages))for(let _=E.messages.length-1;_>=0;_--){let D=E.messages[_];if(D&&D.role==="assistant"&&D.id){z=D.id;break}}u?.({...E,chatId:y,assistantMessageId:z});},[u,y]),c=useCallback(E=>{console.error("Chat error:",E),l?.(E);},[l]),p=useMemo(()=>pn(),[]),w=useMemo(()=>({...p,...r}),[p,r]),m=useMemo(()=>hn(),[]),R=useMemo(()=>({...m,...o}),[m,o]),A=useRef(new Map),H=useRef(new Map),K=useCallback(()=>{try{A.current.forEach(E=>{try{E.remove();}catch{}}),A.current.clear(),H.current.clear();}catch{}},[]),q=useCallback((E,z)=>{xn(E,z,A.current,H.current,_=>L.current.addToolResult(_));},[]),L=useRef(null),F=useRef(new Set),$=useCallback((E,z,_)=>{console.error(`UI Error [${z}]:`,_),L.current&&F.current.has(E)&&(F.current.delete(E),L.current.addToolResult({tool:z,toolCallId:E,state:"output-error",errorText:_?.message||String(_)}));},[]),N=useCallback((E,z)=>{L.current&&F.current.has(E)&&(F.current.delete(E),L.current.addToolResult({tool:z,toolCallId:E,output:{status:"ok",rendered:true,component:z,logs:[]}}));},[]),O=useCallback(E=>{let z=w[E];return z?typeof z=="object"&&"tool"in z?z.tool:typeof z=="function"?z:null:null},[w]),G=useChat({transport:T,onFinish:h,onError:c,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:E}){let z=O(E.toolName);if(E.toolName==="requestInput"){try{q(E.input,E.toolCallId);}catch(te){console.error("requestInput render error",te);}return}let _=E.toolName==="ui";E?.input;let ee=R&&E.toolName in R;if(_||ee){F.current.add(E.toolCallId);return}if(z)try{let te=await z(E.input);G.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,output:te});}catch(te){G.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,state:"output-error",errorText:te?.message||String(te)});}}}),{messages:P,sendMessage:he,status:ue,stop:xe,error:Ie}=G;L.current=G,bn(P,w,q),useEffect(()=>{try{let E=new Set,z=[];if(P.forEach(_=>{_.role==="assistant"&&(_.parts||[]).forEach(D=>{if((D?.toolName||(typeof D?.type=="string"&&D.type.startsWith("tool-")?String(D.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let te=D?.toolCallId||"";if(!te)return;E.add(te);let pe=D?.output;if(pe&&(pe.submitted||pe.skipped||pe.values)){let be={submitted:!!pe.submitted,skipped:!!pe.skipped,values:pe.values||void 0};H.current.set(te,be);}let Z=D?.input||D?.args||{};z.push({input:Z,toolCallId:te});});}),A.current.forEach((_,D)=>{if(!E.has(D)){let ee=A.current.get(D);try{ee?.remove();}catch{}A.current.delete(D),H.current.delete(D);}}),z.length>0){let _=requestAnimationFrame(()=>{z.forEach(({input:D,toolCallId:ee})=>{try{q(D,ee);}catch{}});});return ()=>cancelAnimationFrame(_)}}catch{}},[P,q]),useEffect(()=>{x&&x.length>0&&P.length===0&&console.log("Initial messages:",x);},[x,P.length]);let Y=ue==="submitted"||ue==="streaming",Ke=useCallback(()=>{I&&I(P,y);},[I,P,y]),Be=useCallback(async E=>{let z=E?.text!==void 0?E.text:v,_=E?.files||[],D=z.trim();if(!(!D&&_.length===0)&&!Y){E?.text===void 0&&s("");try{if(i){let ee={role:"user",content:D,createdAt:Date.now(),chatId:y};i(ee);}await he({text:D,files:_});}catch(ee){throw console.error("Failed to send message:",ee),ee}}},[v,Y,he,i,y]),Me=useCallback(()=>{if(Y)return;K(),s("");try{G?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;C(E);},[Y,G,K,C]),Bt=useCallback(E=>{try{G?.setMessages?.(E);}catch{}},[G]);return {input:v,setInput:s,messages:P,isLoading:Y,status:ue,error:Ie,sendMessage:Be,stop:xe,newChat:Me,setMessages:Bt,notifyMessagesChange:Ke,chatApi:G,chatId:y,setChatId:C,tools:w,uiComponents:R,formHostRef:A,formStateRef:H,cleanupForms:K,onUISuccess:N,onUIError:$}}function lt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=y=>`${t}.chat.${y}`,o=`${t}.currentChatId`,i=`${t}.showChat`,u=()=>{try{let y=localStorage.getItem(n);return y?JSON.parse(y):[]}catch{return []}},l=y=>{try{localStorage.setItem(n,JSON.stringify(y));}catch{}},x=y=>{try{let C=localStorage.getItem(r(y));return C?JSON.parse(C):null}catch{return null}},I=y=>{try{localStorage.setItem(r(y.id),JSON.stringify(y));}catch{}},f=y=>{let C=u(),T=C.findIndex(h=>h.id===y.id);T>=0?C[T]=y:C.unshift(y),l(C);},M=y=>{let T=u().filter(h=>h.id!==y);l(T);},b=y=>{try{localStorage.removeItem(r(y));}catch{}};return {loadChatsIndex:u,saveChatsIndex:l,loadChat:x,saveChat:I,upsertChatMeta:f,deleteChatMeta:M,deleteChatData:b,deleteChat:y=>{b(y),M(y);},loadShowChatPreference:y=>{try{let C=localStorage.getItem(i);return C!==null?C==="true":y}catch{return y}},saveShowChatPreference:y=>{try{localStorage.setItem(i,String(y));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:y=>{try{localStorage.setItem(o,y);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Ft(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:i=true,autoRestore:u=true}=e,l=useMemo(()=>lt(t),[t]),[x,I]=useState([]),[f,M]=useState(null),b=useRef(false),k=useRef(false),a=useCallback(()=>{try{let h=l.loadChatsIndex();I(h);let c=h.find(p=>p.id===n);M(c||null);}catch(h){console.error("Failed to refresh chat list:",h);}},[l,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!u||k.current)){try{l.loadCurrentChatId()&&(b.current=!0);}catch(h){console.error("Failed to restore chat:",h);}k.current=true;}},[l,u]),useEffect(()=>{if(!(!i||r.length===0))if(b.current){if(!o){let h=Date.now();try{l.saveChat({id:n,messages:r,agentId:t});let p=l.loadChatsIndex().find(w=>w.id===n);p&&(l.upsertChatMeta({...p,updatedAt:h}),a());}catch(c){console.error("Failed to save chat:",c);}}}else {let h=r.find(c=>c.role==="user");if(h){let c="";if(Array.isArray(h.parts)){let m=h.parts.find(R=>R&&R.type==="text");c=m&&typeof m.text=="string"?m.text:"";}let p=(c||"New chat").slice(0,80),w=Date.now();try{l.upsertChatMeta({id:n,title:p,createdAt:w,updatedAt:w}),l.saveChat({id:n,messages:r,agentId:t}),l.saveCurrentChatId(n),b.current=!0,a();}catch(m){console.error("Failed to create chat:",m);}}}},[]);let v=useRef(false);useEffect(()=>{if(o){v.current=true;return}if(v.current&&i){v.current=false;try{let h=Date.now();l.saveChat({id:n,messages:r,agentId:t});let p=l.loadChatsIndex().find(w=>w.id===n);if(p)l.upsertChatMeta({...p,updatedAt:h});else {let w="",m=Array.isArray(r)?r.find(A=>A&&A.role==="user"):void 0;if(m&&Array.isArray(m.parts)){let A=m.parts.find(H=>H&&H.type==="text");w=A&&typeof A.text=="string"?A.text:"";}let R=(w||"New chat").slice(0,80);l.upsertChatMeta({id:n,title:R,createdAt:h,updatedAt:h});try{l.saveCurrentChatId(n);}catch{}b.current=!0;}a();}catch(h){console.error("Failed to save chat on completion:",h);}}},[o,r,n,t,l,i,a]);let s=useCallback(h=>{try{let c=l.loadChat(h);return c?{id:c.id,messages:c.messages,agentId:c.agentId||t}:null}catch(c){return console.error("Failed to load chat:",c),null}},[l,t]),d=useCallback(()=>{if(r.length!==0)try{let h=Date.now();l.saveChat({id:n,messages:r,agentId:t});let p=l.loadChatsIndex().find(w=>w.id===n);p&&(l.upsertChatMeta({...p,updatedAt:h}),a());}catch(h){console.error("Failed to save chat:",h);}},[l,n,r,t,a]),g=useCallback(h=>{try{l.deleteChat(h),a();}catch(c){console.error("Failed to delete chat:",c);}},[l,a]),y=useCallback((h,c)=>{if(h!==n)try{b.current=!0,l.saveCurrentChatId(h);let p=l.loadChat(h),w=p&&Array.isArray(p.messages)?p.messages:[];c(w),a();}catch(p){console.error("Failed to switch chat:",p);}},[l,n,a]),C=useCallback(h=>{b.current=false,h();},[]),T=useCallback(h=>{if(!h.trim())return x;let c=h.toLowerCase();return x.filter(p=>p.title.toLowerCase().includes(c))},[x]);return {chatList:x,currentChatMeta:f,refreshChatList:a,loadChat:s,saveCurrentChat:d,deleteChat:g,switchToChat:y,createNewChat:C,searchChats:T,storage:l}}function Ko(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:i}=e,{baseUrl:u}=re(),l=i||u||"",[x,I]=useState(null),[f,M]=useState(""),[b,k]=useState([]),[a,v]=useState(false),s=useCallback((h,c,p=[])=>{I(h),M(c),k(p);},[]),d=useCallback(()=>{I(null),M(""),k([]);},[]),g=useCallback(async h=>{if(!n)try{let c=t.findIndex(w=>w.id===h);if(c===-1)return;let p=t.slice(0,c);o(p),await r({text:f.trim(),files:b.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(c){throw console.error("Failed to save edit:",c),c}},[n,t,r,f,b,o,d]),y=useCallback(h=>x===h,[x]),C=useCallback(async h=>{if(!l){console.warn("baseUrl not provided, cannot upload attachments");return}v(true);try{let c=Array.from(h).map(async w=>{if(w.size>26214400)throw new Error(`${w.name} is too large (max 25MB)`);let m=new FormData;m.append("file",w);let R=await fetch(`${l}/api/upload`,{method:"POST",body:m});if(!R.ok)throw new Error(`Upload failed: ${R.statusText}`);let A=await R.json();return {id:A.url||`${Date.now()}-${Math.random()}`,name:w.name,url:A.url,mimeType:w.type,size:w.size}}),p=await Promise.all(c);k(w=>[...w,...p]);}catch(c){throw console.error("Failed to upload files:",c),c}finally{v(false);}},[l]),T=useCallback(h=>{k(c=>c.filter(p=>p.id!==h));},[]);return {editingMessageId:x,editingText:f,setEditingText:M,editAttachments:b,setEditAttachments:k,editUploading:a,startEdit:s,cancelEdit:d,saveEdit:g,isEditing:y,addEditAttachments:C,removeEditAttachment:T}}function X({IconComponent:e,...t}){return at.createElement(e,t)}function Lt({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:i}){return jsx("button",{"aria-label":n,title:i,disabled:o,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:o?"not-allowed":"pointer",opacity:o?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:u=>{o||(u.currentTarget.style.backgroundColor=r.hoverBackground,u.currentTarget.style.color=r.textColor);},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent",u.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function wn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:i,onToggleHistory:u,onClose:l,historyBtnRef:x,t:I}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsx(Lt,{icon:jsx(X,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||i();},ariaLabel:I("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:x,"aria-label":I("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor=o.hoverBackground,f.currentTarget.style.color=o.textColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=o.mutedTextColor;},onClick:u,children:jsx(X,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(Lt,{icon:jsx(X,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:l,ariaLabel:I("header.close"),resolvedColors:o})]})]})}var mt=class extends Component{constructor(t){super(t),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(t){return {hasError:true,error:t,errorInfo:null}}componentDidMount(){let{toolCallId:t,toolName:n,onSuccess:r}=this.props;t&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(t,n);},0);}componentDidCatch(t,n){console.error(`UI Component Error (${this.props.componentName}):`,t,n),this.setState({error:t,errorInfo:n});let{toolCallId:r,toolName:o,onError:i}=this.props;r&&o&&i&&i(r,o,t);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:t,componentName:n}=this.props;return jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var tr=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"]},nr=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}},or=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function Tn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:u,onUISuccess:l,addToolResult:x}){let I=[],f=[],M,b,k=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){f.push(a.text),M||(M=a.startDate),b=a.endDate,a.state==="done"&&(k=true);continue}if(a.type==="text"&&typeof a.text=="string"){f.length&&(I.push({type:"reasoning",texts:f,startDate:M,endDate:b,isCompleted:k}),f=[],M=void 0,b=void 0,k=false),I.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"){f.length&&(I.push({type:"reasoning",texts:f,startDate:M,endDate:b,isCompleted:k}),f=[],M=void 0,b=void 0,k=false);let d=String(v?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");d==="requestInput"?I.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}):I.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 f.length&&I.push({type:"reasoning",texts:f,startDate:M,endDate:b,isCompleted:k}),I.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[I.map((a,v)=>{let s=`${t}-${v}`,d=n.has(s);if(a.type==="reasoning"){let c=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",p=a.texts&&a.texts.length>0&&a.texts.some(m=>m.trim().length>0),w=()=>{p&&r(s);};return c&&!p?null:jsx("div",{onClick:w,style:{cursor:p?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:d?"4px":"0px"},children:[jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!c&&jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{color:o.textColor,fontWeight:600,opacity:.9,background:c?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:c?"auto":"200% 100%",backgroundClip:c?"unset":"text",WebkitBackgroundClip:c?"unset":"text",WebkitTextFillColor:c?o.mutedTextColor:"transparent",animation:c?void 0:"shimmer 2s ease-in-out infinite"},children:c?"Finish Thinking":"Thinking"})]}),p&&jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:d?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsx("div",{style:{display:"grid",gridTemplateRows:d||!c?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsx("div",{style:{fontSize:"13px",color:o.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!c&&d?a.texts:c?d?a.texts:[]:[a.texts[a.texts.length-1]]).map((m,R)=>jsx("div",{style:{marginBottom:"6px"},children:jsx(Ge,{content:m,theme:"dark"})},`rg-line-${v}-${R}`))}):jsxs("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text")return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(Ge,{content:a.text,theme:"dark"})},s);let{color:g,text:y}=tr(a.status),C=a.status==="input-streaming"||a.status==="input-available";if(a.toolName==="requestInput")return jsx("div",{style:{display:"block",position:"relative"},children:jsx("div",{"data-get-from-user-host":a.toolCallId||s,style:{width:"100%"}})},s);let T=i?.[a.toolName||""];if(T)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(mt,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:u,onSuccess:l,children:jsx(T,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:x})})},s);let h=nr(a.toolName||"tool");return jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsx("div",{style:{flex:1,minWidth:0},children:jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxs("span",{style:{fontWeight:600,color:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:g,animation:C?"pulse 1.5s ease-in-out infinite":void 0}}),y]}),h.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:h.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:h.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:or(h.toolName)})]})})},s)}),jsx("style",{children:`
|
|
13
|
+
`),r="",o=false,l="",u=[],i=false,h=false,I=false,f=t==="dark"?"#374151":"#D1D5DB",b=t==="dark"?"#111827":"#F3F4F6",k=t==="dark"?"#E5E7EB":"#374151",a=t==="dark"?"#374151":"#F3F4F6",v=t==="dark"?"#F9FAFB":"#111827",s=()=>{i&&(r+="</ul>",i=false),h&&(r+="</ol>",h=false);},d=c=>{for(let p=c;p<n.length;p++)if(n[p].trim().length>0)return p;return -1},g=c=>{let p=c.trim(),T=p.startsWith("|")?p.slice(1):p;return (T.endsWith("|")?T.slice(0,-1):T).split("|").map(F=>F.trim())},C=c=>{let p=c.trim();if(!p.startsWith("|"))return false;let T=g(p);return T.length>=2&&T.some(m=>m.length>0)},y=c=>{let p=g(c);return p.length===0?false:p.every(T=>/^:?-{3,}:?$/.test(T))},w=c=>{let p=c.startsWith(":"),T=c.endsWith(":");return p&&T?"center":!p&&T?"right":"left"},x=c=>{let p=c,T=d(p+1);if(T===-1)return {tableHtml:"",endIndex:c};let m=g(n[p]),F=g(n[T]),H=Math.max(m.length,F.length),R=[];for(let E=0;E<H;E++){let L=F[E]||"---";R.push(w(L));}let O=[],V=T+1;for(;V<n.length;){let E=n[V].trim();if(E.length===0){V++;continue}if(!E.startsWith("|"))break;let L=g(n[V]),W=[];for(let U=0;U<H;U++)W.push(L[U]??"");O.push(W),V++;}let K=`<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;">`;K+="<thead><tr>";for(let E=0;E<H;E++){let L=Le(ie(m[E]??"")),W=R[E],U=E===0,Z=E===H-1;K+=`<th style="text-align: ${W}; padding: 10px 12px; border-bottom: 1px solid ${f}; background-color: ${a}; color: ${v}; position: sticky; top: 0; z-index: 1; ${`${U?"border-top-left-radius: 10px;":""}${Z?"border-top-right-radius: 10px;":""}`}">${L}</th>`;}K+="</tr></thead>",K+="<tbody>";for(let E of O){K+="<tr>";for(let L=0;L<H;L++){let W=Le(ie(E[L]??"")),U=R[L],Z=L===0;K+=`<td style="text-align: ${U}; padding: 10px 12px; border-bottom: 1px solid ${f}; ${Z?`border-left: 1px solid ${f};`:""} border-right: 1px solid ${f};">${W}</td>`;}K+="</tr>";}return K+="</tbody></table></div>",{tableHtml:K,endIndex:V-1}};for(let c=0;c<n.length;c++){let p=n[c],T=p.match(/^```\s*(\w+)?\s*$/);if(T){if(!o)s(),o=true,l=T[1]?String(T[1]):"",u=[];else {if(l==="mermaid"){I=true;let R=u.join(`
|
|
15
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${ie(R)}"></div>`;}else {let R=ie(u.join(`
|
|
16
|
+
`)),O=l?`language-${l}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${b}; color: ${k}; border: 1px solid ${f}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${O}">${R}</code></pre>`;}o=false,l="",u=[];}continue}if(o){u.push(p);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(p)){s(),r+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let m=p.match(/^(#{1,6})\s+(.+)$/);if(m){s();let R=m[1].length,O=Le(ie(m[2].trim())),V=R<=2?"18px":R===3?"16px":"14px";r+=`<h${R} style="font-size: ${V}; font-weight: 600; margin: 8px 0 4px 0;">${O}</h${R}>`;continue}if(C(p)){let R=d(c+1);if(R!==-1&&y(n[R])){s();let{tableHtml:O,endIndex:V}=x(c);if(O){r+=O,c=V;continue}}}let F=p.match(/^\s*[-*]\s+(.+)$/),H=p.match(/^\s*\d+\.\s+(.+)$/);if(F){i||(s(),r+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',i=true);let R=Le(ie(F[1]));r+=`<li style="margin: 2px 0;">${R}</li>`;continue}if(H){h||(s(),r+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',h=true);let R=Le(ie(H[1]));r+=`<li style="margin: 2px 0;">${R}</li>`;continue}if(p.trim().length===0)s(),r+='<div style="height: 8px;"></div>';else {s();let R=Le(ie(p));r+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${R}</p>`;}}if(o)if(l==="mermaid"){I=true;let c=u.join(`
|
|
17
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${ie(c)}"></div>`;}else {let c=ie(u.join(`
|
|
18
|
+
`)),p=l?`language-${l}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${b}; color: ${k}; border: 1px solid ${f}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${p}">${c}</code></pre>`;}return i&&(r+="</ul>"),h&&(r+="</ol>"),{html:r,hasMermaid:I}}function Ge({content:e,theme:t}){let{html:n,hasMermaid:r}=useMemo(()=>Oo(e,t),[e,t]);if(!r)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let o=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),l=[];return o.forEach((u,i)=>{if(u.includes("mermaid-placeholder")){let h=u.match(/data-mermaid="([^"]*)"/);if(h){let I=h[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");l.push(at.createElement(yn,{key:`mermaid-${i}`,chart:I,theme:t}));}}else u.trim()&&l.push(at.createElement("div",{key:`html-${i}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:u}}));}),at.createElement(at.Fragment,{},...l)}function _o({input:e}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(Ge,{content:e?.text||"",theme:"dark"})})}function xn(){return {plainText:_o}}function bn(e,t,n,r,o,l){let u=n.get(t);if(u){let y=u.parentElement,w=document.querySelector(`[data-get-from-user-host="${t}"]`);if(w&&y!==w){try{y?.removeChild(u);}catch{}w.innerHTML="",w.appendChild(u);}}else {u=document.createElement("div"),u.className="hsafa-inline-form";let y=document.querySelector(`[data-get-from-user-host="${t}"]`);y?(y.innerHTML="",y.appendChild(u)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(u),n.set(t,u);}let i=e?.title||"Provide input",h=e?.description||"",I=e?.submitLabel||"Submit",f=e?.skipLabel||"Skip",S=Array.isArray(e?.fields)?e.fields:e?.label||e?.placeholder?[{id:"value",label:e?.label||"Value",type:"text",placeholder:e?.placeholder||""}]:[],b=r.get(t)||{submitted:false,skipped:false,values:void 0};u.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=i,k.appendChild(a),h){let y=document.createElement("div");y.style.fontSize="12px",y.style.opacity="0.8",y.style.marginBottom="10px",y.textContent=h,k.appendChild(y);}S.forEach(y=>{let w=document.createElement("div");if(w.style.margin="10px 0",y.label){let m=document.createElement("label");m.style.display="block",m.style.fontSize="12px",m.style.marginBottom="6px",m.style.opacity="0.9",m.textContent=y.label,w.appendChild(m);}let x,c=(y.type||"text").toLowerCase();if(c==="textarea"){let m=document.createElement("textarea");m.placeholder=y.placeholder||"",m.value=y.value??"",m.style.width="100%",m.style.minHeight="72px",m.style.padding="10px 12px",m.style.border="1px solid var(--hsafa-border, #2A2C33)",m.style.borderRadius="10px",m.style.background="var(--hsafa-input-bg, #17181C)",m.style.color="inherit",x=m;}else if(c==="select"&&Array.isArray(y.options)){let m=document.createElement("select");m.style.width="100%",m.style.padding="10px 12px",m.style.border="1px solid var(--hsafa-border, #2A2C33)",m.style.borderRadius="10px",m.style.background="var(--hsafa-input-bg, #17181C)",m.style.color="inherit",y.options.forEach(F=>{let H=document.createElement("option");H.value=String(F.value),H.text=String(F.label??F.value),m.appendChild(H);}),m.value=y.value??"",x=m;}else if(c==="checkbox"){let m=document.createElement("input");m.type="checkbox",m.checked=!!y.value,m.style.transform="scale(1.1)",x=m;}else {let m=document.createElement("input");m.type=c,m.placeholder=y.placeholder||"",m.value=y.value??"",m.style.width="100%",m.style.padding="10px 12px",m.style.border="1px solid var(--hsafa-border, #2A2C33)",m.style.borderRadius="10px",m.style.background="var(--hsafa-input-bg, #17181C)",m.style.color="inherit",x=m;}let p=y.id||"value";x.dataset.fieldId=p;let T=b.values&&Object.prototype.hasOwnProperty.call(b.values,p)?b.values[p]:void 0;typeof T<"u"&&(x.type==="checkbox"?x.checked=!!T:x.value=String(T)),(b.submitted||b.skipped)&&(x.setAttribute("disabled","true"),x.style.opacity="0.7"),w.appendChild(x),k.appendChild(w);});let v=String(I).trim(),s=String(f).trim(),d=!!(v||s),g=null,C=null;if(d){let y=document.createElement("div");y.style.display="flex",y.style.gap="8px",y.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",C=document.createElement("button"),C.type="button",C.textContent=s||"Skip",C.style.padding="6px 10px",C.style.borderRadius="8px",C.style.background="transparent",C.style.border="1px solid var(--hsafa-border, #2A2C33)",C.style.color="inherit",y.appendChild(g),y.appendChild(C),k.appendChild(y);}if(k.onsubmit=y=>{y.preventDefault();let w={};k.querySelectorAll("[data-field-id]").forEach(x=>{let c=x.dataset.fieldId||"value";x.type==="checkbox"?w[c]=x.checked:w[c]=x.value??"";}),r.set(t,{submitted:true,skipped:false,values:w}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:w}}),k.querySelectorAll("[data-field-id]").forEach(x=>{x.disabled=true,x.style.opacity="0.7";}),g&&(g.textContent=`${v||"Submit"} \u2713`,g.style.opacity="0.8",g.disabled=true),C&&(C.disabled=true);},C&&(C.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(y=>{y.disabled=true,y.style.opacity="0.7";}),C&&(C.textContent=`${s||"Skip"} \u2713`,C.style.opacity="0.8",C.disabled=true),g&&(g.disabled=true);}),b.submitted||b.skipped){let y=document.createElement("div");y.style.marginTop="10px",y.style.fontSize="12px",y.style.display="flex",y.style.alignItems="center",y.style.gap="8px";let w=document.createElement("span");w.style.display="inline-flex",w.style.alignItems="center",w.style.padding="2px 8px",w.style.borderRadius="999px",w.style.fontWeight="600",w.style.fontSize="11px",b.submitted?(w.style.background="rgba(16,185,129,0.15)",w.style.color="#10b981",w.textContent="Submitted"):(w.style.background="rgba(234,179,8,0.15)",w.style.color="#eab308",w.textContent="Skipped"),y.appendChild(w),k.appendChild(y);try{g&&(g.disabled=!0,g.style.opacity="0.8",b.submitted&&(g.textContent=`${v||"Submit"} \u2713`)),C&&(C.disabled=!0,C.style.opacity="0.8",b.skipped&&(C.textContent=`${s||"Skip"} \u2713`));}catch{}}u.appendChild(k);}function Cn(e,t,n){let r=useRef(new Map),o=useRef(new Map),l=useRef(t),u=useRef(n);l.current=t,u.current=n,useEffect(()=>{e.forEach(i=>{i.role==="assistant"&&i.parts?.forEach(h=>{if(!h.toolCallId)return;let I=h.toolName;if(!I&&h.type?.startsWith("tool-")&&(I=h.type.replace(/^tool-/,"")),!I)return;let f=l.current[I];if(f&&typeof f=="object"&&f.executeEachToken&&f.tool){let S=h.input||h.args||{},b=JSON.stringify(S),k=r.current.get(h.toolCallId);if(b!==k&&b!=="{}"){r.current.set(h.toolCallId,b);try{if(I==="requestInput")u.current(S,h.toolCallId);else {let v=(o.current.get(h.toolCallId)||0)+1;o.current.set(h.toolCallId,v),v>1&&f.tool({...S,toolCallNumber:v-1});}}catch{}}}});});},[e]);}function Rt(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:l,onFinish:u,onError:i,initialMessages:h=[],onMessagesChange:I,controlledChatId:f,onChatIdChange:S,templateParams:b}=e,{baseUrl:k,setCurrentChatId:a}=ae(),v=n&&n.length>0?n:k||"",[s,d]=useState(""),[g,C]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),y=f??g,w=useCallback(A=>{f===void 0&&C(A),S&&S(A);},[f,S]);useEffect(()=>{try{a(y);}catch{}return ()=>{try{a(void 0);}catch{}}},[y,a]);let x=useMemo(()=>Qt(v,t,y,b),[v,t,y,b]),c=useCallback(A=>{console.log("Message finished:",A);let D=A?.message?.id;if(!D&&Array.isArray(A?.messages))for(let _=A.messages.length-1;_>=0;_--){let B=A.messages[_];if(B&&B.role==="assistant"&&B.id){D=B.id;break}}u?.({...A,chatId:y,assistantMessageId:D});},[u,y]),p=useCallback(A=>{console.error("Chat error:",A),i?.(A);},[i]),T=useMemo(()=>mn(),[]),m=useMemo(()=>({...T,...r}),[T,r]),F=useMemo(()=>xn(),[]),H=useMemo(()=>({...F,...o}),[F,o]),R=useRef(new Map),O=useRef(new Map),V=useCallback(()=>{try{R.current.forEach(A=>{try{A.remove();}catch{}}),R.current.clear(),O.current.clear();}catch{}},[]),K=useCallback((A,D)=>{bn(A,D,R.current,O.current,_=>E.current.addToolResult(_));},[]),E=useRef(null),L=useRef(new Set),W=useCallback((A,D,_)=>{console.error(`UI Error [${D}]:`,_),E.current&&L.current.has(A)&&(L.current.delete(A),E.current.addToolResult({tool:D,toolCallId:A,state:"output-error",errorText:_?.message||String(_)}));},[]),U=useCallback((A,D)=>{E.current&&L.current.has(A)&&(L.current.delete(A),E.current.addToolResult({tool:D,toolCallId:A,output:{status:"ok",rendered:true,component:D,logs:[]}}));},[]),Z=useCallback(A=>{let D=m[A];return D?typeof D=="object"&&"tool"in D?D.tool:typeof D=="function"?D:null:null},[m]),G=useChat({transport:x,onFinish:c,onError:p,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:A}){let D=Z(A.toolName);if(A.toolName==="requestInput"){try{K(A.input,A.toolCallId);}catch(ne){console.error("requestInput render error",ne);}return}let _=A.toolName==="ui";A?.input;let te=H&&A.toolName in H;if(_||te){L.current.add(A.toolCallId);return}if(D)try{let ne=await D(A.input);G.addToolResult({tool:A.toolName,toolCallId:A.toolCallId,output:ne});}catch(ne){G.addToolResult({tool:A.toolName,toolCallId:A.toolCallId,state:"output-error",errorText:ne?.message||String(ne)});}}}),{messages:N,sendMessage:xe,status:pe,stop:be,error:ht}=G;E.current=G,Cn(N,m,K),useEffect(()=>{try{let A=new Set,D=[];if(N.forEach(_=>{_.role==="assistant"&&(_.parts||[]).forEach(B=>{if((B?.toolName||(typeof B?.type=="string"&&B.type.startsWith("tool-")?String(B.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let ne=B?.toolCallId||"";if(!ne)return;A.add(ne);let me=B?.output;if(me&&(me.submitted||me.skipped||me.values)){let Ce={submitted:!!me.submitted,skipped:!!me.skipped,values:me.values||void 0};O.current.set(ne,Ce);}let Q=B?.input||B?.args||{};D.push({input:Q,toolCallId:ne});});}),R.current.forEach((_,B)=>{if(!A.has(B)){let te=R.current.get(B);try{te?.remove();}catch{}R.current.delete(B),O.current.delete(B);}}),D.length>0){let _=requestAnimationFrame(()=>{D.forEach(({input:B,toolCallId:te})=>{try{K(B,te);}catch{}});});return ()=>cancelAnimationFrame(_)}}catch{}},[N,K]),useEffect(()=>{h&&h.length>0&&N.length===0&&console.log("Initial messages:",h);},[h,N.length]);let Y=pe==="submitted"||pe==="streaming",Ke=useCallback(()=>{I&&I(N,y);},[I,N,y]),Be=useCallback(async A=>{let D=A?.text!==void 0?A.text:s,_=A?.files||[],B=D.trim();if(!(!B&&_.length===0)&&!Y){A?.text===void 0&&d("");try{if(l){let te={role:"user",content:B,createdAt:Date.now(),chatId:y};l(te);}await xe({text:B,files:_});}catch(te){throw console.error("Failed to send message:",te),te}}},[s,Y,xe,l,y]),Se=useCallback(()=>{if(Y)return;V(),d("");try{G?.setMessages?.([]);}catch{}let A=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;w(A);},[Y,G,V,w]),Dt=useCallback(A=>{try{G?.setMessages?.(A);}catch{}},[G]);return {input:s,setInput:d,messages:N,isLoading:Y,status:pe,error:ht,sendMessage:Be,stop:be,newChat:Se,setMessages:Dt,notifyMessagesChange:Ke,chatApi:G,chatId:y,setChatId:w,tools:m,uiComponents:H,formHostRef:R,formStateRef:O,cleanupForms:V,onUISuccess:U,onUIError:W}}function lt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=C=>`${t}.chat.${C}`,o=`${t}.currentChatId`,l=`${t}.showChat`,u=()=>{try{let C=localStorage.getItem(n);return C?JSON.parse(C):[]}catch{return []}},i=C=>{try{localStorage.setItem(n,JSON.stringify(C));}catch{}},h=C=>{try{let y=localStorage.getItem(r(C));return y?JSON.parse(y):null}catch{return null}},I=C=>{try{localStorage.setItem(r(C.id),JSON.stringify(C));}catch{}},f=C=>{let y=u(),w=y.findIndex(x=>x.id===C.id);w>=0?y[w]=C:y.unshift(C),i(y);},S=C=>{let w=u().filter(x=>x.id!==C);i(w);},b=C=>{try{localStorage.removeItem(r(C));}catch{}};return {loadChatsIndex:u,saveChatsIndex:i,loadChat:h,saveChat:I,upsertChatMeta:f,deleteChatMeta:S,deleteChatData:b,deleteChat:C=>{b(C),S(C);},loadShowChatPreference:C=>{try{let y=localStorage.getItem(l);return y!==null?y==="true":C}catch{return C}},saveShowChatPreference:C=>{try{localStorage.setItem(l,String(C));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:C=>{try{localStorage.setItem(o,C);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Lt(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:l=true,autoRestore:u=true}=e,i=useMemo(()=>lt(t),[t]),[h,I]=useState([]),[f,S]=useState(null),b=useRef(false),k=useRef(false),a=useCallback(()=>{try{let x=i.loadChatsIndex();I(x);let c=x.find(p=>p.id===n);S(c||null);}catch(x){console.error("Failed to refresh chat list:",x);}},[i,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!u||k.current)){try{i.loadCurrentChatId()&&(b.current=!0);}catch(x){console.error("Failed to restore chat:",x);}k.current=true;}},[i,u]),useEffect(()=>{if(!(!l||r.length===0))if(b.current){if(!o){let x=Date.now();try{i.saveChat({id:n,messages:r,agentId:t});let p=i.loadChatsIndex().find(T=>T.id===n);p&&(i.upsertChatMeta({...p,updatedAt:x}),a());}catch(c){console.error("Failed to save chat:",c);}}}else {let x=r.find(c=>c.role==="user");if(x){let c="";if(Array.isArray(x.parts)){let m=x.parts.find(F=>F&&F.type==="text");c=m&&typeof m.text=="string"?m.text:"";}let p=(c||"New chat").slice(0,80),T=Date.now();try{i.upsertChatMeta({id:n,title:p,createdAt:T,updatedAt:T}),i.saveChat({id:n,messages:r,agentId:t}),i.saveCurrentChatId(n),b.current=!0,a();}catch(m){console.error("Failed to create chat:",m);}}}},[]);let v=useRef(false);useEffect(()=>{if(o){v.current=true;return}if(v.current&&l){v.current=false;try{let x=Date.now();i.saveChat({id:n,messages:r,agentId:t});let p=i.loadChatsIndex().find(T=>T.id===n);if(p)i.upsertChatMeta({...p,updatedAt:x});else {let T="",m=Array.isArray(r)?r.find(H=>H&&H.role==="user"):void 0;if(m&&Array.isArray(m.parts)){let H=m.parts.find(R=>R&&R.type==="text");T=H&&typeof H.text=="string"?H.text:"";}let F=(T||"New chat").slice(0,80);i.upsertChatMeta({id:n,title:F,createdAt:x,updatedAt:x});try{i.saveCurrentChatId(n);}catch{}b.current=!0;}a();}catch(x){console.error("Failed to save chat on completion:",x);}}},[o,r,n,t,i,l,a]);let s=useCallback(x=>{try{let c=i.loadChat(x);return c?{id:c.id,messages:c.messages,agentId:c.agentId||t}:null}catch(c){return console.error("Failed to load chat:",c),null}},[i,t]),d=useCallback(()=>{if(r.length!==0)try{let x=Date.now();i.saveChat({id:n,messages:r,agentId:t});let p=i.loadChatsIndex().find(T=>T.id===n);p&&(i.upsertChatMeta({...p,updatedAt:x}),a());}catch(x){console.error("Failed to save chat:",x);}},[i,n,r,t,a]),g=useCallback(x=>{try{i.deleteChat(x),a();}catch(c){console.error("Failed to delete chat:",c);}},[i,a]),C=useCallback((x,c)=>{if(x!==n)try{b.current=!0,i.saveCurrentChatId(x);let p=i.loadChat(x),T=p&&Array.isArray(p.messages)?p.messages:[];c(T),a();}catch(p){console.error("Failed to switch chat:",p);}},[i,n,a]),y=useCallback(x=>{b.current=false,x();},[]),w=useCallback(x=>{if(!x.trim())return h;let c=x.toLowerCase();return h.filter(p=>p.title.toLowerCase().includes(c))},[h]);return {chatList:h,currentChatMeta:f,refreshChatList:a,loadChat:s,saveCurrentChat:d,deleteChat:g,switchToChat:C,createNewChat:y,searchChats:w,storage:i}}function Xo(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:l}=e,{baseUrl:u}=ae(),i=l||u||"",[h,I]=useState(null),[f,S]=useState(""),[b,k]=useState([]),[a,v]=useState(false),s=useCallback((x,c,p=[])=>{I(x),S(c),k(p);},[]),d=useCallback(()=>{I(null),S(""),k([]);},[]),g=useCallback(async x=>{if(!n)try{let c=t.findIndex(T=>T.id===x);if(c===-1)return;let p=t.slice(0,c);o(p),await r({text:f.trim(),files:b.map(T=>({type:"file",url:T.url,mediaType:T.mimeType||"application/octet-stream",...T.name?{name:T.name}:{},...T.size?{size:T.size}:{}}))}),d();}catch(c){throw console.error("Failed to save edit:",c),c}},[n,t,r,f,b,o,d]),C=useCallback(x=>h===x,[h]),y=useCallback(async x=>{if(!i){console.warn("baseUrl not provided, cannot upload attachments");return}v(true);try{let c=Array.from(x).map(async T=>{if(T.size>26214400)throw new Error(`${T.name} is too large (max 25MB)`);let m=new FormData;m.append("file",T);let F=await fetch(`${i}/api/upload`,{method:"POST",body:m});if(!F.ok)throw new Error(`Upload failed: ${F.statusText}`);let H=await F.json();return {id:H.url||`${Date.now()}-${Math.random()}`,name:T.name,url:H.url,mimeType:T.type,size:T.size}}),p=await Promise.all(c);k(T=>[...T,...p]);}catch(c){throw console.error("Failed to upload files:",c),c}finally{v(false);}},[i]),w=useCallback(x=>{k(c=>c.filter(p=>p.id!==x));},[]);return {editingMessageId:h,editingText:f,setEditingText:S,editAttachments:b,setEditAttachments:k,editUploading:a,startEdit:s,cancelEdit:d,saveEdit:g,isEditing:C,addEditAttachments:y,removeEditAttachment:w}}function X({IconComponent:e,...t}){return at.createElement(e,t)}function Ht({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:l}){return jsx("button",{"aria-label":n,title:l,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:u=>{o||(u.currentTarget.style.backgroundColor=r.hoverBackground,u.currentTarget.style.color=r.textColor);},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent",u.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function Tn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:l,onToggleHistory:u,onClose:i,historyBtnRef:h,t:I}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsx(Ht,{icon:jsx(X,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||l();},ariaLabel:I("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:h,"aria-label":I("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor=o.hoverBackground,f.currentTarget.style.color=o.textColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=o.mutedTextColor;},onClick:u,children:jsx(X,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(Ht,{icon:jsx(X,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:i,ariaLabel:I("header.close"),resolvedColors:o})]})]})}var mt=class extends Component{constructor(t){super(t),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(t){return {hasError:true,error:t,errorInfo:null}}componentDidMount(){let{toolCallId:t,toolName:n,onSuccess:r}=this.props;t&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(t,n);},0);}componentDidCatch(t,n){console.error(`UI Component Error (${this.props.componentName}):`,t,n),this.setState({error:t,errorInfo:n});let{toolCallId:r,toolName:o,onError:l}=this.props;r&&o&&l&&l(r,o,t);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:t,componentName:n}=this.props;return jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var nr=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"]},or=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}},rr=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function In({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:l,onUIError:u,onUISuccess:i,addToolResult:h}){let I=[],f=[],S,b,k=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){f.push(a.text),S||(S=a.startDate),b=a.endDate,a.state==="done"&&(k=true);continue}if(a.type==="text"&&typeof a.text=="string"){f.length&&(I.push({type:"reasoning",texts:f,startDate:S,endDate:b,isCompleted:k}),f=[],S=void 0,b=void 0,k=false),I.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"){f.length&&(I.push({type:"reasoning",texts:f,startDate:S,endDate:b,isCompleted:k}),f=[],S=void 0,b=void 0,k=false);let d=String(v?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");d==="requestInput"?I.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}):I.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 f.length&&I.push({type:"reasoning",texts:f,startDate:S,endDate:b,isCompleted:k}),I.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[I.map((a,v)=>{let s=`${t}-${v}`,d=n.has(s);if(a.type==="reasoning"){let c=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",p=a.texts&&a.texts.length>0&&a.texts.some(m=>m.trim().length>0),T=()=>{p&&r(s);};return c&&!p?null:jsx("div",{onClick:T,style:{cursor:p?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:d?"4px":"0px"},children:[jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!c&&jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{color:o.textColor,fontWeight:600,opacity:.9,background:c?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:c?"auto":"200% 100%",backgroundClip:c?"unset":"text",WebkitBackgroundClip:c?"unset":"text",WebkitTextFillColor:c?o.mutedTextColor:"transparent",animation:c?void 0:"shimmer 2s ease-in-out infinite"},children:c?"Finish Thinking":"Thinking"})]}),p&&jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:d?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsx("div",{style:{display:"grid",gridTemplateRows:d||!c?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsx("div",{style:{fontSize:"13px",color:o.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!c&&d?a.texts:c?d?a.texts:[]:[a.texts[a.texts.length-1]]).map((m,F)=>jsx("div",{style:{marginBottom:"6px"},children:jsx(Ge,{content:m,theme:"dark"})},`rg-line-${v}-${F}`))}):jsxs("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text")return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(Ge,{content:a.text,theme:"dark"})},s);let{color:g,text:C}=nr(a.status),y=a.status==="input-streaming"||a.status==="input-available";if(a.toolName==="requestInput")return jsx("div",{style:{display:"block",position:"relative"},children:jsx("div",{"data-get-from-user-host":a.toolCallId||s,style:{width:"100%"}})},s);let w=l?.[a.toolName||""];if(w)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(mt,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:u,onSuccess:i,children:jsx(w,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:h})})},s);let x=or(a.toolName||"tool");return jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsx("div",{style:{flex:1,minWidth:0},children:jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxs("span",{style:{fontWeight:600,color:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:g,animation:y?"pulse 1.5s ease-in-out infinite":void 0}}),C]}),x.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:x.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:x.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:rr(x.toolName)})]})})},s)}),jsx("style",{children:`
|
|
19
19
|
@keyframes shimmer {
|
|
20
20
|
0% { background-position: -200% 0; }
|
|
21
21
|
100% { background-position: 200% 0; }
|
|
22
22
|
}
|
|
23
|
-
`})]}):null}function
|
|
23
|
+
`})]}):null}function Sn(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 Mn({attachment:e,resolvedColors:t,mode:n,onRemove:r,maxWidth:o="200px"}){let l=e.mimeType?.startsWith("image/"),u=n==="editable"||n==="input",i=n==="viewable",h={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:i?"pointer":"default",maxWidth:n==="input"?"140px":o,position:"relative"},I=jsxs(Fragment,{children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",backgroundColor:l?"transparent":t.accentColor,flexShrink:0},children:[l?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:f=>{f.target.style.display="none";let S=f.target.nextElementSibling;S&&(S.style.display="block");}}):null,jsx(X,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:l?"none":"block",color:t.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:Sn(e.size)})]}),n==="input"&&l&&jsx("button",{onClick:f=>{f.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:f=>{f.currentTarget.style.backgroundColor=t.hoverBackground,f.currentTarget.style.color=t.textColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=t.mutedTextColor;},children:jsx(X,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),u&&r&&jsx("button",{onClick:f=>{f.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:f=>{f.currentTarget.style.backgroundColor="#ef444420",f.currentTarget.style.color="#ef4444";},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=t.mutedTextColor;},children:jsx(X,{IconComponent:X$1,size:"12",strokeWidth:"2"})}),i&&jsx(X,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return i?jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...h,textDecoration:"none"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor=t.hoverBackground,f.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor=t.inputBackground,f.currentTarget.style.borderColor=t.borderColor;},children:I}):jsx("div",{style:h,children:I})}function An({attachments:e,resolvedColors:t,onRemove:n}){if(!Array.isArray(e)||e.length===0)return null;let r=typeof n=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(o=>jsx(Mn,{attachment:o,resolvedColors:t,mode:r,onRemove:n},o.id))})}function Rn({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:l,onUserMessageClick:u,HsafaUI:i,onUIError:h,onUISuccess:I,addToolResult:f,editableMessageIcon:S}){return jsxs(Fragment,{children:[jsx("style",{children:`
|
|
24
24
|
@keyframes jumpingDots {
|
|
25
25
|
0%, 80%, 100% {
|
|
26
26
|
transform: translateY(0);
|
|
@@ -30,14 +30,14 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import at,{createContext,useRe
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
`}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((b,k)=>{let a=Array.isArray(b.parts)?b.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||`${b.id}-img-${Date.now()}`,name:d.name||"image",url:g,mimeType:d.mediaType||"image/jpeg",size:d.size||0}}else return {id:d.url||`${b.id}-file-${Date.now()}`,name:d.name||"file",url:d.url||"",mimeType:d.mediaType||"application/octet-stream",size:d.size||0}});return jsx("div",{style:{padding:"0 4px"},children:b.role==="user"?jsx("div",{children:jsx("div",{title:i("editor.clickToEdit"),onClick:()=>u(b,b.id,v,s),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:o.accentColor,color:o.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:d=>d.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor=o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[v,s.length>0&&jsx(En,{attachments:s,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(X,{IconComponent:M||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(Tn,{parts:a,messageId:b.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:l,onUIError:x,onUISuccess:I,addToolResult:f})},b.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function Rn({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:i,attachments:u,formatBytes:l,handleRemoveAttachment:x,onFileInputChange:I,onSend:f,onStop:M,status:b,t:k,resolvedColors:a}){let v=b==="streaming"||b==="submitted",s=u.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[u.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:u.map(d=>{let g=d.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:a.inputBackground,borderRadius:"10px",border:`1px solid ${a.borderColor}`,fontSize:"12px",color:a.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:g?"transparent":a.cardBackground},children:g?jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:d.name}),jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:l(d.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[g&&jsx("a",{href:d.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:k("input.previewImage"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsx("button",{onClick:()=>x(d.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:k("input.removeFile"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},d.id)})}),i&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:k("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:k("input.placeholder"),value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),f());},disabled:o||i,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:a.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:r,type:"file",multiple:true,onChange:I,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:a.mutedTextColor},children:jsx("button",{onClick:()=>r.current?.click(),disabled:o||i,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||i?.5:1},"aria-label":k("input.attachFiles"),children:jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:o?jsx("button",{onClick:M,disabled:!v,"aria-label":k("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:v?1:.4,cursor:v?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{v&&(d.currentTarget.style.backgroundColor="#ef444430",d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:f,disabled:!s||i,"aria-label":k("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground,color:!s||i?a.mutedTextColor:a.primaryColor,cursor:!s||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||i?.5:1},onMouseEnter:d=>{s&&!i&&(d.currentTarget.style.borderColor=a.primaryColor,d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.borderColor=a.borderColor,d.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function Fn({prompts:e,onSelect:t,resolvedColors:n,disabled:r=false}){let[o,i]=useState(null);return !e||e.length===0?null:jsxs("div",{style:{padding:"12px 0",display:"flex",flexDirection:"column",gap:"8px"},children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:n.mutedTextColor,paddingLeft:"4px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Suggested Prompts"}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.map((u,l)=>{let x=o===l,I=u.prompt.length>80,f=I&&!x?u.prompt.slice(0,80)+"...":u.prompt;return jsxs("button",{onClick:()=>{r||t(u.prompt);},disabled:r,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,borderRadius:"12px",cursor:r?"not-allowed":"pointer",transition:"all 0.2s ease",textAlign:"left",opacity:r?.5:1,position:"relative",overflow:"hidden"},onMouseEnter:M=>{r||(M.currentTarget.style.backgroundColor=n.hoverBackground,M.currentTarget.style.borderColor=n.primaryColor,M.currentTarget.style.transform="translateX(2px)");},onMouseLeave:M=>{M.currentTarget.style.backgroundColor=n.cardBackground,M.currentTarget.style.borderColor=n.borderColor,M.currentTarget.style.transform="translateX(0)";},children:[jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:n.textColor,marginBottom:"6px",display:"flex",alignItems:"center",gap:"6px"},children:[jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n.primaryColor,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[jsx("path",{d:"M12 20h9"}),jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),u.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:f}),I&&jsxs("button",{onClick:M=>{M.stopPropagation(),i(x?null:l);},style:{marginTop:"8px",padding:"4px 8px",fontSize:"11px",color:n.primaryColor,backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:"4px",fontWeight:500},children:[x?"Show less":"Show more",jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:x?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},l)})})]})}function Ln(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 u=Math.floor(i/7);if(u<4)return `${u}w`;let l=Math.floor(i/30);return l<12?`${l}mo`:`${Math.floor(l/12)}y`}function Hn({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:i,onSearchChange:u,onChatSelect:l,onChatDelete:x,loadChatsIndex:I,historyPopupRef:f}){if(!e)return null;let M=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:i}),jsxs("div",{ref:f,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:b=>u(b.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:o.inputBackground,padding:"8px 12px",fontSize:"14px",color:o.textColor,border:`1px solid ${o.borderColor}`,outline:"none"},onFocus:b=>b.currentTarget.style.borderColor=o.primaryColor,onBlur:b=>b.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let b=t.toLowerCase().trim(),k=I();return b&&(k=k.filter(a=>(a.title||"").toLowerCase().includes(b))),!k||k.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:k.map((a,v)=>jsx("div",{style:{borderTop:v>0?`1px solid ${o.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===n?o.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:o.textColor},onMouseEnter:s=>s.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor="transparent",onClick:()=>l(a.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:o.textColor},children:a.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:Ln(a.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:o.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:s=>{s.currentTarget.style.color="#ef4444",s.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",s.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:s=>{s.currentTarget.style.color=o.mutedTextColor,s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.borderColor="transparent";},onClick:s=>{s.stopPropagation(),x(a.id);},children:jsx(X,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(M,document.body):M}function $n({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let i=o?.title||"Edit Message",u=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?",l=o?.submit_button_label||"Edit",x=o?.cancel_button_label||"Cancel",I=o?.icon,f=typeof u=="function",M=f?u:null,b=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[I?jsx("div",{style:{flexShrink:0},children:jsx(X,{IconComponent:I,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsx(X,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:i})]}),jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:f&&M?jsx(M,{}):jsx("p",{style:{margin:0},children:u})}),jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${t.borderColor}`,justifyContent:"flex-end"},children:[jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${t.borderColor}`,backgroundColor:"transparent",color:t.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:k=>{k.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:k=>{k.currentTarget.style.backgroundColor="transparent";},children:x}),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:l})]})]})]});return typeof document<"u"&&document.body?createPortal(b,document.body):b}function Cr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:i,borderColor:u,textColor:l,accentColor:x,baseUrl:I="",initialMessages:f=[],onMessagesChange:M,defaultOpen:b=true,floatingButtonPosition:k={bottom:24,right:24},HsafaTools:a={},HsafaUI:v={},componentAboveInput:s,editProcessContent:d,presetPrompts:g,onStart:y,onFinish:C,currentChat:T,onChatChanged:h}){let{dir:c,theme:p,baseUrl:w,setStreamingState:m,setChatOpenState:R}=re(),A=t||p||"dark",H=I&&I.length>0?I:w||"",L={primaryColor:A==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:i||(A==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:u||(A==="dark"?"#2A2C33":"#E5E7EB"),textColor:l||(A==="dark"?"#EDEEF0":"#111827"),accentColor:x||(A==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:A==="dark"?"#6f7276":"#6B7280",inputBackground:A==="dark"?"#17181C":"#F3F4F6",cardBackground:A==="dark"?"#121318":"#FFFFFF",hoverBackground:A==="dark"?"#1c1e25":"#F3F4F6"},F=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,$=At({agentId:e,baseUrl:H,tools:a,uiComponents:v,controlledChatId:T,onChatIdChange:T===void 0?S=>{h&&h(S);}:void 0,onStart:useCallback(S=>{y&&y(S);},[y]),onFinish:useCallback(S=>{C&&C(S);},[C]),onError:useCallback(S=>{console.error("Chat error:",S);},[]),initialMessages:f,onMessagesChange:M}),{input:N,setInput:O,messages:G,isLoading:P,status:he,error:ue,sendMessage:xe,stop:Ie,setMessages:Y,notifyMessagesChange:Ke,chatId:Be,setChatId:Me,tools:Bt,uiComponents:E,formHostRef:z,formStateRef:_,cleanupForms:D,onUISuccess:ee,onUIError:te,chatApi:pe}=$,Z=T!==void 0?T:Be,be=useCallback(S=>{T===void 0&&Me(S),h&&h(S);},[T,Me,h]);useEffect(()=>{T!==void 0&&T!==Be&&Me(T);},[T,Be,Me]);let{attachments:Xe,uploading:Dn,fileInputRef:Ye,formatBytes:Pn,handleRemoveAttachment:zn,handleFileSelection:Dt,clearAttachments:Je,setAttachments:Pt}=Jt(H),[zt,Se]=useState(null),[Ze,Nt]=useState(()=>{try{return lt(e).loadShowChatPreference(!!b)}catch{return !!b}}),[Nn,ht]=useState(false),[Un,Wn]=useState(""),[On,Gn]=useState(0),_n=useRef(null),jn=useRef(null),[qn,Vn]=useState(new Set),[Kn,xt]=useState(false),[De,bt]=useState(null),Ut=useRef(null),Xn=Vt(P),Ct=Ft({agentId:e,chatId:Z,messages:G,isLoading:P,autoSave:true,autoRestore:false}),V=Ct.storage,Pe=useRef(false),ze=useRef(null);useEffect(()=>{if(!Pe.current){if(T!==void 0){try{let S=V.loadChat(T),U=S&&Array.isArray(S.messages)?S.messages:[];if(U.length>0)try{Y(U);}catch{}ze.current=T;}catch{}try{V.saveCurrentChatId(T);}catch{}Pe.current=true;return}try{let S=V.loadCurrentChatId();if(S){be(S);let U=V.loadChat(S),j=U&&Array.isArray(U.messages)?U.messages:[];try{Y(j);}catch{}ze.current=S;}}catch{}Pe.current=true;}},[T]),useEffect(()=>{if(Pe.current&&T!==void 0&&T!==ze.current)try{let S=V.loadChat(T),U=S&&Array.isArray(S.messages)?S.messages:[];try{Y(U);}catch{}ze.current=T;try{V.saveCurrentChatId(T);}catch{}}catch{}},[T,V,Y]),useEffect(()=>{if(Pe.current)try{V.saveCurrentChatId(Z);}catch{}},[Z,V]),useEffect(()=>{try{m(Z,P);}catch{}return ()=>{try{m(Z,!1);}catch{}}},[Z,P,m]),useEffect(()=>{try{R(Z,Ze);}catch{}return ()=>{try{R(Z,!1);}catch{}}},[Z,Ze,R]);let Yn=useCallback(async()=>{let S=N.trim();if(!S&&Xe.length===0||P)return;let U=[...Xe];O(""),Je(),Se(null);try{await xe({text:S,files:U.map(j=>({type:"file",url:j.url,mediaType:j.mimeType||"application/octet-stream",...j.name?{name:j.name}:{},...j.size?{size:j.size}:{}}))});}catch(j){console.error("Failed to send message:",j),Se("Failed to send message. Please try again.");}},[N,Xe,P,xe,Je]),Wt=useCallback(()=>{if(P)return;D(),O(""),Je(),Se(null);try{Y([]);}catch{}let S=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;ze.current=S;try{Ct.createNewChat(()=>{be(S);try{V.saveCurrentChatId(S);}catch{}});}catch{be(S);try{V.saveCurrentChatId(S);}catch{}}},[P,Je,V,Y,be,D,Ct]),Jn=useCallback(()=>{ht(S=>!S);},[]),Zn=useCallback(()=>{Nt(false);try{V.saveShowChatPreference(!1);}catch{}},[V]),Qn=useCallback(async S=>{let U=S.target.files;U&&await Dt(U,Se),Ye.current&&(Ye.current.value="");},[Dt,Ye]);useEffect(()=>{let S=Ut.current;if(!S)return;S.style.height="24px",S.offsetHeight,S.style.height="auto";let U=Math.min(S.scrollHeight,200);S.style.height=`${U}px`;},[N]);let eo=useCallback((S,U,j,oo)=>{bt({id:U,text:j,attachments:oo||[]}),xt(true);},[]),to=useCallback(()=>{if(!(!De||P))try{let S=G.findIndex(j=>j.id===De.id);if(S===-1)return;let U=G.slice(0,S);try{Y(U);}catch{}O(De.text),Pt(De.attachments),xt(!1),bt(null),Ke();}catch(S){console.error("Failed to edit message:",S),Se("Failed to edit message. Please try again.");}},[De,P,G,Y,Pt,Ke]),no=useCallback(()=>{xt(false),bt(null);},[]),Ot=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:L.textColor,gap:"16px",zIndex:1e3,transform:Ze?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(wn,{title:F("general.agent"),alwaysOpen:false,streaming:P,dir:c||"ltr",resolvedColors:L,onNew:Wt,onToggleHistory:Jn,onClose:Zn,historyBtnRef:_n,t:F}),jsx("div",{ref:Xn,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":L.primaryColor,"--hsafa-border":L.borderColor,"--hsafa-card":L.cardBackground,"--hsafa-text":L.textColor,"--hsafa-muted":L.mutedTextColor,"--hsafa-bg":L.backgroundColor,"--hsafa-hover":L.hoverBackground,"--hsafa-input-bg":L.inputBackground,"--hsafa-accent":L.accentColor},children:G.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:g&&g.length>0?jsx(Fn,{prompts:g,onSelect:S=>O(S),resolvedColors:L,disabled:P}):jsx("div",{style:{padding:"32px",textAlign:"center",color:L.mutedTextColor,fontSize:"14px"},children:F("messages.empty")})}):jsx(An,{chatMessages:G,isLoading:P,openReasoningIds:qn,toggleReasoning:S=>Vn(U=>{let j=new Set(U);return j.has(S)?j.delete(S):j.add(S),j}),resolvedColors:L,t:F,onUserMessageClick:eo,HsafaUI:E,onUIError:te,onUISuccess:ee,addToolResult:S=>pe?.addToolResult?.(S),editableMessageIcon:d?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&at.createElement(s,{}),zt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:zt}),jsx("button",{onClick:()=>Se(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),ue&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",ue.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(Rn,{input:N,setInput:O,textareaRef:Ut,fileInputRef:Ye,isLoading:P,uploading:Dn,attachments:Xe,formatBytes:Pn,handleRemoveAttachment:zn,onFileInputChange:Qn,onSend:Yn,onStop:()=>Ie(),status:he,t:F,resolvedColors:L})]}),jsx(Hn,{historyOpen:Nn,historySearch:Un,currentChatId:Z,refreshKey:On,resolvedColors:L,onClose:()=>ht(false),onSearchChange:Wn,onChatSelect:S=>{if(ht(false),S&&S!==Z&&(D(),be(S),T===void 0)){try{V.saveCurrentChatId(S);}catch{}try{let U=V.loadChat(S),j=U&&Array.isArray(U.messages)?U.messages:[];try{Y(j);}catch{}}catch{}}},onChatDelete:S=>{try{V.deleteChat(S),Gn(U=>U+1),S===Z&&Wt();}catch{}},loadChatsIndex:()=>V.loadChatsIndex(),historyPopupRef:jn}),jsx($n,{isOpen:Kn,resolvedColors:L,onConfirm:to,onCancel:no,editProcessContent:d}),jsx("style",{children:`
|
|
33
|
+
`),s=a.filter(d=>d.type==="file"||d.type==="image").map(d=>{if(d.type==="image"){let g=typeof d.image=="string"?d.image:d.image?.toString?.()||"";return {id:g||`${b.id}-img-${Date.now()}`,name:d.name||"image",url:g,mimeType:d.mediaType||"image/jpeg",size:d.size||0}}else return {id:d.url||`${b.id}-file-${Date.now()}`,name:d.name||"file",url:d.url||"",mimeType:d.mediaType||"application/octet-stream",size:d.size||0}});return jsx("div",{style:{padding:"0 4px"},children:b.role==="user"?jsx("div",{children:jsx("div",{title:l("editor.clickToEdit"),onClick:()=>u(b,b.id,v,s),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:o.accentColor,color:o.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:d=>d.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor=o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[v,s.length>0&&jsx(An,{attachments:s,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(X,{IconComponent:S||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(In,{parts:a,messageId:b.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:h,onUISuccess:I,addToolResult:f})},b.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function Fn({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:l,attachments:u,formatBytes:i,handleRemoveAttachment:h,onFileInputChange:I,onSend:f,onStop:S,status:b,t:k,resolvedColors:a}){let v=b==="streaming"||b==="submitted",s=u.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[u.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:u.map(d=>{let g=d.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:a.inputBackground,borderRadius:"10px",border:`1px solid ${a.borderColor}`,fontSize:"12px",color:a.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:g?"transparent":a.cardBackground},children:g?jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:d.name}),jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:i(d.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[g&&jsx("a",{href:d.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:k("input.previewImage"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsx("button",{onClick:()=>h(d.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:k("input.removeFile"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},d.id)})}),l&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:k("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:k("input.placeholder"),value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),f());},disabled:o||l,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:a.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:r,type:"file",multiple:true,onChange:I,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:a.mutedTextColor},children:jsx("button",{onClick:()=>r.current?.click(),disabled:o||l,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||l?.5:1},"aria-label":k("input.attachFiles"),children:jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:o?jsx("button",{onClick:S,disabled:!v,"aria-label":k("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:v?1:.4,cursor:v?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{v&&(d.currentTarget.style.backgroundColor="#ef444430",d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:f,disabled:!s||l,"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||l?a.mutedTextColor:a.primaryColor,cursor:!s||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||l?.5:1},onMouseEnter:d=>{s&&!l&&(d.currentTarget.style.borderColor=a.primaryColor,d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.borderColor=a.borderColor,d.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function Ln({prompts:e,onSelect:t,resolvedColors:n,disabled:r=false}){let[o,l]=useState(null);return !e||e.length===0?null:jsxs("div",{style:{padding:"12px 0",display:"flex",flexDirection:"column",gap:"8px"},children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:n.mutedTextColor,paddingLeft:"4px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Suggested Prompts"}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.map((u,i)=>{let h=o===i,I=u.prompt.length>80,f=I&&!h?u.prompt.slice(0,80)+"...":u.prompt;return jsxs("button",{onClick:()=>{r||t(u.prompt);},disabled:r,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,borderRadius:"12px",cursor:r?"not-allowed":"pointer",transition:"all 0.2s ease",textAlign:"left",opacity:r?.5:1,position:"relative",overflow:"hidden"},onMouseEnter:S=>{r||(S.currentTarget.style.backgroundColor=n.hoverBackground,S.currentTarget.style.borderColor=n.primaryColor,S.currentTarget.style.transform="translateX(2px)");},onMouseLeave:S=>{S.currentTarget.style.backgroundColor=n.cardBackground,S.currentTarget.style.borderColor=n.borderColor,S.currentTarget.style.transform="translateX(0)";},children:[jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:n.textColor,marginBottom:"6px",display:"flex",alignItems:"center",gap:"6px"},children:[jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n.primaryColor,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[jsx("path",{d:"M12 20h9"}),jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),u.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:f}),I&&jsxs("button",{onClick:S=>{S.stopPropagation(),l(h?null:i);},style:{marginTop:"8px",padding:"4px 8px",fontSize:"11px",color:n.primaryColor,backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:"4px",fontWeight:500},children:[h?"Show less":"Show more",jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:h?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},i)})})]})}function Hn(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 l=Math.floor(o/24);if(l<7)return `${l}d`;let u=Math.floor(l/7);if(u<4)return `${u}w`;let i=Math.floor(l/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function $n({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:l,onSearchChange:u,onChatSelect:i,onChatDelete:h,loadChatsIndex:I,historyPopupRef:f}){if(!e)return null;let S=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:l}),jsxs("div",{ref:f,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:b=>u(b.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:o.inputBackground,padding:"8px 12px",fontSize:"14px",color:o.textColor,border:`1px solid ${o.borderColor}`,outline:"none"},onFocus:b=>b.currentTarget.style.borderColor=o.primaryColor,onBlur:b=>b.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let b=t.toLowerCase().trim(),k=I();return b&&(k=k.filter(a=>(a.title||"").toLowerCase().includes(b))),!k||k.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:k.map((a,v)=>jsx("div",{style:{borderTop:v>0?`1px solid ${o.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===n?o.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:o.textColor},onMouseEnter:s=>s.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor="transparent",onClick:()=>i(a.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:o.textColor},children:a.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:Hn(a.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:o.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:s=>{s.currentTarget.style.color="#ef4444",s.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",s.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:s=>{s.currentTarget.style.color=o.mutedTextColor,s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.borderColor="transparent";},onClick:s=>{s.stopPropagation(),h(a.id);},children:jsx(X,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(S,document.body):S}function Bn({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let l=o?.title||"Edit Message",u=o?.content||"This will remove this message and all messages after it, and place its content in the input field for editing. Do you want to continue?",i=o?.submit_button_label||"Edit",h=o?.cancel_button_label||"Cancel",I=o?.icon,f=typeof u=="function",S=f?u:null,b=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[I?jsx("div",{style:{flexShrink:0},children:jsx(X,{IconComponent:I,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsx(X,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:l})]}),jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:f&&S?jsx(S,{}):jsx("p",{style:{margin:0},children:u})}),jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${t.borderColor}`,justifyContent:"flex-end"},children:[jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${t.borderColor}`,backgroundColor:"transparent",color:t.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:k=>{k.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:k=>{k.currentTarget.style.backgroundColor="transparent";},children:h}),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:i})]})]})]});return typeof document<"u"&&document.body?createPortal(b,document.body):b}function vr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:l,borderColor:u,textColor:i,accentColor:h,baseUrl:I="",initialMessages:f=[],onMessagesChange:S,defaultOpen:b=true,floatingButtonPosition:k={bottom:24,right:24},HsafaTools:a={},HsafaUI:v={},componentAboveInput:s,editProcessContent:d,presetPrompts:g,onStart:C,onFinish:y,currentChat:w,onChatChanged:x,templateParams:c}){let{dir:p,theme:T,baseUrl:m,setStreamingState:F,setChatOpenState:H}=ae(),R=t||T||"dark",O=I&&I.length>0?I:m||"",E={primaryColor:R==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:l||(R==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:u||(R==="dark"?"#2A2C33":"#E5E7EB"),textColor:i||(R==="dark"?"#EDEEF0":"#111827"),accentColor:h||(R==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:R==="dark"?"#6f7276":"#6B7280",inputBackground:R==="dark"?"#17181C":"#F3F4F6",cardBackground:R==="dark"?"#121318":"#FFFFFF",hoverBackground:R==="dark"?"#1c1e25":"#F3F4F6"},L=M=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[M]||M,W=Rt({agentId:e,baseUrl:O,tools:a,uiComponents:v,templateParams:c,controlledChatId:w,onChatIdChange:w===void 0?M=>{x&&x(M);}:void 0,onStart:useCallback(M=>{C&&C(M);},[C]),onFinish:useCallback(M=>{y&&y(M);},[y]),onError:useCallback(M=>{console.error("Chat error:",M);},[]),initialMessages:f,onMessagesChange:S}),{input:U,setInput:Z,messages:G,isLoading:N,status:xe,error:pe,sendMessage:be,stop:ht,setMessages:Y,notifyMessagesChange:Ke,chatId:Be,setChatId:Se,tools:Dt,uiComponents:A,formHostRef:D,formStateRef:_,cleanupForms:B,onUISuccess:te,onUIError:ne,chatApi:me}=W,Q=w!==void 0?w:Be,Ce=useCallback(M=>{w===void 0&&Se(M),x&&x(M);},[w,Se,x]);useEffect(()=>{w!==void 0&&w!==Be&&Se(w);},[w,Be,Se]);let{attachments:Xe,uploading:Pn,fileInputRef:Ye,formatBytes:zn,handleRemoveAttachment:Nn,handleFileSelection:Pt,clearAttachments:Je,setAttachments:zt}=Zt(O),[Nt,Me]=useState(null),[Ze,Wt]=useState(()=>{try{return lt(e).loadShowChatPreference(!!b)}catch{return !!b}}),[Wn,xt]=useState(false),[Un,On]=useState(""),[Gn,_n]=useState(0),jn=useRef(null),qn=useRef(null),[Vn,Kn]=useState(new Set),[Xn,bt]=useState(false),[De,Ct]=useState(null),Ut=useRef(null),Yn=Kt(N),vt=Lt({agentId:e,chatId:Q,messages:G,isLoading:N,autoSave:true,autoRestore:false}),q=vt.storage,Pe=useRef(false),ze=useRef(null);useEffect(()=>{if(!Pe.current){if(w!==void 0){try{let M=q.loadChat(w),P=M&&Array.isArray(M.messages)?M.messages:[];if(P.length>0)try{Y(P);}catch{}ze.current=w;}catch{}try{q.saveCurrentChatId(w);}catch{}Pe.current=true;return}try{let M=q.loadCurrentChatId();if(M){Ce(M);let P=q.loadChat(M),j=P&&Array.isArray(P.messages)?P.messages:[];try{Y(j);}catch{}ze.current=M;}}catch{}Pe.current=true;}},[w]),useEffect(()=>{if(Pe.current&&w!==void 0&&w!==ze.current)try{let M=q.loadChat(w),P=M&&Array.isArray(M.messages)?M.messages:[];try{Y(P);}catch{}ze.current=w;try{q.saveCurrentChatId(w);}catch{}}catch{}},[w,q,Y]),useEffect(()=>{if(Pe.current)try{q.saveCurrentChatId(Q);}catch{}},[Q,q]),useEffect(()=>{try{F(Q,N);}catch{}return ()=>{try{F(Q,!1);}catch{}}},[Q,N,F]),useEffect(()=>{try{H(Q,Ze);}catch{}return ()=>{try{H(Q,!1);}catch{}}},[Q,Ze,H]);let Jn=useCallback(async()=>{let M=U.trim();if(!M&&Xe.length===0||N)return;let P=[...Xe];Z(""),Je(),Me(null);try{await be({text:M,files:P.map(j=>({type:"file",url:j.url,mediaType:j.mimeType||"application/octet-stream",...j.name?{name:j.name}:{},...j.size?{size:j.size}:{}}))});}catch(j){console.error("Failed to send message:",j),Me("Failed to send message. Please try again.");}},[U,Xe,N,be,Je]),Ot=useCallback(()=>{if(N)return;B(),Z(""),Je(),Me(null);try{Y([]);}catch{}let M=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;ze.current=M;try{vt.createNewChat(()=>{Ce(M);try{q.saveCurrentChatId(M);}catch{}});}catch{Ce(M);try{q.saveCurrentChatId(M);}catch{}}},[N,Je,q,Y,Ce,B,vt]),Zn=useCallback(()=>{xt(M=>!M);},[]),Qn=useCallback(()=>{Wt(false);try{q.saveShowChatPreference(!1);}catch{}},[q]),eo=useCallback(async M=>{let P=M.target.files;P&&await Pt(P,Me),Ye.current&&(Ye.current.value="");},[Pt,Ye]);useEffect(()=>{let M=Ut.current;if(!M)return;M.style.height="24px",M.offsetHeight,M.style.height="auto";let P=Math.min(M.scrollHeight,200);M.style.height=`${P}px`;},[U]);let to=useCallback((M,P,j,ro)=>{Ct({id:P,text:j,attachments:ro||[]}),bt(true);},[]),no=useCallback(()=>{if(!(!De||N))try{let M=G.findIndex(j=>j.id===De.id);if(M===-1)return;let P=G.slice(0,M);try{Y(P);}catch{}Z(De.text),zt(De.attachments),bt(!1),Ct(null),Ke();}catch(M){console.error("Failed to edit message:",M),Me("Failed to edit message. Please try again.");}},[De,N,G,Y,zt,Ke]),oo=useCallback(()=>{bt(false),Ct(null);},[]),Gt=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:E.textColor,gap:"16px",zIndex:1e3,transform:Ze?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(Tn,{title:L("general.agent"),alwaysOpen:false,streaming:N,dir:p||"ltr",resolvedColors:E,onNew:Ot,onToggleHistory:Zn,onClose:Qn,historyBtnRef:jn,t:L}),jsx("div",{ref:Yn,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":E.primaryColor,"--hsafa-border":E.borderColor,"--hsafa-card":E.cardBackground,"--hsafa-text":E.textColor,"--hsafa-muted":E.mutedTextColor,"--hsafa-bg":E.backgroundColor,"--hsafa-hover":E.hoverBackground,"--hsafa-input-bg":E.inputBackground,"--hsafa-accent":E.accentColor},children:G.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:g&&g.length>0?jsx(Ln,{prompts:g,onSelect:M=>Z(M),resolvedColors:E,disabled:N}):jsx("div",{style:{padding:"32px",textAlign:"center",color:E.mutedTextColor,fontSize:"14px"},children:L("messages.empty")})}):jsx(Rn,{chatMessages:G,isLoading:N,openReasoningIds:Vn,toggleReasoning:M=>Kn(P=>{let j=new Set(P);return j.has(M)?j.delete(M):j.add(M),j}),resolvedColors:E,t:L,onUserMessageClick:to,HsafaUI:A,onUIError:ne,onUISuccess:te,addToolResult:M=>me?.addToolResult?.(M),editableMessageIcon:d?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&at.createElement(s,{}),Nt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:Nt}),jsx("button",{onClick:()=>Me(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),pe&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",pe.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(Fn,{input:U,setInput:Z,textareaRef:Ut,fileInputRef:Ye,isLoading:N,uploading:Pn,attachments:Xe,formatBytes:zn,handleRemoveAttachment:Nn,onFileInputChange:eo,onSend:Jn,onStop:()=>ht(),status:xe,t:L,resolvedColors:E})]}),jsx($n,{historyOpen:Wn,historySearch:Un,currentChatId:Q,refreshKey:Gn,resolvedColors:E,onClose:()=>xt(false),onSearchChange:On,onChatSelect:M=>{if(xt(false),M&&M!==Q&&(B(),Ce(M),w===void 0)){try{q.saveCurrentChatId(M);}catch{}try{let P=q.loadChat(M),j=P&&Array.isArray(P.messages)?P.messages:[];try{Y(j);}catch{}}catch{}}},onChatDelete:M=>{try{q.deleteChat(M),_n(P=>P+1),M===Q&&Ot();}catch{}},loadChatsIndex:()=>q.loadChatsIndex(),historyPopupRef:qn}),jsx(Bn,{isOpen:Xn,resolvedColors:E,onConfirm:no,onCancel:oo,editProcessContent:d}),jsx("style",{children:`
|
|
34
34
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
|
35
35
|
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
|
36
|
-
`})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(ot,{}),createPortal(
|
|
37
|
-
@keyframes ${
|
|
36
|
+
`})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(ot,{}),createPortal(Gt,document.body),jsx(jt,{show:!Ze,onClick:()=>{Wt(true);try{q.saveShowChatPreference(!0);}catch{}},resolvedColors:E,floatingButtonPosition:k})]}):Gt}var Dn={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 Sr({children:e,theme:t="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:l,mutedTextColor:u,enableBorderAnimation:i=true,borderRadius:h=16,enableContentBorder:I=true,className:f="",enableMargin:S=true,chatWidth:b=420,dir:k="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:v,dir:s,theme:d}=ae(),g=(k??s)||"ltr",C=(t??d)||"dark",y=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[w,x]=useState(false);useEffect(()=>{let R=setTimeout(()=>x(true),50);return ()=>clearTimeout(R)},[]);let c=Dn[C],p={primaryColor:n||c.primaryColor,backgroundColor:r||c.backgroundColor,borderColor:o||c.borderColor,textColor:l||c.textColor,accentColor:c.accentColor,mutedTextColor:u||c.mutedTextColor,inputBackground:c.inputBackground,cardBackground:c.cardBackground,hoverBackground:c.hoverBackground},T=typeof h=="number"?`${h}px`:h,m=typeof b=="number"?`${b}px`:b,F=S&&v?g==="rtl"?{marginLeft:m}:{marginRight:m}:{},H=S&&v?`calc(100% - ${m})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:f,style:{width:H,height:"100%",transition:w?"all 0.2s ease-out":"none",padding:v&&I?"16px":"0",...F},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:w?"all 0.2s ease-out":"none",borderRadius:v?T:"0",border:v&&a&&i?"none":v?`1px solid ${p.borderColor}`:"none",padding:v&&a&&i?"1.5px":"0",background:v&&a&&i?`linear-gradient(120deg, ${p.primaryColor}dd 0%, ${p.primaryColor}88 25%, ${p.primaryColor}00 50%, ${p.primaryColor}88 75%, ${p.primaryColor}dd 100%)`:"transparent",backgroundSize:v&&a&&i?"300% 300%":"auto",animation:v&&a&&i?`${y.current}-border-flow 3s ease-in-out infinite`:"none",filter:v&&a&&i?`drop-shadow(0 0 10px ${p.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:v&&I?T:"0",backgroundColor:v&&I?p.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${p.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`
|
|
37
|
+
@keyframes ${y.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
|
|
42
|
+
`})," "]})}var Bt=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())}},Ar=new Bt;export{Lr as Button,Sr as ContentContainer,ot as CursorController,Ue as FillActiveInput,jt as FloatingChatButton,vr as HsafaChat,co as HsafaProvider,Ar as componentRegistry,ke as controlCursor,We as getDomComponents,ke as guideCursor,Kt as useAutoScroll,Lt as useChatStorage,Zt as useFileUpload,ae as useHsafa,Rt as useHsafaAgent,Xo as useMessageEditor};//# sourceMappingURL=index.js.map
|
|
43
43
|
//# sourceMappingURL=index.js.map
|