@hsafa/ui-sdk 0.5.5 → 0.5.6
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 +119 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +119 -8
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {jsxs,jsx,Fragment}from'react/jsx-runtime';import zo,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext,Component}from'react';import {useChat}from'@ai-sdk/react';import {lastAssistantMessageIsCompleteWithToolCalls,DefaultChatTransport}from'ai';import {createRoot}from'react-dom/client';import {XMarkdown}from'@ant-design/x-markdown';import'@ant-design/x-markdown/themes/light.css';import'@ant-design/x-markdown/themes/dark.css';import {createPortal}from'react-dom';import {Plus,History,ChevronRight,Pencil,Trash2,File as File$1,Eye,X,Download}from'lucide-react';var Ce={};var kr=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:c,...u})=>{let i=[Ce.button,Ce[e],Ce[t],n&&Ce.loading,c].filter(Boolean).join(" ");return jsxs("button",{className:i,disabled:r||n,...u,children:[n&&jsx("span",{className:Ce.spinner}),jsx("span",{className:n?Ce.hiddenText:void 0,children:o})]})};function Wt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:r}){if(!e)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:c=>{c.currentTarget.style.borderColor=n.primaryColor,c.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:c=>{c.currentTarget.style.borderColor=n.borderColor,c.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function _t(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let r=t.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),t}function jt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var qt=createContext(void 0);function no({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,c]=useState(new Map),[u,i]=useState(new Map),[x,I]=useState(new Map),[y,T]=useState(new Map),[v,k]=useState(void 0),a=useCallback((d,C)=>(c(M=>{let m=new Map(M);return m.set(String(d),C),m}),()=>{c(M=>{let m=new Map(M),R=m.get(String(d));return (!C||R===C)&&m.delete(String(d)),m});}),[]),b=useCallback((d,C)=>{c(M=>{let m=new Map(M),R=m.get(String(d));return (!C||R===C)&&m.delete(String(d)),m});},[]),s=useCallback((d,C)=>(i(M=>{let m=new Map(M);return m.set(String(d),C),m}),()=>{i(M=>{let m=new Map(M),R=m.get(String(d));return (!C||R===C)&&m.delete(String(d)),m});}),[]),l=useCallback((d,C)=>{i(M=>{let m=new Map(M),R=m.get(String(d));return (!C||R===C)&&m.delete(String(d)),m});},[]),p=useCallback((d,C)=>{I(M=>{let m=new Map(M);return C?m.set(d,true):m.delete(d),m});},[]),h=useCallback((d,C)=>{T(M=>{let m=new Map(M);return m.set(d,C),m});},[]),g=useMemo(()=>Array.from(x.values()).some(d=>d),[x]),w=useMemo(()=>Array.from(y.values()).some(d=>d),[y]),f=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:u,registerAction:a,unregisterAction:b,registerComponent:s,unregisterComponent:l,isAnyStreaming:g,setStreamingState:p,isAnyChatOpen:w,setChatOpenState:h,currentChatId:v,setCurrentChatId:k}),[e,t,n,o,u,a,b,s,l,g,p,w,h,v]);return jsx(qt.Provider,{value:f,children:r})}function ne(){let e=useContext(qt);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{}}}var Ct=25*1024*1024;function Vt(e){let{baseUrl:t}=ne(),n=e||t||"",[r,o]=useState([]),[c,u]=useState(false),i=useRef(null),x=useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let b=["B","KB","MB","GB","TB"],s=Math.min(b.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${b[s]}`},[]),I=useCallback(async a=>{let b=new FormData;b.append("file",a);let s=await fetch(jt(n,"/api/uploads"),{method:"POST",body:b});if(!s.ok){let p=await s.text().catch(()=>"");throw new Error(p||`Failed to upload ${a.name}`)}let l=await s.json();return {id:l.id,name:l.name||a.name,url:l.url,mimeType:l.mimeType||a.type||"application/octet-stream",size:typeof l.size=="number"?l.size:a.size}},[n]),y=useCallback(a=>{o(b=>b.filter(s=>s.id!==a));},[]),T=useCallback(async(a,b)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);b(null),u(true);let l=[];try{for(let p of s){if(p.size>Ct){b(`"${p.name}" exceeds the ${x(Ct)} limit.`);continue}try{let h=await I(p);l.push(h);}catch(h){console.error("Failed to upload attachment:",h),b(String(h?.message??`Failed to upload ${p.name}`));}}l.length&&o(p=>[...p,...l]);}finally{u(false);}},[I,x]),v=useCallback((a,b)=>{let s=[],l=(a||"").trim();l&&s.push({type:"text",text:l});for(let p of b||[]){let h=p.mimeType||"application/octet-stream";h.startsWith("image/")?s.push({type:"image",image:new URL(p.url),mediaType:h}):s.push({type:"file",data:p.url,mediaType:h,name:p.name});}return s},[]),k=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:c,fileInputRef:i,formatBytes:x,handleRemoveAttachment:y,handleFileSelection:T,buildUserContent:v,clearAttachments:k,setAttachments:o,MAX_UPLOAD_SIZE:Ct}}function Xt(e,t,n,r){return console.log("\u{1F680} [SDK] createHsafaTransport called with templateParams:",r),new DefaultChatTransport({api:`${e}/api/run/${t}`,fetch:async(o,c)=>{let u=c||{},i=u?.body?JSON.parse(u.body):{},x=r&&typeof r=="object"?r:{};console.log("\u{1F680} [SDK] Before merge - body:",i),console.log("\u{1F680} [SDK] Before merge - mergedParams:",x);let I={...x,...i,chatId:n};return console.log("\u{1F680} [SDK] After merge - enhancedBody:",I),fetch(o,{...c,body:JSON.stringify(I)})}})}function so(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 io(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),r=n.querySelector("input, select, textarea");return r&&r.remove(),n.textContent?.trim()}}function vt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function kt(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function lo(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let c=n.className.split(" ").filter(u=>u.trim()).slice(0,2);c.length>0&&(r+="."+c.join("."));}let o=n.parentElement;if(o){let c=Array.from(o.children).filter(u=>u.tagName===n.tagName);if(c.length>1){let u=c.indexOf(n)+1;r+=`:nth-child(${u})`;}}t.unshift(r),n=o;}return t.slice(-3).join(" > ")}async function Ne(e={}){try{let{includeHidden:t=!1,selector:n,what:r="content",limit:o}=e,c=document.querySelector(".hsafa-content-container");if(!c)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let u=n&&c.querySelector(n)||c,i=[],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 l=so(s);if(!l&&!t)return;let p={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:l,isInteractive:!0,selector:lo(s)};s instanceof HTMLInputElement?(p.type=s.type,p.name=s.name||void 0,p.placeholder=s.placeholder||void 0,p.value=kt(s),p.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,p.disabled=s.disabled,p.required=s.required):s instanceof HTMLTextAreaElement?(p.name=s.name||void 0,p.placeholder=s.placeholder||void 0,p.value=kt(s),p.disabled=s.disabled,p.required=s.required):s instanceof HTMLSelectElement?(p.name=s.name||void 0,p.value=kt(s),p.disabled=s.disabled,p.required=s.required,p.options=Array.from(s.options).map(h=>({value:h.value,label:h.text,selected:h.selected,disabled:h.disabled}))):s instanceof HTMLButtonElement?(p.type=s.type,p.disabled=s.disabled,p.text=vt(s)):s instanceof HTMLAnchorElement?(p.href=s.href,p.text=vt(s)):s instanceof HTMLImageElement?(p.text=s.alt||void 0,p.label=s.alt||p.label):p.text=vt(s),p.label=io(s),p.role=s.getAttribute("role")||void 0,p.ariaLabel=s.getAttribute("aria-label")||void 0,i.push(p);});let y=s=>s.isVisible?r==="inputs"?s.tag==="input"||s.tag==="textarea"||s.tag==="select"||s.role==="textbox"?3:s.tag==="button"||s.tag==="a"?2:1:["header","nav","main","footer"].includes(s.tag)?5:["section","article","aside"].includes(s.tag)||["h1","h2","h3"].includes(s.tag)?4:["h4","h5","h6"].includes(s.tag)?3:s.tag==="form"?4:s.tag==="label"?3:s.tag==="input"||s.tag==="textarea"||s.tag==="select"?4:s.tag==="p"||s.tag==="img"||s.tag==="button"||s.tag==="a"?3:1:0;i.sort((s,l)=>y(l)-y(s));let T=i.length,k=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=T>k,b=a?i.slice(0,k):i;return {ok:!0,components:b,count:b.length,total:T,truncated:a,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=Ne);async function ve(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(r){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:r?.message||String(r)}]}}}typeof window<"u"&&(window.guideCursor=ve);function Yt(e){return !!e&&e.nodeType===1}function oe(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Jt(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,oe(e,"input");}function co(e,t){e.checked!==t&&e.click();}function uo(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(r=>r.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);oe(e,"input"),oe(e,"change");}function po(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(r=>{r.selected=n.has(r.value)||n.has(r.text);}),oe(e,"input"),oe(e,"change");}function mo(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function go(e,t){let n=Array.isArray(t)?t:[t],r=new DataTransfer;for(let o of n)r.items.add(o);Object.defineProperty(e,"files",{value:r.files,configurable:true}),oe(e,"input"),oe(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&Yt(n)){let r=n.closest('[contenteditable="true"], [contenteditable=""]');r&&(n=r);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let r=n.tagName.toLowerCase();if(r==="input"){let o=n,c=(o.type||"text").toLowerCase();if(c==="checkbox")co(o,!!e);else if(c==="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(c==="file")if(e instanceof File||Array.isArray(e)&&e.every(u=>u instanceof File))go(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=c==="date"?mo(e):String(e??"");Jt(o,u),oe(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,c=String(e??"");return Jt(o,c),oe(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?po(o,Array.isArray(e)?e:[e]):uo(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(Yt(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(e??""),oe(o,"input"),oe(o,"change"),o.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${r}`}],errors:[`Unsupported active element: ${r}`]}}catch(r){return {ok:false,filled:[{key:"active",status:"error",message:r?.message??String(r)}],errors:[r?.message??String(r)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var ze=null,Je={},Qt=false,Ae=null,Qe=false;function wt(e){e.classList.add("visible");}function an(){Qe=true,Ae!=null&&(clearTimeout(Ae),Ae=null);}function yo(e,t=1500){Qe||(Ae!=null&&clearTimeout(Ae),Ae=window.setTimeout(()=>{Qe||e.classList.remove("visible");},t));}function ho(e,t=1200){Qe=false,yo(e,t);}function xo(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 bo(e,t=1500,n=160){let r=performance.now(),o=e?xo(e):[],c=()=>{let y=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(T=>{y.push(T.scrollLeft,T.scrollTop);}),y},u=()=>{if(!e)return {x:0,y:0};let y=e.getBoundingClientRect();return {x:y.left,y:y.top}},i=c(),x=u(),I=performance.now();return new Promise(y=>{function T(v){let k=c(),a=u(),b=false;for(let s=0;s<k.length;s++)if(k[s]!==i[s]){b=true;break}if(!b&&e&&(a.x!==x.x||a.y!==x.y)&&(b=true),b&&(i=k,x=a,I=v),v-I>=n||v-r>=t){y();return}requestAnimationFrame(T);}requestAnimationFrame(T);})}var Co='<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>',vo='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function ko(){if(!Je.arrow)try{Je.arrow=Co,Je.pointer=vo;}catch(e){console.warn("Failed to set cursor SVGs",e);}return Je}function en({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function wo(){let e="demo-fake-cursor",t=document.getElementById(e),n=await ko();if(!Qt){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
|
|
1
|
+
import {jsxs,jsx,Fragment}from'react/jsx-runtime';import so,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext,Component}from'react';import {useChat}from'@ai-sdk/react';import {lastAssistantMessageIsCompleteWithToolCalls,DefaultChatTransport}from'ai';import {createRoot}from'react-dom/client';import {XMarkdown}from'@ant-design/x-markdown';import'@ant-design/x-markdown/themes/light.css';import'@ant-design/x-markdown/themes/dark.css';import {createPortal}from'react-dom';import {Plus,Pencil,History,ChevronRight,Trash2,File as File$1,Eye,X,Download}from'lucide-react';var Se={};var zr=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:l,...u})=>{let c=[Se.button,Se[e],Se[t],n&&Se.loading,l].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:r||n,...u,children:[n&&jsx("span",{className:Se.spinner}),jsx("span",{className:n?Se.hiddenText:void 0,children:o})]})};function kn({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 In(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 Sn(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var Mn=createContext(void 0);function xo({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,l]=useState(new Map),[u,c]=useState(new Map),[x,I]=useState(new Map),[d,S]=useState(new Map),[C,b]=useState(void 0),a=useCallback((m,v)=>(l(M=>{let f=new Map(M);return f.set(String(m),v),f}),()=>{l(M=>{let f=new Map(M),F=f.get(String(m));return (!v||F===v)&&f.delete(String(m)),f});}),[]),w=useCallback((m,v)=>{l(M=>{let f=new Map(M),F=f.get(String(m));return (!v||F===v)&&f.delete(String(m)),f});},[]),i=useCallback((m,v)=>(c(M=>{let f=new Map(M);return f.set(String(m),v),f}),()=>{c(M=>{let f=new Map(M),F=f.get(String(m));return (!v||F===v)&&f.delete(String(m)),f});}),[]),T=useCallback((m,v)=>{c(M=>{let f=new Map(M),F=f.get(String(m));return (!v||F===v)&&f.delete(String(m)),f});},[]),s=useCallback((m,v)=>{I(M=>{let f=new Map(M);return v?f.set(m,true):f.delete(m),f});},[]),g=useCallback((m,v)=>{S(M=>{let f=new Map(M);return f.set(m,v),f});},[]),h=useMemo(()=>Array.from(x.values()).some(m=>m),[x]),k=useMemo(()=>Array.from(d.values()).some(m=>m),[d]),y=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:u,registerAction:a,unregisterAction:w,registerComponent:i,unregisterComponent:T,isAnyStreaming:h,setStreamingState:s,isAnyChatOpen:k,setChatOpenState:g,currentChatId:C,setCurrentChatId:b}),[e,t,n,o,u,a,w,i,T,h,s,k,g,C]);return jsx(Mn.Provider,{value:y,children:r})}function le(){let e=useContext(Mn);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 Ht=25*1024*1024;function Rn(e){let{baseUrl:t}=le(),n=e||t||"",[r,o]=useState([]),[l,u]=useState(false),c=useRef(null),x=useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let w=["B","KB","MB","GB","TB"],i=Math.min(w.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,i)).toFixed(i===0?0:1)} ${w[i]}`},[]),I=useCallback(async a=>{let w=new FormData;w.append("file",a);let i=await fetch(Sn(n,"/api/uploads"),{method:"POST",body:w});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(s||`Failed to upload ${a.name}`)}let T=await i.json();return {id:T.id,name:T.name||a.name,url:T.url,mimeType:T.mimeType||a.type||"application/octet-stream",size:typeof T.size=="number"?T.size:a.size}},[n]),d=useCallback(a=>{o(w=>w.filter(i=>i.id!==a));},[]),S=useCallback(async(a,w)=>{if(!a)return;let i=Array.isArray(a)?a:Array.from(a);w(null),u(true);let T=[];try{for(let s of i){if(s.size>Ht){w(`"${s.name}" exceeds the ${x(Ht)} limit.`);continue}try{let g=await I(s);T.push(g);}catch(g){console.error("Failed to upload attachment:",g),w(String(g?.message??`Failed to upload ${s.name}`));}}T.length&&o(s=>[...s,...T]);}finally{u(false);}},[I,x]),C=useCallback((a,w)=>{let i=[],T=(a||"").trim();T&&i.push({type:"text",text:T});for(let s of w||[]){let g=s.mimeType||"application/octet-stream";g.startsWith("image/")?i.push({type:"image",image:new URL(s.url),mediaType:g}):i.push({type:"file",data:s.url,mediaType:g,name:s.name});}return i},[]),b=useCallback(()=>{o([]);},[]);return {attachments:r,uploading:l,fileInputRef:c,formatBytes:x,handleRemoveAttachment:d,handleFileSelection:S,buildUserContent:C,clearAttachments:b,setAttachments:o,MAX_UPLOAD_SIZE:Ht}}function An(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||{},c=u?.body?JSON.parse(u.body):{},x=r&&typeof r=="object"?r:{};console.log("\u{1F680} [SDK] Before merge - body:",c),console.log("\u{1F680} [SDK] Before merge - mergedParams:",x);let I={...x,...c,chatId:n};return console.log("\u{1F680} [SDK] After merge - enhancedBody:",I),fetch(o,{...l,body:JSON.stringify(I)})}})}function ko(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 wo(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 Ft(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function Bt(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 To(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 _e(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,c=[],x=[];r==="inputs"?x=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:x=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],u.querySelectorAll(x.join(", ")).forEach(i=>{let T=ko(i);if(!T&&!t)return;let s={id:i.id||null,tag:i.tagName.toLowerCase(),className:i.className&&typeof i.className=="string"?i.className:void 0,isVisible:T,isInteractive:!0,selector:To(i)};i instanceof HTMLInputElement?(s.type=i.type,s.name=i.name||void 0,s.placeholder=i.placeholder||void 0,s.value=Bt(i),s.checked=i.type==="checkbox"||i.type==="radio"?i.checked:void 0,s.disabled=i.disabled,s.required=i.required):i instanceof HTMLTextAreaElement?(s.name=i.name||void 0,s.placeholder=i.placeholder||void 0,s.value=Bt(i),s.disabled=i.disabled,s.required=i.required):i instanceof HTMLSelectElement?(s.name=i.name||void 0,s.value=Bt(i),s.disabled=i.disabled,s.required=i.required,s.options=Array.from(i.options).map(g=>({value:g.value,label:g.text,selected:g.selected,disabled:g.disabled}))):i instanceof HTMLButtonElement?(s.type=i.type,s.disabled=i.disabled,s.text=Ft(i)):i instanceof HTMLAnchorElement?(s.href=i.href,s.text=Ft(i)):i instanceof HTMLImageElement?(s.text=i.alt||void 0,s.label=i.alt||s.label):s.text=Ft(i),s.label=wo(i),s.role=i.getAttribute("role")||void 0,s.ariaLabel=i.getAttribute("aria-label")||void 0,c.push(s);});let d=i=>i.isVisible?r==="inputs"?i.tag==="input"||i.tag==="textarea"||i.tag==="select"||i.role==="textbox"?3:i.tag==="button"||i.tag==="a"?2:1:["header","nav","main","footer"].includes(i.tag)?5:["section","article","aside"].includes(i.tag)||["h1","h2","h3"].includes(i.tag)?4:["h4","h5","h6"].includes(i.tag)?3:i.tag==="form"?4:i.tag==="label"?3:i.tag==="input"||i.tag==="textarea"||i.tag==="select"?4:i.tag==="p"||i.tag==="img"||i.tag==="button"||i.tag==="a"?3:1:0;c.sort((i,T)=>d(T)-d(i));let S=c.length,b=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=S>b,w=a?c.slice(0,b):c;return {ok:!0,components:w,count:w.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=_e);async function Me(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=Me);function Ln(e){return !!e&&e.nodeType===1}function ce(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Hn(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ce(e,"input");}function Io(e,t){e.checked!==t&&e.click();}function So(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);ce(e,"input"),ce(e,"change");}function Mo(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(r=>{r.selected=n.has(r.value)||n.has(r.text);}),ce(e,"input"),ce(e,"change");}function Eo(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function Ro(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}),ce(e,"input"),ce(e,"change");}async function qe(e,t={}){let n=document.activeElement||null;if(n&&Ln(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")Io(o,!!e);else if(l==="radio"){let u=o.name;if(u&&e!=null&&String(o.value)!==String(e)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(u)}"][value="${CSS.escape(String(e))}"]`);c?c.click():o.click();}else o.click();}else if(l==="file")if(e instanceof File||Array.isArray(e)&&e.every(u=>u instanceof File))Ro(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"?Eo(e):String(e??"");Hn(o,u),ce(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,l=String(e??"");return Hn(o,l),ce(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?Mo(o,Array.isArray(e)?e:[e]):So(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(Ln(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(e??""),ce(o,"input"),ce(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=qe);var Ke=null,st={},Bn=false,De=null,lt=false;function Dt(e){e.classList.add("visible");}function Wn(){lt=true,De!=null&&(clearTimeout(De),De=null);}function Lo(e,t=1500){lt||(De!=null&&clearTimeout(De),De=window.setTimeout(()=>{lt||e.classList.remove("visible");},t));}function Ho(e,t=1200){lt=false,Lo(e,t);}function Fo(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 Bo(e,t=1500,n=160){let r=performance.now(),o=e?Fo(e):[],l=()=>{let d=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(S=>{d.push(S.scrollLeft,S.scrollTop);}),d},u=()=>{if(!e)return {x:0,y:0};let d=e.getBoundingClientRect();return {x:d.left,y:d.top}},c=l(),x=u(),I=performance.now();return new Promise(d=>{function S(C){let b=l(),a=u(),w=false;for(let i=0;i<b.length;i++)if(b[i]!==c[i]){w=true;break}if(!w&&e&&(a.x!==x.x||a.y!==x.y)&&(w=true),w&&(c=b,x=a,I=C),C-I>=n||C-r>=t){d();return}requestAnimationFrame(S);}requestAnimationFrame(S);})}var Do='<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>',Po='<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 $o(){if(!st.arrow)try{st.arrow=Do,st.pointer=Po;}catch(e){console.warn("Failed to set cursor SVGs",e);}return st}function Dn({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 zo(){let e="demo-fake-cursor",t=document.getElementById(e),n=await $o();if(!Bn){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
|
|
2
2
|
.fake-cursor { pointer-events: none; opacity: 0; transition: opacity 0.2s ease; z-index: 2147483647; }
|
|
3
3
|
.fake-cursor.visible { opacity: 1; }
|
|
4
4
|
.fake-cursor .arrow { display: none; }
|
|
@@ -8,12 +8,12 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import zo,{createContext,useRe
|
|
|
8
8
|
.fake-cursor.as-pointer .arrow { display: none; }
|
|
9
9
|
.fake-cursor.as-pointer .pointer { display: block; }
|
|
10
10
|
.fake-cursor.pressing .pointer svg path { filter: brightness(0.9); }
|
|
11
|
-
`,document.head.appendChild(o);}Qt=true;}return t?(t.classList.add("as-arrow"),ze||(ze=createRoot(t),ze.render(jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),ze=createRoot(t),ze.render(jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Re(e,t,n){return Math.max(t,Math.min(n,e))}function To(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function sn(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let r=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!r)return null;let o=r[1].split(/\s*,\s*/).map(Number),[c,u,i,x=1]=o;return {r:c,g:u,b:i,a:x}}function Io({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 So(e){let t=e?sn(e):null;return !t||t.a===0?false:Io(t)<.5}function Mo(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=sn(u);if(i&&i.a>0)return u;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Tt(e,t,n){let r=Mo(t,n),o=So(r),c=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(i=>{i.style.fill="white",i.style.stroke=c,i.style.strokeWidth="1";}),e.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function Ze(e,t,n,r,o="ease-in-out",c="curve",u=.25,i="auto",x){an(),wt(e);let I=performance.now(),y=o==="linear"?k=>k:To,T=c!=="straight",v={x:0,y:0};if(T){let k=n.x-t.x,a=n.y-t.y,b=Math.hypot(k,a)||1,s=(t.x+n.x)/2,l=(t.y+n.y)/2,p=-a/b,h=k/b,g=1;i==="left"?g=-1:i==="right"?g=1:g=Math.random()<.5?-1:1;let w=Re(u,0,1)*b;v={x:s+g*p*w,y:l+g*h*w};}return new Promise(k=>{function a(b){let s=Re((b-I)/r,0,1),l=y(s),p,h;if(T){let C=1-l;p=C*C*t.x+2*C*l*v.x+l*l*n.x,h=C*C*t.y+2*C*l*v.y+l*l*n.y;}else p=t.x+(n.x-t.x)*l,h=t.y+(n.y-t.y)*l;let w=.35*(1-l),f=Math.sin(b*.02)*w,d=Math.cos(b*.018)*w;e.style.left=`${p+f}px`,e.style.top=`${h+d}px`,Tt(e,p+f,h+d),x&&x({x:p+f,y:h+d,t:s,now:b}),s<1?requestAnimationFrame(a):k();}requestAnimationFrame(a);})}function tn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function le(e,t,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let c=t==="pointerdown"||t==="mousedown",u=t==="pointerup"||t==="mouseup",i={button:0,buttons:c?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let x=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...i});e.dispatchEvent(x);}else {let x=new MouseEvent(t,i);e.dispatchEvent(x);}}catch{let c=new MouseEvent(t,o);e.dispatchEvent(c);}}function ln(e){return e&&typeof e=="object"&&e.nodeType===1}function Eo(e){if(!e)return document;if(ln(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function nn(e){if(ln(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Eo(e.within??null).querySelectorAll(e.selector),r=Math.max(0,Math.min(n.length-1,e.nth??0)),o=n[r]??null;return {kind:o?"element":"position",element:o}}return {kind:"position",point:{x:0,y:0}}}function on(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let r=Re(t.x,0,1),o=Re(t.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function rn(e){return {x:Re(e.x,0,window.innerWidth),y:Re(e.y,0,window.innerHeight)}}function Ao(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await wo();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),wt(o),an();let c=parseFloat(o.style.left||"20")||20,u=parseFloat(o.style.top||"20")||20;Tt(o,c,u);for(let i of n){let{durationMs:x=800,easing:I="ease-in-out",offset:y,highlight:T=true,path:v="curve",curveStrength:k=.25,curveDirection:a="auto",anchor:b,cursorHotspot:s,dragTo:l}=i.options??{},p=i.action??i.options?.action??"none",h=performance.now(),g=nn(i.target),w=null,f=null;if(g.kind==="element"&&g.element?(f=g.element,o.classList.remove("visible"),f.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await bo(f,1500,180),wt(o),w=on(f,b)):g.kind==="position"&&g.point&&(w=g.point),!w){r.push({ok:false,action:p,targetKind:g.kind,durationMs:Math.round(performance.now()-h),error:"Target not found"});continue}let d={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},C=rn(tn(w,y));await Ze(o,d,C,x,I,v,k,a);let M=C.x-d.x,m=C.y-d.y,R=Math.hypot(M,m)||1,N=M/R,U=m/R,te=Math.min(6,Math.max(3,R*.02)),ye={x:C.x+N*te,y:C.y+U*te};await Ze(o,C,ye,Math.max(70,x*.1),"ease-out","straight",0,"right"),await Ze(o,ye,C,120,"ease-out","straight",0,"left"),T&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let ue=null;try{if(p==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let A={x:s?.x??0,y:s?.y??0},B={x:C.x+A.x,y:C.y+A.y};o.style.left=`${B.x}px`,o.style.top=`${B.y}px`,Tt(o,B.x,B.y);let _=f??document.elementFromPoint(B.x,B.y)??document.body;le(_,"pointerdown",B),le(_,"mousedown",B),await new Promise(V=>setTimeout(V,90)),o.classList.remove("pressing"),le(_,"mouseup",B),le(_,"click",B),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),_ instanceof HTMLElement&&_.focus?.(),ue=_?.id??null;}else if(p==="drag"){if(!l)throw new Error("dragTo is required for action 'drag'");let A=nn(l),B=null;if(A.kind==="element"&&A.element&&(B=on(A.element,b)),A.kind==="position"&&A.point&&(B=A.point),!B)throw new Error("dragTo target not found");let _=rn(tn(B,y)),V={x:C.x,y:C.y},ie=f??document.elementFromPoint(V.x,V.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),le(ie,"pointerdown",V),le(ie,"mousedown",V),await Ze(o,V,_,Math.max(200,x),I,v,k,a,({x:$,y:he})=>{let ce=document.elementFromPoint($,he)??document.body,xe={x:$,y:he};le(ce,"pointermove",xe),le(ce,"mousemove",xe);});let O=document.elementFromPoint(_.x,_.y)??document.body;o.classList.remove("pressing"),le(O,"pointerup",_),le(O,"mouseup",_);}r.push({ok:!0,action:p,targetKind:g.kind,durationMs:Math.round(performance.now()-h),clickedElementId:ue});}catch(A){r.push({ok:false,action:p,targetKind:g.kind,durationMs:Math.round(performance.now()-h),error:A?.message??String(A)});}}return ho(o,2e3),{ok:r.every(i=>i.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var tt=Ao;function cn(){return {getDomComponents:{tool:async({includeHidden:e,selector:t})=>await Ne({includeHidden:e,selector:t}),executeEachToken:false},controlCursor:{tool:async({target:e,action:t,anchor:n,durationMs:r,dragTo:o})=>{let c=await ve(e,{action:t,anchor:n,durationMs:r,dragTo:o});if(c&&c.ok){let u=Array.isArray(c.steps)&&c.steps.length?c.steps[c.steps.length-1]:void 0,i=u?.clickedElementId?` (clicked element id: ${u.clickedElementId})`:"",x=t||u?.action||"none";return {success:true,message:x==="click"?`Cursor moved and clicked successfully${i}`:x==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:c}}return {success:false,message:"Cursor action failed",details:c}},executeEachToken:false},fillActiveInput:{tool:async({value:e})=>{let t=await Ue(e);return {success:!!t?.ok,message:t?.ok?"Active input filled successfully":t?.errors?.[0]||"Failed to fill active input",details:t}},executeEachToken:true},requestInput:{tool:async e=>({ok:true}),executeEachToken:true}}}function We({content:e,theme:t="dark",streaming:n=false}){return jsx(XMarkdown,{content:e,className:t==="dark"?"x-markdown-dark":"x-markdown-light",streaming:{hasNextChunk:n,enableAnimation:true,animationConfig:{fadeDuration:200},incompleteMarkdownComponentMap:{html:"IncompleteBlock",link:"IncompleteBlock",image:"IncompleteBlock"}},openLinksInNewTab:true,config:{gfm:true},dompurifyConfig:{ADD_TAGS:["data-chart","welcome","user-card","mermaid"],ADD_ATTR:["data-source","data-spec","data-icon","data-description","data-raw"]},style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"}})}function Bo({input:e}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(We,{content:e?.text||"",theme:"dark"})})}function un(){return {plainText:Bo}}function pn(e,t,n,r,o,c){let u=n.get(t);if(u){let g=u.parentElement,w=document.querySelector(`[data-get-from-user-host="${t}"]`);if(w&&g!==w){try{g?.removeChild(u);}catch{}w.innerHTML="",w.appendChild(u);}}else {u=document.createElement("div"),u.className="hsafa-inline-form";let g=document.querySelector(`[data-get-from-user-host="${t}"]`);g?(g.innerHTML="",g.appendChild(u)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(u),n.set(t,u);}let i=e?.title||"Provide input",x=e?.description||"",I=e?.submitLabel||"Submit",y=e?.skipLabel||"Skip",T=Array.isArray(e?.fields)?e.fields:e?.label||e?.placeholder?[{id:"value",label:e?.label||"Value",type:"text",placeholder:e?.placeholder||""}]:[],v=r.get(t)||{submitted:false,skipped:false,values:void 0};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),x){let g=document.createElement("div");g.style.fontSize="12px",g.style.opacity="0.8",g.style.marginBottom="10px",g.textContent=x,k.appendChild(g);}T.forEach(g=>{let w=document.createElement("div");if(w.style.margin="10px 0",g.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=g.label,w.appendChild(m);}let f,d=(g.type||"text").toLowerCase();if(d==="textarea"){let m=document.createElement("textarea");m.placeholder=g.placeholder||"",m.value=g.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",f=m;}else if(d==="select"&&Array.isArray(g.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",g.options.forEach(R=>{let N=document.createElement("option");N.value=String(R.value),N.text=String(R.label??R.value),m.appendChild(N);}),m.value=g.value??"",f=m;}else if(d==="checkbox"){let m=document.createElement("input");m.type="checkbox",m.checked=!!g.value,m.style.transform="scale(1.1)",f=m;}else {let m=document.createElement("input");m.type=d,m.placeholder=g.placeholder||"",m.value=g.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",f=m;}let C=g.id||"value";f.dataset.fieldId=C;let M=v.values&&Object.prototype.hasOwnProperty.call(v.values,C)?v.values[C]:void 0;typeof M<"u"&&(f.type==="checkbox"?f.checked=!!M:f.value=String(M)),(v.submitted||v.skipped)&&(f.setAttribute("disabled","true"),f.style.opacity="0.7"),w.appendChild(f),k.appendChild(w);});let b=String(I).trim(),s=String(y).trim(),l=!!(b||s),p=null,h=null;if(l){let g=document.createElement("div");g.style.display="flex",g.style.gap="8px",g.style.marginTop="10px",p=document.createElement("button"),p.type="submit",p.textContent=b||"Submit",p.style.padding="6px 10px",p.style.borderRadius="8px",p.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",p.style.color="#000000",h=document.createElement("button"),h.type="button",h.textContent=s||"Skip",h.style.padding="6px 10px",h.style.borderRadius="8px",h.style.background="transparent",h.style.border="1px solid var(--hsafa-border, #2A2C33)",h.style.color="inherit",g.appendChild(p),g.appendChild(h),k.appendChild(g);}if(k.onsubmit=g=>{g.preventDefault();let w={};k.querySelectorAll("[data-field-id]").forEach(f=>{let d=f.dataset.fieldId||"value";f.type==="checkbox"?w[d]=f.checked:w[d]=f.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(f=>{f.disabled=true,f.style.opacity="0.7";}),p&&(p.textContent=`${b||"Submit"} \u2713`,p.style.opacity="0.8",p.disabled=true),h&&(h.disabled=true);},h&&(h.onclick=()=>{r.set(t,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:false,skipped:true}}),k.querySelectorAll("[data-field-id]").forEach(g=>{g.disabled=true,g.style.opacity="0.7";}),h&&(h.textContent=`${s||"Skip"} \u2713`,h.style.opacity="0.8",h.disabled=true),p&&(p.disabled=true);}),v.submitted||v.skipped){let g=document.createElement("div");g.style.marginTop="10px",g.style.fontSize="12px",g.style.display="flex",g.style.alignItems="center",g.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",v.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"),g.appendChild(w),k.appendChild(g);try{p&&(p.disabled=!0,p.style.opacity="0.8",v.submitted&&(p.textContent=`${b||"Submit"} \u2713`)),h&&(h.disabled=!0,h.style.opacity="0.8",v.skipped&&(h.textContent=`${s||"Skip"} \u2713`));}catch{}}u.appendChild(k);}function mn(e,t,n){let r=useRef(new Map),o=useRef(new Map),c=useRef(t),u=useRef(n);c.current=t,u.current=n,useEffect(()=>{e.forEach(i=>{i.role==="assistant"&&i.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 y=c.current[I];if(y&&typeof y=="object"&&y.executeEachToken&&y.tool){let T=x.input||x.args||{},v=JSON.stringify(T),k=r.current.get(x.toolCallId);if(v!==k&&v!=="{}"){r.current.set(x.toolCallId,v);try{if(I==="requestInput")u.current(T,x.toolCallId);else {let b=(o.current.get(x.toolCallId)||0)+1;o.current.set(x.toolCallId,b),b>1&&y.tool({...T,toolCallNumber:b-1});}}catch{}}}});});},[e]);}function St(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:c,onFinish:u,onError:i,initialMessages:x=[],onMessagesChange:I,controlledChatId:y,onChatIdChange:T,templateParams:v}=e,{baseUrl:k,setCurrentChatId:a}=ne(),b=n&&n.length>0?n:k||"",[s,l]=useState(""),[p,h]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),g=y??p,w=useCallback(E=>{y===void 0&&h(E),T&&T(E);},[y,T]);useEffect(()=>{try{a(g);}catch{}return ()=>{try{a(void 0);}catch{}}},[g,a]);let f=useMemo(()=>Xt(b,t,g,v),[b,t,g,v]),d=useCallback(E=>{console.log("Message finished:",E);let F=E?.message?.id;if(!F&&Array.isArray(E?.messages))for(let z=E.messages.length-1;z>=0;z--){let H=E.messages[z];if(H&&H.role==="assistant"&&H.id){F=H.id;break}}u?.({...E,chatId:g,assistantMessageId:F});},[u,g]),C=useCallback(E=>{console.error("Chat error:",E),i?.(E);},[i]),M=useMemo(()=>cn(),[]),m=useMemo(()=>({...M,...r}),[M,r]),R=useMemo(()=>un(),[]),N=useMemo(()=>({...R,...o}),[R,o]),U=useRef(new Map),te=useRef(new Map),ye=useCallback(()=>{try{U.current.forEach(E=>{try{E.remove();}catch{}}),U.current.clear(),te.current.clear();}catch{}},[]),ue=useCallback((E,F)=>{pn(E,F,U.current,te.current,z=>A.current.addToolResult(z));},[]),A=useRef(null),B=useRef(new Set),_=useCallback((E,F,z)=>{console.error(`UI Error [${F}]:`,z),A.current&&B.current.has(E)&&(B.current.delete(E),A.current.addToolResult({tool:F,toolCallId:E,state:"output-error",errorText:z?.message||String(z)}));},[]),V=useCallback((E,F)=>{A.current&&B.current.has(E)&&(B.current.delete(E),A.current.addToolResult({tool:F,toolCallId:E,output:{status:"ok",rendered:true,component:F,logs:[]}}));},[]),ie=useCallback(E=>{let F=m[E];return F?typeof F=="object"&&"tool"in F?F.tool:typeof F=="function"?F:null:null},[m]),O=useChat({transport:f,onFinish:d,onError:C,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:E}){let F=ie(E.toolName);if(E.toolName==="requestInput"){try{ue(E.input,E.toolCallId);}catch(Z){console.error("requestInput render error",Z);}return}let z=E.toolName==="ui";E?.input;let J=N&&E.toolName in N;if(z||J){B.current.add(E.toolCallId);return}if(F)try{let Z=await F(E.input);O.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,output:Z});}catch(Z){O.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,state:"output-error",errorText:Z?.message||String(Z)});}}}),{messages:$,sendMessage:he,status:ce,stop:xe,error:mt}=O;A.current=O,mn($,m,ue),useEffect(()=>{try{let E=new Set,F=[];if($.forEach(z=>{z.role==="assistant"&&(z.parts||[]).forEach(H=>{if((H?.toolName||(typeof H?.type=="string"&&H.type.startsWith("tool-")?String(H.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let Z=H?.toolCallId||"";if(!Z)return;E.add(Z);let de=H?.output;if(de&&(de.submitted||de.skipped||de.values)){let be={submitted:!!de.submitted,skipped:!!de.skipped,values:de.values||void 0};te.current.set(Z,be);}let X=H?.input||H?.args||{};F.push({input:X,toolCallId:Z});});}),U.current.forEach((z,H)=>{if(!E.has(H)){let J=U.current.get(H);try{J?.remove();}catch{}U.current.delete(H),te.current.delete(H);}}),F.length>0){let z=requestAnimationFrame(()=>{F.forEach(({input:H,toolCallId:J})=>{try{ue(H,J);}catch{}});});return ()=>cancelAnimationFrame(z)}}catch{}},[$,ue]),useEffect(()=>{x&&x.length>0&&$.length===0&&console.log("Initial messages:",x);},[x,$.length]);let q=ce==="submitted"||ce==="streaming",qe=useCallback(()=>{I&&I($,g);},[I,$,g]),Fe=useCallback(async E=>{let F=E?.text!==void 0?E.text:s,z=E?.files||[],H=F.trim();if(!(!H&&z.length===0)&&!q){E?.text===void 0&&l("");try{if(c){let J={role:"user",content:H,createdAt:Date.now(),chatId:g};c(J);}await he({text:H,files:z});}catch(J){throw console.error("Failed to send message:",J),J}}},[s,q,he,c,g]),Ie=useCallback(()=>{if(q)return;ye(),l("");try{O?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;w(E);},[q,O,ye,w]),Ht=useCallback(E=>{try{O?.setMessages?.(E);}catch{}},[O]);return {input:s,setInput:l,messages:$,isLoading:q,status:ce,error:mt,sendMessage:Fe,stop:xe,newChat:Ie,setMessages:Ht,notifyMessagesChange:qe,chatApi:O,chatId:g,setChatId:w,tools:m,uiComponents:N,formHostRef:U,formStateRef:te,cleanupForms:ye,onUISuccess:V,onUIError:_}}function rt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=h=>`${t}.chat.${h}`,o=`${t}.currentChatId`,c=`${t}.showChat`,u=()=>{try{let h=localStorage.getItem(n);return h?JSON.parse(h):[]}catch{return []}},i=h=>{try{localStorage.setItem(n,JSON.stringify(h));}catch{}},x=h=>{try{let g=localStorage.getItem(r(h));return g?JSON.parse(g):null}catch{return null}},I=h=>{try{localStorage.setItem(r(h.id),JSON.stringify(h));}catch{}},y=h=>{let g=u(),w=g.findIndex(f=>f.id===h.id);w>=0?g[w]=h:g.unshift(h),i(g);},T=h=>{let w=u().filter(f=>f.id!==h);i(w);},v=h=>{try{localStorage.removeItem(r(h));}catch{}};return {loadChatsIndex:u,saveChatsIndex:i,loadChat:x,saveChat:I,upsertChatMeta:y,deleteChatMeta:T,deleteChatData:v,deleteChat:h=>{v(h),T(h);},loadShowChatPreference:h=>{try{let g=localStorage.getItem(c);return g!==null?g==="true":h}catch{return h}},saveShowChatPreference:h=>{try{localStorage.setItem(c,String(h));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:h=>{try{localStorage.setItem(o,h);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Et(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:c=true,autoRestore:u=true}=e,i=useMemo(()=>rt(t),[t]),[x,I]=useState([]),[y,T]=useState(null),v=useRef(false),k=useRef(false),a=useCallback(()=>{try{let f=i.loadChatsIndex();I(f);let d=f.find(C=>C.id===n);T(d||null);}catch(f){console.error("Failed to refresh chat list:",f);}},[i,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!u||k.current)){try{i.loadCurrentChatId()&&(v.current=!0);}catch(f){console.error("Failed to restore chat:",f);}k.current=true;}},[i,u]),useEffect(()=>{if(!(!c||r.length===0))if(v.current){if(!o){let f=Date.now();try{i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);C&&(i.upsertChatMeta({...C,updatedAt:f}),a());}catch(d){console.error("Failed to save chat:",d);}}}else {let f=r.find(d=>d.role==="user");if(f){let d="";if(Array.isArray(f.parts)){let m=f.parts.find(R=>R&&R.type==="text");d=m&&typeof m.text=="string"?m.text:"";}let C=(d||"New chat").slice(0,80),M=Date.now();try{i.upsertChatMeta({id:n,title:C,createdAt:M,updatedAt:M}),i.saveChat({id:n,messages:r,agentId:t}),i.saveCurrentChatId(n),v.current=!0,a();}catch(m){console.error("Failed to create chat:",m);}}}},[]);let b=useRef(false);useEffect(()=>{if(o){b.current=true;return}if(b.current&&c){b.current=false;try{let f=Date.now();i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);if(C)i.upsertChatMeta({...C,updatedAt:f});else {let M="",m=Array.isArray(r)?r.find(N=>N&&N.role==="user"):void 0;if(m&&Array.isArray(m.parts)){let N=m.parts.find(U=>U&&U.type==="text");M=N&&typeof N.text=="string"?N.text:"";}let R=(M||"New chat").slice(0,80);i.upsertChatMeta({id:n,title:R,createdAt:f,updatedAt:f});try{i.saveCurrentChatId(n);}catch{}v.current=!0;}a();}catch(f){console.error("Failed to save chat on completion:",f);}}},[o,r,n,t,i,c,a]);let s=useCallback(f=>{try{let d=i.loadChat(f);return d?{id:d.id,messages:d.messages,agentId:d.agentId||t}:null}catch(d){return console.error("Failed to load chat:",d),null}},[i,t]),l=useCallback(()=>{if(r.length!==0)try{let f=Date.now();i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);C&&(i.upsertChatMeta({...C,updatedAt:f}),a());}catch(f){console.error("Failed to save chat:",f);}},[i,n,r,t,a]),p=useCallback(f=>{try{i.deleteChat(f),a();}catch(d){console.error("Failed to delete chat:",d);}},[i,a]),h=useCallback((f,d)=>{if(f!==n)try{v.current=!0,i.saveCurrentChatId(f);let C=i.loadChat(f),M=C&&Array.isArray(C.messages)?C.messages:[];d(M),a();}catch(C){console.error("Failed to switch chat:",C);}},[i,n,a]),g=useCallback(f=>{v.current=false,f();},[]),w=useCallback(f=>{if(!f.trim())return x;let d=f.toLowerCase();return x.filter(C=>C.title.toLowerCase().includes(d))},[x]);return {chatList:x,currentChatMeta:y,refreshChatList:a,loadChat:s,saveCurrentChat:l,deleteChat:p,switchToChat:h,createNewChat:g,searchChats:w,storage:i}}function Uo(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:c}=e,{baseUrl:u}=ne(),i=c||u||"",[x,I]=useState(null),[y,T]=useState(""),[v,k]=useState([]),[a,b]=useState(false),s=useCallback((f,d,C=[])=>{I(f),T(d),k(C);},[]),l=useCallback(()=>{I(null),T(""),k([]);},[]),p=useCallback(async f=>{if(!n)try{let d=t.findIndex(M=>M.id===f);if(d===-1)return;let C=t.slice(0,d);o(C),await r({text:y.trim(),files:v.map(M=>({type:"file",url:M.url,mediaType:M.mimeType||"application/octet-stream",...M.name?{name:M.name}:{},...M.size?{size:M.size}:{}}))}),l();}catch(d){throw console.error("Failed to save edit:",d),d}},[n,t,r,y,v,o,l]),h=useCallback(f=>x===f,[x]),g=useCallback(async f=>{if(!i){console.warn("baseUrl not provided, cannot upload attachments");return}b(true);try{let d=Array.from(f).map(async M=>{if(M.size>26214400)throw new Error(`${M.name} is too large (max 25MB)`);let m=new FormData;m.append("file",M);let R=await fetch(`${i}/api/upload`,{method:"POST",body:m});if(!R.ok)throw new Error(`Upload failed: ${R.statusText}`);let N=await R.json();return {id:N.url||`${Date.now()}-${Math.random()}`,name:M.name,url:N.url,mimeType:M.type,size:M.size}}),C=await Promise.all(d);k(M=>[...M,...C]);}catch(d){throw console.error("Failed to upload files:",d),d}finally{b(false);}},[i]),w=useCallback(f=>{k(d=>d.filter(C=>C.id!==f));},[]);return {editingMessageId:x,editingText:y,setEditingText:T,editAttachments:v,setEditAttachments:k,editUploading:a,startEdit:s,cancelEdit:l,saveEdit:p,isEditing:h,addEditAttachments:g,removeEditAttachment:w}}function j({IconComponent:e,...t}){return zo.createElement(e,t)}function At({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:c}){return jsx("button",{"aria-label":n,title:c,disabled:o,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:o?"not-allowed":"pointer",opacity:o?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter: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 hn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:c,onToggleHistory:u,onClose:i,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(At,{icon:jsx(j,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||c();},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:y=>{y.currentTarget.style.backgroundColor=o.hoverBackground,y.currentTarget.style.color=o.textColor;},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color=o.mutedTextColor;},onClick:u,children:jsx(j,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(At,{icon:jsx(j,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:i,ariaLabel:I("header.close"),resolvedColors:o})]})]})}var ct=class extends Component{constructor(t){super(t),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(t){return {hasError:true,error:t,errorInfo:null}}componentDidMount(){let{toolCallId:t,toolName:n,onSuccess:r}=this.props;t&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(t,n);},0);}componentDidCatch(t,n){console.error(`UI Component Error (${this.props.componentName}):`,t,n),this.setState({error:t,errorInfo:n});let{toolCallId:r,toolName:o,onError:c}=this.props;r&&o&&c&&c(r,o,t);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:t,componentName:n}=this.props;return jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var qo=e=>{let t={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return t[e||"output-available"]||t["output-available"]},Ko=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}},Vo=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function xn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:u,onUISuccess:i,addToolResult:x}){let I=[],y=[],T,v,k=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){y.push(a.text),T||(T=a.startDate),v=a.endDate,a.state==="done"&&(k=true);continue}if(a.type==="text"&&typeof a.text=="string"){y.length&&(I.push({type:"reasoning",texts:y,startDate:T,endDate:v,isCompleted:k}),y=[],T=void 0,v=void 0,k=false),I.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let b=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(b||s||a.type==="tool-call"){y.length&&(I.push({type:"reasoning",texts:y,startDate:T,endDate:v,isCompleted:k}),y=[],T=void 0,v=void 0,k=false);let l=String(b?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");l==="requestInput"?I.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):I.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return y.length&&I.push({type:"reasoning",texts:y,startDate:T,endDate:v,isCompleted:k}),I.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[I.map((a,b)=>{let s=`${t}-${b}`,l=n.has(s);if(a.type==="reasoning"){let d=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",C=a.texts&&a.texts.length>0&&a.texts.some(m=>m.trim().length>0),M=()=>{C&&r(s);};return d&&!C?null:jsx("div",{onClick:M,style:{cursor:C?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l?"4px":"0px"},children:[jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!d&&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:d?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:d?"auto":"200% 100%",backgroundClip:d?"unset":"text",WebkitBackgroundClip:d?"unset":"text",WebkitTextFillColor:d?o.mutedTextColor:"transparent",animation:d?void 0:"shimmer 2s ease-in-out infinite"},children:d?"Finish Thinking":"Thinking"})]}),C&&jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:l?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsx("div",{style:{display:"grid",gridTemplateRows:l||!d?"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:(!d&&l?a.texts:d?l?a.texts:[]:[a.texts[a.texts.length-1]]).map((m,R)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(We,{content:m,theme:"dark",streaming:!d})},`rg-line-${b}-${R}`))}):jsxs("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text"){let d=typeof a.endDate!="number";return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(We,{content:a.text,theme:"dark",streaming:d})},s)}let{color:p,text:h}=qo(a.status),g=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=c?.[a.toolName||""];if(w)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(ct,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:u,onSuccess:i,children:jsx(w,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:x})})},s);let f=Ko(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:p,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:p,animation:g?"pulse 1.5s ease-in-out infinite":void 0}}),h]}),f.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:f.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:f.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:Vo(f.toolName)})]})})},s)}),jsx("style",{children:`
|
|
11
|
+
`,document.head.appendChild(o);}Bn=true;}return t?(t.classList.add("as-arrow"),Ke||(Ke=createRoot(t),Ke.render(jsx(Dn,{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),Ke=createRoot(t),Ke.render(jsx(Dn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Pe(e,t,n){return Math.max(t,Math.min(n,e))}function No(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,c,x=1]=o;return {r:l,g:u,b:c,a:x}}function Wo({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 Uo(e){let t=e?Un(e):null;return !t||t.a===0?false:Wo(t)<.5}function Oo(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let u=getComputedStyle(n).backgroundColor,c=Un(u);if(c&&c.a>0)return u;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Pt(e,t,n){let r=Oo(t,n),o=Uo(r),l=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=l,c.style.strokeWidth="1";}),e.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function it(e,t,n,r,o="ease-in-out",l="curve",u=.25,c="auto",x){Wn(),Dt(e);let I=performance.now(),d=o==="linear"?b=>b:No,S=l!=="straight",C={x:0,y:0};if(S){let b=n.x-t.x,a=n.y-t.y,w=Math.hypot(b,a)||1,i=(t.x+n.x)/2,T=(t.y+n.y)/2,s=-a/w,g=b/w,h=1;c==="left"?h=-1:c==="right"?h=1:h=Math.random()<.5?-1:1;let k=Pe(u,0,1)*w;C={x:i+h*s*k,y:T+h*g*k};}return new Promise(b=>{function a(w){let i=Pe((w-I)/r,0,1),T=d(i),s,g;if(S){let v=1-T;s=v*v*t.x+2*v*T*C.x+T*T*n.x,g=v*v*t.y+2*v*T*C.y+T*T*n.y;}else s=t.x+(n.x-t.x)*T,g=t.y+(n.y-t.y)*T;let k=.35*(1-T),y=Math.sin(w*.02)*k,m=Math.cos(w*.018)*k;e.style.left=`${s+y}px`,e.style.top=`${g+m}px`,Pt(e,s+y,g+m),x&&x({x:s+y,y:g+m,t:i,now:w}),i<1?requestAnimationFrame(a):b();}requestAnimationFrame(a);})}function Pn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function he(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",c={button:0,buttons:l?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let x=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...c});e.dispatchEvent(x);}else {let x=new MouseEvent(t,c);e.dispatchEvent(x);}}catch{let l=new MouseEvent(t,o);e.dispatchEvent(l);}}function On(e){return e&&typeof e=="object"&&e.nodeType===1}function Go(e){if(!e)return document;if(On(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 $n(e){if(On(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=Go(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 zn(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=Pe(t.x,0,1),o=Pe(t.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function Nn(e){return {x:Pe(e.x,0,window.innerWidth),y:Pe(e.y,0,window.innerHeight)}}function jo(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await zo();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),Dt(o),Wn();let l=parseFloat(o.style.left||"20")||20,u=parseFloat(o.style.top||"20")||20;Pt(o,l,u);for(let c of n){let{durationMs:x=800,easing:I="ease-in-out",offset:d,highlight:S=true,path:C="curve",curveStrength:b=.25,curveDirection:a="auto",anchor:w,cursorHotspot:i,dragTo:T}=c.options??{},s=c.action??c.options?.action??"none",g=performance.now(),h=$n(c.target),k=null,y=null;if(h.kind==="element"&&h.element?(y=h.element,o.classList.remove("visible"),y.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Bo(y,1500,180),Dt(o),k=zn(y,w)):h.kind==="position"&&h.point&&(k=h.point),!k){r.push({ok:false,action:s,targetKind:h.kind,durationMs:Math.round(performance.now()-g),error:"Target not found"});continue}let m={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},v=Nn(Pn(k,d));await it(o,m,v,x,I,C,b,a);let M=v.x-m.x,f=v.y-m.y,F=Math.hypot(M,f)||1,G=M/F,V=f/F,me=Math.min(6,Math.max(3,F*.02)),ge={x:v.x+G*me,y:v.y+V*me};await it(o,v,ge,Math.max(70,x*.1),"ease-out","straight",0,"right"),await it(o,ge,v,120,"ease-out","straight",0,"left"),S&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let se=null;try{if(s==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let P={x:i?.x??0,y:i?.y??0},U={x:v.x+P.x,y:v.y+P.y};o.style.left=`${U.x}px`,o.style.top=`${U.y}px`,Pt(o,U.x,U.y);let X=y??document.elementFromPoint(U.x,U.y)??document.body;he(X,"pointerdown",U),he(X,"mousedown",U),await new Promise(fe=>setTimeout(fe,90)),o.classList.remove("pressing"),he(X,"mouseup",U),he(X,"click",U),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),X instanceof HTMLElement&&X.focus?.(),se=X?.id??null;}else if(s==="drag"){if(!T)throw new Error("dragTo is required for action 'drag'");let P=$n(T),U=null;if(P.kind==="element"&&P.element&&(U=zn(P.element,w)),P.kind==="position"&&P.point&&(U=P.point),!U)throw new Error("dragTo target not found");let X=Nn(Pn(U,d)),fe={x:v.x,y:v.y},A=y??document.elementFromPoint(fe.x,fe.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),he(A,"pointerdown",fe),he(A,"mousedown",fe),await it(o,fe,X,Math.max(200,x),I,C,b,a,({x:Q,y:ie})=>{let J=document.elementFromPoint(Q,ie)??document.body,ee={x:Q,y:ie};he(J,"pointermove",ee),he(J,"mousemove",ee);});let O=document.elementFromPoint(X.x,X.y)??document.body;o.classList.remove("pressing"),he(O,"pointerup",X),he(O,"mouseup",X);}r.push({ok:!0,action:s,targetKind:h.kind,durationMs:Math.round(performance.now()-g),clickedElementId:se});}catch(P){r.push({ok:false,action:s,targetKind:h.kind,durationMs:Math.round(performance.now()-g),error:P?.message??String(P)});}}return Ho(o,2e3),{ok:r.every(c=>c.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var Ve=jo;function Gn(){return {getDomComponents:{tool:async({includeHidden:e,selector:t})=>await _e({includeHidden:e,selector:t}),executeEachToken:false},controlCursor:{tool:async({target:e,action:t,anchor:n,durationMs:r,dragTo:o})=>{let l=await Me(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,c=u?.clickedElementId?` (clicked element id: ${u.clickedElementId})`:"",x=t||u?.action||"none";return {success:true,message:x==="click"?`Cursor moved and clicked successfully${c}`:x==="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 qe(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 Xe({content:e,theme:t="dark",streaming:n=false}){return jsx(XMarkdown,{content:e,className:t==="dark"?"x-markdown-dark":"x-markdown-light",streaming:{hasNextChunk:n,enableAnimation:true,animationConfig:{fadeDuration:200},incompleteMarkdownComponentMap:{html:"IncompleteBlock",link:"IncompleteBlock",image:"IncompleteBlock"}},openLinksInNewTab:true,config:{gfm:true},dompurifyConfig:{ADD_TAGS:["data-chart","welcome","user-card","mermaid"],ADD_ATTR:["data-source","data-spec","data-icon","data-description","data-raw"]},style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"}})}function Xo({input:e}){return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsx(Xe,{content:e?.text||"",theme:"dark"})})}function _n(){return {plainText:Xo}}function qn(e,t,n,r,o,l){let u=n.get(t);if(u){let h=u.parentElement,k=document.querySelector(`[data-get-from-user-host="${t}"]`);if(k&&h!==k){try{h?.removeChild(u);}catch{}k.innerHTML="",k.appendChild(u);}}else {u=document.createElement("div"),u.className="hsafa-inline-form";let h=document.querySelector(`[data-get-from-user-host="${t}"]`);h?(h.innerHTML="",h.appendChild(u)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(u),n.set(t,u);}let c=e?.title||"Provide input",x=e?.description||"",I=e?.submitLabel||"Submit",d=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||""}]:[],C=r.get(t)||{submitted:false,skipped:false,values:void 0};u.innerHTML="";let b=document.createElement("form");b.style.margin="12px 0",b.style.padding="14px",b.style.border="1px solid var(--hsafa-border, #2A2C33)",b.style.borderRadius="12px",b.style.background="var(--hsafa-card, #121318)",b.style.color="var(--hsafa-text, #EDEEF0)",b.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let a=document.createElement("div");if(a.style.fontWeight="600",a.style.marginBottom="6px",a.textContent=c,b.appendChild(a),x){let h=document.createElement("div");h.style.fontSize="12px",h.style.opacity="0.8",h.style.marginBottom="10px",h.textContent=x,b.appendChild(h);}S.forEach(h=>{let k=document.createElement("div");if(k.style.margin="10px 0",h.label){let f=document.createElement("label");f.style.display="block",f.style.fontSize="12px",f.style.marginBottom="6px",f.style.opacity="0.9",f.textContent=h.label,k.appendChild(f);}let y,m=(h.type||"text").toLowerCase();if(m==="textarea"){let f=document.createElement("textarea");f.placeholder=h.placeholder||"",f.value=h.value??"",f.style.width="100%",f.style.minHeight="72px",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",y=f;}else if(m==="select"&&Array.isArray(h.options)){let f=document.createElement("select");f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",h.options.forEach(F=>{let G=document.createElement("option");G.value=String(F.value),G.text=String(F.label??F.value),f.appendChild(G);}),f.value=h.value??"",y=f;}else if(m==="checkbox"){let f=document.createElement("input");f.type="checkbox",f.checked=!!h.value,f.style.transform="scale(1.1)",y=f;}else {let f=document.createElement("input");f.type=m,f.placeholder=h.placeholder||"",f.value=h.value??"",f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",y=f;}let v=h.id||"value";y.dataset.fieldId=v;let M=C.values&&Object.prototype.hasOwnProperty.call(C.values,v)?C.values[v]:void 0;typeof M<"u"&&(y.type==="checkbox"?y.checked=!!M:y.value=String(M)),(C.submitted||C.skipped)&&(y.setAttribute("disabled","true"),y.style.opacity="0.7"),k.appendChild(y),b.appendChild(k);});let w=String(I).trim(),i=String(d).trim(),T=!!(w||i),s=null,g=null;if(T){let h=document.createElement("div");h.style.display="flex",h.style.gap="8px",h.style.marginTop="10px",s=document.createElement("button"),s.type="submit",s.textContent=w||"Submit",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",s.style.color="#000000",g=document.createElement("button"),g.type="button",g.textContent=i||"Skip",g.style.padding="6px 10px",g.style.borderRadius="8px",g.style.background="transparent",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.color="inherit",h.appendChild(s),h.appendChild(g),b.appendChild(h);}if(b.onsubmit=h=>{h.preventDefault();let k={};b.querySelectorAll("[data-field-id]").forEach(y=>{let m=y.dataset.fieldId||"value";y.type==="checkbox"?k[m]=y.checked:k[m]=y.value??"";}),r.set(t,{submitted:true,skipped:false,values:k}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:k}}),b.querySelectorAll("[data-field-id]").forEach(y=>{y.disabled=true,y.style.opacity="0.7";}),s&&(s.textContent=`${w||"Submit"} \u2713`,s.style.opacity="0.8",s.disabled=true),g&&(g.disabled=true);},g&&(g.onclick=()=>{r.set(t,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:false,skipped:true}}),b.querySelectorAll("[data-field-id]").forEach(h=>{h.disabled=true,h.style.opacity="0.7";}),g&&(g.textContent=`${i||"Skip"} \u2713`,g.style.opacity="0.8",g.disabled=true),s&&(s.disabled=true);}),C.submitted||C.skipped){let h=document.createElement("div");h.style.marginTop="10px",h.style.fontSize="12px",h.style.display="flex",h.style.alignItems="center",h.style.gap="8px";let k=document.createElement("span");k.style.display="inline-flex",k.style.alignItems="center",k.style.padding="2px 8px",k.style.borderRadius="999px",k.style.fontWeight="600",k.style.fontSize="11px",C.submitted?(k.style.background="rgba(16,185,129,0.15)",k.style.color="#10b981",k.textContent="Submitted"):(k.style.background="rgba(234,179,8,0.15)",k.style.color="#eab308",k.textContent="Skipped"),h.appendChild(k),b.appendChild(h);try{s&&(s.disabled=!0,s.style.opacity="0.8",C.submitted&&(s.textContent=`${w||"Submit"} \u2713`)),g&&(g.disabled=!0,g.style.opacity="0.8",C.skipped&&(g.textContent=`${i||"Skip"} \u2713`));}catch{}}u.appendChild(b);}function Kn(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(c=>{c.role==="assistant"&&c.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 d=l.current[I];if(d&&typeof d=="object"&&d.executeEachToken&&d.tool){let S=x.input||x.args||{},C=JSON.stringify(S),b=r.current.get(x.toolCallId);if(C!==b&&C!=="{}"){r.current.set(x.toolCallId,C);try{if(I==="requestInput")u.current(S,x.toolCallId);else {let w=(o.current.get(x.toolCallId)||0)+1;o.current.set(x.toolCallId,w),w>1&&d.tool({...S,toolCallNumber:w-1});}}catch{}}}});});},[e]);}function zt(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:l,onFinish:u,onError:c,initialMessages:x=[],onMessagesChange:I,controlledChatId:d,onChatIdChange:S,templateParams:C}=e,{baseUrl:b,setCurrentChatId:a}=le(),w=n&&n.length>0?n:b||"",[i,T]=useState(""),[s,g]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),h=d??s,k=useCallback(R=>{d===void 0&&g(R),S&&S(R);},[d,S]);useEffect(()=>{try{a(h);}catch{}return ()=>{try{a(void 0);}catch{}}},[h,a]);let y=useMemo(()=>An(w,t,h,C),[w,t,h,C]),m=useCallback(R=>{console.log("Message finished:",R);let B=R?.message?.id;if(!B&&Array.isArray(R?.messages))for(let W=R.messages.length-1;W>=0;W--){let N=R.messages[W];if(N&&N.role==="assistant"&&N.id){B=N.id;break}}u?.({...R,chatId:h,assistantMessageId:B});},[u,h]),v=useCallback(R=>{console.error("Chat error:",R),c?.(R);},[c]),M=useMemo(()=>Gn(),[]),f=useMemo(()=>({...M,...r}),[M,r]),F=useMemo(()=>_n(),[]),G=useMemo(()=>({...F,...o}),[F,o]),V=useRef(new Map),me=useRef(new Map),ge=useCallback(()=>{try{V.current.forEach(R=>{try{R.remove();}catch{}}),V.current.clear(),me.current.clear();}catch{}},[]),se=useCallback((R,B)=>{qn(R,B,V.current,me.current,W=>P.current.addToolResult(W));},[]),P=useRef(null),U=useRef(new Set),X=useCallback((R,B,W)=>{console.error(`UI Error [${B}]:`,W),P.current&&U.current.has(R)&&(U.current.delete(R),P.current.addToolResult({tool:B,toolCallId:R,state:"output-error",errorText:W?.message||String(W)}));},[]),fe=useCallback((R,B)=>{P.current&&U.current.has(R)&&(U.current.delete(R),P.current.addToolResult({tool:B,toolCallId:R,output:{status:"ok",rendered:true,component:B,logs:[]}}));},[]),A=useCallback(R=>{let B=f[R];return B?typeof B=="object"&&"tool"in B?B.tool:typeof B=="function"?B:null:null},[f]),O=useChat({transport:y,onFinish:m,onError:v,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:R}){let B=A(R.toolName);if(R.toolName==="requestInput"){try{se(R.input,R.toolCallId);}catch(oe){console.error("requestInput render error",oe);}return}let W=R.toolName==="ui";R?.input;let Z=G&&R.toolName in G;if(W||Z){U.current.add(R.toolCallId);return}if(B)try{let oe=await B(R.input);O.addToolResult({tool:R.toolName,toolCallId:R.toolCallId,output:oe});}catch(oe){O.addToolResult({tool:R.toolName,toolCallId:R.toolCallId,state:"output-error",errorText:oe?.message||String(oe)});}}}),{messages:Q,sendMessage:ie,status:J,stop:ee,error:j}=O;P.current=O,Kn(Q,f,se),useEffect(()=>{try{let R=new Set,B=[];if(Q.forEach(W=>{W.role==="assistant"&&(W.parts||[]).forEach(N=>{if((N?.toolName||(typeof N?.type=="string"&&N.type.startsWith("tool-")?String(N.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let oe=N?.toolCallId||"";if(!oe)return;R.add(oe);let be=N?.output;if(be&&(be.submitted||be.skipped||be.values)){let nt={submitted:!!be.submitted,skipped:!!be.skipped,values:be.values||void 0};me.current.set(oe,nt);}let we=N?.input||N?.args||{};B.push({input:we,toolCallId:oe});});}),V.current.forEach((W,N)=>{if(!R.has(N)){let Z=V.current.get(N);try{Z?.remove();}catch{}V.current.delete(N),me.current.delete(N);}}),B.length>0){let W=requestAnimationFrame(()=>{B.forEach(({input:N,toolCallId:Z})=>{try{se(N,Z);}catch{}});});return ()=>cancelAnimationFrame(W)}}catch{}},[Q,se]),useEffect(()=>{x&&x.length>0&&Q.length===0&&console.log("Initial messages:",x);},[x,Q.length]);let xe=J==="submitted"||J==="streaming",Ae=useCallback(()=>{I&&I(Q,h);},[I,Q,h]),et=useCallback(async R=>{let B=R?.text!==void 0?R.text:i,W=R?.files||[],N=B.trim();if(!(!N&&W.length===0)&&!xe){R?.text===void 0&&T("");try{if(l){let Z={role:"user",content:N,createdAt:Date.now(),chatId:h};l(Z);}await ie({text:N,files:W});}catch(Z){throw console.error("Failed to send message:",Z),Z}}},[i,xe,ie,l,h]),tt=useCallback(()=>{if(xe)return;ge(),T("");try{O?.setMessages?.([]);}catch{}let R=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;k(R);},[xe,O,ge,k]),te=useCallback(R=>{try{O?.setMessages?.(R);}catch{}},[O]);return {input:i,setInput:T,messages:Q,isLoading:xe,status:J,error:j,sendMessage:et,stop:ee,newChat:tt,setMessages:te,notifyMessagesChange:Ae,chatApi:O,chatId:h,setChatId:k,tools:f,uiComponents:G,formHostRef:V,formStateRef:me,cleanupForms:ge,onUISuccess:fe,onUIError:X}}function pt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=g=>`${t}.chat.${g}`,o=`${t}.currentChatId`,l=`${t}.showChat`,u=()=>{try{let g=localStorage.getItem(n);return g?JSON.parse(g):[]}catch{return []}},c=g=>{try{localStorage.setItem(n,JSON.stringify(g));}catch{}},x=g=>{try{let h=localStorage.getItem(r(g));return h?JSON.parse(h):null}catch{return null}},I=g=>{try{localStorage.setItem(r(g.id),JSON.stringify(g));}catch{}},d=g=>{let h=u(),k=h.findIndex(y=>y.id===g.id);k>=0?h[k]=g:h.unshift(g),c(h);},S=g=>{let k=u().filter(y=>y.id!==g);c(k);},C=g=>{try{localStorage.removeItem(r(g));}catch{}};return {loadChatsIndex:u,saveChatsIndex:c,loadChat:x,saveChat:I,upsertChatMeta:d,deleteChatMeta:S,deleteChatData:C,deleteChat:g=>{C(g),S(g);},loadShowChatPreference:g=>{try{let h=localStorage.getItem(l);return h!==null?h==="true":g}catch{return g}},saveShowChatPreference:g=>{try{localStorage.setItem(l,String(g));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:g=>{try{localStorage.setItem(o,g);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Wt(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:l=true,autoRestore:u=true}=e,c=useMemo(()=>pt(t),[t]),[x,I]=useState([]),[d,S]=useState(null),C=useRef(false),b=useRef(false),a=useCallback(()=>{try{let y=c.loadChatsIndex();I(y);let m=y.find(v=>v.id===n);S(m||null);}catch(y){console.error("Failed to refresh chat list:",y);}},[c,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!u||b.current)){try{c.loadCurrentChatId()&&(C.current=!0);}catch(y){console.error("Failed to restore chat:",y);}b.current=true;}},[c,u]),useEffect(()=>{if(!(!l||r.length===0))if(C.current){if(!o){let y=Date.now();try{c.saveChat({id:n,messages:r,agentId:t});let v=c.loadChatsIndex().find(M=>M.id===n);v&&(c.upsertChatMeta({...v,updatedAt:y}),a());}catch(m){console.error("Failed to save chat:",m);}}}else {let y=r.find(m=>m.role==="user");if(y){let m="";if(Array.isArray(y.parts)){let f=y.parts.find(F=>F&&F.type==="text");m=f&&typeof f.text=="string"?f.text:"";}let v=(m||"New chat").slice(0,80),M=Date.now();try{c.upsertChatMeta({id:n,title:v,createdAt:M,updatedAt:M}),c.saveChat({id:n,messages:r,agentId:t}),c.saveCurrentChatId(n),C.current=!0,a();}catch(f){console.error("Failed to create chat:",f);}}}},[]);let w=useRef(false);useEffect(()=>{if(o){w.current=true;return}if(w.current&&l){w.current=false;try{let y=Date.now();c.saveChat({id:n,messages:r,agentId:t});let v=c.loadChatsIndex().find(M=>M.id===n);if(v)c.upsertChatMeta({...v,updatedAt:y});else {let M="",f=Array.isArray(r)?r.find(G=>G&&G.role==="user"):void 0;if(f&&Array.isArray(f.parts)){let G=f.parts.find(V=>V&&V.type==="text");M=G&&typeof G.text=="string"?G.text:"";}let F=(M||"New chat").slice(0,80);c.upsertChatMeta({id:n,title:F,createdAt:y,updatedAt:y});try{c.saveCurrentChatId(n);}catch{}C.current=!0;}a();}catch(y){console.error("Failed to save chat on completion:",y);}}},[o,r,n,t,c,l,a]);let i=useCallback(y=>{try{let m=c.loadChat(y);return m?{id:m.id,messages:m.messages,agentId:m.agentId||t}:null}catch(m){return console.error("Failed to load chat:",m),null}},[c,t]),T=useCallback(()=>{if(r.length!==0)try{let y=Date.now();c.saveChat({id:n,messages:r,agentId:t});let v=c.loadChatsIndex().find(M=>M.id===n);v&&(c.upsertChatMeta({...v,updatedAt:y}),a());}catch(y){console.error("Failed to save chat:",y);}},[c,n,r,t,a]),s=useCallback(y=>{try{c.deleteChat(y),a();}catch(m){console.error("Failed to delete chat:",m);}},[c,a]),g=useCallback((y,m)=>{if(y!==n)try{C.current=!0,c.saveCurrentChatId(y);let v=c.loadChat(y),M=v&&Array.isArray(v.messages)?v.messages:[];m(M),a();}catch(v){console.error("Failed to switch chat:",v);}},[c,n,a]),h=useCallback(y=>{C.current=false,y();},[]),k=useCallback(y=>{if(!y.trim())return x;let m=y.toLowerCase();return x.filter(v=>v.title.toLowerCase().includes(m))},[x]);return {chatList:x,currentChatMeta:d,refreshChatList:a,loadChat:i,saveCurrentChat:T,deleteChat:s,switchToChat:g,createNewChat:h,searchChats:k,storage:c}}function er(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:l}=e,{baseUrl:u}=le(),c=l||u||"",[x,I]=useState(null),[d,S]=useState(""),[C,b]=useState([]),[a,w]=useState(false),i=useCallback((y,m,v=[])=>{I(y),S(m),b(v);},[]),T=useCallback(()=>{I(null),S(""),b([]);},[]),s=useCallback(async y=>{if(!n)try{let m=t.findIndex(M=>M.id===y);if(m===-1)return;let v=t.slice(0,m);o(v),await r({text:d.trim(),files:C.map(M=>({type:"file",url:M.url,mediaType:M.mimeType||"application/octet-stream",...M.name?{name:M.name}:{},...M.size?{size:M.size}:{}}))}),T();}catch(m){throw console.error("Failed to save edit:",m),m}},[n,t,r,d,C,o,T]),g=useCallback(y=>x===y,[x]),h=useCallback(async y=>{if(!c){console.warn("baseUrl not provided, cannot upload attachments");return}w(true);try{let m=Array.from(y).map(async M=>{if(M.size>26214400)throw new Error(`${M.name} is too large (max 25MB)`);let f=new FormData;f.append("file",M);let F=await fetch(`${c}/api/upload`,{method:"POST",body:f});if(!F.ok)throw new Error(`Upload failed: ${F.statusText}`);let G=await F.json();return {id:G.url||`${Date.now()}-${Math.random()}`,name:M.name,url:G.url,mimeType:M.type,size:M.size}}),v=await Promise.all(m);b(M=>[...M,...v]);}catch(m){throw console.error("Failed to upload files:",m),m}finally{w(false);}},[c]),k=useCallback(y=>{b(m=>m.filter(v=>v.id!==y));},[]);return {editingMessageId:x,editingText:d,setEditingText:S,editAttachments:C,setEditAttachments:b,editUploading:a,startEdit:i,cancelEdit:T,saveEdit:s,isEditing:g,addEditAttachments:h,removeEditAttachment:k}}function q({IconComponent:e,...t}){return so.createElement(e,t)}function Ut({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 Jn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:l,onToggleHistory:u,onClose:c,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(Ut,{icon:jsx(q,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||l();},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:d=>{d.currentTarget.style.backgroundColor=o.hoverBackground,d.currentTarget.style.color=o.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=o.mutedTextColor;},onClick:u,children:jsx(q,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(Ut,{icon:jsx(q,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:I("header.close"),resolvedColors:o})]})]})}var yt=class extends Component{constructor(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 ir=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"]},lr=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}},cr=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function Zn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:l,onUIError:u,onUISuccess:c,addToolResult:x}){let I=[],d=[],S,C,b=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){d.push(a.text),S||(S=a.startDate),C=a.endDate,a.state==="done"&&(b=true);continue}if(a.type==="text"&&typeof a.text=="string"){d.length&&(I.push({type:"reasoning",texts:d,startDate:S,endDate:C,isCompleted:b}),d=[],S=void 0,C=void 0,b=false),I.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let w=a.type==="dynamic-tool",i=typeof a.type=="string"&&a.type.startsWith("tool-");if(w||i||a.type==="tool-call"){d.length&&(I.push({type:"reasoning",texts:d,startDate:S,endDate:C,isCompleted:b}),d=[],S=void 0,C=void 0,b=false);let T=String(w?a.toolName||"dynamic-tool":i?a.type?.slice(5)||"tool":a.toolName||"tool");T==="requestInput"?I.push({type:"tool",toolName:T,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:T,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return d.length&&I.push({type:"reasoning",texts:d,startDate:S,endDate:C,isCompleted:b}),I.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[I.map((a,w)=>{let i=`${t}-${w}`,T=n.has(i);if(a.type==="reasoning"){let m=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",v=a.texts&&a.texts.length>0&&a.texts.some(f=>f.trim().length>0),M=()=>{v&&r(i);};return m&&!v?null:jsx("div",{onClick:M,style:{cursor:v?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:T?"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:[!m&&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:m?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:m?"auto":"200% 100%",backgroundClip:m?"unset":"text",WebkitBackgroundClip:m?"unset":"text",WebkitTextFillColor:m?o.mutedTextColor:"transparent",animation:m?void 0:"shimmer 2s ease-in-out infinite"},children:m?"Finish Thinking":"Thinking"})]}),v&&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:T?"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:T||!m?"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:(!m&&T?a.texts:m?T?a.texts:[]:[a.texts[a.texts.length-1]]).map((f,F)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(Xe,{content:f,theme:"dark",streaming:!m})},`rg-line-${w}-${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:"..."})]})})})]})},i)}if(a.type==="text"){let m=typeof a.endDate!="number";return jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsx(Xe,{content:a.text,theme:"dark",streaming:m})},i)}let{color:s,text:g}=ir(a.status),h=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||i,style:{width:"100%"}})},i);let k=l?.[a.toolName||""];if(k)return jsx("div",{style:{display:"block",position:"relative"},children:jsx(yt,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:u,onSuccess:c,children:jsx(k,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:x})})},i);let y=lr(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:s,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:s,animation:h?"pulse 1.5s ease-in-out infinite":void 0}}),g]}),y.isMCP?jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsx("span",{style:{fontWeight:600},children:y.toolName}),jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsx("span",{style:{fontWeight:600,opacity:.85},children:y.mcpName})]}):jsx("span",{style:{fontWeight:500,color:o.textColor},children:cr(y.toolName)})]})})},i)}),jsx("style",{children:`
|
|
12
12
|
@keyframes shimmer {
|
|
13
13
|
0% { background-position: -200% 0; }
|
|
14
14
|
100% { background-position: 200% 0; }
|
|
15
15
|
}
|
|
16
|
-
`})]}):null}function
|
|
16
|
+
`})]}):null}function Qn(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 eo({attachment:e,resolvedColors:t,mode:n,onRemove:r,maxWidth:o="200px"}){let l=e.mimeType?.startsWith("image/"),u=n==="editable"||n==="input",c=n==="viewable",x={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:c?"pointer":"default",maxWidth:n==="input"?"140px":o,position:"relative"},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:d=>{d.target.style.display="none";let S=d.target.nextElementSibling;S&&(S.style.display="block");}}):null,jsx(q,{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:Qn(e.size)})]}),n==="input"&&l&&jsx("button",{onClick:d=>{d.stopPropagation(),window.open(e.url,"_blank");},style:{background:"none",border:"none",color:t.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:d=>{d.currentTarget.style.backgroundColor=t.hoverBackground,d.currentTarget.style.color=t.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=t.mutedTextColor;},children:jsx(q,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),u&&r&&jsx("button",{onClick:d=>{d.stopPropagation(),r(e.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:t.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.color="#ef4444";},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=t.mutedTextColor;},children:jsx(q,{IconComponent:X,size:"12",strokeWidth:"2"})}),c&&jsx(q,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...x,textDecoration:"none"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=t.hoverBackground,d.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor=t.inputBackground,d.currentTarget.style.borderColor=t.borderColor;},children:I}):jsx("div",{style:x,children:I})}function no({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(eo,{attachment:o,resolvedColors:t,mode:r,onRemove:n},o.id))})}function Gt({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:l,onUserMessageClick:u,HsafaUI:c,onUIError:x,onUISuccess:I,addToolResult:d,editableMessageIcon:S,fullPage:C}){return jsxs(Fragment,{children:[jsx("style",{children:`
|
|
17
17
|
@keyframes jumpingDots {
|
|
18
18
|
0%, 80%, 100% {
|
|
19
19
|
transform: translateY(0);
|
|
@@ -22,15 +22,126 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import zo,{createContext,useRe
|
|
|
22
22
|
transform: translateY(-5px);
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
`}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((
|
|
26
|
-
`),s=a.filter(l=>l.type==="file"||l.type==="image").map(l=>{if(l.type==="image"){let p=typeof l.image=="string"?l.image:l.image?.toString?.()||"";return {id:p||`${v.id}-img-${Date.now()}`,name:l.name||"image",url:p,mimeType:l.mediaType||"image/jpeg",size:l.size||0}}else return {id:l.url||`${v.id}-file-${Date.now()}`,name:l.name||"file",url:l.url||"",mimeType:l.mediaType||"application/octet-stream",size:l.size||0}});return jsx("div",{style:{padding:"0 4px"},children:v.role==="user"?jsx("div",{children:jsx("div",{title:c("editor.clickToEdit"),onClick:()=>u(v,v.id,b,s),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:o.accentColor,color:o.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:l=>l.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:l=>l.currentTarget.style.backgroundColor=o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[b,s.length>0&&jsx(kn,{attachments:s,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(j,{IconComponent:T||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(xn,{parts:a,messageId:v.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:x,onUISuccess:I,addToolResult:y})},v.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function Tn({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:c,attachments:u,formatBytes:i,handleRemoveAttachment:x,onFileInputChange:I,onSend:y,onStop:T,status:v,t:k,resolvedColors:a}){let b=v==="streaming"||v==="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(l=>{let p=l.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:a.inputBackground,borderRadius:"10px",border:`1px solid ${a.borderColor}`,fontSize:"12px",color:a.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:p?"transparent":a.cardBackground},children:p?jsx("img",{src:l.url,alt:l.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:l.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:l.name}),jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:i(l.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[p&&jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title: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(l.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"})]})})]})]},l.id)})}),c&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children: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:l=>t(l.target.value),onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),y());},disabled:o||c,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:a.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:r,type:"file",multiple:true,onChange: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||c,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||c?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||c?.5:1},"aria-label":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:T,disabled:!b,"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:b?1:.4,cursor:b?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{b&&(l.currentTarget.style.backgroundColor="#ef444430",l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="#ef444420",l.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:y,disabled:!s||c,"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||c?a.mutedTextColor:a.primaryColor,cursor:!s||c?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||c?.5:1},onMouseEnter:l=>{s&&!c&&(l.currentTarget.style.borderColor=a.primaryColor,l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.borderColor=a.borderColor,l.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function In({prompts:e,onSelect:t,resolvedColors:n,disabled:r=false}){let[o,c]=useState(null);return !e||e.length===0?null:jsxs("div",{style:{padding:"12px 0",display:"flex",flexDirection:"column",gap:"8px"},children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:n.mutedTextColor,paddingLeft:"4px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Suggested Prompts"}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.map((u,i)=>{let x=o===i,I=u.prompt.length>80,y=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:T=>{r||(T.currentTarget.style.backgroundColor=n.hoverBackground,T.currentTarget.style.borderColor=n.primaryColor,T.currentTarget.style.transform="translateX(2px)");},onMouseLeave:T=>{T.currentTarget.style.backgroundColor=n.cardBackground,T.currentTarget.style.borderColor=n.borderColor,T.currentTarget.style.transform="translateX(0)";},children:[jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:n.textColor,marginBottom:"6px",display:"flex",alignItems:"center",gap:"6px"},children:[jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n.primaryColor,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[jsx("path",{d:"M12 20h9"}),jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),u.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:y}),I&&jsxs("button",{onClick:T=>{T.stopPropagation(),c(x?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:[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"})})]})]},i)})})]})}function Sn(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let r=Math.floor(n/60);if(r<60)return `${r}m`;let o=Math.floor(r/60);if(o<24)return `${o}h`;let c=Math.floor(o/24);if(c<7)return `${c}d`;let u=Math.floor(c/7);if(u<4)return `${u}w`;let i=Math.floor(c/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function Mn({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:c,onSearchChange:u,onChatSelect:i,onChatDelete:x,loadChatsIndex:I,historyPopupRef:y}){if(!e)return null;let T=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:c}),jsxs("div",{ref:y,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:v=>u(v.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:o.inputBackground,padding:"8px 12px",fontSize:"14px",color:o.textColor,border:`1px solid ${o.borderColor}`,outline:"none"},onFocus:v=>v.currentTarget.style.borderColor=o.primaryColor,onBlur:v=>v.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let v=t.toLowerCase().trim(),k=I();return v&&(k=k.filter(a=>(a.title||"").toLowerCase().includes(v))),!k||k.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:k.map((a,b)=>jsx("div",{style:{borderTop:b>0?`1px solid ${o.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===n?o.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:o.textColor},onMouseEnter:s=>s.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor="transparent",onClick:()=>i(a.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:o.textColor},children:a.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:Sn(a.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:o.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:s=>{s.currentTarget.style.color="#ef4444",s.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",s.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:s=>{s.currentTarget.style.color=o.mutedTextColor,s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.borderColor="transparent";},onClick:s=>{s.stopPropagation(),x(a.id);},children:jsx(j,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(T,document.body):T}function En({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let c=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",x=o?.cancel_button_label||"Cancel",I=o?.icon,y=typeof u=="function",T=y?u:null,v=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[I?jsx("div",{style:{flexShrink:0},children:jsx(j,{IconComponent:I,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsx(j,{IconComponent:Pencil,size:"20",strokeWidth:"2"})}),jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:c})]}),jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:y&&T?jsx(T,{}):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:i})]})]})]});return typeof document<"u"&&document.body?createPortal(v,document.body):v}function ur({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:c,borderColor:u,textColor:i,accentColor:x,baseUrl:I="",initialMessages:y=[],onMessagesChange:T,defaultOpen:v=true,floatingButtonPosition:k={bottom:24,right:24},HsafaTools:a={},HsafaUI:b={},componentAboveInput:s,editProcessContent:l,presetPrompts:p,onStart:h,onFinish:g,currentChat:w,onChatChanged:f,templateParams:d}){let{dir:C,theme:M,baseUrl:m,setStreamingState:R,setChatOpenState:N}=ne(),U=t||M||"dark",te=I&&I.length>0?I:m||"",A={primaryColor:U==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:c||(U==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:u||(U==="dark"?"#2A2C33":"#E5E7EB"),textColor:i||(U==="dark"?"#EDEEF0":"#111827"),accentColor:x||(U==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:U==="dark"?"#6f7276":"#6B7280",inputBackground:U==="dark"?"#17181C":"#F3F4F6",cardBackground:U==="dark"?"#121318":"#FFFFFF",hoverBackground:U==="dark"?"#1c1e25":"#F3F4F6"},B=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,_=St({agentId:e,baseUrl:te,tools:a,uiComponents:b,templateParams:d,controlledChatId:w,onChatIdChange:w===void 0?S=>{f&&f(S);}:void 0,onStart:useCallback(S=>{h&&h(S);},[h]),onFinish:useCallback(S=>{g&&g(S);},[g]),onError:useCallback(S=>{console.error("Chat error:",S);},[]),initialMessages:y,onMessagesChange:T}),{input:V,setInput:ie,messages:O,isLoading:$,status:he,error:ce,sendMessage:xe,stop:mt,setMessages:q,notifyMessagesChange:qe,chatId:Fe,setChatId:Ie,tools:Ht,uiComponents:E,formHostRef:F,formStateRef:z,cleanupForms:H,onUISuccess:J,onUIError:Z,chatApi:de}=_,X=w!==void 0?w:Fe,be=useCallback(S=>{w===void 0&&Ie(S),f&&f(S);},[w,Ie,f]);useEffect(()=>{w!==void 0&&w!==Fe&&Ie(w);},[w,Fe,Ie]);let{attachments:Ke,uploading:Rn,fileInputRef:Ve,formatBytes:Ln,handleRemoveAttachment:Hn,handleFileSelection:Ft,clearAttachments:Xe,setAttachments:Bt}=Vt(te),[Dt,Se]=useState(null),[Ye,Pt]=useState(()=>{try{return rt(e).loadShowChatPreference(!!v)}catch{return !!v}}),[Fn,gt]=useState(false),[Bn,Dn]=useState(""),[Pn,$n]=useState(0),Nn=useRef(null),Un=useRef(null),[zn,Wn]=useState(new Set),[On,ft]=useState(false),[Be,yt]=useState(null),$t=useRef(null),Gn=_t($),ht=Et({agentId:e,chatId:X,messages:O,isLoading:$,autoSave:true,autoRestore:false}),G=ht.storage,De=useRef(false),Pe=useRef(null);useEffect(()=>{if(!De.current){if(w!==void 0){try{let S=G.loadChat(w),D=S&&Array.isArray(S.messages)?S.messages:[];if(D.length>0)try{q(D);}catch{}Pe.current=w;}catch{}try{G.saveCurrentChatId(w);}catch{}De.current=true;return}try{let S=G.loadCurrentChatId();if(S){be(S);let D=G.loadChat(S),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}Pe.current=S;}}catch{}De.current=true;}},[w]),useEffect(()=>{if(De.current&&w!==void 0&&w!==Pe.current)try{let S=G.loadChat(w),D=S&&Array.isArray(S.messages)?S.messages:[];try{q(D);}catch{}Pe.current=w;try{G.saveCurrentChatId(w);}catch{}}catch{}},[w,G,q]),useEffect(()=>{if(De.current)try{G.saveCurrentChatId(X);}catch{}},[X,G]),useEffect(()=>{try{R(X,$);}catch{}return ()=>{try{R(X,!1);}catch{}}},[X,$,R]),useEffect(()=>{try{N(X,Ye);}catch{}return ()=>{try{N(X,!1);}catch{}}},[X,Ye,N]);let _n=useCallback(async()=>{let S=V.trim();if(!S&&Ke.length===0||$)return;let D=[...Ke];ie(""),Xe(),Se(null);try{await xe({text:S,files:D.map(W=>({type:"file",url:W.url,mediaType:W.mimeType||"application/octet-stream",...W.name?{name:W.name}:{},...W.size?{size:W.size}:{}}))});}catch(W){console.error("Failed to send message:",W),Se("Failed to send message. Please try again.");}},[V,Ke,$,xe,Xe]),Nt=useCallback(()=>{if($)return;H(),ie(""),Xe(),Se(null);try{q([]);}catch{}let S=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Pe.current=S;try{ht.createNewChat(()=>{be(S);try{G.saveCurrentChatId(S);}catch{}});}catch{be(S);try{G.saveCurrentChatId(S);}catch{}}},[$,Xe,G,q,be,H,ht]),jn=useCallback(()=>{gt(S=>!S);},[]),qn=useCallback(()=>{Pt(false);try{G.saveShowChatPreference(!1);}catch{}},[G]),Kn=useCallback(async S=>{let D=S.target.files;D&&await Ft(D,Se),Ve.current&&(Ve.current.value="");},[Ft,Ve]);useEffect(()=>{let S=$t.current;if(!S)return;S.style.height="24px",S.offsetHeight,S.style.height="auto";let D=Math.min(S.scrollHeight,200);S.style.height=`${D}px`;},[V]);let Vn=useCallback((S,D,W,Jn)=>{yt({id:D,text:W,attachments:Jn||[]}),ft(true);},[]),Xn=useCallback(()=>{if(!(!Be||$))try{let S=O.findIndex(W=>W.id===Be.id);if(S===-1)return;let D=O.slice(0,S);try{q(D);}catch{}ie(Be.text),Bt(Be.attachments),ft(!1),yt(null),qe();}catch(S){console.error("Failed to edit message:",S),Se("Failed to edit message. Please try again.");}},[Be,$,O,q,Bt,qe]),Yn=useCallback(()=>{ft(false),yt(null);},[]),Ut=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:A.textColor,gap:"16px",zIndex:1e3,transform:Ye?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(hn,{title:B("general.agent")+2,alwaysOpen:false,streaming:$,dir:C||"ltr",resolvedColors:A,onNew:Nt,onToggleHistory:jn,onClose:qn,historyBtnRef:Nn,t:B}),jsx("div",{ref:Gn,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":A.primaryColor,"--hsafa-border":A.borderColor,"--hsafa-card":A.cardBackground,"--hsafa-text":A.textColor,"--hsafa-muted":A.mutedTextColor,"--hsafa-bg":A.backgroundColor,"--hsafa-hover":A.hoverBackground,"--hsafa-input-bg":A.inputBackground,"--hsafa-accent":A.accentColor},children:O.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:p&&p.length>0?jsx(In,{prompts:p,onSelect:S=>ie(S),resolvedColors:A,disabled:$}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:B("messages.empty")})}):jsx(wn,{chatMessages:O,isLoading:$,openReasoningIds:zn,toggleReasoning:S=>Wn(D=>{let W=new Set(D);return W.has(S)?W.delete(S):W.add(S),W}),resolvedColors:A,t:B,onUserMessageClick:Vn,HsafaUI:E,onUIError:Z,onUISuccess:J,addToolResult:S=>de?.addToolResult?.(S),editableMessageIcon:l?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&zo.createElement(s,{}),Dt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:Dt}),jsx("button",{onClick:()=>Se(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),ce&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",ce.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(Tn,{input:V,setInput:ie,textareaRef:$t,fileInputRef:Ve,isLoading:$,uploading:Rn,attachments:Ke,formatBytes:Ln,handleRemoveAttachment:Hn,onFileInputChange:Kn,onSend:_n,onStop:()=>mt(),status:he,t:B,resolvedColors:A})]}),jsx(Mn,{historyOpen:Fn,historySearch:Bn,currentChatId:X,refreshKey:Pn,resolvedColors:A,onClose:()=>gt(false),onSearchChange:Dn,onChatSelect:S=>{if(gt(false),S&&S!==X&&(H(),be(S),w===void 0)){try{G.saveCurrentChatId(S);}catch{}try{let D=G.loadChat(S),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}}catch{}}},onChatDelete:S=>{try{G.deleteChat(S),$n(D=>D+1),S===X&&Nt();}catch{}},loadChatsIndex:()=>G.loadChatsIndex(),historyPopupRef:Un}),jsx(En,{isOpen:On,resolvedColors:A,onConfirm:Xn,onCancel:Yn,editProcessContent:l}),jsx("style",{children:`
|
|
25
|
+
`}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((b,a)=>{let w=Array.isArray(b.parts)?b.parts:[],i=w.filter(s=>s.type==="text").map(s=>s&&typeof s.text=="string"?s.text:"").join(`
|
|
26
|
+
`),T=w.filter(s=>s.type==="file"||s.type==="image").map(s=>{if(s.type==="image"){let g=typeof s.image=="string"?s.image:s.image?.toString?.()||"";return {id:g||`${b.id}-img-${Date.now()}`,name:s.name||"image",url:g,mimeType:s.mediaType||"image/jpeg",size:s.size||0}}else return {id:s.url||`${b.id}-file-${Date.now()}`,name:s.name||"file",url:s.url||"",mimeType:s.mediaType||"application/octet-stream",size:s.size||0}});return jsx("div",{style:{padding:"0 4px",display:"flex",flexDirection:"column",alignItems:b.role==="user"&&C?"flex-end":"stretch"},children:b.role==="user"?jsx("div",{style:{maxWidth:C?"80%":"100%"},children:jsx("div",{title:l("editor.clickToEdit"),onClick:()=>u(b,b.id,i,T),style:{maxWidth:C?"100%":"720px",borderRadius:C?"20px":"16px",padding:"12px 16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:C?o.inputBackground:o.accentColor,color:o.textColor,marginBottom:"16px",marginTop:"16px",position:"relative",border:C?`1px solid ${o.borderColor}`:"none"},onMouseEnter:s=>s.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor=C?o.inputBackground:o.accentColor,children:jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxs("div",{style:{flex:1},children:[i,T.length>0&&jsx(no,{attachments:T,resolvedColors:o})]}),jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsx(q,{IconComponent:S||Pencil,size:"14",strokeWidth:"2"})})]})})}):jsx(Zn,{parts:w,messageId:b.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:x,onUISuccess:I,addToolResult:d})},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 jt({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:l,attachments:u,formatBytes:c,handleRemoveAttachment:x,onFileInputChange:I,onSend:d,onStop:S,status:C,t:b,resolvedColors:a,fullPage:w}){let i=C==="streaming"||C==="submitted",T=u.length>0||e.trim().length>0;return w?jsxs("div",{style:{position:"relative",width:"100%",maxWidth:"768px",margin:"0 auto"},children:[jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"26px",padding:"14px 14px 14px 48px",backgroundColor:a.inputBackground,boxShadow:"0 0 0 1px rgba(0,0,0,0.05)",transition:"box-shadow 0.2s ease"},onFocus:s=>{},children:[jsx("div",{style:{position:"absolute",bottom:"10px",left:"12px",zIndex:10},children:jsx("button",{onClick:()=>r.current?.click(),disabled:o||l,style:{borderRadius:"50%",width:"33px",height:"33px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:a.textColor,opacity:o||l?.5:.7},"aria-label":b("input.attachFiles"),onMouseEnter:s=>{!o&&!l&&(s.currentTarget.style.backgroundColor=a.hoverBackground,s.currentTarget.style.opacity="1");},onMouseLeave:s=>{s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.opacity="0.7";},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:"M12 5v14M5 12h14"})})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[u.length>0&&jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",paddingBottom:"8px",marginLeft:"-4px"},children:u.map(s=>{let g=s.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 10px",backgroundColor:a.cardBackground,borderRadius:"8px",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.inputBackground},children:g?jsx("img",{src:s.url,alt:s.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"})})}),jsx("span",{title:s.name,style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:s.name}),jsx("button",{onClick:()=>x(s.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},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"})]})})]},s.id)})}),l&&jsxs("div",{style:{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:b("input.uploadingFiles")})]}),jsx("div",{style:{paddingRight:"40px",display:"flex",alignItems:"center"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:b("input.placeholder"),value:e,onChange:s=>t(s.target.value),onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),d());},disabled:l,style:{maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"16px",lineHeight:"1.5",outline:"none",border:"none",color:a.textColor,fontFamily:"inherit",overflow:"auto",padding:0,margin:0}})})]}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:o?jsx("button",{onClick:S,disabled:!i,"aria-label":b("input.stop"),style:{borderRadius:"50%",width:"36px",height:"36px",transition:"all 0.2s ease-out",backgroundColor:a.textColor,color:a.inputBackground,border:"none",opacity:i?1:.7,cursor:i?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},children:jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:jsx("rect",{width:"24",height:"24",rx:"2"})})}):jsx("button",{onClick:d,disabled:!T||l,"aria-label":b("input.send"),style:{borderRadius:"50%",width:"36px",height:"36px",transition:"all 0.2s ease-out",backgroundColor:!T||l?a.cardBackground:a.textColor,color:!T||l?a.mutedTextColor:a.inputBackground,border:"none",cursor:!T||l?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M5 12h14"}),jsx("path",{d:"M12 5l7 7-7 7"})]})})})]}),jsx("input",{ref:r,type:"file",multiple:true,onChange:I,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{textAlign:"center",padding:"8px 0",fontSize:"12px",color:a.mutedTextColor,opacity:.8},children:"AI can make mistakes. Please check important information."})]}):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(s=>{let g=s.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:s.url,alt:s.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:s.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:s.name}),jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(s.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[g&&jsx("a",{href:s.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:b("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(s.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:b("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"})]})})]})]},s.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:b("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:b("input.placeholder"),value:e,onChange:s=>t(s.target.value),onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),d());},disabled: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":b("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:!i,"aria-label":b("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:i?1:.4,cursor:i?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:s=>{i&&(s.currentTarget.style.backgroundColor="#ef444430",s.currentTarget.style.transform="scale(1.02)");},onMouseLeave:s=>{s.currentTarget.style.backgroundColor="#ef444420",s.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:d,disabled:!T||l,"aria-label":b("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:!T||l?a.mutedTextColor:a.primaryColor,cursor:!T||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!T||l?.5:1},onMouseEnter:s=>{T&&!l&&(s.currentTarget.style.borderColor=a.primaryColor,s.currentTarget.style.transform="scale(1.02)");},onMouseLeave:s=>{s.currentTarget.style.borderColor=a.borderColor,s.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 _t({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,c)=>{let x=o===c,I=u.prompt.length>80,d=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: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:d}),I&&jsxs("button",{onClick:S=>{S.stopPropagation(),l(x?null:c);},style:{marginTop:"8px",padding:"4px 8px",fontSize:"11px",color:n.primaryColor,backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:"4px",fontWeight:500},children:[x?"Show less":"Show more",jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:x?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},c)})})]})}function oo(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 c=Math.floor(l/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function xt({search:e,onSearchChange:t,chats:n,currentChatId:r,resolvedColors:o,onChatSelect:l,onChatDelete:u,className:c,style:x}){let I=e.trim()?n.filter(d=>(d.title||"").toLowerCase().includes(e.toLowerCase().trim())):n;return jsxs("div",{className:c,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",...x},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px",flexShrink:0},children:jsx("div",{style:{flex:"1"},children:jsx("input",{value:e,onChange:d=>t(d.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:d=>d.currentTarget.style.borderColor=o.primaryColor,onBlur:d=>d.currentTarget.style.borderColor=o.borderColor})})}),jsx("div",{style:{flex:1,overflowY:"auto",padding:"0"},children:I.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:I.map((d,S)=>jsx("div",{style:{borderTop:S>0?`1px solid ${o.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"8px 12px",backgroundColor:d.id===r?o.cardBackground:"transparent",transition:"background-color 0.2s"},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,overflow:"hidden"},onMouseEnter:C=>C.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:C=>C.currentTarget.style.backgroundColor="transparent",onClick:()=>l(d.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,fontWeight:d.id===r?600:400},children:d.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:oo(d.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:C=>{C.currentTarget.style.color="#ef4444",C.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",C.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:C=>{C.currentTarget.style.color=o.mutedTextColor,C.currentTarget.style.backgroundColor="transparent",C.currentTarget.style.borderColor="transparent";},onClick:C=>{C.stopPropagation(),u(d.id);},children:jsx(q,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},d.id))})})]})}function Vt({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:l,onSearchChange:u,onChatSelect:c,onChatDelete:x,loadChatsIndex:I,historyPopupRef:d}){if(!e)return null;let S=I(),C=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}),jsx("div",{ref:d,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",height:"60vh",maxHeight:"600px",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)",display:"flex",flexDirection:"column"},children:jsx(xt,{search:t,onSearchChange:u,chats:S,currentChatId:n,resolvedColors:o,onChatSelect:c,onChatDelete:x})})]});return typeof document<"u"&&document.body?createPortal(C,document.body):C}function ao({isOpen:e,historySearch:t,onSearchChange:n,chats:r,currentChatId:o,resolvedColors:l,onChatSelect:u,onChatDelete:c,onNewChat:x,isMobile:I=false}){return jsxs("div",{style:{width:e?"260px":"0px",opacity:e?1:0,marginLeft:e?0:-10,height:"100%",backgroundColor:l.backgroundColor,borderRight:e?`1px solid ${l.borderColor}`:"none",display:"flex",flexDirection:"column",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",overflow:"hidden",flexShrink:0,position:I?"fixed":"relative",zIndex:I?100:1,left:0,top:0,bottom:0,visibility:e?"visible":"hidden"},children:[jsx("div",{style:{padding:"12px",flexShrink:0,opacity:e?1:0,transition:"opacity 0.2s 0.1s"},children:jsxs("button",{onClick:x,style:{width:"100%",display:"flex",alignItems:"center",gap:"12px",padding:"10px 12px",borderRadius:"8px",border:`1px solid ${l.borderColor}`,backgroundColor:"transparent",color:l.textColor,cursor:"pointer",fontSize:"14px",transition:"all 0.2s",textAlign:"left"},onMouseEnter:d=>d.currentTarget.style.backgroundColor=l.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor="transparent",children:[jsx(q,{IconComponent:Plus,size:"16",strokeWidth:"2"}),jsx("span",{children:"New chat"})]})}),jsx(xt,{search:t,onSearchChange:n,chats:r,currentChatId:o,resolvedColors:l,onChatSelect:u,onChatDelete:c,style:{flex:1}})]})}function Xt({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?",c=o?.submit_button_label||"Edit",x=o?.cancel_button_label||"Cancel",I=o?.icon,d=typeof u=="function",S=d?u:null,C=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(q,{IconComponent:I,size:"20",strokeWidth:"2"})}):jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsx(q,{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:d&&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:b=>{b.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:b=>{b.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:b=>{b.currentTarget.style.opacity="0.9";},onMouseLeave:b=>{b.currentTarget.style.opacity="1";},children:c})]})]})]});return typeof document<"u"&&document.body?createPortal(C,document.body):C}function Er({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:l,borderColor:u,textColor:c,accentColor:x,baseUrl:I="",initialMessages:d=[],onMessagesChange:S,defaultOpen:C=true,floatingButtonPosition:b={bottom:24,right:24},HsafaTools:a={},HsafaUI:w={},componentAboveInput:i,editProcessContent:T,presetPrompts:s,onStart:g,onFinish:h,currentChat:k,onChatChanged:y,templateParams:m,fullPageChat:v=false,title:M,placeholder:f,emptyStateMessage:F}){let{dir:G,theme:V,baseUrl:me,setStreamingState:ge,setChatOpenState:se}=le(),P=t||V||"dark",U=I&&I.length>0?I:me||"",A={primaryColor:P==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:l||(P==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:u||(P==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(P==="dark"?"#EDEEF0":"#111827"),accentColor:x||(P==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:P==="dark"?"#6f7276":"#6B7280",inputBackground:P==="dark"?"#17181C":"#F3F4F6",cardBackground:P==="dark"?"#121318":"#FFFFFF",hoverBackground:P==="dark"?"#1c1e25":"#F3F4F6"},O=p=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":f||"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":F||"Start by sending a message to the agent.","general.agent":M||"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[p]||p,Q=zt({agentId:e,baseUrl:U,tools:a,uiComponents:w,templateParams:m,controlledChatId:k,onChatIdChange:k===void 0?p=>{y&&y(p);}:void 0,onStart:useCallback(p=>{g&&g(p);},[g]),onFinish:useCallback(p=>{h&&h(p);},[h]),onError:useCallback(p=>{console.error("Chat error:",p);},[]),initialMessages:d,onMessagesChange:S}),{input:ie,setInput:J,messages:ee,isLoading:j,status:xe,error:Ae,sendMessage:et,stop:tt,setMessages:te,notifyMessagesChange:R,chatId:B,setChatId:W,tools:N,uiComponents:Z,formHostRef:oe,formStateRef:be,cleanupForms:we,onUISuccess:nt,onUIError:Jt,chatApi:Zt}=Q,_=k!==void 0?k:B,Te=useCallback(p=>{k===void 0&&W(p),y&&y(p);},[k,W,y]);useEffect(()=>{k!==void 0&&k!==B&&W(k);},[k,B,W]);let{attachments:ze,uploading:Qt,fileInputRef:Ne,formatBytes:en,handleRemoveAttachment:tn,handleFileSelection:nn,clearAttachments:ot,setAttachments:on}=Rn(U),[rt,Ie]=useState(null),[at,rn]=useState(()=>{try{return pt(e).loadShowChatPreference(!!C)}catch{return !!C}}),[kt,Le]=useState(false),[wt,Tt]=useState(""),[It,St]=useState(0),an=useRef(null),sn=useRef(null),[ln,cn]=useState(new Set),[dn,Mt]=useState(false),[We,Et]=useState(null),Ue=useRef(null),un=In(j),[pn,co]=useState(false);useEffect(()=>{let p=()=>co(window.innerWidth<768);return p(),window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]);let Rt=Wt({agentId:e,chatId:_,messages:ee,isLoading:j,autoSave:true,autoRestore:false}),$=Rt.storage,mn=useMemo(()=>{try{return $.loadChatsIndex()}catch{return []}},[$,It]),Oe=useRef(false),Ge=useRef(null);useEffect(()=>{if(!Oe.current){if(k!==void 0){try{let p=$.loadChat(k),L=p&&Array.isArray(p.messages)?p.messages:[];if(L.length>0)try{te(L);}catch{}Ge.current=k;}catch{}try{$.saveCurrentChatId(k);}catch{}Oe.current=true;return}try{let p=$.loadCurrentChatId();if(p){Te(p);let L=$.loadChat(p),D=L&&Array.isArray(L.messages)?L.messages:[];try{te(D);}catch{}Ge.current=p;}}catch{}Oe.current=true;}},[k]),useEffect(()=>{if(Oe.current&&k!==void 0&&k!==Ge.current)try{let p=$.loadChat(k),L=p&&Array.isArray(p.messages)?p.messages:[];try{te(L);}catch{}Ge.current=k;try{$.saveCurrentChatId(k);}catch{}}catch{}},[k,$,te]),useEffect(()=>{if(Oe.current)try{$.saveCurrentChatId(_);}catch{}},[_,$]),useEffect(()=>{try{ge(_,j);}catch{}return ()=>{try{ge(_,!1);}catch{}}},[_,j,ge]),useEffect(()=>{try{se(_,at);}catch{}return ()=>{try{se(_,!1);}catch{}}},[_,at,se]);let gn=useCallback(async()=>{let p=ie.trim();if(!p&&ze.length===0||j)return;let L=[...ze];J(""),ot(),Ie(null),Ue.current&&Ue.current.focus();try{await et({text:p,files:L.map(D=>({type:"file",url:D.url,mediaType:D.mimeType||"application/octet-stream",...D.name?{name:D.name}:{},...D.size?{size:D.size}:{}}))});}catch(D){console.error("Failed to send message:",D),Ie("Failed to send message. Please try again.");}},[ie,ze,j,et,ot]),He=useCallback(()=>{if(j)return;we(),J(""),ot(),Ie(null);try{te([]);}catch{}let p=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Ge.current=p;try{Rt.createNewChat(()=>{Te(p);try{$.saveCurrentChatId(p);}catch{}});}catch{Te(p);try{$.saveCurrentChatId(p);}catch{}}},[j,ot,$,te,Te,we,Rt]),fn=useCallback(()=>{Le(p=>!p);},[]),uo=useCallback(()=>{rn(false);try{$.saveShowChatPreference(!1);}catch{}},[$]),hn=useCallback(async p=>{let L=p.target.files;L&&await nn(L,Ie),Ne.current&&(Ne.current.value="");},[nn,Ne]);useEffect(()=>{let p=Ue.current;if(!p)return;p.style.height="24px",p.offsetHeight,p.style.height="auto";let L=Math.min(p.scrollHeight,200);p.style.height=`${L}px`;},[ie]);let yn=useCallback((p,L,D,mo)=>{Et({id:L,text:D,attachments:mo||[]}),Mt(true);},[]),xn=useCallback(()=>{if(!(!We||j))try{let p=ee.findIndex(D=>D.id===We.id);if(p===-1)return;let L=ee.slice(0,p);try{te(L);}catch{}J(We.text),on(We.attachments),Mt(!1),Et(null),R();}catch(p){console.error("Failed to edit message:",p),Ie("Failed to edit message. Please try again.");}},[We,j,ee,te,on,R]),bn=useCallback(()=>{Mt(false),Et(null);},[]),po=jsxs("div",{style:{position:"fixed",inset:0,display:"flex",flexDirection:"row",backgroundColor:A.backgroundColor,color:A.textColor,overflow:"hidden"},children:[!pn&&jsx(ao,{isOpen:kt,historySearch:wt,onSearchChange:Tt,chats:mn,currentChatId:_,resolvedColors:A,onChatSelect:p=>{if(p&&p!==_&&(we(),Te(p),k===void 0)){try{$.saveCurrentChatId(p);}catch{}try{let L=$.loadChat(p),D=L&&Array.isArray(L.messages)?L.messages:[];try{te(D);}catch{}}catch{}}},onChatDelete:p=>{try{$.deleteChat(p),St(L=>L+1),p===_&&He();}catch{}},onNewChat:He,onClose:()=>Le(false)}),jsxs("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,position:"relative"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 20px",backgroundColor:A.backgroundColor,minHeight:"60px",zIndex:10},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[jsx("button",{ref:an,onClick:fn,style:{padding:"8px",borderRadius:"8px",border:"none",backgroundColor:"transparent",color:A.mutedTextColor,cursor:"pointer",transition:"all 0.2s",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor=A.hoverBackground,p.currentTarget.style.color=A.textColor;},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=A.mutedTextColor;},"aria-label":O("header.history"),children:jsxs("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",ry:"2"}),jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),jsx("h1",{style:{fontSize:"16px",fontWeight:600,margin:0,color:A.textColor},children:O("general.agent")})]}),jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:jsx("button",{onClick:He,disabled:j,style:{padding:"8px",borderRadius:"8px",border:"none",backgroundColor:"transparent",color:A.mutedTextColor,cursor:j?"not-allowed":"pointer",transition:"all 0.2s",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{j||(p.currentTarget.style.backgroundColor=A.hoverBackground,p.currentTarget.style.color=A.textColor);},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=A.mutedTextColor;},"aria-label":O("header.new"),children:jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M12 5v14M5 12h14"})})})})]}),jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[jsx("div",{ref:un,className:"chat-scroll-container",style:{flex:1,overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column",scrollBehavior:"smooth","--hsafa-primary":A.primaryColor,"--hsafa-border":A.borderColor,"--hsafa-card":A.cardBackground,"--hsafa-text":A.textColor,"--hsafa-muted":A.mutedTextColor,"--hsafa-bg":A.backgroundColor,"--hsafa-hover":A.hoverBackground,"--hsafa-input-bg":A.inputBackground,"--hsafa-accent":A.accentColor},children:jsx("div",{style:{maxWidth:"768px",width:"100%",margin:"0 auto",padding:"32px 24px",display:"flex",flexDirection:"column",gap:"24px"},children:ee.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"64px 0"},children:s&&s.length>0?jsx(_t,{prompts:s,onSelect:p=>J(p),resolvedColors:A,disabled:j}):jsx("div",{style:{padding:"64px 32px",textAlign:"center",color:A.mutedTextColor,fontSize:"16px"},children:O("messages.empty")})}):jsx(Gt,{chatMessages:ee,isLoading:j,openReasoningIds:ln,toggleReasoning:p=>cn(L=>{let D=new Set(L);return D.has(p)?D.delete(p):D.add(p),D}),resolvedColors:A,t:O,onUserMessageClick:yn,HsafaUI:Z,onUIError:Jt,onUISuccess:nt,addToolResult:p=>Zt?.addToolResult?.(p),editableMessageIcon:T?.message_icon,fullPage:true})})}),jsx("div",{style:{backgroundColor:A.backgroundColor,padding:"0 24px 24px",position:"relative",zIndex:20},children:jsxs("div",{style:{maxWidth:"768px",width:"100%",margin:"0 auto"},children:[i&&so.createElement(i,{}),rt&&jsxs("div",{style:{padding:"12px 16px",marginBottom:"12px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:rt}),jsx("button",{onClick:()=>Ie(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px",fontSize:"20px"},children:"\xD7"})]}),Ae&&jsxs("div",{style:{padding:"12px 16px",marginBottom:"12px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",Ae.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(jt,{input:ie,setInput:J,textareaRef:Ue,fileInputRef:Ne,isLoading:j,uploading:Qt,attachments:ze,formatBytes:en,handleRemoveAttachment:tn,onFileInputChange:hn,onSend:gn,onStop:()=>tt(),status:xe,t:O,resolvedColors:A,fullPage:true})]})})]})]}),pn&&jsx(Vt,{historyOpen:kt,historySearch:wt,currentChatId:_,refreshKey:It,resolvedColors:A,onClose:()=>Le(false),onSearchChange:Tt,onChatSelect:p=>{if(Le(false),p&&p!==_&&(we(),Te(p),k===void 0)){try{$.saveCurrentChatId(p);}catch{}try{let L=$.loadChat(p),D=L&&Array.isArray(L.messages)?L.messages:[];try{te(D);}catch{}}catch{}}},onChatDelete:p=>{try{$.deleteChat(p),St(L=>L+1),p===_&&He();}catch{}},loadChatsIndex:()=>mn,historyPopupRef:sn}),jsx(Xt,{isOpen:dn,resolvedColors:A,onConfirm:xn,onCancel:bn,editProcessContent:T}),jsx("style",{children:`
|
|
27
27
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
|
28
28
|
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
|
|
30
|
+
/* Markdown Table Styles */
|
|
31
|
+
.chat-scroll-container .x-markdown-dark table,
|
|
32
|
+
.chat-scroll-container .x-markdown-light table,
|
|
33
|
+
.chat-scroll-container table {
|
|
34
|
+
width: 100%;
|
|
35
|
+
border-collapse: separate;
|
|
36
|
+
border-spacing: 0;
|
|
37
|
+
border-radius: 8px;
|
|
38
|
+
overflow: hidden;
|
|
39
|
+
border: 1px solid var(--hsafa-border);
|
|
40
|
+
margin: 16px 0;
|
|
41
|
+
font-size: 14px;
|
|
42
|
+
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
|
43
|
+
}
|
|
44
|
+
.chat-scroll-container th,
|
|
45
|
+
.chat-scroll-container td {
|
|
46
|
+
padding: 12px 16px;
|
|
47
|
+
text-align: left;
|
|
48
|
+
border-bottom: 1px solid var(--hsafa-border);
|
|
49
|
+
border-right: 1px solid var(--hsafa-border);
|
|
50
|
+
line-height: 1.5;
|
|
51
|
+
}
|
|
52
|
+
.chat-scroll-container th:last-child,
|
|
53
|
+
.chat-scroll-container td:last-child {
|
|
54
|
+
border-right: none;
|
|
55
|
+
}
|
|
56
|
+
.chat-scroll-container tr:last-child td {
|
|
57
|
+
border-bottom: none;
|
|
58
|
+
}
|
|
59
|
+
.chat-scroll-container th {
|
|
60
|
+
background-color: var(--hsafa-hover);
|
|
61
|
+
color: var(--hsafa-text);
|
|
62
|
+
font-weight: 600;
|
|
63
|
+
font-size: 13px;
|
|
64
|
+
text-transform: uppercase;
|
|
65
|
+
letter-spacing: 0.02em;
|
|
66
|
+
}
|
|
67
|
+
.chat-scroll-container td {
|
|
68
|
+
background-color: transparent;
|
|
69
|
+
color: var(--hsafa-text);
|
|
70
|
+
}
|
|
71
|
+
/* Row hover effect */
|
|
72
|
+
.chat-scroll-container tr:hover td {
|
|
73
|
+
background-color: var(--hsafa-hover);
|
|
74
|
+
transition: background-color 0.15s ease;
|
|
75
|
+
}
|
|
76
|
+
/* Ensure code blocks don't overflow */
|
|
77
|
+
.chat-scroll-container pre {
|
|
78
|
+
border-radius: 8px;
|
|
79
|
+
overflow-x: auto;
|
|
80
|
+
margin: 12px 0;
|
|
81
|
+
border: 1px solid var(--hsafa-border);
|
|
82
|
+
}
|
|
83
|
+
`})]}),Cn=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:A.textColor,gap:"16px",zIndex:1e3,transform:at?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(Jn,{title:O("general.agent"),alwaysOpen:false,streaming:j,dir:G||"ltr",resolvedColors:A,onNew:He,onToggleHistory:fn,onClose:uo,historyBtnRef:an,t:O}),jsx("div",{ref:un,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":A.primaryColor,"--hsafa-border":A.borderColor,"--hsafa-card":A.cardBackground,"--hsafa-text":A.textColor,"--hsafa-muted":A.mutedTextColor,"--hsafa-bg":A.backgroundColor,"--hsafa-hover":A.hoverBackground,"--hsafa-input-bg":A.inputBackground,"--hsafa-accent":A.accentColor},children:ee.length===0?jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px 0"},children:s&&s.length>0?jsx(_t,{prompts:s,onSelect:p=>J(p),resolvedColors:A,disabled:j}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:O("messages.empty")})}):jsx(Gt,{chatMessages:ee,isLoading:j,openReasoningIds:ln,toggleReasoning:p=>cn(L=>{let D=new Set(L);return D.has(p)?D.delete(p):D.add(p),D}),resolvedColors:A,t:O,onUserMessageClick:yn,HsafaUI:Z,onUIError:Jt,onUISuccess:nt,addToolResult:p=>Zt?.addToolResult?.(p),editableMessageIcon:T?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[i&&so.createElement(i,{}),rt&&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:rt}),jsx("button",{onClick:()=>Ie(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),Ae&&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: ",Ae.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(jt,{input:ie,setInput:J,textareaRef:Ue,fileInputRef:Ne,isLoading:j,uploading:Qt,attachments:ze,formatBytes:en,handleRemoveAttachment:tn,onFileInputChange:hn,onSend:gn,onStop:()=>tt(),status:xe,t:O,resolvedColors:A})]}),jsx(Vt,{historyOpen:kt,historySearch:wt,currentChatId:_,refreshKey:It,resolvedColors:A,onClose:()=>Le(false),onSearchChange:Tt,onChatSelect:p=>{if(Le(false),p&&p!==_&&(we(),Te(p),k===void 0)){try{$.saveCurrentChatId(p);}catch{}try{let L=$.loadChat(p),D=L&&Array.isArray(L.messages)?L.messages:[];try{te(D);}catch{}}catch{}}},onChatDelete:p=>{try{$.deleteChat(p),St(L=>L+1),p===_&&He();}catch{}},loadChatsIndex:()=>$.loadChatsIndex(),historyPopupRef:sn}),jsx(Xt,{isOpen:dn,resolvedColors:A,onConfirm:xn,onCancel:bn,editProcessContent:T}),jsx("style",{children:`
|
|
84
|
+
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
|
85
|
+
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
|
86
|
+
|
|
87
|
+
/* Markdown Table Styles */
|
|
88
|
+
.chat-scroll-container .x-markdown-dark table,
|
|
89
|
+
.chat-scroll-container .x-markdown-light table,
|
|
90
|
+
.chat-scroll-container table {
|
|
91
|
+
width: 100%;
|
|
92
|
+
border-collapse: separate;
|
|
93
|
+
border-spacing: 0;
|
|
94
|
+
border-radius: 8px;
|
|
95
|
+
overflow: hidden;
|
|
96
|
+
border: 1px solid var(--hsafa-border);
|
|
97
|
+
margin: 16px 0;
|
|
98
|
+
font-size: 14px;
|
|
99
|
+
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
|
100
|
+
}
|
|
101
|
+
.chat-scroll-container th,
|
|
102
|
+
.chat-scroll-container td {
|
|
103
|
+
padding: 12px 16px;
|
|
104
|
+
text-align: left;
|
|
105
|
+
border-bottom: 1px solid var(--hsafa-border);
|
|
106
|
+
border-right: 1px solid var(--hsafa-border);
|
|
107
|
+
line-height: 1.5;
|
|
108
|
+
}
|
|
109
|
+
.chat-scroll-container th:last-child,
|
|
110
|
+
.chat-scroll-container td:last-child {
|
|
111
|
+
border-right: none;
|
|
112
|
+
}
|
|
113
|
+
.chat-scroll-container tr:last-child td {
|
|
114
|
+
border-bottom: none;
|
|
115
|
+
}
|
|
116
|
+
.chat-scroll-container th {
|
|
117
|
+
background-color: var(--hsafa-hover);
|
|
118
|
+
color: var(--hsafa-text);
|
|
119
|
+
font-weight: 600;
|
|
120
|
+
font-size: 13px;
|
|
121
|
+
text-transform: uppercase;
|
|
122
|
+
letter-spacing: 0.02em;
|
|
123
|
+
}
|
|
124
|
+
.chat-scroll-container td {
|
|
125
|
+
background-color: transparent;
|
|
126
|
+
color: var(--hsafa-text);
|
|
127
|
+
}
|
|
128
|
+
/* Row hover effect */
|
|
129
|
+
.chat-scroll-container tr:hover td {
|
|
130
|
+
background-color: var(--hsafa-hover);
|
|
131
|
+
transition: background-color 0.15s ease;
|
|
132
|
+
}
|
|
133
|
+
/* Ensure code blocks don't overflow */
|
|
134
|
+
.chat-scroll-container pre {
|
|
135
|
+
border-radius: 8px;
|
|
136
|
+
overflow-x: auto;
|
|
137
|
+
margin: 12px 0;
|
|
138
|
+
border: 1px solid var(--hsafa-border);
|
|
139
|
+
}
|
|
140
|
+
`})]});return v?jsxs(Fragment,{children:[jsx(Ve,{}),po]}):typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(Ve,{}),createPortal(Cn,document.body),jsx(kn,{show:!at,onClick:()=>{rn(true);try{$.saveShowChatPreference(!0);}catch{}},resolvedColors:A,floatingButtonPosition:b})]}):Cn}var lo={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};function Hr({children:e,theme:t="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:l,mutedTextColor:u,enableBorderAnimation:c=true,borderRadius:x=16,enableContentBorder:I=true,className:d="",enableMargin:S=true,chatWidth:C=420,dir:b="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:w,dir:i,theme:T}=le(),s=(b??i)||"ltr",g=(t??T)||"dark",h=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[k,y]=useState(false);useEffect(()=>{let V=setTimeout(()=>y(true),50);return ()=>clearTimeout(V)},[]);let m=lo[g],v={primaryColor:n||m.primaryColor,backgroundColor:r||m.backgroundColor,borderColor:o||m.borderColor,textColor:l||m.textColor,accentColor:m.accentColor,mutedTextColor:u||m.mutedTextColor,inputBackground:m.inputBackground,cardBackground:m.cardBackground,hoverBackground:m.hoverBackground},M=typeof x=="number"?`${x}px`:x,f=typeof C=="number"?`${C}px`:C,F=S&&w?s==="rtl"?{marginLeft:f}:{marginRight:f}:{},G=S&&w?`calc(100% - ${f})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:d,style:{width:G,height:"100%",transition:k?"all 0.2s ease-out":"none",padding:w&&I?"16px":"0",...F},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:k?"all 0.2s ease-out":"none",borderRadius:w?M:"0",border:w&&a&&c?"none":w?`1px solid ${v.borderColor}`:"none",padding:w&&a&&c?"1.5px":"0",background:w&&a&&c?`linear-gradient(120deg, ${v.primaryColor}dd 0%, ${v.primaryColor}88 25%, ${v.primaryColor}00 50%, ${v.primaryColor}88 75%, ${v.primaryColor}dd 100%)`:"transparent",backgroundSize:w&&a&&c?"300% 300%":"auto",animation:w&&a&&c?`${h.current}-border-flow 3s ease-in-out infinite`:"none",filter:w&&a&&c?`drop-shadow(0 0 10px ${v.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:w&&I?M:"0",backgroundColor:w&&I?v.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${v.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`
|
|
141
|
+
@keyframes ${h.current}-border-flow {
|
|
31
142
|
0% { background-position: 0% 50%; }
|
|
32
143
|
50% { background-position: 100% 50%; }
|
|
33
144
|
100% { background-position: 0% 50%; }
|
|
34
145
|
}
|
|
35
|
-
`})," "]})}var
|
|
146
|
+
`})," "]})}var Yt=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())}},Dr=new Yt;export{zr as Button,Hr as ContentContainer,Ve as CursorController,qe as FillActiveInput,kn as FloatingChatButton,Er as HsafaChat,xo as HsafaProvider,Dr as componentRegistry,Me as controlCursor,_e as getDomComponents,Me as guideCursor,In as useAutoScroll,Wt as useChatStorage,Rn as useFileUpload,le as useHsafa,zt as useHsafaAgent,er as useMessageEditor};//# sourceMappingURL=index.js.map
|
|
36
147
|
//# sourceMappingURL=index.js.map
|