@filigran/chatbot 3.13.0 → 3.15.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/CHANGELOG.md +307 -1
- package/README.md +650 -266
- package/dist/index.d.ts +587 -12
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/markdown.d.ts +58 -1
- package/dist/markdown.js +1 -1
- package/dist/markdown.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/workspaces.d.ts +99 -0
- package/dist/workspaces.js +2 -0
- package/dist/workspaces.js.map +1 -0
- package/package.json +7 -2
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 p}from"react";import{createPortal as g}from"react-dom";import m from"remark-gfm";import f from"remark-parse";import{unified as b}from"unified";import x from"react-markdown";import w 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 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,g=h?" ".repeat(p):d.slice(0,p),m=n(d.slice(p)).length,f=n(u);if(m<2||f.length===m)continue;const b=[];for(let e=0;e<m;e++)b.push(f[e]?a(f[e]):"---");t[e+1]=`${g}| ${b.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)));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 _(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function I(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 A=/\[\[FILE:[^\]]+\]\]/g,E=/\[\[FILE(?::[^\]]*)?\]?$/;function T(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(E,"");return o&&t.push({type:"text",value:o}),t}const M=e=>"up"===e?"positive":"negative";function $(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function z(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function j(e,t,n){return"rest"!==n||t?.singleEndpoint||!t?.feedback?null:`${e}${t.feedback}`}async function D(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:z(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 R=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function U(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 R){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 O(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 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.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 W(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 B(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 F(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=U(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=B(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:O(e.attachments),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:H(e.tool_call_trace),transferChain:W(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:U(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0}:{action:"noop"}}function q(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 P(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 V(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 G(e,t){return null!==e&&"function"==typeof t}function K(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const J=(e,t)=>{const n=t??K();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 Y(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const Z=/^(current-password|new-password|one-time-code|cc-)/;function X(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 Q(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 ee(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=J(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(Q(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 te(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 ne(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&&te(r)}async function re(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(ne(e))return{ok:!0};if(r){if(X(e),await(a=()=>ne(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&&!Y(e.target)&&Array.from(e.addedNodes).some(e=>!Y(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,()=>X(e)))return{ok:!0};var a,o;return n?.aborted?{ok:!1,error:"aborted"}:ee(e,void 0,t)}const ae=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function oe(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=J(e.path,K(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const o=t.get(e.ref);return o&&o.isConnected?te(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 re(o,K(r??o.ownerDocument),a):"click"===e.type?ee(o,n,K(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=>Z.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=>ae.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&&Q(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 ie="[truncated]",se=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function le(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(ce(t))return!0;return!1}function ce(e){const t=e.getAttribute("role");if(t&&se.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 de(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function ue(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(ve(r)||xe(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?ue(r):` ${ue(r)} `}return n}function he(e){return(e??"").replace(/\s+/g," ").trim()}const pe=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function ge(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=he(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const a=he(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=he(Array.from(i.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||he(i.textContent))return e||he(i.textContent)}const s=e.tagName.toLowerCase(),l=(e.getAttribute("type")||"").toLowerCase();if("input"===s&&["submit","reset","button"].includes(l)){const t=he(e.getAttribute("value"));if(t)return t;if("button"!==l)return"submit"===l?"Submit":"Reset"}const c=he(e.getAttribute("alt"))||he(e.querySelector("img[alt]")?.getAttribute("alt"));if(c)return c;const d=xe(e)?"":he(ue(e));if(pe.has(t)&&d)return d;const u=he(e.getAttribute("placeholder"));if(u)return u;const h=he(e.getAttribute("title"));return h||d}function me(e){return JSON.stringify(e.slice(0,80))}function fe(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 be=/^(current-password|new-password|one-time-code|cc-)/;function xe(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>be.test(e))}function we(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(xe(e))return null;const n="value"in e?String(e.value??""):he(ue(e));return n||null}function ye(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 ve(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",Ne="filigranChatLegacyChatId",Ce=e=>`filigranChatDraft:${e??"new"}`;function Se(e){if("undefined"==typeof window)return"";try{return sessionStorage.getItem(Ce(e))??""}catch{return""}}function _e(e,t){if("undefined"!=typeof window)try{t?sessionStorage.setItem(Ce(e),t):sessionStorage.removeItem(Ce(e))}catch{}}const Ie=52428800;function Le({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:s,requestHeaders:l,pageContext:c,onRelativeLinkClick:d,t:u,maxFileCount:h=10,maxTotalSize:p=52428800}){const g="legacy"===n,[m,f]=r([]),[b,x]=r(!1),[w,y]=r(null),[v,k]=r(()=>"undefined"==typeof window?null:localStorage.getItem(ke)),[N,C]=r(()=>Se("undefined"==typeof window?null:localStorage.getItem(ke))),[S,_]=r([]),[I,L]=r(null),[A,E]=r(null),[T,M]=r(null),[$,z]=r(!1),[j,D]=r(null),[R,U]=r(!1),[O,H]=r(0),[W,q]=r(0),[K,J]=r(()=>"undefined"==typeof window?null:localStorage.getItem(Ne)),Z=a(!1),X=a(null),Q=a(null),ee=a(null),te=a(!1),ne=a(v),re=a(b);re.current=b;const ae=a(c);ae.current=c;const se=a(new Map),pe=a(d);pe.current=d;const be=a(l);be.current=l;const xe=a(null),Ce=a(!1),Le=a(null),Ae=a(0),Ee=a(null),Te=a(new AbortController),Me=Number.isFinite(h)&&h>0?Math.floor(h):10,$e=Number.isFinite(p)&&p>0?p:Ie,ze=()=>g||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,je=()=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const r=t?.approve;return r?`${e}${r}`:null},De=a(je);De.current=je;const Re=r=>{if(g||"ag-ui"===n||t?.singleEndpoint)return null;const a=t?.pendingApprovals;return a?`${e}${a}/${r}/pending-approvals`:null},Ue=async e=>{const t=Re(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:B(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Oe=o(()=>{Z.current=!1,H(e=>e+1)},[]),He=()=>g||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,We=o(e=>{ne.current=e,k(e),e?localStorage.setItem(ke,e):localStorage.removeItem(ke)},[]),Be=async n=>{if(ne.current)return ne.current;if(Ee.current)return Ee.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&&We(a),a}catch{return null}finally{Ee.current=null}})();return Ee.current=a,a},Fe=async(e,t,n)=>{const r=He(),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||!He())return;const t=Array.from(e).map(e=>({file:e,tempId:crypto.randomUUID()}));let n=[];_(e=>{const r=e.length,a=e.reduce((e,t)=>e+t.size,0),o=Me-r;if(o<=0)return e;let i=$e-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=Te.current.signal;for(const{file:t,tempId:r}of n)(async()=>{try{const n=await Be(s);if(!n)return void _(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e));const a=await Fe(t,n,e);_(e=>e.map(e=>e.fileId===r?{...e,fileId:a,uploadStatus:"done"}:e))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;_(e=>e.map(e=>e.fileId===r?{...e,uploadStatus:"error"}:e))}})()},0)},Pe=async(e,t,n)=>{const r=De.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",...be.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(!G(r,pe.current))return i("page_actions_not_supported");y(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await oe(t,se.current,pe.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=>!Y(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=he(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(ve(t))continue;const e=ce(t),n=de(t);let r=null;if(e){const n=`e${d.size+1}`,a=we(t,e),s=fe(t);if(r=`[${n}] ${e} ${me(ge(t,e))}${s.length?` (${s.join(", ")})`:""}${a?` = ${me(a)}`:""}${ye(t)}`,c+r.length+1>o)return i=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${me(he(ue(t)))} (level ${n})`,c+r.length+1>o))return i=!0,!1;if(r&&(l.push(r),c+=r.length+1),(!e||le(t))&&!u(t))return!1}return!0};return e.body&&!i&&u(e.body),i&&l.push(ie),{text:l.join("\n"),url:r,title:a,refs:d}}(document);se.current=e.refs,s={text:e.text,url:e.url,title:e.title}}catch(e){se.current=new Map,l=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...be.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)}},Ve=()=>{ee.current?.close(),ee.current=null,X.current?.abort(),X.current=null,Q.current?.abort(),Q.current=null,Te.current.abort(),Te.current=new AbortController,Ee.current=null,f([]),C(""),_([]),x(!1),y(null),L(null),E(null),M(null),D(null),U(!1),xe.current=null,Ce.current=!1,Le.current=null,te.current=!1,Z.current=!1,g?(J(null),localStorage.removeItem(Ne)):We(null)};i(()=>{const e=window.setTimeout(()=>_e(v,N),300);return()=>window.clearTimeout(e)},[N,v]),i(()=>()=>{ee.current?.close(),Q.current?.abort()},[]);const Ge=a({conversationId:v,inputValue:N});Ge.current={conversationId:v,inputValue:N},i(()=>()=>{const{conversationId:e,inputValue:t}=Ge.current;_e(e,t)},[]),i(()=>{const e=v;if(!e||b)return;if(Le.current===e)return;Re(e)&&je()&&(Le.current=e,(async()=>{const t=await Ue(e);t?.proposals&&(ne.current!==e||re.current||(xe.current=e,Ce.current=!0,D(null),M(t.proposals)))})())},[v,b]),i(()=>{if(!T?.length||!Ce.current)return;const e=xe.current,t=e?Re(e):null;if(!t)return;const n=window.setInterval(()=>{fetch(t,{headers:{...l??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[T]),i(()=>{if(!R)return;const e=xe.current;if(!e)return void U(!1);if(Date.now()>=Ae.current)return U(!1),void Oe();let t=!1;const n=window.setTimeout(async()=>{const n=await Ue(e);if(!t){if(n)return n.proposals?(Ce.current=!0,D(null),M(n.proposals),void U(!1)):n.turnRunning?void q(e=>e+1):(U(!1),void Oe());q(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[R,W,Oe]);const Ke=b&&null!==ze()&&null!==v;return{messages:m,inputValue:N,setInputValue:C,isLoading:b,agentStatus:w,attachedFiles:S,conversationId:v,contextUsage:A,transferredAgent:I,canSteer:Ke,pendingApprovals:T,isSubmittingApproval:$,approvalError:j,submitApprovalDecisions:async e=>{const t=je(),n=xe.current??ne.current;if(0!==e.length)if(t&&n){D(null),z(!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 M(null),Ce.current?(Ce.current=!1,Ae.current=Date.now()+9e5,void U(!0)):void y(e=>e?{...e,status:"thinking"}:{status:"thinking"});D(409===r.status?u("This turn is no longer waiting for a decision."):u("Could not send your decision. Please try again."))}catch{D(u("Could not send your decision. Please try again."))}finally{z(!1)}}else D(u("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:R,historyReloadNonce:O,historyLoadedRef:Z,conversationIdRef:ne,handleFileAdd:qe,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),qe(t))},handleSendMessage:async()=>{const r=N.trim();if(b)return void(r&&0===S.length&&ze()&&ne.current&&(C(""),await(async e=>{const t=ze(),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)),C(t=>t?`${e}\n${t}`:e)}})(r)));if(!N.trim()&&0===S.length)return;const a=N.trim(),o={id:crypto.randomUUID(),role:"user",content:a,timestamp:new Date,files:S.length>0?[...S]:void 0};f(e=>[...e,o]),C(""),_([]),x(!0),y({status:"thinking"}),te.current=!1;const i=crypto.randomUUID();f(e=>[...e,{id:i,role:"assistant",content:"",timestamp:new Date}]);let c=i,d="",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=d;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=p;const m=new AbortController;Q.current?.abort();const w=new AbortController;try{X.current=m,Q.current=w;const r=(o.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),b=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.supportsPageActions&&(e.supports_page_actions=!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:ne.current,agentSlug:s,pageContext:ae.current,supportsToolApproval:null!==je(),supportsPageActions:G(je(),pe.current)});r.length>0&&(b.file_ids=r),y({status:"thinking"});const x=await fetch(g||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...l??{}},body:JSON.stringify(b),signal:m.signal});if(!x.ok||!x.body)return void f(e=>e.map(e=>e.id===i?{...e,content:u("Unable to connect. Please check the configuration.")}:e));const v=function(e){switch(e){case"legacy":return P;case"ag-ui":return V;default:return F}}(n),k={hasUsedTools:!1,activeNodeId:""},N=x.body.getReader(),C=new TextDecoder;let S="";const _=()=>{if(!h)return;p.flush(),h=!1,d="",c=crypto.randomUUID();const e=c;f(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),y({status:"thinking"})};for(;;){const{done:e,value:t}=await N.read();if(e)break;S+=C.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=v(JSON.parse(n),k);switch(k.hasUsedTools=k.hasUsedTools||te.current,e.action){case"status":{_();const t=c;if(e.contextUsage&&E(e.contextUsage),"tool_start"===e.status&&(te.current=!0),"thinking_text"===e.status){p.thinking(e.thinkingContent??"");break}if(p.flush(),"stream_retract"===e.status)d="",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":_(),d+=e.content,p.text();break;case"done":{p.flush(),h=!0,M(null),D(null),e.conversationId&&We(e.conversationId),e.contextUsage&&E(e.contextUsage),e.transferAgentId&&e.transferAgentName&&L({id:e.transferAgentId,name:e.transferAgentName});const t=c,n=e.content||d,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,reasoning:e.reasoning,toolCallTrace:e.toolCallTrace,transferChain:e.transferChain,isTruncated:e.isTruncated,serverId:e.messageId??a.serverId}:a));break}case"page_action_required":p.flush(),Pe(e.actionId,e.pageAction,e.conversationId);break;case"approval_required":p.flush(),xe.current=e.conversationId??ne.current,D(null),M(e.proposals),y(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"});break;case"error":{_(),p.flush();const t=c;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":J(e.chatId),localStorage.setItem(Ne,e.chatId)}te.current=k.hasUsedTools}catch{}}}if(p.flush(),d&&!h){const e=c,t=d;f(n=>n.map(n=>n.id===e?{...n,content:t||u("No response.")}:n))}}catch(e){if(p.close(),e instanceof DOMException&&"AbortError"===e.name)return;const t=c;f(e=>e.map(e=>e.id===t?{...e,content:u("Sorry, an error occurred. Please try again.")}:e))}finally{p.close(),ee.current===p&&(ee.current=null),Q.current===w&&w.abort(),X.current===m&&(X.current=null),x(!1),y(null),te.current=!1,M(null),D(null),xe.current=null,Ce.current=!1,Le.current=ne.current}},handleNewChat:Ve,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,M(null),D(null),U(!1),xe.current=null,Ce.current=!1,se.current=new Map,f(e=>e.filter(e=>!("assistant"===e.role&&!e.content)))},setAttachedFiles:_,setMessages:f,setContextUsage:E,updateConversationId:We,handleSwitchConversation:e=>{(g||e!==ne.current)&&(Ve(),g||(We(e),C(Se(e))))}}}const Ae="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,p]=r(null),[g,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(Ae),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:o,agentsLoading:l,agentsError:d,selectedAgent:h,setSelectedAgent:p,agentMenuOpen:g,setAgentMenuOpen:m,handleSwitchAgent:(e,t)=>{e.id!==h?.id?(p(e),e.slug&&localStorage.setItem(Ae,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 Me=400,$e="filigranChatSidebarWidth";let ze=null,je=null,De=0;function Re(){null!==ze&&(window.clearInterval(ze),ze=null),null!==je&&(document.title=je,je=null)}function Ue({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;De+=1;const e=()=>{!document.hidden&&document.hasFocus()&&Re()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),De=Math.max(0,De-1),0===De&&Re()}},[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===je&&(je=document.title),null!==ze&&window.clearInterval(ze);let t=!0;document.title=e,ze=window.setInterval(()=>{t=!t,document.title=t?e:je??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 Oe({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,g=u&&h?`${e}${h}`:null,m=u&&p?`${e}${p}`:null;i(()=>{if(!g)return void l(null);let e=!1;return fetch(g,{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}},[g,a]);const[f,b]=r(0),x=o(()=>b(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:x}}function He({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,p=u&&h?`${e}${h}`:null;return i(()=>{if(!p)return void l(null);let e=!1;d(!0);const t=o?`${p}?agent_slug=${encodeURIComponent(o)}`: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,o,a]),{suggestions:s,loading:c}}function We(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 Be(e){const t=a(e);s(()=>{t.current=e});const n=o((...e)=>t.current?.(...e),[]);return e?n:void 0}const 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:"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"})]}),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:"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"})]}),Pe=({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"})}),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:"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"})]}),Ge=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 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"})]}),Ke=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),Je=({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"})}),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("path",{d:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),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("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"})]}),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("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"})]}),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:"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"})}),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("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"})]}),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("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"})]}),rt=({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"})]}),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("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"})]}),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:"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"})]}),it=({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"})]}),st=({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"})]}),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("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"})]}),ct=({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"})]}),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:"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"})]}),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("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"})]}),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("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),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("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"})]}),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:"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"})]}),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("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"})]}),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("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),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:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),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("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),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:"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"})}),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("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),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("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),Nt=({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"})]}),Ct=({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"})]}),St=({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"})]}),_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:"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"})]}),It="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",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("path",{d:It}),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"})]}),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("path",{d:It}),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 Mt=({open:e,onClose:n,anchorRef:s,placement:c="bottom-start",width:d=280,children:u})=>{const h=a(null),[p,m]=r({top:0,left:0}),f=o(()=>n(),[n]);if(function(e,t,n=!0){i(()=>{if(!n)return;const r=n=>{e.current&&!e.current.contains(n.target)&&t()};return document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r)}},[e,t,n])}(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 b=_(s.current);return g(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}),b)},$t=({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 zt(e){return Math.max(e.maxRight-e.minLeft,0)}const jt=({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=_(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&&g(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:zt(c)},role:"tooltip",children:n}),_(i.current))]})},Dt=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(ot,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(wt,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(st,{...e})}],Rt=({mode:o,agentName:s,agents:l,agentsLoading:d=!1,agentsError:u=!1,selectedAgent:h,transferredFrom:p,agentMenuOpen:g,onAgentMenuToggle:m,onAgentMenuClose:f,onSwitchAgent:b,modeMenuOpen:x,onModeMenuToggle:w,onModeMenuClose:y,onModeChange:v,onNewChat:k,onClose:N,logoIcon:C,agentDashboardUrl:_,historyEnabled:I=!1,historyMenuOpen:A=!1,onHistoryMenuToggle:E,onHistoryMenuClose:T,conversations:M=[],conversationsLoading:$=!1,activeConversationId:z=null,onSelectConversation:j,onDeleteConversation:D,t:R})=>{const U=a(null),O=a(null),H=a(null),[W,B]=r("");i(()=>{g||B("")},[g]);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?wt:"fullscreen"===o?it:ot;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"})]}),p&&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:p})})]}),e(Mt,{open:g,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($t,{size:16})}),0===l.length&&!d&&u&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(Fe,{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(bt,{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:()=>b(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:[_&&e("button",{type:"button",onClick:()=>{f(),window.open(`${_}/agents`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(rt,{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")})]}),_&&e("button",{type:"button",onClick:()=>{f(),window.open(`${_}/agents/new`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",children:[t(_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:R("Create agent")})]})]})]}),t("div",{className:"flex-1"}),I&&e(n,{children:[t(jt,{title:R("Conversation history"),children:t("button",{ref:H,type:"button",onClick:E,"aria-label":R("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(dt,{size:18})})}),e(Mt,{open:A,onClose:()=>T?.(),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:[$&&0===M.length&&t("div",{className:"px-4 py-2",children:t($t,{size:16})}),!$&&0===M.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:R("No conversations yet")}),M.map(n=>{const r=n.conversationId===z,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(St,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px bg-gray-200 dark:bg-white/10 mx-2"}),e("button",{type:"button",onClick:()=>{T?.(),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(nt,{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(jt,{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(nt,{size:18})})}),t(jt,{title:R("Switch view"),children:t("button",{ref:O,type:"button",onClick:w,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(Mt,{open:x,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:Dt.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(jt,{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(Ze,{size:18})})})]})};function Ut(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 Ot(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const Ht=14,Wt=2*Math.PI*6,Bt=[{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"}],Ft=({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),g=p>=.95,m=p>=.8,f=g?"text-red-500":m?"text-amber-500":"text-[var(--chat-accent)]",b=g?"text-red-500 dark:text-red-400":m?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",x=Math.round(100*p),w=`${I(s)}/${I(l)}`,y=i(g?"Context full — older turns are being dropped":m?"Context nearly full — older turns are being summarized":"Context used"),v=S(i,"{counts} tokens",{counts:w}),k=`${y} · ${v}`,N=c?Bt.filter(e=>(c[e.field]??0)>0):[],C=N.length>0,_=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:Ht,height:Ht,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:Wt,strokeDashoffset:Wt*(1-p),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${b}`,children:[x,"%"]})]});return C?e(n,{children:[t(jt,{title:u?"":S(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:_})}),e(Mt,{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 ${b}`,children:S(i,"{percent}% full",{percent:x})}),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:I(c?.[n.field]??0)})]},n.field))}),m&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${b}`,children:y})]})]}):t(jt,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${x}%)`,children:_})})},qt=({prompts:o,onPick:i,t:s})=>{const l=a(null),[c,d]=r(!1),[u,h]=r(""),p=()=>{d(!1),h("")},g=u.trim().toLowerCase(),m=g?o.filter(e=>e.title.toLowerCase().includes(g)||(e.description??"").toLowerCase().includes(g)):o;return e(n,{children:[t(jt,{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(yt,{size:15})})}),e(Mt,{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===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),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))]})]})]})},Pt=({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(jt,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30",role:"img","aria-label":`${e} ${I(a)}`,children:I(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=`${I(a)}/${I(o)}`,g=r(c?"Quota reached":"Quota"),m=s(i?`${g} · ${i}`:g);return t(jt,{title:m,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${m} ${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})]})})},Vt=({inputValue:s,onInputChange:c,onSend:d,onStop:u,isLoading:h,canSteer:p=!1,attachedFiles:g=[],onFileAdd:m,onFileRemove:f,onPaste:b,t:x,mode:w,separatorColor:y,prompts:v,quota:k,contextUsage:N,composerToolbar:C})=>{const S=a(null),_=a(null),I=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!==Ot();return i(()=>{const e=Ot();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=Ut(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=>{I.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`,I.current&&(I.current=!1,e.scrollTop=e.scrollHeight))},[s]);const A=Boolean(v&&v.length>0||k||N||C),E=Boolean(m&&f&&b),T=s.trim()||E&&g.length>0,M=E&&g.some(e=>"pending"===e.uploadStatus),$=T&&!M,z=E&&g.length>0,j=h&&p&&Boolean(s.trim())&&!z,D=()=>{(h?j:$)&&(L.cancel(),d())},R=x(h&&p&&!z?"Enter to send now · Esc to stop":h&&z?"Attachments wait for the current response":"Uses AI. Verify results.");return e("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-white/10 "+("floating"===w?"rounded-b-xl":""),style:y?{borderTopColor:y,borderTopWidth:1}:void 0,children:[E&&g.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:g.map((n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] "+("error"===n.uploadStatus?"border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400":"pending"===n.uploadStatus?"border-gray-200 dark:border-white/10 text-gray-400 dark:text-white/40":"border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60"),children:["pending"===n.uploadStatus?t("span",{className:"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin"}):t(at,{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:[E&&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(Pe,{size:18})})]}),t("textarea",{ref:_,placeholder:L.listening?x("Listening..."):x("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:b,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(jt,{title:L.listening?x("Stop dictation"):x("Dictate a message"),children:e("button",{type:"button",onClick:L.toggle,"aria-label":x("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(ft,{size:18}):t(mt,{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(jt,{title:x("Send now"),children:t("button",{type:"button",onClick:D,"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(xt,{size:18})})}),t(jt,{title:h?x("Stop generating"):M?x("Files uploading..."):"",children:t("button",{type:"button",onClick:h?u:D,disabled:!h&&!$,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":$?"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?vt:xt,{size:18})})})]}),A&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[v&&v.length>0&&t(qt,{prompts:v,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(Ft,{usage:N,t:x}),k&&t(Pt,{quota:k,t:x})]})]}),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})]})},Gt=e=>e.serverId??e.id;const Kt=b().use(f).use(m).freeze(),Jt=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function Yt(e){if(Jt.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 Zt(e,t){if(!Jt.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??[])Zt(n,t)}}const Xt=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;const Qt=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;function en(e){const[t]=r(Qt),[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()&&Zt(Kt.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=o(()=>c.current?.stop(),[]);return i(()=>()=>c.current?.stop(),[]),{supported:t,speakingId:n,toggle:h,stop:p}}const tn={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"}},nn=new Map;function rn(e,t){const n=`${e??""}|${t}`;let r=nn.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,tn[t])}catch{r=new Intl.DateTimeFormat(void 0,tn[t])}nn.set(n,r)}return r}const an={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const on=new Set(["ArrowUp","PageUp","Home"]);function sn(e){return 1===e.length?e[0].clientY:null}const ln=new Set(["auto","scroll","overlay"]);function cn(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function dn(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 un="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",hn=({proposal:n,decision:a,onDecide:o,disabled:i,t:s})=>{const[l,c]=r(!1),[u,h]=r(""),p=d(),g=dn(l),m=a?.verdict,f=Object.keys(n.arguments??{}),b=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:cn(n.arguments?.[r])})]},r)})}),!m&&l&&e("div",{ref:g,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:()=>b("reject"),className:`${un} 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:`${un} 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:`${un} 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:()=>b("approve"),className:`${un} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(Je,{size:13}),s("Yes")]}),t("button",{type:"button",disabled:i,onClick:()=>b("approve_always"),title:s("Also applies to your scheduled runs, until you revoke it"),className:`${un} 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")})]})]})},pn=({proposals:n,onSubmit:o,isSubmitting:s,error:l,t:c})=>{const[d,u]=r({}),h=a(!1),[p,g]=r(!1);i(()=>{l&&(h.current=!1,g(!1))},[l]);const m=s||p,f=e=>{h.current||s||(h.current=!0,g(!0),o(e))},b=n.filter(e=>d[e.toolCallId]).length,x=b===n.length&&n.length>0,w=Object.values(d).some(e=>"approve_always"===e.verdict),y=dn(w),v=dn(!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(Fe,{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(hn,{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)),w&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(Fe,{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:b,total:n.length}):""}),t("button",{type:"button",disabled:!x||m,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${un} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:c(m?"Sending…":"Confirm")})]})]})},gn=({src:n,alt:o,onClose:s,t:l})=>{const c=a(null),d=a(null),[u,h]=r(null);return i(()=>{h(_(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&&g(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(Ze,{size:20})}),t("img",{src:n,alt:o,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},mn=({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),[p,g]=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||g(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,a,s]);const b=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")}):b?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:b,alt:o,loading:"lazy",onClick:()=>f(!0),onError:()=>g(!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})})]}),m&&t(gn,{src:b,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(ut,{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 fn="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",bn=({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,p]=r(0);if(i(()=>{a&&l()},[a,l]),i(()=>{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 g=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:g}),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:[g,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(u?"":"animate-pulse")})]},g),o?e("button",{type:"button",onClick:o,className:fn,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(lt,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:fn,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(lt,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(rt,{size:11})})]}):null]})]})};function xn(e,t){return e>1?S(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function wn(e,t){return e>1?S(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function yn(e,t){return e>1?S(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function vn(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 kn({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 Nn(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 Cn(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 Sn=({agentStatus:a,logoIcon:o,t:s,miniGameEnabled:l=!0,onPlayWaitingGame:d,waitingGameUrl:u,keepEndInView:h})=>{const{label:p,StatusIcon:g,showDots:m}=function(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:Ge,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:xn(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:_t,showDots:!1};if(r.some(e=>"check_task_status"===e))return{label:wn(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:yt,showDots:!1};if(r.some(e=>"get_task_result"===e))return{label:yn(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:yt,showDots:!1};let a,o=Et;if(r.some(e=>e.includes("search")||e.includes("list"))?o=bt:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?o=Qe:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?o=pt:r.some(e=>e.includes("code")||e.includes("execute"))?o=kt:r.some(e=>e.includes("web")||e.includes("browse"))&&(o=ct),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:Fe,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:yt,showDots:!0};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:yt,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:yt,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:Ge,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:S(t,"Consulting {agent}…",{agent:n}),StatusIcon:_t,showDots:!1}}case"delegating":return{label:xn(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:_t,showDots:!1};case"polling":return{label:wn(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:yt,showDots:!1};case"collecting":return{label:yn(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:yt,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:S(t,"Transferring to {agent}…",{agent:n}),StatusIcon:rt,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:Ge,showDots:!1}}}(a,s),f=a?.thinkingContent,b=a?.elapsedStartMs,[x,w]=r(()=>Date.now());i(()=>{if(null==b)return;w(Date.now());const e=window.setInterval(()=>w(Date.now()),1e3);return()=>window.clearInterval(e)},[b]);const y=null!=b?Math.max(0,(x-b)/1e3):a?.elapsedS,v="number"==typeof y&&y>=15,k=c(()=>function(e){if(e.length<=6e3)return vn(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 vn(o)}(f??""),[f]),N=k.length>=3,C=Cn(l&&!N,5e3),_=Cn(l&&N,1e4,f?.length??0),I=N?_: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(g,{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}),v&&t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:Nn(y)})]})]})]}),I?t(bn,{t:s,enabled:l,onPlay:d,playUrl:u,keepEndInView:h}):N?t(kn,{text:k}):null]})},_n=b().use(f).use(m).freeze();function In(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(In);default:return!1}}function Ln(e,t){return e.lastIndexOf("\n",t-1)+1}function An(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Ln(e,t-1),t-1).trim()}function En(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 Tn{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 _n.parse(a).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Ln(a,n),i=o[o.length-1];t>i&&!En(e,i,t)&&o.push(t)}i<0&&In(t)&&(i=o.length-1)}let s=n;for(let t=o.length-1;t>n;t--)if(An(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 Mn=u({copiedBlock:null,onCopyCode:()=>{},t:C}),$n={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(Mn),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(Je,{size:14,className:"text-green-500"}):t(Xe,{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(Mn),a=J(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(Mn);return"string"==typeof e&&e?t(mn,{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})},zn=[m,w],jn=h(({source:e})=>t(x,{remarkPlugins:zn,urlTransform:N,components:$n,children:e}));jn.displayName="MarkdownBody";const Dn=({source:e})=>{const[a]=r(()=>new Tn),o=c(()=>a.split(e),[a,e]);return t(n,{children:o.map((e,n)=>t(jn,{source:e},n))})},Rn=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 p=c(()=>v(e),[e]),g=o(e=>{navigator.clipboard.writeText(e),d(e),setTimeout(()=>d(null),2e3)},[]),m=c(()=>({copiedBlock:l,onCopyCode:g,onRelativeLinkClick:a,requestHeaders:i,t:s}),[l,g,a,i,s]);return t(Mn.Provider,{value:m,children:t(u?Dn:jn,{source:p})})});Rn.displayName="MarkdownMessage";function Un(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function On(e){return e.replace(/_/g," ")}const Hn=({entry:n,index:a,t:o})=>{const[i,s]=r(!1),l=c(()=>Un(n.input),[n.input]),d=c(()=>Un(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(Ke,{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:On(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)")})]})]})]})},Wn=({msg:n,onClose:o,t:s})=>{const l=a(null),c=a(null),d=a(null),[u,h]=r(null);i(()=>{h(_(l.current))},[]),i(()=>{const e=e=>{if("Escape"===e.key)return void o();if("Tab"!==e.key)return;const t=d.current;if(!t)return;const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],a=n[n.length-1],i=document.activeElement;e.shiftKey?i!==r&&t.contains(i)||(e.preventDefault(),a.focus()):i!==a&&t.contains(i)||(e.preventDefault(),r.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),i(()=>{if(!u)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return c.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[u]);const p=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,m=n.toolNames??[],f=n.iterations??1,b=n.transferChain??[],x=n.toolCallTrace??[],w=(n.reasoning??"").trim(),y=[f>1?S(s,"{count} iterations",{count:f}):"",1===p?s("1 tool call"):S(s,"{count} tool calls",{count:p}),1===b.length?s("1 transfer"):b.length>1?S(s,"{count} transfers",{count:b.length}):""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:u&&g(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(Ze,{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(Fe,{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.")]})]}),w&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Ge,{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:vn(w)})})]}),x.length>0?t("div",{className:"flex flex-col gap-1.5",children:x.map((e,n)=>t(Hn,{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:On(n)})]},`${n}-${r}`))}),b.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(qe,{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:b.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(Ve,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},Bn=e=>e.parentElement,Fn=e=>getComputedStyle(e).overflowY;function qn(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function Pn(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 Vn=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const Gn="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",Kn="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",Jn="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",Yn=`opacity-0 ${Gn} ${Jn}`,Zn=`opacity-50 ${Gn} ${Jn}`,Xn="opacity-100 text-[var(--chat-accent)]",Qn=({timestamp:n,locale:r})=>{const a=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:rn(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:rn(t,"full").format(e),iso:e.toISOString()}:null;var r,a}(n,r);return a?t(jt,{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},er=({text:e,label:n,t:a})=>{const[o,i]=r(!1),s=o?a("Copied!"):n;return t(jt,{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:`${Kn} ${o?"opacity-100 text-green-500 dark:text-green-400":Yn}`,children:t(o?Je:Xe,{size:14})})})},tr=({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?Ct:Nt;return t(jt,{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:`${Kn} ${o?Xn:Yn} ${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")})]})},nr=({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")})]})]})},rr=({speaking:e,onToggle:n,t:r})=>{const a=r(e?"Stop reading":"Read aloud");return t(jt,{title:a,children:t("button",{type:"button",onClick:n,"aria-label":a,className:`${Kn} ${e?Xn:Yn}`,children:t(e?At:Lt,{size:14})})})},ar=h(({msg:n,isStreaming:o,agentName:i,logoIcon:s,onRelativeLinkClick:d,onDownloadFile:u,resolveAttachmentUrl:h,requestHeaders:p,feedbackMode:g,feedback:m,onRate:f,onSaveComment:b,onSkipComment:x,locale:w,canSpeak:y,isSpeaking:k,onToggleSpeech:N,t:C})=>{const[S,_]=r(!1),I="assistant"===n.role,L=!n.content,M=a(null),$=!!m?.commentOpen,z=a($);l(()=>{const e=z.current&&!$;z.current=$,!e||document.activeElement&&document.activeElement!==document.body||M.current?.focus()},[$]);const j=(n,r)=>{const a=h&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&Vn.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&Vn.has(e.filename.slice(n+1).toLowerCase())}(n)?h(n):void 0;if(a)return t(mn,{src:a,alt:n.filename,requestHeaders:p,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(at,{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(tt,{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(at,{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=I&&!L&&!o,O=function(e){if(!e)return e;const t=e.replace(A,"").replace(E,"");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 T(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=Gt(n);return e("div",{className:"group/msg flex flex-col "+(I?"items-start":"items-end"),children:[I&&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})]}),!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:Pn(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})()}),I?e("div",{className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=T(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(Rn,{content:e.value,streaming:o,onRelativeLinkClick:d,requestHeaders:p,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}),!I&&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(er,{text:n.content,label:C("Copy message"),t:C}),!n.timestampUnknown&&t(Qn,{timestamp:n.timestamp,locale:w})]}),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(Qn,{timestamp:n.timestamp,locale:w}),R&&t(jt,{title:n.isTruncated?C("Reasoning details — turn limit reached"):C("Reasoning details"),children:t("button",{type:"button",onClick:()=>_(e=>!e),className:`${Kn} ${n.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":Zn}`,"aria-label":n.isTruncated?C("Reasoning details — turn limit reached"):C("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":S,children:n.isTruncated?t(Fe,{size:14}):t(ht,{size:14})})}),t(er,{text:O,label:C("Copy response"),t:C}),g&&t(tr,{value:W.value,locked:W.locked,pending:!!m?.pending,onChange:e=>f(n,e,m),downRef:M,t:C}),H&&(V=H,V.some(e=>/[\p{L}\p{N}]/u.test(e.replace(Xt,""))))&&t(rr,{speaking:k,onToggle:()=>N(P,H),t:C})]}),U&&m?.commentOpen&&t(nr,{pending:m.pending,onSave:e=>b(n,e,m),onSkip:()=>x(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(Wn,{msg:n,onClose:()=>_(!1),t:C})]});var V});ar.displayName="MessageRow";const or=({messages:n,isLoading:d,agentStatus:u,agentName:h,logoIcon:p,onRelativeLinkClick:g,onDownloadFile:m,resolveAttachmentUrl:f,requestHeaders:b,miniGameEnabled:x=!0,onPlayWaitingGame:w,waitingGameUrl:y,onMessageFeedback:v,isResumingAfterDecision:k,pendingApprovals:N,onSubmitApprovalDecisions:C,isSubmittingApproval:S,approvalError:_,feedbackUrl:I,conversationId:L,locale:A,t:E})=>{const T=a(null),[j,R]=r(150),{entries:U,rate:O,saveComment:H,skipComment:W}=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 p=a(0),g=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=Gt(e),c=++p.current;if(!r)return g(l,{seq:c,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void i?.(l,t,e);if(a&&e.serverId){if(g(l,{seq:c,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await D(fetch,r,a,e.serverId,t?{rating:M(t),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)}},[g,m]),saveComment:o(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,t:i}=h.current,s=Gt(e),l=z(t);if(!(r&&a&&e.serverId&&l))return void g(s,{...n,commentOpen:!1,error:null});const c=++p.current;g(s,{...n,seq:c,pending:!0,error:null});const d=await D(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.")})},[g,m]),skipComment:o((e,t)=>g(Gt(e),{...t,commentOpen:!1,error:null}),[g])}}({feedbackUrl:I,conversationId:L,requestHeaders:b,onMessageFeedback:v,t:E}),B=en(A),[F]=r(()=>function(e,t=an){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())}}}(()=>T.current)),q=a(null),P=(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&&ln.has(r(a)))return!0;return!1}(t,e,Bn,Fn)||F.leave())},V=n[0]?.id;i(()=>{R(150)},[V]);let G=0;for(const e of n)"user"===e.role&&(G+=1);const K=a(null);l(()=>{const e=K.current;K.current={firstMessageId:V,userMessageCount:G},!e||e.firstMessageId!==V||G>e.userMessageCount?F.reveal():F.keepUp()},[n,V,G,F]);const J=u?.thinkingContent?.length??0;l(()=>{J&&F.keepUp()},[J,F]);const Y=n.length>j,Z=c(()=>Y?n.slice(n.length-j):n,[n,j,Y]),{speakingId:X,stop:Q}=B,ee=null===X||n.some(e=>Gt(e)===X),te=a({conversationId:L,userMessageCount:G});i(()=>{const e=te.current;te.current={conversationId:L,userMessageCount:G},(e.conversationId!==L||G>e.userMessageCount||!ee)&&Q()},[L,G,ee,Q]);let ne=null;if(d)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){ne=n[e].id;break}const re=!!N?.length&&!!C;return e("div",{ref:T,role:"region","aria-label":E("Conversation transcript"),tabIndex:0,onScroll:F.onScroll,onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&P(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(on.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&qn(e.target)||P(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:qn(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})&&P(t,e.target)},onTouchStart:e=>{q.current=sn(e.touches)},onTouchMove:e=>{const t=sn(e.touches),n=q.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&P(e.currentTarget,e.target),q.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:()=>R(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"}),E("Load earlier messages")]})}),Z.map(e=>{const n=e.id===ne;return"assistant"===e.role&&!e.content&&n?re?null:t("div",{children:t(Sn,{agentStatus:u,logoIcon:p,t:E,miniGameEnabled:x,onPlayWaitingGame:w,waitingGameUrl:y,keepEndInView:F.keepUp})},e.id):t(ar,{msg:e,isStreaming:n,agentName:h,logoIcon:p,onRelativeLinkClick:g,onDownloadFile:m,resolveAttachmentUrl:f,requestHeaders:b,feedbackMode:"assistant"===e.role?$(e.serverId,I,L,!!v):null,feedback:U[Gt(e)],onRate:O,onSaveComment:H,onSkipComment:W,locale:A,canSpeak:B.supported,isSpeaking:X===Gt(e),onToggleSpeech:B.toggle,t:E},e.id)}),k&&!re&&t(Sn,{agentStatus:u,logoIcon:p,t:E,miniGameEnabled:x,onPlayWaitingGame:w,waitingGameUrl:y,keepEndInView:F.keepUp}),re&&t(pn,{proposals:N,onSubmit:C,isSubmitting:S,error:_,t:E},N.map(e=>e.toolCallId).join("|")),t("div",{})]})},ir=({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]})},sr=({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(ir,{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))]})]}),lr=({conversations:n,loading:o,activeConversationId:i,collapsed:s,onToggleCollapsed:l,onSelect:d,onDelete:u,onRename:h,onNewChat:p,t:g})=>{const[m,f]=r(""),[b,x]=r(null),[w,y]=r(""),v=a(!1),k=()=>{if(v.current)return;v.current=!0;const e=b,t=w.trim();x(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(jt,{title:g("Show conversations"),children:t("button",{type:"button",onClick:l,"aria-label":g("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(wt,{size:17})})}),t(jt,{title:g("New conversation"),children:t("button",{type:"button",onClick:p,"aria-label":g("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(nt,{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:p,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(nt,{size:15}),g("New conversation")]}),t(jt,{title:g("Hide conversations"),children:t("button",{type:"button",onClick:l,"aria-label":g("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(wt,{size:17})})})]}),n.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(bt,{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:g("Search conversations..."),"aria-label":g("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($t,{size:16})}),!o&&0===n.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:g("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:g("No conversation matches")}),N.map(n=>{const r=n.conversationId===i,a=n.conversationId===b;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(Ve,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[a?t("input",{autoFocus:!0,value:w,onChange:e=>y(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&k(),"Escape"===e.key&&(v.current=!0,x(null))},onBlur:k,"aria-label":g("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||g("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,g):""]})]}),!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,x(t),y(r)},"aria-label":g("Rename conversation"),title:g("Rename conversation"),className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(nt,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),u(n.conversationId)},"aria-label":g("Delete conversation"),title:g("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(St,{size:13})})]})]},n.conversationId)})]})]})},cr=({mode:n,onClose:s,onModeChange:l,topOffset:d=0,apiBaseUrl:u,apiEndpoints:h,agentDashboardUrl:p,user:g,t:m=C,accentColor:f="#7b5cff",logoIcon:b,promptSuggestions:x,draftBorderColor:w,resizable:v=!1,onWidthChange:k,onResizeStart:N,onResizeEnd:S,disableFileManagement:_=!1,onRelativeLinkClick:I,onDownloadError:L,maxFileCount:A,maxTotalSize:E,requestHeaders:T,pageContext:M,pushContentSelector:$,backendType:z="rest",miniGameEnabled:D=!0,onPlayWaitingGame:R,notifyOnComplete:B=!0,onTaskComplete:F,onMessageFeedback:P,locale:V,disableImagePreviews:G=!1,contextUsageEnabled:K=!0,composerToolbar:J})=>{const Y=We(h),Z=We(T),X=We(M),Q=We(x),ee=Be(I),te=Be(L),ne=Be(R),re=Be(F),ae=Be(P),[oe,ie]=r(!1),{agents:se,agentsLoading:le,agentsError:ce,selectedAgent:de,agentMenuOpen:ue,setAgentMenuOpen:he,handleSwitchAgent:pe}=Ee({apiBaseUrl:u,apiEndpoints:Y,backendType:z,requestHeaders:Z}),{messages:ge,inputValue:me,setInputValue:fe,isLoading:be,agentStatus:xe,attachedFiles:we,conversationId:ye,contextUsage:ve,transferredAgent:ke,canSteer:Ne,pendingApprovals:Ce,isSubmittingApproval:Se,approvalError:_e,submitApprovalDecisions:Ie,isResumingAfterDecision:Ae,historyReloadNonce:ze,historyLoadedRef:je,conversationIdRef:De,handleFileAdd:Re,handlePaste:Fe,handleSendMessage:qe,handleNewChat:Pe,handleStopGenerating:Ve,setAttachedFiles:Ge,setMessages:Ke,setContextUsage:Je,updateConversationId:Ye,handleSwitchConversation:Ze}=Le({apiBaseUrl:u,apiEndpoints:Y,backendType:z,agentSlug:de?.slug,requestHeaders:Z,pageContext:X,onRelativeLinkClick:I?ee:void 0,t:m,maxFileCount:A,maxTotalSize:E}),{suggestions:Xe,loading:Qe}=He({apiBaseUrl:u,apiEndpoints:Y,backendType:z,requestHeaders:Z,agentSlug:de?.slug}),tt=c(()=>(Xe??Q)?.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),[Xe,Q,m]),{prompts:nt,quota:rt,refreshQuota:at}=Oe({apiBaseUrl:u,apiEndpoints:Y,backendType:z,requestHeaders:Z}),{historyEnabled:ot,conversations:it,conversationsLoading:st,refreshConversations:lt,deleteConversation:ct,renameConversation:dt}=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]),p=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]),g=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:p,renameConversation:g}}({apiBaseUrl:u,apiEndpoints:Y,backendType:z,requestHeaders:Z}),[ut,ht]=r(!1),[pt,gt]=r(!1),mt="fullscreen"===n&&ot;i(()=>{mt&<()},[mt,ye,lt]);const ft=a(!1);i(()=>{ft.current&&!be&&(at(),mt&<()),ft.current=be},[be,at,mt,lt]);const bt=e=>{ht(!1),Ze(e)},xt=async e=>{await ct(e)&&e===De.current&&Pe()},{sidebarWidth:wt,handleResizeStart:yt,defaultWidth:vt,isResizing:kt}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:o,onResizeEnd:s}){const[l,c]=r(()=>{if("undefined"==typeof window)return Me;const e=localStorage.getItem($e);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=Me)return t}return Me}),[d,u]=r(!1),h=a(!1),p=a(l);p.current=l;const g=a(n);g.current=n;const m=a(s);return m.current=s,i(()=>{"sidebar"===e&&t&&g.current?.(p.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,Me),n);c(r),p.current=r,g.current?.(r)},r=()=>{h.current&&(h.current=!1,u(!1),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem($e,String(p.current)),m.current?.())},a=()=>{const e=.4*window.innerWidth;if(p.current>e){const t=Math.max(e,Me);c(t),p.current=t,g.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:Me,isResizing:d}}({mode:n,resizable:v,onWidthChange:k,onResizeStart:N,onResizeEnd:S});i(()=>{const e="sidebar"===n?v?wt:vt:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",kt?"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=kt?"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,wt,vt,v,kt]);const Nt=c(()=>b??t(et,{size:24}),[b]),Ct=c(()=>function(e){const t=e?.trim().replace(/\/+$/,"");return t&&/^https?:\/\//i.test(t)?`${t}/chat?arcade=play`:null}(p),[p]),St=g.firstName,[_t,It]=r(null),Lt=ke?.name||_t||de?.name||m("Assistant"),At=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)},[]);Ue({isLoading:be,agentName:Lt,t:m,enabled:B,onComplete:re,isViewingChat:At});const Et=null!=Y?.download,Tt="rest"===z&&null!==Y?.download&&(!Y?.singleEndpoint||Et),Mt=o(e=>`${u}${Y?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[u,Y]),$t=o(async e=>{const t=Mt(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){te?.(t,e)}},[Mt,Z,te]),zt={"--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},jt=a(!0);i(()=>(jt.current=!0,()=>{jt.current=!1}),[]),i(()=>{if(null===Y?.sessions||Y?.singleEndpoint||"legacy"===z||"ag-ui"===z)return;if(!ye)return void It(null);if(je.current||!de)return;je.current=!0;const e=ye,t=()=>!jt.current||De.current!==e;fetch(`${u}${Y?.sessions??"/chat/sessions"}`,{method:"POST",headers:{"Content-Type":"application/json",...Z??{}},body:JSON.stringify({conversation_id:ye,agent_slug:de.slug})}).then(e=>t()?null:e.ok?e.json():(Ye(null),null)).then(n=>{if(n&&!t()&&("string"==typeof n.conversation_id&&n.conversation_id&&n.conversation_id!==e&&Ye(n.conversation_id),It("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?q(r.feedback):void 0,agentName:"string"==typeof r.agent_name?r.agent_name:void 0,attachments:O(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:H(r.tool_call_trace),transferChain:W(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=U(n.messages[e]);if(t){Je(t);break}}}}).catch(()=>{t()||Ye(null)})},[ye,de,u,Y,z,ze,je,De,jt,Z,Ke,Je,Ye]);const Dt=(()=>{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}})(),Ut={...zt,..."sidebar"===n?{top:d,width:v?wt:vt}:"floating"===n?{width:380,height:560}:{top:d}};return e("div",{className:Dt,style:Ut,children:["sidebar"===n&&v&&t("div",{onMouseDown:yt,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(Rt,{mode:n,agentName:Lt,agents:se,agentsLoading:le,agentsError:ce,selectedAgent:de,transferredFrom:ke?de?.name:void 0,agentMenuOpen:ue,onAgentMenuToggle:()=>he(e=>!e),onAgentMenuClose:()=>he(!1),onSwitchAgent:e=>{e&&pe(e,()=>{Pe()})},modeMenuOpen:oe,onModeMenuToggle:()=>ie(e=>!e),onModeMenuClose:()=>ie(!1),onModeChange:l,onNewChat:Pe,onClose:s,logoIcon:Nt,agentDashboardUrl:p,historyEnabled:ot&&!mt,historyMenuOpen:ut,onHistoryMenuToggle:()=>{const e=!ut;e&<(),ht(e)},onHistoryMenuClose:()=>ht(!1),conversations:it,conversationsLoading:st,activeConversationId:ye,onSelectConversation:bt,onDeleteConversation:e=>{xt(e)},t:m}),e("div",{className:mt?"flex flex-1 min-h-0":"contents",children:[mt&&t(lr,{conversations:it,loading:st,activeConversationId:ye,collapsed:pt,onToggleCollapsed:()=>gt(e=>!e),onSelect:bt,onDelete:e=>{xt(e)},onRename:(e,t)=>{dt(e,t)},onNewChat:Pe,t:m}),e("div",{className:mt?"flex flex-1 flex-col min-w-0":"contents",children:[0===ge.length?t(sr,{firstName:St,logoIcon:Nt,promptSuggestions:tt,suggestionsLoading:Qe,agentName:de?.name,agentDescription:de?.description,onPromptClick:fe,t:m}):t(or,{messages:ge,isLoading:be,agentStatus:xe,agentName:Lt,logoIcon:Nt,onRelativeLinkClick:ee,onDownloadFile:Tt?$t:void 0,resolveAttachmentUrl:Tt&&!G?Mt:void 0,requestHeaders:Z,miniGameEnabled:D,onPlayWaitingGame:ne,waitingGameUrl:Ct,onMessageFeedback:ae,feedbackUrl:j(u,Y,z),conversationId:ye,locale:V,isResumingAfterDecision:Ae,pendingApprovals:Ce,onSubmitApprovalDecisions:Ie,isSubmittingApproval:Se,approvalError:_e,t:m}),t(Vt,{inputValue:me,onInputChange:fe,onSend:qe,onStop:Ve,isLoading:be,canSteer:Ne,attachedFiles:_?[]:we,onFileAdd:_?void 0:Re,onFileRemove:_?void 0:e=>Ge(t=>t.filter((t,n)=>n!==e)),onPaste:_?void 0:Fe,t:m,mode:n,separatorColor:w,prompts:nt,quota:rt,contextUsage:K?ve:null,composerToolbar:J})]})]})]})},dr=({isOpen:n,onToggle:r,label:a,accentColor:o="#7b5cff",icon:i,t:s=C})=>{const l=i??t(et,{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{cr as ChatPanel,dr as ChatToggleButton};
|
|
1
|
+
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{createContext as r,useContext as a,useState as o,useRef as s,useEffect as i,useCallback as l,useInsertionEffect as c,useLayoutEffect as d,useMemo as u,useId as p,Component as h,memo as g,forwardRef as m,useImperativeHandle as f}from"react";import v from"remark-gfm";import w from"remark-parse";import{unified as y}from"unified";import{createPortal as x}from"react-dom";import b from"react-markdown";import k from"remark-breaks";function N(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}function C(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 s=(e,n)=>{for(let r=e+1;r<n;r++)if(""!==t[r].trim())return!1;return!0};let i=0,l=3,c=0,d=-1;for(let e=0;e<o.length;e++){const t=o[e];if(t.bare&&0===i){const n=o[e+1];if(!n||!n.bare||s(t.idx,n.idx)){d=t.idx;break}i++}else i=t.bare?Math.max(0,i-1):i+1;c++,l=Math.max(l,t.run)}if(-1===d||0===c)return e;const u="`".repeat(Math.max(l+1,4)),p=t[a].match(n);t[a]=`${p[1]}${u}${p[3]}`;const h=t[d].match(n);return t[d]=`${h[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 s=null,i=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===s?(s=e[0],i=e.length):e[0]===s&&e.length>=i&&""===c[2].trim()&&(s=null,i=0);continue}if(null!==s)continue;const d=t[e],u=t[e+1];if(!d.includes("|")||r(d)||!r(u))continue;const p=d.match(l),h=p?p[0].length:d.length-d.trimStart().length,g=p?" ".repeat(h):d.slice(0,h),m=n(d.slice(h)).length,f=n(u);if(m<2||f.length===m)continue;const v=[];for(let e=0;e<m;e++)v.push(f[e]?a(f[e]):"---");t[e+1]=`${g}| ${v.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)));var t}const S=new Set(["http","https","mailto","tel"]);function I(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 S.has(o)||"data"===o&&/^data:image\//i.test(e)?e:""}const T=e=>e;function A(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function _(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function E(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 M(e,t){if(!e)return"";const n=new Date(e).getTime();if(Number.isNaN(n))return"";const r=Date.now()-n,a=Math.floor(r/6e4);if(a<1)return t("just now");if(a<60)return A(t,"{count}m ago",{count:a});const o=Math.floor(a/60);if(o<24)return A(t,"{count}h ago",{count:o});const s=Math.floor(o/24);return s<7?A(t,"{count}d ago",{count:s}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const L=["FILE","PRESENTATION","REPORT","VIDEO"],R=`(${L.join("|")}):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?`,$=/^[A-Z][A-Z0-9_]*$/;const D=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new Map;function z(e){const t=e.filter(e=>!L.includes(e)),n=t.join(","),r=j.get(n);if(r)return r;const a=[...L,...t].map(D).join("|"),o=t.length>0?`|(${t.map(D).join("|")}):([^\\]]+)`:"",s=[...L,...t].map(e=>`[[${e}:`),i={complete:new RegExp(`\\[\\[(?:${R}${o})\\]\\]`,"gi"),partial:new RegExp(`\\[\\[(?:${a})(?::[^\\]]*)?\\]?$`,"i"),heads:s,longestHead:Math.max(...s.map(e=>e.length))};return j.size>=32&&j.delete(j.keys().next().value),j.set(n,i),i}function O(e,t=!1,n=[]){if(!e)return[];const r=z(n),a=[];let o=0;for(const t of e.matchAll(r.complete)){if(t.index>o&&a.push({type:"text",value:e.slice(o,t.index)}),t[1]){const e=t[1].toUpperCase();n.includes(e)?a.push({type:"marker",kind:e,args:t[3]?`${t[2]}#/${t[3]}`:t[2]}):"FILE"===e?a.push({type:"file",fileId:t[2]}):a.push({type:"artifact",kind:e.toLowerCase(),id:t[2].toLowerCase(),slideRef:t[3]||void 0})}else a.push({type:"marker",kind:t[4].toUpperCase(),args:t[5]});o=t.index+t[0].length}const s=e.slice(o).replace(r.partial,""),i=t?function(e,t){for(let n=Math.max(0,e.length-t.longestHead);n<e.length;n++){if("["!==e[n])continue;const r=e.slice(n).toUpperCase();if(t.heads.some(e=>e.startsWith(r)))return e.slice(0,n)}return e}(s,r):s;return i&&a.push({type:"text",value:i}),a}function P(e,t=[]){const n=[];for(const r of O(e,!1,t))"text"===r.type&&r.value.trim()&&n.push(C(r.value));return n}const U=(e,t)=>`${e}:${t.toLowerCase()}`;function H(e,t){const n=[];if("presentation"===e.kind&&void 0!==e.slideCount&&n.push(A(t,"{count} slides",{count:e.slideCount})),"report"===e.kind&&void 0!==e.sectionCount&&n.push(A(t,"{count} sections",{count:e.sectionCount})),"video"===e.kind){void 0!==e.sceneCount&&n.push(A(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(" · ")}function W(e){const t=new Map;for(const n of e){const e=n.group?.trim()||null;t.has(e)||t.set(e,[]),t.get(e).push(n)}const n=t.get(null);return t.delete(null),[...n?[{group:null,agents:n}]:[],...[...t].map(([e,t])=>({group:e,agents:t}))]}const q=y().use(w).use(v).freeze(),B=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function F(e){if(B.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(F).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function V(e,t){if(!B.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(F(e));case"tableRow":return void t.push((e.children??[]).map(F).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])V(n,t)}}function K(e){const t=[];for(const n of e)n.trim()&&V(q.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")}const G=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;function J(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}async function*Y(e,t,n,r){const a=a=>async function(e,t,n,r){const a=await e(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.requestHeaders??{}},body:JSON.stringify({text:n,format:"mp3"}),signal:r});if(!a.ok)throw new Error(`TTS failed: ${a.status}`);return a.blob()}(e,t,n[a],r).catch(()=>null);let o=n.length>0?a(0):null;for(let e=0;o;e+=1){const t=await o;o=e+1<n.length&&!r.aborted?a(e+1):null,yield t}}function X(e,t,n,r){const a=t?.[r];return"rest"!==n||t?.singleEndpoint||"string"!=typeof a||!a?null:`${e}${a}`}const Z={es:{"(no output)":"(sin salida)","1 tool call":"1 llamada a una herramienta","1 transfer":"1 transferencia","A file failed to upload: remove it, or send once the answer ends":"Un archivo no se pudo subir: quítelo, o envíe cuando termine la respuesta","A message references at most {count} conversations":"Un mensaje puede hacer referencia a {count} conversaciones como máximo","Acting on the page…":"Actuando en la página…","Agent switching is not available here":"El cambio de agente no está disponible aquí","Almost there":"Ya casi estamos","Also applies to your scheduled runs, until you revoke it":"También se aplica a sus ejecuciones programadas, hasta que lo revoque","Always allowed":"Siempre permitido","Analyzing results…":"Analizando los resultados…","Analyzing the details":"Analizando los detalles",Approved:"Aprobado","Ask Assistant":"Preguntar al asistente","Ask a question...":"Haga una pregunta...",Assistant:"Asistente","Attach files":"Adjuntar archivos","Attached files":"Archivos adjuntos","Attachments wait for the current response":"Los archivos adjuntos esperan la respuesta actual",Back:"Volver","Bad response":"Respuesta incorrecta","Browse agents":"Explorar agentes",Cancel:"Cancelar","Cancel question":"Cancelar la pregunta","Clear all conversations":"Borrar todas las conversaciones",Close:"Cerrar","Collecting results from one task…":"Recopilando los resultados de una tarea…","Collecting results from {count} tasks…":"Recopilando los resultados de {count} tareas…","Composing answer…":"Redactando la respuesta…",Confirm:"Confirmar","Connecting the dots":"Atando cabos","Consulting the sources":"Consultando las fuentes","Consulting {agent}…":"Consultando a {agent}…","Context full — older turns are being dropped":"Contexto completo: se están eliminando los turnos más antiguos","Context nearly full — older turns are being summarized":"El contexto está casi lleno: se están resumiendo los turnos más antiguos","Context used":"Contexto utilizado","Continue now":"Continuar ahora",Conversation:"Conversación","Conversation history":"Historial de conversaciones","Conversation title":"Título de la conversación","Conversation transcript":"Hilo de la conversación",Copied:"Copiado","Copied!":"¡Copiado!","Copy code":"Copiar código","Copy message":"Copiar mensaje","Copy response":"Copiar respuesta","Could not reach the assistant service. Check the connection and try again.":"No se ha podido conectar con el servicio del asistente. Compruebe la conexión e inténtelo de nuevo.","Could not send your decision. Please try again.":"No se ha podido enviar su decisión. Inténtelo de nuevo.","Create agent":"Crear agente","Crunching the data":"Procesando los datos","Decline this call":"Rechazar esta llamada",Declined:"Rechazado","Delegating one task…":"Delegando una tarea…","Delegating {count} tasks…":"Delegando {count} tareas…","Delete all conversations":"Eliminar todas las conversaciones","Delete all conversations?":"¿Eliminar todas las conversaciones?","Delete conversation":"Eliminar conversación","Delete workspace":"Eliminar espacio de trabajo","Delete?":"¿Eliminar?","Dictate a message":"Dictar un mensaje","Did not answer":"No respondió",Download:"Descargar","Download {format}":"Descargar en {format}","Drop a conversation here, or start one with +.":"Suelte aquí una conversación o inicie una con +.","Drop files to attach them":"Suelte los archivos para adjuntarlos","End voice call":"Finalizar la llamada de voz","Enter to send now · Esc to stop":"Pulse Intro para enviar ahora · Esc para detener","Enter to send when the answer ends · Esc to stop":"Pulse Intro para enviar cuando termine la respuesta · Esc para detener","Every conversation is in a workspace.":"Todas las conversaciones están en un espacio de trabajo.","Expand image":"Ampliar imagen","Failed to get a response. Resuming…":"No se obtuvo respuesta. Reanudando…","Feedback already submitted":"Valoración ya enviada","Files uploading...":"Cargando archivos...",Floating:"Flotante","Full screen":"Pantalla completa","Good response":"Buena respuesta","Help me create a new simulation scenario":"Ayúdame a crear un nuevo escenario de simulación","Hide conversations":"Ocultar conversaciones","How can I help you, {name}?":"¿En qué puedo ayudarle, {name}?","How can {agent} help you, {name}?":"¿En qué puede ayudarle {agent}, {name}?","How do I configure detection rules?":"¿Cómo configuro las reglas de detección?","Image could not be loaded":"No se ha podido cargar la imagen","Image preview":"Vista previa de la imagen","Incorporating your message…":"Incorporando su mensaje…",Input:"Entrada","Insert prompt template":"Insertar plantilla de prompt","Listening...":"Escuchando...","Load earlier messages":"Cargar mensajes anteriores","Loading image…":"Cargando imagen…","MCP & dynamic tools":"MCP y herramientas dinámicas","Mention an agent":"Mencionar un agente","Model reasoning":"Razonamiento del modelo","Move to workspace":"Mover a un espacio de trabajo","Mute microphone":"Silenciar el micrófono",Muted:"Silenciado","New chat":"Nuevo chat","New conversation":"Nueva conversación","New conversation in this workspace":"Nueva conversación en este espacio de trabajo","New conversation — send a message to start it":"Nueva conversación: envíe un mensaje para iniciarla","New workspace":"Nuevo espacio de trabajo",No:"No","No agent matches":"No hay ningún agente que coincida","No conversation matches":"No hay conversaciones que coincidan","No conversations yet":"Aún no hay conversaciones","No prompt matches":"No hay ningún prompt que coincida","No response.":"Sin respuesta.","Not in a workspace":"Sin espacio de trabajo","Not rendered yet":"Renderizado no iniciado",Open:"Abrir","Open conversation":"Abrir conversación","Open in XTM One":"Abrir en XTM One","Other workspaces":"Otros espacios de trabajo",Output:"Salida","Play Space Invaders":"Jugar a Space Invaders","Play Space Invaders in XTM One":"Jugar a Space Invaders en XTM One","Polishing the answer":"Puliendo la respuesta",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (editable)",Presentation:"Presentación","Putting it together":"Juntando las piezas",Quota:"Cuota","Quota reached":"Cuota alcanzada","Read aloud":"Leer en voz alta","Reasoning details":"Detalles del razonamiento","Reasoning details — turn limit reached":"Detalles del razonamiento: se ha alcanzado el límite de turnos","Reference a conversation":"Hacer referencia a una conversación","Remove from workspace":"Quitar del espacio de trabajo","Rename conversation":"Cambiar el nombre de la conversación","Rename workspace":"Cambiar el nombre del espacio de trabajo","Rendering {progress}%":"Renderizando {progress} %",Report:"Informe","Response ready":"Respuesta lista","Reticulating splines":"Reticulando splines",Retry:"Reintentar",Save:"Guardar","Search agents...":"Buscar agentes...","Search conversations...":"Buscar conversaciones...","Search prompts...":"Buscar prompts...",Send:"Enviar","Send now":"Enviar ahora","Send when the answer ends":"Enviar cuando termine la respuesta","Sending…":"Enviando…","Sends when the answer ends:":"Se enviará cuando termine la respuesta:","Shared with you":"Compartido con usted","Show conversations":"Mostrar conversaciones",Sidebar:"Barra lateral",Skip:"Omitir","Skip response":"Omitir la respuesta","Sorry, an error occurred. Please try again.":"Lo sentimos, se ha producido un error. Inténtelo de nuevo.","Speak or tap to interrupt":"Habla o toca para interrumpir","Speaking…":"Hablando…","Stop dictation":"Detener el dictado","Stop generating":"Detener la generación","Stop reading":"Detener la lectura",Stopped:"Detenido","Stopping…":"Deteniendo…",Suggestions:"Sugerencias","Summarize my recent findings":"Resume mis hallazgos recientes","Summarized conversation":"Conversación resumida","Switch to":"Cambiar a","Switch to another agent":"Cambiar a otro agente","Switch view":"Cambiar de vista","System prompt":"Prompt del sistema","Tap to cancel":"Toca para cancelar","Tell us what went wrong (optional)":"Indíquenos qué ha fallado (opcional)","The agent needs your approval to run a tool:":"El agente necesita su aprobación para ejecutar una herramienta:","The agent needs your approval to run these tools:":"El agente necesita su aprobación para ejecutar estas herramientas:","The conversation could not be moved":"No se ha podido mover la conversación","The render did not finish":"El renderizado no ha finalizado","The workspace could not be created":"No se ha podido crear el espacio de trabajo","The workspace could not be deleted":"No se ha podido eliminar el espacio de trabajo","The workspace could not be renamed":"No se ha podido cambiar el nombre del espacio de trabajo","Thinking it through":"Reflexionando sobre ello","Thinking...":"Pensando...","This conversation could not be loaded.":"No se ha podido cargar esta conversación.","This decision could not be sent. Reload the chat and try again.":"No se ha podido enviar esta decisión. Actualice el chat e inténtelo de nuevo.","This message waits for the current response":"Este mensaje espera la respuesta actual","This message will be read with your next one.":"Este mensaje se leerá con su próximo mensaje.","This item could not be loaded.":"No se ha podido cargar este elemento.","The response could not be stopped. Try again.":"No se ha podido detener la respuesta. Inténtelo de nuevo.","This turn is no longer waiting for a decision.":"Este turno ya no está a la espera de una decisión.","Tool definitions":"Definiciones de herramientas","Tool results":"Resultados de las herramientas","Transfer chain":"Cadena de transferencia","Transferred from {agent}":"Transferido desde {agent}","Transferring to {agent}…":"Transfiriendo a {agent}…","Turn limit reached.":"Se ha alcanzado el límite de turnos.","Unable to connect. Please check the configuration.":"No se puede establecer conexión. Compruebe la configuración.","Unmute microphone":"Activar el micrófono","Untitled conversation":"Conversación sin título",Usage:"Uso","Usage · {period}":"Uso · {period}","Uses AI. Verify results.":"Utiliza IA. Verifique los resultados.","Using tools…":"Usando herramientas…",Video:"Vídeo","Voice call":"Llamada de voz","Waiting before continuing…":"Esperando antes de continuar…","Waiting for one background task…":"Esperando una tarea en segundo plano…","Waiting for your approval…":"Esperando su aprobación…","Waiting for {count} background tasks…":"Esperando {count} tareas en segundo plano…","Waiting to render":"Esperando el renderizado","What are the latest attack patterns?":"¿Cuáles son los últimos patrones de ataque?","What could be improved?":"¿Qué se podría mejorar?","Why not? The agent sees this and can adapt (optional)":"¿Por qué no? El agente ve esto y puede adaptarse (opcional)","Workspace name":"Nombre del espacio de trabajo",Workspaces:"Espacios de trabajo","Wrapping things up":"Finalizando",Yes:"Sí","Yes, always":"Sí, siempre","Your answer is ready":"Su respuesta está lista",default:"predeterminado","e.g. wrong environment — use staging instead":"Por ejemplo, entorno incorrecto: utilice el entorno de pruebas en su lugar","just now":"hace un momento","the agent":"el agente","this month":"este mes","this year":"este año",today:"hoy","unknown tool":"herramienta desconocida","{agent} has finished":"{agent} ha finalizado","{counts} tokens":"{counts} tokens","{count} iterations":"{count} iteraciones","{count} scenes":"{count} escenas","{count} sections":"{count} secciones","{count} slides":"{count} diapositivas","{count} tool calls":"{count} llamadas a herramientas","{count} transfers":"{count} transferencias","{count}d ago":"hace {count} d","{count}h ago":"hace {count} h","{count}m ago":"hace {count} min","{decided}/{total} decided":"{decided}/{total} decididos","{percent}% full":"{percent} % completo","{quota} (shared across all users)":"{quota} (compartido entre todos los usuarios)","{summary} — click for details":"{summary} — haga clic para ver más detalles","{tool} (+{count} more)…":"{tool} (+{count} má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.":"Se agotó el presupuesto de iteraciones del agente: la ejecución se detuvo antes de completar todos los pasos previstos. La respuesta final es un resumen aproximado del trabajo realizado hasta ahora.","“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.":"«Sí, siempre» guarda una preferencia para ti. Esa herramienta se ejecutará entonces sin preguntar, incluso en ejecuciones programadas que nadie supervisa, hasta que la revoques."},fr:{"(no output)":"(pas de sortie)","1 tool call":"1 appel d’outil","1 transfer":"1 transfert","A file failed to upload: remove it, or send once the answer ends":"Un fichier n’a pas pu être envoyé : retirez-le, ou envoyez une fois la réponse terminée","A message references at most {count} conversations":"Un message fait référence à {count} conversations au maximum","Acting on the page…":"Action sur la page…","Agent switching is not available here":"Le changement d’agent n’est pas disponible ici","Almost there":"On y est presque","Also applies to your scheduled runs, until you revoke it":"S’applique également à vos exécutions planifiées, jusqu’à ce que vous la révoquiez","Always allowed":"Toujours autorisé","Analyzing results…":"Analyse des résultats…","Analyzing the details":"Analyse des détails",Approved:"Approuvé","Ask Assistant":"Demander à l’assistant","Ask a question...":"Poser une question...",Assistant:"Assistant","Attach files":"Joindre des fichiers","Attached files":"Fichiers joints","Attachments wait for the current response":"Les pièces jointes attendent la réponse en cours",Back:"Retour","Bad response":"Réponse incorrecte","Browse agents":"Parcourir les agents",Cancel:"Annuler","Cancel question":"Annuler la question","Clear all conversations":"Effacer toutes les conversations",Close:"Fermer","Collecting results from one task…":"Collecte des résultats d’une tâche…","Collecting results from {count} tasks…":"Collecte des résultats de {count} tâches…","Composing answer…":"Rédaction de la réponse…",Confirm:"Confirmer","Connecting the dots":"Relier les points","Consulting the sources":"Consulter les sources","Consulting {agent}…":"Consultation de {agent}…","Context full — older turns are being dropped":"Contexte complet — les tours plus anciens sont supprimés","Context nearly full — older turns are being summarized":"Contexte presque plein — les tours plus anciens sont en cours de synthèse","Context used":"Contexte utilisé","Continue now":"Continuer maintenant",Conversation:"Conversation","Conversation history":"Historique des conversations","Conversation title":"Titre de la conversation","Conversation transcript":"Fil de la conversation",Copied:"Copié","Copied!":"Copié !","Copy code":"Copier le code","Copy message":"Copier le message","Copy response":"Copier la réponse","Could not reach the assistant service. Check the connection and try again.":"Impossible d’accéder au service d’assistant. Vérifiez la connexion et réessayez.","Could not send your decision. Please try again.":"Impossible d’envoyer votre décision. Veuillez réessayer.","Create agent":"Créer un agent","Crunching the data":"Traitement des données","Decline this call":"Refuser cet appel",Declined:"Refusé","Delegating one task…":"Délégation d’une tâche…","Delegating {count} tasks…":"Délégation de {count} tâches…","Delete all conversations":"Supprimer toutes les conversations","Delete all conversations?":"Supprimer toutes les conversations ?","Delete conversation":"Supprimer la conversation","Delete workspace":"Supprimer l’espace de travail","Delete?":"Supprimer ?","Dictate a message":"Dicter un message","Did not answer":"N’a pas répondu",Download:"Télécharger","Download {format}":"Télécharger en {format}","Drop a conversation here, or start one with +.":"Déposez une conversation ici ou démarrez-en une avec +.","Drop files to attach them":"Déposez des fichiers pour les joindre","End voice call":"Terminer l’appel vocal","Enter to send now · Esc to stop":"Appuyez sur Entrée pour envoyer maintenant · Appuyez sur Échap pour arrêter","Enter to send when the answer ends · Esc to stop":"Appuyez sur Entrée pour envoyer à la fin de la réponse · Appuyez sur Échap pour arrêter","Every conversation is in a workspace.":"Toutes les conversations sont dans un espace de travail.","Expand image":"Agrandir l’image","Failed to get a response. Resuming…":"Aucune réponse reçue. Reprise…","Feedback already submitted":"Avis déjà envoyé","Files uploading...":"Envoi des fichiers en cours...",Floating:"Flottant","Full screen":"Plein écran","Good response":"Bonne réponse","Help me create a new simulation scenario":"Aidez-moi à créer un nouveau scénario de simulation","Hide conversations":"Masquer les conversations","How can I help you, {name}?":"Comment puis-je vous aider, {name} ?","How can {agent} help you, {name}?":"Comment {agent} peut-il vous aider, {name} ?","How do I configure detection rules?":"Comment configurer les règles de détection ?","Image could not be loaded":"Impossible de charger l’image","Image preview":"Aperçu de l’image","Incorporating your message…":"Intégration de votre message…",Input:"Entrée","Insert prompt template":"Insérer un modèle de prompt","Listening...":"Écoute en cours...","Load earlier messages":"Charger les messages précédents","Loading image…":"Chargement de l’image…","MCP & dynamic tools":"MCP et outils dynamiques","Mention an agent":"Mentionner un agent","Model reasoning":"Raisonnement du modèle","Move to workspace":"Déplacer vers un espace de travail","Mute microphone":"Couper le micro",Muted:"Micro coupé","New chat":"Nouveau chat","New conversation":"Nouvelle conversation","New conversation in this workspace":"Nouvelle conversation dans cet espace de travail","New conversation — send a message to start it":"Nouvelle conversation — envoyez un message pour la démarrer","New workspace":"Nouvel espace de travail",No:"Non","No agent matches":"Aucun agent ne correspond","No conversation matches":"Aucune conversation ne correspond","No conversations yet":"Aucune conversation pour l’instant","No prompt matches":"Aucun prompt ne correspond","No response.":"Pas de réponse.","Not in a workspace":"Hors espace de travail","Not rendered yet":"Rendu non lancé",Open:"Ouvrir","Open conversation":"Ouvrir la conversation","Open in XTM One":"Ouvrir dans XTM One","Other workspaces":"Autres espaces de travail",Output:"Sortie","Play Space Invaders":"Jouer à Space Invaders","Play Space Invaders in XTM One":"Jouer à Space Invaders dans XTM One","Polishing the answer":"Peaufiner la réponse",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (modifiable)",Presentation:"Présentation","Putting it together":"Assemblage des éléments",Quota:"Quota","Quota reached":"Quota atteint","Read aloud":"Lire à voix haute","Reasoning details":"Détails du raisonnement","Reasoning details — turn limit reached":"Détails du raisonnement — limite de tours atteinte","Reference a conversation":"Faire référence à une conversation","Remove from workspace":"Retirer de l’espace de travail","Rename conversation":"Renommer la conversation","Rename workspace":"Renommer l’espace de travail","Rendering {progress}%":"Rendu en cours : {progress} %",Report:"Rapport","Response ready":"Réponse prête","Reticulating splines":"Réticulation des splines",Retry:"Réessayer",Save:"Sauvegarder","Search agents...":"Rechercher des agents...","Search conversations...":"Rechercher des conversations...","Search prompts...":"Rechercher des prompts...",Send:"Envoyer","Send now":"Envoyer maintenant","Send when the answer ends":"Envoyer à la fin de la réponse","Sending…":"Envoi en cours…","Sends when the answer ends:":"Envoi à la fin de la réponse :","Shared with you":"Partagé avec vous","Show conversations":"Afficher les conversations",Sidebar:"Barre latérale",Skip:"Passer","Skip response":"Passer la réponse","Sorry, an error occurred. Please try again.":"Désolé, une erreur s’est produite. Veuillez réessayer.","Speak or tap to interrupt":"Parlez ou touchez pour interrompre","Speaking…":"Réponse en cours…","Stop dictation":"Arrêter la dictée","Stop generating":"Arrêter la génération","Stop reading":"Arrêter la lecture",Stopped:"Arrêté","Stopping…":"Arrêt en cours…",Suggestions:"Suggestions","Summarize my recent findings":"Résumez mes dernières découvertes","Summarized conversation":"Résumé de la conversation","Switch to":"Basculer vers","Switch to another agent":"Passer à un autre agent","Switch view":"Changer de vue","System prompt":"Prompt système","Tap to cancel":"Touchez pour annuler","Tell us what went wrong (optional)":"Dites-nous ce qui n’a pas fonctionné (facultatif)","The agent needs your approval to run a tool:":"L’agent a besoin de votre accord pour exécuter un outil :","The agent needs your approval to run these tools:":"L’agent a besoin de votre accord pour exécuter ces outils :","The conversation could not be moved":"Impossible de déplacer la conversation","The render did not finish":"Le rendu n’a pas abouti","The workspace could not be created":"Impossible de créer l’espace de travail","The workspace could not be deleted":"Impossible de supprimer l’espace de travail","The workspace could not be renamed":"Impossible de renommer l’espace de travail","Thinking it through":"Réfléchir à la question","Thinking...":"Je réfléchis...","This conversation could not be loaded.":"Impossible de charger cette conversation.","This decision could not be sent. Reload the chat and try again.":"Cette décision n’a pas pu être envoyée. Actualisez le chat et réessayez.","This message waits for the current response":"Ce message attend la réponse en cours","This message will be read with your next one.":"Ce message sera lu avec votre prochain message.","This item could not be loaded.":"Impossible de charger cet élément.","The response could not be stopped. Try again.":"La réponse n’a pas pu être arrêtée. Réessayez.","This turn is no longer waiting for a decision.":"Ce tour n’attend plus de décision.","Tool definitions":"Définitions des outils","Tool results":"Résultats des outils","Transfer chain":"Chaîne de transfert","Transferred from {agent}":"Transféré depuis {agent}","Transferring to {agent}…":"Transfert vers {agent}…","Turn limit reached.":"Limite de tours atteinte.","Unable to connect. Please check the configuration.":"Impossible de se connecter. Veuillez vérifier la configuration.","Unmute microphone":"Réactiver le micro","Untitled conversation":"Conversation sans titre",Usage:"Utilisation","Usage · {period}":"Utilisation · {period}","Uses AI. Verify results.":"Utilise l’IA. Vérifiez les résultats.","Using tools…":"Utilisation des outils…",Video:"Vidéo","Voice call":"Appel vocal","Waiting before continuing…":"En attente avant de continuer…","Waiting for one background task…":"En attente d’une tâche en arrière-plan…","Waiting for your approval…":"En attente de votre accord…","Waiting for {count} background tasks…":"En attente de {count} tâches en arrière-plan…","Waiting to render":"En attente du rendu","What are the latest attack patterns?":"Quels sont les derniers schémas d’attaque ?","What could be improved?":"Qu’est-ce qui pourrait être amélioré ?","Why not? The agent sees this and can adapt (optional)":"Pourquoi pas ? L’agent en prend connaissance et peut s’adapter (facultatif)","Workspace name":"Nom de l’espace de travail",Workspaces:"Espaces de travail","Wrapping things up":"Pour conclure",Yes:"Oui","Yes, always":"Oui, toujours","Your answer is ready":"Votre réponse est prête",default:"par défaut","e.g. wrong environment — use staging instead":"Par exemple : environnement incorrect — utilisez plutôt l’environnement de préproduction","just now":"à l’instant","the agent":"l’agent","this month":"ce mois-ci","this year":"cette année",today:"aujourd’hui","unknown tool":"outil inconnu","{agent} has finished":"{agent} a terminé","{counts} tokens":"{counts} tokens","{count} iterations":"{count} itérations","{count} scenes":"{count} scènes","{count} sections":"{count} sections","{count} slides":"{count} diapositives","{count} tool calls":"{count} appels d’outils","{count} transfers":"{count} transferts","{count}d ago":"il y a {count} j","{count}h ago":"il y a {count} h","{count}m ago":"il y a {count} min","{decided}/{total} decided":"{decided}/{total} décidés","{percent}% full":"{percent} % rempli","{quota} (shared across all users)":"{quota} (partagé entre tous les utilisateurs)","{summary} — click for details":"{summary} — cliquez pour plus de détails","{tool} (+{count} more)…":"{tool} (+{count} autres)…","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.":"Le budget d’itérations de l’agent est épuisé : l’exécution s’est arrêtée avant la fin de toutes les étapes prévues. La réponse finale résume au mieux le travail accompli jusqu’ici.","“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.":"« Oui, toujours » enregistre une préférence pour vous. Cet outil s’exécutera alors sans demander, y compris lors des exécutions planifiées que personne ne surveille, jusqu’à ce que vous la révoquiez."},ja:{"(no output)":"(出力なし)","1 tool call":"ツール呼び出し 1 件","1 transfer":"転送 1 件","A file failed to upload: remove it, or send once the answer ends":"ファイルのアップロードに失敗しました。削除するか、応答の終了後に送信してください","A message references at most {count} conversations":"1 つのメッセージで参照できる会話は最大 {count} 件です","Acting on the page…":"ページを操作中…","Agent switching is not available here":"ここではエージェントの切り替えは利用できません","Almost there":"もうすぐ完了します","Also applies to your scheduled runs, until you revoke it":"予定された実行についても、取り消すまでは同様に適用されます","Always allowed":"常に許可","Analyzing results…":"結果を分析中…","Analyzing the details":"詳細を分析しています",Approved:"承認済み","Ask Assistant":"アシスタントに質問","Ask a question...":"質問する...",Assistant:"アシスタント","Attach files":"ファイルを添付","Attached files":"添付ファイル","Attachments wait for the current response":"添付ファイルは、現在の応答を待機します",Back:"戻る","Bad response":"不適切な回答","Browse agents":"エージェントを閲覧する",Cancel:"キャンセル","Cancel question":"質問をキャンセル","Clear all conversations":"すべての会話を消去",Close:"閉じる","Collecting results from one task…":"1 件のタスクの結果を収集中…","Collecting results from {count} tasks…":"{count} 件のタスクの結果を収集中…","Composing answer…":"回答を作成中…",Confirm:"確認する","Connecting the dots":"情報を関連付けています","Consulting the sources":"情報源を確認しています","Consulting {agent}…":"{agent} に問い合わせ中…","Context full — older turns are being dropped":"コンテキストが満杯 — 古いターンが削除されています","Context nearly full — older turns are being summarized":"コンテキストがほぼ満杯です — 古いターンが要約されています","Context used":"使用されたコンテキスト","Continue now":"今すぐ続行",Conversation:"会話","Conversation history":"会話履歴","Conversation title":"会話のタイトル","Conversation transcript":"会話の履歴",Copied:"コピーしました","Copied!":"コピー完了!","Copy code":"コードをコピー","Copy message":"メッセージをコピー","Copy response":"応答をコピー","Could not reach the assistant service. Check the connection and try again.":"アシスタントサービスに接続できませんでした。接続状態を確認して、もう一度お試しください。","Could not send your decision. Please try again.":"決定内容を送信できませんでした。もう一度お試しください。","Create agent":"エージェントを作成する","Crunching the data":"データを処理しています","Decline this call":"この呼び出しを拒否",Declined:"拒否済み","Delegating one task…":"1 件のタスクを委任中…","Delegating {count} tasks…":"{count} 件のタスクを委任中…","Delete all conversations":"すべての会話を削除","Delete all conversations?":"すべての会話を削除しますか?","Delete conversation":"会話を削除","Delete workspace":"ワークスペースを削除","Delete?":"削除しますか?","Dictate a message":"メッセージを音声入力する","Did not answer":"回答なし",Download:"ダウンロード","Download {format}":"{format} をダウンロード","Drop a conversation here, or start one with +.":"ここに会話をドロップするか、+ で新しく開始してください。","Drop files to attach them":"ファイルをドロップして添付","End voice call":"音声通話を終了","Enter to send now · Esc to stop":"Enterキーで今すぐ送信 · Escキーで停止","Enter to send when the answer ends · Esc to stop":"Enterキーで回答の終了後に送信 · Escキーで停止","Every conversation is in a workspace.":"すべての会話がワークスペースに含まれています。","Expand image":"画像を拡大","Failed to get a response. Resuming…":"応答を取得できませんでした。再開しています…","Feedback already submitted":"フィードバックは送信済みです","Files uploading...":"ファイルのアップロード中...",Floating:"フローティング","Full screen":"全画面表示","Good response":"適切な回答","Help me create a new simulation scenario":"新しいシミュレーションシナリオの作成を手伝ってください","Hide conversations":"会話を非表示にする","How can I help you, {name}?":"{name} さん、何かお手伝いできることはありますか?","How can {agent} help you, {name}?":"{name} さん、{agent} がお手伝いできることはありますか?","How do I configure detection rules?":"検出ルールはどのように設定すればよいですか?","Image could not be loaded":"画像を読み込めませんでした","Image preview":"画像プレビュー","Incorporating your message…":"メッセージを組み込んでいます…",Input:"入力","Insert prompt template":"プロンプトテンプレートを挿入","Listening...":"聞き取り中...","Load earlier messages":"以前のメッセージを読み込む","Loading image…":"画像を読み込み中…","MCP & dynamic tools":"MCPと動的ツール","Mention an agent":"エージェントをメンション","Model reasoning":"モデルの推論","Move to workspace":"ワークスペースに移動","Mute microphone":"マイクをミュート",Muted:"ミュート中","New chat":"新しいチャット","New conversation":"新しい会話","New conversation in this workspace":"このワークスペースで新しい会話","New conversation — send a message to start it":"新しい会話 — メッセージを送信すると開始されます","New workspace":"新しいワークスペース",No:"いいえ","No agent matches":"該当するエージェントはありません","No conversation matches":"一致する会話はありません","No conversations yet":"まだ会話はありません","No prompt matches":"一致するプロンプトはありません","No response.":"応答なし。","Not in a workspace":"ワークスペースなし","Not rendered yet":"まだレンダリングされていません",Open:"開く","Open conversation":"会話を開く","Open in XTM One":"XTM One で開く","Other workspaces":"その他のワークスペース",Output:"出力","Play Space Invaders":"Space Invaders をプレイ","Play Space Invaders in XTM One":"XTM One で Space Invaders をプレイ","Polishing the answer":"回答を仕上げています",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint(編集可能)",Presentation:"プレゼンテーション","Putting it together":"内容をまとめています",Quota:"クォータ","Quota reached":"クォータに達しました","Read aloud":"読み上げ","Reasoning details":"推論の詳細","Reasoning details — turn limit reached":"推論の詳細 — ターン制限に達しました","Reference a conversation":"会話を参照","Remove from workspace":"ワークスペースから外す","Rename conversation":"会話の名前を変更","Rename workspace":"ワークスペースの名前を変更","Rendering {progress}%":"レンダリング中 {progress}%",Report:"レポート","Response ready":"応答準備完了","Reticulating splines":"スプラインを網状化しています",Retry:"再試行",Save:"保存","Search agents...":"エージェントを検索...","Search conversations...":"会話を検索...","Search prompts...":"プロンプトを検索...",Send:"送信","Send now":"今すぐ送信","Send when the answer ends":"回答の終了後に送信","Sending…":"送信中…","Sends when the answer ends:":"回答の終了後に送信:","Shared with you":"他のユーザーから共有","Show conversations":"会話を表示",Sidebar:"サイドバー",Skip:"スキップ","Skip response":"応答をスキップ","Sorry, an error occurred. Please try again.":"申し訳ありません。エラーが発生しました。もう一度お試しください。","Speak or tap to interrupt":"話すかタップして中断","Speaking…":"読み上げ中…","Stop dictation":"ディクテーションを停止","Stop generating":"生成を停止","Stop reading":"読み上げを停止",Stopped:"停止","Stopping…":"停止中…",Suggestions:"提案","Summarize my recent findings":"私の最近の発見を要約してください","Summarized conversation":"会話の要約","Switch to":"切り替え先","Switch to another agent":"別のエージェントに切り替える","Switch view":"ビューを切り替える","System prompt":"システムプロンプト","Tap to cancel":"タップしてキャンセル","Tell us what went wrong (optional)":"問題があった点をお聞かせください(任意)","The agent needs your approval to run a tool:":"エージェントがツールを実行するには、あなたの承認が必要です:","The agent needs your approval to run these tools:":"エージェントがこれらのツールを実行するには、あなたの承認が必要です:","The conversation could not be moved":"会話を移動できませんでした","The render did not finish":"レンダリングが完了しませんでした","The workspace could not be created":"ワークスペースを作成できませんでした","The workspace could not be deleted":"ワークスペースを削除できませんでした","The workspace could not be renamed":"ワークスペースの名前を変更できませんでした","Thinking it through":"じっくり考えています","Thinking...":"考え中...","This conversation could not be loaded.":"この会話を読み込めませんでした。","This decision could not be sent. Reload the chat and try again.":"この決定を送信できませんでした。チャットを再読み込みして、もう一度お試しください。","This message waits for the current response":"このメッセージは、現在の応答を待機します","This message will be read with your next one.":"このメッセージは次のメッセージと一緒に読まれます。","This item could not be loaded.":"この項目を読み込めませんでした。","The response could not be stopped. Try again.":"応答を停止できませんでした。もう一度お試しください。","This turn is no longer waiting for a decision.":"このターンでは、決定を待つ必要がなくなりました。","Tool definitions":"ツールの定義","Tool results":"ツールの結果","Transfer chain":"転送チェーン","Transferred from {agent}":"{agent} から転送されました","Transferring to {agent}…":"{agent} に転送中…","Turn limit reached.":"ターン制限に達しました。","Unable to connect. Please check the configuration.":"接続できません。設定を確認してください。","Unmute microphone":"マイクのミュートを解除","Untitled conversation":"タイトルのない会話",Usage:"使用状況","Usage · {period}":"使用状況 · {period}","Uses AI. Verify results.":"AIを使用しています。結果を確認してください。","Using tools…":"ツールを使用中…",Video:"動画","Voice call":"音声通話","Waiting before continuing…":"続行する前に待機中…","Waiting for one background task…":"バックグラウンドタスク 1 件を待機中…","Waiting for your approval…":"承認をお待ちしています…","Waiting for {count} background tasks…":"バックグラウンドタスク {count} 件を待機中…","Waiting to render":"レンダリング待ち","What are the latest attack patterns?":"最新の攻撃パターンにはどのようなものがありますか?","What could be improved?":"改善できる点はありますか?","Why not? The agent sees this and can adapt (optional)":"なぜですか? エージェントはこれを確認し、対応を調整できます(任意)","Workspace name":"ワークスペース名",Workspaces:"ワークスペース","Wrapping things up":"仕上げをしています",Yes:"はい","Yes, always":"はい、常に","Your answer is ready":"回答の準備が整いました",default:"デフォルト","e.g. wrong environment — use staging instead":"例:環境が間違っている — 代わりにステージング環境を使用してください","just now":"たった今","the agent":"エージェント","this month":"今月","this year":"今年",today:"今日","unknown tool":"不明なツール","{agent} has finished":"{agent} が完了しました","{counts} tokens":"{counts} トークン","{count} iterations":"{count} 回の反復","{count} scenes":"{count} シーン","{count} sections":"{count} セクション","{count} slides":"{count} スライド","{count} tool calls":"ツール呼び出し {count} 件","{count} transfers":"転送 {count} 件","{count}d ago":"{count} 日前","{count}h ago":"{count} 時間前","{count}m ago":"{count} 分前","{decided}/{total} decided":"{decided}/{total} 件が決定済み","{percent}% full":"{percent} % 使用中","{quota} (shared across all users)":"{quota}(全ユーザーで共有)","{summary} — click for details":"{summary} — クリックで詳細を表示","{tool} (+{count} more)…":"{tool}(他 {count} 件)…","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.":"エージェントの反復回数の上限に達したため、予定されたすべてのステップを完了する前に実行が停止しました。最終的な回答は、これまでに行った作業をできる限りまとめたものです。","“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.":"「はい、常に」を選ぶと、あなたの設定として保存されます。以後、そのツールは確認なしで実行されます(誰も見ていない定期実行を含む)。取り消すまでこの設定は有効です。"}};function Q(e,t){const n=t||!e?function(e){const t=e??("undefined"!=typeof navigator?navigator.language:void 0),n=t?.toLowerCase().split(/[-_]/)[0];return n?Z[n]:void 0}(t):void 0;return t=>{const r=e?.(t);return r&&r!==t?r:n?.[t]??t}}const ee=e=>"up"===e?"positive":"negative";function te(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function ne(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function re(e,t,n){return X(e,t,n,"feedback")}async function ae(e,t,n,r,a,o){const{url:s,init:i}=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:ne(r.comment)})}}:{url:o,init:{method:"DELETE",credentials:"include",headers:{...a}}}}(t,n,r,a,o);try{return(await e(s,i)).ok}catch{return!1}}const oe=e=>void 0!==e&&/[\w-]/.test(e),se=/^[\w-]+$/;function ie(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const a=r[1].toLowerCase();oe(e[r.index-1])||t.includes(a)||t.push(a),r=n.exec(e)}return t}function le(e,t){if(0===e.length)return e;const n=new Set(ie(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function ce(e,t){if(0===e.length)return[];const n=[];for(const r of ie(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 de(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&&se.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 ue(e,t,n){return X(e,t,n,"conversationReferences")}const pe={query:null,items:[],failed:!1};function he(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))}function ge(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 me(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function fe(e,t={}){const n=Array.isArray(e)?e:Array.isArray(e?.workspaces)?e.workspaces:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const n=e;"string"==typeof n.id&&n.id&&"string"==typeof n.name&&(!0!==n.is_archived&&r.push({id:n.id,name:n.name,isOwn:"boolean"==typeof n.is_own?n.is_own:!!t.userId&&n.user_id===t.userId,isDefault:!0===n.is_default,canManage:!0===n.can_manage}))}return r}function ve(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 we(e,t,n,r,a){return!!a||(!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e))}function ye(e,t,n){return!n&&!(t&&e.conversations.some(e=>e.conversationId===t))}const xe=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&t.length<=500?t:null};async function be(e){try{return function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;return xe(e.message)??xe(e.detail)}return xe(t)}(await e.json())}catch{return null}}function ke(e){return e?JSON.stringify(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0)):""}function Ne(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}const Ce=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function Se(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 Ce){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 Ie(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 Te=["presentation","report","video"],Ae=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function _e(e){if(!e||"object"!=typeof e)return;const t=e,n=Te.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:Ae(t.slide_count),sectionCount:Ae(t.section_count),sceneCount:Ae(t.scene_count),durationMs:Ae(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:Ae(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function Ee(e){if(!Array.isArray(e))return;const t=e.map(_e).filter(e=>!!e);return t.length>0?t:void 0}function Me(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 Le(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 Re(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 $e(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}const De=e=>"string"==typeof e&&e?e:void 0;function je(e){if("string"==typeof e)return e?{agentName:e}:void 0;if(!e||"object"!=typeof e)return;const t=e,n={agentId:De(t.agent_id),agentName:De(t.agent_name)??De(t.name),agentIcon:De(t.agent_icon)};return n.agentId||n.agentName?Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)):void 0}function ze(e,t){const n=e.type;if("error"===n||"cancelled"===n){const t=De(e.message_id),r=!0===e.provisional||void 0,a={...t?{messageId:t,raw:{...e}}:{},...r?{provisional:r}:{}};return"error"===n?{action:"error",content:e.content||"",...a}:{action:"cancelled",...a}}if("session_expired"===n)return{action:"session_ended",reason:De(e.reason)};if("approval_resolved"===n)return{action:"approval_resolved"};if("folded_into_active_turn"===n)return{action:"folded",turnId:De(e.turn_id)};if("conversation_title"===n){const t=De(e.title);return t?{action:"conversation_title",conversationId:De(e.conversation_id),title:t}:{action:"noop"}}if("user_message"===n){const[t]=Ue([e.message]);return t&&"user"===t.role?{action:"user_message",message:{...t,id:Oe(t.serverId)}}:{action:"noop"}}if("thinking"===n)return{action:"status",status:"thinking",resumed:!0===e.resumed||void 0,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};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("wait_start"===n)return{action:"status",status:"wait_start",waitSeconds:"number"==typeof e.seconds&&e.seconds>0?e.seconds:void 0,waitReason:De(e.reason)};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=Se(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=$e(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:Ie(e.attachments),artifacts:Ee(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:Me(e.tool_call_trace),transferChain:Re(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:Se(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0,intermediate:!0===e.intermediate||void 0,answeredBy:je(e.answered_by),mentionFailed:!0===e.mention_failed||void 0,raw:{...e}}:{action:"noop"}}function Oe(e,t=Ne()){return e?`msg-${e}`:t}function Pe(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 Ue(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,s="assistant"===r.role?je(r.answered_by):void 0,i="string"==typeof r.id&&r.id?r.id:void 0;t.push({id:Oe(i,`restored-${n}`),serverId:i,role:r.role,content:"string"==typeof r.content?r.content:"",timestamp:o??new Date,timestampUnknown:!o||void 0,feedback:"assistant"===r.role?Pe(r.feedback):void 0,agentName:s?.agentName??("string"==typeof r.agent_name?r.agent_name:void 0),answeredBy:s,mentionFailed:"assistant"===r.role&&!0===r.mention_failed||void 0,attachments:Ie(r.attachments),artifacts:"assistant"===r.role?Ee(r.artifacts):void 0,conversationRefs:"user"===r.role?Le(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:Me(r.tool_call_trace),transferChain:Re(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0,raw:{...r}})}),t}function He(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 qe(){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 s=r(()=>a===e,o.signal).catch(()=>null);return t=s,s.finally(()=>{t===s&&(t=null),n===o&&(n=null)}),s},abandon(){e+=1,t=null,n?.abort(),n=null}}}function Be(e,t){return null!==e&&"function"==typeof t}function Fe(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const Ve=(e,t)=>{const n=t??Fe();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 Ge=/^(current-password|new-password|one-time-code|cc-)/;function Je(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 Ye(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 Xe(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=Ve(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"],s=e.matches?.('input[type="checkbox"], input[type="radio"]')??!1,i=e.checked;if(Ye(e.ownerDocument,o,()=>e.click()),s&&a&&e.checked===i){const t=e;t.checked="radio"===t.type||!i,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 Ze(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 Qe(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&&Ze(r)}async function et(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(Qe(e))return{ok:!0};if(r){if(Je(e),await(a=()=>Qe(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(s),r(!0))});o.observe(e.body??e.documentElement,{subtree:!0,childList:!0}),t();const s=setTimeout(()=>{o.disconnect(),r(!1)},n)}):(t(),Promise.resolve(!0))}(e.ownerDocument,()=>Je(e)))return{ok:!0};var a,o;return n?.aborted?{ok:!1,error:"aborted"}:Xe(e,void 0,t)}const tt=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function nt(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=Ve(e.path,Fe(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const o=t.get(e.ref);return o&&o.isConnected?Ze(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 et(o,Fe(r??o.ownerDocument),a):"click"===e.type?Xe(o,n,Fe(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=>Ge.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=>tt.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&&Ye(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 rt="[truncated]",at=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function ot(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(st(t))return!0;return!1}function st(e){const t=e.getAttribute("role");if(t&&at.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 it(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function lt(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(wt(r)||mt(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?lt(r):` ${lt(r)} `}return n}function ct(e){return(e??"").replace(/\s+/g," ").trim()}const dt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function ut(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=ct(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const a=ct(e.getAttribute("aria-label"));if(a)return a;const o=e.getAttribute("id"),s=o&&Array.from(n.getElementsByTagName("label")).find(e=>e.htmlFor===o)||e.closest("label");if(s){const e=ct(Array.from(s.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||ct(s.textContent))return e||ct(s.textContent)}const i=e.tagName.toLowerCase(),l=(e.getAttribute("type")||"").toLowerCase();if("input"===i&&["submit","reset","button"].includes(l)){const t=ct(e.getAttribute("value"));if(t)return t;if("button"!==l)return"submit"===l?"Submit":"Reset"}const c=ct(e.getAttribute("alt"))||ct(e.querySelector("img[alt]")?.getAttribute("alt"));if(c)return c;const d=mt(e)?"":ct(lt(e));if(dt.has(t)&&d)return d;const u=ct(e.getAttribute("placeholder"));if(u)return u;const p=ct(e.getAttribute("title"));return p||d}function pt(e){return JSON.stringify(e.slice(0,80))}function ht(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 gt=/^(current-password|new-password|one-time-code|cc-)/;function mt(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>gt.test(e))}function ft(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(mt(e))return null;const n="value"in e?String(e.value??""):ct(lt(e));return n||null}function vt(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 wt(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 yt="filigranChatConversationId",xt="filigranChatLegacyChatId",bt="filigranChatAgentSlug",kt="filigranChatSidebarWidth",Nt="filigran-chat-collapsed-workspaces",Ct="filigranChatDraft:",St="filigranChatDraftRefs:";function It(e,t){return e?`${e}:${t}`:t}function Tt(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch{return null}}function At(e,t){try{return Tt(e)?.getItem(t)??null}catch{return null}}function _t(e,t,n){try{const r=Tt(e);if(!r)return;n?r.setItem(t,n):r.removeItem(t)}catch{}}async function Et(e,t){const n=e.getReader(),r=new TextDecoder;let a="";const o=e=>{const n=e.replace(/\r$/,"");if(!n.startsWith("data:"))return!0;const r=n.startsWith("data: ")?n.slice(6):n.slice(5);let a;try{a=JSON.parse(r)}catch{return!0}return!(a&&"object"==typeof a&&!Array.isArray(a))||!1!==t(a)};try{for(;;){const{done:e,value:t}=await n.read();if(e)break;a+=r.decode(t,{stream:!0});const s=a.split("\n");a=s.pop()??"";for(const e of s)if(!o(e))return void await n.cancel().catch(()=>{})}a+=r.decode(),a&&o(a)}finally{n.releaseLock()}}function Mt(e,...t){if(e)try{return e(...t)}catch(e){return void console.error("A chat panel host callback threw",e)}}const Lt=e=>e.some(e=>"error"===e.uploadStatus);function Rt(e){if(e.slug&&/^[\w-]+$/.test(e.slug))return e.slug;return e.name.toLowerCase().replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")||null}function $t(e,t){const n=[];for(const r of ie(t))for(const t of e)t.key.toLowerCase()!==r||n.includes(t.agentId)||n.push(t.agentId);return n}const Dt=r({fetch:(e,t)=>globalThis.fetch(e,t),sessionEnded:()=>{}}),jt=Dt.Provider;function zt(){return a(Dt).fetch}const Ot=(e,t)=>It(e,`${Ct}${t??"new"}`),Pt=(e,t)=>It(e,`${St}${t??"new"}`);function Ut(e,t){try{const n=JSON.parse(At("session",Pt(e,t))??"[]");return Array.isArray(n)?n.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.conversationId&&"string"==typeof e.key&&"string"==typeof e.title):[]}catch{return[]}}function Ht(e,t,n,r){_t("session",Ot(e,t),n),_t("session",Pt(e,t),r.length>0?JSON.stringify(r):null)}function Wt(e,t){const n=At("session",Ot(e,t))??"";return{text:n,refs:le(Ut(e,t),n)}}const qt=new Set(["wait_status","tool_progress","consult_progress"]),Bt=new Set(["status","stream","done","approval_required","error","cancelled"]),Ft=new Set(["mentioned_agent_ids","content","conversation_id","agent_slug","supports_tool_approval","supports_page_actions","supports_artifacts","referenced_conversation_ids","file_ids","context"]);function Vt(e,t,n,r){return{...e,content:n,timestamp:r,toolNames:t.toolNames,toolCallCount:t.toolCallCount,iterations:t.iterations,attachments:t.attachments,artifacts:t.artifacts,reasoning:t.reasoning,toolCallTrace:t.toolCallTrace,transferChain:t.transferChain,isTruncated:t.isTruncated,agentName:t.answeredBy?.agentName??e.agentName,answeredBy:t.answeredBy,mentionFailed:t.mentionFailed,serverId:t.messageId??e.serverId,raw:t.raw??e.raw}}const Kt=["toolNames","toolCallCount","iterations","attachments","artifacts","reasoning","toolCallTrace","transferChain","isTruncated","agentName","answeredBy","mentionFailed","feedback"],Gt=Symbol("sentText");function Jt(e,t){return t===e.content?e:{...e,[Gt]:t}}function Yt(e){return e[Gt]??e.content}const Xt=e=>`${e.role}\0${"user"===e.role?Yt(e):e.content}`,Zt=e=>`${e.role}\0${e.content}`;function Qt(e,t){const n={...e,serverId:t.serverId??e.serverId,raw:t.raw??e.raw};if("assistant"!==e.role)return n;const r=n;for(const e of Kt)void 0!==t[e]&&(r[e]=t[e]);return n}const en=(e,t)=>[e,t].filter(Boolean).join("\n\n"),tn=(e,t)=>void 0!==e.displayText||void 0!==t.displayText?en(e.displayText??e.text,t.displayText??t.text):void 0;function nn(e,t){const n=new Set(e.refs.map(e=>e.conversationId)),r=new Set(e.mentions.map(e=>e.agentId));return{text:en(e.text,t.text),draft:en(e.draft,t.draft),files:[...e.files,...t.files],refs:[...e.refs,...t.refs.filter(e=>!n.has(e.conversationId))],mentions:[...e.mentions,...t.mentions.filter(e=>!r.has(e.agentId))],extras:e.extras||t.extras?{...e.extras,...t.extras}:void 0,displayText:tn(e,t)}}const rn={text:"",draft:"",files:[],refs:[],mentions:[]};function an(e){return{...e.reduce(nn,rn),parts:e}}function on(e,t){return an([...e?.parts??[],t])}function sn(e){for(const t of e)Mt(t.onNotSent)}function ln(e,t,n){if(!1===t)return null;const r=t&&"object"==typeof t?t:void 0,a=("string"==typeof r?.text?r.text:e).trim(),o="string"==typeof r?.displayText?r.displayText.trim():"",s="string"==typeof n?n.trim():"";return{text:a,displayText:o||s||a,extras:r?.extras}}function cn(e){return"error"===e.action||"cancelled"===e.action||"done"===e.action&&!e.intermediate?e:null}function dn(e){return("error"===e.action||"cancelled"===e.action)&&!!e.provisional}function un(e){const t=Mt(e);return t&&"object"==typeof t?t:{}}const pn=52428800;function hn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t].serverId;if(n)return n}return null}function gn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:r,requestHeaders:a,pageContext:c,onRelativeLinkClick:d,t:u,maxFileCount:p=10,maxTotalSize:h=52428800,storageKeyPrefix:g,controlledConversationId:m,onConversationIdChange:f,getRequestExtras:v,onStreamEvent:w,onSessionEnded:y,onConversationTitle:x,historySettledFor:b=null,steerAttachments:k=!1,holdSends:N=!1,agentMentionsEnabled:C=!1,onBeforeSend:S,onHeldSendSettled:I}){const T=zt(),A="legacy"===n,[_,E]=o([]),[M,L]=o(!1),[R,$]=o(null),[D,j]=o(null),z=void 0!==m,O=It(g,yt),P=It(g,xt),[U,H]=o(()=>z?m??null:At("local",O)),[W]=o(()=>Wt(g,U)),[q,B]=o(W.text),[F,V]=o(W.refs),[K,G]=o([]),[J,Y]=o([]),[Z,Q]=o(null),[ee,te]=o(null),[ne,re]=o(null),[ae,oe]=o(!1),[se,de]=o(null),[pe,he]=o(!1),[ge,me]=o(0),[fe,ve]=o(0),[we,ye]=o(()=>At("local",P)),xe=s(!1),Ce=s(null),Se=s(null),Ie=s(null),Te=s(!1),Ae=s(null),_e=s(null),Ee=s(null),Me=s(null),Le=s(null),Re=s(!1),[De,je]=o(null),Pe=s(De);Pe.current=De;const[Ue,Fe]=o(null),Ve=s(!1),Ge=s(new Map),Je=s(null),[Ye,Xe]=o(!1),Ze=s(null),Qe=s(!1),et=s("off"),tt=s(0),at=s(null),dt=s(null),gt=s(null),mt=s(null),[bt,kt]=o(!1),Nt=e=>{const t=mt.current?.readBack;t&&e!==mt.current&&window.clearTimeout(t.timer),mt.current=e,kt(null!==e)},Ct=s(_);Ct.current=_;const St=s(0),[Tt,Rt]=o(()=>Ne()),Dt=s(null),jt=s(null),Ot=()=>{null!==Dt.current&&window.clearTimeout(Dt.current),Dt.current=null,jt.current=null},Pt=e=>{Je.current&&window.clearTimeout(Je.current.timer);const t={timer:0,relayed:e};return t.timer=window.setTimeout(()=>Ut(t),5e3),Je.current=t,Xe(!0),t},Ut=e=>{const t=Je.current;!t||e&&e!==t||(window.clearTimeout(t.timer),Je.current=null,Xe(!1))},Kt=()=>{Je.current?.relayed&&Ut()},Gt=s(v);Gt.current=v;const en=s(w);en.current=w;const tn=s(y);tn.current=y;const nn=s(x);nn.current=x;const rn=s(S);rn.current=S;const gn=s(I);gn.current=I;const mn=s(U),fn=s(M);fn.current=M;const vn=e=>{fn.current&&$(e),fn.current=!1,L(!1),Ve.current||Fe(null)},wn=s(c);wn.current=c;const yn=s(new Map),xn=s(d);xn.current=d;const bn=s(a);bn.current=a;const kn=s(null),Nn=s(!1),Cn=s(null),Sn=s(0),[In]=o(qe),Tn=s(null),[An,_n]=o(null),En=s(new AbortController),Mn=Number.isFinite(p)&&p>0?Math.floor(p):10,Ln=Number.isFinite(h)&&h>0?h:pn;i(()=>{V(e=>le(e,q)),G(e=>function(e,t){if(0===e.length)return e;const n=new Set(ie(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}(e,q))},[q]);const Rn=l(e=>{G(t=>{return r=e,(n=t).some(e=>e.agentId===r.agentId)?n:[...n,r];var n,r})},[]),$n=l(e=>{V(t=>{return r=e,(n=t).some(e=>e.conversationId===r.conversationId)?n:[...n,r];var n,r})},[]),Dn=({draft:e,files:t,refs:n,mentions:r},{before:a})=>{e&&B(t=>t?a?`${e}\n${t}`:`${t}\n\n${e}`:e),t.length>0&&Y(e=>a?[...t,...e]:[...e,...t]),n.length>0&&V(e=>{const t=n.filter(t=>!e.some(e=>e.conversationId===t.conversationId));return a?[...t,...e]:[...e,...t]}),r.length>0&&G(e=>{const t=r.filter(t=>!e.some(e=>e.agentId===t.agentId));return a?[...t,...e]:[...e,...t]})},jn=()=>A||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,zn=()=>X(e,t,n,"approve"),On=s(zn);On.current=zn;const Pn=async e=>{const t=Kn(e);if(!t)return null;try{const e=await T(t,{headers:{...a??{}}});if(!e.ok)return null;const n=await e.json();return{proposals:$e(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Un=l(()=>{xe.current=!1,St.current+=1,me(St.current)},[]),Hn=()=>A||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,Wn=()=>X(e,t,n,"cancel"),qn=()=>X(e,t,n,"skipWait"),Bn=X(e,t,n,"events"),Fn=!!Bn,Vn=X(e,t,n,"pendingApprovals"),Kn=e=>Vn?`${Vn}/${encodeURIComponent(e)}/pending-approvals`:null,Gn=()=>Fn?{"X-Chat-Client-Id":Tt}:{},Jn=(e,t,n)=>T(e,{method:"POST",headers:{"Content-Type":"application/json",...bn.current??{},...Gn()},body:JSON.stringify({conversation_id:t,...n})}),Yn=()=>A||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`,Xn=s(f);Xn.current=f;const Zn=l((e,{notify:t=!0}={})=>{const n=mn.current!==e;mn.current=e,H(e),z||_t("local",O,e),n&&t&&Xn.current?.(e)},[z,O]),Qn=async e=>{if(mn.current)return mn.current;if(In.pending)return In.pending;const t=Yn();return t?In.run(async(n,r)=>{const o=Tn.current,s=await T(t,{method:"POST",headers:{"Content-Type":"application/json",...a??{}},body:JSON.stringify(o?{agent_slug:e,workspace_id:o}:{agent_slug:e}),signal:r});if(!s.ok||!n())return null;const i=await s.json();if(!n())return null;const l=i?.conversation_id??null;return l&&(xe.current=!0,Zn(l),Tn.current=null,_n(null)),l}):null},er=async(e,t,n)=>{const r=Hn(),o=new FormData;o.append("conversation_id",t),o.append("file",e,e.name);const s=a?Object.fromEntries(Object.entries(a).filter(([e])=>"content-type"!==e.toLowerCase())):void 0,i=await T(r,{method:"POST",headers:s,body:o,signal:n});if(!i.ok)throw new Error(`File upload failed: ${i.status}`);const l=(await i.json()).file_ids??[];if(0===l.length)throw new Error("No file_id returned");return l[0]},tr=e=>{if(!e||0===e.length||!Hn())return;const t=Array.from(e).map(e=>({file:e,tempId:Ne()}));let n=[];Y(e=>{const r=e.length,a=e.reduce((e,t)=>e+t.size,0),o=Mn-r;if(o<=0)return e;let s=Ln-a;const i=[];for(const e of t.slice(0,o))e.file.size<=s&&(i.push(e),s-=e.file.size);if(0===i.length)return e;n=i;const l=i.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=En.current.signal;for(const{file:t,tempId:a}of n)(async()=>{try{const n=await Qn(r);if(!n)return void Y(e=>e.map(e=>e.fileId===a?{...e,uploadStatus:"error"}:e));const o=await er(t,n,e);Y(e=>e.map(e=>e.fileId===a?{...e,fileId:o,uploadStatus:"done"}:e))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;Y(e=>e.map(e=>e.fileId===a?{...e,uploadStatus:"error"}:e))}})()},0)},nr=async(e,t,n)=>{const r=On.current(),a=n??mn.current;if(!r||!a||"undefined"==typeof document)return;const o=Se.current?.signal,s=async t=>{try{await T(r,{method:"POST",headers:{"Content-Type":"application/json",...bn.current??{},...Gn()},body:JSON.stringify({conversation_id:a,page_action:{action_id:e,ok:!1,error:t,url:"",title:"",snapshot:""}})})}catch{}};if(o?.aborted)return s("panel_closed");if(!Be(r,xn.current))return s("page_actions_not_supported");j(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await nt(t,yn.current,xn.current,document,o);if(o?.aborted)return s("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,s=o?.MutationObserver??globalThis.MutationObserver;let i;const l=()=>{clearTimeout(i),clearTimeout(d),c?.disconnect(),r?.removeEventListener("abort",l),a()},c=s?new s(e=>{e.some(e=>!Ke(e.target))&&(clearTimeout(i),i=setTimeout(l,t))}):null;c?.observe(e.body??e.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),i=setTimeout(l,t);const d=setTimeout(l,n);r?.addEventListener("abort",l)})}(document,{signal:o}),o?.aborted)return s("panel_closed");let i={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=ct(e.title).slice(0,80),o=Math.max(0,t-12);let s=!1,i=`# ${a} — ${r}`;i.length>o&&(i=i.slice(0,o),s=!0);const l=[i];let c=i.length;const d=new Map,u=e=>{for(const t of Array.from(e.children)){if(wt(t))continue;const e=st(t),n=it(t);let r=null;if(e){const n=`e${d.size+1}`,a=ft(t,e),i=ht(t);if(r=`[${n}] ${e} ${pt(ut(t,e))}${i.length?` (${i.join(", ")})`:""}${a?` = ${pt(a)}`:""}${vt(t)}`,c+r.length+1>o)return s=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${pt(ct(lt(t)))} (level ${n})`,c+r.length+1>o))return s=!0,!1;if(r&&(l.push(r),c+=r.length+1),(!e||ot(t))&&!u(t))return!1}return!0};return e.body&&!s&&u(e.body),s&&l.push(rt),{text:l.join("\n"),url:r,title:a,refs:d}}(document);yn.current=e.refs,i={text:e.text,url:e.url,title:e.title}}catch(e){yn.current=new Map,l=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await T(r,{method:"POST",headers:{"Content-Type":"application/json",...bn.current??{},...Gn()},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:i.url,title:i.title,snapshot:i.text}})})}catch{}finally{o?.aborted||j(e=>"acting_on_page"===e?.status?{...e,status:"thinking"}:e)}},rr=(e,t)=>{let n=e;const r=[e];let a="",o=!1,s=!1,i=null;const l=function(e){let t=!1,n="",r=null,a=!1;const o=()=>{null!==r&&cancelAnimationFrame(r),r=null},s=()=>{if(o(),!t&&!n)return;const r=t,a=n;t=!1,n="",e(r,a)},i=()=>{null===r&&("function"==typeof requestAnimationFrame?r=requestAnimationFrame(()=>{r=null,s()}):s())};return{text:()=>{a||(t=!0,i())},thinking:e=>{a||(n+=e,i())},flush:s,close:()=>{a=!0,o(),t=!1,n=""}}}((e,t)=>{if(e){const e=n,t=a;j(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),E(n=>n.map(n=>n.id===e?{...n,content:t}:n))}t&&j(e=>({...e,status:e?.status??"thinking",thinkingContent:(e?.thinkingContent??"")+t}))}),c=()=>{if(!o)return;l.flush(),o=!1,s=!1,a="",n=Ne(),r.push(n);const e=n;E(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),j({status:"thinking"})};return{ctx:{hasUsedTools:!1,activeNodeId:""},deltas:l,apply:e=>{switch(tt.current+=1,e.action){case"status":return(e=>{c();const t=n;if(e.contextUsage&&te(e.contextUsage),"thinking_text"===e.status)return void l.thinking(e.thinkingContent??"");l.flush();const r="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;e.resumed?(a="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),j({status:"thinking",elapsedS:e.elapsedS,elapsedStartMs:r})):"stream_retract"===e.status?(a="",E(e=>e.map(e=>e.id===t?{...e,content:""}:e)),j(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}))):"tool_heartbeat"===e.status?j(t=>t?{...t,elapsedS:e.elapsedS,elapsedStartMs:r}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:r}):"wait_start"===e.status?j(t=>({status:"wait_start",thinkingContent:t?.thinkingContent,waitSeconds:e.waitSeconds,waitReason:e.waitReason,waitStartMs:Date.now()})):j(t=>"wait_start"===t?.status&&qt.has(e.status)?t:{status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent})})(e),"continue";case"stream":return c(),a+=e.content,l.text(),"continue";case"done":return(e=>{l.flush(),o=!0,e.intermediate||(s=!0),re(null),de(null),ar(e,t);const r=n,i=e.content||a,c=new Date;or(r,e.messageId,t=>Vt(t,e,i,c))})(e),t&&!e.intermediate?"end":"continue";case"approval_required":return l.flush(),kn.current=e.conversationId??mn.current,Nn.current=!1,de(null),re(e.proposals),j(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"}),"continue";case"error":{c(),l.flush();const t=n;return i="error",E(n=>n.map(n=>n.id===t?{...n,content:e.content||u("Sorry, an error occurred. Please try again.")}:n)),"end"}case"cancelled":{l.flush(),i="cancelled";const e=n;return E(t=>t.map(t=>t.id===e?{...t,stopped:!0}:t)),"end"}case"session_ended":{l.flush(),i="session";const e=n;return E(t=>t.filter(t=>!(t.id===e&&!t.content))),"end"}default:return"continue"}},currentAssistantId:()=>n,accumulated:()=>a,doneReceived:()=>o,segmentIds:()=>r,ended:()=>i,outcome:()=>"error"===i?"failed":null===i&&s?"answered":"stopped"}},ar=(e,t)=>{e.conversationId&&!t&&Zn(e.conversationId),e.contextUsage&&te(e.contextUsage),e.transferAgentId&&e.transferAgentName&&Q({id:e.transferAgentId,name:e.transferAgentName})},or=(e,t,n)=>{E(r=>t&&r.some(n=>n.id!==e&&n.serverId===t)?r.filter(t=>t.id!==e):r.map(t=>t.id===e?n(t):t))},sr=(e,t,n)=>{const r=cn(t),a=r?.messageId;if(!r||!a)return!1;"done"!==r.action||fn.current||ar(r,n);const o=new Date;return or(e,a,e=>"done"===r.action?Vt(e,r,r.content||e.content,o):{...e,serverId:a,raw:r.raw??e.raw}),!0},ir=(e,t,n,r)=>{let a;try{a=e(t,n)}catch{a=void 0}return Mt(en.current,t,function(e,t){const n={relayed:e};if(!t)return n;const r=cn(t);return r&&dn(r)?n.end="provisional":r?.messageId&&(n.end="stored"),"status"===t.action&&t.resumed&&(n.replayed=!0),n}(r,a)),"session_ended"===a?.action&&Mt(tn.current,a.reason),a},lr=e=>{switch(e.action){case"user_message":{const t=e.message;return E(e=>{if(t.serverId&&e.some(e=>e.serverId===t.serverId))return e;let n=e.length-1;for(;n>=0&&("user"!==e[n].role||e[n].serverId||Yt(e[n])!==t.content);)n-=1;return n>=0&&e.length-n<=3?e.map((e,r)=>r===n?{...e,serverId:t.serverId,raw:t.raw}:e):[...e,t]}),!0}case"conversation_title":return nn.current?.(e.conversationId??mn.current,e.title),!0;case"approval_resolved":return re(null),de(null),!0;default:return!1}},cr=e=>{Tr(),vn(e),j(null),re(null),de(null),kn.current=null,Nn.current=!1,Cn.current=mn.current},dr=async o=>{const s=!o,i=o?o.text:q,l=s?q:o?.draft??"",c=s?J:o?.files??[];if(!i.trim()&&0===c.length)return"dropped";const d=s?"composer":o?.source??"host",p=!fn.current&&(null!==Je.current||null!==mt.current),h=fn.current||null!==mt.current,g=!o?.decided&&h&&rn.current?{text:i,source:d,extras:o?.extras,displayText:o?.displayText}:void 0,m=ln(i,o?.decided?void 0:Mt(rn.current,{text:i,source:d,turnRunning:h}),o?.displayText);if(!m)return"dropped";Ve.current=!1,Fe(null);const f=m.extras,v=o?.extras||f?{...o?.extras,...f}:void 0,w=m.text,y=o?.decided?o.displayText?.trim()||w:m.displayText,x=y!==w?y:void 0,b=s?ue(e,t,n)?ce(F,q):[]:o?.refs??[],S=s?C?K:[]:o?.mentions??[],I=$t(S,w);if(!w&&0===c.length)return"dropped";const _=()=>{s&&(B(""),V([]),G([]),Y([]))};if(fn.current||p){if(Lt(c))return"dropped";const e=c.every(e=>"done"===e.uploadStatus);if(!p&&!!jn()&&!!mn.current&&0===b.length&&0===I.length&&0===Object.keys(v??{}).length&&(0===c.length||k&&e)){_();const e=await(async(e,t,n,o=e)=>{const s=jn(),i=mn.current;if(!s||!i)return{result:"failed"};const l=Jt({id:Ne(),role:"user",content:o,timestamp:new Date,files:t.length>0?t:void 0},e);E(e=>[...e,l]);const c=t.filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId);let d=null;try{const t=await T(s,{method:"POST",headers:{"Content-Type":"application/json",...a??{},...Gn()},body:JSON.stringify({conversation_id:i,content:e,agent_slug:r,...c.length>0?{file_ids:c}:{}})});if(t.ok){const e=await t.json().catch(()=>null),n=e&&"object"==typeof e?e:{},r=n.turn_id;return{result:"ok",turnId:"string"==typeof r&&r?r:null,unanswered:!1===n.answered}}if(E(e=>e.filter(e=>e.id!==l.id)),409===t.status&&N)return{result:"ended"};409!==t.status&&(d=await be(t))}catch{E(e=>e.filter(e=>e.id!==l.id))}return null!==n&&Dn({draft:n,files:t,refs:[],mentions:[]},{before:!0}),{result:"failed",detail:d}})(w,c,s?l:null,y);return"ended"===e.result?(je(e=>on(e,{text:w,draft:l,files:c,refs:[],mentions:[],extras:v,displayText:x,asked:g,onSent:o?.onSent,onNotSent:o?.onNotSent})),"held"):"ok"===e.result?(e.unanswered&&(Ve.current=!0,Fe(u("This message will be read with your next one."))),o?.onSteered?.(e.turnId,e.unanswered),"steered"):(e.detail&&Fe(e.detail),"failed")}return(N||p)&&e?(_(),je(e=>on(e,{text:w,draft:l,files:c,refs:b,mentions:S,extras:v,displayText:x,asked:g,onSent:o?.onSent,onNotSent:o?.onNotSent})),"held"):"dropped"}const M=Jt({id:Ne(),role:"user",content:y,timestamp:new Date,files:c.length>0?[...c]:void 0,conversationRefs:b.length>0?b:void 0},w),R=Ne();E(e=>[...e,M,{id:R,role:"assistant",content:"",timestamp:new Date}]),_(),fn.current=!0,L(!0),j({status:"thinking"});const $=In.generation,D=rr(R,!1);Ie.current=D.deltas,Me.current=D,Re.current=!1,Te.current=!0,Ae.current=null,Qe.current=!1;let z=!1,O=!1,U=!1,H=!1,W=!1,X=!1,Z=null;const Q=()=>{if(!Fn||!mn.current||!Ae.current||D.ended())return!1;if(z=!0,!D.doneReceived()){const e=D.currentAssistantId();E(t=>t.filter(t=>t.id!==e))}return jt.current=Ae.current,Ae.current=null,Rt(Ne()),null!==Dt.current&&window.clearTimeout(Dt.current),Dt.current=window.setTimeout(()=>{Dt.current=null,_e.current||null===jt.current||(jt.current=null,vn("stopped"),j(null),Un())},15e3),!0},ee=new AbortController;Se.current?.abort();const te=new AbortController,ne=()=>{X||(X=!0,D.deltas.close(),Ie.current===D.deltas&&(Ie.current=null),Me.current===D&&(Me.current=null),Te.current=!1,Se.current===te&&te.abort(),Ce.current===ee&&(Ce.current=null),In.generation!==$||z||cr(U?"failed":D.outcome()))};try{Ce.current=ee,Se.current=te;const s=(M.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),i=!!(Wn()||qn()||Fn);if(!mn.current&&(Tn.current||i)){const e=In.generation,t=await Qn(r);if(In.generation!==e)return"dropped";t||(Tn.current=null,_n(null))}const l=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??Ne(),runId:Ne(),messages:[{id:Ne(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={...Object.fromEntries(Object.entries(n.extras??{}).filter(([e])=>!Ft.has(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,w,{legacyChatId:we,conversationId:mn.current,agentSlug:r,pageContext:wn.current,supportsToolApproval:null!==zn(),referencedConversationIds:b.map(e=>e.conversationId),supportsPageActions:Be(zn(),xn.current),extras:{...un(Gt.current),...v??{}}});s.length>0&&(l.file_ids=s),I.length>0&&(l.mentioned_agent_ids=I);const c=await T(A||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...a??{},...Gn()},body:JSON.stringify(l),signal:ee.signal});if(!c.ok||!c.body){const e=c.ok?null:await be(c);return U=!0,E(t=>t.map(t=>t.id===R?{...t,content:e??u("Unable to connect. Please check the configuration.")}:t)),"failed"}O=!0,o?.onSent?.();const d=function(e){switch(e){case"legacy":return He;case"ag-ui":return We;default:return ze}}(n);if(await Et(c.body,e=>{const t=ir(d,e,D.ctx,!1);if(!t)return!0;try{return W?In.generation===$&&(!!lr(t)||!sr(D.currentAssistantId(),t,!1)):(Qe.current||Me.current!==D||(Qe.current=!0,"resend"===et.current&&(et.current="off",null!==Ee.current&&_r(Ee.current))),!Ae.current&&"string"==typeof e.turn_id&&e.turn_id&&(Ae.current=e.turn_id),"folded"===t.action?(t.turnId&&(Ae.current=t.turnId),!0):!!lr(t)||("set_chat_id"===t.action?(ye(t.chatId),_t("local",P,t.chatId),!0):"page_action_required"===t.action?(D.deltas.flush(),nr(t.actionId,t.pageAction,t.conversationId),!0):(("session_ended"===t.action||cn(t))&&(H=!0),"end"!==D.apply(t)||!!dn(t)&&(D.deltas.flush(),W=!0,i&&(Z=Pt(!1)),Ze.current=ee,ne(),!0))))}catch{return!0}}),D.deltas.flush(),!z&&!H&&Q())return"sent";if(!z&&!D.ended()&&D.accumulated()&&!D.doneReceived()){const e=D.currentAssistantId(),t=D.accumulated();E(n=>n.map(n=>n.id===e?{...n,content:t||u("No response.")}:n))}}catch(e){if(D.deltas.close(),X)return"sent";if(e instanceof DOMException&&"AbortError"===e.name)return O?"sent":"dropped";const t=D.currentAssistantId();if(Q())return"sent";O||(U=!0),E(e=>e.map(e=>e.id===t?{...e,content:u("Sorry, an error occurred. Please try again.")}:e))}finally{ne(),Z&&Ut(Z),Ze.current===ee&&(Ze.current=null)}return O?"sent":"failed"},ur=()=>{const e=_e.current;if(!e)return;_e.current=null,e.renderer.deltas.flush(),e.renderer.deltas.close(),Ie.current===e.renderer.deltas&&(Ie.current=null),Me.current===e.renderer&&(Me.current=null);const t=e.renderer.currentAssistantId();E(e=>e.filter(e=>!(e.id===t&&!e.content&&!e.stopped))),cr(e.renderer.outcome())},pr=s(ur);pr.current=ur;const hr=()=>{const e=_e.current;if(!e)return;const t=e.renderer.doneReceived()?null:e.renderer.currentAssistantId();ur(),Nt({turnId:e.turnId,shownUpTo:hn(Ct.current)}),t&&E(e=>e.filter(e=>e.id!==t))},gr=s(hr);gr.current=hr;const mr=e=>{mt.current&&(Nt(null),e&&$(e))},fr=s(mr);fr.current=mr;const vr=()=>{dt.current&&window.clearTimeout(dt.current.timer),dt.current=null},wr=()=>{vr();const e=_e.current;if(e){const t=hn(Ct.current);ur(),Nt({turnId:e.turnId,shownUpTo:t})}const t=mt.current;if(!t||t.readBack)return;if(!Yn())return void mr("stopped");Un();const n=window.setTimeout(()=>{mt.current===t&&mr("stopped")},1e4);t.readBack={from:St.current,timer:n}},yr=s(wr);yr.current=wr;const xr=()=>{const e=_e.current,t=mt.current;if(!e&&t&&(t.readBack||dt.current?.turn===t))return;vr();const n=e??t;if(!n)return;const r=window.setTimeout(()=>{dt.current=null,(e?_e.current===e:mt.current===t)&&wr()},5e3);dt.current={turn:n,timer:r}},br=s(xr);br.current=xr;const kr=s(new Set),Nr=e=>{let t=_e.current;const n=ir(ze,e,t?.renderer.ctx??{hasUsedTools:!1,activeNodeId:""},!0);if(!n)return;if(lr(n))return;if("session_ended"===n.action)return ur(),mr("stopped"),void(null===jt.current||Te.current||(Ot(),vn("stopped"),j(null)));if(!Bt.has(n.action))return;const r="string"==typeof e.turn_id&&e.turn_id?e.turn_id:null;if(!r)return a=String(e.type),void(kr.current.has(a)||(kr.current.add(a),console.warn(`A "${a}" frame of the event stream names no turn and is not read: the events route needs \`turn_id\` on every turn frame (see "Turns that outlive their stream" in the README)`)));var a;const o=Ge.current.get(r);if(void 0!==o)return void(sr(o,n,!0)&&(Ge.current.delete(r),Kt()));if(Te.current||r===Ae.current)return;if(r===Le.current)return;const s=dt.current;if(s)if(vr(),t&&t===s.turn&&r!==t.turnId){const e=t.renderer.doneReceived()?null:t.renderer.currentAssistantId();ur(),e&&E(t=>t.filter(t=>t.id!==e)),Un(),t=null}else t&&t===s.turn&&(gt.current=t.renderer,Un());let i=t;if(i&&i.turnId!==r&&(ur(),i=null),!i){const t=mt.current,a=t?.turnId===r;if(("cancelled"===n.action||"error"===n.action)&&!a)return void(t&&wr());t&&!a&&(mr(),Un());const o=Ne();E(e=>[...e,{id:o,role:"assistant",content:"",timestamp:new Date}]),i={turnId:r,renderer:rr(o,!0)},_e.current=i,Kt(),Ie.current=i.renderer.deltas,Me.current=i.renderer,Nt(null);const s=r===jt.current||a;!0===e.resumed&&s&&(gt.current=i.renderer,Un()),Ot(),Re.current=!1,fn.current=!0,L(!0),j({status:"thinking"})}if("end"===i.renderer.apply(n)){if(dn(n)){const e=Ge.current;for(e.set(i.turnId,i.renderer.currentAssistantId());e.size>20;)e.delete(e.keys().next().value);Pt(!0)}ur()}},Cr=s(Nr);Cr.current=Nr;const Sr=()=>{const e=Pe.current;e&&(gn.current?.(e.text,"cancelled"),sn(e.parts)),je(null)},Ir=(e,t)=>{const n="string"==typeof e&&e?e:null;Tn.current=n,_n(n),Ie.current?.close(),Ie.current=null,Ce.current?.abort(),Ce.current=null,Se.current?.abort(),Se.current=null,En.current.abort(),En.current=new AbortController,In.abandon(),_e.current?.renderer.deltas.close(),_e.current=null,vr(),gt.current=null,Nt(null),Ge.current.clear(),Ze.current?.abort(),Ze.current=null,Ut(),Te.current=!1,Sr(),Tr(),Ot(),Ve.current=!1,vn("stopped"),E([]),B(""),V([]),G([]),Y([]),j(null),Q(null),te(null),re(null),de(null),he(!1),kn.current=null,Nn.current=!1,Cn.current=null,xe.current=!1,A?(ye(null),_t("local",P,null)):Zn(null,{notify:t})},Tr=()=>{null!==Ee.current&&window.clearTimeout(Ee.current),Ee.current=null,et.current="off",at.current=null},Ar=(e=!0)=>{Tr();const t=Me.current;Me.current=null;const n=_e.current,r=n?.turnId??jt.current;r&&(Le.current=r),Ot(),Ie.current?.flush(),Ie.current?.close(),Ie.current=null,Ce.current?.abort(),Ce.current=null,Se.current?.abort(),Se.current=null,_e.current=null,vn("stopped"),j(null),re(null),de(null),he(!1),kn.current=null,Nn.current=!1,yn.current=new Map;const a=e?t?.currentAssistantId():void 0;E(e=>e.map(e=>e.id===a?{...e,stopped:!0}:e).filter(e=>!("assistant"===e.role&&!e.content&&!e.stopped)))},_r=e=>{const t=Wn(),n=mn.current;if(!t||!n)return;const r=Te.current&&!Qe.current;r&&(et.current="asked");const a=()=>Ee.current===e;Jn(t,n,r?{awaiting_send:!0}:void 0).then(async t=>{if(t.ok){const n=await t.json().catch(()=>null);if(!a())return;const o=!!n&&"object"==typeof n&&"none"===n.turn;if(r)return void(o?Qe.current?(et.current="off",_r(e)):et.current="resend":et.current="off");if(!o)return;return Ar(),void Un()}const n=await be(t);if(!a())return;const o=at.current;Tr(),Re.current=!1,j(e=>"cancelling"!==e?.status?e:o&&tt.current===o.frameSeq?o.statusBefore:{...e,status:o?.statusBefore?.status??"thinking"}),o?.approvalsBefore&&re(e=>e??o.approvalsBefore),Fe(n??u("The response could not be stopped. Try again."))}).catch(()=>{a()&&Ar()})},Er=qn(),Mr=U&&b===U?(Lr=U,Bn?`${Bn}/${encodeURIComponent(Lr)}/events?client_id=${encodeURIComponent(Tt)}`:null):null;var Lr;const Rr=ke(a),$r=s(Rr);$r.current=Rr;const[Dr,jr]=o(null),[zr,Or]=o(0);i(()=>{Dr&&Dr.url===Mr&&Dr.headersKey!==Rr&&(jr(null),Or(e=>e+1))},[Dr,Mr,Rr]),i(()=>{if(!Mr)return;let e=!1,t=!1,n=0,r=null,a=null,o=null,s=!1,i=!1;const l=async()=>{if(r=null,e||t)return;if("hidden"===document.visibilityState)return void(s&&(i=!0));t=!0,a=new AbortController;let o=!1,c=null;try{const t=$r.current,r=await T(Mr,{headers:{...bn.current??{},"X-Chat-Client-Id":Tt},signal:a.signal});if([401,403,404,405].includes(r.status))return o=!0,401!==r.status&&403!==r.status||e||jr({url:Mr,headersKey:t}),void(e||yr.current());if(!r.ok||!r.body)return;s&&br.current(),s=!0,c=Date.now(),await Et(r.body,e=>{n=0;try{Cr.current(e)}catch{}})}catch{}finally{if(t=!1,null!==c&&Date.now()-c>=5e3&&(n=0),!e&&!o&&!i){const e=Math.min(3e4,1e3*2**n);n+=1,r=window.setTimeout(()=>{l()},e*(.5+Math.random()/2))}}},c=()=>{o=null,e||"hidden"!==document.visibilityState||(i=!0,null!==r&&window.clearTimeout(r),r=null,a?.abort(),gr.current())},d=()=>{"hidden"!==document.visibilityState?(null!==o&&window.clearTimeout(o),o=null,"visible"===document.visibilityState&&(mt.current&&br.current(),t||(null!==r&&window.clearTimeout(r),n=0,i&&(i=!1,Un()),l()))):null===o&&(o=window.setTimeout(c,6e4))};return l(),document.addEventListener("visibilitychange",d),()=>{e=!0,null!==r&&window.clearTimeout(r),null!==o&&window.clearTimeout(o),a?.abort(),document.removeEventListener("visibilitychange",d),pr.current(),fr.current()}},[Mr,Tt,zr,Un]);const Pr=s([]),[Ur,Hr]=o(0),Wr=e=>{Pr.current.push(e),Hr(e=>e+1)};i(()=>{for(const e of Pr.current.splice(0))gn.current?.(e,"returned")},[Ur]),i(()=>{if(M||bt)return;if(Re.current&&(Re.current=!1,De))return je(null),sn(De.parts),De.draft||0!==De.files.length?(Wr(De.text),void Dn(De,{before:!0})):void gn.current?.(De.text,"dropped");if(Ye||!De)return;je(null);let e=!1;const t=t=>{e||(e=!0,gn.current?.(De.text,t))},n=[],r=[];for(const e of De.parts){const{asked:t}=e;if(!t){n.push(e);continue}const a=ln(t.text,Mt(rn.current,{text:t.text,source:t.source,turnRunning:!1,held:!0}),t.displayText);a?n.push({...e,text:a.text,displayText:a.displayText!==a.text?a.displayText:void 0,extras:t.extras||a.extras?{...t.extras,...a.extras}:void 0,asked:void 0}):r.push(e)}sn(r);const a=r.filter(e=>e.draft||e.files.length>0);for(const e of a)Dn(e,{before:!1});if(0===n.length)return void(a.length>0?Wr(De.text):t("dropped"));const{text:o,draft:s,files:i,refs:l,mentions:c,extras:d,displayText:u}=an(n);qr.current({text:o,draft:s,files:i,refs:l,mentions:c,extras:d,displayText:u,decided:!0,onSent:()=>{t("sent");for(const e of n)Mt(e.onSent)},onNotSent:()=>sn(n)}).then(e=>{if("held"===e)return;const r="sent"===e||"steered"===e;t(r?"sent":"failed"===e?"failed":"dropped"),r||sn(n)},()=>{t("failed"),sn(n)})},[M,bt,Ye,De]);const qr=s(dr);qr.current=dr,i(()=>{const e=window.setTimeout(()=>{Ht(g,U,q,F)},300);return()=>window.clearTimeout(e)},[q,U,F,g]),i(()=>()=>{Ie.current?.close(),Se.current?.abort(),Ze.current?.abort(),Je.current&&window.clearTimeout(Je.current.timer),null!==Dt.current&&window.clearTimeout(Dt.current),dt.current&&window.clearTimeout(dt.current.timer),Sr()},[]);const Br=s({conversationId:U,inputValue:q,conversationRefs:F});Br.current={conversationId:U,inputValue:q,conversationRefs:F},i(()=>()=>{const{conversationId:e,inputValue:t,conversationRefs:n}=Br.current;Ht(g,e,t,n)},[]),i(()=>{const e=U;if(!e||M)return;if(Cn.current===e)return;Kn(e)&&zn()&&(Cn.current=e,(async()=>{const t=await Pn(e);t?.proposals&&(mn.current!==e||fn.current||(kn.current=e,Nn.current=!0,de(null),re(t.proposals)))})())},[U,M]),i(()=>{if(!ne?.length||!Nn.current)return;const e=kn.current,t=e?Kn(e):null;if(!t)return;const n=window.setInterval(()=>{T(t,{headers:{...a??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[ne]),i(()=>{if(!pe)return;const e=kn.current;if(!e)return void he(!1);if(Date.now()>=Sn.current)return he(!1),void Un();let t=!1;const n=window.setTimeout(async()=>{const n=await Pn(e);if(!t){if(n)return n.proposals?(Nn.current=!0,de(null),re(n.proposals),void he(!1)):n.turnRunning?void ve(e=>e+1):(he(!1),void Un());ve(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[pe,fe,Un]);const Fr=M&&null!==jn()&&null!==U;return{messages:_,inputValue:q,setInputValue:B,isLoading:M,turnRunning:M||bt,sendsHeld:!M&&(Ye||bt),turnEnd:R,agentStatus:D,attachedFiles:J,conversationId:U,contextUsage:ee,transferredAgent:Z,canSteer:Fr,pendingApprovals:ne,isSubmittingApproval:ae,approvalError:se,submitApprovalDecisions:async e=>{const t=zn(),n=kn.current??mn.current;if(0!==e.length)if(t&&n){de(null),oe(!0);try{const r=await T(t,{method:"POST",headers:{"Content-Type":"application/json",...a??{},...Gn()},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 re(null),Nn.current&&!_e.current?(Nn.current=!1,Sn.current=Date.now()+9e5,void he(!0)):void j(e=>e?{...e,status:"thinking"}:{status:"thinking"});de(409===r.status?u("This turn is no longer waiting for a decision."):u("Could not send your decision. Please try again."))}catch{de(u("Could not send your decision. Please try again."))}finally{oe(!1)}}else de(u("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:pe,historyReloadNonce:ge,historyLoadedRef:xe,conversationIdRef:mn,handleFileAdd:tr,handlePaste:e=>{const{files:t}=e.clipboardData;t.length>0&&(e.preventDefault(),tr(t))},handleSendMessage:dr,skipWait:Er?async()=>{const e=qn(),t=mn.current;if(e&&t)try{(await Jn(e,t)).ok&&j(e=>"wait_start"===e?.status?{status:"thinking",thinkingContent:e.thinkingContent}:e)}catch{}}:null,readPendingApprovals:Vn?Pn:null,heldMessage:De,notice:Ue,cancelHeldMessage:Sr,reloadHistory:Un,mergeTurnHistory:e=>{const t=gt.current;if(gt.current=null,!t||Te.current)return!1;const n=new Set(t.segmentIds()),r=t.currentAssistantId();return E(t=>function(e,t,n,r){const a=e.findIndex(e=>n.has(e.id));if(a<0)return e;const o=e.slice(0,a),s=e.slice(a),i=new Set(o.map(e=>e.serverId).filter(Boolean));let l=-1;t.forEach((e,t)=>{e.serverId&&i.has(e.serverId)&&(l=t)});const c=new Map;for(const e of o)e.serverId||c.set(Xt(e),(c.get(Xt(e))??0)+1);const d=t.slice(l+1).filter(e=>{if(e.serverId&&i.has(e.serverId))return!1;const t=c.get(Zt(e))??0;return 0===t||(c.set(Zt(e),t-1),!1)});if(0===d.length)return e;const u=new Set,p=d.map(e=>{const t=s.find(t=>!u.has(t.id)&&!!e.serverId&&t.serverId===e.serverId)??s.find(t=>!u.has(t.id)&&t.id!==r&&!t.serverId&&Xt(t)===Zt(e));return t?(u.add(t.id),Qt(t,e)):{...e,id:Oe(e.serverId)}});return[...o,...p,...s.filter(e=>!u.has(e.id))]}(t,e,n,r)),!0},settleUnseenEnd:(e,t)=>{const n=mt.current;!n?.readBack||e<n.readBack.from||mr(t?function(e,t){const n=null===t?0:e.findIndex(e=>e.serverId===t)+1;return null!==t&&0===n?"stopped":e.slice(n).some(e=>"assistant"===e.role)?"answered":"stopped"}(t,n.shownUpTo):"stopped")},agentMentions:K,addAgentMention:Rn,handleNewChat:e=>Ir(e,!0),pendingWorkspaceId:An,clearPendingWorkspace:e=>{Tn.current===e&&(Tn.current=null,_n(null))},handleStopGenerating:()=>{const e=mt.current;if(!fn.current&&e){const t=Wn(),n=mn.current;return t&&n&&Jn(t,n).catch(()=>{}),Le.current=e.turnId,Re.current=!0,vr(),void mr("stopped")}if(!fn.current)return void Ar(!1);Re.current=!0;const t=Wn(),n=mn.current,r=null!==jt.current&&!_e.current;if(!t||!n||r)return t&&n&&Jn(t,n).catch(()=>{}),void Ar();if(null!==Ee.current)return;Ve.current=!1,Fe(null),re(null),de(null),j(e=>({...e,status:"cancelling"}));const a=window.setTimeout(()=>Ar(),1e4);Ee.current=a,at.current={statusBefore:D,approvalsBefore:ne,frameSeq:tt.current},_r(a)},conversationRefs:F,addConversationRef:$n,setAttachedFiles:Y,setMessages:E,setContextUsage:te,updateConversationId:Zn,handleSwitchConversation:e=>{if((A||e!==mn.current)&&(Ir(void 0,!1),!A)){Zn(e);const t=Wt(g,e);B(t.text),V(t.refs)}}}}function mn(e,t){if(t)return e.find(e=>e.id===t)??e.find(e=>e.slug===t)}function fn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,storageKeyPrefix:a,initialAgent:c,onAgentChange:d}){const u=zt(),p=null===t?.agents||!!t?.singleEndpoint||"legacy"===n,h=It(a,bt),[g,m]=o([]),[f,v]=o(!1),[w,y]=o(!1),[x,b]=o(p),[k,N]=o(0),C=l(()=>N(e=>e+1),[]),[S,I]=o(null),[T,A]=o(!1),_=s(0);i(()=>{if(p)return void b(!0);const n=`${e}${t?.agents??"/chat/agents"}`,a=++_.current,o=()=>a===_.current;v(!0),u(n,{headers:r}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}).then(e=>{if(!o())return;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(m(t),y(!1),0===t.length)return void I(null);const n=()=>{const e=At("local",h);return mn(t,c)??(e?t.find(t=>t.slug===e):void 0)??t[0]};I(e=>e?t.find(t=>t.id===e.id)??n():n())}).catch(()=>{o()&&(y(!0),0===k&&m([]))}).finally(()=>{o()&&(v(!1),b(!0))})},[e,t,n,r,p,k]);return{agents:g,agentsLoading:f,agentsError:w,agentsSettled:x,agentsDisabled:p,selectedAgent:S,setSelectedAgent:I,agentMenuOpen:T,setAgentMenuOpen:A,handleSwitchAgent:(e,t)=>{e.id!==S?.id?(I(e),e.slug&&_t("local",h,e.slug),A(!1),d?.(e),t?.()):A(!1)},reloadAgents:C}}function vn(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 wn=400;let yn=null,xn=null,bn=0;function kn(){null!==yn&&(window.clearInterval(yn),yn=null),null!==xn&&(document.title=xn,xn=null)}function Nn({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:a,isViewingChat:o}){const l=s(!1),c=s(0);i(()=>{if(!r||"undefined"==typeof document)return;bn+=1;const e=()=>{!document.hidden&&document.hasFocus()&&kn()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),bn=Math.max(0,bn-1),0===bn&&kn()}},[r]),i(()=>{const s=l.current;if(l.current=e,!e||s){if(!e&&s&&r){if(Date.now()-c.current<4e3)return;const e="undefined"!=typeof document&&document.hidden,r="undefined"!=typeof document&&!document.hasFocus(),s=e||r,i=!o||o();if(!s&&i)return;const l=n("Response ready"),d=t?A(n,"{agent} has finished",{agent:t}):n("Your answer is ready");s&&(function(e){if("undefined"==typeof document)return;null===xn&&(xn=document.title),null!==yn&&window.clearInterval(yn);let t=!0;document.title=e,yn=window.setInterval(()=>{t=!t,document.title=t?e:xn??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)),a?.(l,d)}}else c.current=Date.now()},[e,r,t,n,a,o])}function Cn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=zt(),[s,c]=o(null),[d,u]=o(null),p="rest"===n&&!t?.singleEndpoint,h=void 0===t?.prompts?"/chat/prompts":t.prompts,g=void 0===t?.quota?"/chat/quota":t.quota,m=p&&h?`${e}${h}`:null,f=p&&g?`${e}${g}`:null;i(()=>{if(!m)return void c(null);let e=!1;return a(m,{credentials:"include",headers:{...r??{}}}).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);c(n.length>0?n:null)}).catch(()=>{e||c(null)}),()=>{e=!0}},[m,r]);const[v,w]=o(0),y=l(()=>w(e=>e+1),[]);return i(()=>{if(!f)return void u(null);let e=!1;return a(f,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{e||u(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||u(null)}),()=>{e=!0}},[f,r,v]),{prompts:s,quota:d,refreshQuota:y}}function Sn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,agentSlug:a}){const s=zt(),[l,c]=o(null),[d,u]=o(!1),p="rest"===n&&!t?.singleEndpoint,h=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,g=p&&h?`${e}${h}`:null;return i(()=>{if(!g)return void c(null);let e=!1;u(!0);const t=a?`${g}?agent_slug=${encodeURIComponent(a)}`:g;return s(t,{credentials:"include",headers:{...r??{}}}).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);c(n.length>0?n:null)}).catch(()=>{e||c(null)}).finally(()=>{e||u(!1)}),()=>{e=!0}},[g,a,r]),{suggestions:l,loading:d}}function In(e){const t=s(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 Tn(e){const t=s(e);c(()=>{t.current=e});const n=l((...e)=>t.current?.(...e),[]);return e?n:void 0}function An(e,t){let n="idle",r=!1,a=!1,o=!1;const s=()=>"listening"===n||r,i=()=>{a||s()===o||(o=s(),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("")),i()},e.onend=()=>{if(t.onInterim(""),"listening"===n){if(l())return;n="idle"}else r?(r=!1,n=l()?"listening":"idle"):n="idle";i()},{toggle:()=>{a||(s()?(()=>{if(r=!1,"listening"===n){n="stopping",t.onInterim("");try{e.stop()}catch{n="idle"}}i()})():(l()?n="listening":"idle"!==n&&(r=!0),i()))},cancel:()=>{if(!a){if(r=!1,"listening"===n||"stopping"===n){n="discarding",t.onInterim("");try{e.abort()}catch{n="idle"}}i()}},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 _n(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const En=new Set(["thinking","status","stream","turn_started"]);function Mn(e,t){const n="string"==typeof t.turn_id&&""!==t.turn_id?t.turn_id:null;if(!0===t.relayed){if(null===e.turnId||n!==e.turnId)return{kind:"ignore"}}else{if("folded_into_active_turn"===t.type){if(null!==n)e.turnId=n,e.folded=!0;else if(!1===t.folded)return{kind:"failed"};return{kind:"progress"}}null!==n&&null===e.turnId&&(e.turnId=n)}const r=t.type;if("status"!==r||"transfer_start"!==t.status||"string"!=typeof t.agent_id||!t.agent_id||null!==n&&n!==e.turnId||(e.agentId=t.agent_id),"string"==typeof r&&En.has(r))return{kind:"progress"};if("done"===r){const n=function(e){return"string"==typeof e?e:""}(t.content),r=!0!==t.intermediate,a=function(e){const t=je(e.answered_by);return t?.agentId&&t.agentName?.trim()?{agentId:t.agentId,agentName:t.agentName}:null}(t);if(null!==a&&a.agentId!==e.agentId)return n&&e.others.push({...a,failed:!0===t.mention_failed,text:n}),r?{kind:"answer",text:e.segments.join("\n\n"),others:e.others}:{kind:"progress"};if(!r)return n&&(e.segments=e.folded?[n]:[...e.segments,n]),{kind:"progress"};return{kind:"answer",text:(e.folded?[n]:[...e.segments,n]).filter(Boolean).join("\n\n"),others:e.others}}return"cancelled"===r||"error"===r?{kind:"failed"}:{kind:"ignore"}}function Ln(e){return e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}const Rn=new Set(["no-speech","aborted"]);function $n(e){const t=e.setTimer??((e,t)=>window.setTimeout(e,t)),n=e.clearTimer??(e=>window.clearTimeout(e)),r=e.recognition;let a="listening",o=!1,s="",i=[],l="",c=null,d=!1,u=0,p=null,h="",g=null,m=null,f=null,v=null,w=!1,y=!1,x=0;const b=()=>e.onChange({phase:a,muted:o,heard:s,lines:i}),k=e=>(null!==e&&n(e),null),N=()=>!o&&("listening"===a||"speaking"===a),C=()=>{if(N()){if(w||null!==v)return;try{r.start(),w=!0}catch{}}else if(w)try{r.stop()}catch{}},S=e=>{a=e,C(),b()},I=()=>{p?.abort(),p=null,h=""},T=()=>{g=k(g),f=k(f),l="",s="",S("listening")},A=()=>{m=k(m),c=null,d=!1},_=()=>{A(),S("error"),f=t(()=>{f=null,"error"===a&&T()},2e3)},E=()=>{m=k(m);const n=c;m=t(()=>{m=null,e.probe().then(e=>{c===n&&n&&("over"===e?_():E())})},12e4)},M=t=>{if(!c||!d)return;const n=Mn(c,t);"ignore"!==n.kind&&("answer"===n.kind?((t,n)=>{A();const r=e.present(t),o=function(e){const t=e.text.trim()?[{content:e.text}]:[];for(const n of e.others)n.text.trim()&&t.push({content:n.text,agent:{name:n.agentName,failed:n.failed}});return t}({text:r,others:n.map(t=>({...t,text:e.present(t.text)}))});i=[...i,...o.map(e=>({role:"assistant",...e}))];const c=r.trim()?e.speakable(r):"";if(!c.trim())return void T();const d=new AbortController;p=d,h=c,s="",l="",S("speaking"),e.speak(c,d.signal).catch(()=>{}).then(()=>{p===d&&(p=null,h="","speaking"===a&&T())})})(n.text,n.others):"failed"===n.kind?_():E())},L=()=>{u+=1,A()};return r.continuous=!0,r.interimResults=!0,e.lang&&(r.lang=e.lang),r.onresult=n=>{if(x=0,o||"listening"!==a&&"speaking"!==a)return;let r="",p="";for(let e=n.resultIndex;e<n.results.length;e++){const t=n.results[e];t.isFinal?r+=t[0].transcript:p+=t[0].transcript}if("speaking"===a){if(!function(e,t){const n=Ln(e);if(n.length<2)return!1;const r=new Set(Ln(t));return n.filter(e=>r.has(e)).length/n.length<.6}(`${r} ${p}`,h))return;I(),l="",a="listening"}r.trim()&&(l=[l,r.trim()].filter(Boolean).join(" ")),s=[l,p.trim()].filter(Boolean).join(" "),g=k(g),l&&(g=t(()=>{g=null,"listening"===a&&!o&&l.trim()&&(t=>{const n=++u;g=k(g),l="",s="",i=[...i,{role:"user",content:t}],c=function(e=null){return{turnId:null,folded:!1,agentId:e,segments:[],others:[]}}(e.addressedAgentId()),d=!1,S("processing"),E();const r=()=>n===u&&null!==c;e.send(t,{onAccepted:()=>{r()&&(d=!0)},onNotSent:()=>{r()&&_()},onSteered:(e,t)=>{r()&&(d=!0,M(e?{type:"folded_into_active_turn",folded:!0,turn_id:e}:{type:"folded_into_active_turn",...t?{folded:!1}:{}}))}}).then(e=>{!r()||"dropped"!==e&&"failed"!==e||_()},()=>{r()&&_()})})(l.trim())},1e3)),b()},r.onerror=e=>{y=!0,Rn.has(e?.error??"")||(x+=1)},r.onend=()=>{w=!1;const e=y;if(y=!1,N())return x>=5?(x=0,o=!0,void b()):void(e?v=t(()=>{v=null,C()},300):C())},{start:T,end:()=>{if("ended"!==a){if(L(),I(),g=k(g),f=k(f),v=k(v),a="ended",r.onresult=null,r.onerror=null,r.onend=null,w)try{r.abort()}catch{}w=!1,b()}},frame:(e,t)=>M({...e,relayed:t||!0===e.relayed}),interrupt:()=>{"speaking"===a?(I(),T()):"processing"===a&&(L(),e.stopTurn(),T())},cancel:()=>{"processing"!==a&&"speaking"!==a||(L(),I(),T())},toggleMute:()=>{if("ended"!==a){if(o=!o,x=0,o)g=k(g),l="",s="";else if("speaking"===a)return I(),void T();C(),b()}}}}const Dn=()=>null!==_n();function jn(e,t){return new Promise(n=>{const r=URL.createObjectURL(e),a=new Audio(r),o=e=>{a.pause(),URL.revokeObjectURL(r),t.removeEventListener("abort",s),n(e)},s=()=>o(!0);a.onended=()=>o(!0),a.onerror=()=>o(!1),t.addEventListener("abort",s),a.play().catch(()=>o(!1))})}function zn(e,t,n){return"undefined"!=typeof window&&window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance?new Promise(r=>{const a=new SpeechSynthesisUtterance(e);t&&(a.lang=t);const o=()=>{n.removeEventListener("abort",s),r()},s=()=>{window.speechSynthesis.cancel(),o()};a.onend=o,a.onerror=o,n.addEventListener("abort",s),window.speechSynthesis.speak(a)}):Promise.resolve()}const On=({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"})]}),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("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"})]}),Un=({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"})}),Hn=({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"})]}),Wn=({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"})]}),qn=({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"})]}),Bn=({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"})}),Fn=({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"})}),Vn=({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"})}),Kn=({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"})]}),Gn=({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"})]}),Jn=({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"})]}),Yn=({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"})}),Xn=({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"})]}),Zn=({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"})]}),Qn=({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"})]}),er=({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"})]}),tr=({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"})]}),nr=({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"})}),rr=({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"})]}),ar=({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"})]}),or=({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"})]}),sr=({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"})]}),ir=({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"})]}),lr=({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"})]}),cr=({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"})]}),dr=({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"})]}),ur=({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"})]}),pr=({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"})]}),hr=({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"})]}),gr=({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"})}),mr=({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"})]}),fr=({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"})]}),vr=({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"})]}),wr=({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:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272"}),t("path",{d:"M22 2 2 22"}),t("path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473"})]}),yr=({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"})]}),xr=({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"})]}),br=({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"})]}),kr=({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"})}),Nr=({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"})]}),Cr=({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"})]}),Sr=({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"})]}),Ir=({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"})]}),Tr=({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"})]}),Ar=({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"})]}),_r="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",Er=({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:_r}),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"})]}),Mr=({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:_r}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),Lr=({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"})}),Rr=({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"})]});function $r({onClear:r,className:a,iconButtonClass:s,t:i}){const[l,c]=o(!1);return t("div",{className:`flex items-center gap-1 ${a}`,children:l?e(n,{children:[t("span",{className:"flex-1 text-[0.7rem] text-red-600 dark:text-red-400",children:i("Delete all conversations?")}),t("button",{type:"button",onClick:()=>{c(!1),r()},"aria-label":i("Delete all conversations"),className:`${s} hover:text-red-500`,children:t(Bn,{size:13})}),t("button",{type:"button",onClick:()=>c(!1),"aria-label":i("Cancel"),className:s,children:t(Kn,{size:13})})]}):e("button",{type:"button",onClick:()=>c(!0),className:"flex items-center gap-1.5 rounded-md px-1 py-0.5 text-[0.7rem] text-gray-400 dark:text-white/40 hover:text-red-500 dark:hover:text-red-400 transition-colors",children:[t(Tr,{size:12}),i("Clear all conversations")]})})}const Dr=({open:e,onClose:n,anchorRef:r,placement:a="bottom-start",width:c=280,children:u})=>{const p=s(null),[h,g]=o({top:0,left:0}),m=l(()=>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])}(p,m,e),d(()=>{if(!e||!r.current)return;const t=r.current.getBoundingClientRect(),n=p.current?.offsetHeight??0,o=window.innerHeight-t.bottom-8,s=t.top-8,i=n>0&&o<n&&s>o?Math.max(8,t.top-n-4):t.bottom+4,l="bottom-end"===a?t.right-c:t.left,d=Math.max(8,Math.min(l,window.innerWidth-c-8));g({top:i,left:d})},[e,r,a,c,u]),!e)return null;const f=_(r.current);return x(t("div",{ref:p,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:h.top,left:h.left,width:c},children:u}),f)},jr=({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 zr(e){return Math.max(e.maxRight-e.minLeft,0)}const Or=({title:n,children:r})=>{const a=s(null),i=s(null),[l,c]=o(null),[u,p]=o({below:!1,shift:0});if(d(()=>{if(!l||!i.current)return;const{width:e,height:t}=i.current.getBoundingClientRect();p(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}}(l,{width:e,height:t}))},[l,n]),!n)return r;const h=()=>{if(!a.current)return;const e=_(a.current).getBoundingClientRect();c(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}}(a.current.getBoundingClientRect(),e,window.innerWidth))};return e("span",{ref:a,className:"inline-flex",onMouseEnter:h,onMouseLeave:()=>c(null),onFocus:e=>{const t=e.target;"function"==typeof t.matches&&t.matches(":focus-visible")&&h()},onBlur:()=>c(null),children:[r,l&&x(t("span",{ref:i,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?l.bottom+4:l.top-4,left:l.center+u.shift,maxWidth:zr(l)},role:"tooltip",children:n}),_(a.current))]})},Pr=({icon:e,fallback:n})=>{const r=function(e){const t=e?.trim();return t?/^(https:\/\/|data:image\/)/i.test(t)?"image":t.length<=8&&!/[\p{L}\p{N}]/u.test(t)?"emoji":null:null}(e);return"image"===r?t("img",{src:e.trim(),alt:"",className:"w-4 h-4 rounded-sm object-cover"}):t("span","emoji"===r?{className:"text-sm leading-none",children:e.trim()}:{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:n})},Ur=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(tr,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(br,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(sr,{...e})}],Hr=({mode:r,agentName:a,agents:l,agentsLoading:c=!1,agentsError:d=!1,selectedAgent:p,transferredFrom:h,agentMenuOpen:g,onAgentMenuToggle:m,onAgentMenuClose:f,onSwitchAgent:v,modeMenuOpen:w,onModeMenuToggle:y,onModeMenuClose:x,onModeChange:b,onNewChat:k,onClose:N,logoIcon:C,agentDashboardUrl:S,historyEnabled:I=!1,historyMenuOpen:T=!1,onHistoryMenuToggle:_,onHistoryMenuClose:E,conversations:L=[],conversationsLoading:R=!1,activeConversationId:$=null,onSelectConversation:D,onDeleteConversation:j,onClearAll:z,actions:O,t:P})=>{const U=s(null),H=s(null),q=s(null),[B,F]=o("");i(()=>{g||F("")},[g]);const V=u(()=>{const e=B.trim().toLowerCase();return e?l.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):l},[l,B]),K=l.length>5,G="sidebar"===r?br:"fullscreen"===r?or:tr;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"===r?"rounded-t-xl":""),children:[e("div",{className:"min-w-0",children:[e("button",{ref:U,type:"button",onClick:m,className:"flex max-w-full 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 shrink-0 items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:C}),t("span",{className:"min-w-0 truncate",children:a}),t(Fn,{size:16,className:"shrink-0 text-gray-400 dark:text-white/30"})]}),h&&t("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal text-gray-400 dark:text-white/30",children:A(P,"Transferred from {agent}",{agent:h})})]}),e(Dr,{open:g,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:P("Switch to another agent")}),0===l.length&&c&&t("div",{className:"px-4 py-2",children:t(jr,{size:16})}),0===l.length&&!c&&d&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(On,{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:P("Could not reach the assistant service. Check the connection and try again.")})]}),0===l.length&&!c&&!d&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:P("Agent switching is not available here")}),K&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(yr,{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:B,onChange:e=>F(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f()},placeholder:P("Search agents..."),"aria-label":P("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===V.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:P("No agent matches")}),W(V).map(({group:n,agents:r})=>e("div",{role:"group","aria-label":n??void 0,children:[n&&t("span",{className:"block px-4 pt-2 pb-0.5 text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40",children:n}),r.map(n=>e("button",{type:"button",onClick:()=>v(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===p?.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(Pr,{icon:n.icon,fallback: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))]},n??""))]}),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(Qn,{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:P("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(Ar,{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:P("Create agent")})]})]})]}),t("div",{className:"flex-1"}),I&&e(n,{children:[t(Or,{title:P("Conversation history"),children:t("button",{ref:q,type:"button",onClick:_,"aria-label":P("Conversation history"),"aria-haspopup":"menu","aria-expanded":T,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(cr,{size:18})})}),e(Dr,{open:T,onClose:()=>E?.(),anchorRef:q,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:P("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[R&&0===L.length&&t("div",{className:"px-4 py-2",children:t(jr,{size:16})}),!R&&0===L.length&&t("div",{className:"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:P("No conversations yet")}),L.map(n=>{const r=n.conversationId===$,a=M(n.updatedAt,P);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||P("Untitled conversation")}),a&&t("div",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:a})]}),j&&t("button",{type:"button",onClick:()=>j(n.conversationId),title:P("Delete conversation"),"aria-label":P("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(Tr,{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(Zn,{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:P("New conversation")})]}),z&&L.length>0&&t($r,{onClear:()=>{E?.(),z()},className:"px-3 pb-2",iconButtonClass:"p-1 rounded-md text-gray-400 dark:text-white/40 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors",t:P})]})]}),O,t(Or,{title:P("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(Zn,{size:18})})}),"inline"!==r&&b&&e(n,{children:[t(Or,{title:P("Switch view"),children:t("button",{ref:H,type:"button","aria-label":P("Switch view"),onClick:y,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors",children:t(G,{size:18})})}),e(Dr,{open:w,onClose:x,anchorRef:H,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:P("Switch to")}),t("div",{className:"pb-1",children:Ur.map(n=>e("button",{type:"button",onClick:()=>{b(n.mode),x()},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 "+(r===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(P)})]},n.mode))})]})]}),"inline"!==r&&N&&t(n,{children:t(Or,{title:P("Close"),children:t("button",{type:"button","aria-label":P("Close"),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(Kn,{size:18})})})})]})};function Wr({url:e,query:t,exclude:n,requestHeaders:r}){const a=zt(),[s,l]=o(pe);return i(()=>{if(!e||null===t)return void l(pe);let o=!0;const s=new AbortController,i=window.setTimeout(async()=>{try{const i=await a(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:{...r??{}},signal:s.signal}),c=i.ok?await i.json():null;if(!o)return;l(i.ok?{query:t,items:de(c),failed:!1}:{query:t,items:[],failed:!0})}catch{o&&l({query:t,items:[],failed:!0})}},150);return()=>{o=!1,window.clearTimeout(i),s.abort()}},[e,t,n,r]),s}function qr({url:e,requestHeaders:t,conversationId:n,text:r,onTextChange:a,textareaRef:c,refs:h,onPick:g,agentMentions:m}){const f=null!==e||!!m,[v,w]=o(null),[y,x]=o(null),[b,k]=o(0),N=s(null),C=p(),S=l(e=>`${C}-option-${e}`,[C]),I=l(()=>{const e=c.current,t=f&&e&&document.activeElement===e&&e.selectionStart===e.selectionEnd?function(e){const t=/@([\w-]*)$/.exec(e);return!t||oe(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})},[f,c]),T=l(()=>w(null),[]);d(()=>{const e=N.current;if(null===e)return;N.current=null;const t=c.current;t&&(t.focus(),t.setSelectionRange(e,e))},[r,c]),i(()=>{I()},[r,I]),i(()=>{v||x(null)},[v]);const A=Wr({url:e,query:v?.query??null,exclude:n,requestHeaders:t}),[_,E]=o([]);i(()=>{E([])},[n]),i(()=>{E(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,s=r.toLowerCase(),i=o?e.filter(e=>e.id===n||a.has(e.id)||!e.title.toLowerCase().includes(s)):e;return ge(i.length===e.length?e:i,t.items)}(e,A,n))},[A,n]);const M=u(()=>ge(h.map(me),_),[h,_]);i(()=>{k(0)},[A]);const L=function(e){const{trigger:t,dismissed:n,search:r,referenced:a,exclude:o,known:s=[]}=e;if(!t||n)return{kind:"closed"};if(a>=5)return{kind:"full"};if(r.failed)return{kind:"closed"};const i=t.query?s.filter(e=>he(t.query,e)&&!r.items.some(t=>t.id===e.id)):[],l=[...r.items,...i].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"}}({trigger:v,dismissed:null!==v&&v.anchor===y,search:A,referenced:ce(h,r).length,exclude:n,known:M}),R=null!==v&&v.anchor===y,$=[...u(()=>m&&v&&!R?function(e,t){const n=[];for(const r of e){const e=Rt(r);if(e&&he(t,{key:e,title:r.name})&&(n.push({agentId:r.id,name:r.name,key:e}),n.length>=5))break}return n}(m.agents,v.query):[],[m,v,R]).map(e=>({type:"agent",mention:e})),...null!==e&&"results"===L.kind?L.items.map(e=>({type:"conversation",candidate:e})):[]],D=Math.min(b,Math.max($.length-1,0)),j=e=>{if(!v)return;const t="agent"===e.type?e.mention.key:e.candidate.key,n=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}}(r,v,t);"agent"===e.type?m?.onPick(e.mention):g({conversationId:e.candidate.id,title:e.candidate.title,key:t,isOwn:e.candidate.isOwn}),N.current=n.caret,a(n.text),w(null)},z=f?{"aria-autocomplete":"list","aria-controls":$.length>0?C:void 0,"aria-activedescendant":$.length>0?S(D):void 0}:{};return{view:null===e?{kind:"closed"}:L,items:$,activeIndex:D,setActiveIndex:k,listboxId:C,optionId:S,sync:I,close:T,pick:j,onKeyDown:e=>{if("closed"===L.kind&&0===$.length||!v||e.nativeEvent.isComposing)return!1;if("Escape"===e.key)return e.preventDefault(),x(v.anchor),!0;if(0===$.length)return!1;if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;return k((D+t+$.length)%$.length),!0}return!("Enter"!==e.key&&"Tab"!==e.key||e.shiftKey)&&(e.preventDefault(),j($[D]),!0)},textareaAria:z}}const Br=14,Fr=2*Math.PI*6,Vr=[{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"}],Kr=({usage:r,t:a})=>{const{used:i,limit:l,breakdown:c}=r,d=s(null),[u,p]=o(!1),h=Math.min(Math.max(i/l,0),1),g=h>=.95,m=h>=.8,f=g?"text-red-500":m?"text-amber-500":"text-[var(--chat-accent)]",v=g?"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*h),y=`${E(i)}/${E(l)}`,x=a(g?"Context full — older turns are being dropped":m?"Context nearly full — older turns are being summarized":"Context used"),b=A(a,"{counts} tokens",{counts:y}),k=`${x} · ${b}`,N=c?Vr.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:Br,height:Br,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:Fr,strokeDashoffset:Fr*(1-h),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${v}`,children:[w,"%"]})]});return C?e(n,{children:[t(Or,{title:u?"":A(a,"{summary} — click for details",{summary:k}),children:t("button",{ref:d,type:"button",onClick:()=>p(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:S})}),e(Dr,{open:u,onClose:()=>p(!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 ${v}`,children:A(a,"{percent}% full",{percent:w})}),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(i,1)*Math.min(i/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(a)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0",children:E(c?.[n.field]??0)})]},n.field))}),m&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${v}`,children:x})]})]}):t(Or,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},Gr=({view:n,items:r,activeIndex:a,listboxId:o,optionId:i,onHover:l,onPick:c,t:u})=>{const p=s(null);if(d(()=>{p.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[a,n.kind]),"closed"===n.kind&&0===r.length)return null;const h=r.some(e=>"agent"===e.type),g=u(h?"Mention an agent":"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:g}),r.length>0&&t("div",{ref:p,id:o,role:"listbox","aria-label":g,className:"max-h-[240px] overflow-y-auto pb-1 filigran-chat-scrollable",children:r.map((n,o)=>{const s=o===a,d="conversation"===n.type&&h&&"agent"===r[o-1]?.type;return e("div",{children:[d&&t("span",{className:"block px-4 pt-2 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40",children:u("Reference a conversation")}),e("div",{id:i(o),role:"option","aria-selected":s,onMouseDown:e=>{e.preventDefault(),c(n)},onMouseMove:()=>{s||l(o)},className:"flex items-center gap-2.5 px-4 py-1.5 cursor-pointer transition-colors "+(s?"bg-gray-100 dark:bg-white/10":""),children:[t("span",{className:"shrink-0 text-[var(--chat-accent)]",children:"agent"===n.type?t(Hn,{size:14}):t(gr,{size:14})}),"agent"===n.type?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.mention.name}),e("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:["@",n.mention.key]})]}):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.candidate.title||u("Untitled conversation")}),e("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/40 truncate",children:["@",n.candidate.key,!n.candidate.isOwn&&` · ${u("Shared with you")}`]})]})]})]},"agent"===n.type?`agent-${n.mention.agentId}`:n.candidate.id)})}),"empty"===n.kind&&0===r.length&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] text-gray-400 dark:text-white/40",children:u("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:A(u,"A message references at most {count} conversations",{count:5})})]})},Jr=({prompts:r,onPick:a,t:i})=>{const l=s(null),[c,d]=o(!1),[u,p]=o(""),h=()=>{d(!1),p("")},g=u.trim().toLowerCase(),m=g?r.filter(e=>e.title.toLowerCase().includes(g)||(e.description??"").toLowerCase().includes(g)):r;return e(n,{children:[t(Or,{title:i("Insert prompt template"),children:t("button",{ref:l,type:"button",onClick:()=>c?h():d(!0),"aria-label":i("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(kr,{size:15})})}),e(Dr,{open:c,onClose:h,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:i("Insert prompt template")}),r.length>5&&t("div",{className:"px-3 pb-2 pt-1",children:t("input",{autoFocus:!0,type:"text",value:u,onChange:e=>p(e.target.value),onKeyDown:e=>{"Escape"===e.key&&h()},placeholder:i("Search prompts..."),"aria-label":i("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:i("No prompt matches")}),m.map(n=>e("button",{type:"button",onClick:()=>{a(n.content),h()},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))]})]})]})},Yr=({quota:n,t:r})=>{const{used:a,limit:o}=n,s=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),i=e=>"global"===n.scope?A(r,"{quota} (shared across all users)",{quota:e}):e;if(null===o){const e=i(s?A(r,"Usage · {period}",{period:s}):r("Usage"));return t(Or,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30",role:"img","aria-label":`${e} ${E(a)}`,children:E(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",p=c?"text-red-500 dark:text-red-400":d?"text-amber-600 dark:text-amber-400":"text-gray-400 dark:text-white/30",h=`${E(a)}/${E(o)}`,g=r(c?"Quota reached":"Quota"),m=i(s?`${g} · ${s}`:g);return t(Or,{title:m,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${m} ${h}`,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 ${p}`,children:h})]})})},Xr=[],Zr=({header:r,steerAttachments:a=!1,canHold:c=!1,heldMessage:p,notice:h,onCancelHeld:g,inputValue:m,onInputChange:f,onSend:v,onStop:w,isLoading:y,sendsHeld:x=!1,canSteer:b=!1,attachedFiles:k=[],onFileAdd:N,onFileRemove:C,onPaste:S,t:I,mode:T,separatorColor:A,prompts:_,quota:E,contextUsage:M,composerToolbar:L,conversationReferences:R,agentMentions:$})=>{const D=s(null),j=s(null),z=$?.agents,O=$?.onPick,P=u(()=>z&&O?{agents:z,onPick:O}:void 0,[z,O]),U=qr({url:R?.url??null,requestHeaders:R?.requestHeaders,conversationId:R?.conversationId,text:m,onTextChange:f,textareaRef:j,refs:R?.refs??Xr,onPick:e=>R?.onPick(e),agentMentions:P}),H=s(!1),W=function(e){const[t,n]=o(!1),[r,a]=o(""),c=s(null),d=s(e);d.current=e;const u=null!==_n();return i(()=>{const e=_n();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=An(t,{onFinal:e=>d.current(e),onInterim:a,onListeningChange:n});return c.current=r,()=>{c.current=null,r.dispose(),n(!1),a("")}},[]),{supported:u,listening:t,interim:r,toggle:l(()=>c.current?.toggle(),[]),cancel:l(()=>c.current?.cancel(),[])}}(e=>{H.current=!0,f(m.trim()?`${m.trimEnd()} ${e}`:e)});d(()=>{const e=j.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,H.current&&(H.current=!1,e.scrollTop=e.scrollHeight))},[m]);const q=Boolean(_&&_.length>0||E||M||L),B=Boolean(N&&C&&S),F=m.trim()||B&&k.length>0,V=B&&k.some(e=>"pending"===e.uploadStatus),K=B&&k.length>0,G=B&&(y||x)&&Lt(k),J=F&&!V&&!G,Y=Boolean(R)&&ce(R?.refs??Xr,m).length>0||Boolean($)&&$t($?.mentions??[],m).length>0,X=y&&b&&!Y&&(!K||a),Z=X&&!V&&!G&&(K||Boolean(m.trim())),Q=y&&c&&!Z&&!p&&Boolean(J),ee=()=>{(y?Z||Q:J)&&(W.cancel(),v())},te=I(Q?"Enter to send when the answer ends · Esc to stop":G?"A file failed to upload: remove it, or send once the answer ends":X?"Enter to send now · Esc to stop":y&&K?"Attachments wait for the current response":y&&Y?"This message waits 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"===T?"rounded-b-xl":""),style:A?{borderTopColor:A,borderTopWidth:1}:void 0,"data-testid":"filigran-chat-composer",children:[r&&t("div",{className:"mb-2",children:r}),h&&t("div",{role:"alert","data-testid":"filigran-chat-composer-notice",className:"mb-2 text-[0.75rem] text-red-500 dark:text-red-400",children:h}),p&&e("div",{className:"mb-2 flex items-center gap-2 rounded-lg border border-dashed border-[var(--chat-accent-40)] px-2.5 py-1.5 text-[0.75rem]",children:[t("span",{className:"shrink-0 text-gray-500 dark:text-white/50",children:I("Sends when the answer ends:")}),t("span",{className:"min-w-0 flex-1 truncate text-gray-800 dark:text-white/80",children:p.displayText??(p.text||I("Attached files"))}),g&&t("button",{type:"button",onClick:g,className:"shrink-0 text-gray-400 dark:text-white/40 hover:text-red-500",children:I("Cancel")})]}),B&&k.length>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:k.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(er,{size:14}),n.name,"error"===n.uploadStatus&&t("span",{className:"text-red-400 text-[0.6rem]",children:"✕"}),t("button",{type:"button",onClick:()=>C?.(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 ${W.listening?"border-red-500/50":"border-gray-200 dark:border-white/10 focus-within:border-[var(--chat-accent)]"} ${y?"filigran-chat-active-border":""}`,children:[B&&e(n,{children:[t("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:e=>{N?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>D.current?.click(),"aria-label":I("Attach files"),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(Un,{size:18})})]}),t("textarea",{ref:j,placeholder:W.listening?I("Listening..."):I("Ask a question..."),value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{U.onKeyDown(e)||("Enter"!==e.key||e.shiftKey||(e.preventDefault(),ee()),"Escape"===e.key&&y&&(e.preventDefault(),w()))},onKeyUp:U.sync,onClick:U.sync,onFocus:U.sync,onBlur:U.close,...U.textareaAria,onPaste:S,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(Gr,{view:U.view,items:U.items,activeIndex:U.activeIndex,listboxId:U.listboxId,optionId:U.optionId,onHover:U.setActiveIndex,onPick:U.pick,t:I}),W.supported&&t(Or,{title:W.listening?I("Stop dictation"):I("Dictate a message"),children:e("button",{type:"button",onClick:W.toggle,"aria-label":I("Dictate a message"),"aria-pressed":W.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors "+(W.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:[W.listening?t(fr,{size:18}):t(mr,{size:18}),W.listening&&t("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse"})]})}),Q&&t(Or,{title:I("Send when the answer ends"),children:t("button",{type:"button",onClick:ee,"aria-label":I("Send when the answer ends"),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(xr,{size:18})})}),Z&&t(Or,{title:I("Send now"),children:t("button",{type:"button",onClick:ee,"aria-label":I("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(xr,{size:18})})}),t(Or,{title:y?I("Stop generating"):V?I("Files uploading..."):"",children:t("button",{type:"button",onClick:y?w:ee,"aria-label":I(y?"Stop generating":"Send"),disabled:!y&&!J,className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 "+(y?"text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5":J?"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(y?Nr:xr,{size:18})})})]}),q&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[_&&_.length>0&&t(Jr,{prompts:_,onPick:e=>{f(m.trim()?`${m.trimEnd()}\n\n${e}`:e),j.current?.focus()},t:I}),L,(M||E)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[M&&t(Kr,{usage:M,t:I}),E&&t(Yr,{quota:E,t:I})]})]}),W.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:W.interim})]}):t("p",{"data-testid":"filigran-chat-disclaimer",className:"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70",children:te})]})},Qr=e=>e.serverId??e.id;const ea=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;const ta={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"}},na=new Map;function ra(e,t){const n=`${e??""}|${t}`;let r=na.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,ta[t])}catch{r=new Intl.DateTimeFormat(void 0,ta[t])}na.set(n,r)}return r}const aa={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const oa=new Set(["ArrowUp","PageUp","Home"]);function sa(e){return 1===e.length?e[0].clientY:null}const ia=new Set(["auto","scroll","overlay"]);const la={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"})]})},ca="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)]",da=({artifact:n,t:r,onDownload:a,onRefresh:s,onOpen:l})=>{const[c,d]=o(n),[u,p]=o(null),[h,g]=o(!1);i(()=>d(n),[n]);const m=!!s&&!h&&(e=>"video"===e.kind&&("pending"===e.status||"running"===e.status))(c);i(()=>{if(!m||!s)return;let e=!1;const t=function(e,{intervalMs:t,forMs:n,onGiveUp:r}){let a,o=!1;const s=()=>{a=setTimeout(()=>{e().catch(()=>{}).finally(()=>{o||s()})},t)},i=setTimeout(()=>{o=!0,clearTimeout(a),r?.()},n);return s(),()=>{o=!0,clearTimeout(a),clearTimeout(i)}}(()=>s(c.kind,c.id).then(t=>{!e&&t&&d(t)}),{intervalMs:1e4,forMs:9e5,onGiveUp:()=>g(!0)});return()=>{e=!0,t()}},[m,s,c.kind,c.id]);const f=la[c.kind],v=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(c.kind,r),w=c.title||v,y=H(c,r),x=function(e,t){if("video"===e.kind){if("running"===e.status)return A(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")}}(c,r),b=l?null: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}}(c),k=a?c.downloads:[];return e("div",{role:"group","aria-label":`${v}: ${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(f,{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}),y&&t("span",{className:"text-[0.7rem] text-gray-500 dark:text-white/50",children:y}),x&&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(jr,{size:10}),x]})]})]}),(b||l||k.length>0)&&e("div",{className:"flex flex-wrap items-center gap-1.5 pl-[28px]",children:[l&&t("button",{type:"button",className:ca,onClick:()=>l(c),children:r("Open")}),b&&e("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:ca,children:[r("Open in XTM One"),t(Qn,{size:12})]}),k.map(n=>{const o=function(e,t){return"pdf"===e?"PDF":"mp4"===e?"MP4":"pptx"===e?t("PowerPoint"):"pptx_native"===e?t("PowerPoint (editable)"):e.toUpperCase()}(n,r);return e("button",{type:"button",className:ca,disabled:null!==u,"aria-label":A(r,"Download {format}",{format:o}),onClick:()=>{(async e=>{if(a){p(e);try{await a(c,e)}finally{p(null)}}})(n)},children:[u===n?t(jr,{size:11}):t(Xn,{size:12}),o]},n)})]})]})};function ua(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function pa(e){const t=s(null);return i(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const ha="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",ga=({proposal:n,decision:r,onDecide:a,disabled:s,t:i})=>{const[l,c]=o(!1),[d,u]=o(""),h=p(),g=pa(l),m=r?.verdict,f=Object.keys(n.arguments??{}),v=e=>{a({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&d.trim()?{rejectionReason:d.trim()}:{}})};return e("div",{"data-testid":"filigran-chat-approval",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(Lr,{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||i("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:i("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:ua(n.arguments?.[r])})]},r)})}),!m&&l&&e("div",{ref:g,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:h,className:"text-[0.7rem] text-gray-500 dark:text-white/45",children:i("Why not? The agent sees this and can adapt (optional)")}),t("textarea",{id:h,autoFocus:!0,rows:2,value:d,onChange:e=>u(e.target.value),placeholder:i("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:s,onClick:()=>v("reject"),className:`${ha} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(Rr,{size:13}),i("Decline this call")]}),t("button",{type:"button",disabled:s,onClick:()=>{c(!1),u("")},className:`${ha} text-gray-500 hover:bg-gray-100 dark:text-white/50 dark:hover:bg-white/5`,children:i("Back")})]})]}),!m&&!l&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>c(!0),className:`${ha} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(Rr,{size:13}),i("No")]}),e("button",{type:"button",disabled:s,onClick:()=>v("approve"),className:`${ha} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(Bn,{size:13}),i("Yes")]}),t("button",{type:"button",disabled:s,onClick:()=>v("approve_always"),title:i("Also applies to your scheduled runs, until you revoke it"),className:`${ha} 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:i("Yes, always")})]})]})},ma=({proposals:n,onSubmit:r,isSubmitting:a,error:l,t:c})=>{const[d,u]=o({}),p=s(!1),[h,g]=o(!1);i(()=>{l&&(p.current=!1,g(!1))},[l]);const m=a||h,f=e=>{p.current||a||(p.current=!0,g(!0),r(e))},v=n.filter(e=>d[e.toolCallId]).length,w=v===n.length&&n.length>0,y=Object.values(d).some(e=>"approve_always"===e.verdict),x=pa(y),b=pa(!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(On,{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(ga,{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)),y&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(On,{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:x,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?A(c,"{decided}/{total} decided",{decided:v,total:n.length}):""}),t("button",{type:"button",disabled:!w||m,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${ha} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:c(m?"Sending…":"Confirm")})]})]})},fa=({src:n,alt:r,onClose:a,t:l})=>{const c=s(null),d=s(null),[u,p]=o(null);return i(()=>{p(_(c.current))},[]),i(()=>{const e=e=>{"Escape"===e.key&&a()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[a]),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&&x(e("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4",onClick:a,role:"dialog","aria-modal":"true","aria-label":l("Image preview"),children:[t("button",{ref:d,type:"button",onClick:a,"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(Kn,{size:20})}),t("img",{src:n,alt:r,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),u)})},va=({src:r,alt:a,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))(r),[u,p]=o(null),[h,g]=o(!1),[m,f]=o(!1),v=zt();i(()=>{if(!d)return;let e=!1,t=null;return v(r,{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),p(t))}).catch(()=>{e||g(!0)}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[d,r,s]);const w=d?u:r;return h?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:a,loading:"lazy",onClick:()=>f(!0),onError:()=>g(!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(hr,{size:14})})]}),m&&t(fa,{src:w,alt:a,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(dr,{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 wa="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",ya=({t:n,enabled:r=!0,onPlay:a,playUrl:s,keepEndInView:l,messages:c,content:d})=>{const p=u(()=>c&&c.length>0?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),[c,n]),h=function(){const[e,t]=o(()=>!("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}(),[g,m]=o(0);if(i(()=>{r&&l()},[r,l]),i(()=>{if(!r||d)return;const e=window.setInterval(()=>m(e=>(e+1)%p.length),2600);return()=>window.clearInterval(e)},[r,p.length,!!d]),!r)return null;if(d)return t("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:d});const f=p[g%p.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:f}),e("div",{className:"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5",style:h?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:h?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[f,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(h?"":"animate-pulse")})]},f),a?e("button",{type:"button",onClick:a,className:wa,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(ir,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:wa,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(ir,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(Qn,{size:11})})]}):null]})]})};function xa(e,t){return e>1?A(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function ba(e,t){return e>1?A(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function ka(e,t){return e>1?A(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function Na(e,t){if(!e)return{label:t("Thinking..."),StatusIcon:Wn,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:xa(n.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:Ar,showDots:!1}}if(r.some(e=>"check_task_status"===e)){return{label:ba(n.filter(e=>"check_task_status"===e).length,t),StatusIcon:kr,showDots:!1}}if(r.some(e=>"get_task_result"===e)){return{label:ka(n.filter(e=>"get_task_result"===e).length,t),StatusIcon:kr,showDots:!1}}let a,o=Lr;if(r.some(e=>e.includes("search")||e.includes("list"))?o=yr:r.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?o=Jn:r.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?o=pr:r.some(e=>e.includes("code")||e.includes("execute"))?o=Cr:r.some(e=>e.includes("web")||e.includes("browse"))&&(o=lr),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]}…`:A(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:On,showDots:!1};case"cancelling":return{label:t("Stopping…"),StatusIcon:Wn,showDots:!0};case"wait_start":return{label:e.waitReason||t("Waiting before continuing…"),StatusIcon:kr,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:kr,showDots:!0};case"analyzing":return{label:t("Analyzing results…"),StatusIcon:kr,showDots:!1};case"steering":return{label:t("Incorporating your message…"),StatusIcon:kr,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:Wn,showDots:!0};case"consulting":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Consulting {agent}…",{agent:n}),StatusIcon:Ar,showDots:!1}}case"delegating":return{label:xa(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:Ar,showDots:!1};case"polling":return{label:ba(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:kr,showDots:!1};case"collecting":return{label:ka(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:kr,showDots:!1};case"transferring":{const n=e.tools?.[0]??t("the agent");return{label:A(t,"Transferring to {agent}…",{agent:n}),StatusIcon:Qn,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:Wn,showDots:!1}}}function Ca(e,t,n){return e&&n?.(e)||Na(e,t).label}function Sa(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 Ia({text:e}){const n=s(null),[r,a]=o(!1);return i(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight,a(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"+(r?" [-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 Ta(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 Aa(e,t,n=0){const[r,a]=o(null);return i(()=>{if(a(null),!e)return;const r=window.setTimeout(()=>a(n),t);return()=>window.clearTimeout(r)},[e,t,n]),e&&r===n}const _a=({agentStatus:r,logoIcon:a,t:s,miniGameEnabled:l=!0,onPlayWaitingGame:c,waitingGameUrl:d,keepEndInView:p,onSkipWait:h,statusLabel:g,waitingMessages:m,renderWaitingPanel:f})=>{const v=Na(r,s),{StatusIcon:w,showDots:y}=v,x=Ca(r,s,g),b=r?.thinkingContent,k=r?.elapsedStartMs,N="wait_start"===r?.status?r.waitStartMs:void 0,C=k??N,[S,I]=o(()=>Date.now());i(()=>{if(null==C)return;I(Date.now());const e=window.setInterval(()=>I(Date.now()),1e3);return()=>window.clearInterval(e)},[C]);const T=r?.waitSeconds,A=null!=N&&null!=T?Math.max(0,T-(S-N)/1e3):void 0,_=null!=k?Math.max(0,(S-k)/1e3):r?.elapsedS,E="number"==typeof _&&_>=15,M=u(()=>function(e){if(e.length<=6e3)return Sa(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,s]=t[n],i=Math.max(o,s-a);r.push(e.slice(i,s)),a-=s-i+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 Sa(o)}(b??""),[b]),L=M.length>=3,R=Aa(l&&!L,5e3),$=Aa(l&&L,1e4,b?.length??0),D=L?$:R;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:a})}),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:[y?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(w,{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:x}),void 0!==A?t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:Ta(Math.ceil(A))}):E&&t("span",{className:"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0",children:Ta(_)}),"wait_start"===r?.status&&h&&t("button",{type:"button",onClick:h,className:"ml-1 shrink-0 rounded-md border border-[var(--chat-accent)]/40 px-2 py-0.5 text-xs text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors",children:s("Continue now")})]})]})]}),D?t(ya,{t:s,enabled:l,onPlay:c,playUrl:d,keepEndInView:p,messages:m,content:f?.()}):L?t(Ia,{text:M}):null]})};class Ea extends h{state={failed:!1,resetKey:this.props.resetKey};static getDerivedStateFromError(){return{failed:!0}}static getDerivedStateFromProps(e,t){return e.resetKey===t.resetKey?null:{failed:!1,resetKey:e.resetKey}}componentDidCatch(e,t){console.error(`${this.props.label} failed to render`,e,t.componentStack)}render(){return this.state.failed?this.props.fallback:this.props.children}}function Ma({draw:e}){return t(n,{children:e()})}function La({t:e}){return t("p",{className:"pl-1 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:e("This item could not be loaded.")})}const Ra=y().use(w).use(v).freeze();function $a(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some($a);default:return!1}}function Da(e,t){return e.lastIndexOf("\n",t-1)+1}function ja(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Da(e,t-1),t-1).trim()}function za(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 Oa{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 s=t&&n&&t.firstDefinition<n?t.firstDefinition:-1;o.push(r);for(const t of Ra.parse(a).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Da(a,n),s=o[o.length-1];t>s&&!za(e,s,t)&&o.push(t)}s<0&&$a(t)&&(s=o.length-1)}let i=n;for(let t=o.length-1;t>n;t--)if(ja(e,o[t])){i=t;break}const l=s<0?o.map((t,n)=>e.slice(t,o[n+1]??e.length)):[e];return{source:e,blocks:l,starts:o,settled:i,firstDefinition:s}}(e,this.last)),this.last.blocks}}const Pa=r({copiedBlock:null,onCopyCode:()=>{},streaming:!1,t:T});function Ua({draw:e,block:r}){const a=e();return null==a||!1===a?t(n,{children:r}):t("div",{className:"my-3",children:a})}const Ha={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:o,onCopyCode:s,codeBlockRenderers:i,streaming:l,t:c}=a(Pa),d=/(?:^|\s)language-(\S+)/.exec(n||""),u=String(r).replace(/\n$/,""),p=d?i?.[d[1].toLowerCase()]:void 0;if(d||u.includes("\n")){const 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:d?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>s(u),"aria-label":c(o===u?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors",children:o===u?t(Bn,{size:14,className:"text-green-500"}):t(Gn,{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:u})})]});return p?t(Ea,{label:"A chat code block renderer",resetKey:`${u}\0${l}`,fallback:t(La,{t:c}),children:t(Ua,{draw:()=>p(u,{streaming:l}),block:n})}):n}return 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}=a(Pa),o=Ve(e),s=null!==o&&!!r,i=!(s||(e=>!!e&&!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e)&&null!==o);return t("a",{href:e,onClick:e=>{s&&(e.preventDefault(),r(o))},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:o}=a(Pa);return"string"==typeof e&&e?t(va,{src:e,alt:n||"",requestHeaders:r,t:o},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})},Wa=[v,k],qa=g(({source:e})=>t(b,{remarkPlugins:Wa,urlTransform:I,components:Ha,children:e}));qa.displayName="MarkdownBody";const Ba=({source:e})=>{const[r]=o(()=>new Oa),a=u(()=>r.split(e),[r,e]);return t(n,{children:a.map((e,n)=>t(qa,{source:e},n))})},Fa=g(({codeBlockRenderers:e,...n})=>{const{content:r,streaming:a=!1,onRelativeLinkClick:s,requestHeaders:i,t:c=T}=n,[d,p]=o(null),[h,g]=o(a);a&&!h&&g(!0);const m=u(()=>C(r),[r]),f=l(e=>{navigator.clipboard.writeText(e),p(e),setTimeout(()=>p(null),2e3)},[]),v=u(()=>({copiedBlock:d,onCopyCode:f,onRelativeLinkClick:s,requestHeaders:i,codeBlockRenderers:e,streaming:a,t:c}),[d,f,s,i,e,a,c]);return t(Pa.Provider,{value:v,children:t(h?Ba:qa,{source:m})})});Fa.displayName="MarkdownMessage";function Va(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Ka(e){return e.replace(/_/g," ")}const Ga=({entry:n,index:r,t:a})=>{const[s,i]=o(!1),l=u(()=>Va(n.input),[n.input]),c=u(()=>Va(n.output),[n.output]),d=!!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:()=>i(e=>!e),"aria-expanded":s,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:r+1}),n.success?t(qn,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(Rr,{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:Ka(n.name)}),t(Fn,{size:14,className:"shrink-0 text-gray-400 dark:text-white/50 transition-transform duration-200 "+(s?"rotate-180":"")})]}),s&&e("div",{className:"border-t border-gray-200 dark:border-white/[0.06]",children:[d&&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:a("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:a("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:c||a("(no output)")})]})]})]})},Ja=({msg:n,onClose:r,t:a})=>{const l=s(null),c=s(null),d=s(null),[u,p]=o(null);i(()=>{p(_(l.current))},[]),i(()=>{const e=e=>{if("Escape"===e.key)return void r();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 a=n[0],o=n[n.length-1],s=document.activeElement;e.shiftKey?s!==a&&t.contains(s)||(e.preventDefault(),o.focus()):s!==o&&t.contains(s)||(e.preventDefault(),a.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r]),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 h=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,g=n.toolNames??[],m=n.iterations??1,f=n.transferChain??[],v=n.toolCallTrace??[],w=(n.reasoning??"").trim(),y=[m>1?A(a,"{count} iterations",{count:m}):"",1===h?a("1 tool call"):A(a,"{count} tool calls",{count:h}),1===f.length?a("1 transfer"):f.length>1?A(a,"{count} transfers",{count:f.length}):""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:u&&x(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:r,role:"presentation",children:e("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":a("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(Lr,{size:15,className:"text-[var(--chat-accent)]"}),t("span",{className:"flex-1 text-[0.875rem] font-semibold text-gray-900 dark:text-white",children:a("Reasoning details")}),t("button",{ref:c,type:"button",onClick:r,"aria-label":a("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(Kn,{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(On,{size:14,className:"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400"}),e("span",{children:[t("span",{className:"font-semibold",children:a("Turn limit reached.")})," ",a("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.")]})]}),w&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Wn,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:a("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:Sa(w)})})]}),v.length>0?t("div",{className:"flex flex-col gap-1.5",children:v.map((e,n)=>t(Ga,{entry:e,index:n,t:a},`${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(Lr,{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:Ka(n)})]},`${n}-${r}`))}),f.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(Pn,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium text-gray-500 dark:text-white/50",children:a("Transfer chain")})]}),t("div",{className:"flex items-center gap-1.5 flex-wrap",children:f.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(Hn,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),u)})},Ya=e=>e.parentElement,Xa=e=>getComputedStyle(e).overflowY;function Za(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function Qa(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 eo=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);const to="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",no="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",ro="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",ao=`opacity-0 ${to} ${ro}`,oo=`opacity-50 ${to} ${ro}`,so="opacity-100 text-[var(--chat-accent)]",io=({timestamp:n,locale:r})=>{const a=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:ra(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:ra(t,"full").format(e),iso:e.toISOString()}:null;var r,a}(n,r);return a?t(Or,{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},lo=({text:e,label:n,t:r})=>{const[a,s]=o(!1),i=a?r("Copied!"):n;return t(Or,{title:i,children:t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),s(!0),setTimeout(()=>s(!1),2e3)}catch{}},"aria-label":i,className:`${no} ${a?"opacity-100 text-green-500 dark:text-green-400":ao}`,children:t(a?Bn:Gn,{size:14})})})},co=({value:r,locked:a,pending:o,onChange:s,downRef:i,t:l})=>{const c=p(),d=a||o,u=(e,n)=>{const o=r===e;if(a&&!o)return null;const u="up"===e?Ir:Sr;return t(Or,{title:a?l("Feedback already submitted"):n,children:t("button",{ref:"down"===e?i:void 0,type:"button",onClick:()=>{d||s(o?null:e)},"aria-label":n,"aria-pressed":o,"aria-disabled":d||void 0,"aria-describedby":a?c:void 0,className:`${no} ${o?so:ao} ${d?"cursor-default":""}`,children:t(u,{size:14,filled:o})})})};return e(n,{children:[u("up",l("Good response")),u("down",l("Bad response")),a&&t("span",{id:c,className:"sr-only",children:l("Feedback already submitted")})]})},uo=({pending:n,onSave:r,onSkip:a,t:s})=>{const[i,l]=o(""),c=p(),d=!n&&!!i.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:s("Tell us what went wrong (optional)")}),t("textarea",{id:c,autoFocus:!0,rows:2,maxLength:2e3,value:i,readOnly:n,onChange:e=>l(e.target.value),onKeyDown:e=>{"Escape"===e.key?(e.preventDefault(),e.stopPropagation(),n||a()):"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),d&&r(i))},placeholder:s("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||a()},"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:s("Skip")}),t("button",{type:"button",onClick:()=>{d&&r(i)},"aria-disabled":!d||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)] "+(d?"hover:opacity-90":"opacity-50 cursor-default"),children:s("Save")})]})]})},po=({speaking:e,onToggle:n,t:r})=>{const a=r(e?"Stop reading":"Read aloud");return t(Or,{title:a,children:t("button",{type:"button",onClick:n,"aria-label":a,className:`${no} ${e?so:ao}`,children:t(e?Mr:Er,{size:14})})})},ho=[],go=new Set(["PRESENTATION","REPORT","VIDEO"]),mo=g(({msg:r,isStreaming:a,agentName:i,logoIcon:l,onRelativeLinkClick:c,onDownloadFile:p,resolveAttachmentUrl:h,onDownloadArtifact:g,onRefreshArtifact:m,requestHeaders:f,feedbackMode:v,feedback:w,onRate:y,onSaveComment:x,onSkipComment:b,locale:k,canSpeak:N,isSpeaking:C,onToggleSpeech:S,openableConversationIds:I,onOpenConversation:T,markerRenderers:A,markerKindList:_=ho,codeBlockRenderers:E,transformMessageText:M,onArtifactOpen:L,renderMessageExtras:R,messageFooterActions:$,t:D})=>{const[j,H]=o(!1),W="assistant"===r.role,q=u(()=>Mt(M,r.content,r)??r.content,[M,r]),B=!q,F=s(null),V=!!w?.commentOpen,K=s(V);d(()=>{const e=K.current&&!V;K.current=V,!e||document.activeElement&&document.activeElement!==document.body||F.current?.focus()},[V]);const J=(n,r)=>{const a=h&&function(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&eo.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&eo.has(e.filename.slice(n+1).toLowerCase())}(n)?h(n):void 0;if(a)return t(va,{src:a,alt:n.filename,requestHeaders:f,maxHeightClass:"max-h-[200px]",t:D},r);const o="working_file"===n.fileTag,s=!(i=n.size)||i<=0?"":i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(0)} KB`:`${(i/1048576).toFixed(1)} MB`;var i;return e("button",{type:"button",onClick:()=>p?.(n),title:D("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(er,{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||s)&&t("span",{className:"text-[0.65rem] text-gray-400 dark:text-white/40 uppercase",children:[n.type,s].filter(Boolean).join(" · ")})]}),t("span",{className:"shrink-0 text-gray-400 dark:text-white/30 group-hover:text-[var(--chat-accent)]",children:t(Xn,{size:15})})]},r)},Y=(n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.7rem] text-gray-600 dark:text-white/60",children:[t(er,{size:14}),n]},r),X=(e,n)=>t(da,{artifact:e,t:D,onDownload:g,onRefresh:m,onOpen:L},n),Z=(e,n,o)=>{const s=A?.[e];return!s||a&&!s.renderWhileStreaming?null:t("div",{className:s.fullWidth?"w-full":"w-full max-w-[90%]",children:t(Ea,{label:"A chat marker card",resetKey:`${n}\0${a}`,fallback:t(La,{t:D}),children:t(Ma,{draw:()=>s.render(n,{message:r,streaming:a})})})},o)},Q=r.toolNames&&r.toolNames.length>0||!!(r.reasoning??"").trim()||r.toolCallTrace&&r.toolCallTrace.length>0||r.transferChain&&r.transferChain.length>0||r.isTruncated,ee=W&&!B&&!a,te=function(e,t=[]){if(!e)return e;const n=z(t),r=e.replace(n.complete,"").replace(n.partial,"");return r===e?e:r.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}(q,_),ne=u(()=>ee&&N?P(q,_):null,[ee,N,q,_]),re=(ae=w,oe=r.feedback,ae?{value:ae.value,locked:!1}:oe?{value:(se=oe.rating,"positive"===se?"up":"down"),locked:!0}:{value:null,locked:!1});var ae,oe,se;const ie=Qr(r);return e("div",{"data-message-id":r.serverId??r.id,className:"group/msg flex flex-col "+(W?"items-start":"items-end"),children:[W&&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:l})}),t("span",{className:"font-semibold text-xs text-gray-900 dark:text-white",children:r.agentName??i})]}),!W&&((r.files?.length??0)>0||(r.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(r.files??[]).forEach((n,r)=>{!(!p||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(J({fileId:n.fileId,filename:n.name,type:Qa(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(Y(n.name,`file-${r}`))}),(r.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(p?J(n,`att-${n.fileId}-${r}`):Y(n.filename,`att-${r}`)))}),e})()}),!W&&(r.conversationRefs?.length??0)>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end max-w-[90%]",children:r.conversationRefs.map((r,a)=>{const o=r.title||(r.key?`@${r.key}`:D("Untitled conversation")),s="inline-flex items-center gap-1 max-w-[240px] px-2 py-0.5 rounded-full border text-[0.7rem]",i=e(n,{children:[t(gr,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:o})]});return T&&I?.has(r.conversationId)?t(Or,{title:D("Open conversation"),children:t("button",{type:"button",onClick:()=>T(r.conversationId),className:`${s} 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:i})},`ref-${r.conversationId}-${a}`):t(Or,{title:r.key?`@${r.key}`:"",children:t("span",{className:`${s} border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60`,children:i})},`ref-${r.conversationId}-${a}`)})}),W?e("div",{"data-testid":"filigran-chat-assistant-message",className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=O(q,a,_),n=new Map((r.attachments??[]).map(e=>[e.fileId,e])),o=new Map((r.artifacts??[]).map(e=>[U(e.kind,e.id),e])),s=new Set,i=new Set,l=[];return e.forEach((e,r)=>{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(Fa,{content:e.value,streaming:a,onRelativeLinkClick:c,requestHeaders:f,codeBlockRenderers:E,t:D})},`t-${r}`));else if("marker"===e.type){"FILE"===e.kind?s.add(e.args):go.has(e.kind)&&i.add(U(e.kind.toLowerCase(),e.args.split("#/")[0]));const t=Z(e.kind,e.args,`m-${e.kind}-${r}`);t&&l.push(t)}else if("artifact"===e.type){const t=U(e.kind,e.id),n=o.get(t);n&&!i.has(t)&&(i.add(t),l.push(X(n,`a-${t}-${r}`)))}else if(p){const t=n.get(e.fileId);t&&(s.add(e.fileId),l.push(J(t,`f-${e.fileId}-${r}`)))}}),(r.artifacts??[]).forEach(e=>{const t=U(e.kind,e.id);if(!i.has(t)){i.add(t);const n=e.kind.toUpperCase();if(A?.[n]){const r=Z(n,e.slideRef?`${e.id}#/${e.slideRef}`:e.id,`orphan-a-${t}`);r&&l.push(r)}else l.push(X(e,`orphan-a-${t}`))}}),(r.attachments??[]).forEach(e=>{if(!s.has(e.fileId))if(A?.FILE){const t=Z("FILE",e.fileId,`orphan-${e.fileId}`);t&&l.push(t)}else p&&l.push(J(e,`orphan-${e.fileId}`))}),0!==l.length||a||r.stopped||l.push(t("span",{className:"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic",children:"..."},"empty")),l})(),r.stopped&&!a&&t("p",{className:"pl-1 text-[0.75rem] italic text-gray-400 dark:text-white/40",children:D("Stopped")}),!B&&a&&t("span",{className:"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse"})]}):t("div",{"data-testid":"filigran-chat-user-message",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:q}),R&&t("div",{className:"w-full "+(W?"":"flex justify-end"),children:R(r,{streaming:a})}),!W&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 text-gray-400 dark:text-white/40",children:[!!q.trim()&&t(lo,{text:q,label:D("Copy message"),t:D}),!r.timestampUnknown&&t(io,{timestamp:r.timestamp,locale:k})]}),ee&&e("div",{className:"mt-0.5 flex flex-wrap items-center gap-0.5 text-gray-400 dark:text-white/40",children:[!r.timestampUnknown&&t(io,{timestamp:r.timestamp,locale:k}),Q&&t(Or,{title:r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),children:t("button",{type:"button",onClick:()=>H(e=>!e),className:`${no} ${r.isTruncated?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":oo}`,"aria-label":r.isTruncated?D("Reasoning details — turn limit reached"):D("Reasoning details"),"aria-haspopup":"dialog","aria-expanded":j,children:r.isTruncated?t(On,{size:14}):t(ur,{size:14})})}),t(lo,{text:te,label:D("Copy response"),t:D}),v&&t(co,{value:re.value,locked:re.locked,pending:!!w?.pending,onChange:e=>y(r,e,w),downRef:F,t:D}),ne&&(le=ne,le.some(e=>/[\p{L}\p{N}]/u.test(e.replace(G,""))))&&t(po,{speaking:C,onToggle:()=>S(ie,ne),t:D}),$?.(r,{streaming:a})]}),ee&&w?.commentOpen&&t(uo,{pending:w.pending,onSave:e=>x(r,e,w),onSkip:()=>b(r,w),t:D}),ee&&w?.error&&t("p",{role:"alert",className:"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400",children:w.error}),j&&t(Ja,{msg:r,onClose:()=>H(!1),t:D})]});var le});mo.displayName="MessageRow";const fo=({messages:n,isLoading:r,agentStatus:a,agentName:p,logoIcon:h,onRelativeLinkClick:g,onDownloadFile:m,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,miniGameEnabled:x=!0,onPlayWaitingGame:b,waitingGameUrl:k,onMessageFeedback:N,isResumingAfterDecision:C,onSkipWait:S,pendingApprovals:I,onSubmitApprovalDecisions:T,isSubmittingApproval:A,approvalError:_,feedbackUrl:E,conversationId:M,locale:L,openableConversationIds:R,onOpenConversation:$,markerRenderers:D,markerKindList:j,codeBlockRenderers:z,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,transcriptFooter:W,onLoadEarlier:q,ttsRoute:B,thinking:F,t:V})=>{const G=s(null),[X,Z]=o(150),{entries:Q,rate:re,saveComment:oe,skipComment:se}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a}){const i=zt(),[d,u]=o(()=>({scope:t,entries:{}}));let p=d.entries;d.scope!==t&&(p={},u({scope:t,entries:p}));const h=s({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a});c(()=>{h.current={feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a}});const g=s(0),m=l((e,t)=>u(n=>({...n,entries:{...n.entries,[e]:t}})),[]),f=l((e,t,n)=>u(r=>{const a=r.entries[e];return a&&a.seq===t?{...r,entries:{...r.entries,[e]:n(a)}}:r}),[]),v=l(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,onMessageFeedback:s,t:l}=h.current,c=Qr(e),d=++g.current;if(!r)return m(c,{seq:d,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void s?.(c,t,e);if(a&&e.serverId){if(m(c,{seq:d,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await ae(i,r,a,e.serverId,t?{rating:ee(t),comment:null}:null,o)){const e=l(t?"Could not submit feedback.":"Could not retract feedback.");return void f(c,d,()=>n?{...n,seq:d,pending:!1,commentOpen:!1,error:e}:{seq:d,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}f(c,d,e=>({...e,pending:!1,commentOpen:"down"===t})),h.current.onMessageFeedback?.(c,t,e)}},[m,f]),w=l(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,t:s}=h.current,l=Qr(e),c=ne(t);if(!(r&&a&&e.serverId&&c))return void m(l,{...n,commentOpen:!1,error:null});const d=++g.current;m(l,{...n,seq:d,pending:!0,error:null});const u=await ae(i,r,a,e.serverId,{rating:"negative",comment:c},o);f(l,d,e=>u?{...e,comment:c,pending:!1,commentOpen:!1}:{...e,pending:!1,error:s("Could not submit feedback.")})},[m,f]);return{entries:p,rate:v,saveComment:w,skipComment:l((e,t)=>m(Qr(e),{...t,commentOpen:!1,error:null}),[m])}}({feedbackUrl:E,conversationId:M,requestHeaders:y,onMessageFeedback:N,t:V}),ie=function(e,t){const n=zt(),[r]=o(ea),a=r||!!t,[d,u]=o(null),p=s(null),h=s(e),g=s(t);c(()=>{h.current=e,g.current=t});const m=s(null),f=l(()=>{const e=m.current;e&&(m.current=null,e.abort.abort(),e.audio?.pause(),e.url&&URL.revokeObjectURL(e.url),u(t=>t===e.id?null:t))},[]),v=l(()=>r?(p.current??=function(e,t,n){let r=0,a=null;const o=e=>{e===r&&null!==a&&(r+=1,a=null,n(null))},s=()=>{null!==a&&(r+=1,a=null,e.cancel(),n(null))};return{speak:(i,l,c)=>{s();const d=l.filter(e=>e.trim());if(!d.length)return!1;const u=r;return a=i,n(i),d.forEach((n,a)=>{const s=a===d.length-1,i=t(n,{lang:c,onEnd:()=>{s&&o(u)},onError:()=>{u===r&&(o(u),e.cancel())}});e.speak(i)}),!0},stop:s,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},u),p.current):null,[r]),w=l((e,t)=>v()?.speak(e,J(t),h.current),[v]),y=l(async(e,t,r)=>{const a=new AbortController,o={id:t,abort:a};m.current=o,u(t);const s=J(r,4096),i=new Audio;o.audio=i;let l=0;try{for await(const t of Y(n,e,s,a.signal)){if(m.current!==o)return;if(!t)throw new Error("TTS failed");o.url&&URL.revokeObjectURL(o.url),o.url=URL.createObjectURL(t);const e=new Promise(e=>{i.onended=()=>e(!0),i.onerror=()=>e(!1)});if(i.src=o.url,await i.play(),!await e)throw new Error("TTS playback failed");if(m.current!==o)return;l+=1}f()}catch(e){if(m.current!==o||e instanceof DOMException&&"AbortError"===e.name)return;f(),w(t,s.slice(l).join(" "))}},[w,f]),x=l((e,t)=>{const n=m.current?.id??p.current?.speakingId??null;if(f(),p.current?.stop(),n===e)return;const r=K(t),a=g.current;a?y(a,e,r):w(e,r)},[w,y,f]),b=l(()=>{f(),p.current?.stop()},[f]);return i(()=>()=>b(),[b]),{supported:a,speakingId:d,toggle:x,stop:b}}(L,B),[le]=o(()=>function(e,t=aa){let n=!0,r=0,a=null;const o=e=>{e.scrollTo({top:e.scrollHeight,behavior:"instant"}),r=e.scrollTop},s=()=>{a&&(t.clear(a.timer),a=null)},i=()=>{s();const t=e();t&&n&&o(t)};return{get following(){return n},reveal:()=>{const o=e();if(!o)return;n=!0,s();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(i,1e3)})},keepUp:()=>{const t=e();t&&n&&!a&&o(t)},onScroll:()=>{const t=e();if(!t)return;const o=t.scrollTop,s=o<r-1,l=o>r+1;(s||l)&&(r=o);const c=t.scrollHeight-o-t.clientHeight;s?n=c<=1:l&&c<=100&&(n=!0),a&&(s||o>=a.target-1||c<=1)&&i()},leave:()=>{const t=e();!t||t.scrollTop<=0||(n=!1,s())}}}(()=>G.current)),ce=s(null),de=(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&&ia.has(r(a)))return!0;return!1}(t,e,Ya,Xa)||le.leave())},ue=n[0]?.id,pe=s(null),[he,ge]=o(!1);d(()=>{const e=pe.current,t=e?n.findIndex(t=>t.id===e.firstId):-1;if(e&&t>0)return e.count=t,void Z(e.visible+e.count);Z(150)},[ue]),d(()=>{const e=pe.current;if(!e?.count||X!==e.visible+e.count)return;pe.current=null;const t=G.current;t&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))});let me=0;for(const e of n)"user"===e.role&&(me+=1);const fe=s(null);d(()=>{const e=fe.current;fe.current={firstMessageId:ue,userMessageCount:me},pe.current?.count||(!e||e.firstMessageId!==ue||me>e.userMessageCount?le.reveal():le.keepUp())},[n,ue,me,le]);const ve=a?.thinkingContent?.length??0;d(()=>{ve&&le.keepUp()},[ve,le]);const we=n.length>X,ye=u(()=>we?n.slice(n.length-X):n,[n,X,we]),{speakingId:xe,stop:be}=ie,ke=null===xe||n.some(e=>Qr(e)===xe),Ne=s({conversationId:M,userMessageCount:me});i(()=>{const e=Ne.current;Ne.current={conversationId:M,userMessageCount:me},(e.conversationId!==M||me>e.userMessageCount||!ke)&&be()},[M,me,ke,be]);let Ce=null;if(r)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){Ce=n[e].id;break}const Se=!!I?.length&&!!T;return e("div",{ref:G,role:"region","aria-label":V("Conversation transcript"),tabIndex:0,onScroll:le.onScroll,onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&de(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(oa.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&Za(e.target)||de(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:Za(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})&&de(t,e.target)},onTouchStart:e=>{ce.current=sa(e.touches)},onTouchMove:e=>{const t=sa(e.touches),n=ce.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&de(e.currentTarget,e.target),ce.current=function(e,t){return null===t?null:null===e?t:Math.min(e,t)}(n,t)},"data-testid":"filigran-chat-transcript",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:[(we||q)&&t("div",{className:"flex justify-center",children:e("button",{type:"button",disabled:he,onClick:()=>{(async()=>{if(n.length>X)return void Z(e=>e+50);if(!q||he)return;const e=G.current;ge(!0),pe.current={firstId:n[0]?.id,visible:Math.min(n.length,X),count:0,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0};try{0===await q()&&(pe.current=null)}finally{ge(!1)}})()},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(Fn,{size:13,className:"rotate-180"}),V("Load earlier messages")]})}),ye.map(e=>{const n=e.id===Ce;return"assistant"===e.role&&!e.content&&n?Se?null:t("div",{children:t(_a,{agentStatus:a,logoIcon:h,t:V,miniGameEnabled:x,onPlayWaitingGame:b,waitingGameUrl:k,keepEndInView:le.keepUp,onSkipWait:S,...F})},e.id):t(mo,{msg:e,isStreaming:n,agentName:p,logoIcon:h,onRelativeLinkClick:g,onDownloadFile:m,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:y,feedbackMode:"assistant"===e.role?te(e.serverId,E,M,!!N):null,feedback:Q[Qr(e)],onRate:re,onSaveComment:oe,onSkipComment:se,locale:L,canSpeak:ie.supported,isSpeaking:xe===Qr(e),onToggleSpeech:ie.toggle,openableConversationIds:e.conversationRefs?.length?R:void 0,onOpenConversation:e.conversationRefs?.length?$:void 0,markerRenderers:D,markerKindList:j,codeBlockRenderers:z,transformMessageText:O,onArtifactOpen:P,renderMessageExtras:U,messageFooterActions:H,t:V},e.id)}),C&&!Se&&t(_a,{agentStatus:a,logoIcon:h,t:V,miniGameEnabled:x,onPlayWaitingGame:b,waitingGameUrl:k,keepEndInView:le.keepUp,...F}),Se&&t(ma,{proposals:I,onSubmit:T,isSubmitting:A,error:_,t:V},I.map(e=>e.toolCallId).join("|")),W,t("div",{})]})};function vo(e){const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const wo=({call:n,agentName:r,logoIcon:a,processingLabel:l,onInterrupt:c,onToggleMute:d,onEnd:u,t:p})=>{const[h,g]=o(0);i(()=>{const e=window.setInterval(()=>g(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);const m=s(null);i(()=>{m.current?.scrollIntoView?.({block:"end"})},[n.lines.length,n.heard]);const{phase:f,muted:v}=n,w="listening"===f?p(v?"Muted":"Listening..."):"processing"===f?l:"speaking"===f?p("Speaking…"):"error"===f?p("Failed to get a response. Resuming…"):"",y="speaking"===f||"processing"===f,x="speaking"===f||"listening"===f&&!v,b="w-12 h-12 rounded-full flex items-center justify-center border transition-colors disabled:opacity-40";return e("div",{role:"dialog","aria-label":p("Voice call"),"data-testid":"filigran-chat-voice-call",className:"absolute inset-0 z-40 flex flex-col rounded-[inherit] bg-white dark:bg-[#1e1e2e]",children:[e("div",{className:"flex items-center justify-between px-4 py-3 text-[0.7rem] uppercase tracking-[1px] text-gray-500 dark:text-white/50",children:[t("span",{children:p("Voice call")}),t("span",{className:"font-mono normal-case tracking-normal",children:vo(h)})]}),e("div",{className:"flex flex-1 min-h-0 flex-col items-center justify-center gap-1 px-4",children:[e("button",{type:"button",onClick:y?c:void 0,disabled:!y,"aria-label":"speaking"===f?p("Skip response"):"processing"===f?p("Cancel question"):r,className:`relative mb-4 flex h-28 w-28 items-center justify-center rounded-full border-2 transition-colors ${"error"===f?"border-amber-400/50":x?"border-[var(--chat-accent)]":"border-[var(--chat-accent-40)]"} ${y?"cursor-pointer":"cursor-default"}`,children:[x&&t("span",{className:"absolute inset-0 rounded-full border border-[var(--chat-accent-40)] animate-ping","aria-hidden":"true"}),"processing"===f&&t("span",{className:"absolute inset-3 rounded-full border-2 border-dashed border-[var(--chat-accent-40)] animate-spin","aria-hidden":"true"}),t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-10 [&>svg]:h-10",children:a})]}),t("h2",{className:"max-w-full truncate text-base font-semibold text-gray-900 dark:text-white",children:r}),t("p",{"aria-live":"polite",className:"text-center text-[0.8125rem] text-gray-500 dark:text-white/60",children:w}),"speaking"===f&&t("p",{className:"text-[0.7rem] text-gray-400 dark:text-white/40",children:p("Speak or tap to interrupt")}),"processing"===f&&t("p",{className:"text-[0.7rem] text-gray-400 dark:text-white/40",children:p("Tap to cancel")}),"listening"===f&&n.heard&&e("p",{className:"mt-3 max-w-md text-center text-[0.8125rem] italic text-gray-500 dark:text-white/50",children:["“",n.heard,"”"]})]}),n.lines.length>0&&t("div",{className:"max-h-[35%] overflow-y-auto filigran-chat-scrollable px-4 pb-2",children:e("div",{className:"flex flex-col gap-2",children:[n.lines.map((n,r)=>t("div",{className:"flex "+("user"===n.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[85%] rounded-lg px-3 py-1.5 text-[0.75rem] leading-5 "+("user"===n.role?"bg-[var(--chat-accent)]/10 text-gray-800 dark:text-white/80":"bg-gray-100 dark:bg-white/[0.06] text-gray-700 dark:text-white/70"),children:[n.agent&&e("div",{className:"mb-0.5 text-[0.7rem] font-medium text-[var(--chat-accent)]",children:[n.agent.name,n.agent.failed&&e("span",{className:"font-normal text-gray-500 dark:text-white/50",children:[" · ",p("Did not answer")]})]}),n.content.length>200?`${n.content.slice(0,200)}…`:n.content]})},r)),t("div",{ref:m})]})}),e("div",{className:"flex items-center justify-center gap-5 px-4 pb-5 pt-3",children:[t("button",{type:"button",onClick:d,"aria-label":p(v?"Unmute microphone":"Mute microphone"),"aria-pressed":v,className:`${b} ${v?"border-red-400/40 bg-red-500/10 text-red-500":"border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/70 hover:bg-gray-100 dark:hover:bg-white/[0.06]"}`,children:t(v?fr:mr,{size:20})}),t("button",{type:"button",onClick:u,"aria-label":p("End voice call"),className:"w-14 h-14 rounded-full flex items-center justify-center bg-red-500 text-white hover:bg-red-600 transition-colors",children:t(wr,{size:22})}),t("button",{type:"button",onClick:c,disabled:"speaking"!==f,"aria-label":p("Skip response"),className:`${b} border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/70 hover:bg-gray-100 dark:hover:bg-white/[0.06]`,children:t(Mr,{size:20})})]})]})},yo=({firstName:r,agentName:a,t:o})=>{if(!a)return t(n,{children:A(o,"How can I help you, {name}?",{name:r})});const{before:s,after:i,hasSlot:l}=function(e,t,n,r={}){const a=A(e,t,r),o=`{${n}}`,s=a.indexOf(o);return-1===s?{before:a,after:"",hasSlot:!1}:{before:a.slice(0,s),after:a.slice(s+o.length),hasSlot:!0}}(o,"How can {agent} help you, {name}?","agent",{name:r});return e(n,{children:[s,l&&t("span",{className:"text-[var(--chat-accent)]",children:a}),i]})},xo=({firstName:n,logoIcon:r,promptSuggestions:a,onPromptClick:o,agentName:s,agentDescription:i,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(yo,{firstName:n,agentName:s,t:c})},s??"default"),i&&t("p",{className:"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 text-gray-500 dark:text-white/40",children:i}),!i&&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))}):o&&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))]})]}),bo="application/x-filigran-conversation";const ko="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",No="text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40",Co=({conversations:r,loading:a,activeConversationId:l,collapsed:c,onToggleCollapsed:d,onSelect:p,onDelete:h,onRename:g,onNewChat:m,workspaces:f,storageKeyPrefix:v,rowActions:w,headerActions:y,sections:x,onClearAll:b,t:k})=>{const[N,C]=o(""),[S,I]=o(null),[T,A]=o(""),_=s(!1),E=It(v,Nt),[M,L]=o(()=>function(e){try{const t=JSON.parse(At("local",e)??"[]");return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e):[])}catch{return new Set}}(E)),[R,$]=o(!1),[D,j]=o(null);i(()=>{if(!D)return;const e=setTimeout(()=>j(null),6e3);return()=>clearTimeout(e)},[D]);const z=(e,t)=>{_.current=!1,I(e),A(t)},O=()=>{if(_.current)return;_.current=!0;const e=S,t=T.trim();I(null),e&&t&&g?.(e,t)},P=()=>{_.current=!0,I(null)},U=(e,t)=>j(e||k(t)),H=async(e,t)=>{if(!f||function(e,t,n){const r=e.find(e=>e.conversationId===t);return!!r&&(r.workspaceId??null)===n}(r,e,t))return;const n=await f.onMove(e,t);null!==n&&U(n,"The conversation could not be moved")},W=N.trim().toLowerCase(),q=u(()=>W?e=>(e.title||"").toLowerCase().includes(W):void 0,[W]),B=u(()=>q?r.filter(q):r,[r,q]),F=u(()=>f?function(e,t,n={}){const{matches:r}=n,a=r?e.filter(r):e,o=new Set(t.map(e=>e.id)),s=new Set(e.map(e=>e.workspaceId).filter(e=>!!e)),i=new Map,l=[],c=[];for(const e of a){const t=e.workspaceId??null;t?o.has(t)?i.set(t,[...i.get(t)??[],e]):l.push(e):c.push(e)}const d=[];for(const e of ve(t)){const t=i.get(e.id)??[];(e.canManage||s.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}}(r,f.list,{matches:q}):null,[r,f,q]),V=f?function(e){return ve(e.filter(e=>e.canManage))}(f.list):[],K=F?function(e){const{total:t,unfiled:n,loading:r,searching:a}=e;return n>0||r||a?null:0===t?"none":"all-filed"}({total:r.length,unfiled:F.unfiled.length,loading:a,searching:!!W}):null;if(c)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(Or,{title:k("Show conversations"),children:t("button",{type:"button",onClick:d,"aria-label":k("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(br,{size:17})})}),t(Or,{title:k("New conversation"),children:t("button",{type:"button",onClick:()=>m(),"aria-label":k("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(Zn,{size:17})})})]});const G=e=>t(Ao,{conversation:e,isActive:e.conversationId===l,isEditing:e.conversationId===S,draftTitle:T,onDraftTitleChange:A,onCommitRename:O,onCancelRename:P,onStartRename:g?z:void 0,onSelect:p,onDelete:h,fileable:f?V:void 0,onMove:H,actions:w,t:k},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:()=>m(),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(Zn,{size:15}),k("New conversation")]}),y,t(Or,{title:k("Hide conversations"),children:t("button",{type:"button",onClick:d,"aria-label":k("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(br,{size:17})})})]}),r.length>7&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(yr,{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:N,onChange:e=>C(e.target.value),onKeyDown:e=>{"Escape"===e.key&&C("")},placeholder:k("Search conversations..."),"aria-label":k("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:[a&&0===r.length&&t("div",{className:"px-3 py-2",children:t(jr,{size:16})}),e(n,F&&f?{children:[!W&&e("div",{className:"flex items-center justify-between px-2 pb-1 pt-1",children:[t("span",{className:No,children:k("Workspaces")}),t(Or,{title:k("New workspace"),children:t("button",{type:"button",onClick:()=>$(!0),"aria-label":k("New workspace"),className:ko,children:t(ar,{size:14})})})]}),R&&t(Io,{placeholder:k("Workspace name"),onSubmit:async e=>{if($(!1),!e)return;const t=await f.onCreate(e);t.ok||U(t.error,"The workspace could not be created")},onCancel:()=>$(!1)}),F.groups.map(e=>t(To,{workspace:e.workspace,count:e.conversations.length,open:we(e.key,M,e,l,!!W),toggleable:ye(e,l,!!W),pending:!!e.workspace&&f.pendingWorkspaceId===e.workspace.id&&!l,onToggle:()=>{return t=e.key,void L(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),_t("local",E,JSON.stringify([...n])),n});var t},onNewChat:f.onNewChat,onRename:async(e,t)=>{const n=await f.onRename(e,t);n.ok||U(n.error,"The workspace could not be renamed")},onDelete:async e=>{const t=await f.onDelete(e);t.ok||U(t.error,"The workspace could not be deleted")},onDropConversation:t=>e.workspace&&void H(t,e.workspace.id),t:k,children:e.conversations.length>0?e.conversations.map(G):t("p",{className:"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30",children:k("Drop a conversation here, or start one with +.")})},e.key)),e(So,{onDropConversation:e=>{H(e,null)},accepts:!0,children:[e("div",{className:"flex items-center justify-between px-2 pb-1 pt-3",children:[t("span",{className:No,children:k("Not in a workspace")}),t("span",{className:"text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30",children:F.unfiled.length})]}),F.unfiled.map(G),K&&t("p",{className:"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30",children:k("none"===K?"No conversations yet":"Every conversation is in a workspace.")})]}),W&&0===F.groups.length&&0===F.unfiled.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:k("No conversation matches")})]}:{children:[!a&&0===r.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:k("No conversations yet")}),r.length>0&&0===B.length&&t("p",{className:"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40",children:k("No conversation matches")}),B.map(G)]}),x,b&&r.length>0&&!W&&t($r,{onClear:b,className:"px-2 pt-3",iconButtonClass:ko,t:k})]}),D&&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:D})]})},So=({onDropConversation:e,accepts:n,children:r,className:a=""})=>{const[i,l]=o(!1),c=s(0),d=e=>e.dataTransfer.types.includes(bo);return t("div",{className:`rounded-lg transition-colors ${i?"bg-[var(--chat-accent)]/10 ring-1 ring-[var(--chat-accent)]/40":""} ${a}`,...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(bo);n&&e(n)}}:{},children:r})},Io=({initial:e="",placeholder:n,onSubmit:r,onCancel:a})=>{const[l,c]=o(e),d=s(!1),u=s(null);i(()=>{u.current?.focus(),u.current?.select()},[]);const p=()=>{d.current||(d.current=!0,r(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&&p(),"Escape"===e.key&&(d.current=!0,a())},onBlur:p,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)]"})},To=({workspace:r,count:a,open:s,toggleable:i,pending:l,onToggle:c,onNewChat:d,onRename:u,onDelete:p,onDropConversation:h,t:g,children:m})=>{const[f,v]=o(!1),[w,y]=o(!1),x=!!r?.canManage,b=!!r&&r.isDefault&&r.isOwn;return e(So,{onDropConversation:h,accepts:x,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&&r?t(Io,{initial:r.name,placeholder:g("Workspace name"),onSubmit:e=>{v(!1),e&&e!==r.name&&u(r.id,e)},onCancel:()=>v(!1)}):e("button",{type:"button",onClick:c,disabled:!i,"aria-expanded":s,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left disabled:cursor-default",children:[t(Vn,{size:12,className:"shrink-0 text-gray-400 dark:text-white/30 transition-transform "+(s?"rotate-90":"")}),t(nr,{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:r?r.name:g("Other workspaces")}),b&&t("span",{className:"shrink-0 rounded bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] text-[var(--chat-accent)]",children:g("default")}),t("span",{className:"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30",children:a})]}),r&&x&&!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,w?{children:[t("span",{className:"px-1 text-[0.65rem] text-red-600 dark:text-red-400",children:g("Delete?")}),t("button",{type:"button",onClick:()=>{y(!1),p(r.id)},"aria-label":g("Delete workspace"),className:`${ko} hover:text-red-500`,children:t(Bn,{size:13})}),t("button",{type:"button",onClick:()=>y(!1),"aria-label":g("Cancel"),className:ko,children:t(Kn,{size:13})})]}:{children:[t(Or,{title:g("New conversation in this workspace"),children:t("button",{type:"button",onClick:()=>d(r.id),"aria-label":g("New conversation in this workspace"),className:ko,children:t(Zn,{size:13})})}),t(Or,{title:g("Rename workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":g("Rename workspace"),className:ko,children:t(vr,{size:13})})}),!r.isDefault&&t(Or,{title:g("Delete workspace"),children:t("button",{type:"button",onClick:()=>y(!0),"aria-label":g("Delete workspace"),className:`${ko} hover:text-red-500`,children:t(Tr,{size:13})})})]})})]}),s&&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(Zn,{size:12}),g("New conversation — send a message to start it")]}),m]})]})},Ao=({conversation:r,isActive:a,isEditing:i,draftTitle:l,onDraftTitleChange:c,onCommitRename:d,onCancelRename:u,onStartRename:p,onSelect:h,onDelete:g,fileable:m,onMove:f,actions:v,t:w})=>{const[y,x]=o(!1),b=s(null),k=!!m&&!i;return e("div",{role:"button",tabIndex:0,"aria-current":a,draggable:k,onDragStart:k?e=>{e.dataTransfer.setData(bo,r.conversationId),e.dataTransfer.effectAllowed="move"}:void 0,onClick:()=>h(r.conversationId),onKeyDown:e=>{e.target===e.currentTarget&&("Enter"!==e.key&&" "!==e.key||(e.preventDefault(),h(r.conversationId)))},className:"group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors "+(a?"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 "+(a?"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(Hn,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[i?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] "+(a?"text-gray-900 dark:text-white":"text-gray-700 dark:text-white/70"),children:r.title||w("Untitled conversation")}),(r.agentName||r.updatedAt)&&!i&&e("span",{className:"block text-[0.65rem] text-gray-400 dark:text-white/30 truncate",children:[r.agentName,r.agentName&&r.updatedAt?" · ":"",r.updatedAt?M(r.updatedAt,w):""]})]}),!i&&e("span",{className:"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[v&&t("span",{className:"flex",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:v(r)}),k&&e(n,{children:[t("button",{ref:b,type:"button",onClick:e=>{e.stopPropagation(),x(e=>!e)},"aria-label":w("Move to workspace"),title:w("Move to workspace"),"aria-expanded":y,className:"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]",children:t(rr,{size:13})}),t(Dr,{open:y,onClose:()=>x(!1),anchorRef:b,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")}),m.map(n=>e("button",{type:"button",disabled:n.id===r.workspaceId,onClick:()=>{x(!1),f(r.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(nr,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===r.workspaceId&&t(Bn,{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:!r.workspaceId,onClick:()=>{x(!1),f(r.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(Kn,{size:13,className:"shrink-0"}),w("Remove from workspace")]})]})})]}),p&&t("button",{type:"button",onClick:e=>{e.stopPropagation(),p(r.conversationId,r.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(Zn,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),g(r.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(Tr,{size:13})})]})]})},_o=new Set([502,503,504]),Eo=new Set([401,403]),Mo=m(function(e,n){const r=s(e.onSessionEnded);r.current=e.onSessionEnded;const a=s("");a.current=ke(e.requestHeaders);const o=u(()=>{let e=null;const t=t=>{r.current&&e!==a.current&&(e=a.current,Mt(r.current,t))};return{sessionEnded:t,fetch:(n=()=>r.current?t:void 0,async(e,t)=>{const r=await globalThis.fetch(e,t),a=401===r.status?n():void 0;return a&&"function"==typeof r.clone&&r.clone().json().then(e=>{const t=function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(!t||"object"!=typeof t)return null;const{code:n,reason:r}=t;return"session_expired"!==n?null:{reason:"string"==typeof r&&r?r:void 0}}(e);t&&a(t.reason)}).catch(()=>{}),r})};var n},[]);return t(jt,{value:o,children:t(Lo,{...e,ref:n})})}),Lo=m(function({mode:n,onClose:r,onModeChange:d,topOffset:p=0,apiBaseUrl:h,apiEndpoints:g,agentDashboardUrl:m,waitingGameUrl:v,user:w,t:y,accentColor:x="#7b5cff",logoIcon:b,promptSuggestions:k,draftBorderColor:C,resizable:S=!1,onWidthChange:I,onResizeStart:T,onResizeEnd:A,disableFileManagement:_=!1,onRelativeLinkClick:E,onDownloadError:M,maxFileCount:L,maxTotalSize:R,requestHeaders:D,pageContext:j,pushContentSelector:z,backendType:O="rest",miniGameEnabled:U=!0,onPlayWaitingGame:H,notifyOnComplete:W=!0,onTaskComplete:q,onMessageFeedback:B,locale:F,disableImagePreviews:V=!1,contextUsageEnabled:G=!0,composerToolbar:Z,storageKeyPrefix:ee,conversationId:te,onConversationChange:ne,initialAgent:ae,onAgentChange:oe,readOnly:se=!1,readOnlyNotice:ie,getRequestExtras:le,onStreamEvent:ce,markerRenderers:de,codeBlockRenderers:pe,transformMessageText:he,onArtifactOpen:ge,headerActions:me,banner:ve,composerHeader:we,transcriptFooter:ye,welcome:xe,renderMessageExtras:Ne,messageFooterActions:Ce,sidebarRowActions:Ie,sidebarHeaderActions:Te,sidebarSections:Ae,statusLabel:Ee,waitingMessages:Me,renderWaitingPanel:Le,fontFamily:Re,onReady:$e,onBeforeSend:De,onHeldSendSettled:je,onTurnRunningChange:ze,steerAttachments:Pe=!1,holdSendsDuringTurn:He=!1,agentMentions:We=!1,hideConversationList:qe=!1},Be){const Fe=In(g),Ve=In(D),Ke=In(j),Ge=In(k),Je=Tn(E),Ye=Tn(M),Xe=Tn(H),Ze=Tn(q),Qe=Tn(B),et=Tn(ne),tt=Tn(oe),nt=Tn(le),rt=Tn(De),at=Tn(je),ot=Tn(ce),st=Tn(ze),it=Tn(ge),lt=s(null),{fetch:ct,sessionEnded:dt}=a(Dt),ut=u(()=>Q(y,F),[y,F]),pt=In(Me),ht=u(()=>de?Object.fromEntries(Object.entries(de).map(([e,t])=>[e.toUpperCase(),t])):void 0,[de]),gt=In(u(()=>pe?Object.fromEntries(Object.entries(pe).map(([e,t])=>[e.toLowerCase(),t])):void 0,[pe])),mt=In(u(()=>function(e){const t=new Set;for(const n of e??[]){const e=n.toUpperCase();$.test(e)&&t.add(e)}return[...t].sort()}(ht&&Object.keys(ht)),[ht])),ft=u(()=>({statusLabel:Ee,waitingMessages:pt,renderWaitingPanel:Le}),[Ee,pt,Le]),vt="fullscreen"===n||"inline"===n,[wt,yt]=o(!1),{agents:xt,agentsLoading:bt,agentsError:Nt,agentsSettled:Ct,agentsDisabled:St,selectedAgent:Tt,agentMenuOpen:Et,setAgentMenuOpen:Lt,handleSwitchAgent:Rt,reloadAgents:$t}=fn({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve,storageKeyPrefix:ee,initialAgent:ae,onAgentChange:oe?tt:void 0}),[jt,Ot]=o(null),Pt=s(null),[Ut,Ht]=o(null),[Wt,qt]=o(void 0),[Bt,Ft]=o(null),[Vt,Kt]=o(null),Gt=s(0),[Jt,Yt]=o(null),en=s(async()=>{}),tn=s(()=>{}),nn=l((e,t)=>{Mt(tn.current,e,t.relayed),Mt(ot,e,t)},[ot]),{messages:rn,inputValue:an,setInputValue:on,isLoading:sn,turnRunning:ln,sendsHeld:cn,turnEnd:dn,agentStatus:un,attachedFiles:pn,conversationId:hn,contextUsage:yn,transferredAgent:xn,canSteer:bn,pendingApprovals:kn,isSubmittingApproval:An,approvalError:En,submitApprovalDecisions:Mn,isResumingAfterDecision:Ln,historyReloadNonce:Rn,reloadHistory:Dn,mergeTurnHistory:Pn,settleUnseenEnd:Un,historyLoadedRef:Hn,conversationIdRef:Wn,handleFileAdd:qn,handlePaste:Bn,handleSendMessage:Fn,skipWait:Vn,readPendingApprovals:Kn,heldMessage:Gn,notice:Jn,cancelHeldMessage:Xn,agentMentions:Zn,addAgentMention:Qn,handleNewChat:er,pendingWorkspaceId:tr,clearPendingWorkspace:nr,handleStopGenerating:rr,conversationRefs:ar,addConversationRef:or,setAttachedFiles:sr,setMessages:ir,setContextUsage:lr,updateConversationId:cr,handleSwitchConversation:dr}=gn({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,agentSlug:Tt?.slug,requestHeaders:Ve,pageContext:Ke,onRelativeLinkClick:E?Je:void 0,t:ut,maxFileCount:L,maxTotalSize:R,storageKeyPrefix:ee,controlledConversationId:te,onConversationIdChange:ne?et:void 0,getRequestExtras:le?nt:void 0,onStreamEvent:nn,onSessionEnded:dt,onConversationTitle:()=>{en.current()},historySettledFor:Ut,steerAttachments:Pe,holdSends:He,agentMentionsEnabled:We,onBeforeSend:De?rt:void 0,onHeldSendSettled:je?at:void 0});Wt!==hn&&(qt(hn),null!==Ut&&Ht(null)),i(()=>{void 0!==te&&te!==Wn.current&&(te?dr(te):er())},[te]);const{suggestions:ur,loading:pr}=Sn({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve,agentSlug:Tt?.slug}),hr=u(()=>(ur??Ge)?.map(e=>ut(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")])(ut),[ur,Ge,ut]),{prompts:gr,quota:mr,refreshQuota:fr}=Cn({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve}),{historyEnabled:vr,conversations:wr,conversationsLoading:yr,refreshConversations:xr,deleteConversation:br,renameConversation:kr,moveConversation:Nr,clearConversations:Cr}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=zt(),[s,i]=o([]),[c,d]=o(!1),u="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,p=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,h=l(async()=>{if(u){d(!0);try{const e=await a(p,{method:"GET",headers:{...r??{}}});if(!e.ok)return void i([]);const t=await e.json(),n=Array.isArray(t)?t:Array.isArray(t?.conversations)?t.conversations:[];i(n.map(vn).filter(e=>null!==e))}catch{i([])}finally{d(!1)}}},[u,p,r]),g=l(async e=>{if(!u)return!1;try{return!!(await a(`${p}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...r??{}}})).ok&&(i(t=>t.filter(t=>t.conversationId!==e)),!0)}catch{return!1}},[u,p,r]),m=u&&t?.clearAll?`${e}${t.clearAll}`:null,f=l(async()=>{if(!m)return!1;try{return!!(await a(m,{method:"DELETE",headers:{...r??{}}})).ok&&(i([]),!0)}catch{return!1}},[m,r]),v=l(async(e,t)=>{const n=t.trim();if(!u||!n)return!1;const o=s;i(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{return!!(await a(`${p}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({title:n})})).ok||(i(o),!1)}catch{return i(o),!1}},[u,p,r,s]),w=l(async(e,t)=>{if(!u)return"";const n=s.find(t=>t.conversationId===e)?.workspaceId,o=()=>i(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));i(n=>n.map(n=>n.conversationId===e?{...n,workspaceId:t}:n));try{const n=await a(`${p}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({workspace_id:t})});return n.ok?null:(o(),await be(n)??"")}catch{return o(),""}},[u,p,r,s]);return{historyEnabled:u,conversations:s,conversationsLoading:c,refreshConversations:h,deleteConversation:g,renameConversation:v,moveConversation:w,clearConversations:m?f:null}}({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve});en.current=xr;const{workspacesEnabled:Sr,workspaces:Ir,refreshWorkspaces:Tr,createWorkspace:Ar,renameWorkspace:_r,deleteWorkspace:Er}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=zt(),[i,c]=o([]),[d,u]=o(!1),p=s(0),h=t?.workspaces,g="rest"===n&&!t?.singleEndpoint&&"string"==typeof h&&h.length>0,m=g?`${e}${h}`:null,f=l(async()=>{if(!m)return;const e=++p.current;try{const n=await a(m,{method:"GET",headers:{...r??{}}});if(e!==p.current)return;if(!n.ok)return void(408===(t=n.status)||429===t||t>=500&&501!==t||(u(!1),c([])));const o=fe(await n.json());if(e!==p.current)return;c(o),u(!0)}catch{}var t},[m,r]),v=l(async(e,t,n)=>{try{const o=await a(t,{method:e,headers:{...n?{"Content-Type":"application/json"}:{},...r??{}},...n?{body:JSON.stringify(n)}:{}});if(!o.ok)return{ok:!1,error:await be(o)};const s=204===o.status?[]:fe([await o.json().catch(()=>null)]);return await f(),{ok:!0,workspace:s[0]}}catch{return{ok:!1,error:null}}},[r,f]),w=l(async e=>m?v("POST",m,{name:e.trim()}):{ok:!1,error:null},[m,v]),y=l(async(e,t)=>m?v("PATCH",`${m}/${encodeURIComponent(e)}`,{name:t.trim()}):{ok:!1,error:null},[m,v]),x=l(async e=>m?v("DELETE",`${m}/${encodeURIComponent(e)}`):{ok:!1,error:null},[m,v]);return{workspacesEnabled:g&&d,workspaces:i,refreshWorkspaces:f,createWorkspace:w,renameWorkspace:y,deleteWorkspace:x}}({apiBaseUrl:h,apiEndpoints:Fe,backendType:O,requestHeaders:Ve});i(()=>{Sr&&tr&&!function(e,t){return t.some(t=>t.id===e&&t.canManage)}(tr,Ir)&&nr(tr)},[Sr,Ir,tr,nr]);const[Mr,Lr]=o(!1),[Rr,$r]=o(!1),Dr=vt&&vr&&!qe;i(()=>{Dr&&xr()},[Dr,hn,xr]),i(()=>{Dr&&Tr()},[Dr,hn,Tr]);const jr=s(null);i(()=>{if(!Dr)return;const e=()=>{if("visible"!==document.visibilityState)return;const e=Date.now();(function(e,t){return null===t||e-t>=2e3})(e,jr.current)&&(jr.current=e,xr(),Tr())};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[Dr,xr,Tr]);const zr=s(!1);i(()=>{zr.current!==ln&&(zr.current=ln,ln?Mt(st,!0):Mt(st,!1,{ended:dn??"stopped"}))},[ln,dn,st]),i(()=>()=>{zr.current&&(zr.current=!1,Mt(st,!1,{ended:"stopped"}))},[st]);const Or=s(!1);i(()=>{Or.current&&!ln&&(fr(),Dr&&(xr(),Tr())),Or.current=ln},[ln,fr,Dr,xr,Tr]);const Pr=e=>{Lr(!1),dr(e)},Ur=ue(h,Fe,O),Wr=u(()=>new Set(wr.map(e=>e.conversationId)),[wr]),qr=Tn(vr?Pr:void 0),Br=rn.some(e=>(e.conversationRefs?.length??0)>0);i(()=>{Br&&vr&&xr()},[Br,vr,xr,hn]);const Fr=X(h,Fe,O,"messagesPage"),[Vr,Kr]=o(!1),Gr=X(h,Fe,O,"tts"),Jr=u(()=>Gr?{url:Gr,requestHeaders:Ve}:void 0,[Gr,Ve]),Yr=s(rn);Yr.current=rn,i(()=>Kr(!1),[hn]);const Xr=l(async()=>{const e=Wn.current,t=Yr.current.find(e=>e.serverId)?.serverId;if(!Fr||!e||!t)return Kr(!1),0;try{const n=await ct(`${Fr}/${encodeURIComponent(e)}/messages?before=${encodeURIComponent(t)}&limit=50&supports_artifacts=true`,{headers:{...Ve??{}}});if(!n.ok||Wn.current!==e)return 0;const r=await n.json();if(Wn.current!==e)return 0;const a=new Set(Yr.current.map(e=>e.serverId).filter(Boolean)),o=Ue(r?.messages).filter(e=>!e.serverId||!a.has(e.serverId)).map(e=>({...e,id:Oe(e.serverId)}));return ir(e=>[...o,...e]),Kr(!0===r?.has_more&&o.length>0),o.length}catch{return 0}},[Fr,Wn,Ve,ir]),Qr=(e,t,n)=>{if(Ht(e),Kr(!!Fr&&!0===t.has_more),!t.messages?.length)return;const r=Ue(t.messages);if(n)ir(e=>function(e,t){const n=[...e],r=new Map;n.forEach((e,t)=>{e.serverId&&r.set(e.serverId,t)});const a=new Set,o=new Map;let s=-1,i=!1;for(const e of t){let t=void 0!==e.serverId?r.get(e.serverId):void 0;if(void 0===t){const r=Zt(e),o=n.findIndex((e,t)=>!a.has(t)&&!e.serverId&&Xt(e)===r);o>=0&&(t=o,n[o]=Qt(n[o],e),i=!0)}if(void 0!==t){a.add(t),s=Math.max(s,t);continue}const l=o.get(s)??[];l.push({...e,id:Oe(e.serverId)}),o.set(s,l)}if(0===o.size)return i?n:e;const l=[...o.get(-1)??[]];return n.forEach((e,t)=>{l.push(e,...o.get(t)??[])}),l}(e,r));else{ir(r);for(let e=t.messages.length-1;e>=0;e-=1){const n=Se(t.messages[e]);if(n){lr(n);break}}}},ea=s(sn);ea.current=sn,i(()=>{Gt.current=0},[hn]),i(()=>{Bt&&!sn&&(Ft(null),Bt.conversationId===hn&&Qr(Bt.conversationId,Bt.data,!0))},[Bt,sn,hn]),i(()=>{if(!Vt||Vt!==hn||sn)return;const e=()=>{ea.current||(Kt(null),Gt.current+=1,Dn())},t=Math.min(6e4,5e3*2**Gt.current),n=window.setTimeout(e,t),r=()=>{"visible"===document.visibilityState&&e()};return window.addEventListener("online",e),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(n),window.removeEventListener("online",e),document.removeEventListener("visibilitychange",r)}},[Vt,hn,sn,Dn]);const ta=ke(Ve),na=l(()=>{Yt(null),Dn()},[Dn]);i(()=>{Jt&&Jt.conversationId===hn&&!sn&&Jt.headersKey!==ta&&na()},[Jt,hn,sn,ta,na]);const ra=Jt&&Jt.conversationId===hn?Jt:null,aa="rest"===O&&!Fe?.singleEndpoint&&null!==Fe?.sessions&&!!hn&&jt!==hn,oa=!se&&!_&&"rest"===O&&!Fe?.singleEndpoint&&null!==Fe?.upload,[sa,ia]=o(!1),la=s(0),ca=e=>e.dataTransfer.types.includes("Files"),da=oa?{onDragEnter:e=>{ca(e)&&(la.current+=1,ia(!0))},onDragOver:e=>{ca(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDragLeave:e=>{ca(e)&&(la.current=Math.max(0,la.current-1),0===la.current&&ia(!1))},onDrop:e=>{ca(e)&&(e.preventDefault(),e.stopPropagation(),la.current=0,ia(!1),qn(e.dataTransfer.files))}}:{},ua=async()=>{await(Cr?.())&&er()},pa=async e=>{await br(e)&&e===Wn.current&&er()},{sidebarWidth:ha,handleResizeStart:ga,defaultWidth:ma,isResizing:fa}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:r,onResizeEnd:a,storageKeyPrefix:l}){const c=It(l,kt),[d,u]=o(()=>{const e=At("local",c);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=wn)return t}return wn}),[p,h]=o(!1),g=s(!1),m=s(d);m.current=d;const f=s(n);f.current=n;const v=s(a);return v.current=a,i(()=>{"sidebar"===e&&t&&f.current?.(m.current)},[e,t]),i(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!g.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,wn),n);u(r),m.current=r,f.current?.(r)},r=()=>{g.current&&(g.current=!1,h(!1),document.body.style.cursor="",document.body.style.userSelect="",_t("local",c,String(m.current)),v.current?.())},a=()=>{const e=.4*window.innerWidth;if(m.current>e){const t=Math.max(e,wn);u(t),m.current=t,f.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,c]),{sidebarWidth:d,handleResizeStart:e=>{e.preventDefault(),g.current=!0,h(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",r?.()},defaultWidth:wn,isResizing:p}}({mode:n,resizable:S,onWidthChange:I,onResizeStart:T,onResizeEnd:A,storageKeyPrefix:ee});i(()=>{const e="sidebar"===n?S?ha:ma:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",fa?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),z){const e=document.querySelector(z);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=fa?"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")}},[z,n,ha,ma,S,fa]);const va=u(()=>b??t(Yn,{size:24}),[b]),wa=u(()=>function(e,t){if(void 0!==t){const e=t.trim();return/^https?:\/\//i.test(e)||/^\/(?![/\\])/.test(e)?e:null}const n=e?.trim().replace(/\/+$/,"");return n&&/^https?:\/\//i.test(n)?`${n}/chat?arcade=play`:null}(m,v),[m,v]),ya=w.firstName,[xa,ba]=o(null),ka=xn?.name||xa||Tt?.name||ut("Assistant"),Na=l(()=>{const e=lt.current;return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);Nn({isLoading:ln,agentName:ka,t:ut,enabled:W,onComplete:Ze,isViewingChat:Na});const Sa=null!=Fe?.download,Ia="rest"===O&&null!==Fe?.download&&(!Fe?.singleEndpoint||Sa),Ta=l(e=>`${h}${Fe?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[h,Fe]),Aa=l(async e=>{const t=Ta(e);try{const n=await ct(t,{method:"GET",credentials:"include",headers:{...Ve??{}}});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){Ye?.(t,e)}},[Ta,Ve,Ye]),_a="rest"===O&&Fe?.artifacts?`${h}${Fe.artifacts}`:null,Ea=l((e,t)=>`${_a}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,[_a]),Ma=l(async(e,t)=>{const n=`${e.title||e.kind}.${function(e){return"pptx_native"===e?"pptx":e}(t)}`;try{const r=await ct(`${Ea(e.kind,e.id)}/download`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...Ve??{}},body:JSON.stringify({format:t})});if(!r.ok)throw new Error(`Download failed: ${r.status}`);const a=await r.blob(),o=URL.createObjectURL(a),s=document.createElement("a");s.href=o,s.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(s),s.click(),s.remove(),URL.revokeObjectURL(o)}catch(r){Ye?.(r,{fileId:e.id,filename:n,type:t.toUpperCase()})}},[Ea,Ve,Ye]),La=l(async(e,t)=>{const n=await ct(Ea(e,t),{credentials:"include",headers:{...Ve??{}}});if(n.ok)return _e(await n.json())},[Ea,Ve]),Ra={"--chat-accent":x,"--chat-accent-10":N(x,.1),"--chat-accent-40":N(x,.25),"--chat-accent-50":N(x,.5),"--chat-accent-dark":x,...Re?{fontFamily:Re}:{}},$a=s(Pn);$a.current=Pn;const Da=s(Un);Da.current=Un;const ja=s(!0);i(()=>(ja.current=!0,()=>{ja.current=!1}),[]),i(()=>{if(null===Fe?.sessions||Fe?.singleEndpoint||"legacy"===O||"ag-ui"===O)return;if(!hn)return ba(null),void Ot(null);if(Hn.current)return Pt.current!==hn&&jt!==hn&&Ot(hn),void(Pt.current!==hn&&Ut!==hn&&Bt?.conversationId!==hn&&Ht(hn));if(!Tt&&!St)return void(Ct&&jt!==hn&&Ot(hn));Hn.current=!0,Pt.current=hn,Ot(null);const e=`${h}${Fe?.sessions??"/chat/sessions"}`,t=hn,n=()=>!ja.current||Wn.current!==t,r=ke(Ve),a=Rn;ct(e,{method:"POST",headers:{"Content-Type":"application/json",...Ve??{}},body:JSON.stringify({conversation_id:hn,agent_slug:Tt?.slug,supports_artifacts:!0})}).then(e=>n()?null:e.ok?(Gt.current=0,Kt(null),Yt(null),e.json()):(Da.current(a,null),Eo.has(e.status)?be(e).then(e=>(n()||Yt({conversationId:t,detail:e,headersKey:r}),null)):(_o.has(e.status)?Kt(t):cr(null),null))).then(e=>{if(!e||n())return;"string"==typeof e.conversation_id&&e.conversation_id&&e.conversation_id!==t&&cr(e.conversation_id),ba("string"==typeof e.agent_name?e.agent_name:null);const r=Ue(e.messages);Da.current(a,r),$a.current(r)||(ea.current?Ft({conversationId:t,data:e}):Qr(t,e,!1))}).catch(()=>{n()||(Da.current(a,null),Kt(t))}).finally(()=>{Pt.current===t&&(Pt.current=null),n()||Ot(t)})},[hn,Tt,Ct,jt,Fr,h,Fe,O,Bt,Rn,Hn,Wn,ja,Ve,ir,lr,cr]);const za=s(Fn);za.current=Fn;const Oa=s(er);Oa.current=er;const Pa=s(dr);Pa.current=dr;const Ua=s(xt);Ua.current=xt;const Ha=s(Tt);Ha.current=Tt;const Wa=Ct&&!aa,qa=Tn($e),Ba=s(!1);i(()=>{Wa&&!Ba.current&&(Ba.current=!0,qa?.())},[Wa,qa]);const Fa=s([]),[Va,Ka]=o(0),Ga=(e,t)=>{Fa.current.push({run:e,drop:t}),Ka(e=>e+1)};i(()=>{if(!Wa||0===Fa.current.length)return;Fa.current.shift().run(),Fa.current.length>0&&Ka(e=>e+1)},[Wa,Va]),i(()=>()=>{queueMicrotask(()=>{if(!ja.current)for(const e of Fa.current.splice(0))e.drop?.()})},[]);const Ja=s(Rt);Ja.current=Rt;const Ya=s(rr);Ya.current=rr;const Xa=s(se);Xa.current=se;const Za=s(an);Za.current=an;const Qa=xn?.id??(xa?xt.find(e=>e.name===xa)?.id:void 0)??Tt?.id??null,eo=function(e){const t=zt(),n=s(e);c(()=>{n.current=e});const[r,a]=o(null),d=s(null),u=l(async(e,r)=>{const{tts:a,locale:o}=n.current,s=o||("undefined"!=typeof navigator?navigator.language:void 0),i=J(e,200),l=a?Y(t,a,i,r):null;for(const e of i){if(r.aborted)return;const t=l?(await l.next()).value??null:null;if(r.aborted)return;if(!t||!await jn(t,r)){if(r.aborted)return;await zn(e,s,r)}}},[]),p=l(()=>{if(d.current)return!0;const e=_n();if(!e)return!1;const t=$n({recognition:new e,lang:n.current.locale||("undefined"!=typeof navigator?navigator.language:void 0),send:(e,t)=>n.current.send(e,t),speak:u,speakable:e=>Mt(n.current.speakable,e)??e,present:e=>Mt(n.current.present,e)??e,probe:()=>{const e=n.current.readTurnState;return e?async function(e){try{const t=await e();return t?t.running?"running":"over":"unknown"}catch{return"unknown"}}(e):Promise.resolve("over")},stopTurn:()=>n.current.stopTurn(),addressedAgentId:()=>n.current.addressedAgentId(),onChange:e=>{d.current===t&&a(e)}});return d.current=t,t.start(),!0},[u]),h=l(()=>{const e=d.current;d.current=null,e?.end(),a(null)},[]);return i(()=>h,[h]),{snapshot:r,start:p,end:h,onFrame:l((e,t)=>d.current?.frame(e,t),[]),interrupt:l(()=>d.current?.interrupt(),[]),cancel:l(()=>d.current?.cancel(),[]),toggleMute:l(()=>d.current?.toggleMute(),[])}}({send:(e,t)=>za.current({text:e,source:"voice",onSent:t.onAccepted,onNotSent:t.onNotSent,onSteered:t.onSteered}),stopTurn:()=>Ya.current(),readTurnState:Kn?async()=>{const e=Wn.current,t=e?await Kn(e):null;return t&&{running:t.turnRunning}}:void 0,addressedAgentId:()=>Qa,speakable:e=>K(P(e,mt)),present:e=>he?he(e,{id:"voice-call",role:"assistant",content:e,timestamp:new Date}):e,tts:Jr,locale:F});tn.current=eo.onFrame;f(Be,()=>({send:(e,t)=>Xa.current?Promise.resolve("dropped"):new Promise(n=>Ga(()=>{Xa.current?n("dropped"):za.current({text:e,extras:t?.extras,displayText:t?.displayText,onSent:()=>n("sent")}).then(n,()=>n("failed"))},()=>n("dropped"))),newConversation:e=>Ga(()=>{const t=mn(Ua.current,e?.agent);t&&t.id!==Ha.current?.id&&Ja.current(t),Oa.current(e?.workspaceId)}),selectConversation:e=>Ga(()=>Pa.current(e)),setDraft:e=>{Za.current=e,on(e)},getDraft:()=>Za.current,focusComposer:()=>lt.current?.querySelector("textarea")?.focus(),stop:()=>{eo.cancel(),Ya.current()},startVoiceCall:()=>!Xa.current&&eo.start(),reloadAgents:$t,scrollToMessage:e=>{const t=[...lt.current?.querySelectorAll("[data-message-id]")??[]].find(t=>t.dataset.messageId===e);return!!t&&(t.scrollIntoView?.({block:"center",behavior:"smooth"}),t.classList.add("filigran-chat-highlight"),window.setTimeout(()=>t.classList.remove("filigran-chat-highlight"),2e3),!0)}}),[]);const to=(()=>{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]`;case"inline":return`${e} relative flex flex-col h-full w-full min-h-0 bg-gray-50 dark:bg-[#161622]`;default:return e}})(),no={...Ra,..."sidebar"===n?{top:p,width:S?ha:ma}:"floating"===n?{width:380,height:560}:"inline"===n?{}:{top:p}};return e("div",{ref:lt,className:to,style:no,"data-testid":"filigran-chat-panel",children:["sidebar"===n&&S&&t("div",{onMouseDown:ga,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(Hr,{mode:n,agentName:ka,agents:xt,agentsLoading:bt,agentsError:Nt,selectedAgent:Tt,transferredFrom:xn?Tt?.name:void 0,agentMenuOpen:Et,onAgentMenuToggle:()=>Lt(e=>!e),onAgentMenuClose:()=>Lt(!1),onSwitchAgent:e=>{e&&Rt(e,()=>{er()})},modeMenuOpen:wt,onModeMenuToggle:()=>yt(e=>!e),onModeMenuClose:()=>yt(!1),onModeChange:d,onNewChat:er,onClose:r,logoIcon:va,actions:me,agentDashboardUrl:m,historyEnabled:vr&&!Dr,historyMenuOpen:Mr,onHistoryMenuToggle:()=>{const e=!Mr;e&&xr(),Lr(e)},onHistoryMenuClose:()=>Lr(!1),conversations:wr,conversationsLoading:yr,activeConversationId:hn,onSelectConversation:Pr,onDeleteConversation:e=>{pa(e)},onClearAll:Cr?()=>{ua()}:void 0,t:ut}),e("div",{className:Dr?"flex flex-1 min-h-0":"contents",children:[Dr&&t(Co,{conversations:wr,loading:yr,activeConversationId:hn,collapsed:Rr,onToggleCollapsed:()=>$r(e=>!e),onSelect:Pr,onDelete:e=>{pa(e)},onRename:(e,t)=>{kr(e,t)},onNewChat:er,workspaces:Sr?{list:Ir,pendingWorkspaceId:tr,onCreate:Ar,onRename:_r,onDelete:async e=>{const t=await Er(e);return t.ok&&(nr(e),xr()),t},onMove:Nr,onNewChat:e=>{er(e),Tr()}}:void 0,storageKeyPrefix:ee,rowActions:Ie,headerActions:Te,sections:Ae,onClearAll:Cr?()=>{ua()}:void 0,t:ut}),e("div",{className:Dr?"relative flex flex-1 flex-col min-w-0":"contents",...da,children:[sa&&t("div",{className:"pointer-events-none absolute inset-2 z-30 flex items-center justify-center rounded-xl border-2 border-dashed border-[var(--chat-accent)] bg-[var(--chat-accent)]/10 text-sm font-medium text-[var(--chat-accent)]",children:ut("Drop files to attach them")}),ve&&t("div",{className:"shrink-0",children:ve}),0===rn.length&&aa?t("div",{"data-testid":"filigran-chat-loading",className:"flex-1 flex flex-col gap-4 px-4 py-6","aria-busy":"true",children:[0,1,2].map(e=>t("div",{className:"flex "+(e%2?"justify-end":"justify-start"),children:t("div",{className:"h-10 rounded-xl bg-gray-200/70 dark:bg-white/[0.06] animate-pulse "+(e%2?"w-1/3":"w-2/3")})},e))}):0===rn.length&&ra?e("div",{"data-testid":"filigran-chat-restore-error",role:"alert",className:"flex-1 flex flex-col items-center justify-center gap-3 px-6 py-6 text-center",children:[t(On,{size:18,className:"text-amber-500 dark:text-amber-400"}),t("p",{className:"max-w-sm text-[0.8125rem] leading-6 text-gray-600 dark:text-white/60",children:ra.detail??ut("This conversation could not be loaded.")}),t("button",{type:"button",onClick:na,className:"rounded-md border border-gray-200 dark:border-white/10 px-3 py-1 text-[0.75rem] font-medium text-gray-700 dark:text-white/80 transition-colors hover:bg-gray-100 dark:hover:bg-white/[0.06]",children:ut("Retry")})]}):0===rn.length?xe?t("div",{className:"flex-1 min-h-0 overflow-y-auto filigran-chat-scrollable",children:xe}):t(xo,{firstName:ya,logoIcon:va,promptSuggestions:hr,suggestionsLoading:pr,agentName:Tt?.name,agentDescription:Tt?.description,onPromptClick:se?void 0:on,t:ut}):t(fo,{messages:rn,isLoading:sn,agentStatus:un,agentName:ka,logoIcon:va,onRelativeLinkClick:Je,onDownloadFile:Ia?Aa:void 0,resolveAttachmentUrl:Ia&&!V?Ta:void 0,onDownloadArtifact:_a?Ma:void 0,onRefreshArtifact:_a?La:void 0,requestHeaders:Ve,miniGameEnabled:U,onPlayWaitingGame:Xe,waitingGameUrl:wa,onMessageFeedback:Qe,feedbackUrl:re(h,Fe,O),conversationId:hn,locale:F,isResumingAfterDecision:Ln,onSkipWait:Vn??void 0,pendingApprovals:kn,onSubmitApprovalDecisions:Mn,isSubmittingApproval:An,approvalError:En,openableConversationIds:Wr,onOpenConversation:qr,markerRenderers:ht,markerKindList:mt,codeBlockRenderers:gt,transformMessageText:he,onArtifactOpen:it,renderMessageExtras:Ne,messageFooterActions:Ce,transcriptFooter:ye,onLoadEarlier:Vr?Xr:void 0,ttsRoute:Jr,thinking:ft,t:ut}),se?ie&&t("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-white/10 text-sm text-gray-500 dark:text-white/50",children:ie}):t(Zr,{header:we,sendsHeld:cn,steerAttachments:Pe,canHold:He,heldMessage:Gn,notice:Jn,onCancelHeld:Xn,agentMentions:We&&xt.length>0?{agents:xt,mentions:Zn,onPick:Qn}:void 0,inputValue:an,onInputChange:on,onSend:Fn,onStop:rr,isLoading:sn,canSteer:bn,attachedFiles:_?[]:pn,onFileAdd:_?void 0:qn,onFileRemove:_?void 0:e=>sr(t=>t.filter((t,n)=>n!==e)),onPaste:_?void 0:Bn,t:ut,mode:n,separatorColor:C,prompts:gr,quota:mr,contextUsage:G?yn:null,composerToolbar:Z,conversationReferences:Ur?{url:Ur,requestHeaders:Ve,conversationId:hn,refs:ar,onPick:or}:void 0})]})]}),eo.snapshot&&t(wo,{call:eo.snapshot,agentName:ka,logoIcon:va,processingLabel:Ca(un,ut,Ee),onInterrupt:eo.interrupt,onToggleMute:eo.toggleMute,onEnd:eo.end,t:ut})]})}),Ro=({isOpen:n,onToggle:r,label:a,accentColor:o="#7b5cff",icon:s,t:i,locale:l})=>{const c=u(()=>Q(i,l),[i,l]),d=s??t(Yn,{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:N(o,.5),color:o,backgroundColor:n?N(o,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=o,e.currentTarget.style.backgroundColor=N(o,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?o:N(o,.5),e.currentTarget.style.backgroundColor=n?N(o,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:d}),a??c("Ask Assistant")]})};export{Mo as ChatPanel,Ro as ChatToggleButton,Dn as voiceCallSupported};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|