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