@hsafa/ui-sdk 0.2.2 → 0.2.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.cjs +15 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +15 -15
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
'use strict';var jsxRuntime=require('react/jsx-runtime'),lucideReact=require('lucide-react'),
|
|
2
|
-
`):""}function
|
|
3
|
-
`).filter(o=>o.trim()),s=a.length>0?a[a.length-1]:"";return jsxRuntime.jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:s||"\u2026"})})()]}):null}function
|
|
1
|
+
'use strict';var jsxRuntime=require('react/jsx-runtime'),lucideReact=require('lucide-react'),Bt=require('react'),reactDom=require('react-dom');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Bt__default=/*#__PURE__*/_interopDefault(Bt);var st={};var Yr=({variant:t="primary",size:n="md",loading:e=false,disabled:r,children:a,className:s,...o})=>{let i=[st.button,st[t],st[n],e&&st.loading,s].filter(Boolean).join(" ");return jsxRuntime.jsxs("button",{className:i,disabled:r||e,...o,children:[e&&jsxRuntime.jsx("span",{className:st.spinner}),jsxRuntime.jsx("span",{className:e?st.hiddenText:void 0,children:a})]})};function Te(t){if(!t||Number.isNaN(t))return "0 B";let n=["B","KB","MB","GB","TB"],e=Math.min(n.length-1,Math.floor(Math.log(t)/Math.log(1024)));return `${(t/Math.pow(1024,e)).toFixed(e===0?0:1)} ${n[e]}`}function ve({attachment:t,resolvedColors:n,mode:e,onRemove:r,maxWidth:a="200px"}){let s=t.mimeType?.startsWith("image/"),o=e==="editable"||e==="input",i=e==="viewable",m={display:"flex",alignItems:"center",gap:e==="input"?"8px":"6px",padding:e==="input"?"8px 12px":"6px 10px",backgroundColor:n.inputBackground,borderRadius:e==="input"?"10px":"8px",border:`1px solid ${n.borderColor}`,fontSize:e==="input"?"12px":"11px",color:n.textColor,transition:"all 0.2s ease-out",cursor:i?"pointer":"default",maxWidth:e==="input"?"140px":a,position:"relative"},y=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:e==="input"?"20px":"16px",height:e==="input"?"20px":"16px",borderRadius:e==="input"?"4px":"3px",backgroundColor:s?"transparent":n.accentColor,flexShrink:0},children:[s?jsxRuntime.jsx("img",{src:t.url,alt:t.name,style:{width:e==="input"?"20px":"16px",height:e==="input"?"20px":"16px",borderRadius:e==="input"?"4px":"3px",objectFit:"cover"},onError:l=>{l.target.style.display="none";let b=l.target.nextElementSibling;b&&(b.style.display="block");}}):null,jsxRuntime.jsx(lucideReact.File,{size:e==="input"?14:10,strokeWidth:"2",style:{display:s?"none":"block",color:n.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsxRuntime.jsx("span",{title:t.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:t.name}),jsxRuntime.jsx("span",{style:{fontSize:e==="input"?"10px":"9px",color:n.mutedTextColor,marginTop:e==="input"?"2px":"1px"},children:Te(t.size)})]}),e==="input"&&s&&jsxRuntime.jsx("button",{onClick:l=>{l.stopPropagation(),window.open(t.url,"_blank");},style:{background:"none",border:"none",color:n.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:l=>{l.currentTarget.style.backgroundColor=n.hoverBackground,l.currentTarget.style.color=n.textColor;},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="transparent",l.currentTarget.style.color=n.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),o&&r&&jsxRuntime.jsx("button",{onClick:l=>{l.stopPropagation(),r(t.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:e==="input"?"auto":"16px",height:e==="input"?"auto":"16px",padding:e==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:n.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="#ef444420",l.currentTarget.style.color="#ef4444";},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="transparent",l.currentTarget.style.color=n.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.X,{size:"12",strokeWidth:"2"})}),i&&jsxRuntime.jsx(lucideReact.Download,{size:"10",strokeWidth:"2",style:{color:n.mutedTextColor,flexShrink:0}})]});return i?jsxRuntime.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",style:{...m,textDecoration:"none"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor=n.hoverBackground,l.currentTarget.style.borderColor=n.primaryColor;},onMouseLeave:l=>{l.currentTarget.style.backgroundColor=n.inputBackground,l.currentTarget.style.borderColor=n.borderColor;},children:y}):jsxRuntime.jsx("div",{style:m,children:y})}function Et({attachments:t,resolvedColors:n,onRemove:e}){if(!Array.isArray(t)||t.length===0)return null;let r=typeof e=="function"?"editable":"viewable";return jsxRuntime.jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:t.map(a=>jsxRuntime.jsx(ve,{attachment:a,resolvedColors:n,mode:r,onRemove:e},a.id))})}function we({messageId:t,initialText:n,editingText:e,onEditingTextChange:r,onCancel:a,onSave:s,streaming:o,resolvedColors:i,attachments:m,onRemoveAttachment:y,onAddAttachments:l,uploading:b,t:c}){let k=Bt__default.default.useRef(null),f=x=>{x.key==="Escape"?a():x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),o||s(t,e||n));},M=x=>{let p=x.target.files;p&&p.length>0&&l&&l(p),k.current&&(k.current.value="");};return jsxRuntime.jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${i.primaryColor}`,backgroundColor:i.accentColor,color:i.textColor},children:[jsxRuntime.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((e||n).length/60))),value:e,onChange:x=>r(x.target.value),onKeyDown:f}),m&&m.length>0&&jsxRuntime.jsx("div",{style:{padding:"8px"},children:jsxRuntime.jsx(Et,{attachments:m,resolvedColors:i,onRemove:y})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",padding:"8px 8px 8px 0"},children:[l&&jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("input",{ref:k,type:"file",multiple:true,onChange:M,style:{display:"none"}}),jsxRuntime.jsx("button",{onClick:()=>k.current?.click(),disabled:b||o,title:c(b?"input.uploadingFiles":"input.attachFiles"),style:{display:"flex",margin:"0 10px",alignItems:"center",justifyContent:"center",borderRadius:"50%",width:"28px",height:"28px",transition:"all 0.2s",border:`1px solid ${i.borderColor}`,color:i.mutedTextColor,backgroundColor:"transparent",cursor:b||o?"not-allowed":"pointer",opacity:b||o?.5:1},onMouseEnter:x=>{!b&&!o&&(x.currentTarget.style.backgroundColor=i.inputBackground,x.currentTarget.style.borderColor=i.primaryColor);},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent",x.currentTarget.style.borderColor=i.borderColor;},children:jsxRuntime.jsx(lucideReact.Plus,{size:16,strokeWidth:2})})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"background-color 0.2s",border:`1px solid ${i.borderColor}`,color:i.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:x=>x.currentTarget.style.backgroundColor=i.inputBackground,onMouseLeave:x=>x.currentTarget.style.backgroundColor="transparent",onClick:a,children:c("editor.cancel")}),jsxRuntime.jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${i.borderColor}`,backgroundColor:i.cardBackground,color:i.textColor,cursor:"pointer"},onMouseEnter:x=>x.currentTarget.style.borderColor=i.primaryColor,onMouseLeave:x=>x.currentTarget.style.borderColor=i.borderColor,onClick:()=>{o||s(t,e||n);},children:c("editor.saveAndRegenerate")})]})]})]})}function Kn(t){return t.mimeType.startsWith("image/")?{type:"image",image:new URL(t.url),mediaType:t.mimeType}:{type:"file",data:t.url,mediaType:t.mimeType,name:t.name}}function Yt(t,n){let e=(t||"").trim();if(!n||n.length===0)return e;let r=[];e&&r.push({type:"text",text:e});for(let a of n)r.push(Kn(a));return r}function Se(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
+
`):""}function Re(t){if(typeof t=="string"||!Array.isArray(t))return [];let n=[];for(let e of t)if(e.type==="image"){let r=typeof e.image=="string"?e.image:e.image.toString();n.push({id:`img_${Date.now()}_${Math.random().toString(36).slice(2)}`,name:"image",url:r,mimeType:e.mediaType||"image/jpeg",size:0});}else if(e.type==="file"){let r=typeof e.data=="string"?e.data:e.data.toString();n.push({id:`file_${Date.now()}_${Math.random().toString(36).slice(2)}`,name:e.name||"file",url:r,mimeType:e.mediaType,size:0});}return n}function Gt(t){return t.role==="user"?t.text?t.text:Se(t.content):""}function gt(t){return t.role==="user"?t.attachments?t.attachments:Re(t.content):[]}function $e(t,n=[]){let e=Yt(t,n),r=Date.now();return {id:`user_${r}_${Math.random().toString(36).slice(2)}`,role:"user",content:e,createdAt:r,text:t,attachments:n.length>0?n:void 0}}function Qt(t=false){let n=Date.now();return {id:`assistant_${n}_${Math.random().toString(36).slice(2)}`,role:"assistant",items:[],reasoning:"",reasoningOpen:t,mainAgentActions:[],createdAt:n}}function Ie(t){let n=[];for(let e of t)if(e.role==="user")n.push({role:e.role,content:e.content});else if(e.role==="assistant"){let r=[];if(e.firstAgentMessage&&r.push({type:"text",text:e.firstAgentMessage}),e.mainAgentActions&&e.mainAgentActions.length>0){for(let a of e.mainAgentActions)if(a.type==="reasoning"&&a.reasoning)r.push({type:"reasoning",text:a.reasoning});else if(a.type==="tool-call"&&a.toolName){let s=a.toolCallId||(typeof a.startDate=="number"&&a.toolName?`${a.toolName}_${a.startDate}`:`call_${a.toolName||"tool"}_${Math.abs(a.durationMs||0)}`);r.push({type:"tool-call",toolCallId:s,toolName:a.toolName,input:a.input||{}}),a.output!==void 0&&n.push({role:"tool",content:[{type:"tool-result",toolCallId:s,toolName:a.toolName,output:a.output,isError:a.status==="error"}]});}}if(e.items&&e.items.length>0){let a=JSON.stringify(e.items,null,2);r.push({type:"text",text:a});}r.length>0&&n.push({role:e.role,content:r});}return n}function Fe(t,n,e){let r=e??gt(t),a=Yt(n,r);return {...t,content:a,text:n,attachments:r.length>0?r:void 0}}function De(t){if(t.role==="user"){let n=Gt(t),e=gt(t);return e.length>0?`${n} [${e.length} attachment${e.length>1?"s":""}]`:n}else if(t.role==="assistant"){let e=(t.items||[]).filter(r=>r.type==="text");return e.length>0?e.map(r=>r.text||"").join(" ").slice(0,100):"Assistant response"}return ""}function ze({message:t,isEditing:n,editingText:e,editingAttachments:r,onEditingTextChange:a,onStartEdit:s,onCancelEdit:o,onSaveEdit:i,onRemoveAttachment:m,onAddAttachments:y,uploading:l,streaming:b,resolvedColors:c,t:k}){let f=Gt(t),M=gt(t);return n?jsxRuntime.jsx(we,{messageId:t.id,initialText:f,editingText:e,onEditingTextChange:a,onCancel:o,onSave:i,streaming:b,resolvedColors:c,attachments:r||M,onRemoveAttachment:m,onAddAttachments:y,uploading:l,t:k}):jsxRuntime.jsxs("div",{title:k("editor.clickToEdit"),onClick:()=>{b||s(t.id,f);},style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:c.accentColor,color:c.textColor},onMouseEnter:x=>x.currentTarget.style.backgroundColor=c.hoverBackground,onMouseLeave:x=>x.currentTarget.style.backgroundColor=c.accentColor,children:[f,jsxRuntime.jsx(Et,{attachments:M,resolvedColors:c})]})}function He({reasoning:t,reasoningOpen:n,onToggleReasoning:e,resolvedColors:r}){return t?jsxRuntime.jsxs("div",{style:{borderRadius:"12px",padding:"12px",cursor:"pointer",backgroundColor:r.inputBackground,border:`1px solid ${r.borderColor}`},onClick:e,children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[jsxRuntime.jsx("div",{style:{fontSize:"12px",color:r.mutedTextColor},children:"Reasoning"}),jsxRuntime.jsx("button",{type:"button",style:{fontSize:"12px",transition:"color 0.2s",color:r.mutedTextColor,background:"none",border:"none",cursor:"pointer"},onMouseEnter:a=>a.currentTarget.style.color=r.textColor,onMouseLeave:a=>a.currentTarget.style.color=r.mutedTextColor,children:n?"Hide":"Show full"})]}),n?jsxRuntime.jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:t}):(()=>{let a=(t||"").trim().split(`
|
|
3
|
+
`).filter(o=>o.trim()),s=a.length>0?a[a.length-1]:"";return jsxRuntime.jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:s||"\u2026"})})()]}):null}function _e({chart:t,theme:n}){let e=Bt.useRef(null),[r,a]=Bt.useState(null),[s,o]=Bt.useState(true);Bt.useEffect(()=>{let c=true;return (async()=>{try{o(!0),a(null);let f;try{f=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!c)return;if(f.default?.initialize({startOnLoad:!1,theme:n==="dark"?"dark":"default",themeVariables:{darkMode:n==="dark",primaryColor:n==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:n==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:n==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),e.current&&c){let M=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:x}=await f.default.render(M,t);if(e.current&&c){e.current.innerHTML=x;let p=e.current.querySelector("svg");p&&(p.style.maxWidth="100%",p.style.height="auto",p.style.display="block");}}}catch(f){c&&a(f instanceof Error?f.message:"Failed to render diagram");}finally{c&&o(false);}})(),()=>{c=false;}},[t,n]);let i=n==="dark"?"#374151":"#D1D5DB",m=n==="dark"?"#1F2937":"#F9FAFB",y=n==="dark"?"#7F1D1D":"#FEF2F2",l=n==="dark"?"#FCA5A5":"#DC2626",b=n==="dark"?"#9CA3AF":"#6B7280";return r?jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${i}`,backgroundColor:y,padding:"16px",margin:"8px 0"},children:[jsxRuntime.jsx("div",{style:{fontSize:"14px",color:l,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:l,opacity:.8},children:r})]}):jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${i}`,backgroundColor:m,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[s&&jsxRuntime.jsx("div",{style:{fontSize:"14px",color:b,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsxRuntime.jsx("div",{ref:e,style:{display:s?"none":"block",textAlign:"center",minHeight:s?"0":"50px"}})]})}function G(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Lt(t){return t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),t=t.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),t=t.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),t}function Xn(t,n="dark"){let e=(t||"").replace(/\r\n/g,`
|
|
4
4
|
`).split(`
|
|
5
|
-
`),r="",a=false,s="",o=[],i=false,m=false,
|
|
6
|
-
`);r+=`<div class="mermaid-placeholder" data-mermaid="${G(
|
|
7
|
-
`)),g=s?`language-${s}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${
|
|
8
|
-
`);r+=`<div class="mermaid-placeholder" data-mermaid="${G(
|
|
9
|
-
`)),
|
|
5
|
+
`),r="",a=false,s="",o=[],i=false,m=false,y=false,l=n==="dark"?"#374151":"#D1D5DB",c=n==="dark"?"#111827":"#F3F4F6",k=n==="dark"?"#E5E7EB":"#374151",f=()=>{i&&(r+="</ul>",i=false),m&&(r+="</ol>",m=false);};for(let M=0;M<e.length;M++){let x=e[M],p=x.match(/^```\s*(\w+)?\s*$/);if(p){if(!a)f(),a=true,s=p[1]?String(p[1]):"",o=[];else {if(s==="mermaid"){y=true;let u=o.join(`
|
|
6
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${G(u)}"></div>`;}else {let u=G(o.join(`
|
|
7
|
+
`)),g=s?`language-${s}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${c}; color: ${k}; border: 1px solid ${l}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${g}">${u}</code></pre>`;}a=false,s="",o=[];}continue}if(a){o.push(x);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(x)){f(),r+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let v=x.match(/^(#{1,6})\s+(.+)$/);if(v){f();let u=v[1].length,g=Lt(G(v[2].trim())),T=u<=2?"18px":u===3?"16px":"14px";r+=`<h${u} style="font-size: ${T}; font-weight: 600; margin: 8px 0 4px 0;">${g}</h${u}>`;continue}let h=x.match(/^\s*[-*]\s+(.+)$/),C=x.match(/^\s*\d+\.\s+(.+)$/);if(h){i||(f(),r+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',i=true);let u=Lt(G(h[1]));r+=`<li style="margin: 2px 0;">${u}</li>`;continue}if(C){m||(f(),r+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',m=true);let u=Lt(G(C[1]));r+=`<li style="margin: 2px 0;">${u}</li>`;continue}if(x.trim().length===0)f(),r+='<div style="height: 8px;"></div>';else {f();let u=Lt(G(x));r+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${u}</p>`;}}if(a)if(s==="mermaid"){y=true;let M=o.join(`
|
|
8
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${G(M)}"></div>`;}else {let M=G(o.join(`
|
|
9
|
+
`)),x=s?`language-${s}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${c}; color: ${k}; border: 1px solid ${l}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${x}">${M}</code></pre>`;}return i&&(r+="</ul>"),m&&(r+="</ol>"),{html:r,hasMermaid:y}}function mt({content:t,theme:n}){let{html:e,hasMermaid:r}=Bt.useMemo(()=>Xn(t,n),[t,n]);if(!r)return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:e}});let a=e.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),s=[];return a.forEach((o,i)=>{if(o.includes("mermaid-placeholder")){let m=o.match(/data-mermaid="([^"]*)"/);if(m){let y=m[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");s.push(Bt__default.default.createElement(_e,{key:`mermaid-${i}`,chart:y,theme:n}));}}else o.trim()&&s.push(Bt__default.default.createElement("div",{key:`html-${i}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:o}}));}),Bt__default.default.createElement(Bt__default.default.Fragment,{},...s)}function We({mainAgentActions:t,reasoningOpen:n,onToggleReasoning:e,resolvedColors:r,streaming:a=false,theme:s="dark",hideReasoningContent:o=false}){if(!t||t.length===0)return null;let i=t.filter(b=>b.type==="reasoning"||b.type==="tool-call");if(i.length===0)return null;let m=[...i].reverse().find(b=>b.type==="reasoning"),y=t.some(b=>b.type==="response"),l=Gn(i);return jsxRuntime.jsxs("div",{style:{cursor:"pointer",padding:"0",maxWidth:"100%"},onClick:e,children:[n?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0",maxWidth:"100%",position:"relative"},children:[i.map((b,c)=>jsxRuntime.jsx(Qn,{action:b,resolvedColors:r,theme:s,isFirst:c===0,isLast:c===i.length-1,hideReasoningContent:o},c)),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:"0",position:"relative",marginTop:"16px"},children:[jsxRuntime.jsx("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",width:"24px",flexShrink:0},children:y?jsxRuntime.jsx("div",{style:{width:"8px",height:"8px",marginTop:"6px",zIndex:1},children:jsxRuntime.jsx(lucideReact.CheckCircle,{size:10,color:r.borderColor})}):jsxRuntime.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:r.borderColor,marginTop:"6px",zIndex:1}})}),jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:y&&jsxRuntime.jsx("div",{style:{fontSize:"11px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:jsxRuntime.jsx("span",{children:"Done"})})})]})]}):jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",maxWidth:"100%",minWidth:0,overflow:"hidden"},children:[a&&!y?jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontStyle:"italic",display:"flex",alignItems:"center",gap:"6px",minWidth:0},children:[jsxRuntime.jsx("span",{children:"Thinking"}),jsxRuntime.jsxs("span",{className:"thinking-dots",style:{display:"inline-flex",gap:"2px"},children:[jsxRuntime.jsx("span",{style:{animation:"thinking-pulse 1.4s ease-in-out 0s infinite"},children:"."}),jsxRuntime.jsx("span",{style:{animation:"thinking-pulse 1.4s ease-in-out 0.2s infinite"},children:"."}),jsxRuntime.jsx("span",{style:{animation:"thinking-pulse 1.4s ease-in-out 0.4s infinite"},children:"."})]})]}):jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"4px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxRuntime.jsx("span",{style:{opacity:.9,fontSize:"12px"},children:"Thought"}),jsxRuntime.jsxs("span",{style:{color:r.mutedTextColor,fontFamily:"monospace",fontSize:"12px",opacity:.5,letterSpacing:"0.1px"},children:["for ",Ne(l)]})]}),!o&&m?.type==="reasoning"&&!y&&jsxRuntime.jsx("div",{style:{fontSize:"12px",color:r.mutedTextColor,opacity:.7,overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:jsxRuntime.jsx(mt,{content:m.reasoning,theme:s})})]}),jsxRuntime.jsx("style",{children:`
|
|
10
10
|
@keyframes thinking-pulse {
|
|
11
11
|
0%, 60%, 100% { opacity: 0.3; }
|
|
12
12
|
30% { opacity: 1; }
|
|
13
13
|
}
|
|
14
|
-
`})]})}function _n(t){return t.reduce((n,e)=>"startDate"in e&&"endDate"in e&&e.startDate&&e.endDate?n+(e.endDate-e.startDate):n,0)}function Le(t){if(t<1e3)return `${Math.round(t)}ms`;if(t<6e4)return `${(t/1e3).toFixed(1)}s`;let n=Math.floor(t/6e4),e=Math.round(t%6e4/1e3);return `${n}m ${e}s`}function Nn({action:t,resolvedColors:n,theme:e,isFirst:r,isLast:a,hideReasoningContent:s=false}){let o="startDate"in t&&"endDate"in t&&t.startDate&&t.endDate?Le(t.endDate-t.startDate):null,i=f=>{let c={input_streaming:{color:e==="dark"?"#eab308":"#d97706",text:"Inputting"},running:{color:e==="dark"?"#3b82f6":"#2563eb",text:"Running"},error:{color:e==="dark"?"#ef4444":"#dc2626",text:"Error"},finished:{color:e==="dark"?"#10b981":"#059669",text:"Called"}};return c[f.status]||c.finished},m=f=>jsxRuntime.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",width:"24px",flexShrink:0},children:[jsxRuntime.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:f,marginTop:"6px",zIndex:1}}),jsxRuntime.jsx("div",{style:{position:"absolute",top:"20px",left:"50%",transform:"translateX(-50%)",width:"2px",height:"calc(100% + 4px)",backgroundColor:e==="dark"?n.borderColor:n.mutedTextColor}})]});if(t.type==="reasoning")return jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[m(n.borderColor),jsxRuntime.jsxs("div",{style:{flex:1,minWidth:0},children:[jsxRuntime.jsxs("div",{style:{fontSize:"11px",color:n.mutedTextColor,marginBottom:"4px",fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.jsx("span",{children:"Reasoning"}),o&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px"},children:o})]}),!s&&jsxRuntime.jsx("div",{style:{fontSize:"13px",color:n.mutedTextColor,lineHeight:"1.6",maxWidth:"100%",opacity:t.status==="streaming"?.8:1},children:jsxRuntime.jsx(ut,{content:t.reasoning,theme:e})})]})]});if(t.type==="tool-call"){let{color:f,text:c}=i(t);return jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[m(f),jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:n.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsx("span",{style:{fontWeight:500,opacity:e==="dark"?.7:.6},children:c}),jsxRuntime.jsx("span",{style:{fontWeight:500},children:t.toolName||"tool"}),o&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",opacity:e==="dark"?.5:.6},children:o})]})})]})}return null}function We({mcpToolCalls:t,resolvedColors:n}){if(!t||t.length===0)return null;let e=new Map;t.forEach(s=>{let o=e.get(s.toolName);!o||o.status==="running"&&s.status==="completed"?e.set(s.toolName,{status:s.status||"pending",count:(o?.count||0)+1}):o&&o.count++;});let r=Array.from(e.values()).some(s=>s.status==="running"),a=Array.from(e.values()).filter(s=>s.status==="completed").length;return jsxRuntime.jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,fontSize:"12px",color:n.mutedTextColor},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:r?"#3b82f6":"#10b981"}}),jsxRuntime.jsx("span",{children:r?"Agent is using tools":a>0?`Agent used ${a} tool${a>1?"s":""}`:"Agent used tools"})]}),jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Array.from(e.entries()).map(([s,o])=>jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:n.inputBackground,border:`1px solid ${n.borderColor}`},children:[o.status==="running"?jsxRuntime.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:[jsxRuntime.jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.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"})]}):jsxRuntime.jsx("span",{style:{display:"inline-block",height:"4px",width:"4px",borderRadius:"50%",backgroundColor:o.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsxRuntime.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:s}),o.count>1&&jsxRuntime.jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",o.count]})]},s))})]})}function _e({items:t,mcpToolCalls:n,mcpToolResults:e,actionStatuses:r,components:a,theme:s,resolvedColors:o}){return !Array.isArray(t)||t.length===0?null:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.map((i,m)=>{let f=`it-${m}`;if(typeof i=="string")return jsxRuntime.jsx("div",{style:{padding:"0",color:o.textColor},children:jsxRuntime.jsx(ut,{content:i,theme:s})},f);if(i&&typeof i=="object"){if(i.type==="action"){let C=`${String(i.name??"action")}:${m}`,p=r.get(C);return jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsxRuntime.jsx("div",{style:{padding:"8px",fontSize:"12px",color:o.mutedTextColor},children:p==="executing"?jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.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:[jsxRuntime.jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.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(i.name??"action")," is executing"]}):jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:"#10b981"}}),String(i.name??"action")," has executed"]})})},f)}if(i.type==="ui"){let C=String(i.component??"").trim(),p=C?a.get(C):void 0;return p?jsxRuntime.jsx("div",{style:{padding:"0"},children:jsxRuntime.jsx(p,{...i.props||{}})},f):jsxRuntime.jsxs("div",{style:{padding:"0"},children:[jsxRuntime.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:o.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:o.accentColor,border:`1px solid ${o.borderColor}`},children:"UI"}),jsxRuntime.jsx("span",{children:C||"component"}),jsxRuntime.jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsxRuntime.jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i.props??{},null,2)})]},f)}let c=i.text||i.content||i.message;return typeof c=="string"?jsxRuntime.jsx("div",{style:{padding:"0",color:o.textColor},children:jsxRuntime.jsx(ut,{content:c,theme:s})},f):jsxRuntime.jsx("div",{style:{padding:"0",fontSize:"14px"},children:jsxRuntime.jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i,null,2)})},f)}return null}),jsxRuntime.jsx(We,{mcpToolCalls:n,resolvedColors:o})]})}function Oe({message:t,streaming:n,isLastMessage:e,actionStatuses:r,components:a,theme:s,resolvedColors:o,onToggleReasoning:i,hideReasoningContent:m=false}){let f=t.mainAgentActions&&t.mainAgentActions.length>0;return jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.firstAgentMessage&&jsxRuntime.jsx("div",{style:{padding:"12px 0"},children:jsxRuntime.jsx("div",{style:{fontSize:"13px",color:o.textColor,lineHeight:"1.5"},children:t.firstAgentMessage})}),f?jsxRuntime.jsx(Be,{mainAgentActions:t.mainAgentActions,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o,streaming:n&&e,theme:s,hideReasoningContent:m}):jsxRuntime.jsx(Ee,{reasoning:t.reasoning,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o}),jsxRuntime.jsx(_e,{items:t.items,mcpToolCalls:t.mcpToolCalls,mcpToolResults:t.mcpToolResults,actionStatuses:r,components:a,theme:s,resolvedColors:o}),n&&e&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:o.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsxRuntime.jsx("span",{children:"Working\u2026"})]})]})}function Ue({messages:t,streaming:n,editingMessageId:e,editingMessageText:r,editingAttachments:a,error:s,actionStatuses:o,components:i,theme:m,resolvedColors:f,onEditingTextChange:c,onRemoveAttachment:C,onAddAttachments:p,uploading:M,onStartEdit:x,onCancelEdit:T,onSaveEdit:h,onToggleReasoning:u,scrollAnchorRef:w,hideReasoningContent:y=false,t:b}){return jsxRuntime.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"},children:[s&&jsxRuntime.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:s}),t.length===0&&!n&&jsxRuntime.jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${f.borderColor}`,backgroundColor:f.accentColor,color:f.mutedTextColor},children:b("messages.empty")}),jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:t.map((d,g)=>jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:d.role==="user"?jsxRuntime.jsx(Fe,{message:d,isEditing:e===d.id,editingText:r,editingAttachments:a,onEditingTextChange:c,onStartEdit:x,onCancelEdit:T,onSaveEdit:h,onRemoveAttachment:C,onAddAttachments:p,uploading:M,streaming:n,resolvedColors:f,t:b}):jsxRuntime.jsx(Oe,{message:d,streaming:n,isLastMessage:g===t.length-1,actionStatuses:o,components:i,theme:m,resolvedColors:f,onToggleReasoning:u,hideReasoningContent:y})},d.id))}),jsxRuntime.jsx("div",{ref:w})]})}function Ke({show:t,onClick:n,resolvedColors:e,floatingButtonPosition:r}){if(!t)return null;let a={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsxRuntime.jsx("button",{"aria-label":"Open chat",onClick:n,style:{...a,borderColor:e.borderColor,backgroundColor:e.accentColor,color:e.textColor,borderRadius:"50%",border:`1px solid ${e.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:s=>{s.currentTarget.style.borderColor=e.primaryColor,s.currentTarget.style.backgroundColor=`${e.accentColor}dd`;},onMouseLeave:s=>{s.currentTarget.style.borderColor=e.borderColor,s.currentTarget.style.backgroundColor=e.accentColor;},children:jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function No(t=false){let[n,e]=Pt.useState(t),r=Pt.useCallback(()=>e(o=>!o),[]),a=Pt.useCallback(()=>e(true),[]),s=Pt.useCallback(()=>e(false),[]);return {on:n,toggle:r,setOn:e,setTrue:a,setFalse:s}}function Ko(){let t=Pt.useRef(null);return Pt.useEffect(()=>{let n=t.current;if(!n)return;let e=new MutationObserver(()=>{n.scrollTop=n.scrollHeight;});return e.observe(n,{childList:true,subtree:true}),n.scrollTop=n.scrollHeight,()=>e.disconnect()},[]),t}var je=Pt.createContext(void 0);function Vn({baseUrl:t,children:n}){let[e,r]=Pt.useState(new Map),[a,s]=Pt.useState(new Map),[o,i]=Pt.useState(new Map),[m,f]=Pt.useState(new Map),c=Pt.useCallback((y,b)=>(r(d=>{let g=new Map(d);return g.set(String(y),b),g}),()=>{r(d=>{let g=new Map(d),k=g.get(String(y));return (!b||k===b)&&g.delete(String(y)),g});}),[]),C=Pt.useCallback((y,b)=>{r(d=>{let g=new Map(d),k=g.get(String(y));return (!b||k===b)&&g.delete(String(y)),g});},[]),p=Pt.useCallback((y,b)=>(s(d=>{let g=new Map(d);return g.set(String(y),b),g}),()=>{s(d=>{let g=new Map(d),k=g.get(String(y));return (!b||k===b)&&g.delete(String(y)),g});}),[]),M=Pt.useCallback((y,b)=>{s(d=>{let g=new Map(d),k=g.get(String(y));return (!b||k===b)&&g.delete(String(y)),g});},[]),x=Pt.useCallback((y,b)=>{i(d=>{let g=new Map(d);return b?g.set(y,true):g.delete(y),g});},[]),T=Pt.useCallback((y,b)=>{f(d=>{let g=new Map(d);return b?g.set(y,true):g.delete(y),g});},[]),h=Pt.useMemo(()=>Array.from(o.values()).some(y=>y),[o]),u=Pt.useMemo(()=>Array.from(m.values()).some(y=>y),[m]),w=Pt.useMemo(()=>({baseUrl:t,actions:e,components:a,registerAction:c,unregisterAction:C,registerComponent:p,unregisterComponent:M,isAnyStreaming:h,setStreamingState:x,isAnyChatOpen:u,setChatOpenState:T}),[t,e,a,c,C,p,M,h,x,u,T]);return jsxRuntime.jsx(je.Provider,{value:w,children:n})}function Q(){let t=Pt.useContext(je);return t||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{}}}function Go(t,n){let{registerAction:e}=Q(),r=Pt.useRef(n);Pt.useEffect(()=>{r.current=n;});let a=Pt.useCallback((s,o)=>r.current(s,o),[]);Pt.useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaAction] Invalid action registration: name="${t}", handler type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function na(t,n){let{registerComponent:e}=Q(),r=Pt.useRef(n);Pt.useEffect(()=>{r.current=n;});let a=Pt.useMemo(()=>{let s=o=>{let i=r.current;return Pt__default.default.createElement(i,o)};return s.displayName=`HsafaStable(${t})`,s},[]);Pt.useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaComponent] Invalid component registration: name="${t}", component type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function Xe(t){let n=`hsafaChat_${t}`,e=`${n}.chats`,r=d=>`${n}.chat.${d}`,a=`${n}.currentChatId`,s=`${n}.showChat`,[o,i]=Pt.useState(null),m=Pt.useRef(false),f=Pt.useRef(null),c=()=>{try{let d=localStorage.getItem(e);return d?JSON.parse(d):[]}catch{return []}},C=d=>{try{localStorage.setItem(e,JSON.stringify(d));}catch{}},p=d=>{try{let g=localStorage.getItem(r(d));return g?JSON.parse(g):null}catch{return null}},M=d=>{try{localStorage.setItem(r(d.id),JSON.stringify(d));}catch{}},x=d=>{let g=c(),k=g.findIndex(R=>R.id===d.id);k>=0?g[k]=d:g.unshift(d),C(g);},T=d=>{let k=c().filter(R=>R.id!==d);C(k);},h=d=>{try{localStorage.removeItem(r(d));}catch{}};return {currentChatId:o,setCurrentChatId:i,hasChatRecordRef:m,pendingFirstTitleRef:f,loadChatsIndex:c,loadChat:p,saveChat:M,deleteChat:(d,g)=>{h(d),T(d);let k=o===d;if(k){i(null),m.current=false,f.current=null;try{localStorage.removeItem(a);}catch{}}g?.(k);},loadChatPreferences:()=>{try{let d=localStorage.getItem(a);if(d){let g=p(d);if(g)return i(g.id),m.current=!0,g.messages||[]}}catch{}return []},persistChatData:d=>{if(!o||!m.current)return;M({id:o,messages:d,agentId:t});let k=d.find(E=>E.role==="user"),R=k?$e(k):"New chat",L=(f.current||R).slice(0,80),$={id:o,title:L,createdAt:Date.now(),updatedAt:Date.now()};x($);try{localStorage.setItem(a,o);}catch{}},createNewChat:d=>{let g=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;i(g),m.current=true;let k=(d||"New chat").slice(0,80),R=Date.now();x({id:g,title:k,createdAt:R,updatedAt:R});try{localStorage.setItem(a,g);}catch{}return g},upsertChatMeta:x,showChatKey:s}}function Ze(){let[t,n]=Pt.useState(false),[e,r]=Pt.useState(null),a=Pt.useRef(null),s=Pt.useRef({}),o=Pt.useRef(void 0),i=Pt.useRef(new Set),m=Pt.useRef(new Map),f=Pt.useRef(new Map),[c,C]=Pt.useState(new Map),p=Pt.useCallback((u,w)=>{let y=m.current.get(u)||[],b=JSON.stringify(w);if(y.push(b),y.length>5&&y.shift(),m.current.set(u,y),y.length>=3){let d=y.slice(-3);return d.every(g=>g===d[0])}return false},[]),M=Pt.useCallback((u,w,y,b)=>{!Array.isArray(u)||u.length===0||u.forEach((d,g)=>{if(!(!d||typeof d!="object")&&d.type==="action"){let k=String(d.name??"").trim();if(!k)return;let R=y.get(k);if(!R){console.warn(`Action handler not found for: ${k}`);return}let L=!!s.current[k],$=`${o.current||"assist"}:${k}:${g}`,E=`${k}:${g}`;try{if(w==="partial"&&L){C(H=>new Map(H).set(E,"executing"));let q=setTimeout(()=>{Promise.resolve(R(d.params,{name:k,trigger:w,index:g,assistantMessageId:o.current,chatId:b||void 0})).catch(H=>{console.error(`Error executing streaming action ${k}:`,H),C(D=>new Map(D).set(E,"executed"));});},50);f.current.set(`${E}_timeout`,q);}else if(w==="partial"&&!L){let q=p(E,d.params),H=f.current.get(E);q&&H!=="executed"?(f.current.set(E,"executed"),C(D=>new Map(D).set(E,"executed")),Promise.resolve(R(d.params,{name:k,trigger:"params_complete",index:g,assistantMessageId:o.current,chatId:b||void 0})).catch(D=>{console.error(`Error executing stabilized action ${k}:`,D);})):H||(f.current.set(E,"executing"),C(D=>new Map(D).set(E,"executing")));}else if(w==="final"&&f.current.get(E)!=="executed"&&!i.current.has($)){i.current.add($);let H=f.current.get(`${E}_timeout`);H&&(clearTimeout(H),f.current.delete(`${E}_timeout`)),f.current.set(E,"executed"),C(D=>new Map(D).set(E,"executed")),Promise.resolve(R(d.params,{name:k,trigger:L?"final":"params_complete",index:g,assistantMessageId:o.current,chatId:b||void 0})).catch(D=>{console.error(`Error executing final action ${k}:`,D);});}}catch(q){console.error(`Error processing action ${k}:`,q);}}});},[p]),x=Pt.useCallback(()=>{a.current&&(a.current.abort(),a.current=null),n(false),r("Request stopped by user");},[]),T=Pt.useCallback(()=>{i.current.clear(),m.current.clear(),f.current.clear(),C(new Map);},[]),h=Pt.useCallback(()=>{f.current.forEach((u,w)=>{w.endsWith("_timeout")&&clearTimeout(u);});},[]);return {streaming:t,setStreaming:n,error:e,setError:r,actionStatuses:c,setActionStatuses:C,abortControllerRef:a,actionExecMapRef:s,assistantMsgIdRef:o,calledFinalActionsRef:i,actionParamsHistoryRef:m,actionExecutionStatusRef:f,processActions:M,handleStop:x,resetActionTracking:T,cleanupTimeouts:h,hasActionParamsStabilized:p}}function Ye(t,n){if(!t)return n;let e=t.endsWith("/")?t.slice(0,-1):t,r=n.startsWith("/")?n:`/${n}`;return `${e}${r}`}var ne=25*1024*1024;function Qe(t){let[n,e]=Pt.useState([]),[r,a]=Pt.useState(false),s=Pt.useRef(null),o=Pt.useCallback(p=>{if(!p||Number.isNaN(p))return "0 B";let M=["B","KB","MB","GB","TB"],x=Math.min(M.length-1,Math.floor(Math.log(p)/Math.log(1024)));return `${(p/Math.pow(1024,x)).toFixed(x===0?0:1)} ${M[x]}`},[]),i=Pt.useCallback(async p=>{let M=new FormData;M.append("file",p);let x=await fetch(Ye(t,"/api/uploads"),{method:"POST",body:M});if(!x.ok){let h=await x.text().catch(()=>"");throw new Error(h||`Failed to upload ${p.name}`)}let T=await x.json();return {id:T.id,name:T.name||p.name,url:T.url,mimeType:T.mimeType||p.type||"application/octet-stream",size:typeof T.size=="number"?T.size:p.size}},[t]),m=Pt.useCallback(p=>{e(M=>M.filter(x=>x.id!==p));},[]),f=Pt.useCallback(async(p,M)=>{if(!p)return;let x=Array.isArray(p)?p:Array.from(p);M(null),a(true);let T=[];try{for(let h of x){if(h.size>ne){M(`"${h.name}" exceeds the ${o(ne)} limit.`);continue}try{let u=await i(h);T.push(u);}catch(u){console.error("Failed to upload attachment:",u),M(String(u?.message??`Failed to upload ${h.name}`));}}T.length&&e(h=>[...h,...T]);}finally{a(false);}},[i,o]),c=Pt.useCallback((p,M)=>{let x=[],T=(p||"").trim();T&&x.push({type:"text",text:T});for(let h of M||[]){let u=h.mimeType||"application/octet-stream";u.startsWith("image/")?x.push({type:"image",image:new URL(h.url),mediaType:u}):x.push({type:"file",data:h.url,mediaType:u,name:h.name});}return x},[]),C=Pt.useCallback(()=>{e([]);},[]);return {attachments:n,uploading:r,fileInputRef:s,formatBytes:o,handleRemoveAttachment:m,handleFileSelection:f,buildUserContent:c,clearAttachments:C,MAX_UPLOAD_SIZE:ne}}function or(t){return JSON.parse(JSON.stringify(t))}function tn(){let[t,n]=Pt.useState(false),[e,r]=Pt.useState(null),[a,s]=Pt.useState(null),o=Pt.useRef(null),i=Pt.useCallback(async({agentId:c,body:C,baseUrl:p,onUpdate:M,signal:x})=>{try{let $=function(){let D=or(b);s(D),M?.(D);};var T=$;n(!0),r(null);let h;if(x)o.current=null,h=x;else {let D=new AbortController;o.current=D,h=D.signal;}let w=`${p?p.replace(/\/$/,""):""}/api/run/${encodeURIComponent(c)}`,y=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson"},body:JSON.stringify(C??{}),signal:h});if(!y.ok||!y.body){let D=await y.text().catch(()=>"");throw new Error(`Request failed: ${y.status} ${y.statusText} - ${D}`)}let b={first_agent:{message:"",continue:!1},main_agent:[]},d=null,g=null,k=null,R=null,L=!1,E=y.body.getReader(),q=new TextDecoder("utf-8"),H="";for($();;){let{value:D,done:Ct}=await E.read();if(Ct)break;H+=q.decode(D,{stream:!0});let O=H.indexOf(`
|
|
15
|
-
`);for(;
|
|
16
|
-
`);}}try{E.releaseLock();}catch{}return n(!1),b}catch(h){return h.name==="AbortError"?r("Request was cancelled"):r(h?.message||"Request failed"),n(false),null}},[]),m=Pt.useCallback(()=>{o.current&&(o.current.abort(),o.current=null),n(false);},[]),f=Pt.useCallback(()=>{s(null),r(null),n(false);},[]);return {streaming:t,error:e,streamData:a,startStreaming:i,stopStreaming:m,reset:f}}var en={en:{"header.maximize":"Maximize","header.minimize":"Minimize","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","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit","messages.empty":"Start by sending a message to the agent.","messages.error":"An error occurred","history.search":"Search","history.noChatsFound":"No chats found.","history.untitledChat":"Untitled chat","history.deleteChat":"Delete chat","general.agent":"Agent"},ar:{"header.maximize":"\u062A\u0643\u0628\u064A\u0631","header.minimize":"\u062A\u0635\u063A\u064A\u0631","header.new":"\u062C\u062F\u064A\u062F","header.history":"\u0627\u0644\u0633\u062C\u0644","header.close":"\u0625\u063A\u0644\u0627\u0642 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","input.placeholder":"\u0627\u0637\u0631\u062D \u0633\u0624\u0627\u0644\u0643...","input.attachFiles":"\u0625\u0631\u0641\u0627\u0642 \u0645\u0644\u0641\u0627\u062A","input.insertLink":"\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637","input.send":"\u0625\u0631\u0633\u0627\u0644","input.stop":"\u0625\u064A\u0642\u0627\u0641","input.uploadingFiles":"\u062C\u0627\u0631\u064A \u0631\u0641\u0639 \u0627\u0644\u0645\u0644\u0641\u0627\u062A...","input.previewImage":"\u0645\u0639\u0627\u064A\u0646\u0629 \u0627\u0644\u0635\u0648\u0631\u0629","input.removeFile":"\u062D\u0630\u0641 \u0627\u0644\u0645\u0644\u0641","editor.cancel":"\u0625\u0644\u063A\u0627\u0621","editor.saveAndRegenerate":"\u062D\u0641\u0638 \u0648\u0625\u0639\u0627\u062F\u0629 \u062A\u0648\u0644\u064A\u062F","editor.clickToEdit":"\u0627\u0646\u0642\u0631 \u0644\u0644\u062A\u0639\u062F\u064A\u0644","messages.empty":"\u0627\u0628\u062F\u0623 \u0628\u0625\u0631\u0633\u0627\u0644 \u0631\u0633\u0627\u0644\u0629 \u0625\u0644\u0649 \u0627\u0644\u0648\u0643\u064A\u0644.","messages.error":"\u062D\u062F\u062B \u062E\u0637\u0623","history.search":"\u0628\u062D\u062B","history.noChatsFound":"\u0644\u0645 \u064A\u062A\u0645 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u0645\u062D\u0627\u062F\u062B\u0627\u062A.","history.untitledChat":"\u0645\u062D\u0627\u062F\u062B\u0629 \u0628\u062F\u0648\u0646 \u0639\u0646\u0648\u0627\u0646","history.deleteChat":"\u062D\u0630\u0641 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","general.agent":"\u0627\u0644\u0648\u0643\u064A\u0644"}};function nn(t,n){return en[t]?.[n]||en.en[n]||n}function rn(t="en"){return {t:Pt.useCallback(e=>nn(t,e),[t]),language:t}}function Lt({icon:t,onClick:n,ariaLabel:e,resolvedColors:r,disabled:a=false,title:s}){return jsxRuntime.jsx("button",{"aria-label":e,title:s,disabled:a,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:o=>{a||(o.currentTarget.style.backgroundColor=r.hoverBackground,o.currentTarget.style.color=r.textColor);},onMouseLeave:o=>{o.currentTarget.style.backgroundColor="transparent",o.currentTarget.style.color=r.mutedTextColor;},onClick:n,children:t})}function an({title:t,expandable:n,alwaysOpen:e,maximized:r,streaming:a,dir:s,resolvedColors:o,onMaximize:i,onNew:m,onToggleHistory:f,onClose:c,historyBtnRef:C,t:p}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:s==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:t,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:t})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[n&&jsxRuntime.jsx(Lt,{icon:jsxRuntime.jsx(lucideReact.Maximize2,{size:"20",strokeWidth:"2"}),onClick:i,ariaLabel:p(r?"header.minimize":"header.maximize"),resolvedColors:o}),jsxRuntime.jsx(Lt,{icon:jsxRuntime.jsx(lucideReact.Plus,{size:"20",strokeWidth:"2"}),onClick:()=>{a||m();},ariaLabel:p("header.new"),resolvedColors:o,disabled:a}),jsxRuntime.jsx("button",{ref:C,"aria-label":p("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:M=>{M.currentTarget.style.backgroundColor=o.hoverBackground,M.currentTarget.style.color=o.textColor;},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="transparent",M.currentTarget.style.color=o.mutedTextColor;},onClick:f,children:jsxRuntime.jsx(lucideReact.History,{size:"20",strokeWidth:"2"})}),!e&&jsxRuntime.jsx(Lt,{icon:jsxRuntime.jsx(lucideReact.ChevronRight,{size:"20",strokeWidth:"2",style:{transform:s==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:p("header.close"),resolvedColors:o})]})]})}function sn({value:t,onChange:n,onSend:e,onStop:r,streaming:a,placeholder:s,attachments:o,uploading:i,onRemoveAttachment:m,onFileInputClick:f,resolvedColors:c,formatBytes:C,textareaRef:p,fileInputRef:M,onFileSelection:x,t:T,dir:h="ltr"}){return Pt__default.default.useEffect(()=>{let u=p.current;if(u){u.style.height="auto";let w=Math.min(u.scrollHeight,200);u.style.height=`${w}px`;}},[t,p]),jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:c.backgroundColor},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:"1"},children:jsxRuntime.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${c.borderColor}`,backgroundColor:c.accentColor},children:[o.length>0&&jsxRuntime.jsx("div",{style:{padding:"12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:o.map(u=>{let w=u.mimeType?.startsWith("image/");return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:c.inputBackground,borderRadius:"10px",border:`1px solid ${c.borderColor}`,fontSize:"12px",color:c.textColor,transition:"all 0.2s ease-out",cursor:"pointer",position:"relative"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:w?"transparent":c.accentColor},children:[w?jsxRuntime.jsx("img",{src:u.url,alt:u.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:y=>{y.target.style.display="none";let b=y.target.nextElementSibling;b&&(b.style.display="block");}}):null,jsxRuntime.jsx(lucideReact.File,{size:"14",strokeWidth:"2",style:{display:w?"none":"block",color:c.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsxRuntime.jsx("span",{title:u.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:u.name}),jsxRuntime.jsx("span",{style:{color:c.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:C(u.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[w&&jsxRuntime.jsx("button",{onClick:y=>{y.stopPropagation(),window.open(u.url,"_blank");},style:{background:"none",border:"none",color:c.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:T("input.previewImage"),onMouseEnter:y=>{y.currentTarget.style.backgroundColor=c.hoverBackground,y.currentTarget.style.color=c.textColor;},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color=c.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),jsxRuntime.jsx("button",{onClick:y=>{y.stopPropagation(),m(u.id);},style:{background:"none",border:"none",color:c.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:T("input.removeFile"),onMouseEnter:y=>{y.currentTarget.style.backgroundColor="#ef444420",y.currentTarget.style.color="#ef4444";},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color=c.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.X,{size:"12",strokeWidth:"2"})})]})]},u.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:c.mutedTextColor},children:[jsxRuntime.jsx(lucideReact.Loader2,{size:"14",strokeWidth:"2",style:{animation:"spin 1s linear infinite"}}),jsxRuntime.jsx("span",{children:T("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.jsx("textarea",{"aria-label":"Prompt",rows:1,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:c.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:s,value:t,onChange:u=>n(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),a||e());},ref:p})}),jsxRuntime.jsxs("div",{style:{position:"absolute",bottom:"8px",...h==="rtl"?{right:"8px"}:{left:"8px"},display:"flex",alignItems:"center",gap:"4px",color:c.mutedTextColor},children:[jsxRuntime.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:u=>{u.currentTarget.style.backgroundColor=`${c.backgroundColor}99`,u.currentTarget.style.color=c.textColor;},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent",u.currentTarget.style.color=c.mutedTextColor;},"aria-label":T("input.attachFiles"),onClick:f,children:jsxRuntime.jsx(lucideReact.Paperclip,{size:"18",strokeWidth:"2"})}),jsxRuntime.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:u=>{u.currentTarget.style.backgroundColor=`${c.backgroundColor}99`,u.currentTarget.style.color=c.textColor;},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent",u.currentTarget.style.color=c.mutedTextColor;},"aria-label":T("input.insertLink"),children:jsxRuntime.jsx(lucideReact.Link,{size:"18",strokeWidth:"2"})})]}),jsxRuntime.jsx("input",{type:"file",ref:M,multiple:true,accept:"*/*",style:{display:"none"},onChange:u=>x(u.target.files)}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",...h==="rtl"?{left:"8px"}:{right:"8px"}},children:jsxRuntime.jsx("button",{"aria-label":T(a?"input.stop":"input.send"),disabled:!a&&!t.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a?"#ef4444":c.borderColor}`,backgroundColor:a?"#ef444420":c.cardBackground,color:a?"#ef4444":c.mutedTextColor,opacity:!a&&!t.trim()?.4:1,cursor:!a&&!t.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:u=>{u.currentTarget.disabled||(a?(u.currentTarget.style.borderColor="#dc2626",u.currentTarget.style.backgroundColor="#dc262630",u.currentTarget.style.color="#dc2626"):(u.currentTarget.style.borderColor=c.primaryColor,u.currentTarget.style.backgroundColor=c.hoverBackground,u.currentTarget.style.color=c.textColor));},onMouseLeave:u=>{u.currentTarget.disabled||(a?(u.currentTarget.style.borderColor="#ef4444",u.currentTarget.style.backgroundColor="#ef444420",u.currentTarget.style.color="#ef4444"):(u.currentTarget.style.borderColor=c.borderColor,u.currentTarget.style.backgroundColor=c.cardBackground,u.currentTarget.style.color=c.mutedTextColor));},onClick:()=>{a?r():e();},children:a?jsxRuntime.jsx(lucideReact.Square,{size:"18",strokeWidth:"2"}):jsxRuntime.jsx(lucideReact.ArrowUp,{size:"18",strokeWidth:"2"})})})]})})})}function ln(t){let n=Date.now()-t,e=Math.max(1,Math.floor(n/1e3));if(e<60)return `${e}s`;let r=Math.floor(e/60);if(r<60)return `${r}m`;let a=Math.floor(r/60);if(a<24)return `${a}h`;let s=Math.floor(a/24);if(s<7)return `${s}d`;let o=Math.floor(s/7);if(o<4)return `${o}w`;let i=Math.floor(s/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function cn({isOpen:t,onClose:n,searchQuery:e,onSearchChange:r,chats:a,currentChatId:s,onChatSelect:o,onChatDelete:i,resolvedColors:m,t:f}){if(!t)return null;let c=e.trim()?a.filter(p=>(p.title||"").toLowerCase().includes(e.toLowerCase().trim())):a,C=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:n}),jsxRuntime.jsxs("div",{style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${m.borderColor}`,backgroundColor:`${m.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${m.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.jsx("input",{autoFocus:true,value:e,onChange:p=>r(p.target.value),placeholder:f("history.search"),style:{width:"100%",borderRadius:"8px",backgroundColor:m.inputBackground,padding:"8px 12px",fontSize:"14px",color:m.textColor,border:`1px solid ${m.borderColor}`,outline:"none"},onFocus:p=>p.currentTarget.style.borderColor=m.primaryColor,onBlur:p=>p.currentTarget.style.borderColor=m.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:c.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:m.mutedTextColor,textAlign:"center"},children:f("history.noChatsFound")}):jsxRuntime.jsx("div",{children:c.map((p,M)=>jsxRuntime.jsx("div",{style:{borderTop:M>0?`1px solid ${m.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:p.id===s?m.cardBackground:"transparent"},children:[jsxRuntime.jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:m.textColor},onMouseEnter:x=>x.currentTarget.style.backgroundColor=m.hoverBackground,onMouseLeave:x=>x.currentTarget.style.backgroundColor="transparent",onClick:()=>o(p.id),children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:m.textColor},children:p.title||f("history.untitledChat")})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:m.mutedTextColor},children:ln(p.updatedAt)})]})}),jsxRuntime.jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:m.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:f("history.deleteChat"),onMouseEnter:x=>{x.currentTarget.style.color="#ef4444",x.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",x.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:x=>{x.currentTarget.style.color=m.mutedTextColor,x.currentTarget.style.backgroundColor="transparent",x.currentTarget.style.borderColor="transparent";},onClick:x=>{x.stopPropagation(),i(p.id);},children:jsxRuntime.jsx(lucideReact.Trash2,{size:"16",strokeWidth:"2"})})]})},p.id))})})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(C,document.body):C}var _t={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};var ae=t=>t.map(n=>({...n}));function vr(t){let[n,e]=Pt.useState(()=>{try{return t.loadChatPreferences()}catch(o){return console.warn("Failed to load chat preferences:",o),[]}});Pt.useEffect(()=>{if(n.length!==0)try{t.persistChatData(n);}catch(o){console.warn("Failed to persist chat data:",o);}},[n]);let r=Pt.useCallback(o=>{try{t.setCurrentChatId(o);let i=t.loadChat(o);return e(i?.messages||[]),!0}catch(i){return console.warn("Failed to load selected chat:",i),false}},[t]),a=Pt.useCallback(o=>{try{t.deleteChat(o,i=>{i&&e([]);});}catch(i){console.warn("Failed to delete chat:",i);}},[t]),s=Pt.useCallback(()=>{e([]),t.setCurrentChatId(null);},[t]);return {messages:n,setMessages:e,selectChat:r,deleteChat:a,resetChat:s}}function Ar(t){let{agentId:n,theme:e="dark",primaryColor:r,backgroundColor:a,borderColor:s,textColor:o,accentColor:i,width:m=420,height:f="100vh",expandable:c=true,alwaysOpen:C=false,defaultOpen:p=false,dir:M="ltr",language:x,floatingButtonPosition:T=M==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},placeholder:h,title:u,chatContainerClassName:w="",defaultReasoningOpen:y=false,hideReasoningContent:b=false}=t,d=x||(M==="rtl"?"ar":"en"),{t:g}=rn(d),k=h??g("input.placeholder"),R=u??g("general.agent"),{baseUrl:L,components:$,setStreamingState:E,setChatOpenState:q}=Q(),H=Pt.useRef(`chat-${n}-${Date.now()}`).current,[D,Ct]=Pt.useState(""),[O,kt]=Pt.useState(()=>{if(C)return true;try{let v=localStorage.getItem(`hsafaChat_${n}.showChat`);return v!==null?v==="true":p}catch{return p}}),[l,Mt]=Pt.useState(false),[$t,J]=Pt.useState(""),[V,Ot]=Pt.useState(false),[ie,S]=Pt.useState(0),[Tt,Ut]=Pt.useState(null),[pn,se]=Pt.useState(""),[le,vt]=Pt.useState([]),ce=Pt.useRef(null),[de,pe]=Pt.useState(true),Kt=Pt.useRef(false),un=Pt.useRef(null),gn=Pt.useRef(null),mn=Pt.useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),ot=Xe(n),{messages:et,setMessages:At,selectChat:ue,deleteChat:ge,resetChat:fn}=vr(ot),W=Ze(),wt=Qe(L||""),me=tn();Pt.useEffect(()=>{E(H,W.streaming);},[W.streaming,H,E]),Pt.useEffect(()=>(q(H,O),()=>{q(H,false),E(H,false);}),[O,H,q,E]),Pt.useEffect(()=>{if(!C)try{localStorage.setItem(`hsafaChat_${n}.showChat`,String(O));}catch(v){console.warn("Failed to save chat state:",v);}},[O,n,C]);let{attachments:jt,uploading:fe,fileInputRef:he,formatBytes:hn,handleRemoveAttachment:yn,handleFileSelection:xn,clearAttachments:ye}=wt,xe=Pt.useCallback((v,I)=>{At(B=>B.map(A=>{if(A.id===v&&A.role==="assistant"){let z=I.main_agent.find(U=>U.type==="response"),N=z?.type==="response"?z.items:[];return {...A,items:N,mainAgentActions:I.main_agent,firstAgentMessage:I.first_agent.message,firstAgentContinue:I.first_agent.continue,reasoningOpen:A.reasoningOpen}}return A}));},[]),qt=Pt.useCallback(async({prompt:v,baseMessages:I,userMessage:B,assistantMessageId:A,chatId:z})=>{if(n){W.setError(null),W.setStreaming(true);try{let N=Se(I);N.push({role:"user",content:B.content}),await me.startStreaming({agentId:n,baseUrl:L,body:{prompt:v,chatId:z??void 0,messages:N},onUpdate:U=>xe(A,U)});}catch(N){W.setError(N?.message||"Request failed");}finally{W.setStreaming(false);}}},[n,L,me,W,xe]),bn=Pt.useCallback(v=>{ue(v)&&(Mt(false),J(""));},[ue,Mt,J]),Cn=Pt.useCallback(v=>{ge(v),S(I=>I+1);},[ge]),nt=_t[e],dt={primaryColor:r||nt.primaryColor,backgroundColor:a??"transparent",borderColor:s||nt.borderColor,textColor:o||nt.textColor,accentColor:i||nt.accentColor,mutedTextColor:nt.mutedTextColor,inputBackground:nt.inputBackground,cardBackground:nt.cardBackground,hoverBackground:nt.hoverBackground},kn=Pt.useCallback(async()=>{if(!n)return;let v=D.trim();if(!v)return;let I=ot.currentChatId;I||(I=ot.createNewChat(v));let B=ae(jt),A=we(v,B),z=Yt(y),N=et;At([...N,A,z]),Ct(""),ye(),pe(true),await qt({prompt:v,baseMessages:N,userMessage:A,assistantMessageId:z.id,chatId:I});},[n,D,et,jt,ye,qt,ot,At,Ct]),Mn=Pt.useCallback(async v=>{if(!v||!L)return;let I=Array.from(v);W.setError(null);let B=[];try{for(let A of I){if(A.size>wt.MAX_UPLOAD_SIZE){W.setError(`"${A.name}" exceeds the ${wt.formatBytes(wt.MAX_UPLOAD_SIZE)} limit.`);continue}try{let z=new FormData;z.append("file",A);let N=await fetch(`${L}/api/uploads`,{method:"POST",body:z});if(!N.ok){let Jt=await N.text().catch(()=>"");throw new Error(Jt||`Failed to upload ${A.name}`)}let U=await N.json(),It={id:U.id,name:U.name||A.name,url:U.url,mimeType:U.mimeType||A.type||"application/octet-stream",size:typeof U.size=="number"?U.size:A.size};B.push(It);}catch(z){console.error("Failed to upload attachment:",z),W.setError(String(z?.message??`Failed to upload ${A.name}`));}}B.length&&vt(A=>[...A,...B]);}catch(A){console.error("Error adding attachments during edit:",A);}},[L,wt,W]);return Pt.useEffect(()=>{if(Kt.current){Kt.current=false;return}de&&requestAnimationFrame(()=>{ce.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[et,W.streaming,de]),Pt.useEffect(()=>{let v=document.querySelector(".chat-scroll-container");if(!v)return;let I=()=>{let{scrollTop:B,scrollHeight:A,clientHeight:z}=v,U=A-B-z<40;pe(U);};return v.addEventListener("scroll",I),I(),()=>v.removeEventListener("scroll",I)},[]),typeof document<"u"?reactDom.createPortal(jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:w,style:{width:O?V?"100%":typeof m=="number"?`${m}px`:m:"0",height:f,display:"flex",flexDirection:"column",backgroundColor:O?dt.backgroundColor:"transparent",opacity:O?1:0,padding:O?"24px 16px":"0",transition:"all 0.3s ease-out",position:"fixed",top:0,...M==="rtl"?{left:0}:{right:0},bottom:0,zIndex:V?9999:1e3,pointerEvents:O?"auto":"none"},children:[jsxRuntime.jsx(an,{title:R,expandable:c,alwaysOpen:C,maximized:V,streaming:W.streaming,dir:M,resolvedColors:dt,onMaximize:()=>Ot(v=>!v),onNew:fn,onToggleHistory:()=>Mt(v=>!v),onClose:()=>kt(false),historyBtnRef:gn,t:g}),jsxRuntime.jsx(Ue,{messages:et,streaming:W.streaming,editingMessageId:Tt,editingMessageText:pn,editingAttachments:le,error:W.error,actionStatuses:W.actionStatuses,components:$,theme:e,resolvedColors:dt,hideReasoningContent:b,onEditingTextChange:se,onRemoveAttachment:v=>{vt(I=>I.filter(B=>B.id!==v));},onAddAttachments:Mn,uploading:fe,onStartEdit:(v,I)=>{let B=et.find(A=>A.id===v);Ut(v),se(I),B&&B.role==="user"&&vt(ae(pt(B)));},onCancelEdit:()=>{Ut(null),vt([]);},onSaveEdit:async(v,I)=>{let B=et.findIndex(Jt=>Jt.id===v);if(B===-1)return;let A=et[B];if(A.role!=="user")return;let z=I.trim(),N=Re(A,z,ae(le)),U=et.slice(0,B),It=Yt(y);At([...U,N,It]),Ut(null),vt([]),await qt({prompt:z,baseMessages:U,userMessage:N,assistantMessageId:It.id,chatId:ot.currentChatId??null});},onToggleReasoning:v=>{let I=document.querySelector(".chat-scroll-container"),B=I?.scrollTop||0;Kt.current=true,At(A=>A.map(z=>z.id===v&&z.role==="assistant"?{...z,reasoningOpen:!z.reasoningOpen}:z)),requestAnimationFrame(()=>{I&&(I.scrollTop=B);});},scrollAnchorRef:ce,t:g}),jsxRuntime.jsx(sn,{value:D,onChange:Ct,onSend:kn,onStop:W.handleStop,streaming:W.streaming,placeholder:k,attachments:jt,uploading:fe,onRemoveAttachment:yn,onFileInputClick:()=>he.current?.click(),resolvedColors:dt,formatBytes:hn,textareaRef:un,fileInputRef:he,onFileSelection:v=>xn(v,W.setError),t:g,dir:M})]}),jsxRuntime.jsx(Ke,{show:!O&&!C,onClick:()=>kt(true),resolvedColors:dt,floatingButtonPosition:T}),jsxRuntime.jsx(cn,{isOpen:l,onClose:()=>Mt(false),searchQuery:$t,onSearchChange:J,chats:ot.loadChatsIndex(),currentChatId:ot.currentChatId,onChatSelect:bn,onChatDelete:Cn,resolvedColors:dt,t:g}),jsxRuntime.jsx("style",{children:`
|
|
17
|
-
@keyframes ${
|
|
14
|
+
`})]})}function Gn(t){return t.reduce((n,e)=>"startDate"in e&&"endDate"in e&&e.startDate&&e.endDate?n+(e.endDate-e.startDate):n,0)}function Ne(t){if(t<1e3)return `${Math.round(t)}ms`;if(t<6e4)return `${(t/1e3).toFixed(1)}s`;let n=Math.floor(t/6e4),e=Math.round(t%6e4/1e3);return `${n}m ${e}s`}function Qn({action:t,resolvedColors:n,theme:e,isFirst:r,isLast:a,hideReasoningContent:s=false}){let o="startDate"in t&&"endDate"in t&&t.startDate&&t.endDate?Ne(t.endDate-t.startDate):null,i=y=>{let l={input_streaming:{color:e==="dark"?"#eab308":"#d97706",text:"Inputting"},running:{color:e==="dark"?"#3b82f6":"#2563eb",text:"Running"},error:{color:e==="dark"?"#ef4444":"#dc2626",text:"Error"},finished:{color:e==="dark"?"#10b981":"#059669",text:"Called"}};return l[y.status]||l.finished},m=y=>jsxRuntime.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",width:"24px",flexShrink:0},children:[jsxRuntime.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:y,marginTop:"6px",zIndex:1}}),jsxRuntime.jsx("div",{style:{position:"absolute",top:"20px",left:"50%",transform:"translateX(-50%)",width:"2px",height:"calc(100% + 4px)",backgroundColor:e==="dark"?n.borderColor:n.mutedTextColor}})]});if(t.type==="reasoning")return jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[m(n.borderColor),jsxRuntime.jsxs("div",{style:{flex:1,minWidth:0},children:[jsxRuntime.jsxs("div",{style:{fontSize:"11px",color:n.mutedTextColor,marginBottom:"4px",fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.jsx("span",{children:"Reasoning"}),o&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px"},children:o})]}),!s&&jsxRuntime.jsx("div",{style:{fontSize:"13px",color:n.mutedTextColor,lineHeight:"1.6",maxWidth:"100%",opacity:t.status==="streaming"?.8:1},children:jsxRuntime.jsx(mt,{content:t.reasoning,theme:e})})]})]});if(t.type==="tool-call"){let{color:y,text:l}=i(t);return jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[m(y),jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:n.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsx("span",{style:{fontWeight:500,opacity:e==="dark"?.7:.6},children:l}),jsxRuntime.jsx("span",{style:{fontWeight:500},children:t.toolName||"tool"}),o&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",opacity:e==="dark"?.5:.6},children:o})]})})]})}return null}function Oe({mcpToolCalls:t,resolvedColors:n}){if(!t||t.length===0)return null;let e=new Map;t.forEach(s=>{let o=e.get(s.toolName);!o||o.status==="running"&&s.status==="completed"?e.set(s.toolName,{status:s.status||"pending",count:(o?.count||0)+1}):o&&o.count++;});let r=Array.from(e.values()).some(s=>s.status==="running"),a=Array.from(e.values()).filter(s=>s.status==="completed").length;return jsxRuntime.jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,fontSize:"12px",color:n.mutedTextColor},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:r?"#3b82f6":"#10b981"}}),jsxRuntime.jsx("span",{children:r?"Agent is using tools":a>0?`Agent used ${a} tool${a>1?"s":""}`:"Agent used tools"})]}),jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Array.from(e.entries()).map(([s,o])=>jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:n.inputBackground,border:`1px solid ${n.borderColor}`},children:[o.status==="running"?jsxRuntime.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:[jsxRuntime.jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.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"})]}):jsxRuntime.jsx("span",{style:{display:"inline-block",height:"4px",width:"4px",borderRadius:"50%",backgroundColor:o.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsxRuntime.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:s}),o.count>1&&jsxRuntime.jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",o.count]})]},s))})]})}function Ue({items:t,mcpToolCalls:n,mcpToolResults:e,actionStatuses:r,components:a,theme:s,resolvedColors:o}){return !Array.isArray(t)||t.length===0?null:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.map((i,m)=>{let y=`it-${m}`;if(typeof i=="string")return jsxRuntime.jsx("div",{style:{padding:"0",color:o.textColor},children:jsxRuntime.jsx(mt,{content:i,theme:s})},y);if(i&&typeof i=="object"){if(i.type==="action"){let b=`${String(i.name??"action")}:${m}`,c=r.get(b);return jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsxRuntime.jsx("div",{style:{padding:"8px",fontSize:"12px",color:o.mutedTextColor},children:c==="executing"?jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.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:[jsxRuntime.jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.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(i.name??"action")," is executing"]}):jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:"#10b981"}}),String(i.name??"action")," has executed"]})})},y)}if(i.type==="ui"){let b=String(i.component??"").trim(),c=b?a.get(b):void 0;return c?jsxRuntime.jsx("div",{style:{padding:"0"},children:jsxRuntime.jsx(c,{...i.props||{}})},y):jsxRuntime.jsxs("div",{style:{padding:"0"},children:[jsxRuntime.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:o.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:o.accentColor,border:`1px solid ${o.borderColor}`},children:"UI"}),jsxRuntime.jsx("span",{children:b||"component"}),jsxRuntime.jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsxRuntime.jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i.props??{},null,2)})]},y)}let l=i.text||i.content||i.message;return typeof l=="string"?jsxRuntime.jsx("div",{style:{padding:"0",color:o.textColor},children:jsxRuntime.jsx(mt,{content:l,theme:s})},y):jsxRuntime.jsx("div",{style:{padding:"0",fontSize:"14px"},children:jsxRuntime.jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i,null,2)})},y)}return null}),jsxRuntime.jsx(Oe,{mcpToolCalls:n,resolvedColors:o})]})}function je({message:t,streaming:n,isLastMessage:e,actionStatuses:r,components:a,theme:s,resolvedColors:o,onToggleReasoning:i,hideReasoningContent:m=false}){let y=t.mainAgentActions&&t.mainAgentActions.length>0;return jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.firstAgentMessage&&jsxRuntime.jsx("div",{style:{padding:"12px 0"},children:jsxRuntime.jsx("div",{style:{fontSize:"13px",color:o.textColor,lineHeight:"1.5"},children:t.firstAgentMessage})}),y?jsxRuntime.jsx(We,{mainAgentActions:t.mainAgentActions,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o,streaming:n&&e,theme:s,hideReasoningContent:m}):jsxRuntime.jsx(He,{reasoning:t.reasoning,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o}),jsxRuntime.jsx(Ue,{items:t.items,mcpToolCalls:t.mcpToolCalls,mcpToolResults:t.mcpToolResults,actionStatuses:r,components:a,theme:s,resolvedColors:o}),n&&e&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:o.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsxRuntime.jsx("span",{children:"Working\u2026"})]})]})}function qe({messages:t,streaming:n,editingMessageId:e,editingMessageText:r,editingAttachments:a,error:s,actionStatuses:o,components:i,theme:m,resolvedColors:y,onEditingTextChange:l,onRemoveAttachment:b,onAddAttachments:c,uploading:k,onStartEdit:f,onCancelEdit:M,onSaveEdit:x,onToggleReasoning:p,scrollAnchorRef:v,hideReasoningContent:h=false,t:C}){return jsxRuntime.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"},children:[s&&jsxRuntime.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:s}),t.length===0&&!n&&jsxRuntime.jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${y.borderColor}`,backgroundColor:y.accentColor,color:y.mutedTextColor},children:C("messages.empty")}),jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:t.map((u,g)=>jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:u.role==="user"?jsxRuntime.jsx(ze,{message:u,isEditing:e===u.id,editingText:r,editingAttachments:a,onEditingTextChange:l,onStartEdit:f,onCancelEdit:M,onSaveEdit:x,onRemoveAttachment:b,onAddAttachments:c,uploading:k,streaming:n,resolvedColors:y,t:C}):jsxRuntime.jsx(je,{message:u,streaming:n,isLastMessage:g===t.length-1,actionStatuses:o,components:i,theme:m,resolvedColors:y,onToggleReasoning:p,hideReasoningContent:h})},u.id))}),jsxRuntime.jsx("div",{ref:v})]})}function Je({show:t,onClick:n,resolvedColors:e,floatingButtonPosition:r}){if(!t)return null;let a={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsxRuntime.jsx("button",{"aria-label":"Open chat",onClick:n,style:{...a,borderColor:e.borderColor,backgroundColor:e.accentColor,color:e.textColor,borderRadius:"50%",border:`1px solid ${e.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:s=>{s.currentTarget.style.borderColor=e.primaryColor,s.currentTarget.style.backgroundColor=`${e.accentColor}dd`;},onMouseLeave:s=>{s.currentTarget.style.borderColor=e.borderColor,s.currentTarget.style.backgroundColor=e.accentColor;},children:jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function na(t=false){let[n,e]=Bt.useState(t),r=Bt.useCallback(()=>e(o=>!o),[]),a=Bt.useCallback(()=>e(true),[]),s=Bt.useCallback(()=>e(false),[]);return {on:n,toggle:r,setOn:e,setTrue:a,setFalse:s}}function aa(){let t=Bt.useRef(null);return Bt.useEffect(()=>{let n=t.current;if(!n)return;let e=new MutationObserver(()=>{n.scrollTop=n.scrollHeight;});return e.observe(n,{childList:true,subtree:true}),n.scrollTop=n.scrollHeight,()=>e.disconnect()},[]),t}var Ve=Bt.createContext(void 0);function ir({baseUrl:t,children:n}){let[e,r]=Bt.useState(new Map),[a,s]=Bt.useState(new Map),[o,i]=Bt.useState(new Map),[m,y]=Bt.useState(new Map),l=Bt.useCallback((h,C)=>(r(u=>{let g=new Map(u);return g.set(String(h),C),g}),()=>{r(u=>{let g=new Map(u),T=g.get(String(h));return (!C||T===C)&&g.delete(String(h)),g});}),[]),b=Bt.useCallback((h,C)=>{r(u=>{let g=new Map(u),T=g.get(String(h));return (!C||T===C)&&g.delete(String(h)),g});},[]),c=Bt.useCallback((h,C)=>(s(u=>{let g=new Map(u);return g.set(String(h),C),g}),()=>{s(u=>{let g=new Map(u),T=g.get(String(h));return (!C||T===C)&&g.delete(String(h)),g});}),[]),k=Bt.useCallback((h,C)=>{s(u=>{let g=new Map(u),T=g.get(String(h));return (!C||T===C)&&g.delete(String(h)),g});},[]),f=Bt.useCallback((h,C)=>{i(u=>{let g=new Map(u);return C?g.set(h,true):g.delete(h),g});},[]),M=Bt.useCallback((h,C)=>{y(u=>{let g=new Map(u);return C?g.set(h,true):g.delete(h),g});},[]),x=Bt.useMemo(()=>Array.from(o.values()).some(h=>h),[o]),p=Bt.useMemo(()=>Array.from(m.values()).some(h=>h),[m]),v=Bt.useMemo(()=>({baseUrl:t,actions:e,components:a,registerAction:l,unregisterAction:b,registerComponent:c,unregisterComponent:k,isAnyStreaming:x,setStreamingState:f,isAnyChatOpen:p,setChatOpenState:M}),[t,e,a,l,b,c,k,x,f,p,M]);return jsxRuntime.jsx(Ve.Provider,{value:v,children:n})}function Q(){let t=Bt.useContext(Ve);return t||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{}}}function ga(t,n){let{registerAction:e}=Q(),r=Bt.useRef(n);Bt.useEffect(()=>{r.current=n;});let a=Bt.useCallback((s,o)=>r.current(s,o),[]);Bt.useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaAction] Invalid action registration: name="${t}", handler type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function ya(t,n){let{registerComponent:e}=Q(),r=Bt.useRef(n);Bt.useEffect(()=>{r.current=n;});let a=Bt.useMemo(()=>{let s=o=>{let i=r.current;return Bt__default.default.createElement(i,o)};return s.displayName=`HsafaStable(${t})`,s},[]);Bt.useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaComponent] Invalid component registration: name="${t}", component type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function Ge(t){let n=`hsafaChat_${t}`,e=`${n}.chats`,r=u=>`${n}.chat.${u}`,a=`${n}.currentChatId`,s=`${n}.showChat`,[o,i]=Bt.useState(null),m=Bt.useRef(false),y=Bt.useRef(null),l=()=>{try{let u=localStorage.getItem(e);return u?JSON.parse(u):[]}catch{return []}},b=u=>{try{localStorage.setItem(e,JSON.stringify(u));}catch{}},c=u=>{try{let g=localStorage.getItem(r(u));return g?JSON.parse(g):null}catch{return null}},k=u=>{try{localStorage.setItem(r(u.id),JSON.stringify(u));}catch{}},f=u=>{let g=l(),T=g.findIndex(R=>R.id===u.id);T>=0?g[T]=u:g.unshift(u),b(g);},M=u=>{let T=l().filter(R=>R.id!==u);b(T);},x=u=>{try{localStorage.removeItem(r(u));}catch{}};return {currentChatId:o,setCurrentChatId:i,hasChatRecordRef:m,pendingFirstTitleRef:y,loadChatsIndex:l,loadChat:c,saveChat:k,deleteChat:(u,g)=>{x(u),M(u);let T=o===u;if(T){i(null),m.current=false,y.current=null;try{localStorage.removeItem(a);}catch{}}g?.(T);},loadChatPreferences:()=>{try{let u=localStorage.getItem(a);if(u){let g=c(u);if(g)return i(g.id),m.current=!0,g.messages||[]}}catch{}return []},persistChatData:u=>{if(!o||!m.current)return;k({id:o,messages:u,agentId:t});let T=u.find(H=>H.role==="user"),R=T?De(T):"New chat",L=(y.current||R).slice(0,80),$={id:o,title:L,createdAt:Date.now(),updatedAt:Date.now()};f($);try{localStorage.setItem(a,o);}catch{}},createNewChat:u=>{let g=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;i(g),m.current=true;let T=(u||"New chat").slice(0,80),R=Date.now();f({id:g,title:T,createdAt:R,updatedAt:R});try{localStorage.setItem(a,g);}catch{}return g},upsertChatMeta:f,showChatKey:s}}function Qe(){let[t,n]=Bt.useState(false),[e,r]=Bt.useState(null),a=Bt.useRef(null),s=Bt.useRef({}),o=Bt.useRef(void 0),i=Bt.useRef(new Set),m=Bt.useRef(new Map),y=Bt.useRef(new Map),[l,b]=Bt.useState(new Map),c=Bt.useCallback((p,v)=>{let h=m.current.get(p)||[],C=JSON.stringify(v);if(h.push(C),h.length>5&&h.shift(),m.current.set(p,h),h.length>=3){let u=h.slice(-3);return u.every(g=>g===u[0])}return false},[]),k=Bt.useCallback((p,v,h,C)=>{!Array.isArray(p)||p.length===0||p.forEach((u,g)=>{if(!(!u||typeof u!="object")&&u.type==="action"){let T=String(u.name??"").trim();if(!T)return;let R=h.get(T);if(!R){console.warn(`Action handler not found for: ${T}`);return}let L=!!s.current[T],$=`${o.current||"assist"}:${T}:${g}`,H=`${T}:${g}`;try{if(v==="partial"&&L){b(B=>new Map(B).set(H,"executing"));let j=setTimeout(()=>{Promise.resolve(R(u.params,{name:T,trigger:v,index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(B=>{console.error(`Error executing streaming action ${T}:`,B),b(I=>new Map(I).set(H,"executed"));});},50);y.current.set(`${H}_timeout`,j);}else if(v==="partial"&&!L){let j=c(H,u.params),B=y.current.get(H);j&&B!=="executed"?(y.current.set(H,"executed"),b(I=>new Map(I).set(H,"executed")),Promise.resolve(R(u.params,{name:T,trigger:"params_complete",index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(I=>{console.error(`Error executing stabilized action ${T}:`,I);})):B||(y.current.set(H,"executing"),b(I=>new Map(I).set(H,"executing")));}else if(v==="final"&&y.current.get(H)!=="executed"&&!i.current.has($)){i.current.add($);let B=y.current.get(`${H}_timeout`);B&&(clearTimeout(B),y.current.delete(`${H}_timeout`)),y.current.set(H,"executed"),b(I=>new Map(I).set(H,"executed")),Promise.resolve(R(u.params,{name:T,trigger:L?"final":"params_complete",index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(I=>{console.error(`Error executing final action ${T}:`,I);});}}catch(j){console.error(`Error processing action ${T}:`,j);}}});},[c]),f=Bt.useCallback(()=>{a.current&&(a.current.abort(),a.current=null),n(false),r("Request stopped by user");},[]),M=Bt.useCallback(()=>{i.current.clear(),m.current.clear(),y.current.clear(),b(new Map);},[]),x=Bt.useCallback(()=>{y.current.forEach((p,v)=>{v.endsWith("_timeout")&&clearTimeout(p);});},[]);return {streaming:t,setStreaming:n,error:e,setError:r,actionStatuses:l,setActionStatuses:b,abortControllerRef:a,actionExecMapRef:s,assistantMsgIdRef:o,calledFinalActionsRef:i,actionParamsHistoryRef:m,actionExecutionStatusRef:y,processActions:k,handleStop:f,resetActionTracking:M,cleanupTimeouts:x,hasActionParamsStabilized:c}}function tn(t,n){if(!t)return n;let e=t.endsWith("/")?t.slice(0,-1):t,r=n.startsWith("/")?n:`/${n}`;return `${e}${r}`}var oe=25*1024*1024;function nn(t){let[n,e]=Bt.useState([]),[r,a]=Bt.useState(false),s=Bt.useRef(null),o=Bt.useCallback(c=>{if(!c||Number.isNaN(c))return "0 B";let k=["B","KB","MB","GB","TB"],f=Math.min(k.length-1,Math.floor(Math.log(c)/Math.log(1024)));return `${(c/Math.pow(1024,f)).toFixed(f===0?0:1)} ${k[f]}`},[]),i=Bt.useCallback(async c=>{let k=new FormData;k.append("file",c);let f=await fetch(tn(t,"/api/uploads"),{method:"POST",body:k});if(!f.ok){let x=await f.text().catch(()=>"");throw new Error(x||`Failed to upload ${c.name}`)}let M=await f.json();return {id:M.id,name:M.name||c.name,url:M.url,mimeType:M.mimeType||c.type||"application/octet-stream",size:typeof M.size=="number"?M.size:c.size}},[t]),m=Bt.useCallback(c=>{e(k=>k.filter(f=>f.id!==c));},[]),y=Bt.useCallback(async(c,k)=>{if(!c)return;let f=Array.isArray(c)?c:Array.from(c);k(null),a(true);let M=[];try{for(let x of f){if(x.size>oe){k(`"${x.name}" exceeds the ${o(oe)} limit.`);continue}try{let p=await i(x);M.push(p);}catch(p){console.error("Failed to upload attachment:",p),k(String(p?.message??`Failed to upload ${x.name}`));}}M.length&&e(x=>[...x,...M]);}finally{a(false);}},[i,o]),l=Bt.useCallback((c,k)=>{let f=[],M=(c||"").trim();M&&f.push({type:"text",text:M});for(let x of k||[]){let p=x.mimeType||"application/octet-stream";p.startsWith("image/")?f.push({type:"image",image:new URL(x.url),mediaType:p}):f.push({type:"file",data:x.url,mediaType:p,name:x.name});}return f},[]),b=Bt.useCallback(()=>{e([]);},[]);return {attachments:n,uploading:r,fileInputRef:s,formatBytes:o,handleRemoveAttachment:m,handleFileSelection:y,buildUserContent:l,clearAttachments:b,MAX_UPLOAD_SIZE:oe}}function hr(t){return JSON.parse(JSON.stringify(t))}function rn(){let[t,n]=Bt.useState(false),[e,r]=Bt.useState(null),[a,s]=Bt.useState(null),o=Bt.useRef(null),i=Bt.useCallback(async({agentId:l,body:b,baseUrl:c,onUpdate:k,signal:f})=>{try{let $=function(){let I=hr(C);s(I),k?.(I);};var M=$;n(!0),r(null);let x;if(f)o.current=null,x=f;else {let I=new AbortController;o.current=I,x=I.signal;}let v=`${c?c.replace(/\/$/,""):""}/api/run/${encodeURIComponent(l)}`,h=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson"},body:JSON.stringify(b??{}),signal:x});if(!h.ok||!h.body){let I=await h.text().catch(()=>"");throw new Error(`Request failed: ${h.status} ${h.statusText} - ${I}`)}let C={first_agent:{message:"",continue:!1},main_agent:[]},u=null,g=null,T=null,R=null,L=!1,H=h.body.getReader(),j=new TextDecoder("utf-8"),B="";for($();;){let{value:I,done:Mt}=await H.read();if(Mt)break;B+=j.decode(I,{stream:!0});let et=B.indexOf(`
|
|
15
|
+
`);for(;et!==-1;){let q=B.slice(0,et).trim();if(B=B.slice(et+1),q.length>0)try{let d=JSON.parse(q);switch(d?.type){case "start":break;case "first-agent-start":C.first_agent.startDate=d?.startDate,C.first_agent.durationMs=d?.durationMs,$();break;case "first-agent-partial":typeof d?.message=="string"&&(C.first_agent.message=d.message),typeof d?.continue=="boolean"&&(C.first_agent.continue=d.continue),typeof d?.durationMs=="number"&&(C.first_agent.durationMs=d.durationMs),$();break;case "first-agent-end":typeof d?.message=="string"&&(C.first_agent.message=d.message),typeof d?.continue=="boolean"&&(C.first_agent.continue=d.continue),C.first_agent.endDate=d?.endDate,C.first_agent.durationMs=d?.durationMs,$();break;case "main-agent-start":L=!1;break;case "main-agent-step-finish":{let S={type:"step",stepNumber:void 0,finishReason:d?.finishReason,usage:d?.usage,endDate:d?.endDate,durationMs:d?.durationMs};C.main_agent.push(S),$();break}case "main-agent-skipped":L=!0;break;case "main-agent-reasoning-start":u={type:"reasoning",reasoning:"",status:"streaming",startDate:d?.startDate,durationMs:d?.durationMs},C.main_agent.push(u),$();break;case "main-agent-reasoning-delta":u&&typeof d?.text=="string"&&(u.reasoning+=d.text,u.durationMs=d?.durationMs,$());break;case "main-agent-reasoning-end":if(u){if(typeof d?.text=="string"&&d.text.length>0&&(u.reasoning+=d.text),u.status="finished",u.endDate=d?.endDate,u.durationMs=d?.durationMs,!u.reasoning||u.reasoning.trim().length===0){let S=C.main_agent.indexOf(u);S>-1&&C.main_agent.splice(S,1);}u=null,$();}else if(typeof d?.text=="string"&&d.text.length>0){let S={type:"reasoning",reasoning:d.text,status:"finished",endDate:d?.endDate,durationMs:d?.durationMs};C.main_agent.push(S),$();}break;case "main-agent-tool-call-start":g={type:"tool-call",toolCallId:d?.toolCallId,toolName:d?.toolName,inputText:"",input:void 0,output:void 0,status:"input_streaming",startDate:d?.startDate,durationMs:d?.durationMs},C.main_agent.push(g),$();break;case "main-agent-tool-input-delta":let it=d?.delta||d?.argsTextDelta;g&&typeof it=="string"&&(g.inputText=(g.inputText||"")+it,g.durationMs=d?.durationMs,$());break;case "tool-call":case "main-agent-tool-call":if(g)g.input=d?.input,g.status="running",g.durationMs=d?.durationMs;else {let S=C.main_agent.find(vt=>vt.type==="tool-call"&&(vt.toolCallId===d?.toolCallId||vt.toolName===d?.toolName));S?(S.input=d?.input,S.status="running",S.durationMs=d?.durationMs,g=S):(g={type:"tool-call",toolCallId:d?.toolCallId,toolName:d?.toolName,input:d?.input,inputText:"",output:void 0,status:"running",durationMs:d?.durationMs},C.main_agent.push(g));}$();break;case "tool-result":case "main-agent-tool-result":let Y=g;if(Y||(Y=C.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===d?.toolCallId||S.toolName===d?.toolName))||null),Y)Y.output=d?.output,Y.status="finished",Y.endDate=d?.endDate,Y.durationMs=d?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:d?.toolCallId,toolName:d?.toolName,input:void 0,inputText:"",output:d?.output,status:"finished",endDate:d?.endDate,durationMs:d?.durationMs};C.main_agent.push(S);}$();break;case "tool-error":case "main-agent-tool-error":let J=g;if(J||(J=C.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===d?.toolCallId||S.toolName===d?.toolName))||null),J)J.error=d?.error,J.status="error",J.endDate=d?.endDate,J.durationMs=d?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:d?.toolCallId,toolName:d?.toolName,input:void 0,inputText:"",output:void 0,error:d?.error,status:"error",endDate:d?.endDate,durationMs:d?.durationMs};C.main_agent.push(S);}$();break;case "main-agent-response-partial":if(L)break;if(T||(T={type:"response",items:[],startDate:d?.startDate,durationMs:d?.durationMs},C.main_agent.push(T)),d?.value&&typeof d.value=="object"){let S=Array.isArray(d.value.items)?d.value.items:T.items;Object.assign(T,d.value),T.items=S,T.durationMs=d?.durationMs;}$();break;case "text-delta":case "main-agent-text-delta":typeof d?.text=="string"&&d.text&&(R||(R={type:"text",text:"",status:"streaming",startDate:d?.startDate,durationMs:d?.durationMs},C.main_agent.push(R)),R.text+=d.text,R.durationMs=d?.durationMs,$());break;case "text-end":R&&(R.status="finished",R.endDate=d?.endDate,R.durationMs=d?.durationMs,R=null,$());break;case "source":case "main-agent-source":let Tt={type:"source",source:d?.source,durationMs:d?.durationMs};C.main_agent.push(Tt),$();break;case "file":case "main-agent-file":let Kt={type:"file",file:d?.file,durationMs:d?.durationMs};C.main_agent.push(Kt),$();break;case "final":if(L)break;if(d?.value&&typeof d.value=="object"){T||(T={type:"response",items:[],endDate:d?.endDate,durationMs:d?.durationMs},C.main_agent.push(T));let S=Array.isArray(d.value.items)?d.value.items:T.items;Object.assign(T,d.value),T.items=S,T.endDate=d?.endDate,T.durationMs=d?.durationMs;}$();break;case "error":case "main-agent-error":throw new Error(d?.error||"Unknown agent error");default:break}}catch(d){console.warn("Failed to parse streaming line:",d);}et=B.indexOf(`
|
|
16
|
+
`);}}try{H.releaseLock();}catch{}return n(!1),C}catch(x){return x.name==="AbortError"?r("Request was cancelled"):r(x?.message||"Request failed"),n(false),null}},[]),m=Bt.useCallback(()=>{o.current&&(o.current.abort(),o.current=null),n(false);},[]),y=Bt.useCallback(()=>{s(null),r(null),n(false);},[]);return {streaming:t,error:e,streamData:a,startStreaming:i,stopStreaming:m,reset:y}}var on={en:{"header.maximize":"Maximize","header.minimize":"Minimize","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","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit","messages.empty":"Start by sending a message to the agent.","messages.error":"An error occurred","history.search":"Search","history.noChatsFound":"No chats found.","history.untitledChat":"Untitled chat","history.deleteChat":"Delete chat","general.agent":"Agent"},ar:{"header.maximize":"\u062A\u0643\u0628\u064A\u0631","header.minimize":"\u062A\u0635\u063A\u064A\u0631","header.new":"\u062C\u062F\u064A\u062F","header.history":"\u0627\u0644\u0633\u062C\u0644","header.close":"\u0625\u063A\u0644\u0627\u0642 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","input.placeholder":"\u0627\u0637\u0631\u062D \u0633\u0624\u0627\u0644\u0643...","input.attachFiles":"\u0625\u0631\u0641\u0627\u0642 \u0645\u0644\u0641\u0627\u062A","input.insertLink":"\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637","input.send":"\u0625\u0631\u0633\u0627\u0644","input.stop":"\u0625\u064A\u0642\u0627\u0641","input.uploadingFiles":"\u062C\u0627\u0631\u064A \u0631\u0641\u0639 \u0627\u0644\u0645\u0644\u0641\u0627\u062A...","input.previewImage":"\u0645\u0639\u0627\u064A\u0646\u0629 \u0627\u0644\u0635\u0648\u0631\u0629","input.removeFile":"\u062D\u0630\u0641 \u0627\u0644\u0645\u0644\u0641","editor.cancel":"\u0625\u0644\u063A\u0627\u0621","editor.saveAndRegenerate":"\u062D\u0641\u0638 \u0648\u0625\u0639\u0627\u062F\u0629 \u062A\u0648\u0644\u064A\u062F","editor.clickToEdit":"\u0627\u0646\u0642\u0631 \u0644\u0644\u062A\u0639\u062F\u064A\u0644","messages.empty":"\u0627\u0628\u062F\u0623 \u0628\u0625\u0631\u0633\u0627\u0644 \u0631\u0633\u0627\u0644\u0629 \u0625\u0644\u0649 \u0627\u0644\u0648\u0643\u064A\u0644.","messages.error":"\u062D\u062F\u062B \u062E\u0637\u0623","history.search":"\u0628\u062D\u062B","history.noChatsFound":"\u0644\u0645 \u064A\u062A\u0645 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u0645\u062D\u0627\u062F\u062B\u0627\u062A.","history.untitledChat":"\u0645\u062D\u0627\u062F\u062B\u0629 \u0628\u062F\u0648\u0646 \u0639\u0646\u0648\u0627\u0646","history.deleteChat":"\u062D\u0630\u0641 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","general.agent":"\u0627\u0644\u0648\u0643\u064A\u0644"}};function an(t,n){return on[t]?.[n]||on.en[n]||n}function sn(t="en"){return {t:Bt.useCallback(e=>an(t,e),[t]),language:t}}function cn({actions:t,currentChatId:n}){let e=Bt.useRef({}),r=Bt.useRef(void 0),a=Bt.useRef(new Set),[s,o]=Bt.useState(new Map);Bt.useEffect(()=>()=>{},[]);let i=Bt.useCallback((y,l)=>{if(!Array.isArray(y)||y.length===0){l==="final"&&o(b=>{let c=new Map(b);return c.forEach((k,f)=>c.set(f,"executed")),c});return}y.forEach((b,c)=>{if(!(!b||typeof b!="object")&&b.type==="action"){let k=String(b.name??"").trim();if(!k)return;let f=t.get(k);if(!f){console.warn(`[useActions] Action handler not found: "${k}". Did you register it with useHsafaAction?`);return}let M=typeof b.executeOnStream=="boolean"?b.executeOnStream:!!e.current[k],x=`${r.current||"assist"}:${k}:${c}`,p=`${k}:${c}`;try{l==="partial"&&M?(o(v=>new Map(v).set(p,"executing")),Promise.resolve(f(b.params,{name:k,trigger:l,index:c,assistantMessageId:r.current,chatId:n||void 0})).catch(v=>{o(h=>new Map(h).set(p,"executed"));})):l==="partial"&&!M?o(v=>{if(v.get(p)==="executing")return v;let h=new Map(v);return h.set(p,"executing"),h}):l==="final"&&(a.current.has(x)||(a.current.add(x),o(v=>new Map(v).set(p,"executed")),Promise.resolve(f(b.params,{name:k,trigger:M?"final":"params_complete",index:c,assistantMessageId:r.current,chatId:n||void 0})).catch(v=>{console.error(`[useActions] Error executing final action "${k}":`,v);})));}catch(v){console.error(`[useActions] Error processing action "${k}":`,v);}}});},[t,n]),m=Bt.useCallback(()=>{a.current.clear(),o(new Map);},[]);return {actionExecMapRef:e,assistantMsgIdRef:r,actionStatuses:s,processActions:i,resetActionTracking:m}}function Wt({icon:t,onClick:n,ariaLabel:e,resolvedColors:r,disabled:a=false,title:s}){return jsxRuntime.jsx("button",{"aria-label":e,title:s,disabled:a,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:o=>{a||(o.currentTarget.style.backgroundColor=r.hoverBackground,o.currentTarget.style.color=r.textColor);},onMouseLeave:o=>{o.currentTarget.style.backgroundColor="transparent",o.currentTarget.style.color=r.mutedTextColor;},onClick:n,children:t})}function pn({title:t,expandable:n,alwaysOpen:e,maximized:r,streaming:a,dir:s,resolvedColors:o,onMaximize:i,onNew:m,onToggleHistory:y,onClose:l,historyBtnRef:b,t:c}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:s==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:t,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:t})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[n&&jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.Maximize2,{size:"20",strokeWidth:"2"}),onClick:i,ariaLabel:c(r?"header.minimize":"header.maximize"),resolvedColors:o}),jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.Plus,{size:"20",strokeWidth:"2"}),onClick:()=>{a||m();},ariaLabel:c("header.new"),resolvedColors:o,disabled:a}),jsxRuntime.jsx("button",{ref:b,"aria-label":c("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:k=>{k.currentTarget.style.backgroundColor=o.hoverBackground,k.currentTarget.style.color=o.textColor;},onMouseLeave:k=>{k.currentTarget.style.backgroundColor="transparent",k.currentTarget.style.color=o.mutedTextColor;},onClick:y,children:jsxRuntime.jsx(lucideReact.History,{size:"20",strokeWidth:"2"})}),!e&&jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.ChevronRight,{size:"20",strokeWidth:"2",style:{transform:s==="rtl"?"rotate(180deg)":"none"}}),onClick:l,ariaLabel:c("header.close"),resolvedColors:o})]})]})}function gn({value:t,onChange:n,onSend:e,onStop:r,streaming:a,placeholder:s,attachments:o,uploading:i,onRemoveAttachment:m,onFileInputClick:y,resolvedColors:l,formatBytes:b,textareaRef:c,fileInputRef:k,onFileSelection:f,t:M,dir:x="ltr"}){return Bt__default.default.useEffect(()=>{let p=c.current;if(p){p.style.height="24px",p.offsetHeight,p.style.height="auto";let v=Math.min(p.scrollHeight,200);p.style.height=`${v}px`;}},[t,c]),Bt__default.default.useEffect(()=>{let p=c.current;p&&!t&&(p.style.height="24px");},[c,t]),jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:l.backgroundColor},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:"1"},children:jsxRuntime.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${l.borderColor}`,backgroundColor:l.accentColor},children:[o.length>0&&jsxRuntime.jsx("div",{style:{padding:"12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:o.map(p=>{let v=p.mimeType?.startsWith("image/");return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:l.inputBackground,borderRadius:"10px",border:`1px solid ${l.borderColor}`,fontSize:"12px",color:l.textColor,transition:"all 0.2s ease-out",cursor:"pointer",position:"relative"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:v?"transparent":l.accentColor},children:[v?jsxRuntime.jsx("img",{src:p.url,alt:p.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:h=>{h.target.style.display="none";let C=h.target.nextElementSibling;C&&(C.style.display="block");}}):null,jsxRuntime.jsx(lucideReact.File,{size:"14",strokeWidth:"2",style:{display:v?"none":"block",color:l.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsxRuntime.jsx("span",{title:p.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:p.name}),jsxRuntime.jsx("span",{style:{color:l.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:b(p.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[v&&jsxRuntime.jsx("button",{onClick:h=>{h.stopPropagation(),window.open(p.url,"_blank");},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:M("input.previewImage"),onMouseEnter:h=>{h.currentTarget.style.backgroundColor=l.hoverBackground,h.currentTarget.style.color=l.textColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=l.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),jsxRuntime.jsx("button",{onClick:h=>{h.stopPropagation(),m(p.id);},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:M("input.removeFile"),onMouseEnter:h=>{h.currentTarget.style.backgroundColor="#ef444420",h.currentTarget.style.color="#ef4444";},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=l.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.X,{size:"12",strokeWidth:"2"})})]})]},p.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:l.mutedTextColor},children:[jsxRuntime.jsx(lucideReact.Loader2,{size:"14",strokeWidth:"2",style:{animation:"spin 1s linear infinite"}}),jsxRuntime.jsx("span",{children:M("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.jsx("textarea",{"aria-label":"Prompt",rows:1,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:l.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:s,value:t,onChange:p=>n(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),a||e());},ref:c})}),jsxRuntime.jsxs("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{right:"8px"}:{left:"8px"},display:"flex",alignItems:"center",gap:"4px",color:l.mutedTextColor},children:[jsxRuntime.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:p=>{p.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,p.currentTarget.style.color=l.textColor;},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=l.mutedTextColor;},"aria-label":M("input.attachFiles"),onClick:y,children:jsxRuntime.jsx(lucideReact.Paperclip,{size:"18",strokeWidth:"2"})}),jsxRuntime.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:p=>{p.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,p.currentTarget.style.color=l.textColor;},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=l.mutedTextColor;},"aria-label":M("input.insertLink"),children:jsxRuntime.jsx(lucideReact.Link,{size:"18",strokeWidth:"2"})})]}),jsxRuntime.jsx("input",{type:"file",ref:k,multiple:true,accept:"*/*",style:{display:"none"},onChange:p=>f(p.target.files)}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{left:"8px"}:{right:"8px"}},children:jsxRuntime.jsx("button",{"aria-label":M(a?"input.stop":"input.send"),disabled:!a&&!t.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a?"#ef4444":l.borderColor}`,backgroundColor:a?"#ef444420":l.cardBackground,color:a?"#ef4444":l.mutedTextColor,opacity:!a&&!t.trim()?.4:1,cursor:!a&&!t.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{p.currentTarget.disabled||(a?(p.currentTarget.style.borderColor="#dc2626",p.currentTarget.style.backgroundColor="#dc262630",p.currentTarget.style.color="#dc2626"):(p.currentTarget.style.borderColor=l.primaryColor,p.currentTarget.style.backgroundColor=l.hoverBackground,p.currentTarget.style.color=l.textColor));},onMouseLeave:p=>{p.currentTarget.disabled||(a?(p.currentTarget.style.borderColor="#ef4444",p.currentTarget.style.backgroundColor="#ef444420",p.currentTarget.style.color="#ef4444"):(p.currentTarget.style.borderColor=l.borderColor,p.currentTarget.style.backgroundColor=l.cardBackground,p.currentTarget.style.color=l.mutedTextColor));},onClick:()=>{a?r():e();},children:a?jsxRuntime.jsx(lucideReact.Square,{size:"18",strokeWidth:"2"}):jsxRuntime.jsx(lucideReact.ArrowUp,{size:"18",strokeWidth:"2"})})})]})})})}function mn(t){let n=Date.now()-t,e=Math.max(1,Math.floor(n/1e3));if(e<60)return `${e}s`;let r=Math.floor(e/60);if(r<60)return `${r}m`;let a=Math.floor(r/60);if(a<24)return `${a}h`;let s=Math.floor(a/24);if(s<7)return `${s}d`;let o=Math.floor(s/7);if(o<4)return `${o}w`;let i=Math.floor(s/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function fn({isOpen:t,onClose:n,searchQuery:e,onSearchChange:r,chats:a,currentChatId:s,onChatSelect:o,onChatDelete:i,resolvedColors:m,t:y}){if(!t)return null;let l=e.trim()?a.filter(c=>(c.title||"").toLowerCase().includes(e.toLowerCase().trim())):a,b=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:n}),jsxRuntime.jsxs("div",{style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${m.borderColor}`,backgroundColor:`${m.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${m.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.jsx("input",{autoFocus:true,value:e,onChange:c=>r(c.target.value),placeholder:y("history.search"),style:{width:"100%",borderRadius:"8px",backgroundColor:m.inputBackground,padding:"8px 12px",fontSize:"14px",color:m.textColor,border:`1px solid ${m.borderColor}`,outline:"none"},onFocus:c=>c.currentTarget.style.borderColor=m.primaryColor,onBlur:c=>c.currentTarget.style.borderColor=m.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:l.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:m.mutedTextColor,textAlign:"center"},children:y("history.noChatsFound")}):jsxRuntime.jsx("div",{children:l.map((c,k)=>jsxRuntime.jsx("div",{style:{borderTop:k>0?`1px solid ${m.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:c.id===s?m.cardBackground:"transparent"},children:[jsxRuntime.jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:m.textColor},onMouseEnter:f=>f.currentTarget.style.backgroundColor=m.hoverBackground,onMouseLeave:f=>f.currentTarget.style.backgroundColor="transparent",onClick:()=>o(c.id),children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:m.textColor},children:c.title||y("history.untitledChat")})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:m.mutedTextColor},children:mn(c.updatedAt)})]})}),jsxRuntime.jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:m.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:y("history.deleteChat"),onMouseEnter:f=>{f.currentTarget.style.color="#ef4444",f.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",f.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:f=>{f.currentTarget.style.color=m.mutedTextColor,f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.borderColor="transparent";},onClick:f=>{f.stopPropagation(),i(c.id);},children:jsxRuntime.jsx(lucideReact.Trash2,{size:"16",strokeWidth:"2"})})]})},c.id))})})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(b,document.body):b}var Ot={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};var le=t=>t.map(n=>({...n}));function Br(t){let[n,e]=Bt.useState(()=>{try{return t.loadChatPreferences()}catch(o){return console.warn("Failed to load chat preferences:",o),[]}});Bt.useEffect(()=>{if(n.length!==0)try{t.persistChatData(n);}catch(o){console.warn("Failed to persist chat data:",o);}},[n]);let r=Bt.useCallback(o=>{try{t.setCurrentChatId(o);let i=t.loadChat(o);return e(i?.messages||[]),!0}catch(i){return console.warn("Failed to load selected chat:",i),false}},[t]),a=Bt.useCallback(o=>{try{t.deleteChat(o,i=>{i&&e([]);});}catch(i){console.warn("Failed to delete chat:",i);}},[t]),s=Bt.useCallback(()=>{e([]),t.setCurrentChatId(null);},[t]);return {messages:n,setMessages:e,selectChat:r,deleteChat:a,resetChat:s}}function Lr(t){let{agentId:n,theme:e="dark",primaryColor:r,backgroundColor:a,borderColor:s,textColor:o,accentColor:i,width:m=420,height:y="100vh",expandable:l=true,alwaysOpen:b=false,defaultOpen:c=false,dir:k="ltr",language:f,floatingButtonPosition:M=k==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},placeholder:x,title:p,chatContainerClassName:v="",defaultReasoningOpen:h=false,hideReasoningContent:C=false}=t,u=f||(k==="rtl"?"ar":"en"),{t:g}=sn(u),T=x??g("input.placeholder"),R=p??g("general.agent"),{baseUrl:L,actions:$,components:H,setStreamingState:j,setChatOpenState:B}=Q(),I=Bt.useRef(`chat-${n}-${Date.now()}`).current,[Mt,et]=Bt.useState(""),[q,d]=Bt.useState(()=>{if(b)return true;try{let A=localStorage.getItem(`hsafaChat_${n}.showChat`);return A!==null?A==="true":c}catch{return c}}),[ce,it]=Bt.useState(false),[Y,J]=Bt.useState(""),[Tt,Kt]=Bt.useState(false),[S,vt]=Bt.useState(0),[yn,jt]=Bt.useState(null),[xn,de]=Bt.useState(""),[pe,At]=Bt.useState([]),ue=Bt.useRef(null),[ge,me]=Bt.useState(true),qt=Bt.useRef(false),bn=Bt.useRef(null),Cn=Bt.useRef(null),kn=Bt.useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),nt=Ge(n),{messages:rt,setMessages:wt,selectChat:fe,deleteChat:he,resetChat:Mn}=Br(nt),_=Qe(),St=nn(L||""),Jt=rn(),{assistantMsgIdRef:Tn,actionStatuses:vn,processActions:ye,resetActionTracking:An}=cn({actions:$,currentChatId:nt.currentChatId});Bt.useEffect(()=>{j(I,_.streaming);},[_.streaming,I,j]),Bt.useEffect(()=>(B(I,q),()=>{B(I,false),j(I,false);}),[q,I,B,j]),Bt.useEffect(()=>{if(!b)try{localStorage.setItem(`hsafaChat_${n}.showChat`,String(q));}catch(A){console.warn("Failed to save chat state:",A);}},[q,n,b]);let{attachments:Vt,uploading:xe,fileInputRef:be,formatBytes:wn,handleRemoveAttachment:Sn,handleFileSelection:Rn,clearAttachments:Ce}=St,ke=Bt.useCallback((A,F)=>{wt(P=>P.map(w=>{if(w.id===A&&w.role==="assistant"){let E=F.main_agent.find(O=>O.type==="response"),N=E?.type==="response"?E.items:[];return {...w,items:N,mainAgentActions:F.main_agent,firstAgentMessage:F.first_agent.message,firstAgentContinue:F.first_agent.continue,reasoningOpen:w.reasoningOpen}}return w}));},[]),Xt=Bt.useCallback(async({prompt:A,baseMessages:F,userMessage:P,assistantMessageId:w,chatId:E})=>{if(n){_.setError(null),_.setStreaming(true);try{let N=Ie(F);N.push({role:"user",content:P.content}),Tn.current=w,An(),await Jt.startStreaming({agentId:n,baseUrl:L,body:{prompt:A,chatId:E??void 0,messages:N},onUpdate:Dt=>{ke(w,Dt);let En=Dt.main_agent.find(zn=>zn.type==="response")?.items||[];ye(En,"partial");}});let $t=Jt.streamData?.main_agent?.find(Dt=>Dt.type==="response")?.items||[];ye($t,"final");}catch(N){_.setError(N?.message||"Request failed");}finally{_.setStreaming(false);}}},[n,L,Jt,_,ke]),$n=Bt.useCallback(A=>{fe(A)&&(it(false),J(""));},[fe,it,J]),In=Bt.useCallback(A=>{he(A),vt(F=>F+1);},[he]),ot=Ot[e],ut={primaryColor:r||ot.primaryColor,backgroundColor:a??"transparent",borderColor:s||ot.borderColor,textColor:o||ot.textColor,accentColor:i||ot.accentColor,mutedTextColor:ot.mutedTextColor,inputBackground:ot.inputBackground,cardBackground:ot.cardBackground,hoverBackground:ot.hoverBackground},Fn=Bt.useCallback(async()=>{if(!n)return;let A=Mt.trim();if(!A)return;let F=nt.currentChatId;F||(F=nt.createNewChat(A));let P=le(Vt),w=$e(A,P),E=Qt(h),N=rt;wt([...N,w,E]),et(""),Ce(),me(true),await Xt({prompt:A,baseMessages:N,userMessage:w,assistantMessageId:E.id,chatId:F});},[n,Mt,rt,Vt,Ce,Xt,nt,wt,et]),Dn=Bt.useCallback(async A=>{if(!A||!L)return;let F=Array.from(A);_.setError(null);let P=[];try{for(let w of F){if(w.size>St.MAX_UPLOAD_SIZE){_.setError(`"${w.name}" exceeds the ${St.formatBytes(St.MAX_UPLOAD_SIZE)} limit.`);continue}try{let E=new FormData;E.append("file",w);let N=await fetch(`${L}/api/uploads`,{method:"POST",body:E});if(!N.ok){let $t=await N.text().catch(()=>"");throw new Error($t||`Failed to upload ${w.name}`)}let O=await N.json(),Rt={id:O.id,name:O.name||w.name,url:O.url,mimeType:O.mimeType||w.type||"application/octet-stream",size:typeof O.size=="number"?O.size:w.size};P.push(Rt);}catch(E){console.error("Failed to upload attachment:",E),_.setError(String(E?.message??`Failed to upload ${w.name}`));}}P.length&&At(w=>[...w,...P]);}catch(w){console.error("Error adding attachments during edit:",w);}},[L,St,_]);return Bt.useEffect(()=>{if(qt.current){qt.current=false;return}ge&&requestAnimationFrame(()=>{ue.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[rt,_.streaming,ge]),Bt.useEffect(()=>{let A=document.querySelector(".chat-scroll-container");if(!A)return;let F=()=>{let{scrollTop:P,scrollHeight:w,clientHeight:E}=A,O=w-P-E<40;me(O);};return A.addEventListener("scroll",F),F(),()=>A.removeEventListener("scroll",F)},[]),typeof document<"u"?reactDom.createPortal(jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:v,style:{width:q?Tt?"100%":typeof m=="number"?`${m}px`:m:"0",height:y,display:"flex",flexDirection:"column",backgroundColor:q?ut.backgroundColor:"transparent",opacity:q?1:0,padding:q?"24px 16px":"0",transition:"all 0.3s ease-out",position:"fixed",top:0,...k==="rtl"?{left:0}:{right:0},bottom:0,zIndex:Tt?9999:1e3,pointerEvents:q?"auto":"none"},children:[jsxRuntime.jsx(pn,{title:R,expandable:l,alwaysOpen:b,maximized:Tt,streaming:_.streaming,dir:k,resolvedColors:ut,onMaximize:()=>Kt(A=>!A),onNew:Mn,onToggleHistory:()=>it(A=>!A),onClose:()=>d(false),historyBtnRef:Cn,t:g}),jsxRuntime.jsx(qe,{messages:rt,streaming:_.streaming,editingMessageId:yn,editingMessageText:xn,editingAttachments:pe,error:_.error,actionStatuses:vn,components:H,theme:e,resolvedColors:ut,hideReasoningContent:C,onEditingTextChange:de,onRemoveAttachment:A=>{At(F=>F.filter(P=>P.id!==A));},onAddAttachments:Dn,uploading:xe,onStartEdit:(A,F)=>{let P=rt.find(w=>w.id===A);jt(A),de(F),P&&P.role==="user"&&At(le(gt(P)));},onCancelEdit:()=>{jt(null),At([]);},onSaveEdit:async(A,F)=>{let P=rt.findIndex($t=>$t.id===A);if(P===-1)return;let w=rt[P];if(w.role!=="user")return;let E=F.trim(),N=Fe(w,E,le(pe)),O=rt.slice(0,P),Rt=Qt(h);wt([...O,N,Rt]),jt(null),At([]),await Xt({prompt:E,baseMessages:O,userMessage:N,assistantMessageId:Rt.id,chatId:nt.currentChatId??null});},onToggleReasoning:A=>{let F=document.querySelector(".chat-scroll-container"),P=F?.scrollTop||0;qt.current=true,wt(w=>w.map(E=>E.id===A&&E.role==="assistant"?{...E,reasoningOpen:!E.reasoningOpen}:E)),requestAnimationFrame(()=>{F&&(F.scrollTop=P);});},scrollAnchorRef:ue,t:g}),jsxRuntime.jsx(gn,{value:Mt,onChange:et,onSend:Fn,onStop:_.handleStop,streaming:_.streaming,placeholder:T,attachments:Vt,uploading:xe,onRemoveAttachment:Sn,onFileInputClick:()=>be.current?.click(),resolvedColors:ut,formatBytes:wn,textareaRef:bn,fileInputRef:be,onFileSelection:A=>Rn(A,_.setError),t:g,dir:k})]}),jsxRuntime.jsx(Je,{show:!q&&!b,onClick:()=>d(true),resolvedColors:ut,floatingButtonPosition:M}),jsxRuntime.jsx(fn,{isOpen:ce,onClose:()=>it(false),searchQuery:Y,onSearchChange:J,chats:nt.loadChatsIndex(),currentChatId:nt.currentChatId,onChatSelect:$n,onChatDelete:In,resolvedColors:ut,t:g}),jsxRuntime.jsx("style",{children:`
|
|
17
|
+
@keyframes ${kn.current}-border-flow {
|
|
18
18
|
0% { background-position: 0% 50%; }
|
|
19
19
|
50% { background-position: 100% 50%; }
|
|
20
20
|
100% { background-position: 0% 50%; }
|
|
@@ -29,11 +29,11 @@
|
|
|
29
29
|
from { transform: rotate(0deg); }
|
|
30
30
|
to { transform: rotate(360deg); }
|
|
31
31
|
}
|
|
32
|
-
`})]}),document.body):null}function
|
|
33
|
-
@keyframes ${
|
|
32
|
+
`})]}),document.body):null}function Ur({children:t,theme:n="dark",primaryColor:e,backgroundColor:r,borderColor:a,textColor:s,mutedTextColor:o,enableBorderAnimation:i=true,borderRadius:m=16,enableContentBorder:y=true,className:l="",enableMargin:b=true,chatWidth:c=450,dir:k="ltr"}){let{isAnyStreaming:f,isAnyChatOpen:M}=Q(),x=Bt.useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[p,v]=Bt.useState(false);Bt.useEffect(()=>{let L=setTimeout(()=>v(true),50);return ()=>clearTimeout(L)},[]);let h=Ot[n],C={primaryColor:e||h.primaryColor,backgroundColor:r||h.backgroundColor,borderColor:a||h.borderColor,textColor:s||h.textColor,accentColor:h.accentColor,mutedTextColor:o||h.mutedTextColor,inputBackground:h.inputBackground,cardBackground:h.cardBackground,hoverBackground:h.hoverBackground},u=typeof m=="number"?`${m}px`:m,g=typeof c=="number"?`${c}px`:c,T=b&&M?k==="rtl"?{marginLeft:g}:{marginRight:g}:{},R=b&&M?`calc(100% - ${g})`:"100%";return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:l,style:{width:R,height:"100%",transition:p?"all 0.3s ease-out":"none",padding:M&&y?"16px":"0",...T},children:jsxRuntime.jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:p?"all 0.3s ease-out":"none",borderRadius:M?u:"0",border:M&&f&&i?"none":M?`1px solid ${C.borderColor}`:"none",padding:M&&f&&i?"1.5px":"0",background:M&&f&&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:M&&f&&i?"300% 300%":"auto",animation:M&&f&&i?`${x.current}-border-flow 3s ease-in-out infinite`:"none",filter:M&&f&&i?`drop-shadow(0 0 10px ${C.primaryColor}40)`:"none"},children:jsxRuntime.jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:M&&y?u:"0",backgroundColor:M&&y?C.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${C.mutedTextColor}40 transparent`},children:t})})}),jsxRuntime.jsx("style",{children:`
|
|
33
|
+
@keyframes ${x.current}-border-flow {
|
|
34
34
|
0% { background-position: 0% 50%; }
|
|
35
35
|
50% { background-position: 100% 50%; }
|
|
36
36
|
100% { background-position: 0% 50%; }
|
|
37
37
|
}
|
|
38
|
-
`})," "]})}exports.Button=
|
|
38
|
+
`})," "]})}exports.Button=Yr;exports.ContentContainer=Ur;exports.FloatingChatButton=Je;exports.HsafaChat=Lr;exports.HsafaProvider=ir;exports.MessageList=qe;exports.useAgentStreaming=rn;exports.useAutoScroll=aa;exports.useChatStorage=Ge;exports.useFileUpload=nn;exports.useHsafa=Q;exports.useHsafaAction=ga;exports.useHsafaComponent=ya;exports.useStreaming=Qe;exports.useToggle=na;//# sourceMappingURL=index.cjs.map
|
|
39
39
|
//# sourceMappingURL=index.cjs.map
|