@filigran/chatbot 3.12.2 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,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,useInsertionEffect as s,useLayoutEffect as l,useMemo as c,useId as d,createContext as u,memo as h,useContext as g}from"react";import{createPortal as p}from"react-dom";import m from"remark-gfm";import f from"remark-parse";import{unified as x}from"unified";import w from"react-markdown";import b from"remark-breaks";function y(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}function v(e){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 u="`".repeat(Math.max(l+1,4)),h=t[a].match(n);t[a]=`${h[1]}${u}${h[3]}`;const g=t[d].match(n);return t[d]=`${g[1]}${u}`,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],u=t[e+1];if(!d.includes("|")||r(d)||!r(u))continue;const h=d.match(l),g=h?h[0].length:d.length-d.trimStart().length,p=h?" ".repeat(g):d.slice(0,g),m=n(d.slice(g)).length,f=n(u);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}}((t=e).includes("![")?t.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>`![${t.replace(/\s+/g," ").trim()}](${n})`):t)));var t}const k=new Set(["http","https","mailto","tel"]);function N(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 k.has(o)||"data"===o&&/^data:image\//i.test(e)?e:""}const C=e=>e;function S(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function I(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function _(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 L(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 S(t,"{count}m ago",{count:a});const o=Math.floor(a/60);if(o<24)return S(t,"{count}h ago",{count:o});const i=Math.floor(o/24);return i<7?S(t,"{count}d ago",{count:i}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const M=/\[\[FILE:[^\]]+\]\]/g,T=/\[\[FILE(?::[^\]]*)?\]?$/;function E(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(T,"");return o&&t.push({type:"text",value:o}),t}function z(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function A(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function $(e,t,n){return"rest"!==n||t?.singleEndpoint||!t?.feedback?null:`${e}${t.feedback}`}async function j(e,t,n,r,a,o){const{url:i,init:s}=function(e,t,n,r,a){const o=`${e}/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}/feedback`;return r?{url:o,init:{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...a},body:JSON.stringify({rating:r.rating,comment:A(r.comment)})}}:{url:o,init:{method:"DELETE",credentials:"include",headers:{...a}}}}(t,n,r,a,o);try{return(await e(i,s)).ok}catch{return!1}}const D=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function R(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 D){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 U(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 O(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 H(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 W(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 B(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=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=W(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:U(e.attachments),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:O(e.tool_call_trace),transferChain:H(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:R(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0}:{action:"noop"}}function F(e){if(!e||"object"!=typeof e)return;const{rating:t,comment:n}=e;return"positive"===t||"negative"===t?{rating:t,comment:"string"==typeof n&&n.trim()?n:null}:void 0}function q(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 P(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 G="filigranChatConversationId",V="filigranChatLegacyChatId",K=e=>`filigranChatDraft:${e??"new"}`;function Y(e){if("undefined"==typeof window)return"";try{return sessionStorage.getItem(K(e))??""}catch{return""}}function J(e,t){if("undefined"!=typeof window)try{t?sessionStorage.setItem(K(e),t):sessionStorage.removeItem(K(e))}catch{}}const Z=52428800;function X({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:s,requestHeaders:l,pageContext:c,t:d,maxFileCount:u=10,maxTotalSize:h=52428800}){const g="legacy"===n,[p,m]=r([]),[f,x]=r(!1),[w,b]=r(null),[y,v]=r(()=>"undefined"==typeof window?null:localStorage.getItem(G)),[k,N]=r(()=>Y("undefined"==typeof window?null:localStorage.getItem(G))),[C,S]=r([]),[I,_]=r(null),[L,M]=r(null),[T,E]=r(null),[z,A]=r(!1),[$,j]=r(null),[D,R]=r(!1),[U,O]=r(0),[H,F]=r(0),[K,X]=r(()=>"undefined"==typeof window?null:localStorage.getItem(V)),Q=a(!1),ee=a(null),te=a(null),ne=a(!1),re=a(y),ae=a(f);ae.current=f;const oe=a(c);oe.current=c;const ie=a(null),se=a(!1),le=a(null),ce=a(0),de=a(null),ue=a(new AbortController),he=Number.isFinite(u)&&u>0?Math.floor(u):10,ge=Number.isFinite(h)&&h>0?h:Z,pe=()=>g||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,me=()=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const r=t?.approve;return r?`${e}${r}`:null},fe=r=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const a=t?.pendingApprovals;return a?`${e}${a}/${r}/pending-approvals`:null},xe=async e=>{const t=fe(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:W(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},we=o(()=>{Q.current=!1,O(e=>e+1)},[]),be=()=>g||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,ye=o(e=>{re.current=e,v(e),e?localStorage.setItem(G,e):localStorage.removeItem(G)},[]),ve=async n=>{if(re.current)return re.current;if(de.current)return de.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{de.current=null}})();return de.current=a,a},ke=async(e,t,n)=>{const r=be(),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]},Ne=e=>{if(!e||0===e.length||!be())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=ge-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=ue.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 ke(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)},Ce=()=>{te.current?.close(),te.current=null,ee.current?.abort(),ee.current=null,ue.current.abort(),ue.current=new AbortController,de.current=null,m([]),N(""),S([]),x(!1),b(null),_(null),M(null),E(null),j(null),R(!1),ie.current=null,se.current=!1,le.current=null,ne.current=!1,Q.current=!1,g?(X(null),localStorage.removeItem(V)):ye(null)};i(()=>{const e=window.setTimeout(()=>J(y,k),300);return()=>window.clearTimeout(e)},[k,y]),i(()=>()=>te.current?.close(),[]);const Se=a({conversationId:y,inputValue:k});Se.current={conversationId:y,inputValue:k},i(()=>()=>{const{conversationId:e,inputValue:t}=Se.current;J(e,t)},[]),i(()=>{const e=y;if(!e||f)return;if(le.current===e)return;fe(e)&&me()&&(le.current=e,(async()=>{const t=await xe(e);t?.proposals&&(re.current!==e||ae.current||(ie.current=e,se.current=!0,j(null),E(t.proposals)))})())},[y,f]),i(()=>{if(!T?.length||!se.current)return;const e=ie.current,t=e?fe(e):null;if(!t)return;const n=window.setInterval(()=>{fetch(t,{headers:{...l??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[T]),i(()=>{if(!D)return;const e=ie.current;if(!e)return void R(!1);if(Date.now()>=ce.current)return R(!1),void we();let t=!1;const n=window.setTimeout(async()=>{const n=await xe(e);if(!t){if(n)return n.proposals?(se.current=!0,j(null),E(n.proposals),void R(!1)):n.turnRunning?void F(e=>e+1):(R(!1),void we());F(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[D,H,we]);const Ie=f&&null!==pe()&&null!==y;return{messages:p,inputValue:k,setInputValue:N,isLoading:f,agentStatus:w,attachedFiles:C,conversationId:y,contextUsage:L,transferredAgent:I,canSteer:Ie,pendingApprovals:T,isSubmittingApproval:z,approvalError:$,submitApprovalDecisions:async e=>{const t=me(),n=ie.current??re.current;if(0!==e.length)if(t&&n){j(null),A(!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 E(null),se.current?(se.current=!1,ce.current=Date.now()+9e5,void R(!0)):void b(e=>e?{...e,status:"thinking"}:{status:"thinking"});j(409===r.status?d("This turn is no longer waiting for a decision."):d("Could not send your decision. Please try again."))}catch{j(d("Could not send your decision. Please try again."))}finally{A(!1)}}else j(d("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:D,historyReloadNonce:U,historyLoadedRef:Q,conversationIdRef:re,handleFileAdd:Ne,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),Ne(t))},handleSendMessage:async()=>{const r=k.trim();if(f)return void(r&&0===C.length&&pe()&&re.current&&(N(""),await(async e=>{const t=pe(),n=re.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),b({status:"thinking"}),ne.current=!1;const i=crypto.randomUUID();m(e=>[...e,{id:i,role:"assistant",content:"",timestamp:new Date}]);let c=i,u="",h=!1;const p=function(e){let t=!1,n="",r=null,a=!1;const o=()=>{null!==r&&cancelAnimationFrame(r),r=null},i=()=>{if(o(),!t&&!n)return;const r=t,a=n;t=!1,n="",e(r,a)},s=()=>{null===r&&("function"==typeof requestAnimationFrame?r=requestAnimationFrame(()=>{r=null,i()}):i())};return{text:()=>{a||(t=!0,s())},thinking:e=>{a||(n+=e,s())},flush:i,close:()=>{a=!0,o(),t=!1,n=""}}}((e,t)=>{if(e){const e=c,t=u;b(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),m(n=>n.map(n=>n.id===e?{...n,content:t}:n))}t&&b(e=>({...e,status:e?.status??"thinking",thinkingContent:(e?.thinkingContent??"")+t}))});te.current=p;try{const r=new AbortController;ee.current=r;const f=(o.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),x=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:K,conversationId:re.current,agentSlug:s,pageContext:oe.current,supportsToolApproval:null!==me()});f.length>0&&(x.file_ids=f),b({status:"thinking"});const w=await fetch(g||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify(x),signal:r.signal});if(!w.ok||!w.body)return void m(e=>e.map(e=>e.id===i?{...e,content:d("Unable to connect. Please check the configuration.")}:e));const y=function(e){switch(e){case"legacy":return q;case"ag-ui":return P;default:return B}}(n),v={hasUsedTools:!1,activeNodeId:""},k=w.body.getReader(),N=new TextDecoder;let C="";const S=()=>{if(!h)return;p.flush(),h=!1,u="",c=crypto.randomUUID();const e=c;m(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),b({status:"thinking"})};for(;;){const{done:e,value:t}=await k.read();if(e)break;C+=N.decode(t,{stream:!0});const n=C.split("\n");C=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=y(JSON.parse(n),v);switch(v.hasUsedTools=v.hasUsedTools||ne.current,e.action){case"status":{S();const t=c;if(e.contextUsage&&M(e.contextUsage),"tool_start"===e.status&&(ne.current=!0),"thinking_text"===e.status){p.thinking(e.thinkingContent??"");break}if(p.flush(),"stream_retract"===e.status)u="",m(e=>e.map(e=>e.id===t?{...e,content:""}:e)),b(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}));else if("tool_heartbeat"===e.status){const t="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;b(n=>n?{...n,elapsedS:e.elapsedS,elapsedStartMs:t}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:t})}else b(t=>({status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent}));break}case"stream":S(),u+=e.content,p.text();break;case"done":{p.flush(),h=!0,E(null),j(null),e.conversationId&&ye(e.conversationId),e.contextUsage&&M(e.contextUsage),e.transferAgentId&&e.transferAgentName&&_({id:e.transferAgentId,name:e.transferAgentName});const t=c,n=e.content||u,r=new Date;m(a=>a.map(a=>a.id===t?{...a,content:n,timestamp:r,toolNames:e.toolNames,toolCallCount:e.toolCallCount,iterations:e.iterations,attachments:e.attachments,reasoning:e.reasoning,toolCallTrace:e.toolCallTrace,transferChain:e.transferChain,isTruncated:e.isTruncated,serverId:e.messageId??a.serverId}:a));break}case"approval_required":p.flush(),ie.current=e.conversationId??re.current,j(null),E(e.proposals),b(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"});break;case"error":{S(),p.flush();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":X(e.chatId),localStorage.setItem(V,e.chatId)}ne.current=v.hasUsedTools}catch{}}}if(p.flush(),u&&!h){const e=c,t=u;m(n=>n.map(n=>n.id===e?{...n,content:t||d("No response.")}:n))}}catch(e){if(p.close(),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{p.close(),te.current===p&&(te.current=null),ee.current=null,x(!1),b(null),ne.current=!1,E(null),j(null),ie.current=null,se.current=!1,le.current=re.current}},handleNewChat:Ce,handleStopGenerating:()=>{te.current?.flush(),te.current?.close(),te.current=null,ee.current?.abort(),ee.current=null,x(!1),b(null),ne.current=!1,E(null),j(null),R(!1),ie.current=null,se.current=!1,m(e=>e.filter(e=>!("assistant"===e.role&&!e.content)))},setAttachedFiles:S,setMessages:m,setContextUsage:M,updateConversationId:ye,handleSwitchConversation:e=>{(g||e!==re.current)&&(Ce(),g||(ye(e),N(Y(e))))}}}const Q="filigranChatAgentSlug";function ee({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[o,s]=r([]),[l,c]=r(!1),[d,u]=r(!1),[h,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),u(!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&&!h){const e=localStorage.getItem(Q),n=e?t.find(t=>t.slug===e):null;g(n||t[0])}}).catch(()=>{s([]),u(!0)}).finally(()=>c(!1))},[e,t,n,a]);return{agents:o,agentsLoading:l,agentsError:d,selectedAgent:h,setSelectedAgent:g,agentMenuOpen:p,setAgentMenuOpen:m,handleSwitchAgent:(e,t)=>{e.id!==h?.id?(g(e),e.slug&&localStorage.setItem(Q,e.slug),m(!1),t?.()):m(!1)}}}function te(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 ne=400,re="filigranChatSidebarWidth";let ae=null,oe=null,ie=0;function se(){null!==ae&&(window.clearInterval(ae),ae=null),null!==oe&&(document.title=oe,oe=null)}function le({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;ie+=1;const e=()=>{!document.hidden&&document.hasFocus()&&se()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),ie=Math.max(0,ie-1),0===ie&&se()}},[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?S(n,"{agent} has finished",{agent:t}):n("Your answer is ready");a&&(function(e){if("undefined"==typeof document)return;null===oe&&(oe=document.title),null!==ae&&window.clearInterval(ae);let t=!0;document.title=e,ae=window.setInterval(()=>{t=!t,document.title=t?e:oe??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 ce({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[s,l]=r(null),[c,d]=r(null),u="rest"===n&&!t?.singleEndpoint,h=void 0===t?.prompts?"/chat/prompts":t.prompts,g=void 0===t?.quota?"/chat/quota":t.quota,p=u&&h?`${e}${h}`:null,m=u&&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:"",..."global"===t.scope||"user"===t.scope?{scope:t.scope}:{}}}(t))}).catch(()=>{e||d(null)}),()=>{e=!0}},[m,a,f]),{prompts:s,quota:c,refreshQuota:w}}function de({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a,agentSlug:o}){const[s,l]=r(null),[c,d]=r(!1),u="rest"===n&&!t?.singleEndpoint,h=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,g=u&&h?`${e}${h}`: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}}function ue(e){const t=a(e);return function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||"object"!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}(t.current,e)||(t.current=e),t.current}function he(e){const t=a(e);s(()=>{t.current=e});const n=o((...e)=>t.current?.(...e),[]);return e?n:void 0}const 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:"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"})]}),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:"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"})]}),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:"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"})}),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:"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"})]}),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:"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"})]}),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("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),be=({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"})}),ye=({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"})}),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:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),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:"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"})]}),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("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"})]}),Ce=({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"})}),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:"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"})]}),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 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"})]}),_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:"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"})]}),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:"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"})]}),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:"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"})]}),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:"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"})]}),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("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"})]}),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:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),t("path",{d:"M2 12h20"})]}),$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:"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"})]}),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("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"})]}),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("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),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("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"})]}),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:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),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("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"})]}),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:"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"})]}),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("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),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:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),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("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),qe=({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"})}),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("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),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("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),Ve=({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"})]}),Ke=({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"})]}),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("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"})]}),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:"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"})]}),Ze="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",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:Ze}),t("path",{d:"M16 9a5 5 0 0 1 0 6"}),t("path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"})]}),Qe=({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:Ze}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),et=({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"})}),tt=({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 nt=({open:e,onClose:n,anchorRef:s,placement:c="bottom-start",width:d=280,children:u})=>{const h=a(null),[g,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])}(h,f,e),l(()=>{if(!e||!s.current)return;const t=s.current.getBoundingClientRect(),n=h.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,l=Math.max(8,Math.min(i,window.innerWidth-d-8));m({top:o,left:l})},[e,s,c,d,u]),!e)return null;const x=I(s.current);return p(t("div",{ref:h,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:g.top,left:g.left,width:d},children:u}),x)},rt=({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}});function at(e){return Math.max(e.maxRight-e.minLeft,0)}const ot=({title:n,children:o})=>{const i=a(null),s=a(null),[c,d]=r(null),[u,h]=r({below:!1,shift:0});if(l(()=>{if(!c||!s.current)return;const{width:e,height:t}=s.current.getBoundingClientRect();h(function(e,t){const n=e.center-t.width/2;let r=0;return n<e.minLeft?r=e.minLeft-n:n+t.width>e.maxRight&&(r=e.maxRight-(n+t.width)),{below:e.top-4-t.height<e.minTop,shift:r}}(c,{width:e,height:t}))},[c,n]),!n)return o;const g=()=>{if(!i.current)return;const e=I(i.current).getBoundingClientRect();d(function(e,t,n){return{top:e.top,bottom:e.bottom,center:(e.left+e.right)/2,minTop:Math.max(t.top,0),minLeft:Math.max(t.left,0)+4,maxRight:Math.min(t.right,n)-4}}(i.current.getBoundingClientRect(),e,window.innerWidth))};return e("span",{ref:i,className:"inline-flex",onMouseEnter:g,onMouseLeave:()=>d(null),onFocus:e=>{const t=e.target;"function"==typeof t.matches&&t.matches(":focus-visible")&&g()},onBlur:()=>d(null),children:[o,c&&p(t("span",{ref:s,className:`pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${u.below?"":"-translate-y-full"} whitespace-normal break-words 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:u.below?c.bottom+4:c.top-4,left:c.center+u.shift,maxWidth:at(c)},role:"tooltip",children:n}),I(i.current))]})},it=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(Me,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(Fe,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(Ee,{...e})}],st=({mode:o,agentName:s,agents:l,agentsLoading:d=!1,agentsError:u=!1,selectedAgent:h,transferredFrom:g,agentMenuOpen:p,onAgentMenuToggle:m,onAgentMenuClose:f,onSwitchAgent:x,modeMenuOpen:w,onModeMenuToggle:b,onModeMenuClose:y,onModeChange:v,onNewChat:k,onClose:N,logoIcon:C,agentDashboardUrl:I,historyEnabled:_=!1,historyMenuOpen:M=!1,onHistoryMenuToggle:T,onHistoryMenuClose:E,conversations:z=[],conversationsLoading:A=!1,activeConversationId:$=null,onSelectConversation:j,onDeleteConversation:D,t:R})=>{const U=a(null),O=a(null),H=a(null),[W,B]=r("");i(()=>{p||B("")},[p]);const F=c(()=>{const e=W.trim().toLowerCase();return e?l.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):l},[l,W]),q=l.length>5,P="sidebar"===o?Fe:"fullscreen"===o?Te: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: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:C}),t("span",{children:s}),t(ye,{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:S(R,"Transferred from {agent}",{agent:g})})]}),e(nt,{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===l.length&&d&&t("div",{className:"px-4 py-2",children:t(rt,{size:16})}),0===l.length&&!d&&u&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(ge,{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===l.length&&!d&&!u&&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")}),q&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(We,{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=>B(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:[l.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===h?.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:C})}),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(_e,{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(Je,{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"}),_&&e(n,{children:[t(ot,{title:R("Conversation history"),children:t("button",{ref:H,type:"button",onClick:T,"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($e,{size:18})})}),e(nt,{open:M,onClose:()=>E?.(),anchorRef:H,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:[A&&0===z.length&&t("div",{className:"px-4 py-2",children:t(rt,{size:16})}),!A&&0===z.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:R("No conversations yet")}),z.map(n=>{const r=n.conversationId===$,a=L(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(Ye,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("button",{type:"button",onClick:()=>{E?.(),k()},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(Ie,{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(ot,{title:R("New chat"),children:t("button",{type:"button",onClick:k,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(Ie,{size:18})})}),t(ot,{title:R("Switch view"),children:t("button",{ref:O,type:"button",onClick:b,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(nt,{open:w,onClose:y,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:it.map(n=>e("button",{type:"button",onClick:()=>{v(n.mode),y()},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(ot,{title:R("Close"),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(ve,{size:18})})})]})};function lt(e,t){let n="idle",r=!1,a=!1,o=!1;const i=()=>"listening"===n||r,s=()=>{a||i()===o||(o=i(),t.onListeningChange(o))},l=()=>{try{return e.start(),!0}catch{return!1}};return e.onresult=e=>{if("listening"!==n&&"stopping"!==n)return;let r="",a="";for(let t=e.resultIndex;t<e.results.length;t++){const n=e.results[t];n.isFinal?r+=n[0].transcript:a+=n[0].transcript}const o=r.trim();o&&t.onFinal(o),"listening"===n&&t.onInterim(a.trim())},e.onerror=()=>{"listening"===n&&(n="stopping",t.onInterim("")),s()},e.onend=()=>{if(t.onInterim(""),"listening"===n){if(l())return;n="idle"}else r?(r=!1,n=l()?"listening":"idle"):n="idle";s()},{toggle:()=>{a||(i()?(()=>{if(r=!1,"listening"===n){n="stopping",t.onInterim("");try{e.stop()}catch{n="idle"}}s()})():(l()?n="listening":"idle"!==n&&(r=!0),s()))},cancel:()=>{if(!a){if(r=!1,"listening"===n||"stopping"===n){n="discarding",t.onInterim("");try{e.abort()}catch{n="idle"}}s()}},dispose:()=>{if(!a){if(a=!0,e.onresult=null,e.onerror=null,e.onend=null,"idle"!==n)try{e.abort()}catch{}n="idle",r=!1}}}}function ct(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const dt=14,ut=2*Math.PI*6,ht=[{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"}],gt=({usage:o,t:i})=>{const{used:s,limit:l,breakdown:c}=o,d=a(null),[u,h]=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),b=`${_(s)}/${_(l)}`,y=i(p?"Context full — older turns are being dropped":m?"Context nearly full — older turns are being summarized":"Context used"),v=S(i,"{counts} tokens",{counts:b}),k=`${y} · ${v}`,N=c?ht.filter(e=>(c[e.field]??0)>0):[],C=N.length>0,I=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:dt,height:dt,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:ut,strokeDashoffset:ut*(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(ot,{title:u?"":S(i,"{summary} — click for details",{summary:k}),children:t("button",{ref:d,type:"button",onClick:()=>h(e=>!e),"aria-label":`${k} (${w}%)`,"aria-haspopup":"dialog","aria-expanded":u,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(nt,{open:u,onClose:()=>h(!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:S(i,"{percent}% full",{percent:w})}),e("span",{className:"text-[0.7rem] tabular-nums text-gray-400 dark:text-white/40 shrink-0",children:["~",v]})]}),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:n.label(i)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0",children:_(c?.[n.field]??0)})]},n.field))}),m&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${x}`,children:y})]})]}):t(ot,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:I})})},pt=({prompts:o,onPick:i,t:s})=>{const l=a(null),[c,d]=r(!1),[u,h]=r(""),g=()=>{d(!1),h("")},p=u.trim().toLowerCase(),m=p?o.filter(e=>e.title.toLowerCase().includes(p)||(e.description??"").toLowerCase().includes(p)):o;return e(n,{children:[t(ot,{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(qe,{size:15})})}),e(nt,{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:u,onChange:e=>h(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))]})]})]})},mt=({quota:n,t:r})=>{const{used:a,limit:o}=n,i=function(e,t){switch(e){case"daily":return t("today");case"monthly":return t("this month");case"yearly":return t("this year");default:return e}}(n.period,r),s=e=>"global"===n.scope?S(r,"{quota} (shared across all users)",{quota:e}):e;if(null===o){const e=s(i?S(r,"Usage · {period}",{period:i}):r("Usage"));return t(ot,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30",role:"img","aria-label":`${e} ${_(a)}`,children:_(a)})})}const l=o>0?Math.min(a/o,1):1,c=!(o>0)||a>=o,d=l>=.75,u=c?"bg-red-500":d?"bg-amber-500":"bg-[var(--chat-accent)]/60",h=c?"text-red-500 dark:text-red-400":d?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",g=`${_(a)}/${_(o)}`,p=r(c?"Quota reached":"Quota"),m=s(i?`${p} · ${i}`:p);return t(ot,{title:m,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${m} ${g}`,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 ${u}`,style:{width:100*l+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${h}`,children:g})]})})},ft=({inputValue:s,onInputChange:c,onSend:d,onStop:u,isLoading:h,canSteer:g=!1,attachedFiles:p=[],onFileAdd:m,onFileRemove:f,onPaste:x,t:w,mode:b,separatorColor:y,prompts:v,quota:k,contextUsage:N,composerToolbar:C})=>{const S=a(null),I=a(null),_=a(!1),L=function(e){const[t,n]=r(!1),[s,l]=r(""),c=a(null),d=a(e);d.current=e;const u=null!==ct();return i(()=>{const e=ct();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=lt(t,{onFinal:e=>d.current(e),onInterim:l,onListeningChange:n});return c.current=r,()=>{c.current=null,r.dispose(),n(!1),l("")}},[]),{supported:u,listening:t,interim:s,toggle:o(()=>c.current?.toggle(),[]),cancel:o(()=>c.current?.cancel(),[])}}(e=>{_.current=!0,c(s.trim()?`${s.trimEnd()} ${e}`:e)});l(()=>{const e=I.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,_.current&&(_.current=!1,e.scrollTop=e.scrollHeight))},[s]);const M=Boolean(v&&v.length>0||k||N||C),T=Boolean(m&&f&&x),E=s.trim()||T&&p.length>0,z=T&&p.some(e=>"pending"===e.uploadStatus),A=E&&!z,$=T&&p.length>0,j=h&&g&&Boolean(s.trim())&&!$,D=()=>{(h?j:A)&&(L.cancel(),d())},R=w(h&&g&&!$?"Enter to send now · Esc to stop":h&&$?"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"===b?"rounded-b-xl":""),style:y?{borderTopColor:y,borderTopWidth:1}:void 0,children:[T&&p.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:p.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(Le,{size:14}),n.name,"error"===n.uploadStatus&&t("span",{className:"text-red-400 text-[0.6rem]",children:"✕"}),t("button",{type:"button",onClick:()=>f?.(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-end border rounded-xl px-2 py-1 transition-colors "+(L.listening?"border-red-500/50":"border-gray-200 dark:border-white/10 focus-within:border-[var(--chat-accent)]"),children:[T&&e(n,{children:[t("input",{ref:S,type:"file",multiple:!0,hidden:!0,onChange:e=>{m?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>S.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(me,{size:18})})]}),t("textarea",{ref:I,placeholder:L.listening?w("Listening..."):w("Ask a question..."),value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),D()),"Escape"===e.key&&h&&(e.preventDefault(),u())},onPaste:x,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}}),L.supported&&t(ot,{title:L.listening?w("Stop dictation"):w("Dictate a message"),children:e("button",{type:"button",onClick:L.toggle,"aria-label":w("Dictate a message"),"aria-pressed":L.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors "+(L.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:[L.listening?t(He,{size:18}):t(Oe,{size:18}),L.listening&&t("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse"})]})}),j&&t(ot,{title:w("Send now"),children:t("button",{type:"button",onClick:D,"aria-label":w("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(Be,{size:18})})}),t(ot,{title:h?w("Stop generating"):z?w("Files uploading..."):"",children:t("button",{type:"button",onClick:h?u:D,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?Pe:Be,{size:18})})})]}),M&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[v&&v.length>0&&t(pt,{prompts:v,onPick:e=>{c(s.trim()?`${s.trimEnd()}\n\n${e}`:e),I.current?.focus()},t:w}),C,(N||k)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[N&&t(gt,{usage:N,t:w}),k&&t(mt,{quota:k,t:w})]})]}),L.interim?e("p",{className:"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-red-500 dark:text-red-400 mt-1.5",children:[t("span",{className:"w-1.5 h-1.5 shrink-0 rounded-full bg-red-500 motion-safe:animate-pulse"}),t("span",{className:"truncate",children:L.interim})]}):t("p",{className:"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70",children:R})]})},xt=e=>e.serverId??e.id;const wt=x().use(f).use(m).freeze(),bt=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function yt(e){if(bt.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(yt).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function vt(e,t){if(!bt.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(yt(e));case"tableRow":return void t.push((e.children??[]).map(yt).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])vt(n,t)}}const kt=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;const Nt=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;function Ct(e){const[t]=r(Nt),[n,l]=r(null),c=a(null),d=a(e);s(()=>{d.current=e});const u=o(()=>t?(c.current??=function(e,t,n){let r=0,a=null;const o=e=>{e===r&&null!==a&&(r+=1,a=null,n(null))},i=()=>{null!==a&&(r+=1,a=null,e.cancel(),n(null))};return{speak:(s,l,c)=>{i();const d=l.filter(e=>e.trim());if(!d.length)return!1;const u=r;return a=s,n(s),d.forEach((n,a)=>{const i=a===d.length-1,s=t(n,{lang:c,onEnd:()=>{i&&o(u)},onError:()=>{u===r&&(o(u),e.cancel())}});e.speak(s)}),!0},stop:i,get speakingId(){return a}}}(window.speechSynthesis,(e,{lang:t,onEnd:n,onError:r})=>{const a=new SpeechSynthesisUtterance(e);return t&&(a.lang=t),a.onend=n,a.onerror=r,a},l),c.current):null,[t]),h=o((e,t)=>{const n=u();n&&(n.speakingId===e?n.stop():n.speak(e,function(e,t=220){const n=e.split(/\n+|(?<=[.!?;:\u3002\uff01\uff1f])\s+/).map(e=>e.trim()).filter(Boolean),r=[];for(const e of n){if(e.length<=t){r.push(e);continue}let n="";for(const a of e.split(" "))for(let e=0;e<a.length;e+=t){const o=a.slice(e,e+t);n?n.length+1+o.length<=t?n=`${n} ${o}`:(r.push(n),n=o):n=o}n&&r.push(n)}const a=[];for(const e of r){const n=a.length-1;n>=0&&a[n].length+1+e.length<=t?a[n]=`${a[n]} ${e}`:a.push(e)}return a}(function(e){const t=[];for(const n of e)n.trim()&&vt(wt.parse(n),t);return t.map(e=>e.replace(/\s+/g," ").replace(/ ([.,!?;:])/g,"$1").trim()).filter(e=>/[\p{L}\p{N}]/u.test(e)).map(e=>/[.!?;:\u3002\uff01\uff1f]$/.test(e)?e:`${e}.`).join("\n")}(t)),d.current))},[u]),g=o(()=>c.current?.stop(),[]);return i(()=>()=>c.current?.stop(),[]),{supported:t,speakingId:n,toggle:h,stop:g}}const St={time:{hour:"2-digit",minute:"2-digit"},date:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"},dateWithYear:{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"},full:{dateStyle:"full",timeStyle:"short"}},It=new Map;function _t(e,t){const n=`${e??""}|${t}`;let r=It.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,St[t])}catch{r=new Intl.DateTimeFormat(void 0,St[t])}It.set(n,r)}return r}const Lt={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const Mt=new Set(["ArrowUp","PageUp","Home"]);function Tt(e){return 1===e.length?e[0].clientY:null}const Et=new Set(["auto","scroll","overlay"]);function zt(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function At(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 $t="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",jt=({proposal:n,decision:a,onDecide:o,disabled:i,t:s})=>{const[l,c]=r(!1),[u,h]=r(""),g=d(),p=At(l),m=a?.verdict,f=Object.keys(n.arguments??{}),x=e=>{o({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&u.trim()?{rejectionReason:u.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(et,{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:zt(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:u,onChange:e=>h(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:`${$t} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(tt,{size:13}),s("Decline this call")]}),t("button",{type:"button",disabled:i,onClick:()=>{c(!1),h("")},className:`${$t} 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:()=>c(!0),className:`${$t} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(tt,{size:13}),s("No")]}),e("button",{type:"button",disabled:i,onClick:()=>x("approve"),className:`${$t} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(be,{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:`${$t} 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")})]})]})},Dt=({proposals:n,onSubmit:o,isSubmitting:s,error:l,t:c})=>{const[d,u]=r({}),h=a(!1),[g,p]=r(!1);i(()=>{l&&(h.current=!1,p(!1))},[l]);const m=s||g,f=e=>{h.current||s||(h.current=!0,p(!0),o(e))},x=n.filter(e=>d[e.toolCallId]).length,w=x===n.length&&n.length>0,b=Object.values(d).some(e=>"approve_always"===e.verdict),y=At(b),v=At(!0);return e("div",{ref:v,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(ge,{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(jt,{proposal:e,decision:d[e.toolCallId],disabled:m,t:c,onDecide:e=>{const t={...d,[e.toolCallId]:e};u(t);const r=n.map(e=>t[e.toolCallId]);r.every(Boolean)&&!r.some(e=>"approve_always"===e.verdict)&&f(r)}},e.toolCallId)),b&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(ge,{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:y,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?S(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:`${$t} 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,h]=r(null);return i(()=>{h(I(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&&p(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(ve,{size:20})}),t("img",{src:n,alt:o,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},Ut=({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),[u,h]=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),h(t))}).catch(()=>{e||p(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,a,s]);const x=d?u: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(Ue,{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(je,{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…")})]})};const Ot="inline-flex items-center gap-1.5 self-start rounded text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100",Ht=({t:n,enabled:a=!0,onPlay:o,playUrl:s,keepEndInView:l})=>{const d=c(()=>(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]),u=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}(),[h,g]=r(0);if(i(()=>{a&&l()},[a,l]),i(()=>{if(!a)return;const e=window.setInterval(()=>g(e=>(e+1)%d.length),2600);return()=>window.clearInterval(e)},[a,d.length]),!a)return null;const p=d[h%d.length];return e("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:p}),e("div",{className:"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5",style:u?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[e("span",{"aria-hidden":!0,className:"text-xs text-gray-500 dark:text-white/45",style:u?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[p,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(u?"":"animate-pulse")})]},p),o?e("button",{type:"button",onClick:o,className:Ot,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(ze,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:Ot,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(ze,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(_e,{size:11})})]}):null]})]})};function Wt(e,t){return e>1?S(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function Bt(e,t){return e>1?S(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function Ft(e,t){return e>1?S(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function qt(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 Pt({text:e}){const n=a(null),[o,s]=r(!1);return i(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight,s(e.scrollHeight>e.clientHeight+1))},[e]),t("div",{className:"filigran-chat-reasoning 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",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:e})})})}function Gt(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`}function Vt(e,t,n=0){const[a,o]=r(null);return i(()=>{if(o(null),!e)return;const r=window.setTimeout(()=>o(n),t);return()=>window.clearTimeout(r)},[e,t,n]),e&&a===n}const Kt=({agentStatus:a,logoIcon:o,t:s,miniGameEnabled:l=!0,onPlayWaitingGame:d,waitingGameUrl:u,keepEndInView:h})=>{const{label:g,StatusIcon:p,showDots:m}=function(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:xe,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:Wt(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:Je,showDots:!1};if(r.some(e=>"check_task_status"===e))return{label:Bt(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:qe,showDots:!1};if(r.some(e=>"get_task_result"===e))return{label:Ft(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:qe,showDots:!1};let a,o=et;if(r.some(e=>e.includes("search")||e.includes("list"))?o=We:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?o=Ne:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?o=Re:r.some(e=>e.includes("code")||e.includes("execute"))?o=Ge:r.some(e=>e.includes("web")||e.includes("browse"))&&(o=Ae),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]}…`:S(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:ge,showDots:!1};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:qe,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:qe,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:xe,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:S(t,"Consulting {agent}…",{agent:n}),StatusIcon:Je,showDots:!1}}case"delegating":return{label:Wt(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:Je,showDots:!1};case"polling":return{label:Bt(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:qe,showDots:!1};case"collecting":return{label:Ft(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:qe,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:S(t,"Transferring to {agent}…",{agent:n}),StatusIcon:_e,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:xe,showDots:!1}}}(a,s),f=a?.thinkingContent,x=a?.elapsedStartMs,[w,b]=r(()=>Date.now());i(()=>{if(null==x)return;b(Date.now());const e=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(e)},[x]);const y=null!=x?Math.max(0,(w-x)/1e3):a?.elapsedS,v="number"==typeof y&&y>=15,k=c(()=>function(e){if(e.length<=6e3)return qt(e);const t=[];let n=0;for(let r=e.indexOf("```");-1!==r;r=e.indexOf("```",n)){const a=e.indexOf("```",r+3);if(-1===a)break;t.push([n,r]),n=a+3}t.push([n,e.length]);const r=[];let a=6e3;for(let n=t.length-1;n>=0&&a>0;n--){const[o,i]=t[n],s=Math.max(o,i-a);r.push(e.slice(s,i)),a-=i-s+1}let o=r.reverse().join(" ");if(a<=0){const e=o.indexOf("\n\n");-1!==e&&e<o.length/2&&(o=o.slice(e+2))}return qt(o)}(f??""),[f]),N=k.length>=3,C=Vt(l&&!N,5e3),I=Vt(l&&N,1e4,f?.length??0),_=N?I:C;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:o})}),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:[m?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(p,{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:g}),v&&t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:Gt(y)})]})]})]}),_?t(Ht,{t:s,enabled:l,onPlay:d,playUrl:u,keepEndInView:h}):N?t(Pt,{text:k}):null]})},Yt=x().use(f).use(m).freeze();function Jt(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(Jt);default:return!1}}function Zt(e,t){return e.lastIndexOf("\n",t-1)+1}function Xt(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Zt(e,t-1),t-1).trim()}function Qt(e,t,n){const r=e.slice(t,n).split("\n");for(let e=r.length-1;e>=0;e--)if(r[e].trim())return/^(?: {4}|\t)/.test(r[e]);return!1}class en{last=null;split(e){return this.last?.source!==e&&(this.last=function(e,t){if(!e.trim())return function(e){return{source:e,blocks:e?[e]:[],starts:e?[0]:[],settled:0,firstDefinition:-1}}(e);const n=t&&t.settled>0&&e.startsWith(t.source)?t.settled:0,r=n?t.starts[n]:0,a=e.slice(r),o=t&&n?t.starts.slice(0,n):[];let i=t&&n&&t.firstDefinition<n?t.firstDefinition:-1;o.push(r);for(const t of Yt.parse(a).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Zt(a,n),i=o[o.length-1];t>i&&!Qt(e,i,t)&&o.push(t)}i<0&&Jt(t)&&(i=o.length-1)}let s=n;for(let t=o.length-1;t>n;t--)if(Xt(e,o[t])){s=t;break}const l=i<0?o.map((t,n)=>e.slice(t,o[n+1]??e.length)):[e];return{source:e,blocks:l,starts:o,settled:s,firstDefinition:i}}(e,this.last)),this.last.blocks}}const tn=e=>{if(!e)return!1;if(e.startsWith("//"))return!1;return!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e)},nn=u({copiedBlock:null,onCopyCode:()=>{},t:C}),rn={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{copiedBlock:a,onCopyCode:o,t:i}=g(nn),s=/language-(\w+)/.exec(n||""),l=String(r).replace(/\n$/,"");return s||l.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:s?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>o(l),"aria-label":i(a===l?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors",children:a===l?t(be,{size:14,className:"text-green-500"}):t(ke,{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:l})})]}):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{onRelativeLinkClick:r}=g(nn),a=(e=>{if(!e)return null;if(tn(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),o=null!==a&&!!r,i=!o&&!tn(e);return t("a",{href:e,onClick:e=>{o&&(e.preventDefault(),r(a))},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})=>{const{requestHeaders:r,t:a}=g(nn);return"string"==typeof e&&e?t(Ut,{src:e,alt:n||"",requestHeaders:r,t:a},e):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})},an=[m,b],on=h(({source:e})=>t(w,{remarkPlugins:an,urlTransform:N,components:rn,children:e}));on.displayName="MarkdownBody";const sn=({source:e})=>{const[a]=r(()=>new en),o=c(()=>a.split(e),[a,e]);return t(n,{children:o.map((e,n)=>t(on,{source:e},n))})},ln=h(({content:e,streaming:n=!1,onRelativeLinkClick:a,requestHeaders:i,t:s=C})=>{const[l,d]=r(null),[u,h]=r(n);n&&!u&&h(!0);const g=c(()=>v(e),[e]),p=o(e=>{navigator.clipboard.writeText(e),d(e),setTimeout(()=>d(null),2e3)},[]),m=c(()=>({copiedBlock:l,onCopyCode:p,onRelativeLinkClick:a,requestHeaders:i,t:s}),[l,p,a,i,s]);return t(nn.Provider,{value:m,children:t(u?sn:on,{source:g})})});ln.displayName="MarkdownMessage";function cn(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function dn(e){return e.replace(/_/g," ")}const un=({entry:n,index:a,t:o})=>{const[i,s]=r(!1),l=c(()=>cn(n.input),[n.input]),d=c(()=>cn(n.output),[n.output]),u=!!l&&"{}"!==l;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(we,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(tt,{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:dn(n.name)}),t(ye,{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:[u&&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:l})]}),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)")})]})]})]})},hn=({msg:n,onClose:o,t:s})=>{const l=a(null),c=a(null),d=a(null),[u,h]=r(null);i(()=>{h(I(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 g=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(),y=[f>1?S(s,"{count} iterations",{count:f}):"",1===g?s("1 tool call"):S(s,"{count} tool calls",{count:g}),1===x.length?s("1 transfer"):x.length>1?S(s,"{count} transfers",{count:x.length}):""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:u&&p(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(et,{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(ve,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] text-gray-500 dark:text-white/40",children:y.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(ge,{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(xe,{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:qt(b)})})]}),w.length>0?t("div",{className:"flex flex-col gap-1.5",children:w.map((e,n)=>t(un,{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(et,{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:dn(n)})]},`${n}-${r}`))}),x.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(pe,{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(fe,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},gn=e=>e.parentElement,pn=e=>getComputedStyle(e).overflowY;function mn(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function fn(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 xn=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const wn="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",bn="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",yn="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",vn=`opacity-0 ${wn} ${yn}`,kn=`opacity-50 ${wn} ${yn}`,Nn="opacity-100 text-[var(--chat-accent)]",Cn=({timestamp:n,locale:r})=>{const a=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:_t(t,(a=n,(r=e).getFullYear()===a.getFullYear()&&r.getMonth()===a.getMonth()&&r.getDate()===a.getDate()?"time":e.getFullYear()===n.getFullYear()?"date":"dateWithYear")).format(e),full:_t(t,"full").format(e),iso:e.toISOString()}:null;var r,a}(n,r);return a?t(ot,{title:a.full,children:e("time",{dateTime:a.iso,className:"px-1 text-[0.65rem] tabular-nums text-gray-400 dark:text-white/40 select-none",children:[t("span",{"aria-hidden":"true",children:a.label}),t("span",{className:"sr-only",children:a.full})]})}):null},Sn=({text:e,label:n,t:a})=>{const[o,i]=r(!1),s=o?a("Copied!"):n;return t(ot,{title:s,children:t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),i(!0),setTimeout(()=>i(!1),2e3)}catch{}},"aria-label":s,className:`${bn} ${o?"opacity-100 text-green-500 dark:text-green-400":vn}`,children:t(o?be:ke,{size:14})})})},In=({value:r,locked:a,pending:o,onChange:i,downRef:s,t:l})=>{const c=d(),u=a||o,h=(e,n)=>{const o=r===e;if(a&&!o)return null;const d="up"===e?Ke:Ve;return t(ot,{title:a?l("Feedback already submitted"):n,children:t("button",{ref:"down"===e?s:void 0,type:"button",onClick:()=>{u||i(o?null:e)},"aria-label":n,"aria-pressed":o,"aria-disabled":u||void 0,"aria-describedby":a?c:void 0,className:`${bn} ${o?Nn:vn} ${u?"cursor-default":""}`,children:t(d,{size:14,filled:o})})})};return e(n,{children:[h("up",l("Good response")),h("down",l("Bad response")),a&&t("span",{id:c,className:"sr-only",children:l("Feedback already submitted")})]})},_n=({pending:n,onSave:a,onSkip:o,t:i})=>{const[s,l]=r(""),c=d(),u=!n&&!!s.trim();return e("div",{className:"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] p-2",children:[t("label",{htmlFor:c,className:"text-[0.7rem] text-gray-600 dark:text-white/60",children:i("Tell us what went wrong (optional)")}),t("textarea",{id:c,autoFocus:!0,rows:2,maxLength:2e3,value:s,readOnly:n,onChange:e=>l(e.target.value),onKeyDown:e=>{"Escape"===e.key?(e.preventDefault(),e.stopPropagation(),n||o()):"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),u&&a(s))},placeholder:i("What could be improved?"),className:"w-full resize-y rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-transparent px-2 py-1 text-[0.75rem] leading-5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]"}),e("div",{className:"flex justify-end gap-1.5",children:[t("button",{type:"button",onClick:()=>{n||o()},"aria-disabled":n||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:i("Skip")}),t("button",{type:"button",onClick:()=>{u&&a(s)},"aria-disabled":!u||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] "+(u?"hover:opacity-90":"opacity-50 cursor-default"),children:i("Save")})]})]})},Ln=({speaking:e,onToggle:n,t:r})=>{const a=r(e?"Stop reading":"Read aloud");return t(ot,{title:a,children:t("button",{type:"button",onClick:n,"aria-label":a,className:`${bn} ${e?Nn:vn}`,children:t(e?Qe:Xe,{size:14})})})},Mn=h(({msg:n,isStreaming:o,agentName:i,logoIcon:s,onRelativeLinkClick:d,onDownloadFile:u,resolveAttachmentUrl:h,requestHeaders:g,feedbackMode:p,feedback:m,onRate:f,onSaveComment:x,onSkipComment:w,locale:b,canSpeak:y,isSpeaking:k,onToggleSpeech:N,t:C})=>{const[S,I]=r(!1),_="assistant"===n.role,L=!n.content,z=a(null),A=!!m?.commentOpen,$=a(A);l(()=>{const e=$.current&&!A;$.current=A,!e||document.activeElement&&document.activeElement!==document.body||z.current?.focus()},[A]);const j=(n,r)=>{const a=h&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&xn.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&xn.has(e.filename.slice(n+1).toLowerCase())}(n)?h(n):void 0;if(a)return t(Ut,{src:a,alt:n.filename,requestHeaders:g,maxHeightClass:"max-h-[200px]",t:C},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:()=>u?.(n),title:C("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(Le,{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(Se,{size:15})})]},r)},D=(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(Le,{size:14}),n]},r),R=n.toolNames&&n.toolNames.length>0||!!(n.reasoning??"").trim()||n.toolCallTrace&&n.toolCallTrace.length>0||n.transferChain&&n.transferChain.length>0||n.isTruncated,U=_&&!L&&!o,O=function(e){if(!e)return e;const t=e.replace(M,"").replace(T,"");return t===e?e:t.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}(n.content),H=c(()=>U&&y?function(e){const t=[];for(const n of E(e))"text"===n.type&&n.value.trim()&&t.push(v(n.value));return t}(n.content):null,[U,y,n.content]),W=(B=m,F=n.feedback,B?{value:B.value,locked:!1}:F?{value:(q=F.rating,"positive"===q?"up":"down"),locked:!0}:{value:null,locked:!1});var B,F,q;const P=xt(n);return e("div",{className:"group/msg flex flex-col "+(_?"items-start":"items-end"),children:[_&&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:s})}),t("span",{className:"font-semibold text-xs text-gray-900 dark:text-white",children:n.agentName??i})]}),!_&&((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)=>{!(!u||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(j({fileId:n.fileId,filename:n.name,type:fn(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(D(n.name,`file-${r}`))}),(n.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(u?j(n,`att-${n.fileId}-${r}`):D(n.filename,`att-${r}`)))}),e})()}),_?e("div",{className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=E(n.content),r=new Map((n.attachments??[]).map(e=>[e.fileId,e])),a=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(ln,{content:e.value,streaming:o,onRelativeLinkClick:d,requestHeaders:g,t:C})},`t-${n}`));else if(u){const t=r.get(e.fileId);t&&(a.add(e.fileId),i.push(j(t,`f-${e.fileId}-${n}`)))}}),u&&(n.attachments??[]).forEach(e=>{a.has(e.fileId)||i.push(j(e,`orphan-${e.fileId}`))}),0!==i.length||o||i.push(t("span",{className:"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic",children:"..."},"empty")),i})(),!L&&o&&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}),!_&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 text-gray-400 dark:text-white/40",children:[!!n.content.trim()&&t(Sn,{text:n.content,label:C("Copy message"),t:C}),!n.timestampUnknown&&t(Cn,{timestamp:n.timestamp,locale:b})]}),U&&e("div",{className:"mt-0.5 flex flex-wrap items-center gap-0.5 text-gray-400 dark:text-white/40",children:[!n.timestampUnknown&&t(Cn,{timestamp:n.timestamp,locale:b}),R&&t(ot,{title:n.isTruncated?C("Reasoning details — turn limit reached"):C("Reasoning details"),children:t("button",{type:"button",onClick:()=>I(e=>!e),className:`${bn} ${n.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":kn}`,"aria-label":n.isTruncated?C("Reasoning details — turn limit reached"):C("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":S,children:n.isTruncated?t(ge,{size:14}):t(De,{size:14})})}),t(Sn,{text:O,label:C("Copy response"),t:C}),p&&t(In,{value:W.value,locked:W.locked,pending:!!m?.pending,onChange:e=>f(n,e,m),downRef:z,t:C}),H&&(G=H,G.some(e=>/[\p{L}\p{N}]/u.test(e.replace(kt,""))))&&t(Ln,{speaking:k,onToggle:()=>N(P,H),t:C})]}),U&&m?.commentOpen&&t(_n,{pending:m.pending,onSave:e=>x(n,e,m),onSkip:()=>w(n,m),t:C}),U&&m?.error&&t("p",{role:"alert",className:"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400",children:m.error}),S&&t(hn,{msg:n,onClose:()=>I(!1),t:C})]});var G});Mn.displayName="MessageRow";const Tn=({messages:n,isLoading:d,agentStatus:u,agentName:h,logoIcon:g,onRelativeLinkClick:p,onDownloadFile:m,resolveAttachmentUrl:f,requestHeaders:x,miniGameEnabled:w=!0,onPlayWaitingGame:b,waitingGameUrl:y,onMessageFeedback:v,isResumingAfterDecision:k,pendingApprovals:N,onSubmitApprovalDecisions:C,isSubmittingApproval:S,approvalError:I,feedbackUrl:_,conversationId:L,locale:M,t:T})=>{const E=a(null),[$,D]=r(150),{entries:R,rate:U,saveComment:O,skipComment:H}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:i,t:l}){const[c,d]=r(()=>({scope:t,entries:{}}));let u=c.entries;c.scope!==t&&(u={},d({scope:t,entries:u}));const h=a({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:i,t:l});s(()=>{h.current={feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:i,t:l}});const g=a(0),p=o((e,t)=>d(n=>({...n,entries:{...n.entries,[e]:t}})),[]),m=o((e,t,n)=>d(r=>{const a=r.entries[e];return a&&a.seq===t?{...r,entries:{...r.entries,[e]:n(a)}}:r}),[]);return{entries:u,rate:o(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,onMessageFeedback:i,t:s}=h.current,l=xt(e),c=++g.current;if(!r)return p(l,{seq:c,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void i?.(l,t,e);if(a&&e.serverId){var d;if(p(l,{seq:c,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await j(fetch,r,a,e.serverId,t?{rating:(d=t,"up"===d?"positive":"negative"),comment:null}:null,o)){const e=s(t?"Could not submit feedback.":"Could not retract feedback.");return void m(l,c,()=>n?{...n,seq:c,pending:!1,commentOpen:!1,error:e}:{seq:c,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}m(l,c,e=>({...e,pending:!1,commentOpen:"down"===t})),h.current.onMessageFeedback?.(l,t,e)}},[p,m]),saveComment:o(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,t:i}=h.current,s=xt(e),l=A(t);if(!(r&&a&&e.serverId&&l))return void p(s,{...n,commentOpen:!1,error:null});const c=++g.current;p(s,{...n,seq:c,pending:!0,error:null});const d=await j(fetch,r,a,e.serverId,{rating:"negative",comment:l},o);m(s,c,e=>d?{...e,comment:l,pending:!1,commentOpen:!1}:{...e,pending:!1,error:i("Could not submit feedback.")})},[p,m]),skipComment:o((e,t)=>p(xt(e),{...t,commentOpen:!1,error:null}),[p])}}({feedbackUrl:_,conversationId:L,requestHeaders:x,onMessageFeedback:v,t:T}),W=Ct(M),[B]=r(()=>function(e,t=Lt){let n=!0,r=0,a=null;const o=e=>{e.scrollTo({top:e.scrollHeight,behavior:"instant"}),r=e.scrollTop},i=()=>{a&&(t.clear(a.timer),a=null)},s=()=>{i();const t=e();t&&n&&o(t)};return{get following(){return n},reveal:()=>{const o=e();if(!o)return;n=!0,i();const l=Math.max(0,o.scrollHeight-o.clientHeight);o.scrollTo({top:o.scrollHeight,behavior:"smooth"}),r=o.scrollTop,r>=l-1||(a={target:l,timer:t.set(s,1e3)})},keepUp:()=>{const t=e();t&&n&&!a&&o(t)},onScroll:()=>{const t=e();if(!t)return;const o=t.scrollTop,i=o<r-1,l=o>r+1;(i||l)&&(r=o);const c=t.scrollHeight-o-t.clientHeight;i?n=c<=1:l&&c<=100&&(n=!0),a&&(i||o>=a.target-1||c<=1)&&s()},leave:()=>{const t=e();!t||t.scrollTop<=0||(n=!1,i())}}}(()=>E.current)),F=a(null),q=(e,t)=>{t instanceof Element&&e.contains(t)&&(function(e,t,n,r){for(let a=e;a&&a!==t;a=n(a))if(a.scrollTop>0&&a.scrollHeight>a.clientHeight&&Et.has(r(a)))return!0;return!1}(t,e,gn,pn)||B.leave())},P=n[0]?.id;i(()=>{D(150)},[P]);let G=0;for(const e of n)"user"===e.role&&(G+=1);const V=a(null);l(()=>{const e=V.current;V.current={firstMessageId:P,userMessageCount:G},!e||e.firstMessageId!==P||G>e.userMessageCount?B.reveal():B.keepUp()},[n,P,G,B]);const K=u?.thinkingContent?.length??0;l(()=>{K&&B.keepUp()},[K,B]);const Y=n.length>$,J=c(()=>Y?n.slice(n.length-$):n,[n,$,Y]),{speakingId:Z,stop:X}=W,Q=null===Z||n.some(e=>xt(e)===Z),ee=a({conversationId:L,userMessageCount:G});i(()=>{const e=ee.current;ee.current={conversationId:L,userMessageCount:G},(e.conversationId!==L||G>e.userMessageCount||!Q)&&X()},[L,G,Q,X]);let te=null;if(d)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){te=n[e].id;break}const ne=!!N?.length&&!!C;return e("div",{ref:E,role:"region","aria-label":T("Conversation transcript"),tabIndex:0,onScroll:B.onScroll,onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&q(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(Mt.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&mn(e.target)||q(e.currentTarget,e.target))},onPointerDown:e=>{const t=e.currentTarget,n=t.getBoundingClientRect();(function(e){if(1===e.button)return!e.onControl;if(0!==e.button||!e.onContainer||e.x<e.clientWidth)return!1;const t=(e.scrollTop+e.clientHeight)/e.scrollHeight*e.clientHeight;return e.y<=t})({button:e.button,onContainer:e.target===t,onControl:mn(e.target),x:e.clientX-n.left-t.clientLeft,y:e.clientY-n.top-t.clientTop,clientWidth:t.clientWidth,clientHeight:t.clientHeight,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight})&&q(t,e.target)},onTouchStart:e=>{F.current=Tt(e.touches)},onTouchMove:e=>{const t=Tt(e.touches),n=F.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&q(e.currentTarget,e.target),F.current=function(e,t){return null===t?null:null===e?t:Math.min(e,t)}(n,t)},className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]",children:[Y&&t("div",{className:"flex justify-center",children:e("button",{type:"button",onClick:()=>D(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(ye,{size:13,className:"rotate-180"}),T("Load earlier messages")]})}),J.map(e=>{const n=e.id===te;return"assistant"===e.role&&!e.content&&n?ne?null:t("div",{children:t(Kt,{agentStatus:u,logoIcon:g,t:T,miniGameEnabled:w,onPlayWaitingGame:b,waitingGameUrl:y,keepEndInView:B.keepUp})},e.id):t(Mn,{msg:e,isStreaming:n,agentName:h,logoIcon:g,onRelativeLinkClick:p,onDownloadFile:m,resolveAttachmentUrl:f,requestHeaders:x,feedbackMode:"assistant"===e.role?z(e.serverId,_,L,!!v):null,feedback:R[xt(e)],onRate:U,onSaveComment:O,onSkipComment:H,locale:M,canSpeak:W.supported,isSpeaking:Z===xt(e),onToggleSpeech:W.toggle,t:T},e.id)}),k&&!ne&&t(Kt,{agentStatus:u,logoIcon:g,t:T,miniGameEnabled:w,onPlayWaitingGame:b,waitingGameUrl:y,keepEndInView:B.keepUp}),ne&&t(Dt,{proposals:N,onSubmit:C,isSubmitting:S,error:I,t:T},N.map(e=>e.toolCallId).join("|")),t("div",{})]})},En=({firstName:r,agentName:a,t:o})=>{if(!a)return t(n,{children:S(o,"How can I help you, {name}?",{name:r})});const{before:i,after:s,hasSlot:l}=function(e,t,n,r={}){const a=S(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]})},zn=({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(En,{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))]})]}),An=({conversations:n,loading:o,activeConversationId:i,collapsed:s,onToggleCollapsed:l,onSelect:d,onDelete:u,onRename:h,onNewChat:g,t:p})=>{const[m,f]=r(""),[x,w]=r(null),[b,y]=r(""),v=a(!1),k=()=>{if(v.current)return;v.current=!0;const e=x,t=b.trim();w(null),e&&t&&h?.(e,t)},N=c(()=>{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(ot,{title:p("Show conversations"),children:t("button",{type:"button",onClick:l,"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(Fe,{size:17})})}),t(ot,{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(Ie,{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(Ie,{size:15}),p("New conversation")]}),t(ot,{title:p("Hide conversations"),children:t("button",{type:"button",onClick:l,"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(Fe,{size:17})})})]}),n.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(We,{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(rt,{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===N.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:p("No conversation matches")}),N.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(fe,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[a?t("input",{autoFocus:!0,value:b,onChange:e=>y(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&k(),"Escape"===e.key&&(v.current=!0,w(null))},onBlur:k,"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?L(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:[h&&t("button",{type:"button",onClick:e=>{var t,r;e.stopPropagation(),t=n.conversationId,r=n.title||"",v.current=!1,w(t),y(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(Ie,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),u(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(Ye,{size:13})})]})]},n.conversationId)})]})]})},$n=({mode:n,onClose:s,onModeChange:l,topOffset:d=0,apiBaseUrl:u,apiEndpoints:h,agentDashboardUrl:g,user:p,t:m=C,accentColor:f="#7b5cff",logoIcon:x,promptSuggestions:w,draftBorderColor:b,resizable:v=!1,onWidthChange:k,onResizeStart:N,onResizeEnd:S,disableFileManagement:I=!1,onRelativeLinkClick:_,onDownloadError:L,maxFileCount:M,maxTotalSize:T,requestHeaders:E,pageContext:z,pushContentSelector:A,backendType:j="rest",miniGameEnabled:D=!0,onPlayWaitingGame:W,notifyOnComplete:B=!0,onTaskComplete:q,onMessageFeedback:P,locale:G,disableImagePreviews:V=!1,contextUsageEnabled:K=!0,composerToolbar:Y})=>{const J=ue(h),Z=ue(E),Q=ue(z),ae=ue(w),oe=he(_),ie=he(L),se=he(W),ge=he(q),pe=he(P),[me,fe]=r(!1),{agents:xe,agentsLoading:we,agentsError:be,selectedAgent:ye,agentMenuOpen:ve,setAgentMenuOpen:ke,handleSwitchAgent:Ne}=ee({apiBaseUrl:u,apiEndpoints:J,backendType:j,requestHeaders:Z}),{messages:Se,inputValue:Ie,setInputValue:_e,isLoading:Le,agentStatus:Me,attachedFiles:Te,conversationId:Ee,contextUsage:ze,transferredAgent:Ae,canSteer:$e,pendingApprovals:je,isSubmittingApproval:De,approvalError:Re,submitApprovalDecisions:Ue,isResumingAfterDecision:Oe,historyReloadNonce:He,historyLoadedRef:We,conversationIdRef:Be,handleFileAdd:Fe,handlePaste:qe,handleSendMessage:Pe,handleNewChat:Ge,handleStopGenerating:Ve,setAttachedFiles:Ke,setMessages:Ye,setContextUsage:Je,updateConversationId:Ze,handleSwitchConversation:Xe}=X({apiBaseUrl:u,apiEndpoints:J,backendType:j,agentSlug:ye?.slug,requestHeaders:Z,pageContext:Q,t:m,maxFileCount:M,maxTotalSize:T}),{suggestions:Qe,loading:et}=de({apiBaseUrl:u,apiEndpoints:J,backendType:j,requestHeaders:Z,agentSlug:ye?.slug}),tt=c(()=>(Qe??ae)?.map(e=>m(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")])(m),[Qe,ae,m]),{prompts:nt,quota:rt,refreshQuota:at}=ce({apiBaseUrl:u,apiEndpoints:J,backendType:j,requestHeaders:Z}),{historyEnabled:ot,conversations:it,conversationsLoading:lt,refreshConversations:ct,deleteConversation:dt,renameConversation:ut}=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,u=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,h=o(async()=>{if(d){c(!0);try{const e=await fetch(u,{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(te).filter(e=>null!==e))}catch{s([])}finally{c(!1)}}},[d,u,a]),g=o(async e=>{if(!d)return!1;try{return!!(await fetch(`${u}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...a??{}}})).ok&&(s(t=>t.filter(t=>t.conversationId!==e)),!0)}catch{return!1}},[d,u,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(`${u}/${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,u,a,i]);return{historyEnabled:d,conversations:i,conversationsLoading:l,refreshConversations:h,deleteConversation:g,renameConversation:p}}({apiBaseUrl:u,apiEndpoints:J,backendType:j,requestHeaders:Z}),[ht,gt]=r(!1),[pt,mt]=r(!1),xt="fullscreen"===n&&ot;i(()=>{xt&&ct()},[xt,Ee,ct]);const wt=a(!1);i(()=>{wt.current&&!Le&&(at(),xt&&ct()),wt.current=Le},[Le,at,xt,ct]);const bt=e=>{gt(!1),Xe(e)},yt=async e=>{await dt(e)&&e===Be.current&&Ge()},{sidebarWidth:vt,handleResizeStart:kt,defaultWidth:Nt,isResizing:Ct}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:o,onResizeEnd:s}){const[l,c]=r(()=>{if("undefined"==typeof window)return ne;const e=localStorage.getItem(re);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=ne)return t}return ne}),[d,u]=r(!1),h=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(!h.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,ne),n);c(r),g.current=r,p.current?.(r)},r=()=>{h.current&&(h.current=!1,u(!1),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem(re,String(g.current)),m.current?.())},a=()=>{const e=.4*window.innerWidth;if(g.current>e){const t=Math.max(e,ne);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(),h.current=!0,u(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",o?.()},defaultWidth:ne,isResizing:d}}({mode:n,resizable:v,onWidthChange:k,onResizeStart:N,onResizeEnd:S});i(()=>{const e="sidebar"===n?v?vt:Nt: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)"),A){const e=document.querySelector(A);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")}},[A,n,vt,Nt,v,Ct]);const St=c(()=>x??t(Ce,{size:24}),[x]),It=c(()=>function(e){const t=e?.trim().replace(/\/+$/,"");return t&&/^https?:\/\//i.test(t)?`${t}/chat?arcade=play`:null}(g),[g]),_t=p.firstName,[Lt,Mt]=r(null),Tt=Ae?.name||Lt||ye?.name||m("Assistant"),Et=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)},[]);le({isLoading:Le,agentName:Tt,t:m,enabled:B,onComplete:ge,isViewingChat:Et});const zt=null!=J?.download,At="rest"===j&&null!==J?.download&&(!J?.singleEndpoint||zt),$t=o(e=>`${u}${J?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[u,J]),jt=o(async e=>{const t=$t(e);try{const n=await fetch(t,{method:"GET",credentials:"include",headers:{...Z??{}}});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){ie?.(t,e)}},[$t,Z,ie]),Dt={"--chat-accent":f,"--chat-accent-10":y(f,.1),"--chat-accent-40":y(f,.25),"--chat-accent-50":y(f,.5),"--chat-accent-dark":f},Rt=a(!0);i(()=>(Rt.current=!0,()=>{Rt.current=!1}),[]),i(()=>{if(null===J?.sessions||J?.singleEndpoint||"legacy"===j||"ag-ui"===j)return;if(!Ee)return void Mt(null);if(We.current||!ye)return;We.current=!0;const e=Ee,t=()=>!Rt.current||Be.current!==e;fetch(`${u}${J?.sessions??"/chat/sessions"}`,{method:"POST",headers:{"Content-Type":"application/json",...Z??{}},body:JSON.stringify({conversation_id:Ee,agent_slug:ye.slug})}).then(e=>t()?null:e.ok?e.json():(Ze(null),null)).then(n=>{if(n&&!t()&&("string"==typeof n.conversation_id&&n.conversation_id&&n.conversation_id!==e&&Ze(n.conversation_id),Mt("string"==typeof n.agent_name?n.agent_name:null),n.messages?.length)){Ye(function(e){if(!Array.isArray(e))return[];const t=[];return e.forEach((e,n)=>{if(!e||"object"!=typeof e)return;const r=e;if("user"!==r.role&&"assistant"!==r.role)return;const a="string"==typeof r.created_at?new Date(r.created_at):null,o=a&&!Number.isNaN(a.getTime())?a:null;t.push({id:`restored-${n}`,serverId:"string"==typeof r.id&&r.id?r.id:void 0,role:r.role,content:"string"==typeof r.content?r.content:"",timestamp:o??new Date,timestampUnknown:!o||void 0,feedback:"assistant"===r.role?F(r.feedback):void 0,agentName:"string"==typeof r.agent_name?r.agent_name:void 0,attachments:U(r.attachments),toolNames:Array.isArray(r.tool_names)?r.tool_names:void 0,toolCallCount:"number"==typeof r.tool_call_count?r.tool_call_count:void 0,iterations:"number"==typeof r.iterations?r.iterations:void 0,reasoning:"string"==typeof r.reasoning?r.reasoning:void 0,toolCallTrace:O(r.tool_call_trace),transferChain:H(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0})}),t}(n.messages));for(let e=n.messages.length-1;e>=0;e-=1){const t=R(n.messages[e]);if(t){Je(t);break}}}}).catch(()=>{t()||Ze(null)})},[Ee,ye,u,J,j,He,We,Be,Rt,Z,Ye,Je,Ze]);const Ut=(()=>{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}})(),Ot={...Dt,..."sidebar"===n?{top:d,width:v?vt:Nt}:"floating"===n?{width:380,height:560}:{top:d}};return e("div",{className:Ut,style:Ot,children:["sidebar"===n&&v&&t("div",{onMouseDown:kt,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(st,{mode:n,agentName:Tt,agents:xe,agentsLoading:we,agentsError:be,selectedAgent:ye,transferredFrom:Ae?ye?.name:void 0,agentMenuOpen:ve,onAgentMenuToggle:()=>ke(e=>!e),onAgentMenuClose:()=>ke(!1),onSwitchAgent:e=>{e&&Ne(e,()=>{Ge()})},modeMenuOpen:me,onModeMenuToggle:()=>fe(e=>!e),onModeMenuClose:()=>fe(!1),onModeChange:l,onNewChat:Ge,onClose:s,logoIcon:St,agentDashboardUrl:g,historyEnabled:ot&&!xt,historyMenuOpen:ht,onHistoryMenuToggle:()=>{const e=!ht;e&&ct(),gt(e)},onHistoryMenuClose:()=>gt(!1),conversations:it,conversationsLoading:lt,activeConversationId:Ee,onSelectConversation:bt,onDeleteConversation:e=>{yt(e)},t:m}),e("div",{className:xt?"flex flex-1 min-h-0":"contents",children:[xt&&t(An,{conversations:it,loading:lt,activeConversationId:Ee,collapsed:pt,onToggleCollapsed:()=>mt(e=>!e),onSelect:bt,onDelete:e=>{yt(e)},onRename:(e,t)=>{ut(e,t)},onNewChat:Ge,t:m}),e("div",{className:xt?"flex flex-1 flex-col min-w-0":"contents",children:[0===Se.length?t(zn,{firstName:_t,logoIcon:St,promptSuggestions:tt,suggestionsLoading:et,agentName:ye?.name,agentDescription:ye?.description,onPromptClick:_e,t:m}):t(Tn,{messages:Se,isLoading:Le,agentStatus:Me,agentName:Tt,logoIcon:St,onRelativeLinkClick:oe,onDownloadFile:At?jt:void 0,resolveAttachmentUrl:At&&!V?$t:void 0,requestHeaders:Z,miniGameEnabled:D,onPlayWaitingGame:se,waitingGameUrl:It,onMessageFeedback:pe,feedbackUrl:$(u,J,j),conversationId:Ee,locale:G,isResumingAfterDecision:Oe,pendingApprovals:je,onSubmitApprovalDecisions:Ue,isSubmittingApproval:De,approvalError:Re,t:m}),t(ft,{inputValue:Ie,onInputChange:_e,onSend:Pe,onStop:Ve,isLoading:Le,canSteer:$e,attachedFiles:I?[]:Te,onFileAdd:I?void 0:Fe,onFileRemove:I?void 0:e=>Ke(t=>t.filter((t,n)=>n!==e)),onPaste:I?void 0:qe,t:m,mode:n,separatorColor:b,prompts:nt,quota:rt,contextUsage:K?ze:null,composerToolbar:Y})]})]})]})},jn=({isOpen:n,onToggle:r,label:a,accentColor:o="#7b5cff",icon:i,t:s=C})=>{const l=i??t(Ce,{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:y(o,.5),color:o,backgroundColor:n?y(o,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=o,e.currentTarget.style.backgroundColor=y(o,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?o:y(o,.5),e.currentTarget.style.backgroundColor=n?y(o,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:l}),a??s("Ask Assistant")]})};export{$n as ChatPanel,jn as ChatToggleButton};
1
+ import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{useState as r,useRef as a,useEffect as o,useCallback as i,useInsertionEffect as s,useLayoutEffect as l,useMemo as c,useId as d,createContext as u,memo as h,useContext as p}from"react";import{createPortal as m}from"react-dom";import g from"remark-gfm";import f from"remark-parse";import{unified as w}from"unified";import x from"react-markdown";import v from"remark-breaks";function y(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}function b(e){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 u="`".repeat(Math.max(l+1,4)),h=t[a].match(n);t[a]=`${h[1]}${u}${h[3]}`;const p=t[d].match(n);return t[d]=`${p[1]}${u}`,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],u=t[e+1];if(!d.includes("|")||r(d)||!r(u))continue;const h=d.match(l),p=h?h[0].length:d.length-d.trimStart().length,m=h?" ".repeat(p):d.slice(0,p),g=n(d.slice(p)).length,f=n(u);if(g<2||f.length===g)continue;const w=[];for(let e=0;e<g;e++)w.push(f[e]?a(f[e]):"---");t[e+1]=`${m}| ${w.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}}((t=e).includes("![")?t.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>`![${t.replace(/\s+/g," ").trim()}](${n})`):t)));var t}const k=new Set(["http","https","mailto","tel"]);function N(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 k.has(o)||"data"===o&&/^data:image\//i.test(e)?e:""}const C=e=>e;function I(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function S(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function _(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 L(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 I(t,"{count}m ago",{count:a});const o=Math.floor(a/60);if(o<24)return I(t,"{count}h ago",{count:o});const i=Math.floor(o/24);return i<7?I(t,"{count}d ago",{count:i}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const A=/\[\[(FILE|PRESENTATION|REPORT|VIDEO):([^\]#]+)(?:#\/([A-Za-z0-9_-]{1,64}))?\]\]/gi,T=/\[\[(?:FILE|PRESENTATION|REPORT|VIDEO)(?::[^\]]*)?\]?$/i,M=["[[FILE:","[[PRESENTATION:","[[REPORT:","[[VIDEO:"],E=Math.max(...M.map(e=>e.length));function $(e,t=!1){if(!e)return[];const n=[],r=new RegExp(A.source,"gi");let a=0,o=r.exec(e);for(;null!==o;){o.index>a&&n.push({type:"text",value:e.slice(a,o.index)});const t=o[1].toLowerCase();"file"===t?n.push({type:"file",fileId:o[2]}):n.push({type:"artifact",kind:t,id:o[2].toLowerCase(),slideRef:o[3]||void 0}),a=r.lastIndex,o=r.exec(e)}const i=e.slice(a).replace(T,""),s=t?function(e){for(let t=Math.max(0,e.length-E);t<e.length;t++){if("["!==e[t])continue;const n=e.slice(t).toUpperCase();if(M.some(e=>e.startsWith(n)))return e.slice(0,t)}return e}(i):i;return s&&n.push({type:"text",value:s}),n}const z=(e,t)=>`${e}:${t.toLowerCase()}`;function D(e,t){const n=[];if("presentation"===e.kind&&void 0!==e.slideCount&&n.push(I(t,"{count} slides",{count:e.slideCount})),"report"===e.kind&&void 0!==e.sectionCount&&n.push(I(t,"{count} sections",{count:e.sectionCount})),"video"===e.kind){void 0!==e.sceneCount&&n.push(I(t,"{count} scenes",{count:e.sceneCount}));const r=function(e){if(!e||e<=0)return;const t=Math.round(e/1e3);return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}(e.durationMs);r&&n.push(r)}return n.join(" · ")}const R=e=>"up"===e?"positive":"negative";function j(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function O(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function U(e,t,n){return"rest"!==n||t?.singleEndpoint||!t?.feedback?null:`${e}${t.feedback}`}async function W(e,t,n,r,a,o){const{url:i,init:s}=function(e,t,n,r,a){const o=`${e}/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}/feedback`;return r?{url:o,init:{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...a},body:JSON.stringify({rating:r.rating,comment:O(r.comment)})}}:{url:o,init:{method:"DELETE",credentials:"include",headers:{...a}}}}(t,n,r,a,o);try{return(await e(i,s)).ok}catch{return!1}}const H=e=>void 0!==e&&/[\w-]/.test(e),P=/^[\w-]+$/;function q(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const a=r[1].toLowerCase();H(e[r.index-1])||t.includes(a)||t.push(a),r=n.exec(e)}return t}function B(e,t){if(0===e.length)return e;const n=new Set(q(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function F(e,t){if(0===e.length)return[];const n=[];for(const r of q(t))for(const t of e)t.key.toLowerCase()!==r||n.some(e=>e.conversationId===t.conversationId)||n.push(t);return n.slice(0,5)}function V(e){const t=Array.isArray(e)?e:Array.isArray(e?.conversations)?e.conversations:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.id&&t.id&&"string"==typeof t.key&&P.test(t.key)&&(n.some(e=>e.id===t.id)||n.push({id:t.id,title:"string"==typeof t.title?t.title.trim():"",key:t.key,updatedAt:"string"==typeof t.updated_at?t.updated_at:void 0,isOwn:!1!==t.is_own}))}return n}function G(e,t,n){const r=t?.conversationReferences;return"rest"!==n||t?.singleEndpoint||"string"!=typeof r||!r?null:`${e}${r}`}const K={query:null,items:[],failed:!1};function J(e,t){if(t.every(t=>e.some(e=>{return r=t,(n=e).id===r.id&&n.key===r.key&&n.title===r.title&&n.isOwn===r.isOwn&&n.updatedAt===r.updatedAt;var n,r})))return e;const n=new Set(t.map(e=>e.id)),r=[...e.filter(e=>!n.has(e.id)),...t];return r.length>200?r.slice(r.length-200):r}function Z(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function Y(e){const{trigger:t,dismissed:n,search:r,referenced:a,exclude:o,known:i=[]}=e;if(!t||n)return{kind:"closed"};if(a>=5)return{kind:"full"};if(r.failed)return{kind:"closed"};const s=t.query?i.filter(e=>function(e,t){const n=e.toLowerCase();if(!n||t.key.toLowerCase().startsWith(n))return!0;const r=t.title.toLowerCase(),a=n.split(/[\s_-]+/).filter(Boolean);return a.length>0&&a.every(e=>r.includes(e))}(t.query,e)&&!r.items.some(t=>t.id===e.id)):[],l=[...r.items,...s].slice(0,8),c=o?l.filter(e=>e.id!==o):l;return c.length>0?{kind:"results",items:c}:t.query&&r.query===t.query?{kind:"empty"}:{kind:"closed"}}function X(e){const t=Array.isArray(e)?e:Array.isArray(e?.workspaces)?e.workspaces:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.id&&t.id&&"string"==typeof t.name&&(!0!==t.is_archived&&n.push({id:t.id,name:t.name,isOwn:!0===t.is_own,isDefault:!0===t.is_default,canManage:!0===t.can_manage}))}return n}function Q(e){const t=e=>e.isDefault&&e.isOwn;return[...e].sort((e,n)=>t(e)!==t(n)?t(e)?-1:1:e.name.localeCompare(n.name))}function ee(e,t,n,r,a){return!!a||(!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e))}function te(e,t,n){return!n&&!(t&&e.conversations.some(e=>e.conversationId===t))}async function ne(e){try{const t=await e.json(),n=t?.detail;return"string"==typeof n&&n?n:null}catch{return null}}const re=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function ae(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 re){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 oe(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}const ie=["presentation","report","video"],se=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function le(e){if(!e||"object"!=typeof e)return;const t=e,n=ie.find(e=>e===t.kind);return n&&"string"==typeof t.id&&t.id?{kind:n,id:t.id,title:"string"==typeof t.title?t.title:"",url:"string"==typeof t.url&&t.url?t.url:void 0,slideRef:"string"==typeof t.slide_ref&&t.slide_ref?t.slide_ref:void 0,slideCount:se(t.slide_count),sectionCount:se(t.section_count),sceneCount:se(t.scene_count),durationMs:se(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:se(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function ce(e){if(!Array.isArray(e))return;const t=e.map(le).filter(e=>!!e);return t.length>0?t:void 0}function de(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 ue(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.conversation_id&&e.conversation_id&&(t.some(t=>t.conversationId===e.conversation_id)||t.push({conversationId:e.conversation_id,title:"string"==typeof e.title?e.title.trim():"",key:"string"==typeof e.key?e.key:""}))}return t.length>0?t:void 0}function he(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 pe(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 me(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_progress"===n&&"page_action_required"===e.event){if("string"!=typeof e.action_id||!e.action_id)return{action:"noop"};const t=function(e){if(!e||"object"!=typeof e)return{type:"unsupported",requested:"malformed"};const t=e,n=e=>"string"==typeof e&&e.length>0;return"snapshot"===t.type?{type:"snapshot"}:"navigate"===t.type&&n(t.path)?{type:"navigate",path:t.path}:"click"===t.type&&n(t.ref)?{type:"click",ref:t.ref}:"open"===t.type&&n(t.ref)?{type:"open",ref:t.ref}:"type"===t.type&&n(t.ref)&&"string"==typeof t.text?{type:"type",ref:t.ref,text:t.text}:{type:"unsupported",requested:"string"==typeof t.type?t.type.slice(0,64):"unknown"}}(e.action);return{action:"page_action_required",actionId:e.action_id,pageAction:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}}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=ae(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=pe(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:oe(e.attachments),artifacts:ce(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:de(e.tool_call_trace),transferChain:he(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:ae(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0}:{action:"noop"}}function ge(e){if(!e||"object"!=typeof e)return;const{rating:t,comment:n}=e;return"positive"===t||"negative"===t?{rating:t,comment:"string"==typeof n&&n.trim()?n:null}:void 0}function fe(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 we(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"}}function xe(){let e=0,t=null,n=null;return{get generation(){return e},get pending(){return t},run(r){if(t)return t;const a=e,o=new AbortController;n=o;const i=r(()=>a===e,o.signal).catch(()=>null);return t=i,i.finally(()=>{t===i&&(t=null),n===o&&(n=null)}),i},abandon(){e+=1,t=null,n?.abort(),n=null}}}function ve(e,t){return null!==e&&"function"==typeof t}function ye(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const be=(e,t)=>{const n=t??ye();if(!e||!n)return null;try{const t=new URL(e,n);if("http:"!==t.protocol&&"https:"!==t.protocol)return null;if(t.origin!==new URL(n).origin)return null;const r=`${t.pathname}${t.search}${t.hash}`||"/";return r.startsWith("//")?null:r}catch{return null}};function ke(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const Ne=/^(current-password|new-password|one-time-code|cc-)/;function Ce(e){const t=e.ownerDocument.defaultView,n={bubbles:!0,cancelable:!0,view:t??void 0,pointerType:"mouse"},r=t?.PointerEvent??t?.MouseEvent??MouseEvent,a=t?.MouseEvent??MouseEvent;e.dispatchEvent(new r("pointerover",n)),e.dispatchEvent(new r("pointerenter",{...n,bubbles:!1})),e.dispatchEvent(new a("mouseover",n)),e.dispatchEvent(new a("mouseenter",{...n,bubbles:!1}))}function Ie(e,t,n){const r=e=>e.preventDefault();for(const n of t)e.addEventListener(n,r,!0);try{n()}finally{for(const n of t)e.removeEventListener(n,r,!0)}}function Se(e,t,n){if(e.matches?.("a[href]")){const r=e.getAttribute("target");if(r&&"_self"!==r)return{ok:!1,error:"opens_new_tab"};const a=e.getAttribute("href")??"";if(a&&!a.startsWith("#")){const e=be(a,n);if(!e)return{ok:!1,error:"external_link"};if(t)return t(e),{ok:!0}}}e.focus?.();const r=e.closest?.("a[href]"),a=!!r&&!(r.getAttribute("href")??"").startsWith("#"),o=a?["submit","click"]:["submit"],i=e.matches?.('input[type="checkbox"], input[type="radio"]')??!1,s=e.checked;if(Ie(e.ownerDocument,o,()=>e.click()),i&&a&&e.checked===s){const t=e;t.checked="radio"===t.type||!s,t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("input",{bubbles:!0})),t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("change",{bubbles:!0}))}return{ok:!0}}function _e(e){const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!1}for(let t=e;t;t=t.parentElement){if(t.hidden||t.hasAttribute("inert"))return!1;if("true"===t.getAttribute("aria-hidden"))return!1;const e=t.ownerDocument.defaultView?.getComputedStyle(t);if("none"===e?.display||"hidden"===e?.visibility)return!1}return!0}function Le(e){const t=e.getAttribute("aria-expanded");if("true"===t)return!0;if("false"===t)return!1;const n=e.getAttribute("aria-controls");if(!n)return!1;const r=e.ownerDocument.getElementById(n);return!!r&&_e(r)}async function Ae(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(Le(e))return{ok:!0};if(r){if(Ce(e),await(a=()=>Le(e),o=300,new Promise(e=>{const t=Date.now(),n=()=>a()?e(!0):Date.now()-t>=o?e(!1):void setTimeout(n,30);n()})))return{ok:!0}}else if(await function(e,t,n=300){const r=e.defaultView,a=r?.MutationObserver??globalThis.MutationObserver;return a?new Promise(r=>{const o=new a(e=>{e.some(e=>e.addedNodes.length>0&&!ke(e.target)&&Array.from(e.addedNodes).some(e=>!ke(e)))&&(o.disconnect(),clearTimeout(i),r(!0))});o.observe(e.body??e.documentElement,{subtree:!0,childList:!0}),t();const i=setTimeout(()=>{o.disconnect(),r(!1)},n)}):(t(),Promise.resolve(!0))}(e.ownerDocument,()=>Ce(e)))return{ok:!0};var a,o;return n?.aborted?{ok:!1,error:"aborted"}:Se(e,void 0,t)}const Te=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function Me(e,t,n,r,a){try{if(a?.aborted)return{ok:!1,error:"aborted"};if("snapshot"===e.type)return{ok:!0};if("unsupported"===e.type)return{ok:!1,error:`unsupported_action: ${e.requested}`.slice(0,500)};if("navigate"===e.type){if(!n)return{ok:!1,error:"navigation_unavailable"};const t=be(e.path,ye(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const o=t.get(e.ref);return o&&o.isConnected?_e(o)?function(e){if(e.hasAttribute("disabled"))return!0;if("true"===e.getAttribute("aria-disabled"))return!0;if(e.matches?.(":disabled"))return!0;if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(o)?{ok:!1,error:"disabled"}:o.matches?.('input[type="file"]')?{ok:!1,error:"opens_file_dialog"}:"open"===e.type?await Ae(o,ye(r??o.ownerDocument),a):"click"===e.type?Se(o,n,ye(r??o.ownerDocument)):function(e){return e.matches?.('textarea, [contenteditable="true"], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="number"]')??!1}(o)?function(e){return!0===e.readOnly||"true"===e.getAttribute("aria-readonly")}(o)?{ok:!1,error:"read_only"}:function(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>Ne.test(e))}(o)?{ok:!1,error:"secret_field"}:(o.focus?.(),function(e,t){const n=e.ownerDocument.defaultView;if(n&&(e instanceof n.HTMLInputElement||e instanceof n.HTMLTextAreaElement)){const r=e instanceof n.HTMLInputElement?n.HTMLInputElement.prototype:n.HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(r,"value")?.set?.call(e,t)}else e.textContent=t;e.dispatchEvent(new(n?.Event??Event)("input",{bubbles:!0})),e.dispatchEvent(new(n?.Event??Event)("change",{bubbles:!0}))}(o,e.text),function(e){if("searchbox"===e.getAttribute("role"))return!0;if("search"===e.type)return!0;if(null!==e.closest('[role="search"]'))return!0;if(!["name","id","placeholder","aria-label","title"].some(t=>Te.test(e.getAttribute(t)??"")))return!1;const t=e.form;return!t||1===t.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]), select, textarea, [contenteditable="true"]').length}(o)&&function(e){const t=e.ownerDocument.defaultView,n=t?.KeyboardEvent??KeyboardEvent,r={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:!0,cancelable:!0},a=new n("keydown",r);e.dispatchEvent(a),e.dispatchEvent(new n("keyup",r));const o=e.form;o&&!a.defaultPrevented&&Ie(e.ownerDocument,["submit"],()=>o.requestSubmit?.())}(o),{ok:!0}):{ok:!1,error:"not_a_text_field"}:{ok:!1,error:"not_visible"}:{ok:!1,error:"unknown_ref"}}catch(e){return{ok:!1,error:`failed: ${e instanceof Error?e.message:String(e)}`.slice(0,500)}}}const Ee="[truncated]",$e=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function ze(e){if("select"===e.tagName.toLowerCase())return!1;for(const t of Array.from(e.querySelectorAll('a[href], button, summary, select, textarea, input, [contenteditable="true"], [role]')))if(De(t))return!0;return!1}function De(e){const t=e.getAttribute("role");if(t&&$e.has(t))return t;const n=e.tagName.toLowerCase();if("a"===n&&e.hasAttribute("href"))return"link";if("button"===n||"summary"===n)return"button";if("select"===n)return"combobox";if("textarea"===n)return"textbox";if("input"===n){const t=(e.getAttribute("type")||"text").toLowerCase();return"hidden"===t?null:["button","submit","reset","image"].includes(t)?"button":"checkbox"===t||"radio"===t?t:"search"===t?"searchbox":"file"===t?"button":"textbox"}return"true"===e.getAttribute("contenteditable")?"textbox":null}function Re(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function je(e){const t=e.ownerDocument.defaultView;let n="";for(const r of Array.from(e.childNodes))if(3===r.nodeType)n+=r.textContent??"";else if(1===r.nodeType){if(Ge(r)||Be(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?je(r):` ${je(r)} `}return n}function Oe(e){return(e??"").replace(/\s+/g," ").trim()}const Ue=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function We(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=Oe(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const a=Oe(e.getAttribute("aria-label"));if(a)return a;const o=e.getAttribute("id"),i=o&&Array.from(n.getElementsByTagName("label")).find(e=>e.htmlFor===o)||e.closest("label");if(i){const e=Oe(Array.from(i.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||Oe(i.textContent))return e||Oe(i.textContent)}const s=e.tagName.toLowerCase(),l=(e.getAttribute("type")||"").toLowerCase();if("input"===s&&["submit","reset","button"].includes(l)){const t=Oe(e.getAttribute("value"));if(t)return t;if("button"!==l)return"submit"===l?"Submit":"Reset"}const c=Oe(e.getAttribute("alt"))||Oe(e.querySelector("img[alt]")?.getAttribute("alt"));if(c)return c;const d=Be(e)?"":Oe(je(e));if(Ue.has(t)&&d)return d;const u=Oe(e.getAttribute("placeholder"));if(u)return u;const h=Oe(e.getAttribute("title"));return h||d}function He(e){return JSON.stringify(e.slice(0,80))}function Pe(e){const t=[];(e.hasAttribute("disabled")||function(e){if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(e)||"true"===e.getAttribute("aria-disabled"))&&t.push("disabled"),"true"===e.getAttribute("aria-selected")&&t.push("selected"),(e.checked||"true"===e.getAttribute("aria-checked"))&&t.push("checked"),"true"===e.getAttribute("aria-expanded")?t.push("expanded"):"false"!==(e.getAttribute("aria-haspopup")??"false")?t.push("menu"):"false"===e.getAttribute("aria-expanded")&&t.push("collapsed"),"true"===e.getAttribute("aria-pressed")&&t.push("pressed");const n=e.getAttribute("aria-current");return n&&"false"!==n&&t.push("current"),t}const qe=/^(current-password|new-password|one-time-code|cc-)/;function Be(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>qe.test(e))}function Fe(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(Be(e))return null;const n="value"in e?String(e.value??""):Oe(je(e));return n||null}function Ve(e){const t=e.getAttribute("href"),n=e.ownerDocument.defaultView?.location;if(!t||!n)return"";try{const e=new URL(t,n.href);return e.origin===n.origin?` -> ${e.pathname}${e.search}`:""}catch{return""}}function Ge(e){if(e.classList.contains("filigran-chatbot"))return!0;const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!0}if(e.hidden||e.hasAttribute("inert"))return!0;if("true"===e.getAttribute("aria-hidden"))return!0;const n=e.ownerDocument.defaultView?.getComputedStyle(e);return"none"===n?.display||"hidden"===n?.visibility}const Ke="filigranChatConversationId",Je="filigranChatLegacyChatId",Ze=e=>`filigranChatDraft:${e??"new"}`;function Ye(e,t){if("undefined"!=typeof window)try{t?sessionStorage.setItem(Ze(e),t):sessionStorage.removeItem(Ze(e))}catch{}}const Xe=e=>`filigranChatDraftRefs:${e??"new"}`;function Qe(e){if("undefined"==typeof window)return[];try{const t=JSON.parse(sessionStorage.getItem(Xe(e))??"[]");return Array.isArray(t)?t.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.conversationId&&"string"==typeof e.key&&"string"==typeof e.title):[]}catch{return[]}}function et(e,t){if("undefined"!=typeof window)try{t.length>0?sessionStorage.setItem(Xe(e),JSON.stringify(t)):sessionStorage.removeItem(Xe(e))}catch{}}function tt(e){const t=function(e){if("undefined"==typeof window)return"";try{return sessionStorage.getItem(Ze(e))??""}catch{return""}}(e);return{text:t,refs:B(Qe(e),t)}}const nt=52428800;function rt({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:s,requestHeaders:l,pageContext:c,onRelativeLinkClick:d,t:u,maxFileCount:h=10,maxTotalSize:p=52428800}){const m="legacy"===n,[g,f]=r([]),[w,x]=r(!1),[v,y]=r(null),[b,k]=r(()=>"undefined"==typeof window?null:localStorage.getItem(Ke)),[N]=r(()=>tt("undefined"==typeof window?null:localStorage.getItem(Ke))),[C,I]=r(N.text),[S,_]=r(N.refs),[L,A]=r([]),[T,M]=r(null),[E,$]=r(null),[z,D]=r(null),[R,j]=r(!1),[O,U]=r(null),[W,H]=r(!1),[P,q]=r(0),[V,K]=r(0),[J,Z]=r(()=>"undefined"==typeof window?null:localStorage.getItem(Je)),Y=a(!1),X=a(null),Q=a(null),ee=a(null),te=a(!1),ne=a(b),re=a(w);re.current=w;const ae=a(c);ae.current=c;const oe=a(new Map),ie=a(d);ie.current=d;const se=a(l);se.current=l;const le=a(null),ce=a(!1),de=a(null),ue=a(0),[he]=r(xe),ge=a(null),[ye,be]=r(null),Ne=a(new AbortController),Ce=Number.isFinite(h)&&h>0?Math.floor(h):10,Ie=Number.isFinite(p)&&p>0?p:nt;o(()=>{_(e=>B(e,C))},[C]);const Se=i(e=>{_(t=>{return r=e,(n=t).some(e=>e.conversationId===r.conversationId)?n:[...n,r];var n,r})},[]),_e=()=>m||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,Le=()=>{if(m||"ag-ui"===n||t?.singleEndpoint)return null;const r=t?.approve;return r?`${e}${r}`:null},Ae=a(Le);Ae.current=Le;const Te=r=>{if(m||"ag-ui"===n||t?.singleEndpoint)return null;const a=t?.pendingApprovals;return a?`${e}${a}/${r}/pending-approvals`:null},$e=async e=>{const t=Te(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:pe(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Ue=i(()=>{Y.current=!1,q(e=>e+1)},[]),qe=()=>m||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,Be=i(e=>{ne.current=e,k(e),e?localStorage.setItem(Ke,e):localStorage.removeItem(Ke)},[]),Ze=async n=>{if(ne.current)return ne.current;if(he.pending)return he.pending;const r=m||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`;return r?he.run(async(e,t)=>{const a=ge.current,o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify(a?{agent_slug:n,workspace_id:a}:{agent_slug:n}),signal:t});if(!o.ok||!e())return null;const i=await o.json();if(!e())return null;const s=i?.conversation_id??null;return s&&(Y.current=!0,Be(s),ge.current=null,be(null)),s}):null},Xe=async(e,t,n)=>{const r=qe(),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]},Qe=e=>{if(!e||0===e.length||!qe())return;const t=Array.from(e).map(e=>({file:e,tempId:crypto.randomUUID()}));let n=[];A(e=>{const r=e.length,a=e.reduce((e,t)=>e+t.size,0),o=Ce-r;if(o<=0)return e;let i=Ie-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=Ne.current.signal;for(const{file:t,tempId:r}of n)(async()=>{try{const n=await Ze(s);if(!n)return void A(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e));const a=await Xe(t,n,e);A(e=>e.map(e=>e.fileId===r?{...e,fileId:a,uploadStatus:"done"}:e))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;A(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e))}})()},0)},rt=async(e,t,n)=>{const r=Ae.current(),a=n??ne.current;if(!r||!a||"undefined"==typeof document)return;const o=Q.current?.signal,i=async t=>{try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...se.current??{}},body:JSON.stringify({conversation_id:a,page_action:{action_id:e,ok:!1,error:t,url:"",title:"",snapshot:""}})})}catch{}};if(o?.aborted)return i("panel_closed");if(!ve(r,ie.current))return i("page_actions_not_supported");y(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await Me(t,oe.current,ie.current,document,o);if(o?.aborted)return i("panel_closed");if("snapshot"!==t.type&&await function(e,{quietMs:t=300,maxMs:n=3e3,signal:r}={}){return new Promise(a=>{if(r?.aborted)return a();const o=e.defaultView,i=o?.MutationObserver??globalThis.MutationObserver;let s;const l=()=>{clearTimeout(s),clearTimeout(d),c?.disconnect(),r?.removeEventListener("abort",l),a()},c=i?new i(e=>{e.some(e=>!ke(e.target))&&(clearTimeout(s),s=setTimeout(l,t))}):null;c?.observe(e.body??e.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),s=setTimeout(l,t);const d=setTimeout(l,n);r?.addEventListener("abort",l)})}(document,{signal:o}),o?.aborted)return i("panel_closed");let s={text:"",url:"",title:""},l=null;try{const e=function(e,t=2e4){const n=e.defaultView?.location,r=(n?`${n.pathname}${n.search}`:"").slice(0,500),a=Oe(e.title).slice(0,80),o=Math.max(0,t-12);let i=!1,s=`# ${a} — ${r}`;s.length>o&&(s=s.slice(0,o),i=!0);const l=[s];let c=s.length;const d=new Map,u=e=>{for(const t of Array.from(e.children)){if(Ge(t))continue;const e=De(t),n=Re(t);let r=null;if(e){const n=`e${d.size+1}`,a=Fe(t,e),s=Pe(t);if(r=`[${n}] ${e} ${He(We(t,e))}${s.length?` (${s.join(", ")})`:""}${a?` = ${He(a)}`:""}${Ve(t)}`,c+r.length+1>o)return i=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${He(Oe(je(t)))} (level ${n})`,c+r.length+1>o))return i=!0,!1;if(r&&(l.push(r),c+=r.length+1),(!e||ze(t))&&!u(t))return!1}return!0};return e.body&&!i&&u(e.body),i&&l.push(Ee),{text:l.join("\n"),url:r,title:a,refs:d}}(document);oe.current=e.refs,s={text:e.text,url:e.url,title:e.title}}catch(e){oe.current=new Map,l=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...se.current??{}},signal:o,body:JSON.stringify({conversation_id:a,page_action:{action_id:e,ok:n.ok,error:n.error??(null===l?null:`snapshot_failed: ${l}`),url:s.url,title:s.title,snapshot:s.text}})})}catch{}finally{o?.aborted||y(e=>"acting_on_page"===e?.status?{...e,status:"thinking"}:e)}},at=e=>{const t="string"==typeof e&&e?e:null;ge.current=t,be(t),ee.current?.close(),ee.current=null,X.current?.abort(),X.current=null,Q.current?.abort(),Q.current=null,Ne.current.abort(),Ne.current=new AbortController,he.abandon(),f([]),I(""),_([]),A([]),x(!1),y(null),M(null),$(null),D(null),U(null),H(!1),le.current=null,ce.current=!1,de.current=null,te.current=!1,Y.current=!1,m?(Z(null),localStorage.removeItem(Je)):Be(null)};o(()=>{const e=window.setTimeout(()=>{Ye(b,C),et(b,S)},300);return()=>window.clearTimeout(e)},[C,b,S]),o(()=>()=>{ee.current?.close(),Q.current?.abort()},[]);const ot=a({conversationId:b,inputValue:C,conversationRefs:S});ot.current={conversationId:b,inputValue:C,conversationRefs:S},o(()=>()=>{const{conversationId:e,inputValue:t,conversationRefs:n}=ot.current;Ye(e,t),et(e,n)},[]),o(()=>{const e=b;if(!e||w)return;if(de.current===e)return;Te(e)&&Le()&&(de.current=e,(async()=>{const t=await $e(e);t?.proposals&&(ne.current!==e||re.current||(le.current=e,ce.current=!0,U(null),D(t.proposals)))})())},[b,w]),o(()=>{if(!z?.length||!ce.current)return;const e=le.current,t=e?Te(e):null;if(!t)return;const n=window.setInterval(()=>{fetch(t,{headers:{...l??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[z]),o(()=>{if(!W)return;const e=le.current;if(!e)return void H(!1);if(Date.now()>=ue.current)return H(!1),void Ue();let t=!1;const n=window.setTimeout(async()=>{const n=await $e(e);if(!t){if(n)return n.proposals?(ce.current=!0,U(null),D(n.proposals),void H(!1)):n.turnRunning?void K(e=>e+1):(H(!1),void Ue());K(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[W,V,Ue]);const it=w&&null!==_e()&&null!==b;return{messages:g,inputValue:C,setInputValue:I,isLoading:w,agentStatus:v,attachedFiles:L,conversationId:b,contextUsage:E,transferredAgent:T,canSteer:it,pendingApprovals:z,isSubmittingApproval:R,approvalError:O,submitApprovalDecisions:async e=>{const t=Le(),n=le.current??ne.current;if(0!==e.length)if(t&&n){U(null),j(!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 D(null),ce.current?(ce.current=!1,ue.current=Date.now()+9e5,void H(!0)):void y(e=>e?{...e,status:"thinking"}:{status:"thinking"});U(409===r.status?u("This turn is no longer waiting for a decision."):u("Could not send your decision. Please try again."))}catch{U(u("Could not send your decision. Please try again."))}finally{j(!1)}}else U(u("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:W,historyReloadNonce:P,historyLoadedRef:Y,conversationIdRef:ne,handleFileAdd:Qe,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),Qe(t))},handleSendMessage:async()=>{const r=C.trim(),a=G(e,t,n)?F(S,C):[];if(w)return void(r&&0===L.length&&0===a.length&&_e()&&ne.current&&(I(""),await(async e=>{const t=_e(),n=ne.current;if(!t||!n)return;const r={id:crypto.randomUUID(),role:"user",content:e,timestamp:new Date};f(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{f(e=>e.filter(e=>e.id!==r.id)),I(t=>t?`${e}\n${t}`:e)}})(r)));if(!C.trim()&&0===L.length)return;const o=C.trim(),i={id:crypto.randomUUID(),role:"user",content:o,timestamp:new Date,files:L.length>0?[...L]:void 0,conversationRefs:a.length>0?a:void 0};f(e=>[...e,i]),I(""),_([]),A([]),x(!0),y({status:"thinking"}),te.current=!1;const c=he.generation,d=crypto.randomUUID();f(e=>[...e,{id:d,role:"assistant",content:"",timestamp:new Date}]);let h=d,p="",g=!1;const v=function(e){let t=!1,n="",r=null,a=!1;const o=()=>{null!==r&&cancelAnimationFrame(r),r=null},i=()=>{if(o(),!t&&!n)return;const r=t,a=n;t=!1,n="",e(r,a)},s=()=>{null===r&&("function"==typeof requestAnimationFrame?r=requestAnimationFrame(()=>{r=null,i()}):i())};return{text:()=>{a||(t=!0,s())},thinking:e=>{a||(n+=e,s())},flush:i,close:()=>{a=!0,o(),t=!1,n=""}}}((e,t)=>{if(e){const e=h,t=p;y(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),f(n=>n.map(n=>n.id===e?{...n,content:t}:n))}t&&y(e=>({...e,status:e?.status??"thinking",thinkingContent:(e?.thinkingContent??"")+t}))});ee.current=v;const b=new AbortController;Q.current?.abort();const k=new AbortController;try{X.current=b,Q.current=k;const r=(i.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId);if(!ne.current&&ge.current){const e=he.generation,t=await Ze(s);if(he.generation!==e)return;t||(ge.current=null,be(null))}const c=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.referencedConversationIds&&n.referencedConversationIds.length>0&&(e.referenced_conversation_ids=n.referencedConversationIds),n.supportsPageActions&&(e.supports_page_actions=!0),e.supports_artifacts=!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,o,{legacyChatId:J,conversationId:ne.current,agentSlug:s,pageContext:ae.current,supportsToolApproval:null!==Le(),referencedConversationIds:a.map(e=>e.conversationId),supportsPageActions:ve(Le(),ie.current)});r.length>0&&(c.file_ids=r),y({status:"thinking"});const w=await fetch(m||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify(c),signal:b.signal});if(!w.ok||!w.body)return void f(e=>e.map(e=>e.id===d?{...e,content:u("Unable to connect. Please check the configuration.")}:e));const x=function(e){switch(e){case"legacy":return fe;case"ag-ui":return we;default:return me}}(n),N={hasUsedTools:!1,activeNodeId:""},C=w.body.getReader(),I=new TextDecoder;let S="";const _=()=>{if(!g)return;v.flush(),g=!1,p="",h=crypto.randomUUID();const e=h;f(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),y({status:"thinking"})};for(;;){const{done:e,value:t}=await C.read();if(e)break;S+=I.decode(t,{stream:!0});const n=S.split("\n");S=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=x(JSON.parse(n),N);switch(N.hasUsedTools=N.hasUsedTools||te.current,e.action){case"status":{_();const t=h;if(e.contextUsage&&$(e.contextUsage),"tool_start"===e.status&&(te.current=!0),"thinking_text"===e.status){v.thinking(e.thinkingContent??"");break}if(v.flush(),"stream_retract"===e.status)p="",f(e=>e.map(e=>e.id===t?{...e,content:""}:e)),y(e=>({status:"analyzing",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":_(),p+=e.content,v.text();break;case"done":{v.flush(),g=!0,D(null),U(null),e.conversationId&&Be(e.conversationId),e.contextUsage&&$(e.contextUsage),e.transferAgentId&&e.transferAgentName&&M({id:e.transferAgentId,name:e.transferAgentName});const t=h,n=e.content||p,r=new Date;f(a=>a.map(a=>a.id===t?{...a,content:n,timestamp:r,toolNames:e.toolNames,toolCallCount:e.toolCallCount,iterations:e.iterations,attachments:e.attachments,artifacts:e.artifacts,reasoning:e.reasoning,toolCallTrace:e.toolCallTrace,transferChain:e.transferChain,isTruncated:e.isTruncated,serverId:e.messageId??a.serverId}:a));break}case"page_action_required":v.flush(),rt(e.actionId,e.pageAction,e.conversationId);break;case"approval_required":v.flush(),le.current=e.conversationId??ne.current,U(null),D(e.proposals),y(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"});break;case"error":{_(),v.flush();const t=h;return void f(n=>n.map(n=>n.id===t?{...n,content:e.content||u("Sorry, an error occurred. Please try again.")}:n))}case"set_chat_id":Z(e.chatId),localStorage.setItem(Je,e.chatId)}te.current=N.hasUsedTools}catch{}}}if(v.flush(),p&&!g){const e=h,t=p;f(n=>n.map(n=>n.id===e?{...n,content:t||u("No response.")}:n))}}catch(e){if(v.close(),e instanceof DOMException&&"AbortError"===e.name)return;const t=h;f(e=>e.map(e=>e.id===t?{...e,content:u("Sorry, an error occurred. Please try again.")}:e))}finally{v.close(),ee.current===v&&(ee.current=null),Q.current===k&&k.abort(),X.current===b&&(X.current=null),he.generation===c&&(x(!1),y(null),te.current=!1,D(null),U(null),le.current=null,ce.current=!1,de.current=ne.current)}},handleNewChat:at,pendingWorkspaceId:ye,clearPendingWorkspace:e=>{ge.current===e&&(ge.current=null,be(null))},handleStopGenerating:()=>{ee.current?.flush(),ee.current?.close(),ee.current=null,X.current?.abort(),X.current=null,Q.current?.abort(),Q.current=null,x(!1),y(null),te.current=!1,D(null),U(null),H(!1),le.current=null,ce.current=!1,oe.current=new Map,f(e=>e.filter(e=>!("assistant"===e.role&&!e.content)))},conversationRefs:S,addConversationRef:Se,setAttachedFiles:A,setMessages:f,setContextUsage:$,updateConversationId:Be,handleSwitchConversation:e=>{if((m||e!==ne.current)&&(at(),!m)){Be(e);const t=tt(e);I(t.text),_(t.refs)}}}}const at="filigranChatAgentSlug";function ot({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[i,s]=r([]),[l,c]=r(!1),[d,u]=r(!1),[h,p]=r(null),[m,g]=r(!1);o(()=>{if(null===t?.agents||t?.singleEndpoint||"legacy"===n)return;const r=`${e}${t?.agents??"/chat/agents"}`;c(!0),u(!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&&!h){const e=localStorage.getItem(at),n=e?t.find(t=>t.slug===e):null;p(n||t[0])}}).catch(()=>{s([]),u(!0)}).finally(()=>c(!1))},[e,t,n,a]);return{agents:i,agentsLoading:l,agentsError:d,selectedAgent:h,setSelectedAgent:p,agentMenuOpen:m,setAgentMenuOpen:g,handleSwitchAgent:(e,t)=>{e.id!==h?.id?(p(e),e.slug&&localStorage.setItem(at,e.slug),g(!1),t?.()):g(!1)}}}function it(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,workspaceId:"string"==typeof t.workspace_id&&t.workspace_id?t.workspace_id:null===t.workspace_id?null:void 0}}const st=400,lt="filigranChatSidebarWidth";let ct=null,dt=null,ut=0;function ht(){null!==ct&&(window.clearInterval(ct),ct=null),null!==dt&&(document.title=dt,dt=null)}function pt({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:i,isViewingChat:s}){const l=a(!1),c=a(0);o(()=>{if(!r||"undefined"==typeof document)return;ut+=1;const e=()=>{!document.hidden&&document.hasFocus()&&ht()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),ut=Math.max(0,ut-1),0===ut&&ht()}},[r]),o(()=>{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,o=!s||s();if(!a&&o)return;const l=n("Response ready"),d=t?I(n,"{agent} has finished",{agent:t}):n("Your answer is ready");a&&(function(e){if("undefined"==typeof document)return;null===dt&&(dt=document.title),null!==ct&&window.clearInterval(ct);let t=!0;document.title=e,ct=window.setInterval(()=>{t=!t,document.title=t?e:dt??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)),i?.(l,d)}}else c.current=Date.now()},[e,r,t,n,i,s])}function mt({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[s,l]=r(null),[c,d]=r(null),u="rest"===n&&!t?.singleEndpoint,h=void 0===t?.prompts?"/chat/prompts":t.prompts,p=void 0===t?.quota?"/chat/quota":t.quota,m=u&&h?`${e}${h}`:null,g=u&&p?`${e}${p}`:null;o(()=>{if(!m)return void l(null);let e=!1;return fetch(m,{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}},[m,a]);const[f,w]=r(0),x=i(()=>w(e=>e+1),[]);return o(()=>{if(!g)return void d(null);let e=!1;return fetch(g,{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:"",..."global"===t.scope||"user"===t.scope?{scope:t.scope}:{}}}(t))}).catch(()=>{e||d(null)}),()=>{e=!0}},[g,a,f]),{prompts:s,quota:c,refreshQuota:x}}function gt({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a,agentSlug:i}){const[s,l]=r(null),[c,d]=r(!1),u="rest"===n&&!t?.singleEndpoint,h=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,p=u&&h?`${e}${h}`:null;return o(()=>{if(!p)return void l(null);let e=!1;d(!0);const t=i?`${p}?agent_slug=${encodeURIComponent(i)}`:p;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}},[p,i,a]),{suggestions:s,loading:c}}function ft(e){const t=a(e);return function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||"object"!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}(t.current,e)||(t.current=e),t.current}function wt(e){const t=a(e);s(()=>{t.current=e});const n=i((...e)=>t.current?.(...e),[]);return e?n:void 0}const xt=({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"})]}),vt=({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"})]}),yt=({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"})}),bt=({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"})]}),kt=({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"})]}),Nt=({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"})]}),Ct=({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"})}),It=({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"})}),St=({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 18 6-6-6-6"})}),_t=({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"})]}),Lt=({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"})]}),At=({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"})]}),Tt=({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"})}),Mt=({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"})]}),Et=({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"})]}),$t=({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"})]}),zt=({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"})]}),Dt=({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"})]}),Rt=({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 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}),jt=({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:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1"}),t("path",{d:"M2 13h10"}),t("path",{d:"m9 16 3-3-3-3"})]}),Ot=({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 10v6"}),t("path",{d:"M9 13h6"}),t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})]}),Ut=({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"})]}),Wt=({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"})]}),Ht=({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"})]}),Pt=({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"})]}),qt=({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"})]}),Bt=({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"})]}),Ft=({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"})]}),Vt=({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"})]}),Gt=({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"})]}),Kt=({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 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),Jt=({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"})]}),Zt=({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"})]}),Yt=({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.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}),t("path",{d:"m15 5 4 4"})]}),Xt=({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"})]}),Qt=({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"})]}),en=({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"})]}),tn=({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"})}),nn=({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"})]}),rn=({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"})]}),an=({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"})]}),on=({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"})]}),sn=({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"})]}),ln=({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"})]}),cn="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",dn=({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:cn}),t("path",{d:"M16 9a5 5 0 0 1 0 6"}),t("path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"})]}),un=({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:cn}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),hn=({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"})}),pn=({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 mn=({open:e,onClose:n,anchorRef:s,placement:c="bottom-start",width:d=280,children:u})=>{const h=a(null),[p,g]=r({top:0,left:0}),f=i(()=>n(),[n]);if(function(e,t,n=!0){o(()=>{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])}(h,f,e),l(()=>{if(!e||!s.current)return;const t=s.current.getBoundingClientRect(),n=h.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,l=Math.max(8,Math.min(i,window.innerWidth-d-8));g({top:o,left:l})},[e,s,c,d,u]),!e)return null;const w=S(s.current);return m(t("div",{ref:h,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}),w)},gn=({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}});function fn(e){return Math.max(e.maxRight-e.minLeft,0)}const wn=({title:n,children:o})=>{const i=a(null),s=a(null),[c,d]=r(null),[u,h]=r({below:!1,shift:0});if(l(()=>{if(!c||!s.current)return;const{width:e,height:t}=s.current.getBoundingClientRect();h(function(e,t){const n=e.center-t.width/2;let r=0;return n<e.minLeft?r=e.minLeft-n:n+t.width>e.maxRight&&(r=e.maxRight-(n+t.width)),{below:e.top-4-t.height<e.minTop,shift:r}}(c,{width:e,height:t}))},[c,n]),!n)return o;const p=()=>{if(!i.current)return;const e=S(i.current).getBoundingClientRect();d(function(e,t,n){return{top:e.top,bottom:e.bottom,center:(e.left+e.right)/2,minTop:Math.max(t.top,0),minLeft:Math.max(t.left,0)+4,maxRight:Math.min(t.right,n)-4}}(i.current.getBoundingClientRect(),e,window.innerWidth))};return e("span",{ref:i,className:"inline-flex",onMouseEnter:p,onMouseLeave:()=>d(null),onFocus:e=>{const t=e.target;"function"==typeof t.matches&&t.matches(":focus-visible")&&p()},onBlur:()=>d(null),children:[o,c&&m(t("span",{ref:s,className:`pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${u.below?"":"-translate-y-full"} whitespace-normal break-words 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:u.below?c.bottom+4:c.top-4,left:c.center+u.shift,maxWidth:fn(c)},role:"tooltip",children:n}),S(i.current))]})},xn=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(Dt,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(en,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(Wt,{...e})}],vn=({mode:i,agentName:s,agents:l,agentsLoading:d=!1,agentsError:u=!1,selectedAgent:h,transferredFrom:p,agentMenuOpen:m,onAgentMenuToggle:g,onAgentMenuClose:f,onSwitchAgent:w,modeMenuOpen:x,onModeMenuToggle:v,onModeMenuClose:y,onModeChange:b,onNewChat:k,onClose:N,logoIcon:C,agentDashboardUrl:S,historyEnabled:_=!1,historyMenuOpen:A=!1,onHistoryMenuToggle:T,onHistoryMenuClose:M,conversations:E=[],conversationsLoading:$=!1,activeConversationId:z=null,onSelectConversation:D,onDeleteConversation:R,t:j})=>{const O=a(null),U=a(null),W=a(null),[H,P]=r("");o(()=>{m||P("")},[m]);const q=c(()=>{const e=H.trim().toLowerCase();return e?l.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):l},[l,H]),B=l.length>5,F="sidebar"===i?en:"fullscreen"===i?Ut:Dt;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"===i?"rounded-t-xl":""),children:[e("div",{className:"min-w-0",children:[e("button",{ref:O,type:"button",onClick:g,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:C}),t("span",{children:s}),t(It,{size:16,className:"text-gray-400 dark:text-white/30"})]}),p&&t("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal text-gray-400 dark:text-white/30",children:I(j,"Transferred from {agent}",{agent:p})})]}),e(mn,{open:m,onClose:f,anchorRef:O,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:j("Switch to another agent")}),0===l.length&&d&&t("div",{className:"px-4 py-2",children:t(gn,{size:16})}),0===l.length&&!d&&u&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(xt,{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:j("Could not reach the assistant service. Check the connection and try again.")})]}),0===l.length&&!d&&!u&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:j("Agent switching is not available here")}),B&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(Xt,{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:H,onChange:e=>P(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f()},placeholder:j("Search agents..."),"aria-label":j("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:[l.length>0&&0===q.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:j("No agent matches")}),q.map(n=>e("button",{type:"button",onClick:()=>w(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===h?.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:C})}),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:[S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/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($t,{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:j("Browse agents")})]}),S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/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(ln,{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:j("Create agent")})]})]})]}),t("div",{className:"flex-1"}),_&&e(n,{children:[t(wn,{title:j("Conversation history"),children:t("button",{ref:W,type:"button",onClick:T,"aria-label":j("Conversation history"),"aria-haspopup":"menu","aria-expanded":A,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(qt,{size:18})})}),e(mn,{open:A,onClose:()=>M?.(),anchorRef:W,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:j("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[$&&0===E.length&&t("div",{className:"px-4 py-2",children:t(gn,{size:16})}),!$&&0===E.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:j("No conversations yet")}),E.map(n=>{const r=n.conversationId===z,a=L(n.updatedAt,j);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:()=>D?.(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||j("Untitled conversation")}),a&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:a})]}),R&&t("button",{type:"button",onClick:()=>R(n.conversationId),title:j("Delete conversation"),"aria-label":j("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(sn,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("button",{type:"button",onClick:()=>{M?.(),k()},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(Et,{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:j("New conversation")})]})]})]}),t(wn,{title:j("New chat"),children:t("button",{type:"button",onClick:k,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(Et,{size:18})})}),t(wn,{title:j("Switch view"),children:t("button",{ref:U,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(F,{size:18})})}),e(mn,{open:x,onClose:y,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:j("Switch to")}),t("div",{className:"pb-1",children:xn.map(n=>e("button",{type:"button",onClick:()=>{b(n.mode),y()},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 "+(i===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(j)})]},n.mode))})]}),t(wn,{title:j("Close"),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(_t,{size:18})})})]})};function yn({url:e,query:t,exclude:n,requestHeaders:a}){const[i,s]=r(K);return o(()=>{if(!e||null===t)return void s(K);let r=!0;const o=new AbortController,i=window.setTimeout(async()=>{try{const i=await fetch(function(e,t,n){const r=new URLSearchParams({limit:String(8)});return t&&r.set("q",t),n&&r.set("exclude",n),`${e}${e.includes("?")?"&":"?"}${r.toString()}`}(e,t,n),{credentials:"include",headers:{...a??{}},signal:o.signal}),l=i.ok?await i.json():null;if(!r)return;s(i.ok?{query:t,items:V(l),failed:!1}:{query:t,items:[],failed:!0})}catch{r&&s({query:t,items:[],failed:!0})}},150);return()=>{r=!1,window.clearTimeout(i),o.abort()}},[e,t,n,a]),i}function bn({url:e,requestHeaders:t,conversationId:n,text:s,onTextChange:u,textareaRef:h,refs:p,onPick:m}){const g=null!==e,[f,w]=r(null),[x,v]=r(null),[y,b]=r(0),k=a(null),N=d(),C=i(e=>`${N}-option-${e}`,[N]),I=i(()=>{const e=h.current,t=g&&e&&document.activeElement===e&&e.selectionStart===e.selectionEnd?function(e){const t=/@([\w-]*)$/.exec(e);return!t||H(e[t.index-1])?null:{anchor:t.index,query:t[1]}}(e.value.slice(0,e.selectionStart)):null;w(e=>{return(n=e)===(r=t)||n&&r&&n.anchor===r.anchor&&n.query===r.query?e:t;var n,r})},[g,h]),S=i(()=>w(null),[]);l(()=>{const e=k.current;if(null===e)return;k.current=null;const t=h.current;t&&(t.focus(),t.setSelectionRange(e,e))},[s,h]),o(()=>{I()},[s,I]),o(()=>{f||v(null)},[f]);const _=yn({url:e,query:f?.query??null,exclude:n,requestHeaders:t}),[L,A]=r([]);o(()=>{A([])},[n]),o(()=>{A(e=>function(e,t,n){if(null===t.query||t.failed)return e;const r=t.query,a=new Set(t.items.map(e=>e.id)),o=t.items.length<8,i=r.toLowerCase(),s=o?e.filter(e=>e.id===n||a.has(e.id)||!e.title.toLowerCase().includes(i)):e;return J(s.length===e.length?e:s,t.items)}(e,_,n))},[_,n]);const T=c(()=>J(p.map(Z),L),[p,L]);o(()=>{b(0)},[_]);const M=Y({trigger:f,dismissed:null!==f&&f.anchor===x,search:_,referenced:F(p,s).length,exclude:n,known:T}),E="results"===M.kind?M.items:[],$=Math.min(y,Math.max(E.length-1,0)),z=e=>{if(!f)return;const t=function(e,t,n){const r=e.slice(0,t.anchor),a=e.slice(t.anchor+1+t.query.length),o=`@${n}`;return{text:`${r}${o}${/^\s/.test(a)?"":" "}${a}`,caret:r.length+o.length+1}}(s,f,e.key);m({conversationId:e.id,title:e.title,key:e.key,isOwn:e.isOwn}),k.current=t.caret,u(t.text),w(null)},D=g?{"aria-autocomplete":"list","aria-controls":"results"===M.kind?N:void 0,"aria-activedescendant":"results"===M.kind?C($):void 0}:{};return{view:M,activeIndex:$,setActiveIndex:b,listboxId:N,optionId:C,sync:I,close:S,pick:z,onKeyDown:e=>{if("closed"===M.kind||!f||e.nativeEvent.isComposing)return!1;if("Escape"===e.key)return e.preventDefault(),v(f.anchor),!0;if(0===E.length)return!1;if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;return b(($+t+E.length)%E.length),!0}return!("Enter"!==e.key&&"Tab"!==e.key||e.shiftKey)&&(e.preventDefault(),z(E[$]),!0)},textareaAria:D}}function kn(e,t){let n="idle",r=!1,a=!1,o=!1;const i=()=>"listening"===n||r,s=()=>{a||i()===o||(o=i(),t.onListeningChange(o))},l=()=>{try{return e.start(),!0}catch{return!1}};return e.onresult=e=>{if("listening"!==n&&"stopping"!==n)return;let r="",a="";for(let t=e.resultIndex;t<e.results.length;t++){const n=e.results[t];n.isFinal?r+=n[0].transcript:a+=n[0].transcript}const o=r.trim();o&&t.onFinal(o),"listening"===n&&t.onInterim(a.trim())},e.onerror=()=>{"listening"===n&&(n="stopping",t.onInterim("")),s()},e.onend=()=>{if(t.onInterim(""),"listening"===n){if(l())return;n="idle"}else r?(r=!1,n=l()?"listening":"idle"):n="idle";s()},{toggle:()=>{a||(i()?(()=>{if(r=!1,"listening"===n){n="stopping",t.onInterim("");try{e.stop()}catch{n="idle"}}s()})():(l()?n="listening":"idle"!==n&&(r=!0),s()))},cancel:()=>{if(!a){if(r=!1,"listening"===n||"stopping"===n){n="discarding",t.onInterim("");try{e.abort()}catch{n="idle"}}s()}},dispose:()=>{if(!a){if(a=!0,e.onresult=null,e.onerror=null,e.onend=null,"idle"!==n)try{e.abort()}catch{}n="idle",r=!1}}}}function Nn(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const Cn=14,In=2*Math.PI*6,Sn=[{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"}],_n=({usage:o,t:i})=>{const{used:s,limit:l,breakdown:c}=o,d=a(null),[u,h]=r(!1),p=Math.min(Math.max(s/l,0),1),m=p>=.95,g=p>=.8,f=m?"text-red-500":g?"text-amber-500":"text-[var(--chat-accent)]",w=m?"text-red-500 dark:text-red-400":g?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",x=Math.round(100*p),v=`${_(s)}/${_(l)}`,y=i(m?"Context full — older turns are being dropped":g?"Context nearly full — older turns are being summarized":"Context used"),b=I(i,"{counts} tokens",{counts:v}),k=`${y} · ${b}`,N=c?Sn.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:Cn,height:Cn,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:In,strokeDashoffset:In*(1-p),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${w}`,children:[x,"%"]})]});return C?e(n,{children:[t(wn,{title:u?"":I(i,"{summary} — click for details",{summary:k}),children:t("button",{ref:d,type:"button",onClick:()=>h(e=>!e),"aria-label":`${k} (${x}%)`,"aria-haspopup":"dialog","aria-expanded":u,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(mn,{open:u,onClose:()=>h(!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 ${w}`,children:I(i,"{percent}% full",{percent:x})}),e("span",{className:"text-[0.7rem] tabular-nums text-gray-400 dark:text-white/40 shrink-0",children:["~",b]})]}),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:n.label(i)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0",children:_(c?.[n.field]??0)})]},n.field))}),g&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${w}`,children:y})]})]}):t(wn,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${x}%)`,children:S})})},Ln=({view:n,activeIndex:r,listboxId:o,optionId:i,onHover:s,onPick:c,t:d})=>{const u=a(null);if(l(()=>{u.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[r,n.kind]),"closed"===n.kind)return null;const h=d("Reference a conversation");return e("div",{className:"absolute left-0 right-0 bottom-full mb-1.5 z-20 rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl",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:h}),"results"===n.kind&&t("div",{ref:u,id:o,role:"listbox","aria-label":h,className:"max-h-[240px] overflow-y-auto pb-1 filigran-chat-scrollable",children:n.items.map((n,a)=>{const o=a===r;return e("div",{id:i(a),role:"option","aria-selected":o,onMouseDown:e=>{e.preventDefault(),c(n)},onMouseMove:()=>{o||s(a)},className:"flex items-center gap-2.5 px-4 py-1.5 cursor-pointer transition-colors "+(o?"bg-gray-100 dark:bg-white/10":""),children:[t("span",{className:"shrink-0 text-[var(--chat-accent)]",children:t(Kt,{size:14})}),e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] text-gray-900 dark:text-white truncate",children:n.title||d("Untitled conversation")}),e("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:["@",n.key,!n.isOwn&&` · ${d("Shared with you")}`]})]})]},n.id)})}),"empty"===n.kind&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:d("No conversation matches")}),"full"===n.kind&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:I(d,"A message references at most {count} conversations",{count:5})})]})},An=({prompts:o,onPick:i,t:s})=>{const l=a(null),[c,d]=r(!1),[u,h]=r(""),p=()=>{d(!1),h("")},m=u.trim().toLowerCase(),g=m?o.filter(e=>e.title.toLowerCase().includes(m)||(e.description??"").toLowerCase().includes(m)):o;return e(n,{children:[t(wn,{title:s("Insert prompt template"),children:t("button",{ref:l,type:"button",onClick:()=>c?p():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(tn,{size:15})})}),e(mn,{open:c,onClose:p,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:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Escape"===e.key&&p()},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===g.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:s("No prompt matches")}),g.map(n=>e("button",{type:"button",onClick:()=>{i(n.content),p()},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))]})]})]})},Tn=({quota:n,t:r})=>{const{used:a,limit:o}=n,i=function(e,t){switch(e){case"daily":return t("today");case"monthly":return t("this month");case"yearly":return t("this year");default:return e}}(n.period,r),s=e=>"global"===n.scope?I(r,"{quota} (shared across all users)",{quota:e}):e;if(null===o){const e=s(i?I(r,"Usage · {period}",{period:i}):r("Usage"));return t(wn,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30",role:"img","aria-label":`${e} ${_(a)}`,children:_(a)})})}const l=o>0?Math.min(a/o,1):1,c=!(o>0)||a>=o,d=l>=.75,u=c?"bg-red-500":d?"bg-amber-500":"bg-[var(--chat-accent)]/60",h=c?"text-red-500 dark:text-red-400":d?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",p=`${_(a)}/${_(o)}`,m=r(c?"Quota reached":"Quota"),g=s(i?`${m} · ${i}`:m);return t(wn,{title:g,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${g} ${p}`,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 ${u}`,style:{width:100*l+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${h}`,children:p})]})})},Mn=[],En=({inputValue:s,onInputChange:c,onSend:d,onStop:u,isLoading:h,canSteer:p=!1,attachedFiles:m=[],onFileAdd:g,onFileRemove:f,onPaste:w,t:x,mode:v,separatorColor:y,prompts:b,quota:k,contextUsage:N,composerToolbar:C,conversationReferences:I})=>{const S=a(null),_=a(null),L=bn({url:I?.url??null,requestHeaders:I?.requestHeaders,conversationId:I?.conversationId,text:s,onTextChange:c,textareaRef:_,refs:I?.refs??Mn,onPick:e=>I?.onPick(e)}),A=a(!1),T=function(e){const[t,n]=r(!1),[s,l]=r(""),c=a(null),d=a(e);d.current=e;const u=null!==Nn();return o(()=>{const e=Nn();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=kn(t,{onFinal:e=>d.current(e),onInterim:l,onListeningChange:n});return c.current=r,()=>{c.current=null,r.dispose(),n(!1),l("")}},[]),{supported:u,listening:t,interim:s,toggle:i(()=>c.current?.toggle(),[]),cancel:i(()=>c.current?.cancel(),[])}}(e=>{A.current=!0,c(s.trim()?`${s.trimEnd()} ${e}`:e)});l(()=>{const e=_.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,A.current&&(A.current=!1,e.scrollTop=e.scrollHeight))},[s]);const M=Boolean(b&&b.length>0||k||N||C),E=Boolean(g&&f&&w),$=s.trim()||E&&m.length>0,z=E&&m.some(e=>"pending"===e.uploadStatus),D=$&&!z,R=E&&m.length>0,j=Boolean(I)&&F(I?.refs??Mn,s).length>0,O=h&&p&&Boolean(s.trim())&&!R&&!j,U=()=>{(h?O:D)&&(T.cancel(),d())},W=x(h&&p&&!R&&!j?"Enter to send now · Esc to stop":h&&R?"Attachments wait for the current response":h&&j?"Referenced conversations 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"===v?"rounded-b-xl":""),style:y?{borderTopColor:y,borderTopWidth:1}:void 0,children:[E&&m.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:m.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(zt,{size:14}),n.name,"error"===n.uploadStatus&&t("span",{className:"text-red-400 text-[0.6rem]",children:"✕"}),t("button",{type:"button",onClick:()=>f?.(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:`relative flex items-end border rounded-xl px-2 py-1 transition-colors ${T.listening?"border-red-500/50":"border-gray-200 dark:border-white/10 focus-within:border-[var(--chat-accent)]"} ${h?"filigran-chat-active-border":""}`,children:[E&&e(n,{children:[t("input",{ref:S,type:"file",multiple:!0,hidden:!0,onChange:e=>{g?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>S.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(yt,{size:18})})]}),t("textarea",{ref:_,placeholder:T.listening?x("Listening..."):x("Ask a question..."),value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{L.onKeyDown(e)||("Enter"!==e.key||e.shiftKey||(e.preventDefault(),U()),"Escape"===e.key&&h&&(e.preventDefault(),u()))},onKeyUp:L.sync,onClick:L.sync,onFocus:L.sync,onBlur:L.close,...L.textareaAria,onPaste:w,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(Ln,{view:L.view,activeIndex:L.activeIndex,listboxId:L.listboxId,optionId:L.optionId,onHover:L.setActiveIndex,onPick:L.pick,t:x}),T.supported&&t(wn,{title:T.listening?x("Stop dictation"):x("Dictate a message"),children:e("button",{type:"button",onClick:T.toggle,"aria-label":x("Dictate a message"),"aria-pressed":T.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors "+(T.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:[T.listening?t(Zt,{size:18}):t(Jt,{size:18}),T.listening&&t("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse"})]})}),O&&t(wn,{title:x("Send now"),children:t("button",{type:"button",onClick:U,"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(Qt,{size:18})})}),t(wn,{title:h?x("Stop generating"):z?x("Files uploading..."):"",children:t("button",{type:"button",onClick:h?u:U,disabled:!h&&!D,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":D?"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?nn:Qt,{size:18})})})]}),M&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[b&&b.length>0&&t(An,{prompts:b,onPick:e=>{c(s.trim()?`${s.trimEnd()}\n\n${e}`:e),_.current?.focus()},t:x}),C,(N||k)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[N&&t(_n,{usage:N,t:x}),k&&t(Tn,{quota:k,t:x})]})]}),T.interim?e("p",{className:"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-red-500 dark:text-red-400 mt-1.5",children:[t("span",{className:"w-1.5 h-1.5 shrink-0 rounded-full bg-red-500 motion-safe:animate-pulse"}),t("span",{className:"truncate",children:T.interim})]}):t("p",{className:"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70",children:W})]})},$n=e=>e.serverId??e.id;const zn=w().use(f).use(g).freeze(),Dn=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function Rn(e){if(Dn.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(Rn).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function jn(e,t){if(!Dn.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(Rn(e));case"tableRow":return void t.push((e.children??[]).map(Rn).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])jn(n,t)}}const On=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;const Un=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;function Wn(e){const[t]=r(Un),[n,l]=r(null),c=a(null),d=a(e);s(()=>{d.current=e});const u=i(()=>t?(c.current??=function(e,t,n){let r=0,a=null;const o=e=>{e===r&&null!==a&&(r+=1,a=null,n(null))},i=()=>{null!==a&&(r+=1,a=null,e.cancel(),n(null))};return{speak:(s,l,c)=>{i();const d=l.filter(e=>e.trim());if(!d.length)return!1;const u=r;return a=s,n(s),d.forEach((n,a)=>{const i=a===d.length-1,s=t(n,{lang:c,onEnd:()=>{i&&o(u)},onError:()=>{u===r&&(o(u),e.cancel())}});e.speak(s)}),!0},stop:i,get speakingId(){return a}}}(window.speechSynthesis,(e,{lang:t,onEnd:n,onError:r})=>{const a=new SpeechSynthesisUtterance(e);return t&&(a.lang=t),a.onend=n,a.onerror=r,a},l),c.current):null,[t]),h=i((e,t)=>{const n=u();n&&(n.speakingId===e?n.stop():n.speak(e,function(e,t=220){const n=e.split(/\n+|(?<=[.!?;:\u3002\uff01\uff1f])\s+/).map(e=>e.trim()).filter(Boolean),r=[];for(const e of n){if(e.length<=t){r.push(e);continue}let n="";for(const a of e.split(" "))for(let e=0;e<a.length;e+=t){const o=a.slice(e,e+t);n?n.length+1+o.length<=t?n=`${n} ${o}`:(r.push(n),n=o):n=o}n&&r.push(n)}const a=[];for(const e of r){const n=a.length-1;n>=0&&a[n].length+1+e.length<=t?a[n]=`${a[n]} ${e}`:a.push(e)}return a}(function(e){const t=[];for(const n of e)n.trim()&&jn(zn.parse(n),t);return t.map(e=>e.replace(/\s+/g," ").replace(/ ([.,!?;:])/g,"$1").trim()).filter(e=>/[\p{L}\p{N}]/u.test(e)).map(e=>/[.!?;:\u3002\uff01\uff1f]$/.test(e)?e:`${e}.`).join("\n")}(t)),d.current))},[u]),p=i(()=>c.current?.stop(),[]);return o(()=>()=>c.current?.stop(),[]),{supported:t,speakingId:n,toggle:h,stop:p}}const Hn={time:{hour:"2-digit",minute:"2-digit"},date:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"},dateWithYear:{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"},full:{dateStyle:"full",timeStyle:"short"}},Pn=new Map;function qn(e,t){const n=`${e??""}|${t}`;let r=Pn.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,Hn[t])}catch{r=new Intl.DateTimeFormat(void 0,Hn[t])}Pn.set(n,r)}return r}const Bn={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const Fn=new Set(["ArrowUp","PageUp","Home"]);function Vn(e){return 1===e.length?e[0].clientY:null}const Gn=new Set(["auto","scroll","overlay"]);const Kn={presentation:({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:"M2 3h20"}),t("path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"}),t("path",{d:"m7 21 5-5 5 5"})]}),report:({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"}),t("path",{d:"M10 9H8"}),t("path",{d:"M16 13H8"}),t("path",{d:"M16 17H8"})]}),video:({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:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z"}),t("path",{d:"m6.2 5.3 3.1 3.9"}),t("path",{d:"m12.4 3.4 3.1 4"}),t("path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})]})},Jn="inline-flex items-center gap-1 rounded-md border border-gray-200 dark:border-white/10 px-2 py-1 text-[0.7rem] text-gray-700 dark:text-white/70 transition-colors hover:border-[var(--chat-accent)] hover:text-[var(--chat-accent)] disabled:opacity-50 disabled:cursor-default outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",Zn=({artifact:n,t:a,onDownload:i,onRefresh:s})=>{const[l,c]=r(n),[d,u]=r(null),[h,p]=r(!1);o(()=>c(n),[n]);const m=!!s&&!h&&(e=>"video"===e.kind&&("pending"===e.status||"running"===e.status))(l);o(()=>{if(!m||!s)return;let e=!1;const t=function(e,{intervalMs:t,forMs:n,onGiveUp:r}){let a,o=!1;const i=()=>{a=setTimeout(()=>{e().catch(()=>{}).finally(()=>{o||i()})},t)},s=setTimeout(()=>{o=!0,clearTimeout(a),r?.()},n);return i(),()=>{o=!0,clearTimeout(a),clearTimeout(s)}}(()=>s(l.kind,l.id).then(t=>{!e&&t&&c(t)}),{intervalMs:1e4,forMs:9e5,onGiveUp:()=>p(!0)});return()=>{e=!0,t()}},[m,s,l.kind,l.id]);const g=Kn[l.kind],f=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(l.kind,a),w=l.title||f,x=D(l,a),v=function(e,t){if("video"===e.kind){if("running"===e.status)return I(t,"Rendering {progress}%",{progress:Math.round(e.progress??0)});if("pending"===e.status)return t("Waiting to render");if(!(e.downloads.length>0))return"failed"===e.status||"cancelled"===e.status?t("The render did not finish"):t("Not rendered yet")}}(l,a),y=function(e){if(e.url)try{const t=new URL(e.url);return"http:"===t.protocol||"https:"===t.protocol?t.toString():void 0}catch{return}}(l),b=i?l.downloads:[];return e("div",{role:"group","aria-label":`${f}: ${w}`,className:"flex flex-col gap-2 w-full max-w-[90%] rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] px-3 py-2.5",children:[e("div",{className:"flex items-start gap-2.5 min-w-0",children:[t("span",{className:"shrink-0 mt-0.5 text-[var(--chat-accent)]",children:t(g,{size:18})}),e("span",{className:"flex flex-col min-w-0 flex-1 gap-0.5",children:[t("span",{className:"truncate text-[0.8125rem] font-medium text-gray-900 dark:text-white",children:w}),x&&t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/50",children:x}),v&&e("span",{className:"flex items-center gap-1.5 text-[0.7rem] text-gray-500 dark:text-white/50","aria-live":"polite",children:[m&&t(gn,{size:10}),v]})]})]}),(y||b.length>0)&&e("div",{className:"flex flex-wrap items-center gap-1.5 pl-[28px]",children:[y&&e("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:Jn,children:[a("Open in XTM One"),t($t,{size:12})]}),b.map(n=>{const r=function(e,t){return"pdf"===e?"PDF":"mp4"===e?"MP4":"pptx"===e?t("PowerPoint"):"pptx_native"===e?t("PowerPoint (editable)"):e.toUpperCase()}(n,a);return e("button",{type:"button",className:Jn,disabled:null!==d,"aria-label":I(a,"Download {format}",{format:r}),onClick:()=>{(async e=>{if(i){u(e);try{await i(l,e)}finally{u(null)}}})(n)},children:[d===n?t(gn,{size:11}):t(Mt,{size:12}),r]},n)})]})]})};function Yn(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function Xn(e){const t=a(null);return o(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const Qn="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",er=({proposal:n,decision:a,onDecide:o,disabled:i,t:s})=>{const[l,c]=r(!1),[u,h]=r(""),p=d(),m=Xn(l),g=a?.verdict,f=Object.keys(n.arguments??{}),w=e=>{o({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&u.trim()?{rejectionReason:u.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(hn,{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})]})]}),g&&t("span",{className:"shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===g?"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"===g?"Declined":"approve_always"===g?"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:Yn(n.arguments?.[r])})]},r)})}),!g&&l&&e("div",{ref:m,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:p,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:p,autoFocus:!0,rows:2,value:u,onChange:e=>h(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:()=>w("reject"),className:`${Qn} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(pn,{size:13}),s("Decline this call")]}),t("button",{type:"button",disabled:i,onClick:()=>{c(!1),h("")},className:`${Qn} text-gray-500 hover:bg-gray-100 dark:text-white/50 dark:hover:bg-white/5`,children:s("Back")})]})]}),!g&&!l&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:i,onClick:()=>c(!0),className:`${Qn} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(pn,{size:13}),s("No")]}),e("button",{type:"button",disabled:i,onClick:()=>w("approve"),className:`${Qn} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(Ct,{size:13}),s("Yes")]}),t("button",{type:"button",disabled:i,onClick:()=>w("approve_always"),title:s("Also applies to your scheduled runs, until you revoke it"),className:`${Qn} 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")})]})]})},tr=({proposals:n,onSubmit:i,isSubmitting:s,error:l,t:c})=>{const[d,u]=r({}),h=a(!1),[p,m]=r(!1);o(()=>{l&&(h.current=!1,m(!1))},[l]);const g=s||p,f=e=>{h.current||s||(h.current=!0,m(!0),i(e))},w=n.filter(e=>d[e.toolCallId]).length,x=w===n.length&&n.length>0,v=Object.values(d).some(e=>"approve_always"===e.verdict),y=Xn(v),b=Xn(!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(xt,{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(er,{proposal:e,decision:d[e.toolCallId],disabled:g,t:c,onDecide:e=>{const t={...d,[e.toolCallId]:e};u(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(xt,{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:y,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?I(c,"{decided}/{total} decided",{decided:w,total:n.length}):""}),t("button",{type:"button",disabled:!x||g,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${Qn} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:c(g?"Sending…":"Confirm")})]})]})},nr=({src:n,alt:i,onClose:s,t:l})=>{const c=a(null),d=a(null),[u,h]=r(null);return o(()=>{h(S(c.current))},[]),o(()=>{const e=e=>{"Escape"===e.key&&s()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[s]),o(()=>{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&&m(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(_t,{size:20})}),t("img",{src:n,alt:i,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},rr=({src:a,alt:i,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),[u,h]=r(null),[p,m]=r(!1),[g,f]=r(!1);o(()=>{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),h(t))}).catch(()=>{e||m(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,a,s]);const w=d?u:a;return p?t("p",{className:"my-2 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:c("Image could not be loaded")}):w?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:w,alt:i,loading:"lazy",onClick:()=>f(!0),onError:()=>m(!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(Gt,{size:14})})]}),g&&t(nr,{src:w,alt:i,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(Bt,{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…")})]})};const ar="inline-flex items-center gap-1.5 self-start rounded text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100",or=({t:n,enabled:a=!0,onPlay:i,playUrl:s,keepEndInView:l})=>{const d=c(()=>(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]),u=function(){const[e,t]=r(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return o(()=>{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}(),[h,p]=r(0);if(o(()=>{a&&l()},[a,l]),o(()=>{if(!a)return;const e=window.setInterval(()=>p(e=>(e+1)%d.length),2600);return()=>window.clearInterval(e)},[a,d.length]),!a)return null;const m=d[h%d.length];return e("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:m}),e("div",{className:"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5",style:u?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[e("span",{"aria-hidden":!0,className:"text-xs text-gray-500 dark:text-white/45",style:u?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[m,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(u?"":"animate-pulse")})]},m),i?e("button",{type:"button",onClick:i,className:ar,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(Ht,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:ar,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(Ht,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t($t,{size:11})})]}):null]})]})};function ir(e,t){return e>1?I(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function sr(e,t){return e>1?I(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function lr(e,t){return e>1?I(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function cr(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 dr({text:e}){const n=a(null),[i,s]=r(!1);return o(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight,s(e.scrollHeight>e.clientHeight+1))},[e]),t("div",{className:"filigran-chat-reasoning 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",children:t("div",{ref:n,className:"max-h-40 overflow-hidden"+(i?" [-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:e})})})}function ur(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`}function hr(e,t,n=0){const[a,i]=r(null);return o(()=>{if(i(null),!e)return;const r=window.setTimeout(()=>i(n),t);return()=>window.clearTimeout(r)},[e,t,n]),e&&a===n}const pr=({agentStatus:a,logoIcon:i,t:s,miniGameEnabled:l=!0,onPlayWaitingGame:d,waitingGameUrl:u,keepEndInView:h})=>{const{label:p,StatusIcon:m,showDots:g}=function(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:kt,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:ir(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:ln,showDots:!1};if(r.some(e=>"check_task_status"===e))return{label:sr(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:tn,showDots:!1};if(r.some(e=>"get_task_result"===e))return{label:lr(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:tn,showDots:!1};let a,o=hn;if(r.some(e=>e.includes("search")||e.includes("list"))?o=Xt:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?o=At:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?o=Vt:r.some(e=>e.includes("code")||e.includes("execute"))?o=rn:r.some(e=>e.includes("web")||e.includes("browse"))&&(o=Pt),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]}…`:I(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:xt,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:tn,showDots:!0};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:tn,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:tn,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:kt,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:I(t,"Consulting {agent}…",{agent:n}),StatusIcon:ln,showDots:!1}}case"delegating":return{label:ir(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:ln,showDots:!1};case"polling":return{label:sr(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:tn,showDots:!1};case"collecting":return{label:lr(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:tn,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:I(t,"Transferring to {agent}…",{agent:n}),StatusIcon:$t,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:kt,showDots:!1}}}(a,s),f=a?.thinkingContent,w=a?.elapsedStartMs,[x,v]=r(()=>Date.now());o(()=>{if(null==w)return;v(Date.now());const e=window.setInterval(()=>v(Date.now()),1e3);return()=>window.clearInterval(e)},[w]);const y=null!=w?Math.max(0,(x-w)/1e3):a?.elapsedS,b="number"==typeof y&&y>=15,k=c(()=>function(e){if(e.length<=6e3)return cr(e);const t=[];let n=0;for(let r=e.indexOf("```");-1!==r;r=e.indexOf("```",n)){const a=e.indexOf("```",r+3);if(-1===a)break;t.push([n,r]),n=a+3}t.push([n,e.length]);const r=[];let a=6e3;for(let n=t.length-1;n>=0&&a>0;n--){const[o,i]=t[n],s=Math.max(o,i-a);r.push(e.slice(s,i)),a-=i-s+1}let o=r.reverse().join(" ");if(a<=0){const e=o.indexOf("\n\n");-1!==e&&e<o.length/2&&(o=o.slice(e+2))}return cr(o)}(f??""),[f]),N=k.length>=3,C=hr(l&&!N,5e3),S=hr(l&&N,1e4,f?.length??0),_=N?S:C;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:i})}),e("div",{className:"filigran-chat-active-border 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:[g?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(m,{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:p}),b&&t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:ur(y)})]})]})]}),_?t(or,{t:s,enabled:l,onPlay:d,playUrl:u,keepEndInView:h}):N?t(dr,{text:k}):null]})},mr=w().use(f).use(g).freeze();function gr(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(gr);default:return!1}}function fr(e,t){return e.lastIndexOf("\n",t-1)+1}function wr(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(fr(e,t-1),t-1).trim()}function xr(e,t,n){const r=e.slice(t,n).split("\n");for(let e=r.length-1;e>=0;e--)if(r[e].trim())return/^(?: {4}|\t)/.test(r[e]);return!1}class vr{last=null;split(e){return this.last?.source!==e&&(this.last=function(e,t){if(!e.trim())return function(e){return{source:e,blocks:e?[e]:[],starts:e?[0]:[],settled:0,firstDefinition:-1}}(e);const n=t&&t.settled>0&&e.startsWith(t.source)?t.settled:0,r=n?t.starts[n]:0,a=e.slice(r),o=t&&n?t.starts.slice(0,n):[];let i=t&&n&&t.firstDefinition<n?t.firstDefinition:-1;o.push(r);for(const t of mr.parse(a).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+fr(a,n),i=o[o.length-1];t>i&&!xr(e,i,t)&&o.push(t)}i<0&&gr(t)&&(i=o.length-1)}let s=n;for(let t=o.length-1;t>n;t--)if(wr(e,o[t])){s=t;break}const l=i<0?o.map((t,n)=>e.slice(t,o[n+1]??e.length)):[e];return{source:e,blocks:l,starts:o,settled:s,firstDefinition:i}}(e,this.last)),this.last.blocks}}const yr=u({copiedBlock:null,onCopyCode:()=>{},t:C}),br={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{copiedBlock:a,onCopyCode:o,t:i}=p(yr),s=/language-(\w+)/.exec(n||""),l=String(r).replace(/\n$/,"");return s||l.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:s?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>o(l),"aria-label":i(a===l?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors",children:a===l?t(Ct,{size:14,className:"text-green-500"}):t(Lt,{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:l})})]}):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{onRelativeLinkClick:r}=p(yr),a=be(e),o=null!==a&&!!r,i=!(o||(e=>!!e&&!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e)&&null!==a);return t("a",{href:e,onClick:e=>{o&&(e.preventDefault(),r(a))},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})=>{const{requestHeaders:r,t:a}=p(yr);return"string"==typeof e&&e?t(rr,{src:e,alt:n||"",requestHeaders:r,t:a},e):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})},kr=[g,v],Nr=h(({source:e})=>t(x,{remarkPlugins:kr,urlTransform:N,components:br,children:e}));Nr.displayName="MarkdownBody";const Cr=({source:e})=>{const[a]=r(()=>new vr),o=c(()=>a.split(e),[a,e]);return t(n,{children:o.map((e,n)=>t(Nr,{source:e},n))})},Ir=h(({content:e,streaming:n=!1,onRelativeLinkClick:a,requestHeaders:o,t:s=C})=>{const[l,d]=r(null),[u,h]=r(n);n&&!u&&h(!0);const p=c(()=>b(e),[e]),m=i(e=>{navigator.clipboard.writeText(e),d(e),setTimeout(()=>d(null),2e3)},[]),g=c(()=>({copiedBlock:l,onCopyCode:m,onRelativeLinkClick:a,requestHeaders:o,t:s}),[l,m,a,o,s]);return t(yr.Provider,{value:g,children:t(u?Cr:Nr,{source:p})})});Ir.displayName="MarkdownMessage";function Sr(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function _r(e){return e.replace(/_/g," ")}const Lr=({entry:n,index:a,t:o})=>{const[i,s]=r(!1),l=c(()=>Sr(n.input),[n.input]),d=c(()=>Sr(n.output),[n.output]),u=!!l&&"{}"!==l;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(Nt,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(pn,{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:_r(n.name)}),t(It,{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:[u&&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:l})]}),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)")})]})]})]})},Ar=({msg:n,onClose:i,t:s})=>{const l=a(null),c=a(null),d=a(null),[u,h]=r(null);o(()=>{h(S(l.current))},[]),o(()=>{const e=e=>{if("Escape"===e.key)return void i();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],o=document.activeElement;e.shiftKey?o!==r&&t.contains(o)||(e.preventDefault(),a.focus()):o!==a&&t.contains(o)||(e.preventDefault(),r.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[i]),o(()=>{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,g=n.toolNames??[],f=n.iterations??1,w=n.transferChain??[],x=n.toolCallTrace??[],v=(n.reasoning??"").trim(),y=[f>1?I(s,"{count} iterations",{count:f}):"",1===p?s("1 tool call"):I(s,"{count} tool calls",{count:p}),1===w.length?s("1 transfer"):w.length>1?I(s,"{count} transfers",{count:w.length}):""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:u&&m(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:i,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(hn,{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:i,"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(_t,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] text-gray-500 dark:text-white/40",children:y.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(xt,{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(kt,{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:cr(v)})})]}),x.length>0?t("div",{className:"flex flex-col gap-1.5",children:x.map((e,n)=>t(Lr,{entry:e,index:n,t:s},`${e.name}-${n}`))}):g.length>0&&t("div",{children:g.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(hn,{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:_r(n)})]},`${n}-${r}`))}),w.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(vt,{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:w.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(bt,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},Tr=e=>e.parentElement,Mr=e=>getComputedStyle(e).overflowY;function Er(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function $r(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 zr=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const Dr="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",Rr="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",jr="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",Or=`opacity-0 ${Dr} ${jr}`,Ur=`opacity-50 ${Dr} ${jr}`,Wr="opacity-100 text-[var(--chat-accent)]",Hr=({timestamp:n,locale:r})=>{const a=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:qn(t,(a=n,(r=e).getFullYear()===a.getFullYear()&&r.getMonth()===a.getMonth()&&r.getDate()===a.getDate()?"time":e.getFullYear()===n.getFullYear()?"date":"dateWithYear")).format(e),full:qn(t,"full").format(e),iso:e.toISOString()}:null;var r,a}(n,r);return a?t(wn,{title:a.full,children:e("time",{dateTime:a.iso,className:"px-1 text-[0.65rem] tabular-nums text-gray-400 dark:text-white/40 select-none",children:[t("span",{"aria-hidden":"true",children:a.label}),t("span",{className:"sr-only",children:a.full})]})}):null},Pr=({text:e,label:n,t:a})=>{const[o,i]=r(!1),s=o?a("Copied!"):n;return t(wn,{title:s,children:t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),i(!0),setTimeout(()=>i(!1),2e3)}catch{}},"aria-label":s,className:`${Rr} ${o?"opacity-100 text-green-500 dark:text-green-400":Or}`,children:t(o?Ct:Lt,{size:14})})})},qr=({value:r,locked:a,pending:o,onChange:i,downRef:s,t:l})=>{const c=d(),u=a||o,h=(e,n)=>{const o=r===e;if(a&&!o)return null;const d="up"===e?on:an;return t(wn,{title:a?l("Feedback already submitted"):n,children:t("button",{ref:"down"===e?s:void 0,type:"button",onClick:()=>{u||i(o?null:e)},"aria-label":n,"aria-pressed":o,"aria-disabled":u||void 0,"aria-describedby":a?c:void 0,className:`${Rr} ${o?Wr:Or} ${u?"cursor-default":""}`,children:t(d,{size:14,filled:o})})})};return e(n,{children:[h("up",l("Good response")),h("down",l("Bad response")),a&&t("span",{id:c,className:"sr-only",children:l("Feedback already submitted")})]})},Br=({pending:n,onSave:a,onSkip:o,t:i})=>{const[s,l]=r(""),c=d(),u=!n&&!!s.trim();return e("div",{className:"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] p-2",children:[t("label",{htmlFor:c,className:"text-[0.7rem] text-gray-600 dark:text-white/60",children:i("Tell us what went wrong (optional)")}),t("textarea",{id:c,autoFocus:!0,rows:2,maxLength:2e3,value:s,readOnly:n,onChange:e=>l(e.target.value),onKeyDown:e=>{"Escape"===e.key?(e.preventDefault(),e.stopPropagation(),n||o()):"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),u&&a(s))},placeholder:i("What could be improved?"),className:"w-full resize-y rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-transparent px-2 py-1 text-[0.75rem] leading-5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]"}),e("div",{className:"flex justify-end gap-1.5",children:[t("button",{type:"button",onClick:()=>{n||o()},"aria-disabled":n||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:i("Skip")}),t("button",{type:"button",onClick:()=>{u&&a(s)},"aria-disabled":!u||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] "+(u?"hover:opacity-90":"opacity-50 cursor-default"),children:i("Save")})]})]})},Fr=({speaking:e,onToggle:n,t:r})=>{const a=r(e?"Stop reading":"Read aloud");return t(wn,{title:a,children:t("button",{type:"button",onClick:n,"aria-label":a,className:`${Rr} ${e?Wr:Or}`,children:t(e?un:dn,{size:14})})})},Vr=h(({msg:o,isStreaming:i,agentName:s,logoIcon:d,onRelativeLinkClick:u,onDownloadFile:h,resolveAttachmentUrl:p,onDownloadArtifact:m,onRefreshArtifact:g,requestHeaders:f,feedbackMode:w,feedback:x,onRate:v,onSaveComment:y,onSkipComment:k,locale:N,canSpeak:C,isSpeaking:I,onToggleSpeech:S,openableConversationIds:_,onOpenConversation:L,t:M})=>{const[E,D]=r(!1),R="assistant"===o.role,j=!o.content,O=a(null),U=!!x?.commentOpen,W=a(U);l(()=>{const e=W.current&&!U;W.current=U,!e||document.activeElement&&document.activeElement!==document.body||O.current?.focus()},[U]);const H=(n,r)=>{const a=p&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&zr.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&zr.has(e.filename.slice(n+1).toLowerCase())}(n)?p(n):void 0;if(a)return t(rr,{src:a,alt:n.filename,requestHeaders:f,maxHeightClass:"max-h-[200px]",t:M},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:()=>h?.(n),title:M("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(zt,{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(Mt,{size:15})})]},r)},P=(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(zt,{size:14}),n]},r),q=(e,n)=>t(Zn,{artifact:e,t:M,onDownload:m,onRefresh:g},n),B=o.toolNames&&o.toolNames.length>0||!!(o.reasoning??"").trim()||o.toolCallTrace&&o.toolCallTrace.length>0||o.transferChain&&o.transferChain.length>0||o.isTruncated,F=R&&!j&&!i,V=function(e){if(!e)return e;const t=e.replace(A,"").replace(T,"");return t===e?e:t.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}(o.content),G=c(()=>F&&C?function(e){const t=[];for(const n of $(e))"text"===n.type&&n.value.trim()&&t.push(b(n.value));return t}(o.content):null,[F,C,o.content]),K=(J=x,Z=o.feedback,J?{value:J.value,locked:!1}:Z?{value:(Y=Z.rating,"positive"===Y?"up":"down"),locked:!0}:{value:null,locked:!1});var J,Z,Y;const X=$n(o);return e("div",{className:"group/msg flex flex-col "+(R?"items-start":"items-end"),children:[R&&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:d})}),t("span",{className:"font-semibold text-xs text-gray-900 dark:text-white",children:o.agentName??s})]}),!R&&((o.files?.length??0)>0||(o.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(o.files??[]).forEach((n,r)=>{!(!h||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(H({fileId:n.fileId,filename:n.name,type:$r(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(P(n.name,`file-${r}`))}),(o.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(h?H(n,`att-${n.fileId}-${r}`):P(n.filename,`att-${r}`)))}),e})()}),!R&&(o.conversationRefs?.length??0)>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end max-w-[90%]",children:o.conversationRefs.map((r,a)=>{const o=r.title||(r.key?`@${r.key}`:M("Untitled conversation")),i="inline-flex items-center gap-1 max-w-[240px] px-2 py-0.5 rounded-full border text-[0.7rem]",s=e(n,{children:[t(Kt,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:o})]});return L&&_?.has(r.conversationId)?t(wn,{title:M("Open conversation"),children:t("button",{type:"button",onClick:()=>L(r.conversationId),className:`${i} border-[var(--chat-accent-40)] text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]`,children:s})},`ref-${r.conversationId}-${a}`):t(wn,{title:r.key?`@${r.key}`:"",children:t("span",{className:`${i} border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60`,children:s})},`ref-${r.conversationId}-${a}`)})}),R?e("div",{className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=$(o.content,i),n=new Map((o.attachments??[]).map(e=>[e.fileId,e])),r=new Map((o.artifacts??[]).map(e=>[z(e.kind,e.id),e])),a=new Set,s=new Set,l=[];return e.forEach((e,o)=>{if("text"===e.type)e.value.trim()&&l.push(t("div",{className:"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7",children:t(Ir,{content:e.value,streaming:i,onRelativeLinkClick:u,requestHeaders:f,t:M})},`t-${o}`));else if("artifact"===e.type){const t=z(e.kind,e.id),n=r.get(t);n&&!s.has(t)&&(s.add(t),l.push(q(n,`a-${t}-${o}`)))}else if(h){const t=n.get(e.fileId);t&&(a.add(e.fileId),l.push(H(t,`f-${e.fileId}-${o}`)))}}),(o.artifacts??[]).forEach(e=>{const t=z(e.kind,e.id);s.has(t)||(s.add(t),l.push(q(e,`orphan-a-${t}`)))}),h&&(o.attachments??[]).forEach(e=>{a.has(e.fileId)||l.push(H(e,`orphan-${e.fileId}`))}),0!==l.length||i||l.push(t("span",{className:"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic",children:"..."},"empty")),l})(),!j&&i&&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:o.content}),!R&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 text-gray-400 dark:text-white/40",children:[!!o.content.trim()&&t(Pr,{text:o.content,label:M("Copy message"),t:M}),!o.timestampUnknown&&t(Hr,{timestamp:o.timestamp,locale:N})]}),F&&e("div",{className:"mt-0.5 flex flex-wrap items-center gap-0.5 text-gray-400 dark:text-white/40",children:[!o.timestampUnknown&&t(Hr,{timestamp:o.timestamp,locale:N}),B&&t(wn,{title:o.isTruncated?M("Reasoning details — turn limit reached"):M("Reasoning details"),children:t("button",{type:"button",onClick:()=>D(e=>!e),className:`${Rr} ${o.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":Ur}`,"aria-label":o.isTruncated?M("Reasoning details — turn limit reached"):M("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":E,children:o.isTruncated?t(xt,{size:14}):t(Ft,{size:14})})}),t(Pr,{text:V,label:M("Copy response"),t:M}),w&&t(qr,{value:K.value,locked:K.locked,pending:!!x?.pending,onChange:e=>v(o,e,x),downRef:O,t:M}),G&&(Q=G,Q.some(e=>/[\p{L}\p{N}]/u.test(e.replace(On,""))))&&t(Fr,{speaking:I,onToggle:()=>S(X,G),t:M})]}),F&&x?.commentOpen&&t(Br,{pending:x.pending,onSave:e=>y(o,e,x),onSkip:()=>k(o,x),t:M}),F&&x?.error&&t("p",{role:"alert",className:"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400",children:x.error}),E&&t(Ar,{msg:o,onClose:()=>D(!1),t:M})]});var Q});Vr.displayName="MessageRow";const Gr=({messages:n,isLoading:d,agentStatus:u,agentName:h,logoIcon:p,onRelativeLinkClick:m,onDownloadFile:g,resolveAttachmentUrl:f,onDownloadArtifact:w,onRefreshArtifact:x,requestHeaders:v,miniGameEnabled:y=!0,onPlayWaitingGame:b,waitingGameUrl:k,onMessageFeedback:N,isResumingAfterDecision:C,pendingApprovals:I,onSubmitApprovalDecisions:S,isSubmittingApproval:_,approvalError:L,feedbackUrl:A,conversationId:T,locale:M,openableConversationIds:E,onOpenConversation:$,t:z})=>{const D=a(null),[U,H]=r(150),{entries:P,rate:q,saveComment:B,skipComment:F}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:o,t:l}){const[c,d]=r(()=>({scope:t,entries:{}}));let u=c.entries;c.scope!==t&&(u={},d({scope:t,entries:u}));const h=a({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:o,t:l});s(()=>{h.current={feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:o,t:l}});const p=a(0),m=i((e,t)=>d(n=>({...n,entries:{...n.entries,[e]:t}})),[]),g=i((e,t,n)=>d(r=>{const a=r.entries[e];return a&&a.seq===t?{...r,entries:{...r.entries,[e]:n(a)}}:r}),[]);return{entries:u,rate:i(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,onMessageFeedback:i,t:s}=h.current,l=$n(e),c=++p.current;if(!r)return m(l,{seq:c,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void i?.(l,t,e);if(a&&e.serverId){if(m(l,{seq:c,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await W(fetch,r,a,e.serverId,t?{rating:R(t),comment:null}:null,o)){const e=s(t?"Could not submit feedback.":"Could not retract feedback.");return void g(l,c,()=>n?{...n,seq:c,pending:!1,commentOpen:!1,error:e}:{seq:c,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}g(l,c,e=>({...e,pending:!1,commentOpen:"down"===t})),h.current.onMessageFeedback?.(l,t,e)}},[m,g]),saveComment:i(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,t:i}=h.current,s=$n(e),l=O(t);if(!(r&&a&&e.serverId&&l))return void m(s,{...n,commentOpen:!1,error:null});const c=++p.current;m(s,{...n,seq:c,pending:!0,error:null});const d=await W(fetch,r,a,e.serverId,{rating:"negative",comment:l},o);g(s,c,e=>d?{...e,comment:l,pending:!1,commentOpen:!1}:{...e,pending:!1,error:i("Could not submit feedback.")})},[m,g]),skipComment:i((e,t)=>m($n(e),{...t,commentOpen:!1,error:null}),[m])}}({feedbackUrl:A,conversationId:T,requestHeaders:v,onMessageFeedback:N,t:z}),V=Wn(M),[G]=r(()=>function(e,t=Bn){let n=!0,r=0,a=null;const o=e=>{e.scrollTo({top:e.scrollHeight,behavior:"instant"}),r=e.scrollTop},i=()=>{a&&(t.clear(a.timer),a=null)},s=()=>{i();const t=e();t&&n&&o(t)};return{get following(){return n},reveal:()=>{const o=e();if(!o)return;n=!0,i();const l=Math.max(0,o.scrollHeight-o.clientHeight);o.scrollTo({top:o.scrollHeight,behavior:"smooth"}),r=o.scrollTop,r>=l-1||(a={target:l,timer:t.set(s,1e3)})},keepUp:()=>{const t=e();t&&n&&!a&&o(t)},onScroll:()=>{const t=e();if(!t)return;const o=t.scrollTop,i=o<r-1,l=o>r+1;(i||l)&&(r=o);const c=t.scrollHeight-o-t.clientHeight;i?n=c<=1:l&&c<=100&&(n=!0),a&&(i||o>=a.target-1||c<=1)&&s()},leave:()=>{const t=e();!t||t.scrollTop<=0||(n=!1,i())}}}(()=>D.current)),K=a(null),J=(e,t)=>{t instanceof Element&&e.contains(t)&&(function(e,t,n,r){for(let a=e;a&&a!==t;a=n(a))if(a.scrollTop>0&&a.scrollHeight>a.clientHeight&&Gn.has(r(a)))return!0;return!1}(t,e,Tr,Mr)||G.leave())},Z=n[0]?.id;o(()=>{H(150)},[Z]);let Y=0;for(const e of n)"user"===e.role&&(Y+=1);const X=a(null);l(()=>{const e=X.current;X.current={firstMessageId:Z,userMessageCount:Y},!e||e.firstMessageId!==Z||Y>e.userMessageCount?G.reveal():G.keepUp()},[n,Z,Y,G]);const Q=u?.thinkingContent?.length??0;l(()=>{Q&&G.keepUp()},[Q,G]);const ee=n.length>U,te=c(()=>ee?n.slice(n.length-U):n,[n,U,ee]),{speakingId:ne,stop:re}=V,ae=null===ne||n.some(e=>$n(e)===ne),oe=a({conversationId:T,userMessageCount:Y});o(()=>{const e=oe.current;oe.current={conversationId:T,userMessageCount:Y},(e.conversationId!==T||Y>e.userMessageCount||!ae)&&re()},[T,Y,ae,re]);let ie=null;if(d)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){ie=n[e].id;break}const se=!!I?.length&&!!S;return e("div",{ref:D,role:"region","aria-label":z("Conversation transcript"),tabIndex:0,onScroll:G.onScroll,onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&J(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(Fn.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&Er(e.target)||J(e.currentTarget,e.target))},onPointerDown:e=>{const t=e.currentTarget,n=t.getBoundingClientRect();(function(e){if(1===e.button)return!e.onControl;if(0!==e.button||!e.onContainer||e.x<e.clientWidth)return!1;const t=(e.scrollTop+e.clientHeight)/e.scrollHeight*e.clientHeight;return e.y<=t})({button:e.button,onContainer:e.target===t,onControl:Er(e.target),x:e.clientX-n.left-t.clientLeft,y:e.clientY-n.top-t.clientTop,clientWidth:t.clientWidth,clientHeight:t.clientHeight,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight})&&J(t,e.target)},onTouchStart:e=>{K.current=Vn(e.touches)},onTouchMove:e=>{const t=Vn(e.touches),n=K.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&J(e.currentTarget,e.target),K.current=function(e,t){return null===t?null:null===e?t:Math.min(e,t)}(n,t)},className:"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]",children:[ee&&t("div",{className:"flex justify-center",children:e("button",{type:"button",onClick:()=>H(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(It,{size:13,className:"rotate-180"}),z("Load earlier messages")]})}),te.map(e=>{const n=e.id===ie;return"assistant"===e.role&&!e.content&&n?se?null:t("div",{children:t(pr,{agentStatus:u,logoIcon:p,t:z,miniGameEnabled:y,onPlayWaitingGame:b,waitingGameUrl:k,keepEndInView:G.keepUp})},e.id):t(Vr,{msg:e,isStreaming:n,agentName:h,logoIcon:p,onRelativeLinkClick:m,onDownloadFile:g,resolveAttachmentUrl:f,onDownloadArtifact:w,onRefreshArtifact:x,requestHeaders:v,feedbackMode:"assistant"===e.role?j(e.serverId,A,T,!!N):null,feedback:P[$n(e)],onRate:q,onSaveComment:B,onSkipComment:F,locale:M,canSpeak:V.supported,isSpeaking:ne===$n(e),onToggleSpeech:V.toggle,openableConversationIds:e.conversationRefs?.length?E:void 0,onOpenConversation:e.conversationRefs?.length?$:void 0,t:z},e.id)}),C&&!se&&t(pr,{agentStatus:u,logoIcon:p,t:z,miniGameEnabled:y,onPlayWaitingGame:b,waitingGameUrl:k,keepEndInView:G.keepUp}),se&&t(tr,{proposals:I,onSubmit:S,isSubmitting:_,error:L,t:z},I.map(e=>e.toolCallId).join("|")),t("div",{})]})},Kr=({firstName:r,agentName:a,t:o})=>{if(!a)return t(n,{children:I(o,"How can I help you, {name}?",{name:r})});const{before:i,after:s,hasSlot:l}=function(e,t,n,r={}){const a=I(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]})},Jr=({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(Kr,{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))]})]}),Zr="application/x-filigran-conversation",Yr="filigran-chat-collapsed-workspaces";function Xr(){try{const e=JSON.parse(localStorage.getItem(Yr)??"[]");return new Set(Array.isArray(e)?e.filter(e=>"string"==typeof e):[])}catch{return new Set}}const Qr="p-1 rounded-md text-gray-400 dark:text-white/30 hover:bg-gray-200/60 dark:hover:bg-white/10 transition-colors disabled:opacity-40 disabled:pointer-events-none",ea="text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40",ta=({conversations:i,loading:s,activeConversationId:l,collapsed:d,onToggleCollapsed:u,onSelect:h,onDelete:p,onRename:m,onNewChat:g,workspaces:f,t:w})=>{const[x,v]=r(""),[y,b]=r(null),[k,N]=r(""),C=a(!1),[I,S]=r(Xr),[_,L]=r(!1),[A,T]=r(null);o(()=>{if(!A)return;const e=setTimeout(()=>T(null),6e3);return()=>clearTimeout(e)},[A]);const M=(e,t)=>{C.current=!1,b(e),N(t)},E=()=>{if(C.current)return;C.current=!0;const e=y,t=k.trim();b(null),e&&t&&m?.(e,t)},$=()=>{C.current=!0,b(null)},z=(e,t)=>T(e||w(t)),D=async(e,t)=>{if(!f||function(e,t,n){const r=e.find(e=>e.conversationId===t);return!!r&&(r.workspaceId??null)===n}(i,e,t))return;const n=await f.onMove(e,t);null!==n&&z(n,"The conversation could not be moved")},R=x.trim().toLowerCase(),j=c(()=>R?e=>(e.title||"").toLowerCase().includes(R):void 0,[R]),O=c(()=>j?i.filter(j):i,[i,j]),U=c(()=>f?function(e,t,n={}){const{matches:r}=n,a=r?e.filter(r):e,o=new Set(t.map(e=>e.id)),i=new Set(e.map(e=>e.workspaceId).filter(e=>!!e)),s=new Map,l=[],c=[];for(const e of a){const t=e.workspaceId??null;t?o.has(t)?s.set(t,[...s.get(t)??[],e]):l.push(e):c.push(e)}const d=[];for(const e of Q(t)){const t=s.get(e.id)??[];(e.canManage||i.has(e.id))&&(r&&0===t.length||d.push({workspace:e,key:e.id,conversations:t}))}return l.length>0&&d.push({workspace:null,key:"__elsewhere__",conversations:l}),{groups:d,unfiled:c}}(i,f.list,{matches:j}):null,[i,f,j]),W=f?function(e){return Q(e.filter(e=>e.canManage))}(f.list):[],H=U?function(e){const{total:t,unfiled:n,loading:r,searching:a}=e;return n>0||r||a?null:0===t?"none":"all-filed"}({total:i.length,unfiled:U.unfiled.length,loading:s,searching:!!R}):null;if(d)return e("div",{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(wn,{title:w("Show conversations"),children:t("button",{type:"button",onClick:u,"aria-label":w("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(en,{size:17})})}),t(wn,{title:w("New conversation"),children:t("button",{type:"button",onClick:()=>g(),"aria-label":w("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(Et,{size:17})})})]});const P=e=>t(oa,{conversation:e,isActive:e.conversationId===l,isEditing:e.conversationId===y,draftTitle:k,onDraftTitleChange:N,onCommitRename:E,onCancelRename:$,onStartRename:m?M:void 0,onSelect:h,onDelete:p,fileable:f?W:void 0,onMove:D,t:w},e.conversationId);return e("div",{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(Et,{size:15}),w("New conversation")]}),t(wn,{title:w("Hide conversations"),children:t("button",{type:"button",onClick:u,"aria-label":w("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(en,{size:17})})})]}),i.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Xt,{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:x,onChange:e=>v(e.target.value),onKeyDown:e=>{"Escape"===e.key&&v("")},placeholder:w("Search conversations..."),"aria-label":w("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:[s&&0===i.length&&t("div",{className:"px-3 py-2",children:t(gn,{size:16})}),e(n,U&&f?{children:[!R&&e("div",{className:"flex items-center justify-between px-2 pb-1 pt-1",children:[t("span",{className:ea,children:w("Workspaces")}),t(wn,{title:w("New workspace"),children:t("button",{type:"button",onClick:()=>L(!0),"aria-label":w("New workspace"),className:Qr,children:t(Ot,{size:14})})})]}),_&&t(ra,{placeholder:w("Workspace name"),onSubmit:async e=>{if(L(!1),!e)return;const t=await f.onCreate(e);t.ok||z(t.error,"The workspace could not be created")},onCancel:()=>L(!1)}),U.groups.map(e=>t(aa,{workspace:e.workspace,count:e.conversations.length,open:ee(e.key,I,e,l,!!R),toggleable:te(e,l,!!R),pending:!!e.workspace&&f.pendingWorkspaceId===e.workspace.id&&!l,onToggle:()=>{return t=e.key,void S(e=>{const n=new Set(e);n.has(t)?n.delete(t):n.add(t);try{localStorage.setItem(Yr,JSON.stringify([...n]))}catch{}return n});var t},onNewChat:f.onNewChat,onRename:async(e,t)=>{const n=await f.onRename(e,t);n.ok||z(n.error,"The workspace could not be renamed")},onDelete:async e=>{const t=await f.onDelete(e);t.ok||z(t.error,"The workspace could not be deleted")},onDropConversation:t=>e.workspace&&void D(t,e.workspace.id),t:w,children:e.conversations.length>0?e.conversations.map(P):t("p",{className:"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30",children:w("Drop a conversation here, or start one with +.")})},e.key)),e(na,{onDropConversation:e=>{D(e,null)},accepts:!0,children:[e("div",{className:"flex items-center justify-between px-2 pb-1 pt-3",children:[t("span",{className:ea,children:w("Not in a workspace")}),t("span",{className:"text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30",children:U.unfiled.length})]}),U.unfiled.map(P),H&&t("p",{className:"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30",children:w("none"===H?"No conversations yet":"Every conversation is in a workspace.")})]}),R&&0===U.groups.length&&0===U.unfiled.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:w("No conversation matches")})]}:{children:[!s&&0===i.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:w("No conversations yet")}),i.length>0&&0===O.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:w("No conversation matches")}),O.map(P)]})]}),A&&t("p",{role:"alert",className:"mx-3 mb-3 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[0.7rem] text-red-600 dark:text-red-400",children:A})]})},na=({onDropConversation:e,accepts:n,children:o,className:i=""})=>{const[s,l]=r(!1),c=a(0),d=e=>e.dataTransfer.types.includes(Zr);return t("div",{className:`rounded-lg transition-colors ${s?"bg-[var(--chat-accent)]/10 ring-1 ring-[var(--chat-accent)]/40":""} ${i}`,...n?{onDragEnter:e=>{d(e)&&(c.current+=1,l(!0))},onDragOver:e=>{d(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},onDragLeave:e=>{d(e)&&(c.current=Math.max(0,c.current-1),0===c.current&&l(!1))},onDrop:t=>{if(!d(t))return;t.preventDefault(),c.current=0,l(!1);const n=t.dataTransfer.getData(Zr);n&&e(n)}}:{},children:o})},ra=({initial:e="",placeholder:n,onSubmit:i,onCancel:s})=>{const[l,c]=r(e),d=a(!1),u=a(null);o(()=>{u.current?.focus(),u.current?.select()},[]);const h=()=>{d.current||(d.current=!0,i(l.trim()))};return t("input",{ref:u,value:l,maxLength:200,onChange:e=>c(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&h(),"Escape"===e.key&&(d.current=!0,s())},onBlur:h,placeholder:n,"aria-label":n,className:"mx-2 mb-1 w-[calc(100%-1rem)] rounded-md bg-white dark:bg-white/10 px-2 py-1 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]"})},aa=({workspace:a,count:o,open:i,toggleable:s,pending:l,onToggle:c,onNewChat:d,onRename:u,onDelete:h,onDropConversation:p,t:m,children:g})=>{const[f,w]=r(!1),[x,v]=r(!1),y=!!a?.canManage,b=!!a&&a.isDefault&&a.isOwn;return e(na,{onDropConversation:p,accepts:y,className:"mb-0.5",children:[e("div",{className:"group/ws flex items-center gap-1 rounded-lg px-1.5 py-1 hover:bg-gray-100 dark:hover:bg-white/[0.06]",children:[f&&a?t(ra,{initial:a.name,placeholder:m("Workspace name"),onSubmit:e=>{w(!1),e&&e!==a.name&&u(a.id,e)},onCancel:()=>w(!1)}):e("button",{type:"button",onClick:c,disabled:!s,"aria-expanded":i,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left disabled:cursor-default",children:[t(St,{size:12,className:"shrink-0 text-gray-400 dark:text-white/30 transition-transform "+(i?"rotate-90":"")}),t(Rt,{size:14,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate text-[0.8125rem] font-medium text-gray-800 dark:text-white/80",children:a?a.name:m("Other workspaces")}),b&&t("span",{className:"shrink-0 rounded bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] text-[var(--chat-accent)]",children:m("default")}),t("span",{className:"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30",children:o})]}),a&&y&&!f&&t("span",{className:"flex shrink-0 items-center opacity-0 group-hover/ws:opacity-100 focus-within:opacity-100 transition-opacity",children:e(n,x?{children:[t("span",{className:"px-1 text-[0.65rem] text-red-600 dark:text-red-400",children:m("Delete?")}),t("button",{type:"button",onClick:()=>{v(!1),h(a.id)},"aria-label":m("Delete workspace"),className:`${Qr} hover:text-red-500`,children:t(Ct,{size:13})}),t("button",{type:"button",onClick:()=>v(!1),"aria-label":m("Cancel"),className:Qr,children:t(_t,{size:13})})]}:{children:[t(wn,{title:m("New conversation in this workspace"),children:t("button",{type:"button",onClick:()=>d(a.id),"aria-label":m("New conversation in this workspace"),className:Qr,children:t(Et,{size:13})})}),t(wn,{title:m("Rename workspace"),children:t("button",{type:"button",onClick:()=>w(!0),"aria-label":m("Rename workspace"),className:Qr,children:t(Yt,{size:13})})}),!a.isDefault&&t(wn,{title:m("Delete workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":m("Delete workspace"),className:`${Qr} hover:text-red-500`,children:t(sn,{size:13})})})]})})]}),i&&e("div",{className:"space-y-0.5 pb-1 pl-3",children:[l&&e("div",{className:"flex items-center gap-2 rounded-lg bg-[var(--chat-accent)]/10 px-2.5 py-1.5 text-[0.75rem] text-[var(--chat-accent)]",children:[t(Et,{size:12}),m("New conversation — send a message to start it")]}),g]})]})},oa=({conversation:o,isActive:i,isEditing:s,draftTitle:l,onDraftTitleChange:c,onCommitRename:d,onCancelRename:u,onStartRename:h,onSelect:p,onDelete:m,fileable:g,onMove:f,t:w})=>{const[x,v]=r(!1),y=a(null),b=!!g&&!s;return e("div",{role:"button",tabIndex:0,"aria-current":i,draggable:b,onDragStart:b?e=>{e.dataTransfer.setData(Zr,o.conversationId),e.dataTransfer.effectAllowed="move"}:void 0,onClick:()=>p(o.conversationId),onKeyDown:e=>{e.target===e.currentTarget&&("Enter"!==e.key&&" "!==e.key||(e.preventDefault(),p(o.conversationId)))},className:"group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors "+(i?"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 "+(i?"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(bt,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[s?t("input",{autoFocus:!0,value:l,onChange:e=>c(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&d(),"Escape"===e.key&&u()},onBlur:d,"aria-label":w("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] "+(i?"text-gray-900 dark:text-white":"text-gray-700 dark:text-white/70"),children:o.title||w("Untitled conversation")}),(o.agentName||o.updatedAt)&&!s&&e("span",{className:"block text-[0.65rem] text-gray-400 dark:text-white/30 truncate",children:[o.agentName,o.agentName&&o.updatedAt?" · ":"",o.updatedAt?L(o.updatedAt,w):""]})]}),!s&&e("span",{className:"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[b&&e(n,{children:[t("button",{ref:y,type:"button",onClick:e=>{e.stopPropagation(),v(e=>!e)},"aria-label":w("Move to workspace"),title:w("Move to workspace"),"aria-expanded":x,className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(jt,{size:13})}),t(mn,{open:x,onClose:()=>v(!1),anchorRef:y,placement:"bottom-end",width:220,children:e("div",{className:"py-1",onClick:e=>e.stopPropagation(),children:[t("p",{className:"px-3 pb-1 pt-1.5 text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40",children:w("Move to workspace")}),g.map(n=>e("button",{type:"button",disabled:n.id===o.workspaceId,onClick:()=>{v(!1),f(o.conversationId,n.id)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] text-gray-700 dark:text-white/80 hover:bg-gray-100 dark:hover:bg-white/10 disabled:opacity-40",children:[t(Rt,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===o.workspaceId&&t(Ct,{size:12,className:"ml-auto shrink-0"})]},n.id)),t("div",{className:"my-1 h-px bg-gray-200 dark:bg-white/10"}),e("button",{type:"button",disabled:!o.workspaceId,onClick:()=>{v(!1),f(o.conversationId,null)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] text-gray-700 dark:text-white/80 hover:bg-gray-100 dark:hover:bg-white/10 disabled:opacity-40",children:[t(_t,{size:13,className:"shrink-0"}),w("Remove from workspace")]})]})})]}),h&&t("button",{type:"button",onClick:e=>{e.stopPropagation(),h(o.conversationId,o.title||"")},"aria-label":w("Rename conversation"),title:w("Rename conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(Et,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),m(o.conversationId)},"aria-label":w("Delete conversation"),title:w("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(sn,{size:13})})]})]})},ia=({mode:n,onClose:s,onModeChange:l,topOffset:d=0,apiBaseUrl:u,apiEndpoints:h,agentDashboardUrl:p,user:m,t:g=C,accentColor:f="#7b5cff",logoIcon:w,promptSuggestions:x,draftBorderColor:v,resizable:b=!1,onWidthChange:k,onResizeStart:N,onResizeEnd:I,disableFileManagement:S=!1,onRelativeLinkClick:_,onDownloadError:L,maxFileCount:A,maxTotalSize:T,requestHeaders:M,pageContext:E,pushContentSelector:$,backendType:z="rest",miniGameEnabled:D=!0,onPlayWaitingGame:R,notifyOnComplete:j=!0,onTaskComplete:O,onMessageFeedback:W,locale:H,disableImagePreviews:P=!1,contextUsageEnabled:q=!0,composerToolbar:B})=>{const F=ft(h),V=ft(M),K=ft(E),J=ft(x),Z=wt(_),Y=wt(L),Q=wt(R),ee=wt(O),te=wt(W),[re,ie]=r(!1),{agents:se,agentsLoading:pe,agentsError:me,selectedAgent:fe,agentMenuOpen:we,setAgentMenuOpen:xe,handleSwitchAgent:ve}=ot({apiBaseUrl:u,apiEndpoints:F,backendType:z,requestHeaders:V}),{messages:ye,inputValue:be,setInputValue:ke,isLoading:Ne,agentStatus:Ce,attachedFiles:Ie,conversationId:Se,contextUsage:_e,transferredAgent:Le,canSteer:Ae,pendingApprovals:Te,isSubmittingApproval:Me,approvalError:Ee,submitApprovalDecisions:$e,isResumingAfterDecision:ze,historyReloadNonce:De,historyLoadedRef:Re,conversationIdRef:je,handleFileAdd:Oe,handlePaste:Ue,handleSendMessage:We,handleNewChat:He,pendingWorkspaceId:Pe,clearPendingWorkspace:qe,handleStopGenerating:Be,conversationRefs:Fe,addConversationRef:Ve,setAttachedFiles:Ge,setMessages:Ke,setContextUsage:Je,updateConversationId:Ze,handleSwitchConversation:Ye}=rt({apiBaseUrl:u,apiEndpoints:F,backendType:z,agentSlug:fe?.slug,requestHeaders:V,pageContext:K,onRelativeLinkClick:_?Z:void 0,t:g,maxFileCount:A,maxTotalSize:T}),{suggestions:Xe,loading:Qe}=gt({apiBaseUrl:u,apiEndpoints:F,backendType:z,requestHeaders:V,agentSlug:fe?.slug}),et=c(()=>(Xe??J)?.map(e=>g(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")])(g),[Xe,J,g]),{prompts:tt,quota:nt,refreshQuota:at}=mt({apiBaseUrl:u,apiEndpoints:F,backendType:z,requestHeaders:V}),{historyEnabled:ct,conversations:dt,conversationsLoading:ut,refreshConversations:ht,deleteConversation:xt,renameConversation:vt,moveConversation:yt}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:a}){const[o,s]=r([]),[l,c]=r(!1),d="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,u=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,h=i(async()=>{if(d){c(!0);try{const e=await fetch(u,{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(it).filter(e=>null!==e))}catch{s([])}finally{c(!1)}}},[d,u,a]),p=i(async e=>{if(!d)return!1;try{return!!(await fetch(`${u}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...a??{}}})).ok&&(s(t=>t.filter(t=>t.conversationId!==e)),!0)}catch{return!1}},[d,u,a]),m=i(async(e,t)=>{const n=t.trim();if(!d||!n)return!1;const r=o;s(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{return!!(await fetch(`${u}/${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,u,a,o]),g=i(async(e,t)=>{if(!d)return"";const n=o.find(t=>t.conversationId===e)?.workspaceId,r=()=>s(r=>function(e,t,n,r){const a=e.findIndex(e=>e.conversationId===t);if(a<0||(e[a].workspaceId??null)!==n)return e;const o=[...e];return o[a]={...e[a],workspaceId:r},o}(r,e,t,n));s(n=>n.map(n=>n.conversationId===e?{...n,workspaceId:t}:n));try{const n=await fetch(`${u}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...a??{}},body:JSON.stringify({workspace_id:t})});return n.ok?null:(r(),await ne(n)??"")}catch{return r(),""}},[d,u,a,o]);return{historyEnabled:d,conversations:o,conversationsLoading:l,refreshConversations:h,deleteConversation:p,renameConversation:m,moveConversation:g}}({apiBaseUrl:u,apiEndpoints:F,backendType:z,requestHeaders:V}),{workspacesEnabled:bt,workspaces:kt,refreshWorkspaces:Nt,createWorkspace:Ct,renameWorkspace:It,deleteWorkspace:St}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:o}){const[s,l]=r([]),[c,d]=r(!1),u=a(0),h=t?.workspaces,p="rest"===n&&!t?.singleEndpoint&&"string"==typeof h&&h.length>0,m=p?`${e}${h}`:null,g=i(async()=>{if(!m)return;const e=++u.current;try{const n=await fetch(m,{method:"GET",headers:{...o??{}}});if(e!==u.current)return;if(!n.ok)return void(408===(t=n.status)||429===t||t>=500&&501!==t||(d(!1),l([])));const r=X(await n.json());if(e!==u.current)return;l(r),d(!0)}catch{}var t},[m,o]),f=i(async(e,t,n)=>{try{const r=await fetch(t,{method:e,headers:{...n?{"Content-Type":"application/json"}:{},...o??{}},...n?{body:JSON.stringify(n)}:{}});if(!r.ok)return{ok:!1,error:await ne(r)};const a=204===r.status?[]:X([await r.json().catch(()=>null)]);return await g(),{ok:!0,workspace:a[0]}}catch{return{ok:!1,error:null}}},[o,g]),w=i(async e=>m?f("POST",m,{name:e.trim()}):{ok:!1,error:null},[m,f]),x=i(async(e,t)=>m?f("PATCH",`${m}/${encodeURIComponent(e)}`,{name:t.trim()}):{ok:!1,error:null},[m,f]),v=i(async e=>m?f("DELETE",`${m}/${encodeURIComponent(e)}`):{ok:!1,error:null},[m,f]);return{workspacesEnabled:p&&c,workspaces:s,refreshWorkspaces:g,createWorkspace:w,renameWorkspace:x,deleteWorkspace:v}}({apiBaseUrl:u,apiEndpoints:F,backendType:z,requestHeaders:V});o(()=>{bt&&Pe&&!function(e,t){return t.some(t=>t.id===e&&t.canManage)}(Pe,kt)&&qe(Pe)},[bt,kt,Pe,qe]);const[_t,Lt]=r(!1),[At,Mt]=r(!1),Et="fullscreen"===n&&ct;o(()=>{Et&&ht()},[Et,Se,ht]),o(()=>{Et&&Nt()},[Et,Se,Nt]);const $t=a(null);o(()=>{if(!Et)return;const e=()=>{if("visible"!==document.visibilityState)return;const e=Date.now();(function(e,t){return null===t||e-t>=2e3})(e,$t.current)&&($t.current=e,ht(),Nt())};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[Et,ht,Nt]);const zt=a(!1);o(()=>{zt.current&&!Ne&&(at(),Et&&(ht(),Nt())),zt.current=Ne},[Ne,at,Et,ht,Nt]);const Dt=e=>{Lt(!1),Ye(e)},Rt=G(u,F,z),jt=c(()=>new Set(dt.map(e=>e.conversationId)),[dt]),Ot=wt(ct?Dt:void 0),Ut=ye.some(e=>(e.conversationRefs?.length??0)>0);o(()=>{Ut&&ct&&ht()},[Ut,ct,ht,Se]);const Wt=async e=>{await xt(e)&&e===je.current&&He()},{sidebarWidth:Ht,handleResizeStart:Pt,defaultWidth:qt,isResizing:Bt}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:i,onResizeEnd:s}){const[l,c]=r(()=>{if("undefined"==typeof window)return st;const e=localStorage.getItem(lt);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=st)return t}return st}),[d,u]=r(!1),h=a(!1),p=a(l);p.current=l;const m=a(n);m.current=n;const g=a(s);return g.current=s,o(()=>{"sidebar"===e&&t&&m.current?.(p.current)},[e,t]),o(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!h.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,st),n);c(r),p.current=r,m.current?.(r)},r=()=>{h.current&&(h.current=!1,u(!1),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem(lt,String(p.current)),g.current?.())},a=()=>{const e=.4*window.innerWidth;if(p.current>e){const t=Math.max(e,st);c(t),p.current=t,m.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(),h.current=!0,u(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",i?.()},defaultWidth:st,isResizing:d}}({mode:n,resizable:b,onWidthChange:k,onResizeStart:N,onResizeEnd:I});o(()=>{const e="sidebar"===n?b?Ht:qt:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",Bt?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),$){const e=document.querySelector($);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=Bt?"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")}},[$,n,Ht,qt,b,Bt]);const Ft=c(()=>w??t(Tt,{size:24}),[w]),Vt=c(()=>function(e){const t=e?.trim().replace(/\/+$/,"");return t&&/^https?:\/\//i.test(t)?`${t}/chat?arcade=play`:null}(p),[p]),Gt=m.firstName,[Kt,Jt]=r(null),Zt=Le?.name||Kt||fe?.name||g("Assistant"),Yt=i(()=>{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)},[]);pt({isLoading:Ne,agentName:Zt,t:g,enabled:j,onComplete:ee,isViewingChat:Yt});const Xt=null!=F?.download,Qt="rest"===z&&null!==F?.download&&(!F?.singleEndpoint||Xt),en=i(e=>`${u}${F?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[u,F]),tn=i(async e=>{const t=en(e);try{const n=await fetch(t,{method:"GET",credentials:"include",headers:{...V??{}}});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){Y?.(t,e)}},[en,V,Y]),nn="rest"===z&&F?.artifacts?`${u}${F.artifacts}`:null,rn=i((e,t)=>`${nn}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,[nn]),an=i(async(e,t)=>{const n=`${e.title||e.kind}.${function(e){return"pptx_native"===e?"pptx":e}(t)}`;try{const r=await fetch(`${rn(e.kind,e.id)}/download`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...V??{}},body:JSON.stringify({format:t})});if(!r.ok)throw new Error(`Download failed: ${r.status}`);const a=await r.blob(),o=URL.createObjectURL(a),i=document.createElement("a");i.href=o,i.download=function(e){if(!e)return;const t=/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(e);if(t)try{return decodeURIComponent(t[1].trim().replace(/^"|"$/g,""))||void 0}catch{}const n=/filename\s*=\s*("([^"]*)"|[^;]+)/.exec(e);return(n?(n[2]??n[1]).trim():"")||void 0}(r.headers.get("content-disposition"))??n,document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(o)}catch(r){Y?.(r,{fileId:e.id,filename:n,type:t.toUpperCase()})}},[rn,V,Y]),on=i(async(e,t)=>{const n=await fetch(rn(e,t),{credentials:"include",headers:{...V??{}}});if(n.ok)return le(await n.json())},[rn,V]),sn={"--chat-accent":f,"--chat-accent-10":y(f,.1),"--chat-accent-40":y(f,.25),"--chat-accent-50":y(f,.5),"--chat-accent-dark":f},ln=a(!0);o(()=>(ln.current=!0,()=>{ln.current=!1}),[]),o(()=>{if(null===F?.sessions||F?.singleEndpoint||"legacy"===z||"ag-ui"===z)return;if(!Se)return void Jt(null);if(Re.current||!fe)return;Re.current=!0;const e=Se,t=()=>!ln.current||je.current!==e;fetch(`${u}${F?.sessions??"/chat/sessions"}`,{method:"POST",headers:{"Content-Type":"application/json",...V??{}},body:JSON.stringify({conversation_id:Se,agent_slug:fe.slug,supports_artifacts:!0})}).then(e=>t()?null:e.ok?e.json():(Ze(null),null)).then(n=>{if(n&&!t()&&("string"==typeof n.conversation_id&&n.conversation_id&&n.conversation_id!==e&&Ze(n.conversation_id),Jt("string"==typeof n.agent_name?n.agent_name:null),n.messages?.length)){Ke(function(e){if(!Array.isArray(e))return[];const t=[];return e.forEach((e,n)=>{if(!e||"object"!=typeof e)return;const r=e;if("user"!==r.role&&"assistant"!==r.role)return;const a="string"==typeof r.created_at?new Date(r.created_at):null,o=a&&!Number.isNaN(a.getTime())?a:null;t.push({id:`restored-${n}`,serverId:"string"==typeof r.id&&r.id?r.id:void 0,role:r.role,content:"string"==typeof r.content?r.content:"",timestamp:o??new Date,timestampUnknown:!o||void 0,feedback:"assistant"===r.role?ge(r.feedback):void 0,agentName:"string"==typeof r.agent_name?r.agent_name:void 0,attachments:oe(r.attachments),artifacts:"assistant"===r.role?ce(r.artifacts):void 0,conversationRefs:"user"===r.role?ue(r.conversation_refs):void 0,toolNames:Array.isArray(r.tool_names)?r.tool_names:void 0,toolCallCount:"number"==typeof r.tool_call_count?r.tool_call_count:void 0,iterations:"number"==typeof r.iterations?r.iterations:void 0,reasoning:"string"==typeof r.reasoning?r.reasoning:void 0,toolCallTrace:de(r.tool_call_trace),transferChain:he(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0})}),t}(n.messages));for(let e=n.messages.length-1;e>=0;e-=1){const t=ae(n.messages[e]);if(t){Je(t);break}}}}).catch(()=>{t()||Ze(null)})},[Se,fe,u,F,z,De,Re,je,ln,V,Ke,Je,Ze]);const cn=(()=>{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}})(),dn={...sn,..."sidebar"===n?{top:d,width:b?Ht:qt}:"floating"===n?{width:380,height:560}:{top:d}};return e("div",{className:cn,style:dn,children:["sidebar"===n&&b&&t("div",{onMouseDown:Pt,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(vn,{mode:n,agentName:Zt,agents:se,agentsLoading:pe,agentsError:me,selectedAgent:fe,transferredFrom:Le?fe?.name:void 0,agentMenuOpen:we,onAgentMenuToggle:()=>xe(e=>!e),onAgentMenuClose:()=>xe(!1),onSwitchAgent:e=>{e&&ve(e,()=>{He()})},modeMenuOpen:re,onModeMenuToggle:()=>ie(e=>!e),onModeMenuClose:()=>ie(!1),onModeChange:l,onNewChat:He,onClose:s,logoIcon:Ft,agentDashboardUrl:p,historyEnabled:ct&&!Et,historyMenuOpen:_t,onHistoryMenuToggle:()=>{const e=!_t;e&&ht(),Lt(e)},onHistoryMenuClose:()=>Lt(!1),conversations:dt,conversationsLoading:ut,activeConversationId:Se,onSelectConversation:Dt,onDeleteConversation:e=>{Wt(e)},t:g}),e("div",{className:Et?"flex flex-1 min-h-0":"contents",children:[Et&&t(ta,{conversations:dt,loading:ut,activeConversationId:Se,collapsed:At,onToggleCollapsed:()=>Mt(e=>!e),onSelect:Dt,onDelete:e=>{Wt(e)},onRename:(e,t)=>{vt(e,t)},onNewChat:He,workspaces:bt?{list:kt,pendingWorkspaceId:Pe,onCreate:Ct,onRename:It,onDelete:async e=>{const t=await St(e);return t.ok&&(qe(e),ht()),t},onMove:yt,onNewChat:e=>{He(e),Nt()}}:void 0,t:g}),e("div",{className:Et?"flex flex-1 flex-col min-w-0":"contents",children:[0===ye.length?t(Jr,{firstName:Gt,logoIcon:Ft,promptSuggestions:et,suggestionsLoading:Qe,agentName:fe?.name,agentDescription:fe?.description,onPromptClick:ke,t:g}):t(Gr,{messages:ye,isLoading:Ne,agentStatus:Ce,agentName:Zt,logoIcon:Ft,onRelativeLinkClick:Z,onDownloadFile:Qt?tn:void 0,resolveAttachmentUrl:Qt&&!P?en:void 0,onDownloadArtifact:nn?an:void 0,onRefreshArtifact:nn?on:void 0,requestHeaders:V,miniGameEnabled:D,onPlayWaitingGame:Q,waitingGameUrl:Vt,onMessageFeedback:te,feedbackUrl:U(u,F,z),conversationId:Se,locale:H,isResumingAfterDecision:ze,pendingApprovals:Te,onSubmitApprovalDecisions:$e,isSubmittingApproval:Me,approvalError:Ee,openableConversationIds:jt,onOpenConversation:Ot,t:g}),t(En,{inputValue:be,onInputChange:ke,onSend:We,onStop:Be,isLoading:Ne,canSteer:Ae,attachedFiles:S?[]:Ie,onFileAdd:S?void 0:Oe,onFileRemove:S?void 0:e=>Ge(t=>t.filter((t,n)=>n!==e)),onPaste:S?void 0:Ue,t:g,mode:n,separatorColor:v,prompts:tt,quota:nt,contextUsage:q?_e:null,composerToolbar:B,conversationReferences:Rt?{url:Rt,requestHeaders:V,conversationId:Se,refs:Fe,onPick:Ve}:void 0})]})]})]})},sa=({isOpen:n,onToggle:r,label:a,accentColor:o="#7b5cff",icon:i,t:s=C})=>{const l=i??t(Tt,{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:y(o,.5),color:o,backgroundColor:n?y(o,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=o,e.currentTarget.style.backgroundColor=y(o,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?o:y(o,.5),e.currentTarget.style.backgroundColor=n?y(o,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:l}),a??s("Ask Assistant")]})};export{ia as ChatPanel,sa as ChatToggleButton};
2
2
  //# sourceMappingURL=index.js.map