@hsafa/ui-sdk 0.1.8 → 0.1.9
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 +19 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +67 -7
- package/dist/index.d.ts +67 -7
- package/dist/index.js +19 -13
- 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(
|
|
1
|
+
'use strict';var jsxRuntime=require('react/jsx-runtime'),lucideReact=require('lucide-react'),Pt=require('react'),reactDom=require('react-dom');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Pt__default=/*#__PURE__*/_interopDefault(Pt);var at={};var zr=({variant:t="primary",size:n="md",loading:e=false,disabled:r,children:a,className:s,...o})=>{let i=[at.button,at[t],at[n],e&&at.loading,s].filter(Boolean).join(" ");return jsxRuntime.jsxs("button",{className:i,disabled:r||e,...o,children:[e&&jsxRuntime.jsx("span",{className:at.spinner}),jsxRuntime.jsx("span",{className:e?at.hiddenText:void 0,children:a})]})};function Ce(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 ke({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"},f=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:c=>{c.target.style.display="none";let C=c.target.nextElementSibling;C&&(C.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:Ce(t.size)})]}),e==="input"&&s&&jsxRuntime.jsx("button",{onClick:c=>{c.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:c=>{c.currentTarget.style.backgroundColor=n.hoverBackground,c.currentTarget.style.color=n.textColor;},onMouseLeave:c=>{c.currentTarget.style.backgroundColor="transparent",c.currentTarget.style.color=n.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),o&&r&&jsxRuntime.jsx("button",{onClick:c=>{c.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:c=>{c.currentTarget.style.backgroundColor="#ef444420",c.currentTarget.style.color="#ef4444";},onMouseLeave:c=>{c.currentTarget.style.backgroundColor="transparent",c.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:c=>{c.currentTarget.style.backgroundColor=n.hoverBackground,c.currentTarget.style.borderColor=n.primaryColor;},onMouseLeave:c=>{c.currentTarget.style.backgroundColor=n.inputBackground,c.currentTarget.style.borderColor=n.borderColor;},children:f}):jsxRuntime.jsx("div",{style:m,children:f})}function Ft({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(ke,{attachment:a,resolvedColors:n,mode:r,onRemove:e},a.id))})}function Te({messageId:t,initialText:n,editingText:e,onEditingTextChange:r,onCancel:a,onSave:s,streaming:o,resolvedColors:i,attachments:m,onRemoveAttachment:f,onAddAttachments:c,uploading:C,t:u}){let k=Pt__default.default.useRef(null),y=h=>{h.key==="Escape"?a():h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),o||s(t,e||n));},M=h=>{let d=h.target.files;d&&d.length>0&&c&&c(d),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:h=>r(h.target.value),onKeyDown:y}),m&&m.length>0&&jsxRuntime.jsx("div",{style:{padding:"8px"},children:jsxRuntime.jsx(Ft,{attachments:m,resolvedColors:i,onRemove:f})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",padding:"8px 8px 8px 0"},children:[c&&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:C||o,title:u(C?"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:C||o?"not-allowed":"pointer",opacity:C||o?.5:1},onMouseEnter:h=>{!C&&!o&&(h.currentTarget.style.backgroundColor=i.inputBackground,h.currentTarget.style.borderColor=i.primaryColor);},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.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:h=>h.currentTarget.style.backgroundColor=i.inputBackground,onMouseLeave:h=>h.currentTarget.style.backgroundColor="transparent",onClick:a,children:u("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:h=>h.currentTarget.style.borderColor=i.primaryColor,onMouseLeave:h=>h.currentTarget.style.borderColor=i.borderColor,onClick:()=>{o||s(t,e||n);},children:u("editor.saveAndRegenerate")})]})]})]})}function Dn(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 Xt(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(Dn(a));return r}function ve(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
+
`):""}function Ae(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 Zt(t){return t.role==="user"?t.text?t.text:ve(t.content):""}function pt(t){return t.role==="user"?t.attachments?t.attachments:Ae(t.content):[]}function we(t,n=[]){let e=Xt(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 Yt(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 Se(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 Re(t,n,e){let r=e??pt(t),a=Xt(n,r);return {...t,content:a,text:n,attachments:r.length>0?r:void 0}}function $e(t){if(t.role==="user"){let n=Zt(t),e=pt(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 Fe({message:t,isEditing:n,editingText:e,editingAttachments:r,onEditingTextChange:a,onStartEdit:s,onCancelEdit:o,onSaveEdit:i,onRemoveAttachment:m,onAddAttachments:f,uploading:c,streaming:C,resolvedColors:u,t:k}){let y=Zt(t),M=pt(t);return n?jsxRuntime.jsx(Te,{messageId:t.id,initialText:y,editingText:e,onEditingTextChange:a,onCancel:o,onSave:i,streaming:C,resolvedColors:u,attachments:r||M,onRemoveAttachment:m,onAddAttachments:f,uploading:c,t:k}):jsxRuntime.jsxs("div",{title:k("editor.clickToEdit"),onClick:()=>{C||s(t.id,y);},style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:u.accentColor,color:u.textColor},onMouseEnter:h=>h.currentTarget.style.backgroundColor=u.hoverBackground,onMouseLeave:h=>h.currentTarget.style.backgroundColor=u.accentColor,children:[y,jsxRuntime.jsx(Ft,{attachments:M,resolvedColors:u})]})}function Ee({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 He({chart:t,theme:n}){let e=Pt.useRef(null),[r,a]=Pt.useState(null),[s,o]=Pt.useState(true);Pt.useEffect(()=>{let u=true;return (async()=>{try{o(!0),a(null);let y;try{y=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!u)return;if(y.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&&u){let M=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:h}=await y.default.render(M,t);if(e.current&&u){e.current.innerHTML=h;let d=e.current.querySelector("svg");d&&(d.style.maxWidth="100%",d.style.height="auto",d.style.display="block");}}}catch(y){u&&a(y instanceof Error?y.message:"Failed to render diagram");}finally{u&&o(false);}})(),()=>{u=false;}},[t,n]);let i=n==="dark"?"#374151":"#D1D5DB",m=n==="dark"?"#1F2937":"#F9FAFB",f=n==="dark"?"#7F1D1D":"#FEF2F2",c=n==="dark"?"#FCA5A5":"#DC2626",C=n==="dark"?"#9CA3AF":"#6B7280";return r?jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${i}`,backgroundColor:f,padding:"16px",margin:"8px 0"},children:[jsxRuntime.jsx("div",{style:{fontSize:"14px",color:c,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:c,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:C,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsxRuntime.jsx("div",{ref:e,style:{display:s?"none":"block",textAlign:"center",minHeight:s?"0":"50px"}})]})}function Q(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ht(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 Bn(t,n="dark"){let e=(t||"").replace(/\r\n/g,`
|
|
4
4
|
`).split(`
|
|
5
|
-
`),
|
|
6
|
-
`);
|
|
7
|
-
`)),
|
|
8
|
-
`);
|
|
9
|
-
`)),
|
|
5
|
+
`),r="",a=false,s="",o=[],i=false,m=false,f=false,c=n==="dark"?"#374151":"#D1D5DB",u=n==="dark"?"#111827":"#F3F4F6",k=n==="dark"?"#E5E7EB":"#374151",y=()=>{i&&(r+="</ul>",i=false),m&&(r+="</ol>",m=false);};for(let M=0;M<e.length;M++){let h=e[M],d=h.match(/^```\s*(\w+)?\s*$/);if(d){if(!a)y(),a=true,s=d[1]?String(d[1]):"",o=[];else {if(s==="mermaid"){f=true;let p=o.join(`
|
|
6
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${Q(p)}"></div>`;}else {let p=Q(o.join(`
|
|
7
|
+
`)),g=s?`language-${s}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${u}; color: ${k}; border: 1px solid ${c}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${g}">${p}</code></pre>`;}a=false,s="",o=[];}continue}if(a){o.push(h);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(h)){y(),r+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let A=h.match(/^(#{1,6})\s+(.+)$/);if(A){y();let p=A[1].length,g=Ht(Q(A[2].trim())),T=p<=2?"18px":p===3?"16px":"14px";r+=`<h${p} style="font-size: ${T}; font-weight: 600; margin: 8px 0 4px 0;">${g}</h${p}>`;continue}let x=h.match(/^\s*[-*]\s+(.+)$/),b=h.match(/^\s*\d+\.\s+(.+)$/);if(x){i||(y(),r+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',i=true);let p=Ht(Q(x[1]));r+=`<li style="margin: 2px 0;">${p}</li>`;continue}if(b){m||(y(),r+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',m=true);let p=Ht(Q(b[1]));r+=`<li style="margin: 2px 0;">${p}</li>`;continue}if(h.trim().length===0)y(),r+='<div style="height: 8px;"></div>';else {y();let p=Ht(Q(h));r+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${p}</p>`;}}if(a)if(s==="mermaid"){f=true;let M=o.join(`
|
|
8
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${Q(M)}"></div>`;}else {let M=Q(o.join(`
|
|
9
|
+
`)),h=s?`language-${s}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${u}; color: ${k}; border: 1px solid ${c}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${h}">${M}</code></pre>`;}return i&&(r+="</ul>"),m&&(r+="</ol>"),{html:r,hasMermaid:f}}function ut({content:t,theme:n}){let{html:e,hasMermaid:r}=Pt.useMemo(()=>Bn(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 f=m[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");s.push(Pt__default.default.createElement(He,{key:`mermaid-${i}`,chart:f,theme:n}));}}else o.trim()&&s.push(Pt__default.default.createElement("div",{key:`html-${i}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:o}}));}),Pt__default.default.createElement(Pt__default.default.Fragment,{},...s)}function Be({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(C=>C.type==="reasoning"||C.type==="tool-call");if(i.length===0)return null;let m=[...i].reverse().find(C=>C.type==="reasoning"),f=t.some(C=>C.type==="response"),c=Wn(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((C,u)=>jsxRuntime.jsx(Nn,{action:C,resolvedColors:r,theme:s,isFirst:u===0,isLast:u===i.length-1,hideReasoningContent:o},u)),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:f?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:f&&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&&!f?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 ",Le(c)]})]}),!o&&m?.type==="reasoning"&&!f&&jsxRuntime.jsx("div",{style:{fontSize:"12px",color:r.mutedTextColor,opacity:.7,overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:jsxRuntime.jsx(ut,{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 Wn(t){let e=0;for(let n of t)"startDate"in n&&"endDate"in n&&n.startDate&&n.endDate&&(e+=n.endDate-n.startDate);return e}function Be(t){if(t<1e3)return `${Math.round(t)}ms`;if(t<6e4)return `${(t/1e3).toFixed(1)}s`;{let e=Math.floor(t/6e4),n=Math.round(t%6e4/1e3);return `${e}m ${n}s`}}function _n({action:t,resolvedColors:e,theme:n,isFirst:o,isLast:a,hideReasoningContent:c=false}){let r=null;if("startDate"in t&&"endDate"in t&&t.startDate&&t.endDate&&(r=Be(t.endDate-t.startDate)),t.type==="reasoning"){let l=t.status==="streaming";return jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[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:e.borderColor,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.borderColor}})]}),jsxRuntime.jsxs("div",{style:{flex:1,minWidth:0},children:[jsxRuntime.jsxs("div",{style:{fontSize:"11px",color:e.mutedTextColor,marginBottom:"4px",fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.jsx("span",{children:"Reasoning"}),r&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",color:e.mutedTextColor},children:r})]}),!c&&jsxRuntime.jsx("div",{style:{fontSize:"13px",color:e.mutedTextColor,lineHeight:"1.6",maxWidth:"100%",opacity:l?.8:1},children:jsxRuntime.jsx(mt,{content:t.reasoning,theme:n})})]})]})}if(t.type==="tool-call"){let l=t.status==="input_streaming",m=t.status==="running";t.status==="finished";let g=t.status==="error",C=n==="dark"?"#10b981":"#059669";l&&(C=n==="dark"?"#eab308":"#d97706"),m&&(C=n==="dark"?"#3b82f6":"#2563eb"),g&&(C=n==="dark"?"#ef4444":"#dc2626");let d="Called";return l&&(d="Inputting"),m&&(d="Running"),g&&(d="Error"),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[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:C,marginTop:"6px",zIndex:1}}),jsxRuntime.jsx("div",{style:{position:"absolute",top:"20px",left:"50%",transform:"translateX(-50%)",width:"2px",height:"calc(100% + 4px)",backgroundColor:n==="dark"?e.borderColor:e.mutedTextColor}})]}),jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:e.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsx("span",{style:{fontWeight:500,opacity:n==="dark"?.7:.6},children:d}),jsxRuntime.jsx("span",{style:{color:e.mutedTextColor,fontWeight:500},children:t.toolName||"tool"}),r&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",color:e.mutedTextColor,opacity:n==="dark"?.5:.6},children:r})]})})]})}return null}function Pe({mcpToolCalls:t,resolvedColors:e}){if(!t||t.length===0)return null;let n=new Map;t.forEach(c=>{let r=n.get(c.toolName);!r||r.status==="running"&&c.status==="completed"?n.set(c.toolName,{status:c.status||"pending",count:(r?.count||0)+1}):r&&r.count++;});let o=Array.from(n.values()).some(c=>c.status==="running"),a=Array.from(n.values()).filter(c=>c.status==="completed").length;return jsxRuntime.jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:e.cardBackground,border:`1px solid ${e.borderColor}`,fontSize:"12px",color:e.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:o?"#3b82f6":"#10b981"}}),jsxRuntime.jsx("span",{children:o?"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(n.entries()).map(([c,r])=>jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:e.inputBackground,border:`1px solid ${e.borderColor}`},children:[r.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:r.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsxRuntime.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:c}),r.count>1&&jsxRuntime.jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",r.count]})]},c))})]})}function Le({items:t,mcpToolCalls:e,mcpToolResults:n,actionStatuses:o,components:a,theme:c,resolvedColors:r}){return !Array.isArray(t)||t.length===0?null:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.map((l,m)=>{let b=`it-${m}`;if(typeof l=="string")return jsxRuntime.jsx("div",{style:{padding:"0",color:r.textColor},children:jsxRuntime.jsx(mt,{content:l,theme:c})},b);if(l&&typeof l=="object"){if(l.type==="action"){let C=`${String(l.name??"action")}:${m}`,d=o.get(C);return jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsxRuntime.jsx("div",{style:{padding:"8px",fontSize:"12px",color:r.mutedTextColor},children:d==="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(l.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(l.name??"action")," has executed"]})})},b)}if(l.type==="ui"){let C=String(l.component??"").trim(),d=C?a.get(C):void 0;return d?jsxRuntime.jsx("div",{style:{padding:"0"},children:jsxRuntime.jsx(d,{...l.props||{}})},b):jsxRuntime.jsxs("div",{style:{padding:"0"},children:[jsxRuntime.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:r.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:r.accentColor,border:`1px solid ${r.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:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(l.props??{},null,2)})]},b)}let g=l.text||l.content||l.message;return typeof g=="string"?jsxRuntime.jsx("div",{style:{padding:"0",color:r.textColor},children:jsxRuntime.jsx(mt,{content:g,theme:c})},b):jsxRuntime.jsx("div",{style:{padding:"0",fontSize:"14px"},children:jsxRuntime.jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(l,null,2)})},b)}return null}),jsxRuntime.jsx(Pe,{mcpToolCalls:e,resolvedColors:r})]})}function We({message:t,streaming:e,isLastMessage:n,actionStatuses:o,components:a,theme:c,resolvedColors:r,onToggleReasoning:l,hideReasoningContent:m=false}){let b=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:r.textColor,lineHeight:"1.5"},children:t.firstAgentMessage})}),b?jsxRuntime.jsx(He,{mainAgentActions:t.mainAgentActions,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>l(t.id),resolvedColors:r,streaming:e&&n,theme:c,hideReasoningContent:m}):jsxRuntime.jsx(Fe,{reasoning:t.reasoning,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>l(t.id),resolvedColors:r}),jsxRuntime.jsx(Le,{items:t.items,mcpToolCalls:t.mcpToolCalls,mcpToolResults:t.mcpToolResults,actionStatuses:o,components:a,theme:c,resolvedColors:r}),e&&n&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:r.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsxRuntime.jsx("span",{children:"Working\u2026"})]})]})}function _e({messages:t,streaming:e,editingMessageId:n,editingMessageText:o,editingAttachments:a,error:c,actionStatuses:r,components:l,theme:m,resolvedColors:b,onEditingTextChange:g,onRemoveAttachment:C,onAddAttachments:d,uploading:f,onStartEdit:y,onCancelEdit:M,onSaveEdit:u,onToggleReasoning:i,scrollAnchorRef:k,hideReasoningContent:h=false,t:x}){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:[c&&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:c}),t.length===0&&!e&&jsxRuntime.jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${b.borderColor}`,backgroundColor:b.accentColor,color:b.mutedTextColor},children:x("messages.empty")}),jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:t.map((p,T)=>jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:p.role==="user"?jsxRuntime.jsx($e,{message:p,isEditing:n===p.id,editingText:o,editingAttachments:a,onEditingTextChange:g,onStartEdit:y,onCancelEdit:M,onSaveEdit:u,onRemoveAttachment:C,onAddAttachments:d,uploading:f,streaming:e,resolvedColors:b,t:x}):jsxRuntime.jsx(We,{message:p,streaming:e,isLastMessage:T===t.length-1,actionStatuses:r,components:l,theme:m,resolvedColors:b,onToggleReasoning:i,hideReasoningContent:h})},p.id))}),jsxRuntime.jsx("div",{ref:k})]})}function Oe({show:t,onClick:e,resolvedColors:n,floatingButtonPosition:o}){if(!t)return null;let a={position:"fixed",bottom:typeof o.bottom=="number"?`${o.bottom}px`:o.bottom,right:o.right?typeof o.right=="number"?`${o.right}px`:o.right:void 0,top:o.top?typeof o.top=="number"?`${o.top}px`:o.top:void 0,left:o.left?typeof o.left=="number"?`${o.left}px`:o.left:void 0,zIndex:1e3};return jsxRuntime.jsx("button",{"aria-label":"Open chat",onClick:e,style:{...a,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:c=>{c.currentTarget.style.borderColor=n.primaryColor,c.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:c=>{c.currentTarget.style.borderColor=n.borderColor,c.currentTarget.style.backgroundColor=n.accentColor;},children: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 Eo(t=false){let[e,n]=zt.useState(t),o=zt.useCallback(()=>n(r=>!r),[]),a=zt.useCallback(()=>n(true),[]),c=zt.useCallback(()=>n(false),[]);return {on:e,toggle:o,setOn:n,setTrue:a,setFalse:c}}function Bo(){let t=zt.useRef(null);return zt.useEffect(()=>{let e=t.current;if(!e)return;let n=new MutationObserver(()=>{e.scrollTop=e.scrollHeight;});return n.observe(e,{childList:true,subtree:true}),e.scrollTop=e.scrollHeight,()=>n.disconnect()},[]),t}var qe=zt.createContext(void 0);function Zn({baseUrl:t,children:e}){let[n,o]=zt.useState(new Map),[a,c]=zt.useState(new Map),[r,l]=zt.useState(null);zt.useEffect(()=>{let i=false,k=()=>{if(i)return;let h=typeof document<"u"?document.getElementById("hsafa-content-box"):null;h?l(h):setTimeout(k,100);};return k(),()=>{i=true;}},[]);let m=zt.useCallback((i,k)=>(o(h=>{let x=new Map(h);return x.set(String(i),k),x}),()=>{o(h=>{let x=new Map(h),p=x.get(String(i));return (!k||p===k)&&x.delete(String(i)),x});}),[]),b=zt.useCallback((i,k)=>{o(h=>{let x=new Map(h),p=x.get(String(i));return (!k||p===k)&&x.delete(String(i)),x});},[]),g=zt.useCallback((i,k)=>(c(h=>{let x=new Map(h);return x.set(String(i),k),x}),()=>{c(h=>{let x=new Map(h),p=x.get(String(i));return (!k||p===k)&&x.delete(String(i)),x});}),[]),C=zt.useCallback((i,k)=>{c(h=>{let x=new Map(h),p=x.get(String(i));return (!k||p===k)&&x.delete(String(i)),x});},[]),d=zt.useMemo(()=>({baseUrl:t,actions:n,components:a,registerAction:m,unregisterAction:b,registerComponent:g,unregisterComponent:C}),[t,n,a,m,b,g,C]),f=i=>{let k=i.type;return (k?.displayName||k?.name)==="HsafaChat"};function y(i){if(i==null||typeof i=="boolean")return {chats:[],content:null};if(typeof i=="string"||typeof i=="number")return {chats:[],content:i};if(Array.isArray(i)){let k=[],h=[];for(let x of i){let p=y(x);k.push(...p.chats),p.content!==null&&h.push(p.content);}return {chats:k,content:h.length?jsxRuntime.jsx(jsxRuntime.Fragment,{children:h}):null}}if(zt__default.default.isValidElement(i)){if(f(i))return {chats:[i],content:null};let k=y(i.props?.children),h=zt__default.default.cloneElement(i,i.props,k.content);return {chats:k.chats,content:h}}return {chats:[],content:i}}let{chats:M,content:u}=y(e);return jsxRuntime.jsxs(qe.Provider,{value:d,children:[M,r?null:u,r&&u?reactDom.createPortal(jsxRuntime.jsx(jsxRuntime.Fragment,{children:u}),r):null]})}function dt(){let t=zt.useContext(qe);return t||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{}}}function jo(t,e){let{registerAction:n}=dt(),o=zt.useRef(e);zt.useEffect(()=>{o.current=e;});let a=zt.useCallback((c,r)=>o.current(c,r),[]);zt.useEffect(()=>{if(!t||typeof e!="function"){console.warn(`[useHsafaAction] Invalid action registration: name="${t}", handler type="${typeof e}"`);return}return n(t,a)},[t,n,a]);}function Jo(t,e){let{registerComponent:n}=dt(),o=zt.useRef(e);zt.useEffect(()=>{o.current=e;});let a=zt.useMemo(()=>{let c=r=>{let l=o.current;return zt__default.default.createElement(l,r)};return c.displayName=`HsafaStable(${t})`,c},[]);zt.useEffect(()=>{if(!t||typeof e!="function"){console.warn(`[useHsafaComponent] Invalid component registration: name="${t}", component type="${typeof e}"`);return}return n(t,a)},[t,n,a]);}function Ye(t){let e=`hsafaChat_${t}`,n=`${e}.chats`,o=p=>`${e}.chat.${p}`,a=`${e}.currentChatId`,c=`${e}.showChat`,[r,l]=zt.useState(null),m=zt.useRef(false),b=zt.useRef(null),g=()=>{try{let p=localStorage.getItem(n);return p?JSON.parse(p):[]}catch{return []}},C=p=>{try{localStorage.setItem(n,JSON.stringify(p));}catch{}},d=p=>{try{let T=localStorage.getItem(o(p));return T?JSON.parse(T):null}catch{return null}},f=p=>{try{localStorage.setItem(o(p.id),JSON.stringify(p));}catch{}},y=p=>{let T=g(),v=T.findIndex(D=>D.id===p.id);v>=0?T[v]=p:T.unshift(p),C(T);},M=p=>{let v=g().filter(D=>D.id!==p);C(v);},u=p=>{try{localStorage.removeItem(o(p));}catch{}};return {currentChatId:r,setCurrentChatId:l,hasChatRecordRef:m,pendingFirstTitleRef:b,loadChatsIndex:g,loadChat:d,saveChat:f,deleteChat:(p,T)=>{u(p),M(p);let v=r===p;if(v){l(null),m.current=false,b.current=null;try{localStorage.removeItem(a);}catch{}}T?.(v);},loadChatPreferences:()=>{try{let p=localStorage.getItem(a);if(p){let T=d(p);if(T)return l(T.id),m.current=!0,T.messages||[]}}catch{}return []},persistChatData:p=>{if(!r||!m.current)return;f({id:r,messages:p,agentId:t});let v=p.find(E=>E.role==="user"),D=v?Se(v):"New chat",q=(b.current||D).slice(0,80),R={id:r,title:q,createdAt:Date.now(),updatedAt:Date.now()};y(R);try{localStorage.setItem(a,r);}catch{}},createNewChat:p=>{let T=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;l(T),m.current=true;let v=(p||"New chat").slice(0,80),D=Date.now();y({id:T,title:v,createdAt:D,updatedAt:D});try{localStorage.setItem(a,T);}catch{}return T},upsertChatMeta:y,showChatKey:c}}function Ze(){let[t,e]=zt.useState(false),[n,o]=zt.useState(null),a=zt.useRef(null),c=zt.useRef({}),r=zt.useRef(void 0),l=zt.useRef(new Set),m=zt.useRef(new Map),b=zt.useRef(new Map),[g,C]=zt.useState(new Map),d=zt.useCallback((i,k)=>{let h=m.current.get(i)||[],x=JSON.stringify(k);if(h.push(x),h.length>5&&h.shift(),m.current.set(i,h),h.length>=3){let p=h.slice(-3);return p.every(T=>T===p[0])}return false},[]),f=zt.useCallback((i,k,h,x)=>{!Array.isArray(i)||i.length===0||i.forEach((p,T)=>{if(!(!p||typeof p!="object")&&p.type==="action"){let v=String(p.name??"").trim();if(!v)return;let D=h.get(v);if(!D){console.warn(`Action handler not found for: ${v}`);return}let q=!!c.current[v],R=`${r.current||"assist"}:${v}:${T}`,E=`${v}:${T}`;try{if(k==="partial"&&q){C(L=>new Map(L).set(E,"executing"));let X=setTimeout(()=>{Promise.resolve(D(p.params,{name:v,trigger:k,index:T,assistantMessageId:r.current,chatId:x||void 0})).catch(L=>{console.error(`Error executing streaming action ${v}:`,L),C($=>new Map($).set(E,"executed"));});},50);b.current.set(`${E}_timeout`,X);}else if(k==="partial"&&!q){let X=d(E,p.params),L=b.current.get(E);X&&L!=="executed"?(b.current.set(E,"executed"),C($=>new Map($).set(E,"executed")),Promise.resolve(D(p.params,{name:v,trigger:"params_complete",index:T,assistantMessageId:r.current,chatId:x||void 0})).catch($=>{console.error(`Error executing stabilized action ${v}:`,$);})):L||(b.current.set(E,"executing"),C($=>new Map($).set(E,"executing")));}else if(k==="final"&&b.current.get(E)!=="executed"&&!l.current.has(R)){l.current.add(R);let L=b.current.get(`${E}_timeout`);L&&(clearTimeout(L),b.current.delete(`${E}_timeout`)),b.current.set(E,"executed"),C($=>new Map($).set(E,"executed")),Promise.resolve(D(p.params,{name:v,trigger:q?"final":"params_complete",index:T,assistantMessageId:r.current,chatId:x||void 0})).catch($=>{console.error(`Error executing final action ${v}:`,$);});}}catch(X){console.error(`Error processing action ${v}:`,X);}}});},[d]),y=zt.useCallback(()=>{a.current&&(a.current.abort(),a.current=null),e(false),o("Request stopped by user");},[]),M=zt.useCallback(()=>{l.current.clear(),m.current.clear(),b.current.clear(),C(new Map);},[]),u=zt.useCallback(()=>{b.current.forEach((i,k)=>{k.endsWith("_timeout")&&clearTimeout(i);});},[]);return {streaming:t,setStreaming:e,error:n,setError:o,actionStatuses:g,setActionStatuses:C,abortControllerRef:a,actionExecMapRef:c,assistantMsgIdRef:r,calledFinalActionsRef:l,actionParamsHistoryRef:m,actionExecutionStatusRef:b,processActions:f,handleStop:y,resetActionTracking:M,cleanupTimeouts:u,hasActionParamsStabilized:d}}function Ge(t,e){if(!t)return e;let n=t.endsWith("/")?t.slice(0,-1):t,o=e.startsWith("/")?e:`/${e}`;return `${n}${o}`}var te=25*1024*1024;function tn(t){let[e,n]=zt.useState([]),[o,a]=zt.useState(false),c=zt.useRef(null),r=zt.useCallback(d=>{if(!d||Number.isNaN(d))return "0 B";let f=["B","KB","MB","GB","TB"],y=Math.min(f.length-1,Math.floor(Math.log(d)/Math.log(1024)));return `${(d/Math.pow(1024,y)).toFixed(y===0?0:1)} ${f[y]}`},[]),l=zt.useCallback(async d=>{let f=new FormData;f.append("file",d);let y=await fetch(Ge(t,"/api/uploads"),{method:"POST",body:f});if(!y.ok){let u=await y.text().catch(()=>"");throw new Error(u||`Failed to upload ${d.name}`)}let M=await y.json();return {id:M.id,name:M.name||d.name,url:M.url,mimeType:M.mimeType||d.type||"application/octet-stream",size:typeof M.size=="number"?M.size:d.size}},[t]),m=zt.useCallback(d=>{n(f=>f.filter(y=>y.id!==d));},[]),b=zt.useCallback(async(d,f)=>{if(!d)return;let y=Array.isArray(d)?d:Array.from(d);f(null),a(true);let M=[];try{for(let u of y){if(u.size>te){f(`"${u.name}" exceeds the ${r(te)} limit.`);continue}try{let i=await l(u);M.push(i);}catch(i){console.error("Failed to upload attachment:",i),f(String(i?.message??`Failed to upload ${u.name}`));}}M.length&&n(u=>[...u,...M]);}finally{a(false);}},[l,r]),g=zt.useCallback((d,f)=>{let y=[],M=(d||"").trim();M&&y.push({type:"text",text:M});for(let u of f||[]){let i=u.mimeType||"application/octet-stream";i.startsWith("image/")?y.push({type:"image",image:new URL(u.url),mediaType:i}):y.push({type:"file",data:u.url,mediaType:i,name:u.name});}return y},[]),C=zt.useCallback(()=>{n([]);},[]);return {attachments:e,uploading:o,fileInputRef:c,formatBytes:r,handleRemoveAttachment:m,handleFileSelection:b,buildUserContent:g,clearAttachments:C,MAX_UPLOAD_SIZE:te}}function sr(t){return JSON.parse(JSON.stringify(t))}function en(){let[t,e]=zt.useState(false),[n,o]=zt.useState(null),[a,c]=zt.useState(null),r=zt.useRef(null),l=zt.useCallback(async({agentId:g,body:C,baseUrl:d,onUpdate:f,signal:y})=>{try{let R=function(){let $=sr(x);c($),f?.($);};var M=R;e(!0),o(null);let u;if(y)r.current=null,u=y;else {let $=new AbortController;r.current=$,u=$.signal;}let k=`${d?d.replace(/\/$/,""):""}/api/run/${encodeURIComponent(g)}`,h=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson"},body:JSON.stringify(C??{}),signal:u});if(!h.ok||!h.body){let $=await h.text().catch(()=>"");throw new Error(`Request failed: ${h.status} ${h.statusText} - ${$}`)}let x={first_agent:{message:"",continue:!1},main_agent:[]},p=null,T=null,v=null,D=null,q=!1,E=h.body.getReader(),X=new TextDecoder("utf-8"),L="";for(R();;){let{value:$,done:Nt}=await E.read();if(Nt)break;L+=X.decode($,{stream:!0});let nt=L.indexOf(`
|
|
15
|
-
`);for(;
|
|
16
|
-
`);}}try{E.releaseLock();}catch{}return e(!1),x}catch(u){return u.name==="AbortError"?o("Request was cancelled"):o(u?.message||"Request failed"),e(false),null}},[]),m=zt.useCallback(()=>{r.current&&(r.current.abort(),r.current=null),e(false);},[]),b=zt.useCallback(()=>{c(null),o(null),e(false);},[]);return {streaming:t,error:n,streamData:a,startStreaming:l,stopStreaming:m,reset:b}}var nn={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 rn(t,e){return nn[t]?.[e]||nn.en[e]||e}function on(t="en"){return {t:zt.useCallback(n=>rn(t,n),[t]),language:t}}function sn({title:t,expandable:e,alwaysOpen:n,maximized:o,streaming:a,dir:c,resolvedColors:r,onMaximize:l,onNew:m,onToggleHistory:b,onClose:g,historyBtnRef:C,t:d}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:c==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:t,style:{color:r.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:r.mutedTextColor},children:[e&&jsxRuntime.jsx("button",{"aria-label":d(o?"header.minimize":"header.maximize"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor=r.hoverBackground,f.currentTarget.style.color=r.textColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=r.mutedTextColor;},onClick:l,children:jsxRuntime.jsx(lucideReact.Maximize2,{size:"20",strokeWidth:"2"})}),jsxRuntime.jsx("button",{"aria-label":d("header.new"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor=r.hoverBackground,f.currentTarget.style.color=r.textColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=r.mutedTextColor;},onClick:()=>{a||m();},children:jsxRuntime.jsx(lucideReact.Plus,{size:"20",strokeWidth:"2"})}),jsxRuntime.jsx("button",{"aria-label":d("header.history"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor=r.hoverBackground,f.currentTarget.style.color=r.textColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=r.mutedTextColor;},onClick:b,ref:C,children:jsxRuntime.jsx(lucideReact.History,{size:"20",strokeWidth:"2"})}),!n&&jsxRuntime.jsx("button",{"aria-label":d("header.close"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor=r.hoverBackground,f.currentTarget.style.color=r.textColor;},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent",f.currentTarget.style.color=r.mutedTextColor;},onClick:g,children:jsxRuntime.jsx(lucideReact.ChevronRight,{size:"20",strokeWidth:"2",style:{transform:c==="rtl"?"rotate(180deg)":"none"}})})]})]})}function ln({value:t,onChange:e,onSend:n,onStop:o,streaming:a,placeholder:c,attachments:r,uploading:l,onRemoveAttachment:m,onFileInputClick:b,resolvedColors:g,formatBytes:C,textareaRef:d,fileInputRef:f,onFileSelection:y,t:M,dir:u="ltr"}){return zt__default.default.useEffect(()=>{let i=d.current;if(i){i.style.height="auto";let k=Math.min(i.scrollHeight,200);i.style.height=`${k}px`;}},[t,d]),jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:g.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 ${g.borderColor}`,backgroundColor:g.accentColor},children:[r.length>0&&jsxRuntime.jsx("div",{style:{padding:"12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:r.map(i=>{let k=i.mimeType?.startsWith("image/");return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:g.inputBackground,borderRadius:"10px",border:`1px solid ${g.borderColor}`,fontSize:"12px",color:g.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:k?"transparent":g.accentColor},children:[k?jsxRuntime.jsx("img",{src:i.url,alt:i.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:h=>{h.target.style.display="none";let x=h.target.nextElementSibling;x&&(x.style.display="block");}}):null,jsxRuntime.jsx(lucideReact.File,{size:"14",strokeWidth:"2",style:{display:k?"none":"block",color:g.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsxRuntime.jsx("span",{title:i.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:i.name}),jsxRuntime.jsx("span",{style:{color:g.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:C(i.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[k&&jsxRuntime.jsx("button",{onClick:h=>{h.stopPropagation(),window.open(i.url,"_blank");},style:{background:"none",border:"none",color:g.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=g.hoverBackground,h.currentTarget.style.color=g.textColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=g.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),jsxRuntime.jsx("button",{onClick:h=>{h.stopPropagation(),m(i.id);},style:{background:"none",border:"none",color:g.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=g.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.X,{size:"12",strokeWidth:"2"})})]})]},i.id)})}),l&&jsxRuntime.jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:g.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:g.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:c,value:t,onChange:i=>e(i.target.value),onKeyDown:i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),a||n());},ref:d})}),jsxRuntime.jsxs("div",{style:{position:"absolute",bottom:"8px",...u==="rtl"?{right:"8px"}:{left:"8px"},display:"flex",alignItems:"center",gap:"4px",color:g.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:i=>{i.currentTarget.style.backgroundColor=`${g.backgroundColor}99`,i.currentTarget.style.color=g.textColor;},onMouseLeave:i=>{i.currentTarget.style.backgroundColor="transparent",i.currentTarget.style.color=g.mutedTextColor;},"aria-label":M("input.attachFiles"),onClick:b,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:i=>{i.currentTarget.style.backgroundColor=`${g.backgroundColor}99`,i.currentTarget.style.color=g.textColor;},onMouseLeave:i=>{i.currentTarget.style.backgroundColor="transparent",i.currentTarget.style.color=g.mutedTextColor;},"aria-label":M("input.insertLink"),children:jsxRuntime.jsx(lucideReact.Link,{size:"18",strokeWidth:"2"})})]}),jsxRuntime.jsx("input",{type:"file",ref:f,multiple:true,accept:"*/*",style:{display:"none"},onChange:i=>y(i.target.files)}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",...u==="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":g.borderColor}`,backgroundColor:a?"#ef444420":g.cardBackground,color:a?"#ef4444":g.mutedTextColor,opacity:!a&&!t.trim()?.4:1,cursor:!a&&!t.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{i.currentTarget.disabled||(a?(i.currentTarget.style.borderColor="#dc2626",i.currentTarget.style.backgroundColor="#dc262630",i.currentTarget.style.color="#dc2626"):(i.currentTarget.style.borderColor=g.primaryColor,i.currentTarget.style.backgroundColor=g.hoverBackground,i.currentTarget.style.color=g.textColor));},onMouseLeave:i=>{i.currentTarget.disabled||(a?(i.currentTarget.style.borderColor="#ef4444",i.currentTarget.style.backgroundColor="#ef444420",i.currentTarget.style.color="#ef4444"):(i.currentTarget.style.borderColor=g.borderColor,i.currentTarget.style.backgroundColor=g.cardBackground,i.currentTarget.style.color=g.mutedTextColor));},onClick:()=>{a?o():n();},children:a?jsxRuntime.jsx(lucideReact.Square,{size:"18",strokeWidth:"2"}):jsxRuntime.jsx(lucideReact.ArrowUp,{size:"18",strokeWidth:"2"})})})]})})})}function cn(t){let e=Date.now()-t,n=Math.max(1,Math.floor(e/1e3));if(n<60)return `${n}s`;let o=Math.floor(n/60);if(o<60)return `${o}m`;let a=Math.floor(o/60);if(a<24)return `${a}h`;let c=Math.floor(a/24);if(c<7)return `${c}d`;let r=Math.floor(c/7);if(r<4)return `${r}w`;let l=Math.floor(c/30);return l<12?`${l}mo`:`${Math.floor(l/12)}y`}function dn({isOpen:t,onClose:e,searchQuery:n,onSearchChange:o,chats:a,currentChatId:c,onChatSelect:r,onChatDelete:l,resolvedColors:m,t:b}){if(!t)return null;let g=n.trim()?a.filter(d=>(d.title||"").toLowerCase().includes(n.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:e}),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:n,onChange:d=>o(d.target.value),placeholder:b("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:d=>d.currentTarget.style.borderColor=m.primaryColor,onBlur:d=>d.currentTarget.style.borderColor=m.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:g.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:m.mutedTextColor,textAlign:"center"},children:b("history.noChatsFound")}):jsxRuntime.jsx("div",{children:g.map((d,f)=>jsxRuntime.jsx("div",{style:{borderTop:f>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:d.id===c?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:y=>y.currentTarget.style.backgroundColor=m.hoverBackground,onMouseLeave:y=>y.currentTarget.style.backgroundColor="transparent",onClick:()=>r(d.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:d.title||b("history.untitledChat")})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:m.mutedTextColor},children:cn(d.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:b("history.deleteChat"),onMouseEnter:y=>{y.currentTarget.style.color="#ef4444",y.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",y.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:y=>{y.currentTarget.style.color=m.mutedTextColor,y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.borderColor="transparent";},onClick:y=>{y.stopPropagation(),l(d.id);},children:jsxRuntime.jsx(lucideReact.Trash2,{size:"16",strokeWidth:"2"})})]})},d.id))})})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(C,document.body):C}var pn={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 re=t=>t.map(e=>({...e}));function wr(t,e){let n=Ae(t);return n.push({role:"user",content:e.content}),n}un.displayName="HsafaChat";function Sr(t){let[e,n]=zt.useState(()=>{try{return t.loadChatPreferences()}catch(r){return console.warn("Failed to load chat preferences:",r),[]}});zt.useEffect(()=>{if(e.length!==0)try{t.persistChatData(e);}catch(r){console.warn("Failed to persist chat data:",r);}},[e]);let o=zt.useCallback(r=>{try{t.setCurrentChatId(r);let l=t.loadChat(r);return n(l?.messages||[]),!0}catch(l){return console.warn("Failed to load selected chat:",l),false}},[t]),a=zt.useCallback(r=>{try{t.deleteChat(r,l=>{l&&n([]);});}catch(l){console.warn("Failed to delete chat:",l);}},[t]),c=zt.useCallback(()=>{n([]),t.setCurrentChatId(null);},[t]);return {messages:e,setMessages:n,selectChat:o,deleteChat:a,resetChat:c}}function un(t){let{agentId:e,theme:n="dark",primaryColor:o,backgroundColor:a,borderColor:c,textColor:r,accentColor:l,width:m=420,height:b="100vh",expandable:g=true,alwaysOpen:C=false,defaultOpen:d=true,dir:f="ltr",language:y,floatingButtonPosition:M=f==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},enableBorderAnimation:u=true,enableContentPadding:i=true,borderRadius:k=16,enableContentBorder:h=true,placeholder:x,title:p,className:T="",chatContainerClassName:v="",defaultReasoningOpen:D=false,hideReasoningContent:q=false}=t,R=y||(f==="rtl"?"ar":"en"),{t:E}=on(R),X=x??E("input.placeholder"),L=p??E("general.agent"),{baseUrl:$,components:Nt}=dt(),[nt,ut]=zt.useState(""),[s,Wt]=zt.useState(()=>{if(C)return true;try{let A=localStorage.getItem(`hsafaChat_${e}.showChat`);return A!==null?A==="true":d}catch{return d}}),[wt,V]=zt.useState(false),[Z,xt]=zt.useState(""),[St,S]=zt.useState(false),[Rt,gn]=zt.useState(0),[mn,_t]=zt.useState(null),[fn,ae]=zt.useState(""),[ie,bt]=zt.useState([]),se=zt.useRef(null),[le,ce]=zt.useState(true),Ot=zt.useRef(false),hn=zt.useRef(null),yn=zt.useRef(null),de=zt.useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),at=Ye(e),{messages:rt,setMessages:Ct,selectChat:pe,deleteChat:ue,resetChat:xn}=Sr(at),B=Ze(),kt=tn($||""),ge=en(),{attachments:Ut,uploading:me,fileInputRef:fe,formatBytes:bn,handleRemoveAttachment:Cn,handleFileSelection:kn,clearAttachments:he}=kt,ye=zt.useCallback((A,I)=>{Ct(P=>P.map(w=>{if(w.id===A&&w.role==="assistant"){let z=I.main_agent.find(O=>O.type==="response"),_=z?.type==="response"?z.items:[];return {...w,items:_,mainAgentActions:I.main_agent,firstAgentMessage:I.first_agent.message,firstAgentContinue:I.first_agent.continue,reasoningOpen:w.reasoningOpen}}return w}));},[]),jt=zt.useCallback(async({prompt:A,baseMessages:I,userMessage:P,assistantMessageId:w,chatId:z})=>{if(e){B.setError(null),B.setStreaming(true);try{let _=wr(I,P);await ge.startStreaming({agentId:e,baseUrl:$,body:{prompt:A,chatId:z??void 0,messages:_},onUpdate:O=>ye(w,O)});}catch(_){B.setError(_?.message||"Request failed");}finally{B.setStreaming(false);}}},[e,$,ge,B,ye]),Tn=zt.useCallback(A=>{pe(A)&&(V(false),xt(""));},[pe,V,xt]),Mn=zt.useCallback(A=>{ue(A),gn(I=>I+1);},[ue]),G=pn[n],W={primaryColor:o||G.primaryColor,backgroundColor:a||G.backgroundColor,borderColor:c||G.borderColor,textColor:r||G.textColor,accentColor:l||G.accentColor,mutedTextColor:G.mutedTextColor,inputBackground:G.inputBackground,cardBackground:G.cardBackground,hoverBackground:G.hoverBackground},xe=typeof k=="number"?`${k}px`:k,vn=zt.useCallback(async()=>{if(!e)return;let A=nt.trim();if(!A)return;let I=at.currentChatId;I||(I=at.createNewChat(A));let P=re(Ut),w=ve(A,P),z=Xt(D),_=rt;Ct([..._,w,z]),ut(""),he(),ce(true),await jt({prompt:A,baseMessages:_,userMessage:w,assistantMessageId:z.id,chatId:I});},[e,nt,rt,Ut,he,jt,at,Ct,ut]),An=zt.useCallback(async A=>{if(!A||!$)return;let I=Array.from(A);B.setError(null);let P=[];try{for(let w of I){if(w.size>kt.MAX_UPLOAD_SIZE){B.setError(`"${w.name}" exceeds the ${kt.formatBytes(kt.MAX_UPLOAD_SIZE)} limit.`);continue}try{let z=new FormData;z.append("file",w);let _=await fetch(`${$}/api/uploads`,{method:"POST",body:z});if(!_.ok){let Kt=await _.text().catch(()=>"");throw new Error(Kt||`Failed to upload ${w.name}`)}let O=await _.json(),$t={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($t);}catch(z){console.error("Failed to upload attachment:",z),B.setError(String(z?.message??`Failed to upload ${w.name}`));}}P.length&&bt(w=>[...w,...P]);}catch(w){console.error("Error adding attachments during edit:",w);}},[$,kt,B]);return zt.useEffect(()=>{if(Ot.current){Ot.current=false;return}le&&requestAnimationFrame(()=>{se.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[rt,B.streaming,le]),zt.useEffect(()=>{let A=document.querySelector(".chat-scroll-container");if(!A)return;let I=()=>{let{scrollTop:P,scrollHeight:w,clientHeight:z}=A,O=w-P-z<40;ce(O);};return A.addEventListener("scroll",I),I(),()=>A.removeEventListener("scroll",I)},[]),zt.useEffect(()=>{if(!C)try{localStorage.setItem(`hsafaChat_${e}.showChat`,String(s));}catch{}},[s,e,C]),typeof document>"u"?null:reactDom.createPortal(jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:T,style:{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100%",height:b,display:"flex",flexDirection:f==="rtl"?"row-reverse":"row",backgroundColor:W.backgroundColor,color:W.textColor,fontFamily:"Rubik, ui-sans-serif, system-ui, sans-serif",zIndex:999},dir:f,children:[jsxRuntime.jsx("div",{style:{flex:1,display:"flex",height:"100%",transition:"all 0.3s ease-out",padding:s&&i?"16px":"0"},children:jsxRuntime.jsx("div",{style:{position:"relative",display:"flex",width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:s&&h?xe:"0",border:s&&h&&!(B.streaming&&u)?`1px solid ${W.borderColor}`:"none",padding:s&&h&&B.streaming&&u?"1.5px":"0",background:s&&h&&B.streaming&&u?`linear-gradient(120deg, ${W.primaryColor}dd 0%, ${W.primaryColor}88 25%, ${W.primaryColor}00 50%, ${W.primaryColor}88 75%, ${W.primaryColor}dd 100%)`:"transparent",backgroundSize:s&&h&&B.streaming&&u?"300% 300%":"auto",animation:s&&h&&B.streaming&&u?`${de.current}-border-flow 3s ease-in-out infinite`:"none",filter:s&&h&&B.streaming&&u?`drop-shadow(0 0 10px ${W.primaryColor}40)`:"none"},children:jsxRuntime.jsx("div",{id:"hsafa-content-box",className:"content-container",style:{width:"100%",height:"100%",borderRadius:s&&h?xe:"0",backgroundColor:W.backgroundColor,overflowY:"auto",overflowX:"hidden",position:"relative",scrollbarWidth:"thin",scrollbarColor:`${W.mutedTextColor}40 transparent`}})})}),jsxRuntime.jsxs("div",{className:v,style:{width:s?St?"100%":typeof m=="number"?`${m}px`:m:"0",height:"100%",display:"flex",flexDirection:"column",backgroundColor:s?W.backgroundColor:"transparent",opacity:s?1:0,padding:s?"24px 16px":"0",transition:"all 0.3s ease-out",overflow:"hidden",pointerEvents:s?"auto":"none"},children:[jsxRuntime.jsx(sn,{title:L,expandable:g,alwaysOpen:C,maximized:St,streaming:B.streaming,dir:f,resolvedColors:W,onMaximize:()=>S(A=>!A),onNew:xn,onToggleHistory:()=>V(A=>!A),onClose:()=>Wt(false),historyBtnRef:yn,t:E}),jsxRuntime.jsx(_e,{messages:rt,streaming:B.streaming,editingMessageId:mn,editingMessageText:fn,editingAttachments:ie,error:B.error,actionStatuses:B.actionStatuses,components:Nt,theme:n,resolvedColors:W,hideReasoningContent:q,onEditingTextChange:ae,onRemoveAttachment:A=>{bt(I=>I.filter(P=>P.id!==A));},onAddAttachments:An,uploading:me,onStartEdit:(A,I)=>{let P=rt.find(w=>w.id===A);_t(A),ae(I),P&&P.role==="user"&&bt(re(gt(P)));},onCancelEdit:()=>{_t(null),bt([]);},onSaveEdit:async(A,I)=>{let P=rt.findIndex(Kt=>Kt.id===A);if(P===-1)return;let w=rt[P];if(w.role!=="user")return;let z=I.trim(),_=we(w,z,re(ie)),O=rt.slice(0,P),$t=Xt(D);Ct([...O,_,$t]),_t(null),bt([]),await jt({prompt:z,baseMessages:O,userMessage:_,assistantMessageId:$t.id,chatId:at.currentChatId??null});},onToggleReasoning:A=>{let I=document.querySelector(".chat-scroll-container"),P=I?.scrollTop||0;Ot.current=true,Ct(w=>w.map(z=>z.id===A&&z.role==="assistant"?{...z,reasoningOpen:!z.reasoningOpen}:z)),requestAnimationFrame(()=>{I&&(I.scrollTop=P);});},scrollAnchorRef:se,t:E}),jsxRuntime.jsx(ln,{value:nt,onChange:ut,onSend:vn,onStop:B.handleStop,streaming:B.streaming,placeholder:X,attachments:Ut,uploading:me,onRemoveAttachment:Cn,onFileInputClick:()=>fe.current?.click(),resolvedColors:W,formatBytes:bn,textareaRef:hn,fileInputRef:fe,onFileSelection:A=>kn(A,B.setError),t:E,dir:f})]})]}),jsxRuntime.jsx(Oe,{show:!s&&!C,onClick:()=>Wt(true),resolvedColors:W,floatingButtonPosition:M}),jsxRuntime.jsx(dn,{isOpen:wt,onClose:()=>V(false),searchQuery:Z,onSearchChange:xt,chats:at.loadChatsIndex(),currentChatId:at.currentChatId,onChatSelect:Tn,onChatDelete:Mn,resolvedColors:W,t:E}),jsxRuntime.jsx("style",{children:`
|
|
17
|
-
@keyframes ${
|
|
14
|
+
`})]})}function Wn(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 _e({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 We({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}`,u=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:u==="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(),u=C?a.get(C):void 0;return u?jsxRuntime.jsx("div",{style:{padding:"0"},children:jsxRuntime.jsx(u,{...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(_e,{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(We,{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:u,uploading:k,onStartEdit:y,onCancelEdit:M,onSaveEdit:h,onToggleReasoning:d,scrollAnchorRef:A,hideReasoningContent:x=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((p,g)=>jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:p.role==="user"?jsxRuntime.jsx(Fe,{message:p,isEditing:e===p.id,editingText:r,editingAttachments:a,onEditingTextChange:c,onStartEdit:y,onCancelEdit:M,onSaveEdit:h,onRemoveAttachment:C,onAddAttachments:u,uploading:k,streaming:n,resolvedColors:f,t:b}):jsxRuntime.jsx(Oe,{message:p,streaming:n,isLastMessage:g===t.length-1,actionStatuses:o,components:i,theme:m,resolvedColors:f,onToggleReasoning:d,hideReasoningContent:x})},p.id))}),jsxRuntime.jsx("div",{ref:A})]})}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 _o(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 Oo(){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((x,b)=>(r(p=>{let g=new Map(p);return g.set(String(x),b),g}),()=>{r(p=>{let g=new Map(p),T=g.get(String(x));return (!b||T===b)&&g.delete(String(x)),g});}),[]),C=Pt.useCallback((x,b)=>{r(p=>{let g=new Map(p),T=g.get(String(x));return (!b||T===b)&&g.delete(String(x)),g});},[]),u=Pt.useCallback((x,b)=>(s(p=>{let g=new Map(p);return g.set(String(x),b),g}),()=>{s(p=>{let g=new Map(p),T=g.get(String(x));return (!b||T===b)&&g.delete(String(x)),g});}),[]),k=Pt.useCallback((x,b)=>{s(p=>{let g=new Map(p),T=g.get(String(x));return (!b||T===b)&&g.delete(String(x)),g});},[]),y=Pt.useCallback((x,b)=>{i(p=>{let g=new Map(p);return b?g.set(x,true):g.delete(x),g});},[]),M=Pt.useCallback((x,b)=>{f(p=>{let g=new Map(p);return b?g.set(x,true):g.delete(x),g});},[]),h=Pt.useMemo(()=>Array.from(o.values()).some(x=>x),[o]),d=Pt.useMemo(()=>Array.from(m.values()).some(x=>x),[m]),A=Pt.useMemo(()=>({baseUrl:t,actions:e,components:a,registerAction:c,unregisterAction:C,registerComponent:u,unregisterComponent:k,isAnyStreaming:h,setStreamingState:y,isAnyChatOpen:d,setChatOpenState:M}),[t,e,a,c,C,u,k,h,y,d,M]);return jsxRuntime.jsx(je.Provider,{value:A,children:n})}function tt(){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 Zo(t,n){let{registerAction:e}=tt(),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 ta(t,n){let{registerComponent:e}=tt(),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=p=>`${n}.chat.${p}`,a=`${n}.currentChatId`,s=`${n}.showChat`,[o,i]=Pt.useState(null),m=Pt.useRef(false),f=Pt.useRef(null),c=()=>{try{let p=localStorage.getItem(e);return p?JSON.parse(p):[]}catch{return []}},C=p=>{try{localStorage.setItem(e,JSON.stringify(p));}catch{}},u=p=>{try{let g=localStorage.getItem(r(p));return g?JSON.parse(g):null}catch{return null}},k=p=>{try{localStorage.setItem(r(p.id),JSON.stringify(p));}catch{}},y=p=>{let g=c(),T=g.findIndex(I=>I.id===p.id);T>=0?g[T]=p:g.unshift(p),C(g);},M=p=>{let T=c().filter(I=>I.id!==p);C(T);},h=p=>{try{localStorage.removeItem(r(p));}catch{}};return {currentChatId:o,setCurrentChatId:i,hasChatRecordRef:m,pendingFirstTitleRef:f,loadChatsIndex:c,loadChat:u,saveChat:k,deleteChat:(p,g)=>{h(p),M(p);let T=o===p;if(T){i(null),m.current=false,f.current=null;try{localStorage.removeItem(a);}catch{}}g?.(T);},loadChatPreferences:()=>{try{let p=localStorage.getItem(a);if(p){let g=u(p);if(g)return i(g.id),m.current=!0,g.messages||[]}}catch{}return []},persistChatData:p=>{if(!o||!m.current)return;k({id:o,messages:p,agentId:t});let T=p.find(E=>E.role==="user"),I=T?$e(T):"New chat",W=(f.current||I).slice(0,80),R={id:o,title:W,createdAt:Date.now(),updatedAt:Date.now()};y(R);try{localStorage.setItem(a,o);}catch{}},createNewChat:p=>{let g=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;i(g),m.current=true;let T=(p||"New chat").slice(0,80),I=Date.now();y({id:g,title:T,createdAt:I,updatedAt:I});try{localStorage.setItem(a,g);}catch{}return g},upsertChatMeta:y,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),u=Pt.useCallback((d,A)=>{let x=m.current.get(d)||[],b=JSON.stringify(A);if(x.push(b),x.length>5&&x.shift(),m.current.set(d,x),x.length>=3){let p=x.slice(-3);return p.every(g=>g===p[0])}return false},[]),k=Pt.useCallback((d,A,x,b)=>{!Array.isArray(d)||d.length===0||d.forEach((p,g)=>{if(!(!p||typeof p!="object")&&p.type==="action"){let T=String(p.name??"").trim();if(!T)return;let I=x.get(T);if(!I){console.warn(`Action handler not found for: ${T}`);return}let W=!!s.current[T],R=`${o.current||"assist"}:${T}:${g}`,E=`${T}:${g}`;try{if(A==="partial"&&W){C(H=>new Map(H).set(E,"executing"));let q=setTimeout(()=>{Promise.resolve(I(p.params,{name:T,trigger:A,index:g,assistantMessageId:o.current,chatId:b||void 0})).catch(H=>{console.error(`Error executing streaming action ${T}:`,H),C(D=>new Map(D).set(E,"executed"));});},50);f.current.set(`${E}_timeout`,q);}else if(A==="partial"&&!W){let q=u(E,p.params),H=f.current.get(E);q&&H!=="executed"?(f.current.set(E,"executed"),C(D=>new Map(D).set(E,"executed")),Promise.resolve(I(p.params,{name:T,trigger:"params_complete",index:g,assistantMessageId:o.current,chatId:b||void 0})).catch(D=>{console.error(`Error executing stabilized action ${T}:`,D);})):H||(f.current.set(E,"executing"),C(D=>new Map(D).set(E,"executing")));}else if(A==="final"&&f.current.get(E)!=="executed"&&!i.current.has(R)){i.current.add(R);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(I(p.params,{name:T,trigger:W?"final":"params_complete",index:g,assistantMessageId:o.current,chatId:b||void 0})).catch(D=>{console.error(`Error executing final action ${T}:`,D);});}}catch(q){console.error(`Error processing action ${T}:`,q);}}});},[u]),y=Pt.useCallback(()=>{a.current&&(a.current.abort(),a.current=null),n(false),r("Request stopped by user");},[]),M=Pt.useCallback(()=>{i.current.clear(),m.current.clear(),f.current.clear(),C(new Map);},[]),h=Pt.useCallback(()=>{f.current.forEach((d,A)=>{A.endsWith("_timeout")&&clearTimeout(d);});},[]);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:k,handleStop:y,resetActionTracking:M,cleanupTimeouts:h,hasActionParamsStabilized:u}}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(u=>{if(!u||Number.isNaN(u))return "0 B";let k=["B","KB","MB","GB","TB"],y=Math.min(k.length-1,Math.floor(Math.log(u)/Math.log(1024)));return `${(u/Math.pow(1024,y)).toFixed(y===0?0:1)} ${k[y]}`},[]),i=Pt.useCallback(async u=>{let k=new FormData;k.append("file",u);let y=await fetch(Ye(t,"/api/uploads"),{method:"POST",body:k});if(!y.ok){let h=await y.text().catch(()=>"");throw new Error(h||`Failed to upload ${u.name}`)}let M=await y.json();return {id:M.id,name:M.name||u.name,url:M.url,mimeType:M.mimeType||u.type||"application/octet-stream",size:typeof M.size=="number"?M.size:u.size}},[t]),m=Pt.useCallback(u=>{e(k=>k.filter(y=>y.id!==u));},[]),f=Pt.useCallback(async(u,k)=>{if(!u)return;let y=Array.isArray(u)?u:Array.from(u);k(null),a(true);let M=[];try{for(let h of y){if(h.size>ne){k(`"${h.name}" exceeds the ${o(ne)} limit.`);continue}try{let d=await i(h);M.push(d);}catch(d){console.error("Failed to upload attachment:",d),k(String(d?.message??`Failed to upload ${h.name}`));}}M.length&&e(h=>[...h,...M]);}finally{a(false);}},[i,o]),c=Pt.useCallback((u,k)=>{let y=[],M=(u||"").trim();M&&y.push({type:"text",text:M});for(let h of k||[]){let d=h.mimeType||"application/octet-stream";d.startsWith("image/")?y.push({type:"image",image:new URL(h.url),mediaType:d}):y.push({type:"file",data:h.url,mediaType:d,name:h.name});}return y},[]),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:u,onUpdate:k,signal:y})=>{try{let R=function(){let D=or(b);s(D),k?.(D);};var M=R;n(!0),r(null);let h;if(y)o.current=null,h=y;else {let D=new AbortController;o.current=D,h=D.signal;}let A=`${u?u.replace(/\/$/,""):""}/api/run/${encodeURIComponent(c)}`,x=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson"},body:JSON.stringify(C??{}),signal:h});if(!x.ok||!x.body){let D=await x.text().catch(()=>"");throw new Error(`Request failed: ${x.status} ${x.statusText} - ${D}`)}let b={first_agent:{message:"",continue:!1},main_agent:[]},p=null,g=null,T=null,I=null,W=!1,E=x.body.getReader(),q=new TextDecoder("utf-8"),H="";for(R();;){let{value:D,done:Ct}=await E.read();if(Ct)break;H+=q.decode(D,{stream:!0});let O=H.indexOf(`
|
|
15
|
+
`);for(;O!==-1;){let kt=H.slice(0,O).trim();if(H=H.slice(O+1),kt.length>0)try{let l=JSON.parse(kt);switch(l?.type){case "start":break;case "first-agent-start":b.first_agent.startDate=l?.startDate,b.first_agent.durationMs=l?.durationMs,R();break;case "first-agent-partial":typeof l?.message=="string"&&(b.first_agent.message=l.message),typeof l?.continue=="boolean"&&(b.first_agent.continue=l.continue),typeof l?.durationMs=="number"&&(b.first_agent.durationMs=l.durationMs),R();break;case "first-agent-end":typeof l?.message=="string"&&(b.first_agent.message=l.message),typeof l?.continue=="boolean"&&(b.first_agent.continue=l.continue),b.first_agent.endDate=l?.endDate,b.first_agent.durationMs=l?.durationMs,R();break;case "main-agent-start":W=!1;break;case "main-agent-step-finish":{let S={type:"step",stepNumber:void 0,finishReason:l?.finishReason,usage:l?.usage,endDate:l?.endDate,durationMs:l?.durationMs};b.main_agent.push(S),R();break}case "main-agent-skipped":W=!0;break;case "main-agent-reasoning-start":p={type:"reasoning",reasoning:"",status:"streaming",startDate:l?.startDate,durationMs:l?.durationMs},b.main_agent.push(p),R();break;case "main-agent-reasoning-delta":p&&typeof l?.text=="string"&&(p.reasoning+=l.text,p.durationMs=l?.durationMs,R());break;case "main-agent-reasoning-end":if(p){if(typeof l?.text=="string"&&l.text.length>0&&(p.reasoning+=l.text),p.status="finished",p.endDate=l?.endDate,p.durationMs=l?.durationMs,!p.reasoning||p.reasoning.trim().length===0){let S=b.main_agent.indexOf(p);S>-1&&b.main_agent.splice(S,1);}p=null,R();}else if(typeof l?.text=="string"&&l.text.length>0){let S={type:"reasoning",reasoning:l.text,status:"finished",endDate:l?.endDate,durationMs:l?.durationMs};b.main_agent.push(S),R();}break;case "main-agent-tool-call-start":g={type:"tool-call",toolCallId:l?.toolCallId,toolName:l?.toolName,inputText:"",input:void 0,output:void 0,status:"input_streaming",startDate:l?.startDate,durationMs:l?.durationMs},b.main_agent.push(g),R();break;case "main-agent-tool-input-delta":let $t=l?.delta||l?.argsTextDelta;g&&typeof $t=="string"&&(g.inputText=(g.inputText||"")+$t,g.durationMs=l?.durationMs,R());break;case "tool-call":case "main-agent-tool-call":if(g)g.input=l?.input,g.status="running",g.durationMs=l?.durationMs;else {let S=b.main_agent.find(Tt=>Tt.type==="tool-call"&&(Tt.toolCallId===l?.toolCallId||Tt.toolName===l?.toolName));S?(S.input=l?.input,S.status="running",S.durationMs=l?.durationMs,g=S):(g={type:"tool-call",toolCallId:l?.toolCallId,toolName:l?.toolName,input:l?.input,inputText:"",output:void 0,status:"running",durationMs:l?.durationMs},b.main_agent.push(g));}R();break;case "tool-result":case "main-agent-tool-result":let J=g;if(J||(J=b.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===l?.toolCallId||S.toolName===l?.toolName))||null),J)J.output=l?.output,J.status="finished",J.endDate=l?.endDate,J.durationMs=l?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:l?.toolCallId,toolName:l?.toolName,input:void 0,inputText:"",output:l?.output,status:"finished",endDate:l?.endDate,durationMs:l?.durationMs};b.main_agent.push(S);}R();break;case "tool-error":case "main-agent-tool-error":let V=g;if(V||(V=b.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===l?.toolCallId||S.toolName===l?.toolName))||null),V)V.error=l?.error,V.status="error",V.endDate=l?.endDate,V.durationMs=l?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:l?.toolCallId,toolName:l?.toolName,input:void 0,inputText:"",output:void 0,error:l?.error,status:"error",endDate:l?.endDate,durationMs:l?.durationMs};b.main_agent.push(S);}R();break;case "main-agent-response-partial":if(W)break;if(T||(T={type:"response",items:[],startDate:l?.startDate,durationMs:l?.durationMs},b.main_agent.push(T)),l?.value&&typeof l.value=="object"){let S=Array.isArray(l.value.items)?l.value.items:T.items;Object.assign(T,l.value),T.items=S,T.durationMs=l?.durationMs;}R();break;case "text-delta":case "main-agent-text-delta":typeof l?.text=="string"&&l.text&&(I||(I={type:"text",text:"",status:"streaming",startDate:l?.startDate,durationMs:l?.durationMs},b.main_agent.push(I)),I.text+=l.text,I.durationMs=l?.durationMs,R());break;case "text-end":I&&(I.status="finished",I.endDate=l?.endDate,I.durationMs=l?.durationMs,I=null,R());break;case "source":case "main-agent-source":let Ot={type:"source",source:l?.source,durationMs:l?.durationMs};b.main_agent.push(Ot),R();break;case "file":case "main-agent-file":let ie={type:"file",file:l?.file,durationMs:l?.durationMs};b.main_agent.push(ie),R();break;case "final":if(W)break;if(l?.value&&typeof l.value=="object"){T||(T={type:"response",items:[],endDate:l?.endDate,durationMs:l?.durationMs},b.main_agent.push(T));let S=Array.isArray(l.value.items)?l.value.items:T.items;Object.assign(T,l.value),T.items=S,T.endDate=l?.endDate,T.durationMs=l?.durationMs;}R();break;case "error":case "main-agent-error":throw new Error(l?.error||"Unknown agent error");default:break}}catch(l){console.warn("Failed to parse streaming line:",l);}O=H.indexOf(`
|
|
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:u}){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:u(r?"header.minimize":"header.maximize"),resolvedColors:o}),jsxRuntime.jsx(Lt,{icon:jsxRuntime.jsx(lucideReact.Plus,{size:"20",strokeWidth:"2"}),onClick:()=>{a||m();},ariaLabel:u("header.new"),resolvedColors:o,disabled:a}),jsxRuntime.jsx("button",{ref:C,"aria-label":u("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: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:u("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:u,fileInputRef:k,onFileSelection:y,t:M,dir:h="ltr"}){return Pt__default.default.useEffect(()=>{let d=u.current;if(d){d.style.height="auto";let A=Math.min(d.scrollHeight,200);d.style.height=`${A}px`;}},[t,u]),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(d=>{let A=d.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:A?"transparent":c.accentColor},children:[A?jsxRuntime.jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:x=>{x.target.style.display="none";let b=x.target.nextElementSibling;b&&(b.style.display="block");}}):null,jsxRuntime.jsx(lucideReact.File,{size:"14",strokeWidth:"2",style:{display:A?"none":"block",color:c.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsxRuntime.jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:d.name}),jsxRuntime.jsx("span",{style:{color:c.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:C(d.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[A&&jsxRuntime.jsx("button",{onClick:x=>{x.stopPropagation(),window.open(d.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:M("input.previewImage"),onMouseEnter:x=>{x.currentTarget.style.backgroundColor=c.hoverBackground,x.currentTarget.style.color=c.textColor;},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent",x.currentTarget.style.color=c.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),jsxRuntime.jsx("button",{onClick:x=>{x.stopPropagation(),m(d.id);},style:{background:"none",border:"none",color:c.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:M("input.removeFile"),onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#ef444420",x.currentTarget.style.color="#ef4444";},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent",x.currentTarget.style.color=c.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.X,{size:"12",strokeWidth:"2"})})]})]},d.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: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:c.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:s,value:t,onChange:d=>n(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),a||e());},ref:u})}),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:d=>{d.currentTarget.style.backgroundColor=`${c.backgroundColor}99`,d.currentTarget.style.color=c.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=c.mutedTextColor;},"aria-label":M("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:d=>{d.currentTarget.style.backgroundColor=`${c.backgroundColor}99`,d.currentTarget.style.color=c.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=c.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:d=>y(d.target.files)}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",...h==="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":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:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#dc2626",d.currentTarget.style.backgroundColor="#dc262630",d.currentTarget.style.color="#dc2626"):(d.currentTarget.style.borderColor=c.primaryColor,d.currentTarget.style.backgroundColor=c.hoverBackground,d.currentTarget.style.color=c.textColor));},onMouseLeave:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#ef4444",d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.color="#ef4444"):(d.currentTarget.style.borderColor=c.borderColor,d.currentTarget.style.backgroundColor=c.cardBackground,d.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(u=>(u.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:u=>r(u.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:u=>u.currentTarget.style.borderColor=m.primaryColor,onBlur:u=>u.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((u,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:u.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:y=>y.currentTarget.style.backgroundColor=m.hoverBackground,onMouseLeave:y=>y.currentTarget.style.backgroundColor="transparent",onClick:()=>o(u.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:u.title||f("history.untitledChat")})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:m.mutedTextColor},children:ln(u.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:y=>{y.currentTarget.style.color="#ef4444",y.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",y.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:y=>{y.currentTarget.style.color=m.mutedTextColor,y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.borderColor="transparent";},onClick:y=>{y.stopPropagation(),i(u.id);},children:jsxRuntime.jsx(lucideReact.Trash2,{size:"16",strokeWidth:"2"})})]})},u.id))})})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(C,document.body):C}var Wt={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:u=false,dir:k="ltr",language:y,floatingButtonPosition:M=k==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},placeholder:h,title:d,chatContainerClassName:A="",defaultReasoningOpen:x=false,hideReasoningContent:b=false}=t,p=y||(k==="rtl"?"ar":"en"),{t:g}=rn(p),T=h??g("input.placeholder"),I=d??g("general.agent"),{baseUrl:W,components:R,setStreamingState:E,setChatOpenState:q}=tt(),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":u}catch{return u}}),[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:nt,setMessages:At,selectChat:ue,deleteChat:ge,resetChat:fn}=vr(ot),L=Ze(),wt=Qe(W||""),me=tn();Pt.useEffect(()=>{E(H,L.streaming);},[L.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,$)=>{At(B=>B.map(w=>{if(w.id===v&&w.role==="assistant"){let z=$.main_agent.find(U=>U.type==="response"),N=z?.type==="response"?z.items:[];return {...w,items:N,mainAgentActions:$.main_agent,firstAgentMessage:$.first_agent.message,firstAgentContinue:$.first_agent.continue,reasoningOpen:w.reasoningOpen}}return w}));},[]),qt=Pt.useCallback(async({prompt:v,baseMessages:$,userMessage:B,assistantMessageId:w,chatId:z})=>{if(n){L.setError(null),L.setStreaming(true);try{let N=Se($);N.push({role:"user",content:B.content}),await me.startStreaming({agentId:n,baseUrl:W,body:{prompt:v,chatId:z??void 0,messages:N},onUpdate:U=>xe(w,U)});}catch(N){L.setError(N?.message||"Request failed");}finally{L.setStreaming(false);}}},[n,W,me,L,xe]),bn=Pt.useCallback(v=>{ue(v)&&(Mt(false),J(""));},[ue,Mt,J]),Cn=Pt.useCallback(v=>{ge(v),S($=>$+1);},[ge]),G=Wt[e],dt={primaryColor:r||G.primaryColor,backgroundColor:a||G.backgroundColor,borderColor:s||G.borderColor,textColor:o||G.textColor,accentColor:i||G.accentColor,mutedTextColor:G.mutedTextColor,inputBackground:G.inputBackground,cardBackground:G.cardBackground,hoverBackground:G.hoverBackground},kn=Pt.useCallback(async()=>{if(!n)return;let v=D.trim();if(!v)return;let $=ot.currentChatId;$||($=ot.createNewChat(v));let B=ae(jt),w=we(v,B),z=Yt(x),N=nt;At([...N,w,z]),Ct(""),ye(),pe(true),await qt({prompt:v,baseMessages:N,userMessage:w,assistantMessageId:z.id,chatId:$});},[n,D,nt,jt,ye,qt,ot,At,Ct]),Mn=Pt.useCallback(async v=>{if(!v||!W)return;let $=Array.from(v);L.setError(null);let B=[];try{for(let w of $){if(w.size>wt.MAX_UPLOAD_SIZE){L.setError(`"${w.name}" exceeds the ${wt.formatBytes(wt.MAX_UPLOAD_SIZE)} limit.`);continue}try{let z=new FormData;z.append("file",w);let N=await fetch(`${W}/api/uploads`,{method:"POST",body:z});if(!N.ok){let Jt=await N.text().catch(()=>"");throw new Error(Jt||`Failed to upload ${w.name}`)}let U=await N.json(),It={id:U.id,name:U.name||w.name,url:U.url,mimeType:U.mimeType||w.type||"application/octet-stream",size:typeof U.size=="number"?U.size:w.size};B.push(It);}catch(z){console.error("Failed to upload attachment:",z),L.setError(String(z?.message??`Failed to upload ${w.name}`));}}B.length&&vt(w=>[...w,...B]);}catch(w){console.error("Error adding attachments during edit:",w);}},[W,wt,L]);return Pt.useEffect(()=>{if(Kt.current){Kt.current=false;return}de&&requestAnimationFrame(()=>{ce.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[nt,L.streaming,de]),Pt.useEffect(()=>{let v=document.querySelector(".chat-scroll-container");if(!v)return;let $=()=>{let{scrollTop:B,scrollHeight:w,clientHeight:z}=v,U=w-B-z<40;pe(U);};return v.addEventListener("scroll",$),$(),()=>v.removeEventListener("scroll",$)},[]),typeof document<"u"?reactDom.createPortal(jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:A,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,...k==="rtl"?{left:0}:{right:0},bottom:0,zIndex:V?9999:1e3,pointerEvents:O?"auto":"none"},children:[jsxRuntime.jsx(an,{title:I,expandable:c,alwaysOpen:C,maximized:V,streaming:L.streaming,dir:k,resolvedColors:dt,onMaximize:()=>Ot(v=>!v),onNew:fn,onToggleHistory:()=>Mt(v=>!v),onClose:()=>kt(false),historyBtnRef:gn,t:g}),jsxRuntime.jsx(Ue,{messages:nt,streaming:L.streaming,editingMessageId:Tt,editingMessageText:pn,editingAttachments:le,error:L.error,actionStatuses:L.actionStatuses,components:R,theme:e,resolvedColors:dt,hideReasoningContent:b,onEditingTextChange:se,onRemoveAttachment:v=>{vt($=>$.filter(B=>B.id!==v));},onAddAttachments:Mn,uploading:fe,onStartEdit:(v,$)=>{let B=nt.find(w=>w.id===v);Ut(v),se($),B&&B.role==="user"&&vt(ae(pt(B)));},onCancelEdit:()=>{Ut(null),vt([]);},onSaveEdit:async(v,$)=>{let B=nt.findIndex(Jt=>Jt.id===v);if(B===-1)return;let w=nt[B];if(w.role!=="user")return;let z=$.trim(),N=Re(w,z,ae(le)),U=nt.slice(0,B),It=Yt(x);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 $=document.querySelector(".chat-scroll-container"),B=$?.scrollTop||0;Kt.current=true,At(w=>w.map(z=>z.id===v&&z.role==="assistant"?{...z,reasoningOpen:!z.reasoningOpen}:z)),requestAnimationFrame(()=>{$&&($.scrollTop=B);});},scrollAnchorRef:ce,t:g}),jsxRuntime.jsx(sn,{value:D,onChange:Ct,onSend:kn,onStop:L.handleStop,streaming:L.streaming,placeholder:T,attachments:jt,uploading:fe,onRemoveAttachment:yn,onFileInputClick:()=>he.current?.click(),resolvedColors:dt,formatBytes:hn,textareaRef:un,fileInputRef:he,onFileSelection:v=>xn(v,L.setError),t:g,dir:k})]}),jsxRuntime.jsx(Ke,{show:!O&&!C,onClick:()=>kt(true),resolvedColors:dt,floatingButtonPosition:M}),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 ${mn.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,5 +29,11 @@
|
|
|
29
29
|
from { transform: rotate(0deg); }
|
|
30
30
|
to { transform: rotate(360deg); }
|
|
31
31
|
}
|
|
32
|
-
`})]}),document.body)}
|
|
32
|
+
`})]}),document.body):null}function Rr({children:t,theme:n="dark",primaryColor:e,backgroundColor:r,borderColor:a,textColor:s,mutedTextColor:o,enableBorderAnimation:i=true,borderRadius:m=16,enableContentBorder:f=true,className:c="",enableMargin:C=true,chatWidth:u=420,dir:k="ltr"}){let{isAnyStreaming:y,isAnyChatOpen:M}=tt(),h=Pt.useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),d=Wt[n],A={primaryColor:e||d.primaryColor,backgroundColor:r||d.backgroundColor,borderColor:a||d.borderColor,textColor:s||d.textColor,accentColor:d.accentColor,mutedTextColor:o||d.mutedTextColor,inputBackground:d.inputBackground,cardBackground:d.cardBackground,hoverBackground:d.hoverBackground},x=typeof m=="number"?`${m}px`:m,b=typeof u=="number"?`${u}px`:u;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:c,style:{width:"100%",height:"100%",transition:"all 0.3s ease-out",padding:M&&f?"16px":"0",...C&&M?k==="rtl"?{marginLeft:b}:{marginRight:b}:{}},children:jsxRuntime.jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:x,border:y&&i?"none":`1px solid ${A.borderColor}`,padding:y&&i?"1.5px":"0",background:y&&i?`linear-gradient(120deg, ${A.primaryColor}dd 0%, ${A.primaryColor}88 25%, ${A.primaryColor}00 50%, ${A.primaryColor}88 75%, ${A.primaryColor}dd 100%)`:"transparent",backgroundSize:y&&i?"300% 300%":"auto",animation:y&&i?`${h.current}-border-flow 3s ease-in-out infinite`:"none",filter:y&&i?`drop-shadow(0 0 10px ${A.primaryColor}40)`:"none"},children:jsxRuntime.jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:M&&f?x:"0",backgroundColor:M&&f?A.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${A.mutedTextColor}40 transparent`},children:t})})}),jsxRuntime.jsx("style",{children:`
|
|
33
|
+
@keyframes ${h.current}-border-flow {
|
|
34
|
+
0% { background-position: 0% 50%; }
|
|
35
|
+
50% { background-position: 100% 50%; }
|
|
36
|
+
100% { background-position: 0% 50%; }
|
|
37
|
+
}
|
|
38
|
+
`})," "]})}exports.Button=zr;exports.ContentContainer=Rr;exports.FloatingChatButton=Ke;exports.HsafaChat=Ar;exports.HsafaProvider=Vn;exports.MessageList=Ue;exports.useAgentStreaming=tn;exports.useAutoScroll=Oo;exports.useChatStorage=Xe;exports.useFileUpload=Qe;exports.useHsafa=tt;exports.useHsafaAction=Zo;exports.useHsafaComponent=ta;exports.useStreaming=Ze;exports.useToggle=_o;//# sourceMappingURL=index.cjs.map
|
|
33
39
|
//# sourceMappingURL=index.cjs.map
|