@hsafa/ui-sdk 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createContext,useState,useCallback,useRef,useEffect,useMemo,useContext}from'react';import {createPortal}from'react-dom';import {IconArrowsMaximize,IconPlus,IconHistory,IconTrash,IconChevronRight,IconPaperclip,IconLink,IconPlayerStop,IconArrowUp,IconMessage}from'@tabler/icons-react';var te={};var tr=({variant:s="primary",size:p="md",loading:g=false,disabled:b,children:z,className:$,...O})=>{let U=[te.button,te[s],te[p],g&&te.loading,$].filter(Boolean).join(" ");return jsxs("button",{className:U,disabled:b||g,...O,children:[g&&jsx("span",{className:te.spinner}),jsx("span",{className:g?te.hiddenText:void 0,children:z})]})};function ar(s=false){let[p,g]=useState(s),b=useCallback(()=>g(O=>!O),[]),z=useCallback(()=>g(true),[]),$=useCallback(()=>g(false),[]);return {on:p,toggle:b,setOn:g,setTrue:z,setFalse:$}}function lr(){let s=useRef(null);return useEffect(()=>{let p=s.current;if(!p)return;let g=new MutationObserver(()=>{p.scrollTop=p.scrollHeight;});return g.observe(p,{childList:true,subtree:true}),p.scrollTop=p.scrollHeight,()=>g.disconnect()},[]),s}var Ye=createContext(void 0);function zt({baseUrl:s,children:p}){let[g,b]=useState(new Map),[z,$]=useState(new Map),O=useCallback((I,w)=>(b(F=>{let f=new Map(F);return f.set(String(I),w),f}),()=>{b(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});}),[]),U=useCallback((I,w)=>{b(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});},[]),G=useCallback((I,w)=>($(F=>{let f=new Map(F);return f.set(String(I),w),f}),()=>{$(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});}),[]),oe=useCallback((I,w)=>{$(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});},[]),ge=useMemo(()=>({baseUrl:s,actions:g,components:z,registerAction:O,unregisterAction:U,registerComponent:G,unregisterComponent:oe}),[s,g,z,O,U,G,oe]);return jsx(Ye.Provider,{value:ge,children:p})}function re(){let s=useContext(Ye);return s||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{}}}function yr(s,p){let{registerAction:g}=re(),b=useRef(p);useEffect(()=>{b.current=p;},[p]),useEffect(()=>!s||typeof b.current!="function"?void 0:g(s,($,O)=>b.current($,O)),[s,g]);}function Cr(s,p){let{registerComponent:g}=re(),b=useRef(p);useEffect(()=>{b.current=p;},[p]),useEffect(()=>!s||typeof b.current!="function"?void 0:g(s,b.current),[s,g]);}function Xt(s){let p=Date.now()-s,g=Math.max(1,Math.floor(p/1e3));if(g<60)return `${g}s`;let b=Math.floor(g/60);if(b<60)return `${b}m`;let z=Math.floor(b/60);if(z<24)return `${z}h`;let $=Math.floor(z/24);if($<7)return `${$}d`;let O=Math.floor($/7);if(O<4)return `${O}w`;let U=Math.floor($/30);return U<12?`${U}mo`:`${Math.floor(U/12)}y`}function et(s,p){if(!s)return p;let g=s.endsWith("/")?s.slice(0,-1):s,b=p.startsWith("/")?p:`/${p}`;return `${g}${b}`}var Vt={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 Yt({agentId:s,children:p,theme:g="dark",primaryColor:b,backgroundColor:z,borderColor:$,textColor:O,accentColor:U,width:G=420,maxWidth:oe=420,height:ge="100vh",expandable:I=true,alwaysOpen:w=false,defaultOpen:F=true,dir:f="ltr",floatingButtonPosition:m=f==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},enableBorderAnimation:ne=true,enableContentPadding:tt=true,borderRadius:ke=16,enableContentBorder:Ae=true,placeholder:rt="Ask your question...",title:He="Agent",className:ot="",chatContainerClassName:nt=""}){let{baseUrl:Ee,actions:ze,components:at}=re(),fe=`hsafaChat_${s}`,Fe=`${fe}.chats`,ve=e=>`${fe}.chat.${e}`,J=`${fe}.currentChatId`,Be=`${fe}.showChat`,[ie,Ne]=useState(""),[V,xe]=useState(()=>{if(w)return true;try{let e=localStorage.getItem(Be);return e!==null?e==="true":F}catch{return F}});async function Le(e,n){if(!s)return;let r=n.trim();if(!r)return;_(null),ae(true);let a=A.findIndex(c=>c.id===e);if(a===-1||A[a].role!=="user"){ae(false);return}let i=A.slice(0,a),d={id:e,role:"user",text:r},B=ue(),k=[...i,d,{id:B,role:"assistant",items:[],reasoning:"",reasoningOpen:false}];M(k),ye(null);try{let c=[...i.map(N=>N.role==="user"?{role:"user",content:N.text}:{role:"assistant",items:Array.isArray(N.items)?N.items:[]}),{role:"user",content:r}],R={prompt:r,chatId:S??void 0,messages:c};M(N=>N.map(K=>K.id===B||K.id===e?{...K,requestParams:R}:K));let v=await fetch(et(Ee,`/api/run/${s}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(R)});if(!v.ok||!v.body){let N=await v.text().catch(()=>"");throw new Error(N||`Request failed with ${v.status}`)}let T=v.body.getReader(),ee=new TextDecoder,P="";for(;;){let{done:N,value:K}=await T.read();if(N)break;P+=ee.decode(K,{stream:!0});let x;for(;(x=P.indexOf(`
2
- `))!==-1;){let L=P.slice(0,x).trim();if(P=P.slice(x+1),!!L)try{let u=JSON.parse(L);if(u?.type==="meta"){if(u.actionExecuteMap&&typeof u.actionExecuteMap=="object"&&(Me.current=u.actionExecuteMap),u.assistantMessageId&&(se.current=String(u.assistantMessageId),me.current.clear(),he.current.clear(),W.current.clear(),Q(new Map)),u.chatId&&!S){Y(u.chatId),j.current=!0;let l=r,X=(Z.current||l||"New chat").slice(0,80),h=Date.now();de({id:u.chatId,title:X,createdAt:h,updatedAt:h}),ce({id:u.chatId,messages:k,agentId:s});try{localStorage.setItem(J,u.chatId);}catch{}}continue}if(u?.type==="reasoning"){let l=String(u.text??"");M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,reasoning:(h.reasoning??"")+l}:h));continue}if(u?.type==="partial"||u?.type==="final"){let l=u.value;l&&Array.isArray(l.items)&&(M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,items:l.items}:h)),Je(l.items,u.type==="partial"?"partial":"final")),u?.type==="final"&&M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,reasoningOpen:!1}:h));continue}if(u?.type==="usage"){let l=u?.value?.reasoningTokens;typeof l=="number"&&M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,reasoningTokens:l}:h));continue}if(u?.type==="error"){_(String(u.error??"Unknown error"));continue}}catch{}}}}catch(c){_(String(c?.message??c));}finally{if(ae(false),!S&&!j.current){let c=`local-${ue()}`;Y(c),j.current=true;let R=(Z.current||"New chat").slice(0,80),v=Date.now();de({id:c,title:R,createdAt:v,updatedAt:v}),ce({id:c,messages:A,agentId:s});try{localStorage.setItem(J,c);}catch{}}}}let[A,M]=useState([]),[y,ae]=useState(false),[De,_]=useState(null),le=useRef(null),[S,Y]=useState(null),[st,we]=useState(false),[Oe,it]=useState(""),[Gt,lt]=useState(0),[Pe,ct]=useState(false),[dt,ye]=useState(null),[be,je]=useState(""),ut=useRef(null),We=useRef(null),pt=useRef(null),[Te,gt]=useState(true),Se=useRef(false),j=useRef(false),Z=useRef(null),ft=useRef(null),xt=useRef(null),Me=useRef({}),se=useRef(void 0),me=useRef(new Set),he=useRef(new Map),W=useRef(new Map),[yt,Q]=useState(new Map),Ue=useCallback((e,n)=>{let r=he.current.get(e)||[],a=JSON.stringify(n);if(r.push(a),r.length>5&&r.shift(),he.current.set(e,r),r.length>=3){let i=r.slice(-3);return i.every(d=>d===i[0])}return false},[]),Je=useCallback((e,n)=>{!Array.isArray(e)||e.length===0||e.forEach((r,a)=>{if(!(!r||typeof r!="object")&&r.type==="action"){let i=String(r.name??"").trim();if(!i)return;let d=ze.get(i);if(!d){console.warn(`Action handler not found for: ${i}`);return}let B=!!Me.current[i],k=`${se.current||"assist"}:${i}:${a}`,c=`${i}:${a}`;try{if(n==="partial"&&B){Q(v=>new Map(v).set(c,"executing"));let R=setTimeout(()=>{Promise.resolve(d(r.params,{name:i,trigger:n,index:a,assistantMessageId:se.current,chatId:S||void 0})).catch(v=>{console.error(`Error executing streaming action ${i}:`,v),Q(T=>new Map(T).set(c,"executed"));});},50);W.current.set(`${c}_timeout`,R);}else if(n==="partial"&&!B){let R=Ue(c,r.params),v=W.current.get(c);R&&v!=="executed"?(W.current.set(c,"executed"),Q(T=>new Map(T).set(c,"executed")),Promise.resolve(d(r.params,{name:i,trigger:"params_complete",index:a,assistantMessageId:se.current,chatId:S||void 0})).catch(T=>{console.error(`Error executing stabilized action ${i}:`,T);})):v||(W.current.set(c,"executing"),Q(T=>new Map(T).set(c,"executing")));}else if(n==="final"&&W.current.get(c)!=="executed"&&!me.current.has(k)){me.current.add(k);let v=W.current.get(`${c}_timeout`);v&&(clearTimeout(v),W.current.delete(`${c}_timeout`)),W.current.set(c,"executed"),Q(T=>new Map(T).set(c,"executed")),Promise.resolve(d(r.params,{name:i,trigger:B?"final":"params_complete",index:a,assistantMessageId:se.current,chatId:S||void 0})).catch(T=>{console.error(`Error executing final action ${i}:`,T);});}}catch(R){console.error(`Error processing action ${i}:`,R);}}});},[ze,S,Ue]),$e=()=>{try{let e=localStorage.getItem(Fe);return e?JSON.parse(e):[]}catch{return []}},_e=e=>{try{localStorage.setItem(Fe,JSON.stringify(e));}catch{}},qe=e=>{try{let n=localStorage.getItem(ve(e));return n?JSON.parse(n):null}catch{return null}},ce=e=>{try{localStorage.setItem(ve(e.id),JSON.stringify(e));}catch{}},de=e=>{let n=$e(),r=n.findIndex(a=>a.id===e.id);r>=0?n[r]=e:n.unshift(e),_e(n);},bt=e=>{let r=$e().filter(a=>a.id!==e);_e(r);},mt=e=>{try{localStorage.removeItem(ve(e));}catch{}},ht=e=>{if(mt(e),bt(e),S===e){M([]),_(null),Y(null),j.current=false,Z.current=null;try{localStorage.removeItem(J);}catch{}}};useEffect(()=>{if(Se.current){Se.current=false;return}Te&&We.current?.scrollIntoView({behavior:"smooth",block:"end"});},[A,y,Te]),useEffect(()=>{try{let e=localStorage.getItem(J);if(e){let n=qe(e);n&&(Y(n.id),j.current=!0,M(n.messages||[]));}}catch{}},[]),useEffect(()=>{try{localStorage.setItem(Be,String(V));}catch{}},[V]),useEffect(()=>()=>{W.current.forEach((e,n)=>{n.endsWith("_timeout")&&clearTimeout(e);});},[]),useEffect(()=>{if(!S||!j.current)return;ce({id:S,messages:A,agentId:s});let n=A.find(i=>i.role==="user"),r=(Z.current||(n?.text??"New chat")).slice(0,80),a={id:S,title:r,createdAt:Date.now(),updatedAt:Date.now()};de(a);try{localStorage.setItem(J,S);}catch{}},[A,S,s]);let ue=()=>`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;function Ct(){le.current&&(le.current.abort(),le.current=null),ae(false),_("Request stopped by user");}async function Ke(){if(!s)return;let e=ie.trim();if(!e)return;_(null),ae(true),!S&&A.length===0&&(Z.current=e);let n=ue(),r=ue(),a={id:n,role:"user",text:e},i={id:r,role:"assistant",items:[],reasoning:"",reasoningOpen:false},d=[...A,a,i],B=[...A.map(k=>k.role==="user"?{role:"user",content:k.text}:{role:"assistant",items:Array.isArray(k.items)?k.items:[]}),{role:"user",content:e}];M(d),Ne("");try{le.current=new AbortController;let k={prompt:e,chatId:S??void 0,messages:B};M(ee=>ee.map(P=>P.id===r||P.id===n?{...P,requestParams:k}:P));let c=await fetch(et(Ee,`/api/run/${s}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k),signal:le.current.signal});if(!c.ok||!c.body){let ee=await c.text().catch(()=>"");throw new Error(ee||`Request failed with ${c.status}`)}let R=c.body.getReader(),v=new TextDecoder,T="";for(;;){let{done:ee,value:P}=await R.read();if(ee)break;T+=v.decode(P,{stream:!0});let N;for(;(N=T.indexOf(`
3
- `))!==-1;){let K=T.slice(0,N).trim();if(T=T.slice(N+1),!!K)try{let x=JSON.parse(K);if(x?.type==="meta"){if(x.actionExecuteMap&&typeof x.actionExecuteMap=="object"&&(Me.current=x.actionExecuteMap),x.assistantMessageId&&(se.current=String(x.assistantMessageId),me.current.clear(),he.current.clear(),W.current.clear(),Q(new Map)),x.chatId&&!S){Y(x.chatId),j.current=!0;let L=e,u=(Z.current||L||"New chat").slice(0,80),l=Date.now();de({id:x.chatId,title:u,createdAt:l,updatedAt:l}),ce({id:x.chatId,messages:d,agentId:s});try{localStorage.setItem(J,x.chatId);}catch{}}continue}if(x?.type==="reasoning"){let L=String(x.text??"");M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoning:(l.reasoning??"")+L}:l));continue}if(x?.type==="partial"||x?.type==="final"){let L=x.value;L&&Array.isArray(L.items)&&(M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,items:L.items}:l)),Je(L.items,x.type==="partial"?"partial":"final")),x?.type==="final"&&M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoningOpen:!1}:l));continue}if(x?.type==="usage"){let L=x?.value?.reasoningTokens;typeof L=="number"&&M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoningTokens:L}:l));continue}if(x?.type==="error"){_(String(x.error??"Unknown error"));continue}}catch{}}}}catch(k){_(String(k?.message??k));}finally{if(ae(false),!S&&!j.current){let k=`local-${ue()}`;Y(k),j.current=true;let c=(Z.current||"New chat").slice(0,80),R=Date.now();de({id:k,title:c,createdAt:R,updatedAt:R}),ce({id:k,messages:A,agentId:s});try{localStorage.setItem(J,k);}catch{}}}}function kt(e){return !Array.isArray(e)||e.length===0?null:jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:e.map((n,r)=>{let a=`it-${r}`;if(typeof n=="string")return jsx("div",{style:{borderRadius:"12px",padding:"16px",fontSize:"14px",whiteSpace:"pre-wrap",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`,color:t.textColor},children:n},a);if(n&&typeof n=="object"){if(n.type==="action"){let i=`${String(n.name??"action")}:${r}`,d=yt.get(i);return jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsx("div",{style:{padding:"8px",fontSize:"12px",color:t.mutedTextColor},children:d==="executing"?jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxs("svg",{style:{animation:"spin 1s linear infinite",height:"12px",width:"12px"},xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{style:{opacity:.75},fill:"currentColor",d:"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),String(n.name??"action")," is executing"]}):jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:"#10b981"}}),String(n.name??"action")," has executed"]})})},a)}if(n.type==="ui-component"||n.type==="ui"){let i=String(n.name??n.component??"").trim(),d=i?at.get(i):void 0;return d?jsx("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:jsx(d,{...n.props||{}})},a):jsxs("div",{style:{borderRadius:"12px",padding:"16px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:[jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:t.mutedTextColor},children:[jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:t.accentColor,border:`1px solid ${t.borderColor}`},children:"UI"}),jsx("span",{children:i||"component"}),jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(n.props??{},null,2)})]},a)}return jsx("div",{style:{borderRadius:"12px",padding:"16px",fontSize:"14px",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`},children:jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(n,null,2)})},a)}return null})})}let q=Vt[g],t={primaryColor:b||q.primaryColor,backgroundColor:z||q.backgroundColor,borderColor:$||q.borderColor,textColor:O||q.textColor,accentColor:U||q.accentColor,mutedTextColor:q.mutedTextColor,inputBackground:q.inputBackground,cardBackground:q.cardBackground,hoverBackground:q.hoverBackground},vt={backgroundColor:t.backgroundColor,color:t.textColor,height:ge,display:"flex",width:"100%",fontFamily:'Rubik, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif'},wt={width:typeof G=="number"?`${G}px`:G,maxWidth:typeof oe=="number"?`${oe}px`:oe,display:"flex",flexDirection:"column",transition:"all 0.3s ease-out",overflow:"hidden"},Tt={position:"fixed",bottom:typeof m.bottom=="number"?`${m.bottom}px`:m.bottom,right:m.right?typeof m.right=="number"?`${m.right}px`:m.right:void 0,top:m.top?typeof m.top=="number"?`${m.top}px`:m.top:void 0,left:m.left?typeof m.left=="number"?`${m.left}px`:m.left:void 0,zIndex:1e3},Ie=typeof ke=="number"?`${ke}px`:ke,H=useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return jsxs("div",{className:ot,style:vt,dir:f,"data-hsafa-chat":H.current,children:[jsx("div",{style:{display:"flex",alignItems:"stretch",justifyContent:"stretch",width:"100%",height:"100%",transition:"all 0.3s ease-out",padding:V&&tt?"16px":"0"},children:jsx("div",{style:{position:"relative",display:"flex",width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:V&&Ae?Ie:"0"},children:V&&Ae?jsx("div",{style:{width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:Ie,border:y&&ne?"none":`1px solid ${t.borderColor}`,padding:y&&ne?"1.5px":"0",background:y&&ne?`linear-gradient(120deg, ${t.primaryColor}dd 0%, ${t.primaryColor}88 25%, ${t.primaryColor}00 50%, ${t.primaryColor}88 75%, ${t.primaryColor}dd 100%)`:"transparent",backgroundSize:y&&ne?"300% 300%":"auto",animation:y&&ne?`${H.current}-border-flow 3s ease-in-out infinite`:"none",filter:y&&ne?`drop-shadow(0 0 10px ${t.primaryColor}40)`:"none"},children:jsx("div",{className:"content-container",style:{width:"100%",height:"100%",borderRadius:Ie,backgroundColor:t.backgroundColor,overflowY:"auto",overflowX:"hidden",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${t.mutedTextColor}40 transparent`},children:p})}):jsx("div",{className:"content-container",style:{width:"100%",height:"100%",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",overflowY:"auto",overflowX:"hidden",scrollbarWidth:"thin",scrollbarColor:`${t.mutedTextColor}40 transparent`},children:p})})}),jsxs("div",{className:nt,style:{...wt,height:ge,backgroundColor:V||w?t.backgroundColor:"transparent",...V||w?Pe&&I?{position:"fixed",inset:"0",zIndex:1050,width:"100%",maxWidth:"100%",padding:"24px"}:{padding:"24px 16px",opacity:1,transform:"translateX(0)",pointerEvents:"auto"}:{width:"0",maxWidth:"0",padding:"24px 0",opacity:0,transform:f==="rtl"?"translateX(8px)":"translateX(-8px)",pointerEvents:"none"}},children:[jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:He,style:{color:t.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:He})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:t.mutedTextColor},children:[I&&jsx("button",{"aria-label":Pe?"Minimize":"Maximize",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{xe(true),ct(e=>!e);},children:jsx(IconArrowsMaximize,{size:20,stroke:2})}),jsx("button",{"aria-label":"New",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{if(!y){M([]),_(null),Y(null),j.current=false,Z.current=null;try{localStorage.removeItem(J);}catch{}}},children:jsx(IconPlus,{size:20,stroke:2})}),jsx("button",{"aria-label":"History",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>we(e=>!e),ref:ft,children:jsx(IconHistory,{size:20,stroke:2})}),st&&(()=>{let e=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:()=>we(false)}),jsxs("div",{ref:xt,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:`${t.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 ${t.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:Oe,onChange:n=>it(n.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:t.inputBackground,padding:"8px 12px",fontSize:"14px",color:t.textColor,border:`1px solid ${t.borderColor}`,outline:"none"},onFocus:n=>n.currentTarget.style.borderColor=t.primaryColor,onBlur:n=>n.currentTarget.style.borderColor=t.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let n=Oe.toLowerCase().trim(),r=$e();return n&&(r=r.filter(a=>(a.title||"").toLowerCase().includes(n))),!r||r.length===0?jsx("div",{style:{padding:"24px",color:t.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:r.map((a,i)=>jsx("div",{style:{borderTop:i>0?`1px solid ${t.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===S?t.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:t.textColor},onMouseEnter:d=>d.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor="transparent",onClick:()=>{let d=qe(a.id);if(d){Y(a.id),j.current=true,M(d.messages||[]);try{localStorage.setItem(J,a.id);}catch{}we(false),xe(true);}},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:t.textColor},children:a.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:t.mutedTextColor},children:Xt(a.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:t.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:d=>{d.currentTarget.style.color="#ef4444",d.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",d.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:d=>{d.currentTarget.style.color=t.mutedTextColor,d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.borderColor="transparent";},onClick:d=>{d.stopPropagation(),ht(a.id),lt(B=>B+1);},children:jsx(IconTrash,{size:16,stroke:2})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(e,document.body):e})(),!w&&jsx("button",{"aria-label":"Close chat",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>xe(false),children:jsx(IconChevronRight,{size:20,stroke:2,style:{transform:f==="rtl"?"rotate(180deg)":"none"}})})]})]}),jsxs("div",{className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth"},ref:pt,onScroll:e=>{let n=e.currentTarget,i=n.scrollHeight-(n.scrollTop+n.clientHeight)<=64;i!==Te&&gt(i);},children:[De&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",backgroundColor:"rgba(239, 68, 68, 0.1)",color:"#fca5a5",border:"1px solid rgba(239, 68, 68, 0.3)",padding:"12px",fontSize:"14px"},children:De}),A.length===0&&!y&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.accentColor,color:t.mutedTextColor},children:"Start by sending a message to the agent."}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:A.map((e,n)=>jsx("div",{style:{padding:"0 4px"},children:e.role==="user"?dt===e.id?jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${t.primaryColor}`,backgroundColor:t.accentColor,color:t.textColor},children:[jsx("textarea",{autoFocus:true,style:{width:"100%",resize:"none",backgroundColor:"transparent",padding:"8px",lineHeight:"1.6",outline:"none",border:"none",color:"inherit",fontFamily:"inherit",fontSize:"inherit"},rows:Math.max(2,Math.min(10,Math.ceil((be||e.text).length/60))),value:be,onChange:r=>je(r.target.value),onKeyDown:r=>{r.key==="Escape"?ye(null):r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),y||Le(e.id,be||e.text));}}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",padding:"8px 8px 8px 0"},children:[jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"background-color 0.2s",border:`1px solid ${t.borderColor}`,color:t.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:r=>r.currentTarget.style.backgroundColor=t.inputBackground,onMouseLeave:r=>r.currentTarget.style.backgroundColor="transparent",onClick:()=>ye(null),children:"Cancel"}),jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${t.borderColor}`,backgroundColor:t.cardBackground,color:t.textColor,cursor:"pointer"},onMouseEnter:r=>r.currentTarget.style.borderColor=t.primaryColor,onMouseLeave:r=>r.currentTarget.style.borderColor=t.borderColor,onClick:()=>{y||Le(e.id,be||e.text);},children:"Save"})]})]}):jsx("div",{title:"Click to edit",onClick:()=>{y||(ye(e.id),je(e.text));},style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:t.accentColor,color:t.textColor},onMouseEnter:r=>r.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:r=>r.currentTarget.style.backgroundColor=t.accentColor,children:e.text}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.reasoning&&jsxs("div",{style:{borderRadius:"12px",padding:"12px",cursor:"pointer",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},onClick:()=>{Se.current=true,M(r=>r.map(a=>a.id===e.id&&a.role==="assistant"?{...a,reasoningOpen:!a.reasoningOpen}:a));},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[jsx("div",{style:{fontSize:"12px",color:t.mutedTextColor},children:"Reasoning"}),jsx("button",{type:"button",style:{fontSize:"12px",transition:"color 0.2s",color:t.mutedTextColor,background:"none",border:"none",cursor:"pointer"},onMouseEnter:r=>r.currentTarget.style.color=t.textColor,onMouseLeave:r=>r.currentTarget.style.color=t.mutedTextColor,children:e.reasoningOpen?"Hide":"Show full"})]}),e.reasoningOpen?jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:e.reasoning}):(()=>{let r=(e.reasoning||"").trim().split(`
4
- `).filter(i=>i.trim()),a=r.length>0?r[r.length-1]:"";return jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:a||"\u2026"})})()]}),kt(e.items),y&&n===A.length-1&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:t.mutedTextColor},children:[jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:t.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsx("span",{children:"Working\u2026"})]})]})},e.id))}),jsx("div",{ref:We})]}),jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:t.backgroundColor},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 ${t.borderColor}`,backgroundColor:t.accentColor},children:[jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{"aria-label":"Prompt",rows:2,style:{height:"auto",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:t.textColor,fontFamily:"inherit"},placeholder:rt,value:ie,onChange:e=>Ne(e.target.value),onKeyDown:e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),y||Ke());},ref:ut})}),jsxs("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:t.mutedTextColor},children:[jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Attach files",children:jsx(IconPaperclip,{size:18,stroke:2})}),jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Insert link",children:jsx(IconLink,{size:18,stroke:2})})]}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:jsx("button",{"aria-label":y?"Stop":"Send",disabled:!y&&!ie.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${y?"#ef4444":t.borderColor}`,backgroundColor:y?"#ef444420":t.cardBackground,color:y?"#ef4444":t.mutedTextColor,opacity:!y&&!ie.trim()?.4:1,cursor:!y&&!ie.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.disabled||(y?(e.currentTarget.style.borderColor="#dc2626",e.currentTarget.style.backgroundColor="#dc262630",e.currentTarget.style.color="#dc2626"):(e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor));},onMouseLeave:e=>{e.currentTarget.disabled||(y?(e.currentTarget.style.borderColor="#ef4444",e.currentTarget.style.backgroundColor="#ef444420",e.currentTarget.style.color="#ef4444"):(e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.cardBackground,e.currentTarget.style.color=t.mutedTextColor));},onClick:()=>{y?Ct():Ke();},children:y?jsx(IconPlayerStop,{size:18,stroke:2}):jsx(IconArrowUp,{size:18,stroke:2})})})]})})})]}),!V&&!w&&jsx("button",{"aria-label":"Open chat",onClick:()=>xe(true),style:{...Tt,borderColor:t.borderColor,backgroundColor:t.accentColor,color:t.textColor,borderRadius:"50%",border:`1px solid ${t.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=`${t.accentColor}dd`;},onMouseLeave:e=>{e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.accentColor;},children:jsx(IconMessage,{size:20,stroke:2})}),jsx("style",{children:`
1
+ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createContext,useState,useCallback,useRef,useEffect,useMemo,useContext}from'react';import {createPortal}from'react-dom';import {IconArrowsMaximize,IconPlus,IconHistory,IconTrash,IconChevronRight,IconPaperclip,IconLink,IconPlayerStop,IconArrowUp,IconMessage}from'@tabler/icons-react';var re={};var or=({variant:l="primary",size:x="md",loading:m=false,disabled:v,children:N,className:A,...P})=>{let q=[re.button,re[l],re[x],m&&re.loading,A].filter(Boolean).join(" ");return jsxs("button",{className:q,disabled:v||m,...P,children:[m&&jsx("span",{className:re.spinner}),jsx("span",{className:m?re.hiddenText:void 0,children:N})]})};function ir(l=false){let[x,m]=useState(l),v=useCallback(()=>m(P=>!P),[]),N=useCallback(()=>m(true),[]),A=useCallback(()=>m(false),[]);return {on:x,toggle:v,setOn:m,setTrue:N,setFalse:A}}function dr(){let l=useRef(null);return useEffect(()=>{let x=l.current;if(!x)return;let m=new MutationObserver(()=>{x.scrollTop=x.scrollHeight;});return m.observe(x,{childList:true,subtree:true}),x.scrollTop=x.scrollHeight,()=>m.disconnect()},[]),l}var Ge=createContext(void 0);function Ft({baseUrl:l,children:x}){let[m,v]=useState(new Map),[N,A]=useState(new Map),P=useCallback((H,M)=>(v(D=>{let h=new Map(D);return h.set(String(H),M),h}),()=>{v(D=>{let h=new Map(D),w=h.get(String(H));return (!M||w===M)&&h.delete(String(H)),h});}),[]),q=useCallback((H,M)=>{v(D=>{let h=new Map(D),w=h.get(String(H));return (!M||w===M)&&h.delete(String(H)),h});},[]),Q=useCallback((H,M)=>(A(D=>{let h=new Map(D);return h.set(String(H),M),h}),()=>{A(D=>{let h=new Map(D),w=h.get(String(H));return (!M||w===M)&&h.delete(String(H)),h});}),[]),ne=useCallback((H,M)=>{A(D=>{let h=new Map(D),w=h.get(String(H));return (!M||w===M)&&h.delete(String(H)),h});},[]),fe=useMemo(()=>({baseUrl:l,actions:m,components:N,registerAction:P,unregisterAction:q,registerComponent:Q,unregisterComponent:ne}),[l,m,N,P,q,Q,ne]);return jsx(Ge.Provider,{value:fe,children:x})}function oe(){let l=useContext(Ge);return l||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{}}}function br(l,x){let{registerAction:m}=oe(),v=useRef(x);useEffect(()=>{v.current=x;},[x]),useEffect(()=>!l||typeof v.current!="function"?void 0:m(l,(A,P)=>v.current(A,P)),[l,m]);}function vr(l,x){let{registerComponent:m}=oe(),v=useRef(x);useEffect(()=>{v.current=x;},[x]),useEffect(()=>!l||typeof v.current!="function"?void 0:m(l,v.current),[l,m]);}function Yt(l){let x=Date.now()-l,m=Math.max(1,Math.floor(x/1e3));if(m<60)return `${m}s`;let v=Math.floor(m/60);if(v<60)return `${v}m`;let N=Math.floor(v/60);if(N<24)return `${N}h`;let A=Math.floor(N/24);if(A<7)return `${A}d`;let P=Math.floor(A/7);if(P<4)return `${P}w`;let q=Math.floor(A/30);return q<12?`${q}mo`:`${Math.floor(q/12)}y`}function rt(l,x){if(!l)return x;let m=l.endsWith("/")?l.slice(0,-1):l,v=x.startsWith("/")?x:`/${x}`;return `${m}${v}`}var Zt={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 Gt({agentId:l,children:x,theme:m="dark",primaryColor:v,backgroundColor:N,borderColor:A,textColor:P,accentColor:q,width:Q=420,maxWidth:ne=420,height:fe="100vh",expandable:H=true,alwaysOpen:M=false,defaultOpen:D=true,dir:h="ltr",floatingButtonPosition:w=h==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},enableBorderAnimation:ae=true,enableContentPadding:ot=true,borderRadius:ve=16,enableContentBorder:ze=true,placeholder:nt="Ask your question...",title:Ee="Agent",className:at="",chatContainerClassName:st=""}){let{baseUrl:Be,actions:Fe,components:it}=oe(),ye=`hsafaChat_${l}`,Ne=`${ye}.chats`,we=e=>`${ye}.chat.${e}`,_=`${ye}.currentChatId`,De=`${ye}.showChat`,[le,Le]=useState(""),[Y,xe]=useState(()=>{if(M)return true;try{let e=localStorage.getItem(De);return e!==null?e==="true":D}catch{return D}});async function Oe(e,a){if(!l)return;let o=a.trim();if(!o)return;K(null),se(true);let n=E.findIndex(g=>g.id===e);if(n===-1||E[n].role!=="user"){se(false);return}let u=E.slice(0,n),c={id:e,role:"user",text:o},p=pe(),d=[...u,c,{id:p,role:"assistant",items:[],reasoning:"",reasoningOpen:false,mcpToolCalls:[],mcpToolResults:{}}];T(d),me(null);try{let g=[...u.map(L=>L.role==="user"?{role:"user",content:L.text}:{role:"assistant",items:Array.isArray(L.items)?L.items:[]}),{role:"user",content:o}],z={prompt:o,chatId:I??void 0,messages:g};T(L=>L.map(X=>X.id===p||X.id===e?{...X,requestParams:z}:X));let S=await fetch(rt(Be,`/api/run/${l}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)});if(!S.ok||!S.body){let L=await S.text().catch(()=>"");throw new Error(L||`Request failed with ${S.status}`)}let R=S.body.getReader(),te=new TextDecoder,j="";for(;;){let{done:L,value:X}=await R.read();if(L)break;j+=te.decode(X,{stream:!0});let f;for(;(f=j.indexOf(`
2
+ `))!==-1;){let $=j.slice(0,f).trim();if(j=j.slice(f+1),!!$)try{let i=JSON.parse($);if(i?.type==="meta"){if(i.actionExecuteMap&&typeof i.actionExecuteMap=="object"&&(Re.current=i.actionExecuteMap),i.assistantMessageId&&(ie.current=String(i.assistantMessageId),he.current.clear(),Ce.current.clear(),J.current.clear(),ee(new Map)),i.chatId&&!I){Z(i.chatId),U.current=!0;let s=o,C=(G.current||s||"New chat").slice(0,80),y=Date.now();ue({id:i.chatId,title:C,createdAt:y,updatedAt:y}),de({id:i.chatId,messages:d,agentId:l});try{localStorage.setItem(_,i.chatId);}catch{}}continue}if(i?.type==="reasoning"){let s=String(i.text??"");T(C=>C.map(y=>y.id===p&&y.role==="assistant"?{...y,reasoning:(y.reasoning??"")+s}:y));continue}if(i?.type==="tool-call"){let s=i.toolName,C=i.args;T(y=>y.map(W=>W.id===p&&W.role==="assistant"?{...W,mcpToolCalls:[...W.mcpToolCalls||[],{toolName:s,args:C,timestamp:Date.now(),status:"running"}]}:W));continue}if(i?.type==="tool-result"){let s=i.toolName,C=i.result;T(y=>y.map(W=>W.id===p&&W.role==="assistant"?{...W,mcpToolCalls:(W.mcpToolCalls||[]).map(Ae=>Ae.toolName===s?{...Ae,status:"completed"}:Ae),mcpToolResults:{...W.mcpToolResults||{},[s]:C}}:W));continue}if(i?.type==="partial"||i?.type==="final"){let s=i.value;s&&Array.isArray(s.items)&&(T(C=>C.map(y=>y.id===p&&y.role==="assistant"?{...y,items:s.items}:y)),_e(s.items,i.type==="partial"?"partial":"final")),i?.type==="final"&&T(C=>C.map(y=>y.id===p&&y.role==="assistant"?{...y,reasoningOpen:!1}:y));continue}if(i?.type==="usage"){let s=i?.value?.reasoningTokens;typeof s=="number"&&T(C=>C.map(y=>y.id===p&&y.role==="assistant"?{...y,reasoningTokens:s}:y));continue}if(i?.type==="error"){K(String(i.error??"Unknown error"));continue}}catch{}}}}catch(g){K(String(g?.message??g));}finally{if(se(false),!I&&!U.current){let g=`local-${pe()}`;Z(g),U.current=true;let z=(G.current||"New chat").slice(0,80),S=Date.now();ue({id:g,title:z,createdAt:S,updatedAt:S}),de({id:g,messages:E,agentId:l});try{localStorage.setItem(_,g);}catch{}}}}let[E,T]=useState([]),[k,se]=useState(false),[Pe,K]=useState(null),ce=useRef(null),[I,Z]=useState(null),[lt,Te]=useState(false),[je,ct]=useState(""),[er,dt]=useState(0),[We,ut]=useState(false),[pt,me]=useState(null),[be,Ue]=useState(""),gt=useRef(null),Je=useRef(null),ft=useRef(null),[Se,yt]=useState(true),Me=useRef(false),U=useRef(false),G=useRef(null),xt=useRef(null),mt=useRef(null),Re=useRef({}),ie=useRef(void 0),he=useRef(new Set),Ce=useRef(new Map),J=useRef(new Map),[bt,ee]=useState(new Map),qe=useCallback((e,a)=>{let o=Ce.current.get(e)||[],n=JSON.stringify(a);if(o.push(n),o.length>5&&o.shift(),Ce.current.set(e,o),o.length>=3){let u=o.slice(-3);return u.every(c=>c===u[0])}return false},[]),_e=useCallback((e,a)=>{!Array.isArray(e)||e.length===0||e.forEach((o,n)=>{if(!(!o||typeof o!="object")&&o.type==="action"){let u=String(o.name??"").trim();if(!u)return;let c=Fe.get(u);if(!c){console.warn(`Action handler not found for: ${u}`);return}let p=!!Re.current[u],d=`${ie.current||"assist"}:${u}:${n}`,g=`${u}:${n}`;try{if(a==="partial"&&p){ee(S=>new Map(S).set(g,"executing"));let z=setTimeout(()=>{Promise.resolve(c(o.params,{name:u,trigger:a,index:n,assistantMessageId:ie.current,chatId:I||void 0})).catch(S=>{console.error(`Error executing streaming action ${u}:`,S),ee(R=>new Map(R).set(g,"executed"));});},50);J.current.set(`${g}_timeout`,z);}else if(a==="partial"&&!p){let z=qe(g,o.params),S=J.current.get(g);z&&S!=="executed"?(J.current.set(g,"executed"),ee(R=>new Map(R).set(g,"executed")),Promise.resolve(c(o.params,{name:u,trigger:"params_complete",index:n,assistantMessageId:ie.current,chatId:I||void 0})).catch(R=>{console.error(`Error executing stabilized action ${u}:`,R);})):S||(J.current.set(g,"executing"),ee(R=>new Map(R).set(g,"executing")));}else if(a==="final"&&J.current.get(g)!=="executed"&&!he.current.has(d)){he.current.add(d);let S=J.current.get(`${g}_timeout`);S&&(clearTimeout(S),J.current.delete(`${g}_timeout`)),J.current.set(g,"executed"),ee(R=>new Map(R).set(g,"executed")),Promise.resolve(c(o.params,{name:u,trigger:p?"final":"params_complete",index:n,assistantMessageId:ie.current,chatId:I||void 0})).catch(R=>{console.error(`Error executing final action ${u}:`,R);});}}catch(z){console.error(`Error processing action ${u}:`,z);}}});},[Fe,I,qe]),$e=()=>{try{let e=localStorage.getItem(Ne);return e?JSON.parse(e):[]}catch{return []}},Ke=e=>{try{localStorage.setItem(Ne,JSON.stringify(e));}catch{}},Ve=e=>{try{let a=localStorage.getItem(we(e));return a?JSON.parse(a):null}catch{return null}},de=e=>{try{localStorage.setItem(we(e.id),JSON.stringify(e));}catch{}},ue=e=>{let a=$e(),o=a.findIndex(n=>n.id===e.id);o>=0?a[o]=e:a.unshift(e),Ke(a);},ht=e=>{let o=$e().filter(n=>n.id!==e);Ke(o);},Ct=e=>{try{localStorage.removeItem(we(e));}catch{}},kt=e=>{if(Ct(e),ht(e),I===e){T([]),K(null),Z(null),U.current=false,G.current=null;try{localStorage.removeItem(_);}catch{}}};useEffect(()=>{if(Me.current){Me.current=false;return}Se&&Je.current?.scrollIntoView({behavior:"smooth",block:"end"});},[E,k,Se]),useEffect(()=>{try{let e=localStorage.getItem(_);if(e){let a=Ve(e);a&&(Z(a.id),U.current=!0,T(a.messages||[]));}}catch{}},[]),useEffect(()=>{try{localStorage.setItem(De,String(Y));}catch{}},[Y]),useEffect(()=>()=>{J.current.forEach((e,a)=>{a.endsWith("_timeout")&&clearTimeout(e);});},[]),useEffect(()=>{if(!I||!U.current)return;de({id:I,messages:E,agentId:l});let a=E.find(u=>u.role==="user"),o=(G.current||(a?.text??"New chat")).slice(0,80),n={id:I,title:o,createdAt:Date.now(),updatedAt:Date.now()};ue(n);try{localStorage.setItem(_,I);}catch{}},[E,I,l]);let pe=()=>`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;function vt(){ce.current&&(ce.current.abort(),ce.current=null),se(false),K("Request stopped by user");}async function Xe(){if(!l)return;let e=le.trim();if(!e)return;K(null),se(true),!I&&E.length===0&&(G.current=e);let a=pe(),o=pe(),n={id:a,role:"user",text:e},u={id:o,role:"assistant",items:[],reasoning:"",reasoningOpen:false,mcpToolCalls:[],mcpToolResults:{}},c=[...E,n,u],p=[...E.map(d=>d.role==="user"?{role:"user",content:d.text}:{role:"assistant",items:Array.isArray(d.items)?d.items:[]}),{role:"user",content:e}];T(c),Le("");try{ce.current=new AbortController;let d={prompt:e,chatId:I??void 0,messages:p};T(te=>te.map(j=>j.id===o||j.id===a?{...j,requestParams:d}:j));let g=await fetch(rt(Be,`/api/run/${l}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:ce.current.signal});if(!g.ok||!g.body){let te=await g.text().catch(()=>"");throw new Error(te||`Request failed with ${g.status}`)}let z=g.body.getReader(),S=new TextDecoder,R="";for(;;){let{done:te,value:j}=await z.read();if(te)break;R+=S.decode(j,{stream:!0});let L;for(;(L=R.indexOf(`
3
+ `))!==-1;){let X=R.slice(0,L).trim();if(R=R.slice(L+1),!!X)try{let f=JSON.parse(X);if(f?.type==="meta"){if(f.actionExecuteMap&&typeof f.actionExecuteMap=="object"&&(Re.current=f.actionExecuteMap),f.assistantMessageId&&(ie.current=String(f.assistantMessageId),he.current.clear(),Ce.current.clear(),J.current.clear(),ee(new Map)),f.chatId&&!I){Z(f.chatId),U.current=!0;let $=e,i=(G.current||$||"New chat").slice(0,80),s=Date.now();ue({id:f.chatId,title:i,createdAt:s,updatedAt:s}),de({id:f.chatId,messages:c,agentId:l});try{localStorage.setItem(_,f.chatId);}catch{}}continue}if(f?.type==="reasoning"){let $=String(f.text??"");T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,reasoning:(s.reasoning??"")+$}:s));continue}if(f?.type==="tool-call"){let $=f.toolName,i=f.args;T(s=>s.map(C=>C.id===o&&C.role==="assistant"?{...C,mcpToolCalls:[...C.mcpToolCalls||[],{toolName:$,args:i,timestamp:Date.now(),status:"running"}]}:C));continue}if(f?.type==="tool-result"){let $=f.toolName,i=f.result;T(s=>s.map(C=>C.id===o&&C.role==="assistant"?{...C,mcpToolCalls:(C.mcpToolCalls||[]).map(y=>y.toolName===$?{...y,status:"completed"}:y),mcpToolResults:{...C.mcpToolResults||{},[$]:i}}:C));continue}if(f?.type==="partial"||f?.type==="final"){let $=f.value;$&&Array.isArray($.items)&&(T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,items:$.items}:s)),_e($.items,f.type==="partial"?"partial":"final")),f?.type==="final"&&T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,reasoningOpen:!1}:s));continue}if(f?.type==="usage"){let $=f?.value?.reasoningTokens;typeof $=="number"&&T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,reasoningTokens:$}:s));continue}if(f?.type==="error"){K(String(f.error??"Unknown error"));continue}}catch{}}}}catch(d){K(String(d?.message??d));}finally{if(se(false),!I&&!U.current){let d=`local-${pe()}`;Z(d),U.current=true;let g=(G.current||"New chat").slice(0,80),z=Date.now();ue({id:d,title:g,createdAt:z,updatedAt:z}),de({id:d,messages:E,agentId:l});try{localStorage.setItem(_,d);}catch{}}}}function wt(e,a,o){return !Array.isArray(e)||e.length===0?null:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.map((n,u)=>{let c=`it-${u}`;if(typeof n=="string")return jsx("div",{style:{borderRadius:"12px",padding:"16px",fontSize:"14px",whiteSpace:"pre-wrap",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`,color:t.textColor},children:n},c);if(n&&typeof n=="object"){if(n.type==="action"){let p=`${String(n.name??"action")}:${u}`,d=bt.get(p);return jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsx("div",{style:{padding:"8px",fontSize:"12px",color:t.mutedTextColor},children:d==="executing"?jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxs("svg",{style:{animation:"spin 1s linear infinite",height:"12px",width:"12px"},xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{style:{opacity:.75},fill:"currentColor",d:"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),String(n.name??"action")," is executing"]}):jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:"#10b981"}}),String(n.name??"action")," has executed"]})})},c)}if(n.type==="ui-component"||n.type==="ui"){let p=String(n.name??n.component??"").trim(),d=p?it.get(p):void 0;return d?jsx("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:jsx(d,{...n.props||{}})},c):jsxs("div",{style:{borderRadius:"12px",padding:"16px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:[jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:t.mutedTextColor},children:[jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:t.accentColor,border:`1px solid ${t.borderColor}`},children:"UI"}),jsx("span",{children:p||"component"}),jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(n.props??{},null,2)})]},c)}return jsx("div",{style:{borderRadius:"12px",padding:"16px",fontSize:"14px",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`},children:jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(n,null,2)})},c)}return null}),a&&a.length>0&&(()=>{let n=new Map;a.forEach(p=>{let d=n.get(p.toolName);!d||d.status==="running"&&p.status==="completed"?n.set(p.toolName,{status:p.status||"pending",count:(d?.count||0)+1}):d&&d.count++;});let u=Array.from(n.values()).some(p=>p.status==="running"),c=Array.from(n.values()).filter(p=>p.status==="completed").length;return jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`,fontSize:"12px",color:t.mutedTextColor},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:u?"#3b82f6":"#10b981"}}),jsx("span",{children:u?"Agent is using tools":c>0?`Agent used ${c} tool${c>1?"s":""}`:"Agent used tools"})]}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Array.from(n.entries()).map(([p,d])=>jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:[d.status==="running"?jsxs("svg",{style:{animation:"spin 1s linear infinite",height:"8px",width:"8px",flexShrink:0},xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{style:{opacity:.75},fill:"currentColor",d:"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):jsx("span",{style:{display:"inline-block",height:"4px",width:"4px",borderRadius:"50%",backgroundColor:d.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:p}),d.count>1&&jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",d.count]})]},p))})]})})()]})}let V=Zt[m],t={primaryColor:v||V.primaryColor,backgroundColor:N||V.backgroundColor,borderColor:A||V.borderColor,textColor:P||V.textColor,accentColor:q||V.accentColor,mutedTextColor:V.mutedTextColor,inputBackground:V.inputBackground,cardBackground:V.cardBackground,hoverBackground:V.hoverBackground},Tt={backgroundColor:t.backgroundColor,color:t.textColor,height:fe,display:"flex",width:"100%",fontFamily:'Rubik, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif'},St={width:typeof Q=="number"?`${Q}px`:Q,maxWidth:typeof ne=="number"?`${ne}px`:ne,display:"flex",flexDirection:"column",transition:"all 0.3s ease-out",overflow:"hidden"},Mt={position:"fixed",bottom:typeof w.bottom=="number"?`${w.bottom}px`:w.bottom,right:w.right?typeof w.right=="number"?`${w.right}px`:w.right:void 0,top:w.top?typeof w.top=="number"?`${w.top}px`:w.top:void 0,left:w.left?typeof w.left=="number"?`${w.left}px`:w.left:void 0,zIndex:1e3},Ie=typeof ve=="number"?`${ve}px`:ve,B=useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return jsxs("div",{className:at,style:Tt,dir:h,"data-hsafa-chat":B.current,children:[jsx("div",{style:{display:"flex",alignItems:"stretch",justifyContent:"stretch",width:"100%",height:"100%",transition:"all 0.3s ease-out",padding:Y&&ot?"16px":"0"},children:jsx("div",{style:{position:"relative",display:"flex",width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:Y&&ze?Ie:"0"},children:Y&&ze?jsx("div",{style:{width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:Ie,border:k&&ae?"none":`1px solid ${t.borderColor}`,padding:k&&ae?"1.5px":"0",background:k&&ae?`linear-gradient(120deg, ${t.primaryColor}dd 0%, ${t.primaryColor}88 25%, ${t.primaryColor}00 50%, ${t.primaryColor}88 75%, ${t.primaryColor}dd 100%)`:"transparent",backgroundSize:k&&ae?"300% 300%":"auto",animation:k&&ae?`${B.current}-border-flow 3s ease-in-out infinite`:"none",filter:k&&ae?`drop-shadow(0 0 10px ${t.primaryColor}40)`:"none"},children:jsx("div",{className:"content-container",style:{width:"100%",height:"100%",borderRadius:Ie,backgroundColor:t.backgroundColor,overflowX:"hidden",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${t.mutedTextColor}40 transparent`},children:x})}):jsx("div",{className:"content-container",style:{width:"100%",height:"100%",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",overflowX:"hidden",scrollbarWidth:"thin",scrollbarColor:`${t.mutedTextColor}40 transparent`},children:x})})}),jsxs("div",{className:st,style:{...St,height:fe,backgroundColor:Y||M?t.backgroundColor:"transparent",...Y||M?We&&H?{position:"fixed",inset:"0",zIndex:1050,width:"100%",maxWidth:"100%",padding:"24px"}:{padding:"24px 16px",opacity:1,transform:"translateX(0)",pointerEvents:"auto"}:{width:"0",maxWidth:"0",padding:"24px 0",opacity:0,transform:h==="rtl"?"translateX(8px)":"translateX(-8px)",pointerEvents:"none"}},children:[jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:Ee,style:{color:t.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:Ee})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:t.mutedTextColor},children:[H&&jsx("button",{"aria-label":We?"Minimize":"Maximize",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{xe(true),ut(e=>!e);},children:jsx(IconArrowsMaximize,{size:20,stroke:2})}),jsx("button",{"aria-label":"New",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{if(!k){T([]),K(null),Z(null),U.current=false,G.current=null;try{localStorage.removeItem(_);}catch{}}},children:jsx(IconPlus,{size:20,stroke:2})}),jsx("button",{"aria-label":"History",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>Te(e=>!e),ref:xt,children:jsx(IconHistory,{size:20,stroke:2})}),lt&&(()=>{let e=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:()=>Te(false)}),jsxs("div",{ref:mt,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:`${t.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 ${t.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:je,onChange:a=>ct(a.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:t.inputBackground,padding:"8px 12px",fontSize:"14px",color:t.textColor,border:`1px solid ${t.borderColor}`,outline:"none"},onFocus:a=>a.currentTarget.style.borderColor=t.primaryColor,onBlur:a=>a.currentTarget.style.borderColor=t.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let a=je.toLowerCase().trim(),o=$e();return a&&(o=o.filter(n=>(n.title||"").toLowerCase().includes(a))),!o||o.length===0?jsx("div",{style:{padding:"24px",color:t.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:o.map((n,u)=>jsx("div",{style:{borderTop:u>0?`1px solid ${t.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:n.id===I?t.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:t.textColor},onMouseEnter:c=>c.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:c=>c.currentTarget.style.backgroundColor="transparent",onClick:()=>{let c=Ve(n.id);if(c){Z(n.id),U.current=true,T(c.messages||[]);try{localStorage.setItem(_,n.id);}catch{}Te(false),xe(true);}},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:t.textColor},children:n.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:t.mutedTextColor},children:Yt(n.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:t.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:c=>{c.currentTarget.style.color="#ef4444",c.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",c.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:c=>{c.currentTarget.style.color=t.mutedTextColor,c.currentTarget.style.backgroundColor="transparent",c.currentTarget.style.borderColor="transparent";},onClick:c=>{c.stopPropagation(),kt(n.id),dt(p=>p+1);},children:jsx(IconTrash,{size:16,stroke:2})})]})},n.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(e,document.body):e})(),!M&&jsx("button",{"aria-label":"Close chat",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>xe(false),children:jsx(IconChevronRight,{size:20,stroke:2,style:{transform:h==="rtl"?"rotate(180deg)":"none"}})})]})]}),jsxs("div",{className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth"},ref:ft,onScroll:e=>{let a=e.currentTarget,u=a.scrollHeight-(a.scrollTop+a.clientHeight)<=64;u!==Se&&yt(u);},children:[Pe&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",backgroundColor:"rgba(239, 68, 68, 0.1)",color:"#fca5a5",border:"1px solid rgba(239, 68, 68, 0.3)",padding:"12px",fontSize:"14px"},children:Pe}),E.length===0&&!k&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.accentColor,color:t.mutedTextColor},children:"Start by sending a message to the agent."}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:E.map((e,a)=>jsx("div",{style:{padding:"0 4px"},children:e.role==="user"?pt===e.id?jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${t.primaryColor}`,backgroundColor:t.accentColor,color:t.textColor},children:[jsx("textarea",{autoFocus:true,style:{width:"100%",resize:"none",backgroundColor:"transparent",padding:"8px",lineHeight:"1.6",outline:"none",border:"none",color:"inherit",fontFamily:"inherit",fontSize:"inherit"},rows:Math.max(2,Math.min(10,Math.ceil((be||e.text).length/60))),value:be,onChange:o=>Ue(o.target.value),onKeyDown:o=>{o.key==="Escape"?me(null):o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),k||Oe(e.id,be||e.text));}}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",padding:"8px 8px 8px 0"},children:[jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"background-color 0.2s",border:`1px solid ${t.borderColor}`,color:t.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:o=>o.currentTarget.style.backgroundColor=t.inputBackground,onMouseLeave:o=>o.currentTarget.style.backgroundColor="transparent",onClick:()=>me(null),children:"Cancel"}),jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${t.borderColor}`,backgroundColor:t.cardBackground,color:t.textColor,cursor:"pointer"},onMouseEnter:o=>o.currentTarget.style.borderColor=t.primaryColor,onMouseLeave:o=>o.currentTarget.style.borderColor=t.borderColor,onClick:()=>{k||Oe(e.id,be||e.text);},children:"Save"})]})]}):jsx("div",{title:"Click to edit",onClick:()=>{k||(me(e.id),Ue(e.text));},style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:t.accentColor,color:t.textColor},onMouseEnter:o=>o.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:o=>o.currentTarget.style.backgroundColor=t.accentColor,children:e.text}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.reasoning&&jsxs("div",{style:{borderRadius:"12px",padding:"12px",cursor:"pointer",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},onClick:()=>{Me.current=true,T(o=>o.map(n=>n.id===e.id&&n.role==="assistant"?{...n,reasoningOpen:!n.reasoningOpen}:n));},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[jsx("div",{style:{fontSize:"12px",color:t.mutedTextColor},children:"Reasoning"}),jsx("button",{type:"button",style:{fontSize:"12px",transition:"color 0.2s",color:t.mutedTextColor,background:"none",border:"none",cursor:"pointer"},onMouseEnter:o=>o.currentTarget.style.color=t.textColor,onMouseLeave:o=>o.currentTarget.style.color=t.mutedTextColor,children:e.reasoningOpen?"Hide":"Show full"})]}),e.reasoningOpen?jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:e.reasoning}):(()=>{let o=(e.reasoning||"").trim().split(`
4
+ `).filter(u=>u.trim()),n=o.length>0?o[o.length-1]:"";return jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:n||"\u2026"})})()]}),wt(e.items,e.mcpToolCalls,e.mcpToolResults),k&&a===E.length-1&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:t.mutedTextColor},children:[jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:t.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsx("span",{children:"Working\u2026"})]})]})},e.id))}),jsx("div",{ref:Je})]}),jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:t.backgroundColor},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 ${t.borderColor}`,backgroundColor:t.accentColor},children:[jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{"aria-label":"Prompt",rows:2,style:{height:"auto",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:t.textColor,fontFamily:"inherit"},placeholder:nt,value:le,onChange:e=>Le(e.target.value),onKeyDown:e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),k||Xe());},ref:gt})}),jsxs("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:t.mutedTextColor},children:[jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Attach files",children:jsx(IconPaperclip,{size:18,stroke:2})}),jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Insert link",children:jsx(IconLink,{size:18,stroke:2})})]}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:jsx("button",{"aria-label":k?"Stop":"Send",disabled:!k&&!le.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${k?"#ef4444":t.borderColor}`,backgroundColor:k?"#ef444420":t.cardBackground,color:k?"#ef4444":t.mutedTextColor,opacity:!k&&!le.trim()?.4:1,cursor:!k&&!le.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.disabled||(k?(e.currentTarget.style.borderColor="#dc2626",e.currentTarget.style.backgroundColor="#dc262630",e.currentTarget.style.color="#dc2626"):(e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor));},onMouseLeave:e=>{e.currentTarget.disabled||(k?(e.currentTarget.style.borderColor="#ef4444",e.currentTarget.style.backgroundColor="#ef444420",e.currentTarget.style.color="#ef4444"):(e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.cardBackground,e.currentTarget.style.color=t.mutedTextColor));},onClick:()=>{k?vt():Xe();},children:k?jsx(IconPlayerStop,{size:18,stroke:2}):jsx(IconArrowUp,{size:18,stroke:2})})})]})})})]}),!Y&&!M&&jsx("button",{"aria-label":"Open chat",onClick:()=>xe(true),style:{...Mt,borderColor:t.borderColor,backgroundColor:t.accentColor,color:t.textColor,borderRadius:"50%",border:`1px solid ${t.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=`${t.accentColor}dd`;},onMouseLeave:e=>{e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.accentColor;},children:jsx(IconMessage,{size:20,stroke:2})}),jsx("style",{children:`
5
5
  /* Import Rubik font from Google Fonts */
6
6
  @import url('https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,300..900;1,300..900&display=swap');
7
7
 
8
- @keyframes ${H.current}-border-flow {
8
+ @keyframes ${B.current}-border-flow {
9
9
  0% { background-position: 0% 50%; }
10
10
  50% { background-position: 100% 50%; }
11
11
  100% { background-position: 0% 50%; }
@@ -22,12 +22,12 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createContext,useState
22
22
  }
23
23
 
24
24
  /* Scoped placeholder styles */
25
- [data-hsafa-chat="${H.current}"] textarea::placeholder {
25
+ [data-hsafa-chat="${B.current}"] textarea::placeholder {
26
26
  color: ${t.mutedTextColor};
27
27
  }
28
28
 
29
29
  /* Ensure textarea styles work in all environments */
30
- [data-hsafa-chat="${H.current}"] textarea {
30
+ [data-hsafa-chat="${B.current}"] textarea {
31
31
  background: transparent !important;
32
32
  border: none !important;
33
33
  outline: none !important;
@@ -36,52 +36,52 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createContext,useState
36
36
  }
37
37
 
38
38
  /* Custom scrollbar styles for content container */
39
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar {
39
+ [data-hsafa-chat="${B.current}"] .content-container::-webkit-scrollbar {
40
40
  width: 6px;
41
41
  }
42
42
 
43
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar-track {
43
+ [data-hsafa-chat="${B.current}"] .content-container::-webkit-scrollbar-track {
44
44
  background: transparent;
45
45
  border-radius: 3px;
46
46
  }
47
47
 
48
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar-thumb {
48
+ [data-hsafa-chat="${B.current}"] .content-container::-webkit-scrollbar-thumb {
49
49
  background: ${t.mutedTextColor}40;
50
50
  border-radius: 3px;
51
51
  border: 1px solid transparent;
52
52
  }
53
53
 
54
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar-thumb:hover {
54
+ [data-hsafa-chat="${B.current}"] .content-container::-webkit-scrollbar-thumb:hover {
55
55
  background: ${t.mutedTextColor}60;
56
56
  }
57
57
 
58
58
  /* Chat scrollbar styles */
59
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar {
59
+ [data-hsafa-chat="${B.current}"] .chat-scroll-container::-webkit-scrollbar {
60
60
  width: 4px;
61
61
  }
62
62
 
63
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar-track {
63
+ [data-hsafa-chat="${B.current}"] .chat-scroll-container::-webkit-scrollbar-track {
64
64
  background: transparent;
65
65
  }
66
66
 
67
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar-thumb {
67
+ [data-hsafa-chat="${B.current}"] .chat-scroll-container::-webkit-scrollbar-thumb {
68
68
  background: ${t.borderColor};
69
69
  border-radius: 2px;
70
70
  }
71
71
 
72
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar-thumb:hover {
72
+ [data-hsafa-chat="${B.current}"] .chat-scroll-container::-webkit-scrollbar-thumb:hover {
73
73
  background: ${t.mutedTextColor};
74
74
  }
75
75
 
76
76
  /* Ensure all fixed positioned elements stay within content box */
77
- [data-hsafa-chat="${H.current}"] * {
77
+ [data-hsafa-chat="${B.current}"] * {
78
78
  /* Prevent any child from breaking out of the content container */
79
79
  }
80
80
 
81
81
  /* Force fixed elements to be contained within the content box */
82
- [data-hsafa-chat="${H.current}"] .content-container * {
82
+ [data-hsafa-chat="${B.current}"] .content-container * {
83
83
  /* Any fixed, absolute, or sticky elements will be contained */
84
84
  max-width: 100% !important;
85
85
  }
86
- `})]})}export{tr as Button,Yt as HsafaChat,zt as HsafaProvider,lr as useAutoScroll,re as useHsafa,yr as useHsafaAction,Cr as useHsafaComponent,ar as useToggle};//# sourceMappingURL=index.js.map
86
+ `})]})}export{or as Button,Gt as HsafaChat,Ft as HsafaProvider,dr as useAutoScroll,oe as useHsafa,br as useHsafaAction,vr as useHsafaComponent,ir as useToggle};//# sourceMappingURL=index.js.map
87
87
  //# sourceMappingURL=index.js.map