@hsafa/ui-sdk 5.5.6 → 5.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Wo,{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 Io(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,m,i,w=1]=o;return {r:c,g:m,b:i,a:w}}function So({r:e,g:t,b:n}){let r=[e,t,n].map(o=>o/255).map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*r[0]+.7152*r[1]+.0722*r[2]}function Mo(e){let t=e?sn(e):null;return !t||t.a===0?false:So(t)<.5}function Eo(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let m=getComputedStyle(n).backgroundColor,i=sn(m);if(i&&i.a>0)return m;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Tt(e,t,n){let r=Eo(t,n),o=Mo(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 Qe(e,t,n,r,o="ease-in-out",c="curve",m=.25,i="auto",w){an(),wt(e);let S=performance.now(),d=o==="linear"?x=>x:Io,T=c!=="straight",v={x:0,y:0};if(T){let x=n.x-t.x,a=n.y-t.y,b=Math.hypot(x,a)||1,s=(t.x+n.x)/2,l=(t.y+n.y)/2,u=-a/b,h=x/b,f=1;i==="left"?f=-1:i==="right"?f=1:f=Math.random()<.5?-1:1;let k=Re(m,0,1)*b;v={x:s+f*u*k,y:l+f*h*k};}return new Promise(x=>{function a(b){let s=Re((b-S)/r,0,1),l=d(s),u,h;if(T){let C=1-l;u=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 u=t.x+(n.x-t.x)*l,h=t.y+(n.y-t.y)*l;let k=.35*(1-l),y=Math.sin(b*.02)*k,p=Math.cos(b*.018)*k;e.style.left=`${u+y}px`,e.style.top=`${h+p}px`,Tt(e,u+y,h+p),w&&w({x:u+y,y:h+p,t:s,now:b}),s<1?requestAnimationFrame(a):x();}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",m=t==="pointerup"||t==="mouseup",i={button:0,buttons:c?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let w=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...i});e.dispatchEvent(w);}else {let w=new MouseEvent(t,i);e.dispatchEvent(w);}}catch{let c=new MouseEvent(t,o);e.dispatchEvent(c);}}function ln(e){return e&&typeof e=="object"&&e.nodeType===1}function Ao(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=Ao(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 Ro(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await To();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),wt(o),an();let c=parseFloat(o.style.left||"20")||20,m=parseFloat(o.style.top||"20")||20;Tt(o,c,m);for(let i of n){let{durationMs:w=800,easing:S="ease-in-out",offset:d,highlight:T=true,path:v="curve",curveStrength:x=.25,curveDirection:a="auto",anchor:b,cursorHotspot:s,dragTo:l}=i.options??{},u=i.action??i.options?.action??"none",h=performance.now(),f=nn(i.target),k=null,y=null;if(f.kind==="element"&&f.element?(y=f.element,o.classList.remove("visible"),y.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Co(y,1500,180),wt(o),k=on(y,b)):f.kind==="position"&&f.point&&(k=f.point),!k){r.push({ok:false,action:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),error:"Target not found"});continue}let p={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},C=rn(tn(k,d));await Qe(o,p,C,w,S,v,x,a);let M=C.x-p.x,g=C.y-p.y,R=Math.hypot(M,g)||1,N=M/R,U=g/R,te=Math.min(6,Math.max(3,R*.02)),ye={x:C.x+N*te,y:C.y+U*te};await Qe(o,C,ye,Math.max(70,w*.1),"ease-out","straight",0,"right"),await Qe(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(u==="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 _=y??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(u==="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,d)),V={x:C.x,y:C.y},ie=y??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 Qe(o,V,_,Math.max(200,w),S,v,x,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:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),clickedElementId:ue});}catch(A){r.push({ok:false,action:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),error:A?.message??String(A)});}}return xo(o,2e3),{ok:r.every(i=>i.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var nt=Ro;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 m=Array.isArray(c.steps)&&c.steps.length?c.steps[c.steps.length-1]:void 0,i=m?.clickedElementId?` (clicked element id: ${m.clickedElementId})`:"",w=t||m?.action||"none";return {success:true,message:w==="click"?`Cursor moved and clicked successfully${i}`:w==="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 Do({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:Do}}function pn(e,t,n,r,o,c){let m=n.get(t);if(m){let f=m.parentElement,k=document.querySelector(`[data-get-from-user-host="${t}"]`);if(k&&f!==k){try{f?.removeChild(m);}catch{}k.innerHTML="",k.appendChild(m);}}else {m=document.createElement("div"),m.className="hsafa-inline-form";let f=document.querySelector(`[data-get-from-user-host="${t}"]`);f?(f.innerHTML="",f.appendChild(m)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(m),n.set(t,m);}let i=e?.title||"Provide input",w=e?.description||"",S=e?.submitLabel||"Submit",d=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};m.innerHTML="";let x=document.createElement("form");x.style.margin="12px 0",x.style.padding="14px",x.style.border="1px solid var(--hsafa-border, #2A2C33)",x.style.borderRadius="12px",x.style.background="var(--hsafa-card, #121318)",x.style.color="var(--hsafa-text, #EDEEF0)",x.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,x.appendChild(a),w){let f=document.createElement("div");f.style.fontSize="12px",f.style.opacity="0.8",f.style.marginBottom="10px",f.textContent=w,x.appendChild(f);}T.forEach(f=>{let k=document.createElement("div");if(k.style.margin="10px 0",f.label){let g=document.createElement("label");g.style.display="block",g.style.fontSize="12px",g.style.marginBottom="6px",g.style.opacity="0.9",g.textContent=f.label,k.appendChild(g);}let y,p=(f.type||"text").toLowerCase();if(p==="textarea"){let g=document.createElement("textarea");g.placeholder=f.placeholder||"",g.value=f.value??"",g.style.width="100%",g.style.minHeight="72px",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",y=g;}else if(p==="select"&&Array.isArray(f.options)){let g=document.createElement("select");g.style.width="100%",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",f.options.forEach(R=>{let N=document.createElement("option");N.value=String(R.value),N.text=String(R.label??R.value),g.appendChild(N);}),g.value=f.value??"",y=g;}else if(p==="checkbox"){let g=document.createElement("input");g.type="checkbox",g.checked=!!f.value,g.style.transform="scale(1.1)",y=g;}else {let g=document.createElement("input");g.type=p,g.placeholder=f.placeholder||"",g.value=f.value??"",g.style.width="100%",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",y=g;}let C=f.id||"value";y.dataset.fieldId=C;let M=v.values&&Object.prototype.hasOwnProperty.call(v.values,C)?v.values[C]:void 0;typeof M<"u"&&(y.type==="checkbox"?y.checked=!!M:y.value=String(M)),(v.submitted||v.skipped)&&(y.setAttribute("disabled","true"),y.style.opacity="0.7"),k.appendChild(y),x.appendChild(k);});let b=String(S).trim(),s=String(d).trim(),l=!!(b||s),u=null,h=null;if(l){let f=document.createElement("div");f.style.display="flex",f.style.gap="8px",f.style.marginTop="10px",u=document.createElement("button"),u.type="submit",u.textContent=b||"Submit",u.style.padding="6px 10px",u.style.borderRadius="8px",u.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",u.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",f.appendChild(u),f.appendChild(h),x.appendChild(f);}if(x.onsubmit=f=>{f.preventDefault();let k={};x.querySelectorAll("[data-field-id]").forEach(y=>{let p=y.dataset.fieldId||"value";y.type==="checkbox"?k[p]=y.checked:k[p]=y.value??"";}),r.set(t,{submitted:true,skipped:false,values:k}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:k}}),x.querySelectorAll("[data-field-id]").forEach(y=>{y.disabled=true,y.style.opacity="0.7";}),u&&(u.textContent=`${b||"Submit"} \u2713`,u.style.opacity="0.8",u.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}}),x.querySelectorAll("[data-field-id]").forEach(f=>{f.disabled=true,f.style.opacity="0.7";}),h&&(h.textContent=`${s||"Skip"} \u2713`,h.style.opacity="0.8",h.disabled=true),u&&(u.disabled=true);}),v.submitted||v.skipped){let f=document.createElement("div");f.style.marginTop="10px",f.style.fontSize="12px",f.style.display="flex",f.style.alignItems="center",f.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",v.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"),f.appendChild(k),x.appendChild(f);try{u&&(u.disabled=!0,u.style.opacity="0.8",v.submitted&&(u.textContent=`${b||"Submit"} \u2713`)),h&&(h.disabled=!0,h.style.opacity="0.8",v.skipped&&(h.textContent=`${s||"Skip"} \u2713`));}catch{}}m.appendChild(x);}function mn(e){return !!e&&typeof e=="object"}function gn(e,t,n){let r=useRef(new Map),o=useRef(new Map),c=useRef(new Map),m=useRef(t),i=useRef(n);m.current=t,i.current=n,useEffect(()=>{e.forEach(w=>{if(!mn(w)||w.role!=="assistant")return;(Array.isArray(w.parts)?w.parts:[]).forEach(d=>{if(!mn(d)||typeof d.toolCallId!="string"||!d.toolCallId)return;let T=typeof d.toolName=="string"?d.toolName:void 0,v=typeof d.type=="string"?d.type:"";if(!T&&v.startsWith("tool-")&&(T=v.replace(/^tool-/,"")),!T)return;let x=m.current[T];try{let a=String(d.state||d.status||""),b=o.current.get(d.toolCallId);if(a&&a!==b&&x&&typeof x=="object"){o.current.set(d.toolCallId,a);let s=d.input??d.args??{},l={toolCallId:d.toolCallId,toolName:T},u=x;a==="input-streaming"&&typeof u.inputting_start=="function"&&u.inputting_start(s,l),a==="input-available"&&typeof u.running_start=="function"&&u.running_start(s,l);}}catch{}if(x&&typeof x=="object"&&x.executeEachToken&&x.tool){let a=d.input??d.args??{},b=JSON.stringify(a),s=r.current.get(d.toolCallId);if(b!==s&&b!=="{}"){r.current.set(d.toolCallId,b);try{if(T==="requestInput")i.current(a,d.toolCallId);else {let u=(c.current.get(d.toolCallId)||0)+1;c.current.set(d.toolCallId,u),u>1&&x.tool({...a,toolCallNumber:u-1});}}catch{}}}});});},[e]);}function St(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:c,onFinish:m,onError:i,initialMessages:w=[],onMessagesChange:S,controlledChatId:d,onChatIdChange:T,templateParams:v}=e,{baseUrl:x,setCurrentChatId:a}=ne(),b=n&&n.length>0?n:x||"",[s,l]=useState(""),[u,h]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),f=d??u,k=useCallback(E=>{d===void 0&&h(E),T&&T(E);},[d,T]);useEffect(()=>{try{a(f);}catch{}return ()=>{try{a(void 0);}catch{}}},[f,a]);let y=useMemo(()=>Xt(b,t,f,v),[b,t,f,v]),p=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}}m?.({...E,chatId:f,assistantMessageId:F});},[m,f]),C=useCallback(E=>{console.error("Chat error:",E),i?.(E);},[i]),M=useMemo(()=>cn(),[]),g=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=g[E];return F?typeof F=="object"&&"tool"in F?F.tool:typeof F=="function"?F:null:null},[g]),O=useChat({transport:y,onFinish:p,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,gn($,g,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(()=>{w&&w.length>0&&$.length===0&&console.log("Initial messages:",w);},[w,$.length]);let q=ce==="submitted"||ce==="streaming",Ke=useCallback(()=>{S&&S($,f);},[S,$,f]),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:f};c(J);}await he({text:H,files:z});}catch(J){throw console.error("Failed to send message:",J),J}}},[s,q,he,c,f]),Ie=useCallback(()=>{if(q)return;ye(),l("");try{O?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;k(E);},[q,O,ye,k]),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:Ke,chatApi:O,chatId:f,setChatId:k,tools:g,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`,m=()=>{try{let h=localStorage.getItem(n);return h?JSON.parse(h):[]}catch{return []}},i=h=>{try{localStorage.setItem(n,JSON.stringify(h));}catch{}},w=h=>{try{let f=localStorage.getItem(r(h));return f?JSON.parse(f):null}catch{return null}},S=h=>{try{localStorage.setItem(r(h.id),JSON.stringify(h));}catch{}},d=h=>{let f=m(),k=f.findIndex(y=>y.id===h.id);k>=0?f[k]=h:f.unshift(h),i(f);},T=h=>{let k=m().filter(y=>y.id!==h);i(k);},v=h=>{try{localStorage.removeItem(r(h));}catch{}};return {loadChatsIndex:m,saveChatsIndex:i,loadChat:w,saveChat:S,upsertChatMeta:d,deleteChatMeta:T,deleteChatData:v,deleteChat:h=>{v(h),T(h);},loadShowChatPreference:h=>{try{let f=localStorage.getItem(c);return f!==null?f==="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:m=true}=e,i=useMemo(()=>rt(t),[t]),[w,S]=useState([]),[d,T]=useState(null),v=useRef(false),x=useRef(false),a=useCallback(()=>{try{let y=i.loadChatsIndex();S(y);let p=y.find(C=>C.id===n);T(p||null);}catch(y){console.error("Failed to refresh chat list:",y);}},[i,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!m||x.current)){try{i.loadCurrentChatId()&&(v.current=!0);}catch(y){console.error("Failed to restore chat:",y);}x.current=true;}},[i,m]),useEffect(()=>{if(!(!c||r.length===0))if(v.current){if(!o){let y=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:y}),a());}catch(p){console.error("Failed to save chat:",p);}}}else {let y=r.find(p=>p.role==="user");if(y){let p="";if(Array.isArray(y.parts)){let g=y.parts.find(R=>R&&R.type==="text");p=g&&typeof g.text=="string"?g.text:"";}let C=(p||"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(g){console.error("Failed to create chat:",g);}}}},[]);let b=useRef(false);useEffect(()=>{if(o){b.current=true;return}if(b.current&&c){b.current=false;try{let y=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:y});else {let M="",g=Array.isArray(r)?r.find(N=>N&&N.role==="user"):void 0;if(g&&Array.isArray(g.parts)){let N=g.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:y,updatedAt:y});try{i.saveCurrentChatId(n);}catch{}v.current=!0;}a();}catch(y){console.error("Failed to save chat on completion:",y);}}},[o,r,n,t,i,c,a]);let s=useCallback(y=>{try{let p=i.loadChat(y);return p?{id:p.id,messages:p.messages,agentId:p.agentId||t}:null}catch(p){return console.error("Failed to load chat:",p),null}},[i,t]),l=useCallback(()=>{if(r.length!==0)try{let y=Date.now();i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);C&&(i.upsertChatMeta({...C,updatedAt:y}),a());}catch(y){console.error("Failed to save chat:",y);}},[i,n,r,t,a]),u=useCallback(y=>{try{i.deleteChat(y),a();}catch(p){console.error("Failed to delete chat:",p);}},[i,a]),h=useCallback((y,p)=>{if(y!==n)try{v.current=!0,i.saveCurrentChatId(y);let C=i.loadChat(y),M=C&&Array.isArray(C.messages)?C.messages:[];p(M),a();}catch(C){console.error("Failed to switch chat:",C);}},[i,n,a]),f=useCallback(y=>{v.current=false,y();},[]),k=useCallback(y=>{if(!y.trim())return w;let p=y.toLowerCase();return w.filter(C=>C.title.toLowerCase().includes(p))},[w]);return {chatList:w,currentChatMeta:d,refreshChatList:a,loadChat:s,saveCurrentChat:l,deleteChat:u,switchToChat:h,createNewChat:f,searchChats:k,storage:i}}function zo(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:c}=e,{baseUrl:m}=ne(),i=c||m||"",[w,S]=useState(null),[d,T]=useState(""),[v,x]=useState([]),[a,b]=useState(false),s=useCallback((y,p,C=[])=>{S(y),T(p),x(C);},[]),l=useCallback(()=>{S(null),T(""),x([]);},[]),u=useCallback(async y=>{if(!n)try{let p=t.findIndex(M=>M.id===y);if(p===-1)return;let C=t.slice(0,p);o(C),await r({text:d.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(p){throw console.error("Failed to save edit:",p),p}},[n,t,r,d,v,o,l]),h=useCallback(y=>w===y,[w]),f=useCallback(async y=>{if(!i){console.warn("baseUrl not provided, cannot upload attachments");return}b(true);try{let p=Array.from(y).map(async M=>{if(M.size>26214400)throw new Error(`${M.name} is too large (max 25MB)`);let g=new FormData;g.append("file",M);let R=await fetch(`${i}/api/upload`,{method:"POST",body:g});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(p);x(M=>[...M,...C]);}catch(p){throw console.error("Failed to upload files:",p),p}finally{b(false);}},[i]),k=useCallback(y=>{x(p=>p.filter(C=>C.id!==y));},[]);return {editingMessageId:w,editingText:d,setEditingText:T,editAttachments:v,setEditAttachments:x,editUploading:a,startEdit:s,cancelEdit:l,saveEdit:u,isEditing:h,addEditAttachments:f,removeEditAttachment:k}}function j({IconComponent:e,...t}){return Wo.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:m=>{o||(m.currentTarget.style.backgroundColor=r.hoverBackground,m.currentTarget.style.color=r.textColor);},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function xn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:c,onToggleHistory:m,onClose:i,historyBtnRef:w,t:S}){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:S("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:w,"aria-label":S("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:m,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:S("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 Ko=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"]},Vo=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}},Xo=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function bn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:m,onUISuccess:i,addToolResult:w}){let S=[],d=[],T,v,x=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){d.push(a.text),T||(T=a.startDate),v=a.endDate,a.state==="done"&&(x=true);continue}if(a.type==="text"&&typeof a.text=="string"){d.length&&(S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),d=[],T=void 0,v=void 0,x=false),S.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"){d.length&&(S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),d=[],T=void 0,v=void 0,x=false);let l=String(b?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");l==="requestInput"?S.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}):S.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 d.length&&S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),S.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[S.map((a,b)=>{let s=`${t}-${b}`,l=n.has(s);if(a.type==="reasoning"){let p=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",C=a.texts&&a.texts.length>0&&a.texts.some(g=>g.trim().length>0),M=()=>{C&&r(s);};return p&&!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:[!p&&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:p?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:p?"auto":"200% 100%",backgroundClip:p?"unset":"text",WebkitBackgroundClip:p?"unset":"text",WebkitTextFillColor:p?o.mutedTextColor:"transparent",animation:p?void 0:"shimmer 2s ease-in-out infinite"},children:p?"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||!p?"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:(!p&&l?a.texts:p?l?a.texts:[]:[a.texts[a.texts.length-1]]).map((g,R)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(We,{content:g,theme:"dark",streaming:!p})},`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 p=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:p})},s)}let{color:u,text:h}=Ko(a.status),f=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 k=c?.[a.toolName||""];if(k)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:m,onSuccess:i,children:jsx(k,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:w})})},s);let y=Vo(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:u,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:u,animation:f?"pulse 1.5s ease-in-out infinite":void 0}}),h]}),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:Xo(y.toolName)})]})})},s)}),jsx("style",{children:`
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 Io(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,m,i,w=1]=o;return {r:c,g:m,b:i,a:w}}function So({r:e,g:t,b:n}){let r=[e,t,n].map(o=>o/255).map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*r[0]+.7152*r[1]+.0722*r[2]}function Mo(e){let t=e?sn(e):null;return !t||t.a===0?false:So(t)<.5}function Eo(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let m=getComputedStyle(n).backgroundColor,i=sn(m);if(i&&i.a>0)return m;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Tt(e,t,n){let r=Eo(t,n),o=Mo(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 Qe(e,t,n,r,o="ease-in-out",c="curve",m=.25,i="auto",w){an(),wt(e);let S=performance.now(),d=o==="linear"?x=>x:Io,T=c!=="straight",v={x:0,y:0};if(T){let x=n.x-t.x,a=n.y-t.y,b=Math.hypot(x,a)||1,s=(t.x+n.x)/2,l=(t.y+n.y)/2,u=-a/b,h=x/b,f=1;i==="left"?f=-1:i==="right"?f=1:f=Math.random()<.5?-1:1;let k=Re(m,0,1)*b;v={x:s+f*u*k,y:l+f*h*k};}return new Promise(x=>{function a(b){let s=Re((b-S)/r,0,1),l=d(s),u,h;if(T){let C=1-l;u=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 u=t.x+(n.x-t.x)*l,h=t.y+(n.y-t.y)*l;let k=.35*(1-l),y=Math.sin(b*.02)*k,p=Math.cos(b*.018)*k;e.style.left=`${u+y}px`,e.style.top=`${h+p}px`,Tt(e,u+y,h+p),w&&w({x:u+y,y:h+p,t:s,now:b}),s<1?requestAnimationFrame(a):x();}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",m=t==="pointerup"||t==="mouseup",i={button:0,buttons:c?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let w=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...i});e.dispatchEvent(w);}else {let w=new MouseEvent(t,i);e.dispatchEvent(w);}}catch{let c=new MouseEvent(t,o);e.dispatchEvent(c);}}function ln(e){return e&&typeof e=="object"&&e.nodeType===1}function Ao(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=Ao(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 Ro(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await To();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),wt(o),an();let c=parseFloat(o.style.left||"20")||20,m=parseFloat(o.style.top||"20")||20;Tt(o,c,m);for(let i of n){let{durationMs:w=800,easing:S="ease-in-out",offset:d,highlight:T=true,path:v="curve",curveStrength:x=.25,curveDirection:a="auto",anchor:b,cursorHotspot:s,dragTo:l}=i.options??{},u=i.action??i.options?.action??"none",h=performance.now(),f=nn(i.target),k=null,y=null;if(f.kind==="element"&&f.element?(y=f.element,o.classList.remove("visible"),y.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Co(y,1500,180),wt(o),k=on(y,b)):f.kind==="position"&&f.point&&(k=f.point),!k){r.push({ok:false,action:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),error:"Target not found"});continue}let p={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},C=rn(tn(k,d));await Qe(o,p,C,w,S,v,x,a);let M=C.x-p.x,g=C.y-p.y,R=Math.hypot(M,g)||1,N=M/R,U=g/R,te=Math.min(6,Math.max(3,R*.02)),ye={x:C.x+N*te,y:C.y+U*te};await Qe(o,C,ye,Math.max(70,w*.1),"ease-out","straight",0,"right"),await Qe(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(u==="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 _=y??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(u==="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,d)),V={x:C.x,y:C.y},ie=y??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 Qe(o,V,_,Math.max(200,w),S,v,x,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:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),clickedElementId:ue});}catch(A){r.push({ok:false,action:u,targetKind:f.kind,durationMs:Math.round(performance.now()-h),error:A?.message??String(A)});}}return xo(o,2e3),{ok:r.every(i=>i.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var nt=Ro;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 m=Array.isArray(c.steps)&&c.steps.length?c.steps[c.steps.length-1]:void 0,i=m?.clickedElementId?` (clicked element id: ${m.clickedElementId})`:"",w=t||m?.action||"none";return {success:true,message:w==="click"?`Cursor moved and clicked successfully${i}`:w==="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 Do({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:Do}}function pn(e,t,n,r,o,c){let m=n.get(t);if(m){let f=m.parentElement,k=document.querySelector(`[data-get-from-user-host="${t}"]`);if(k&&f!==k){try{f?.removeChild(m);}catch{}k.innerHTML="",k.appendChild(m);}}else {m=document.createElement("div"),m.className="hsafa-inline-form";let f=document.querySelector(`[data-get-from-user-host="${t}"]`);f?(f.innerHTML="",f.appendChild(m)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(m),n.set(t,m);}let i=e?.title||"Provide input",w=e?.description||"",S=e?.submitLabel||"Submit",d=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};m.innerHTML="";let x=document.createElement("form");x.style.margin="12px 0",x.style.padding="14px",x.style.border="1px solid var(--hsafa-border, #2A2C33)",x.style.borderRadius="12px",x.style.background="var(--hsafa-card, #121318)",x.style.color="var(--hsafa-text, #EDEEF0)",x.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,x.appendChild(a),w){let f=document.createElement("div");f.style.fontSize="12px",f.style.opacity="0.8",f.style.marginBottom="10px",f.textContent=w,x.appendChild(f);}T.forEach(f=>{let k=document.createElement("div");if(k.style.margin="10px 0",f.label){let g=document.createElement("label");g.style.display="block",g.style.fontSize="12px",g.style.marginBottom="6px",g.style.opacity="0.9",g.textContent=f.label,k.appendChild(g);}let y,p=(f.type||"text").toLowerCase();if(p==="textarea"){let g=document.createElement("textarea");g.placeholder=f.placeholder||"",g.value=f.value??"",g.style.width="100%",g.style.minHeight="72px",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",y=g;}else if(p==="select"&&Array.isArray(f.options)){let g=document.createElement("select");g.style.width="100%",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",f.options.forEach(R=>{let N=document.createElement("option");N.value=String(R.value),N.text=String(R.label??R.value),g.appendChild(N);}),g.value=f.value??"",y=g;}else if(p==="checkbox"){let g=document.createElement("input");g.type="checkbox",g.checked=!!f.value,g.style.transform="scale(1.1)",y=g;}else {let g=document.createElement("input");g.type=p,g.placeholder=f.placeholder||"",g.value=f.value??"",g.style.width="100%",g.style.padding="10px 12px",g.style.border="1px solid var(--hsafa-border, #2A2C33)",g.style.borderRadius="10px",g.style.background="var(--hsafa-input-bg, #17181C)",g.style.color="inherit",y=g;}let C=f.id||"value";y.dataset.fieldId=C;let M=v.values&&Object.prototype.hasOwnProperty.call(v.values,C)?v.values[C]:void 0;typeof M<"u"&&(y.type==="checkbox"?y.checked=!!M:y.value=String(M)),(v.submitted||v.skipped)&&(y.setAttribute("disabled","true"),y.style.opacity="0.7"),k.appendChild(y),x.appendChild(k);});let b=String(S).trim(),s=String(d).trim(),l=!!(b||s),u=null,h=null;if(l){let f=document.createElement("div");f.style.display="flex",f.style.gap="8px",f.style.marginTop="10px",u=document.createElement("button"),u.type="submit",u.textContent=b||"Submit",u.style.padding="6px 10px",u.style.borderRadius="8px",u.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",u.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",f.appendChild(u),f.appendChild(h),x.appendChild(f);}if(x.onsubmit=f=>{f.preventDefault();let k={};x.querySelectorAll("[data-field-id]").forEach(y=>{let p=y.dataset.fieldId||"value";y.type==="checkbox"?k[p]=y.checked:k[p]=y.value??"";}),r.set(t,{submitted:true,skipped:false,values:k}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:k}}),x.querySelectorAll("[data-field-id]").forEach(y=>{y.disabled=true,y.style.opacity="0.7";}),u&&(u.textContent=`${b||"Submit"} \u2713`,u.style.opacity="0.8",u.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}}),x.querySelectorAll("[data-field-id]").forEach(f=>{f.disabled=true,f.style.opacity="0.7";}),h&&(h.textContent=`${s||"Skip"} \u2713`,h.style.opacity="0.8",h.disabled=true),u&&(u.disabled=true);}),v.submitted||v.skipped){let f=document.createElement("div");f.style.marginTop="10px",f.style.fontSize="12px",f.style.display="flex",f.style.alignItems="center",f.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",v.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"),f.appendChild(k),x.appendChild(f);try{u&&(u.disabled=!0,u.style.opacity="0.8",v.submitted&&(u.textContent=`${b||"Submit"} \u2713`)),h&&(h.disabled=!0,h.style.opacity="0.8",v.skipped&&(h.textContent=`${s||"Skip"} \u2713`));}catch{}}m.appendChild(x);}function mn(e){return !!e&&typeof e=="object"}function gn(e,t,n){let r=useRef(new Map),o=useRef(new Map),c=useRef(new Map),m=useRef(t),i=useRef(n);m.current=t,i.current=n,useEffect(()=>{e.forEach(w=>{if(!mn(w)||w.role!=="assistant")return;(Array.isArray(w.parts)?w.parts:[]).forEach(d=>{if(!mn(d)||typeof d.toolCallId!="string"||!d.toolCallId)return;let T=typeof d.toolName=="string"?d.toolName:void 0,v=typeof d.type=="string"?d.type:"";if(!T&&v.startsWith("tool-")&&(T=v.replace(/^tool-/,"")),!T)return;let x=m.current[T];try{let a=String(d.state||d.status||""),b=o.current.get(d.toolCallId);if(a&&a!==b&&x&&typeof x=="object"){o.current.set(d.toolCallId,a);let s=d.input??d.args??{},l={toolCallId:d.toolCallId,toolName:T},u=x;a==="input-streaming"&&typeof u.inputting_start=="function"&&u.inputting_start(s,l),a==="input-available"&&typeof u.running_start=="function"&&u.running_start(s,l);}}catch{}if(x&&typeof x=="object"&&x.executeEachToken&&x.tool){let a=d.input??d.args??{},b=JSON.stringify(a),s=r.current.get(d.toolCallId);if(b!==s&&b!=="{}"){r.current.set(d.toolCallId,b);try{if(T==="requestInput")i.current(a,d.toolCallId);else {let u=(c.current.get(d.toolCallId)||0)+1;c.current.set(d.toolCallId,u),u>1&&x.tool({...a,toolCallNumber:u-1});}}catch{}}}});});},[e]);}function St(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:c,onFinish:m,onError:i,initialMessages:w=[],onMessagesChange:S,controlledChatId:d,onChatIdChange:T,templateParams:v}=e,{baseUrl:x,setCurrentChatId:a}=ne(),b=n&&n.length>0?n:x||"",[s,l]=useState(""),[u,h]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),f=d??u,k=useCallback(E=>{d===void 0&&h(E),T&&T(E);},[d,T]);useEffect(()=>{try{a(f);}catch{}return ()=>{try{a(void 0);}catch{}}},[f,a]);let y=useMemo(()=>Xt(b,t,f,v),[b,t,f,v]),p=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}}m?.({...E,chatId:f,assistantMessageId:F});},[m,f]),C=useCallback(E=>{console.error("Chat error:",E),i?.(E);},[i]),M=useMemo(()=>cn(),[]),g=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=g[E];return F?typeof F=="object"&&"tool"in F?F.tool:typeof F=="function"?F:null:null},[g]),O=useChat({transport:y,onFinish:p,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(J){console.error("requestInput render error",J);}return}let z=E.toolName==="ui",H=N&&E.toolName in N;if((z||H)&&!F){B.current.add(E.toolCallId);return}if(F)try{let J=await F(E.input);O.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,output:J});}catch(J){O.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,state:"output-error",errorText:J?.message||String(J)});}}}),{messages:$,sendMessage:he,status:ce,stop:xe,error:mt}=O;A.current=O,gn($,g,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 J=H?.toolCallId||"";if(!J)return;E.add(J);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(J,be);}let X=H?.input||H?.args||{};F.push({input:X,toolCallId:J});});}),U.current.forEach((z,H)=>{if(!E.has(H)){let Z=U.current.get(H);try{Z?.remove();}catch{}U.current.delete(H),te.current.delete(H);}}),F.length>0){let z=requestAnimationFrame(()=>{F.forEach(({input:H,toolCallId:Z})=>{try{ue(H,Z);}catch{}});});return ()=>cancelAnimationFrame(z)}}catch{}},[$,ue]),useEffect(()=>{w&&w.length>0&&$.length===0&&console.log("Initial messages:",w);},[w,$.length]);let q=ce==="submitted"||ce==="streaming",Ke=useCallback(()=>{S&&S($,f);},[S,$,f]),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 Z={role:"user",content:H,createdAt:Date.now(),chatId:f};c(Z);}await he({text:H,files:z});}catch(Z){throw console.error("Failed to send message:",Z),Z}}},[s,q,he,c,f]),Ie=useCallback(()=>{if(q)return;ye(),l("");try{O?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;k(E);},[q,O,ye,k]),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:Ke,chatApi:O,chatId:f,setChatId:k,tools:g,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`,m=()=>{try{let h=localStorage.getItem(n);return h?JSON.parse(h):[]}catch{return []}},i=h=>{try{localStorage.setItem(n,JSON.stringify(h));}catch{}},w=h=>{try{let f=localStorage.getItem(r(h));return f?JSON.parse(f):null}catch{return null}},S=h=>{try{localStorage.setItem(r(h.id),JSON.stringify(h));}catch{}},d=h=>{let f=m(),k=f.findIndex(y=>y.id===h.id);k>=0?f[k]=h:f.unshift(h),i(f);},T=h=>{let k=m().filter(y=>y.id!==h);i(k);},v=h=>{try{localStorage.removeItem(r(h));}catch{}};return {loadChatsIndex:m,saveChatsIndex:i,loadChat:w,saveChat:S,upsertChatMeta:d,deleteChatMeta:T,deleteChatData:v,deleteChat:h=>{v(h),T(h);},loadShowChatPreference:h=>{try{let f=localStorage.getItem(c);return f!==null?f==="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:m=true}=e,i=useMemo(()=>rt(t),[t]),[w,S]=useState([]),[d,T]=useState(null),v=useRef(false),x=useRef(false),a=useCallback(()=>{try{let y=i.loadChatsIndex();S(y);let p=y.find(C=>C.id===n);T(p||null);}catch(y){console.error("Failed to refresh chat list:",y);}},[i,n]);useEffect(()=>{a();},[a]),useEffect(()=>{if(!(!m||x.current)){try{i.loadCurrentChatId()&&(v.current=!0);}catch(y){console.error("Failed to restore chat:",y);}x.current=true;}},[i,m]),useEffect(()=>{if(!(!c||r.length===0))if(v.current){if(!o){let y=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:y}),a());}catch(p){console.error("Failed to save chat:",p);}}}else {let y=r.find(p=>p.role==="user");if(y){let p="";if(Array.isArray(y.parts)){let g=y.parts.find(R=>R&&R.type==="text");p=g&&typeof g.text=="string"?g.text:"";}let C=(p||"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(g){console.error("Failed to create chat:",g);}}}},[]);let b=useRef(false);useEffect(()=>{if(o){b.current=true;return}if(b.current&&c){b.current=false;try{let y=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:y});else {let M="",g=Array.isArray(r)?r.find(N=>N&&N.role==="user"):void 0;if(g&&Array.isArray(g.parts)){let N=g.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:y,updatedAt:y});try{i.saveCurrentChatId(n);}catch{}v.current=!0;}a();}catch(y){console.error("Failed to save chat on completion:",y);}}},[o,r,n,t,i,c,a]);let s=useCallback(y=>{try{let p=i.loadChat(y);return p?{id:p.id,messages:p.messages,agentId:p.agentId||t}:null}catch(p){return console.error("Failed to load chat:",p),null}},[i,t]),l=useCallback(()=>{if(r.length!==0)try{let y=Date.now();i.saveChat({id:n,messages:r,agentId:t});let C=i.loadChatsIndex().find(M=>M.id===n);C&&(i.upsertChatMeta({...C,updatedAt:y}),a());}catch(y){console.error("Failed to save chat:",y);}},[i,n,r,t,a]),u=useCallback(y=>{try{i.deleteChat(y),a();}catch(p){console.error("Failed to delete chat:",p);}},[i,a]),h=useCallback((y,p)=>{if(y!==n)try{v.current=!0,i.saveCurrentChatId(y);let C=i.loadChat(y),M=C&&Array.isArray(C.messages)?C.messages:[];p(M),a();}catch(C){console.error("Failed to switch chat:",C);}},[i,n,a]),f=useCallback(y=>{v.current=false,y();},[]),k=useCallback(y=>{if(!y.trim())return w;let p=y.toLowerCase();return w.filter(C=>C.title.toLowerCase().includes(p))},[w]);return {chatList:w,currentChatMeta:d,refreshChatList:a,loadChat:s,saveCurrentChat:l,deleteChat:u,switchToChat:h,createNewChat:f,searchChats:k,storage:i}}function zo(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:c}=e,{baseUrl:m}=ne(),i=c||m||"",[w,S]=useState(null),[d,T]=useState(""),[v,x]=useState([]),[a,b]=useState(false),s=useCallback((y,p,C=[])=>{S(y),T(p),x(C);},[]),l=useCallback(()=>{S(null),T(""),x([]);},[]),u=useCallback(async y=>{if(!n)try{let p=t.findIndex(M=>M.id===y);if(p===-1)return;let C=t.slice(0,p);o(C),await r({text:d.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(p){throw console.error("Failed to save edit:",p),p}},[n,t,r,d,v,o,l]),h=useCallback(y=>w===y,[w]),f=useCallback(async y=>{if(!i){console.warn("baseUrl not provided, cannot upload attachments");return}b(true);try{let p=Array.from(y).map(async M=>{if(M.size>26214400)throw new Error(`${M.name} is too large (max 25MB)`);let g=new FormData;g.append("file",M);let R=await fetch(`${i}/api/upload`,{method:"POST",body:g});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(p);x(M=>[...M,...C]);}catch(p){throw console.error("Failed to upload files:",p),p}finally{b(false);}},[i]),k=useCallback(y=>{x(p=>p.filter(C=>C.id!==y));},[]);return {editingMessageId:w,editingText:d,setEditingText:T,editAttachments:v,setEditAttachments:x,editUploading:a,startEdit:s,cancelEdit:l,saveEdit:u,isEditing:h,addEditAttachments:f,removeEditAttachment:k}}function j({IconComponent:e,...t}){return Wo.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:m=>{o||(m.currentTarget.style.backgroundColor=r.hoverBackground,m.currentTarget.style.color=r.textColor);},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function xn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:c,onToggleHistory:m,onClose:i,historyBtnRef:w,t:S}){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:S("header.new"),resolvedColors:o,disabled:n}),jsx("button",{ref:w,"aria-label":S("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:m,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:S("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 Ko=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"]},Vo=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}},Xo=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function bn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:m,onUISuccess:i,addToolResult:w}){let S=[],d=[],T,v,x=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){d.push(a.text),T||(T=a.startDate),v=a.endDate,a.state==="done"&&(x=true);continue}if(a.type==="text"&&typeof a.text=="string"){d.length&&(S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),d=[],T=void 0,v=void 0,x=false),S.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"){d.length&&(S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),d=[],T=void 0,v=void 0,x=false);let l=String(b?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");l==="requestInput"?S.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}):S.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 d.length&&S.push({type:"reasoning",texts:d,startDate:T,endDate:v,isCompleted:x}),S.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[S.map((a,b)=>{let s=`${t}-${b}`,l=n.has(s);if(a.type==="reasoning"){let p=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",C=a.texts&&a.texts.length>0&&a.texts.some(g=>g.trim().length>0),M=()=>{C&&r(s);};return p&&!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:[!p&&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:p?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:p?"auto":"200% 100%",backgroundClip:p?"unset":"text",WebkitBackgroundClip:p?"unset":"text",WebkitTextFillColor:p?o.mutedTextColor:"transparent",animation:p?void 0:"shimmer 2s ease-in-out infinite"},children:p?"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||!p?"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:(!p&&l?a.texts:p?l?a.texts:[]:[a.texts[a.texts.length-1]]).map((g,R)=>jsx("div",{style:{marginBottom:"6px",opacity:.5},children:jsx(We,{content:g,theme:"dark",streaming:!p})},`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 p=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:p})},s)}let{color:u,text:h}=Ko(a.status),f=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 k=c?.[a.toolName||""];if(k)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:m,onSuccess:i,children:jsx(k,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:w})})},s);let y=Vo(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:u,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:u,animation:f?"pulse 1.5s ease-in-out infinite":void 0}}),h]}),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:Xo(y.toolName)})]})})},s)}),jsx("style",{children:`
12
12
  @keyframes shimmer {
13
13
  0% { background-position: -200% 0; }
14
14
  100% { background-position: 200% 0; }
@@ -23,7 +23,7 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Wo,{createContext,useRe
23
23
  }
24
24
  }
25
25
  `}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((v,x)=>{let a=Array.isArray(v.parts)?v.parts:[],b=a.filter(l=>l.type==="text").map(l=>l&&typeof l.text=="string"?l.text:"").join(`
26
- `),s=a.filter(l=>l.type==="file"||l.type==="image").map(l=>{if(l.type==="image"){let u=typeof l.image=="string"?l.image:l.image?.toString?.()||"";return {id:u||`${v.id}-img-${Date.now()}`,name:l.name||"image",url:u,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:()=>m(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(wn,{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(bn,{parts:a,messageId:v.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:w,onUISuccess:S,addToolResult:d})},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 In({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:c,attachments:m,formatBytes:i,handleRemoveAttachment:w,onFileInputChange:S,onSend:d,onStop:T,status:v,t:x,resolvedColors:a}){let b=v==="streaming"||v==="submitted",s=m.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:[m.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:m.map(l=>{let u=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:u?"transparent":a.cardBackground},children:u?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:[u&&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:x("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:()=>w(l.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:x("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:x("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:x("input.placeholder"),value:e,onChange:l=>t(l.target.value),onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),d());},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:S,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":x("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":x("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:d,disabled:!s||c,"aria-label":x("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 Sn({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((m,i)=>{let w=o===i,S=m.prompt.length>80,d=S&&!w?m.prompt.slice(0,80)+"...":m.prompt;return jsxs("button",{onClick:()=>{r||t(m.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"})]}),m.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:d}),S&&jsxs("button",{onClick:T=>{T.stopPropagation(),c(w?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:[w?"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:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},i)})})]})}function Mn(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 m=Math.floor(c/7);if(m<4)return `${m}w`;let i=Math.floor(c/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function En({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:c,onSearchChange:m,onChatSelect:i,onChatDelete:w,loadChatsIndex:S,historyPopupRef:d}){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:d,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=>m(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(),x=S();return v&&(x=x.filter(a=>(a.title||"").toLowerCase().includes(v))),!x||x.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:x.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:Mn(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(),w(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 An({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let c=o?.title||"Edit Message",m=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",w=o?.cancel_button_label||"Cancel",S=o?.icon,d=typeof m=="function",T=d?m: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:[S?jsx("div",{style:{flexShrink:0},children:jsx(j,{IconComponent:S,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:d&&T?jsx(T,{}):jsx("p",{style:{margin:0},children:m})}),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:x=>{x.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent";},children:w}),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:x=>{x.currentTarget.style.opacity="0.9";},onMouseLeave:x=>{x.currentTarget.style.opacity="1";},children:i})]})]})]});return typeof document<"u"&&document.body?createPortal(v,document.body):v}function pr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:c,borderColor:m,textColor:i,accentColor:w,baseUrl:S="",initialMessages:d=[],onMessagesChange:T,defaultOpen:v=true,floatingButtonPosition:x={bottom:24,right:24},HsafaTools:a={},HsafaUI:b={},componentAboveInput:s,editProcessContent:l,presetPrompts:u,onStart:h,onFinish:f,currentChat:k,onChatChanged:y,templateParams:p}){let{dir:C,theme:M,baseUrl:g,setStreamingState:R,setChatOpenState:N}=ne(),U=t||M||"dark",te=S&&S.length>0?S:g||"",A={primaryColor:U==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:c||(U==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:m||(U==="dark"?"#2A2C33":"#E5E7EB"),textColor:i||(U==="dark"?"#EDEEF0":"#111827"),accentColor:w||(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=I=>({"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"})[I]||I,_=St({agentId:e,baseUrl:te,tools:a,uiComponents:b,templateParams:p,controlledChatId:k,onChatIdChange:k===void 0?I=>{y&&y(I);}:void 0,onStart:useCallback(I=>{h&&h(I);},[h]),onFinish:useCallback(I=>{f&&f(I);},[f]),onError:useCallback(I=>{console.error("Chat error:",I);},[]),initialMessages:d,onMessagesChange:T}),{input:V,setInput:ie,messages:O,isLoading:$,status:he,error:ce,sendMessage:xe,stop:mt,setMessages:q,notifyMessagesChange:Ke,chatId:Fe,setChatId:Ie,tools:Ht,uiComponents:E,formHostRef:F,formStateRef:z,cleanupForms:H,onUISuccess:J,onUIError:Z,chatApi:de}=_,X=k!==void 0?k:Fe,be=useCallback(I=>{k===void 0&&Ie(I),y&&y(I);},[k,Ie,y]);useEffect(()=>{k!==void 0&&k!==Fe&&Ie(k);},[k,Fe,Ie]);let{attachments:Ve,uploading:Ln,fileInputRef:Xe,formatBytes:Hn,handleRemoveAttachment:Fn,handleFileSelection:Ft,clearAttachments:Ye,setAttachments:Bt}=Vt(te),[Dt,Se]=useState(null),[Je,Pt]=useState(()=>{try{return rt(e).loadShowChatPreference(!!v)}catch{return !!v}}),[Bn,gt]=useState(false),[Dn,Pn]=useState(""),[$n,Nn]=useState(0),Un=useRef(null),zn=useRef(null),[Wn,On]=useState(new Set),[Gn,ft]=useState(false),[Be,yt]=useState(null),$t=useRef(null),_n=_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(k!==void 0){try{let I=G.loadChat(k),D=I&&Array.isArray(I.messages)?I.messages:[];if(D.length>0)try{q(D);}catch{}Pe.current=k;}catch{}try{G.saveCurrentChatId(k);}catch{}De.current=true;return}try{let I=G.loadCurrentChatId();if(I){be(I);let D=G.loadChat(I),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}Pe.current=I;}}catch{}De.current=true;}},[k]),useEffect(()=>{if(De.current&&k!==void 0&&k!==Pe.current)try{let I=G.loadChat(k),D=I&&Array.isArray(I.messages)?I.messages:[];try{q(D);}catch{}Pe.current=k;try{G.saveCurrentChatId(k);}catch{}}catch{}},[k,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,Je);}catch{}return ()=>{try{N(X,!1);}catch{}}},[X,Je,N]);let jn=useCallback(async()=>{let I=V.trim();if(!I&&Ve.length===0||$)return;let D=[...Ve];ie(""),Ye(),Se(null);try{await xe({text:I,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,Ve,$,xe,Ye]),Nt=useCallback(()=>{if($)return;H(),ie(""),Ye(),Se(null);try{q([]);}catch{}let I=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Pe.current=I;try{ht.createNewChat(()=>{be(I);try{G.saveCurrentChatId(I);}catch{}});}catch{be(I);try{G.saveCurrentChatId(I);}catch{}}},[$,Ye,G,q,be,H,ht]),qn=useCallback(()=>{gt(I=>!I);},[]),Kn=useCallback(()=>{Pt(false);try{G.saveShowChatPreference(!1);}catch{}},[G]),Vn=useCallback(async I=>{let D=I.target.files;D&&await Ft(D,Se),Xe.current&&(Xe.current.value="");},[Ft,Xe]);useEffect(()=>{let I=$t.current;if(!I)return;I.style.height="24px",I.offsetHeight,I.style.height="auto";let D=Math.min(I.scrollHeight,200);I.style.height=`${D}px`;},[V]);let Xn=useCallback((I,D,W,Zn)=>{yt({id:D,text:W,attachments:Zn||[]}),ft(true);},[]),Yn=useCallback(()=>{if(!(!Be||$))try{let I=O.findIndex(W=>W.id===Be.id);if(I===-1)return;let D=O.slice(0,I);try{q(D);}catch{}ie(Be.text),Bt(Be.attachments),ft(!1),yt(null),Ke();}catch(I){console.error("Failed to edit message:",I),Se("Failed to edit message. Please try again.");}},[Be,$,O,q,Bt,Ke]),Jn=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:Je?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(xn,{title:B("general.agent")+2,alwaysOpen:false,streaming:$,dir:C||"ltr",resolvedColors:A,onNew:Nt,onToggleHistory:qn,onClose:Kn,historyBtnRef:Un,t:B}),jsx("div",{ref:_n,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:u&&u.length>0?jsx(Sn,{prompts:u,onSelect:I=>ie(I),resolvedColors:A,disabled:$}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:B("messages.empty")})}):jsx(Tn,{chatMessages:O,isLoading:$,openReasoningIds:Wn,toggleReasoning:I=>On(D=>{let W=new Set(D);return W.has(I)?W.delete(I):W.add(I),W}),resolvedColors:A,t:B,onUserMessageClick:Xn,HsafaUI:E,onUIError:Z,onUISuccess:J,addToolResult:I=>de?.addToolResult?.(I),editableMessageIcon:l?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&Wo.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(In,{input:V,setInput:ie,textareaRef:$t,fileInputRef:Xe,isLoading:$,uploading:Ln,attachments:Ve,formatBytes:Hn,handleRemoveAttachment:Fn,onFileInputChange:Vn,onSend:jn,onStop:()=>mt(),status:he,t:B,resolvedColors:A})]}),jsx(En,{historyOpen:Bn,historySearch:Dn,currentChatId:X,refreshKey:$n,resolvedColors:A,onClose:()=>gt(false),onSearchChange:Pn,onChatSelect:I=>{if(gt(false),I&&I!==X&&(H(),be(I),k===void 0)){try{G.saveCurrentChatId(I);}catch{}try{let D=G.loadChat(I),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}}catch{}}},onChatDelete:I=>{try{G.deleteChat(I),Nn(D=>D+1),I===X&&Nt();}catch{}},loadChatsIndex:()=>G.loadChatsIndex(),historyPopupRef:zn}),jsx(An,{isOpen:Gn,resolvedColors:A,onConfirm:Yn,onCancel:Jn,editProcessContent:l}),jsx("style",{children:`
26
+ `),s=a.filter(l=>l.type==="file"||l.type==="image").map(l=>{if(l.type==="image"){let u=typeof l.image=="string"?l.image:l.image?.toString?.()||"";return {id:u||`${v.id}-img-${Date.now()}`,name:l.name||"image",url:u,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:()=>m(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(wn,{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(bn,{parts:a,messageId:v.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:w,onUISuccess:S,addToolResult:d})},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 In({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:c,attachments:m,formatBytes:i,handleRemoveAttachment:w,onFileInputChange:S,onSend:d,onStop:T,status:v,t:x,resolvedColors:a}){let b=v==="streaming"||v==="submitted",s=m.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:[m.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:m.map(l=>{let u=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:u?"transparent":a.cardBackground},children:u?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:[u&&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:x("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:()=>w(l.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:x("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:x("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:x("input.placeholder"),value:e,onChange:l=>t(l.target.value),onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),d());},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:S,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":x("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":x("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:d,disabled:!s||c,"aria-label":x("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 Sn({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((m,i)=>{let w=o===i,S=m.prompt.length>80,d=S&&!w?m.prompt.slice(0,80)+"...":m.prompt;return jsxs("button",{onClick:()=>{r||t(m.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"})]}),m.label]}),jsx("div",{style:{fontSize:"12px",color:n.mutedTextColor,lineHeight:"1.5",width:"100%",wordWrap:"break-word",whiteSpace:"pre-wrap"},children:d}),S&&jsxs("button",{onClick:T=>{T.stopPropagation(),c(w?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:[w?"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:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:jsx("polyline",{points:"6 9 12 15 18 9"})})]})]},i)})})]})}function Mn(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 m=Math.floor(c/7);if(m<4)return `${m}w`;let i=Math.floor(c/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function En({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:c,onSearchChange:m,onChatSelect:i,onChatDelete:w,loadChatsIndex:S,historyPopupRef:d}){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:d,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=>m(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(),x=S();return v&&(x=x.filter(a=>(a.title||"").toLowerCase().includes(v))),!x||x.length===0?jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:x.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:Mn(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(),w(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 An({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let c=o?.title||"Edit Message",m=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",w=o?.cancel_button_label||"Cancel",S=o?.icon,d=typeof m=="function",T=d?m: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:[S?jsx("div",{style:{flexShrink:0},children:jsx(j,{IconComponent:S,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:d&&T?jsx(T,{}):jsx("p",{style:{margin:0},children:m})}),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:x=>{x.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent";},children:w}),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:x=>{x.currentTarget.style.opacity="0.9";},onMouseLeave:x=>{x.currentTarget.style.opacity="1";},children:i})]})]})]});return typeof document<"u"&&document.body?createPortal(v,document.body):v}function pr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:c,borderColor:m,textColor:i,accentColor:w,baseUrl:S="",initialMessages:d=[],onMessagesChange:T,defaultOpen:v=true,floatingButtonPosition:x={bottom:24,right:24},HsafaTools:a={},HsafaUI:b={},componentAboveInput:s,editProcessContent:l,presetPrompts:u,onStart:h,onFinish:f,currentChat:k,onChatChanged:y,templateParams:p}){let{dir:C,theme:M,baseUrl:g,setStreamingState:R,setChatOpenState:N}=ne(),U=t||M||"dark",te=S&&S.length>0?S:g||"",A={primaryColor:U==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:c||(U==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:m||(U==="dark"?"#2A2C33":"#E5E7EB"),textColor:i||(U==="dark"?"#EDEEF0":"#111827"),accentColor:w||(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=I=>({"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"})[I]||I,_=St({agentId:e,baseUrl:te,tools:a,uiComponents:b,templateParams:p,controlledChatId:k,onChatIdChange:k===void 0?I=>{y&&y(I);}:void 0,onStart:useCallback(I=>{h&&h(I);},[h]),onFinish:useCallback(I=>{f&&f(I);},[f]),onError:useCallback(I=>{console.error("Chat error:",I);},[]),initialMessages:d,onMessagesChange:T}),{input:V,setInput:ie,messages:O,isLoading:$,status:he,error:ce,sendMessage:xe,stop:mt,setMessages:q,notifyMessagesChange:Ke,chatId:Fe,setChatId:Ie,tools:Ht,uiComponents:E,formHostRef:F,formStateRef:z,cleanupForms:H,onUISuccess:Z,onUIError:J,chatApi:de}=_,X=k!==void 0?k:Fe,be=useCallback(I=>{k===void 0&&Ie(I),y&&y(I);},[k,Ie,y]);useEffect(()=>{k!==void 0&&k!==Fe&&Ie(k);},[k,Fe,Ie]);let{attachments:Ve,uploading:Ln,fileInputRef:Xe,formatBytes:Hn,handleRemoveAttachment:Fn,handleFileSelection:Ft,clearAttachments:Ye,setAttachments:Bt}=Vt(te),[Dt,Se]=useState(null),[Je,Pt]=useState(()=>{try{return rt(e).loadShowChatPreference(!!v)}catch{return !!v}}),[Bn,gt]=useState(false),[Dn,Pn]=useState(""),[$n,Nn]=useState(0),Un=useRef(null),zn=useRef(null),[Wn,On]=useState(new Set),[Gn,ft]=useState(false),[Be,yt]=useState(null),$t=useRef(null),_n=_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(k!==void 0){try{let I=G.loadChat(k),D=I&&Array.isArray(I.messages)?I.messages:[];if(D.length>0)try{q(D);}catch{}Pe.current=k;}catch{}try{G.saveCurrentChatId(k);}catch{}De.current=true;return}try{let I=G.loadCurrentChatId();if(I){be(I);let D=G.loadChat(I),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}Pe.current=I;}}catch{}De.current=true;}},[k]),useEffect(()=>{if(De.current&&k!==void 0&&k!==Pe.current)try{let I=G.loadChat(k),D=I&&Array.isArray(I.messages)?I.messages:[];try{q(D);}catch{}Pe.current=k;try{G.saveCurrentChatId(k);}catch{}}catch{}},[k,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,Je);}catch{}return ()=>{try{N(X,!1);}catch{}}},[X,Je,N]);let jn=useCallback(async()=>{let I=V.trim();if(!I&&Ve.length===0||$)return;let D=[...Ve];ie(""),Ye(),Se(null);try{await xe({text:I,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,Ve,$,xe,Ye]),Nt=useCallback(()=>{if($)return;H(),ie(""),Ye(),Se(null);try{q([]);}catch{}let I=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Pe.current=I;try{ht.createNewChat(()=>{be(I);try{G.saveCurrentChatId(I);}catch{}});}catch{be(I);try{G.saveCurrentChatId(I);}catch{}}},[$,Ye,G,q,be,H,ht]),qn=useCallback(()=>{gt(I=>!I);},[]),Kn=useCallback(()=>{Pt(false);try{G.saveShowChatPreference(!1);}catch{}},[G]),Vn=useCallback(async I=>{let D=I.target.files;D&&await Ft(D,Se),Xe.current&&(Xe.current.value="");},[Ft,Xe]);useEffect(()=>{let I=$t.current;if(!I)return;I.style.height="24px",I.offsetHeight,I.style.height="auto";let D=Math.min(I.scrollHeight,200);I.style.height=`${D}px`;},[V]);let Xn=useCallback((I,D,W,Zn)=>{yt({id:D,text:W,attachments:Zn||[]}),ft(true);},[]),Yn=useCallback(()=>{if(!(!Be||$))try{let I=O.findIndex(W=>W.id===Be.id);if(I===-1)return;let D=O.slice(0,I);try{q(D);}catch{}ie(Be.text),Bt(Be.attachments),ft(!1),yt(null),Ke();}catch(I){console.error("Failed to edit message:",I),Se("Failed to edit message. Please try again.");}},[Be,$,O,q,Bt,Ke]),Jn=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:Je?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(xn,{title:B("general.agent")+2,alwaysOpen:false,streaming:$,dir:C||"ltr",resolvedColors:A,onNew:Nt,onToggleHistory:qn,onClose:Kn,historyBtnRef:Un,t:B}),jsx("div",{ref:_n,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:u&&u.length>0?jsx(Sn,{prompts:u,onSelect:I=>ie(I),resolvedColors:A,disabled:$}):jsx("div",{style:{padding:"32px",textAlign:"center",color:A.mutedTextColor,fontSize:"14px"},children:B("messages.empty")})}):jsx(Tn,{chatMessages:O,isLoading:$,openReasoningIds:Wn,toggleReasoning:I=>On(D=>{let W=new Set(D);return W.has(I)?W.delete(I):W.add(I),W}),resolvedColors:A,t:B,onUserMessageClick:Xn,HsafaUI:E,onUIError:J,onUISuccess:Z,addToolResult:I=>de?.addToolResult?.(I),editableMessageIcon:l?.message_icon})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&Wo.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(In,{input:V,setInput:ie,textareaRef:$t,fileInputRef:Xe,isLoading:$,uploading:Ln,attachments:Ve,formatBytes:Hn,handleRemoveAttachment:Fn,onFileInputChange:Vn,onSend:jn,onStop:()=>mt(),status:he,t:B,resolvedColors:A})]}),jsx(En,{historyOpen:Bn,historySearch:Dn,currentChatId:X,refreshKey:$n,resolvedColors:A,onClose:()=>gt(false),onSearchChange:Pn,onChatSelect:I=>{if(gt(false),I&&I!==X&&(H(),be(I),k===void 0)){try{G.saveCurrentChatId(I);}catch{}try{let D=G.loadChat(I),W=D&&Array.isArray(D.messages)?D.messages:[];try{q(W);}catch{}}catch{}}},onChatDelete:I=>{try{G.deleteChat(I),Nn(D=>D+1),I===X&&Nt();}catch{}},loadChatsIndex:()=>G.loadChatsIndex(),historyPopupRef:zn}),jsx(An,{isOpen:Gn,resolvedColors:A,onConfirm:Yn,onCancel:Jn,editProcessContent:l}),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
29
  `})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[jsx(nt,{}),createPortal(Ut,document.body),jsx(Wt,{show:!Je,onClick:()=>{Pt(true);try{G.saveShowChatPreference(!0);}catch{}},resolvedColors:A,floatingButtonPosition:x})]}):Ut}var Rn={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:c,mutedTextColor:m,enableBorderAnimation:i=true,borderRadius:w=16,enableContentBorder:S=true,className:d="",enableMargin:T=true,chatWidth:v=420,dir:x="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:b,dir:s,theme:l}=ne(),u=(x??s)||"ltr",h=(t??l)||"dark",f=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[k,y]=useState(false);useEffect(()=>{let U=setTimeout(()=>y(true),50);return ()=>clearTimeout(U)},[]);let p=Rn[h],C={primaryColor:n||p.primaryColor,backgroundColor:r||p.backgroundColor,borderColor:o||p.borderColor,textColor:c||p.textColor,accentColor:p.accentColor,mutedTextColor:m||p.mutedTextColor,inputBackground:p.inputBackground,cardBackground:p.cardBackground,hoverBackground:p.hoverBackground},M=typeof w=="number"?`${w}px`:w,g=typeof v=="number"?`${v}px`:v,R=T&&b?u==="rtl"?{marginLeft:g}:{marginRight:g}:{},N=T&&b?`calc(100% - ${g})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:d,style:{width:N,height:"100%",transition:k?"all 0.2s ease-out":"none",padding:b&&S?"16px":"0",...R},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:k?"all 0.2s ease-out":"none",borderRadius:b?M:"0",border:b&&a&&i?"none":b?`1px solid ${C.borderColor}`:"none",padding:b&&a&&i?"1.5px":"0",background:b&&a&&i?`linear-gradient(120deg, ${C.primaryColor}dd 0%, ${C.primaryColor}88 25%, ${C.primaryColor}00 50%, ${C.primaryColor}88 75%, ${C.primaryColor}dd 100%)`:"transparent",backgroundSize:b&&a&&i?"300% 300%":"auto",animation:b&&a&&i?`${f.current}-border-flow 3s ease-in-out infinite`:"none",filter:b&&a&&i?`drop-shadow(0 0 10px ${C.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:b&&S?M:"0",backgroundColor:b&&S?C.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${C.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`