@filigran/chatbot 3.9.0 → 3.9.1
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/README.md +217 -45
- package/dist/index.d.ts +13 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/markdown.js +1 -1
- package/dist/markdown.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{useState as r,useRef as a,useCallback as o,useEffect as i,useLayoutEffect as s,useMemo as l,useId as c,memo as d}from"react";import{createPortal as h}from"react-dom";import u from"react-markdown";import g from"remark-gfm";import p from"remark-breaks";function m(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}const f=new Set(["http","https","mailto","tel"]);function x(e){const t=e.indexOf(":");if(t<0)return e;const n=e.indexOf("/"),r=e.indexOf("?"),a=e.indexOf("#");if(n>-1&&t>n||r>-1&&t>r||a>-1&&t>a)return e;const o=e.slice(0,t).toLowerCase();return f.has(o)||"data"===o&&/^data:image\//i.test(e)?e:""}const w=e=>e;function y(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function v(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}M`}function b(e,t){if(!e)return"";const n=new Date(e).getTime();if(Number.isNaN(n))return"";const r=Date.now()-n,a=Math.floor(r/6e4);if(a<1)return t("just now");if(a<60)return`${a}${t("m ago")}`;const o=Math.floor(a/60);if(o<24)return`${o}${t("h ago")}`;const i=Math.floor(o/24);return i<7?`${i}${t("d ago")}`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const k=/\[\[FILE:[^\]]+\]\]/g,N=/\[\[FILE(?::[^\]]*)?\]?$/;function C(e){if(!e)return e;const t=e.replace(k,"").replace(N,"");return t===e?e:t.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}const S=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function _(e){const t=e.context_tokens,n=e.context_window;if("number"!=typeof t||"number"!=typeof n)return;if(!Number.isFinite(t)||!Number.isFinite(n)||n<=0||t<0)return;const r=function(e){if(!e||"object"!=typeof e)return;const t=e,n={};let r=!1;for(const[e,a]of S){const o=t[e];"number"==typeof o&&Number.isFinite(o)&&o>0&&(n[a]=o,r=!0)}return r?n:void 0}(e.context_breakdown);return r?{used:t,limit:n,breakdown:r}:{used:t,limit:n}}function I(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.file_id;"string"==typeof r&&r&&t.push({fileId:r,filename:"string"==typeof e.filename?e.filename:"file",type:"string"==typeof e.type?e.type:void 0,size:"number"==typeof e.size?e.size:void 0,contentType:"string"==typeof e.content_type?e.content_type:void 0,fileTag:"working_file"===e.file_tag?"working_file":"download_file"})}return t.length>0?t:void 0}function L(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.name&&e.name&&t.push({name:e.name,input:"string"==typeof e.input?e.input:void 0,output:"string"==typeof e.output?e.output:void 0,success:"boolean"!=typeof e.success||e.success})}return t.length>0?t:void 0}function $(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.agent_name&&e.agent_name&&t.push({agentId:"string"==typeof e.agent_id?e.agent_id:"",agentName:e.agent_name})}return t.length>0?t:void 0}function M(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.tool_call_id;if("string"!=typeof r||!r)continue;const a=e.arguments,o=e.input_schema;t.push({toolCallId:r,toolName:"string"==typeof e.tool_name&&e.tool_name?e.tool_name:"unknown tool",toolDescription:"string"==typeof e.tool_description?e.tool_description:void 0,arguments:a&&"object"==typeof a&&!Array.isArray(a)?a:{},inputSchema:o&&"object"==typeof o&&!Array.isArray(o)?o:void 0,source:"string"==typeof e.source?e.source:void 0})}return t.length>0?t:void 0}function z(e,t){const n=e.type;if("error"===n)return{action:"error",content:e.content||""};if("status"===n){const n=e.status;if("tool_done"===n||"wind_down"===n)return{action:"noop"};if("streaming"===n)return{action:"status",status:"streaming"};if("thinking_text"===n)return{action:"status",status:"thinking_text",thinkingContent:e.content};if("tool_start"===n)return t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:e.tools};if("tool_heartbeat"===n)return{action:"status",status:"tool_heartbeat",tools:e.tools,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};const r=_(e);return"thinking"===n&&t.hasUsedTools?{action:"status",status:"analyzing",contextUsage:r}:{action:"status",status:n,tools:e.tools,contextUsage:r}}if("approval_required"===n){const t=M(e.proposals);return t?{action:"approval_required",proposals:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}:{action:"noop"}}return"stream"===n?{action:"stream",content:e.content}:"done"===n?{action:"done",content:e.content,conversationId:e.conversation_id,toolNames:e.tool_names,toolCallCount:e.tool_call_count,iterations:e.iterations,transferAgentId:e.transfer_agent_id,transferAgentName:e.transfer_agent_name,attachments:I(e.attachments),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:L(e.tool_call_trace),transferChain:$(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:_(e)}:{action:"noop"}}function A(e,t){const n=e.event;if("nextAgentFlow"===n){const n=e.data,r=n?.nodeId;return"INPROGRESS"===n?.status&&r&&(t.activeNodeId=r),{action:"noop"}}if("start"===n)return{action:"noop"};if("token"===n){return{action:"stream",content:(e.data??"").replace(/<br\s*\/?>/g,"\n")}}if("agentReasoning"===n){const n=e.data,r=n?.usedTools;return r?.length?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:r.map(e=>e.tool)}):t.hasUsedTools?{action:"status",status:"analyzing"}:{action:"status",status:"thinking"}}if("usedTools"===n){t.hasUsedTools=!0;const n=e.data;return{action:"status",status:"tool_start",tools:Array.isArray(n)?n.map(e=>e.tool):[]}}if("metadata"===n){const t=e.data,n=t?.chatId;return n?{action:"set_chat_id",chatId:n}:{action:"noop"}}return"error"===n?{action:"error",content:e.data||""}:"end"===n?{action:"done",content:""}:{action:"noop"}}function T(e,t){const n=e.type;if("RUN_STARTED"===n)return{action:"status",status:"thinking"};if("RUN_FINISHED"===n)return{action:"done",content:""};if("RUN_ERROR"===n)return{action:"error",content:e.message||"Unknown error"};if("STEP_STARTED"===n){return{action:"status",status:e.stepName||"thinking"}}if("STEP_FINISHED"===n)return{action:"noop"};if("TEXT_MESSAGE_START"===n)return{action:"status",status:"streaming"};if("TEXT_MESSAGE_CONTENT"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TEXT_MESSAGE_END"===n)return{action:"noop"};if("TEXT_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TOOL_CALL_START"===n){t.hasUsedTools=!0;const n=e.toolCallName;return{action:"status",status:"tool_start",tools:n?[n]:[]}}if("TOOL_CALL_ARGS"===n)return{action:"noop"};if("TOOL_CALL_END"===n)return{action:"status",status:"analyzing"};if("TOOL_CALL_RESULT"===n)return{action:"noop"};if("TOOL_CALL_CHUNK"===n){const n=e.toolCallName;return n?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:[n]}):{action:"noop"}}if("REASONING_START"===n||"REASONING_MESSAGE_START"===n)return{action:"status",status:"thinking"};if("REASONING_MESSAGE_CONTENT"===n||"REASONING_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"status",status:"thinking_text",thinkingContent:t}:{action:"status",status:"thinking"}}return{action:"noop"}}const E="filigranChatConversationId",j="filigranChatLegacyChatId",D=e=>`filigranChatDraft:${e??"new"}`;function R(e){if("undefined"==typeof window)return"";try{return sessionStorage.getItem(D(e))??""}catch{return""}}function U(e,t){if("undefined"!=typeof window)try{t?sessionStorage.setItem(D(e),t):sessionStorage.removeItem(D(e))}catch{}}const B=52428800;function W({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:s,requestHeaders:l,pageContext:c,t:d,maxFileCount:h=10,maxTotalSize:u=52428800}){const g="legacy"===n,[p,m]=r([]),[f,x]=r(!1),[w,y]=r(null),[v,b]=r(()=>"undefined"==typeof window?null:localStorage.getItem(E)),[k,N]=r(()=>R("undefined"==typeof window?null:localStorage.getItem(E))),[C,S]=r([]),[_,I]=r(null),[L,$]=r(null),[D,W]=r(null),[O,H]=r(!1),[F,P]=r(null),[q,V]=r(!1),[G,J]=r(0),[K,Z]=r(0),[X,Q]=r(()=>"undefined"==typeof window?null:localStorage.getItem(j)),Y=a(!1),ee=a(null),te=a(!1),ne=a(v),re=a(f);re.current=f;const ae=a(c);ae.current=c;const oe=a(null),ie=a(!1),se=a(null),le=a(0),ce=a(null),de=a(new AbortController),he=Number.isFinite(h)&&h>0?Math.floor(h):10,ue=Number.isFinite(u)&&u>0?u:B,ge=()=>g||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,pe=()=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const r=t?.approve;return r?`${e}${r}`:null},me=r=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const a=t?.pendingApprovals;return a?`${e}${a}/${r}/pending-approvals`:null},fe=async e=>{const t=me(e);if(!t)return null;try{const e=await fetch(t,{headers:{...l??{}}});if(!e.ok)return null;const n=await e.json();return{proposals:M(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},xe=o(()=>{Y.current=!1,J(e=>e+1)},[]),we=()=>g||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,ye=o(e=>{ne.current=e,b(e),e?localStorage.setItem(E,e):localStorage.removeItem(E)},[]),ve=async n=>{if(ne.current)return ne.current;if(ce.current)return ce.current;const r=g||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`;if(!r)return null;const a=(async()=>{try{const e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify({agent_slug:n})});if(!e.ok)return null;const t=await e.json(),a=t?.conversation_id??null;return a&&ye(a),a}catch{return null}finally{ce.current=null}})();return ce.current=a,a},be=async(e,t,n)=>{const r=we(),a=new FormData;a.append("conversation_id",t),a.append("file",e,e.name);const o=l?Object.fromEntries(Object.entries(l).filter(([e])=>"content-type"!==e.toLowerCase())):void 0,i=await fetch(r,{method:"POST",headers:o,body:a,signal:n});if(!i.ok)throw new Error(`File upload failed: ${i.status}`);const s=(await i.json()).file_ids??[];if(0===s.length)throw new Error("No file_id returned");return s[0]},ke=e=>{if(!e||0===e.length||!we())return;const t=Array.from(e).map(e=>({file:e,tempId:crypto.randomUUID()}));let n=[];S(e=>{const r=e.length,a=e.reduce((e,t)=>e+t.size,0),o=he-r;if(o<=0)return e;let i=ue-a;const s=[];for(const e of t.slice(0,o))e.file.size<=i&&(s.push(e),i-=e.file.size);if(0===s.length)return e;n=s;const l=s.map(({file:e,tempId:t})=>({name:e.name,type:e.type,size:e.size,rawFile:e,uploadStatus:"pending",fileId:t}));return[...e,...l]}),setTimeout(()=>{const e=de.current.signal;for(const{file:t,tempId:r}of n)(async()=>{try{const n=await ve(s);if(!n)return void S(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e));const a=await be(t,n,e);S(e=>e.map(e=>e.fileId===r?{...e,fileId:a,uploadStatus:"done"}:e))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;S(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e))}})()},0)},Ne=()=>{ee.current?.abort(),ee.current=null,de.current.abort(),de.current=new AbortController,ce.current=null,m([]),N(""),S([]),x(!1),y(null),I(null),$(null),W(null),P(null),V(!1),oe.current=null,ie.current=!1,se.current=null,te.current=!1,Y.current=!1,g?(Q(null),localStorage.removeItem(j)):ye(null)};i(()=>{const e=window.setTimeout(()=>U(v,k),300);return()=>window.clearTimeout(e)},[k,v]);const Ce=a({conversationId:v,inputValue:k});Ce.current={conversationId:v,inputValue:k},i(()=>()=>{const{conversationId:e,inputValue:t}=Ce.current;U(e,t)},[]),i(()=>{const e=v;if(!e||f)return;if(se.current===e)return;me(e)&&pe()&&(se.current=e,(async()=>{const t=await fe(e);t?.proposals&&(ne.current!==e||re.current||(oe.current=e,ie.current=!0,P(null),W(t.proposals)))})())},[v,f]),i(()=>{if(!D?.length||!ie.current)return;const e=oe.current,t=e?me(e):null;if(!t)return;const n=window.setInterval(()=>{fetch(t,{headers:{...l??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[D]),i(()=>{if(!q)return;const e=oe.current;if(!e)return void V(!1);if(Date.now()>=le.current)return V(!1),void xe();let t=!1;const n=window.setTimeout(async()=>{const n=await fe(e);if(!t){if(n)return n.proposals?(ie.current=!0,P(null),W(n.proposals),void V(!1)):n.turnRunning?void Z(e=>e+1):(V(!1),void xe());Z(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[q,K,xe]);const Se=f&&null!==ge()&&null!==v;return{messages:p,inputValue:k,setInputValue:N,isLoading:f,agentStatus:w,attachedFiles:C,conversationId:v,contextUsage:L,transferredAgent:_,canSteer:Se,pendingApprovals:D,isSubmittingApproval:O,approvalError:F,submitApprovalDecisions:async e=>{const t=pe(),n=oe.current??ne.current;if(0!==e.length)if(t&&n){P(null),H(!0);try{const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify({conversation_id:n,decisions:e.map(e=>({tool_call_id:e.toolCallId,decision:e.verdict,..."reject"===e.verdict&&e.rejectionReason?{rejection_reason:e.rejectionReason}:{}}))})});if(r.ok)return W(null),ie.current?(ie.current=!1,le.current=Date.now()+9e5,void V(!0)):void y(e=>e?{...e,status:"thinking"}:{status:"thinking"});P(409===r.status?d("This turn is no longer waiting for a decision."):d("Could not send your decision. Please try again."))}catch{P(d("Could not send your decision. Please try again."))}finally{H(!1)}}else P(d("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:q,historyReloadNonce:G,historyLoadedRef:Y,conversationIdRef:ne,handleFileAdd:ke,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),ke(t))},handleSendMessage:async()=>{const r=k.trim();if(f)return void(r&&0===C.length&&ge()&&ne.current&&(N(""),await(async e=>{const t=ge(),n=ne.current;if(!t||!n)return;const r={id:crypto.randomUUID(),role:"user",content:e,timestamp:new Date};m(e=>[...e,r]);try{const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify({conversation_id:n,content:e,agent_slug:s})});if(!r.ok)throw new Error(`Steer failed: ${r.status}`)}catch{m(e=>e.filter(e=>e.id!==r.id)),N(t=>t?`${e}\n${t}`:e)}})(r)));if(!k.trim()&&0===C.length)return;const a=k.trim(),o={id:crypto.randomUUID(),role:"user",content:a,timestamp:new Date,files:C.length>0?[...C]:void 0};m(e=>[...e,o]),N(""),S([]),x(!0),y({status:"thinking"}),te.current=!1;const i=crypto.randomUUID();m(e=>[...e,{id:i,role:"assistant",content:"",timestamp:new Date}]);let c=i;try{const r=new AbortController;ee.current=r;const h=(o.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),u=function(e,t,n){switch(e){case"legacy":return{question:t,chatId:n.legacyChatId??void 0,streaming:!0};case"ag-ui":return{threadId:n.conversationId??crypto.randomUUID(),runId:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={content:t,conversation_id:n.conversationId,agent_slug:n.agentSlug};if(n.supportsToolApproval&&(e.supports_tool_approval=!0),n.pageContext&&Object.keys(n.pageContext).length>0)try{const t=JSON.stringify(n.pageContext);t&&"{}"!==t&&(e.context=n.pageContext)}catch{}return e}}}(n,a,{legacyChatId:X,conversationId:ne.current,agentSlug:s,pageContext:ae.current,supportsToolApproval:null!==pe()});h.length>0&&(u.file_ids=h),y({status:"thinking"});const p=await fetch(g||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify(u),signal:r.signal});if(!p.ok||!p.body)return void m(e=>e.map(e=>e.id===i?{...e,content:d("Unable to connect. Please check the configuration.")}:e));const f=function(e){switch(e){case"legacy":return A;case"ag-ui":return T;default:return z}}(n),x={hasUsedTools:!1,activeNodeId:""},w=p.body.getReader(),v=new TextDecoder;let b="",k="",N=!1;const C=()=>{if(!N)return;N=!1,k="",c=crypto.randomUUID();const e=c;m(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),y({status:"thinking"})};for(;;){const{done:e,value:t}=await w.read();if(e)break;b+=v.decode(t,{stream:!0});const n=b.split("\n");b=n.pop()||"";for(const e of n){const t=e.replace(/\r$/,"");if(!t.startsWith("data:"))continue;const n=t.startsWith("data: ")?t.slice(6):t.slice(5);try{const e=f(JSON.parse(n),x);switch(x.hasUsedTools=x.hasUsedTools||te.current,e.action){case"status":{C();const t=c;if(e.contextUsage&&$(e.contextUsage),"tool_start"===e.status&&(te.current=!0),"stream_retract"===e.status)k="",m(e=>e.map(e=>e.id===t?{...e,content:""}:e)),y(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}));else if("thinking_text"===e.status)y(t=>({...t,status:t?.status??"thinking",thinkingContent:(t?.thinkingContent??"")+(e.thinkingContent??"")}));else if("tool_heartbeat"===e.status){const t="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;y(n=>n?{...n,elapsedS:e.elapsedS,elapsedStartMs:t}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:t})}else y(t=>({status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent}));break}case"stream":{C(),k+=e.content;const t=c,n=k;y(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),m(e=>e.map(e=>e.id===t?{...e,content:n}:e));break}case"done":{N=!0,W(null),P(null),e.conversationId&&ye(e.conversationId),e.contextUsage&&$(e.contextUsage),e.transferAgentId&&e.transferAgentName&&I({id:e.transferAgentId,name:e.transferAgentName});const t=c,n=e.content||k;m(r=>r.map(r=>r.id===t?{...r,content:n,toolNames:e.toolNames,toolCallCount:e.toolCallCount,iterations:e.iterations,attachments:e.attachments,reasoning:e.reasoning,toolCallTrace:e.toolCallTrace,transferChain:e.transferChain,isTruncated:e.isTruncated}:r));break}case"approval_required":oe.current=e.conversationId??ne.current,P(null),W(e.proposals),y(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"});break;case"error":{C();const t=c;return void m(n=>n.map(n=>n.id===t?{...n,content:e.content||d("Unable to connect. Please check the configuration.")}:n))}case"set_chat_id":Q(e.chatId),localStorage.setItem(j,e.chatId)}te.current=x.hasUsedTools}catch{}}}if(k&&!N){const e=c,t=k;m(n=>n.map(n=>n.id===e?{...n,content:t||"No response."}:n))}}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;const t=c;m(e=>e.map(e=>e.id===t?{...e,content:d("Sorry, an error occurred. Please try again.")}:e))}finally{ee.current=null,x(!1),y(null),te.current=!1,W(null),P(null),oe.current=null,ie.current=!1,se.current=ne.current}},handleNewChat:Ne,handleStopGenerating:()=>{ee.current?.abort(),ee.current=null,x(!1),y(null),te.current=!1,W(null),P(null),V(!1),oe.current=null,ie.current=!1,m(e=>e.filter(e=>!("assistant"===e.role&&!e.content)))},setAttachedFiles:S,setMessages:m,setContextUsage:$,updateConversationId:ye,handleSwitchConversation:e=>{(g||e!==ne.current)&&(Ne(),g||(ye(e),N(R(e))))}}}const O="filigranChatAgentSlug";function H({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[o,s]=r([]),[l,c]=r(!1),[d,h]=r(!1),[u,g]=r(null),[p,m]=r(!1);i(()=>{if(null===t?.agents||t?.singleEndpoint||"legacy"===n)return;const r=`${e}${t?.agents??"/chat/agents"}`;c(!0),h(!1),fetch(r,{headers:a}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}).then(e=>{const t=function(e){return(Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]).filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id)}(e);if(s(t),t.length>0&&!u){const e=localStorage.getItem(O),n=e?t.find(t=>t.slug===e):null;g(n||t[0])}}).catch(()=>{s([]),h(!0)}).finally(()=>c(!1))},[e,t,n,a]);return{agents:o,agentsLoading:l,agentsError:d,selectedAgent:u,setSelectedAgent:g,agentMenuOpen:p,setAgentMenuOpen:m,handleSwitchAgent:(e,t)=>{e.id!==u?.id?(g(e),e.slug&&localStorage.setItem(O,e.slug),m(!1),t?.()):m(!1)}}}function F(e){if(!e||"object"!=typeof e)return null;const t=e,n=t.conversation_id??t.id;if("string"!=typeof n||!n)return null;return{conversationId:n,title:"string"==typeof t.title?t.title.trim():"",updatedAt:"string"==typeof t.updated_at?t.updated_at:"string"==typeof t.created_at?t.created_at:void 0,messageCount:"number"==typeof t.message_count?t.message_count:void 0,agentName:"string"==typeof t.agent_name&&t.agent_name?t.agent_name:void 0}}const P=400,q="filigranChatSidebarWidth";let V=null,G=null,J=0;function K(){null!==V&&(window.clearInterval(V),V=null),null!==G&&(document.title=G,G=null)}function Z({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:o,isViewingChat:s}){const l=a(!1),c=a(0);i(()=>{if(!r||"undefined"==typeof document)return;J+=1;const e=()=>{!document.hidden&&document.hasFocus()&&K()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),J=Math.max(0,J-1),0===J&&K()}},[r]),i(()=>{const a=l.current;if(l.current=e,!e||a){if(!e&&a&&r){if(Date.now()-c.current<4e3)return;const e="undefined"!=typeof document&&document.hidden,r="undefined"!=typeof document&&!document.hasFocus(),a=e||r,i=!s||s();if(!a&&i)return;const l=n("Response ready"),d=`${t} ${n("has finished")}`;a&&(function(e){if("undefined"==typeof document)return;null===G&&(G=document.title),null!==V&&window.clearInterval(V);let t=!0;document.title=e,V=window.setInterval(()=>{t=!t,document.title=t?e:G??e},1200)}(l),function(e,t){try{if("undefined"==typeof Notification||"granted"!==Notification.permission)return;new Notification(e,{body:t,tag:"filigran-chat-complete"})}catch{}}(l,d)),o?.(l,d)}}else c.current=Date.now()},[e,r,t,n,o,s])}function X({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[s,l]=r(null),[c,d]=r(null),h="rest"===n&&!t?.singleEndpoint,u=void 0===t?.prompts?"/chat/prompts":t.prompts,g=void 0===t?.quota?"/chat/quota":t.quota,p=h&&u?`${e}${u}`:null,m=h&&g?`${e}${g}`:null;i(()=>{if(!p)return void l(null);let e=!1;return fetch(p,{credentials:"include",headers:{...a??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){const t=Array.isArray(e)?e:Array.isArray(e?.prompts)?e.prompts:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,r="string"==typeof t.id?t.id:"",a="string"==typeof t.content?t.content:"";r&&a&&n.push({id:r,title:"string"==typeof t.title&&t.title?t.title:r,content:a,description:"string"==typeof t.description?t.description:void 0})}return n}(t);l(n.length>0?n:null)}).catch(()=>{e||l(null)}),()=>{e=!0}},[p,a]);const[f,x]=r(0),w=o(()=>x(e=>e+1),[]);return i(()=>{if(!m)return void d(null);let e=!1;return fetch(m,{credentials:"include",headers:{...a??{}}}).then(e=>e.ok?e.json():null).then(t=>{e||d(function(e){if(!e||"object"!=typeof e)return null;const t=e;return"number"!=typeof t.used?null:{used:t.used,limit:"number"==typeof t.limit?t.limit:null,period:"string"==typeof t.period?t.period:""}}(t))}).catch(()=>{e||d(null)}),()=>{e=!0}},[m,a,f]),{prompts:s,quota:c,refreshQuota:w}}function Q({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a,agentSlug:o}){const[s,l]=r(null),[c,d]=r(!1),h="rest"===n&&!t?.singleEndpoint,u=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,g=h&&u?`${e}${u}`:null;return i(()=>{if(!g)return void l(null);let e=!1;d(!0);const t=o?`${g}?agent_slug=${encodeURIComponent(o)}`:g;return fetch(t,{credentials:"include",headers:{...a??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){return(Array.isArray(e)?e:Array.isArray(e?.suggestions)?e.suggestions:[]).map(e=>{if("string"==typeof e)return e.trim();if(e&&"object"==typeof e){const t=e,n=t.prompt??t.label??t.text;if("string"==typeof n)return n.trim()}return""}).filter(e=>e.length>0)}(t);l(n.length>0?n:null)}).catch(()=>{e||l(null)}).finally(()=>{e||d(!1)}),()=>{e=!0}},[g,o,a]),{suggestions:s,loading:c}}const Y=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),t("path",{d:"M12 9v4"}),t("path",{d:"M12 17h.01"})]}),ee=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m16 3 4 4-4 4"}),t("path",{d:"M20 7H4"}),t("path",{d:"m8 21-4-4 4-4"}),t("path",{d:"M4 17h16"})]}),te=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),ne=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 8V4H8"}),t("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),t("path",{d:"M2 14h2"}),t("path",{d:"M20 14h2"}),t("path",{d:"M15 13v2"}),t("path",{d:"M9 13v2"})]}),re=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),t("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),t("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),t("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),t("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),t("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),t("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),t("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),t("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),ae=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),oe=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 6 9 17l-5-5"})}),ie=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m6 9 6 6 6-6"})}),se=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),le=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),t("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),ce=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),t("path",{d:"M3 5V19A9 3 0 0 0 21 19V5"}),t("path",{d:"M3 12A9 3 0 0 0 21 12"})]}),de=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),he=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),t("polyline",{points:"7 10 12 15 17 10"}),t("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]}),ue=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 20h9"}),t("path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"})]}),ge=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M10 14 21 3"}),t("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),pe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),me=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7"}),t("rect",{width:"12",height:"12",x:"10",y:"10",rx:"2"})]}),fe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),t("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),t("path",{d:"M3 16h3a2 2 0 0 0 2 2v3"}),t("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"})]}),xe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),t("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),t("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),t("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]}),we=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("line",{x1:"6",x2:"10",y1:"11",y2:"11"}),t("line",{x1:"8",x2:"8",y1:"9",y2:"13"}),t("line",{x1:"15",x2:"15.01",y1:"12",y2:"12"}),t("line",{x1:"18",x2:"18.01",y1:"10",y2:"10"}),t("path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"})]}),ye=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),t("path",{d:"M2 12h20"})]}),ve=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),t("path",{d:"M3 3v5h5"}),t("path",{d:"M12 7v5l4 2"})]}),be=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),t("circle",{cx:"9",cy:"9",r:"2"}),t("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]}),ke=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),Ne=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),t("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),Ce=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),Se=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]}),_e=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-.11 1.23"}),t("path",{d:"M5 10v2a7 7 0 0 0 12 5"}),t("path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33"}),t("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12"}),t("path",{d:"m2 2 20 20"})]}),Ie=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),Le=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),$e=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),Me=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),ze=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),Ae=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),Te=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M17 14V2"}),t("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),Ee=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M7 10v12"}),t("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),je=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 6h18"}),t("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),t("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),t("line",{x1:"10",x2:"10",y1:"11",y2:"17"}),t("line",{x1:"14",x2:"14",y1:"11",y2:"17"})]}),De=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t("circle",{cx:"9",cy:"7",r:"4"}),t("line",{x1:"19",x2:"19",y1:"8",y2:"14"}),t("line",{x1:"22",x2:"16",y1:"11",y2:"11"})]}),Re=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),Ue=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]});const Be=({open:e,onClose:n,anchorRef:l,placement:c="bottom-start",width:d=280,children:u})=>{const g=a(null),[p,m]=r({top:0,left:0}),f=o(()=>n(),[n]);if(function(e,t,n=!0){i(()=>{if(!n)return;const r=n=>{e.current&&!e.current.contains(n.target)&&t()};return document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r)}},[e,t,n])}(g,f,e),s(()=>{if(!e||!l.current)return;const t=l.current.getBoundingClientRect(),n=g.current?.offsetHeight??0,r=window.innerHeight-t.bottom-8,a=t.top-8,o=n>0&&r<n&&a>r?Math.max(8,t.top-n-4):t.bottom+4,i="bottom-end"===c?t.right-d:t.left,s=Math.max(8,Math.min(i,window.innerWidth-d-8));m({top:o,left:s})},[e,l,c,d,u]),!e)return null;const x=y(l.current);return h(t("div",{ref:g,className:"fixed z-[10000] rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl",style:{top:p.top,left:p.left,width:d},children:u}),x)},We=({size:e=16,className:n=""})=>t("div",{className:`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${n}`,style:{width:e,height:e}}),Oe=({title:n,children:o})=>{const i=a(null),[s,l]=r(!1),[c,d]=r({top:0,left:0}),[u,g]=r(!1);if(!n)return o;return e("span",{ref:i,className:"inline-flex",onMouseEnter:()=>{if(!i.current)return;const e=i.current.getBoundingClientRect(),t=y(i.current).getBoundingClientRect().top,n=e.top-t<28;g(n),d({top:n?e.bottom+4:e.top-4,left:e.left+e.width/2}),l(!0)},onMouseLeave:()=>l(!1),children:[o,s&&h(t("span",{className:`pointer-events-none fixed z-[10001] -translate-x-1/2 ${u?"":"-translate-y-full"} whitespace-nowrap rounded-md bg-gray-900 dark:bg-gray-100 px-2 py-1 text-xs text-white dark:text-gray-900 shadow-lg`,style:{top:c.top,left:c.left},role:"tooltip",children:n}),y(i.current))]})},He=[{mode:"floating",label:"Floating",getIcon:e=>t(me,{...e})},{mode:"sidebar",label:"Sidebar",getIcon:e=>t($e,{...e})},{mode:"fullscreen",label:"Full screen",getIcon:e=>t(xe,{...e})}],Fe=({mode:o,agentName:s,agents:c,agentsLoading:d=!1,agentsError:h=!1,selectedAgent:u,transferredFrom:g,agentMenuOpen:p,onAgentMenuToggle:m,onAgentMenuClose:f,onSwitchAgent:x,modeMenuOpen:w,onModeMenuToggle:y,onModeMenuClose:v,onModeChange:k,onNewChat:N,onClose:C,logoIcon:S,agentDashboardUrl:_,historyEnabled:I=!1,historyMenuOpen:L=!1,onHistoryMenuToggle:$,onHistoryMenuClose:M,conversations:z=[],conversationsLoading:A=!1,activeConversationId:T=null,onSelectConversation:E,onDeleteConversation:j,t:D})=>{const R=a(null),U=a(null),B=a(null),[W,O]=r("");i(()=>{p||O("")},[p]);const H=l(()=>{const e=W.trim().toLowerCase();return e?c.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):c},[c,W]),F=c.length>5,P="sidebar"===o?$e:"fullscreen"===o?fe:me;return e("div",{className:"flex items-center px-3 py-2 min-h-[48px] border-b border-gray-200 dark:border-white/10 bg-gradient-to-br from-[var(--chat-accent-dark)]/[0.13] to-[var(--chat-accent)]/[0.07] "+("floating"===o?"rounded-t-xl":""),children:[e("div",{className:"min-w-0",children:[e("button",{ref:R,type:"button",onClick:m,className:"flex items-center gap-1.5 text-sm font-semibold text-gray-900 dark:text-white px-2 py-1 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t("span",{className:"flex items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:S}),t("span",{children:s}),t(ie,{size:16,className:"text-gray-400 dark:text-white/30"})]}),g&&e("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal text-gray-400 dark:text-white/30",children:[D("Transferred from")," ",g]})]}),e(Be,{open:p,onClose:f,anchorRef:R,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:D("Switch to another agent")}),0===c.length&&d&&t("div",{className:"px-4 py-2",children:t(We,{size:16})}),0===c.length&&!d&&h&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(Y,{size:14,className:"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400"}),t("span",{className:"text-[0.75rem] leading-5 text-gray-600 dark:text-white/60",children:D("Could not reach the assistant service. Check the connection and try again.")})]}),0===c.length&&!d&&!h&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:D("Agent switching is not available here")}),F&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(Ie,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40"}),t("input",{autoFocus:!0,type:"text",value:W,onChange:e=>O(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f()},placeholder:D("Search agents..."),"aria-label":D("Search agents..."),className:"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[c.length>0&&0===H.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:D("No agent matches")}),H.map(n=>e("button",{type:"button",onClick:()=>x(n),className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(n.id===u?.id?"bg-[var(--chat-accent)]/10":""),children:[t("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:S})}),e("div",{className:"min-w-0",children:[t("div",{className:"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate",children:n.name}),n.description&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:n.description})]})]},n.id))]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("div",{children:[_&&e("button",{type:"button",onClick:()=>{f(),window.open(`${_}/agents`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(ge,{size:18,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:D("Browse agents")})]}),_&&e("button",{type:"button",onClick:()=>{f(),window.open(`${_}/agents/new`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(De,{size:18,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:D("Create agent")})]})]})]}),t("div",{className:"flex-1"}),I&&e(n,{children:[t(Oe,{title:D("Conversation history"),children:t("button",{ref:B,type:"button",onClick:$,"aria-label":D("Conversation history"),"aria-haspopup":"menu","aria-expanded":L,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(ve,{size:18})})}),e(Be,{open:L,onClose:()=>M?.(),anchorRef:B,placement:"bottom-end",width:300,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:D("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[A&&0===z.length&&t("div",{className:"px-4 py-2",children:t(We,{size:16})}),!A&&0===z.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:D("No conversations yet")}),z.map(n=>{const r=n.conversationId===T,a=b(n.updatedAt,D);return e("div",{className:"group flex items-center gap-2 px-4 py-1.5 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(r?"bg-[var(--chat-accent)]/10":""),children:[e("button",{type:"button",onClick:()=>E?.(n.conversationId),className:"flex-1 min-w-0 text-left",children:[t("div",{className:"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate",children:n.title||D("Untitled conversation")}),a&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:a})]}),j&&t("button",{type:"button",onClick:()=>j(n.conversationId),title:D("Delete conversation"),"aria-label":D("Delete conversation"),className:"shrink-0 p-1 rounded-md text-gray-400 dark:text-white/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all",children:t(je,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("button",{type:"button",onClick:()=>{M?.(),N()},className:"w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(ue,{size:16,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:D("New conversation")})]})]})]}),t(Oe,{title:D("New chat"),children:t("button",{type:"button",onClick:N,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(ue,{size:18})})}),t(Oe,{title:D("Switch view"),children:t("button",{ref:U,type:"button",onClick:y,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(P,{size:18})})}),e(Be,{open:w,onClose:v,anchorRef:U,placement:"bottom-end",width:180,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:D("Switch to")}),t("div",{className:"pb-1",children:He.map(n=>e("button",{type:"button",onClick:()=>{k(n.mode),v()},className:"w-full flex items-center gap-3 px-4 py-1 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(o===n.mode?"bg-[var(--chat-accent)]/10":""),children:[n.getIcon({size:18,className:"text-gray-400 dark:text-white/40"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:D(n.label)})]},n.mode))})]}),t(Oe,{title:D("Close"),children:t("button",{type:"button",onClick:C,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(se,{size:18})})})]})};function Pe(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const qe=14,Ve=2*Math.PI*6,Ge=[{field:"system",label:"System prompt",color:"#9ca3af"},{field:"tools",label:"Tool definitions",color:"#a78bfa"},{field:"dynamicTools",label:"MCP & dynamic tools",color:"#f0abfc"},{field:"summary",label:"Summarized conversation",color:"#fb7185"},{field:"toolResults",label:"Tool results",color:"#34d399"},{field:"conversation",label:"Conversation",color:"#a1a1aa"}],Je=({usage:o,t:i})=>{const{used:s,limit:l,breakdown:c}=o,d=a(null),[h,u]=r(!1),g=Math.min(Math.max(s/l,0),1),p=g>=.95,m=g>=.8,f=p?"text-red-500":m?"text-amber-500":"text-[var(--chat-accent)]",x=p?"text-red-500 dark:text-red-400":m?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",w=Math.round(100*g),y=`${v(s)}/${v(l)}`,b=i(p?"Context full — older turns are being dropped":m?"Context nearly full — older turns are being summarized":"Context used"),k=`${b} · ${y} ${i("tokens")}`,N=c?Ge.filter(e=>(c[e.field]??0)>0):[],C=N.length>0,S=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:qe,height:qe,viewBox:"0 0 14 14",className:f,"aria-hidden":"true",children:[t("circle",{cx:7,cy:7,r:6,fill:"none",strokeWidth:2,className:"stroke-gray-200 dark:stroke-white/15"}),t("circle",{cx:7,cy:7,r:6,fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeDasharray:Ve,strokeDashoffset:Ve*(1-g),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${x}`,children:[w,"%"]})]});return C?e(n,{children:[t(Oe,{title:h?"":`${k} — ${i("click for details")}`,children:t("button",{ref:d,type:"button",onClick:()=>u(e=>!e),"aria-label":`${k} (${w}%)`,"aria-haspopup":"dialog","aria-expanded":h,className:"flex items-center rounded-md px-1 -mx-1 py-0.5 transition-colors hover:bg-gray-100 dark:hover:bg-white/10",children:S})}),e(Be,{open:h,onClose:()=>u(!1),anchorRef:d,placement:"bottom-end",width:296,children:[e("div",{className:"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3",children:[t("span",{className:`text-[0.8125rem] tabular-nums ${x}`,children:i("{percent}% full").replace("{percent}",String(w))}),e("span",{className:"text-[0.7rem] tabular-nums text-gray-400 dark:text-white/40 shrink-0",children:["~",y," ",i("tokens")]})]}),t("div",{className:"px-3.5 pb-2.5 pt-1.5",children:t("span",{className:"flex h-1.5 w-full gap-px rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:N.map(e=>t("span",{className:"h-full first:rounded-l-full",style:{width:(c?.[e.field]??0)/Math.max(s,1)*Math.min(s/l,1)*100+"%",backgroundColor:e.color}},e.field))})}),t("div",{className:"px-3.5 pb-1",children:N.map(n=>e("div",{className:"flex items-center gap-2 py-[3px]",children:[t("span",{className:"h-2 w-2 shrink-0",style:{backgroundColor:n.color,borderRadius:2},"aria-hidden":"true"}),t("span",{className:"text-[0.75rem] text-gray-700 dark:text-white/70 truncate",children:i(n.label)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0",children:v(c?.[n.field]??0)})]},n.field))}),m&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${x}`,children:b})]})]}):t(Oe,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},Ke=({prompts:o,onPick:i,t:s})=>{const l=a(null),[c,d]=r(!1),[h,u]=r(""),g=()=>{d(!1),u("")},p=h.trim().toLowerCase(),m=p?o.filter(e=>e.title.toLowerCase().includes(p)||(e.description??"").toLowerCase().includes(p)):o;return e(n,{children:[t(Oe,{title:s("Insert prompt template"),children:t("button",{ref:l,type:"button",onClick:()=>c?g():d(!0),"aria-label":s("Insert prompt template"),"aria-haspopup":"menu","aria-expanded":c,className:"w-7 h-7 flex items-center justify-center rounded-lg transition-colors "+(c?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10":"text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10"),children:t(Me,{size:15})})}),e(Be,{open:c,onClose:g,anchorRef:l,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:s("Insert prompt template")}),o.length>5&&t("div",{className:"px-3 pb-2 pt-1",children:t("input",{autoFocus:!0,type:"text",value:h,onChange:e=>u(e.target.value),onKeyDown:e=>{"Escape"===e.key&&g()},placeholder:s("Search prompts..."),"aria-label":s("Search prompts..."),className:"w-full h-7 px-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[0===m.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:s("No prompt matches")}),m.map(n=>e("button",{type:"button",onClick:()=>{i(n.content),g()},className:"w-full px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t("div",{className:"text-[0.8125rem] text-gray-900 dark:text-white truncate",children:n.title}),n.description&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:n.description})]},n.id))]})]})]})},Ze=({quota:n,t:r})=>{const{used:a,limit:o,period:i}=n;if(null===o)return t(Oe,{title:i?`${r("Usage")} · ${i}`:r("Usage"),children:t("span",{className:"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30",children:v(a)})});const s=o>0?Math.min(a/o,1):1,l=!(o>0)||a>=o,c=s>=.75,d=l?"bg-red-500":c?"bg-amber-500":"bg-[var(--chat-accent)]/60",h=l?"text-red-500 dark:text-red-400":c?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",u=`${v(a)}/${v(o)}`,g=[r(l?"Quota reached":"Quota"),i].filter(Boolean).join(" · ");return t(Oe,{title:g,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${g} ${u}`,children:[t("span",{className:"h-1 w-10 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:t("span",{className:`block h-full rounded-full transition-[width] duration-300 ${d}`,style:{width:100*s+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${h}`,children:u})]})})},Xe=({inputValue:s,onInputChange:l,onSend:c,onStop:d,isLoading:h,canSteer:u=!1,attachedFiles:g=[],onFileAdd:p,onFileRemove:m,onPaste:f,t:x,mode:w,separatorColor:y,prompts:v,quota:b,contextUsage:k,composerToolbar:N})=>{const C=a(null),S=a(null),_=function(e){const[t,n]=r(!1),[s,l]=r(""),c=a(null),d=a(!1),h=a(e);h.current=e;const u=null!==Pe();i(()=>{const e=Pe();if(!e)return;const t=new e;return t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US",t.onresult=e=>{let t="",n="";for(let r=e.resultIndex;r<e.results.length;r++){const a=e.results[r];a.isFinal?n+=a[0].transcript:t+=a[0].transcript}n?(h.current(n),l("")):l(t)},t.onerror=()=>{d.current=!1,n(!1),l("")},t.onend=()=>{if(d.current)try{return void t.start()}catch{}n(!1),l("")},c.current=t,()=>{d.current=!1,c.current=null;try{t.stop()}catch{}}},[]);const g=o(()=>{d.current=!1,l(""),n(!1);try{c.current?.stop()}catch{}},[]);return{supported:u,listening:t,interim:s,toggle:o(()=>{const e=c.current;if(e)if(d.current)g();else try{d.current=!0,e.start(),n(!0)}catch{d.current=!1,n(!1)}},[g]),stop:g}}(e=>{l(s.trim()?`${s.trimEnd()} ${e}`:e)}),I=Boolean(v&&v.length>0||b||k||N||_.supported),L=Boolean(p&&m&&f),$=s.trim()||L&&g.length>0,M=L&&g.some(e=>"pending"===e.uploadStatus),z=$&&!M,A=L&&g.length>0,T=h&&u&&Boolean(s.trim())&&!A,E=x(h&&u&&!A?"Enter to send now · Esc to stop":h&&A?"Attachments wait for the current response":"Uses AI. Verify results.");return e("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-white/10 "+("floating"===w?"rounded-b-xl":""),style:y?{borderTopColor:y,borderTopWidth:1}:void 0,children:[L&&g.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:g.map((n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] "+("error"===n.uploadStatus?"border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400":"pending"===n.uploadStatus?"border-gray-200 dark:border-white/10 text-gray-400 dark:text-white/40":"border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60"),children:["pending"===n.uploadStatus?t("span",{className:"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin"}):t(pe,{size:14}),n.name,"error"===n.uploadStatus&&t("span",{className:"text-red-400 text-[0.6rem]",children:"✕"}),t("button",{type:"button",onClick:()=>m?.(r),className:"ml-0.5 text-gray-400 dark:text-white/30 hover:text-gray-600 dark:hover:text-white/60",children:"×"})]},r))}),e("div",{className:"flex items-center border border-gray-200 dark:border-white/10 rounded-xl px-2 py-1 transition-colors focus-within:border-[var(--chat-accent)]",children:[L&&e(n,{children:[t("input",{ref:C,type:"file",multiple:!0,hidden:!0,onChange:e=>{p?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>C.current?.click(),className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 mr-0.5 transition-colors",children:t(te,{size:18})})]}),t("textarea",{ref:S,placeholder:x("Ask a question..."),value:s,onChange:e=>{l(e.target.value);const t=e.target;t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,120)}px`},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),_.stop(),c()),"Escape"===e.key&&h&&(e.preventDefault(),d())},onPaste:f,rows:1,className:"flex-1 bg-transparent border-none outline-hidden resize-none text-[0.8125rem] py-1.5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 filigran-chat-scrollable",style:{maxHeight:120}}),T&&t(Oe,{title:x("Send now"),children:t("button",{type:"button",onClick:c,"aria-label":x("Send now"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Le,{size:18})})}),t(Oe,{title:h?x("Stop generating"):M?x("Files uploading..."):"",children:t("button",{type:"button",onClick:h?d:c,disabled:!h&&!z,className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 "+(h?"text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5":z?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20":"text-gray-300 dark:text-white/20 cursor-not-allowed"),children:t(h?ze:Le,{size:18})})})]}),I&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[v&&v.length>0&&t(Ke,{prompts:v,onPick:e=>{l(s.trim()?`${s.trimEnd()}\n\n${e}`:e),S.current?.focus()},t:x}),_.supported&&t(Oe,{title:_.listening?x("Stop dictation"):x("Dictate a message"),children:t("button",{type:"button",onClick:_.toggle,"aria-label":_.listening?x("Stop dictation"):x("Dictate a message"),"aria-pressed":_.listening,className:"w-7 h-7 flex items-center justify-center rounded-lg transition-colors "+(_.listening?"text-red-500 bg-red-500/10 hover:bg-red-500/20":"text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10"),children:_.listening?t(_e,{size:15}):t(Se,{size:15})})}),_.interim&&t("span",{className:"text-[0.7rem] italic text-gray-400 dark:text-white/30 truncate max-w-[45%]",children:_.interim}),N,(k||b)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[k&&t(Je,{usage:k,t:x}),b&&t(Ze,{quota:b,t:x})]})]}),t("p",{className:"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70",children:E})]})};function Qe(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function Ye(e){const t=a(null);return i(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const et="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",tt=({proposal:n,decision:a,onDecide:o,disabled:i,t:s})=>{const[l,d]=r(!1),[h,u]=r(""),g=c(),p=Ye(l),m=a?.verdict,f=Object.keys(n.arguments??{}),x=e=>{o({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&h.trim()?{rejectionReason:h.trim()}:{}})};return e("div",{className:"rounded-lg border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2",children:[e("div",{className:"flex items-start justify-between gap-2",children:[e("div",{className:"min-w-0 flex items-start gap-2",children:[t(Re,{size:13,className:"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400"}),e("div",{className:"min-w-0",children:[t("p",{className:"truncate font-mono text-xs text-gray-800 dark:text-white/85",children:n.toolName}),n.toolDescription&&t("p",{className:"mt-0.5 text-[0.7rem] text-gray-600 dark:text-white/60",children:n.toolDescription}),n.source&&t("p",{className:"mt-0.5 text-[0.65rem] text-gray-400 dark:text-white/35",children:n.source})]})]}),m&&t("span",{className:"shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===m?"bg-red-500/15 text-red-600 dark:text-red-300":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"),children:s("reject"===m?"Declined":"approve_always"===m?"Always allowed":"Approved")})]}),f.length>0&&t("div",{className:"flex flex-col gap-1.5",children:f.map(r=>{const a=function(e,t){const n=e?.properties;if(!n||"object"!=typeof n)return{};const r=n[t];if(!r||"object"!=typeof r)return{};const a=r;return{description:"string"==typeof a.description?a.description:void 0,type:"string"==typeof a.type?a.type:void 0}}(n.inputSchema,r);return e("div",{className:"text-[0.7rem]",children:[e("div",{className:"flex flex-wrap items-baseline gap-1.5",children:[t("span",{className:"font-mono text-gray-700 dark:text-white/75",children:r}),a.description&&e("span",{className:"text-gray-500 dark:text-white/45",children:["— ",a.description]})]}),t("pre",{className:"mt-0.5 whitespace-pre-wrap break-all font-mono text-gray-600 dark:text-white/60",children:Qe(n.arguments?.[r])})]},r)})}),!m&&l&&e("div",{ref:p,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:g,className:"text-[0.7rem] text-gray-500 dark:text-white/45",children:s("Why not? The agent sees this and can adapt (optional)")}),t("textarea",{id:g,autoFocus:!0,rows:2,value:h,onChange:e=>u(e.target.value),placeholder:s("e.g. wrong environment — use staging instead"),className:"w-full resize-none rounded-md border border-gray-200 bg-white px-2 py-1 text-[0.7rem] text-gray-800 outline-none focus:border-[var(--chat-accent)]/50 dark:border-white/10 dark:bg-white/[0.03] dark:text-white/85"}),e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",disabled:i,onClick:()=>x("reject"),className:`${et} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(Ue,{size:13}),s("Decline this call")]}),t("button",{type:"button",disabled:i,onClick:()=>{d(!1),u("")},className:`${et} text-gray-500 hover:bg-gray-100 dark:text-white/50 dark:hover:bg-white/5`,children:s("Back")})]})]}),!m&&!l&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:i,onClick:()=>d(!0),className:`${et} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(Ue,{size:13}),s("No")]}),e("button",{type:"button",disabled:i,onClick:()=>x("approve"),className:`${et} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(oe,{size:13}),s("Yes")]}),t("button",{type:"button",disabled:i,onClick:()=>x("approve_always"),title:s("Also applies to your scheduled runs, until you revoke it"),className:`${et} border border-gray-200 text-gray-700 hover:bg-gray-100 dark:border-white/15 dark:text-white/70 dark:hover:bg-white/5`,children:s("Yes, always")})]})]})},nt=({proposals:n,onSubmit:o,isSubmitting:s,error:l,t:c})=>{const[d,h]=r({}),u=a(!1),[g,p]=r(!1);i(()=>{l&&(u.current=!1,p(!1))},[l]);const m=s||g,f=e=>{u.current||s||(u.current=!0,p(!0),o(e))},x=n.filter(e=>d[e.toolCallId]).length,w=x===n.length&&n.length>0,y=Object.values(d).some(e=>"approve_always"===e.verdict),v=Ye(y),b=Ye(!0);return e("div",{ref:b,className:"flex flex-col gap-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.02] p-3",children:[e("p",{className:"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300",children:[t(Y,{size:13,className:"mt-0.5 shrink-0"}),1===n.length?c("The agent needs your approval to run a tool:"):c("The agent needs your approval to run these tools:")]}),n.map(e=>t(tt,{proposal:e,decision:d[e.toolCallId],disabled:m,t:c,onDecide:e=>{const t={...d,[e.toolCallId]:e};h(t);const r=n.map(e=>t[e.toolCallId]);r.every(Boolean)&&!r.some(e=>"approve_always"===e.verdict)&&f(r)}},e.toolCallId)),y&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(Y,{size:13,className:"mt-0.5 shrink-0"}),c("“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.")]}),l&&t("p",{className:"text-[0.7rem] text-red-600 dark:text-red-300",children:l}),e("div",{ref:v,className:"flex items-center justify-between gap-2",children:[t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40",children:n.length>1?`${x}/${n.length} ${c("decided")}`:""}),t("button",{type:"button",disabled:!w||m,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${et} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:c(m?"Sending…":"Confirm")})]})]})},rt=({src:n,alt:o,onClose:s,t:l})=>{const c=a(null),d=a(null),[u,g]=r(null);return i(()=>{g(y(c.current))},[]),i(()=>{const e=e=>{"Escape"===e.key&&s()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[s]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return d.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]),t("span",{ref:c,className:"hidden",children:u&&h(e("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4",onClick:s,role:"dialog","aria-modal":"true","aria-label":l("Image preview"),children:[t("button",{ref:d,type:"button",onClick:s,"aria-label":l("Close"),className:"absolute top-4 right-4 rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(se,{size:20})}),t("img",{src:n,alt:o,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},at=({src:a,alt:o,requestHeaders:s,maxHeightClass:l="max-h-[400px]",t:c})=>{const d=!!s&&Object.keys(s).length>0&&(e=>!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(a),[h,u]=r(null),[g,p]=r(!1),[m,f]=r(!1);i(()=>{if(!d)return;let e=!1,t=null;return fetch(a,{credentials:"include",headers:{...s}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(n=>{e||(t=URL.createObjectURL(n),u(t))}).catch(()=>{e||p(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,a,s]);const x=d?h:a;return g?t("p",{className:"my-2 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:c("Image could not be loaded")}):x?e(n,{children:[e("span",{className:"group/img relative my-3 inline-block max-w-full rounded-lg border border-gray-200 p-1 transition-colors hover:border-[var(--chat-accent)]/40 dark:border-white/10",children:[t("img",{src:x,alt:o,loading:"lazy",onClick:()=>f(!0),onError:()=>p(!0),className:`max-w-full cursor-zoom-in rounded-md object-contain ${l}`}),t("button",{type:"button",onClick:()=>f(!0),"aria-label":c("Expand image"),className:"absolute top-2 right-2 rounded-md bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100",children:t(Ce,{size:14})})]}),m&&t(rt,{src:x,alt:o,onClose:()=>f(!1),t:c})]}):e("span",{className:"my-3 inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 dark:border-white/10",children:[t(be,{size:14,className:"shrink-0 animate-pulse text-[var(--chat-accent)]"}),t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40",children:c("Loading image…")})]})},ot=["Crunching the data","Connecting the dots","Consulting the sources","Thinking it through","Reticulating splines","Analyzing the details","Almost there","Putting it together","Polishing the answer","Wrapping things up"],it="filigranChatMiniGame",st=e=>`700 ${e}px 'Courier New', ui-monospace, monospace`,lt=[["00100000100","00010001000","00111111100","01101110110","11111111111","10111111101","10100000101","00011011000"],["00100000100","10010001001","10111111101","11101110111","11111111111","00111111100","00100000100","01000000010"]];function ct(){if("undefined"==typeof window)return!0;try{return"off"!==window.localStorage.getItem(it)}catch{return!0}}function dt(e,t,n){const r=e.getContext("2d");if(!r)return()=>{};const a=r;let o=0,i=0;let s=13,l="#7b5cff",c=0,d=[],h=-1,u=[],g=[],p=0,m=0,f=0,x=0,w=0,y=performance.now();const v=Math.round(29.4);function b(e){for(let t=e;t<d.length;t++)if(d[t].alive)return t;return-1}function k(){if(i<=0)return;const e=t[c%t.length]||"";for(n(c%t.length),s=13;s>=8&&(a.font=st(s),!(a.measureText(e).width<=i-16));s--);a.font=st(s);const r=Array.from(e).map(e=>a.measureText(e).width),o=r.reduce((e,t)=>e+t,0);let l=(i-o)/2;d=Array.from(e).map((e,t)=>{const n=l;return l+=r[t],{char:e,x:n,w:r[t],alive:e.trim().length>0}}),h=b(0),u=[],g=[],m=0,f=0,p<=0&&(p=i/2)}function N(e){return d[e].x+d[e].w/2}function C(){const t=e.getBoundingClientRect(),n=window.devicePixelRatio||1;i=t.width,e.width=Math.max(1,Math.round(i*n)),e.height=Math.round(70*n),a.setTransform(n,0,0,n,0,0),function(){const t=getComputedStyle(e).getPropertyValue("--chat-accent").trim();t&&(l=t)}(),k()}let S=null;return"undefined"!=typeof ResizeObserver?(S=new ResizeObserver(C),S.observe(e)):window.addEventListener("resize",C),C(),o=requestAnimationFrame(function e(t){const n=t-y;y=t,!document.hidden&&i>0&&(function(e){const t=Math.min(e/16.6667,3);if(w+=e,w>320&&(w=0,x^=1),-1===h)0===f?f=performance.now():performance.now()-f>650&&(c++,k());else{const n=N(h);p+=(n-p)*Math.min(.16*t,1),m-=e,0===u.length&&m<=0&&Math.abs(p-n)<4&&(u.push({x:p,y:50}),m=130)}for(let e=u.length-1;e>=0;e--)if(u[e].y-=2.6*t,u[e].y<=v){if(-1!==h){const e=N(h);d[h].alive=!1;for(let t=0;t<7;t++){const n=2*Math.PI*t/7+Math.random(),r=.6+1.4*Math.random();g.push({x:e,y:v,vx:Math.cos(n)*r,vy:Math.sin(n)*r,life:1})}h=b(h+1)}u.splice(e,1)}for(let e=g.length-1;e>=0;e--){const n=g[e];n.x+=n.vx*t,n.y+=n.vy*t,n.life-=.045*t,n.life<=0&&g.splice(e,1)}}(n),function(){a.clearRect(0,0,i,70),a.fillStyle=l,a.font=st(s),a.textBaseline="middle",a.globalAlpha=.85;for(const e of d)e.alive&&a.fillText(e.char,e.x,v);a.globalAlpha=1;for(const e of u)a.fillRect(e.x-1,e.y,2,7);for(const e of g)a.globalAlpha=.9*Math.max(e.life,0),a.fillRect(e.x-1.5,e.y-1.5,3,3);a.globalAlpha=1;const e=lt[x],t=Math.round(p-11);for(let n=0;n<e.length;n++){const r=e[n];for(let e=0;e<r.length;e++)"1"===r[e]&&a.fillRect(t+2*e,50+2*n,2,2)}}()),o=requestAnimationFrame(e)}),()=>{cancelAnimationFrame(o),S?S.disconnect():window.removeEventListener("resize",C)}}const ht=({t:n,enabled:o=!0})=>{const s=l(()=>ot.map(e=>n(e)),[n]),c=function(){const[e,t]=r(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return i(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=()=>t(e.matches);return"function"==typeof e.addEventListener?(e.addEventListener("change",n),()=>e.removeEventListener("change",n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}(),[d,h]=r(ct),[u,g]=r(0),p=a(null),m=a(null),f=o&&d&&!c;if(i(()=>{const e=function(e){let t=e?.parentElement??null;for(;t;){const e=getComputedStyle(t).overflowY;if(("auto"===e||"scroll"===e)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}(m.current);if(!e)return;e.scrollHeight-e.scrollTop-e.clientHeight<=140&&(e.scrollTop=e.scrollHeight)},[]),i(()=>{if(f||!o)return;const e=window.setInterval(()=>g(e=>(e+1)%s.length),2600);return()=>window.clearInterval(e)},[f,o,s.length]),i(()=>{if(!f)return;const e=p.current;return e?dt(e,s,g):void 0},[f,s]),!o)return null;const x=s[u%s.length];return e("div",{ref:m,className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:x}),e("div",{className:"relative overflow-hidden rounded-md bg-[var(--chat-accent)]/[0.03]",style:c?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[f?t("canvas",{ref:p,"aria-hidden":!0,className:"block w-full",style:{height:70}}):t("div",{className:"flex items-center",style:{height:70},children:e("span",{className:"px-3 text-xs text-gray-500 dark:text-white/45",style:c?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[x,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(c?"":"animate-pulse")})]},x)}),!c&&t("button",{type:"button",onClick:()=>{const e=!d;h(e),function(e){try{window.localStorage.setItem(it,e?"on":"off")}catch{}}(e)},"aria-pressed":d,"aria-label":n(d?"Turn off the waiting mini-game":"Turn on the waiting mini-game"),title:n(d?"Turn off the waiting mini-game":"Turn on the waiting mini-game"),className:"absolute top-1 right-1 rounded p-1 transition-opacity "+(d?"text-[var(--chat-accent)] opacity-50 hover:opacity-100":"text-gray-400 dark:text-white/40 opacity-40 hover:opacity-90"),children:t(we,{size:13})})]})]})};function ut(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/#{1,6}\s+/g,"").replace(/^[ \t]*[-*>]+[ \t]*/gm,"").replace(/[ \t]+/g," ").replace(/\n{3,}/g,"\n\n").trim()}function gt({content:e}){const n=a(null),[o,s]=r(!1),l=ut(e);return i(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight,s(e.scrollHeight>e.clientHeight+1))},[l]),l.length<3?null:t("div",{className:"ml-11 mt-2.5 max-w-[75%] rounded-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3",style:{animation:"reasoningGlow 3s ease-in-out infinite, chat-fade-in 0.5s ease-out"},children:t("div",{ref:n,className:"max-h-40 overflow-hidden"+(o?" [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)] [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]":""),children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-xs leading-5 text-gray-500 dark:text-white/45",children:l})})})}function pt(e){const t=Math.floor(e);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}const mt=({agentStatus:o,logoIcon:s,t:l,miniGameEnabled:c=!0})=>{const{label:d,StatusIcon:h,showDots:u}=function(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:re,showDots:!1};switch(e.status){case"tool_start":{const n=e.tools??[],r=n.map(e=>e.toLowerCase());if(r.some(e=>"spawn_background_task"===e)){const e=n.filter(e=>"spawn_background_task"===e).length;return{label:e>1?`${t("Delegating")} ${e} ${t("tasks")}…`:`${t("Delegating task")}…`,StatusIcon:De,showDots:!1}}if(r.some(e=>"check_task_status"===e)){const e=n.filter(e=>"check_task_status"===e).length,r=e>1?`${e} ${t("background tasks")}`:t("background task");return{label:`${t("Waiting for")} ${r}…`,StatusIcon:Me,showDots:!1}}if(r.some(e=>"get_task_result"===e)){const e=n.filter(e=>"get_task_result"===e).length,r=e>1?`${e} ${t("tasks")}`:t("task");return{label:`${t("Collecting results from")} ${r}…`,StatusIcon:Me,showDots:!1}}let a,o=Re;if(r.some(e=>e.includes("search")||e.includes("list"))?o=Ie:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?o=ce:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?o=Ne:r.some(e=>e.includes("code")||e.includes("execute"))?o=Ae:r.some(e=>e.includes("web")||e.includes("browse"))&&(o=ye),n.length>0){const e=n.map(e=>e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())),t=Array.from(new Set(e));a=1===t.length?`${t[0]}…`:`${t[0]} (+${t.length-1} more)…`}else a=t("Using tools…");return{label:a,StatusIcon:o,showDots:!1}}case"awaiting_approval":return{label:t("Waiting for your approval…"),StatusIcon:Y,showDots:!1};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:Me,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:Me,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:re,showDots:!0};case"consulting":{const n=e.tools?.[0]??"agent";return{label:`${t("Consulting")} ${n}…`,StatusIcon:De,showDots:!1}}case"delegating":{const n=e.tools?.filter(e=>"spawn_background_task"===e).length??0;return{label:n>1?`${t("Delegating")} ${n} ${t("tasks")}…`:`${t("Delegating task")}…`,StatusIcon:De,showDots:!1}}case"polling":{const n=e.tools?.filter(e=>"check_task_status"===e).length??0,r=n>1?`${n} ${t("background tasks")}`:t("background task");return{label:`${t("Waiting for")} ${r}…`,StatusIcon:Me,showDots:!1}}case"collecting":{const n=e.tools?.filter(e=>"get_task_result"===e).length??0,r=n>1?`${n} ${t("tasks")}`:t("task");return{label:`${t("Collecting results from")} ${r}…`,StatusIcon:Me,showDots:!1}}case"transferring":{const n=e.tools?.[0]??"agent";return{label:`${t("Transferring to")} ${n}…`,StatusIcon:ge,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:re,showDots:!1}}}(o,l),g=o?.thinkingContent,p=o?.elapsedStartMs,[m,f]=r(()=>Date.now());i(()=>{if(null==p)return;f(Date.now());const e=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(e)},[p]);const x=null!=p?Math.max(0,(m-p)/1e3):o?.elapsedS,w="number"==typeof x&&x>=15,y=function(e,t,n){const[o,s]=r(!1),l=a(e),c=l.current!==e;return i(()=>{if(l.current=e,s(!1),!n)return;const r=window.setTimeout(()=>s(!0),t);return()=>window.clearTimeout(r)},[e,t,n]),n&&o&&!c}(g?.length??0,5e3,c),v=c&&y;return e(n,{children:[e("div",{className:"flex gap-3 items-center justify-start",children:[t("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:s})}),e("div",{className:"rounded-lg bg-gray-50 dark:bg-white/[0.03] px-4 py-3 relative overflow-hidden",children:[t("div",{className:"absolute inset-0 bg-gradient-to-r from-[var(--chat-accent)]/[0.03] via-transparent to-[var(--chat-accent)]/[0.03] animate-pulse pointer-events-none"}),e("div",{className:"relative flex items-center gap-2.5",children:[u?t("div",{className:"flex gap-[3px] items-center h-3.5 w-3.5 justify-center",children:[0,.15,.3].map((e,n)=>t("span",{className:"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50",style:{animation:`chat-dot 1s ease-in-out infinite ${e}s`}},n))}):t(h,{size:14,className:"text-[var(--chat-accent)] animate-pulse transition-all duration-300"}),t("span",{className:"text-sm text-gray-500 dark:text-white/50 transition-all duration-300",children:d}),w&&t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:pt(x)})]})]})]}),g&&!v?t(gt,{content:g}):v?t(ht,{t:l,enabled:c}):null]})},ft=e=>{if(!e)return!1;if(e.startsWith("//"))return!1;return!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e)},xt=d(({content:a,onRelativeLinkClick:o,requestHeaders:i,t:s=w})=>{const[c,d]=r(null),h=l(()=>{return function(e){if(!e)return e;const t=e.split("\n"),n=/^(\s*)(`{3,})(.*)$/,r=/^(markdown|md|mdx|markup)\b/i;let a=-1;for(let e=0;e<t.length;e++){const o=t[e].match(n);if(o&&3===o[2].length&&r.test(o[3].trim())){a=e;break}}if(-1===a)return e;let o=3,i=0,s=-1;for(let e=a+1;e<t.length;e++){const r=t[e].match(n);r&&(i++,o=Math.max(o,r[2].length),""===r[3].trim()&&(s=e))}if(0===i)return e;const l="`".repeat(Math.max(o+1,4)),c=t[a].match(n);if(t[a]=`${c[1]}${l}${c[3]}`,s>a){const e=t[s].match(n);t[s]=`${e[1]}${l}`}return t.join("\n")}(function(e){if(!e||-1===e.indexOf("|"))return e;const t=e.split("\n"),n=e=>{let t=e.trim();t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=[];let r="";for(let e=0;e<t.length;e++){const a=t[e];"\\"===a&&e+1<t.length?(r+=a+t[e+1],e++):"|"===a?(n.push(r),r=""):r+=a}return n.push(r),n},r=e=>e.includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e),a=e=>{const t=e.trim(),n=t.startsWith(":"),r=t.endsWith(":");return n&&r?":---:":r?"---:":n?":---":"---"},o=/^\s*(?:(?:>\s?)|(?:[-*+]\s+)|(?:\d{1,9}[.)]\s+))*(`{3,}|~{3,})(.*)$/;let i=null,s=0;const l=/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/;for(let e=0;e<t.length-1;e++){const c=t[e].match(o);if(c){const e=c[1];null===i?(i=e[0],s=e.length):e[0]===i&&e.length>=s&&""===c[2].trim()&&(i=null,s=0);continue}if(null!==i)continue;const d=t[e],h=t[e+1];if(!d.includes("|")||r(d)||!r(h))continue;const u=d.match(l),g=u?u[0].length:d.length-d.trimStart().length,p=u?" ".repeat(g):d.slice(0,g),m=n(d.slice(g)).length,f=n(h);if(m<2||f.length===m)continue;const x=[];for(let e=0;e<m;e++)x.push(f[e]?a(f[e]):"---");t[e+1]=`${p}| ${x.join(" | ")} |`}return t.join("\n")}(function(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("[")||t.startsWith("```"))return e;try{return JSON.parse(t),"```json\n"+t+"\n```"}catch{return e}}((e=a).includes("![")?e.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>``):e)));var e},[a]);return t(u,{remarkPlugins:[g,p],urlTransform:x,components:{p:({children:e})=>t("p",{className:"mb-3 last:mb-0 leading-7 break-words text-[0.8125rem] text-gray-900 dark:text-white/90",children:e}),pre:({children:e})=>t(n,{children:e}),code:({className:n,children:r})=>{const a=/language-(\w+)/.exec(n||""),o=String(r).replace(/\n$/,"");return a||o.includes("\n")?e("div",{className:"my-3 rounded-lg border border-gray-200 dark:border-white/10 overflow-hidden bg-gray-50 dark:bg-white/[0.03]",children:[e("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-gray-200 dark:border-white/10 bg-gray-100 dark:bg-white/[0.03]",children:[t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 font-mono",children:a?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>{return e=o,navigator.clipboard.writeText(e),d(e),void setTimeout(()=>d(null),2e3);var e},"aria-label":s(c===o?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors",children:c===o?t(oe,{size:14,className:"text-green-500"}):t(le,{size:14,className:"text-gray-400 dark:text-white/40"})})]}),t("pre",{className:"m-0 px-3 py-2 overflow-x-auto",children:t("code",{className:"font-mono text-xs leading-[1.7] text-gray-800 dark:text-white/90 whitespace-pre",children:o})})]}):t("code",{className:"bg-gray-100 dark:bg-white/[0.08] px-1.5 py-0.5 rounded-sm font-mono text-xs text-[var(--chat-accent)]",children:r})},ul:({children:e})=>t("ul",{className:"list-disc pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),ol:({children:e})=>t("ol",{className:"list-decimal pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),li:({children:e})=>t("li",{className:"leading-7 break-words",children:e}),strong:({children:e})=>t("strong",{className:"font-semibold text-gray-900 dark:text-white",children:e}),em:({children:e})=>t("em",{className:"italic",children:e}),hr:()=>t("hr",{className:"my-4 border-gray-200 dark:border-white/10"}),blockquote:({children:e})=>t("blockquote",{className:"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 rounded-r-md italic text-gray-500 dark:text-white/60",children:e}),a:({href:e,children:n})=>{const r=(e=>{if(!e)return null;if(ft(e))return e;if("undefined"==typeof window)return null;try{const t=new URL(e,window.location.href);if(("http:"===t.protocol||"https:"===t.protocol)&&t.origin===window.location.origin)return`${t.pathname}${t.search}${t.hash}`||"/"}catch{}return null})(e),a=null!==r&&!!o,i=!a&&!ft(e);return t("a",{href:e,onClick:e=>{a&&(e.preventDefault(),o(r))},target:i?"_blank":void 0,rel:i?"noopener noreferrer":void 0,className:"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125",children:n})},img:({src:e,alt:n})=>"string"==typeof e&&e?t(at,{src:e,alt:n||"",requestHeaders:i,t:s}):null,h1:({children:e})=>t("h1",{className:"mt-4 first:mt-0 mb-2 font-bold text-base text-gray-900 dark:text-white",children:e}),h2:({children:e})=>t("h2",{className:"mt-3 first:mt-0 mb-2 font-bold text-[0.9rem] text-gray-900 dark:text-white",children:e}),h3:({children:e})=>t("h3",{className:"mt-3 first:mt-0 mb-1.5 font-semibold text-[0.85rem] text-gray-900 dark:text-white",children:e}),table:({children:e})=>t("div",{className:"my-3 overflow-x-auto rounded-lg border border-gray-200 dark:border-white/10",children:t("table",{className:"w-full border-collapse text-xs",children:e})}),tr:({children:e})=>t("tr",{className:"transition-colors hover:bg-gray-50 dark:hover:bg-white/[0.02]",children:e}),th:({children:e})=>t("th",{className:"px-3 py-2 text-left font-semibold bg-gray-50 dark:bg-white/[0.04] border-b border-gray-200 dark:border-white/10 text-gray-900 dark:text-white",children:e}),td:({children:e})=>t("td",{className:"px-3 py-2 border-b border-gray-200 dark:border-white/10 text-gray-700 dark:text-white/80",children:e})},children:h})});xt.displayName="MarkdownMessage";function wt(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function yt(e){return e.replace(/_/g," ")}const vt=({entry:n,index:a,t:o})=>{const[i,s]=r(!1),c=l(()=>wt(n.input),[n.input]),d=l(()=>wt(n.output),[n.output]),h=!!c&&"{}"!==c;return e("div",{className:"border border-gray-200 dark:border-white/[0.06] rounded-md overflow-hidden",children:[e("button",{type:"button",onClick:()=>s(e=>!e),"aria-expanded":i,className:"w-full flex items-center gap-2.5 px-3 py-2 hover:bg-gray-50 dark:hover:bg-white/[0.03] transition-colors text-left",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:a+1}),n.success?t(ae,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(Ue,{size:12,className:"shrink-0 text-red-500 dark:text-red-400"}),t("span",{className:"flex-1 min-w-0 text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono",children:yt(n.name)}),t(ie,{size:14,className:"shrink-0 text-gray-400 dark:text-white/50 transition-transform duration-200 "+(i?"rotate-180":"")})]}),i&&e("div",{className:"border-t border-gray-200 dark:border-white/[0.06]",children:[h&&e("div",{className:"px-3 py-2 border-b border-gray-100 dark:border-white/[0.04] bg-gray-50/50 dark:bg-white/[0.01]",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium",children:o("Input")}),t("pre",{className:"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable",children:c})]}),e("div",{className:"px-3 py-2 bg-gray-50/50 dark:bg-white/[0.01]",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium",children:o("Output")}),t("pre",{className:"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable",children:d||o("(no output)")})]})]})]})},bt=({msg:n,onClose:o,t:s})=>{const l=a(null),c=a(null),d=a(null),[u,g]=r(null);i(()=>{g(y(l.current))},[]),i(()=>{const e=e=>{if("Escape"===e.key)return void o();if("Tab"!==e.key)return;const t=d.current;if(!t)return;const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],a=n[n.length-1],i=document.activeElement;e.shiftKey?i!==r&&t.contains(i)||(e.preventDefault(),a.focus()):i!==a&&t.contains(i)||(e.preventDefault(),r.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return c.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]);const p=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,m=n.toolNames??[],f=n.iterations??1,x=n.transferChain??[],w=n.toolCallTrace??[],v=(n.reasoning??"").trim(),b=[f>1?`${f} ${s("iterations")}`:"",`${p} ${s(1===p?"tool call":"tool calls")}`,x.length>0?`${x.length} ${1===x.length?s("transfer"):s("transfers")}`:""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:u&&h(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:o,role:"presentation",children:e("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":s("Reasoning details"),onClick:e=>e.stopPropagation(),className:"w-full max-w-md max-h-full flex flex-col rounded-xl border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1e1e2e] shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]",children:[e("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-gray-200 dark:border-white/10",children:[e("div",{className:"flex items-center gap-2",children:[t(Re,{size:15,className:"text-[var(--chat-accent)]"}),t("span",{className:"flex-1 text-[0.875rem] font-semibold text-gray-900 dark:text-white",children:s("Reasoning details")}),t("button",{ref:c,type:"button",onClick:o,"aria-label":s("Close"),className:"w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(se,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] text-gray-500 dark:text-white/40",children:b.join(" · ")})]}),e("div",{className:"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3",children:[n.isTruncated&&e("div",{className:"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90",children:[t(Y,{size:14,className:"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400"}),e("span",{children:[t("span",{className:"font-semibold",children:s("Turn limit reached.")})," ",s("The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.")]})]}),v&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(re,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:s("Model reasoning")})]}),t("div",{className:"rounded-md border border-gray-200 dark:border-white/[0.06] bg-gray-50/50 dark:bg-white/[0.01] px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable",children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 text-gray-500 dark:text-white/45",children:ut(v)})})]}),w.length>0?t("div",{className:"flex flex-col gap-1.5",children:w.map((e,n)=>t(vt,{entry:e,index:n,t:s},`${e.name}-${n}`))}):m.length>0&&t("div",{children:m.map((n,r)=>e("div",{className:"flex items-center gap-3 py-2 border-b border-gray-100 dark:border-white/[0.04] last:border-0",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),t(Re,{size:12,className:"shrink-0 text-gray-400 dark:text-white/50"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono",children:yt(n)})]},`${n}-${r}`))}),x.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(ee,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:s("Transfer chain")})]}),t("div",{className:"flex items-center gap-1.5 flex-wrap",children:x.map((n,r)=>e("div",{className:"flex items-center gap-1.5",children:[r>0&&t("span",{className:"text-gray-300 dark:text-white/30 text-[0.72rem]",children:"→"}),e("span",{className:"inline-flex items-center gap-1 rounded-md bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]",children:[t(ne,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})};function kt(e){const t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return;const n=e.slice(t+1);return n.length<=8?n.toUpperCase():void 0}const Nt=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const Ct=({text:e,t:n})=>{const[a,o]=r(!1);return t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),o(!0),setTimeout(()=>o(!1),2e3)}catch{}},title:n(a?"Copied!":"Copy response"),"aria-label":n(a?"Copied!":"Copy response"),className:"p-1 rounded-lg transition-opacity "+(a?"opacity-100 text-green-500 dark:text-green-400":"opacity-0 group-hover/msg:opacity-100 focus-visible:opacity-100 hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]"),children:t(a?oe:le,{size:14})})},St=({value:r,onChange:a,t:o})=>{const i=e=>"p-1 rounded-lg transition-opacity "+(e?"opacity-100 text-[var(--chat-accent)]":"opacity-0 group-hover/msg:opacity-100 focus-visible:opacity-100 hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]");return e(n,{children:[t("button",{type:"button",onClick:()=>a("up"===r?null:"up"),title:o("Good response"),"aria-label":o("Good response"),"aria-pressed":"up"===r,className:i("up"===r),children:t(Ee,{size:14,filled:"up"===r})}),t("button",{type:"button",onClick:()=>a("down"===r?null:"down"),title:o("Bad response"),"aria-label":o("Bad response"),"aria-pressed":"down"===r,className:i("down"===r),children:t(Te,{size:14,filled:"down"===r})})]})},_t=d(({msg:n,isStreaming:a,agentName:o,logoIcon:i,onRelativeLinkClick:s,onDownloadFile:l,resolveAttachmentUrl:c,requestHeaders:d,feedback:h,onFeedbackChange:u,t:g})=>{const[p,m]=r(!1),f="assistant"===n.role,x=!n.content,w=(n,r)=>{const a=c&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&Nt.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&Nt.has(e.filename.slice(n+1).toLowerCase())}(n)?c(n):void 0;if(a)return t(at,{src:a,alt:n.filename,requestHeaders:d,maxHeightClass:"max-h-[200px]",t:g},r);const o="working_file"===n.fileTag,i=!(s=n.size)||s<=0?"":s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(0)} KB`:`${(s/1048576).toFixed(1)} MB`;var s;return e("button",{type:"button",onClick:()=>l?.(n),title:g("Download"),className:"group flex items-center gap-2 text-left rounded-lg border px-2.5 py-1.5 transition-colors cursor-pointer max-w-[90%] "+(o?"border-gray-200 dark:border-white/10 bg-transparent":"border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5"),children:[t("span",{className:"shrink-0 "+(o?"text-gray-400 dark:text-white/40":"text-[var(--chat-accent)]"),children:t(pe,{size:16})}),e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"truncate text-[0.75rem] text-gray-900 dark:text-white",children:n.filename}),(n.type||i)&&t("span",{className:"text-[0.65rem] text-gray-400 dark:text-white/40 uppercase",children:[n.type,i].filter(Boolean).join(" · ")})]}),t("span",{className:"shrink-0 text-gray-400 dark:text-white/30 group-hover:text-[var(--chat-accent)]",children:t(he,{size:15})})]},r)},y=(n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.7rem] text-gray-600 dark:text-white/60",children:[t(pe,{size:14}),n]},r),v=n.toolNames&&n.toolNames.length>0||!!(n.reasoning??"").trim()||n.toolCallTrace&&n.toolCallTrace.length>0||n.transferChain&&n.transferChain.length>0||n.isTruncated,b=f&&!x&&!a;return e("div",{className:"group/msg flex flex-col "+(f?"items-start":"items-end"),children:[f&&e("div",{className:"flex items-center gap-1.5 mb-1",children:[t("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3",children:i})}),t("span",{className:"font-semibold text-xs text-gray-900 dark:text-white",children:n.agentName??o})]}),!f&&((n.files?.length??0)>0||(n.attachments?.length??0)>0)&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end",children:(()=>{const e=[],t=new Set;return(n.files??[]).forEach((n,r)=>{!(!l||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(w({fileId:n.fileId,filename:n.name,type:kt(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(y(n.name,`file-${r}`))}),(n.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(l?w(n,`att-${n.fileId}-${r}`):y(n.filename,`att-${r}`)))}),e})()}),f?e("div",{className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=function(e){if(!e)return[];const t=[],n=/\[\[FILE:([^\]]+)\]\]/g;let r=0,a=n.exec(e);for(;null!==a;)a.index>r&&t.push({type:"text",value:e.slice(r,a.index)}),t.push({type:"file",fileId:a[1]}),r=n.lastIndex,a=n.exec(e);const o=e.slice(r).replace(N,"");return o&&t.push({type:"text",value:o}),t}(n.content),r=new Map((n.attachments??[]).map(e=>[e.fileId,e])),o=new Set,i=[];return e.forEach((e,n)=>{if("text"===e.type)e.value.trim()&&i.push(t("div",{className:"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7",children:t(xt,{content:e.value,onRelativeLinkClick:s,requestHeaders:d,t:g})},`t-${n}`));else if(l){const t=r.get(e.fileId);t&&(o.add(e.fileId),i.push(w(t,`f-${e.fileId}-${n}`)))}}),l&&(n.attachments??[]).forEach(e=>{o.has(e.fileId)||i.push(w(e,`orphan-${e.fileId}`))}),0!==i.length||a||i.push(t("span",{className:"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic",children:"..."},"empty")),i})(),!x&&a&&t("span",{className:"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse"})]}):t("div",{className:"max-w-[90%] px-3.5 py-2 rounded-[14px_14px_4px_14px] bg-[var(--chat-accent-dark)] text-white text-[0.8125rem] leading-6",children:n.content}),b&&e("div",{className:"mt-0.5 flex items-center gap-0.5 text-gray-400 dark:text-white/40",children:[t(Ct,{text:C(n.content),t:g}),u&&t(St,{value:h,onChange:e=>u(n.id,e,n),t:g}),v&&t("button",{type:"button",onClick:()=>m(e=>!e),className:"p-1 rounded-lg transition-opacity "+(n.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":"opacity-50 hover:opacity-100 hover:text-[var(--chat-accent)]"),title:n.isTruncated?g("Reasoning details — turn limit reached"):g("Reasoning details"),"aria-label":n.isTruncated?g("Reasoning details — turn limit reached"):g("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":p,children:n.isTruncated?t(Y,{size:14}):t(ke,{size:14})})]}),p&&t(bt,{msg:n,onClose:()=>m(!1),t:g})]})});_t.displayName="MessageRow";const It=({messages:n,isLoading:s,agentStatus:c,agentName:d,logoIcon:h,onRelativeLinkClick:u,onDownloadFile:g,resolveAttachmentUrl:p,requestHeaders:m,miniGameEnabled:f=!0,onMessageFeedback:x,isResumingAfterDecision:w,pendingApprovals:y,onSubmitApprovalDecisions:v,isSubmittingApproval:b,approvalError:k,t:N})=>{const C=a(null),[S,_]=r(150),[I,L]=r({});i(()=>{C.current?.scrollIntoView({behavior:"smooth"})},[n]);const $=c?.thinkingContent?.length??0;i(()=>{$&&C.current?.scrollIntoView({behavior:"instant"})},[$]);const M=n[0]?.id;i(()=>{_(150)},[M]);const z=n.length>S,A=l(()=>z?n.slice(n.length-S):n,[n,S,z]),T=o((e,t,n)=>{L(n=>{if(null!==t)return{...n,[e]:t};if(!(e in n))return n;const r={...n};return delete r[e],r}),x?.(e,t,n)},[x]);let E=null;if(s)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){E=n[e].id;break}const j=!!y?.length&&!!v;return e("div",{className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable",children:[z&&t("div",{className:"flex justify-center",children:e("button",{type:"button",onClick:()=>_(e=>e+50),className:"flex items-center gap-1.5 rounded-full border border-gray-200 dark:border-white/10 px-3 py-1 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]",children:[t(ie,{size:13,className:"rotate-180"}),N("Load earlier messages")]})}),A.map(e=>{const n=e.id===E;return"assistant"===e.role&&!e.content&&n?j?null:t("div",{children:t(mt,{agentStatus:c,logoIcon:h,t:N,miniGameEnabled:f})},e.id):t(_t,{msg:e,isStreaming:n,agentName:d,logoIcon:h,onRelativeLinkClick:u,onDownloadFile:g,resolveAttachmentUrl:p,requestHeaders:m,feedback:I[e.id]??null,onFeedbackChange:x?T:void 0,t:N},e.id)}),w&&!j&&t(mt,{agentStatus:c,logoIcon:h,t:N,miniGameEnabled:f}),j&&t(nt,{proposals:y,onSubmit:v,isSubmitting:b,error:k,t:N},y.map(e=>e.toolCallId).join("|")),t("div",{ref:C})]})},Lt=({firstName:r,logoIcon:a,promptSuggestions:o,onPromptClick:i,agentName:s,agentDescription:l,suggestionsLoading:c=!1,t:d})=>e("div",{className:"flex-1 flex flex-col items-center justify-center px-6 pb-8",children:[t("span",{className:"text-[var(--chat-accent)] mb-4 [&>svg]:w-12 [&>svg]:h-12 drop-shadow-[0_0_12px_var(--chat-accent-40)]",children:a}),t("h2",{className:"text-xl font-medium mb-1 text-center text-gray-900 dark:text-white",style:{fontFamily:'"Geologica", sans-serif',animation:"chat-fade-in 0.35s ease-out"},children:e(n,s?{children:[d("How can "),t("span",{className:"text-[var(--chat-accent)]",children:s}),d(" help you, "),r,"?"]}:{children:[d("How can I help you, "),r,"?"]})},s??"default"),l&&t("p",{className:"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 text-gray-500 dark:text-white/40",children:l}),!l&&t("span",{className:"mb-5"}),e("div",{className:"w-full max-w-[320px]",children:[t("span",{className:"block text-center mb-2 text-[0.65rem] tracking-[1.5px] uppercase text-[var(--chat-accent)] font-semibold",children:d("Suggestions")}),c?t("div",{"aria-hidden":!0,className:"space-y-1",children:[0,1,2].map(e=>t("div",{className:"h-8 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-100/50 dark:bg-white/[0.03] animate-pulse"},e))}):o.map(e=>t("button",{type:"button",onClick:()=>i(e),className:"w-full text-left text-[0.8125rem] text-gray-800 dark:text-white py-1.5 px-3 mb-1 rounded-lg border border-gray-200 dark:border-white/10 bg-transparent transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)]",children:d(e)},e))]})]}),$t=({conversations:n,loading:o,activeConversationId:i,collapsed:s,onToggleCollapsed:c,onSelect:d,onDelete:h,onRename:u,onNewChat:g,t:p})=>{const[m,f]=r(""),[x,w]=r(null),[y,v]=r(""),k=a(!1),N=()=>{if(k.current)return;k.current=!0;const e=x,t=y.trim();w(null),e&&t&&u?.(e,t)},C=l(()=>{const e=m.trim().toLowerCase();return e?n.filter(t=>(t.title||"").toLowerCase().includes(e)):n},[n,m]);return e("div",s?{className:"flex flex-col items-center gap-1 border-r border-gray-200 dark:border-white/10 px-2 py-3 shrink-0",children:[t(Oe,{title:p("Show conversations"),children:t("button",{type:"button",onClick:c,"aria-label":p("Show conversations"),"aria-expanded":!1,className:"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t($e,{size:17})})}),t(Oe,{title:p("New conversation"),children:t("button",{type:"button",onClick:g,"aria-label":p("New conversation"),className:"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t(ue,{size:17})})})]}:{className:"w-64 shrink-0 flex flex-col border-r border-gray-200 dark:border-white/10",children:[e("div",{className:"flex items-center gap-1 px-3 py-3",children:[e("button",{type:"button",onClick:g,className:"flex-1 flex items-center gap-2 rounded-lg border border-gray-200 dark:border-white/10 px-3 py-1.5 text-[0.8125rem] text-gray-700 dark:text-white/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors",children:[t(ue,{size:15}),p("New conversation")]}),t(Oe,{title:p("Hide conversations"),children:t("button",{type:"button",onClick:c,"aria-label":p("Hide conversations"),"aria-expanded":!0,className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t($e,{size:17})})})]}),n.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Ie,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40"}),t("input",{type:"text",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f("")},placeholder:p("Search conversations..."),"aria-label":p("Search conversations..."),className:"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable",children:[o&&0===n.length&&t("div",{className:"px-3 py-2",children:t(We,{size:16})}),!o&&0===n.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:p("No conversations yet")}),n.length>0&&0===C.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:p("No conversation matches")}),C.map(n=>{const r=n.conversationId===i,a=n.conversationId===x;return e("div",{role:"button",tabIndex:0,"aria-current":r,onClick:()=>d(n.conversationId),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),d(n.conversationId))},className:"group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors "+(r?"bg-[var(--chat-accent)]/10":"hover:bg-gray-100 dark:hover:bg-white/[0.06]"),children:[t("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg "+(r?"bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]":"bg-gray-100 dark:bg-white/[0.06] text-gray-400 dark:text-white/30"),children:t(ne,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[a?t("input",{autoFocus:!0,value:y,onChange:e=>v(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&N(),"Escape"===e.key&&(k.current=!0,w(null))},onBlur:N,"aria-label":p("Conversation title"),className:"w-full rounded-md bg-white dark:bg-white/10 px-1.5 py-0.5 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]"}):t("span",{className:"block truncate text-[0.8125rem] "+(r?"text-gray-900 dark:text-white":"text-gray-700 dark:text-white/70"),children:n.title||p("Untitled conversation")}),(n.agentName||n.updatedAt)&&!a&&e("span",{className:"block text-[0.65rem] text-gray-400 dark:text-white/30 truncate",children:[n.agentName,n.agentName&&n.updatedAt?" · ":"",n.updatedAt?b(n.updatedAt,p):""]})]}),!a&&e("span",{className:"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[u&&t("button",{type:"button",onClick:e=>{var t,r;e.stopPropagation(),t=n.conversationId,r=n.title||"",k.current=!1,w(t),v(r)},"aria-label":p("Rename conversation"),title:p("Rename conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(ue,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),h(n.conversationId)},"aria-label":p("Delete conversation"),title:p("Delete conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-red-500 dark:hover:text-red-400",children:t(je,{size:13})})]})]},n.conversationId)})]})]})},Mt=["Help me create a new simulation scenario","What are the latest attack patterns?","How do I configure detection rules?","Summarize my recent findings"],zt=({mode:n,onClose:s,onModeChange:c,topOffset:d=0,apiBaseUrl:h,apiEndpoints:u,agentDashboardUrl:g,user:p,t:f=w,accentColor:x="#7b5cff",logoIcon:y,promptSuggestions:v=Mt,draftBorderColor:b,resizable:k=!1,onWidthChange:N,onResizeStart:C,onResizeEnd:S,disableFileManagement:M=!1,onRelativeLinkClick:z,onDownloadError:A,maxFileCount:T,maxTotalSize:E,requestHeaders:j,pageContext:D,pushContentSelector:R,backendType:U="rest",miniGameEnabled:B=!0,notifyOnComplete:O=!0,onTaskComplete:V,onMessageFeedback:G,disableImagePreviews:J=!1,contextUsageEnabled:K=!0,composerToolbar:Y})=>{const[ee,te]=r(!1),{agents:ne,agentsLoading:re,agentsError:ae,selectedAgent:oe,agentMenuOpen:ie,setAgentMenuOpen:se,handleSwitchAgent:le}=H({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j}),{messages:ce,inputValue:he,setInputValue:ue,isLoading:ge,agentStatus:pe,attachedFiles:me,conversationId:fe,contextUsage:xe,transferredAgent:we,canSteer:ye,pendingApprovals:ve,isSubmittingApproval:be,approvalError:ke,submitApprovalDecisions:Ne,isResumingAfterDecision:Ce,historyReloadNonce:Se,historyLoadedRef:_e,conversationIdRef:Ie,handleFileAdd:Le,handlePaste:$e,handleSendMessage:Me,handleNewChat:ze,handleStopGenerating:Ae,setAttachedFiles:Te,setMessages:Ee,setContextUsage:je,updateConversationId:De,handleSwitchConversation:Re}=W({apiBaseUrl:h,apiEndpoints:u,backendType:U,agentSlug:oe?.slug,requestHeaders:j,pageContext:D,t:f,maxFileCount:T,maxTotalSize:E}),{suggestions:Ue,loading:Be}=Q({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j,agentSlug:oe?.slug}),{prompts:We,quota:Oe,refreshQuota:He}=X({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j}),{historyEnabled:Pe,conversations:qe,conversationsLoading:Ve,refreshConversations:Ge,deleteConversation:Je,renameConversation:Ke}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[i,s]=r([]),[l,c]=r(!1),d="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,h=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,u=o(async()=>{if(d){c(!0);try{const e=await fetch(h,{method:"GET",headers:{...a??{}}});if(!e.ok)return void s([]);const t=await e.json(),n=Array.isArray(t)?t:Array.isArray(t?.conversations)?t.conversations:[];s(n.map(F).filter(e=>null!==e))}catch{s([])}finally{c(!1)}}},[d,h,a]),g=o(async e=>{if(!d)return!1;try{return!!(await fetch(`${h}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...a??{}}})).ok&&(s(t=>t.filter(t=>t.conversationId!==e)),!0)}catch{return!1}},[d,h,a]),p=o(async(e,t)=>{const n=t.trim();if(!d||!n)return!1;const r=i;s(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{return!!(await fetch(`${h}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...a??{}},body:JSON.stringify({title:n})})).ok||(s(r),!1)}catch{return s(r),!1}},[d,h,a,i]);return{historyEnabled:d,conversations:i,conversationsLoading:l,refreshConversations:u,deleteConversation:g,renameConversation:p}}({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j}),[Ze,Qe]=r(!1),[Ye,et]=r(!1),tt="fullscreen"===n&&Pe;i(()=>{tt&&Ge()},[tt,fe,Ge]);const nt=a(!1);i(()=>{nt.current&&!ge&&(He(),tt&&Ge()),nt.current=ge},[ge,He,tt,Ge]);const rt=e=>{Qe(!1),Re(e)},at=async e=>{await Je(e)&&e===Ie.current&&ze()},{sidebarWidth:ot,handleResizeStart:it,defaultWidth:st,isResizing:lt}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:o,onResizeEnd:s}){const[l,c]=r(()=>{if("undefined"==typeof window)return P;const e=localStorage.getItem(q);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=P)return t}return P}),[d,h]=r(!1),u=a(!1),g=a(l);g.current=l;const p=a(n);p.current=n;const m=a(s);return m.current=s,i(()=>{"sidebar"===e&&t&&p.current?.(g.current)},[e,t]),i(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!u.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,P),n);c(r),g.current=r,p.current?.(r)},r=()=>{u.current&&(u.current=!1,h(!1),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem(q,String(g.current)),m.current?.())},a=()=>{const e=.4*window.innerWidth;if(g.current>e){const t=Math.max(e,P);c(t),g.current=t,p.current?.(t)}};return document.addEventListener("mousemove",n),document.addEventListener("mouseup",r),window.addEventListener("resize",a),()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",r),window.removeEventListener("resize",a)}},[e,t]),{sidebarWidth:l,handleResizeStart:e=>{e.preventDefault(),u.current=!0,h(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",o?.()},defaultWidth:P,isResizing:d}}({mode:n,resizable:k,onWidthChange:N,onResizeStart:C,onResizeEnd:S});i(()=>{const e="sidebar"===n?k?ot:st:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",lt?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),R){const e=document.querySelector(R);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=lt?"none":"padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)",()=>{e.style.paddingRight=n,e.style.transition=r,document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}}}return()=>{document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}},[R,n,ot,st,k,lt]);const ct=l(()=>y??t(de,{size:24}),[y]),dt=p.firstName,[ht,ut]=r(null),gt=we?.name||ht||oe?.name||"Assistant",pt=o(()=>{if("undefined"==typeof document)return!1;const e=document.querySelector(".filigran-chatbot.fixed");return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);Z({isLoading:ge,agentName:gt,t:f,enabled:O,onComplete:V,isViewingChat:pt});const mt=null!=u?.download,ft="rest"===U&&null!==u?.download&&(!u?.singleEndpoint||mt),xt=o(e=>`${h}${u?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[h,u]),wt=o(async e=>{const t=xt(e);try{const n=await fetch(t,{method:"GET",credentials:"include",headers:{...j??{}}});if(!n.ok)throw new Error(`Download failed: ${n.status}`);const r=await n.blob(),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=e.filename||"download",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a)}catch(t){A?.(t,e)}},[xt,j,A]),yt={"--chat-accent":x,"--chat-accent-10":m(x,.1),"--chat-accent-40":m(x,.25),"--chat-accent-50":m(x,.5),"--chat-accent-dark":x},vt=a(!0);i(()=>(vt.current=!0,()=>{vt.current=!1}),[]),i(()=>{if(null===u?.sessions||u?.singleEndpoint||"legacy"===U||"ag-ui"===U)return;if(!fe)return void ut(null);if(_e.current||!oe)return;_e.current=!0;const e=fe,t=()=>!vt.current||Ie.current!==e;fetch(`${h}${u?.sessions??"/chat/sessions"}`,{method:"POST",headers:{"Content-Type":"application/json",...j??{}},body:JSON.stringify({conversation_id:fe,agent_slug:oe.slug})}).then(e=>t()?null:e.ok?e.json():(De(null),null)).then(n=>{if(!n||t())return;if("string"==typeof n.conversation_id&&n.conversation_id&&n.conversation_id!==e&&De(n.conversation_id),ut("string"==typeof n.agent_name?n.agent_name:null),!n.messages?.length)return;const r=n.messages.map((e,t)=>({id:`restored-${t}`,role:e.role,content:e.content,timestamp:new Date,agentName:"string"==typeof e.agent_name?e.agent_name:void 0,attachments:I(e.attachments),toolNames:Array.isArray(e.tool_names)?e.tool_names:void 0,toolCallCount:"number"==typeof e.tool_call_count?e.tool_call_count:void 0,iterations:"number"==typeof e.iterations?e.iterations:void 0,reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:L(e.tool_call_trace),transferChain:$(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0}));Ee(r);for(let e=n.messages.length-1;e>=0;e-=1){const t=_(n.messages[e]);if(t){je(t);break}}}).catch(()=>{t()||De(null)})},[fe,oe,h,u,U,Se,_e,Ie,vt,j,Ee,je,De]);const bt=(()=>{const e="filigran-chatbot";switch(n){case"sidebar":return`${e} fixed right-0 bottom-0 flex flex-col bg-white dark:bg-[#1e1e2e] border-l border-gray-200 dark:border-white/10 z-[1200]`;case"floating":return`${e} fixed bottom-5 right-5 flex flex-col bg-white dark:bg-[#1e1e2e] rounded-xl shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border border-gray-200 dark:border-white/10`;case"fullscreen":return`${e} fixed right-0 bottom-0 left-0 flex flex-col bg-gray-50 dark:bg-[#161622] z-[1400]`;default:return e}})(),kt={...yt,..."sidebar"===n?{top:d,width:k?ot:st}:"floating"===n?{width:380,height:560}:{top:d}};return e("div",{className:bt,style:kt,children:["sidebar"===n&&k&&t("div",{onMouseDown:it,className:"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group",children:t("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 rounded-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100"})}),t(Fe,{mode:n,agentName:gt,agents:ne,agentsLoading:re,agentsError:ae,selectedAgent:oe,transferredFrom:we?oe?.name:void 0,agentMenuOpen:ie,onAgentMenuToggle:()=>se(e=>!e),onAgentMenuClose:()=>se(!1),onSwitchAgent:e=>{e&&le(e,()=>{ze()})},modeMenuOpen:ee,onModeMenuToggle:()=>te(e=>!e),onModeMenuClose:()=>te(!1),onModeChange:c,onNewChat:ze,onClose:s,logoIcon:ct,agentDashboardUrl:g,historyEnabled:Pe&&!tt,historyMenuOpen:Ze,onHistoryMenuToggle:()=>{const e=!Ze;e&&Ge(),Qe(e)},onHistoryMenuClose:()=>Qe(!1),conversations:qe,conversationsLoading:Ve,activeConversationId:fe,onSelectConversation:rt,onDeleteConversation:e=>{at(e)},t:f}),e("div",{className:tt?"flex flex-1 min-h-0":"contents",children:[tt&&t($t,{conversations:qe,loading:Ve,activeConversationId:fe,collapsed:Ye,onToggleCollapsed:()=>et(e=>!e),onSelect:rt,onDelete:e=>{at(e)},onRename:(e,t)=>{Ke(e,t)},onNewChat:ze,t:f}),e("div",{className:tt?"flex flex-1 flex-col min-w-0":"contents",children:[0===ce.length?t(Lt,{firstName:dt,logoIcon:ct,promptSuggestions:Ue??v,suggestionsLoading:Be,agentName:oe?.name,agentDescription:oe?.description,onPromptClick:ue,t:f}):t(It,{messages:ce,isLoading:ge,agentStatus:pe,agentName:gt,logoIcon:ct,onRelativeLinkClick:z,onDownloadFile:ft?wt:void 0,resolveAttachmentUrl:ft&&!J?xt:void 0,requestHeaders:j,miniGameEnabled:B,onMessageFeedback:G,isResumingAfterDecision:Ce,pendingApprovals:ve,onSubmitApprovalDecisions:Ne,isSubmittingApproval:be,approvalError:ke,t:f}),t(Xe,{inputValue:he,onInputChange:ue,onSend:Me,onStop:Ae,isLoading:ge,canSteer:ye,attachedFiles:M?[]:me,onFileAdd:M?void 0:Le,onFileRemove:M?void 0:e=>Te(t=>t.filter((t,n)=>n!==e)),onPaste:M?void 0:$e,t:f,mode:n,separatorColor:b,prompts:We,quota:Oe,contextUsage:K?xe:null,composerToolbar:Y})]})]})]})},At=({isOpen:n,onToggle:r,label:a="Ask Assistant",accentColor:o="#7b5cff",icon:i})=>{const s=i??t(de,{size:16});return e("button",{type:"button",onClick:r,className:"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap rounded-md border transition-colors",style:{borderColor:n?o:m(o,.5),color:o,backgroundColor:n?m(o,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=o,e.currentTarget.style.backgroundColor=m(o,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?o:m(o,.5),e.currentTarget.style.backgroundColor=n?m(o,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:s}),a]})};export{zt as ChatPanel,At as ChatToggleButton};
|
|
1
|
+
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{useState as r,useRef as a,useCallback as o,useEffect as i,useLayoutEffect as s,useMemo as l,useId as c,memo as d}from"react";import{createPortal as h}from"react-dom";import u from"react-markdown";import g from"remark-gfm";import p from"remark-breaks";function m(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}const f=new Set(["http","https","mailto","tel"]);function x(e){const t=e.indexOf(":");if(t<0)return e;const n=e.indexOf("/"),r=e.indexOf("?"),a=e.indexOf("#");if(n>-1&&t>n||r>-1&&t>r||a>-1&&t>a)return e;const o=e.slice(0,t).toLowerCase();return f.has(o)||"data"===o&&/^data:image\//i.test(e)?e:""}const w=e=>e;function y(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function v(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function b(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}M`}function k(e,t){if(!e)return"";const n=new Date(e).getTime();if(Number.isNaN(n))return"";const r=Date.now()-n,a=Math.floor(r/6e4);if(a<1)return t("just now");if(a<60)return y(t,"{count}m ago",{count:a});const o=Math.floor(a/60);if(o<24)return y(t,"{count}h ago",{count:o});const i=Math.floor(o/24);return i<7?y(t,"{count}d ago",{count:i}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const N=/\[\[FILE:[^\]]+\]\]/g,C=/\[\[FILE(?::[^\]]*)?\]?$/;function S(e){if(!e)return e;const t=e.replace(N,"").replace(C,"");return t===e?e:t.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}const _=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function I(e){const t=e.context_tokens,n=e.context_window;if("number"!=typeof t||"number"!=typeof n)return;if(!Number.isFinite(t)||!Number.isFinite(n)||n<=0||t<0)return;const r=function(e){if(!e||"object"!=typeof e)return;const t=e,n={};let r=!1;for(const[e,a]of _){const o=t[e];"number"==typeof o&&Number.isFinite(o)&&o>0&&(n[a]=o,r=!0)}return r?n:void 0}(e.context_breakdown);return r?{used:t,limit:n,breakdown:r}:{used:t,limit:n}}function L(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.file_id;"string"==typeof r&&r&&t.push({fileId:r,filename:"string"==typeof e.filename?e.filename:"file",type:"string"==typeof e.type?e.type:void 0,size:"number"==typeof e.size?e.size:void 0,contentType:"string"==typeof e.content_type?e.content_type:void 0,fileTag:"working_file"===e.file_tag?"working_file":"download_file"})}return t.length>0?t:void 0}function M(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.name&&e.name&&t.push({name:e.name,input:"string"==typeof e.input?e.input:void 0,output:"string"==typeof e.output?e.output:void 0,success:"boolean"!=typeof e.success||e.success})}return t.length>0?t:void 0}function z(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.agent_name&&e.agent_name&&t.push({agentId:"string"==typeof e.agent_id?e.agent_id:"",agentName:e.agent_name})}return t.length>0?t:void 0}function A(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.tool_call_id;if("string"!=typeof r||!r)continue;const a=e.arguments,o=e.input_schema;t.push({toolCallId:r,toolName:"string"==typeof e.tool_name&&e.tool_name?e.tool_name:"",toolDescription:"string"==typeof e.tool_description?e.tool_description:void 0,arguments:a&&"object"==typeof a&&!Array.isArray(a)?a:{},inputSchema:o&&"object"==typeof o&&!Array.isArray(o)?o:void 0,source:"string"==typeof e.source?e.source:void 0})}return t.length>0?t:void 0}function T(e,t){const n=e.type;if("error"===n)return{action:"error",content:e.content||""};if("status"===n){const n=e.status;if("tool_done"===n||"wind_down"===n)return{action:"noop"};if("streaming"===n)return{action:"status",status:"streaming"};if("thinking_text"===n)return{action:"status",status:"thinking_text",thinkingContent:e.content};if("tool_start"===n)return t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:e.tools};if("tool_heartbeat"===n)return{action:"status",status:"tool_heartbeat",tools:e.tools,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};const r=I(e);return"thinking"===n&&t.hasUsedTools?{action:"status",status:"analyzing",contextUsage:r}:{action:"status",status:n,tools:e.tools,contextUsage:r}}if("approval_required"===n){const t=A(e.proposals);return t?{action:"approval_required",proposals:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}:{action:"noop"}}return"stream"===n?{action:"stream",content:e.content}:"done"===n?{action:"done",content:e.content,conversationId:e.conversation_id,toolNames:e.tool_names,toolCallCount:e.tool_call_count,iterations:e.iterations,transferAgentId:e.transfer_agent_id,transferAgentName:e.transfer_agent_name,attachments:L(e.attachments),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:M(e.tool_call_trace),transferChain:z(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:I(e)}:{action:"noop"}}function E(e,t){const n=e.event;if("nextAgentFlow"===n){const n=e.data,r=n?.nodeId;return"INPROGRESS"===n?.status&&r&&(t.activeNodeId=r),{action:"noop"}}if("start"===n)return{action:"noop"};if("token"===n){return{action:"stream",content:(e.data??"").replace(/<br\s*\/?>/g,"\n")}}if("agentReasoning"===n){const n=e.data,r=n?.usedTools;return r?.length?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:r.map(e=>e.tool)}):t.hasUsedTools?{action:"status",status:"analyzing"}:{action:"status",status:"thinking"}}if("usedTools"===n){t.hasUsedTools=!0;const n=e.data;return{action:"status",status:"tool_start",tools:Array.isArray(n)?n.map(e=>e.tool):[]}}if("metadata"===n){const t=e.data,n=t?.chatId;return n?{action:"set_chat_id",chatId:n}:{action:"noop"}}return"error"===n?{action:"error",content:e.data||""}:"end"===n?{action:"done",content:""}:{action:"noop"}}function $(e,t){const n=e.type;if("RUN_STARTED"===n)return{action:"status",status:"thinking"};if("RUN_FINISHED"===n)return{action:"done",content:""};if("RUN_ERROR"===n)return{action:"error",content:"string"==typeof e.message?e.message:""};if("STEP_STARTED"===n){return{action:"status",status:e.stepName||"thinking"}}if("STEP_FINISHED"===n)return{action:"noop"};if("TEXT_MESSAGE_START"===n)return{action:"status",status:"streaming"};if("TEXT_MESSAGE_CONTENT"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TEXT_MESSAGE_END"===n)return{action:"noop"};if("TEXT_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TOOL_CALL_START"===n){t.hasUsedTools=!0;const n=e.toolCallName;return{action:"status",status:"tool_start",tools:n?[n]:[]}}if("TOOL_CALL_ARGS"===n)return{action:"noop"};if("TOOL_CALL_END"===n)return{action:"status",status:"analyzing"};if("TOOL_CALL_RESULT"===n)return{action:"noop"};if("TOOL_CALL_CHUNK"===n){const n=e.toolCallName;return n?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:[n]}):{action:"noop"}}if("REASONING_START"===n||"REASONING_MESSAGE_START"===n)return{action:"status",status:"thinking"};if("REASONING_MESSAGE_CONTENT"===n||"REASONING_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"status",status:"thinking_text",thinkingContent:t}:{action:"status",status:"thinking"}}return{action:"noop"}}const j="filigranChatConversationId",D="filigranChatLegacyChatId",R=e=>`filigranChatDraft:${e??"new"}`;function U(e){if("undefined"==typeof window)return"";try{return sessionStorage.getItem(R(e))??""}catch{return""}}function O(e,t){if("undefined"!=typeof window)try{t?sessionStorage.setItem(R(e),t):sessionStorage.removeItem(R(e))}catch{}}const B=52428800;function W({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:s,requestHeaders:l,pageContext:c,t:d,maxFileCount:h=10,maxTotalSize:u=52428800}){const g="legacy"===n,[p,m]=r([]),[f,x]=r(!1),[w,y]=r(null),[v,b]=r(()=>"undefined"==typeof window?null:localStorage.getItem(j)),[k,N]=r(()=>U("undefined"==typeof window?null:localStorage.getItem(j))),[C,S]=r([]),[_,I]=r(null),[L,M]=r(null),[z,R]=r(null),[W,H]=r(!1),[F,P]=r(null),[q,V]=r(!1),[G,J]=r(0),[K,Z]=r(0),[X,Y]=r(()=>"undefined"==typeof window?null:localStorage.getItem(D)),Q=a(!1),ee=a(null),te=a(!1),ne=a(v),re=a(f);re.current=f;const ae=a(c);ae.current=c;const oe=a(null),ie=a(!1),se=a(null),le=a(0),ce=a(null),de=a(new AbortController),he=Number.isFinite(h)&&h>0?Math.floor(h):10,ue=Number.isFinite(u)&&u>0?u:B,ge=()=>g||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,pe=()=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const r=t?.approve;return r?`${e}${r}`:null},me=r=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const a=t?.pendingApprovals;return a?`${e}${a}/${r}/pending-approvals`:null},fe=async e=>{const t=me(e);if(!t)return null;try{const e=await fetch(t,{headers:{...l??{}}});if(!e.ok)return null;const n=await e.json();return{proposals:A(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},xe=o(()=>{Q.current=!1,J(e=>e+1)},[]),we=()=>g||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,ye=o(e=>{ne.current=e,b(e),e?localStorage.setItem(j,e):localStorage.removeItem(j)},[]),ve=async n=>{if(ne.current)return ne.current;if(ce.current)return ce.current;const r=g||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`;if(!r)return null;const a=(async()=>{try{const e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify({agent_slug:n})});if(!e.ok)return null;const t=await e.json(),a=t?.conversation_id??null;return a&&ye(a),a}catch{return null}finally{ce.current=null}})();return ce.current=a,a},be=async(e,t,n)=>{const r=we(),a=new FormData;a.append("conversation_id",t),a.append("file",e,e.name);const o=l?Object.fromEntries(Object.entries(l).filter(([e])=>"content-type"!==e.toLowerCase())):void 0,i=await fetch(r,{method:"POST",headers:o,body:a,signal:n});if(!i.ok)throw new Error(`File upload failed: ${i.status}`);const s=(await i.json()).file_ids??[];if(0===s.length)throw new Error("No file_id returned");return s[0]},ke=e=>{if(!e||0===e.length||!we())return;const t=Array.from(e).map(e=>({file:e,tempId:crypto.randomUUID()}));let n=[];S(e=>{const r=e.length,a=e.reduce((e,t)=>e+t.size,0),o=he-r;if(o<=0)return e;let i=ue-a;const s=[];for(const e of t.slice(0,o))e.file.size<=i&&(s.push(e),i-=e.file.size);if(0===s.length)return e;n=s;const l=s.map(({file:e,tempId:t})=>({name:e.name,type:e.type,size:e.size,rawFile:e,uploadStatus:"pending",fileId:t}));return[...e,...l]}),setTimeout(()=>{const e=de.current.signal;for(const{file:t,tempId:r}of n)(async()=>{try{const n=await ve(s);if(!n)return void S(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e));const a=await be(t,n,e);S(e=>e.map(e=>e.fileId===r?{...e,fileId:a,uploadStatus:"done"}:e))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;S(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e))}})()},0)},Ne=()=>{ee.current?.abort(),ee.current=null,de.current.abort(),de.current=new AbortController,ce.current=null,m([]),N(""),S([]),x(!1),y(null),I(null),M(null),R(null),P(null),V(!1),oe.current=null,ie.current=!1,se.current=null,te.current=!1,Q.current=!1,g?(Y(null),localStorage.removeItem(D)):ye(null)};i(()=>{const e=window.setTimeout(()=>O(v,k),300);return()=>window.clearTimeout(e)},[k,v]);const Ce=a({conversationId:v,inputValue:k});Ce.current={conversationId:v,inputValue:k},i(()=>()=>{const{conversationId:e,inputValue:t}=Ce.current;O(e,t)},[]),i(()=>{const e=v;if(!e||f)return;if(se.current===e)return;me(e)&&pe()&&(se.current=e,(async()=>{const t=await fe(e);t?.proposals&&(ne.current!==e||re.current||(oe.current=e,ie.current=!0,P(null),R(t.proposals)))})())},[v,f]),i(()=>{if(!z?.length||!ie.current)return;const e=oe.current,t=e?me(e):null;if(!t)return;const n=window.setInterval(()=>{fetch(t,{headers:{...l??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[z]),i(()=>{if(!q)return;const e=oe.current;if(!e)return void V(!1);if(Date.now()>=le.current)return V(!1),void xe();let t=!1;const n=window.setTimeout(async()=>{const n=await fe(e);if(!t){if(n)return n.proposals?(ie.current=!0,P(null),R(n.proposals),void V(!1)):n.turnRunning?void Z(e=>e+1):(V(!1),void xe());Z(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[q,K,xe]);const Se=f&&null!==ge()&&null!==v;return{messages:p,inputValue:k,setInputValue:N,isLoading:f,agentStatus:w,attachedFiles:C,conversationId:v,contextUsage:L,transferredAgent:_,canSteer:Se,pendingApprovals:z,isSubmittingApproval:W,approvalError:F,submitApprovalDecisions:async e=>{const t=pe(),n=oe.current??ne.current;if(0!==e.length)if(t&&n){P(null),H(!0);try{const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify({conversation_id:n,decisions:e.map(e=>({tool_call_id:e.toolCallId,decision:e.verdict,..."reject"===e.verdict&&e.rejectionReason?{rejection_reason:e.rejectionReason}:{}}))})});if(r.ok)return R(null),ie.current?(ie.current=!1,le.current=Date.now()+9e5,void V(!0)):void y(e=>e?{...e,status:"thinking"}:{status:"thinking"});P(409===r.status?d("This turn is no longer waiting for a decision."):d("Could not send your decision. Please try again."))}catch{P(d("Could not send your decision. Please try again."))}finally{H(!1)}}else P(d("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:q,historyReloadNonce:G,historyLoadedRef:Q,conversationIdRef:ne,handleFileAdd:ke,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),ke(t))},handleSendMessage:async()=>{const r=k.trim();if(f)return void(r&&0===C.length&&ge()&&ne.current&&(N(""),await(async e=>{const t=ge(),n=ne.current;if(!t||!n)return;const r={id:crypto.randomUUID(),role:"user",content:e,timestamp:new Date};m(e=>[...e,r]);try{const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify({conversation_id:n,content:e,agent_slug:s})});if(!r.ok)throw new Error(`Steer failed: ${r.status}`)}catch{m(e=>e.filter(e=>e.id!==r.id)),N(t=>t?`${e}\n${t}`:e)}})(r)));if(!k.trim()&&0===C.length)return;const a=k.trim(),o={id:crypto.randomUUID(),role:"user",content:a,timestamp:new Date,files:C.length>0?[...C]:void 0};m(e=>[...e,o]),N(""),S([]),x(!0),y({status:"thinking"}),te.current=!1;const i=crypto.randomUUID();m(e=>[...e,{id:i,role:"assistant",content:"",timestamp:new Date}]);let c=i;try{const r=new AbortController;ee.current=r;const h=(o.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),u=function(e,t,n){switch(e){case"legacy":return{question:t,chatId:n.legacyChatId??void 0,streaming:!0};case"ag-ui":return{threadId:n.conversationId??crypto.randomUUID(),runId:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={content:t,conversation_id:n.conversationId,agent_slug:n.agentSlug};if(n.supportsToolApproval&&(e.supports_tool_approval=!0),n.pageContext&&Object.keys(n.pageContext).length>0)try{const t=JSON.stringify(n.pageContext);t&&"{}"!==t&&(e.context=n.pageContext)}catch{}return e}}}(n,a,{legacyChatId:X,conversationId:ne.current,agentSlug:s,pageContext:ae.current,supportsToolApproval:null!==pe()});h.length>0&&(u.file_ids=h),y({status:"thinking"});const p=await fetch(g||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify(u),signal:r.signal});if(!p.ok||!p.body)return void m(e=>e.map(e=>e.id===i?{...e,content:d("Unable to connect. Please check the configuration.")}:e));const f=function(e){switch(e){case"legacy":return E;case"ag-ui":return $;default:return T}}(n),x={hasUsedTools:!1,activeNodeId:""},w=p.body.getReader(),v=new TextDecoder;let b="",k="",N=!1;const C=()=>{if(!N)return;N=!1,k="",c=crypto.randomUUID();const e=c;m(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),y({status:"thinking"})};for(;;){const{done:e,value:t}=await w.read();if(e)break;b+=v.decode(t,{stream:!0});const n=b.split("\n");b=n.pop()||"";for(const e of n){const t=e.replace(/\r$/,"");if(!t.startsWith("data:"))continue;const n=t.startsWith("data: ")?t.slice(6):t.slice(5);try{const e=f(JSON.parse(n),x);switch(x.hasUsedTools=x.hasUsedTools||te.current,e.action){case"status":{C();const t=c;if(e.contextUsage&&M(e.contextUsage),"tool_start"===e.status&&(te.current=!0),"stream_retract"===e.status)k="",m(e=>e.map(e=>e.id===t?{...e,content:""}:e)),y(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}));else if("thinking_text"===e.status)y(t=>({...t,status:t?.status??"thinking",thinkingContent:(t?.thinkingContent??"")+(e.thinkingContent??"")}));else if("tool_heartbeat"===e.status){const t="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;y(n=>n?{...n,elapsedS:e.elapsedS,elapsedStartMs:t}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:t})}else y(t=>({status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent}));break}case"stream":{C(),k+=e.content;const t=c,n=k;y(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),m(e=>e.map(e=>e.id===t?{...e,content:n}:e));break}case"done":{N=!0,R(null),P(null),e.conversationId&&ye(e.conversationId),e.contextUsage&&M(e.contextUsage),e.transferAgentId&&e.transferAgentName&&I({id:e.transferAgentId,name:e.transferAgentName});const t=c,n=e.content||k;m(r=>r.map(r=>r.id===t?{...r,content:n,toolNames:e.toolNames,toolCallCount:e.toolCallCount,iterations:e.iterations,attachments:e.attachments,reasoning:e.reasoning,toolCallTrace:e.toolCallTrace,transferChain:e.transferChain,isTruncated:e.isTruncated}:r));break}case"approval_required":oe.current=e.conversationId??ne.current,P(null),R(e.proposals),y(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"});break;case"error":{C();const t=c;return void m(n=>n.map(n=>n.id===t?{...n,content:e.content||d("Sorry, an error occurred. Please try again.")}:n))}case"set_chat_id":Y(e.chatId),localStorage.setItem(D,e.chatId)}te.current=x.hasUsedTools}catch{}}}if(k&&!N){const e=c,t=k;m(n=>n.map(n=>n.id===e?{...n,content:t||d("No response.")}:n))}}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;const t=c;m(e=>e.map(e=>e.id===t?{...e,content:d("Sorry, an error occurred. Please try again.")}:e))}finally{ee.current=null,x(!1),y(null),te.current=!1,R(null),P(null),oe.current=null,ie.current=!1,se.current=ne.current}},handleNewChat:Ne,handleStopGenerating:()=>{ee.current?.abort(),ee.current=null,x(!1),y(null),te.current=!1,R(null),P(null),V(!1),oe.current=null,ie.current=!1,m(e=>e.filter(e=>!("assistant"===e.role&&!e.content)))},setAttachedFiles:S,setMessages:m,setContextUsage:M,updateConversationId:ye,handleSwitchConversation:e=>{(g||e!==ne.current)&&(Ne(),g||(ye(e),N(U(e))))}}}const H="filigranChatAgentSlug";function F({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[o,s]=r([]),[l,c]=r(!1),[d,h]=r(!1),[u,g]=r(null),[p,m]=r(!1);i(()=>{if(null===t?.agents||t?.singleEndpoint||"legacy"===n)return;const r=`${e}${t?.agents??"/chat/agents"}`;c(!0),h(!1),fetch(r,{headers:a}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}).then(e=>{const t=function(e){return(Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]).filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id)}(e);if(s(t),t.length>0&&!u){const e=localStorage.getItem(H),n=e?t.find(t=>t.slug===e):null;g(n||t[0])}}).catch(()=>{s([]),h(!0)}).finally(()=>c(!1))},[e,t,n,a]);return{agents:o,agentsLoading:l,agentsError:d,selectedAgent:u,setSelectedAgent:g,agentMenuOpen:p,setAgentMenuOpen:m,handleSwitchAgent:(e,t)=>{e.id!==u?.id?(g(e),e.slug&&localStorage.setItem(H,e.slug),m(!1),t?.()):m(!1)}}}function P(e){if(!e||"object"!=typeof e)return null;const t=e,n=t.conversation_id??t.id;if("string"!=typeof n||!n)return null;return{conversationId:n,title:"string"==typeof t.title?t.title.trim():"",updatedAt:"string"==typeof t.updated_at?t.updated_at:"string"==typeof t.created_at?t.created_at:void 0,messageCount:"number"==typeof t.message_count?t.message_count:void 0,agentName:"string"==typeof t.agent_name&&t.agent_name?t.agent_name:void 0}}const q=400,V="filigranChatSidebarWidth";let G=null,J=null,K=0;function Z(){null!==G&&(window.clearInterval(G),G=null),null!==J&&(document.title=J,J=null)}function X({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:o,isViewingChat:s}){const l=a(!1),c=a(0);i(()=>{if(!r||"undefined"==typeof document)return;K+=1;const e=()=>{!document.hidden&&document.hasFocus()&&Z()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),K=Math.max(0,K-1),0===K&&Z()}},[r]),i(()=>{const a=l.current;if(l.current=e,!e||a){if(!e&&a&&r){if(Date.now()-c.current<4e3)return;const e="undefined"!=typeof document&&document.hidden,r="undefined"!=typeof document&&!document.hasFocus(),a=e||r,i=!s||s();if(!a&&i)return;const l=n("Response ready"),d=t?y(n,"{agent} has finished",{agent:t}):n("Your answer is ready");a&&(function(e){if("undefined"==typeof document)return;null===J&&(J=document.title),null!==G&&window.clearInterval(G);let t=!0;document.title=e,G=window.setInterval(()=>{t=!t,document.title=t?e:J??e},1200)}(l),function(e,t){try{if("undefined"==typeof Notification||"granted"!==Notification.permission)return;new Notification(e,{body:t,tag:"filigran-chat-complete"})}catch{}}(l,d)),o?.(l,d)}}else c.current=Date.now()},[e,r,t,n,o,s])}function Y({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[s,l]=r(null),[c,d]=r(null),h="rest"===n&&!t?.singleEndpoint,u=void 0===t?.prompts?"/chat/prompts":t.prompts,g=void 0===t?.quota?"/chat/quota":t.quota,p=h&&u?`${e}${u}`:null,m=h&&g?`${e}${g}`:null;i(()=>{if(!p)return void l(null);let e=!1;return fetch(p,{credentials:"include",headers:{...a??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){const t=Array.isArray(e)?e:Array.isArray(e?.prompts)?e.prompts:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,r="string"==typeof t.id?t.id:"",a="string"==typeof t.content?t.content:"";r&&a&&n.push({id:r,title:"string"==typeof t.title&&t.title?t.title:r,content:a,description:"string"==typeof t.description?t.description:void 0})}return n}(t);l(n.length>0?n:null)}).catch(()=>{e||l(null)}),()=>{e=!0}},[p,a]);const[f,x]=r(0),w=o(()=>x(e=>e+1),[]);return i(()=>{if(!m)return void d(null);let e=!1;return fetch(m,{credentials:"include",headers:{...a??{}}}).then(e=>e.ok?e.json():null).then(t=>{e||d(function(e){if(!e||"object"!=typeof e)return null;const t=e;return"number"!=typeof t.used?null:{used:t.used,limit:"number"==typeof t.limit?t.limit:null,period:"string"==typeof t.period?t.period:""}}(t))}).catch(()=>{e||d(null)}),()=>{e=!0}},[m,a,f]),{prompts:s,quota:c,refreshQuota:w}}function Q({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a,agentSlug:o}){const[s,l]=r(null),[c,d]=r(!1),h="rest"===n&&!t?.singleEndpoint,u=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,g=h&&u?`${e}${u}`:null;return i(()=>{if(!g)return void l(null);let e=!1;d(!0);const t=o?`${g}?agent_slug=${encodeURIComponent(o)}`:g;return fetch(t,{credentials:"include",headers:{...a??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){return(Array.isArray(e)?e:Array.isArray(e?.suggestions)?e.suggestions:[]).map(e=>{if("string"==typeof e)return e.trim();if(e&&"object"==typeof e){const t=e,n=t.prompt??t.label??t.text;if("string"==typeof n)return n.trim()}return""}).filter(e=>e.length>0)}(t);l(n.length>0?n:null)}).catch(()=>{e||l(null)}).finally(()=>{e||d(!1)}),()=>{e=!0}},[g,o,a]),{suggestions:s,loading:c}}const ee=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),t("path",{d:"M12 9v4"}),t("path",{d:"M12 17h.01"})]}),te=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m16 3 4 4-4 4"}),t("path",{d:"M20 7H4"}),t("path",{d:"m8 21-4-4 4-4"}),t("path",{d:"M4 17h16"})]}),ne=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),re=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 8V4H8"}),t("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),t("path",{d:"M2 14h2"}),t("path",{d:"M20 14h2"}),t("path",{d:"M15 13v2"}),t("path",{d:"M9 13v2"})]}),ae=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),t("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),t("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),t("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),t("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),t("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),t("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),t("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),t("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),oe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),ie=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 6 9 17l-5-5"})}),se=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m6 9 6 6 6-6"})}),le=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),ce=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),t("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),de=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),t("path",{d:"M3 5V19A9 3 0 0 0 21 19V5"}),t("path",{d:"M3 12A9 3 0 0 0 21 12"})]}),he=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),ue=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),t("polyline",{points:"7 10 12 15 17 10"}),t("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]}),ge=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 20h9"}),t("path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"})]}),pe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M10 14 21 3"}),t("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),me=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),fe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7"}),t("rect",{width:"12",height:"12",x:"10",y:"10",rx:"2"})]}),xe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),t("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),t("path",{d:"M3 16h3a2 2 0 0 0 2 2v3"}),t("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"})]}),we=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),t("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),t("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),t("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]}),ye=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("line",{x1:"6",x2:"10",y1:"11",y2:"11"}),t("line",{x1:"8",x2:"8",y1:"9",y2:"13"}),t("line",{x1:"15",x2:"15.01",y1:"12",y2:"12"}),t("line",{x1:"18",x2:"18.01",y1:"10",y2:"10"}),t("path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"})]}),ve=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),t("path",{d:"M2 12h20"})]}),be=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),t("path",{d:"M3 3v5h5"}),t("path",{d:"M12 7v5l4 2"})]}),ke=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),t("circle",{cx:"9",cy:"9",r:"2"}),t("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]}),Ne=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),Ce=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),t("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),Se=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),_e=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]}),Ie=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-.11 1.23"}),t("path",{d:"M5 10v2a7 7 0 0 0 12 5"}),t("path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33"}),t("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12"}),t("path",{d:"m2 2 20 20"})]}),Le=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),Me=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),ze=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),Ae=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),Te=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),Ee=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),$e=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M17 14V2"}),t("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),je=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M7 10v12"}),t("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),De=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 6h18"}),t("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),t("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),t("line",{x1:"10",x2:"10",y1:"11",y2:"17"}),t("line",{x1:"14",x2:"14",y1:"11",y2:"17"})]}),Re=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t("circle",{cx:"9",cy:"7",r:"4"}),t("line",{x1:"19",x2:"19",y1:"8",y2:"14"}),t("line",{x1:"22",x2:"16",y1:"11",y2:"11"})]}),Ue=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),Oe=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]});const Be=({open:e,onClose:n,anchorRef:l,placement:c="bottom-start",width:d=280,children:u})=>{const g=a(null),[p,m]=r({top:0,left:0}),f=o(()=>n(),[n]);if(function(e,t,n=!0){i(()=>{if(!n)return;const r=n=>{e.current&&!e.current.contains(n.target)&&t()};return document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r)}},[e,t,n])}(g,f,e),s(()=>{if(!e||!l.current)return;const t=l.current.getBoundingClientRect(),n=g.current?.offsetHeight??0,r=window.innerHeight-t.bottom-8,a=t.top-8,o=n>0&&r<n&&a>r?Math.max(8,t.top-n-4):t.bottom+4,i="bottom-end"===c?t.right-d:t.left,s=Math.max(8,Math.min(i,window.innerWidth-d-8));m({top:o,left:s})},[e,l,c,d,u]),!e)return null;const x=v(l.current);return h(t("div",{ref:g,className:"fixed z-[10000] rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl",style:{top:p.top,left:p.left,width:d},children:u}),x)},We=({size:e=16,className:n=""})=>t("div",{className:`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${n}`,style:{width:e,height:e}}),He=({title:n,children:o})=>{const i=a(null),[s,l]=r(!1),[c,d]=r({top:0,left:0}),[u,g]=r(!1);if(!n)return o;return e("span",{ref:i,className:"inline-flex",onMouseEnter:()=>{if(!i.current)return;const e=i.current.getBoundingClientRect(),t=v(i.current).getBoundingClientRect().top,n=e.top-t<28;g(n),d({top:n?e.bottom+4:e.top-4,left:e.left+e.width/2}),l(!0)},onMouseLeave:()=>l(!1),children:[o,s&&h(t("span",{className:`pointer-events-none fixed z-[10001] -translate-x-1/2 ${u?"":"-translate-y-full"} whitespace-nowrap rounded-md bg-gray-900 dark:bg-gray-100 px-2 py-1 text-xs text-white dark:text-gray-900 shadow-lg`,style:{top:c.top,left:c.left},role:"tooltip",children:n}),v(i.current))]})},Fe=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(fe,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(ze,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(we,{...e})}],Pe=({mode:o,agentName:s,agents:c,agentsLoading:d=!1,agentsError:h=!1,selectedAgent:u,transferredFrom:g,agentMenuOpen:p,onAgentMenuToggle:m,onAgentMenuClose:f,onSwitchAgent:x,modeMenuOpen:w,onModeMenuToggle:v,onModeMenuClose:b,onModeChange:N,onNewChat:C,onClose:S,logoIcon:_,agentDashboardUrl:I,historyEnabled:L=!1,historyMenuOpen:M=!1,onHistoryMenuToggle:z,onHistoryMenuClose:A,conversations:T=[],conversationsLoading:E=!1,activeConversationId:$=null,onSelectConversation:j,onDeleteConversation:D,t:R})=>{const U=a(null),O=a(null),B=a(null),[W,H]=r("");i(()=>{p||H("")},[p]);const F=l(()=>{const e=W.trim().toLowerCase();return e?c.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):c},[c,W]),P=c.length>5,q="sidebar"===o?ze:"fullscreen"===o?xe:fe;return e("div",{className:"flex items-center px-3 py-2 min-h-[48px] border-b border-gray-200 dark:border-white/10 bg-gradient-to-br from-[var(--chat-accent-dark)]/[0.13] to-[var(--chat-accent)]/[0.07] "+("floating"===o?"rounded-t-xl":""),children:[e("div",{className:"min-w-0",children:[e("button",{ref:U,type:"button",onClick:m,className:"flex items-center gap-1.5 text-sm font-semibold text-gray-900 dark:text-white px-2 py-1 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t("span",{className:"flex items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:_}),t("span",{children:s}),t(se,{size:16,className:"text-gray-400 dark:text-white/30"})]}),g&&t("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal text-gray-400 dark:text-white/30",children:y(R,"Transferred from {agent}",{agent:g})})]}),e(Be,{open:p,onClose:f,anchorRef:U,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:R("Switch to another agent")}),0===c.length&&d&&t("div",{className:"px-4 py-2",children:t(We,{size:16})}),0===c.length&&!d&&h&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(ee,{size:14,className:"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400"}),t("span",{className:"text-[0.75rem] leading-5 text-gray-600 dark:text-white/60",children:R("Could not reach the assistant service. Check the connection and try again.")})]}),0===c.length&&!d&&!h&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:R("Agent switching is not available here")}),P&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(Le,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40"}),t("input",{autoFocus:!0,type:"text",value:W,onChange:e=>H(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f()},placeholder:R("Search agents..."),"aria-label":R("Search agents..."),className:"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[c.length>0&&0===F.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:R("No agent matches")}),F.map(n=>e("button",{type:"button",onClick:()=>x(n),className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(n.id===u?.id?"bg-[var(--chat-accent)]/10":""),children:[t("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:_})}),e("div",{className:"min-w-0",children:[t("div",{className:"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate",children:n.name}),n.description&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:n.description})]})]},n.id))]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("div",{children:[I&&e("button",{type:"button",onClick:()=>{f(),window.open(`${I}/agents`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(pe,{size:18,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:R("Browse agents")})]}),I&&e("button",{type:"button",onClick:()=>{f(),window.open(`${I}/agents/new`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(Re,{size:18,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:R("Create agent")})]})]})]}),t("div",{className:"flex-1"}),L&&e(n,{children:[t(He,{title:R("Conversation history"),children:t("button",{ref:B,type:"button",onClick:z,"aria-label":R("Conversation history"),"aria-haspopup":"menu","aria-expanded":M,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(be,{size:18})})}),e(Be,{open:M,onClose:()=>A?.(),anchorRef:B,placement:"bottom-end",width:300,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:R("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[E&&0===T.length&&t("div",{className:"px-4 py-2",children:t(We,{size:16})}),!E&&0===T.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:R("No conversations yet")}),T.map(n=>{const r=n.conversationId===$,a=k(n.updatedAt,R);return e("div",{className:"group flex items-center gap-2 px-4 py-1.5 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(r?"bg-[var(--chat-accent)]/10":""),children:[e("button",{type:"button",onClick:()=>j?.(n.conversationId),className:"flex-1 min-w-0 text-left",children:[t("div",{className:"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate",children:n.title||R("Untitled conversation")}),a&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:a})]}),D&&t("button",{type:"button",onClick:()=>D(n.conversationId),title:R("Delete conversation"),"aria-label":R("Delete conversation"),className:"shrink-0 p-1 rounded-md text-gray-400 dark:text-white/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all",children:t(De,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("button",{type:"button",onClick:()=>{A?.(),C()},className:"w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(ge,{size:16,className:"text-gray-400 dark:text-white/40 shrink-0"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:R("New conversation")})]})]})]}),t(He,{title:R("New chat"),children:t("button",{type:"button",onClick:C,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(ge,{size:18})})}),t(He,{title:R("Switch view"),children:t("button",{ref:O,type:"button",onClick:v,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(q,{size:18})})}),e(Be,{open:w,onClose:b,anchorRef:O,placement:"bottom-end",width:180,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:R("Switch to")}),t("div",{className:"pb-1",children:Fe.map(n=>e("button",{type:"button",onClick:()=>{N(n.mode),b()},className:"w-full flex items-center gap-3 px-4 py-1 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors "+(o===n.mode?"bg-[var(--chat-accent)]/10":""),children:[n.getIcon({size:18,className:"text-gray-400 dark:text-white/40"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/70",children:n.label(R)})]},n.mode))})]}),t(He,{title:R("Close"),children:t("button",{type:"button",onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(le,{size:18})})})]})};function qe(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const Ve=14,Ge=2*Math.PI*6,Je=[{field:"system",label:e=>e("System prompt"),color:"#9ca3af"},{field:"tools",label:e=>e("Tool definitions"),color:"#a78bfa"},{field:"dynamicTools",label:e=>e("MCP & dynamic tools"),color:"#f0abfc"},{field:"summary",label:e=>e("Summarized conversation"),color:"#fb7185"},{field:"toolResults",label:e=>e("Tool results"),color:"#34d399"},{field:"conversation",label:e=>e("Conversation"),color:"#a1a1aa"}],Ke=({usage:o,t:i})=>{const{used:s,limit:l,breakdown:c}=o,d=a(null),[h,u]=r(!1),g=Math.min(Math.max(s/l,0),1),p=g>=.95,m=g>=.8,f=p?"text-red-500":m?"text-amber-500":"text-[var(--chat-accent)]",x=p?"text-red-500 dark:text-red-400":m?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",w=Math.round(100*g),v=`${b(s)}/${b(l)}`,k=i(p?"Context full — older turns are being dropped":m?"Context nearly full — older turns are being summarized":"Context used"),N=y(i,"{counts} tokens",{counts:v}),C=`${k} · ${N}`,S=c?Je.filter(e=>(c[e.field]??0)>0):[],_=S.length>0,I=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:Ve,height:Ve,viewBox:"0 0 14 14",className:f,"aria-hidden":"true",children:[t("circle",{cx:7,cy:7,r:6,fill:"none",strokeWidth:2,className:"stroke-gray-200 dark:stroke-white/15"}),t("circle",{cx:7,cy:7,r:6,fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeDasharray:Ge,strokeDashoffset:Ge*(1-g),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${x}`,children:[w,"%"]})]});return _?e(n,{children:[t(He,{title:h?"":y(i,"{summary} — click for details",{summary:C}),children:t("button",{ref:d,type:"button",onClick:()=>u(e=>!e),"aria-label":`${C} (${w}%)`,"aria-haspopup":"dialog","aria-expanded":h,className:"flex items-center rounded-md px-1 -mx-1 py-0.5 transition-colors hover:bg-gray-100 dark:hover:bg-white/10",children:I})}),e(Be,{open:h,onClose:()=>u(!1),anchorRef:d,placement:"bottom-end",width:296,children:[e("div",{className:"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3",children:[t("span",{className:`text-[0.8125rem] tabular-nums ${x}`,children:y(i,"{percent}% full",{percent:w})}),e("span",{className:"text-[0.7rem] tabular-nums text-gray-400 dark:text-white/40 shrink-0",children:["~",N]})]}),t("div",{className:"px-3.5 pb-2.5 pt-1.5",children:t("span",{className:"flex h-1.5 w-full gap-px rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:S.map(e=>t("span",{className:"h-full first:rounded-l-full",style:{width:(c?.[e.field]??0)/Math.max(s,1)*Math.min(s/l,1)*100+"%",backgroundColor:e.color}},e.field))})}),t("div",{className:"px-3.5 pb-1",children:S.map(n=>e("div",{className:"flex items-center gap-2 py-[3px]",children:[t("span",{className:"h-2 w-2 shrink-0",style:{backgroundColor:n.color,borderRadius:2},"aria-hidden":"true"}),t("span",{className:"text-[0.75rem] text-gray-700 dark:text-white/70 truncate",children:n.label(i)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0",children:b(c?.[n.field]??0)})]},n.field))}),m&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${x}`,children:k})]})]}):t(He,{title:C,children:t("span",{className:"flex items-center",role:"img","aria-label":`${C} (${w}%)`,children:I})})},Ze=({prompts:o,onPick:i,t:s})=>{const l=a(null),[c,d]=r(!1),[h,u]=r(""),g=()=>{d(!1),u("")},p=h.trim().toLowerCase(),m=p?o.filter(e=>e.title.toLowerCase().includes(p)||(e.description??"").toLowerCase().includes(p)):o;return e(n,{children:[t(He,{title:s("Insert prompt template"),children:t("button",{ref:l,type:"button",onClick:()=>c?g():d(!0),"aria-label":s("Insert prompt template"),"aria-haspopup":"menu","aria-expanded":c,className:"w-7 h-7 flex items-center justify-center rounded-lg transition-colors "+(c?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10":"text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10"),children:t(Ae,{size:15})})}),e(Be,{open:c,onClose:g,anchorRef:l,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:s("Insert prompt template")}),o.length>5&&t("div",{className:"px-3 pb-2 pt-1",children:t("input",{autoFocus:!0,type:"text",value:h,onChange:e=>u(e.target.value),onKeyDown:e=>{"Escape"===e.key&&g()},placeholder:s("Search prompts..."),"aria-label":s("Search prompts..."),className:"w-full h-7 px-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[0===m.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:s("No prompt matches")}),m.map(n=>e("button",{type:"button",onClick:()=>{i(n.content),g()},className:"w-full px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t("div",{className:"text-[0.8125rem] text-gray-900 dark:text-white truncate",children:n.title}),n.description&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:n.description})]},n.id))]})]})]})},Xe=({quota:n,t:r})=>{const{used:a,limit:o,period:i}=n;if(null===o)return t(He,{title:i?y(r,"Usage · {period}",{period:i}):r("Usage"),children:t("span",{className:"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30",children:b(a)})});const s=o>0?Math.min(a/o,1):1,l=!(o>0)||a>=o,c=s>=.75,d=l?"bg-red-500":c?"bg-amber-500":"bg-[var(--chat-accent)]/60",h=l?"text-red-500 dark:text-red-400":c?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",u=`${b(a)}/${b(o)}`,g=r(l?"Quota reached":"Quota"),p=i?`${g} · ${i}`:g;return t(He,{title:p,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${p} ${u}`,children:[t("span",{className:"h-1 w-10 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:t("span",{className:`block h-full rounded-full transition-[width] duration-300 ${d}`,style:{width:100*s+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${h}`,children:u})]})})},Ye=({inputValue:s,onInputChange:l,onSend:c,onStop:d,isLoading:h,canSteer:u=!1,attachedFiles:g=[],onFileAdd:p,onFileRemove:m,onPaste:f,t:x,mode:w,separatorColor:y,prompts:v,quota:b,contextUsage:k,composerToolbar:N})=>{const C=a(null),S=a(null),_=function(e){const[t,n]=r(!1),[s,l]=r(""),c=a(null),d=a(!1),h=a(e);h.current=e;const u=null!==qe();i(()=>{const e=qe();if(!e)return;const t=new e;return t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US",t.onresult=e=>{let t="",n="";for(let r=e.resultIndex;r<e.results.length;r++){const a=e.results[r];a.isFinal?n+=a[0].transcript:t+=a[0].transcript}n?(h.current(n),l("")):l(t)},t.onerror=()=>{d.current=!1,n(!1),l("")},t.onend=()=>{if(d.current)try{return void t.start()}catch{}n(!1),l("")},c.current=t,()=>{d.current=!1,c.current=null;try{t.stop()}catch{}}},[]);const g=o(()=>{d.current=!1,l(""),n(!1);try{c.current?.stop()}catch{}},[]);return{supported:u,listening:t,interim:s,toggle:o(()=>{const e=c.current;if(e)if(d.current)g();else try{d.current=!0,e.start(),n(!0)}catch{d.current=!1,n(!1)}},[g]),stop:g}}(e=>{l(s.trim()?`${s.trimEnd()} ${e}`:e)}),I=Boolean(v&&v.length>0||b||k||N||_.supported),L=Boolean(p&&m&&f),M=s.trim()||L&&g.length>0,z=L&&g.some(e=>"pending"===e.uploadStatus),A=M&&!z,T=L&&g.length>0,E=h&&u&&Boolean(s.trim())&&!T,$=x(h&&u&&!T?"Enter to send now · Esc to stop":h&&T?"Attachments wait for the current response":"Uses AI. Verify results.");return e("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-white/10 "+("floating"===w?"rounded-b-xl":""),style:y?{borderTopColor:y,borderTopWidth:1}:void 0,children:[L&&g.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:g.map((n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] "+("error"===n.uploadStatus?"border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400":"pending"===n.uploadStatus?"border-gray-200 dark:border-white/10 text-gray-400 dark:text-white/40":"border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60"),children:["pending"===n.uploadStatus?t("span",{className:"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin"}):t(me,{size:14}),n.name,"error"===n.uploadStatus&&t("span",{className:"text-red-400 text-[0.6rem]",children:"✕"}),t("button",{type:"button",onClick:()=>m?.(r),className:"ml-0.5 text-gray-400 dark:text-white/30 hover:text-gray-600 dark:hover:text-white/60",children:"×"})]},r))}),e("div",{className:"flex items-center border border-gray-200 dark:border-white/10 rounded-xl px-2 py-1 transition-colors focus-within:border-[var(--chat-accent)]",children:[L&&e(n,{children:[t("input",{ref:C,type:"file",multiple:!0,hidden:!0,onChange:e=>{p?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>C.current?.click(),className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 mr-0.5 transition-colors",children:t(ne,{size:18})})]}),t("textarea",{ref:S,placeholder:x("Ask a question..."),value:s,onChange:e=>{l(e.target.value);const t=e.target;t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,120)}px`},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),_.stop(),c()),"Escape"===e.key&&h&&(e.preventDefault(),d())},onPaste:f,rows:1,className:"flex-1 bg-transparent border-none outline-hidden resize-none text-[0.8125rem] py-1.5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 filigran-chat-scrollable",style:{maxHeight:120}}),E&&t(He,{title:x("Send now"),children:t("button",{type:"button",onClick:c,"aria-label":x("Send now"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Me,{size:18})})}),t(He,{title:h?x("Stop generating"):z?x("Files uploading..."):"",children:t("button",{type:"button",onClick:h?d:c,disabled:!h&&!A,className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 "+(h?"text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5":A?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20":"text-gray-300 dark:text-white/20 cursor-not-allowed"),children:t(h?Te:Me,{size:18})})})]}),I&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[v&&v.length>0&&t(Ze,{prompts:v,onPick:e=>{l(s.trim()?`${s.trimEnd()}\n\n${e}`:e),S.current?.focus()},t:x}),_.supported&&t(He,{title:_.listening?x("Stop dictation"):x("Dictate a message"),children:t("button",{type:"button",onClick:_.toggle,"aria-label":_.listening?x("Stop dictation"):x("Dictate a message"),"aria-pressed":_.listening,className:"w-7 h-7 flex items-center justify-center rounded-lg transition-colors "+(_.listening?"text-red-500 bg-red-500/10 hover:bg-red-500/20":"text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10"),children:_.listening?t(Ie,{size:15}):t(_e,{size:15})})}),_.interim&&t("span",{className:"text-[0.7rem] italic text-gray-400 dark:text-white/30 truncate max-w-[45%]",children:_.interim}),N,(k||b)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[k&&t(Ke,{usage:k,t:x}),b&&t(Xe,{quota:b,t:x})]})]}),t("p",{className:"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70",children:$})]})};function Qe(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function et(e){const t=a(null);return i(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const tt="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",nt=({proposal:n,decision:a,onDecide:o,disabled:i,t:s})=>{const[l,d]=r(!1),[h,u]=r(""),g=c(),p=et(l),m=a?.verdict,f=Object.keys(n.arguments??{}),x=e=>{o({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&h.trim()?{rejectionReason:h.trim()}:{}})};return e("div",{className:"rounded-lg border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2",children:[e("div",{className:"flex items-start justify-between gap-2",children:[e("div",{className:"min-w-0 flex items-start gap-2",children:[t(Ue,{size:13,className:"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400"}),e("div",{className:"min-w-0",children:[t("p",{className:"truncate font-mono text-xs text-gray-800 dark:text-white/85",children:n.toolName||s("unknown tool")}),n.toolDescription&&t("p",{className:"mt-0.5 text-[0.7rem] text-gray-600 dark:text-white/60",children:n.toolDescription}),n.source&&t("p",{className:"mt-0.5 text-[0.65rem] text-gray-400 dark:text-white/35",children:n.source})]})]}),m&&t("span",{className:"shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===m?"bg-red-500/15 text-red-600 dark:text-red-300":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"),children:s("reject"===m?"Declined":"approve_always"===m?"Always allowed":"Approved")})]}),f.length>0&&t("div",{className:"flex flex-col gap-1.5",children:f.map(r=>{const a=function(e,t){const n=e?.properties;if(!n||"object"!=typeof n)return{};const r=n[t];if(!r||"object"!=typeof r)return{};const a=r;return{description:"string"==typeof a.description?a.description:void 0,type:"string"==typeof a.type?a.type:void 0}}(n.inputSchema,r);return e("div",{className:"text-[0.7rem]",children:[e("div",{className:"flex flex-wrap items-baseline gap-1.5",children:[t("span",{className:"font-mono text-gray-700 dark:text-white/75",children:r}),a.description&&e("span",{className:"text-gray-500 dark:text-white/45",children:["— ",a.description]})]}),t("pre",{className:"mt-0.5 whitespace-pre-wrap break-all font-mono text-gray-600 dark:text-white/60",children:Qe(n.arguments?.[r])})]},r)})}),!m&&l&&e("div",{ref:p,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:g,className:"text-[0.7rem] text-gray-500 dark:text-white/45",children:s("Why not? The agent sees this and can adapt (optional)")}),t("textarea",{id:g,autoFocus:!0,rows:2,value:h,onChange:e=>u(e.target.value),placeholder:s("e.g. wrong environment — use staging instead"),className:"w-full resize-none rounded-md border border-gray-200 bg-white px-2 py-1 text-[0.7rem] text-gray-800 outline-none focus:border-[var(--chat-accent)]/50 dark:border-white/10 dark:bg-white/[0.03] dark:text-white/85"}),e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",disabled:i,onClick:()=>x("reject"),className:`${tt} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(Oe,{size:13}),s("Decline this call")]}),t("button",{type:"button",disabled:i,onClick:()=>{d(!1),u("")},className:`${tt} text-gray-500 hover:bg-gray-100 dark:text-white/50 dark:hover:bg-white/5`,children:s("Back")})]})]}),!m&&!l&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:i,onClick:()=>d(!0),className:`${tt} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(Oe,{size:13}),s("No")]}),e("button",{type:"button",disabled:i,onClick:()=>x("approve"),className:`${tt} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(ie,{size:13}),s("Yes")]}),t("button",{type:"button",disabled:i,onClick:()=>x("approve_always"),title:s("Also applies to your scheduled runs, until you revoke it"),className:`${tt} border border-gray-200 text-gray-700 hover:bg-gray-100 dark:border-white/15 dark:text-white/70 dark:hover:bg-white/5`,children:s("Yes, always")})]})]})},rt=({proposals:n,onSubmit:o,isSubmitting:s,error:l,t:c})=>{const[d,h]=r({}),u=a(!1),[g,p]=r(!1);i(()=>{l&&(u.current=!1,p(!1))},[l]);const m=s||g,f=e=>{u.current||s||(u.current=!0,p(!0),o(e))},x=n.filter(e=>d[e.toolCallId]).length,w=x===n.length&&n.length>0,v=Object.values(d).some(e=>"approve_always"===e.verdict),b=et(v),k=et(!0);return e("div",{ref:k,className:"flex flex-col gap-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.02] p-3",children:[e("p",{className:"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300",children:[t(ee,{size:13,className:"mt-0.5 shrink-0"}),1===n.length?c("The agent needs your approval to run a tool:"):c("The agent needs your approval to run these tools:")]}),n.map(e=>t(nt,{proposal:e,decision:d[e.toolCallId],disabled:m,t:c,onDecide:e=>{const t={...d,[e.toolCallId]:e};h(t);const r=n.map(e=>t[e.toolCallId]);r.every(Boolean)&&!r.some(e=>"approve_always"===e.verdict)&&f(r)}},e.toolCallId)),v&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(ee,{size:13,className:"mt-0.5 shrink-0"}),c("“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.")]}),l&&t("p",{className:"text-[0.7rem] text-red-600 dark:text-red-300",children:l}),e("div",{ref:b,className:"flex items-center justify-between gap-2",children:[t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40",children:n.length>1?y(c,"{decided}/{total} decided",{decided:x,total:n.length}):""}),t("button",{type:"button",disabled:!w||m,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${tt} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:c(m?"Sending…":"Confirm")})]})]})},at=({src:n,alt:o,onClose:s,t:l})=>{const c=a(null),d=a(null),[u,g]=r(null);return i(()=>{g(v(c.current))},[]),i(()=>{const e=e=>{"Escape"===e.key&&s()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[s]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return d.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]),t("span",{ref:c,className:"hidden",children:u&&h(e("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4",onClick:s,role:"dialog","aria-modal":"true","aria-label":l("Image preview"),children:[t("button",{ref:d,type:"button",onClick:s,"aria-label":l("Close"),className:"absolute top-4 right-4 rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(le,{size:20})}),t("img",{src:n,alt:o,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},ot=({src:a,alt:o,requestHeaders:s,maxHeightClass:l="max-h-[400px]",t:c})=>{const d=!!s&&Object.keys(s).length>0&&(e=>!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(a),[h,u]=r(null),[g,p]=r(!1),[m,f]=r(!1);i(()=>{if(!d)return;let e=!1,t=null;return fetch(a,{credentials:"include",headers:{...s}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(n=>{e||(t=URL.createObjectURL(n),u(t))}).catch(()=>{e||p(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,a,s]);const x=d?h:a;return g?t("p",{className:"my-2 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:c("Image could not be loaded")}):x?e(n,{children:[e("span",{className:"group/img relative my-3 inline-block max-w-full rounded-lg border border-gray-200 p-1 transition-colors hover:border-[var(--chat-accent)]/40 dark:border-white/10",children:[t("img",{src:x,alt:o,loading:"lazy",onClick:()=>f(!0),onError:()=>p(!0),className:`max-w-full cursor-zoom-in rounded-md object-contain ${l}`}),t("button",{type:"button",onClick:()=>f(!0),"aria-label":c("Expand image"),className:"absolute top-2 right-2 rounded-md bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100",children:t(Se,{size:14})})]}),m&&t(at,{src:x,alt:o,onClose:()=>f(!1),t:c})]}):e("span",{className:"my-3 inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 dark:border-white/10",children:[t(ke,{size:14,className:"shrink-0 animate-pulse text-[var(--chat-accent)]"}),t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40",children:c("Loading image…")})]})},it="filigranChatMiniGame",st=e=>`700 ${e}px 'Courier New', ui-monospace, monospace`,lt=[["00100000100","00010001000","00111111100","01101110110","11111111111","10111111101","10100000101","00011011000"],["00100000100","10010001001","10111111101","11101110111","11111111111","00111111100","00100000100","01000000010"]];function ct(){if("undefined"==typeof window)return!0;try{return"off"!==window.localStorage.getItem(it)}catch{return!0}}function dt(e,t,n){const r=e.getContext("2d");if(!r)return()=>{};const a=r;let o=0,i=0;let s=13,l="#7b5cff",c=0,d=[],h=-1,u=[],g=[],p=0,m=0,f=0,x=0,w=0,y=performance.now();const v=Math.round(29.4);function b(e){for(let t=e;t<d.length;t++)if(d[t].alive)return t;return-1}function k(){if(i<=0)return;const e=t[c%t.length]||"";for(n(c%t.length),s=13;s>=8&&(a.font=st(s),!(a.measureText(e).width<=i-16));s--);a.font=st(s);const r=Array.from(e).map(e=>a.measureText(e).width),o=r.reduce((e,t)=>e+t,0);let l=(i-o)/2;d=Array.from(e).map((e,t)=>{const n=l;return l+=r[t],{char:e,x:n,w:r[t],alive:e.trim().length>0}}),h=b(0),u=[],g=[],m=0,f=0,p<=0&&(p=i/2)}function N(e){return d[e].x+d[e].w/2}function C(){const t=e.getBoundingClientRect(),n=window.devicePixelRatio||1;i=t.width,e.width=Math.max(1,Math.round(i*n)),e.height=Math.round(70*n),a.setTransform(n,0,0,n,0,0),function(){const t=getComputedStyle(e).getPropertyValue("--chat-accent").trim();t&&(l=t)}(),k()}let S=null;return"undefined"!=typeof ResizeObserver?(S=new ResizeObserver(C),S.observe(e)):window.addEventListener("resize",C),C(),o=requestAnimationFrame(function e(t){const n=t-y;y=t,!document.hidden&&i>0&&(function(e){const t=Math.min(e/16.6667,3);if(w+=e,w>320&&(w=0,x^=1),-1===h)0===f?f=performance.now():performance.now()-f>650&&(c++,k());else{const n=N(h);p+=(n-p)*Math.min(.16*t,1),m-=e,0===u.length&&m<=0&&Math.abs(p-n)<4&&(u.push({x:p,y:50}),m=130)}for(let e=u.length-1;e>=0;e--)if(u[e].y-=2.6*t,u[e].y<=v){if(-1!==h){const e=N(h);d[h].alive=!1;for(let t=0;t<7;t++){const n=2*Math.PI*t/7+Math.random(),r=.6+1.4*Math.random();g.push({x:e,y:v,vx:Math.cos(n)*r,vy:Math.sin(n)*r,life:1})}h=b(h+1)}u.splice(e,1)}for(let e=g.length-1;e>=0;e--){const n=g[e];n.x+=n.vx*t,n.y+=n.vy*t,n.life-=.045*t,n.life<=0&&g.splice(e,1)}}(n),function(){a.clearRect(0,0,i,70),a.fillStyle=l,a.font=st(s),a.textBaseline="middle",a.globalAlpha=.85;for(const e of d)e.alive&&a.fillText(e.char,e.x,v);a.globalAlpha=1;for(const e of u)a.fillRect(e.x-1,e.y,2,7);for(const e of g)a.globalAlpha=.9*Math.max(e.life,0),a.fillRect(e.x-1.5,e.y-1.5,3,3);a.globalAlpha=1;const e=lt[x],t=Math.round(p-11);for(let n=0;n<e.length;n++){const r=e[n];for(let e=0;e<r.length;e++)"1"===r[e]&&a.fillRect(t+2*e,50+2*n,2,2)}}()),o=requestAnimationFrame(e)}),()=>{cancelAnimationFrame(o),S?S.disconnect():window.removeEventListener("resize",C)}}const ht=({t:n,enabled:o=!0})=>{const s=l(()=>(e=>[e("Crunching the data"),e("Connecting the dots"),e("Consulting the sources"),e("Thinking it through"),e("Reticulating splines"),e("Analyzing the details"),e("Almost there"),e("Putting it together"),e("Polishing the answer"),e("Wrapping things up")])(n),[n]),c=function(){const[e,t]=r(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return i(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=()=>t(e.matches);return"function"==typeof e.addEventListener?(e.addEventListener("change",n),()=>e.removeEventListener("change",n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}(),[d,h]=r(ct),[u,g]=r(0),p=a(null),m=a(null),f=o&&d&&!c;if(i(()=>{const e=function(e){let t=e?.parentElement??null;for(;t;){const e=getComputedStyle(t).overflowY;if(("auto"===e||"scroll"===e)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}(m.current);if(!e)return;e.scrollHeight-e.scrollTop-e.clientHeight<=140&&(e.scrollTop=e.scrollHeight)},[]),i(()=>{if(f||!o)return;const e=window.setInterval(()=>g(e=>(e+1)%s.length),2600);return()=>window.clearInterval(e)},[f,o,s.length]),i(()=>{if(!f)return;const e=p.current;return e?dt(e,s,g):void 0},[f,s]),!o)return null;const x=s[u%s.length];return e("div",{ref:m,className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:x}),e("div",{className:"relative overflow-hidden rounded-md bg-[var(--chat-accent)]/[0.03]",style:c?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[f?t("canvas",{ref:p,"aria-hidden":!0,className:"block w-full",style:{height:70}}):t("div",{className:"flex items-center",style:{height:70},children:e("span",{className:"px-3 text-xs text-gray-500 dark:text-white/45",style:c?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[x,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(c?"":"animate-pulse")})]},x)}),!c&&t("button",{type:"button",onClick:()=>{const e=!d;h(e),function(e){try{window.localStorage.setItem(it,e?"on":"off")}catch{}}(e)},"aria-pressed":d,"aria-label":n(d?"Turn off the waiting mini-game":"Turn on the waiting mini-game"),title:n(d?"Turn off the waiting mini-game":"Turn on the waiting mini-game"),className:"absolute top-1 right-1 rounded p-1 transition-opacity "+(d?"text-[var(--chat-accent)] opacity-50 hover:opacity-100":"text-gray-400 dark:text-white/40 opacity-40 hover:opacity-90"),children:t(ye,{size:13})})]})]})};function ut(e,t){return e>1?y(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function gt(e,t){return e>1?y(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function pt(e,t){return e>1?y(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function mt(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/#{1,6}\s+/g,"").replace(/^[ \t]*[-*>]+[ \t]*/gm,"").replace(/[ \t]+/g," ").replace(/\n{3,}/g,"\n\n").trim()}function ft({content:e}){const n=a(null),[o,s]=r(!1),l=mt(e);return i(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight,s(e.scrollHeight>e.clientHeight+1))},[l]),l.length<3?null:t("div",{className:"ml-11 mt-2.5 max-w-[75%] rounded-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3",style:{animation:"reasoningGlow 3s ease-in-out infinite, chat-fade-in 0.5s ease-out"},children:t("div",{ref:n,className:"max-h-40 overflow-hidden"+(o?" [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)] [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]":""),children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-xs leading-5 text-gray-500 dark:text-white/45",children:l})})})}function xt(e){const t=Math.floor(e);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}const wt=({agentStatus:o,logoIcon:s,t:l,miniGameEnabled:c=!0})=>{const{label:d,StatusIcon:h,showDots:u}=function(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:ae,showDots:!1};switch(e.status){case"tool_start":{const n=e.tools??[],r=n.map(e=>e.toLowerCase());if(r.some(e=>"spawn_background_task"===e))return{label:ut(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:Re,showDots:!1};if(r.some(e=>"check_task_status"===e))return{label:gt(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:Ae,showDots:!1};if(r.some(e=>"get_task_result"===e))return{label:pt(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:Ae,showDots:!1};let a,o=Ue;if(r.some(e=>e.includes("search")||e.includes("list"))?o=Le:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?o=de:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?o=Ce:r.some(e=>e.includes("code")||e.includes("execute"))?o=Ee:r.some(e=>e.includes("web")||e.includes("browse"))&&(o=ve),n.length>0){const e=n.map(e=>e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())),r=Array.from(new Set(e));a=1===r.length?`${r[0]}…`:y(t,"{tool} (+{count} more)…",{tool:r[0],count:r.length-1})}else a=t("Using tools…");return{label:a,StatusIcon:o,showDots:!1}}case"awaiting_approval":return{label:t("Waiting for your approval…"),StatusIcon:ee,showDots:!1};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:Ae,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:Ae,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:ae,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:y(t,"Consulting {agent}…",{agent:n}),StatusIcon:Re,showDots:!1}}case"delegating":return{label:ut(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:Re,showDots:!1};case"polling":return{label:gt(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:Ae,showDots:!1};case"collecting":return{label:pt(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:Ae,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:y(t,"Transferring to {agent}…",{agent:n}),StatusIcon:pe,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:ae,showDots:!1}}}(o,l),g=o?.thinkingContent,p=o?.elapsedStartMs,[m,f]=r(()=>Date.now());i(()=>{if(null==p)return;f(Date.now());const e=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(e)},[p]);const x=null!=p?Math.max(0,(m-p)/1e3):o?.elapsedS,w="number"==typeof x&&x>=15,v=function(e,t,n){const[o,s]=r(!1),l=a(e),c=l.current!==e;return i(()=>{if(l.current=e,s(!1),!n)return;const r=window.setTimeout(()=>s(!0),t);return()=>window.clearTimeout(r)},[e,t,n]),n&&o&&!c}(g?.length??0,5e3,c),b=c&&v;return e(n,{children:[e("div",{className:"flex gap-3 items-center justify-start",children:[t("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:s})}),e("div",{className:"rounded-lg bg-gray-50 dark:bg-white/[0.03] px-4 py-3 relative overflow-hidden",children:[t("div",{className:"absolute inset-0 bg-gradient-to-r from-[var(--chat-accent)]/[0.03] via-transparent to-[var(--chat-accent)]/[0.03] animate-pulse pointer-events-none"}),e("div",{className:"relative flex items-center gap-2.5",children:[u?t("div",{className:"flex gap-[3px] items-center h-3.5 w-3.5 justify-center",children:[0,.15,.3].map((e,n)=>t("span",{className:"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50",style:{animation:`chat-dot 1s ease-in-out infinite ${e}s`}},n))}):t(h,{size:14,className:"text-[var(--chat-accent)] animate-pulse transition-all duration-300"}),t("span",{className:"text-sm text-gray-500 dark:text-white/50 transition-all duration-300",children:d}),w&&t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:xt(x)})]})]})]}),g&&!b?t(ft,{content:g}):b?t(ht,{t:l,enabled:c}):null]})},yt=e=>{if(!e)return!1;if(e.startsWith("//"))return!1;return!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e)},vt=d(({content:a,onRelativeLinkClick:o,requestHeaders:i,t:s=w})=>{const[c,d]=r(null),h=l(()=>{return function(e){if(!e)return e;const t=e.split("\n"),n=/^(\s*)(`{3,})(.*)$/,r=/^(markdown|md|mdx|markup)\b/i;let a=-1;for(let e=0;e<t.length;e++){const o=t[e].match(n);if(o&&3===o[2].length&&r.test(o[3].trim())){a=e;break}}if(-1===a)return e;const o=[];for(let e=a+1;e<t.length;e++){const r=t[e].match(n);r&&o.push({idx:e,run:r[2].length,bare:""===r[3].trim()})}const i=(e,n)=>{for(let r=e+1;r<n;r++)if(""!==t[r].trim())return!1;return!0};let s=0,l=3,c=0,d=-1;for(let e=0;e<o.length;e++){const t=o[e];if(t.bare&&0===s){const n=o[e+1];if(!n||!n.bare||i(t.idx,n.idx)){d=t.idx;break}s++}else s=t.bare?Math.max(0,s-1):s+1;c++,l=Math.max(l,t.run)}if(-1===d||0===c)return e;const h="`".repeat(Math.max(l+1,4)),u=t[a].match(n);t[a]=`${u[1]}${h}${u[3]}`;const g=t[d].match(n);return t[d]=`${g[1]}${h}`,t.join("\n")}(function(e){if(!e||-1===e.indexOf("|"))return e;const t=e.split("\n"),n=e=>{let t=e.trim();t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=[];let r="";for(let e=0;e<t.length;e++){const a=t[e];"\\"===a&&e+1<t.length?(r+=a+t[e+1],e++):"|"===a?(n.push(r),r=""):r+=a}return n.push(r),n},r=e=>e.includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e),a=e=>{const t=e.trim(),n=t.startsWith(":"),r=t.endsWith(":");return n&&r?":---:":r?"---:":n?":---":"---"},o=/^\s*(?:(?:>\s?)|(?:[-*+]\s+)|(?:\d{1,9}[.)]\s+))*(`{3,}|~{3,})(.*)$/;let i=null,s=0;const l=/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/;for(let e=0;e<t.length-1;e++){const c=t[e].match(o);if(c){const e=c[1];null===i?(i=e[0],s=e.length):e[0]===i&&e.length>=s&&""===c[2].trim()&&(i=null,s=0);continue}if(null!==i)continue;const d=t[e],h=t[e+1];if(!d.includes("|")||r(d)||!r(h))continue;const u=d.match(l),g=u?u[0].length:d.length-d.trimStart().length,p=u?" ".repeat(g):d.slice(0,g),m=n(d.slice(g)).length,f=n(h);if(m<2||f.length===m)continue;const x=[];for(let e=0;e<m;e++)x.push(f[e]?a(f[e]):"---");t[e+1]=`${p}| ${x.join(" | ")} |`}return t.join("\n")}(function(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("[")||t.startsWith("```"))return e;try{return JSON.parse(t),"```json\n"+t+"\n```"}catch{return e}}((e=a).includes("![")?e.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>``):e)));var e},[a]);return t(u,{remarkPlugins:[g,p],urlTransform:x,components:{p:({children:e})=>t("p",{className:"mb-3 last:mb-0 leading-7 break-words text-[0.8125rem] text-gray-900 dark:text-white/90",children:e}),pre:({children:e})=>t(n,{children:e}),code:({className:n,children:r})=>{const a=/language-(\w+)/.exec(n||""),o=String(r).replace(/\n$/,"");return a||o.includes("\n")?e("div",{className:"my-3 rounded-lg border border-gray-200 dark:border-white/10 overflow-hidden bg-gray-50 dark:bg-white/[0.03]",children:[e("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-gray-200 dark:border-white/10 bg-gray-100 dark:bg-white/[0.03]",children:[t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 font-mono",children:a?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>{return e=o,navigator.clipboard.writeText(e),d(e),void setTimeout(()=>d(null),2e3);var e},"aria-label":s(c===o?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors",children:c===o?t(ie,{size:14,className:"text-green-500"}):t(ce,{size:14,className:"text-gray-400 dark:text-white/40"})})]}),t("pre",{className:"m-0 px-3 py-2 overflow-x-auto",children:t("code",{className:"font-mono text-xs leading-[1.7] text-gray-800 dark:text-white/90 whitespace-pre",children:o})})]}):t("code",{className:"bg-gray-100 dark:bg-white/[0.08] px-1.5 py-0.5 rounded-sm font-mono text-xs text-[var(--chat-accent)]",children:r})},ul:({children:e})=>t("ul",{className:"list-disc pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),ol:({children:e})=>t("ol",{className:"list-decimal pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),li:({children:e})=>t("li",{className:"leading-7 break-words",children:e}),strong:({children:e})=>t("strong",{className:"font-semibold text-gray-900 dark:text-white",children:e}),em:({children:e})=>t("em",{className:"italic",children:e}),hr:()=>t("hr",{className:"my-4 border-gray-200 dark:border-white/10"}),blockquote:({children:e})=>t("blockquote",{className:"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 rounded-r-md italic text-gray-500 dark:text-white/60",children:e}),a:({href:e,children:n})=>{const r=(e=>{if(!e)return null;if(yt(e))return e;if("undefined"==typeof window)return null;try{const t=new URL(e,window.location.href);if(("http:"===t.protocol||"https:"===t.protocol)&&t.origin===window.location.origin)return`${t.pathname}${t.search}${t.hash}`||"/"}catch{}return null})(e),a=null!==r&&!!o,i=!a&&!yt(e);return t("a",{href:e,onClick:e=>{a&&(e.preventDefault(),o(r))},target:i?"_blank":void 0,rel:i?"noopener noreferrer":void 0,className:"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125",children:n})},img:({src:e,alt:n})=>"string"==typeof e&&e?t(ot,{src:e,alt:n||"",requestHeaders:i,t:s}):null,h1:({children:e})=>t("h1",{className:"mt-4 first:mt-0 mb-2 font-bold text-base text-gray-900 dark:text-white",children:e}),h2:({children:e})=>t("h2",{className:"mt-3 first:mt-0 mb-2 font-bold text-[0.9rem] text-gray-900 dark:text-white",children:e}),h3:({children:e})=>t("h3",{className:"mt-3 first:mt-0 mb-1.5 font-semibold text-[0.85rem] text-gray-900 dark:text-white",children:e}),table:({children:e})=>t("div",{className:"my-3 overflow-x-auto rounded-lg border border-gray-200 dark:border-white/10",children:t("table",{className:"w-full border-collapse text-xs",children:e})}),tr:({children:e})=>t("tr",{className:"transition-colors hover:bg-gray-50 dark:hover:bg-white/[0.02]",children:e}),th:({children:e})=>t("th",{className:"px-3 py-2 text-left font-semibold bg-gray-50 dark:bg-white/[0.04] border-b border-gray-200 dark:border-white/10 text-gray-900 dark:text-white",children:e}),td:({children:e})=>t("td",{className:"px-3 py-2 border-b border-gray-200 dark:border-white/10 text-gray-700 dark:text-white/80",children:e})},children:h})});vt.displayName="MarkdownMessage";function bt(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function kt(e){return e.replace(/_/g," ")}const Nt=({entry:n,index:a,t:o})=>{const[i,s]=r(!1),c=l(()=>bt(n.input),[n.input]),d=l(()=>bt(n.output),[n.output]),h=!!c&&"{}"!==c;return e("div",{className:"border border-gray-200 dark:border-white/[0.06] rounded-md overflow-hidden",children:[e("button",{type:"button",onClick:()=>s(e=>!e),"aria-expanded":i,className:"w-full flex items-center gap-2.5 px-3 py-2 hover:bg-gray-50 dark:hover:bg-white/[0.03] transition-colors text-left",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:a+1}),n.success?t(oe,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(Oe,{size:12,className:"shrink-0 text-red-500 dark:text-red-400"}),t("span",{className:"flex-1 min-w-0 text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono",children:kt(n.name)}),t(se,{size:14,className:"shrink-0 text-gray-400 dark:text-white/50 transition-transform duration-200 "+(i?"rotate-180":"")})]}),i&&e("div",{className:"border-t border-gray-200 dark:border-white/[0.06]",children:[h&&e("div",{className:"px-3 py-2 border-b border-gray-100 dark:border-white/[0.04] bg-gray-50/50 dark:bg-white/[0.01]",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium",children:o("Input")}),t("pre",{className:"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable",children:c})]}),e("div",{className:"px-3 py-2 bg-gray-50/50 dark:bg-white/[0.01]",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium",children:o("Output")}),t("pre",{className:"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable",children:d||o("(no output)")})]})]})]})},Ct=({msg:n,onClose:o,t:s})=>{const l=a(null),c=a(null),d=a(null),[u,g]=r(null);i(()=>{g(v(l.current))},[]),i(()=>{const e=e=>{if("Escape"===e.key)return void o();if("Tab"!==e.key)return;const t=d.current;if(!t)return;const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],a=n[n.length-1],i=document.activeElement;e.shiftKey?i!==r&&t.contains(i)||(e.preventDefault(),a.focus()):i!==a&&t.contains(i)||(e.preventDefault(),r.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return c.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]);const p=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,m=n.toolNames??[],f=n.iterations??1,x=n.transferChain??[],w=n.toolCallTrace??[],b=(n.reasoning??"").trim(),k=[f>1?y(s,"{count} iterations",{count:f}):"",1===p?s("1 tool call"):y(s,"{count} tool calls",{count:p}),1===x.length?s("1 transfer"):x.length>1?y(s,"{count} transfers",{count:x.length}):""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:u&&h(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:o,role:"presentation",children:e("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":s("Reasoning details"),onClick:e=>e.stopPropagation(),className:"w-full max-w-md max-h-full flex flex-col rounded-xl border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1e1e2e] shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]",children:[e("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-gray-200 dark:border-white/10",children:[e("div",{className:"flex items-center gap-2",children:[t(Ue,{size:15,className:"text-[var(--chat-accent)]"}),t("span",{className:"flex-1 text-[0.875rem] font-semibold text-gray-900 dark:text-white",children:s("Reasoning details")}),t("button",{ref:c,type:"button",onClick:o,"aria-label":s("Close"),className:"w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(le,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] text-gray-500 dark:text-white/40",children:k.join(" · ")})]}),e("div",{className:"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3",children:[n.isTruncated&&e("div",{className:"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90",children:[t(ee,{size:14,className:"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400"}),e("span",{children:[t("span",{className:"font-semibold",children:s("Turn limit reached.")})," ",s("The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.")]})]}),b&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(ae,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:s("Model reasoning")})]}),t("div",{className:"rounded-md border border-gray-200 dark:border-white/[0.06] bg-gray-50/50 dark:bg-white/[0.01] px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable",children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 text-gray-500 dark:text-white/45",children:mt(b)})})]}),w.length>0?t("div",{className:"flex flex-col gap-1.5",children:w.map((e,n)=>t(Nt,{entry:e,index:n,t:s},`${e.name}-${n}`))}):m.length>0&&t("div",{children:m.map((n,r)=>e("div",{className:"flex items-center gap-3 py-2 border-b border-gray-100 dark:border-white/[0.04] last:border-0",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),t(Ue,{size:12,className:"shrink-0 text-gray-400 dark:text-white/50"}),t("span",{className:"text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono",children:kt(n)})]},`${n}-${r}`))}),x.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(te,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:s("Transfer chain")})]}),t("div",{className:"flex items-center gap-1.5 flex-wrap",children:x.map((n,r)=>e("div",{className:"flex items-center gap-1.5",children:[r>0&&t("span",{className:"text-gray-300 dark:text-white/30 text-[0.72rem]",children:"→"}),e("span",{className:"inline-flex items-center gap-1 rounded-md bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]",children:[t(re,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})};function St(e){const t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return;const n=e.slice(t+1);return n.length<=8?n.toUpperCase():void 0}const _t=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const It=({text:e,t:n})=>{const[a,o]=r(!1);return t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),o(!0),setTimeout(()=>o(!1),2e3)}catch{}},title:n(a?"Copied!":"Copy response"),"aria-label":n(a?"Copied!":"Copy response"),className:"p-1 rounded-lg transition-opacity "+(a?"opacity-100 text-green-500 dark:text-green-400":"opacity-0 group-hover/msg:opacity-100 focus-visible:opacity-100 hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]"),children:t(a?ie:ce,{size:14})})},Lt=({value:r,onChange:a,t:o})=>{const i=e=>"p-1 rounded-lg transition-opacity "+(e?"opacity-100 text-[var(--chat-accent)]":"opacity-0 group-hover/msg:opacity-100 focus-visible:opacity-100 hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]");return e(n,{children:[t("button",{type:"button",onClick:()=>a("up"===r?null:"up"),title:o("Good response"),"aria-label":o("Good response"),"aria-pressed":"up"===r,className:i("up"===r),children:t(je,{size:14,filled:"up"===r})}),t("button",{type:"button",onClick:()=>a("down"===r?null:"down"),title:o("Bad response"),"aria-label":o("Bad response"),"aria-pressed":"down"===r,className:i("down"===r),children:t($e,{size:14,filled:"down"===r})})]})},Mt=d(({msg:n,isStreaming:a,agentName:o,logoIcon:i,onRelativeLinkClick:s,onDownloadFile:l,resolveAttachmentUrl:c,requestHeaders:d,feedback:h,onFeedbackChange:u,t:g})=>{const[p,m]=r(!1),f="assistant"===n.role,x=!n.content,w=(n,r)=>{const a=c&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&_t.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&_t.has(e.filename.slice(n+1).toLowerCase())}(n)?c(n):void 0;if(a)return t(ot,{src:a,alt:n.filename,requestHeaders:d,maxHeightClass:"max-h-[200px]",t:g},r);const o="working_file"===n.fileTag,i=!(s=n.size)||s<=0?"":s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(0)} KB`:`${(s/1048576).toFixed(1)} MB`;var s;return e("button",{type:"button",onClick:()=>l?.(n),title:g("Download"),className:"group flex items-center gap-2 text-left rounded-lg border px-2.5 py-1.5 transition-colors cursor-pointer max-w-[90%] "+(o?"border-gray-200 dark:border-white/10 bg-transparent":"border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5"),children:[t("span",{className:"shrink-0 "+(o?"text-gray-400 dark:text-white/40":"text-[var(--chat-accent)]"),children:t(me,{size:16})}),e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"truncate text-[0.75rem] text-gray-900 dark:text-white",children:n.filename}),(n.type||i)&&t("span",{className:"text-[0.65rem] text-gray-400 dark:text-white/40 uppercase",children:[n.type,i].filter(Boolean).join(" · ")})]}),t("span",{className:"shrink-0 text-gray-400 dark:text-white/30 group-hover:text-[var(--chat-accent)]",children:t(ue,{size:15})})]},r)},y=(n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.7rem] text-gray-600 dark:text-white/60",children:[t(me,{size:14}),n]},r),v=n.toolNames&&n.toolNames.length>0||!!(n.reasoning??"").trim()||n.toolCallTrace&&n.toolCallTrace.length>0||n.transferChain&&n.transferChain.length>0||n.isTruncated,b=f&&!x&&!a;return e("div",{className:"group/msg flex flex-col "+(f?"items-start":"items-end"),children:[f&&e("div",{className:"flex items-center gap-1.5 mb-1",children:[t("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3",children:i})}),t("span",{className:"font-semibold text-xs text-gray-900 dark:text-white",children:n.agentName??o})]}),!f&&((n.files?.length??0)>0||(n.attachments?.length??0)>0)&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end",children:(()=>{const e=[],t=new Set;return(n.files??[]).forEach((n,r)=>{!(!l||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(w({fileId:n.fileId,filename:n.name,type:St(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(y(n.name,`file-${r}`))}),(n.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(l?w(n,`att-${n.fileId}-${r}`):y(n.filename,`att-${r}`)))}),e})()}),f?e("div",{className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=function(e){if(!e)return[];const t=[],n=/\[\[FILE:([^\]]+)\]\]/g;let r=0,a=n.exec(e);for(;null!==a;)a.index>r&&t.push({type:"text",value:e.slice(r,a.index)}),t.push({type:"file",fileId:a[1]}),r=n.lastIndex,a=n.exec(e);const o=e.slice(r).replace(C,"");return o&&t.push({type:"text",value:o}),t}(n.content),r=new Map((n.attachments??[]).map(e=>[e.fileId,e])),o=new Set,i=[];return e.forEach((e,n)=>{if("text"===e.type)e.value.trim()&&i.push(t("div",{className:"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7",children:t(vt,{content:e.value,onRelativeLinkClick:s,requestHeaders:d,t:g})},`t-${n}`));else if(l){const t=r.get(e.fileId);t&&(o.add(e.fileId),i.push(w(t,`f-${e.fileId}-${n}`)))}}),l&&(n.attachments??[]).forEach(e=>{o.has(e.fileId)||i.push(w(e,`orphan-${e.fileId}`))}),0!==i.length||a||i.push(t("span",{className:"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic",children:"..."},"empty")),i})(),!x&&a&&t("span",{className:"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse"})]}):t("div",{className:"max-w-[90%] px-3.5 py-2 rounded-[14px_14px_4px_14px] bg-[var(--chat-accent-dark)] text-white text-[0.8125rem] leading-6",children:n.content}),b&&e("div",{className:"mt-0.5 flex items-center gap-0.5 text-gray-400 dark:text-white/40",children:[t(It,{text:S(n.content),t:g}),u&&t(Lt,{value:h,onChange:e=>u(n.id,e,n),t:g}),v&&t("button",{type:"button",onClick:()=>m(e=>!e),className:"p-1 rounded-lg transition-opacity "+(n.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":"opacity-50 hover:opacity-100 hover:text-[var(--chat-accent)]"),title:n.isTruncated?g("Reasoning details — turn limit reached"):g("Reasoning details"),"aria-label":n.isTruncated?g("Reasoning details — turn limit reached"):g("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":p,children:n.isTruncated?t(ee,{size:14}):t(Ne,{size:14})})]}),p&&t(Ct,{msg:n,onClose:()=>m(!1),t:g})]})});Mt.displayName="MessageRow";const zt=({messages:n,isLoading:s,agentStatus:c,agentName:d,logoIcon:h,onRelativeLinkClick:u,onDownloadFile:g,resolveAttachmentUrl:p,requestHeaders:m,miniGameEnabled:f=!0,onMessageFeedback:x,isResumingAfterDecision:w,pendingApprovals:y,onSubmitApprovalDecisions:v,isSubmittingApproval:b,approvalError:k,t:N})=>{const C=a(null),[S,_]=r(150),[I,L]=r({});i(()=>{C.current?.scrollIntoView({behavior:"smooth"})},[n]);const M=c?.thinkingContent?.length??0;i(()=>{M&&C.current?.scrollIntoView({behavior:"instant"})},[M]);const z=n[0]?.id;i(()=>{_(150)},[z]);const A=n.length>S,T=l(()=>A?n.slice(n.length-S):n,[n,S,A]),E=o((e,t,n)=>{L(n=>{if(null!==t)return{...n,[e]:t};if(!(e in n))return n;const r={...n};return delete r[e],r}),x?.(e,t,n)},[x]);let $=null;if(s)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){$=n[e].id;break}const j=!!y?.length&&!!v;return e("div",{className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable",children:[A&&t("div",{className:"flex justify-center",children:e("button",{type:"button",onClick:()=>_(e=>e+50),className:"flex items-center gap-1.5 rounded-full border border-gray-200 dark:border-white/10 px-3 py-1 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]",children:[t(se,{size:13,className:"rotate-180"}),N("Load earlier messages")]})}),T.map(e=>{const n=e.id===$;return"assistant"===e.role&&!e.content&&n?j?null:t("div",{children:t(wt,{agentStatus:c,logoIcon:h,t:N,miniGameEnabled:f})},e.id):t(Mt,{msg:e,isStreaming:n,agentName:d,logoIcon:h,onRelativeLinkClick:u,onDownloadFile:g,resolveAttachmentUrl:p,requestHeaders:m,feedback:I[e.id]??null,onFeedbackChange:x?E:void 0,t:N},e.id)}),w&&!j&&t(wt,{agentStatus:c,logoIcon:h,t:N,miniGameEnabled:f}),j&&t(rt,{proposals:y,onSubmit:v,isSubmitting:b,error:k,t:N},y.map(e=>e.toolCallId).join("|")),t("div",{ref:C})]})},At=({firstName:r,agentName:a,t:o})=>{if(!a)return t(n,{children:y(o,"How can I help you, {name}?",{name:r})});const{before:i,after:s,hasSlot:l}=function(e,t,n,r={}){const a=y(e,t,r),o=`{${n}}`,i=a.indexOf(o);return-1===i?{before:a,after:"",hasSlot:!1}:{before:a.slice(0,i),after:a.slice(i+o.length),hasSlot:!0}}(o,"How can {agent} help you, {name}?","agent",{name:r});return e(n,{children:[i,l&&t("span",{className:"text-[var(--chat-accent)]",children:a}),s]})},Tt=({firstName:n,logoIcon:r,promptSuggestions:a,onPromptClick:o,agentName:i,agentDescription:s,suggestionsLoading:l=!1,t:c})=>e("div",{className:"flex-1 flex flex-col items-center justify-center px-6 pb-8",children:[t("span",{className:"text-[var(--chat-accent)] mb-4 [&>svg]:w-12 [&>svg]:h-12 drop-shadow-[0_0_12px_var(--chat-accent-40)]",children:r}),t("h2",{className:"text-xl font-medium mb-1 text-center text-gray-900 dark:text-white",style:{fontFamily:'"Geologica", sans-serif',animation:"chat-fade-in 0.35s ease-out"},children:t(At,{firstName:n,agentName:i,t:c})},i??"default"),s&&t("p",{className:"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 text-gray-500 dark:text-white/40",children:s}),!s&&t("span",{className:"mb-5"}),(l||a.length>0)&&e("div",{className:"w-full max-w-[320px]",children:[t("span",{className:"block text-center mb-2 text-[0.65rem] tracking-[1.5px] uppercase text-[var(--chat-accent)] font-semibold",children:c("Suggestions")}),l?t("div",{"aria-hidden":!0,className:"space-y-1",children:[0,1,2].map(e=>t("div",{className:"h-8 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-100/50 dark:bg-white/[0.03] animate-pulse"},e))}):a.map(e=>t("button",{type:"button",onClick:()=>o(e),className:"w-full text-left text-[0.8125rem] text-gray-800 dark:text-white py-1.5 px-3 mb-1 rounded-lg border border-gray-200 dark:border-white/10 bg-transparent transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)]",children:e},e))]})]}),Et=({conversations:n,loading:o,activeConversationId:i,collapsed:s,onToggleCollapsed:c,onSelect:d,onDelete:h,onRename:u,onNewChat:g,t:p})=>{const[m,f]=r(""),[x,w]=r(null),[y,v]=r(""),b=a(!1),N=()=>{if(b.current)return;b.current=!0;const e=x,t=y.trim();w(null),e&&t&&u?.(e,t)},C=l(()=>{const e=m.trim().toLowerCase();return e?n.filter(t=>(t.title||"").toLowerCase().includes(e)):n},[n,m]);return e("div",s?{className:"flex flex-col items-center gap-1 border-r border-gray-200 dark:border-white/10 px-2 py-3 shrink-0",children:[t(He,{title:p("Show conversations"),children:t("button",{type:"button",onClick:c,"aria-label":p("Show conversations"),"aria-expanded":!1,className:"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t(ze,{size:17})})}),t(He,{title:p("New conversation"),children:t("button",{type:"button",onClick:g,"aria-label":p("New conversation"),className:"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t(ge,{size:17})})})]}:{className:"w-64 shrink-0 flex flex-col border-r border-gray-200 dark:border-white/10",children:[e("div",{className:"flex items-center gap-1 px-3 py-3",children:[e("button",{type:"button",onClick:g,className:"flex-1 flex items-center gap-2 rounded-lg border border-gray-200 dark:border-white/10 px-3 py-1.5 text-[0.8125rem] text-gray-700 dark:text-white/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors",children:[t(ge,{size:15}),p("New conversation")]}),t(He,{title:p("Hide conversations"),children:t("button",{type:"button",onClick:c,"aria-label":p("Hide conversations"),"aria-expanded":!0,className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:t(ze,{size:17})})})]}),n.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Le,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40"}),t("input",{type:"text",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f("")},placeholder:p("Search conversations..."),"aria-label":p("Search conversations..."),className:"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable",children:[o&&0===n.length&&t("div",{className:"px-3 py-2",children:t(We,{size:16})}),!o&&0===n.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:p("No conversations yet")}),n.length>0&&0===C.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:p("No conversation matches")}),C.map(n=>{const r=n.conversationId===i,a=n.conversationId===x;return e("div",{role:"button",tabIndex:0,"aria-current":r,onClick:()=>d(n.conversationId),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),d(n.conversationId))},className:"group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors "+(r?"bg-[var(--chat-accent)]/10":"hover:bg-gray-100 dark:hover:bg-white/[0.06]"),children:[t("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg "+(r?"bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]":"bg-gray-100 dark:bg-white/[0.06] text-gray-400 dark:text-white/30"),children:t(re,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[a?t("input",{autoFocus:!0,value:y,onChange:e=>v(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&N(),"Escape"===e.key&&(b.current=!0,w(null))},onBlur:N,"aria-label":p("Conversation title"),className:"w-full rounded-md bg-white dark:bg-white/10 px-1.5 py-0.5 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]"}):t("span",{className:"block truncate text-[0.8125rem] "+(r?"text-gray-900 dark:text-white":"text-gray-700 dark:text-white/70"),children:n.title||p("Untitled conversation")}),(n.agentName||n.updatedAt)&&!a&&e("span",{className:"block text-[0.65rem] text-gray-400 dark:text-white/30 truncate",children:[n.agentName,n.agentName&&n.updatedAt?" · ":"",n.updatedAt?k(n.updatedAt,p):""]})]}),!a&&e("span",{className:"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[u&&t("button",{type:"button",onClick:e=>{var t,r;e.stopPropagation(),t=n.conversationId,r=n.title||"",b.current=!1,w(t),v(r)},"aria-label":p("Rename conversation"),title:p("Rename conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(ge,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),h(n.conversationId)},"aria-label":p("Delete conversation"),title:p("Delete conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-red-500 dark:hover:text-red-400",children:t(De,{size:13})})]})]},n.conversationId)})]})]})},$t=({mode:n,onClose:s,onModeChange:c,topOffset:d=0,apiBaseUrl:h,apiEndpoints:u,agentDashboardUrl:g,user:p,t:f=w,accentColor:x="#7b5cff",logoIcon:y,promptSuggestions:v,draftBorderColor:b,resizable:k=!1,onWidthChange:N,onResizeStart:C,onResizeEnd:S,disableFileManagement:_=!1,onRelativeLinkClick:A,onDownloadError:T,maxFileCount:E,maxTotalSize:$,requestHeaders:j,pageContext:D,pushContentSelector:R,backendType:U="rest",miniGameEnabled:O=!0,notifyOnComplete:B=!0,onTaskComplete:H,onMessageFeedback:G,disableImagePreviews:J=!1,contextUsageEnabled:K=!0,composerToolbar:Z})=>{const[ee,te]=r(!1),{agents:ne,agentsLoading:re,agentsError:ae,selectedAgent:oe,agentMenuOpen:ie,setAgentMenuOpen:se,handleSwitchAgent:le}=F({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j}),{messages:ce,inputValue:de,setInputValue:ue,isLoading:ge,agentStatus:pe,attachedFiles:me,conversationId:fe,contextUsage:xe,transferredAgent:we,canSteer:ye,pendingApprovals:ve,isSubmittingApproval:be,approvalError:ke,submitApprovalDecisions:Ne,isResumingAfterDecision:Ce,historyReloadNonce:Se,historyLoadedRef:_e,conversationIdRef:Ie,handleFileAdd:Le,handlePaste:Me,handleSendMessage:ze,handleNewChat:Ae,handleStopGenerating:Te,setAttachedFiles:Ee,setMessages:$e,setContextUsage:je,updateConversationId:De,handleSwitchConversation:Re}=W({apiBaseUrl:h,apiEndpoints:u,backendType:U,agentSlug:oe?.slug,requestHeaders:j,pageContext:D,t:f,maxFileCount:E,maxTotalSize:$}),{suggestions:Ue,loading:Oe}=Q({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j,agentSlug:oe?.slug}),Be=l(()=>(Ue??v)?.map(e=>f(e))??(e=>[e("Help me create a new simulation scenario"),e("What are the latest attack patterns?"),e("How do I configure detection rules?"),e("Summarize my recent findings")])(f),[Ue,v,f]),{prompts:We,quota:He,refreshQuota:Fe}=Y({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j}),{historyEnabled:qe,conversations:Ve,conversationsLoading:Ge,refreshConversations:Je,deleteConversation:Ke,renameConversation:Ze}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[i,s]=r([]),[l,c]=r(!1),d="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,h=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,u=o(async()=>{if(d){c(!0);try{const e=await fetch(h,{method:"GET",headers:{...a??{}}});if(!e.ok)return void s([]);const t=await e.json(),n=Array.isArray(t)?t:Array.isArray(t?.conversations)?t.conversations:[];s(n.map(P).filter(e=>null!==e))}catch{s([])}finally{c(!1)}}},[d,h,a]),g=o(async e=>{if(!d)return!1;try{return!!(await fetch(`${h}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...a??{}}})).ok&&(s(t=>t.filter(t=>t.conversationId!==e)),!0)}catch{return!1}},[d,h,a]),p=o(async(e,t)=>{const n=t.trim();if(!d||!n)return!1;const r=i;s(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{return!!(await fetch(`${h}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...a??{}},body:JSON.stringify({title:n})})).ok||(s(r),!1)}catch{return s(r),!1}},[d,h,a,i]);return{historyEnabled:d,conversations:i,conversationsLoading:l,refreshConversations:u,deleteConversation:g,renameConversation:p}}({apiBaseUrl:h,apiEndpoints:u,backendType:U,requestHeaders:j}),[Xe,Qe]=r(!1),[et,tt]=r(!1),nt="fullscreen"===n&&qe;i(()=>{nt&&Je()},[nt,fe,Je]);const rt=a(!1);i(()=>{rt.current&&!ge&&(Fe(),nt&&Je()),rt.current=ge},[ge,Fe,nt,Je]);const at=e=>{Qe(!1),Re(e)},ot=async e=>{await Ke(e)&&e===Ie.current&&Ae()},{sidebarWidth:it,handleResizeStart:st,defaultWidth:lt,isResizing:ct}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:o,onResizeEnd:s}){const[l,c]=r(()=>{if("undefined"==typeof window)return q;const e=localStorage.getItem(V);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=q)return t}return q}),[d,h]=r(!1),u=a(!1),g=a(l);g.current=l;const p=a(n);p.current=n;const m=a(s);return m.current=s,i(()=>{"sidebar"===e&&t&&p.current?.(g.current)},[e,t]),i(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!u.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,q),n);c(r),g.current=r,p.current?.(r)},r=()=>{u.current&&(u.current=!1,h(!1),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem(V,String(g.current)),m.current?.())},a=()=>{const e=.4*window.innerWidth;if(g.current>e){const t=Math.max(e,q);c(t),g.current=t,p.current?.(t)}};return document.addEventListener("mousemove",n),document.addEventListener("mouseup",r),window.addEventListener("resize",a),()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",r),window.removeEventListener("resize",a)}},[e,t]),{sidebarWidth:l,handleResizeStart:e=>{e.preventDefault(),u.current=!0,h(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",o?.()},defaultWidth:q,isResizing:d}}({mode:n,resizable:k,onWidthChange:N,onResizeStart:C,onResizeEnd:S});i(()=>{const e="sidebar"===n?k?it:lt:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",ct?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),R){const e=document.querySelector(R);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=ct?"none":"padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)",()=>{e.style.paddingRight=n,e.style.transition=r,document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}}}return()=>{document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}},[R,n,it,lt,k,ct]);const dt=l(()=>y??t(he,{size:24}),[y]),ht=p.firstName,[ut,gt]=r(null),pt=we?.name||ut||oe?.name||f("Assistant"),mt=o(()=>{if("undefined"==typeof document)return!1;const e=document.querySelector(".filigran-chatbot.fixed");return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);X({isLoading:ge,agentName:pt,t:f,enabled:B,onComplete:H,isViewingChat:mt});const ft=null!=u?.download,xt="rest"===U&&null!==u?.download&&(!u?.singleEndpoint||ft),wt=o(e=>`${h}${u?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[h,u]),yt=o(async e=>{const t=wt(e);try{const n=await fetch(t,{method:"GET",credentials:"include",headers:{...j??{}}});if(!n.ok)throw new Error(`Download failed: ${n.status}`);const r=await n.blob(),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=e.filename||"download",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a)}catch(t){T?.(t,e)}},[wt,j,T]),vt={"--chat-accent":x,"--chat-accent-10":m(x,.1),"--chat-accent-40":m(x,.25),"--chat-accent-50":m(x,.5),"--chat-accent-dark":x},bt=a(!0);i(()=>(bt.current=!0,()=>{bt.current=!1}),[]),i(()=>{if(null===u?.sessions||u?.singleEndpoint||"legacy"===U||"ag-ui"===U)return;if(!fe)return void gt(null);if(_e.current||!oe)return;_e.current=!0;const e=fe,t=()=>!bt.current||Ie.current!==e;fetch(`${h}${u?.sessions??"/chat/sessions"}`,{method:"POST",headers:{"Content-Type":"application/json",...j??{}},body:JSON.stringify({conversation_id:fe,agent_slug:oe.slug})}).then(e=>t()?null:e.ok?e.json():(De(null),null)).then(n=>{if(!n||t())return;if("string"==typeof n.conversation_id&&n.conversation_id&&n.conversation_id!==e&&De(n.conversation_id),gt("string"==typeof n.agent_name?n.agent_name:null),!n.messages?.length)return;const r=n.messages.map((e,t)=>({id:`restored-${t}`,role:e.role,content:e.content,timestamp:new Date,agentName:"string"==typeof e.agent_name?e.agent_name:void 0,attachments:L(e.attachments),toolNames:Array.isArray(e.tool_names)?e.tool_names:void 0,toolCallCount:"number"==typeof e.tool_call_count?e.tool_call_count:void 0,iterations:"number"==typeof e.iterations?e.iterations:void 0,reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:M(e.tool_call_trace),transferChain:z(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0}));$e(r);for(let e=n.messages.length-1;e>=0;e-=1){const t=I(n.messages[e]);if(t){je(t);break}}}).catch(()=>{t()||De(null)})},[fe,oe,h,u,U,Se,_e,Ie,bt,j,$e,je,De]);const kt=(()=>{const e="filigran-chatbot";switch(n){case"sidebar":return`${e} fixed right-0 bottom-0 flex flex-col bg-white dark:bg-[#1e1e2e] border-l border-gray-200 dark:border-white/10 z-[1200]`;case"floating":return`${e} fixed bottom-5 right-5 flex flex-col bg-white dark:bg-[#1e1e2e] rounded-xl shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border border-gray-200 dark:border-white/10`;case"fullscreen":return`${e} fixed right-0 bottom-0 left-0 flex flex-col bg-gray-50 dark:bg-[#161622] z-[1400]`;default:return e}})(),Nt={...vt,..."sidebar"===n?{top:d,width:k?it:lt}:"floating"===n?{width:380,height:560}:{top:d}};return e("div",{className:kt,style:Nt,children:["sidebar"===n&&k&&t("div",{onMouseDown:st,className:"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group",children:t("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 rounded-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100"})}),t(Pe,{mode:n,agentName:pt,agents:ne,agentsLoading:re,agentsError:ae,selectedAgent:oe,transferredFrom:we?oe?.name:void 0,agentMenuOpen:ie,onAgentMenuToggle:()=>se(e=>!e),onAgentMenuClose:()=>se(!1),onSwitchAgent:e=>{e&&le(e,()=>{Ae()})},modeMenuOpen:ee,onModeMenuToggle:()=>te(e=>!e),onModeMenuClose:()=>te(!1),onModeChange:c,onNewChat:Ae,onClose:s,logoIcon:dt,agentDashboardUrl:g,historyEnabled:qe&&!nt,historyMenuOpen:Xe,onHistoryMenuToggle:()=>{const e=!Xe;e&&Je(),Qe(e)},onHistoryMenuClose:()=>Qe(!1),conversations:Ve,conversationsLoading:Ge,activeConversationId:fe,onSelectConversation:at,onDeleteConversation:e=>{ot(e)},t:f}),e("div",{className:nt?"flex flex-1 min-h-0":"contents",children:[nt&&t(Et,{conversations:Ve,loading:Ge,activeConversationId:fe,collapsed:et,onToggleCollapsed:()=>tt(e=>!e),onSelect:at,onDelete:e=>{ot(e)},onRename:(e,t)=>{Ze(e,t)},onNewChat:Ae,t:f}),e("div",{className:nt?"flex flex-1 flex-col min-w-0":"contents",children:[0===ce.length?t(Tt,{firstName:ht,logoIcon:dt,promptSuggestions:Be,suggestionsLoading:Oe,agentName:oe?.name,agentDescription:oe?.description,onPromptClick:ue,t:f}):t(zt,{messages:ce,isLoading:ge,agentStatus:pe,agentName:pt,logoIcon:dt,onRelativeLinkClick:A,onDownloadFile:xt?yt:void 0,resolveAttachmentUrl:xt&&!J?wt:void 0,requestHeaders:j,miniGameEnabled:O,onMessageFeedback:G,isResumingAfterDecision:Ce,pendingApprovals:ve,onSubmitApprovalDecisions:Ne,isSubmittingApproval:be,approvalError:ke,t:f}),t(Ye,{inputValue:de,onInputChange:ue,onSend:ze,onStop:Te,isLoading:ge,canSteer:ye,attachedFiles:_?[]:me,onFileAdd:_?void 0:Le,onFileRemove:_?void 0:e=>Ee(t=>t.filter((t,n)=>n!==e)),onPaste:_?void 0:Me,t:f,mode:n,separatorColor:b,prompts:We,quota:He,contextUsage:K?xe:null,composerToolbar:Z})]})]})]})},jt=({isOpen:n,onToggle:r,label:a,accentColor:o="#7b5cff",icon:i,t:s=w})=>{const l=i??t(he,{size:16});return e("button",{type:"button",onClick:r,className:"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap rounded-md border transition-colors",style:{borderColor:n?o:m(o,.5),color:o,backgroundColor:n?m(o,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=o,e.currentTarget.style.backgroundColor=m(o,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?o:m(o,.5),e.currentTarget.style.backgroundColor=n?m(o,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:l}),a??s("Ask Assistant")]})};export{$t as ChatPanel,jt as ChatToggleButton};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|