@rubytech/taskmaster 1.1.1 → 1.2.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.
@@ -1,25 +1,25 @@
1
- var cd=Object.defineProperty;var ud=(e,t,n)=>t in e?cd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var U=(e,t,n)=>ud(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const r of o.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&i(r)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const dd="modulepreload",pd=function(e,t){return new URL(e,t).href},wr={},ie=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(p=>Promise.resolve(p).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const r=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),u=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));s=c(n.map(l=>{if(l=pd(l,i),l in wr)return;wr[l]=!0;const p=l.endsWith(".css"),f=p?'[rel="stylesheet"]':"";if(i)for(let h=r.length-1;h>=0;h--){const v=r[h];if(v.href===l&&(!p||v.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${f}`))return;const b=document.createElement("link");if(b.rel=p?"stylesheet":dd,p||(b.as="script"),b.crossOrigin="",b.href=l,u&&b.setAttribute("nonce",u),document.head.appendChild(b),p)return new Promise((h,v)=>{b.addEventListener("load",h),b.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return s.then(r=>{for(const a of r||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};const ni=globalThis,lo=ni.ShadowRoot&&(ni.ShadyCSS===void 0||ni.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,co=Symbol(),kr=new WeakMap;let pl=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==co)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o;const n=this.t;if(lo&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=kr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&kr.set(n,t))}return t}toString(){return this.cssText}};const hd=e=>new pl(typeof e=="string"?e:e+"",void 0,co),fd=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((i,s,o)=>i+(r=>{if(r._$cssResult$===!0)return r.cssText;if(typeof r=="number")return r;throw Error("Value passed to 'css' function must be a 'css' function result: "+r+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[o+1],e[0]);return new pl(n,e,co)},gd=(e,t)=>{if(lo)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=ni.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},Sr=lo?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return hd(n)})(e):e;const{is:md,defineProperty:yd,getOwnPropertyDescriptor:vd,getOwnPropertyNames:bd,getOwnPropertySymbols:wd,getPrototypeOf:kd}=Object,Xe=globalThis,$r=Xe.trustedTypes,Sd=$r?$r.emptyScript:"",Xi=Xe.reactiveElementPolyfillSupport,dn=(e,t)=>e,ai={toAttribute(e,t){switch(t){case Boolean:e=e?Sd:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},uo=(e,t)=>!md(e,t),xr={attribute:!0,type:String,converter:ai,reflect:!1,useDefault:!1,hasChanged:uo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Xe.litPropertyMetadata??(Xe.litPropertyMetadata=new WeakMap);let Pt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=xr){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,n);s!==void 0&&yd(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=vd(this.prototype,t)??{get(){return this[n]},set(r){this[n]=r}};return{get:s,set(r){const a=s==null?void 0:s.call(this);o==null||o.call(this,r),this.requestUpdate(t,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??xr}static _$Ei(){if(this.hasOwnProperty(dn("elementProperties")))return;const t=kd(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(dn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(dn("properties"))){const n=this.properties,i=[...bd(n),...wd(n)];for(const s of i)this.createProperty(s,n[s])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[i,s]of n)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[n,i]of this.elementProperties){const s=this._$Eu(n,i);s!==void 0&&this._$Eh.set(s,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const n=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)n.unshift(Sr(s))}else t!==void 0&&n.push(Sr(t));return n}static _$Eu(t,n){const i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$ES=new Promise(n=>this.enableUpdating=n),this._$AL=new Map,this._$E_(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(n=>n(this))}addController(t){var n;(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&((n=t.hostConnected)==null||n.call(t))}removeController(t){var n;(n=this._$EO)==null||n.delete(t)}_$E_(){const t=new Map,n=this.constructor.elementProperties;for(const i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return gd(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$EO)==null||t.forEach(n=>{var i;return(i=n.hostConnected)==null?void 0:i.call(n)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$EO)==null||t.forEach(n=>{var i;return(i=n.hostDisconnected)==null?void 0:i.call(n)})}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){var o;const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const r=(((o=i.converter)==null?void 0:o.toAttribute)!==void 0?i.converter:ai).toAttribute(n,i.type);this._$Em=t,r==null?this.removeAttribute(s):this.setAttribute(s,r),this._$Em=null}}_$AK(t,n){var o,r;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),u=typeof a.converter=="function"?{fromAttribute:a.converter}:((o=a.converter)==null?void 0:o.fromAttribute)!==void 0?a.converter:ai;this._$Em=s;const c=u.fromAttribute(n,a.type);this[s]=c??((r=this._$Ej)==null?void 0:r.get(s))??c,this._$Em=null}}requestUpdate(t,n,i,s=!1,o){var r;if(t!==void 0){const a=this.constructor;if(s===!1&&(o=this[t]),i??(i=a.getPropertyOptions(t)),!((i.hasChanged??uo)(o,n)||i.useDefault&&i.reflect&&o===((r=this._$Ej)==null?void 0:r.get(t))&&!this.hasAttribute(a._$Eu(t,i))))return;this.C(t,n,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,n,{useDefault:i,reflect:s,wrapped:o},r){i&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,r??n??this[t]),o!==!0||r!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(n=void 0),this._$AL.set(t,n)),s===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(n){Promise.reject(n)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:a}=r,u=this[o];a!==!0||this._$AL.has(o)||u===void 0||this.C(o,void 0,r,u)}}let t=!1;const n=this._$AL;try{t=this.shouldUpdate(n),t?(this.willUpdate(n),(i=this._$EO)==null||i.forEach(s=>{var o;return(o=s.hostUpdate)==null?void 0:o.call(s)}),this.update(n)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(n)}willUpdate(t){}_$AE(t){var n;(n=this._$EO)==null||n.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach(n=>this._$ET(n,this[n]))),this._$EM()}updated(t){}firstUpdated(t){}};Pt.elementStyles=[],Pt.shadowRootOptions={mode:"open"},Pt[dn("elementProperties")]=new Map,Pt[dn("finalized")]=new Map,Xi==null||Xi({ReactiveElement:Pt}),(Xe.reactiveElementVersions??(Xe.reactiveElementVersions=[])).push("2.1.2");const pn=globalThis,Ar=e=>e,li=pn.trustedTypes,Er=li?li.createPolicy("lit-html",{createHTML:e=>e}):void 0,hl="$lit$",Je=`lit$${Math.random().toFixed(9).slice(2)}$`,fl="?"+Je,$d=`<${fl}>`,ht=document,kn=()=>ht.createComment(""),Sn=e=>e===null||typeof e!="object"&&typeof e!="function",po=Array.isArray,xd=e=>po(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Zi=`[
1
+ var cd=Object.defineProperty;var ud=(e,t,n)=>t in e?cd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var U=(e,t,n)=>ud(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const r of o.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&i(r)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const dd="modulepreload",pd=function(e,t){return new URL(e,t).href},wr={},ie=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(p=>Promise.resolve(p).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const r=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),u=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));s=c(n.map(l=>{if(l=pd(l,i),l in wr)return;wr[l]=!0;const p=l.endsWith(".css"),h=p?'[rel="stylesheet"]':"";if(i)for(let f=r.length-1;f>=0;f--){const v=r[f];if(v.href===l&&(!p||v.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${h}`))return;const b=document.createElement("link");if(b.rel=p?"stylesheet":dd,p||(b.as="script"),b.crossOrigin="",b.href=l,u&&b.setAttribute("nonce",u),document.head.appendChild(b),p)return new Promise((f,v)=>{b.addEventListener("load",f),b.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return s.then(r=>{for(const a of r||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};const ni=globalThis,lo=ni.ShadowRoot&&(ni.ShadyCSS===void 0||ni.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,co=Symbol(),kr=new WeakMap;let pl=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==co)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o;const n=this.t;if(lo&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=kr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&kr.set(n,t))}return t}toString(){return this.cssText}};const hd=e=>new pl(typeof e=="string"?e:e+"",void 0,co),fd=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((i,s,o)=>i+(r=>{if(r._$cssResult$===!0)return r.cssText;if(typeof r=="number")return r;throw Error("Value passed to 'css' function must be a 'css' function result: "+r+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[o+1],e[0]);return new pl(n,e,co)},gd=(e,t)=>{if(lo)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=ni.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},Sr=lo?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return hd(n)})(e):e;const{is:md,defineProperty:yd,getOwnPropertyDescriptor:vd,getOwnPropertyNames:bd,getOwnPropertySymbols:wd,getPrototypeOf:kd}=Object,Xe=globalThis,$r=Xe.trustedTypes,Sd=$r?$r.emptyScript:"",Xi=Xe.reactiveElementPolyfillSupport,dn=(e,t)=>e,ai={toAttribute(e,t){switch(t){case Boolean:e=e?Sd:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},uo=(e,t)=>!md(e,t),Ar={attribute:!0,type:String,converter:ai,reflect:!1,useDefault:!1,hasChanged:uo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Xe.litPropertyMetadata??(Xe.litPropertyMetadata=new WeakMap);let Pt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Ar){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,n);s!==void 0&&yd(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=vd(this.prototype,t)??{get(){return this[n]},set(r){this[n]=r}};return{get:s,set(r){const a=s==null?void 0:s.call(this);o==null||o.call(this,r),this.requestUpdate(t,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ar}static _$Ei(){if(this.hasOwnProperty(dn("elementProperties")))return;const t=kd(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(dn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(dn("properties"))){const n=this.properties,i=[...bd(n),...wd(n)];for(const s of i)this.createProperty(s,n[s])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[i,s]of n)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[n,i]of this.elementProperties){const s=this._$Eu(n,i);s!==void 0&&this._$Eh.set(s,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const n=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)n.unshift(Sr(s))}else t!==void 0&&n.push(Sr(t));return n}static _$Eu(t,n){const i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$ES=new Promise(n=>this.enableUpdating=n),this._$AL=new Map,this._$E_(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(n=>n(this))}addController(t){var n;(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&((n=t.hostConnected)==null||n.call(t))}removeController(t){var n;(n=this._$EO)==null||n.delete(t)}_$E_(){const t=new Map,n=this.constructor.elementProperties;for(const i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return gd(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$EO)==null||t.forEach(n=>{var i;return(i=n.hostConnected)==null?void 0:i.call(n)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$EO)==null||t.forEach(n=>{var i;return(i=n.hostDisconnected)==null?void 0:i.call(n)})}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){var o;const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const r=(((o=i.converter)==null?void 0:o.toAttribute)!==void 0?i.converter:ai).toAttribute(n,i.type);this._$Em=t,r==null?this.removeAttribute(s):this.setAttribute(s,r),this._$Em=null}}_$AK(t,n){var o,r;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),u=typeof a.converter=="function"?{fromAttribute:a.converter}:((o=a.converter)==null?void 0:o.fromAttribute)!==void 0?a.converter:ai;this._$Em=s;const c=u.fromAttribute(n,a.type);this[s]=c??((r=this._$Ej)==null?void 0:r.get(s))??c,this._$Em=null}}requestUpdate(t,n,i,s=!1,o){var r;if(t!==void 0){const a=this.constructor;if(s===!1&&(o=this[t]),i??(i=a.getPropertyOptions(t)),!((i.hasChanged??uo)(o,n)||i.useDefault&&i.reflect&&o===((r=this._$Ej)==null?void 0:r.get(t))&&!this.hasAttribute(a._$Eu(t,i))))return;this.C(t,n,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,n,{useDefault:i,reflect:s,wrapped:o},r){i&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,r??n??this[t]),o!==!0||r!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(n=void 0),this._$AL.set(t,n)),s===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(n){Promise.reject(n)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:a}=r,u=this[o];a!==!0||this._$AL.has(o)||u===void 0||this.C(o,void 0,r,u)}}let t=!1;const n=this._$AL;try{t=this.shouldUpdate(n),t?(this.willUpdate(n),(i=this._$EO)==null||i.forEach(s=>{var o;return(o=s.hostUpdate)==null?void 0:o.call(s)}),this.update(n)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(n)}willUpdate(t){}_$AE(t){var n;(n=this._$EO)==null||n.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach(n=>this._$ET(n,this[n]))),this._$EM()}updated(t){}firstUpdated(t){}};Pt.elementStyles=[],Pt.shadowRootOptions={mode:"open"},Pt[dn("elementProperties")]=new Map,Pt[dn("finalized")]=new Map,Xi==null||Xi({ReactiveElement:Pt}),(Xe.reactiveElementVersions??(Xe.reactiveElementVersions=[])).push("2.1.2");const pn=globalThis,xr=e=>e,li=pn.trustedTypes,Er=li?li.createPolicy("lit-html",{createHTML:e=>e}):void 0,hl="$lit$",Je=`lit$${Math.random().toFixed(9).slice(2)}$`,fl="?"+Je,$d=`<${fl}>`,ht=document,kn=()=>ht.createComment(""),Sn=e=>e===null||typeof e!="object"&&typeof e!="function",po=Array.isArray,Ad=e=>po(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Zi=`[
2
2
  \f\r]`,Jt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Cr=/-->/g,Tr=/>/g,rt=RegExp(`>|${Zi}(?:([^\\s"'>=/]+)(${Zi}*=${Zi}*(?:[^
3
- \f\r"'\`<>=]|("|')|))|$)`,"g"),_r=/'/g,Mr=/"/g,gl=/^(?:script|style|textarea|title)$/i,Ad=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),d=Ad(1),et=Symbol.for("lit-noChange"),S=Symbol.for("lit-nothing"),Pr=new WeakMap,ut=ht.createTreeWalker(ht,129);function ml(e,t){if(!po(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Er!==void 0?Er.createHTML(t):t}const Ed=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",r=Jt;for(let a=0;a<n;a++){const u=e[a];let c,l,p=-1,f=0;for(;f<u.length&&(r.lastIndex=f,l=r.exec(u),l!==null);)f=r.lastIndex,r===Jt?l[1]==="!--"?r=Cr:l[1]!==void 0?r=Tr:l[2]!==void 0?(gl.test(l[2])&&(s=RegExp("</"+l[2],"g")),r=rt):l[3]!==void 0&&(r=rt):r===rt?l[0]===">"?(r=s??Jt,p=-1):l[1]===void 0?p=-2:(p=r.lastIndex-l[2].length,c=l[1],r=l[3]===void 0?rt:l[3]==='"'?Mr:_r):r===Mr||r===_r?r=rt:r===Cr||r===Tr?r=Jt:(r=rt,s=void 0);const b=r===rt&&e[a+1].startsWith("/>")?" ":"";o+=r===Jt?u+$d:p>=0?(i.push(c),u.slice(0,p)+hl+u.slice(p)+Je+b):u+Je+(p===-2?a:b)}return[ml(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let Rs=class yl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,r=0;const a=t.length-1,u=this.parts,[c,l]=Ed(t,n);if(this.el=yl.createElement(c,i),ut.currentNode=this.el.content,n===2||n===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(s=ut.nextNode())!==null&&u.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const p of s.getAttributeNames())if(p.endsWith(hl)){const f=l[r++],b=s.getAttribute(p).split(Je),h=/([.?@])?(.*)/.exec(f);u.push({type:1,index:o,name:h[2],strings:b,ctor:h[1]==="."?Td:h[1]==="?"?_d:h[1]==="@"?Md:_i}),s.removeAttribute(p)}else p.startsWith(Je)&&(u.push({type:6,index:o}),s.removeAttribute(p));if(gl.test(s.tagName)){const p=s.textContent.split(Je),f=p.length-1;if(f>0){s.textContent=li?li.emptyScript:"";for(let b=0;b<f;b++)s.append(p[b],kn()),ut.nextNode(),u.push({type:2,index:++o});s.append(p[f],kn())}}}else if(s.nodeType===8)if(s.data===fl)u.push({type:2,index:o});else{let p=-1;for(;(p=s.data.indexOf(Je,p+1))!==-1;)u.push({type:7,index:o}),p+=Je.length-1}o++}}static createElement(t,n){const i=ht.createElement("template");return i.innerHTML=t,i}};function Bt(e,t,n=e,i){var r,a;if(t===et)return t;let s=i!==void 0?(r=n._$Co)==null?void 0:r[i]:n._$Cl;const o=Sn(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==o&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),o===void 0?s=void 0:(s=new o(e),s._$AT(e,n,i)),i!==void 0?(n._$Co??(n._$Co=[]))[i]=s:n._$Cl=s),s!==void 0&&(t=Bt(e,s._$AS(e,t.values),s,i)),t}class Cd{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:n},parts:i}=this._$AD,s=((t==null?void 0:t.creationScope)??ht).importNode(n,!0);ut.currentNode=s;let o=ut.nextNode(),r=0,a=0,u=i[0];for(;u!==void 0;){if(r===u.index){let c;u.type===2?c=new Ti(o,o.nextSibling,this,t):u.type===1?c=new u.ctor(o,u.name,u.strings,this,t):u.type===6&&(c=new Pd(o,this,t)),this._$AV.push(c),u=i[++a]}r!==(u==null?void 0:u.index)&&(o=ut.nextNode(),r++)}return ut.currentNode=ht,s}p(t){let n=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}}let Ti=class vl{get _$AU(){var t;return((t=this._$AM)==null?void 0:t._$AU)??this._$Cv}constructor(t,n,i,s){this.type=2,this._$AH=S,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let t=this._$AA.parentNode;const n=this._$AM;return n!==void 0&&(t==null?void 0:t.nodeType)===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=Bt(this,t,n),Sn(t)?t===S||t==null||t===""?(this._$AH!==S&&this._$AR(),this._$AH=S):t!==this._$AH&&t!==et&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):xd(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==S&&Sn(this._$AH)?this._$AA.nextSibling.data=t:this.T(ht.createTextNode(t)),this._$AH=t}$(t){var o;const{values:n,_$litType$:i}=t,s=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Rs.createElement(ml(i.h,i.h[0]),this.options)),i);if(((o=this._$AH)==null?void 0:o._$AD)===s)this._$AH.p(n);else{const r=new Cd(s,this),a=r.u(this.options);r.p(n),this.T(a),this._$AH=r}}_$AC(t){let n=Pr.get(t.strings);return n===void 0&&Pr.set(t.strings,n=new Rs(t)),n}k(t){po(this._$AH)||(this._$AH=[],this._$AR());const n=this._$AH;let i,s=0;for(const o of t)s===n.length?n.push(i=new vl(this.O(kn()),this.O(kn()),this,this.options)):i=n[s],i._$AI(o),s++;s<n.length&&(this._$AR(i&&i._$AB.nextSibling,s),n.length=s)}_$AR(t=this._$AA.nextSibling,n){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,n);t!==this._$AB;){const s=Ar(t).nextSibling;Ar(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class _i{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,s,o){this.type=1,this._$AH=S,this._$AN=void 0,this.element=t,this.name=n,this._$AM=s,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=S}_$AI(t,n=this,i,s){const o=this.strings;let r=!1;if(o===void 0)t=Bt(this,t,n,0),r=!Sn(t)||t!==this._$AH&&t!==et,r&&(this._$AH=t);else{const a=t;let u,c;for(t=o[0],u=0;u<o.length-1;u++)c=Bt(this,a[i+u],n,u),c===et&&(c=this._$AH[u]),r||(r=!Sn(c)||c!==this._$AH[u]),c===S?t=S:t!==S&&(t+=(c??"")+o[u+1]),this._$AH[u]=c}r&&!s&&this.j(t)}j(t){t===S?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let Td=class extends _i{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===S?void 0:t}},_d=class extends _i{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==S)}},Md=class extends _i{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=Bt(this,t,n,0)??S)===et)return;const i=this._$AH,s=t===S&&i!==S||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==S&&(i===S||s);s&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var n;typeof this._$AH=="function"?this._$AH.call(((n=this.options)==null?void 0:n.host)??this.element,t):this._$AH.handleEvent(t)}},Pd=class{constructor(t,n,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=n,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){Bt(this,t)}};const Ld={I:Ti},es=pn.litHtmlPolyfillSupport;es==null||es(Rs,Ti),(pn.litHtmlVersions??(pn.litHtmlVersions=[])).push("3.3.2");const Id=(e,t,n)=>{const i=(n==null?void 0:n.renderBefore)??t;let s=i._$litPart$;if(s===void 0){const o=(n==null?void 0:n.renderBefore)??null;i._$litPart$=s=new Ti(t.insertBefore(kn(),o),o,void 0,n??{})}return s._$AI(e),s};const pt=globalThis;let It=class extends Pt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var n;const t=super.createRenderRoot();return(n=this.renderOptions).renderBefore??(n.renderBefore=t.firstChild),t}update(t){const n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Id(n,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)==null||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)==null||t.setConnected(!1)}render(){return et}};var dl;It._$litElement$=!0,It.finalized=!0,(dl=pt.litElementHydrateSupport)==null||dl.call(pt,{LitElement:It});const ts=pt.litElementPolyfillSupport;ts==null||ts({LitElement:It});(pt.litElementVersions??(pt.litElementVersions=[])).push("4.2.2");const bl=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Rd={attribute:!0,type:String,converter:ai,reflect:!1,hasChanged:uo},Dd=(e=Rd,t,n)=>{const{kind:i,metadata:s}=n;let o=globalThis.litPropertyMetadata.get(s);if(o===void 0&&globalThis.litPropertyMetadata.set(s,o=new Map),i==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(n.name,e),i==="accessor"){const{name:r}=n;return{set(a){const u=t.get.call(this);t.set.call(this,a),this.requestUpdate(r,u,e,!0,a)},init(a){return a!==void 0&&this.C(r,void 0,e,a),a}}}if(i==="setter"){const{name:r}=n;return function(a){const u=this[r];t.call(this,a),this.requestUpdate(r,u,e,!0,a)}}throw Error("Unsupported decorator location: "+i)};function Mi(e){return(t,n)=>typeof n=="object"?Dd(e,t,n):((i,s,o)=>{const r=s.hasOwnProperty(o);return s.constructor.createProperty(o,i),r?Object.getOwnPropertyDescriptor(s,o):void 0})(e,t,n)}function y(e){return Mi({...e,state:!0,attribute:!1})}const Bd=50,Nd=200,Od="Assistant";function Lr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function Ds(e){const t=Lr(e==null?void 0:e.name,Bd)??Od,n=Lr((e==null?void 0:e.avatar)??void 0,Nd)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function Fd(){return Ds(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const Ud="Taskmaster",Wd="/taskmaster-icon.png",Kd="#00d4ff",zd="";let Fn=null;function ze(){return Fn||(Fn={name:window.__TASKMASTER_BRAND_NAME__||Ud,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||Wd,accentColor:window.__TASKMASTER_ACCENT_COLOR__||Kd,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||zd},Fn)}function Me(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function wl(e){const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return t?`${parseInt(t[1],16)}, ${parseInt(t[2],16)}, ${parseInt(t[3],16)}`:null}function Hd(e){const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);if(!t)return 0;const[n,i,s]=[t[1],t[2],t[3]].map(o=>{const r=parseInt(o,16)/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)});return .2126*n+.7152*i+.0722*s}function kl(e){const t=wl(e);if(!t)return;const n=document.documentElement;n.style.setProperty("--accent",e),n.style.setProperty("--accent-hover",e),n.style.setProperty("--accent-muted",e),n.style.setProperty("--primary",e),n.style.setProperty("--ring",e),n.style.setProperty("--accent-subtle",`rgba(${t}, 0.15)`),n.style.setProperty("--accent-glow",`rgba(${t}, 0.25)`),n.style.setProperty("--tasker-orange",e),n.style.setProperty("--tasker-orange-hover",e),n.style.setProperty("--tasker-orange-glow",`rgba(${t}, 0.25)`);const i=Hd(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function Un(e,t,n){const i=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!i||!s)return e;const o=(c,l)=>Math.round(parseInt(i[c],16)*(1-n)+parseInt(s[l],16)*n),r=o(1,1),a=o(2,2),u=o(3,3);return`#${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${u.toString(16).padStart(2,"0")}`}const Xt={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function Sl(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries(Xt))t.style.setProperty(i,s);t.style.removeProperty("--brand-bg"),t.style.removeProperty("--brand-bg-subtle"),t.style.removeProperty("--brand-bg-card");return}const n=wl(e);n&&(t.style.setProperty("--bg",Un(Xt["--bg"],e,.08)),t.style.setProperty("--bg-muted",Un(Xt["--bg-muted"],e,.1)),t.style.setProperty("--card",Un(Xt["--card"],e,.12)),t.style.setProperty("--secondary",Un(Xt["--secondary"],e,.1)),t.style.setProperty("--brand-bg",e),t.style.setProperty("--brand-bg-subtle",`rgba(${n}, 0.08)`),t.style.setProperty("--brand-bg-card",`rgba(${n}, 0.12)`))}function hn(e){const t=ze(),n=Me(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;kl(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;Sl(o)}const ci="taskmaster.control.settings.v1",$l="taskmaster.account.settings.";function fn(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const Mt={gatewayUrl:fn(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},Ye={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function qd(){try{const e=localStorage.getItem(ci);if(!e)return{...Mt,gatewayUrl:fn()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():fn(),token:typeof t.token=="string"?t.token:Mt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:Mt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:Mt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:Mt.navGroupsCollapsed}}catch{return{...Mt,gatewayUrl:fn()}}}function jd(e){if(!e)return{...Ye};try{const t=localStorage.getItem($l+e);if(!t)return{...Ye};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():Ye.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||Ye.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:Ye.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:Ye.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:Ye.splitRatio}}catch{return{...Ye}}}let ui=null;function Ir(e){ui=e}function ns(){return{...qd(),...jd(ui)}}function Vd(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(ci,JSON.stringify(t)),ui){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem($l+ui,JSON.stringify(n))}}(function(){try{const t=localStorage.getItem(ci);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:fn(),token:typeof n.token=="string"?n.token:"",theme:n.theme==="light"||n.theme==="dark"||n.theme==="system"?n.theme:"system",navCollapsed:typeof n.navCollapsed=="boolean"?n.navCollapsed:!1,navGroupsCollapsed:typeof n.navGroupsCollapsed=="object"&&n.navGroupsCollapsed!==null?n.navGroupsCollapsed:{}};localStorage.setItem(ci,JSON.stringify(i))}catch{}})();function xl(e){var o;const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const i=(o=n[1])==null?void 0:o.trim(),s=n.slice(2).join(":");return!i||!s?null:{agentId:i,rest:s}}const Gd=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,Wn=/<\s*\/?\s*final\b[^>]*>/gi,Rr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function Qd(e,t){return e.trimStart()}function Yd(e,t){if(!e||!Gd.test(e))return e;let n=e;Wn.test(n)?(Wn.lastIndex=0,n=n.replace(Wn,"")):Wn.lastIndex=0,Rr.lastIndex=0;let i="",s=0,o=!1;for(const r of n.matchAll(Rr)){const a=r.index??0,u=r[1]==="/";o?u&&(o=!1):(i+=n.slice(s,a),u||(o=!0)),s=a+r[0].length}return i+=n.slice(s),Qd(i)}function Al(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function Pi(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0){const r=-t,a=Math.round(r/1e3);if(a<60)return`in ${a}s`;const u=Math.round(a/60);if(u<60)return`in ${u}m`;const c=Math.round(u/60);return c<48?`in ${c}h`:`in ${Math.round(c/24)}d`}const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const i=Math.round(n/60);if(i<60)return`${i}m ago`;const s=Math.round(i/60);return s<48?`${s}h ago`:`${Math.round(s/24)}d ago`}function El(e){if(!e&&e!==0)return"n/a";if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);if(n<60)return`${n}m`;const i=Math.round(n/60);return i<48?`${i}h`:`${Math.round(i/24)}d`}function Jd(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Cl(e,t){return e.length<=t?{text:e,truncated:!1,total:e.length}:{text:e.slice(0,Math.max(0,t)),truncated:!0,total:e.length}}function di(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function is(e){return Yd(e)}const Xd=/^\[([^\]]+)\]\s*/,Zd=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],ss=new WeakMap,os=new WeakMap;function ep(e){return/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z\b/.test(e)||/\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b/.test(e)?!0:Zd.some(t=>e.startsWith(`${t} `))}function rs(e){const t=e.match(Xd);if(!t)return e;const n=t[1]??"";return ep(n)?e.slice(t[0].length):e}function gn(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?is(i):rs(i);if(Array.isArray(i)){const s=i.map(o=>{const r=o;return r.type==="text"&&typeof r.text=="string"?r.text:null}).filter(o=>typeof o=="string");if(s.length>0){const o=s.join(`
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),_r=/'/g,Mr=/"/g,gl=/^(?:script|style|textarea|title)$/i,xd=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),d=xd(1),et=Symbol.for("lit-noChange"),S=Symbol.for("lit-nothing"),Pr=new WeakMap,ut=ht.createTreeWalker(ht,129);function ml(e,t){if(!po(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Er!==void 0?Er.createHTML(t):t}const Ed=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",r=Jt;for(let a=0;a<n;a++){const u=e[a];let c,l,p=-1,h=0;for(;h<u.length&&(r.lastIndex=h,l=r.exec(u),l!==null);)h=r.lastIndex,r===Jt?l[1]==="!--"?r=Cr:l[1]!==void 0?r=Tr:l[2]!==void 0?(gl.test(l[2])&&(s=RegExp("</"+l[2],"g")),r=rt):l[3]!==void 0&&(r=rt):r===rt?l[0]===">"?(r=s??Jt,p=-1):l[1]===void 0?p=-2:(p=r.lastIndex-l[2].length,c=l[1],r=l[3]===void 0?rt:l[3]==='"'?Mr:_r):r===Mr||r===_r?r=rt:r===Cr||r===Tr?r=Jt:(r=rt,s=void 0);const b=r===rt&&e[a+1].startsWith("/>")?" ":"";o+=r===Jt?u+$d:p>=0?(i.push(c),u.slice(0,p)+hl+u.slice(p)+Je+b):u+Je+(p===-2?a:b)}return[ml(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let Rs=class yl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,r=0;const a=t.length-1,u=this.parts,[c,l]=Ed(t,n);if(this.el=yl.createElement(c,i),ut.currentNode=this.el.content,n===2||n===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(s=ut.nextNode())!==null&&u.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const p of s.getAttributeNames())if(p.endsWith(hl)){const h=l[r++],b=s.getAttribute(p).split(Je),f=/([.?@])?(.*)/.exec(h);u.push({type:1,index:o,name:f[2],strings:b,ctor:f[1]==="."?Td:f[1]==="?"?_d:f[1]==="@"?Md:_i}),s.removeAttribute(p)}else p.startsWith(Je)&&(u.push({type:6,index:o}),s.removeAttribute(p));if(gl.test(s.tagName)){const p=s.textContent.split(Je),h=p.length-1;if(h>0){s.textContent=li?li.emptyScript:"";for(let b=0;b<h;b++)s.append(p[b],kn()),ut.nextNode(),u.push({type:2,index:++o});s.append(p[h],kn())}}}else if(s.nodeType===8)if(s.data===fl)u.push({type:2,index:o});else{let p=-1;for(;(p=s.data.indexOf(Je,p+1))!==-1;)u.push({type:7,index:o}),p+=Je.length-1}o++}}static createElement(t,n){const i=ht.createElement("template");return i.innerHTML=t,i}};function Bt(e,t,n=e,i){var r,a;if(t===et)return t;let s=i!==void 0?(r=n._$Co)==null?void 0:r[i]:n._$Cl;const o=Sn(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==o&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),o===void 0?s=void 0:(s=new o(e),s._$AT(e,n,i)),i!==void 0?(n._$Co??(n._$Co=[]))[i]=s:n._$Cl=s),s!==void 0&&(t=Bt(e,s._$AS(e,t.values),s,i)),t}class Cd{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:n},parts:i}=this._$AD,s=((t==null?void 0:t.creationScope)??ht).importNode(n,!0);ut.currentNode=s;let o=ut.nextNode(),r=0,a=0,u=i[0];for(;u!==void 0;){if(r===u.index){let c;u.type===2?c=new Ti(o,o.nextSibling,this,t):u.type===1?c=new u.ctor(o,u.name,u.strings,this,t):u.type===6&&(c=new Pd(o,this,t)),this._$AV.push(c),u=i[++a]}r!==(u==null?void 0:u.index)&&(o=ut.nextNode(),r++)}return ut.currentNode=ht,s}p(t){let n=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}}let Ti=class vl{get _$AU(){var t;return((t=this._$AM)==null?void 0:t._$AU)??this._$Cv}constructor(t,n,i,s){this.type=2,this._$AH=S,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let t=this._$AA.parentNode;const n=this._$AM;return n!==void 0&&(t==null?void 0:t.nodeType)===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=Bt(this,t,n),Sn(t)?t===S||t==null||t===""?(this._$AH!==S&&this._$AR(),this._$AH=S):t!==this._$AH&&t!==et&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ad(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==S&&Sn(this._$AH)?this._$AA.nextSibling.data=t:this.T(ht.createTextNode(t)),this._$AH=t}$(t){var o;const{values:n,_$litType$:i}=t,s=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Rs.createElement(ml(i.h,i.h[0]),this.options)),i);if(((o=this._$AH)==null?void 0:o._$AD)===s)this._$AH.p(n);else{const r=new Cd(s,this),a=r.u(this.options);r.p(n),this.T(a),this._$AH=r}}_$AC(t){let n=Pr.get(t.strings);return n===void 0&&Pr.set(t.strings,n=new Rs(t)),n}k(t){po(this._$AH)||(this._$AH=[],this._$AR());const n=this._$AH;let i,s=0;for(const o of t)s===n.length?n.push(i=new vl(this.O(kn()),this.O(kn()),this,this.options)):i=n[s],i._$AI(o),s++;s<n.length&&(this._$AR(i&&i._$AB.nextSibling,s),n.length=s)}_$AR(t=this._$AA.nextSibling,n){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,n);t!==this._$AB;){const s=xr(t).nextSibling;xr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class _i{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,s,o){this.type=1,this._$AH=S,this._$AN=void 0,this.element=t,this.name=n,this._$AM=s,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=S}_$AI(t,n=this,i,s){const o=this.strings;let r=!1;if(o===void 0)t=Bt(this,t,n,0),r=!Sn(t)||t!==this._$AH&&t!==et,r&&(this._$AH=t);else{const a=t;let u,c;for(t=o[0],u=0;u<o.length-1;u++)c=Bt(this,a[i+u],n,u),c===et&&(c=this._$AH[u]),r||(r=!Sn(c)||c!==this._$AH[u]),c===S?t=S:t!==S&&(t+=(c??"")+o[u+1]),this._$AH[u]=c}r&&!s&&this.j(t)}j(t){t===S?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let Td=class extends _i{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===S?void 0:t}},_d=class extends _i{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==S)}},Md=class extends _i{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=Bt(this,t,n,0)??S)===et)return;const i=this._$AH,s=t===S&&i!==S||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==S&&(i===S||s);s&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var n;typeof this._$AH=="function"?this._$AH.call(((n=this.options)==null?void 0:n.host)??this.element,t):this._$AH.handleEvent(t)}},Pd=class{constructor(t,n,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=n,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){Bt(this,t)}};const Ld={I:Ti},es=pn.litHtmlPolyfillSupport;es==null||es(Rs,Ti),(pn.litHtmlVersions??(pn.litHtmlVersions=[])).push("3.3.2");const Id=(e,t,n)=>{const i=(n==null?void 0:n.renderBefore)??t;let s=i._$litPart$;if(s===void 0){const o=(n==null?void 0:n.renderBefore)??null;i._$litPart$=s=new Ti(t.insertBefore(kn(),o),o,void 0,n??{})}return s._$AI(e),s};const pt=globalThis;let It=class extends Pt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var n;const t=super.createRenderRoot();return(n=this.renderOptions).renderBefore??(n.renderBefore=t.firstChild),t}update(t){const n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Id(n,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)==null||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)==null||t.setConnected(!1)}render(){return et}};var dl;It._$litElement$=!0,It.finalized=!0,(dl=pt.litElementHydrateSupport)==null||dl.call(pt,{LitElement:It});const ts=pt.litElementPolyfillSupport;ts==null||ts({LitElement:It});(pt.litElementVersions??(pt.litElementVersions=[])).push("4.2.2");const bl=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Rd={attribute:!0,type:String,converter:ai,reflect:!1,hasChanged:uo},Dd=(e=Rd,t,n)=>{const{kind:i,metadata:s}=n;let o=globalThis.litPropertyMetadata.get(s);if(o===void 0&&globalThis.litPropertyMetadata.set(s,o=new Map),i==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(n.name,e),i==="accessor"){const{name:r}=n;return{set(a){const u=t.get.call(this);t.set.call(this,a),this.requestUpdate(r,u,e,!0,a)},init(a){return a!==void 0&&this.C(r,void 0,e,a),a}}}if(i==="setter"){const{name:r}=n;return function(a){const u=this[r];t.call(this,a),this.requestUpdate(r,u,e,!0,a)}}throw Error("Unsupported decorator location: "+i)};function Mi(e){return(t,n)=>typeof n=="object"?Dd(e,t,n):((i,s,o)=>{const r=s.hasOwnProperty(o);return s.constructor.createProperty(o,i),r?Object.getOwnPropertyDescriptor(s,o):void 0})(e,t,n)}function y(e){return Mi({...e,state:!0,attribute:!1})}const Bd=50,Nd=200,Od="Assistant";function Lr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function Ds(e){const t=Lr(e==null?void 0:e.name,Bd)??Od,n=Lr((e==null?void 0:e.avatar)??void 0,Nd)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function Fd(){return Ds(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const Ud="Taskmaster",Wd="/taskmaster-icon.png",Kd="#00d4ff",zd="";let Fn=null;function ze(){return Fn||(Fn={name:window.__TASKMASTER_BRAND_NAME__||Ud,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||Wd,accentColor:window.__TASKMASTER_ACCENT_COLOR__||Kd,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||zd},Fn)}function Me(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function wl(e){const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return t?`${parseInt(t[1],16)}, ${parseInt(t[2],16)}, ${parseInt(t[3],16)}`:null}function Hd(e){const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);if(!t)return 0;const[n,i,s]=[t[1],t[2],t[3]].map(o=>{const r=parseInt(o,16)/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)});return .2126*n+.7152*i+.0722*s}function kl(e){const t=wl(e);if(!t)return;const n=document.documentElement;n.style.setProperty("--accent",e),n.style.setProperty("--accent-hover",e),n.style.setProperty("--accent-muted",e),n.style.setProperty("--primary",e),n.style.setProperty("--ring",e),n.style.setProperty("--accent-subtle",`rgba(${t}, 0.15)`),n.style.setProperty("--accent-glow",`rgba(${t}, 0.25)`),n.style.setProperty("--tasker-orange",e),n.style.setProperty("--tasker-orange-hover",e),n.style.setProperty("--tasker-orange-glow",`rgba(${t}, 0.25)`);const i=Hd(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function Un(e,t,n){const i=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!i||!s)return e;const o=(c,l)=>Math.round(parseInt(i[c],16)*(1-n)+parseInt(s[l],16)*n),r=o(1,1),a=o(2,2),u=o(3,3);return`#${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${u.toString(16).padStart(2,"0")}`}const Xt={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function Sl(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries(Xt))t.style.setProperty(i,s);t.style.removeProperty("--brand-bg"),t.style.removeProperty("--brand-bg-subtle"),t.style.removeProperty("--brand-bg-card");return}const n=wl(e);n&&(t.style.setProperty("--bg",Un(Xt["--bg"],e,.08)),t.style.setProperty("--bg-muted",Un(Xt["--bg-muted"],e,.1)),t.style.setProperty("--card",Un(Xt["--card"],e,.12)),t.style.setProperty("--secondary",Un(Xt["--secondary"],e,.1)),t.style.setProperty("--brand-bg",e),t.style.setProperty("--brand-bg-subtle",`rgba(${n}, 0.08)`),t.style.setProperty("--brand-bg-card",`rgba(${n}, 0.12)`))}function hn(e){const t=ze(),n=Me(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;kl(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;Sl(o)}const ci="taskmaster.control.settings.v1",$l="taskmaster.account.settings.";function fn(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const Mt={gatewayUrl:fn(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},Ye={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function qd(){try{const e=localStorage.getItem(ci);if(!e)return{...Mt,gatewayUrl:fn()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():fn(),token:typeof t.token=="string"?t.token:Mt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:Mt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:Mt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:Mt.navGroupsCollapsed}}catch{return{...Mt,gatewayUrl:fn()}}}function jd(e){if(!e)return{...Ye};try{const t=localStorage.getItem($l+e);if(!t)return{...Ye};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():Ye.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||Ye.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:Ye.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:Ye.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:Ye.splitRatio}}catch{return{...Ye}}}let ui=null;function Ir(e){ui=e}function ns(){return{...qd(),...jd(ui)}}function Vd(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(ci,JSON.stringify(t)),ui){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem($l+ui,JSON.stringify(n))}}(function(){try{const t=localStorage.getItem(ci);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:fn(),token:typeof n.token=="string"?n.token:"",theme:n.theme==="light"||n.theme==="dark"||n.theme==="system"?n.theme:"system",navCollapsed:typeof n.navCollapsed=="boolean"?n.navCollapsed:!1,navGroupsCollapsed:typeof n.navGroupsCollapsed=="object"&&n.navGroupsCollapsed!==null?n.navGroupsCollapsed:{}};localStorage.setItem(ci,JSON.stringify(i))}catch{}})();function Al(e){var o;const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const i=(o=n[1])==null?void 0:o.trim(),s=n.slice(2).join(":");return!i||!s?null:{agentId:i,rest:s}}const Gd=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,Wn=/<\s*\/?\s*final\b[^>]*>/gi,Rr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function Qd(e,t){return e.trimStart()}function Yd(e,t){if(!e||!Gd.test(e))return e;let n=e;Wn.test(n)?(Wn.lastIndex=0,n=n.replace(Wn,"")):Wn.lastIndex=0,Rr.lastIndex=0;let i="",s=0,o=!1;for(const r of n.matchAll(Rr)){const a=r.index??0,u=r[1]==="/";o?u&&(o=!1):(i+=n.slice(s,a),u||(o=!0)),s=a+r[0].length}return i+=n.slice(s),Qd(i)}function xl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function Pi(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0){const r=-t,a=Math.round(r/1e3);if(a<60)return`in ${a}s`;const u=Math.round(a/60);if(u<60)return`in ${u}m`;const c=Math.round(u/60);return c<48?`in ${c}h`:`in ${Math.round(c/24)}d`}const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const i=Math.round(n/60);if(i<60)return`${i}m ago`;const s=Math.round(i/60);return s<48?`${s}h ago`:`${Math.round(s/24)}d ago`}function El(e){if(!e&&e!==0)return"n/a";if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);if(n<60)return`${n}m`;const i=Math.round(n/60);return i<48?`${i}h`:`${Math.round(i/24)}d`}function Jd(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Cl(e,t){return e.length<=t?{text:e,truncated:!1,total:e.length}:{text:e.slice(0,Math.max(0,t)),truncated:!0,total:e.length}}function di(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function is(e){return Yd(e)}const Xd=/^\[([^\]]+)\]\s*/,Zd=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],ss=new WeakMap,os=new WeakMap;function ep(e){return/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z\b/.test(e)||/\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b/.test(e)?!0:Zd.some(t=>e.startsWith(`${t} `))}function rs(e){const t=e.match(Xd);if(!t)return e;const n=t[1]??"";return ep(n)?e.slice(t[0].length):e}function gn(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?is(i):rs(i);if(Array.isArray(i)){const s=i.map(o=>{const r=o;return r.type==="text"&&typeof r.text=="string"?r.text:null}).filter(o=>typeof o=="string");if(s.length>0){const o=s.join(`
4
4
  `);return n==="assistant"?is(o):rs(o)}}return typeof t.text=="string"?n==="assistant"?is(t.text):rs(t.text):null}function Tl(e){if(!e||typeof e!="object")return gn(e);const t=e;if(ss.has(t))return ss.get(t)??null;const n=gn(e);return ss.set(t,n),n}function Dr(e){const n=e.content,i=[];if(Array.isArray(n))for(const a of n){const u=a;if(u.type==="thinking"&&typeof u.thinking=="string"){const c=u.thinking.trim();c&&i.push(c)}}if(i.length>0)return i.join(`
5
5
  `);const s=np(e);if(!s)return null;const r=[...s.matchAll(/<\s*think(?:ing)?\s*>([\s\S]*?)<\s*\/\s*think(?:ing)?\s*>/gi)].map(a=>(a[1]??"").trim()).filter(Boolean);return r.length>0?r.join(`
6
6
  `):null}function tp(e){if(!e||typeof e!="object")return Dr(e);const t=e;if(os.has(t))return os.get(t)??null;const n=Dr(e);return os.set(t,n),n}function np(e){const t=e,n=t.content;if(typeof n=="string")return n;if(Array.isArray(n)){const i=n.map(s=>{const o=s;return o.type==="text"&&typeof o.text=="string"?o.text:null}).filter(s=>typeof s=="string");if(i.length>0)return i.join(`
7
7
  `)}return typeof t.text=="string"?t.text:null}function ip(e){const t=e.trim();if(!t)return"";const n=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).map(i=>`_${i}_`);return n.length?["_Reasoning:_",...n].join(`
8
8
  `):""}const sp=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,op=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,rp=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,ap=/^A new session was started via \/new or \/reset\./;function lp(e){const t=e,n=typeof t.role=="string"?t.role:"";let i="";typeof t.content=="string"?i=t.content:Array.isArray(t.content)?i=t.content.filter(o=>typeof o=="object"&&o!==null).map(o=>o.text??"").join(" "):typeof t.text=="string"&&(i=t.text);const s=i.trim();return s?!!(n==="user"&&sp.test(s)||n==="assistant"&&op.test(s)||n==="user"&&ap.test(s)||n==="assistant"&&rp.test(s)):!1}function _l(e){return e.filter(t=>!lp(t))}function Ml(e){const t=e;let n=typeof t.role=="string"?t.role:"unknown";const i=typeof t.toolCallId=="string"||typeof t.tool_call_id=="string",s=t.content,o=Array.isArray(s)?s:null,r=Array.isArray(o)&&o.some(p=>{const b=String(p.type??"").toLowerCase();return b==="toolresult"||b==="tool_result"}),a=typeof t.toolName=="string"||typeof t.tool_name=="string";(i||r||a)&&(n="toolResult");let u=[];typeof t.content=="string"?u=[{type:"text",text:t.content}]:Array.isArray(t.content)?u=t.content.map(p=>({type:p.type||"text",text:p.text,name:p.name,args:p.args||p.arguments})):typeof t.text=="string"&&(u=[{type:"text",text:t.text}]);const c=typeof t.timestamp=="number"?t.timestamp:Date.now(),l=typeof t.id=="string"?t.id:void 0;return{role:n,content:u,timestamp:c,id:l}}function Pl(e){const t=e.toLowerCase();return e==="user"||e==="User"?e:e==="assistant"?"assistant":e==="system"?"system":t==="toolresult"||t==="tool_result"||t==="tool"||t==="function"?"tool":e}function Ll(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function Br(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function cp(){const e=new Uint8Array(16),t=Date.now();for(let n=0;n<e.length;n++)e[n]=Math.floor(Math.random()*256);return e[0]^=t&255,e[1]^=t>>>8&255,e[2]^=t>>>16&255,e[3]^=t>>>24&255,e}function ho(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(e&&typeof e.getRandomValues=="function"){const t=new Uint8Array(16);return e.getRandomValues(t),Br(t)}return Br(cp())}const Ie=50;async function Le(e,t){if(!e.client||!e.connected)return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??Ie;try{const i=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:n}),s=Array.isArray(i.messages)?i.messages:[],o=typeof i.totalMessages=="number"?i.totalMessages:s.length,r=_l(s);e.chatMessages=r,e.chatHistoryTotal=o,e.chatHistoryHasMore=o>s.length,e.chatThinkingLevel=i.thinkingLevel??null,e.chatModelProvider=typeof i.modelProvider=="string"?i.modelProvider:null,e.chatModel=typeof i.model=="string"?i.model:null,e.chatVerboseLevel=typeof i.verboseLevel=="string"?i.verboseLevel:null,e.chatFillerEnabled=typeof i.fillerEnabled=="boolean"?i.fillerEnabled:null}catch(i){e.lastError=String(i)}finally{e.chatLoading=!1}}async function up(e){if(!e.client||!e.connected||e.chatLoadingOlder||!e.chatHistoryHasMore)return!1;e.chatLoadingOlder=!0;try{const t=e.chatMessages.length,n=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:Ie,offset:t}),i=Array.isArray(n.messages)?n.messages:[],s=typeof n.totalMessages=="number"?n.totalMessages:0;if(i.length===0)return e.chatHistoryHasMore=!1,!1;const o=_l(i);return e.chatMessages=[...o,...e.chatMessages],e.chatHistoryTotal=s,e.chatHistoryHasMore=s>t+i.length,!0}catch(t){return e.lastError=String(t),!1}finally{e.chatLoadingOlder=!1}}function dp(e){const t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function Il(e,t,n){if(e.chatSuggestion=null,!e.client||!e.connected)return!1;const i=t.trim(),s=n&&n.length>0;if(!i&&!s)return!1;const o=Date.now(),r=(n??[]).filter(b=>!b.fileName),a=(n??[]).filter(b=>b.fileName),u=[],c=a.map(b=>b.fileName).filter(Boolean);if(c.length>0){const b=i?`${c.join(", ")}
9
9
 
10
- ${i}`:c.join(", ");u.push({type:"text",text:b})}else i&&u.push({type:"text",text:i});for(const b of r)u.push({type:"image",source:{type:"base64",media_type:b.mimeType,data:b.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:u,timestamp:o}],e.chatSending=!0,e.lastError=null;const l=ho();e.chatRunId=l,e.chatStream="",e.chatStreamStartedAt=o;const p=[...r,...a],f=p.length>0?p.map(b=>{if(b.textContent)return{type:"document",mimeType:b.mimeType||"text/plain",fileName:b.fileName,content:btoa(unescape(encodeURIComponent(b.textContent)))};const h=dp(b.dataUrl);return h?{type:b.fileName?"document":"image",mimeType:h.mimeType,fileName:b.fileName,content:h.content}:null}).filter(b=>b!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:l,attachments:f}),!0}catch(b){const h=String(b);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=h,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+h}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function Rl(e){if(!e.client||!e.connected)return!1;const t=e.chatRunId;try{return await e.client.request("chat.abort",t?{sessionKey:e.sessionKey,runId:t}:{sessionKey:e.sessionKey}),!0}catch(n){return e.lastError=String(n),!1}}function Dl(e,t){var n,i;if(!t||t.sessionKey!==e.sessionKey)return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return t.state==="final"?"final":null;if(t.state==="working"){const o=(t.message?(n=gn(t.message))==null?void 0:n.trim():void 0)||((i=e.chatStream)==null?void 0:i.trim());if(o)if(!e.chatInterimText)e.chatInterimText=o;else{const r=e.chatInterimText.lastIndexOf(`
10
+ ${i}`:c.join(", ");u.push({type:"text",text:b})}else i&&u.push({type:"text",text:i});for(const b of r)u.push({type:"image",source:{type:"base64",media_type:b.mimeType,data:b.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:u,timestamp:o}],e.chatSending=!0,e.lastError=null;const l=ho();e.chatRunId=l,e.chatStream="",e.chatStreamStartedAt=o;const p=[...r,...a],h=p.length>0?p.map(b=>{if(b.textContent)return{type:"document",mimeType:b.mimeType||"text/plain",fileName:b.fileName,content:btoa(unescape(encodeURIComponent(b.textContent)))};const f=dp(b.dataUrl);return f?{type:b.fileName?"document":"image",mimeType:f.mimeType,fileName:b.fileName,content:f.content}:null}).filter(b=>b!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:l,attachments:h}),!0}catch(b){const f=String(b);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=f,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+f}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function Rl(e){if(!e.client||!e.connected)return!1;const t=e.chatRunId;try{return await e.client.request("chat.abort",t?{sessionKey:e.sessionKey,runId:t}:{sessionKey:e.sessionKey}),!0}catch(n){return e.lastError=String(n),!1}}function Dl(e,t){var n,i;if(!t||t.sessionKey!==e.sessionKey)return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return t.state==="final"?"final":null;if(t.state==="working"){const o=(t.message?(n=gn(t.message))==null?void 0:n.trim():void 0)||((i=e.chatStream)==null?void 0:i.trim());if(o)if(!e.chatInterimText)e.chatInterimText=o;else{const r=e.chatInterimText.lastIndexOf(`
11
11
 
12
12
  `),a=r>=0?e.chatInterimText.slice(r+2).trim():e.chatInterimText.trim();o.trim()!==a&&(e.chatInterimText=`${e.chatInterimText}
13
13
 
14
14
  ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.message);return typeof s=="string"&&s.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:s.trim()}],timestamp:Date.now(),filler:!0}]),"block"}else if(t.state==="delta"){e.chatSuggestion=null;const s=gn(t.message);if(typeof s=="string"){if(s.trim()==="NO_REPLY")return null;const o=e.chatStream??"";(!o||s.length>=o.length)&&(e.chatStream=s)}}else t.state==="final"||t.state==="aborted"?(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null):t.state==="error"&&(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null,e.lastError=t.errorMessage??"chat error");return t.state}const pi=Object.freeze(Object.defineProperty({__proto__:null,CHAT_PAGE_SIZE:Ie,abortChatRun:Rl,handleChatEvent:Dl,loadChatHistory:Le,loadOlderChatHistory:up,sendChatMessage:Il},Symbol.toStringTag,{value:"Module"}));async function fo(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:e.sessionsIncludeGlobal??!0,includeUnknown:e.sessionsIncludeUnknown??!1},n=di(e.sessionsFilterActive??"",0),i=di(e.sessionsFilterLimit??"",0);n>0&&(t.activeMinutes=n),i>0&&(t.limit=i);const s=await e.client.request("sessions.list",t);s&&(e.sessionsResult=s)}catch(t){e.sessionsError=String(t)}finally{e.sessionsLoading=!1}}}async function Kn(e,t,n){if(!e.client||!e.connected)return;const i={key:t};"label"in n&&(i.label=n.label),"thinkingLevel"in n&&(i.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(i.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(i.reasoningLevel=n.reasoningLevel),"model"in n&&(i.model=n.model),"fillerEnabled"in n&&(i.fillerEnabled=n.fillerEnabled);try{await e.client.request("sessions.patch",i),await fo(e)}catch(s){e.sessionsError=String(s)}}const Nr=50,pp=80,hp=12e4;function fp(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.text=="string")return t.text;const n=t.content;if(!Array.isArray(n))return null;const i=n.map(s=>{if(!s||typeof s!="object")return null;const o=s;return o.type==="text"&&typeof o.text=="string"?o.text:null}).filter(s=>!!s);return i.length===0?null:i.join(`
15
15
  `)}function Or(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=fp(e);let n;if(typeof e=="string")n=e;else if(t)n=t;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}const i=Cl(n,hp);return i.truncated?`${i.text}
16
16
 
17
- … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function gp(e){const t=[];return t.push({type:"toolcall",name:e.name,arguments:e.args??{}}),e.output&&t.push({type:"toolresult",name:e.name,text:e.output}),{role:"assistant",toolCallId:e.toolCallId,runId:e.runId,content:t,timestamp:e.startedAt}}function mp(e){if(e.toolStreamOrder.length<=Nr)return;const t=e.toolStreamOrder.length-Nr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function yp(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function Bs(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),yp(e)}function vp(e,t=!1){if(t){Bs(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>Bs(e),pp))}function go(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],Bs(e)}const bp=5e3;function wp(e,t){var s;const n=t.data??{},i=typeof n.phase=="string"?n.phase:"";e.compactionClearTimer!=null&&(window.clearTimeout(e.compactionClearTimer),e.compactionClearTimer=null),i==="start"?e.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null}:i==="end"&&(e.compactionStatus={active:!1,startedAt:((s=e.compactionStatus)==null?void 0:s.startedAt)??null,completedAt:Date.now()},e.compactionClearTimer=window.setTimeout(()=>{e.compactionStatus=null,e.compactionClearTimer=null},bp))}function kp(e,t){if(!t)return;if(t.stream==="compaction"){wp(e,t);return}if(t.stream!=="tool")return;const n=typeof t.sessionKey=="string"?t.sessionKey:void 0;if(n&&n!==e.sessionKey||!n&&e.chatRunId&&t.runId!==e.chatRunId||e.chatRunId&&t.runId!==e.chatRunId||!e.chatRunId)return;const i=t.data??{},s=typeof i.toolCallId=="string"?i.toolCallId:"";if(!s)return;const o=typeof i.name=="string"?i.name:"tool",r=typeof i.phase=="string"?i.phase:"",a=r==="start"?i.args:void 0,u=r==="update"?Or(i.partialResult):r==="result"?Or(i.result):void 0,c=Date.now();let l=e.toolStreamById.get(s);l?(l.name=o,a!==void 0&&(l.args=a),u!==void 0&&(l.output=u),l.updatedAt=c):(l={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:a,output:u,startedAt:typeof t.ts=="number"?t.ts:c,updatedAt:c,message:{}},e.toolStreamById.set(s,l),e.toolStreamOrder.push(s)),l.message=gp(l),mp(e),vp(e,r==="result")}let zn=0;function Wt(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++zn,i=()=>{const s=e.querySelector(".chat-thread");if(s){const o=getComputedStyle(s).overflowY;if(o==="auto"||o==="scroll"||s.scrollHeight-s.clientHeight>1)return s}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{n===zn&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==zn)return;const s=i();if(!s)return;const o=s.scrollHeight-s.scrollTop-s.clientHeight;if(!(t||e.chatUserNearBottom||o<200))return;t&&(e.chatHasAutoScrolled=!0),s.scrollTop=s.scrollHeight,e.chatUserNearBottom=!0;const a=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{if(e.chatScrollTimeout=null,n!==zn)return;const u=i();if(!u)return;const c=u.scrollHeight-u.scrollTop-u.clientHeight;(t||e.chatUserNearBottom||c<200)&&(u.scrollTop=u.scrollHeight,e.chatUserNearBottom=!0)},a)}))})}function Bl(e,t=!1){e.logsScrollFrame&&cancelAnimationFrame(e.logsScrollFrame),e.updateComplete.then(()=>{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");!n||!(t||n.scrollTop<80)||(n.scrollTop=0)})})}function Sp(e,t){const n=t.currentTarget;if(!n)return;const i=n.scrollHeight-n.scrollTop-n.clientHeight;e.chatUserNearBottom=i<200,n.scrollTop<100&&e.onLoadOlder&&e.onLoadOlder()}function $p(e){const t=e.querySelector(".chat-thread");if(!t)return null;const n=t.scrollHeight,i=t.scrollTop;return()=>{const s=t.scrollHeight-n;t.scrollTop=i+s}}function xp(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Ap(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Ep(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function Cp(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
17
+ … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function gp(e){const t=[];return t.push({type:"toolcall",name:e.name,arguments:e.args??{}}),e.output&&t.push({type:"toolresult",name:e.name,text:e.output}),{role:"assistant",toolCallId:e.toolCallId,runId:e.runId,content:t,timestamp:e.startedAt}}function mp(e){if(e.toolStreamOrder.length<=Nr)return;const t=e.toolStreamOrder.length-Nr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function yp(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function Bs(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),yp(e)}function vp(e,t=!1){if(t){Bs(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>Bs(e),pp))}function go(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],Bs(e)}const bp=5e3;function wp(e,t){var s;const n=t.data??{},i=typeof n.phase=="string"?n.phase:"";e.compactionClearTimer!=null&&(window.clearTimeout(e.compactionClearTimer),e.compactionClearTimer=null),i==="start"?e.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null}:i==="end"&&(e.compactionStatus={active:!1,startedAt:((s=e.compactionStatus)==null?void 0:s.startedAt)??null,completedAt:Date.now()},e.compactionClearTimer=window.setTimeout(()=>{e.compactionStatus=null,e.compactionClearTimer=null},bp))}function kp(e,t){if(!t)return;if(t.stream==="compaction"){wp(e,t);return}if(t.stream!=="tool")return;const n=typeof t.sessionKey=="string"?t.sessionKey:void 0;if(n&&n!==e.sessionKey||!n&&e.chatRunId&&t.runId!==e.chatRunId||e.chatRunId&&t.runId!==e.chatRunId||!e.chatRunId)return;const i=t.data??{},s=typeof i.toolCallId=="string"?i.toolCallId:"";if(!s)return;const o=typeof i.name=="string"?i.name:"tool",r=typeof i.phase=="string"?i.phase:"",a=r==="start"?i.args:void 0,u=r==="update"?Or(i.partialResult):r==="result"?Or(i.result):void 0,c=Date.now();let l=e.toolStreamById.get(s);l?(l.name=o,a!==void 0&&(l.args=a),u!==void 0&&(l.output=u),l.updatedAt=c):(l={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:a,output:u,startedAt:typeof t.ts=="number"?t.ts:c,updatedAt:c,message:{}},e.toolStreamById.set(s,l),e.toolStreamOrder.push(s)),l.message=gp(l),mp(e),vp(e,r==="result")}let zn=0;function Wt(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++zn,i=()=>{const s=e.querySelector(".chat-thread");if(s){const o=getComputedStyle(s).overflowY;if(o==="auto"||o==="scroll"||s.scrollHeight-s.clientHeight>1)return s}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{n===zn&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==zn)return;const s=i();if(!s)return;const o=s.scrollHeight-s.scrollTop-s.clientHeight;if(!(t||e.chatUserNearBottom||o<200))return;t&&(e.chatHasAutoScrolled=!0),s.scrollTop=s.scrollHeight,e.chatUserNearBottom=!0;const a=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{if(e.chatScrollTimeout=null,n!==zn)return;const u=i();if(!u)return;const c=u.scrollHeight-u.scrollTop-u.clientHeight;(t||e.chatUserNearBottom||c<200)&&(u.scrollTop=u.scrollHeight,e.chatUserNearBottom=!0)},a)}))})}function Bl(e,t=!1){e.logsScrollFrame&&cancelAnimationFrame(e.logsScrollFrame),e.updateComplete.then(()=>{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");!n||!(t||n.scrollTop<80)||(n.scrollTop=0)})})}function Sp(e,t){const n=t.currentTarget;if(!n)return;const i=n.scrollHeight-n.scrollTop-n.clientHeight;e.chatUserNearBottom=i<200,n.scrollTop<100&&e.onLoadOlder&&e.onLoadOlder()}function $p(e){const t=e.querySelector(".chat-thread");if(!t)return null;const n=t.scrollHeight,i=t.scrollTop;return()=>{const s=t.scrollHeight-n;t.scrollTop=i+s}}function Ap(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function xp(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Ep(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function Cp(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
18
18
  `)}
19
19
  `],{type:"text/plain"}),i=URL.createObjectURL(n),s=document.createElement("a"),o=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");s.href=i,s.download=`taskmaster-logs-${t}-${o}.log`,s.click(),URL.revokeObjectURL(i)}function Tp(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
20
20
  `)}
21
21
  `],{type:"text/plain"}),i=URL.createObjectURL(n),s=document.createElement("a"),o=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");s.href=i,s.download=`taskmaster-session-logs-${t}-${o}.log`,s.click(),URL.revokeObjectURL(i)}function _p(e){if(typeof ResizeObserver>"u")return;const t=e.querySelector(".topbar");if(!t)return;const n=()=>{const{height:i}=t.getBoundingClientRect();e.style.setProperty("--topbar-height",`${i}px`)};n(),e.topbarObserver=new ResizeObserver(()=>n()),e.topbarObserver.observe(t)}function tt(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function ft(e){return`${JSON.stringify(e,null,2).trimEnd()}
22
- `}function Nl(e,t,n){if(t.length===0)return;let i=e;for(let o=0;o<t.length-1;o+=1){const r=t[o],a=t[o+1];if(typeof r=="number"){if(!Array.isArray(i))return;i[r]==null&&(i[r]=typeof a=="number"?[]:{}),i=i[r]}else{if(typeof i!="object"||i==null)return;const u=i;u[r]==null&&(u[r]=typeof a=="number"?[]:{}),i=u[r]}}const s=t[t.length-1];if(typeof s=="number"){Array.isArray(i)&&(i[s]=n);return}typeof i=="object"&&i!=null&&(i[s]=n)}async function Re(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});Pp(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function Ol(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});Mp(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function Mp(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function Pp(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?ft(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=ft(e.configForm):e.configRaw=n,e.configValid=typeof t.valid=="boolean"?t.valid:null,e.configIssues=Array.isArray(t.issues)?t.issues:[],e.configFormDirty||(e.configForm=tt(t.config??{}),e.configFormOriginal=tt(t.config??{}),e.configRawOriginal=n)}async function Lp(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?ft(e.configForm):e.configRaw,i=(t=e.configSnapshot)==null?void 0:t.hash;if(!i){e.lastError="Config hash missing; reload and retry.";return}await e.client.request("config.set",{raw:n,baseHash:i}),e.configFormDirty=!1,await Re(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function Kt(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("cron.status",{});e.cronStatus=t}catch(t){e.cronError=String(t)}}async function An(e){if(!(!e.client||!e.connected)&&!e.cronLoading){e.cronLoading=!0,e.cronError=null;try{const t={includeDisabled:!0};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(t.agentIds=e.workspaceAgentIds);const n=await e.client.request("cron.list",t);e.cronJobs=Array.isArray(n.jobs)?n.jobs:[]}catch(t){e.cronError=String(t)}finally{e.cronLoading=!1}}}function Fl(e){if(e.scheduleKind==="at"){const n=Date.parse(e.scheduleAt);if(!Number.isFinite(n))throw new Error("Invalid run time.");return{kind:"at",atMs:n}}if(e.scheduleKind==="every"){const n=di(e.everyAmount,0);if(n<=0)throw new Error("Invalid interval amount.");const i=e.everyUnit;return{kind:"every",everyMs:n*(i==="minutes"?6e4:i==="hours"?36e5:864e5)}}const t=e.cronExpr.trim();if(!t)throw new Error("Cron expression required.");return{kind:"cron",expr:t,tz:e.cronTz.trim()||void 0}}function Ul(e){if(e.payloadKind==="systemEvent"){const o=e.payloadText.trim();if(!o)throw new Error("System event text required.");return{kind:"systemEvent",text:o}}const t=e.payloadText.trim();if(!t)throw new Error("Agent message required.");const n={kind:"agentTurn",message:t};e.deliver&&(n.deliver=!0),e.channel&&(n.channel=e.channel);const i=[];e.toAdmins&&i.push("admins");for(const o of e.recipients){const r=o.trim();r&&i.push(r)}i.length>0&&(n.to=i.join(","));const s=di(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function Ip(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Fl(e.cronForm),i=Ul(e.cronForm),s=e.cronForm.agentId.trim(),o=(t=e.cronForm.accountId)==null?void 0:t.trim(),r={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,accountId:o||void 0,enabled:e.cronForm.enabled,schedule:n,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:i,isolation:e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?{postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:void 0};if(!r.name)throw new Error("Name required.");await e.client.request("cron.add",r),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await An(e),await Kt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Rp(e,t,n){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.update",{id:t.id,patch:{enabled:n}}),await An(e),await Kt(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function Dp(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.run",{id:t.id,mode:"force"}),await Ns(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Bp(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.remove",{id:t.id}),e.cronRunsJobId===t.id&&(e.cronRunsJobId=null,e.cronRuns=[]),await An(e),await Kt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function Np(e){var n;const t={name:e.name||"",description:e.description||"",agentId:e.agentId||"",enabled:e.enabled,scheduleKind:e.schedule.kind,scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"",cronTz:"",sessionTarget:e.sessionTarget||"main",wakeMode:e.wakeMode||"next-heartbeat",payloadKind:e.payload.kind,payloadText:"",deliver:!1,channel:"last",recipients:[],toAdmins:!1,timeoutSeconds:"",postToMainPrefix:""};if(e.schedule.kind==="at"){const i=new Date(e.schedule.atMs),s=o=>String(o).padStart(2,"0");t.scheduleAt=`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())}T${s(i.getHours())}:${s(i.getMinutes())}`}else if(e.schedule.kind==="every"){const i=e.schedule.everyMs;i%864e5===0?(t.everyAmount=String(i/864e5),t.everyUnit="days"):i%36e5===0?(t.everyAmount=String(i/36e5),t.everyUnit="hours"):(t.everyAmount=String(i/6e4),t.everyUnit="minutes")}else e.schedule.kind==="cron"&&(t.cronExpr=e.schedule.expr,t.cronTz=e.schedule.tz||"");if(e.payload.kind==="systemEvent")t.payloadText=e.payload.text;else if(e.payload.kind==="agentTurn"){t.payloadText=e.payload.message,t.deliver=e.payload.deliver??!1,t.timeoutSeconds=e.payload.timeoutSeconds?String(e.payload.timeoutSeconds):"";const i=e.payload.channel??e.payload.provider;t.channel=i||"last";const s=e.payload.to||"";if(s){const o=s.split(",").map(r=>r.trim()).filter(Boolean);t.toAdmins=o.some(r=>r.toLowerCase()==="admins"),t.recipients=o.filter(r=>r.toLowerCase()!=="admins")}}return(n=e.isolation)!=null&&n.postToMainPrefix&&(t.postToMainPrefix=e.isolation.postToMainPrefix),t}async function Op(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Fl(e.cronForm),i=Ul(e.cronForm),s={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:e.cronForm.agentId.trim()||void 0,enabled:e.cronForm.enabled,schedule:n,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:i};if(e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?s.isolation={postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:s.isolation=void 0,!s.name)throw new Error("Name required.");await e.client.request("cron.update",{id:t,patch:s}),await An(e),await Kt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Ns(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("cron.runs",{id:t,limit:50});e.cronRunsJobId=t,e.cronRuns=Array.isArray(n.entries)?n.entries:[]}catch(n){e.cronError=String(n)}}async function G(e,t){if(!(!e.client||!e.connected)&&!e.channelsLoading){e.channelsLoading=!0,e.channelsError=null;try{const n=await e.client.request("channels.status",{probe:t,timeoutMs:8e3});e.channelsSnapshot=n,e.channelsLastSuccess=Date.now()}catch(n){e.channelsError=String(n)}finally{e.channelsLoading=!1}}}async function mo(e,t,n){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0,e.whatsappActiveQrAccountId=n??null;try{const i=await e.client.request("web.login.start",{force:t,timeoutMs:3e4,accountId:n});e.whatsappLoginMessage=i.message??null,e.whatsappLoginQrDataUrl=i.qrDataUrl??null,e.whatsappLoginConnected=null}catch(i){e.whatsappLoginMessage=String(i),e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Wl(e,t){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const n=await e.client.request("web.login.wait",{timeoutMs:12e4,accountId:t});e.whatsappLoginMessage=n.message??null,e.whatsappLoginConnected=n.connected??null,n.connected&&(e.whatsappLoginQrDataUrl=null,e.whatsappActiveQrAccountId=null,e.whatsappPairedPhone=n.selfPhone??null)}catch(n){e.whatsappLoginMessage=String(n),e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Kl(e,t){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t}),e.whatsappLoginMessage="Logged out.",e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null}catch(n){e.whatsappLoginMessage=String(n)}finally{e.whatsappBusy=!1}}}async function zl(e,t){if(!e.client||!e.connected||e.whatsappAccountSaving)return;const n=t.trim();if(!n){e.whatsappAccountError="Account name is required.";return}const i=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");if(!i){e.whatsappAccountError="Invalid account name.";return}e.whatsappAccountSaving=!0,e.whatsappAccountError=null;try{const s=await e.client.request("config.get",{});e.configSnapshot=s;const o=tt(s.config??{});(!o.channels||typeof o.channels!="object")&&(o.channels={});const r=o.channels;(!r.whatsapp||typeof r.whatsapp!="object")&&(r.whatsapp={});const a=r.whatsapp;(!a.accounts||typeof a.accounts!="object")&&(a.accounts={});const u=a.accounts;if(u[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}u[i]={name:n,provider:"baileys"};const c=s.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const l=ft(o);await e.client.request("config.set",{raw:l,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await G(e,!0),await mo(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function Hl(e,t){if(!(!e.client||!e.connected)&&!e.whatsappAccountSaving){e.whatsappAccountSaving=!0,e.whatsappAccountError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=tt(n.config??{}),s=i.channels,o=s==null?void 0:s.whatsapp,r=o==null?void 0:o.accounts;if(!r){e.whatsappAccountError="No accounts found in config.";return}if(Object.keys(r).length<=1){e.whatsappAccountError="Cannot remove the last account.";return}if(!r[t]){e.whatsappAccountError=`Account "${t}" not found.`;return}try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t})}catch{}delete r[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(l=>{const p=l.match;return!p||p.channel!=="whatsapp"?!0:p.accountId!==t}));const u=n.hash;if(!u){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=ft(i);await e.client.request("config.set",{raw:c,baseHash:u}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await G(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const Fp=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:zl,loadChannels:G,logoutWhatsApp:Kl,removeWhatsAppAccount:Hl,startWhatsAppLogin:mo,waitWhatsAppLogin:Wl},Symbol.toStringTag,{value:"Module"}));async function yo(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,i,s]=await Promise.all([e.client.request("status",{}),e.client.request("health",{}),e.client.request("models.list",{}),e.client.request("last-heartbeat",{})]);e.debugStatus=t,e.debugHealth=n;const o=i;e.debugModels=Array.isArray(o==null?void 0:o.models)?o==null?void 0:o.models:[],e.debugHeartbeat=s}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}const Up=2e3,Wp=new Set(["trace","debug","info","warn","error","fatal"]);function Kp(e){if(typeof e!="string")return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return!n||typeof n!="object"?null:n}catch{return null}}function zp(e){if(typeof e!="string")return null;const t=e.toLowerCase();return Wp.has(t)?t:null}function ql(e){if(!e.trim())return{raw:e,message:e};try{const t=JSON.parse(e),n=t&&typeof t._meta=="object"&&t._meta!==null?t._meta:null,i=typeof t.time=="string"?t.time:typeof(n==null?void 0:n.date)=="string"?n==null?void 0:n.date:null,s=zp((n==null?void 0:n.logLevelName)??(n==null?void 0:n.level)),o=typeof t[0]=="string"?t[0]:typeof(n==null?void 0:n.name)=="string"?n==null?void 0:n.name:null,r=Kp(o);let a=null;r&&(typeof r.subsystem=="string"?a=r.subsystem:typeof r.module=="string"&&(a=r.module)),!a&&o&&o.length<120&&(a=o);let u=null;return typeof t[1]=="string"?u=t[1]:!r&&typeof t[0]=="string"?u=t[0]:typeof t.message=="string"&&(u=t.message),{raw:e,time:i,level:s,subsystem:a,message:u??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function Rt(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.logsLoading=!0),e.logsError=null;try{const i=await e.client.request("logs.tail",{cursor:t!=null&&t.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),o=(Array.isArray(i.lines)?i.lines.filter(a=>typeof a=="string"):[]).map(ql),r=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=r?o:[...e.logsEntries,...o].slice(-Up),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t!=null&&t.quiet||(e.logsLoading=!1)}}}const Hp=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:Rt,parseLogLine:ql},Symbol.toStringTag,{value:"Module"}));const jl={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:re,n:ii,Gx:Fr,Gy:Ur,a:as,d:ls,h:qp}=jl,gt=32,vo=64,jp=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},te=(e="")=>{const t=new Error(e);throw jp(t,te),t},Vp=e=>typeof e=="bigint",Gp=e=>typeof e=="string",Qp=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",nt=(e,t,n="")=>{const i=Qp(e),s=e==null?void 0:e.length,o=t!==void 0;if(!i||o&&s!==t){const r=n&&`"${n}" `,a=o?` of length ${t}`:"",u=i?`length=${s}`:`type=${typeof e}`;te(r+"expected Uint8Array"+a+", got "+u)}return e},Li=e=>new Uint8Array(e),Vl=e=>Uint8Array.from(e),Gl=(e,t)=>e.toString(16).padStart(t,"0"),Ql=e=>Array.from(nt(e)).map(t=>Gl(t,2)).join(""),Fe={_0:48,_9:57,A:65,F:70,a:97,f:102},Wr=e=>{if(e>=Fe._0&&e<=Fe._9)return e-Fe._0;if(e>=Fe.A&&e<=Fe.F)return e-(Fe.A-10);if(e>=Fe.a&&e<=Fe.f)return e-(Fe.a-10)},Yl=e=>{const t="hex invalid";if(!Gp(e))return te(t);const n=e.length,i=n/2;if(n%2)return te(t);const s=Li(i);for(let o=0,r=0;o<i;o++,r+=2){const a=Wr(e.charCodeAt(r)),u=Wr(e.charCodeAt(r+1));if(a===void 0||u===void 0)return te(t);s[o]=a*16+u}return s},Jl=()=>globalThis==null?void 0:globalThis.crypto,Yp=()=>{var e;return((e=Jl())==null?void 0:e.subtle)??te("crypto.subtle must be defined, consider polyfill")},$n=(...e)=>{const t=Li(e.reduce((i,s)=>i+nt(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Jp=(e=gt)=>Jl().getRandomValues(Li(e)),hi=BigInt,ct=(e,t,n,i="bad number: out of range")=>Vp(e)&&t<=e&&e<n?e:te(i),P=(e,t=re)=>{const n=e%t;return n>=0n?n:t+n},Xl=e=>P(e,ii),Xp=(e,t)=>{(e===0n||t<=0n)&&te("no inverse n="+e+" mod="+t);let n=P(e,t),i=t,s=0n,o=1n;for(;n!==0n;){const r=i/n,a=i%n,u=s-o*r;i=n,n=a,s=o,o=u}return i===1n?P(s,t):te("no inverse")},Zp=e=>{const t=nc[e];return typeof t!="function"&&te("hashes."+e+" not set"),t},cs=e=>e instanceof mt?e:te("Point expected"),Os=2n**256n,Pe=class Pe{constructor(t,n,i,s){U(this,"X");U(this,"Y");U(this,"Z");U(this,"T");const o=Os;this.X=ct(t,0n,o),this.Y=ct(n,0n,o),this.Z=ct(i,1n,o),this.T=ct(s,0n,o),Object.freeze(this)}static CURVE(){return jl}static fromAffine(t){return new Pe(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){const i=ls,s=Vl(nt(t,gt)),o=t[31];s[31]=o&-129;const r=ec(s);ct(r,0n,n?Os:re);const u=P(r*r),c=P(u-1n),l=P(i*u+1n);let{isValid:p,value:f}=th(c,l);p||te("bad point: y not sqrt");const b=(f&1n)===1n,h=(o&128)!==0;return!n&&f===0n&&h&&te("bad point: x==0, isLastByteOdd"),h!==b&&(f=P(-f)),new Pe(f,r,1n,P(f*r))}static fromHex(t,n){return Pe.fromBytes(Yl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=as,n=ls,i=this;if(i.is0())return te("bad point: ZERO");const{X:s,Y:o,Z:r,T:a}=i,u=P(s*s),c=P(o*o),l=P(r*r),p=P(l*l),f=P(u*t),b=P(l*P(f+c)),h=P(p+P(n*P(u*c)));if(b!==h)return te("bad point: equation left != right (1)");const v=P(s*o),k=P(r*a);return v!==k?te("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:r,Z:a}=cs(t),u=P(n*a),c=P(o*s),l=P(i*a),p=P(r*s);return u===c&&l===p}is0(){return this.equals(Lt)}negate(){return new Pe(P(-this.X),this.Y,this.Z,P(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=as,o=P(t*t),r=P(n*n),a=P(2n*P(i*i)),u=P(s*o),c=t+n,l=P(P(c*c)-o-r),p=u+r,f=p-a,b=u-r,h=P(l*f),v=P(p*b),k=P(l*b),$=P(f*p);return new Pe(h,v,$,k)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:r,Y:a,Z:u,T:c}=cs(t),l=as,p=ls,f=P(n*r),b=P(i*a),h=P(o*p*c),v=P(s*u),k=P((n+i)*(r+a)-f-b),$=P(v-h),A=P(v+h),C=P(b-l*f),T=P(k*$),_=P(A*C),R=P(k*C),O=P($*A);return new Pe(T,_,O,R)}subtract(t){return this.add(cs(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return Lt;if(ct(t,1n,ii),t===1n)return this;if(this.equals(yt))return ph(t).p;let i=Lt,s=yt;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?i=i.add(o):n&&(s=s.add(o));return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:i}=this;if(this.equals(Lt))return{x:0n,y:1n};const s=Xp(i,re);P(i*s)!==1n&&te("invalid inverse");const o=P(t*s),r=P(n*s);return{x:o,y:r}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=Zl(n);return i[31]|=t&1n?128:0,i}toHex(){return Ql(this.toBytes())}clearCofactor(){return this.multiply(hi(qp),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ii/2n,!1).double();return ii%2n&&(t=t.add(this)),t.is0()}};U(Pe,"BASE"),U(Pe,"ZERO");let mt=Pe;const yt=new mt(Fr,Ur,1n,P(Fr*Ur)),Lt=new mt(0n,1n,1n,0n);mt.BASE=yt;mt.ZERO=Lt;const Zl=e=>Yl(Gl(ct(e,0n,Os),vo)).reverse(),ec=e=>hi("0x"+Ql(Vl(nt(e)).reverse())),Ee=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=re;return n},eh=e=>{const n=e*e%re*e%re,i=Ee(n,2n)*n%re,s=Ee(i,1n)*e%re,o=Ee(s,5n)*s%re,r=Ee(o,10n)*o%re,a=Ee(r,20n)*r%re,u=Ee(a,40n)*a%re,c=Ee(u,80n)*u%re,l=Ee(c,80n)*u%re,p=Ee(l,10n)*o%re;return{pow_p_5_8:Ee(p,2n)*e%re,b2:n}},Kr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,th=(e,t)=>{const n=P(t*t*t),i=P(n*n*t),s=eh(e*i).pow_p_5_8;let o=P(e*n*s);const r=P(t*o*o),a=o,u=P(o*Kr),c=r===e,l=r===P(-e),p=r===P(-e*Kr);return c&&(o=a),(l||p)&&(o=u),(P(o)&1n)===1n&&(o=P(-o)),{isValid:c||l,value:o}},Fs=e=>Xl(ec(e)),bo=(...e)=>nc.sha512Async($n(...e)),nh=(...e)=>Zp("sha512")($n(...e)),tc=e=>{const t=e.slice(0,gt);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(gt,vo),i=Fs(t),s=yt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},wo=e=>bo(nt(e,gt)).then(tc),ih=e=>tc(nh(nt(e,gt))),sh=e=>wo(e).then(t=>t.pointBytes),oh=e=>bo(e.hashable).then(e.finish),rh=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=Fs(t),r=yt.multiply(o).toBytes();return{hashable:$n(r,i,n),finish:c=>{const l=Xl(o+Fs(c)*s);return nt($n(r,Zl(l)),vo)}}},ah=async(e,t)=>{const n=nt(e),i=await wo(t),s=await bo(i.prefix,n);return oh(rh(i,s,n))},nc={sha512Async:async e=>{const t=Yp(),n=$n(e);return Li(await t.digest("SHA-512",n.buffer))},sha512:void 0},lh=(e=Jp(gt))=>e,ch={getExtendedPublicKeyAsync:wo,getExtendedPublicKey:ih,randomSecretKey:lh},fi=8,uh=256,ic=Math.ceil(uh/fi)+1,Us=2**(fi-1),dh=()=>{const e=[];let t=yt,n=t;for(let i=0;i<ic;i++){n=t,e.push(n);for(let s=1;s<Us;s++)n=n.add(t),e.push(n);t=n.double()}return e};let zr;const Hr=(e,t)=>{const n=t.negate();return e?n:t},ph=e=>{const t=zr||(zr=dh());let n=Lt,i=yt;const s=2**fi,o=s,r=hi(s-1),a=hi(fi);for(let u=0;u<ic;u++){let c=Number(e&r);e>>=a,c>Us&&(c-=o,e+=1n);const l=u*Us,p=l,f=l+Math.abs(c)-1,b=u%2!==0,h=c<0;c===0?i=i.add(Hr(b,t[p])):n=n.add(Hr(h,t[f]))}return e!==0n&&te("invalid wnaf"),{p:n,f:i}},us="taskmaster-device-identity-v1";function Ws(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function sc(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4),i=atob(n),s=new Uint8Array(i.length);for(let o=0;o<i.length;o+=1)s[o]=i.charCodeAt(o);return s}function hh(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function oc(e){const t=await crypto.subtle.digest("SHA-256",e);return hh(new Uint8Array(t))}async function fh(){const e=ch.randomSecretKey(),t=await sh(e);return{deviceId:await oc(t),publicKey:Ws(t),privateKey:Ws(e)}}async function gh(){try{const n=localStorage.getItem(us);if(n){const i=JSON.parse(n);if((i==null?void 0:i.version)===1&&typeof i.deviceId=="string"&&typeof i.publicKey=="string"&&typeof i.privateKey=="string"){const s=await oc(sc(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(us,JSON.stringify(o)),{deviceId:s,publicKey:i.publicKey,privateKey:i.privateKey}}return{deviceId:i.deviceId,publicKey:i.publicKey,privateKey:i.privateKey}}}}catch{}const e=await fh(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(us,JSON.stringify(t)),e}async function mh(e,t){const n=sc(e),i=new TextEncoder().encode(t),s=await ah(i,n);return Ws(s)}const rc="taskmaster.device.auth.v1";function ko(e){return e.trim()}function yh(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const i=n.trim();i&&t.add(i)}return[...t].sort()}function So(){try{const e=window.localStorage.getItem(rc);if(!e)return null;const t=JSON.parse(e);return!t||t.version!==1||!t.deviceId||typeof t.deviceId!="string"||!t.tokens||typeof t.tokens!="object"?null:t}catch{return null}}function ac(e){try{window.localStorage.setItem(rc,JSON.stringify(e))}catch{}}function vh(e){const t=So();if(!t||t.deviceId!==e.deviceId)return null;const n=ko(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function bh(e){const t=ko(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=So();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:yh(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,ac(n),s}function wh(e){const t=So();if(!t||t.deviceId!==e.deviceId)return;const n=ko(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],ac(i)}async function $o(e,t){if(!(!e.client||!e.connected)&&!e.devicesLoading){e.devicesLoading=!0,t!=null&&t.quiet||(e.devicesError=null);try{const n=await e.client.request("device.pair.list",{});e.devicesList={pending:Array.isArray(n==null?void 0:n.pending)?n.pending:[],paired:Array.isArray(n==null?void 0:n.paired)?n.paired:[]}}catch(n){t!=null&&t.quiet||(e.devicesError=String(n))}finally{e.devicesLoading=!1}}}async function xo(e,t){if(!(!e.client||!e.connected)&&!e.nodesLoading){e.nodesLoading=!0,t!=null&&t.quiet||(e.lastError=null);try{const n=await e.client.request("node.list",{});e.nodes=Array.isArray(n.nodes)?n.nodes:[]}catch(n){t!=null&&t.quiet||(e.lastError=String(n))}finally{e.nodesLoading=!1}}}function kh(e){return{method:"exec.approvals.get",params:{}}}async function Sh(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=kh(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);$h(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function $h(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=tt(t.file??{}))}async function lc(e){if(!(!e.client||!e.connected)&&!e.presenceLoading){e.presenceLoading=!0,e.presenceError=null,e.presenceStatus=null;try{const t=await e.client.request("system-presence",{});Array.isArray(t)?(e.presenceEntries=t,e.presenceStatus=t.length===0?"No instances yet.":null):(e.presenceEntries=[],e.presenceStatus="No presence payload.")}catch(t){e.presenceError=String(t)}finally{e.presenceLoading=!1}}}function Nt(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function qe(e){return e instanceof Error?e.message:String(e)}function Ii(){return{name:"",skillContent:"",references:[]}}async function He(e,t){if(t!=null&&t.clearMessages&&Object.keys(e.skillMessages).length>0&&(e.skillMessages={}),!(!e.client||!e.connected)&&!e.skillsLoading){e.skillsLoading=!0,e.skillsError=null;try{const n=await e.client.request("skills.status",{});n&&(e.skillsReport=n)}catch(n){e.skillsError=qe(n)}finally{e.skillsLoading=!1}}}function cc(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function uc(e,t,n){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.update",{skillKey:t,enabled:n}),await He(e),Nt(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=qe(i);e.skillsError=s,Nt(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function dc(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const n=e.skillEdits[t]??"";await e.client.request("skills.update",{skillKey:t,apiKey:n}),await He(e),Nt(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=qe(n);e.skillsError=i,Nt(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function pc(e,t,n,i){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const s=await e.client.request("skills.install",{name:n,installId:i,timeoutMs:12e4});await He(e),Nt(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=qe(s);e.skillsError=o,Nt(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function hc(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("skills.read",{name:t});n&&(e.skillDetail=n,e.skillDetailTab="SKILL.md")}catch(n){e.skillsError=qe(n)}}function fc(e){e.skillDetail=null,e.skillDetailTab=""}function gc(e,t){e.skillDetailTab=t}async function mc(e){if(e.skillAddModal=!0,e.skillAddForm=Ii(),e.skillDrafts=[],!(!e.client||!e.connected))try{const t=await e.client.request("skills.drafts",{});t&&(e.skillDrafts=t.drafts)}catch{}}function yc(e){e.skillAddModal=!1,e.skillAddForm=Ii(),e.skillDrafts=[]}function vc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n}))}}async function bc(e){if(!e.client||!e.connected)return;const t=e.skillAddForm;if(!(!t.name.trim()||!t.skillContent.trim())){e.skillsBusyKey="__add__",e.skillsError=null;try{const n=t.references.filter(i=>i.name.trim()&&i.content.trim()).map(i=>({name:i.name.trim(),content:i.content}));await e.client.request("skills.create",{name:t.name.trim(),skillContent:t.skillContent,references:n.length>0?n:void 0}),e.skillAddModal=!1,e.skillAddForm=Ii(),e.skillDrafts=[],await He(e)}catch(n){e.skillsError=qe(n)}finally{e.skillsBusyKey=null}}}async function wc(e,t){if(!(!e.client||!e.connected))try{await e.client.request("skills.deleteDraft",{name:t}),e.skillDrafts=e.skillDrafts.filter(n=>n.name!==t)}catch(n){e.skillsError=qe(n)}}async function kc(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("skills.read",{name:t});if(!n)return;e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i}))},e.skillAddModal=!0,e.skillDrafts=[]}catch(n){e.skillsError=qe(n)}}async function Sc(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await He(e)}catch(n){e.skillsError=qe(n)}finally{e.skillsBusyKey=null}}}const xh=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:yc,closeSkillDetail:fc,deleteDraft:wc,deleteSkill:Sc,editSkill:kc,emptyAddForm:Ii,importDraft:vc,installSkill:pc,loadSkills:He,openAddSkillModal:mc,saveNewSkill:bc,saveSkillApiKey:dc,setSkillDetailTab:gc,updateSkillEdit:cc,updateSkillEnabled:uc,viewSkillDetail:hc},Symbol.toStringTag,{value:"Module"})),$c={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},xc=new Map(Object.entries($c).map(([e,t])=>[t,e]));function Ri(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function xn(e){if(!e)return"/";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Ah(e,t=""){const n=Ri(t),i=$c[e];return n?`${n}${i}`:i}function Ac(e,t=""){const n=Ri(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=xn(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":xc.get(s)??null}function Eh(e){let t=xn(e);if(t.endsWith("/index.html")&&(t=xn(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let i=0;i<n.length;i++){const s=`/${n.slice(i).join("/")}`.toLowerCase();if(xc.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function Ch(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Ao(e){return e==="system"?Ch():e}const Hn=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,Th=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,qn=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},_h=({nextTheme:e,applyTheme:t,context:n,currentTheme:i})=>{var c;if(i===e)return;const s=globalThis.document??null;if(!s){t();return}const o=s.documentElement,r=s,a=Th();if(!!r.startViewTransition&&!a){let l=.5,p=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")l=Hn(n.pointerClientX/window.innerWidth),p=Hn(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const f=n.element.getBoundingClientRect();f.width>0&&f.height>0&&typeof window<"u"&&(l=Hn((f.left+f.width/2)/window.innerWidth),p=Hn((f.top+f.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${l*100}%`),o.style.setProperty("--theme-switch-y",`${p*100}%`),o.classList.add("theme-transition");try{const f=(c=r.startViewTransition)==null?void 0:c.call(r,()=>{t()});f!=null&&f.finished?f.finished.finally(()=>qn(o)):qn(o)}catch{qn(o),t()}return}t(),qn(o)},Mh=2e3;async function mn(e,t){if(!(!e.client||!e.connected)&&!(e.sessionLogsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.sessionLogsLoading=!0),e.sessionLogsError=null;try{const n={cursors:t!=null&&t.reset?void 0:e.sessionLogsCursors,limit:500};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(n.agents=e.workspaceAgentIds);const s=await e.client.request("sessions.transcript",n),o=Array.isArray(s.entries)?s.entries:[],r=!!(t!=null&&t.reset||Object.keys(e.sessionLogsCursors).length===0);e.sessionLogsEntries=r?o:[...e.sessionLogsEntries,...o].slice(-Mh),s.cursors&&(e.sessionLogsCursors=s.cursors),Array.isArray(s.agents)&&(e.sessionLogsAgents=s.agents),e.sessionLogsLastFetchAt=Date.now()}catch(n){e.sessionLogsError=String(n)}finally{t!=null&&t.quiet||(e.sessionLogsLoading=!1)}}}const Ec=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:mn},Symbol.toStringTag,{value:"Module"}));async function Cc(e,t){if(!(!e.client||!e.connected))try{const n={},i=await e.client.request("memory.audit",n);i!=null&&i.ok&&(e.auditEntries=i.entries??[])}catch{}}async function Ph(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function De(e){return e instanceof Error?e.message:String(e)}let jn=null;function zt(e,t){jn&&clearTimeout(jn),e.filesMessage={kind:"success",text:t},jn=setTimeout(()=>{e.filesMessage=null,jn=null},3e3)}async function Ht(e,t){if(!(!e.client||!e.connected)){if(!t){e.filesTree=[],e.filesRoot="";return}if(!e.filesLoading){e.filesLoading=!0,e.filesError=null;try{const n={};t&&(n.agentId=t);const i=await e.client.request("files.tree",n);i!=null&&i.tree&&(e.filesTree=i.tree,e.filesRoot=i.root??"")}catch(n){e.filesError=De(n)}finally{e.filesLoading=!1}}}}async function Lh(e,t,n){e.filesSelectedPaths=new Set([t]),await Tc(e,t,n)}async function Ih(e,t,n){const i=new Set(e.filesSelectedPaths);if(i.has(t)?i.delete(t):i.add(t),e.filesSelectedPaths=i,i.size===1){const s=[...i][0];await Tc(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function Rh(e,t){if(!e.client||!e.connected)return;const n=[...e.filesSelectedPaths];if(n.length===0)return;let i=0,s="";for(const o of n)try{await _c(e,o,t),i++}catch(r){s=De(r)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:zt(e,`${i} file${i!==1?"s":""} downloaded`)}async function Dh(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await Fh(e,t,o,i)}async function Tc(e,t,n){if(!(!e.client||!e.connected)){e.filesSelectedPath=t,e.filesPreviewLoading=!0,e.filesPreviewContent=null,e.filesPreviewBinary=!1,e.filesPreviewSize=null;try{const i={path:t};n&&(i.agentId=n);const s=await e.client.request("files.read",i);e.filesPreviewContent=(s==null?void 0:s.content)??null,e.filesPreviewBinary=(s==null?void 0:s.binary)??!1,e.filesPreviewSize=(s==null?void 0:s.size)??null}catch(i){e.filesError=De(i)}finally{e.filesPreviewLoading=!1}}}async function _c(e,t,n){if(!(!e.client||!e.connected))try{const i={path:t};n&&(i.agentId=n);const s=await e.client.request("files.download",i);if(!(s!=null&&s.base64)){e.filesMessage={kind:"error",text:"Download failed: no data"};return}const o=Uint8Array.from(atob(s.base64),c=>c.charCodeAt(0)),r=new Blob([o]),a=URL.createObjectURL(r),u=document.createElement("a");u.href=a,u.download=s.name??t.split("/").pop()??"download",document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(a)}catch(i){e.filesMessage={kind:"error",text:De(i)}}}async function Bh(e,t,n,i){if(!e.client||!e.connected)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="";for(const r of n)try{const a=await r.arrayBuffer(),u=btoa(new Uint8Array(a).reduce((l,p)=>l+String.fromCharCode(p),"")),c={path:t,name:r.name,data:u};i&&(c.agentId=i),await e.client.request("files.upload",c),s++}catch(a){o=De(a)}e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:zt(e,`${s} file${s!==1?"s":""} uploaded`),await Ht(e,i)}async function Nh(e,t,n,i){if(!e.client||!e.connected)return;e.filesMessage=null;const s=t==="."?n:`${t}/${n}`;try{const o={path:s};i&&(o.agentId=i),await e.client.request("files.mkdir",o),zt(e,`Created ${s}`),await Ht(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:De(o)}}}async function Oh(e,t,n){if(!(!e.client||!e.connected)){e.filesMessage=null;try{const i={path:t};n&&(i.agentId=n),await e.client.request("files.delete",i),zt(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await Ht(e,n)}catch(i){e.filesMessage={kind:"error",text:De(i)}}}}async function Fh(e,t,n,i){if(!(!e.client||!e.connected)){e.filesMessage=null;try{const s={from:t,to:n};i&&(s.agentId=i),await e.client.request("files.move",s),zt(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await Ht(e,i)}catch(s){e.filesMessage={kind:"error",text:De(s)}}}}async function Eo(e,t){if(!(!e.client||!e.connected))try{const n={};t&&(n.agentId=t);const i=await e.client.request("memory.status",n);i!=null&&i.ok&&(e.filesMemoryStatus={dirty:i.dirty??!1,syncing:i.syncing,syncProgress:i.syncProgress,files:i.files??0,chunks:i.chunks??0,model:i.model,embeddingState:i.embeddingState})}catch{}}async function Uh(e,t){if(!(!e.client||!e.connected)&&!e.filesReindexBusy){e.filesReindexBusy=!0,e.filesMessage=null;try{const n={force:!0};t&&(n.agentId=t);const i=await e.client.request("memory.reindex",n),s=(i==null?void 0:i.files)??0,o=(i==null?void 0:i.chunks)??0;zt(e,`Re-indexed: ${s} files, ${o} chunks`),await Eo(e,t)}catch(n){e.filesMessage={kind:"error",text:De(n)}}finally{e.filesReindexBusy=!1}}}function Wh(e,t){const n=new Set(e.filesExpandedDirs);n.has(t)?n.delete(t):n.add(t),e.filesExpandedDirs=n,e.filesCurrentDir=t}async function Kh(e,t,n){if(!(!e.client||!e.connected)){if(!t.trim()){e.filesSearchResults=null;return}e.filesSearchLoading=!0,e.filesSearchResults=null;try{const i={query:t.trim(),maxResults:20};n&&(i.agentId=n);const s=await e.client.request("memory.search",i);e.filesSearchResults=(s==null?void 0:s.results)??[]}catch(i){e.filesMessage={kind:"error",text:De(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function zh(e){e.filesSearchQuery="",e.filesSearchResults=null}function Hh(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{xo(e,{quiet:!0})},5e3))}function qh(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Co(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Rt(e,{quiet:!0})},2e3))}function To(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function _o(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||mn(e,{quiet:!0})},2e3))}function Mo(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function Po(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&yo(e)},3e3))}function Lo(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function jh(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{Cc(e)},3e4))}function Vh(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function Gh(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{if(e.tab!=="files")return;const t=e;Eo(t,t.filesResolvedAgentId)},3e3))}function Qh(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function Ze(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,Vd(n),t.theme!==e.theme&&(e.theme=t.theme,Di(e,Ao(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Mc(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&Ze(e,{...e.settings,lastActiveSessionKey:n})}function Yh(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),i=t.get("password"),s=t.get("session"),o=t.get("gatewayUrl");let r=!1;if(n!=null){const u=n.trim();u&&u!==e.settings.token&&Ze(e,{...e.settings,token:u}),t.delete("token"),r=!0}if(i!=null){const u=i.trim();u&&(e.password=u),t.delete("password"),r=!0}if(s!=null){const u=s.trim();u&&(e.sessionKey=u,Ze(e,{...e.settings,sessionKey:u,lastActiveSessionKey:u}))}if(o!=null){const u=o.trim();u&&u!==e.settings.gatewayUrl&&Ze(e,{...e.settings,gatewayUrl:u}),t.delete("gatewayUrl"),r=!0}if(!r)return;const a=new URL(window.location.href);a.search=t.toString(),window.history.replaceState({},"",a.toString())}function Jh(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?_o(e):Co(e):(To(e),Mo(e)),t==="debug"?Po(e):Lo(e),gi(e),Lc(e,t,!1)}function Xh(e,t,n){_h({nextTheme:t,applyTheme:()=>{e.theme=t,Ze(e,{...e.settings,theme:t}),Di(e,Ao(t))},context:n,currentTheme:e.theme})}async function gi(e){if(e.tab==="overview"&&await Ic(e),e.tab==="channels"&&await rf(e),e.tab==="instances"&&await lc(e),e.tab==="cron"&&await Io(e),e.tab==="skills"&&await He(e),e.tab==="nodes"&&(await xo(e),await $o(e),await Re(e),await Sh(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await df(e),Wt(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await Ol(e),await Re(e)),e.tab==="debug"&&(await yo(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await ie(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>Ec);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await Rt(e,{reset:!0});Bl(e,!0)}}function Zh(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?Ri(e):Eh(window.location.pathname)}function ef(e){e.theme=e.settings.theme??"system",Di(e,Ao(e.theme))}function Di(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function tf(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;if(e.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),e.themeMediaHandler=n=>{e.theme==="system"&&Di(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function nf(e){if(!e.themeMedia||!e.themeMediaHandler)return;if(typeof e.themeMedia.removeEventListener=="function"){e.themeMedia.removeEventListener("change",e.themeMediaHandler);return}e.themeMedia.removeListener(e.themeMediaHandler),e.themeMedia=null,e.themeMediaHandler=null}function sf(e,t){if(typeof window>"u")return;const n=Ac(window.location.pathname,e.basePath)??"chat";Pc(e,n),Lc(e,n,t)}function of(e){var s;if(typeof window>"u")return;const t=Ac(window.location.pathname,e.basePath);if(!t)return;const i=(s=new URL(window.location.href).searchParams.get("session"))==null?void 0:s.trim();i&&(e.sessionKey=i,Ze(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),Pc(e,t)}function Pc(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?_o(e):Co(e):(To(e),Mo(e)),t==="debug"?Po(e):Lo(e),e.connected&&gi(e)}function Lc(e,t,n){if(typeof window>"u")return;const i=xn(Ah(t,e.basePath)),s=xn(window.location.pathname),o=new URL(window.location.href);t==="chat"&&e.sessionKey?o.searchParams.set("session",e.sessionKey):o.searchParams.delete("session"),s!==i&&(o.pathname=i),n?window.history.replaceState({},"",o.toString()):window.history.pushState({},"",o.toString())}async function Ic(e){await Promise.all([G(e,!1),lc(e),fo(e),Kt(e),yo(e)])}async function rf(e){await Promise.all([G(e,!0),Ol(e),Re(e)])}async function Io(e){await Promise.all([G(e,!1),Kt(e),An(e)])}function Rc(e){return e.chatSending||!!e.chatRunId}function af(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/stop"?!0:n==="stop"||n==="esc"||n==="abort"||n==="wait"||n==="exit"}async function Dc(e){e.connected&&(e.chatMessage="",await Rl(e))}function lf(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:ho(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],Wt(e))}async function Bc(e,t,n){var s,o;go(e);const i=await Il(e,t,n==null?void 0:n.attachments);return!i&&(n==null?void 0:n.previousDraft)!=null&&(e.chatMessage=n.previousDraft),!i&&(n!=null&&n.previousAttachments)&&(e.chatAttachments=n.previousAttachments),i&&Mc(e,e.sessionKey),i&&(n!=null&&n.restoreDraft)&&((s=n.previousDraft)!=null&&s.trim())&&(e.chatMessage=n.previousDraft),i&&(n!=null&&n.restoreAttachments)&&((o=n.previousAttachments)!=null&&o.length)&&(e.chatAttachments=n.previousAttachments),Wt(e),i&&!e.chatRunId&&Nc(e),i}async function Nc(e){if(!e.connected||Rc(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await Bc(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function cf(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function uf(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),o=e.chatAttachments??[],r=t==null?o:[],a=r.length>0;if(!(!s&&!a)){if(af(s)){await Dc(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[]),Rc(e)){lf(e,s,r);return}await Bc(e,s,{previousDraft:t==null?i:void 0,restoreDraft:!!(t&&(n!=null&&n.restoreDraft)),attachments:a?r:void 0,previousAttachments:t==null?o:void 0,restoreAttachments:!!(t&&(n!=null&&n.restoreDraft))})}}async function df(e){var i;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,Ie);await Promise.all([Le(t,{limit:n}),fo(t),Ks(e)]),Wt(e,!0)}const pf=Nc;function hf(e){var s,o,r;const t=xl(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(s=e.hello)==null?void 0:s.snapshot;return((r=(o=n==null?void 0:n.sessionDefaults)==null?void 0:o.defaultAgentId)==null?void 0:r.trim())||"main"}function ff(e,t){const n=Ri(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Ks(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=hf(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=ff(e.basePath,t);try{const i=await fetch(n,{method:"GET"});if(!i.ok){e.chatAvatarUrl=null;return}const s=await i.json(),o=typeof s.avatarUrl=="string"?s.avatarUrl.trim():"";e.chatAvatarUrl=o||null}catch{e.chatAvatarUrl=null}}const D={messageSquare:d`<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`,barChart:d`<svg viewBox="0 0 24 24"><line x1="12" x2="12" y1="20" y2="10"/><line x1="18" x2="18" y1="20" y2="4"/><line x1="6" x2="6" y1="20" y2="16"/></svg>`,link:d`<svg viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,unlink:d`<svg viewBox="0 0 24 24"><path d="m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71"/><path d="m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71"/><line x1="8" x2="8" y1="2" y2="5"/><line x1="2" x2="5" y1="8" y2="8"/><line x1="16" x2="16" y1="19" y2="22"/><line x1="19" x2="22" y1="16" y2="16"/></svg>`,radio:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="2"/><path d="M16.24 7.76a6 6 0 0 1 0 8.49m-8.48-.01a6 6 0 0 1 0-8.49m11.31-2.82a10 10 0 0 1 0 14.14m-14.14 0a10 10 0 0 1 0-14.14"/></svg>`,fileText:d`<svg viewBox="0 0 24 24"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" x2="8" y1="13" y2="13"/><line x1="16" x2="8" y1="17" y2="17"/><line x1="10" x2="8" y1="9" y2="9"/></svg>`,zap:d`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:d`<svg viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg>`,settings:d`<svg viewBox="0 0 24 24"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>`,bug:d`<svg viewBox="0 0 24 24"><path d="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/></svg>`,scrollText:d`<svg viewBox="0 0 24 24"><path d="M8 21h12a2 2 0 0 0 2-2v-2H10v2a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v3h4"/><path d="M19 17V5a2 2 0 0 0-2-2H4"/><path d="M15 8h-5"/><path d="M15 12h-5"/></svg>`,folder:d`<svg viewBox="0 0 24 24"><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"/></svg>`,users:d`<svg viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>`,menu:d`<svg viewBox="0 0 24 24"><line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/></svg>`,x:d`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:d`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:d`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>`,search:d`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:d`<svg viewBox="0 0 24 24"><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"/><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"/><path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/><path d="M17.599 6.5a3 3 0 0 0 .399-1.375"/><path d="M6.003 5.125A3 3 0 0 0 6.401 6.5"/><path d="M3.477 10.896a4 4 0 0 1 .585-.396"/><path d="M19.938 10.5a4 4 0 0 1 .585.396"/><path d="M6 18a4 4 0 0 1-1.967-.516"/><path d="M19.967 17.484A4 4 0 0 1 18 18"/></svg>`,book:d`<svg viewBox="0 0 24 24"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/></svg>`,loader:d`<svg viewBox="0 0 24 24"><path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/></svg>`,rotateCw:d`<svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg>`,download:d`<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>`,wrench:d`<svg viewBox="0 0 24 24"><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"/></svg>`,fileCode:d`<svg viewBox="0 0 24 24"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><path d="m10 13-2 2 2 2"/><path d="m14 17 2-2-2-2"/></svg>`,edit:d`<svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,penLine:d`<svg viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>`,paperclip:d`<svg viewBox="0 0 24 24"><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"/></svg>`,globe:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>`,image:d`<svg viewBox="0 0 24 24"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>`,smartphone:d`<svg viewBox="0 0 24 24"><rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/></svg>`,plug:d`<svg viewBox="0 0 24 24"><path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/></svg>`,circle:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>`,puzzle:d`<svg viewBox="0 0 24 24"><path d="M19.439 7.85c-.049.322.059.648.289.878l1.568 1.568c.47.47.706 1.087.706 1.704s-.235 1.233-.706 1.704l-1.611 1.611a.98.98 0 0 1-.837.276c-.47-.07-.802-.48-.968-.925a2.501 2.501 0 1 0-3.214 3.214c.446.166.855.497.925.968a.979.979 0 0 1-.276.837l-1.61 1.61a2.404 2.404 0 0 1-1.705.707 2.402 2.402 0 0 1-1.704-.706l-1.568-1.568a1.026 1.026 0 0 0-.877-.29c-.493.074-.84.504-1.02.968a2.5 2.5 0 1 1-3.237-3.237c.464-.18.894-.527.967-1.02a1.026 1.026 0 0 0-.289-.877l-1.568-1.568A2.402 2.402 0 0 1 1.998 12c0-.617.236-1.234.706-1.704L4.23 8.77c.24-.24.581-.353.917-.303.515.076.874.54 1.02 1.02a2.5 2.5 0 1 0 3.237-3.237c-.48-.146-.944-.505-1.02-1.02a.98.98 0 0 1 .303-.917l1.526-1.526A2.402 2.402 0 0 1 11.998 2c.617 0 1.234.236 1.704.706l1.568 1.568c.23.23.556.338.877.29.493-.074.84-.504 1.02-.968a2.5 2.5 0 1 1 3.236 3.236c-.464.18-.894.527-.967 1.02Z"/></svg>`,info:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>`,send:d`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>`,slidersHorizontal:d`<svg viewBox="0 0 24 24"><line x1="21" x2="14" y1="4" y2="4"/><line x1="10" x2="3" y1="4" y2="4"/><line x1="21" x2="12" y1="12" y2="12"/><line x1="8" x2="3" y1="12" y2="12"/><line x1="21" x2="16" y1="20" y2="20"/><line x1="12" x2="3" y1="20" y2="20"/><line x1="14" x2="14" y1="2" y2="6"/><line x1="8" x2="8" y1="10" y2="14"/><line x1="16" x2="16" y1="18" y2="22"/></svg>`,square:d`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:d`<svg viewBox="0 0 24 24"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>`,eyeOff:d`<svg viewBox="0 0 24 24"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/></svg>`,trash:d`<svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>`,chevronDown:d`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,film:d`<svg viewBox="0 0 24 24"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M7 3v18"/><path d="M3 7.5h4"/><path d="M3 12h18"/><path d="M3 16.5h4"/><path d="M17 3v18"/><path d="M17 7.5h4"/><path d="M17 16.5h4"/></svg>`,wifi:d`<svg viewBox="0 0 24 24"><path d="M12 20h.01"/><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.859a10 10 0 0 1 14 0"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/></svg>`,wifiOff:d`<svg viewBox="0 0 24 24"><path d="M12 20h.01"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/><path d="M5 12.859a10 10 0 0 1 5.17-2.69"/><path d="M13.41 10.28a10 10 0 0 1 5.59 2.58"/><path d="M2 8.82a15 15 0 0 1 4.17-2.65"/><path d="M10.66 5c4.01-.36 8.14.9 11.34 3.76"/><line x1="2" x2="22" y1="2" y2="22"/></svg>`},gf=d`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>`,mf=d`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>`;let qr=!1;function yf(){qr||(qr=!0,document.addEventListener("click",e=>{const t=document.getElementById("nav-burger-toggle");if(!(t!=null&&t.checked))return;const n=t.closest(".setup-header");n!=null&&n.contains(e.target)||(t.checked=!1)}))}function kt(e,t){var l;const n=(p,f)=>p===e?d`<span class="sp-page-nav-current">${p}</span>`:d`<a href=${f}>${p}</a>`,i=d`
22
+ `}function Nl(e,t,n){if(t.length===0)return;let i=e;for(let o=0;o<t.length-1;o+=1){const r=t[o],a=t[o+1];if(typeof r=="number"){if(!Array.isArray(i))return;i[r]==null&&(i[r]=typeof a=="number"?[]:{}),i=i[r]}else{if(typeof i!="object"||i==null)return;const u=i;u[r]==null&&(u[r]=typeof a=="number"?[]:{}),i=u[r]}}const s=t[t.length-1];if(typeof s=="number"){Array.isArray(i)&&(i[s]=n);return}typeof i=="object"&&i!=null&&(i[s]=n)}async function Re(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});Pp(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function Ol(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});Mp(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function Mp(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function Pp(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?ft(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=ft(e.configForm):e.configRaw=n,e.configValid=typeof t.valid=="boolean"?t.valid:null,e.configIssues=Array.isArray(t.issues)?t.issues:[],e.configFormDirty||(e.configForm=tt(t.config??{}),e.configFormOriginal=tt(t.config??{}),e.configRawOriginal=n)}async function Lp(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?ft(e.configForm):e.configRaw,i=(t=e.configSnapshot)==null?void 0:t.hash;if(!i){e.lastError="Config hash missing; reload and retry.";return}await e.client.request("config.set",{raw:n,baseHash:i}),e.configFormDirty=!1,await Re(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function Kt(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("cron.status",{});e.cronStatus=t}catch(t){e.cronError=String(t)}}async function xn(e){if(!(!e.client||!e.connected)&&!e.cronLoading){e.cronLoading=!0,e.cronError=null;try{const t={includeDisabled:!0};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(t.agentIds=e.workspaceAgentIds);const n=await e.client.request("cron.list",t);e.cronJobs=Array.isArray(n.jobs)?n.jobs:[]}catch(t){e.cronError=String(t)}finally{e.cronLoading=!1}}}function Fl(e){if(e.scheduleKind==="at"){const n=Date.parse(e.scheduleAt);if(!Number.isFinite(n))throw new Error("Invalid run time.");return{kind:"at",atMs:n}}if(e.scheduleKind==="every"){const n=di(e.everyAmount,0);if(n<=0)throw new Error("Invalid interval amount.");const i=e.everyUnit;return{kind:"every",everyMs:n*(i==="minutes"?6e4:i==="hours"?36e5:864e5)}}const t=e.cronExpr.trim();if(!t)throw new Error("Cron expression required.");return{kind:"cron",expr:t,tz:e.cronTz.trim()||void 0}}function Ul(e){if(e.payloadKind==="systemEvent"){const o=e.payloadText.trim();if(!o)throw new Error("System event text required.");return{kind:"systemEvent",text:o}}const t=e.payloadText.trim();if(!t)throw new Error("Agent message required.");const n={kind:"agentTurn",message:t};e.deliver&&(n.deliver=!0),e.channel&&(n.channel=e.channel);const i=[];e.toAdmins&&i.push("admins");for(const o of e.recipients){const r=o.trim();r&&i.push(r)}i.length>0&&(n.to=i.join(","));const s=di(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function Ip(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Fl(e.cronForm),i=Ul(e.cronForm),s=e.cronForm.agentId.trim(),o=(t=e.cronForm.accountId)==null?void 0:t.trim(),r={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,accountId:o||void 0,enabled:e.cronForm.enabled,schedule:n,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:i,isolation:e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?{postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:void 0};if(!r.name)throw new Error("Name required.");await e.client.request("cron.add",r),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await xn(e),await Kt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Rp(e,t,n){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.update",{id:t.id,patch:{enabled:n}}),await xn(e),await Kt(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function Dp(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.run",{id:t.id,mode:"force"}),await Ns(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Bp(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.remove",{id:t.id}),e.cronRunsJobId===t.id&&(e.cronRunsJobId=null,e.cronRuns=[]),await xn(e),await Kt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function Np(e){var n;const t={name:e.name||"",description:e.description||"",agentId:e.agentId||"",enabled:e.enabled,scheduleKind:e.schedule.kind,scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"",cronTz:"",sessionTarget:e.sessionTarget||"main",wakeMode:e.wakeMode||"next-heartbeat",payloadKind:e.payload.kind,payloadText:"",deliver:!1,channel:"last",recipients:[],toAdmins:!1,timeoutSeconds:"",postToMainPrefix:""};if(e.schedule.kind==="at"){const i=new Date(e.schedule.atMs),s=o=>String(o).padStart(2,"0");t.scheduleAt=`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())}T${s(i.getHours())}:${s(i.getMinutes())}`}else if(e.schedule.kind==="every"){const i=e.schedule.everyMs;i%864e5===0?(t.everyAmount=String(i/864e5),t.everyUnit="days"):i%36e5===0?(t.everyAmount=String(i/36e5),t.everyUnit="hours"):(t.everyAmount=String(i/6e4),t.everyUnit="minutes")}else e.schedule.kind==="cron"&&(t.cronExpr=e.schedule.expr,t.cronTz=e.schedule.tz||"");if(e.payload.kind==="systemEvent")t.payloadText=e.payload.text;else if(e.payload.kind==="agentTurn"){t.payloadText=e.payload.message,t.deliver=e.payload.deliver??!1,t.timeoutSeconds=e.payload.timeoutSeconds?String(e.payload.timeoutSeconds):"";const i=e.payload.channel??e.payload.provider;t.channel=i||"last";const s=e.payload.to||"";if(s){const o=s.split(",").map(r=>r.trim()).filter(Boolean);t.toAdmins=o.some(r=>r.toLowerCase()==="admins"),t.recipients=o.filter(r=>r.toLowerCase()!=="admins")}}return(n=e.isolation)!=null&&n.postToMainPrefix&&(t.postToMainPrefix=e.isolation.postToMainPrefix),t}async function Op(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Fl(e.cronForm),i=Ul(e.cronForm),s={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:e.cronForm.agentId.trim()||void 0,enabled:e.cronForm.enabled,schedule:n,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:i};if(e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?s.isolation={postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:s.isolation=void 0,!s.name)throw new Error("Name required.");await e.client.request("cron.update",{id:t,patch:s}),await xn(e),await Kt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Ns(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("cron.runs",{id:t,limit:50});e.cronRunsJobId=t,e.cronRuns=Array.isArray(n.entries)?n.entries:[]}catch(n){e.cronError=String(n)}}async function G(e,t){if(!(!e.client||!e.connected)&&!e.channelsLoading){e.channelsLoading=!0,e.channelsError=null;try{const n=await e.client.request("channels.status",{probe:t,timeoutMs:8e3});e.channelsSnapshot=n,e.channelsLastSuccess=Date.now()}catch(n){e.channelsError=String(n)}finally{e.channelsLoading=!1}}}async function mo(e,t,n){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0,e.whatsappActiveQrAccountId=n??null;try{const i=await e.client.request("web.login.start",{force:t,timeoutMs:3e4,accountId:n});e.whatsappLoginMessage=i.message??null,e.whatsappLoginQrDataUrl=i.qrDataUrl??null,e.whatsappLoginConnected=null}catch(i){e.whatsappLoginMessage=String(i),e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Wl(e,t){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const n=await e.client.request("web.login.wait",{timeoutMs:12e4,accountId:t});e.whatsappLoginMessage=n.message??null,e.whatsappLoginConnected=n.connected??null,n.connected&&(e.whatsappLoginQrDataUrl=null,e.whatsappActiveQrAccountId=null,e.whatsappPairedPhone=n.selfPhone??null)}catch(n){e.whatsappLoginMessage=String(n),e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Kl(e,t){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t}),e.whatsappLoginMessage="Logged out.",e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null}catch(n){e.whatsappLoginMessage=String(n)}finally{e.whatsappBusy=!1}}}async function zl(e,t){if(!e.client||!e.connected||e.whatsappAccountSaving)return;const n=t.trim();if(!n){e.whatsappAccountError="Account name is required.";return}const i=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");if(!i){e.whatsappAccountError="Invalid account name.";return}e.whatsappAccountSaving=!0,e.whatsappAccountError=null;try{const s=await e.client.request("config.get",{});e.configSnapshot=s;const o=tt(s.config??{});(!o.channels||typeof o.channels!="object")&&(o.channels={});const r=o.channels;(!r.whatsapp||typeof r.whatsapp!="object")&&(r.whatsapp={});const a=r.whatsapp;(!a.accounts||typeof a.accounts!="object")&&(a.accounts={});const u=a.accounts;if(u[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}u[i]={name:n,provider:"baileys"};const c=s.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const l=ft(o);await e.client.request("config.set",{raw:l,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await G(e,!0),await mo(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function Hl(e,t){if(!(!e.client||!e.connected)&&!e.whatsappAccountSaving){e.whatsappAccountSaving=!0,e.whatsappAccountError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=tt(n.config??{}),s=i.channels,o=s==null?void 0:s.whatsapp,r=o==null?void 0:o.accounts;if(!r){e.whatsappAccountError="No accounts found in config.";return}if(Object.keys(r).length<=1){e.whatsappAccountError="Cannot remove the last account.";return}if(!r[t]){e.whatsappAccountError=`Account "${t}" not found.`;return}try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t})}catch{}delete r[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(l=>{const p=l.match;return!p||p.channel!=="whatsapp"?!0:p.accountId!==t}));const u=n.hash;if(!u){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=ft(i);await e.client.request("config.set",{raw:c,baseHash:u}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await G(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const Fp=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:zl,loadChannels:G,logoutWhatsApp:Kl,removeWhatsAppAccount:Hl,startWhatsAppLogin:mo,waitWhatsAppLogin:Wl},Symbol.toStringTag,{value:"Module"}));async function yo(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,i,s]=await Promise.all([e.client.request("status",{}),e.client.request("health",{}),e.client.request("models.list",{}),e.client.request("last-heartbeat",{})]);e.debugStatus=t,e.debugHealth=n;const o=i;e.debugModels=Array.isArray(o==null?void 0:o.models)?o==null?void 0:o.models:[],e.debugHeartbeat=s}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}const Up=2e3,Wp=new Set(["trace","debug","info","warn","error","fatal"]);function Kp(e){if(typeof e!="string")return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return!n||typeof n!="object"?null:n}catch{return null}}function zp(e){if(typeof e!="string")return null;const t=e.toLowerCase();return Wp.has(t)?t:null}function ql(e){if(!e.trim())return{raw:e,message:e};try{const t=JSON.parse(e),n=t&&typeof t._meta=="object"&&t._meta!==null?t._meta:null,i=typeof t.time=="string"?t.time:typeof(n==null?void 0:n.date)=="string"?n==null?void 0:n.date:null,s=zp((n==null?void 0:n.logLevelName)??(n==null?void 0:n.level)),o=typeof t[0]=="string"?t[0]:typeof(n==null?void 0:n.name)=="string"?n==null?void 0:n.name:null,r=Kp(o);let a=null;r&&(typeof r.subsystem=="string"?a=r.subsystem:typeof r.module=="string"&&(a=r.module)),!a&&o&&o.length<120&&(a=o);let u=null;return typeof t[1]=="string"?u=t[1]:!r&&typeof t[0]=="string"?u=t[0]:typeof t.message=="string"&&(u=t.message),{raw:e,time:i,level:s,subsystem:a,message:u??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function Rt(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.logsLoading=!0),e.logsError=null;try{const i=await e.client.request("logs.tail",{cursor:t!=null&&t.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),o=(Array.isArray(i.lines)?i.lines.filter(a=>typeof a=="string"):[]).map(ql),r=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=r?o:[...e.logsEntries,...o].slice(-Up),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t!=null&&t.quiet||(e.logsLoading=!1)}}}const Hp=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:Rt,parseLogLine:ql},Symbol.toStringTag,{value:"Module"}));const jl={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:re,n:ii,Gx:Fr,Gy:Ur,a:as,d:ls,h:qp}=jl,gt=32,vo=64,jp=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},te=(e="")=>{const t=new Error(e);throw jp(t,te),t},Vp=e=>typeof e=="bigint",Gp=e=>typeof e=="string",Qp=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",nt=(e,t,n="")=>{const i=Qp(e),s=e==null?void 0:e.length,o=t!==void 0;if(!i||o&&s!==t){const r=n&&`"${n}" `,a=o?` of length ${t}`:"",u=i?`length=${s}`:`type=${typeof e}`;te(r+"expected Uint8Array"+a+", got "+u)}return e},Li=e=>new Uint8Array(e),Vl=e=>Uint8Array.from(e),Gl=(e,t)=>e.toString(16).padStart(t,"0"),Ql=e=>Array.from(nt(e)).map(t=>Gl(t,2)).join(""),Fe={_0:48,_9:57,A:65,F:70,a:97,f:102},Wr=e=>{if(e>=Fe._0&&e<=Fe._9)return e-Fe._0;if(e>=Fe.A&&e<=Fe.F)return e-(Fe.A-10);if(e>=Fe.a&&e<=Fe.f)return e-(Fe.a-10)},Yl=e=>{const t="hex invalid";if(!Gp(e))return te(t);const n=e.length,i=n/2;if(n%2)return te(t);const s=Li(i);for(let o=0,r=0;o<i;o++,r+=2){const a=Wr(e.charCodeAt(r)),u=Wr(e.charCodeAt(r+1));if(a===void 0||u===void 0)return te(t);s[o]=a*16+u}return s},Jl=()=>globalThis==null?void 0:globalThis.crypto,Yp=()=>{var e;return((e=Jl())==null?void 0:e.subtle)??te("crypto.subtle must be defined, consider polyfill")},$n=(...e)=>{const t=Li(e.reduce((i,s)=>i+nt(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Jp=(e=gt)=>Jl().getRandomValues(Li(e)),hi=BigInt,ct=(e,t,n,i="bad number: out of range")=>Vp(e)&&t<=e&&e<n?e:te(i),P=(e,t=re)=>{const n=e%t;return n>=0n?n:t+n},Xl=e=>P(e,ii),Xp=(e,t)=>{(e===0n||t<=0n)&&te("no inverse n="+e+" mod="+t);let n=P(e,t),i=t,s=0n,o=1n;for(;n!==0n;){const r=i/n,a=i%n,u=s-o*r;i=n,n=a,s=o,o=u}return i===1n?P(s,t):te("no inverse")},Zp=e=>{const t=nc[e];return typeof t!="function"&&te("hashes."+e+" not set"),t},cs=e=>e instanceof mt?e:te("Point expected"),Os=2n**256n,Pe=class Pe{constructor(t,n,i,s){U(this,"X");U(this,"Y");U(this,"Z");U(this,"T");const o=Os;this.X=ct(t,0n,o),this.Y=ct(n,0n,o),this.Z=ct(i,1n,o),this.T=ct(s,0n,o),Object.freeze(this)}static CURVE(){return jl}static fromAffine(t){return new Pe(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){const i=ls,s=Vl(nt(t,gt)),o=t[31];s[31]=o&-129;const r=ec(s);ct(r,0n,n?Os:re);const u=P(r*r),c=P(u-1n),l=P(i*u+1n);let{isValid:p,value:h}=th(c,l);p||te("bad point: y not sqrt");const b=(h&1n)===1n,f=(o&128)!==0;return!n&&h===0n&&f&&te("bad point: x==0, isLastByteOdd"),f!==b&&(h=P(-h)),new Pe(h,r,1n,P(h*r))}static fromHex(t,n){return Pe.fromBytes(Yl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=as,n=ls,i=this;if(i.is0())return te("bad point: ZERO");const{X:s,Y:o,Z:r,T:a}=i,u=P(s*s),c=P(o*o),l=P(r*r),p=P(l*l),h=P(u*t),b=P(l*P(h+c)),f=P(p+P(n*P(u*c)));if(b!==f)return te("bad point: equation left != right (1)");const v=P(s*o),k=P(r*a);return v!==k?te("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:r,Z:a}=cs(t),u=P(n*a),c=P(o*s),l=P(i*a),p=P(r*s);return u===c&&l===p}is0(){return this.equals(Lt)}negate(){return new Pe(P(-this.X),this.Y,this.Z,P(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=as,o=P(t*t),r=P(n*n),a=P(2n*P(i*i)),u=P(s*o),c=t+n,l=P(P(c*c)-o-r),p=u+r,h=p-a,b=u-r,f=P(l*h),v=P(p*b),k=P(l*b),$=P(h*p);return new Pe(f,v,$,k)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:r,Y:a,Z:u,T:c}=cs(t),l=as,p=ls,h=P(n*r),b=P(i*a),f=P(o*p*c),v=P(s*u),k=P((n+i)*(r+a)-h-b),$=P(v-f),A=P(v+f),C=P(b-l*h),T=P(k*$),_=P(A*C),R=P(k*C),O=P($*A);return new Pe(T,_,O,R)}subtract(t){return this.add(cs(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return Lt;if(ct(t,1n,ii),t===1n)return this;if(this.equals(yt))return ph(t).p;let i=Lt,s=yt;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?i=i.add(o):n&&(s=s.add(o));return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:i}=this;if(this.equals(Lt))return{x:0n,y:1n};const s=Xp(i,re);P(i*s)!==1n&&te("invalid inverse");const o=P(t*s),r=P(n*s);return{x:o,y:r}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=Zl(n);return i[31]|=t&1n?128:0,i}toHex(){return Ql(this.toBytes())}clearCofactor(){return this.multiply(hi(qp),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ii/2n,!1).double();return ii%2n&&(t=t.add(this)),t.is0()}};U(Pe,"BASE"),U(Pe,"ZERO");let mt=Pe;const yt=new mt(Fr,Ur,1n,P(Fr*Ur)),Lt=new mt(0n,1n,1n,0n);mt.BASE=yt;mt.ZERO=Lt;const Zl=e=>Yl(Gl(ct(e,0n,Os),vo)).reverse(),ec=e=>hi("0x"+Ql(Vl(nt(e)).reverse())),Ee=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=re;return n},eh=e=>{const n=e*e%re*e%re,i=Ee(n,2n)*n%re,s=Ee(i,1n)*e%re,o=Ee(s,5n)*s%re,r=Ee(o,10n)*o%re,a=Ee(r,20n)*r%re,u=Ee(a,40n)*a%re,c=Ee(u,80n)*u%re,l=Ee(c,80n)*u%re,p=Ee(l,10n)*o%re;return{pow_p_5_8:Ee(p,2n)*e%re,b2:n}},Kr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,th=(e,t)=>{const n=P(t*t*t),i=P(n*n*t),s=eh(e*i).pow_p_5_8;let o=P(e*n*s);const r=P(t*o*o),a=o,u=P(o*Kr),c=r===e,l=r===P(-e),p=r===P(-e*Kr);return c&&(o=a),(l||p)&&(o=u),(P(o)&1n)===1n&&(o=P(-o)),{isValid:c||l,value:o}},Fs=e=>Xl(ec(e)),bo=(...e)=>nc.sha512Async($n(...e)),nh=(...e)=>Zp("sha512")($n(...e)),tc=e=>{const t=e.slice(0,gt);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(gt,vo),i=Fs(t),s=yt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},wo=e=>bo(nt(e,gt)).then(tc),ih=e=>tc(nh(nt(e,gt))),sh=e=>wo(e).then(t=>t.pointBytes),oh=e=>bo(e.hashable).then(e.finish),rh=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=Fs(t),r=yt.multiply(o).toBytes();return{hashable:$n(r,i,n),finish:c=>{const l=Xl(o+Fs(c)*s);return nt($n(r,Zl(l)),vo)}}},ah=async(e,t)=>{const n=nt(e),i=await wo(t),s=await bo(i.prefix,n);return oh(rh(i,s,n))},nc={sha512Async:async e=>{const t=Yp(),n=$n(e);return Li(await t.digest("SHA-512",n.buffer))},sha512:void 0},lh=(e=Jp(gt))=>e,ch={getExtendedPublicKeyAsync:wo,getExtendedPublicKey:ih,randomSecretKey:lh},fi=8,uh=256,ic=Math.ceil(uh/fi)+1,Us=2**(fi-1),dh=()=>{const e=[];let t=yt,n=t;for(let i=0;i<ic;i++){n=t,e.push(n);for(let s=1;s<Us;s++)n=n.add(t),e.push(n);t=n.double()}return e};let zr;const Hr=(e,t)=>{const n=t.negate();return e?n:t},ph=e=>{const t=zr||(zr=dh());let n=Lt,i=yt;const s=2**fi,o=s,r=hi(s-1),a=hi(fi);for(let u=0;u<ic;u++){let c=Number(e&r);e>>=a,c>Us&&(c-=o,e+=1n);const l=u*Us,p=l,h=l+Math.abs(c)-1,b=u%2!==0,f=c<0;c===0?i=i.add(Hr(b,t[p])):n=n.add(Hr(f,t[h]))}return e!==0n&&te("invalid wnaf"),{p:n,f:i}},us="taskmaster-device-identity-v1";function Ws(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function sc(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4),i=atob(n),s=new Uint8Array(i.length);for(let o=0;o<i.length;o+=1)s[o]=i.charCodeAt(o);return s}function hh(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function oc(e){const t=await crypto.subtle.digest("SHA-256",e);return hh(new Uint8Array(t))}async function fh(){const e=ch.randomSecretKey(),t=await sh(e);return{deviceId:await oc(t),publicKey:Ws(t),privateKey:Ws(e)}}async function gh(){try{const n=localStorage.getItem(us);if(n){const i=JSON.parse(n);if((i==null?void 0:i.version)===1&&typeof i.deviceId=="string"&&typeof i.publicKey=="string"&&typeof i.privateKey=="string"){const s=await oc(sc(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(us,JSON.stringify(o)),{deviceId:s,publicKey:i.publicKey,privateKey:i.privateKey}}return{deviceId:i.deviceId,publicKey:i.publicKey,privateKey:i.privateKey}}}}catch{}const e=await fh(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(us,JSON.stringify(t)),e}async function mh(e,t){const n=sc(e),i=new TextEncoder().encode(t),s=await ah(i,n);return Ws(s)}const rc="taskmaster.device.auth.v1";function ko(e){return e.trim()}function yh(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const i=n.trim();i&&t.add(i)}return[...t].sort()}function So(){try{const e=window.localStorage.getItem(rc);if(!e)return null;const t=JSON.parse(e);return!t||t.version!==1||!t.deviceId||typeof t.deviceId!="string"||!t.tokens||typeof t.tokens!="object"?null:t}catch{return null}}function ac(e){try{window.localStorage.setItem(rc,JSON.stringify(e))}catch{}}function vh(e){const t=So();if(!t||t.deviceId!==e.deviceId)return null;const n=ko(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function bh(e){const t=ko(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=So();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:yh(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,ac(n),s}function wh(e){const t=So();if(!t||t.deviceId!==e.deviceId)return;const n=ko(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],ac(i)}async function $o(e,t){if(!(!e.client||!e.connected)&&!e.devicesLoading){e.devicesLoading=!0,t!=null&&t.quiet||(e.devicesError=null);try{const n=await e.client.request("device.pair.list",{});e.devicesList={pending:Array.isArray(n==null?void 0:n.pending)?n.pending:[],paired:Array.isArray(n==null?void 0:n.paired)?n.paired:[]}}catch(n){t!=null&&t.quiet||(e.devicesError=String(n))}finally{e.devicesLoading=!1}}}async function Ao(e,t){if(!(!e.client||!e.connected)&&!e.nodesLoading){e.nodesLoading=!0,t!=null&&t.quiet||(e.lastError=null);try{const n=await e.client.request("node.list",{});e.nodes=Array.isArray(n.nodes)?n.nodes:[]}catch(n){t!=null&&t.quiet||(e.lastError=String(n))}finally{e.nodesLoading=!1}}}function kh(e){return{method:"exec.approvals.get",params:{}}}async function Sh(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=kh(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);$h(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function $h(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=tt(t.file??{}))}async function lc(e){if(!(!e.client||!e.connected)&&!e.presenceLoading){e.presenceLoading=!0,e.presenceError=null,e.presenceStatus=null;try{const t=await e.client.request("system-presence",{});Array.isArray(t)?(e.presenceEntries=t,e.presenceStatus=t.length===0?"No instances yet.":null):(e.presenceEntries=[],e.presenceStatus="No presence payload.")}catch(t){e.presenceError=String(t)}finally{e.presenceLoading=!1}}}function Nt(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function qe(e){return e instanceof Error?e.message:String(e)}function Ii(){return{name:"",skillContent:"",references:[]}}async function He(e,t){if(t!=null&&t.clearMessages&&Object.keys(e.skillMessages).length>0&&(e.skillMessages={}),!(!e.client||!e.connected)&&!e.skillsLoading){e.skillsLoading=!0,e.skillsError=null;try{const n=await e.client.request("skills.status",{});n&&(e.skillsReport=n)}catch(n){e.skillsError=qe(n)}finally{e.skillsLoading=!1}}}function cc(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function uc(e,t,n){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.update",{skillKey:t,enabled:n}),await He(e),Nt(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=qe(i);e.skillsError=s,Nt(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function dc(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const n=e.skillEdits[t]??"";await e.client.request("skills.update",{skillKey:t,apiKey:n}),await He(e),Nt(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=qe(n);e.skillsError=i,Nt(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function pc(e,t,n,i){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const s=await e.client.request("skills.install",{name:n,installId:i,timeoutMs:12e4});await He(e),Nt(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=qe(s);e.skillsError=o,Nt(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function hc(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("skills.read",{name:t});n&&(e.skillDetail=n,e.skillDetailTab="SKILL.md")}catch(n){e.skillsError=qe(n)}}function fc(e){e.skillDetail=null,e.skillDetailTab=""}function gc(e,t){e.skillDetailTab=t}async function mc(e){if(e.skillAddModal=!0,e.skillAddForm=Ii(),e.skillDrafts=[],!(!e.client||!e.connected))try{const t=await e.client.request("skills.drafts",{});t&&(e.skillDrafts=t.drafts)}catch{}}function yc(e){e.skillAddModal=!1,e.skillAddForm=Ii(),e.skillDrafts=[]}function vc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n}))}}async function bc(e){if(!e.client||!e.connected)return;const t=e.skillAddForm;if(!(!t.name.trim()||!t.skillContent.trim())){e.skillsBusyKey="__add__",e.skillsError=null;try{const n=t.references.filter(i=>i.name.trim()&&i.content.trim()).map(i=>({name:i.name.trim(),content:i.content}));await e.client.request("skills.create",{name:t.name.trim(),skillContent:t.skillContent,references:n.length>0?n:void 0}),e.skillAddModal=!1,e.skillAddForm=Ii(),e.skillDrafts=[],await He(e)}catch(n){e.skillsError=qe(n)}finally{e.skillsBusyKey=null}}}async function wc(e,t){if(!(!e.client||!e.connected))try{await e.client.request("skills.deleteDraft",{name:t}),e.skillDrafts=e.skillDrafts.filter(n=>n.name!==t)}catch(n){e.skillsError=qe(n)}}async function kc(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("skills.read",{name:t});if(!n)return;e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i}))},e.skillAddModal=!0,e.skillDrafts=[]}catch(n){e.skillsError=qe(n)}}async function Sc(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await He(e)}catch(n){e.skillsError=qe(n)}finally{e.skillsBusyKey=null}}}const Ah=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:yc,closeSkillDetail:fc,deleteDraft:wc,deleteSkill:Sc,editSkill:kc,emptyAddForm:Ii,importDraft:vc,installSkill:pc,loadSkills:He,openAddSkillModal:mc,saveNewSkill:bc,saveSkillApiKey:dc,setSkillDetailTab:gc,updateSkillEdit:cc,updateSkillEnabled:uc,viewSkillDetail:hc},Symbol.toStringTag,{value:"Module"})),$c={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},Ac=new Map(Object.entries($c).map(([e,t])=>[t,e]));function Ri(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function An(e){if(!e)return"/";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function xh(e,t=""){const n=Ri(t),i=$c[e];return n?`${n}${i}`:i}function xc(e,t=""){const n=Ri(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=An(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":Ac.get(s)??null}function Eh(e){let t=An(e);if(t.endsWith("/index.html")&&(t=An(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let i=0;i<n.length;i++){const s=`/${n.slice(i).join("/")}`.toLowerCase();if(Ac.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function Ch(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function xo(e){return e==="system"?Ch():e}const Hn=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,Th=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,qn=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},_h=({nextTheme:e,applyTheme:t,context:n,currentTheme:i})=>{var c;if(i===e)return;const s=globalThis.document??null;if(!s){t();return}const o=s.documentElement,r=s,a=Th();if(!!r.startViewTransition&&!a){let l=.5,p=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")l=Hn(n.pointerClientX/window.innerWidth),p=Hn(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const h=n.element.getBoundingClientRect();h.width>0&&h.height>0&&typeof window<"u"&&(l=Hn((h.left+h.width/2)/window.innerWidth),p=Hn((h.top+h.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${l*100}%`),o.style.setProperty("--theme-switch-y",`${p*100}%`),o.classList.add("theme-transition");try{const h=(c=r.startViewTransition)==null?void 0:c.call(r,()=>{t()});h!=null&&h.finished?h.finished.finally(()=>qn(o)):qn(o)}catch{qn(o),t()}return}t(),qn(o)},Mh=2e3;async function mn(e,t){if(!(!e.client||!e.connected)&&!(e.sessionLogsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.sessionLogsLoading=!0),e.sessionLogsError=null;try{const n={cursors:t!=null&&t.reset?void 0:e.sessionLogsCursors,limit:500};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(n.agents=e.workspaceAgentIds);const s=await e.client.request("sessions.transcript",n),o=Array.isArray(s.entries)?s.entries:[],r=!!(t!=null&&t.reset||Object.keys(e.sessionLogsCursors).length===0);e.sessionLogsEntries=r?o:[...e.sessionLogsEntries,...o].slice(-Mh),s.cursors&&(e.sessionLogsCursors=s.cursors),Array.isArray(s.agents)&&(e.sessionLogsAgents=s.agents),e.sessionLogsLastFetchAt=Date.now()}catch(n){e.sessionLogsError=String(n)}finally{t!=null&&t.quiet||(e.sessionLogsLoading=!1)}}}const Ec=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:mn},Symbol.toStringTag,{value:"Module"}));async function Cc(e,t){if(!(!e.client||!e.connected))try{const n={},i=await e.client.request("memory.audit",n);i!=null&&i.ok&&(e.auditEntries=i.entries??[])}catch{}}async function Ph(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function De(e){return e instanceof Error?e.message:String(e)}let jn=null;function zt(e,t){jn&&clearTimeout(jn),e.filesMessage={kind:"success",text:t},jn=setTimeout(()=>{e.filesMessage=null,jn=null},3e3)}async function Ht(e,t){if(!(!e.client||!e.connected)){if(!t){e.filesTree=[],e.filesRoot="";return}if(!e.filesLoading){e.filesLoading=!0,e.filesError=null;try{const n={};t&&(n.agentId=t);const i=await e.client.request("files.tree",n);i!=null&&i.tree&&(e.filesTree=i.tree,e.filesRoot=i.root??"")}catch(n){e.filesError=De(n)}finally{e.filesLoading=!1}}}}async function Lh(e,t,n){e.filesSelectedPaths=new Set([t]),await Tc(e,t,n)}async function Ih(e,t,n){const i=new Set(e.filesSelectedPaths);if(i.has(t)?i.delete(t):i.add(t),e.filesSelectedPaths=i,i.size===1){const s=[...i][0];await Tc(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function Rh(e,t){if(!e.client||!e.connected)return;const n=[...e.filesSelectedPaths];if(n.length===0)return;let i=0,s="";for(const o of n)try{await _c(e,o,t),i++}catch(r){s=De(r)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:zt(e,`${i} file${i!==1?"s":""} downloaded`)}async function Dh(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await Fh(e,t,o,i)}async function Tc(e,t,n){if(!(!e.client||!e.connected)){e.filesSelectedPath=t,e.filesPreviewLoading=!0,e.filesPreviewContent=null,e.filesPreviewBinary=!1,e.filesPreviewSize=null;try{const i={path:t};n&&(i.agentId=n);const s=await e.client.request("files.read",i);e.filesPreviewContent=(s==null?void 0:s.content)??null,e.filesPreviewBinary=(s==null?void 0:s.binary)??!1,e.filesPreviewSize=(s==null?void 0:s.size)??null}catch(i){e.filesError=De(i)}finally{e.filesPreviewLoading=!1}}}async function _c(e,t,n){if(!(!e.client||!e.connected))try{const i={path:t};n&&(i.agentId=n);const s=await e.client.request("files.download",i);if(!(s!=null&&s.base64)){e.filesMessage={kind:"error",text:"Download failed: no data"};return}const o=Uint8Array.from(atob(s.base64),c=>c.charCodeAt(0)),r=new Blob([o]),a=URL.createObjectURL(r),u=document.createElement("a");u.href=a,u.download=s.name??t.split("/").pop()??"download",document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(a)}catch(i){e.filesMessage={kind:"error",text:De(i)}}}async function Bh(e,t,n,i){if(!e.client||!e.connected)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="";for(const r of n)try{const a=await r.arrayBuffer(),u=btoa(new Uint8Array(a).reduce((l,p)=>l+String.fromCharCode(p),"")),c={path:t,name:r.name,data:u};i&&(c.agentId=i),await e.client.request("files.upload",c),s++}catch(a){o=De(a)}e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:zt(e,`${s} file${s!==1?"s":""} uploaded`),await Ht(e,i)}async function Nh(e,t,n,i){if(!e.client||!e.connected)return;e.filesMessage=null;const s=t==="."?n:`${t}/${n}`;try{const o={path:s};i&&(o.agentId=i),await e.client.request("files.mkdir",o),zt(e,`Created ${s}`),await Ht(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:De(o)}}}async function Oh(e,t,n){if(!(!e.client||!e.connected)){e.filesMessage=null;try{const i={path:t};n&&(i.agentId=n),await e.client.request("files.delete",i),zt(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await Ht(e,n)}catch(i){e.filesMessage={kind:"error",text:De(i)}}}}async function Fh(e,t,n,i){if(!(!e.client||!e.connected)){e.filesMessage=null;try{const s={from:t,to:n};i&&(s.agentId=i),await e.client.request("files.move",s),zt(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await Ht(e,i)}catch(s){e.filesMessage={kind:"error",text:De(s)}}}}async function Eo(e,t){if(!(!e.client||!e.connected))try{const n={};t&&(n.agentId=t);const i=await e.client.request("memory.status",n);i!=null&&i.ok&&(e.filesMemoryStatus={dirty:i.dirty??!1,syncing:i.syncing,syncProgress:i.syncProgress,files:i.files??0,chunks:i.chunks??0,model:i.model,embeddingState:i.embeddingState})}catch{}}async function Uh(e,t){if(!(!e.client||!e.connected)&&!e.filesReindexBusy){e.filesReindexBusy=!0,e.filesMessage=null;try{const n={force:!0};t&&(n.agentId=t);const i=await e.client.request("memory.reindex",n),s=(i==null?void 0:i.files)??0,o=(i==null?void 0:i.chunks)??0;zt(e,`Re-indexed: ${s} files, ${o} chunks`),await Eo(e,t)}catch(n){e.filesMessage={kind:"error",text:De(n)}}finally{e.filesReindexBusy=!1}}}function Wh(e,t){const n=new Set(e.filesExpandedDirs);n.has(t)?n.delete(t):n.add(t),e.filesExpandedDirs=n,e.filesCurrentDir=t}async function Kh(e,t,n){if(!(!e.client||!e.connected)){if(!t.trim()){e.filesSearchResults=null;return}e.filesSearchLoading=!0,e.filesSearchResults=null;try{const i={query:t.trim(),maxResults:20};n&&(i.agentId=n);const s=await e.client.request("memory.search",i);e.filesSearchResults=(s==null?void 0:s.results)??[]}catch(i){e.filesMessage={kind:"error",text:De(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function zh(e){e.filesSearchQuery="",e.filesSearchResults=null}function Hh(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{Ao(e,{quiet:!0})},5e3))}function qh(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Co(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Rt(e,{quiet:!0})},2e3))}function To(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function _o(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||mn(e,{quiet:!0})},2e3))}function Mo(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function Po(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&yo(e)},3e3))}function Lo(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function jh(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{Cc(e)},3e4))}function Vh(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function Gh(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{if(e.tab!=="files")return;const t=e;Eo(t,t.filesResolvedAgentId)},3e3))}function Qh(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function Ze(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,Vd(n),t.theme!==e.theme&&(e.theme=t.theme,Di(e,xo(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Mc(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&Ze(e,{...e.settings,lastActiveSessionKey:n})}function Yh(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),i=t.get("password"),s=t.get("session"),o=t.get("gatewayUrl");let r=!1;if(n!=null){const u=n.trim();u&&u!==e.settings.token&&Ze(e,{...e.settings,token:u}),t.delete("token"),r=!0}if(i!=null){const u=i.trim();u&&(e.password=u),t.delete("password"),r=!0}if(s!=null){const u=s.trim();u&&(e.sessionKey=u,Ze(e,{...e.settings,sessionKey:u,lastActiveSessionKey:u}))}if(o!=null){const u=o.trim();u&&u!==e.settings.gatewayUrl&&Ze(e,{...e.settings,gatewayUrl:u}),t.delete("gatewayUrl"),r=!0}if(!r)return;const a=new URL(window.location.href);a.search=t.toString(),window.history.replaceState({},"",a.toString())}function Jh(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?_o(e):Co(e):(To(e),Mo(e)),t==="debug"?Po(e):Lo(e),gi(e),Lc(e,t,!1)}function Xh(e,t,n){_h({nextTheme:t,applyTheme:()=>{e.theme=t,Ze(e,{...e.settings,theme:t}),Di(e,xo(t))},context:n,currentTheme:e.theme})}async function gi(e){if(e.tab==="overview"&&await Ic(e),e.tab==="channels"&&await rf(e),e.tab==="instances"&&await lc(e),e.tab==="cron"&&await Io(e),e.tab==="skills"&&await He(e),e.tab==="nodes"&&(await Ao(e),await $o(e),await Re(e),await Sh(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await df(e),Wt(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await Ol(e),await Re(e)),e.tab==="debug"&&(await yo(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await ie(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>Ec);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await Rt(e,{reset:!0});Bl(e,!0)}}function Zh(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?Ri(e):Eh(window.location.pathname)}function ef(e){e.theme=e.settings.theme??"system",Di(e,xo(e.theme))}function Di(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function tf(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;if(e.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),e.themeMediaHandler=n=>{e.theme==="system"&&Di(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function nf(e){if(!e.themeMedia||!e.themeMediaHandler)return;if(typeof e.themeMedia.removeEventListener=="function"){e.themeMedia.removeEventListener("change",e.themeMediaHandler);return}e.themeMedia.removeListener(e.themeMediaHandler),e.themeMedia=null,e.themeMediaHandler=null}function sf(e,t){if(typeof window>"u")return;const n=xc(window.location.pathname,e.basePath)??"chat";Pc(e,n),Lc(e,n,t)}function of(e){var s;if(typeof window>"u")return;const t=xc(window.location.pathname,e.basePath);if(!t)return;const i=(s=new URL(window.location.href).searchParams.get("session"))==null?void 0:s.trim();i&&(e.sessionKey=i,Ze(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),Pc(e,t)}function Pc(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?_o(e):Co(e):(To(e),Mo(e)),t==="debug"?Po(e):Lo(e),e.connected&&gi(e)}function Lc(e,t,n){if(typeof window>"u")return;const i=An(xh(t,e.basePath)),s=An(window.location.pathname),o=new URL(window.location.href);t==="chat"&&e.sessionKey?o.searchParams.set("session",e.sessionKey):o.searchParams.delete("session"),s!==i&&(o.pathname=i),n?window.history.replaceState({},"",o.toString()):window.history.pushState({},"",o.toString())}async function Ic(e){await Promise.all([G(e,!1),lc(e),fo(e),Kt(e),yo(e)])}async function rf(e){await Promise.all([G(e,!0),Ol(e),Re(e)])}async function Io(e){await Promise.all([G(e,!1),Kt(e),xn(e)])}function Rc(e){return e.chatSending||!!e.chatRunId}function af(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/stop"?!0:n==="stop"||n==="esc"||n==="abort"||n==="wait"||n==="exit"}async function Dc(e){e.connected&&(e.chatMessage="",await Rl(e))}function lf(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:ho(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],Wt(e))}async function Bc(e,t,n){var s,o;go(e);const i=await Il(e,t,n==null?void 0:n.attachments);return!i&&(n==null?void 0:n.previousDraft)!=null&&(e.chatMessage=n.previousDraft),!i&&(n!=null&&n.previousAttachments)&&(e.chatAttachments=n.previousAttachments),i&&Mc(e,e.sessionKey),i&&(n!=null&&n.restoreDraft)&&((s=n.previousDraft)!=null&&s.trim())&&(e.chatMessage=n.previousDraft),i&&(n!=null&&n.restoreAttachments)&&((o=n.previousAttachments)!=null&&o.length)&&(e.chatAttachments=n.previousAttachments),Wt(e),i&&!e.chatRunId&&Nc(e),i}async function Nc(e){if(!e.connected||Rc(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await Bc(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function cf(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function uf(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),o=e.chatAttachments??[],r=t==null?o:[],a=r.length>0;if(!(!s&&!a)){if(af(s)){await Dc(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[]),Rc(e)){lf(e,s,r);return}await Bc(e,s,{previousDraft:t==null?i:void 0,restoreDraft:!!(t&&(n!=null&&n.restoreDraft)),attachments:a?r:void 0,previousAttachments:t==null?o:void 0,restoreAttachments:!!(t&&(n!=null&&n.restoreDraft))})}}async function df(e){var i;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,Ie);await Promise.all([Le(t,{limit:n}),fo(t),Ks(e)]),Wt(e,!0)}const pf=Nc;function hf(e){var s,o,r;const t=Al(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(s=e.hello)==null?void 0:s.snapshot;return((r=(o=n==null?void 0:n.sessionDefaults)==null?void 0:o.defaultAgentId)==null?void 0:r.trim())||"main"}function ff(e,t){const n=Ri(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Ks(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=hf(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=ff(e.basePath,t);try{const i=await fetch(n,{method:"GET"});if(!i.ok){e.chatAvatarUrl=null;return}const s=await i.json(),o=typeof s.avatarUrl=="string"?s.avatarUrl.trim():"";e.chatAvatarUrl=o||null}catch{e.chatAvatarUrl=null}}const D={messageSquare:d`<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`,barChart:d`<svg viewBox="0 0 24 24"><line x1="12" x2="12" y1="20" y2="10"/><line x1="18" x2="18" y1="20" y2="4"/><line x1="6" x2="6" y1="20" y2="16"/></svg>`,link:d`<svg viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,unlink:d`<svg viewBox="0 0 24 24"><path d="m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71"/><path d="m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71"/><line x1="8" x2="8" y1="2" y2="5"/><line x1="2" x2="5" y1="8" y2="8"/><line x1="16" x2="16" y1="19" y2="22"/><line x1="19" x2="22" y1="16" y2="16"/></svg>`,radio:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="2"/><path d="M16.24 7.76a6 6 0 0 1 0 8.49m-8.48-.01a6 6 0 0 1 0-8.49m11.31-2.82a10 10 0 0 1 0 14.14m-14.14 0a10 10 0 0 1 0-14.14"/></svg>`,fileText:d`<svg viewBox="0 0 24 24"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" x2="8" y1="13" y2="13"/><line x1="16" x2="8" y1="17" y2="17"/><line x1="10" x2="8" y1="9" y2="9"/></svg>`,zap:d`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:d`<svg viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg>`,settings:d`<svg viewBox="0 0 24 24"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>`,bug:d`<svg viewBox="0 0 24 24"><path d="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/></svg>`,scrollText:d`<svg viewBox="0 0 24 24"><path d="M8 21h12a2 2 0 0 0 2-2v-2H10v2a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v3h4"/><path d="M19 17V5a2 2 0 0 0-2-2H4"/><path d="M15 8h-5"/><path d="M15 12h-5"/></svg>`,folder:d`<svg viewBox="0 0 24 24"><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"/></svg>`,users:d`<svg viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>`,menu:d`<svg viewBox="0 0 24 24"><line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/></svg>`,x:d`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:d`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:d`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>`,search:d`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:d`<svg viewBox="0 0 24 24"><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"/><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"/><path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/><path d="M17.599 6.5a3 3 0 0 0 .399-1.375"/><path d="M6.003 5.125A3 3 0 0 0 6.401 6.5"/><path d="M3.477 10.896a4 4 0 0 1 .585-.396"/><path d="M19.938 10.5a4 4 0 0 1 .585.396"/><path d="M6 18a4 4 0 0 1-1.967-.516"/><path d="M19.967 17.484A4 4 0 0 1 18 18"/></svg>`,book:d`<svg viewBox="0 0 24 24"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/></svg>`,loader:d`<svg viewBox="0 0 24 24"><path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/></svg>`,rotateCw:d`<svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg>`,download:d`<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>`,wrench:d`<svg viewBox="0 0 24 24"><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"/></svg>`,fileCode:d`<svg viewBox="0 0 24 24"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><path d="m10 13-2 2 2 2"/><path d="m14 17 2-2-2-2"/></svg>`,edit:d`<svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,penLine:d`<svg viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>`,paperclip:d`<svg viewBox="0 0 24 24"><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"/></svg>`,globe:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>`,image:d`<svg viewBox="0 0 24 24"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>`,smartphone:d`<svg viewBox="0 0 24 24"><rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/></svg>`,plug:d`<svg viewBox="0 0 24 24"><path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/></svg>`,circle:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>`,puzzle:d`<svg viewBox="0 0 24 24"><path d="M19.439 7.85c-.049.322.059.648.289.878l1.568 1.568c.47.47.706 1.087.706 1.704s-.235 1.233-.706 1.704l-1.611 1.611a.98.98 0 0 1-.837.276c-.47-.07-.802-.48-.968-.925a2.501 2.501 0 1 0-3.214 3.214c.446.166.855.497.925.968a.979.979 0 0 1-.276.837l-1.61 1.61a2.404 2.404 0 0 1-1.705.707 2.402 2.402 0 0 1-1.704-.706l-1.568-1.568a1.026 1.026 0 0 0-.877-.29c-.493.074-.84.504-1.02.968a2.5 2.5 0 1 1-3.237-3.237c.464-.18.894-.527.967-1.02a1.026 1.026 0 0 0-.289-.877l-1.568-1.568A2.402 2.402 0 0 1 1.998 12c0-.617.236-1.234.706-1.704L4.23 8.77c.24-.24.581-.353.917-.303.515.076.874.54 1.02 1.02a2.5 2.5 0 1 0 3.237-3.237c-.48-.146-.944-.505-1.02-1.02a.98.98 0 0 1 .303-.917l1.526-1.526A2.402 2.402 0 0 1 11.998 2c.617 0 1.234.236 1.704.706l1.568 1.568c.23.23.556.338.877.29.493-.074.84-.504 1.02-.968a2.5 2.5 0 1 1 3.236 3.236c-.464.18-.894.527-.967 1.02Z"/></svg>`,info:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>`,send:d`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:d`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>`,slidersHorizontal:d`<svg viewBox="0 0 24 24"><line x1="21" x2="14" y1="4" y2="4"/><line x1="10" x2="3" y1="4" y2="4"/><line x1="21" x2="12" y1="12" y2="12"/><line x1="8" x2="3" y1="12" y2="12"/><line x1="21" x2="16" y1="20" y2="20"/><line x1="12" x2="3" y1="20" y2="20"/><line x1="14" x2="14" y1="2" y2="6"/><line x1="8" x2="8" y1="10" y2="14"/><line x1="16" x2="16" y1="18" y2="22"/></svg>`,square:d`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:d`<svg viewBox="0 0 24 24"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>`,eyeOff:d`<svg viewBox="0 0 24 24"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/></svg>`,trash:d`<svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>`,chevronDown:d`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,film:d`<svg viewBox="0 0 24 24"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M7 3v18"/><path d="M3 7.5h4"/><path d="M3 12h18"/><path d="M3 16.5h4"/><path d="M17 3v18"/><path d="M17 7.5h4"/><path d="M17 16.5h4"/></svg>`,wifi:d`<svg viewBox="0 0 24 24"><path d="M12 20h.01"/><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.859a10 10 0 0 1 14 0"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/></svg>`,wifiOff:d`<svg viewBox="0 0 24 24"><path d="M12 20h.01"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/><path d="M5 12.859a10 10 0 0 1 5.17-2.69"/><path d="M13.41 10.28a10 10 0 0 1 5.59 2.58"/><path d="M2 8.82a15 15 0 0 1 4.17-2.65"/><path d="M10.66 5c4.01-.36 8.14.9 11.34 3.76"/><line x1="2" x2="22" y1="2" y2="22"/></svg>`},gf=d`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>`,mf=d`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>`;let qr=!1;function yf(){qr||(qr=!0,document.addEventListener("click",e=>{const t=document.getElementById("nav-burger-toggle");if(!(t!=null&&t.checked))return;const n=t.closest(".setup-header");n!=null&&n.contains(e.target)||(t.checked=!1)}))}function kt(e,t){var l;const n=(p,h)=>p===e?d`<span class="sp-page-nav-current">${p}</span>`:d`<a href=${h}>${p}</a>`,i=d`
23
23
  ${n("Setup","/setup")}
24
24
  ${n("Chat","/chat")}
25
25
  ${n("Admins","/admins")}
@@ -296,7 +296,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
296
296
  Clear
297
297
  </button>`:S}
298
298
  </div>
299
- `}function xf(e){return e.searchResults?e.searchResults.length===0?d`<div class="sp-search-results">
299
+ `}function Af(e){return e.searchResults?e.searchResults.length===0?d`<div class="sp-search-results">
300
300
  <div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No results found.</div>
301
301
  </div>`:d`
302
302
  <div class="sp-search-results">
@@ -316,7 +316,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
316
316
  </div>
317
317
  `)}
318
318
  </div>
319
- `:S}function Af(e){const t=e.currentDir;return e.connected?d`
319
+ `:S}function xf(e){const t=e.currentDir;return e.connected?d`
320
320
  <div class="setup-container">
321
321
  ${kt("Files",e.wsProps)}
322
322
  <div class="setup-card sp-card-wide">
@@ -382,7 +382,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
382
382
 
383
383
  ${$f(e)}
384
384
 
385
- ${e.searchResults!==null?xf(e):d`<div
385
+ ${e.searchResults!==null?Af(e):d`<div
386
386
  class="sp-file-tree"
387
387
  @dragover=${n=>{n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(mi)?"move":"copy")}}
388
388
  @drop=${n=>{var o,r;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(mi);if(i){Fc(i)!=="."&&e.onMoveToDir(i,".");return}const s=(r=n.dataTransfer)==null?void 0:r.files;if(s&&s.length>0){const a=Array.from(s).filter(u=>u.name.toLowerCase().endsWith(".md"));a.length>0&&e.onUpload(t,a)}}}
@@ -1046,13 +1046,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
1046
1046
  </div>
1047
1047
  </div>
1048
1048
  ${Df(e)}
1049
- `}function Df(e){if(!e.apiKeyModalOpen)return S;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,l)=>{const p=l==null?void 0:l.closest(".setup-apikey-input"),f=p==null?void 0:p.querySelector("input"),b=f==null?void 0:f.value.trim();!b||b===n[c]||e.onApiKeySave(c,b)},s=c=>{const l=c.currentTarget,p=l.closest(".setup-apikey-input"),f=p==null?void 0:p.querySelector("input");if(!f)return;const b=f.type==="text";f.type=b?"password":"text",l.classList.toggle("active",!b)},o=(c,l)=>{const p=l.target,f=p.closest(".setup-apikey-input"),b=p.value.trim(),h=b.length>0&&b!==n[c],v=f==null?void 0:f.querySelector(".setup-apikey-save");v&&(v.style.display=h?"":"none");const k=f==null?void 0:f.querySelector(".setup-apikey-eye");k&&(k.style.display=b.length>0?"":"none")},r=t.filter(c=>c.primary),a=t.filter(c=>!c.primary),u=c=>{const l=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,p=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,f=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`;return d`
1049
+ `}function Df(e){if(!e.apiKeyModalOpen)return S;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,l)=>{const p=l==null?void 0:l.closest(".setup-apikey-input"),h=p==null?void 0:p.querySelector("input"),b=h==null?void 0:h.value.trim();!b||b===n[c]||e.onApiKeySave(c,b)},s=c=>{const l=c.currentTarget,p=l.closest(".setup-apikey-input"),h=p==null?void 0:p.querySelector("input");if(!h)return;const b=h.type==="text";h.type=b?"password":"text",l.classList.toggle("active",!b)},o=(c,l)=>{const p=l.target,h=p.closest(".setup-apikey-input"),b=p.value.trim(),f=b.length>0&&b!==n[c],v=h==null?void 0:h.querySelector(".setup-apikey-save");v&&(v.style.display=f?"":"none");const k=h==null?void 0:h.querySelector(".setup-apikey-eye");k&&(k.style.display=b.length>0?"":"none")},r=t.filter(c=>c.primary),a=t.filter(c=>!c.primary),u=c=>{const l=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,p=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,h=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`;return d`
1050
1050
  <div class="setup-apikey-row">
1051
1051
  <div class="setup-apikey-info">
1052
1052
  <strong>${c.name}</strong>
1053
1053
  <span class="setup-apikey-category">${c.category}</span>
1054
1054
  ${p?d`<span class="setup-apikey-badge saved">Saved</span>`:S}
1055
- ${f?d`<span class="setup-apikey-badge removed">Removed</span>`:S}
1055
+ ${h?d`<span class="setup-apikey-badge removed">Removed</span>`:S}
1056
1056
  </div>
1057
1057
  <div class="setup-apikey-input">
1058
1058
  <input
@@ -1488,13 +1488,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
1488
1488
 
1489
1489
  ${s&&!i.find(c=>c.ssid===s&&c.active)?d`
1490
1490
  <div style="display: flex; gap: 8px; align-items: center;">
1491
- ${(()=>{const c=i.find(f=>f.ssid===s),l=(c==null?void 0:c.security)!=="Open",p=t.savedSsid===s;return l&&!p?d`
1491
+ ${(()=>{const c=i.find(h=>h.ssid===s),l=(c==null?void 0:c.security)!=="Open",p=t.savedSsid===s;return l&&!p?d`
1492
1492
  <input
1493
1493
  type="password"
1494
1494
  placeholder="Password"
1495
1495
  .value=${e.wifiPassword}
1496
- @input=${f=>e.onWifiPasswordChange(f.target.value)}
1497
- @keydown=${f=>{f.key==="Enter"&&e.onWifiConnect()}}
1496
+ @input=${h=>e.onWifiPasswordChange(h.target.value)}
1497
+ @keydown=${h=>{h.key==="Enter"&&e.onWifiConnect()}}
1498
1498
  ?disabled=${n}
1499
1499
  style="
1500
1500
  flex: 1;
@@ -1577,7 +1577,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
1577
1577
  @click=${()=>e.onAccountPinModalOpen()}
1578
1578
  >${t?"Change":"Set PIN"}</button>
1579
1579
  </div>
1580
- `}function ca(e){if(!e.accountPinModalOpen)return S;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const r=c=>l=>{const p=l.target;p.value=p.value.replace(/\D/g,"").slice(0,6),c(p.value)},a=(c,l)=>{var f;let p=c.querySelector(".pin-modal-validation");p||(p=document.createElement("p"),p.className="login-error pin-modal-validation",(f=c.querySelector("button[type=submit]"))==null||f.before(p)),p.textContent=l},u=c=>{c.preventDefault();const l=c.target;if(!n){if(t&&!i){a(l,"Enter your current PIN");return}if(!s){a(l,"Enter a new PIN");return}if(!o){a(l,"Confirm your new PIN");return}if(s!==o){a(l,"PINs do not match");return}if(s.length<4){a(l,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return d`
1580
+ `}function ca(e){if(!e.accountPinModalOpen)return S;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const r=c=>l=>{const p=l.target;p.value=p.value.replace(/\D/g,"").slice(0,6),c(p.value)},a=(c,l)=>{var h;let p=c.querySelector(".pin-modal-validation");p||(p=document.createElement("p"),p.className="login-error pin-modal-validation",(h=c.querySelector("button[type=submit]"))==null||h.before(p)),p.textContent=l},u=c=>{c.preventDefault();const l=c.target;if(!n){if(t&&!i){a(l,"Enter your current PIN");return}if(!s){a(l,"Enter a new PIN");return}if(!o){a(l,"Confirm your new PIN");return}if(s!==o){a(l,"PINs do not match");return}if(s.length<4){a(l,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return d`
1581
1581
  <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onAccountPinModalClose()}}>
1582
1582
  <div class="setup-info-card" style="max-width: 340px;">
1583
1583
  <div class="setup-info-header">
@@ -2257,8 +2257,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
2257
2257
 
2258
2258
  ${i?Hf(i,e):S}
2259
2259
  ${s?qf(s,e):S}
2260
- `}const zc={CHILD:2},Hc=e=>(...t)=>({_$litDirective$:e,values:t});let qc=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,n,i){this._$Ct=t,this._$AM=n,this._$Ci=i}_$AS(t,n){return this.update(t,n)}update(t,n){return this.render(...n)}};const{I:Qf}=Ld,fa=e=>e,ga=()=>document.createComment(""),Zt=(e,t,n)=>{var o;const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const r=i.insertBefore(ga(),s),a=i.insertBefore(ga(),s);n=new Qf(r,a,e,e.options)}else{const r=n._$AB.nextSibling,a=n._$AM,u=a!==e;if(u){let c;(o=n._$AQ)==null||o.call(n,e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==a._$AU&&n._$AP(c)}if(r!==s||u){let c=n._$AA;for(;c!==r;){const l=fa(c).nextSibling;fa(i).insertBefore(c,s),c=l}}}return n},lt=(e,t,n=e)=>(e._$AI(t,n),e),Yf={},Jf=(e,t=Yf)=>e._$AH=t,Xf=e=>e._$AH,ds=e=>{e._$AR(),e._$AA.remove()};const ma=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},Zf=Hc(class extends qc{constructor(e){if(super(e),e.type!==zc.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,n){let i;n===void 0?n=t:t!==void 0&&(i=t);const s=[],o=[];let r=0;for(const a of e)s[r]=i?i(a,r):r,o[r]=n(a,r),r++;return{values:o,keys:s}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,i]){const s=Xf(e),{values:o,keys:r}=this.dt(t,n,i);if(!Array.isArray(s))return this.ut=r,o;const a=this.ut??(this.ut=[]),u=[];let c,l,p=0,f=s.length-1,b=0,h=o.length-1;for(;p<=f&&b<=h;)if(s[p]===null)p++;else if(s[f]===null)f--;else if(a[p]===r[b])u[b]=lt(s[p],o[b]),p++,b++;else if(a[f]===r[h])u[h]=lt(s[f],o[h]),f--,h--;else if(a[p]===r[h])u[h]=lt(s[p],o[h]),Zt(e,u[h+1],s[p]),p++,h--;else if(a[f]===r[b])u[b]=lt(s[f],o[b]),Zt(e,s[p],s[f]),f--,b++;else if(c===void 0&&(c=ma(r,b,h),l=ma(a,p,f)),c.has(a[p]))if(c.has(a[f])){const v=l.get(r[b]),k=v!==void 0?s[v]:null;if(k===null){const $=Zt(e,s[p]);lt($,o[b]),u[b]=$}else u[b]=lt(k,o[b]),Zt(e,s[p],k),s[v]=null;b++}else ds(s[f]),f--;else ds(s[p]),p++;for(;b<=h;){const v=Zt(e,u[h+1]);lt(v,o[b]),u[b++]=v}for(;p<=f;){const v=s[p++];v!==null&&ds(v)}return this.ut=r,Jf(e,u),et}});class zs extends qc{constructor(t){if(super(t),this.it=S,t.type!==zc.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===S||t==null)return this._t=void 0,this.it=t;if(t===et)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const n=[t];return n.raw=n,this._t={_$litType$:this.constructor.resultType,strings:n,values:[]}}}zs.directiveName="unsafeHTML",zs.resultType=1;const vi=Hc(zs);const{entries:jc,setPrototypeOf:ya,isFrozen:eg,getPrototypeOf:tg,getOwnPropertyDescriptor:ng}=Object;let{freeze:pe,seal:me,create:Hs}=Object,{apply:qs,construct:js}=typeof Reflect<"u"&&Reflect;pe||(pe=function(t){return t});me||(me=function(t){return t});qs||(qs=function(t,n){for(var i=arguments.length,s=new Array(i>2?i-2:0),o=2;o<i;o++)s[o-2]=arguments[o];return t.apply(n,s)});js||(js=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return new t(...i)});const Vn=he(Array.prototype.forEach),ig=he(Array.prototype.lastIndexOf),va=he(Array.prototype.pop),en=he(Array.prototype.push),sg=he(Array.prototype.splice),si=he(String.prototype.toLowerCase),ps=he(String.prototype.toString),hs=he(String.prototype.match),tn=he(String.prototype.replace),og=he(String.prototype.indexOf),rg=he(String.prototype.trim),ve=he(Object.prototype.hasOwnProperty),ce=he(RegExp.prototype.test),nn=ag(TypeError);function he(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return qs(e,t,i)}}function ag(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return js(e,n)}}function F(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:si;ya&&ya(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(eg(t)||(t[i]=o),s=o)}e[s]=!0}return e}function lg(e){for(let t=0;t<e.length;t++)ve(e,t)||(e[t]=null);return e}function Te(e){const t=Hs(null);for(const[n,i]of jc(e))ve(e,n)&&(Array.isArray(i)?t[n]=lg(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Te(i):t[n]=i);return t}function sn(e,t){for(;e!==null;){const i=ng(e,t);if(i){if(i.get)return he(i.get);if(typeof i.value=="function")return he(i.value)}e=tg(e)}function n(){return null}return n}const ba=pe(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),fs=pe(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),gs=pe(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),cg=pe(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ms=pe(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),ug=pe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),wa=pe(["#text"]),ka=pe(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),ys=pe(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Sa=pe(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Gn=pe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),dg=me(/\{\{[\w\W]*|[\w\W]*\}\}/gm),pg=me(/<%[\w\W]*|[\w\W]*%>/gm),hg=me(/\$\{[\w\W]*/gm),fg=me(/^data-[\-\w.\u00B7-\uFFFF]+$/),gg=me(/^aria-[\-\w]+$/),Vc=me(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),mg=me(/^(?:\w+script|data):/i),yg=me(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Gc=me(/^html$/i),vg=me(/^[a-z][.\w]*(-[.\w]+)+$/i);var $a=Object.freeze({__proto__:null,ARIA_ATTR:gg,ATTR_WHITESPACE:yg,CUSTOM_ELEMENT:vg,DATA_ATTR:fg,DOCTYPE_NAME:Gc,ERB_EXPR:pg,IS_ALLOWED_URI:Vc,IS_SCRIPT_OR_DATA:mg,MUSTACHE_EXPR:dg,TMPLIT_EXPR:hg});const on={element:1,text:3,progressingInstruction:7,comment:8,document:9},bg=function(){return typeof window>"u"?null:window},wg=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let i=null;const s="data-tt-policy-suffix";n&&n.hasAttribute(s)&&(i=n.getAttribute(s));const o="dompurify"+(i?"#"+i:"");try{return t.createPolicy(o,{createHTML(r){return r},createScriptURL(r){return r}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},xa=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Qc(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:bg();const t=I=>Qc(I);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==on.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,s=i.currentScript,{DocumentFragment:o,HTMLTemplateElement:r,Node:a,Element:u,NodeFilter:c,NamedNodeMap:l=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:f,trustedTypes:b}=e,h=u.prototype,v=sn(h,"cloneNode"),k=sn(h,"remove"),$=sn(h,"nextSibling"),A=sn(h,"childNodes"),C=sn(h,"parentNode");if(typeof r=="function"){const I=n.createElement("template");I.content&&I.content.ownerDocument&&(n=I.content.ownerDocument)}let T,_="";const{implementation:R,createNodeIterator:O,createDocumentFragment:ee,getElementsByTagName:ye}=n,{importNode:Ve}=i;let X=xa();t.isSupported=typeof jc=="function"&&typeof C=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Vt,ERB_EXPR:xt,TMPLIT_EXPR:it,DATA_ATTR:Ui,ARIA_ATTR:Wi,IS_SCRIPT_OR_DATA:Ki,ATTR_WHITESPACE:Tn,CUSTOM_ELEMENT:zi}=$a;let{IS_ALLOWED_URI:_n}=$a,Q=null;const Mn=F({},[...ba,...fs,...gs,...ms,...wa]);let Y=null;const Pn=F({},[...ka,...ys,...Sa,...Gn]);let j=Object.seal(Hs(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),st=null,Gt=null;const Ge=Object.seal(Hs(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ln=!0,x=!0,M=!1,B=!0,N=!1,V=!0,z=!1,le=!1,Qe=!1,At=!1,In=!1,Rn=!1,ir=!0,sr=!1;const td="user-content-";let Hi=!0,Qt=!1,Et={},xe=null;const qi=F({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let or=null;const rr=F({},["audio","video","img","source","image","track"]);let ji=null;const ar=F({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Dn="http://www.w3.org/1998/Math/MathML",Bn="http://www.w3.org/2000/svg",Be="http://www.w3.org/1999/xhtml";let Ct=Be,Vi=!1,Gi=null;const nd=F({},[Dn,Bn,Be],ps);let Nn=F({},["mi","mo","mn","ms","mtext"]),On=F({},["annotation-xml"]);const id=F({},["title","style","font","a","script"]);let Yt=null;const sd=["application/xhtml+xml","text/html"],od="text/html";let Z=null,Tt=null;const rd=n.createElement("form"),lr=function(w){return w instanceof RegExp||w instanceof Function},Qi=function(){let w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Tt&&Tt===w)){if((!w||typeof w!="object")&&(w={}),w=Te(w),Yt=sd.indexOf(w.PARSER_MEDIA_TYPE)===-1?od:w.PARSER_MEDIA_TYPE,Z=Yt==="application/xhtml+xml"?ps:si,Q=ve(w,"ALLOWED_TAGS")?F({},w.ALLOWED_TAGS,Z):Mn,Y=ve(w,"ALLOWED_ATTR")?F({},w.ALLOWED_ATTR,Z):Pn,Gi=ve(w,"ALLOWED_NAMESPACES")?F({},w.ALLOWED_NAMESPACES,ps):nd,ji=ve(w,"ADD_URI_SAFE_ATTR")?F(Te(ar),w.ADD_URI_SAFE_ATTR,Z):ar,or=ve(w,"ADD_DATA_URI_TAGS")?F(Te(rr),w.ADD_DATA_URI_TAGS,Z):rr,xe=ve(w,"FORBID_CONTENTS")?F({},w.FORBID_CONTENTS,Z):qi,st=ve(w,"FORBID_TAGS")?F({},w.FORBID_TAGS,Z):Te({}),Gt=ve(w,"FORBID_ATTR")?F({},w.FORBID_ATTR,Z):Te({}),Et=ve(w,"USE_PROFILES")?w.USE_PROFILES:!1,Ln=w.ALLOW_ARIA_ATTR!==!1,x=w.ALLOW_DATA_ATTR!==!1,M=w.ALLOW_UNKNOWN_PROTOCOLS||!1,B=w.ALLOW_SELF_CLOSE_IN_ATTR!==!1,N=w.SAFE_FOR_TEMPLATES||!1,V=w.SAFE_FOR_XML!==!1,z=w.WHOLE_DOCUMENT||!1,At=w.RETURN_DOM||!1,In=w.RETURN_DOM_FRAGMENT||!1,Rn=w.RETURN_TRUSTED_TYPE||!1,Qe=w.FORCE_BODY||!1,ir=w.SANITIZE_DOM!==!1,sr=w.SANITIZE_NAMED_PROPS||!1,Hi=w.KEEP_CONTENT!==!1,Qt=w.IN_PLACE||!1,_n=w.ALLOWED_URI_REGEXP||Vc,Ct=w.NAMESPACE||Be,Nn=w.MATHML_TEXT_INTEGRATION_POINTS||Nn,On=w.HTML_INTEGRATION_POINTS||On,j=w.CUSTOM_ELEMENT_HANDLING||{},w.CUSTOM_ELEMENT_HANDLING&&lr(w.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(j.tagNameCheck=w.CUSTOM_ELEMENT_HANDLING.tagNameCheck),w.CUSTOM_ELEMENT_HANDLING&&lr(w.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(j.attributeNameCheck=w.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),w.CUSTOM_ELEMENT_HANDLING&&typeof w.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(j.allowCustomizedBuiltInElements=w.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),N&&(x=!1),In&&(At=!0),Et&&(Q=F({},wa),Y=[],Et.html===!0&&(F(Q,ba),F(Y,ka)),Et.svg===!0&&(F(Q,fs),F(Y,ys),F(Y,Gn)),Et.svgFilters===!0&&(F(Q,gs),F(Y,ys),F(Y,Gn)),Et.mathMl===!0&&(F(Q,ms),F(Y,Sa),F(Y,Gn))),w.ADD_TAGS&&(typeof w.ADD_TAGS=="function"?Ge.tagCheck=w.ADD_TAGS:(Q===Mn&&(Q=Te(Q)),F(Q,w.ADD_TAGS,Z))),w.ADD_ATTR&&(typeof w.ADD_ATTR=="function"?Ge.attributeCheck=w.ADD_ATTR:(Y===Pn&&(Y=Te(Y)),F(Y,w.ADD_ATTR,Z))),w.ADD_URI_SAFE_ATTR&&F(ji,w.ADD_URI_SAFE_ATTR,Z),w.FORBID_CONTENTS&&(xe===qi&&(xe=Te(xe)),F(xe,w.FORBID_CONTENTS,Z)),w.ADD_FORBID_CONTENTS&&(xe===qi&&(xe=Te(xe)),F(xe,w.ADD_FORBID_CONTENTS,Z)),Hi&&(Q["#text"]=!0),z&&F(Q,["html","head","body"]),Q.table&&(F(Q,["tbody"]),delete st.tbody),w.TRUSTED_TYPES_POLICY){if(typeof w.TRUSTED_TYPES_POLICY.createHTML!="function")throw nn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof w.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw nn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=w.TRUSTED_TYPES_POLICY,_=T.createHTML("")}else T===void 0&&(T=wg(b,s)),T!==null&&typeof _=="string"&&(_=T.createHTML(""));pe&&pe(w),Tt=w}},cr=F({},[...fs,...gs,...cg]),ur=F({},[...ms,...ug]),ad=function(w){let E=C(w);(!E||!E.tagName)&&(E={namespaceURI:Ct,tagName:"template"});const L=si(w.tagName),H=si(E.tagName);return Gi[w.namespaceURI]?w.namespaceURI===Bn?E.namespaceURI===Be?L==="svg":E.namespaceURI===Dn?L==="svg"&&(H==="annotation-xml"||Nn[H]):!!cr[L]:w.namespaceURI===Dn?E.namespaceURI===Be?L==="math":E.namespaceURI===Bn?L==="math"&&On[H]:!!ur[L]:w.namespaceURI===Be?E.namespaceURI===Bn&&!On[H]||E.namespaceURI===Dn&&!Nn[H]?!1:!ur[L]&&(id[L]||!cr[L]):!!(Yt==="application/xhtml+xml"&&Gi[w.namespaceURI]):!1},Ae=function(w){en(t.removed,{element:w});try{C(w).removeChild(w)}catch{k(w)}},ot=function(w,E){try{en(t.removed,{attribute:E.getAttributeNode(w),from:E})}catch{en(t.removed,{attribute:null,from:E})}if(E.removeAttribute(w),w==="is")if(At||In)try{Ae(E)}catch{}else try{E.setAttribute(w,"")}catch{}},dr=function(w){let E=null,L=null;if(Qe)w="<remove></remove>"+w;else{const J=hs(w,/^[\r\n\t ]+/);L=J&&J[0]}Yt==="application/xhtml+xml"&&Ct===Be&&(w='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+w+"</body></html>");const H=T?T.createHTML(w):w;if(Ct===Be)try{E=new f().parseFromString(H,Yt)}catch{}if(!E||!E.documentElement){E=R.createDocument(Ct,"template",null);try{E.documentElement.innerHTML=Vi?_:H}catch{}}const se=E.body||E.documentElement;return w&&L&&se.insertBefore(n.createTextNode(L),se.childNodes[0]||null),Ct===Be?ye.call(E,z?"html":"body")[0]:z?E.documentElement:se},pr=function(w){return O.call(w.ownerDocument||w,w,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Yi=function(w){return w instanceof p&&(typeof w.nodeName!="string"||typeof w.textContent!="string"||typeof w.removeChild!="function"||!(w.attributes instanceof l)||typeof w.removeAttribute!="function"||typeof w.setAttribute!="function"||typeof w.namespaceURI!="string"||typeof w.insertBefore!="function"||typeof w.hasChildNodes!="function")},hr=function(w){return typeof a=="function"&&w instanceof a};function Ne(I,w,E){Vn(I,L=>{L.call(t,w,E,Tt)})}const fr=function(w){let E=null;if(Ne(X.beforeSanitizeElements,w,null),Yi(w))return Ae(w),!0;const L=Z(w.nodeName);if(Ne(X.uponSanitizeElement,w,{tagName:L,allowedTags:Q}),V&&w.hasChildNodes()&&!hr(w.firstElementChild)&&ce(/<[/\w!]/g,w.innerHTML)&&ce(/<[/\w!]/g,w.textContent)||w.nodeType===on.progressingInstruction||V&&w.nodeType===on.comment&&ce(/<[/\w]/g,w.data))return Ae(w),!0;if(!(Ge.tagCheck instanceof Function&&Ge.tagCheck(L))&&(!Q[L]||st[L])){if(!st[L]&&mr(L)&&(j.tagNameCheck instanceof RegExp&&ce(j.tagNameCheck,L)||j.tagNameCheck instanceof Function&&j.tagNameCheck(L)))return!1;if(Hi&&!xe[L]){const H=C(w)||w.parentNode,se=A(w)||w.childNodes;if(se&&H){const J=se.length;for(let fe=J-1;fe>=0;--fe){const Oe=v(se[fe],!0);Oe.__removalCount=(w.__removalCount||0)+1,H.insertBefore(Oe,$(w))}}}return Ae(w),!0}return w instanceof u&&!ad(w)||(L==="noscript"||L==="noembed"||L==="noframes")&&ce(/<\/no(script|embed|frames)/i,w.innerHTML)?(Ae(w),!0):(N&&w.nodeType===on.text&&(E=w.textContent,Vn([Vt,xt,it],H=>{E=tn(E,H," ")}),w.textContent!==E&&(en(t.removed,{element:w.cloneNode()}),w.textContent=E)),Ne(X.afterSanitizeElements,w,null),!1)},gr=function(w,E,L){if(ir&&(E==="id"||E==="name")&&(L in n||L in rd))return!1;if(!(x&&!Gt[E]&&ce(Ui,E))){if(!(Ln&&ce(Wi,E))){if(!(Ge.attributeCheck instanceof Function&&Ge.attributeCheck(E,w))){if(!Y[E]||Gt[E]){if(!(mr(w)&&(j.tagNameCheck instanceof RegExp&&ce(j.tagNameCheck,w)||j.tagNameCheck instanceof Function&&j.tagNameCheck(w))&&(j.attributeNameCheck instanceof RegExp&&ce(j.attributeNameCheck,E)||j.attributeNameCheck instanceof Function&&j.attributeNameCheck(E,w))||E==="is"&&j.allowCustomizedBuiltInElements&&(j.tagNameCheck instanceof RegExp&&ce(j.tagNameCheck,L)||j.tagNameCheck instanceof Function&&j.tagNameCheck(L))))return!1}else if(!ji[E]){if(!ce(_n,tn(L,Tn,""))){if(!((E==="src"||E==="xlink:href"||E==="href")&&w!=="script"&&og(L,"data:")===0&&or[w])){if(!(M&&!ce(Ki,tn(L,Tn,"")))){if(L)return!1}}}}}}}return!0},mr=function(w){return w!=="annotation-xml"&&hs(w,zi)},yr=function(w){Ne(X.beforeSanitizeAttributes,w,null);const{attributes:E}=w;if(!E||Yi(w))return;const L={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Y,forceKeepAttr:void 0};let H=E.length;for(;H--;){const se=E[H],{name:J,namespaceURI:fe,value:Oe}=se,_t=Z(J),Ji=Oe;let ne=J==="value"?Ji:rg(Ji);if(L.attrName=_t,L.attrValue=ne,L.keepAttr=!0,L.forceKeepAttr=void 0,Ne(X.uponSanitizeAttribute,w,L),ne=L.attrValue,sr&&(_t==="id"||_t==="name")&&(ot(J,w),ne=td+ne),V&&ce(/((--!?|])>)|<\/(style|title|textarea)/i,ne)){ot(J,w);continue}if(_t==="attributename"&&hs(ne,"href")){ot(J,w);continue}if(L.forceKeepAttr)continue;if(!L.keepAttr){ot(J,w);continue}if(!B&&ce(/\/>/i,ne)){ot(J,w);continue}N&&Vn([Vt,xt,it],br=>{ne=tn(ne,br," ")});const vr=Z(w.nodeName);if(!gr(vr,_t,ne)){ot(J,w);continue}if(T&&typeof b=="object"&&typeof b.getAttributeType=="function"&&!fe)switch(b.getAttributeType(vr,_t)){case"TrustedHTML":{ne=T.createHTML(ne);break}case"TrustedScriptURL":{ne=T.createScriptURL(ne);break}}if(ne!==Ji)try{fe?w.setAttributeNS(fe,J,ne):w.setAttribute(J,ne),Yi(w)?Ae(w):va(t.removed)}catch{ot(J,w)}}Ne(X.afterSanitizeAttributes,w,null)},ld=function I(w){let E=null;const L=pr(w);for(Ne(X.beforeSanitizeShadowDOM,w,null);E=L.nextNode();)Ne(X.uponSanitizeShadowNode,E,null),fr(E),yr(E),E.content instanceof o&&I(E.content);Ne(X.afterSanitizeShadowDOM,w,null)};return t.sanitize=function(I){let w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E=null,L=null,H=null,se=null;if(Vi=!I,Vi&&(I="<!-->"),typeof I!="string"&&!hr(I))if(typeof I.toString=="function"){if(I=I.toString(),typeof I!="string")throw nn("dirty is not a string, aborting")}else throw nn("toString is not a function");if(!t.isSupported)return I;if(le||Qi(w),t.removed=[],typeof I=="string"&&(Qt=!1),Qt){if(I.nodeName){const Oe=Z(I.nodeName);if(!Q[Oe]||st[Oe])throw nn("root node is forbidden and cannot be sanitized in-place")}}else if(I instanceof a)E=dr("<!---->"),L=E.ownerDocument.importNode(I,!0),L.nodeType===on.element&&L.nodeName==="BODY"||L.nodeName==="HTML"?E=L:E.appendChild(L);else{if(!At&&!N&&!z&&I.indexOf("<")===-1)return T&&Rn?T.createHTML(I):I;if(E=dr(I),!E)return At?null:Rn?_:""}E&&Qe&&Ae(E.firstChild);const J=pr(Qt?I:E);for(;H=J.nextNode();)fr(H),yr(H),H.content instanceof o&&ld(H.content);if(Qt)return I;if(At){if(In)for(se=ee.call(E.ownerDocument);E.firstChild;)se.appendChild(E.firstChild);else se=E;return(Y.shadowroot||Y.shadowrootmode)&&(se=Ve.call(i,se,!0)),se}let fe=z?E.outerHTML:E.innerHTML;return z&&Q["!doctype"]&&E.ownerDocument&&E.ownerDocument.doctype&&E.ownerDocument.doctype.name&&ce(Gc,E.ownerDocument.doctype.name)&&(fe="<!DOCTYPE "+E.ownerDocument.doctype.name+`>
2261
- `+fe),N&&Vn([Vt,xt,it],Oe=>{fe=tn(fe,Oe," ")}),T&&Rn?T.createHTML(fe):fe},t.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Qi(I),le=!0},t.clearConfig=function(){Tt=null,le=!1},t.isValidAttribute=function(I,w,E){Tt||Qi({});const L=Z(I),H=Z(w);return gr(L,H,E)},t.addHook=function(I,w){typeof w=="function"&&en(X[I],w)},t.removeHook=function(I,w){if(w!==void 0){const E=ig(X[I],w);return E===-1?void 0:sg(X[I],E,1)[0]}return va(X[I])},t.removeHooks=function(I){X[I]=[]},t.removeAllHooks=function(){X=xa()},t}var Vs=Qc();function Oo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var St=Oo();function Yc(e){St=e}var yn={exec:()=>null};function W(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(s,o)=>{let r=typeof o=="string"?o:o.source;return r=r.replace(ue.caret,"$1"),n=n.replace(s,r),i},getRegex:()=>new RegExp(n,t)};return i}var kg=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),ue={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},Sg=/^(?:[ \t]*(?:\n|$))+/,$g=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,xg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,En=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ag=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Fo=/(?:[*+-]|\d{1,9}[.)])/,Jc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Xc=W(Jc).replace(/bull/g,Fo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Eg=W(Jc).replace(/bull/g,Fo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Uo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Cg=/^[^\n]+/,Wo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Tg=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Wo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_g=W(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Fo).getRegex(),Bi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ko=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Mg=W("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ko).replace("tag",Bi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Zc=W(Uo).replace("hr",En).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex(),Pg=W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Zc).getRegex(),zo={blockquote:Pg,code:$g,def:Tg,fences:xg,heading:Ag,hr:En,html:Mg,lheading:Xc,list:_g,newline:Sg,paragraph:Zc,table:yn,text:Cg},Aa=W("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",En).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex(),Lg={...zo,lheading:Eg,table:Aa,paragraph:W(Uo).replace("hr",En).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Aa).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex()},Ig={...zo,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ko).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:yn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(Uo).replace("hr",En).replace("heading",` *#{1,6} *[^
2260
+ `}const zc={CHILD:2},Hc=e=>(...t)=>({_$litDirective$:e,values:t});let qc=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,n,i){this._$Ct=t,this._$AM=n,this._$Ci=i}_$AS(t,n){return this.update(t,n)}update(t,n){return this.render(...n)}};const{I:Qf}=Ld,fa=e=>e,ga=()=>document.createComment(""),Zt=(e,t,n)=>{var o;const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const r=i.insertBefore(ga(),s),a=i.insertBefore(ga(),s);n=new Qf(r,a,e,e.options)}else{const r=n._$AB.nextSibling,a=n._$AM,u=a!==e;if(u){let c;(o=n._$AQ)==null||o.call(n,e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==a._$AU&&n._$AP(c)}if(r!==s||u){let c=n._$AA;for(;c!==r;){const l=fa(c).nextSibling;fa(i).insertBefore(c,s),c=l}}}return n},lt=(e,t,n=e)=>(e._$AI(t,n),e),Yf={},Jf=(e,t=Yf)=>e._$AH=t,Xf=e=>e._$AH,ds=e=>{e._$AR(),e._$AA.remove()};const ma=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},Zf=Hc(class extends qc{constructor(e){if(super(e),e.type!==zc.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,n){let i;n===void 0?n=t:t!==void 0&&(i=t);const s=[],o=[];let r=0;for(const a of e)s[r]=i?i(a,r):r,o[r]=n(a,r),r++;return{values:o,keys:s}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,i]){const s=Xf(e),{values:o,keys:r}=this.dt(t,n,i);if(!Array.isArray(s))return this.ut=r,o;const a=this.ut??(this.ut=[]),u=[];let c,l,p=0,h=s.length-1,b=0,f=o.length-1;for(;p<=h&&b<=f;)if(s[p]===null)p++;else if(s[h]===null)h--;else if(a[p]===r[b])u[b]=lt(s[p],o[b]),p++,b++;else if(a[h]===r[f])u[f]=lt(s[h],o[f]),h--,f--;else if(a[p]===r[f])u[f]=lt(s[p],o[f]),Zt(e,u[f+1],s[p]),p++,f--;else if(a[h]===r[b])u[b]=lt(s[h],o[b]),Zt(e,s[p],s[h]),h--,b++;else if(c===void 0&&(c=ma(r,b,f),l=ma(a,p,h)),c.has(a[p]))if(c.has(a[h])){const v=l.get(r[b]),k=v!==void 0?s[v]:null;if(k===null){const $=Zt(e,s[p]);lt($,o[b]),u[b]=$}else u[b]=lt(k,o[b]),Zt(e,s[p],k),s[v]=null;b++}else ds(s[h]),h--;else ds(s[p]),p++;for(;b<=f;){const v=Zt(e,u[f+1]);lt(v,o[b]),u[b++]=v}for(;p<=h;){const v=s[p++];v!==null&&ds(v)}return this.ut=r,Jf(e,u),et}});class zs extends qc{constructor(t){if(super(t),this.it=S,t.type!==zc.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===S||t==null)return this._t=void 0,this.it=t;if(t===et)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const n=[t];return n.raw=n,this._t={_$litType$:this.constructor.resultType,strings:n,values:[]}}}zs.directiveName="unsafeHTML",zs.resultType=1;const vi=Hc(zs);const{entries:jc,setPrototypeOf:ya,isFrozen:eg,getPrototypeOf:tg,getOwnPropertyDescriptor:ng}=Object;let{freeze:pe,seal:me,create:Hs}=Object,{apply:qs,construct:js}=typeof Reflect<"u"&&Reflect;pe||(pe=function(t){return t});me||(me=function(t){return t});qs||(qs=function(t,n){for(var i=arguments.length,s=new Array(i>2?i-2:0),o=2;o<i;o++)s[o-2]=arguments[o];return t.apply(n,s)});js||(js=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return new t(...i)});const Vn=he(Array.prototype.forEach),ig=he(Array.prototype.lastIndexOf),va=he(Array.prototype.pop),en=he(Array.prototype.push),sg=he(Array.prototype.splice),si=he(String.prototype.toLowerCase),ps=he(String.prototype.toString),hs=he(String.prototype.match),tn=he(String.prototype.replace),og=he(String.prototype.indexOf),rg=he(String.prototype.trim),ve=he(Object.prototype.hasOwnProperty),ce=he(RegExp.prototype.test),nn=ag(TypeError);function he(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return qs(e,t,i)}}function ag(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return js(e,n)}}function F(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:si;ya&&ya(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(eg(t)||(t[i]=o),s=o)}e[s]=!0}return e}function lg(e){for(let t=0;t<e.length;t++)ve(e,t)||(e[t]=null);return e}function Te(e){const t=Hs(null);for(const[n,i]of jc(e))ve(e,n)&&(Array.isArray(i)?t[n]=lg(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Te(i):t[n]=i);return t}function sn(e,t){for(;e!==null;){const i=ng(e,t);if(i){if(i.get)return he(i.get);if(typeof i.value=="function")return he(i.value)}e=tg(e)}function n(){return null}return n}const ba=pe(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),fs=pe(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),gs=pe(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),cg=pe(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ms=pe(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),ug=pe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),wa=pe(["#text"]),ka=pe(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),ys=pe(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Sa=pe(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Gn=pe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),dg=me(/\{\{[\w\W]*|[\w\W]*\}\}/gm),pg=me(/<%[\w\W]*|[\w\W]*%>/gm),hg=me(/\$\{[\w\W]*/gm),fg=me(/^data-[\-\w.\u00B7-\uFFFF]+$/),gg=me(/^aria-[\-\w]+$/),Vc=me(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),mg=me(/^(?:\w+script|data):/i),yg=me(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Gc=me(/^html$/i),vg=me(/^[a-z][.\w]*(-[.\w]+)+$/i);var $a=Object.freeze({__proto__:null,ARIA_ATTR:gg,ATTR_WHITESPACE:yg,CUSTOM_ELEMENT:vg,DATA_ATTR:fg,DOCTYPE_NAME:Gc,ERB_EXPR:pg,IS_ALLOWED_URI:Vc,IS_SCRIPT_OR_DATA:mg,MUSTACHE_EXPR:dg,TMPLIT_EXPR:hg});const on={element:1,text:3,progressingInstruction:7,comment:8,document:9},bg=function(){return typeof window>"u"?null:window},wg=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let i=null;const s="data-tt-policy-suffix";n&&n.hasAttribute(s)&&(i=n.getAttribute(s));const o="dompurify"+(i?"#"+i:"");try{return t.createPolicy(o,{createHTML(r){return r},createScriptURL(r){return r}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},Aa=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Qc(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:bg();const t=I=>Qc(I);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==on.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,s=i.currentScript,{DocumentFragment:o,HTMLTemplateElement:r,Node:a,Element:u,NodeFilter:c,NamedNodeMap:l=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:h,trustedTypes:b}=e,f=u.prototype,v=sn(f,"cloneNode"),k=sn(f,"remove"),$=sn(f,"nextSibling"),A=sn(f,"childNodes"),C=sn(f,"parentNode");if(typeof r=="function"){const I=n.createElement("template");I.content&&I.content.ownerDocument&&(n=I.content.ownerDocument)}let T,_="";const{implementation:R,createNodeIterator:O,createDocumentFragment:ee,getElementsByTagName:ye}=n,{importNode:Ve}=i;let X=Aa();t.isSupported=typeof jc=="function"&&typeof C=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Vt,ERB_EXPR:At,TMPLIT_EXPR:it,DATA_ATTR:Ui,ARIA_ATTR:Wi,IS_SCRIPT_OR_DATA:Ki,ATTR_WHITESPACE:Tn,CUSTOM_ELEMENT:zi}=$a;let{IS_ALLOWED_URI:_n}=$a,Q=null;const Mn=F({},[...ba,...fs,...gs,...ms,...wa]);let Y=null;const Pn=F({},[...ka,...ys,...Sa,...Gn]);let j=Object.seal(Hs(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),st=null,Gt=null;const Ge=Object.seal(Hs(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ln=!0,x=!0,M=!1,B=!0,N=!1,V=!0,z=!1,le=!1,Qe=!1,xt=!1,In=!1,Rn=!1,ir=!0,sr=!1;const td="user-content-";let Hi=!0,Qt=!1,Et={},Ae=null;const qi=F({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let or=null;const rr=F({},["audio","video","img","source","image","track"]);let ji=null;const ar=F({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Dn="http://www.w3.org/1998/Math/MathML",Bn="http://www.w3.org/2000/svg",Be="http://www.w3.org/1999/xhtml";let Ct=Be,Vi=!1,Gi=null;const nd=F({},[Dn,Bn,Be],ps);let Nn=F({},["mi","mo","mn","ms","mtext"]),On=F({},["annotation-xml"]);const id=F({},["title","style","font","a","script"]);let Yt=null;const sd=["application/xhtml+xml","text/html"],od="text/html";let Z=null,Tt=null;const rd=n.createElement("form"),lr=function(w){return w instanceof RegExp||w instanceof Function},Qi=function(){let w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Tt&&Tt===w)){if((!w||typeof w!="object")&&(w={}),w=Te(w),Yt=sd.indexOf(w.PARSER_MEDIA_TYPE)===-1?od:w.PARSER_MEDIA_TYPE,Z=Yt==="application/xhtml+xml"?ps:si,Q=ve(w,"ALLOWED_TAGS")?F({},w.ALLOWED_TAGS,Z):Mn,Y=ve(w,"ALLOWED_ATTR")?F({},w.ALLOWED_ATTR,Z):Pn,Gi=ve(w,"ALLOWED_NAMESPACES")?F({},w.ALLOWED_NAMESPACES,ps):nd,ji=ve(w,"ADD_URI_SAFE_ATTR")?F(Te(ar),w.ADD_URI_SAFE_ATTR,Z):ar,or=ve(w,"ADD_DATA_URI_TAGS")?F(Te(rr),w.ADD_DATA_URI_TAGS,Z):rr,Ae=ve(w,"FORBID_CONTENTS")?F({},w.FORBID_CONTENTS,Z):qi,st=ve(w,"FORBID_TAGS")?F({},w.FORBID_TAGS,Z):Te({}),Gt=ve(w,"FORBID_ATTR")?F({},w.FORBID_ATTR,Z):Te({}),Et=ve(w,"USE_PROFILES")?w.USE_PROFILES:!1,Ln=w.ALLOW_ARIA_ATTR!==!1,x=w.ALLOW_DATA_ATTR!==!1,M=w.ALLOW_UNKNOWN_PROTOCOLS||!1,B=w.ALLOW_SELF_CLOSE_IN_ATTR!==!1,N=w.SAFE_FOR_TEMPLATES||!1,V=w.SAFE_FOR_XML!==!1,z=w.WHOLE_DOCUMENT||!1,xt=w.RETURN_DOM||!1,In=w.RETURN_DOM_FRAGMENT||!1,Rn=w.RETURN_TRUSTED_TYPE||!1,Qe=w.FORCE_BODY||!1,ir=w.SANITIZE_DOM!==!1,sr=w.SANITIZE_NAMED_PROPS||!1,Hi=w.KEEP_CONTENT!==!1,Qt=w.IN_PLACE||!1,_n=w.ALLOWED_URI_REGEXP||Vc,Ct=w.NAMESPACE||Be,Nn=w.MATHML_TEXT_INTEGRATION_POINTS||Nn,On=w.HTML_INTEGRATION_POINTS||On,j=w.CUSTOM_ELEMENT_HANDLING||{},w.CUSTOM_ELEMENT_HANDLING&&lr(w.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(j.tagNameCheck=w.CUSTOM_ELEMENT_HANDLING.tagNameCheck),w.CUSTOM_ELEMENT_HANDLING&&lr(w.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(j.attributeNameCheck=w.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),w.CUSTOM_ELEMENT_HANDLING&&typeof w.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(j.allowCustomizedBuiltInElements=w.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),N&&(x=!1),In&&(xt=!0),Et&&(Q=F({},wa),Y=[],Et.html===!0&&(F(Q,ba),F(Y,ka)),Et.svg===!0&&(F(Q,fs),F(Y,ys),F(Y,Gn)),Et.svgFilters===!0&&(F(Q,gs),F(Y,ys),F(Y,Gn)),Et.mathMl===!0&&(F(Q,ms),F(Y,Sa),F(Y,Gn))),w.ADD_TAGS&&(typeof w.ADD_TAGS=="function"?Ge.tagCheck=w.ADD_TAGS:(Q===Mn&&(Q=Te(Q)),F(Q,w.ADD_TAGS,Z))),w.ADD_ATTR&&(typeof w.ADD_ATTR=="function"?Ge.attributeCheck=w.ADD_ATTR:(Y===Pn&&(Y=Te(Y)),F(Y,w.ADD_ATTR,Z))),w.ADD_URI_SAFE_ATTR&&F(ji,w.ADD_URI_SAFE_ATTR,Z),w.FORBID_CONTENTS&&(Ae===qi&&(Ae=Te(Ae)),F(Ae,w.FORBID_CONTENTS,Z)),w.ADD_FORBID_CONTENTS&&(Ae===qi&&(Ae=Te(Ae)),F(Ae,w.ADD_FORBID_CONTENTS,Z)),Hi&&(Q["#text"]=!0),z&&F(Q,["html","head","body"]),Q.table&&(F(Q,["tbody"]),delete st.tbody),w.TRUSTED_TYPES_POLICY){if(typeof w.TRUSTED_TYPES_POLICY.createHTML!="function")throw nn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof w.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw nn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=w.TRUSTED_TYPES_POLICY,_=T.createHTML("")}else T===void 0&&(T=wg(b,s)),T!==null&&typeof _=="string"&&(_=T.createHTML(""));pe&&pe(w),Tt=w}},cr=F({},[...fs,...gs,...cg]),ur=F({},[...ms,...ug]),ad=function(w){let E=C(w);(!E||!E.tagName)&&(E={namespaceURI:Ct,tagName:"template"});const L=si(w.tagName),H=si(E.tagName);return Gi[w.namespaceURI]?w.namespaceURI===Bn?E.namespaceURI===Be?L==="svg":E.namespaceURI===Dn?L==="svg"&&(H==="annotation-xml"||Nn[H]):!!cr[L]:w.namespaceURI===Dn?E.namespaceURI===Be?L==="math":E.namespaceURI===Bn?L==="math"&&On[H]:!!ur[L]:w.namespaceURI===Be?E.namespaceURI===Bn&&!On[H]||E.namespaceURI===Dn&&!Nn[H]?!1:!ur[L]&&(id[L]||!cr[L]):!!(Yt==="application/xhtml+xml"&&Gi[w.namespaceURI]):!1},xe=function(w){en(t.removed,{element:w});try{C(w).removeChild(w)}catch{k(w)}},ot=function(w,E){try{en(t.removed,{attribute:E.getAttributeNode(w),from:E})}catch{en(t.removed,{attribute:null,from:E})}if(E.removeAttribute(w),w==="is")if(xt||In)try{xe(E)}catch{}else try{E.setAttribute(w,"")}catch{}},dr=function(w){let E=null,L=null;if(Qe)w="<remove></remove>"+w;else{const J=hs(w,/^[\r\n\t ]+/);L=J&&J[0]}Yt==="application/xhtml+xml"&&Ct===Be&&(w='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+w+"</body></html>");const H=T?T.createHTML(w):w;if(Ct===Be)try{E=new h().parseFromString(H,Yt)}catch{}if(!E||!E.documentElement){E=R.createDocument(Ct,"template",null);try{E.documentElement.innerHTML=Vi?_:H}catch{}}const se=E.body||E.documentElement;return w&&L&&se.insertBefore(n.createTextNode(L),se.childNodes[0]||null),Ct===Be?ye.call(E,z?"html":"body")[0]:z?E.documentElement:se},pr=function(w){return O.call(w.ownerDocument||w,w,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Yi=function(w){return w instanceof p&&(typeof w.nodeName!="string"||typeof w.textContent!="string"||typeof w.removeChild!="function"||!(w.attributes instanceof l)||typeof w.removeAttribute!="function"||typeof w.setAttribute!="function"||typeof w.namespaceURI!="string"||typeof w.insertBefore!="function"||typeof w.hasChildNodes!="function")},hr=function(w){return typeof a=="function"&&w instanceof a};function Ne(I,w,E){Vn(I,L=>{L.call(t,w,E,Tt)})}const fr=function(w){let E=null;if(Ne(X.beforeSanitizeElements,w,null),Yi(w))return xe(w),!0;const L=Z(w.nodeName);if(Ne(X.uponSanitizeElement,w,{tagName:L,allowedTags:Q}),V&&w.hasChildNodes()&&!hr(w.firstElementChild)&&ce(/<[/\w!]/g,w.innerHTML)&&ce(/<[/\w!]/g,w.textContent)||w.nodeType===on.progressingInstruction||V&&w.nodeType===on.comment&&ce(/<[/\w]/g,w.data))return xe(w),!0;if(!(Ge.tagCheck instanceof Function&&Ge.tagCheck(L))&&(!Q[L]||st[L])){if(!st[L]&&mr(L)&&(j.tagNameCheck instanceof RegExp&&ce(j.tagNameCheck,L)||j.tagNameCheck instanceof Function&&j.tagNameCheck(L)))return!1;if(Hi&&!Ae[L]){const H=C(w)||w.parentNode,se=A(w)||w.childNodes;if(se&&H){const J=se.length;for(let fe=J-1;fe>=0;--fe){const Oe=v(se[fe],!0);Oe.__removalCount=(w.__removalCount||0)+1,H.insertBefore(Oe,$(w))}}}return xe(w),!0}return w instanceof u&&!ad(w)||(L==="noscript"||L==="noembed"||L==="noframes")&&ce(/<\/no(script|embed|frames)/i,w.innerHTML)?(xe(w),!0):(N&&w.nodeType===on.text&&(E=w.textContent,Vn([Vt,At,it],H=>{E=tn(E,H," ")}),w.textContent!==E&&(en(t.removed,{element:w.cloneNode()}),w.textContent=E)),Ne(X.afterSanitizeElements,w,null),!1)},gr=function(w,E,L){if(ir&&(E==="id"||E==="name")&&(L in n||L in rd))return!1;if(!(x&&!Gt[E]&&ce(Ui,E))){if(!(Ln&&ce(Wi,E))){if(!(Ge.attributeCheck instanceof Function&&Ge.attributeCheck(E,w))){if(!Y[E]||Gt[E]){if(!(mr(w)&&(j.tagNameCheck instanceof RegExp&&ce(j.tagNameCheck,w)||j.tagNameCheck instanceof Function&&j.tagNameCheck(w))&&(j.attributeNameCheck instanceof RegExp&&ce(j.attributeNameCheck,E)||j.attributeNameCheck instanceof Function&&j.attributeNameCheck(E,w))||E==="is"&&j.allowCustomizedBuiltInElements&&(j.tagNameCheck instanceof RegExp&&ce(j.tagNameCheck,L)||j.tagNameCheck instanceof Function&&j.tagNameCheck(L))))return!1}else if(!ji[E]){if(!ce(_n,tn(L,Tn,""))){if(!((E==="src"||E==="xlink:href"||E==="href")&&w!=="script"&&og(L,"data:")===0&&or[w])){if(!(M&&!ce(Ki,tn(L,Tn,"")))){if(L)return!1}}}}}}}return!0},mr=function(w){return w!=="annotation-xml"&&hs(w,zi)},yr=function(w){Ne(X.beforeSanitizeAttributes,w,null);const{attributes:E}=w;if(!E||Yi(w))return;const L={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Y,forceKeepAttr:void 0};let H=E.length;for(;H--;){const se=E[H],{name:J,namespaceURI:fe,value:Oe}=se,_t=Z(J),Ji=Oe;let ne=J==="value"?Ji:rg(Ji);if(L.attrName=_t,L.attrValue=ne,L.keepAttr=!0,L.forceKeepAttr=void 0,Ne(X.uponSanitizeAttribute,w,L),ne=L.attrValue,sr&&(_t==="id"||_t==="name")&&(ot(J,w),ne=td+ne),V&&ce(/((--!?|])>)|<\/(style|title|textarea)/i,ne)){ot(J,w);continue}if(_t==="attributename"&&hs(ne,"href")){ot(J,w);continue}if(L.forceKeepAttr)continue;if(!L.keepAttr){ot(J,w);continue}if(!B&&ce(/\/>/i,ne)){ot(J,w);continue}N&&Vn([Vt,At,it],br=>{ne=tn(ne,br," ")});const vr=Z(w.nodeName);if(!gr(vr,_t,ne)){ot(J,w);continue}if(T&&typeof b=="object"&&typeof b.getAttributeType=="function"&&!fe)switch(b.getAttributeType(vr,_t)){case"TrustedHTML":{ne=T.createHTML(ne);break}case"TrustedScriptURL":{ne=T.createScriptURL(ne);break}}if(ne!==Ji)try{fe?w.setAttributeNS(fe,J,ne):w.setAttribute(J,ne),Yi(w)?xe(w):va(t.removed)}catch{ot(J,w)}}Ne(X.afterSanitizeAttributes,w,null)},ld=function I(w){let E=null;const L=pr(w);for(Ne(X.beforeSanitizeShadowDOM,w,null);E=L.nextNode();)Ne(X.uponSanitizeShadowNode,E,null),fr(E),yr(E),E.content instanceof o&&I(E.content);Ne(X.afterSanitizeShadowDOM,w,null)};return t.sanitize=function(I){let w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E=null,L=null,H=null,se=null;if(Vi=!I,Vi&&(I="<!-->"),typeof I!="string"&&!hr(I))if(typeof I.toString=="function"){if(I=I.toString(),typeof I!="string")throw nn("dirty is not a string, aborting")}else throw nn("toString is not a function");if(!t.isSupported)return I;if(le||Qi(w),t.removed=[],typeof I=="string"&&(Qt=!1),Qt){if(I.nodeName){const Oe=Z(I.nodeName);if(!Q[Oe]||st[Oe])throw nn("root node is forbidden and cannot be sanitized in-place")}}else if(I instanceof a)E=dr("<!---->"),L=E.ownerDocument.importNode(I,!0),L.nodeType===on.element&&L.nodeName==="BODY"||L.nodeName==="HTML"?E=L:E.appendChild(L);else{if(!xt&&!N&&!z&&I.indexOf("<")===-1)return T&&Rn?T.createHTML(I):I;if(E=dr(I),!E)return xt?null:Rn?_:""}E&&Qe&&xe(E.firstChild);const J=pr(Qt?I:E);for(;H=J.nextNode();)fr(H),yr(H),H.content instanceof o&&ld(H.content);if(Qt)return I;if(xt){if(In)for(se=ee.call(E.ownerDocument);E.firstChild;)se.appendChild(E.firstChild);else se=E;return(Y.shadowroot||Y.shadowrootmode)&&(se=Ve.call(i,se,!0)),se}let fe=z?E.outerHTML:E.innerHTML;return z&&Q["!doctype"]&&E.ownerDocument&&E.ownerDocument.doctype&&E.ownerDocument.doctype.name&&ce(Gc,E.ownerDocument.doctype.name)&&(fe="<!DOCTYPE "+E.ownerDocument.doctype.name+`>
2261
+ `+fe),N&&Vn([Vt,At,it],Oe=>{fe=tn(fe,Oe," ")}),T&&Rn?T.createHTML(fe):fe},t.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Qi(I),le=!0},t.clearConfig=function(){Tt=null,le=!1},t.isValidAttribute=function(I,w,E){Tt||Qi({});const L=Z(I),H=Z(w);return gr(L,H,E)},t.addHook=function(I,w){typeof w=="function"&&en(X[I],w)},t.removeHook=function(I,w){if(w!==void 0){const E=ig(X[I],w);return E===-1?void 0:sg(X[I],E,1)[0]}return va(X[I])},t.removeHooks=function(I){X[I]=[]},t.removeAllHooks=function(){X=Aa()},t}var Vs=Qc();function Oo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var St=Oo();function Yc(e){St=e}var yn={exec:()=>null};function W(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(s,o)=>{let r=typeof o=="string"?o:o.source;return r=r.replace(ue.caret,"$1"),n=n.replace(s,r),i},getRegex:()=>new RegExp(n,t)};return i}var kg=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),ue={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},Sg=/^(?:[ \t]*(?:\n|$))+/,$g=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ag=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,En=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,xg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Fo=/(?:[*+-]|\d{1,9}[.)])/,Jc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Xc=W(Jc).replace(/bull/g,Fo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Eg=W(Jc).replace(/bull/g,Fo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Uo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Cg=/^[^\n]+/,Wo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Tg=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Wo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_g=W(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Fo).getRegex(),Bi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ko=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Mg=W("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ko).replace("tag",Bi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Zc=W(Uo).replace("hr",En).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex(),Pg=W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Zc).getRegex(),zo={blockquote:Pg,code:$g,def:Tg,fences:Ag,heading:xg,hr:En,html:Mg,lheading:Xc,list:_g,newline:Sg,paragraph:Zc,table:yn,text:Cg},xa=W("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",En).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex(),Lg={...zo,lheading:Eg,table:xa,paragraph:W(Uo).replace("hr",En).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",xa).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex()},Ig={...zo,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ko).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:yn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(Uo).replace("hr",En).replace("heading",` *#{1,6} *[^
2262
2262
  ]`).replace("lheading",Xc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Rg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Dg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,eu=/^( {2,}|\\)\n(?!\s*$)/,Bg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ni=/[\p{P}\p{S}]/u,Ho=/[\s\p{P}\p{S}]/u,tu=/[^\s\p{P}\p{S}]/u,Ng=W(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ho).getRegex(),nu=/(?!~)[\p{P}\p{S}]/u,Og=/(?!~)[\s\p{P}\p{S}]/u,Fg=/(?:[^\s\p{P}\p{S}]|~)/u,Ug=W(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",kg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),iu=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Wg=W(iu,"u").replace(/punct/g,Ni).getRegex(),Kg=W(iu,"u").replace(/punct/g,nu).getRegex(),su="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",zg=W(su,"gu").replace(/notPunctSpace/g,tu).replace(/punctSpace/g,Ho).replace(/punct/g,Ni).getRegex(),Hg=W(su,"gu").replace(/notPunctSpace/g,Fg).replace(/punctSpace/g,Og).replace(/punct/g,nu).getRegex(),qg=W("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,tu).replace(/punctSpace/g,Ho).replace(/punct/g,Ni).getRegex(),jg=W(/\\(punct)/,"gu").replace(/punct/g,Ni).getRegex(),Vg=W(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Gg=W(Ko).replace("(?:-->|$)","-->").getRegex(),Qg=W("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Gg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),bi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Yg=W(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",bi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ou=W(/^!?\[(label)\]\[(ref)\]/).replace("label",bi).replace("ref",Wo).getRegex(),ru=W(/^!?\[(ref)\](?:\[\])?/).replace("ref",Wo).getRegex(),Jg=W("reflink|nolink(?!\\()","g").replace("reflink",ou).replace("nolink",ru).getRegex(),Ea=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,qo={_backpedal:yn,anyPunctuation:jg,autolink:Vg,blockSkip:Ug,br:eu,code:Dg,del:yn,emStrongLDelim:Wg,emStrongRDelimAst:zg,emStrongRDelimUnd:qg,escape:Rg,link:Yg,nolink:ru,punctuation:Ng,reflink:ou,reflinkSearch:Jg,tag:Qg,text:Bg,url:yn},Xg={...qo,link:W(/^!?\[(label)\]\((.*?)\)/).replace("label",bi).getRegex(),reflink:W(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",bi).getRegex()},Gs={...qo,emStrongRDelimAst:Hg,emStrongLDelim:Kg,url:W(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Ea).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:W(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Ea).getRegex()},Zg={...Gs,br:W(eu).replace("{2,}","*").getRegex(),text:W(Gs.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Qn={normal:zo,gfm:Lg,pedantic:Ig},rn={normal:qo,gfm:Gs,breaks:Zg,pedantic:Xg},em={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ca=e=>em[e];function Ue(e,t){if(t){if(ue.escapeTest.test(e))return e.replace(ue.escapeReplace,Ca)}else if(ue.escapeTestNoEncode.test(e))return e.replace(ue.escapeReplaceNoEncode,Ca);return e}function Ta(e){try{e=encodeURI(e).replace(ue.percentDecode,"%")}catch{return null}return e}function _a(e,t){var o;let n=e.replace(ue.findPipe,(r,a,u)=>{let c=!1,l=a;for(;--l>=0&&u[l]==="\\";)c=!c;return c?"|":" |"}),i=n.split(ue.splitPipe),s=0;if(i[0].trim()||i.shift(),i.length>0&&!((o=i.at(-1))!=null&&o.trim())&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;s<i.length;s++)i[s]=i[s].trim().replace(ue.slashPipe,"|");return i}function an(e,t,n){let i=e.length;if(i===0)return"";let s=0;for(;s<i&&e.charAt(i-s-1)===t;)s++;return e.slice(0,i-s)}function tm(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])n++;else if(e[i]===t[1]&&(n--,n<0))return i;return n>0?-2:-1}function Ma(e,t,n,i,s){let o=t.href,r=t.title||null,a=e[1].replace(s.other.outputLinkReplace,"$1");i.state.inLink=!0;let u={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:r,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,u}function nm(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2263
2263
  `).map(o=>{let r=o.match(n.other.beginningSpace);if(r===null)return o;let[a]=r;return a.length>=s.length?o.slice(s.length):o}).join(`
2264
2264
  `)}var wi=class{constructor(e){U(this,"options");U(this,"rules");U(this,"lexer");this.options=e||St}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:an(n,`
@@ -2269,21 +2269,21 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=gn(t.
2269
2269
  `),l=c.replace(this.rules.other.blockquoteSetextReplace,`
2270
2270
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
2271
2271
  ${c}`:c,s=s?`${s}
2272
- ${l}`:l;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(l,o,!0),this.lexer.state.top=p,n.length===0)break;let f=o.at(-1);if((f==null?void 0:f.type)==="code")break;if((f==null?void 0:f.type)==="blockquote"){let b=f,h=b.raw+`
2272
+ ${l}`:l;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(l,o,!0),this.lexer.state.top=p,n.length===0)break;let h=o.at(-1);if((h==null?void 0:h.type)==="code")break;if((h==null?void 0:h.type)==="blockquote"){let b=h,f=b.raw+`
2273
2273
  `+n.join(`
2274
- `),v=this.blockquote(h);o[o.length-1]=v,i=i.substring(0,i.length-b.raw.length)+v.raw,s=s.substring(0,s.length-b.text.length)+v.text;break}else if((f==null?void 0:f.type)==="list"){let b=f,h=b.raw+`
2274
+ `),v=this.blockquote(f);o[o.length-1]=v,i=i.substring(0,i.length-b.raw.length)+v.raw,s=s.substring(0,s.length-b.text.length)+v.text;break}else if((h==null?void 0:h.type)==="list"){let b=h,f=b.raw+`
2275
2275
  `+n.join(`
2276
- `),v=this.list(h);o[o.length-1]=v,i=i.substring(0,i.length-f.raw.length)+v.raw,s=s.substring(0,s.length-b.raw.length)+v.raw,n=h.substring(o.at(-1).raw.length).split(`
2277
- `);continue}}return{type:"blockquote",raw:i,tokens:o,text:s}}}list(e){var n,i;let t=this.rules.block.list.exec(e);if(t){let s=t[1].trim(),o=s.length>1,r={type:"list",raw:"",ordered:o,start:o?+s.slice(0,-1):"",loose:!1,items:[]};s=o?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=o?s:"[*+-]");let a=this.rules.other.listItemRegex(s),u=!1;for(;e;){let l=!1,p="",f="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let b=t[2].split(`
2278
- `,1)[0].replace(this.rules.other.listReplaceTabs,$=>" ".repeat(3*$.length)),h=e.split(`
2279
- `,1)[0],v=!b.trim(),k=0;if(this.options.pedantic?(k=2,f=b.trimStart()):v?k=t[1].length+1:(k=t[2].search(this.rules.other.nonSpaceChar),k=k>4?1:k,f=b.slice(k),k+=t[1].length),v&&this.rules.other.blankLine.test(h)&&(p+=h+`
2280
- `,e=e.substring(h.length+1),l=!0),!l){let $=this.rules.other.nextBulletRegex(k),A=this.rules.other.hrRegex(k),C=this.rules.other.fencesBeginRegex(k),T=this.rules.other.headingBeginRegex(k),_=this.rules.other.htmlBeginRegex(k);for(;e;){let R=e.split(`
2281
- `,1)[0],O;if(h=R,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),O=h):O=h.replace(this.rules.other.tabCharGlobal," "),C.test(h)||T.test(h)||_.test(h)||$.test(h)||A.test(h))break;if(O.search(this.rules.other.nonSpaceChar)>=k||!h.trim())f+=`
2282
- `+O.slice(k);else{if(v||b.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||C.test(b)||T.test(b)||A.test(b))break;f+=`
2283
- `+h}!v&&!h.trim()&&(v=!0),p+=R+`
2284
- `,e=e.substring(R.length+1),b=O.slice(k)}}r.loose||(u?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(u=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(f),loose:!1,text:f,tokens:[]}),r.raw+=p}let c=r.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let l of r.items){if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),l.task){if(l.text=l.text.replace(this.rules.other.listReplaceTask,""),((n=l.tokens[0])==null?void 0:n.type)==="text"||((i=l.tokens[0])==null?void 0:i.type)==="paragraph"){l.tokens[0].raw=l.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),l.tokens[0].text=l.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let f={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=f.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=f.raw+l.tokens[0].raw,l.tokens[0].text=f.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(f)):l.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):l.tokens.unshift(f)}}if(!r.loose){let p=l.tokens.filter(b=>b.type==="space"),f=p.length>0&&p.some(b=>this.rules.other.anyLine.test(b.raw));r.loose=f}}if(r.loose)for(let l of r.items){l.loose=!0;for(let p of l.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:i,title:s}}}table(e){var r;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=_a(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=(r=t[3])!=null&&r.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
2276
+ `),v=this.list(f);o[o.length-1]=v,i=i.substring(0,i.length-h.raw.length)+v.raw,s=s.substring(0,s.length-b.raw.length)+v.raw,n=f.substring(o.at(-1).raw.length).split(`
2277
+ `);continue}}return{type:"blockquote",raw:i,tokens:o,text:s}}}list(e){var n,i;let t=this.rules.block.list.exec(e);if(t){let s=t[1].trim(),o=s.length>1,r={type:"list",raw:"",ordered:o,start:o?+s.slice(0,-1):"",loose:!1,items:[]};s=o?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=o?s:"[*+-]");let a=this.rules.other.listItemRegex(s),u=!1;for(;e;){let l=!1,p="",h="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let b=t[2].split(`
2278
+ `,1)[0].replace(this.rules.other.listReplaceTabs,$=>" ".repeat(3*$.length)),f=e.split(`
2279
+ `,1)[0],v=!b.trim(),k=0;if(this.options.pedantic?(k=2,h=b.trimStart()):v?k=t[1].length+1:(k=t[2].search(this.rules.other.nonSpaceChar),k=k>4?1:k,h=b.slice(k),k+=t[1].length),v&&this.rules.other.blankLine.test(f)&&(p+=f+`
2280
+ `,e=e.substring(f.length+1),l=!0),!l){let $=this.rules.other.nextBulletRegex(k),A=this.rules.other.hrRegex(k),C=this.rules.other.fencesBeginRegex(k),T=this.rules.other.headingBeginRegex(k),_=this.rules.other.htmlBeginRegex(k);for(;e;){let R=e.split(`
2281
+ `,1)[0],O;if(f=R,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),O=f):O=f.replace(this.rules.other.tabCharGlobal," "),C.test(f)||T.test(f)||_.test(f)||$.test(f)||A.test(f))break;if(O.search(this.rules.other.nonSpaceChar)>=k||!f.trim())h+=`
2282
+ `+O.slice(k);else{if(v||b.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||C.test(b)||T.test(b)||A.test(b))break;h+=`
2283
+ `+f}!v&&!f.trim()&&(v=!0),p+=R+`
2284
+ `,e=e.substring(R.length+1),b=O.slice(k)}}r.loose||(u?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(u=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),r.raw+=p}let c=r.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let l of r.items){if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),l.task){if(l.text=l.text.replace(this.rules.other.listReplaceTask,""),((n=l.tokens[0])==null?void 0:n.type)==="text"||((i=l.tokens[0])==null?void 0:i.type)==="paragraph"){l.tokens[0].raw=l.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),l.tokens[0].text=l.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let h={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=h.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=h.raw+l.tokens[0].raw,l.tokens[0].text=h.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(h)):l.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):l.tokens.unshift(h)}}if(!r.loose){let p=l.tokens.filter(b=>b.type==="space"),h=p.length>0&&p.some(b=>this.rules.other.anyLine.test(b.raw));r.loose=h}}if(r.loose)for(let l of r.items){l.loose=!0;for(let p of l.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:i,title:s}}}table(e){var r;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=_a(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=(r=t[3])!=null&&r.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
2285
2285
  `):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===i.length){for(let a of i)this.rules.other.tableAlignRight.test(a)?o.align.push("right"):this.rules.other.tableAlignCenter.test(a)?o.align.push("center"):this.rules.other.tableAlignLeft.test(a)?o.align.push("left"):o.align.push(null);for(let a=0;a<n.length;a++)o.header.push({text:n[a],tokens:this.lexer.inline(n[a]),header:!0,align:o.align[a]});for(let a of s)o.rows.push(_a(a,o.header.length).map((u,c)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
2286
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=an(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=tm(t[2],"()");if(o===-2)return;if(o>-1){let r=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,r).trim(),t[3]=""}}let i=t[2],s="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(i);o&&(i=o[1],s=o[3])}else s=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?i=i.slice(1):i=i.slice(1,-1)),Ma(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let i=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[i.toLowerCase()];if(!s){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return Ma(n,s,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||i[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[2])||!n||this.rules.inline.punctuation.exec(n))){let s=[...i[0]].length-1,o,r,a=s,u=0,c=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(i=c.exec(t))!=null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o)continue;if(r=[...o].length,i[3]||i[4]){a+=r;continue}else if((i[5]||i[6])&&s%3&&!((s+r)%3)){u+=r;continue}if(a-=r,a>0)continue;r=Math.min(r,r+a+u);let l=[...i[0]][0].length,p=e.slice(0,s+i.index+l+r);if(Math.min(s,r)%2){let b=p.slice(1,-1);return{type:"em",raw:p,text:b,tokens:this.lexer.inlineTokens(b)}}let f=p.slice(2,-2);return{type:"strong",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,i;return t[2]==="@"?(n=t[1],i="mailto:"+n):(n=t[1],i=n),{type:"link",raw:t[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n;let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=((n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},be=class Qs{constructor(t){U(this,"tokens");U(this,"options");U(this,"state");U(this,"inlineQueue");U(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||St,this.options.tokenizer=this.options.tokenizer||new wi,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:ue,block:Qn.normal,inline:rn.normal};this.options.pedantic?(n.block=Qn.pedantic,n.inline=rn.pedantic):this.options.gfm&&(n.block=Qn.gfm,this.options.breaks?n.inline=rn.breaks:n.inline=rn.gfm),this.tokenizer.rules=n}static get rules(){return{block:Qn,inline:rn}}static lex(t,n){return new Qs(n).lex(t)}static lexInline(t,n){return new Qs(n).inlineTokens(t)}lex(t){t=t.replace(ue.carriageReturn,`
2286
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=an(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=tm(t[2],"()");if(o===-2)return;if(o>-1){let r=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,r).trim(),t[3]=""}}let i=t[2],s="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(i);o&&(i=o[1],s=o[3])}else s=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?i=i.slice(1):i=i.slice(1,-1)),Ma(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let i=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[i.toLowerCase()];if(!s){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return Ma(n,s,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||i[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[2])||!n||this.rules.inline.punctuation.exec(n))){let s=[...i[0]].length-1,o,r,a=s,u=0,c=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(i=c.exec(t))!=null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o)continue;if(r=[...o].length,i[3]||i[4]){a+=r;continue}else if((i[5]||i[6])&&s%3&&!((s+r)%3)){u+=r;continue}if(a-=r,a>0)continue;r=Math.min(r,r+a+u);let l=[...i[0]][0].length,p=e.slice(0,s+i.index+l+r);if(Math.min(s,r)%2){let b=p.slice(1,-1);return{type:"em",raw:p,text:b,tokens:this.lexer.inlineTokens(b)}}let h=p.slice(2,-2);return{type:"strong",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,i;return t[2]==="@"?(n=t[1],i="mailto:"+n):(n=t[1],i=n),{type:"link",raw:t[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n;let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=((n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},be=class Qs{constructor(t){U(this,"tokens");U(this,"options");U(this,"state");U(this,"inlineQueue");U(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||St,this.options.tokenizer=this.options.tokenizer||new wi,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:ue,block:Qn.normal,inline:rn.normal};this.options.pedantic?(n.block=Qn.pedantic,n.inline=rn.pedantic):this.options.gfm&&(n.block=Qn.gfm,this.options.breaks?n.inline=rn.breaks:n.inline=rn.gfm),this.tokenizer.rules=n}static get rules(){return{block:Qn,inline:rn}}static lex(t,n){return new Qs(n).lex(t)}static lexInline(t,n){return new Qs(n).inlineTokens(t)}lex(t){t=t.replace(ue.carriageReturn,`
2287
2287
  `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let i=this.inlineQueue[n];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],i=!1){var s,o,r;for(this.options.pedantic&&(t=t.replace(ue.tabCharGlobal," ").replace(ue.spaceLine,""));t;){let a;if((o=(s=this.options.extensions)==null?void 0:s.block)!=null&&o.some(c=>(a=c.call({lexer:this},t,n))?(t=t.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let c=n.at(-1);a.raw.length===1&&c!==void 0?c.raw+=`
2288
2288
  `:n.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2289
2289
  `)?"":`
@@ -2291,13 +2291,13 @@ ${l}`:l;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
2291
2291
  `+a.text,this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2292
2292
  `)?"":`
2293
2293
  `)+a.raw,c.text+=`
2294
- `+a.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},n.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),n.push(a);continue}let u=t;if((r=this.options.extensions)!=null&&r.startBlock){let c=1/0,l=t.slice(1),p;this.options.extensions.startBlock.forEach(f=>{p=f.call({lexer:this},l),typeof p=="number"&&p>=0&&(c=Math.min(c,p))}),c<1/0&&c>=0&&(u=t.substring(0,c+1))}if(this.state.top&&(a=this.tokenizer.paragraph(u))){let c=n.at(-1);i&&(c==null?void 0:c.type)==="paragraph"?(c.raw+=(c.raw.endsWith(`
2294
+ `+a.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},n.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),n.push(a);continue}let u=t;if((r=this.options.extensions)!=null&&r.startBlock){let c=1/0,l=t.slice(1),p;this.options.extensions.startBlock.forEach(h=>{p=h.call({lexer:this},l),typeof p=="number"&&p>=0&&(c=Math.min(c,p))}),c<1/0&&c>=0&&(u=t.substring(0,c+1))}if(this.state.top&&(a=this.tokenizer.paragraph(u))){let c=n.at(-1);i&&(c==null?void 0:c.type)==="paragraph"?(c.raw+=(c.raw.endsWith(`
2295
2295
  `)?"":`
2296
2296
  `)+a.raw,c.text+=`
2297
2297
  `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a),i=u.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2298
2298
  `)?"":`
2299
2299
  `)+a.raw,c.text+=`
2300
- `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var u,c,l,p,f;let i=t,s=null;if(this.tokens.links){let b=Object.keys(this.tokens.links);if(b.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)b.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(i))!=null;)i=i.slice(0,s.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)o=s[2]?s[2].length:0,i=i.slice(0,s.index+o)+"["+"a".repeat(s[0].length-o-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);i=((c=(u=this.options.hooks)==null?void 0:u.emStrongMask)==null?void 0:c.call({lexer:this},i))??i;let r=!1,a="";for(;t;){r||(a=""),r=!1;let b;if((p=(l=this.options.extensions)==null?void 0:l.inline)!=null&&p.some(v=>(b=v.call({lexer:this},t,n))?(t=t.substring(b.raw.length),n.push(b),!0):!1))continue;if(b=this.tokenizer.escape(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.tag(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.link(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(b.raw.length);let v=n.at(-1);b.type==="text"&&(v==null?void 0:v.type)==="text"?(v.raw+=b.raw,v.text+=b.text):n.push(b);continue}if(b=this.tokenizer.emStrong(t,i,a)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.codespan(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.br(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.del(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.autolink(t)){t=t.substring(b.raw.length),n.push(b);continue}if(!this.state.inLink&&(b=this.tokenizer.url(t))){t=t.substring(b.raw.length),n.push(b);continue}let h=t;if((f=this.options.extensions)!=null&&f.startInline){let v=1/0,k=t.slice(1),$;this.options.extensions.startInline.forEach(A=>{$=A.call({lexer:this},k),typeof $=="number"&&$>=0&&(v=Math.min(v,$))}),v<1/0&&v>=0&&(h=t.substring(0,v+1))}if(b=this.tokenizer.inlineText(h)){t=t.substring(b.raw.length),b.raw.slice(-1)!=="_"&&(a=b.raw.slice(-1)),r=!0;let v=n.at(-1);(v==null?void 0:v.type)==="text"?(v.raw+=b.raw,v.text+=b.text):n.push(b);continue}if(t){let v="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(v);break}else throw new Error(v)}}return n}},ki=class{constructor(e){U(this,"options");U(this,"parser");this.options=e||St}space(e){return""}code({text:e,lang:t,escaped:n}){var o;let i=(o=(t||"").match(ue.notSpaceStart))==null?void 0:o[0],s=e.replace(ue.endingNewline,"")+`
2300
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var u,c,l,p,h;let i=t,s=null;if(this.tokens.links){let b=Object.keys(this.tokens.links);if(b.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)b.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(i))!=null;)i=i.slice(0,s.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)o=s[2]?s[2].length:0,i=i.slice(0,s.index+o)+"["+"a".repeat(s[0].length-o-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);i=((c=(u=this.options.hooks)==null?void 0:u.emStrongMask)==null?void 0:c.call({lexer:this},i))??i;let r=!1,a="";for(;t;){r||(a=""),r=!1;let b;if((p=(l=this.options.extensions)==null?void 0:l.inline)!=null&&p.some(v=>(b=v.call({lexer:this},t,n))?(t=t.substring(b.raw.length),n.push(b),!0):!1))continue;if(b=this.tokenizer.escape(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.tag(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.link(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(b.raw.length);let v=n.at(-1);b.type==="text"&&(v==null?void 0:v.type)==="text"?(v.raw+=b.raw,v.text+=b.text):n.push(b);continue}if(b=this.tokenizer.emStrong(t,i,a)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.codespan(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.br(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.del(t)){t=t.substring(b.raw.length),n.push(b);continue}if(b=this.tokenizer.autolink(t)){t=t.substring(b.raw.length),n.push(b);continue}if(!this.state.inLink&&(b=this.tokenizer.url(t))){t=t.substring(b.raw.length),n.push(b);continue}let f=t;if((h=this.options.extensions)!=null&&h.startInline){let v=1/0,k=t.slice(1),$;this.options.extensions.startInline.forEach(A=>{$=A.call({lexer:this},k),typeof $=="number"&&$>=0&&(v=Math.min(v,$))}),v<1/0&&v>=0&&(f=t.substring(0,v+1))}if(b=this.tokenizer.inlineText(f)){t=t.substring(b.raw.length),b.raw.slice(-1)!=="_"&&(a=b.raw.slice(-1)),r=!0;let v=n.at(-1);(v==null?void 0:v.type)==="text"?(v.raw+=b.raw,v.text+=b.text):n.push(b);continue}if(t){let v="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(v);break}else throw new Error(v)}}return n}},ki=class{constructor(e){U(this,"options");U(this,"parser");this.options=e||St}space(e){return""}code({text:e,lang:t,escaped:n}){var o;let i=(o=(t||"").match(ue.notSpaceStart))==null?void 0:o[0],s=e.replace(ue.endingNewline,"")+`
2301
2301
  `;return i?'<pre><code class="language-'+Ue(i)+'">'+(n?s:Ue(s,!0))+`</code></pre>
2302
2302
  `:"<pre><code>"+(n?s:Ue(s,!0))+`</code></pre>
2303
2303
  `}blockquote({tokens:e}){return`<blockquote>
@@ -2331,7 +2331,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2331
2331
  <span class="chat-copy-btn__icon-check">${D.check}</span>
2332
2332
  </span>
2333
2333
  </button>
2334
- `}function mm(e){return gm({text:()=>e,label:au})}function ym(e){const t=e,n=vm(t.content),i=[];for(const s of n){const o=String(s.type??"").toLowerCase();(["toolcall","tool_call","tooluse","tool_use"].includes(o)||typeof s.name=="string"&&s.arguments!=null)&&i.push({kind:"call",name:s.name??"tool",args:bm(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const r=wm(s),a=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:a,text:r})}if(Ll(e)&&!i.some(s=>s.kind==="result")){const s=typeof t.toolName=="string"&&t.toolName||typeof t.tool_name=="string"&&t.tool_name||"tool",o=Tl(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function vm(e){return Array.isArray(e)?e.filter(Boolean):[]}function bm(e){if(typeof e!="string")return e;const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function wm(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}function km(e){var s;const n=e.content,i=[];if(Array.isArray(n))for(const o of n){if(typeof o!="object"||o===null)continue;const r=o;if(r.type==="image")if(((s=r.source)==null?void 0:s.type)==="base64"){const a=r.source,u=a.data,c=a.media_type||"image/png",l=u.startsWith("data:")?u:`data:${c};base64,${u}`;i.push({url:l})}else if(typeof r.data=="string"&&r.data){const a=r.data,u=r.mimeType||r.media_type||"image/png",c=a.startsWith("data:")?a:`data:${u};base64,${a}`;i.push({url:c})}else typeof r.url=="string"&&i.push({url:r.url});else if(r.type==="image_url"){const a=r.image_url;typeof(a==null?void 0:a.url)=="string"&&i.push({url:a.url})}}return i}function Sm(e){return d`
2334
+ `}function mm(e){return gm({text:()=>e,label:au})}function ym(e){const t=e,n=vm(t.content),i=[];for(const s of n){const o=String(s.type??"").toLowerCase();(["toolcall","tool_call","tooluse","tool_use"].includes(o)||typeof s.name=="string"&&s.arguments!=null)&&i.push({kind:"call",name:s.name??"tool",args:bm(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const r=wm(s),a=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:a,text:r})}if(Ll(e)&&!i.some(s=>s.kind==="result")){const s=typeof t.toolName=="string"&&t.toolName||typeof t.tool_name=="string"&&t.tool_name||"tool",o=Tl(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function vm(e){return Array.isArray(e)?e.filter(Boolean):[]}function bm(e){if(typeof e!="string")return e;const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function wm(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}function km(e){var s;const n=e.content,i=[];if(Array.isArray(n))for(const o of n){if(typeof o!="object"||o===null)continue;const r=o;if(r.type==="image")if(((s=r.source)==null?void 0:s.type)==="base64"){const a=r.source,u=a.data,c=a.media_type||"image/png",l=u.startsWith("data:")?u:`data:${c};base64,${u}`;i.push({url:l})}else if(typeof r.data=="string"&&r.data){const a=r.data,u=r.mimeType||r.media_type||"image/png",c=a.startsWith("data:")?a:`data:${u};base64,${a}`;i.push({url:c})}else typeof r.url=="string"&&i.push({url:r.url});else if(r.type==="image_url"){const a=r.image_url;typeof(a==null?void 0:a.url)=="string"&&i.push({url:a.url})}}return i}function Sm(e){const n=e.content,i=[];if(Array.isArray(n))for(const s of n){if(typeof s!="object"||s===null)continue;const o=s;o.type==="file"&&typeof o.url=="string"&&typeof o.name=="string"&&i.push({url:o.url,name:o.name,mimeType:o.mimeType??"application/octet-stream"})}return i}function $m(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Am(e){return d`
2335
2335
  <div class="chat-group assistant">
2336
2336
  <div class="chat-group-messages">
2337
2337
  <div class="chat-bubble chat-reading-indicator" aria-hidden="true">
@@ -2341,7 +2341,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2341
2341
  </div>
2342
2342
  </div>
2343
2343
  </div>
2344
- `}function $m(e){return d`
2344
+ `}function xm(e){return d`
2345
2345
  <div class="chat-group assistant">
2346
2346
  <div class="chat-group-messages">
2347
2347
  <div class="chat-interim fade-in">
@@ -2349,13 +2349,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2349
2349
  </div>
2350
2350
  </div>
2351
2351
  </div>
2352
- `}function xm(e,t,n,i){return d`
2352
+ `}function Em(e,t,n,i){return d`
2353
2353
  <div class="chat-group assistant">
2354
2354
  <div class="chat-group-messages">
2355
2355
  ${lu({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
2356
2356
  </div>
2357
2357
  </div>
2358
- `}function Am(e,t){const n=Pl(e.role),i=n==="user"?"user":n==="assistant"?"assistant":"other",s=new Date(e.timestamp).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"});return d`
2358
+ `}function Cm(e,t){const n=Pl(e.role),i=n==="user"?"user":n==="assistant"?"assistant":"other",s=new Date(e.timestamp).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"});return d`
2359
2359
  <div class="chat-group ${i}">
2360
2360
  <div class="chat-group-messages">
2361
2361
  ${e.messages.map((o,r)=>lu(o.message,{isStreaming:e.isStreaming&&r===e.messages.length-1,showReasoning:t.showReasoning}))}
@@ -2364,7 +2364,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2364
2364
  </div>
2365
2365
  </div>
2366
2366
  </div>
2367
- `}function Em(e){return e.length===0?S:d`
2367
+ `}function Tm(e){return e.length===0?S:d`
2368
2368
  <div class="chat-message-images">
2369
2369
  ${e.map(t=>d`
2370
2370
  <img
@@ -2375,14 +2375,43 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2375
2375
  />
2376
2376
  `)}
2377
2377
  </div>
2378
- `}function lu(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=Ll(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",a=ym(e).length>0,u=km(e),c=u.length>0,l=Tl(e),p=t.showReasoning&&s==="assistant"?tp(e):null,f=l!=null&&l.trim()?l:null,b=p?ip(p):null,h=f,v=(s==="assistant"||s==="user")&&!!(h!=null&&h.trim()),k=["chat-bubble",v?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!h&&(a||o)||!h&&!c?S:d`
2379
- <div class="${k}">
2380
- ${v?mm(h):S}
2381
- ${Em(u)}
2382
- ${b?d`<div class="chat-thinking">${vi(Si(b))}</div>`:S}
2383
- ${h?d`<div class="chat-text">${vi(Si(h))}</div>`:S}
2384
- </div>
2385
- `}function Cm(e){return d`
2378
+ `}function _m(e){return e.length===0?S:d`
2379
+ <div class="chat-message-files">
2380
+ ${e.map(t=>t.mimeType==="application/pdf"?Mm(t):Pm(t))}
2381
+ </div>
2382
+ `}function Mm(e){return d`
2383
+ <div class="chat-pdf-preview">
2384
+ <iframe
2385
+ src=${e.url}
2386
+ class="chat-pdf-preview__frame"
2387
+ title=${e.name}
2388
+ ></iframe>
2389
+ <a
2390
+ class="chat-pdf-preview__link"
2391
+ href=${e.url}
2392
+ target="_blank"
2393
+ rel="noreferrer noopener"
2394
+ >${e.name}</a>
2395
+ </div>
2396
+ `}function Pm(e){return d`
2397
+ <a
2398
+ class="chat-file-card"
2399
+ href=${e.url}
2400
+ target="_blank"
2401
+ rel="noreferrer noopener"
2402
+ >
2403
+ <span class="chat-file-card__icon">${$m(e.mimeType)}</span>
2404
+ <span class="chat-file-card__name">${e.name}</span>
2405
+ </a>
2406
+ `}function lu(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=Ll(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",a=ym(e).length>0,u=km(e),c=u.length>0,l=Sm(e),p=l.length>0,h=Tl(e),b=t.showReasoning&&s==="assistant"?tp(e):null,f=h!=null&&h.trim()?h:null,v=b?ip(b):null,k=f,$=(s==="assistant"||s==="user")&&!!(k!=null&&k.trim()),A=["chat-bubble",$?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!k&&(a||o)||!k&&!c&&!p?S:d`
2407
+ <div class="${A}">
2408
+ ${$?mm(k):S}
2409
+ ${Tm(u)}
2410
+ ${_m(l)}
2411
+ ${v?d`<div class="chat-thinking">${vi(Si(v))}</div>`:S}
2412
+ ${k?d`<div class="chat-text">${vi(Si(k))}</div>`:S}
2413
+ </div>
2414
+ `}function Lm(e){return d`
2386
2415
  <div class="sidebar-panel">
2387
2416
  <div class="sidebar-header">
2388
2417
  <div class="sidebar-title">Tool Output</div>
@@ -2399,7 +2428,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2399
2428
  `:e.content?d`<div class="sidebar-markdown">${vi(Si(e.content))}</div>`:d`<div class="muted">No content available</div>`}
2400
2429
  </div>
2401
2430
  </div>
2402
- `}var Tm=Object.defineProperty,_m=Object.getOwnPropertyDescriptor,Oi=(e,t,n,i)=>{for(var s=i>1?void 0:i?_m(t,n):t,o=e.length-1,r;o>=0;o--)(r=e[o])&&(s=(i?r(t,n,s):r(s))||s);return i&&s&&Tm(t,n,s),s};let Ot=class extends It{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,s=(e.clientX-this.startX)/n;let o=this.startRatio+s;o=Math.max(this.minRatio,Math.min(this.maxRatio,o)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:o},bubbles:!0,composed:!0}))},this.handleMouseUp=()=>{this.isDragging=!1,this.classList.remove("dragging"),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}render(){return d``}connectedCallback(){super.connectedCallback(),this.addEventListener("mousedown",this.handleMouseDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}};Ot.styles=fd`
2431
+ `}var Im=Object.defineProperty,Rm=Object.getOwnPropertyDescriptor,Oi=(e,t,n,i)=>{for(var s=i>1?void 0:i?Rm(t,n):t,o=e.length-1,r;o>=0;o--)(r=e[o])&&(s=(i?r(t,n,s):r(s))||s);return i&&s&&Im(t,n,s),s};let Ot=class extends It{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,s=(e.clientX-this.startX)/n;let o=this.startRatio+s;o=Math.max(this.minRatio,Math.min(this.maxRatio,o)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:o},bubbles:!0,composed:!0}))},this.handleMouseUp=()=>{this.isDragging=!1,this.classList.remove("dragging"),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}render(){return d``}connectedCallback(){super.connectedCallback(),this.addEventListener("mousedown",this.handleMouseDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}};Ot.styles=fd`
2403
2432
  :host {
2404
2433
  width: 4px;
2405
2434
  cursor: col-resize;
@@ -2425,21 +2454,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2425
2454
  :host(.dragging) {
2426
2455
  background: var(--accent, #007bff);
2427
2456
  }
2428
- `;Oi([Mi({type:Number})],Ot.prototype,"splitRatio",2);Oi([Mi({type:Number})],Ot.prototype,"minRatio",2);Oi([Mi({type:Number})],Ot.prototype,"maxRatio",2);Ot=Oi([bl("resizable-divider")],Ot);function Jn(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function bs(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const Mm=1,Pm=1,$t="emoji",Ft="keyvalue",Vo="favorites",Lm="tokens",cu="tokens",Im="unicode",uu="count",Rm="group",Dm="order",du="group-order",Js="eTag",$i="url",Da="skinTone",jt="readonly",Go="readwrite",pu="skinUnicodes",Bm="skinUnicodes",Nm="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Om="en";function Fm(e,t){const n=new Set,i=[];for(const s of e){const o=t(s);n.has(o)||(n.add(o),i.push(s))}return i}function Ba(e){return Fm(e,t=>t.unicode)}function Um(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[r,[a,u]]of Object.entries(s))o.createIndex(r,a,{multiEntry:u});return o}t(Ft),t($t,Im,{[cu]:[Lm,!0],[du]:[[Rm,Dm]],[pu]:[Bm,!0]}),t(Vo,void 0,{[uu]:[""]})}const Xs={},oi={},xi={};function hu(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function Wm(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,Mm);Xs[e]=s,s.onupgradeneeded=o=>{o.oldVersion<Pm&&Um(s.result)},hu(n,i,s)});return t.onclose=()=>Qo(e),t}function Km(e){return oi[e]||(oi[e]=Wm(e)),oi[e]}function je(e,t,n,i){return new Promise((s,o)=>{const r=e.transaction(t,n,{durability:"relaxed"}),a=typeof t=="string"?r.objectStore(t):t.map(c=>r.objectStore(c));let u;i(a,r,c=>{u=c}),r.oncomplete=()=>s(u),r.onerror=()=>o(r.error)})}function Qo(e){const t=Xs[e],n=t&&t.result;if(n){n.close();const i=xi[e];if(i)for(const s of i)s()}delete Xs[e],delete oi[e],delete xi[e]}function zm(e){return new Promise((t,n)=>{Qo(e);const i=indexedDB.deleteDatabase(e);hu(t,n,i)})}function Hm(e,t){let n=xi[e];n||(n=xi[e]=[]),n.push(t)}const qm=new Set([":D","XD",":'D","O:)",":X",":P",";P","XP",":L",":Z",":j","8D","XO","8)",":B",":O",":S",":'o","Dx","X(","D:",":C",">0)",":3","</3","<3","\\M/",":E","8#"]);function Dt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||qm.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const jm=2;function fu(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=jm)}function Vm(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:r,skins:a,tags:u,emoji:c,version:l})=>{const p=[...new Set(fu([...(r||[]).map(Dt).flat(),...(u||[]).map(Dt).flat(),...Dt(n),i]))].sort(),f={annotation:n,group:s,order:o,tags:u,tokens:p,unicode:c,version:l};if(i&&(f.emoticon=i),r&&(f.shortcodes=r),a){f.skinTones=[],f.skinUnicodes=[],f.skinVersions=[];for(const{tone:b,emoji:h,version:v}of a)f.skinTones.push(b),f.skinUnicodes.push(h),f.skinVersions.push(v)}return f})}function gu(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function bt(e,t,n){gu(e,"get",t,n)}function mu(e,t,n){gu(e,"getAll",t,n)}function Yo(e){e.commit&&e.commit()}function Gm(e,t){let n=e[0];for(let i=1;i<e.length;i++){const s=e[i];t(n)>t(s)&&(n=s)}return n}function yu(e,t){const n=Gm(e,s=>s.length),i=[];for(const s of n)e.some(o=>o.findIndex(r=>t(r)===t(s))===-1)||i.push(s);return i}async function Qm(e){return!await Jo(e,Ft,$i)}async function Ym(e,t,n){const[i,s]=await Promise.all([Js,$i].map(o=>Jo(e,Ft,o)));return i===n&&s===t}async function Jm(e,t){return je(e,$t,jt,(i,s,o)=>{let r;const a=()=>{i.getAll(r&&IDBKeyRange.lowerBound(r,!0),50).onsuccess=u=>{const c=u.target.result;for(const l of c)if(r=l.unicode,t(l))return o(l);if(c.length<50)return o();a()}};a()})}async function vu(e,t,n,i){{const s=Vm(t);await je(e,[$t,Ft],Go,([o,r],a)=>{let u,c,l=0;function p(){++l===2&&f()}function f(){if(!(u===i&&c===n)){o.clear();for(const b of s)o.put(b);r.put(i,Js),r.put(n,$i),Yo(a)}}bt(r,Js,b=>{u=b,p()}),bt(r,$i,b=>{c=b,p()})})}}async function Xm(e,t){return je(e,$t,jt,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);mu(n.index(du),o,s)})}async function bu(e,t){const n=fu(Dt(t));return n.length?je(e,$t,jt,(i,s,o)=>{const r=[],a=()=>{r.length===n.length&&u()},u=()=>{const c=yu(r,l=>l.unicode);o(c.sort((l,p)=>l.order<p.order?-1:1))};for(let c=0;c<n.length;c++){const l=n[c],p=c===n.length-1?IDBKeyRange.bound(l,l+"￿",!1,!0):IDBKeyRange.only(l);mu(i.index(cu),p,f=>{r.push(f),a()})}}):[]}async function Zm(e,t){const n=await bu(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await Jm(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function ey(e,t){return je(e,$t,jt,(n,i,s)=>bt(n,t,o=>{if(o)return s(o);bt(n.index(pu),t,r=>s(r||null))}))}function Jo(e,t,n){return je(e,t,jt,(i,s,o)=>bt(i,n,o))}function ty(e,t,n,i){return je(e,t,Go,(s,o)=>{s.put(i,n),Yo(o)})}function ny(e,t){return je(e,Vo,Go,(n,i)=>bt(n,t,s=>{n.put((s||0)+1,t),Yo(i)}))}function iy(e,t,n){return n===0?[]:je(e,[Vo,$t],jt,([i,s],o,r)=>{const a=[];i.index(uu).openCursor(void 0,"prev").onsuccess=u=>{const c=u.target.result;if(!c)return r(a);function l(b){if(a.push(b),a.length===n)return r(a);c.continue()}const p=c.primaryKey,f=t.byName(p);if(f)return l(f);bt(s,p,b=>{if(b)return l(b);c.continue()})}})}const Xn="";function sy(e,t){const n=new Map;for(const s of e){const o=t(s);for(const r of o){let a=n;for(let c=0;c<r.length;c++){const l=r.charAt(c);let p=a.get(l);p||(p=new Map,a.set(l,p)),a=p}let u=a.get(Xn);u||(u=[],a.set(Xn,u)),u.push(s)}}return(s,o)=>{let r=n;for(let c=0;c<s.length;c++){const l=s.charAt(c),p=r.get(l);if(p)r=p;else return[]}if(o)return r.get(Xn)||[];const a=[],u=[r];for(;u.length;){const l=[...u.shift().entries()].sort((p,f)=>p[0]<f[0]?-1:1);for(const[p,f]of l)p===Xn?a.push(...f):u.push(f)}return a}}const oy=["name","url"];function ry(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||oy.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function Na(e){ry(e);const t=(f,b)=>f.name.toLowerCase()<b.name.toLowerCase()?-1:1,n=e.sort(t),s=sy(e,f=>{const b=new Set;if(f.shortcodes)for(const h of f.shortcodes)for(const v of Dt(h))b.add(v);return b}),o=f=>s(f,!0),r=f=>s(f,!1),a=f=>{const b=Dt(f),h=b.map((v,k)=>(k<b.length-1?o:r)(v));return yu(h,v=>v.name).sort(t)},u=new Map,c=new Map;for(const f of e){c.set(f.name.toLowerCase(),f);for(const b of f.shortcodes||[])u.set(b.toLowerCase(),f)}return{all:n,search:a,byShortcode:f=>u.get(f.toLowerCase()),byName:f=>c.get(f.toLowerCase())}}const ay=typeof wrappedJSObject<"u";function ln(e){if(!e)return e;if(ay&&(e=structuredClone(e)),delete e.tokens,e.skinTones){const t=e.skinTones.length;e.skins=Array(t);for(let n=0;n<t;n++)e.skins[n]={tone:e.skinTones[n],unicode:e.skinUnicodes[n],version:e.skinVersions[n]};delete e.skinTones,delete e.skinUnicodes,delete e.skinVersions}return e}function wu(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const ly=["annotation","emoji","group","order","version"];function cy(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||ly.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function ku(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function uy(e){const t=await fetch(e,{method:"HEAD"});ku(t,e);const n=t.headers.get("etag");return wu(n),n}async function Zs(e){const t=await fetch(e);ku(t,e);const n=t.headers.get("etag");wu(n);const i=await t.json();return cy(i),[n,i]}function dy(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function py(e){for(var t=e.length,n=new ArrayBuffer(t),i=new Uint8Array(n),s=-1;++s<t;)i[s]=e.charCodeAt(s);return n}async function Su(e){const t=JSON.stringify(e);let n=py(t);const i=await crypto.subtle.digest("SHA-1",n),s=dy(i);return btoa(s)}async function hy(e,t){let n,i=await uy(t);if(!i){const s=await Zs(t);i=s[0],n=s[1],i||(i=await Su(n))}await Ym(e,t,i)||(n||(n=(await Zs(t))[1]),await vu(e,n,t,i))}async function fy(e,t){let[n,i]=await Zs(t);n||(n=await Su(i)),await vu(e,i,t,n)}async function gy(e,t){try{await hy(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class my{constructor({dataSource:t=Nm,locale:n=Om,customEmoji:i=[]}={}){this.dataSource=t,this.locale=n,this._dbName=`emoji-picker-element-${this.locale}`,this._db=void 0,this._lazyUpdate=void 0,this._custom=Na(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await Km(this._dbName);Hm(this._dbName,this._clear);const n=this.dataSource;await Qm(t)?await fy(t,n):this._lazyUpdate=gy(t,n)}async ready(){const t=async()=>(this._ready||(this._ready=this._init()),this._ready);await t(),this._db||await t()}async getEmojiByGroup(t){return bs(t),await this.ready(),Ba(await Xm(this._db,t)).map(ln)}async getEmojiBySearchQuery(t){Jn(t),await this.ready();const n=this._custom.search(t),i=Ba(await bu(this._db,t)).map(ln);return[...n,...i]}async getEmojiByShortcode(t){Jn(t),await this.ready();const n=this._custom.byShortcode(t);return n||ln(await Zm(this._db,t))}async getEmojiByUnicodeOrName(t){Jn(t),await this.ready();const n=this._custom.byName(t);return n||ln(await ey(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Jo(this._db,Ft,Da)||0}async setPreferredSkinTone(t){return bs(t),await this.ready(),ty(this._db,Ft,Da,t)}async incrementFavoriteEmojiCount(t){return Jn(t),await this.ready(),ny(this._db,t)}async getTopFavoriteEmoji(t){return bs(t),await this.ready(),(await iy(this._db,this._custom,t)).map(ln)}set customEmoji(t){this._custom=Na(t)}get customEmoji(){return this._custom.all}async _shutdown(){await this.ready();try{await this._lazyUpdate}catch{}}_clear(){this._db=this._ready=this._lazyUpdate=void 0}async close(){await this._shutdown(),await Qo(this._dbName)}async delete(){await this._shutdown(),await zm(this._dbName)}}const eo=[[-1,"✨","custom"],[0,"😀","smileys-emotion"],[1,"👋","people-body"],[3,"🐱","animals-nature"],[4,"🍎","food-drink"],[5,"🏠️","travel-places"],[6,"⚽","activities"],[7,"📝","objects"],[8,"⛔️","symbols"],[9,"🏁","flags"]].map(([e,t,n])=>({id:e,emoji:t,name:n})),ws=eo.slice(1),yy=2,Oa=6,$u=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function Fa(e){return e.unicode.includes("‍")}const vy={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},by=1e3,wy="🖐️",ky=8,Sy=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],xu='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',$y=(e,t)=>e<t?-1:e>t?1:0,Ua=(e,t)=>{const n=document.createElement("canvas");n.width=n.height=1;const i=n.getContext("2d",{willReadFrequently:!0});return i.textBaseline="top",i.font=`100px ${xu}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},xy=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function Ay(e){const t=Ua(e,"#000"),n=Ua(e,"#fff");return t&&n&&xy(t,n)}function Ey(){const e=Object.entries(vy);try{for(const[t,n]of e)if(Ay(t))return n}catch{}return e[0][1]}let ks;const Ss=()=>(ks||(ks=new Promise(e=>$u(()=>e(Ey())))),ks),to=new Map,Cy="️",Ty="\uD83C",_y="‍",My=127995,Py=57339;function Ly(e,t){if(t===0)return e;const n=e.indexOf(_y);return n!==-1?e.substring(0,n)+String.fromCodePoint(My+t-1)+e.substring(n):(e.endsWith(Cy)&&(e=e.substring(0,e.length-1)),e+Ty+String.fromCodePoint(Py+t-1))}function Ce(e){e.preventDefault(),e.stopPropagation()}function $s(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function Au(e,t){const n=new Set,i=[];for(const s of e){const o=t(s);n.has(o)||(n.add(o),i.push(s))}return i}function Iy(e,t){const n=i=>{const s={};for(const o of i)typeof o.tone=="number"&&o.version<=t&&(s[o.tone]=o.unicode);return s};return e.map(({unicode:i,skins:s,shortcodes:o,url:r,name:a,category:u,annotation:c})=>({unicode:i,name:a,shortcodes:o,url:r,category:u,annotation:c,id:i||a,skins:s&&n(s)}))}const ri=requestAnimationFrame;let Ry=typeof ResizeObserver=="function";function Dy(e,t,n){let i;Ry?(i=new ResizeObserver(n),i.observe(e)):ri(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function Wa(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let xs;function By(e,t,n){let i=!0,s=!1;for(const o of e){const r=n(o);if(!r)continue;const a=Wa(r);a===0&&(s=!0),typeof xs>"u"&&(xs=Wa(t));const u=a/1.8<xs;to.set(o.unicode,u),u||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
2457
+ `;Oi([Mi({type:Number})],Ot.prototype,"splitRatio",2);Oi([Mi({type:Number})],Ot.prototype,"minRatio",2);Oi([Mi({type:Number})],Ot.prototype,"maxRatio",2);Ot=Oi([bl("resizable-divider")],Ot);function Jn(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function bs(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const Dm=1,Bm=1,$t="emoji",Ft="keyvalue",Vo="favorites",Nm="tokens",cu="tokens",Om="unicode",uu="count",Fm="group",Um="order",du="group-order",Js="eTag",$i="url",Da="skinTone",jt="readonly",Go="readwrite",pu="skinUnicodes",Wm="skinUnicodes",Km="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",zm="en";function Hm(e,t){const n=new Set,i=[];for(const s of e){const o=t(s);n.has(o)||(n.add(o),i.push(s))}return i}function Ba(e){return Hm(e,t=>t.unicode)}function qm(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[r,[a,u]]of Object.entries(s))o.createIndex(r,a,{multiEntry:u});return o}t(Ft),t($t,Om,{[cu]:[Nm,!0],[du]:[[Fm,Um]],[pu]:[Wm,!0]}),t(Vo,void 0,{[uu]:[""]})}const Xs={},oi={},Ai={};function hu(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function jm(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,Dm);Xs[e]=s,s.onupgradeneeded=o=>{o.oldVersion<Bm&&qm(s.result)},hu(n,i,s)});return t.onclose=()=>Qo(e),t}function Vm(e){return oi[e]||(oi[e]=jm(e)),oi[e]}function je(e,t,n,i){return new Promise((s,o)=>{const r=e.transaction(t,n,{durability:"relaxed"}),a=typeof t=="string"?r.objectStore(t):t.map(c=>r.objectStore(c));let u;i(a,r,c=>{u=c}),r.oncomplete=()=>s(u),r.onerror=()=>o(r.error)})}function Qo(e){const t=Xs[e],n=t&&t.result;if(n){n.close();const i=Ai[e];if(i)for(const s of i)s()}delete Xs[e],delete oi[e],delete Ai[e]}function Gm(e){return new Promise((t,n)=>{Qo(e);const i=indexedDB.deleteDatabase(e);hu(t,n,i)})}function Qm(e,t){let n=Ai[e];n||(n=Ai[e]=[]),n.push(t)}const Ym=new Set([":D","XD",":'D","O:)",":X",":P",";P","XP",":L",":Z",":j","8D","XO","8)",":B",":O",":S",":'o","Dx","X(","D:",":C",">0)",":3","</3","<3","\\M/",":E","8#"]);function Dt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||Ym.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const Jm=2;function fu(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=Jm)}function Xm(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:r,skins:a,tags:u,emoji:c,version:l})=>{const p=[...new Set(fu([...(r||[]).map(Dt).flat(),...(u||[]).map(Dt).flat(),...Dt(n),i]))].sort(),h={annotation:n,group:s,order:o,tags:u,tokens:p,unicode:c,version:l};if(i&&(h.emoticon=i),r&&(h.shortcodes=r),a){h.skinTones=[],h.skinUnicodes=[],h.skinVersions=[];for(const{tone:b,emoji:f,version:v}of a)h.skinTones.push(b),h.skinUnicodes.push(f),h.skinVersions.push(v)}return h})}function gu(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function bt(e,t,n){gu(e,"get",t,n)}function mu(e,t,n){gu(e,"getAll",t,n)}function Yo(e){e.commit&&e.commit()}function Zm(e,t){let n=e[0];for(let i=1;i<e.length;i++){const s=e[i];t(n)>t(s)&&(n=s)}return n}function yu(e,t){const n=Zm(e,s=>s.length),i=[];for(const s of n)e.some(o=>o.findIndex(r=>t(r)===t(s))===-1)||i.push(s);return i}async function ey(e){return!await Jo(e,Ft,$i)}async function ty(e,t,n){const[i,s]=await Promise.all([Js,$i].map(o=>Jo(e,Ft,o)));return i===n&&s===t}async function ny(e,t){return je(e,$t,jt,(i,s,o)=>{let r;const a=()=>{i.getAll(r&&IDBKeyRange.lowerBound(r,!0),50).onsuccess=u=>{const c=u.target.result;for(const l of c)if(r=l.unicode,t(l))return o(l);if(c.length<50)return o();a()}};a()})}async function vu(e,t,n,i){{const s=Xm(t);await je(e,[$t,Ft],Go,([o,r],a)=>{let u,c,l=0;function p(){++l===2&&h()}function h(){if(!(u===i&&c===n)){o.clear();for(const b of s)o.put(b);r.put(i,Js),r.put(n,$i),Yo(a)}}bt(r,Js,b=>{u=b,p()}),bt(r,$i,b=>{c=b,p()})})}}async function iy(e,t){return je(e,$t,jt,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);mu(n.index(du),o,s)})}async function bu(e,t){const n=fu(Dt(t));return n.length?je(e,$t,jt,(i,s,o)=>{const r=[],a=()=>{r.length===n.length&&u()},u=()=>{const c=yu(r,l=>l.unicode);o(c.sort((l,p)=>l.order<p.order?-1:1))};for(let c=0;c<n.length;c++){const l=n[c],p=c===n.length-1?IDBKeyRange.bound(l,l+"￿",!1,!0):IDBKeyRange.only(l);mu(i.index(cu),p,h=>{r.push(h),a()})}}):[]}async function sy(e,t){const n=await bu(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await ny(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function oy(e,t){return je(e,$t,jt,(n,i,s)=>bt(n,t,o=>{if(o)return s(o);bt(n.index(pu),t,r=>s(r||null))}))}function Jo(e,t,n){return je(e,t,jt,(i,s,o)=>bt(i,n,o))}function ry(e,t,n,i){return je(e,t,Go,(s,o)=>{s.put(i,n),Yo(o)})}function ay(e,t){return je(e,Vo,Go,(n,i)=>bt(n,t,s=>{n.put((s||0)+1,t),Yo(i)}))}function ly(e,t,n){return n===0?[]:je(e,[Vo,$t],jt,([i,s],o,r)=>{const a=[];i.index(uu).openCursor(void 0,"prev").onsuccess=u=>{const c=u.target.result;if(!c)return r(a);function l(b){if(a.push(b),a.length===n)return r(a);c.continue()}const p=c.primaryKey,h=t.byName(p);if(h)return l(h);bt(s,p,b=>{if(b)return l(b);c.continue()})}})}const Xn="";function cy(e,t){const n=new Map;for(const s of e){const o=t(s);for(const r of o){let a=n;for(let c=0;c<r.length;c++){const l=r.charAt(c);let p=a.get(l);p||(p=new Map,a.set(l,p)),a=p}let u=a.get(Xn);u||(u=[],a.set(Xn,u)),u.push(s)}}return(s,o)=>{let r=n;for(let c=0;c<s.length;c++){const l=s.charAt(c),p=r.get(l);if(p)r=p;else return[]}if(o)return r.get(Xn)||[];const a=[],u=[r];for(;u.length;){const l=[...u.shift().entries()].sort((p,h)=>p[0]<h[0]?-1:1);for(const[p,h]of l)p===Xn?a.push(...h):u.push(h)}return a}}const uy=["name","url"];function dy(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||uy.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function Na(e){dy(e);const t=(h,b)=>h.name.toLowerCase()<b.name.toLowerCase()?-1:1,n=e.sort(t),s=cy(e,h=>{const b=new Set;if(h.shortcodes)for(const f of h.shortcodes)for(const v of Dt(f))b.add(v);return b}),o=h=>s(h,!0),r=h=>s(h,!1),a=h=>{const b=Dt(h),f=b.map((v,k)=>(k<b.length-1?o:r)(v));return yu(f,v=>v.name).sort(t)},u=new Map,c=new Map;for(const h of e){c.set(h.name.toLowerCase(),h);for(const b of h.shortcodes||[])u.set(b.toLowerCase(),h)}return{all:n,search:a,byShortcode:h=>u.get(h.toLowerCase()),byName:h=>c.get(h.toLowerCase())}}const py=typeof wrappedJSObject<"u";function ln(e){if(!e)return e;if(py&&(e=structuredClone(e)),delete e.tokens,e.skinTones){const t=e.skinTones.length;e.skins=Array(t);for(let n=0;n<t;n++)e.skins[n]={tone:e.skinTones[n],unicode:e.skinUnicodes[n],version:e.skinVersions[n]};delete e.skinTones,delete e.skinUnicodes,delete e.skinVersions}return e}function wu(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const hy=["annotation","emoji","group","order","version"];function fy(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||hy.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function ku(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function gy(e){const t=await fetch(e,{method:"HEAD"});ku(t,e);const n=t.headers.get("etag");return wu(n),n}async function Zs(e){const t=await fetch(e);ku(t,e);const n=t.headers.get("etag");wu(n);const i=await t.json();return fy(i),[n,i]}function my(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function yy(e){for(var t=e.length,n=new ArrayBuffer(t),i=new Uint8Array(n),s=-1;++s<t;)i[s]=e.charCodeAt(s);return n}async function Su(e){const t=JSON.stringify(e);let n=yy(t);const i=await crypto.subtle.digest("SHA-1",n),s=my(i);return btoa(s)}async function vy(e,t){let n,i=await gy(t);if(!i){const s=await Zs(t);i=s[0],n=s[1],i||(i=await Su(n))}await ty(e,t,i)||(n||(n=(await Zs(t))[1]),await vu(e,n,t,i))}async function by(e,t){let[n,i]=await Zs(t);n||(n=await Su(i)),await vu(e,i,t,n)}async function wy(e,t){try{await vy(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class ky{constructor({dataSource:t=Km,locale:n=zm,customEmoji:i=[]}={}){this.dataSource=t,this.locale=n,this._dbName=`emoji-picker-element-${this.locale}`,this._db=void 0,this._lazyUpdate=void 0,this._custom=Na(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await Vm(this._dbName);Qm(this._dbName,this._clear);const n=this.dataSource;await ey(t)?await by(t,n):this._lazyUpdate=wy(t,n)}async ready(){const t=async()=>(this._ready||(this._ready=this._init()),this._ready);await t(),this._db||await t()}async getEmojiByGroup(t){return bs(t),await this.ready(),Ba(await iy(this._db,t)).map(ln)}async getEmojiBySearchQuery(t){Jn(t),await this.ready();const n=this._custom.search(t),i=Ba(await bu(this._db,t)).map(ln);return[...n,...i]}async getEmojiByShortcode(t){Jn(t),await this.ready();const n=this._custom.byShortcode(t);return n||ln(await sy(this._db,t))}async getEmojiByUnicodeOrName(t){Jn(t),await this.ready();const n=this._custom.byName(t);return n||ln(await oy(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Jo(this._db,Ft,Da)||0}async setPreferredSkinTone(t){return bs(t),await this.ready(),ry(this._db,Ft,Da,t)}async incrementFavoriteEmojiCount(t){return Jn(t),await this.ready(),ay(this._db,t)}async getTopFavoriteEmoji(t){return bs(t),await this.ready(),(await ly(this._db,this._custom,t)).map(ln)}set customEmoji(t){this._custom=Na(t)}get customEmoji(){return this._custom.all}async _shutdown(){await this.ready();try{await this._lazyUpdate}catch{}}_clear(){this._db=this._ready=this._lazyUpdate=void 0}async close(){await this._shutdown(),await Qo(this._dbName)}async delete(){await this._shutdown(),await Gm(this._dbName)}}const eo=[[-1,"✨","custom"],[0,"😀","smileys-emotion"],[1,"👋","people-body"],[3,"🐱","animals-nature"],[4,"🍎","food-drink"],[5,"🏠️","travel-places"],[6,"⚽","activities"],[7,"📝","objects"],[8,"⛔️","symbols"],[9,"🏁","flags"]].map(([e,t,n])=>({id:e,emoji:t,name:n})),ws=eo.slice(1),Sy=2,Oa=6,$u=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function Fa(e){return e.unicode.includes("‍")}const $y={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},Ay=1e3,xy="🖐️",Ey=8,Cy=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],Au='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',Ty=(e,t)=>e<t?-1:e>t?1:0,Ua=(e,t)=>{const n=document.createElement("canvas");n.width=n.height=1;const i=n.getContext("2d",{willReadFrequently:!0});return i.textBaseline="top",i.font=`100px ${Au}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},_y=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function My(e){const t=Ua(e,"#000"),n=Ua(e,"#fff");return t&&n&&_y(t,n)}function Py(){const e=Object.entries($y);try{for(const[t,n]of e)if(My(t))return n}catch{}return e[0][1]}let ks;const Ss=()=>(ks||(ks=new Promise(e=>$u(()=>e(Py())))),ks),to=new Map,Ly="️",Iy="\uD83C",Ry="‍",Dy=127995,By=57339;function Ny(e,t){if(t===0)return e;const n=e.indexOf(Ry);return n!==-1?e.substring(0,n)+String.fromCodePoint(Dy+t-1)+e.substring(n):(e.endsWith(Ly)&&(e=e.substring(0,e.length-1)),e+Iy+String.fromCodePoint(By+t-1))}function Ce(e){e.preventDefault(),e.stopPropagation()}function $s(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function xu(e,t){const n=new Set,i=[];for(const s of e){const o=t(s);n.has(o)||(n.add(o),i.push(s))}return i}function Oy(e,t){const n=i=>{const s={};for(const o of i)typeof o.tone=="number"&&o.version<=t&&(s[o.tone]=o.unicode);return s};return e.map(({unicode:i,skins:s,shortcodes:o,url:r,name:a,category:u,annotation:c})=>({unicode:i,name:a,shortcodes:o,url:r,category:u,annotation:c,id:i||a,skins:s&&n(s)}))}const ri=requestAnimationFrame;let Fy=typeof ResizeObserver=="function";function Uy(e,t,n){let i;Fy?(i=new ResizeObserver(n),i.observe(e)):ri(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function Wa(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let As;function Wy(e,t,n){let i=!0,s=!1;for(const o of e){const r=n(o);if(!r)continue;const a=Wa(r);a===0&&(s=!0),typeof As>"u"&&(As=Wa(t));const u=a/1.8<As;to.set(o.unicode,u),u||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
2429
2458
  This is likely due to using \`display:none\` which is unsupported.
2430
2459
  If this is a Jest/Vitest environment, you can ignore this warning.
2431
- For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function Ny(e){return Au(e,t=>t)}function Oy(e){e&&(e.scrollTop=0)}function vn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function Ka(e){return""+e}function Fy(e){const t=document.createElement("template");return t.innerHTML=e,t}const Uy=new WeakMap,Wy=new WeakMap,Ky=Symbol("un-keyed"),zy="replaceChildren"in Element.prototype;function Hy(e,t){zy?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function qy(e,t){let n=e.firstChild,i=0;for(;n;){if(t[i]!==n)return!0;n=n.nextSibling,i++}return i!==t.length}function jy(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=qy(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&Hy(i,e)}function Vy(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:r,attributeValuePre:a,attributeValuePost:u}}=n,c=e[o];if(s!==c)if(n.currentExpression=c,r)if(c===null)i.removeAttribute(r);else{const l=a+Ka(c)+u;i.setAttribute(r,l)}else{let l;Array.isArray(c)?jy(c,n):c instanceof Element?(l=c,i.replaceWith(l)):i.nodeValue=Ka(c),l&&(n.targetNode=l)}}}function Gy(e){let t="",n=!1,i=!1,s=-1;const o=new Map,r=[];let a=0;for(let c=0,l=e.length;c<l;c++){const p=e[c];if(t+=p.slice(a),c===l-1)break;for(let A=0;A<p.length;A++)switch(p.charAt(A)){case"<":{p.charAt(A+1)==="/"?r.pop():(n=!0,r.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const f=r[r.length-1],b=vn(o,f,()=>[]);let h,v,k;if(i){const A=/(\S+)="?([^"=]*)$/.exec(p);h=A[1],v=A[2];const C=/^([^">]*)("?)/.exec(e[c+1]);k=C[1],t=t.slice(0,-1*A[0].length),a=C[0].length}else a=0;const $={attributeName:h,attributeValuePre:v,attributeValuePost:k,expressionIndex:c};b.push($),!n&&!i&&(t+=" ")}return{template:Fy(t),elementsToBindings:o}}function za(e,t,n){for(let i=0;i<e.length;i++){const s=e[i],o=s.attributeName?t:t.firstChild,r={binding:s,targetNode:o,targetParentNode:void 0,currentExpression:void 0};n.push(r)}}function Qy(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))za(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,r=-1;do{const a=t.get(++r);a&&za(a,o,n)}while(o=s.nextNode())}return n}function Yy(e){const{template:t,elementsToBindings:n}=vn(Uy,e,()=>Gy(e)),i=t.cloneNode(!0).content.firstElementChild,s=Qy(i,n);return function(r){return Vy(r,s),i}}function Jy(e){const t=vn(Wy,e,()=>new Map);let n=Ky;function i(o,...r){const a=vn(t,o,()=>new Map);return vn(a,n,()=>Yy(o))(r)}function s(o,r,a){return o.map((u,c)=>{const l=n;n=a(u);try{return r(u,c)}finally{n=l}})}return{map:s,html:i}}function Xy(e,t,n,i,s,o,r,a,u){const{labelWithSkin:c,titleForEmoji:l,unicodeWithSkin:p}=n,{html:f,map:b}=Jy(t);function h(A,C,T){return b(A,(_,R)=>f`<button role="${C?"option":"menuitem"}" aria-selected="${C?R===t.activeSearchItem:null}" aria-label="${c(_,t.currentSkinTone)}" title="${l(_)}" class="${"emoji"+(C&&R===t.activeSearchItem?" active":"")+(_.unicode?"":" custom-emoji")}" id="${`${T}-${_.id}`}" style="${_.unicode?null:`--custom-emoji-background: url(${JSON.stringify(_.url)})`}">${_.unicode?p(_,t.currentSkinTone):""}</button>`,_=>`${T}-${_.id}`)}const k=f`<section data-ref="rootElement" class="picker" aria-label="${t.i18n.regionLabel}" style="${t.pickerStyle||""}"><div class="pad-top"></div><div class="search-row"><div class="search-wrapper"><input id="search" class="search" type="search" role="combobox" enterkeyhint="search" placeholder="${t.i18n.searchLabel}" autocapitalize="none" autocomplete="off" spellcheck="true" aria-expanded="${!!(t.searchMode&&t.currentEmojis.length)}" aria-controls="search-results" aria-describedby="search-description" aria-autocomplete="list" aria-activedescendant="${t.activeSearchItemId?`emo-${t.activeSearchItemId}`:null}" data-ref="searchElement" data-on-input="onSearchInput" data-on-keydown="onSearchKeydown"><label class="sr-only" for="search">${t.i18n.searchLabel}</label> <span id="search-description" class="sr-only">${t.i18n.searchDescription}</span></div><div class="skintone-button-wrapper ${t.skinTonePickerExpandedAfterAnimation?"expanded":""}"><button id="skintone-button" class="emoji ${t.skinTonePickerExpanded?"hide-focus":""}" aria-label="${t.skinToneButtonLabel}" title="${t.skinToneButtonLabel}" aria-describedby="skintone-description" aria-haspopup="listbox" aria-expanded="${t.skinTonePickerExpanded}" aria-controls="skintone-list" data-on-click="onClickSkinToneButton">${t.skinToneButtonText||""}</button></div><span id="skintone-description" class="sr-only">${t.i18n.skinToneDescription}</span><div data-ref="skinToneDropdown" id="skintone-list" class="skintone-list hide-focus ${t.skinTonePickerExpanded?"":"hidden no-animate"}" style="transform:translateY(${t.skinTonePickerExpanded?0:"calc(-1 * var(--num-skintones) * var(--total-emoji-size))"})" role="listbox" aria-label="${t.i18n.skinTonesLabel}" aria-activedescendant="skintone-${t.activeSkinTone}" aria-hidden="${!t.skinTonePickerExpanded}" tabIndex="-1" data-on-focusout="onSkinToneOptionsFocusOut" data-on-click="onSkinToneOptionsClick" data-on-keydown="onSkinToneOptionsKeydown" data-on-keyup="onSkinToneOptionsKeyup">${b(t.skinTones,(A,C)=>f`<div id="skintone-${C}" class="emoji ${C===t.activeSkinTone?"active":""}" aria-selected="${C===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[C]}" aria-label="${t.i18n.skinTones[C]}">${A}</div>`,A=>A)}</div></div><div class="nav" role="tablist" style="grid-template-columns:repeat(${t.groups.length},1fr)" aria-label="${t.i18n.categoriesLabel}" data-on-keydown="onNavKeydown" data-on-click="onNavClick">${b(t.groups,A=>f`<button role="tab" class="nav-button" aria-controls="tab-${A.id}" aria-label="${t.i18n.categories[A.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===A.id}" title="${t.i18n.categories[A.name]}" data-group-id="${A.id}"><div class="nav-emoji emoji">${A.emoji}</div></button>`,A=>A.id)}</div><div class="indicator-wrapper"><div class="indicator" style="transform:translateX(${(t.isRtl?-1:1)*t.currentGroupIndex*100}%)"></div></div><div class="message ${t.message?"":"gone"}" role="alert" aria-live="polite">${t.message||""}</div><div data-ref="tabpanelElement" class="tabpanel ${!t.databaseLoaded||t.message?"gone":""}" role="${t.searchMode?"region":"tabpanel"}" aria-label="${t.searchMode?t.i18n.searchResultsLabel:t.i18n.categories[t.currentGroup.name]}" id="${t.searchMode?null:`tab-${t.currentGroup.id}`}" tabIndex="0" data-on-click="onEmojiClick"><div data-action="calculateEmojiGridStyle">${b(t.currentEmojisWithCategories,(A,C)=>f`<div><div id="menu-label-${C}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:A.category?A.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${C!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(A.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${C}" id="${t.searchMode?"search-results":null}">${h(A.emojis,t.searchMode,"emo")}</div></div>`,A=>A.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${h(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,$=(A,C)=>{for(const T of e.querySelectorAll(`[${A}]`))C(T,T.getAttribute(A))};if(u){e.appendChild(k);for(const A of["click","focusout","input","keydown","keyup"])$(`data-on-${A}`,(C,T)=>{C.addEventListener(A,i[T])});$("data-ref",(A,C)=>{o[C]=A}),r.addEventListener("abort",()=>{e.removeChild(k)})}$("data-action",(A,C)=>{let T=a.get(C);T||a.set(C,T=new WeakSet),T.has(A)||(T.add(A),s[C](A))})}const Ai=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function Zy(e){let t=!1,n;const i=new Map,s=new Set;let o;const r=()=>{if(t)return;const c=[...s];s.clear();try{for(const l of c)l()}finally{o=!1,s.size&&(o=!0,Ai(r))}},a=new Proxy({},{get(c,l){if(n){let p=i.get(l);p||(p=new Set,i.set(l,p)),p.add(n)}return c[l]},set(c,l,p){if(c[l]!==p){c[l]=p;const f=i.get(l);if(f){for(const b of f)s.add(b);o||(o=!0,Ai(r))}}return!0}}),u=c=>{const l=()=>{const p=n;n=l;try{return c()}finally{n=p}};return l()};return e.addEventListener("abort",()=>{t=!0}),{state:a,createEffect:u}}function As(e,t,n){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0}const Ha=new WeakMap;function ev(e,t,n){{const i=e.closest(".tabpanel");let s=Ha.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),Ha.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const Es=[],{assign:Zn}=Object;function tv(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:r}=Zy(s),a=new Map;Zn(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),Zn(o,t),Zn(o,{initialLoad:!0,currentEmojis:[],currentEmojisWithCategories:[],rawSearchText:"",searchText:"",searchMode:!1,activeSearchItem:-1,message:void 0,skinTonePickerExpanded:!1,skinTonePickerExpandedAfterAnimation:!1,currentSkinTone:0,activeSkinTone:0,skinToneButtonText:void 0,pickerStyle:void 0,skinToneButtonLabel:"",skinTones:[],currentFavorites:[],defaultFavoriteEmojis:void 0,numColumns:ky,isRtl:!1,currentGroupIndex:0,groups:ws,databaseLoaded:!1,activeSearchItemId:void 0}),r(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const u=x=>{e.getElementById(x).focus()},c=x=>e.getElementById(`emo-${x.id}`),l=(x,M)=>{n.rootElement.dispatchEvent(new CustomEvent(x,{detail:M,bubbles:!0,composed:!0}))},p=(x,M)=>x.id===M.id,f=(x,M)=>{const{category:B,emojis:N}=x,{category:V,emojis:z}=M;return B!==V?!1:As(N,z,p)},b=x=>{As(o.currentEmojis,x,p)||(o.currentEmojis=x)},h=x=>{o.searchMode!==x&&(o.searchMode=x)},v=x=>{As(o.currentEmojisWithCategories,x,f)||(o.currentEmojisWithCategories=x)},k=(x,M)=>M&&x.skins&&x.skins[M]||x.unicode,C={labelWithSkin:(x,M)=>Ny([x.name||k(x,M),x.annotation,...x.shortcodes||Es].filter(Boolean)).join(", "),titleForEmoji:x=>x.annotation||(x.shortcodes||Es).join(", "),unicodeWithSkin:k},T={onClickSkinToneButton:j,onEmojiClick:Mn,onNavClick:Tn,onNavKeydown:zi,onSearchKeydown:Ki,onSkinToneOptionsClick:Pn,onSkinToneOptionsFocusOut:Ge,onSkinToneOptionsKeydown:st,onSkinToneOptionsKeyup:Gt,onSearchInput:Ln},_={calculateEmojiGridStyle:ee,updateOnIntersection:ye};let R=!0;r(()=>{Xy(e,o,C,T,_,n,s,a,R),R=!1}),o.emojiVersion||Ss().then(x=>{x||(o.message=o.i18n.emojiUnsupportedMessage)}),r(()=>{async function x(){let M=!1;const B=setTimeout(()=>{M=!0,o.message=o.i18n.loadingMessage},by);try{await o.database.ready(),o.databaseLoaded=!0}catch(N){console.error(N),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(B),M&&(M=!1,o.message="")}}o.database&&x()}),r(()=>{o.pickerStyle=`
2460
+ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function Ky(e){return xu(e,t=>t)}function zy(e){e&&(e.scrollTop=0)}function vn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function Ka(e){return""+e}function Hy(e){const t=document.createElement("template");return t.innerHTML=e,t}const qy=new WeakMap,jy=new WeakMap,Vy=Symbol("un-keyed"),Gy="replaceChildren"in Element.prototype;function Qy(e,t){Gy?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function Yy(e,t){let n=e.firstChild,i=0;for(;n;){if(t[i]!==n)return!0;n=n.nextSibling,i++}return i!==t.length}function Jy(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=Yy(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&Qy(i,e)}function Xy(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:r,attributeValuePre:a,attributeValuePost:u}}=n,c=e[o];if(s!==c)if(n.currentExpression=c,r)if(c===null)i.removeAttribute(r);else{const l=a+Ka(c)+u;i.setAttribute(r,l)}else{let l;Array.isArray(c)?Jy(c,n):c instanceof Element?(l=c,i.replaceWith(l)):i.nodeValue=Ka(c),l&&(n.targetNode=l)}}}function Zy(e){let t="",n=!1,i=!1,s=-1;const o=new Map,r=[];let a=0;for(let c=0,l=e.length;c<l;c++){const p=e[c];if(t+=p.slice(a),c===l-1)break;for(let A=0;A<p.length;A++)switch(p.charAt(A)){case"<":{p.charAt(A+1)==="/"?r.pop():(n=!0,r.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const h=r[r.length-1],b=vn(o,h,()=>[]);let f,v,k;if(i){const A=/(\S+)="?([^"=]*)$/.exec(p);f=A[1],v=A[2];const C=/^([^">]*)("?)/.exec(e[c+1]);k=C[1],t=t.slice(0,-1*A[0].length),a=C[0].length}else a=0;const $={attributeName:f,attributeValuePre:v,attributeValuePost:k,expressionIndex:c};b.push($),!n&&!i&&(t+=" ")}return{template:Hy(t),elementsToBindings:o}}function za(e,t,n){for(let i=0;i<e.length;i++){const s=e[i],o=s.attributeName?t:t.firstChild,r={binding:s,targetNode:o,targetParentNode:void 0,currentExpression:void 0};n.push(r)}}function ev(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))za(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,r=-1;do{const a=t.get(++r);a&&za(a,o,n)}while(o=s.nextNode())}return n}function tv(e){const{template:t,elementsToBindings:n}=vn(qy,e,()=>Zy(e)),i=t.cloneNode(!0).content.firstElementChild,s=ev(i,n);return function(r){return Xy(r,s),i}}function nv(e){const t=vn(jy,e,()=>new Map);let n=Vy;function i(o,...r){const a=vn(t,o,()=>new Map);return vn(a,n,()=>tv(o))(r)}function s(o,r,a){return o.map((u,c)=>{const l=n;n=a(u);try{return r(u,c)}finally{n=l}})}return{map:s,html:i}}function iv(e,t,n,i,s,o,r,a,u){const{labelWithSkin:c,titleForEmoji:l,unicodeWithSkin:p}=n,{html:h,map:b}=nv(t);function f(A,C,T){return b(A,(_,R)=>h`<button role="${C?"option":"menuitem"}" aria-selected="${C?R===t.activeSearchItem:null}" aria-label="${c(_,t.currentSkinTone)}" title="${l(_)}" class="${"emoji"+(C&&R===t.activeSearchItem?" active":"")+(_.unicode?"":" custom-emoji")}" id="${`${T}-${_.id}`}" style="${_.unicode?null:`--custom-emoji-background: url(${JSON.stringify(_.url)})`}">${_.unicode?p(_,t.currentSkinTone):""}</button>`,_=>`${T}-${_.id}`)}const k=h`<section data-ref="rootElement" class="picker" aria-label="${t.i18n.regionLabel}" style="${t.pickerStyle||""}"><div class="pad-top"></div><div class="search-row"><div class="search-wrapper"><input id="search" class="search" type="search" role="combobox" enterkeyhint="search" placeholder="${t.i18n.searchLabel}" autocapitalize="none" autocomplete="off" spellcheck="true" aria-expanded="${!!(t.searchMode&&t.currentEmojis.length)}" aria-controls="search-results" aria-describedby="search-description" aria-autocomplete="list" aria-activedescendant="${t.activeSearchItemId?`emo-${t.activeSearchItemId}`:null}" data-ref="searchElement" data-on-input="onSearchInput" data-on-keydown="onSearchKeydown"><label class="sr-only" for="search">${t.i18n.searchLabel}</label> <span id="search-description" class="sr-only">${t.i18n.searchDescription}</span></div><div class="skintone-button-wrapper ${t.skinTonePickerExpandedAfterAnimation?"expanded":""}"><button id="skintone-button" class="emoji ${t.skinTonePickerExpanded?"hide-focus":""}" aria-label="${t.skinToneButtonLabel}" title="${t.skinToneButtonLabel}" aria-describedby="skintone-description" aria-haspopup="listbox" aria-expanded="${t.skinTonePickerExpanded}" aria-controls="skintone-list" data-on-click="onClickSkinToneButton">${t.skinToneButtonText||""}</button></div><span id="skintone-description" class="sr-only">${t.i18n.skinToneDescription}</span><div data-ref="skinToneDropdown" id="skintone-list" class="skintone-list hide-focus ${t.skinTonePickerExpanded?"":"hidden no-animate"}" style="transform:translateY(${t.skinTonePickerExpanded?0:"calc(-1 * var(--num-skintones) * var(--total-emoji-size))"})" role="listbox" aria-label="${t.i18n.skinTonesLabel}" aria-activedescendant="skintone-${t.activeSkinTone}" aria-hidden="${!t.skinTonePickerExpanded}" tabIndex="-1" data-on-focusout="onSkinToneOptionsFocusOut" data-on-click="onSkinToneOptionsClick" data-on-keydown="onSkinToneOptionsKeydown" data-on-keyup="onSkinToneOptionsKeyup">${b(t.skinTones,(A,C)=>h`<div id="skintone-${C}" class="emoji ${C===t.activeSkinTone?"active":""}" aria-selected="${C===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[C]}" aria-label="${t.i18n.skinTones[C]}">${A}</div>`,A=>A)}</div></div><div class="nav" role="tablist" style="grid-template-columns:repeat(${t.groups.length},1fr)" aria-label="${t.i18n.categoriesLabel}" data-on-keydown="onNavKeydown" data-on-click="onNavClick">${b(t.groups,A=>h`<button role="tab" class="nav-button" aria-controls="tab-${A.id}" aria-label="${t.i18n.categories[A.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===A.id}" title="${t.i18n.categories[A.name]}" data-group-id="${A.id}"><div class="nav-emoji emoji">${A.emoji}</div></button>`,A=>A.id)}</div><div class="indicator-wrapper"><div class="indicator" style="transform:translateX(${(t.isRtl?-1:1)*t.currentGroupIndex*100}%)"></div></div><div class="message ${t.message?"":"gone"}" role="alert" aria-live="polite">${t.message||""}</div><div data-ref="tabpanelElement" class="tabpanel ${!t.databaseLoaded||t.message?"gone":""}" role="${t.searchMode?"region":"tabpanel"}" aria-label="${t.searchMode?t.i18n.searchResultsLabel:t.i18n.categories[t.currentGroup.name]}" id="${t.searchMode?null:`tab-${t.currentGroup.id}`}" tabIndex="0" data-on-click="onEmojiClick"><div data-action="calculateEmojiGridStyle">${b(t.currentEmojisWithCategories,(A,C)=>h`<div><div id="menu-label-${C}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:A.category?A.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${C!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(A.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${C}" id="${t.searchMode?"search-results":null}">${f(A.emojis,t.searchMode,"emo")}</div></div>`,A=>A.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${f(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,$=(A,C)=>{for(const T of e.querySelectorAll(`[${A}]`))C(T,T.getAttribute(A))};if(u){e.appendChild(k);for(const A of["click","focusout","input","keydown","keyup"])$(`data-on-${A}`,(C,T)=>{C.addEventListener(A,i[T])});$("data-ref",(A,C)=>{o[C]=A}),r.addEventListener("abort",()=>{e.removeChild(k)})}$("data-action",(A,C)=>{let T=a.get(C);T||a.set(C,T=new WeakSet),T.has(A)||(T.add(A),s[C](A))})}const xi=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function sv(e){let t=!1,n;const i=new Map,s=new Set;let o;const r=()=>{if(t)return;const c=[...s];s.clear();try{for(const l of c)l()}finally{o=!1,s.size&&(o=!0,xi(r))}},a=new Proxy({},{get(c,l){if(n){let p=i.get(l);p||(p=new Set,i.set(l,p)),p.add(n)}return c[l]},set(c,l,p){if(c[l]!==p){c[l]=p;const h=i.get(l);if(h){for(const b of h)s.add(b);o||(o=!0,xi(r))}}return!0}}),u=c=>{const l=()=>{const p=n;n=l;try{return c()}finally{n=p}};return l()};return e.addEventListener("abort",()=>{t=!0}),{state:a,createEffect:u}}function xs(e,t,n){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0}const Ha=new WeakMap;function ov(e,t,n){{const i=e.closest(".tabpanel");let s=Ha.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),Ha.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const Es=[],{assign:Zn}=Object;function rv(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:r}=sv(s),a=new Map;Zn(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),Zn(o,t),Zn(o,{initialLoad:!0,currentEmojis:[],currentEmojisWithCategories:[],rawSearchText:"",searchText:"",searchMode:!1,activeSearchItem:-1,message:void 0,skinTonePickerExpanded:!1,skinTonePickerExpandedAfterAnimation:!1,currentSkinTone:0,activeSkinTone:0,skinToneButtonText:void 0,pickerStyle:void 0,skinToneButtonLabel:"",skinTones:[],currentFavorites:[],defaultFavoriteEmojis:void 0,numColumns:Ey,isRtl:!1,currentGroupIndex:0,groups:ws,databaseLoaded:!1,activeSearchItemId:void 0}),r(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const u=x=>{e.getElementById(x).focus()},c=x=>e.getElementById(`emo-${x.id}`),l=(x,M)=>{n.rootElement.dispatchEvent(new CustomEvent(x,{detail:M,bubbles:!0,composed:!0}))},p=(x,M)=>x.id===M.id,h=(x,M)=>{const{category:B,emojis:N}=x,{category:V,emojis:z}=M;return B!==V?!1:xs(N,z,p)},b=x=>{xs(o.currentEmojis,x,p)||(o.currentEmojis=x)},f=x=>{o.searchMode!==x&&(o.searchMode=x)},v=x=>{xs(o.currentEmojisWithCategories,x,h)||(o.currentEmojisWithCategories=x)},k=(x,M)=>M&&x.skins&&x.skins[M]||x.unicode,C={labelWithSkin:(x,M)=>Ky([x.name||k(x,M),x.annotation,...x.shortcodes||Es].filter(Boolean)).join(", "),titleForEmoji:x=>x.annotation||(x.shortcodes||Es).join(", "),unicodeWithSkin:k},T={onClickSkinToneButton:j,onEmojiClick:Mn,onNavClick:Tn,onNavKeydown:zi,onSearchKeydown:Ki,onSkinToneOptionsClick:Pn,onSkinToneOptionsFocusOut:Ge,onSkinToneOptionsKeydown:st,onSkinToneOptionsKeyup:Gt,onSearchInput:Ln},_={calculateEmojiGridStyle:ee,updateOnIntersection:ye};let R=!0;r(()=>{iv(e,o,C,T,_,n,s,a,R),R=!1}),o.emojiVersion||Ss().then(x=>{x||(o.message=o.i18n.emojiUnsupportedMessage)}),r(()=>{async function x(){let M=!1;const B=setTimeout(()=>{M=!0,o.message=o.i18n.loadingMessage},Ay);try{await o.database.ready(),o.databaseLoaded=!0}catch(N){console.error(N),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(B),M&&(M=!1,o.message="")}}o.database&&x()}),r(()=>{o.pickerStyle=`
2432
2461
  --num-groups: ${o.groups.length};
2433
2462
  --indicator-opacity: ${o.searchMode?0:1};
2434
- --num-skintones: ${Oa};`}),r(()=>{o.customEmoji&&o.database&&O()}),r(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==eo&&(o.groups=eo):o.groups!==ws&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=ws)}),r(()=>{async function x(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}x()}),r(()=>{o.skinTones=Array(Oa).fill().map((x,M)=>Ly(o.skinToneEmoji,M))}),r(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),r(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),r(()=>{async function x(){const{database:M}=o,B=(await Promise.all(Sy.map(N=>M.getEmojiByUnicodeOrName(N)))).filter(Boolean);o.defaultFavoriteEmojis=B}o.databaseLoaded&&x()});function O(){const{customEmoji:x,database:M}=o,B=x||Es;M.customEmoji!==B&&(M.customEmoji=B)}r(()=>{async function x(){O();const{database:M,defaultFavoriteEmojis:B,numColumns:N}=o,V=await M.getTopFavoriteEmoji(N),z=await it(Au([...V,...B],le=>le.unicode||le.name).slice(0,N));o.currentFavorites=z}o.databaseLoaded&&o.defaultFavoriteEmojis&&x()});function ee(x){Dy(x,s,()=>{{const M=getComputedStyle(n.rootElement),B=parseInt(M.getPropertyValue("--num-columns"),10),N=M.getPropertyValue("direction")==="rtl";o.numColumns=B,o.isRtl=N}})}function ye(x){ev(x,s,M=>{for(const{target:B,isIntersecting:N}of M)B.classList.toggle("onscreen",N)})}r(()=>{async function x(){const{searchText:M,currentGroup:B,databaseLoaded:N,customEmoji:V}=o;if(!N)o.currentEmojis=[],o.searchMode=!1;else if(M.length>=yy){const z=await Wi(M);o.searchText===M&&(b(z),h(!0))}else{const{id:z}=B;if(z!==-1||V&&V.length){const le=await Ui(z);o.currentGroup.id===z&&(b(le),h(!1))}}}x()});const Ve=()=>{ri(()=>Oy(n.tabpanelElement))};r(()=>{const{currentEmojis:x,emojiVersion:M}=o,B=x.filter(N=>N.unicode).filter(N=>Fa(N)&&!to.has(N.unicode));if(!M&&B.length)b(x),ri(()=>X(B));else{const N=M?x:x.filter(Vt);b(N),Ve()}});function X(x){By(x,n.baselineEmoji,c)?Ve():o.currentEmojis=[...o.currentEmojis]}function Vt(x){return!x.unicode||!Fa(x)||to.get(x.unicode)}async function xt(x){const M=o.emojiVersion||await Ss();return x.filter(({version:B})=>!B||B<=M)}async function it(x){return Iy(x,o.emojiVersion||await Ss())}async function Ui(x){const M=x===-1?o.customEmoji:await o.database.getEmojiByGroup(x);return it(await xt(M))}async function Wi(x){return it(await xt(await o.database.getEmojiBySearchQuery(x)))}r(()=>{}),r(()=>{function x(){const{searchMode:B,currentEmojis:N}=o;if(B)return[{category:"",emojis:N}];const V=new Map;for(const z of N){const le=z.category||"";let Qe=V.get(le);Qe||(Qe=[],V.set(le,Qe)),Qe.push(z)}return[...V.entries()].map(([z,le])=>({category:z,emojis:le})).sort((z,le)=>o.customCategorySorting(z.category,le.category))}const M=x();v(M)}),r(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),r(()=>{const{rawSearchText:x}=o;$u(()=>{o.searchText=(x||"").trim(),o.activeSearchItem=-1})});function Ki(x){if(!o.searchMode||!o.currentEmojis.length)return;const M=B=>{Ce(x),o.activeSearchItem=$s(B,o.activeSearchItem,o.currentEmojis)};switch(x.key){case"ArrowDown":return M(!1);case"ArrowUp":return M(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Ce(x),Q(o.currentEmojis[o.activeSearchItem].id)}}function Tn(x){const{target:M}=x,B=M.closest(".nav-button");if(!B)return;const N=parseInt(B.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(V=>V.id===N)}function zi(x){const{target:M,key:B}=x,N=V=>{V&&(Ce(x),V.focus())};switch(B){case"ArrowLeft":return N(M.previousElementSibling);case"ArrowRight":return N(M.nextElementSibling);case"Home":return N(M.parentElement.firstElementChild);case"End":return N(M.parentElement.lastElementChild)}}async function _n(x){const M=await o.database.getEmojiByUnicodeOrName(x),B=[...o.currentEmojis,...o.currentFavorites].find(V=>V.id===x),N=B.unicode&&k(B,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(x),{emoji:M,skinTone:o.currentSkinTone,...N&&{unicode:N},...B.name&&{name:B.name}}}async function Q(x){const M=_n(x);l("emoji-click-sync",M),l("emoji-click",await M)}function Mn(x){const{target:M}=x;if(!M.classList.contains("emoji"))return;Ce(x);const B=M.id.substring(4);Q(B)}function Y(x){o.currentSkinTone=x,o.skinTonePickerExpanded=!1,u("skintone-button"),l("skin-tone-change",{skinTone:x}),o.database.setPreferredSkinTone(x)}function Pn(x){const{target:{id:M}}=x,B=M&&M.match(/^skintone-(\d)/);if(!B)return;Ce(x);const N=parseInt(B[1],10);Y(N)}function j(x){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Ce(x),ri(()=>u("skintone-list")))}r(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function st(x){if(!o.skinTonePickerExpanded)return;const M=async B=>{Ce(x),o.activeSkinTone=B};switch(x.key){case"ArrowUp":return M($s(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return M($s(!1,o.activeSkinTone,o.skinTones));case"Home":return M(0);case"End":return M(o.skinTones.length-1);case"Enter":return Ce(x),Y(o.activeSkinTone);case"Escape":return Ce(x),o.skinTonePickerExpanded=!1,u("skintone-button")}}function Gt(x){if(o.skinTonePickerExpanded&&x.key===" ")return Ce(x),Y(o.activeSkinTone)}async function Ge(x){const{relatedTarget:M}=x;(!M||M.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function Ln(x){o.rawSearchText=x.target.value}return{$set(x){Zn(o,x)},$destroy(){i.abort()}}}const nv="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",iv="en";var sv={categoriesLabel:"Categories",emojiUnsupportedMessage:"Your browser does not support color emoji.",favoritesLabel:"Favorites",loadingMessage:"Loading…",networkErrorMessage:"Could not load emoji.",regionLabel:"Emoji picker",searchDescription:"When search results are available, press up or down to select and enter to choose.",searchLabel:"Search",searchResultsLabel:"Search results",skinToneDescription:"When expanded, press up or down to select and enter to choose.",skinToneLabel:"Choose a skin tone (currently {skinTone})",skinTonesLabel:"Skin tones",skinTones:["Default","Light","Medium-Light","Medium","Medium-Dark","Dark"],categories:{custom:"Custom","smileys-emotion":"Smileys and emoticons","people-body":"People and body","animals-nature":"Animals and nature","food-drink":"Food and drink","travel-places":"Travel and places",activities:"Activities",objects:"Objects",symbols:"Symbols",flags:"Flags"}},ov=':host{--emoji-size:1.375rem;--emoji-padding:0.5rem;--category-emoji-size:var(--emoji-size);--category-emoji-padding:var(--emoji-padding);--indicator-height:3px;--input-border-radius:0.5rem;--input-border-size:1px;--input-font-size:1rem;--input-line-height:1.5;--input-padding:0.25rem;--num-columns:8;--outline-size:2px;--border-size:1px;--border-radius:0;--skintone-border-radius:1rem;--category-font-size:1rem;display:flex;width:min-content;height:400px}:host,:host(.light){color-scheme:light;--background:#fff;--border-color:#e0e0e0;--indicator-color:#385ac1;--input-border-color:#999;--input-font-color:#111;--input-placeholder-color:#999;--outline-color:#999;--category-font-color:#111;--button-active-background:#e6e6e6;--button-hover-background:#d9d9d9}:host(.dark){color-scheme:dark;--background:#222;--border-color:#444;--indicator-color:#5373ec;--input-border-color:#ccc;--input-font-color:#efefef;--input-placeholder-color:#ccc;--outline-color:#fff;--category-font-color:#efefef;--button-active-background:#555555;--button-hover-background:#484848}@media (prefers-color-scheme:dark){:host{color-scheme:dark;--background:#222;--border-color:#444;--indicator-color:#5373ec;--input-border-color:#ccc;--input-font-color:#efefef;--input-placeholder-color:#ccc;--outline-color:#fff;--category-font-color:#efefef;--button-active-background:#555555;--button-hover-background:#484848}}:host([hidden]){display:none}button{margin:0;padding:0;border:0;background:0 0;box-shadow:none;-webkit-tap-highlight-color:transparent}button::-moz-focus-inner{border:0}input{padding:0;margin:0;line-height:1.15;font-family:inherit}input[type=search]{-webkit-appearance:none}:focus{outline:var(--outline-color) solid var(--outline-size);outline-offset:calc(-1*var(--outline-size))}:host([data-js-focus-visible]) :focus:not([data-focus-visible-added]){outline:0}:focus:not(:focus-visible){outline:0}.hide-focus{outline:0}*{box-sizing:border-box}.picker{contain:content;display:flex;flex-direction:column;background:var(--background);border:var(--border-size) solid var(--border-color);border-radius:var(--border-radius);width:100%;height:100%;overflow:hidden;--total-emoji-size:calc(var(--emoji-size) + (2 * var(--emoji-padding)));--total-category-emoji-size:calc(var(--category-emoji-size) + (2 * var(--category-emoji-padding)))}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.hidden{opacity:0;pointer-events:none}.abs-pos{position:absolute;left:0;top:0}.gone{display:none!important}.skintone-button-wrapper,.skintone-list{background:var(--background);z-index:3}.skintone-button-wrapper.expanded{z-index:1}.skintone-list{position:absolute;inset-inline-end:0;top:0;z-index:2;overflow:visible;border-bottom:var(--border-size) solid var(--border-color);border-radius:0 0 var(--skintone-border-radius) var(--skintone-border-radius);will-change:transform;transition:transform .2s ease-in-out;transform-origin:center 0}@media (prefers-reduced-motion:reduce){.skintone-list{transition-duration:.001s}}@supports not (inset-inline-end:0){.skintone-list{right:0}}.skintone-list.no-animate{transition:none}.tabpanel{overflow-y:auto;scrollbar-gutter:stable;-webkit-overflow-scrolling:touch;will-change:transform;min-height:0;flex:1;contain:content}.emoji-menu{display:grid;grid-template-columns:repeat(var(--num-columns),var(--total-emoji-size));justify-content:space-around;align-items:flex-start;width:100%}.emoji-menu.visibility-auto{content-visibility:auto;contain-intrinsic-size:calc(var(--num-columns)*var(--total-emoji-size)) calc(var(--num-rows)*var(--total-emoji-size))}.category{padding:var(--emoji-padding);font-size:var(--category-font-size);color:var(--category-font-color)}.emoji,button.emoji{font-size:var(--emoji-size);display:flex;align-items:center;justify-content:center;border-radius:100%;height:var(--total-emoji-size);width:var(--total-emoji-size);line-height:1;overflow:hidden;font-family:var(--emoji-font-family);cursor:pointer}@media (hover:hover) and (pointer:fine){.emoji:hover,button.emoji:hover{background:var(--button-hover-background)}}.emoji.active,.emoji:active,button.emoji.active,button.emoji:active{background:var(--button-active-background)}.onscreen .custom-emoji::after{content:"";width:var(--emoji-size);height:var(--emoji-size);background-repeat:no-repeat;background-position:center center;background-size:contain;background-image:var(--custom-emoji-background)}.nav,.nav-button{align-items:center}.nav{display:grid;justify-content:space-between;contain:content}.nav-button{display:flex;justify-content:center}.nav-emoji{font-size:var(--category-emoji-size);width:var(--total-category-emoji-size);height:var(--total-category-emoji-size)}.indicator-wrapper{display:flex;border-bottom:1px solid var(--border-color)}.indicator{width:calc(100%/var(--num-groups));height:var(--indicator-height);opacity:var(--indicator-opacity);background-color:var(--indicator-color);will-change:transform,opacity;transition:opacity .1s linear,transform .25s ease-in-out}@media (prefers-reduced-motion:reduce){.indicator{will-change:opacity;transition:opacity .1s linear}}.pad-top,input.search{background:var(--background);width:100%}.pad-top{height:var(--emoji-padding);z-index:3}.search-row{display:flex;align-items:center;position:relative;padding-inline-start:var(--emoji-padding);padding-bottom:var(--emoji-padding)}.search-wrapper{flex:1;min-width:0}input.search{padding:var(--input-padding);border-radius:var(--input-border-radius);border:var(--input-border-size) solid var(--input-border-color);color:var(--input-font-color);font-size:var(--input-font-size);line-height:var(--input-line-height)}input.search::placeholder{color:var(--input-placeholder-color)}.favorites{overflow-y:auto;scrollbar-gutter:stable;display:flex;flex-direction:row;border-top:var(--border-size) solid var(--border-color);contain:content}.message{padding:var(--emoji-padding)}';const Eu=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],rv=`:host{--emoji-font-family:${xu}}`;class Xo extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=ov+rv,this.shadowRoot.appendChild(n),this._ctx={locale:iv,dataSource:nv,skinToneEmoji:wy,customCategorySorting:$y,customEmoji:null,i18n:sv,emojiVersion:null,...t};for(const i of Eu)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){qa(this),this._cmp||(this._cmp=tv(this.shadowRoot,this._ctx))}disconnectedCallback(){qa(this),Ai(()=>{if(!this.isConnected&&this._cmp){this._cmp.$destroy(),this._cmp=void 0;const{database:t}=this._ctx;t.close().catch(n=>console.error(n))}})}static get observedAttributes(){return["locale","data-source","skin-tone-emoji","emoji-version"]}attributeChangedCallback(t,n,i){this._set(t.replace(/-([a-z])/g,(s,o)=>o.toUpperCase()),t==="emoji-version"?parseFloat(i):i)}_set(t,n){this._ctx[t]=n,this._cmp&&this._cmp.$set({[t]:n}),["locale","dataSource"].includes(t)&&this._dbFlush()}_dbCreate(){const{locale:t,dataSource:n,database:i}=this._ctx;(!i||i.locale!==t||i.dataSource!==n)&&this._set("database",new my({locale:t,dataSource:n}))}_dbFlush(){Ai(()=>this._dbCreate())}}const Cu={};for(const e of Eu)Cu[e]={get(){return e==="database"&&this._dbCreate(),this._ctx[e]},set(t){if(e==="database")throw new Error("database is read-only");this._set(e,t)}};Object.defineProperties(Xo.prototype,Cu);function qa(e){e instanceof Xo||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Xo);function av(e){e.style.height="0";const t=Math.max(e.scrollHeight,44);e.style.height=`${t}px`,e.style.overflowY=e.scrollHeight>e.offsetHeight?"auto":"hidden"}function ja(e){e.style.height="44px",e.style.overflowY="hidden"}const lv=5e3;function cv(e){return e?e.active?d`
2463
+ --num-skintones: ${Oa};`}),r(()=>{o.customEmoji&&o.database&&O()}),r(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==eo&&(o.groups=eo):o.groups!==ws&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=ws)}),r(()=>{async function x(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}x()}),r(()=>{o.skinTones=Array(Oa).fill().map((x,M)=>Ny(o.skinToneEmoji,M))}),r(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),r(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),r(()=>{async function x(){const{database:M}=o,B=(await Promise.all(Cy.map(N=>M.getEmojiByUnicodeOrName(N)))).filter(Boolean);o.defaultFavoriteEmojis=B}o.databaseLoaded&&x()});function O(){const{customEmoji:x,database:M}=o,B=x||Es;M.customEmoji!==B&&(M.customEmoji=B)}r(()=>{async function x(){O();const{database:M,defaultFavoriteEmojis:B,numColumns:N}=o,V=await M.getTopFavoriteEmoji(N),z=await it(xu([...V,...B],le=>le.unicode||le.name).slice(0,N));o.currentFavorites=z}o.databaseLoaded&&o.defaultFavoriteEmojis&&x()});function ee(x){Uy(x,s,()=>{{const M=getComputedStyle(n.rootElement),B=parseInt(M.getPropertyValue("--num-columns"),10),N=M.getPropertyValue("direction")==="rtl";o.numColumns=B,o.isRtl=N}})}function ye(x){ov(x,s,M=>{for(const{target:B,isIntersecting:N}of M)B.classList.toggle("onscreen",N)})}r(()=>{async function x(){const{searchText:M,currentGroup:B,databaseLoaded:N,customEmoji:V}=o;if(!N)o.currentEmojis=[],o.searchMode=!1;else if(M.length>=Sy){const z=await Wi(M);o.searchText===M&&(b(z),f(!0))}else{const{id:z}=B;if(z!==-1||V&&V.length){const le=await Ui(z);o.currentGroup.id===z&&(b(le),f(!1))}}}x()});const Ve=()=>{ri(()=>zy(n.tabpanelElement))};r(()=>{const{currentEmojis:x,emojiVersion:M}=o,B=x.filter(N=>N.unicode).filter(N=>Fa(N)&&!to.has(N.unicode));if(!M&&B.length)b(x),ri(()=>X(B));else{const N=M?x:x.filter(Vt);b(N),Ve()}});function X(x){Wy(x,n.baselineEmoji,c)?Ve():o.currentEmojis=[...o.currentEmojis]}function Vt(x){return!x.unicode||!Fa(x)||to.get(x.unicode)}async function At(x){const M=o.emojiVersion||await Ss();return x.filter(({version:B})=>!B||B<=M)}async function it(x){return Oy(x,o.emojiVersion||await Ss())}async function Ui(x){const M=x===-1?o.customEmoji:await o.database.getEmojiByGroup(x);return it(await At(M))}async function Wi(x){return it(await At(await o.database.getEmojiBySearchQuery(x)))}r(()=>{}),r(()=>{function x(){const{searchMode:B,currentEmojis:N}=o;if(B)return[{category:"",emojis:N}];const V=new Map;for(const z of N){const le=z.category||"";let Qe=V.get(le);Qe||(Qe=[],V.set(le,Qe)),Qe.push(z)}return[...V.entries()].map(([z,le])=>({category:z,emojis:le})).sort((z,le)=>o.customCategorySorting(z.category,le.category))}const M=x();v(M)}),r(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),r(()=>{const{rawSearchText:x}=o;$u(()=>{o.searchText=(x||"").trim(),o.activeSearchItem=-1})});function Ki(x){if(!o.searchMode||!o.currentEmojis.length)return;const M=B=>{Ce(x),o.activeSearchItem=$s(B,o.activeSearchItem,o.currentEmojis)};switch(x.key){case"ArrowDown":return M(!1);case"ArrowUp":return M(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Ce(x),Q(o.currentEmojis[o.activeSearchItem].id)}}function Tn(x){const{target:M}=x,B=M.closest(".nav-button");if(!B)return;const N=parseInt(B.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(V=>V.id===N)}function zi(x){const{target:M,key:B}=x,N=V=>{V&&(Ce(x),V.focus())};switch(B){case"ArrowLeft":return N(M.previousElementSibling);case"ArrowRight":return N(M.nextElementSibling);case"Home":return N(M.parentElement.firstElementChild);case"End":return N(M.parentElement.lastElementChild)}}async function _n(x){const M=await o.database.getEmojiByUnicodeOrName(x),B=[...o.currentEmojis,...o.currentFavorites].find(V=>V.id===x),N=B.unicode&&k(B,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(x),{emoji:M,skinTone:o.currentSkinTone,...N&&{unicode:N},...B.name&&{name:B.name}}}async function Q(x){const M=_n(x);l("emoji-click-sync",M),l("emoji-click",await M)}function Mn(x){const{target:M}=x;if(!M.classList.contains("emoji"))return;Ce(x);const B=M.id.substring(4);Q(B)}function Y(x){o.currentSkinTone=x,o.skinTonePickerExpanded=!1,u("skintone-button"),l("skin-tone-change",{skinTone:x}),o.database.setPreferredSkinTone(x)}function Pn(x){const{target:{id:M}}=x,B=M&&M.match(/^skintone-(\d)/);if(!B)return;Ce(x);const N=parseInt(B[1],10);Y(N)}function j(x){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Ce(x),ri(()=>u("skintone-list")))}r(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function st(x){if(!o.skinTonePickerExpanded)return;const M=async B=>{Ce(x),o.activeSkinTone=B};switch(x.key){case"ArrowUp":return M($s(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return M($s(!1,o.activeSkinTone,o.skinTones));case"Home":return M(0);case"End":return M(o.skinTones.length-1);case"Enter":return Ce(x),Y(o.activeSkinTone);case"Escape":return Ce(x),o.skinTonePickerExpanded=!1,u("skintone-button")}}function Gt(x){if(o.skinTonePickerExpanded&&x.key===" ")return Ce(x),Y(o.activeSkinTone)}async function Ge(x){const{relatedTarget:M}=x;(!M||M.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function Ln(x){o.rawSearchText=x.target.value}return{$set(x){Zn(o,x)},$destroy(){i.abort()}}}const av="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",lv="en";var cv={categoriesLabel:"Categories",emojiUnsupportedMessage:"Your browser does not support color emoji.",favoritesLabel:"Favorites",loadingMessage:"Loading…",networkErrorMessage:"Could not load emoji.",regionLabel:"Emoji picker",searchDescription:"When search results are available, press up or down to select and enter to choose.",searchLabel:"Search",searchResultsLabel:"Search results",skinToneDescription:"When expanded, press up or down to select and enter to choose.",skinToneLabel:"Choose a skin tone (currently {skinTone})",skinTonesLabel:"Skin tones",skinTones:["Default","Light","Medium-Light","Medium","Medium-Dark","Dark"],categories:{custom:"Custom","smileys-emotion":"Smileys and emoticons","people-body":"People and body","animals-nature":"Animals and nature","food-drink":"Food and drink","travel-places":"Travel and places",activities:"Activities",objects:"Objects",symbols:"Symbols",flags:"Flags"}},uv=':host{--emoji-size:1.375rem;--emoji-padding:0.5rem;--category-emoji-size:var(--emoji-size);--category-emoji-padding:var(--emoji-padding);--indicator-height:3px;--input-border-radius:0.5rem;--input-border-size:1px;--input-font-size:1rem;--input-line-height:1.5;--input-padding:0.25rem;--num-columns:8;--outline-size:2px;--border-size:1px;--border-radius:0;--skintone-border-radius:1rem;--category-font-size:1rem;display:flex;width:min-content;height:400px}:host,:host(.light){color-scheme:light;--background:#fff;--border-color:#e0e0e0;--indicator-color:#385ac1;--input-border-color:#999;--input-font-color:#111;--input-placeholder-color:#999;--outline-color:#999;--category-font-color:#111;--button-active-background:#e6e6e6;--button-hover-background:#d9d9d9}:host(.dark){color-scheme:dark;--background:#222;--border-color:#444;--indicator-color:#5373ec;--input-border-color:#ccc;--input-font-color:#efefef;--input-placeholder-color:#ccc;--outline-color:#fff;--category-font-color:#efefef;--button-active-background:#555555;--button-hover-background:#484848}@media (prefers-color-scheme:dark){:host{color-scheme:dark;--background:#222;--border-color:#444;--indicator-color:#5373ec;--input-border-color:#ccc;--input-font-color:#efefef;--input-placeholder-color:#ccc;--outline-color:#fff;--category-font-color:#efefef;--button-active-background:#555555;--button-hover-background:#484848}}:host([hidden]){display:none}button{margin:0;padding:0;border:0;background:0 0;box-shadow:none;-webkit-tap-highlight-color:transparent}button::-moz-focus-inner{border:0}input{padding:0;margin:0;line-height:1.15;font-family:inherit}input[type=search]{-webkit-appearance:none}:focus{outline:var(--outline-color) solid var(--outline-size);outline-offset:calc(-1*var(--outline-size))}:host([data-js-focus-visible]) :focus:not([data-focus-visible-added]){outline:0}:focus:not(:focus-visible){outline:0}.hide-focus{outline:0}*{box-sizing:border-box}.picker{contain:content;display:flex;flex-direction:column;background:var(--background);border:var(--border-size) solid var(--border-color);border-radius:var(--border-radius);width:100%;height:100%;overflow:hidden;--total-emoji-size:calc(var(--emoji-size) + (2 * var(--emoji-padding)));--total-category-emoji-size:calc(var(--category-emoji-size) + (2 * var(--category-emoji-padding)))}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.hidden{opacity:0;pointer-events:none}.abs-pos{position:absolute;left:0;top:0}.gone{display:none!important}.skintone-button-wrapper,.skintone-list{background:var(--background);z-index:3}.skintone-button-wrapper.expanded{z-index:1}.skintone-list{position:absolute;inset-inline-end:0;top:0;z-index:2;overflow:visible;border-bottom:var(--border-size) solid var(--border-color);border-radius:0 0 var(--skintone-border-radius) var(--skintone-border-radius);will-change:transform;transition:transform .2s ease-in-out;transform-origin:center 0}@media (prefers-reduced-motion:reduce){.skintone-list{transition-duration:.001s}}@supports not (inset-inline-end:0){.skintone-list{right:0}}.skintone-list.no-animate{transition:none}.tabpanel{overflow-y:auto;scrollbar-gutter:stable;-webkit-overflow-scrolling:touch;will-change:transform;min-height:0;flex:1;contain:content}.emoji-menu{display:grid;grid-template-columns:repeat(var(--num-columns),var(--total-emoji-size));justify-content:space-around;align-items:flex-start;width:100%}.emoji-menu.visibility-auto{content-visibility:auto;contain-intrinsic-size:calc(var(--num-columns)*var(--total-emoji-size)) calc(var(--num-rows)*var(--total-emoji-size))}.category{padding:var(--emoji-padding);font-size:var(--category-font-size);color:var(--category-font-color)}.emoji,button.emoji{font-size:var(--emoji-size);display:flex;align-items:center;justify-content:center;border-radius:100%;height:var(--total-emoji-size);width:var(--total-emoji-size);line-height:1;overflow:hidden;font-family:var(--emoji-font-family);cursor:pointer}@media (hover:hover) and (pointer:fine){.emoji:hover,button.emoji:hover{background:var(--button-hover-background)}}.emoji.active,.emoji:active,button.emoji.active,button.emoji:active{background:var(--button-active-background)}.onscreen .custom-emoji::after{content:"";width:var(--emoji-size);height:var(--emoji-size);background-repeat:no-repeat;background-position:center center;background-size:contain;background-image:var(--custom-emoji-background)}.nav,.nav-button{align-items:center}.nav{display:grid;justify-content:space-between;contain:content}.nav-button{display:flex;justify-content:center}.nav-emoji{font-size:var(--category-emoji-size);width:var(--total-category-emoji-size);height:var(--total-category-emoji-size)}.indicator-wrapper{display:flex;border-bottom:1px solid var(--border-color)}.indicator{width:calc(100%/var(--num-groups));height:var(--indicator-height);opacity:var(--indicator-opacity);background-color:var(--indicator-color);will-change:transform,opacity;transition:opacity .1s linear,transform .25s ease-in-out}@media (prefers-reduced-motion:reduce){.indicator{will-change:opacity;transition:opacity .1s linear}}.pad-top,input.search{background:var(--background);width:100%}.pad-top{height:var(--emoji-padding);z-index:3}.search-row{display:flex;align-items:center;position:relative;padding-inline-start:var(--emoji-padding);padding-bottom:var(--emoji-padding)}.search-wrapper{flex:1;min-width:0}input.search{padding:var(--input-padding);border-radius:var(--input-border-radius);border:var(--input-border-size) solid var(--input-border-color);color:var(--input-font-color);font-size:var(--input-font-size);line-height:var(--input-line-height)}input.search::placeholder{color:var(--input-placeholder-color)}.favorites{overflow-y:auto;scrollbar-gutter:stable;display:flex;flex-direction:row;border-top:var(--border-size) solid var(--border-color);contain:content}.message{padding:var(--emoji-padding)}';const Eu=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],dv=`:host{--emoji-font-family:${Au}}`;class Xo extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=uv+dv,this.shadowRoot.appendChild(n),this._ctx={locale:lv,dataSource:av,skinToneEmoji:xy,customCategorySorting:Ty,customEmoji:null,i18n:cv,emojiVersion:null,...t};for(const i of Eu)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){qa(this),this._cmp||(this._cmp=rv(this.shadowRoot,this._ctx))}disconnectedCallback(){qa(this),xi(()=>{if(!this.isConnected&&this._cmp){this._cmp.$destroy(),this._cmp=void 0;const{database:t}=this._ctx;t.close().catch(n=>console.error(n))}})}static get observedAttributes(){return["locale","data-source","skin-tone-emoji","emoji-version"]}attributeChangedCallback(t,n,i){this._set(t.replace(/-([a-z])/g,(s,o)=>o.toUpperCase()),t==="emoji-version"?parseFloat(i):i)}_set(t,n){this._ctx[t]=n,this._cmp&&this._cmp.$set({[t]:n}),["locale","dataSource"].includes(t)&&this._dbFlush()}_dbCreate(){const{locale:t,dataSource:n,database:i}=this._ctx;(!i||i.locale!==t||i.dataSource!==n)&&this._set("database",new ky({locale:t,dataSource:n}))}_dbFlush(){xi(()=>this._dbCreate())}}const Cu={};for(const e of Eu)Cu[e]={get(){return e==="database"&&this._dbCreate(),this._ctx[e]},set(t){if(e==="database")throw new Error("database is read-only");this._set(e,t)}};Object.defineProperties(Xo.prototype,Cu);function qa(e){e instanceof Xo||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Xo);function pv(e){e.style.height="0";const t=Math.max(e.scrollHeight,44);e.style.height=`${t}px`,e.style.overflowY=e.scrollHeight>e.offsetHeight?"auto":"hidden"}function ja(e){e.style.height="44px",e.style.overflowY="hidden"}const hv=5e3;function fv(e){return e?e.active?d`
2435
2464
  <div class="callout info compaction-indicator compaction-indicator--active">
2436
2465
  ${D.loader} Compacting context...
2437
2466
  </div>
2438
- `:e.completedAt&&Date.now()-e.completedAt<lv?d`
2467
+ `:e.completedAt&&Date.now()-e.completedAt<hv?d`
2439
2468
  <div class="callout success compaction-indicator compaction-indicator--complete">
2440
2469
  ${D.check} Context compacted
2441
2470
  </div>
2442
- `:S:S}const We=5*1024*1024;function Ke(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Se(e,t){var i,s,o;let n=(i=e.closest(".chat"))==null?void 0:i.querySelector(".chat-attachment-error");if(!n){n=document.createElement("div"),n.className="callout danger chat-attachment-error",n.style.cssText="margin: 8px 4px; animation: fade-in 200ms ease-out;";const r=(s=e.closest(".chat"))==null?void 0:s.querySelector(".chat-compose");(o=r==null?void 0:r.parentElement)==null||o.insertBefore(n,r)}n.textContent=t,setTimeout(()=>n==null?void 0:n.remove(),4e3)}const uv=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function Tu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function _u(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||uv.test(e.name)}function Mu(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function Pu(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function dv(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(Tu(e)){if(e.size>We){n&&Se(n,`Image too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(_u(e)){if(e.size>We){n&&Se(n,`File too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:"",mimeType:e.type||"text/plain",fileName:e.name,textContent:i.result};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsText(e)}else if(Mu(e)){if(e.size>We){n&&Se(n,`PDF too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(Pu(e)){if(e.size>We){n&&Se(n,`Video too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:i.result,mimeType:e.type||"video/mp4",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else n&&Se(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function pv(e,t){var s;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;n.classList.remove("chat--dragover");const i=(s=e.dataTransfer)==null?void 0:s.files;if(!(!i||i.length===0))for(let o=0;o<i.length;o++){const r=i[o];if(Tu(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`Image too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:u,mimeType:r.type},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsDataURL(r)}else if(_u(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`File too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:"",mimeType:r.type||"text/plain",fileName:r.name,textContent:u},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsText(r)}else if(Mu(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`PDF too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:u,mimeType:"application/pdf",fileName:r.name},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsDataURL(r)}else if(Pu(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`Video too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:u,mimeType:r.type||"video/mp4",fileName:r.name},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsDataURL(r)}else Se(n,`Unsupported file type: ${r.name}. Use the Files page to upload to workspace.`)}}function hv(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function fv(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function gv(e,t){var s,o,r;const n=(s=e.clipboardData)==null?void 0:s.items;if(!n||!t.onAttachmentsChange)return;const i=[];for(let a=0;a<n.length;a++){const u=n[a];(u.type.startsWith("image/")||u.type.startsWith("video/"))&&i.push(u)}if(i.length!==0){e.preventDefault();for(const a of i){const u=a.getAsFile();if(!u)continue;const c=u.type.startsWith("video/")?"Video":"Image";if(u.size>We){const p=((r=(o=e.target)==null?void 0:o.closest)==null?void 0:r.call(o,".chat"))??document.querySelector(".chat");p&&Se(p,`${c} too large (${(u.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const l=new FileReader;l.onload=()=>{var v;const p=l.result,f=u.type.startsWith("video/"),b={id:Ke(),dataUrl:p,mimeType:u.type,fileName:f?u.name||"video.mp4":void 0},h=t.attachments??[];(v=t.onAttachmentsChange)==null||v.call(t,[...h,b])},l.readAsDataURL(u)}}}function mv(e){const t=e.currentTarget,n=t.closest(".chat-compose"),i=n==null?void 0:n.querySelector(".emoji-picker-popup");if(!i)return;const s=i.classList.toggle("active");if(t.classList.toggle("active",s),s){const o=r=>{i.contains(r.target)||t.contains(r.target)||(i.classList.remove("active"),t.classList.remove("active"),document.removeEventListener("click",o,!0))};requestAnimationFrame(()=>document.addEventListener("click",o,!0))}}function yv(e,t){const n=e.detail,i=n==null?void 0:n.unicode;if(!i)return;const s=e.currentTarget.closest(".chat-compose"),o=s==null?void 0:s.querySelector("textarea");if(!o)return;const r=o.selectionStart??t.draft.length,a=o.selectionEnd??r,u=t.draft.slice(0,r),c=t.draft.slice(a);t.onDraftChange(u+i+c);const l=s==null?void 0:s.querySelector(".emoji-picker-popup"),p=s==null?void 0:s.querySelector(".chat-compose__emoji");l==null||l.classList.remove("active"),p==null||p.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const f=r+i.length;o.setSelectionRange(f,f)})}function vv(e){const t=e.attachments??[];return t.length===0?S:d`
2471
+ `:S:S}const We=5*1024*1024;function Ke(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Se(e,t){var i,s,o;let n=(i=e.closest(".chat"))==null?void 0:i.querySelector(".chat-attachment-error");if(!n){n=document.createElement("div"),n.className="callout danger chat-attachment-error",n.style.cssText="margin: 8px 4px; animation: fade-in 200ms ease-out;";const r=(s=e.closest(".chat"))==null?void 0:s.querySelector(".chat-compose");(o=r==null?void 0:r.parentElement)==null||o.insertBefore(n,r)}n.textContent=t,setTimeout(()=>n==null?void 0:n.remove(),4e3)}const gv=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function Tu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function _u(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||gv.test(e.name)}function Mu(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function Pu(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function mv(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(Tu(e)){if(e.size>We){n&&Se(n,`Image too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(_u(e)){if(e.size>We){n&&Se(n,`File too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:"",mimeType:e.type||"text/plain",fileName:e.name,textContent:i.result};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsText(e)}else if(Mu(e)){if(e.size>We){n&&Se(n,`PDF too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(Pu(e)){if(e.size>We){n&&Se(n,`Video too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Ke(),dataUrl:i.result,mimeType:e.type||"video/mp4",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else n&&Se(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function yv(e,t){var s;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;n.classList.remove("chat--dragover");const i=(s=e.dataTransfer)==null?void 0:s.files;if(!(!i||i.length===0))for(let o=0;o<i.length;o++){const r=i[o];if(Tu(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`Image too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:u,mimeType:r.type},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsDataURL(r)}else if(_u(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`File too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:"",mimeType:r.type||"text/plain",fileName:r.name,textContent:u},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsText(r)}else if(Mu(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`PDF too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:u,mimeType:"application/pdf",fileName:r.name},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsDataURL(r)}else if(Pu(r)){if(!t.onAttachmentsChange)continue;if(r.size>We){Se(n,`Video too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var p;const u=a.result,c={id:Ke(),dataUrl:u,mimeType:r.type||"video/mp4",fileName:r.name},l=t.attachments??[];(p=t.onAttachmentsChange)==null||p.call(t,[...l,c])},a.readAsDataURL(r)}else Se(n,`Unsupported file type: ${r.name}. Use the Files page to upload to workspace.`)}}function vv(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function bv(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function wv(e,t){var s,o,r;const n=(s=e.clipboardData)==null?void 0:s.items;if(!n||!t.onAttachmentsChange)return;const i=[];for(let a=0;a<n.length;a++){const u=n[a];(u.type.startsWith("image/")||u.type.startsWith("video/"))&&i.push(u)}if(i.length!==0){e.preventDefault();for(const a of i){const u=a.getAsFile();if(!u)continue;const c=u.type.startsWith("video/")?"Video":"Image";if(u.size>We){const p=((r=(o=e.target)==null?void 0:o.closest)==null?void 0:r.call(o,".chat"))??document.querySelector(".chat");p&&Se(p,`${c} too large (${(u.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const l=new FileReader;l.onload=()=>{var v;const p=l.result,h=u.type.startsWith("video/"),b={id:Ke(),dataUrl:p,mimeType:u.type,fileName:h?u.name||"video.mp4":void 0},f=t.attachments??[];(v=t.onAttachmentsChange)==null||v.call(t,[...f,b])},l.readAsDataURL(u)}}}function kv(e){const t=e.currentTarget,n=t.closest(".chat-compose"),i=n==null?void 0:n.querySelector(".emoji-picker-popup");if(!i)return;const s=i.classList.toggle("active");if(t.classList.toggle("active",s),s){const o=r=>{i.contains(r.target)||t.contains(r.target)||(i.classList.remove("active"),t.classList.remove("active"),document.removeEventListener("click",o,!0))};requestAnimationFrame(()=>document.addEventListener("click",o,!0))}}function Sv(e,t){const n=e.detail,i=n==null?void 0:n.unicode;if(!i)return;const s=e.currentTarget.closest(".chat-compose"),o=s==null?void 0:s.querySelector("textarea");if(!o)return;const r=o.selectionStart??t.draft.length,a=o.selectionEnd??r,u=t.draft.slice(0,r),c=t.draft.slice(a);t.onDraftChange(u+i+c);const l=s==null?void 0:s.querySelector(".emoji-picker-popup"),p=s==null?void 0:s.querySelector(".chat-compose__emoji");l==null||l.classList.remove("active"),p==null||p.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const h=r+i.length;o.setSelectionRange(h,h)})}function $v(e){const t=e.attachments??[];return t.length===0?S:d`
2443
2472
  <div class="chat-attachments">
2444
2473
  ${t.map(n=>{var i;return n.fileName?d`
2445
2474
  <div class="chat-attachment chat-attachment--file">
@@ -2472,7 +2501,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
2472
2501
  </div>
2473
2502
  `})}
2474
2503
  </div>
2475
- `}function Lu(e){var f,b,h;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(b=(f=e.sessions)==null?void 0:f.sessions)==null?void 0:b.find(v=>v.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",r=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const a=(((h=e.attachments)==null?void 0:h.length)??0)>0,u=e.connected?a?"Add a message...":"Message...":"Connecting…",c=e.splitRatio??.6,l=!!(e.sidebarOpen&&e.onCloseSidebar),p=d`
2504
+ `}function Lu(e){var h,b,f;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(b=(h=e.sessions)==null?void 0:h.sessions)==null?void 0:b.find(v=>v.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",r=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const a=(((f=e.attachments)==null?void 0:f.length)??0)>0,u=e.connected?a?"Add a message...":"Message...":"Connecting…",c=e.splitRatio??.6,l=!!(e.sidebarOpen&&e.onCloseSidebar),p=d`
2476
2505
  <div
2477
2506
  class="chat-thread"
2478
2507
  role="log"
@@ -2483,20 +2512,20 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
2483
2512
  ${e.loadingOlder?d`<span class="chat-load-more__spinner">${D.loader}</span> Loading older messages…`:d`<button class="chat-load-more__btn" type="button" @click=${e.onLoadOlder}>Load older messages</button>`}
2484
2513
  </div>`:S}
2485
2514
  ${e.loading?d`<div class="muted">Loading chat…</div>`:S}
2486
- ${Zf(Av(e),v=>v.key,v=>v.kind==="interim"?$m(v.text):v.kind==="reading-indicator"?Sm():v.kind==="stream"?xm(v.text,v.startedAt,e.onOpenSidebar):v.kind==="group"?Am(v,{onOpenSidebar:e.onOpenSidebar,showReasoning:r,assistantName:e.assistantName}):S)}
2515
+ ${Zf(Mv(e),v=>v.key,v=>v.kind==="interim"?xm(v.text):v.kind==="reading-indicator"?Am():v.kind==="stream"?Em(v.text,v.startedAt,e.onOpenSidebar):v.kind==="group"?Cm(v,{onOpenSidebar:e.onOpenSidebar,showReasoning:r,assistantName:e.assistantName}):S)}
2487
2516
  </div>
2488
2517
  `;return d`
2489
2518
  <section
2490
2519
  class="card chat"
2491
- @drop=${v=>pv(v,e)}
2492
- @dragover=${hv}
2493
- @dragleave=${fv}
2520
+ @drop=${v=>yv(v,e)}
2521
+ @dragover=${vv}
2522
+ @dragleave=${bv}
2494
2523
  >
2495
2524
  ${e.disabledReason?d`<div class="callout">${e.disabledReason}</div>`:S}
2496
2525
 
2497
2526
  ${e.error?d`<div class="callout danger">${e.error}</div>`:S}
2498
2527
 
2499
- ${cv(e.compactionStatus)}
2528
+ ${fv(e.compactionStatus)}
2500
2529
 
2501
2530
  ${e.focusMode?d`
2502
2531
  <button
@@ -2537,7 +2566,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
2537
2566
  @resize=${v=>{var k;return(k=e.onSplitRatioChange)==null?void 0:k.call(e,v.detail.splitRatio)}}
2538
2567
  ></resizable-divider>
2539
2568
  <div class="chat-sidebar">
2540
- ${Cm({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
2569
+ ${Lm({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
2541
2570
  ${e.sidebarContent}
2542
2571
  \`\`\``)}})}
2543
2572
  </div>
@@ -2557,12 +2586,12 @@ ${e.sidebarContent}
2557
2586
  `:S}
2558
2587
 
2559
2588
  <div class="chat-compose">
2560
- ${vv(e)}
2589
+ ${$v(e)}
2561
2590
  <div class="chat-compose__row">
2562
2591
  <button
2563
2592
  class="chat-compose__emoji"
2564
2593
  type="button"
2565
- @click=${mv}
2594
+ @click=${kv}
2566
2595
  aria-label="Emoji"
2567
2596
  title="Emoji"
2568
2597
  >
@@ -2583,7 +2612,7 @@ ${e.sidebarContent}
2583
2612
  multiple
2584
2613
  accept="image/*,video/*,.pdf,.md,.txt,.csv,.json,.xml,.html,.css,.js,.ts,.py,.sh,.yaml,.yml,.toml,.ini,.cfg,.log,.sql"
2585
2614
  style="display:none"
2586
- @change=${v=>{const k=v.target,$=k.files;if(!(!$||$.length===0||!e.onAttachmentsChange)){for(let A=0;A<$.length;A++)dv($[A],e);k.value=""}}}
2615
+ @change=${v=>{const k=v.target,$=k.files;if(!(!$||$.length===0||!e.onAttachmentsChange)){for(let A=0;A<$.length;A++)mv($[A],e);k.value=""}}}
2587
2616
  />
2588
2617
  <label class="field chat-compose__field">
2589
2618
  <span>Message</span>
@@ -2591,8 +2620,8 @@ ${e.sidebarContent}
2591
2620
  .value=${e.draft}
2592
2621
  ?disabled=${!e.connected}
2593
2622
  @keydown=${v=>{v.key==="Enter"&&(v.isComposing||v.keyCode===229||v.shiftKey||e.connected&&(v.preventDefault(),t&&(e.onSend(),ja(v.target))))}}
2594
- @input=${v=>{const k=v.target;e.onDraftChange(k.value),av(k)}}
2595
- @paste=${v=>gv(v,e)}
2623
+ @input=${v=>{const k=v.target;e.onDraftChange(k.value),pv(k)}}
2624
+ @paste=${v=>wv(v,e)}
2596
2625
  placeholder=${u}
2597
2626
  ></textarea>
2598
2627
  </label>
@@ -2618,13 +2647,13 @@ ${e.sidebarContent}
2618
2647
  </div>
2619
2648
  <div class="emoji-picker-popup">
2620
2649
  <emoji-picker
2621
- @emoji-click=${v=>yv(v,e)}
2650
+ @emoji-click=${v=>Sv(v,e)}
2622
2651
  ></emoji-picker>
2623
2652
  </div>
2624
- ${e.publicMode?S:$v(e)}
2653
+ ${e.publicMode?S:Tv(e)}
2625
2654
  </div>
2626
2655
  </section>
2627
- `}const bv=[{id:"claude-opus-4-6",shortName:"Opus",description:"Most capable"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet",description:"Fast & capable"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku",description:"Fastest"}];function wv(e){const t=new Set(e.filter(n=>n.provider==="anthropic").map(n=>n.id));return bv.filter(n=>t.has(n.id)).map(n=>({key:`anthropic/${n.id}`,...n}))}const kv=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function Sv(e){var s;const t=e.currentTarget,n=(s=t.closest(".chat-model-bar"))==null?void 0:s.querySelector(".chat-settings-menu");if(!n)return;const i=n.classList.contains("active");if(document.querySelectorAll(".chat-settings-menu.active").forEach(o=>o.classList.remove("active")),!i){n.classList.add("active");const o=r=>{!n.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&(n.classList.remove("active"),document.removeEventListener("click",o))};requestAnimationFrame(()=>document.addEventListener("click",o))}}function $v(e){if(!e.connected)return S;const t=e.modelCatalog??[],n=wv(t);if(n.length===0)return S;const i=e.modelProvider&&e.model?`${e.modelProvider}/${e.model}`:null,s=e.thinkingLevel??"off",o=e.verboseLevel==="on"||e.verboseLevel==="full",r=e.fillerEnabled===!0;return d`
2656
+ `}const Av=[{id:"claude-opus-4-6",shortName:"Opus",description:"Most capable"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet",description:"Fast & capable"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku",description:"Fastest"}];function xv(e){const t=new Set(e.filter(n=>n.provider==="anthropic").map(n=>n.id));return Av.filter(n=>t.has(n.id)).map(n=>({key:`anthropic/${n.id}`,...n}))}const Ev=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function Cv(e){var s;const t=e.currentTarget,n=(s=t.closest(".chat-model-bar"))==null?void 0:s.querySelector(".chat-settings-menu");if(!n)return;const i=n.classList.contains("active");if(document.querySelectorAll(".chat-settings-menu.active").forEach(o=>o.classList.remove("active")),!i){n.classList.add("active");const o=r=>{!n.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&(n.classList.remove("active"),document.removeEventListener("click",o))};requestAnimationFrame(()=>document.addEventListener("click",o))}}function Tv(e){if(!e.connected)return S;const t=e.modelCatalog??[],n=xv(t);if(n.length===0)return S;const i=e.modelProvider&&e.model?`${e.modelProvider}/${e.model}`:null,s=e.thinkingLevel??"off",o=e.verboseLevel==="on"||e.verboseLevel==="full",r=e.fillerEnabled===!0;return d`
2628
2657
  <div class="chat-model-bar">
2629
2658
  <div class="chat-model-bar__select">
2630
2659
  <select
@@ -2645,7 +2674,7 @@ ${e.sidebarContent}
2645
2674
  .value=${s}
2646
2675
  @change=${a=>{const u=a.target.value;e.onThinkingLevelChange&&e.onThinkingLevelChange(u)}}
2647
2676
  >
2648
- ${kv.map(a=>d`
2677
+ ${Ev.map(a=>d`
2649
2678
  <option value=${a.value} ?selected=${a.value===s}>
2650
2679
  Thinking: ${a.label}
2651
2680
  </option>
@@ -2655,7 +2684,7 @@ ${e.sidebarContent}
2655
2684
  <button
2656
2685
  class="chat-model-bar__settings-btn"
2657
2686
  type="button"
2658
- @click=${Sv}
2687
+ @click=${Cv}
2659
2688
  aria-label="Message settings"
2660
2689
  title="Message settings"
2661
2690
  >
@@ -2682,9 +2711,9 @@ ${e.sidebarContent}
2682
2711
  </label>
2683
2712
  </div>
2684
2713
  </div>
2685
- `}function xv(e){const t=[];let n=null;for(const i of e){if(i.kind!=="message"){n&&(t.push(n),n=null),t.push(i);continue}const s=Ml(i.message),o=Pl(s.role),r=s.timestamp||Date.now();!n||n.role!==o?(n&&t.push(n),n={kind:"group",key:`group:${o}:${i.key}`,role:o,messages:[{message:i.message,key:i.key}],timestamp:r,isStreaming:!1}):n.messages.push({message:i.message,key:i.key})}return n&&t.push(n),t}function Av(e){var o;const t=[],n=Array.isArray(e.messages)?e.messages:[],i=Array.isArray(e.toolMessages)?e.toolMessages:[],s=e.showThinking||e.verboseLevel==="on"||e.verboseLevel==="full";for(let r=0;r<n.length;r++){const a=n[r],u=Ml(a);if(!s&&u.role.toLowerCase()==="toolresult"){const c=a,p=(Array.isArray(c.content)?c.content:[]).filter(f=>f.type==="image");p.length>0&&t.push({kind:"message",key:Cs(a,r),message:{role:"assistant",content:p,timestamp:u.timestamp}});continue}t.push({kind:"message",key:Cs(a,r),message:a})}if(s)for(let r=0;r<i.length;r++)t.push({kind:"message",key:Cs(i[r],r+n.length),message:i[r]});if(e.interimText&&t.push({kind:"interim",key:"interim:thinking",text:e.interimText}),e.stream!==null){const r=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:r,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:r})}for(const r of e.queue){const a=((o=r.attachments)==null?void 0:o.filter(c=>c.fileName).map(c=>c.fileName))??[],u=a.length>0?r.text?`${a.join(", ")}
2714
+ `}function _v(e){const t=[];let n=null;for(const i of e){if(i.kind!=="message"){n&&(t.push(n),n=null),t.push(i);continue}const s=Ml(i.message),o=Pl(s.role),r=s.timestamp||Date.now();!n||n.role!==o?(n&&t.push(n),n={kind:"group",key:`group:${o}:${i.key}`,role:o,messages:[{message:i.message,key:i.key}],timestamp:r,isStreaming:!1}):n.messages.push({message:i.message,key:i.key})}return n&&t.push(n),t}function Mv(e){var o;const t=[],n=Array.isArray(e.messages)?e.messages:[],i=Array.isArray(e.toolMessages)?e.toolMessages:[],s=e.showThinking||e.verboseLevel==="on"||e.verboseLevel==="full";for(let r=0;r<n.length;r++){const a=n[r],u=Ml(a);if(!s&&u.role.toLowerCase()==="toolresult"){const c=a,p=(Array.isArray(c.content)?c.content:[]).filter(h=>{const b=h.type;return b==="image"||b==="file"});p.length>0&&t.push({kind:"message",key:Cs(a,r),message:{role:"assistant",content:p,timestamp:u.timestamp}});continue}t.push({kind:"message",key:Cs(a,r),message:a})}if(s)for(let r=0;r<i.length;r++)t.push({kind:"message",key:Cs(i[r],r+n.length),message:i[r]});if(e.interimText&&t.push({kind:"interim",key:"interim:thinking",text:e.interimText}),e.stream!==null){const r=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:r,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:r})}for(const r of e.queue){const a=((o=r.attachments)==null?void 0:o.filter(c=>c.fileName).map(c=>c.fileName))??[],u=a.length>0?r.text?`${a.join(", ")}
2686
2715
 
2687
- ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,message:{role:"user",content:[{type:"text",text:u}],timestamp:r.createdAt}})}return xv(t)}function Cs(e,t){const n=e,i=typeof n.toolCallId=="string"?n.toolCallId:"";if(i)return`tool:${i}`;const s=typeof n.id=="string"?n.id:"";if(s)return`msg:${s}`;const o=typeof n.messageId=="string"?n.messageId:"";if(o)return`msg:${o}`;const r=typeof n.timestamp=="number"?n.timestamp:null,a=typeof n.role=="string"?n.role:"unknown";return r!=null?`msg:${a}:${r}:${t}`:`msg:${a}:${t}`}const Ev=d`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`;function Cv(e){if(!e.connected)return d`
2716
+ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,message:{role:"user",content:[{type:"text",text:u}],timestamp:r.createdAt}})}return _v(t)}function Cs(e,t){const n=e,i=typeof n.toolCallId=="string"?n.toolCallId:"";if(i)return`tool:${i}`;const s=typeof n.id=="string"?n.id:"";if(s)return`msg:${s}`;const o=typeof n.messageId=="string"?n.messageId:"";if(o)return`msg:${o}`;const r=typeof n.timestamp=="number"?n.timestamp:null,a=typeof n.role=="string"?n.role:"unknown";return r!=null?`msg:${a}:${r}:${t}`:`msg:${a}:${t}`}const Pv=d`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`;function Lv(e){if(!e.connected)return d`
2688
2717
  <div class="setup-container">
2689
2718
  <div class="setup-card">
2690
2719
  <div class="setup-spinner"></div>
@@ -2697,7 +2726,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2697
2726
  target="_blank"
2698
2727
  rel="noopener"
2699
2728
  title="Open public chat in new tab"
2700
- >Public ${Ev}</a>`:S;return d`
2729
+ >Public ${Pv}</a>`:S;return d`
2701
2730
  <div class="setup-container setup-container--full chat-page">
2702
2731
  ${kt("Chat",e.wsProps)}
2703
2732
  ${t}
@@ -2705,12 +2734,12 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2705
2734
  ${Lu(e)}
2706
2735
  </div>
2707
2736
  </div>
2708
- `}function Tv(e){return e?`${Al(e)} (${Pi(e)})`:"n/a"}function Iu(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?Pi(t.lastRunAtMs):"never";return`${n} · last ${i}`}function Ru(e){const t=e.schedule;return t.kind==="at"?`One-time: ${Al(t.atMs)}`:t.kind==="every"?`Every ${El(t.everyMs)}`:_v(t.expr,t.tz)}function _v(e,t){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[i,s,o,r,a]=n,u=t?` (${t.replace(/^.*\//,"").replace(/_/g," ")})`:"",c=(v,k)=>new Date(2e3,0,1,v,k).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),l=/^\d{1,2}$/.test(i)?parseInt(i,10):null,p=Va(s);if(l===null||!p)return`${e}${t?` (${t})`:""}`;const f=p.map(v=>c(v,l)),b=f.length<=3?f.join(" & "):`${f.slice(0,-1).join(", ")} & ${f[f.length-1]}`,h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&r==="*"){if(a==="*")return`Daily at ${b}${u}`;if(a==="1-5")return`Weekdays at ${b}${u}`;if(a==="0,6"||a==="6,0")return`Weekends at ${b}${u}`;const v=Va(a);if(v)return`${v.map($=>h[$%7]??String($)).join(", ")} at ${b}${u}`}return`${e}${t?` (${t})`:""}`}function Va(e){if(e==="*")return null;if(/^\d+(,\d+)*$/.test(e))return e.split(",").map(Number);if(/^\d+-\d+$/.test(e)){const[t,n]=e.split("-").map(Number);if(t>n)return null;const i=[];for(let s=t;s<=n;s++)i.push(s);return i}return null}function Mv(e,t=!0){const n=e.payload;return n.kind==="systemEvent"?`Task: ${t&&n.text.length>60?`${n.text.slice(0,57)}…`:n.text}`:`Message: ${t&&n.message.length>60?`${n.message.slice(0,57)}…`:n.message}`}function Ga(e){const t=e.payload;if(t.kind!=="agentTurn")return null;const n=t.channel??t.provider,i=t.to;if(!i&&!n)return null;const s=[];if(i){const r=i.split(",").map(a=>a.trim()).filter(Boolean).map(a=>a.toLowerCase()==="admins"?"All admins":a);s.push(r.join(", "))}return n&&n!=="last"&&s.push(`via ${n}`),s.join(" ")||null}let ge=null;function Pv(e){var s;const t=["last",...e.channels.filter(Boolean)],n=(s=e.form.channel)==null?void 0:s.trim();n&&!t.includes(n)&&t.push(n);const i=new Set;return t.filter(o=>i.has(o)?!1:(i.add(o),!0))}function Lv(e,t){var i,s;if(t==="last")return"last";const n=(i=e.channelMeta)==null?void 0:i.find(o=>o.id===t);return n!=null&&n.label?n.label:((s=e.channelLabels)==null?void 0:s[t])??t}function Iv(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function Rv(e){return e||"Default"}const Dv=d`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,Bv=d`<svg viewBox="0 0 24 24"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>`,Nv=d`<svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>`,Zo=d`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,Ov=d`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,Du=d`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,Fv=d`<svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`;function Qa(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return d`
2709
- ${Uv(e)}
2710
- ${Wv(e)}
2711
- ${n?zv(e):S}
2712
- ${t?jv(t,e):S}
2713
- `}function Uv(e){const t=e.status,n=(t==null?void 0:t.enabled)??!1,i=(t==null?void 0:t.jobs)??0,s=t==null?void 0:t.nextWakeAtMs;return d`
2737
+ `}function Iv(e){return e?`${xl(e)} (${Pi(e)})`:"n/a"}function Iu(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?Pi(t.lastRunAtMs):"never";return`${n} · last ${i}`}function Ru(e){const t=e.schedule;return t.kind==="at"?`One-time: ${xl(t.atMs)}`:t.kind==="every"?`Every ${El(t.everyMs)}`:Rv(t.expr,t.tz)}function Rv(e,t){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[i,s,o,r,a]=n,u=t?` (${t.replace(/^.*\//,"").replace(/_/g," ")})`:"",c=(v,k)=>new Date(2e3,0,1,v,k).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),l=/^\d{1,2}$/.test(i)?parseInt(i,10):null,p=Va(s);if(l===null||!p)return`${e}${t?` (${t})`:""}`;const h=p.map(v=>c(v,l)),b=h.length<=3?h.join(" & "):`${h.slice(0,-1).join(", ")} & ${h[h.length-1]}`,f=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&r==="*"){if(a==="*")return`Daily at ${b}${u}`;if(a==="1-5")return`Weekdays at ${b}${u}`;if(a==="0,6"||a==="6,0")return`Weekends at ${b}${u}`;const v=Va(a);if(v)return`${v.map($=>f[$%7]??String($)).join(", ")} at ${b}${u}`}return`${e}${t?` (${t})`:""}`}function Va(e){if(e==="*")return null;if(/^\d+(,\d+)*$/.test(e))return e.split(",").map(Number);if(/^\d+-\d+$/.test(e)){const[t,n]=e.split("-").map(Number);if(t>n)return null;const i=[];for(let s=t;s<=n;s++)i.push(s);return i}return null}function Dv(e,t=!0){const n=e.payload;return n.kind==="systemEvent"?`Task: ${t&&n.text.length>60?`${n.text.slice(0,57)}…`:n.text}`:`Message: ${t&&n.message.length>60?`${n.message.slice(0,57)}…`:n.message}`}function Ga(e){const t=e.payload;if(t.kind!=="agentTurn")return null;const n=t.channel??t.provider,i=t.to;if(!i&&!n)return null;const s=[];if(i){const r=i.split(",").map(a=>a.trim()).filter(Boolean).map(a=>a.toLowerCase()==="admins"?"All admins":a);s.push(r.join(", "))}return n&&n!=="last"&&s.push(`via ${n}`),s.join(" ")||null}let ge=null;function Bv(e){var s;const t=["last",...e.channels.filter(Boolean)],n=(s=e.form.channel)==null?void 0:s.trim();n&&!t.includes(n)&&t.push(n);const i=new Set;return t.filter(o=>i.has(o)?!1:(i.add(o),!0))}function Nv(e,t){var i,s;if(t==="last")return"last";const n=(i=e.channelMeta)==null?void 0:i.find(o=>o.id===t);return n!=null&&n.label?n.label:((s=e.channelLabels)==null?void 0:s[t])??t}function Ov(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function Fv(e){return e||"Default"}const Uv=d`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,Wv=d`<svg viewBox="0 0 24 24"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>`,Kv=d`<svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>`,Zo=d`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,zv=d`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,Du=d`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,Hv=d`<svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`;function Qa(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return d`
2738
+ ${qv(e)}
2739
+ ${jv(e)}
2740
+ ${n?Gv(e):S}
2741
+ ${t?Jv(t,e):S}
2742
+ `}function qv(e){const t=e.status,n=(t==null?void 0:t.enabled)??!1,i=(t==null?void 0:t.jobs)??0,s=t==null?void 0:t.nextWakeAtMs;return d`
2714
2743
  <div class="event-status-bar">
2715
2744
  <div class="event-status-bar__info">
2716
2745
  <span class="statusDot ${n?"ok":""}"></span>
@@ -2735,11 +2764,11 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2735
2764
  ${Du} New Event
2736
2765
  </button>
2737
2766
  </div>
2738
- `}function Wv(e){return e.jobs.length===0?d`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:d`
2767
+ `}function jv(e){return e.jobs.length===0?d`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:d`
2739
2768
  <div class="event-grid">
2740
- ${e.jobs.map(t=>Kv(t,e))}
2769
+ ${e.jobs.map(t=>Vv(t,e))}
2741
2770
  </div>
2742
- `}function Kv(e,t){return d`
2771
+ `}function Vv(e,t){return d`
2743
2772
  <div
2744
2773
  class="event-card ${e.enabled?"":"disabled"}"
2745
2774
  @click=${()=>t.onDetailOpen(e)}
@@ -2751,7 +2780,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2751
2780
  </span>
2752
2781
  </div>
2753
2782
  <div class="event-card__schedule">${Ru(e)}</div>
2754
- ${e.agentId?d`<div class="event-card__agent">${Rv(e.agentId)}</div>`:S}
2783
+ ${e.agentId?d`<div class="event-card__agent">${Fv(e.agentId)}</div>`:S}
2755
2784
  ${Ga(e)?d`<div class="event-card__agent muted" style="font-size: 11px;">\u2192 ${Ga(e)}</div>`:S}
2756
2785
  <div class="event-card__footer">
2757
2786
  <div class="event-card__status">
@@ -2764,7 +2793,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2764
2793
  ?disabled=${t.busy}
2765
2794
  @click=${()=>t.onToggle(e,!e.enabled)}
2766
2795
  >
2767
- ${e.enabled?Bv:Dv}
2796
+ ${e.enabled?Wv:Uv}
2768
2797
  </button>
2769
2798
  <button
2770
2799
  class="btn-icon"
@@ -2772,7 +2801,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2772
2801
  ?disabled=${t.busy}
2773
2802
  @click=${()=>t.onRun(e)}
2774
2803
  >
2775
- ${Ov}
2804
+ ${zv}
2776
2805
  </button>
2777
2806
  ${t.pendingDeleteId===e.id?d`<button
2778
2807
  class="btn danger btn--sm"
@@ -2783,11 +2812,11 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2783
2812
  title="Delete"
2784
2813
  ?disabled=${t.busy}
2785
2814
  @click=${()=>{t.onArmDelete(e.id),ge&&clearTimeout(ge),ge=setTimeout(()=>{t.onArmDelete(""),ge=null},3e3)}}
2786
- >${Nv}</button>`}
2815
+ >${Kv}</button>`}
2787
2816
  </div>
2788
2817
  </div>
2789
2818
  </div>
2790
- `}function zv(e){const t=!!e.editJobId,n=Pv(e),i=()=>{e.onNewEventModalClose()};return d`
2819
+ `}function Gv(e){const t=!!e.editJobId,n=Bv(e),i=()=>{e.onNewEventModalClose()};return d`
2791
2820
  <div class="event-modal-overlay" @click=${i}>
2792
2821
  <div class="event-modal" @click=${s=>s.stopPropagation()}>
2793
2822
  <div class="event-modal__header">
@@ -2845,7 +2874,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2845
2874
  </label>
2846
2875
  </div>
2847
2876
 
2848
- ${qv(e)}
2877
+ ${Yv(e)}
2849
2878
 
2850
2879
  <div class="form-grid" style="margin-top: 12px;">
2851
2880
  <label class="field">
@@ -2907,7 +2936,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2907
2936
  @change=${s=>e.onFormChange({channel:s.target.value})}
2908
2937
  >
2909
2938
  ${n.map(s=>d`<option value=${s}>
2910
- ${Lv(e,s)}
2939
+ ${Nv(e,s)}
2911
2940
  </option>`)}
2912
2941
  </select>
2913
2942
  </label>
@@ -2920,7 +2949,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2920
2949
  />
2921
2950
  </label>
2922
2951
  </div>
2923
- ${Hv(e)}
2952
+ ${Qv(e)}
2924
2953
  <div class="form-grid" style="margin-top: 12px;">
2925
2954
  <label class="field">
2926
2955
  <span>Timeout (seconds)</span>
@@ -2951,7 +2980,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2951
2980
  </div>
2952
2981
  </div>
2953
2982
  </div>
2954
- `}function Hv(e){const t=e.form.recipients;return d`
2983
+ `}function Qv(e){const t=e.form.recipients;return d`
2955
2984
  <div style="margin-top: 8px;">
2956
2985
  <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
2957
2986
  <span style="font-size: 13px; color: var(--muted);">Recipients</span>
@@ -2981,7 +3010,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
2981
3010
  </div>
2982
3011
  `)}
2983
3012
  </div>
2984
- `}function qv(e){const t=e.form;return t.scheduleKind==="at"?d`
3013
+ `}function Yv(e){const t=e.form;return t.scheduleKind==="at"?d`
2985
3014
  <label class="field" style="margin-top: 12px;">
2986
3015
  <span>Run at</span>
2987
3016
  <input
@@ -3030,7 +3059,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3030
3059
  />
3031
3060
  </label>
3032
3061
  </div>
3033
- `}function jv(e,t){var n;return d`
3062
+ `}function Jv(e,t){var n;return d`
3034
3063
  <div class="event-modal-overlay" @click=${t.onDetailClose}>
3035
3064
  <div class="event-modal" @click=${i=>i.stopPropagation()}>
3036
3065
  <div class="event-modal__header">
@@ -3048,7 +3077,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3048
3077
  ?disabled=${t.busy}
3049
3078
  @click=${()=>t.onEdit(e)}
3050
3079
  >
3051
- ${Fv} Edit
3080
+ ${Hv} Edit
3052
3081
  </button>
3053
3082
  <button
3054
3083
  class="btn"
@@ -3106,12 +3135,12 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3106
3135
  </div>
3107
3136
  <div class="event-detail-row" style="flex-direction: column; align-items: stretch; gap: 4px;">
3108
3137
  <span class="event-detail-label">Action</span>
3109
- <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${Mv(e,!1)}</span>
3138
+ <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${Dv(e,!1)}</span>
3110
3139
  </div>
3111
3140
  ${e.payload.kind==="agentTurn"&&e.payload.to?d`
3112
3141
  <div class="event-detail-row">
3113
3142
  <span class="event-detail-label">Send to</span>
3114
- <span class="event-detail-value mono">${Iv(e.payload.to)}</span>
3143
+ <span class="event-detail-value mono">${Ov(e.payload.to)}</span>
3115
3144
  </div>
3116
3145
  `:S}
3117
3146
  ${e.payload.kind==="agentTurn"&&(e.payload.channel??e.payload.provider)?d`
@@ -3136,7 +3165,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3136
3165
  ${(n=e.state)!=null&&n.nextRunAtMs?d`
3137
3166
  <div class="event-detail-row">
3138
3167
  <span class="event-detail-label">Next run</span>
3139
- <span class="event-detail-value">${Tv(e.state.nextRunAtMs)}</span>
3168
+ <span class="event-detail-value">${Iv(e.state.nextRunAtMs)}</span>
3140
3169
  </div>
3141
3170
  `:S}
3142
3171
  </div>
@@ -3147,17 +3176,17 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3147
3176
  </div>
3148
3177
  ${t.runs.length===0?d`<div class="muted" style="font-size: 13px;">No runs recorded yet.</div>`:d`
3149
3178
  <div class="list">
3150
- ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>Gv(i))}
3179
+ ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>Zv(i))}
3151
3180
  </div>
3152
3181
  `}
3153
3182
  </div>
3154
3183
 
3155
3184
  </div>
3156
3185
  </div>
3157
- `}function Vv(e){const t=e.toLowerCase();return t==="ok"||t==="success"?"chip chip-ok":t==="error"||t==="fail"||t==="failed"?"chip chip-warn":"chip"}function Gv(e){return d`
3186
+ `}function Xv(e){const t=e.toLowerCase();return t==="ok"||t==="success"?"chip chip-ok":t==="error"||t==="fail"||t==="failed"?"chip chip-warn":"chip"}function Zv(e){return d`
3158
3187
  <div class="list-item" style="grid-template-columns: 1fr; gap: 6px;">
3159
3188
  <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
3160
- <span class=${Vv(e.status)} style="font-size: 11px; padding: 2px 8px;">
3189
+ <span class=${Xv(e.status)} style="font-size: 11px; padding: 2px 8px;">
3161
3190
  ${e.status}
3162
3191
  </span>
3163
3192
  <span class="muted" style="font-size: 12px;">${Pi(e.ts)}</span>
@@ -3171,7 +3200,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3171
3200
  </details>
3172
3201
  `:S}
3173
3202
  </div>
3174
- `}function Qv(e){var s;const t=((s=e.report)==null?void 0:s.skills)??[],n=e.filter.trim().toLowerCase(),i=n?t.filter(o=>[o.name,o.description,o.preloaded?"preloaded":"user"].join(" ").toLowerCase().includes(n)):t;return d`
3203
+ `}function eb(e){var s;const t=((s=e.report)==null?void 0:s.skills)??[],n=e.filter.trim().toLowerCase(),i=n?t.filter(o=>[o.name,o.description,o.preloaded?"preloaded":"user"].join(" ").toLowerCase().includes(n)):t;return d`
3175
3204
  <section class="card">
3176
3205
  <div class="row" style="justify-content: space-between;">
3177
3206
  <div>
@@ -3202,14 +3231,14 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3202
3231
 
3203
3232
  ${i.length===0?d`<div class="muted" style="margin-top: 16px;">No skills found.</div>`:d`
3204
3233
  <div class="list" style="margin-top: 16px;">
3205
- ${i.map(o=>Yv(o,e))}
3234
+ ${i.map(o=>tb(o,e))}
3206
3235
  </div>
3207
3236
  `}
3208
3237
  </section>
3209
3238
 
3210
- ${e.detail?Jv(e):S}
3211
- ${e.addModal?Xv(e):S}
3212
- `}function Yv(e,t){const n=t.busyKey===e.skillKey,i=t.edits[e.skillKey]??"",s=t.messages[e.skillKey]??null,o=e.install.length>0&&e.missing.bins.length>0,r=[...e.missing.bins.map(u=>`bin:${u}`),...e.missing.env.map(u=>`env:${u}`),...e.missing.config.map(u=>`config:${u}`),...e.missing.os.map(u=>`os:${u}`)],a=[];return e.disabled&&a.push("disabled"),e.blockedByAllowlist&&a.push("blocked by allowlist"),d`
3239
+ ${e.detail?nb(e):S}
3240
+ ${e.addModal?ib(e):S}
3241
+ `}function tb(e,t){const n=t.busyKey===e.skillKey,i=t.edits[e.skillKey]??"",s=t.messages[e.skillKey]??null,o=e.install.length>0&&e.missing.bins.length>0,r=[...e.missing.bins.map(u=>`bin:${u}`),...e.missing.env.map(u=>`env:${u}`),...e.missing.config.map(u=>`config:${u}`),...e.missing.os.map(u=>`os:${u}`)],a=[];return e.disabled&&a.push("disabled"),e.blockedByAllowlist&&a.push("blocked by allowlist"),d`
3213
3242
  <div class="list-item" style="cursor: pointer;" @click=${()=>t.onViewDetail(e.name)}>
3214
3243
  <div class="list-main">
3215
3244
  <div class="list-title">
@@ -3290,7 +3319,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3290
3319
  `:S}
3291
3320
  </div>
3292
3321
  </div>
3293
- `}function Jv(e){var r;const t=e.detail,n=["SKILL.md",...t.references.map(a=>a.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((r=t.references.find(a=>a.name===i))==null?void 0:r.content)??"";return d`
3322
+ `}function nb(e){var r;const t=e.detail,n=["SKILL.md",...t.references.map(a=>a.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((r=t.references.find(a=>a.name===i))==null?void 0:r.content)??"";return d`
3294
3323
  <div class="event-modal-overlay" @click=${a=>{a.target.classList.contains("event-modal-overlay")&&e.onDetailClose()}}>
3295
3324
  <div class="event-modal" style="width: min(720px, 100%);" @click=${a=>a.stopPropagation()}>
3296
3325
  <div class="event-modal__header">
@@ -3313,7 +3342,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3313
3342
  <pre style="white-space: pre-wrap; word-break: break-word; font-size: 12px; line-height: 1.5; max-height: 60vh; overflow-y: auto; background: var(--bg, #111); padding: 16px; border-radius: 8px; border: 1px solid var(--border);">${s}</pre>
3314
3343
  </div>
3315
3344
  </div>
3316
- `}function Xv(e){const t=e.drafts.length>0,n=e.busyKey==="__add__";return d`
3345
+ `}function ib(e){const t=e.drafts.length>0,n=e.busyKey==="__add__";return d`
3317
3346
  <div class="event-modal-overlay" @click=${s=>{s.target.classList.contains("event-modal-overlay")&&e.onAddClose()}}>
3318
3347
  <div class="event-modal" style="width: min(520px, 100%);" @click=${s=>s.stopPropagation()}>
3319
3348
  <div class="event-modal__header">
@@ -3362,10 +3391,10 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3362
3391
  `}
3363
3392
  </div>
3364
3393
  </div>
3365
- `}const Zv=["user","assistant","tool_call","tool_result","thinking","error"],Ya={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function Bu(e){return e==="tool"?"tool_call":e}function eb(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function tb(e){return e.split(":").slice(2).join(":")||e}function nb(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function ib(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const Ja=300;function sb(e,t){const n=Bu(e);return t[n]??!0}function ob(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!sb(i.type,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:nb(i,t));return d`
3394
+ `}const sb=["user","assistant","tool_call","tool_result","thinking","error"],Ya={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function Bu(e){return e==="tool"?"tool_call":e}function ob(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function rb(e){return e.split(":").slice(2).join(":")||e}function ab(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function lb(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const Ja=300;function cb(e,t){const n=Bu(e);return t[n]??!0}function ub(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!cb(i.type,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:ab(i,t));return d`
3366
3395
  <div>
3367
3396
  <div class="chip-row" style="margin-top: 10px;">
3368
- ${Zv.map(i=>d`
3397
+ ${sb.map(i=>d`
3369
3398
  <label class="chip session-log-chip ${i}">
3370
3399
  <input
3371
3400
  type="checkbox"
@@ -3398,13 +3427,13 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3398
3427
  ${e.error?d`<div class="callout danger" style="margin-top: 10px;">${e.error}</div>`:S}
3399
3428
 
3400
3429
  <div class="log-stream" style="margin-top: 10px;" @scroll=${e.onScroll}>
3401
- ${n.length===0?d`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=Bu(i.type),r=ib(i,s),a=e.expandedIds.has(r),u=i.content.length>Ja,c=a||!u?i.content:i.content.slice(0,Ja)+"…";return d`
3430
+ ${n.length===0?d`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=Bu(i.type),r=lb(i,s),a=e.expandedIds.has(r),u=i.content.length>Ja,c=a||!u?i.content:i.content.slice(0,Ja)+"…";return d`
3402
3431
  <div class="log-row session-entry ${o}">
3403
3432
  <div class="log-row-header">
3404
- <span class="log-time mono">${eb(i.timestamp)}</span>
3433
+ <span class="log-time mono">${ob(i.timestamp)}</span>
3405
3434
  <span class="session-log-type ${o}">${Ya[o]}</span>
3406
3435
  <span class="log-subsystem mono">${i.agentId}</span>
3407
- <span class="session-label mono">${tb(i.sessionKey)}</span>
3436
+ <span class="session-label mono">${rb(i.sessionKey)}</span>
3408
3437
  ${i.toolName?d`<span class="session-tool mono">${i.toolName}</span>`:S}
3409
3438
  ${i.toolCallId?d`<span class="session-call-id mono">${i.toolCallId.slice(0,12)}</span>`:S}
3410
3439
  ${i.model?d`<span class="session-model mono">${i.model}</span>`:S}
@@ -3418,7 +3447,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3418
3447
  `})}
3419
3448
  </div>
3420
3449
  </div>
3421
- `}const no=["trace","debug","info","warn","error","fatal"];function rb(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function Nu(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function ab(e){const t=e.logsSubTab==="session";return d`
3450
+ `}const no=["trace","debug","info","warn","error","fatal"];function db(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function Nu(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function pb(e){const t=e.logsSubTab==="session";return d`
3422
3451
  <section class="card">
3423
3452
  <div class="logs-toolbar">
3424
3453
  <div class="sp-tabs" style="margin: 0;">
@@ -3475,9 +3504,9 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3475
3504
  </div>
3476
3505
  </div>
3477
3506
 
3478
- ${t?ob(e.sessionLogsProps):lb(e)}
3507
+ ${t?ub(e.sessionLogsProps):hb(e)}
3479
3508
  </section>
3480
- `}function lb(e){const t=e.filterText.trim().toLowerCase();no.some(i=>!e.levelFilters[i]);const n=e.entries.filter(i=>i.level&&!e.levelFilters[i.level]?!1:Nu(i,t));return d`
3509
+ `}function hb(e){const t=e.filterText.trim().toLowerCase();no.some(i=>!e.levelFilters[i]);const n=e.entries.filter(i=>i.level&&!e.levelFilters[i.level]?!1:Nu(i,t));return d`
3481
3510
  <div class="chip-row" style="margin-top: 10px; align-items: center;">
3482
3511
  ${no.map(i=>d`
3483
3512
  <label class="chip log-chip ${i}">
@@ -3509,7 +3538,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3509
3538
  ${n.length===0?d`<div class="muted" style="padding: 12px;">No log entries.</div>`:[...n].reverse().map(i=>d`
3510
3539
  <div class="log-row">
3511
3540
  <div class="log-row-header">
3512
- <span class="log-time mono">${rb(i.time)}</span>
3541
+ <span class="log-time mono">${db(i.time)}</span>
3513
3542
  <span class="log-level ${i.level??""}">${i.level??""}</span>
3514
3543
  <span class="log-subsystem mono">${i.subsystem??""}</span>
3515
3544
  </div>
@@ -3517,12 +3546,12 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3517
3546
  </div>
3518
3547
  `)}
3519
3548
  </div>
3520
- `}const cb=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"logs",label:"Logs"}];function ub(e){switch(e.activeTab){case"cron":return Qa(e.cronProps);case"skills":return Qv(e.skillsProps);case"logs":return ab(e.logsProps);default:return Qa(e.cronProps)}}function db(e){return e.connected?d`
3549
+ `}const fb=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"logs",label:"Logs"}];function gb(e){switch(e.activeTab){case"cron":return Qa(e.cronProps);case"skills":return eb(e.skillsProps);case"logs":return pb(e.logsProps);default:return Qa(e.cronProps)}}function mb(e){return e.connected?d`
3521
3550
  <div class="setup-container">
3522
3551
  ${kt("Advanced",e.wsProps)}
3523
3552
  <div class="setup-card sp-card-advanced" style="text-align: left;">
3524
3553
  <div class="sp-tabs">
3525
- ${cb.map(t=>d`
3554
+ ${fb.map(t=>d`
3526
3555
  <button
3527
3556
  class="sp-tab ${e.activeTab===t.id?"active":""}"
3528
3557
  @click=${()=>e.onTabChange(t.id)}
@@ -3531,7 +3560,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3531
3560
  </button>
3532
3561
  `)}
3533
3562
  </div>
3534
- ${ub(e)}
3563
+ ${gb(e)}
3535
3564
  </div>
3536
3565
  </div>
3537
3566
  `:d`
@@ -3541,19 +3570,19 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3541
3570
  <p>Connecting to gateway...</p>
3542
3571
  </div>
3543
3572
  </div>
3544
- `}function Xa(e){if(!e.show)return S;const t=ze(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const r=f=>{var h;o=f.target.value;const b=(h=f.target.closest(".login-card"))==null?void 0:h.querySelector(".login-change-pin");b&&(b.style.display=o==="__master__"?"":"none")},a=f=>b=>{const h=b.target;h.value=h.value.replace(/\D/g,"").slice(0,6),f(h.value)},u=!n&&e.accounts.length>1?d`
3573
+ `}function Xa(e){if(!e.show)return S;const t=ze(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const r=h=>{var f;o=h.target.value;const b=(f=h.target.closest(".login-card"))==null?void 0:f.querySelector(".login-change-pin");b&&(b.style.display=o==="__master__"?"":"none")},a=h=>b=>{const f=b.target;f.value=f.value.replace(/\D/g,"").slice(0,6),h(f.value)},u=!n&&e.accounts.length>1?d`
3545
3574
  <select
3546
3575
  class="login-account-select"
3547
3576
  @change=${r}
3548
3577
  ?disabled=${e.busy||s}
3549
3578
  >
3550
- ${e.accounts.map((f,b)=>d`
3551
- <option value=${f.id} ?selected=${b===0}>
3552
- ${f.displayName}
3579
+ ${e.accounts.map((h,b)=>d`
3580
+ <option value=${h.id} ?selected=${b===0}>
3581
+ ${h.displayName}
3553
3582
  </option>
3554
3583
  `)}
3555
3584
  </select>
3556
- `:S;if(i){let f="",b="",h="";const v=k=>{var $;k.preventDefault(),!s&&(!f||!b||!h||b===h&&o&&(($=e.onChangePin)==null||$.call(e,o,f,b)))};return d`
3585
+ `:S;if(i){let h="",b="",f="";const v=k=>{var $;k.preventDefault(),!s&&(!h||!b||!f||b===f&&o&&(($=e.onChangePin)==null||$.call(e,o,h,b)))};return d`
3557
3586
  <div class="login-overlay">
3558
3587
  <div class="login-card">
3559
3588
  <img class="login-logo" src="${t.iconUrl}" alt="${t.name}" />
@@ -3570,7 +3599,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3570
3599
  maxlength="6"
3571
3600
  placeholder="Current PIN"
3572
3601
  ?disabled=${s}
3573
- @input=${a(k=>{f=k})}
3602
+ @input=${a(k=>{h=k})}
3574
3603
  autofocus
3575
3604
  />
3576
3605
  <input
@@ -3593,7 +3622,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3593
3622
  maxlength="6"
3594
3623
  placeholder="Confirm new PIN"
3595
3624
  ?disabled=${s}
3596
- @input=${a(k=>{h=k})}
3625
+ @input=${a(k=>{f=k})}
3597
3626
  />
3598
3627
  ${e.changePinError?d`<p class="login-error">${e.changePinError}</p>`:S}
3599
3628
  ${e.changePinSuccess?d`<p class="login-success">${e.changePinSuccess}</p>`:S}
@@ -3612,7 +3641,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3612
3641
  </p>
3613
3642
  </div>
3614
3643
  </div>
3615
- `}let c="",l="";const p=f=>{if(f.preventDefault(),!e.busy)if(n){if(!c||!l||c!==l)return;e.onSubmit(c)}else{if(!c||!o)return;e.onSubmit(o,c)}};return d`
3644
+ `}let c="",l="";const p=h=>{if(h.preventDefault(),!e.busy)if(n){if(!c||!l||c!==l)return;e.onSubmit(c)}else{if(!c||!o)return;e.onSubmit(o,c)}};return d`
3616
3645
  <div class="login-overlay">
3617
3646
  <div class="login-card">
3618
3647
  <img class="login-logo" src="${t.iconUrl}" alt="${t.name}" />
@@ -3631,7 +3660,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3631
3660
  maxlength="6"
3632
3661
  placeholder="${n?"Choose a 4-6 digit PIN":"PIN"}"
3633
3662
  ?disabled=${e.busy}
3634
- @input=${a(f=>{c=f})}
3663
+ @input=${a(h=>{c=h})}
3635
3664
  autofocus
3636
3665
  />
3637
3666
  ${n?d`
@@ -3644,7 +3673,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3644
3673
  maxlength="6"
3645
3674
  placeholder="Confirm PIN"
3646
3675
  ?disabled=${e.busy}
3647
- @input=${a(f=>{l=f})}
3676
+ @input=${a(h=>{l=h})}
3648
3677
  />
3649
3678
  `:S}
3650
3679
  ${e.error?d`<p class="login-error">${e.error}</p>`:S}
@@ -3656,16 +3685,16 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3656
3685
  ${e.busy?d`<span class="login-spinner"></span>`:n?"Set PIN":"Unlock"}
3657
3686
  </button>
3658
3687
  </form>
3659
- ${n?d`<p class="login-hint">This PIN protects all accounts on this device. You'll need it every time you open the dashboard.</p>`:e.accounts.some(f=>f.id==="__master__")?d`<p class="login-hint login-change-pin" style="margin-top: 16px;${o!=="__master__"?" display: none;":""}">
3688
+ ${n?d`<p class="login-hint">This PIN protects all accounts on this device. You'll need it every time you open the dashboard.</p>`:e.accounts.some(h=>h.id==="__master__")?d`<p class="login-hint login-change-pin" style="margin-top: 16px;${o!=="__master__"?" display: none;":""}">
3660
3689
  <a
3661
3690
  class="login-link"
3662
3691
  href="#"
3663
- @click=${f=>{var b;f.preventDefault(),(b=e.onToggleChangePinMode)==null||b.call(e)}}
3692
+ @click=${h=>{var b;h.preventDefault(),(b=e.onToggleChangePinMode)==null||b.call(e)}}
3664
3693
  >Change PIN</a>
3665
3694
  </p>`:S}
3666
3695
  </div>
3667
3696
  </div>
3668
- `}function pb(e){if(!e.connected)return d`
3697
+ `}function yb(e){if(!e.connected)return d`
3669
3698
  <div class="setup-container">
3670
3699
  <div class="setup-card">
3671
3700
  <div class="setup-spinner"></div>
@@ -3681,7 +3710,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3681
3710
  ${Lu(t)}
3682
3711
  </div>
3683
3712
  </div>
3684
- `}async function hb(e){if(!(!e.client||!e.connected)&&!e.agentsLoading){e.agentsLoading=!0,e.agentsError=null;try{const t=await e.client.request("agents.list",{});t&&(e.agentsList=t)}catch(t){e.agentsError=String(t)}finally{e.agentsLoading=!1}}}async function Cn(e){if(!(!e.client||!e.connected)&&!e.workspacesLoading){e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});e.workspaces=t.workspaces}catch(t){e.workspacesError=String(t)}finally{e.workspacesLoading=!1}}}async function fb(e,t){var i,s;if(!e.client||!e.connected||e.workspaceSaving)return;const n=t.name.trim();if(!n){e.workspacesError="Account name is required.";return}e.workspaceSaving=!0,e.workspacesError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const r=o.hash;if(!r){e.workspacesError="Config hash missing; reload and retry.";return}const a={name:n,baseHash:r,whatsappAccountName:n};(i=t.workspacePath)!=null&&i.trim()&&(a.workspaceDir=t.workspacePath.trim());const u=await e.client.request("workspaces.create",a);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Cn(e),(s=t.onCreated)==null||s.call(t,u)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function gb(e,t){if(!(!e.client||!e.connected)&&!e.workspaceSaving){e.workspaceSaving=!0,e.workspacesError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=n.hash;if(!i){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.remove",{name:t,baseHash:i}),e.workspaceRemoveConfirm=null,await Cn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function mb(e,t,n){if(!(!e.client||!e.connected)){e.workspacesError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.hash;if(!s){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.rename",{name:t,displayName:n,baseHash:s}),await Cn(e)}catch(i){e.workspacesError=String(i)}}}const ei=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:fb,loadWorkspaces:Cn,removeWorkspace:gb,renameWorkspace:mb},Symbol.toStringTag,{value:"Module"})),Ou={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"taskmaster-control-ui",SETUP_UI:"setup-ui",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"taskmaster-macos",IOS_APP:"taskmaster-ios",ANDROID_APP:"taskmaster-android",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"taskmaster-probe",PUBLIC_CHAT:"public-chat"},Za=Ou,io={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Ou));new Set(Object.values(io));function yb(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),i=e.token??"",s=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),i];return t==="v2"&&s.push(e.nonce??""),s.join("|")}const vb=4008;class bb{constructor(t){this.opts=t,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=null,this.connectNonce=null,this.connectSent=!1,this.connectTimer=null,this.backoffMs=800}start(){this.closed=!1,this.connect()}stop(){var t;this.closed=!0,(t=this.ws)==null||t.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.onopen=()=>this.queueConnect(),this.ws.onmessage=t=>this.handleMessage(String(t.data??"")),this.ws.onclose=t=>{var i,s;const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),(s=(i=this.opts).onClose)==null||s.call(i,{code:t.code,reason:n}),this.scheduleReconnect()},this.ws.onerror=()=>{})}scheduleReconnect(){if(this.closed)return;const t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),t)}flushPending(t){for(const[,n]of this.pending)n.reject(t);this.pending.clear()}async sendConnect(){var p;if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=this.opts.role??"operator",n=this.opts.scopes??["operator.admin","operator.approvals","operator.pairing"],s=!(t!=="operator")&&typeof crypto<"u"&&!!crypto.subtle;let o=null,r=!1,a=this.opts.token;if(s){o=await gh();const f=(p=vh({deviceId:o.deviceId,role:t}))==null?void 0:p.token;a=f??this.opts.token,r=!!(f&&this.opts.token)}const u=a||this.opts.password?{token:a,password:this.opts.password}:void 0;let c;if(s&&o){const f=Date.now(),b=this.connectNonce??void 0,h=yb({deviceId:o.deviceId,clientId:this.opts.clientName??Za.CONTROL_UI,clientMode:this.opts.mode??io.WEBCHAT,role:t,scopes:n,signedAtMs:f,token:a??null,nonce:b}),v=await mh(o.privateKey,h);c={id:o.deviceId,publicKey:o.publicKey,signature:v,signedAt:f,nonce:b}}const l={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Za.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??io.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:u,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",l).then(f=>{var b,h,v;(b=f==null?void 0:f.auth)!=null&&b.deviceToken&&o&&bh({deviceId:o.deviceId,role:f.auth.role??t,token:f.auth.deviceToken,scopes:f.auth.scopes??[]}),this.backoffMs=800,(v=(h=this.opts).onHello)==null||v.call(h,f)}).catch(()=>{var f;r&&o&&wh({deviceId:o.deviceId,role:t}),(f=this.ws)==null||f.close(vb,"connect failed")})}handleMessage(t){var s,o,r,a,u,c;let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const l=n;if(l.event==="connect.challenge"){const f=l.payload,b=f&&typeof f.nonce=="string"?f.nonce:null;b&&(this.connectNonce=b,this.sendConnect());return}const p=typeof l.seq=="number"?l.seq:null;p!==null&&(this.lastSeq!==null&&p>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:p})),this.lastSeq=p);try{(a=(r=this.opts).onEvent)==null||a.call(r,l)}catch(f){console.error("[gateway] event handler error:",f)}return}if(i.type==="res"){const l=n,p=this.pending.get(l.id);if(!p)return;if(this.pending.delete(l.id),l.ok)p.resolve(l.payload);else{const f=new Error(((u=l.error)==null?void 0:u.message)??"request failed");f.payload=l.payload,f.details=(c=l.error)==null?void 0:c.details,p.reject(f)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=ho(),s={type:"req",id:i,method:t,params:n},o=new Promise((r,a)=>{this.pending.set(i,{resolve:u=>r(u),reject:a})});return this.ws.send(JSON.stringify(s)),o}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}function so(e){return typeof e=="object"&&e!==null}function wb(e){if(!so(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!so(n))return null;const i=typeof n.command=="string"?n.command.trim():"";if(!i)return null;const s=typeof e.createdAtMs=="number"?e.createdAtMs:0,o=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!s||!o?null:{id:t,request:{command:i,cwd:typeof n.cwd=="string"?n.cwd:null,host:typeof n.host=="string"?n.host:null,security:typeof n.security=="string"?n.security:null,ask:typeof n.ask=="string"?n.ask:null,agentId:typeof n.agentId=="string"?n.agentId:null,resolvedPath:typeof n.resolvedPath=="string"?n.resolvedPath:null,sessionKey:typeof n.sessionKey=="string"?n.sessionKey:null},createdAtMs:s,expiresAtMs:o}}function kb(e){if(!so(e))return null;const t=typeof e.id=="string"?e.id.trim():"";return t?{id:t,decision:typeof e.decision=="string"?e.decision:null,resolvedBy:typeof e.resolvedBy=="string"?e.resolvedBy:null,ts:typeof e.ts=="number"?e.ts:null}:null}function Fu(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Sb(e,t){const n=Fu(e).filter(i=>i.id!==t.id);return n.push(t),n}function el(e,t){return Fu(e).filter(n=>n.id!==t)}class $b{constructor(){this.canvas=null,this.ctx=null,this.img=new Image,this.pendingFrame=null,this.rafId=null,this.deviceWidth=1280,this.deviceHeight=720,this.lastMouseMoveAt=0,this.MOUSE_THROTTLE_MS=30}attach(t){this.canvas=t,this.ctx=t.getContext("2d")}detach(){this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.canvas=null,this.ctx=null,this.pendingFrame=null}updateFrame(t,n){if(n!=null&&n.deviceWidth&&(this.deviceWidth=n.deviceWidth),n!=null&&n.deviceHeight&&(this.deviceHeight=n.deviceHeight),this.pendingFrame=t,!this.canvas){const i=document.getElementById("browser-screencast-canvas");i&&this.attach(i)}this.rafId==null&&(this.rafId=requestAnimationFrame(()=>this.renderFrame()))}renderFrame(){this.rafId=null;const t=this.pendingFrame;!t||!this.canvas||!this.ctx||(this.pendingFrame=null,this.img.onload=()=>{!this.canvas||!this.ctx||((this.canvas.width!==this.img.width||this.canvas.height!==this.img.height)&&(this.canvas.width=this.img.width,this.canvas.height=this.img.height),this.ctx.drawImage(this.img,0,0))},this.img.src=`data:image/jpeg;base64,${t}`)}translateCoordinates(t,n){if(!this.canvas)return{x:t,y:n};const i=this.canvas.getBoundingClientRect(),s=this.canvas.width/i.width,o=this.canvas.height/i.height,r=this.deviceWidth/this.canvas.width,a=this.deviceHeight/this.canvas.height;return{x:Math.round(t*s*r),y:Math.round(n*o*a)}}shouldThrottleMouseMove(){const t=performance.now();return t-this.lastMouseMoveAt<this.MOUSE_THROTTLE_MS?!0:(this.lastMouseMoveAt=t,!1)}getDeviceDimensions(){return{width:this.deviceWidth,height:this.deviceHeight}}}let Ts=null;function bn(){return Ts||(Ts=new $b),Ts}function er(e){return e instanceof Error?e.message:String(e)}async function xb(e){if(!e.client){console.error("[browser] startScreencast: no client"),e.browserError="Not connected to gateway";return}if(!e.connected){console.error("[browser] startScreencast: client exists but not connected"),e.browserError="Not connected to gateway";return}console.log("[browser] startScreencast: sending request"),e.browserLoading=!0,e.browserError=null;try{const t=await e.client.request("browser.screencast.start",{quality:60,maxWidth:1280,maxHeight:720});console.log("[browser] startScreencast response:",t),t!=null&&t.ok?e.browserScreencastActive=!0:(console.warn("[browser] startScreencast: response did not have ok=true",t),e.browserError="Screencast start failed (no ok in response)")}catch(t){console.error("[browser] startScreencast error:",t),e.browserError=er(t)}finally{e.browserLoading=!1}}async function Ab(e){if(!(!e.client||!e.connected)){e.browserLoading=!0,e.browserFullscreen=!1;try{await e.client.request("browser.screencast.stop",{}),e.browserScreencastActive=!1,e.browserScreencastFrame=null,e.browserScreencastMetadata=null}catch(t){e.browserError=er(t)}finally{e.browserLoading=!1}}}async function _s(e,t,n,i,s){if(!(!e.client||!e.connected||!e.browserInputMode))try{await e.client.request("browser.screencast.input",{type:"mouse",action:t,x:n,y:i,button:s??"left",clickCount:t==="mousePressed"?1:0})}catch{}}async function Ms(e,t,n,i){if(!(!e.client||!e.connected||!e.browserInputMode))try{await e.client.request("browser.screencast.input",{type:"key",action:t,key:n,...i!=null&&i.text?{text:i.text}:{},...i!=null&&i.code?{code:i.code}:{},...i!=null&&i.modifiers?{modifiers:i.modifiers}:{}})}catch{}}async function Eb(e){if(!(!e.client||!e.connected))try{await e.client.request("browser.handoff.complete",{}),e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}catch(t){e.browserError=er(t)}}function Cb(e){e.browserInputMode=!e.browserInputMode}function Tb(e){e.browserFullscreen=!e.browserFullscreen,bn().detach()}function _b(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,bn().updateFrame(t.data,t.metadata)}function Mb(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Pb(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function oo(e,t){if(!e.client||!e.connected)return;const n=e.sessionKey.trim(),i=n?{sessionKey:n}:{};try{const s=await e.client.request("agent.identity.get",i);if(!s)return;const o=Ds(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function ro(e){return(await e.request("apikeys.list")).providers??[]}async function tl(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Lb(e,t){await e.request("apikeys.remove",{provider:t})}const Ei="taskmaster_update_pending";async function Uu(e){var t,n;if(!(!e.client||!e.connected)&&!e.updateChecking){e.updateChecking=!0,e.updateMessage=null,(t=e.requestUpdate)==null||t.call(e);try{const i=await e.client.request("update.status",{});e.currentVersion=i.current,e.latestVersion=i.latest,e.updateAvailable=i.updateAvailable,e.updateMessage=i.updateAvailable?`v${i.latest} available`:"Up to date"}catch(i){e.updateMessage=`Check failed: ${String(i)}`,e.updateAvailable=null}finally{e.updateChecking=!1,(n=e.requestUpdate)==null||n.call(e)}}}async function Ib(e){var t,n,i,s;if(!(!e.client||e.updateRunning)){e.updateRunning=!0,e.updateMessage="Starting update...",e.updateProgressSteps=[],e.updateLastResult=null,(t=e.requestUpdate)==null||t.call(e);try{localStorage.setItem(Ei,String(Date.now())),localStorage.removeItem(tr)}catch{}try{const o=await e.client.request("update.run",{restartDelayMs:2e3,note:"Update from setup page"});if(o.ok&&o.result.status==="ok")e.updateMessage="Updated — restarting gateway...",(n=e.requestUpdate)==null||n.call(e);else if(o.ok&&o.result.status==="skipped")wn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw wn(),new Error(o.result.reason||"Update failed")}catch(o){wn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function Rb(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const r=t.name,a=t.index,u=t.total;e.updateMessage=`Updating: ${r} (${a+1}/${u})`;const c=e.updateProgressSteps.find(l=>l.index===a);c?(c.status="running",c.name=r):e.updateProgressSteps=[...e.updateProgressSteps,{name:r,index:a,total:u,status:"running"}],(i=e.requestUpdate)==null||i.call(e)}else if(n==="step-done"){const r=t.name,a=t.index,u=t.total,c=t.ok,l=t.durationMs,p=e.updateProgressSteps.find(b=>b.index===a);p?(p.status=c?"done":"failed",p.durationMs=l):e.updateProgressSteps=[...e.updateProgressSteps,{name:r,index:a,total:u,status:c?"done":"failed",durationMs:l}];const f=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${r} done (${a+1}/${u})`:`Update step failed: ${r}${f}`,(s=e.requestUpdate)==null||s.call(e)}else if(n==="complete"){if(t.status==="ok")e.updateMessage="Update complete — restarting gateway...";else{const a=t.reason;e.updateMessage=a?`Update failed: ${a}`:"Update failed",e.updateRunning=!1,wn()}(o=e.requestUpdate)==null||o.call(e)}}async function Db(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=Nb();wn();try{const r=await e.client.request("update.lastResult",{});if(!r.ok||!r.result)return;const a=5*6e4,u=Date.now()-r.result.ts<a;if(!t&&!u||Ob(r.result.ts))return;e.updateLastResult=r.result;const c=(n=r.result.after)==null?void 0:n.version;if(r.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,r.result.status==="ok"){const l=(i=r.result.before)==null?void 0:i.version,p=c??r.result.currentVersion;e.updateMessage=l?`Updated: v${l} → v${p}`:`Updated to v${p}`}else{const l=r.result.reason??((s=r.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${l}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const tr="taskmaster_update_dismissed";function Bb(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(tr,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function Nb(){try{const e=localStorage.getItem(Ei);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(Ei),!1):!0:!1}catch{return!1}}function wn(){try{localStorage.removeItem(Ei)}catch{}}function Ob(e){try{const t=localStorage.getItem(tr);return t?Number(t)>=e:!1}catch{return!1}}function Ps(e,t){var a,u,c;const n=(e??"").trim(),i=(a=t.mainSessionKey)==null?void 0:a.trim();if(!i)return n;if(!n)return i;const s=((u=t.mainKey)==null?void 0:u.trim())||"main",o=(c=t.defaultAgentId)==null?void 0:c.trim();return n==="main"||n===s||o&&(n===`agent:${o}:main`||n===`agent:${o}:${s}`)?i:n}function Fb(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=Ps(e.sessionKey,t),i=Ps(e.settings.sessionKey,t),s=Ps(e.settings.lastActiveSessionKey,t),o=n||i||e.sessionKey,r={...e.settings,sessionKey:i||o,lastActiveSessionKey:s||o},a=r.sessionKey!==e.settings.sessionKey||r.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),a&&Ze(e,r)}function _e(e){var s;e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;const t=!!e.publicChat,n=e.setup||e.filesPage||e.browserPage||e.chatPage||e.adminsPage||e.contactsPage||e.advancedPage,i=t?"public-chat":n?"setup-ui":"taskmaster-control-ui";(s=e.client)==null||s.stop(),e.client=new bb({url:e.settings.gatewayUrl,token:t?void 0:e.settings.token.trim()?e.settings.token:void 0,password:t?void 0:e.password.trim()?e.password:void 0,clientName:i,mode:"webchat",role:t?"public":void 0,scopes:t?[]:void 0,onHello:o=>{var r;if(e.connected=!0,e.lastError=null,e.hello=o,t){nl(e,o),oo(e),(((r=e.publicChatConfig)==null?void 0:r.auth)??"anonymous")==="anonymous"&&jb(e);return}yi()&&(Do(),e.uninstallDone=!1),nl(e,o),e.handleAccessCheck(),Db(e).then(()=>{Uu(e)}),oo(e),hb(e),(e.chatPage||e.setup)&&Kb(e),xo(e,{quiet:!0}),$o(e,{quiet:!0}),Cn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Re(e),e.setup&&(zb(e),Hb(e),qb(e)),gi(e)},onClose:({code:o,reason:r})=>{e.connected=!1,o!==1012&&(e.lastError=`disconnected (${o}): ${r||"no reason"}`)},onEvent:o=>Ub(e,o),onGap:({expected:o,received:r})=>{console.warn(`[gateway] event gap: expected seq ${o}, got ${r}`),gi(e)}}),e.client.start()}function Ub(e,t){try{Wb(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function Wb(e,t){var n;if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),e.tab==="debug"&&(e.eventLog=e.eventLogBuffer),t.event==="agent"){if(e.onboarding)return;kp(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&Mc(e,i.sessionKey);const s=Dl(e,i);if((s==="final"||s==="error"||s==="aborted")&&(go(e),pf(e)),s==="final"){const o=e,r=Math.max((((n=o.chatMessages)==null?void 0:n.length)??0)+10,Ie);Le(o,{limit:r})}return}if(t.event==="suggestions"){const i=t.payload;(i==null?void 0:i.sessionKey)===e.sessionKey&&Array.isArray(i.suggestions)&&i.suggestions.length>0&&(e.chatSuggestion=i.suggestions[0]);return}if(t.event==="presence"){const i=t.payload;i!=null&&i.presence&&Array.isArray(i.presence)&&(e.presenceEntries=i.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"&&e.tab==="cron"&&Io(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&$o(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=wb(t.payload);if(i){e.execApprovalQueue=Sb(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=el(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){_b(e,t.payload);return}if(t.event==="browser.handoff"){Mb(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Pb(e);return}if(t.event==="exec.approval.resolved"){const i=kb(t.payload);i&&(e.execApprovalQueue=el(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){Rb(e,t.payload);return}}function nl(e,t){const n=t.snapshot;n!=null&&n.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n!=null&&n.health&&(e.debugHealth=n.health),n!=null&&n.sessionDefaults&&Fb(e,n.sessionDefaults)}async function Kb(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("models.list",{});Array.isArray(t==null?void 0:t.models)&&(e.chatModelCatalog=t.models)}catch{}}async function zb(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await ro(e.client)}catch{}}async function Hb(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status")}catch{}}async function qb(e){if(!(!e.client||!e.connected))try{e.wifiStatus=await e.client.request("wifi.status")}catch{}}const il="taskmaster_public_id";function Wu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${il}=`));if(t)return t.split("=")[1];const n=`anon-${((s=crypto.randomUUID)==null?void 0:s.call(crypto))??Math.random().toString(36).slice(2)}`,i=new Date(Date.now()+e*864e5).toUTCString();return document.cookie=`${il}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function jb(e){var n,i;if(!e.client||!e.connected)return;const t=Wu((n=e.publicChatConfig)==null?void 0:n.cookieTtlDays);try{const s=(i=e.publicChatConfig)==null?void 0:i.accountId,o=await e.client.request("public.session",{cookieId:t,accountId:s});o!=null&&o.sessionKey&&(e.publicChatSessionKey=o.sessionKey,e.sessionKey=o.sessionKey,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready",Le(e))}catch(s){console.error("[public-chat] failed to resolve anonymous session:",s),e.lastError="Failed to start chat session"}}let $e=!1,de=null,Ut="",Ci="";function Ku(e){return e.replace(/[\s\-()]/g,"")}function zu(){$e=!1,de=null,Ut="",Ci=""}async function Vb(e){if(!e.client||!e.connected)return;const t=Wu(e.cookieTtlDays);try{const n=await e.client.request("public.session",{cookieId:t,accountId:e.accountId});n!=null&&n.sessionKey&&e.onAuthenticated(n.sessionKey)}catch(n){de=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function sl(e){if(!e.client||$e)return;const t=Ku(Ut);if(!t){de="Please enter your phone number",e.requestUpdate();return}$e=!0,de=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:Ci.trim()||void 0,accountId:e.accountId});n!=null&&n.ok?e.onAuthStepChange("otp"):de=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){de=n instanceof Error?n.message:"Failed to send verification code"}finally{$e=!1,e.requestUpdate()}}async function ol(e,t){if(!(!e.client||$e)){if(!t.trim()){de="Please enter the verification code",e.requestUpdate();return}$e=!0,de=null,e.requestUpdate();try{const n=await e.client.request("public.otp.verify",{phone:Ku(Ut),code:t.trim(),accountId:e.accountId});n!=null&&n.ok&&n.sessionKey?(zu(),e.onAuthenticated(n.sessionKey)):de=(n==null?void 0:n.error)??"Invalid verification code"}catch(n){de=n instanceof Error?n.message:"Verification failed"}finally{$e=!1,e.requestUpdate()}}}function Ls(e){return S}function rl(e){return d`
3713
+ `}async function vb(e){if(!(!e.client||!e.connected)&&!e.agentsLoading){e.agentsLoading=!0,e.agentsError=null;try{const t=await e.client.request("agents.list",{});t&&(e.agentsList=t)}catch(t){e.agentsError=String(t)}finally{e.agentsLoading=!1}}}async function Cn(e){if(!(!e.client||!e.connected)&&!e.workspacesLoading){e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});e.workspaces=t.workspaces}catch(t){e.workspacesError=String(t)}finally{e.workspacesLoading=!1}}}async function bb(e,t){var i,s;if(!e.client||!e.connected||e.workspaceSaving)return;const n=t.name.trim();if(!n){e.workspacesError="Account name is required.";return}e.workspaceSaving=!0,e.workspacesError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const r=o.hash;if(!r){e.workspacesError="Config hash missing; reload and retry.";return}const a={name:n,baseHash:r,whatsappAccountName:n};(i=t.workspacePath)!=null&&i.trim()&&(a.workspaceDir=t.workspacePath.trim());const u=await e.client.request("workspaces.create",a);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Cn(e),(s=t.onCreated)==null||s.call(t,u)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function wb(e,t){if(!(!e.client||!e.connected)&&!e.workspaceSaving){e.workspaceSaving=!0,e.workspacesError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=n.hash;if(!i){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.remove",{name:t,baseHash:i}),e.workspaceRemoveConfirm=null,await Cn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function kb(e,t,n){if(!(!e.client||!e.connected)){e.workspacesError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.hash;if(!s){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.rename",{name:t,displayName:n,baseHash:s}),await Cn(e)}catch(i){e.workspacesError=String(i)}}}const ei=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:bb,loadWorkspaces:Cn,removeWorkspace:wb,renameWorkspace:kb},Symbol.toStringTag,{value:"Module"})),Ou={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"taskmaster-control-ui",SETUP_UI:"setup-ui",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"taskmaster-macos",IOS_APP:"taskmaster-ios",ANDROID_APP:"taskmaster-android",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"taskmaster-probe",PUBLIC_CHAT:"public-chat"},Za=Ou,io={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Ou));new Set(Object.values(io));function Sb(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),i=e.token??"",s=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),i];return t==="v2"&&s.push(e.nonce??""),s.join("|")}const $b=4008;class Ab{constructor(t){this.opts=t,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=null,this.connectNonce=null,this.connectSent=!1,this.connectTimer=null,this.backoffMs=800}start(){this.closed=!1,this.connect()}stop(){var t;this.closed=!0,(t=this.ws)==null||t.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.onopen=()=>this.queueConnect(),this.ws.onmessage=t=>this.handleMessage(String(t.data??"")),this.ws.onclose=t=>{var i,s;const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),(s=(i=this.opts).onClose)==null||s.call(i,{code:t.code,reason:n}),this.scheduleReconnect()},this.ws.onerror=()=>{})}scheduleReconnect(){if(this.closed)return;const t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),t)}flushPending(t){for(const[,n]of this.pending)n.reject(t);this.pending.clear()}async sendConnect(){var p;if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=this.opts.role??"operator",n=this.opts.scopes??["operator.admin","operator.approvals","operator.pairing"],s=!(t!=="operator")&&typeof crypto<"u"&&!!crypto.subtle;let o=null,r=!1,a=this.opts.token;if(s){o=await gh();const h=(p=vh({deviceId:o.deviceId,role:t}))==null?void 0:p.token;a=h??this.opts.token,r=!!(h&&this.opts.token)}const u=a||this.opts.password?{token:a,password:this.opts.password}:void 0;let c;if(s&&o){const h=Date.now(),b=this.connectNonce??void 0,f=Sb({deviceId:o.deviceId,clientId:this.opts.clientName??Za.CONTROL_UI,clientMode:this.opts.mode??io.WEBCHAT,role:t,scopes:n,signedAtMs:h,token:a??null,nonce:b}),v=await mh(o.privateKey,f);c={id:o.deviceId,publicKey:o.publicKey,signature:v,signedAt:h,nonce:b}}const l={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Za.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??io.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:u,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",l).then(h=>{var b,f,v;(b=h==null?void 0:h.auth)!=null&&b.deviceToken&&o&&bh({deviceId:o.deviceId,role:h.auth.role??t,token:h.auth.deviceToken,scopes:h.auth.scopes??[]}),this.backoffMs=800,(v=(f=this.opts).onHello)==null||v.call(f,h)}).catch(()=>{var h;r&&o&&wh({deviceId:o.deviceId,role:t}),(h=this.ws)==null||h.close($b,"connect failed")})}handleMessage(t){var s,o,r,a,u,c;let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const l=n;if(l.event==="connect.challenge"){const h=l.payload,b=h&&typeof h.nonce=="string"?h.nonce:null;b&&(this.connectNonce=b,this.sendConnect());return}const p=typeof l.seq=="number"?l.seq:null;p!==null&&(this.lastSeq!==null&&p>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:p})),this.lastSeq=p);try{(a=(r=this.opts).onEvent)==null||a.call(r,l)}catch(h){console.error("[gateway] event handler error:",h)}return}if(i.type==="res"){const l=n,p=this.pending.get(l.id);if(!p)return;if(this.pending.delete(l.id),l.ok)p.resolve(l.payload);else{const h=new Error(((u=l.error)==null?void 0:u.message)??"request failed");h.payload=l.payload,h.details=(c=l.error)==null?void 0:c.details,p.reject(h)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=ho(),s={type:"req",id:i,method:t,params:n},o=new Promise((r,a)=>{this.pending.set(i,{resolve:u=>r(u),reject:a})});return this.ws.send(JSON.stringify(s)),o}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}function so(e){return typeof e=="object"&&e!==null}function xb(e){if(!so(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!so(n))return null;const i=typeof n.command=="string"?n.command.trim():"";if(!i)return null;const s=typeof e.createdAtMs=="number"?e.createdAtMs:0,o=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!s||!o?null:{id:t,request:{command:i,cwd:typeof n.cwd=="string"?n.cwd:null,host:typeof n.host=="string"?n.host:null,security:typeof n.security=="string"?n.security:null,ask:typeof n.ask=="string"?n.ask:null,agentId:typeof n.agentId=="string"?n.agentId:null,resolvedPath:typeof n.resolvedPath=="string"?n.resolvedPath:null,sessionKey:typeof n.sessionKey=="string"?n.sessionKey:null},createdAtMs:s,expiresAtMs:o}}function Eb(e){if(!so(e))return null;const t=typeof e.id=="string"?e.id.trim():"";return t?{id:t,decision:typeof e.decision=="string"?e.decision:null,resolvedBy:typeof e.resolvedBy=="string"?e.resolvedBy:null,ts:typeof e.ts=="number"?e.ts:null}:null}function Fu(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Cb(e,t){const n=Fu(e).filter(i=>i.id!==t.id);return n.push(t),n}function el(e,t){return Fu(e).filter(n=>n.id!==t)}class Tb{constructor(){this.canvas=null,this.ctx=null,this.img=new Image,this.pendingFrame=null,this.rafId=null,this.deviceWidth=1280,this.deviceHeight=720,this.lastMouseMoveAt=0,this.MOUSE_THROTTLE_MS=30}attach(t){this.canvas=t,this.ctx=t.getContext("2d")}detach(){this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.canvas=null,this.ctx=null,this.pendingFrame=null}updateFrame(t,n){if(n!=null&&n.deviceWidth&&(this.deviceWidth=n.deviceWidth),n!=null&&n.deviceHeight&&(this.deviceHeight=n.deviceHeight),this.pendingFrame=t,!this.canvas){const i=document.getElementById("browser-screencast-canvas");i&&this.attach(i)}this.rafId==null&&(this.rafId=requestAnimationFrame(()=>this.renderFrame()))}renderFrame(){this.rafId=null;const t=this.pendingFrame;!t||!this.canvas||!this.ctx||(this.pendingFrame=null,this.img.onload=()=>{!this.canvas||!this.ctx||((this.canvas.width!==this.img.width||this.canvas.height!==this.img.height)&&(this.canvas.width=this.img.width,this.canvas.height=this.img.height),this.ctx.drawImage(this.img,0,0))},this.img.src=`data:image/jpeg;base64,${t}`)}translateCoordinates(t,n){if(!this.canvas)return{x:t,y:n};const i=this.canvas.getBoundingClientRect(),s=this.canvas.width/i.width,o=this.canvas.height/i.height,r=this.deviceWidth/this.canvas.width,a=this.deviceHeight/this.canvas.height;return{x:Math.round(t*s*r),y:Math.round(n*o*a)}}shouldThrottleMouseMove(){const t=performance.now();return t-this.lastMouseMoveAt<this.MOUSE_THROTTLE_MS?!0:(this.lastMouseMoveAt=t,!1)}getDeviceDimensions(){return{width:this.deviceWidth,height:this.deviceHeight}}}let Ts=null;function bn(){return Ts||(Ts=new Tb),Ts}function er(e){return e instanceof Error?e.message:String(e)}async function _b(e){if(!e.client){console.error("[browser] startScreencast: no client"),e.browserError="Not connected to gateway";return}if(!e.connected){console.error("[browser] startScreencast: client exists but not connected"),e.browserError="Not connected to gateway";return}console.log("[browser] startScreencast: sending request"),e.browserLoading=!0,e.browserError=null;try{const t=await e.client.request("browser.screencast.start",{quality:60,maxWidth:1280,maxHeight:720});console.log("[browser] startScreencast response:",t),t!=null&&t.ok?e.browserScreencastActive=!0:(console.warn("[browser] startScreencast: response did not have ok=true",t),e.browserError="Screencast start failed (no ok in response)")}catch(t){console.error("[browser] startScreencast error:",t),e.browserError=er(t)}finally{e.browserLoading=!1}}async function Mb(e){if(!(!e.client||!e.connected)){e.browserLoading=!0,e.browserFullscreen=!1;try{await e.client.request("browser.screencast.stop",{}),e.browserScreencastActive=!1,e.browserScreencastFrame=null,e.browserScreencastMetadata=null}catch(t){e.browserError=er(t)}finally{e.browserLoading=!1}}}async function _s(e,t,n,i,s){if(!(!e.client||!e.connected||!e.browserInputMode))try{await e.client.request("browser.screencast.input",{type:"mouse",action:t,x:n,y:i,button:s??"left",clickCount:t==="mousePressed"?1:0})}catch{}}async function Ms(e,t,n,i){if(!(!e.client||!e.connected||!e.browserInputMode))try{await e.client.request("browser.screencast.input",{type:"key",action:t,key:n,...i!=null&&i.text?{text:i.text}:{},...i!=null&&i.code?{code:i.code}:{},...i!=null&&i.modifiers?{modifiers:i.modifiers}:{}})}catch{}}async function Pb(e){if(!(!e.client||!e.connected))try{await e.client.request("browser.handoff.complete",{}),e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}catch(t){e.browserError=er(t)}}function Lb(e){e.browserInputMode=!e.browserInputMode}function Ib(e){e.browserFullscreen=!e.browserFullscreen,bn().detach()}function Rb(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,bn().updateFrame(t.data,t.metadata)}function Db(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Bb(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function oo(e,t){if(!e.client||!e.connected)return;const n=e.sessionKey.trim(),i=n?{sessionKey:n}:{};try{const s=await e.client.request("agent.identity.get",i);if(!s)return;const o=Ds(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function ro(e){return(await e.request("apikeys.list")).providers??[]}async function tl(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Nb(e,t){await e.request("apikeys.remove",{provider:t})}const Ei="taskmaster_update_pending";async function Uu(e){var t,n;if(!(!e.client||!e.connected)&&!e.updateChecking){e.updateChecking=!0,e.updateMessage=null,(t=e.requestUpdate)==null||t.call(e);try{const i=await e.client.request("update.status",{});e.currentVersion=i.current,e.latestVersion=i.latest,e.updateAvailable=i.updateAvailable,e.updateMessage=i.updateAvailable?`v${i.latest} available`:"Up to date"}catch(i){e.updateMessage=`Check failed: ${String(i)}`,e.updateAvailable=null}finally{e.updateChecking=!1,(n=e.requestUpdate)==null||n.call(e)}}}async function Ob(e){var t,n,i,s;if(!(!e.client||e.updateRunning)){e.updateRunning=!0,e.updateMessage="Starting update...",e.updateProgressSteps=[],e.updateLastResult=null,(t=e.requestUpdate)==null||t.call(e);try{localStorage.setItem(Ei,String(Date.now())),localStorage.removeItem(tr)}catch{}try{const o=await e.client.request("update.run",{restartDelayMs:2e3,note:"Update from setup page"});if(o.ok&&o.result.status==="ok")e.updateMessage="Updated — restarting gateway...",(n=e.requestUpdate)==null||n.call(e);else if(o.ok&&o.result.status==="skipped")wn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw wn(),new Error(o.result.reason||"Update failed")}catch(o){wn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function Fb(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const r=t.name,a=t.index,u=t.total;e.updateMessage=`Updating: ${r} (${a+1}/${u})`;const c=e.updateProgressSteps.find(l=>l.index===a);c?(c.status="running",c.name=r):e.updateProgressSteps=[...e.updateProgressSteps,{name:r,index:a,total:u,status:"running"}],(i=e.requestUpdate)==null||i.call(e)}else if(n==="step-done"){const r=t.name,a=t.index,u=t.total,c=t.ok,l=t.durationMs,p=e.updateProgressSteps.find(b=>b.index===a);p?(p.status=c?"done":"failed",p.durationMs=l):e.updateProgressSteps=[...e.updateProgressSteps,{name:r,index:a,total:u,status:c?"done":"failed",durationMs:l}];const h=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${r} done (${a+1}/${u})`:`Update step failed: ${r}${h}`,(s=e.requestUpdate)==null||s.call(e)}else if(n==="complete"){if(t.status==="ok")e.updateMessage="Update complete — restarting gateway...";else{const a=t.reason;e.updateMessage=a?`Update failed: ${a}`:"Update failed",e.updateRunning=!1,wn()}(o=e.requestUpdate)==null||o.call(e)}}async function Ub(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=Kb();wn();try{const r=await e.client.request("update.lastResult",{});if(!r.ok||!r.result)return;const a=5*6e4,u=Date.now()-r.result.ts<a;if(!t&&!u||zb(r.result.ts))return;e.updateLastResult=r.result;const c=(n=r.result.after)==null?void 0:n.version;if(r.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,r.result.status==="ok"){const l=(i=r.result.before)==null?void 0:i.version,p=c??r.result.currentVersion;e.updateMessage=l?`Updated: v${l} → v${p}`:`Updated to v${p}`}else{const l=r.result.reason??((s=r.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${l}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const tr="taskmaster_update_dismissed";function Wb(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(tr,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function Kb(){try{const e=localStorage.getItem(Ei);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(Ei),!1):!0:!1}catch{return!1}}function wn(){try{localStorage.removeItem(Ei)}catch{}}function zb(e){try{const t=localStorage.getItem(tr);return t?Number(t)>=e:!1}catch{return!1}}function Ps(e,t){var a,u,c;const n=(e??"").trim(),i=(a=t.mainSessionKey)==null?void 0:a.trim();if(!i)return n;if(!n)return i;const s=((u=t.mainKey)==null?void 0:u.trim())||"main",o=(c=t.defaultAgentId)==null?void 0:c.trim();return n==="main"||n===s||o&&(n===`agent:${o}:main`||n===`agent:${o}:${s}`)?i:n}function Hb(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=Ps(e.sessionKey,t),i=Ps(e.settings.sessionKey,t),s=Ps(e.settings.lastActiveSessionKey,t),o=n||i||e.sessionKey,r={...e.settings,sessionKey:i||o,lastActiveSessionKey:s||o},a=r.sessionKey!==e.settings.sessionKey||r.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),a&&Ze(e,r)}function _e(e){var s;e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;const t=!!e.publicChat,n=e.setup||e.filesPage||e.browserPage||e.chatPage||e.adminsPage||e.contactsPage||e.advancedPage,i=t?"public-chat":n?"setup-ui":"taskmaster-control-ui";(s=e.client)==null||s.stop(),e.client=new Ab({url:e.settings.gatewayUrl,token:t?void 0:e.settings.token.trim()?e.settings.token:void 0,password:t?void 0:e.password.trim()?e.password:void 0,clientName:i,mode:"webchat",role:t?"public":void 0,scopes:t?[]:void 0,onHello:o=>{var r;if(e.connected=!0,e.lastError=null,e.hello=o,t){nl(e,o),oo(e),(((r=e.publicChatConfig)==null?void 0:r.auth)??"anonymous")==="anonymous"&&Jb(e);return}yi()&&(Do(),e.uninstallDone=!1),nl(e,o),e.handleAccessCheck(),Ub(e).then(()=>{Uu(e)}),oo(e),vb(e),(e.chatPage||e.setup)&&Vb(e),Ao(e,{quiet:!0}),$o(e,{quiet:!0}),Cn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Re(e),e.setup&&(Gb(e),Qb(e),Yb(e)),gi(e)},onClose:({code:o,reason:r})=>{e.connected=!1,o!==1012&&(e.lastError=`disconnected (${o}): ${r||"no reason"}`)},onEvent:o=>qb(e,o),onGap:({expected:o,received:r})=>{console.warn(`[gateway] event gap: expected seq ${o}, got ${r}`),gi(e)}}),e.client.start()}function qb(e,t){try{jb(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function jb(e,t){var n;if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),e.tab==="debug"&&(e.eventLog=e.eventLogBuffer),t.event==="agent"){if(e.onboarding)return;kp(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&Mc(e,i.sessionKey);const s=Dl(e,i);if((s==="final"||s==="error"||s==="aborted")&&(go(e),pf(e)),s==="final"){const o=e,r=Math.max((((n=o.chatMessages)==null?void 0:n.length)??0)+10,Ie);Le(o,{limit:r})}return}if(t.event==="suggestions"){const i=t.payload;(i==null?void 0:i.sessionKey)===e.sessionKey&&Array.isArray(i.suggestions)&&i.suggestions.length>0&&(e.chatSuggestion=i.suggestions[0]);return}if(t.event==="presence"){const i=t.payload;i!=null&&i.presence&&Array.isArray(i.presence)&&(e.presenceEntries=i.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"&&e.tab==="cron"&&Io(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&$o(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=xb(t.payload);if(i){e.execApprovalQueue=Cb(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=el(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){Rb(e,t.payload);return}if(t.event==="browser.handoff"){Db(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Bb(e);return}if(t.event==="exec.approval.resolved"){const i=Eb(t.payload);i&&(e.execApprovalQueue=el(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){Fb(e,t.payload);return}}function nl(e,t){const n=t.snapshot;n!=null&&n.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n!=null&&n.health&&(e.debugHealth=n.health),n!=null&&n.sessionDefaults&&Hb(e,n.sessionDefaults)}async function Vb(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("models.list",{});Array.isArray(t==null?void 0:t.models)&&(e.chatModelCatalog=t.models)}catch{}}async function Gb(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await ro(e.client)}catch{}}async function Qb(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status")}catch{}}async function Yb(e){if(!(!e.client||!e.connected))try{e.wifiStatus=await e.client.request("wifi.status")}catch{}}const il="taskmaster_public_id";function Wu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${il}=`));if(t)return t.split("=")[1];const n=`anon-${((s=crypto.randomUUID)==null?void 0:s.call(crypto))??Math.random().toString(36).slice(2)}`,i=new Date(Date.now()+e*864e5).toUTCString();return document.cookie=`${il}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function Jb(e){var n,i;if(!e.client||!e.connected)return;const t=Wu((n=e.publicChatConfig)==null?void 0:n.cookieTtlDays);try{const s=(i=e.publicChatConfig)==null?void 0:i.accountId,o=await e.client.request("public.session",{cookieId:t,accountId:s});o!=null&&o.sessionKey&&(e.publicChatSessionKey=o.sessionKey,e.sessionKey=o.sessionKey,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready",Le(e))}catch(s){console.error("[public-chat] failed to resolve anonymous session:",s),e.lastError="Failed to start chat session"}}let $e=!1,de=null,Ut="",Ci="";function Ku(e){return e.replace(/[\s\-()]/g,"")}function zu(){$e=!1,de=null,Ut="",Ci=""}async function Xb(e){if(!e.client||!e.connected)return;const t=Wu(e.cookieTtlDays);try{const n=await e.client.request("public.session",{cookieId:t,accountId:e.accountId});n!=null&&n.sessionKey&&e.onAuthenticated(n.sessionKey)}catch(n){de=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function sl(e){if(!e.client||$e)return;const t=Ku(Ut);if(!t){de="Please enter your phone number",e.requestUpdate();return}$e=!0,de=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:Ci.trim()||void 0,accountId:e.accountId});n!=null&&n.ok?e.onAuthStepChange("otp"):de=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){de=n instanceof Error?n.message:"Failed to send verification code"}finally{$e=!1,e.requestUpdate()}}async function ol(e,t){if(!(!e.client||$e)){if(!t.trim()){de="Please enter the verification code",e.requestUpdate();return}$e=!0,de=null,e.requestUpdate();try{const n=await e.client.request("public.otp.verify",{phone:Ku(Ut),code:t.trim(),accountId:e.accountId});n!=null&&n.ok&&n.sessionKey?(zu(),e.onAuthenticated(n.sessionKey)):de=(n==null?void 0:n.error)??"Invalid verification code"}catch(n){de=n instanceof Error?n.message:"Verification failed"}finally{$e=!1,e.requestUpdate()}}}function Ls(e){return S}function rl(e){return d`
3685
3714
  <div class="public-auth__form">
3686
3715
  <label class="field public-auth__field">
3687
3716
  <span>Your name (optional)</span>
@@ -3744,7 +3773,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3744
3773
  Use a different number
3745
3774
  </button>
3746
3775
  </div>
3747
- `}function Gb(e){const{authMode:t,authStep:n}=e;return t==="anonymous"?d`
3776
+ `}function Zb(e){const{authMode:t,authStep:n}=e;return t==="anonymous"?d`
3748
3777
  <div class="setup-container">
3749
3778
  <div class="setup-card">
3750
3779
  <div class="setup-spinner"></div>
@@ -3778,7 +3807,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3778
3807
  <div class="public-auth__choices">
3779
3808
  <button
3780
3809
  class="btn primary public-auth__btn"
3781
- @click=${()=>{Vb(e)}}
3810
+ @click=${()=>{Xb(e)}}
3782
3811
  >
3783
3812
  Chat now
3784
3813
  </button>
@@ -3794,7 +3823,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3794
3823
  </p>
3795
3824
  </div>
3796
3825
  </div>
3797
- `}const nr="taskmaster-access-session",Hu={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function qu(){try{return localStorage.getItem(nr)}catch{return null}}function ju(e){try{localStorage.setItem(nr,e)}catch{}}function Qb(){try{localStorage.removeItem(nr)}catch{}}async function ll(e){if(e.client)try{const t=qu(),n=await e.client.request("access.status",{token:t});e.accessState={...e.accessState,checked:!0,hasPins:n.hasPins,hasMasterPin:n.hasMasterPin,accounts:n.accounts??[],authenticated:n.authenticated,workspace:n.workspace,master:n.master,error:null}}catch{e.accessState={...e.accessState,checked:!0,hasPins:!1,hasMasterPin:!1,accounts:[],authenticated:!0,error:null}}}async function Yb(e,t,n){if(e.client){e.accessState={...e.accessState,busy:!0,error:null};try{const i=await e.client.request("access.verify",{account:t,pin:n});i.ok&&i.token?(ju(i.token),e.accessState={...e.accessState,authenticated:!0,workspace:i.workspace??null,master:i.master??!1,busy:!1,error:null}):e.accessState={...e.accessState,busy:!1,error:i.message??"Incorrect PIN"}}catch{e.accessState={...e.accessState,busy:!1,error:"Failed to verify PIN"}}}}async function Jb(e,t){if(e.client){e.accessState={...e.accessState,busy:!0,error:null};try{const n=await e.client.request("access.setMasterPin",{pin:t});n.ok&&n.token?(ju(n.token),e.accessState={...e.accessState,checked:!0,hasPins:!0,hasMasterPin:!0,authenticated:!0,workspace:null,master:!0,busy:!1,error:null}):e.accessState={...e.accessState,busy:!1,error:"Failed to set PIN"}}catch{e.accessState={...e.accessState,busy:!1,error:"Failed to set PIN"}}}}async function Xb(e,t,n){if(!e.client)return!1;try{return(await e.client.request("access.setAccountPin",{workspace:t,pin:n})).ok}catch{return!1}}async function Zb(e){const t=qu();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}Qb(),e.accessState={...Hu,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}function ew(e,t="admin"){var s;if(!e)return[];const n=e.bindings;if(!Array.isArray(n))return[];const i=[];for(const o of n){if(!o||typeof o!="object"||o.agentId!==t&&o.agentId!=="management")continue;const r=o.match;if(!r||typeof r!="object"||(r.channel??"").toLowerCase()!=="whatsapp")continue;const u=r.peer;if(!u||typeof u!="object"||u.kind!=="dm")continue;const c=u.id??"";c&&i.push({phone:c,paired:((s=o.meta)==null?void 0:s.paired)===!0})}return i.sort((o,r)=>o.paired&&!r.paired?-1:!o.paired&&r.paired?1:0),i}function Vu(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,r=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const l=c.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="whatsapp")continue;const f=l.peer;if(!f||typeof f!="object"||f.kind!=="dm")continue;const b=f.id??"";b&&(c.meta&&o.set(b,c.meta),l.accountId&&r.set(b,l.accountId))}const a=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const l=c.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="whatsapp")return!0;const f=l.peer;return!f||typeof f!="object"?!0:f.kind!=="dm"}),u=t.map(c=>{const l=i??r.get(c.phone),p={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};l&&(p.accountId=l);const f={agentId:n,match:p},b=o.get(c.phone);return b?f.meta=b:c.paired&&(f.meta={paired:!0}),f});return[...a,...u]}async function Fi(e,t){if(!e.client||!e.connected)return;if(!t){e.adminPhones=[];return}if(e.adminsLoading)return;e.adminsLoading=!0,e.adminsError=null;const n=t;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.config;e.configForm=tt(s??{}),e.adminPhones=ew(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function Gu(e,t,n,i){var r,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n;let o=t.replace(/[\s\-\(\)]/g,"");if(!o){e.adminsError="Phone number is required";return}if(o.startsWith("+")||(o="+"+o),!/^\+[1-9]\d{6,14}$/.test(o)){e.adminsError="Invalid phone number. Use international format (e.g., +44 7504 472444)";return}if(e.adminPhones.some(u=>u.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const u=tt(e.configForm??((r=e.configSnapshot)==null?void 0:r.config)??{}),c=u.bindings??[],l=[...e.adminPhones,{phone:o}],p=Vu(c,l,s,i);Nl(u,["bindings"],p);const f=(a=e.configSnapshot)==null?void 0:a.hash;if(!f){e.adminsError="Config hash missing; reload and retry.";return}const b=ft(u);await e.client.request("config.set",{raw:b,baseHash:f}),await Fi(e,n)}catch(u){e.adminsError=String(u)}finally{e.adminsSaving=!1}}async function Qu(e,t,n,i){var r,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n,o=e.adminPhones.find(u=>u.phone===t);if(o!=null&&o.paired){e.adminsError="Cannot remove the paired phone. Unlink WhatsApp first.";return}e.adminsSaving=!0,e.adminsError=null;try{const u=tt(e.configForm??((r=e.configSnapshot)==null?void 0:r.config)??{}),c=u.bindings??[],l=e.adminPhones.filter(h=>h.phone!==t),p=Vu(c,l,s,i);Nl(u,["bindings"],p);const f=(a=e.configSnapshot)==null?void 0:a.hash;if(!f){e.adminsError="Config hash missing; reload and retry.";return}const b=ft(u);await e.client.request("config.set",{raw:b,baseHash:f}),await Fi(e,n)}catch(u){e.adminsError=String(u)}finally{e.adminsSaving=!1}}const tw=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:Gu,loadAdmins:Fi,removeAdmin:Qu},Symbol.toStringTag,{value:"Module"}));async function wt(e,t){if(!(!e.client||!e.connected)){if(!t){e.contactsRecords=[];return}if(!e.contactsLoading){e.contactsLoading=!0,e.contactsError=null;try{const n=e.contactsSearchQuery.trim(),i=n?await e.client.request("records.search",{query:n,workspace:t}):await e.client.request("records.list",{workspace:t});e.contactsRecords=i.records??[]}catch(n){e.contactsError=String(n)}finally{e.contactsLoading=!1}}}}async function Yu(e,t,n,i){if(!e.client||!e.connected||e.contactsSaving)return;let s=t.replace(/[\s\-\(\)]/g,"");const o=n.trim();if(!s){e.contactsError="Phone number is required";return}if(!o){e.contactsError="Name is required";return}if(s.startsWith("+")||(s="+"+s),!/^\+[1-9]\d{6,14}$/.test(s)){e.contactsError="Invalid phone number. Use international format (e.g., +44 7490 553305)";return}e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.set",{id:s,name:o,fields:{},workspace:i}),e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName="",await wt(e,i)}catch(r){e.contactsError=String(r)}finally{e.contactsSaving=!1}}async function Ju(e,t,n){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.delete",{id:t}),e.contactsEditingId===t&&(e.contactsEditingId=null),await wt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function ao(e,t,n,i,s){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.setField",{id:t,key:n,value:i}),await wt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Xu(e,t,n,i){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.deleteField",{id:t,key:n}),await wt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const nw=Object.freeze(Object.defineProperty({__proto__:null,addContact:Yu,deleteContact:Ju,deleteContactField:Xu,loadContacts:wt,setContactField:ao},Symbol.toStringTag,{value:"Module"}));function cn(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0}}}function iw(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),onAddAccount:()=>{e.addingWorkspace=!0},hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0}}}function sw(e){const t=oe(e);if(!t)return;const n=t.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return n==null?void 0:n.id}function ow(e){const t=oe(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function rw(e){var i;const t=oe(e);if(!t)return;const n=t.agents.find(s=>s.id.endsWith("-admin")||s.id==="admin");return(n==null?void 0:n.id)??((i=t.agents[0])==null?void 0:i.id)}function aw(e){return e.selectedWorkspace??void 0}function oe(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const lw=/^data:/i,cw=/^https?:\/\//i;function cl(e){var a,u;const t=((a=e.agentsList)==null?void 0:a.agents)??[],n=xl(e.sessionKey),i=(n==null?void 0:n.agentId)??((u=e.agentsList)==null?void 0:u.defaultId)??"main",s=t.find(c=>c.id===i),o=s==null?void 0:s.identity,r=(o==null?void 0:o.avatarUrl)??(o==null?void 0:o.avatar);if(r)return lw.test(r)||cw.test(r)?r:o==null?void 0:o.avatarUrl}function uw(e){var i;if(!e)return null;const t=(i=e.channelAccounts)==null?void 0:i.whatsapp;if(!t||t.length===0)return null;const n=t[0];return{running:n.running??!1,connected:n.connected??!1,linked:n.linked??!1,lastError:n.lastError}}function dw(e){var r;if(!e)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const t=(r=e.channelAccounts)==null?void 0:r.imessage;if(!t||t.length===0)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const n=t[0],i=n.running??!1,s=n.probe,o=s!=null?s.ok===!0:i;return{configured:n.configured??!1,running:i,connected:o,lastError:n.lastError??null,selfChatMode:n.mode==="self-chat"||!!n.selfChatMode,dmPolicy:n.dmPolicy??null,cliPath:n.cliPath??null}}function pw(e){var r;const t=(r=e.configSnapshot)==null?void 0:r.config;if(!t)return null;const n=t.bindings;if(!Array.isArray(n))return null;const i=n.find(a=>{var u,c;return((u=a.match)==null?void 0:u.channel)==="imessage"&&((c=a.meta)==null?void 0:c.imessageOwner)});if(!i)return null;const s=i.agentId;for(const a of e.workspaces)if(a.agents.some(u=>u.id===s))return a.name;if(s==="admin"||s==="public"){const a=e.workspaces.find(u=>u.isDefault);return(a==null?void 0:a.name)??null}const o=s.replace(/-(admin|public)$/,"");if(o!==s){const a=e.workspaces.find(u=>u.name===o);return(a==null?void 0:a.name)??null}return null}function hw(e){var t,n,i,s,o,r,a,u,c;if(e.embeddingDownloading&&!e.publicChat)return d`
3826
+ `}const nr="taskmaster-access-session",Hu={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function qu(){try{return localStorage.getItem(nr)}catch{return null}}function ju(e){try{localStorage.setItem(nr,e)}catch{}}function ew(){try{localStorage.removeItem(nr)}catch{}}async function ll(e){if(e.client)try{const t=qu(),n=await e.client.request("access.status",{token:t});e.accessState={...e.accessState,checked:!0,hasPins:n.hasPins,hasMasterPin:n.hasMasterPin,accounts:n.accounts??[],authenticated:n.authenticated,workspace:n.workspace,master:n.master,error:null}}catch{e.accessState={...e.accessState,checked:!0,hasPins:!1,hasMasterPin:!1,accounts:[],authenticated:!0,error:null}}}async function tw(e,t,n){if(e.client){e.accessState={...e.accessState,busy:!0,error:null};try{const i=await e.client.request("access.verify",{account:t,pin:n});i.ok&&i.token?(ju(i.token),e.accessState={...e.accessState,authenticated:!0,workspace:i.workspace??null,master:i.master??!1,busy:!1,error:null}):e.accessState={...e.accessState,busy:!1,error:i.message??"Incorrect PIN"}}catch{e.accessState={...e.accessState,busy:!1,error:"Failed to verify PIN"}}}}async function nw(e,t){if(e.client){e.accessState={...e.accessState,busy:!0,error:null};try{const n=await e.client.request("access.setMasterPin",{pin:t});n.ok&&n.token?(ju(n.token),e.accessState={...e.accessState,checked:!0,hasPins:!0,hasMasterPin:!0,authenticated:!0,workspace:null,master:!0,busy:!1,error:null}):e.accessState={...e.accessState,busy:!1,error:"Failed to set PIN"}}catch{e.accessState={...e.accessState,busy:!1,error:"Failed to set PIN"}}}}async function iw(e,t,n){if(!e.client)return!1;try{return(await e.client.request("access.setAccountPin",{workspace:t,pin:n})).ok}catch{return!1}}async function sw(e){const t=qu();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}ew(),e.accessState={...Hu,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}function ow(e,t="admin"){var s;if(!e)return[];const n=e.bindings;if(!Array.isArray(n))return[];const i=[];for(const o of n){if(!o||typeof o!="object"||o.agentId!==t&&o.agentId!=="management")continue;const r=o.match;if(!r||typeof r!="object"||(r.channel??"").toLowerCase()!=="whatsapp")continue;const u=r.peer;if(!u||typeof u!="object"||u.kind!=="dm")continue;const c=u.id??"";c&&i.push({phone:c,paired:((s=o.meta)==null?void 0:s.paired)===!0})}return i.sort((o,r)=>o.paired&&!r.paired?-1:!o.paired&&r.paired?1:0),i}function Vu(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,r=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const l=c.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="whatsapp")continue;const h=l.peer;if(!h||typeof h!="object"||h.kind!=="dm")continue;const b=h.id??"";b&&(c.meta&&o.set(b,c.meta),l.accountId&&r.set(b,l.accountId))}const a=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const l=c.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="whatsapp")return!0;const h=l.peer;return!h||typeof h!="object"?!0:h.kind!=="dm"}),u=t.map(c=>{const l=i??r.get(c.phone),p={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};l&&(p.accountId=l);const h={agentId:n,match:p},b=o.get(c.phone);return b?h.meta=b:c.paired&&(h.meta={paired:!0}),h});return[...a,...u]}async function Fi(e,t){if(!e.client||!e.connected)return;if(!t){e.adminPhones=[];return}if(e.adminsLoading)return;e.adminsLoading=!0,e.adminsError=null;const n=t;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.config;e.configForm=tt(s??{}),e.adminPhones=ow(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function Gu(e,t,n,i){var r,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n;let o=t.replace(/[\s\-\(\)]/g,"");if(!o){e.adminsError="Phone number is required";return}if(o.startsWith("+")||(o="+"+o),!/^\+[1-9]\d{6,14}$/.test(o)){e.adminsError="Invalid phone number. Use international format (e.g., +44 7504 472444)";return}if(e.adminPhones.some(u=>u.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const u=tt(e.configForm??((r=e.configSnapshot)==null?void 0:r.config)??{}),c=u.bindings??[],l=[...e.adminPhones,{phone:o}],p=Vu(c,l,s,i);Nl(u,["bindings"],p);const h=(a=e.configSnapshot)==null?void 0:a.hash;if(!h){e.adminsError="Config hash missing; reload and retry.";return}const b=ft(u);await e.client.request("config.set",{raw:b,baseHash:h}),await Fi(e,n)}catch(u){e.adminsError=String(u)}finally{e.adminsSaving=!1}}async function Qu(e,t,n,i){var r,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n,o=e.adminPhones.find(u=>u.phone===t);if(o!=null&&o.paired){e.adminsError="Cannot remove the paired phone. Unlink WhatsApp first.";return}e.adminsSaving=!0,e.adminsError=null;try{const u=tt(e.configForm??((r=e.configSnapshot)==null?void 0:r.config)??{}),c=u.bindings??[],l=e.adminPhones.filter(f=>f.phone!==t),p=Vu(c,l,s,i);Nl(u,["bindings"],p);const h=(a=e.configSnapshot)==null?void 0:a.hash;if(!h){e.adminsError="Config hash missing; reload and retry.";return}const b=ft(u);await e.client.request("config.set",{raw:b,baseHash:h}),await Fi(e,n)}catch(u){e.adminsError=String(u)}finally{e.adminsSaving=!1}}const rw=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:Gu,loadAdmins:Fi,removeAdmin:Qu},Symbol.toStringTag,{value:"Module"}));async function wt(e,t){if(!(!e.client||!e.connected)){if(!t){e.contactsRecords=[];return}if(!e.contactsLoading){e.contactsLoading=!0,e.contactsError=null;try{const n=e.contactsSearchQuery.trim(),i=n?await e.client.request("records.search",{query:n,workspace:t}):await e.client.request("records.list",{workspace:t});e.contactsRecords=i.records??[]}catch(n){e.contactsError=String(n)}finally{e.contactsLoading=!1}}}}async function Yu(e,t,n,i){if(!e.client||!e.connected||e.contactsSaving)return;let s=t.replace(/[\s\-\(\)]/g,"");const o=n.trim();if(!s){e.contactsError="Phone number is required";return}if(!o){e.contactsError="Name is required";return}if(s.startsWith("+")||(s="+"+s),!/^\+[1-9]\d{6,14}$/.test(s)){e.contactsError="Invalid phone number. Use international format (e.g., +44 7490 553305)";return}e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.set",{id:s,name:o,fields:{},workspace:i}),e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName="",await wt(e,i)}catch(r){e.contactsError=String(r)}finally{e.contactsSaving=!1}}async function Ju(e,t,n){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.delete",{id:t}),e.contactsEditingId===t&&(e.contactsEditingId=null),await wt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function ao(e,t,n,i,s){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.setField",{id:t,key:n,value:i}),await wt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Xu(e,t,n,i){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.deleteField",{id:t,key:n}),await wt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const aw=Object.freeze(Object.defineProperty({__proto__:null,addContact:Yu,deleteContact:Ju,deleteContactField:Xu,loadContacts:wt,setContactField:ao},Symbol.toStringTag,{value:"Module"}));function cn(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0}}}function lw(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),onAddAccount:()=>{e.addingWorkspace=!0},hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0}}}function cw(e){const t=oe(e);if(!t)return;const n=t.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return n==null?void 0:n.id}function uw(e){const t=oe(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function dw(e){var i;const t=oe(e);if(!t)return;const n=t.agents.find(s=>s.id.endsWith("-admin")||s.id==="admin");return(n==null?void 0:n.id)??((i=t.agents[0])==null?void 0:i.id)}function pw(e){return e.selectedWorkspace??void 0}function oe(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const hw=/^data:/i,fw=/^https?:\/\//i;function cl(e){var a,u;const t=((a=e.agentsList)==null?void 0:a.agents)??[],n=Al(e.sessionKey),i=(n==null?void 0:n.agentId)??((u=e.agentsList)==null?void 0:u.defaultId)??"main",s=t.find(c=>c.id===i),o=s==null?void 0:s.identity,r=(o==null?void 0:o.avatarUrl)??(o==null?void 0:o.avatar);if(r)return hw.test(r)||fw.test(r)?r:o==null?void 0:o.avatarUrl}function gw(e){var i;if(!e)return null;const t=(i=e.channelAccounts)==null?void 0:i.whatsapp;if(!t||t.length===0)return null;const n=t[0];return{running:n.running??!1,connected:n.connected??!1,linked:n.linked??!1,lastError:n.lastError}}function mw(e){var r;if(!e)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const t=(r=e.channelAccounts)==null?void 0:r.imessage;if(!t||t.length===0)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const n=t[0],i=n.running??!1,s=n.probe,o=s!=null?s.ok===!0:i;return{configured:n.configured??!1,running:i,connected:o,lastError:n.lastError??null,selfChatMode:n.mode==="self-chat"||!!n.selfChatMode,dmPolicy:n.dmPolicy??null,cliPath:n.cliPath??null}}function yw(e){var r;const t=(r=e.configSnapshot)==null?void 0:r.config;if(!t)return null;const n=t.bindings;if(!Array.isArray(n))return null;const i=n.find(a=>{var u,c;return((u=a.match)==null?void 0:u.channel)==="imessage"&&((c=a.meta)==null?void 0:c.imessageOwner)});if(!i)return null;const s=i.agentId;for(const a of e.workspaces)if(a.agents.some(u=>u.id===s))return a.name;if(s==="admin"||s==="public"){const a=e.workspaces.find(u=>u.isDefault);return(a==null?void 0:a.name)??null}const o=s.replace(/-(admin|public)$/,"");if(o!==s){const a=e.workspaces.find(u=>u.name===o);return(a==null?void 0:a.name)??null}return null}function vw(e){var t,n,i,s,o,r,a,u,c;if(e.embeddingDownloading&&!e.publicChat)return d`
3798
3827
  <div class="setup-container">
3799
3828
  <div class="setup-card" style="text-align:center; max-width:420px;">
3800
3829
  <div class="setup-spinner"></div>
@@ -3808,14 +3837,14 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3808
3837
  </p>
3809
3838
  </div>
3810
3839
  </div>
3811
- `;if(e.publicChat)return e.connected?e.publicChatAuthenticated?pb({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??cl(e)??null,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,canAbort:!!e.chatRunId,disabledReason:e.connected?null:"Disconnected.",error:e.lastError,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,suggestion:e.chatSuggestion,onSuggestionClick:l=>{e.chatMessage=l,e.chatSuggestion=null,e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),ie(async()=>{const{loadChatHistory:l}=await Promise.resolve().then(()=>pi);return{loadChatHistory:l}},void 0,import.meta.url).then(({loadChatHistory:l})=>{l(e)})),onDraftChange:l=>e.chatMessage=l,attachments:e.chatAttachments,onAttachmentsChange:l=>e.chatAttachments=l,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:l=>e.removeQueuedMessage(l),onChatScroll:l=>e.handleChatScroll(l),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}}):Gb({authMode:e.publicChatConfig.auth??"anonymous",authStep:e.publicChatAuthStep,connected:e.connected,client:e.client,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,accountId:e.publicChatConfig.accountId,cookieTtlDays:e.publicChatConfig.cookieTtlDays,onAuthenticated:l=>{e.publicChatSessionKey=l,e.sessionKey=l,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready",ie(async()=>{const{loadChatHistory:p}=await Promise.resolve().then(()=>pi);return{loadChatHistory:p}},void 0,import.meta.url).then(({loadChatHistory:p})=>{p(e)})},onAuthStepChange:l=>{e.publicChatAuthStep=l},requestUpdate:()=>{e.requestUpdate()}}):d`
3840
+ `;if(e.publicChat)return e.connected?e.publicChatAuthenticated?yb({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??cl(e)??null,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,canAbort:!!e.chatRunId,disabledReason:e.connected?null:"Disconnected.",error:e.lastError,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,suggestion:e.chatSuggestion,onSuggestionClick:l=>{e.chatMessage=l,e.chatSuggestion=null,e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),ie(async()=>{const{loadChatHistory:l}=await Promise.resolve().then(()=>pi);return{loadChatHistory:l}},void 0,import.meta.url).then(({loadChatHistory:l})=>{l(e)})),onDraftChange:l=>e.chatMessage=l,attachments:e.chatAttachments,onAttachmentsChange:l=>e.chatAttachments=l,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:l=>e.removeQueuedMessage(l),onChatScroll:l=>e.handleChatScroll(l),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}}):Zb({authMode:e.publicChatConfig.auth??"anonymous",authStep:e.publicChatAuthStep,connected:e.connected,client:e.client,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,accountId:e.publicChatConfig.accountId,cookieTtlDays:e.publicChatConfig.cookieTtlDays,onAuthenticated:l=>{e.publicChatSessionKey=l,e.sessionKey=l,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready",ie(async()=>{const{loadChatHistory:p}=await Promise.resolve().then(()=>pi);return{loadChatHistory:p}},void 0,import.meta.url).then(({loadChatHistory:p})=>{p(e)})},onAuthStepChange:l=>{e.publicChatAuthStep=l},requestUpdate:()=>{e.requestUpdate()}}):d`
3812
3841
  <div class="setup-container">
3813
3842
  <div class="setup-card">
3814
3843
  <div class="setup-spinner"></div>
3815
3844
  <p>Connecting...</p>
3816
3845
  </div>
3817
3846
  </div>
3818
- `;if(e.connected&&e.accessState.checked){const{accessState:l}=e;if(l.hasPins&&!l.authenticated)return Xa({show:!0,isFirstTime:!1,accounts:l.accounts,error:l.error,busy:l.busy,onSubmit:(p,f)=>{f!=null&&e.handlePinSubmit(p,f)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,f,b)=>e.handleChangePin(p,f,b)});if(!l.hasMasterPin&&!l.authenticated&&e.setup)return Xa({show:!0,isFirstTime:!0,accounts:[],error:l.error,busy:l.busy,onSubmit:p=>e.handleSetMasterPin(p)});if(!l.hasMasterPin&&!l.authenticated&&!e.setup)return window.location.href="/setup",S}if(e.setup){const l=uw(e.channelsSnapshot),p=((n=(t=e.channelsSnapshot)==null?void 0:t.channelAccounts)==null?void 0:n.whatsapp)??[],f=dw(e.channelsSnapshot),b=pw(e);return Uf({connected:e.connected,serverPlatform:((s=(i=e.hello)==null?void 0:i.server)==null?void 0:s.platform)??null,assistantName:e.assistantName,currentStep:e.setupStep,licenseKey:e.licenseKey,licenseBusy:e.licenseBusy,licenseValid:e.licenseValid,licenseMessage:e.licenseMessage,licenseTier:e.licenseTier,licenseDeviceId:e.licenseDeviceId,licenseStoredKey:e.licenseStoredKey,onLicenseKeyChange:h=>e.handleLicenseKeyChange(h),onLicenseActivate:()=>e.handleLicenseActivate(),onLicenseRemove:async()=>{await e.handleLicenseRemove(),e.licenseRemoveConfirm=!1},licenseRemoveConfirm:e.licenseRemoveConfirm,onLicenseRemoveConfirm:()=>{e.licenseRemoveConfirm=!0},onLicenseRemoveCancel:()=>{e.licenseRemoveConfirm=!1},authConnected:e.authConnected,authBusy:e.authBusy,authMessage:e.authMessage,authUrl:e.authUrl,authCodeInput:e.authCodeInput,authExpiresIn:e.authExpiresIn,whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:l,whatsappAccounts:p,whatsappActiveQrAccountId:e.whatsappActiveQrAccountId,whatsappAccountSaving:e.whatsappAccountSaving,gatewayHealthy:e.gatewayHealthy,gatewayHealthLoading:e.gatewayHealthLoading,gatewayHealthMessage:e.gatewayHealthMessage,gatewayRestartBusy:e.gatewayRestartBusy,updateAvailable:e.updateAvailable,currentVersion:e.currentVersion,latestVersion:e.latestVersion,updateChecking:e.updateChecking,updateRunning:e.updateRunning,updateMessage:e.updateMessage,updateProgressSteps:e.updateProgressSteps,updateLastResult:e.updateLastResult,onUpdateCheck:()=>e.handleUpdateCheck(),onUpdateRun:()=>e.handleUpdateRun(),onUpdateDismissResult:()=>e.handleUpdateDismissResult(),uninstallConfirm:e.uninstallConfirm,uninstallBusy:e.uninstallBusy,uninstallDone:e.uninstallDone,uninstallError:e.uninstallError,uninstallConfirmText:e.uninstallConfirmText,onUninstallConfirm:()=>e.handleUninstallConfirm(),onUninstallCancel:()=>e.handleUninstallCancel(),onUninstallConfirmTextChange:h=>e.handleUninstallConfirmTextChange(h),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:h=>e.handleAuthSubmitCode(h),onAuthCodeChange:h=>e.handleAuthCodeChange(h),onSkipToWhatsApp:()=>e.handleSkipToWhatsApp(),onWhatsAppRelink:async h=>{await e.handleWhatsAppStart(!0,h),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(h),await G(e,!0),e.requestUpdate())},onWhatsAppUnlink:async h=>{await e.handleWhatsAppLogout(h)},onWhatsAppReset:async h=>{await e.handleWhatsAppLogout(h),await e.handleWhatsAppStart(!0,h),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(h),await G(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await G(e,!0),await e.handleGatewayHealthCheck()},onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),G(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:h=>e.handleRemoveWhatsAppAccount(h),workspaces:e.workspaces,workspacesLoading:e.workspacesLoading,workspacesError:e.workspacesError,addingWorkspace:e.addingWorkspace,newWorkspaceName:e.newWorkspaceName,newWorkspacePath:e.newWorkspacePath,workspaceSaving:e.workspaceSaving,workspaceRemoveConfirm:e.workspaceRemoveConfirm,newWorkspacePin:e.newWorkspacePin,onSetNewWorkspacePin:h=>{e.newWorkspacePin=h},onWorkspaceCreate:async(h,v)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(h,v),k.match(/^\d{4,6}$/)&&(await Xb(e,h,k),e.newWorkspacePin="")},onWorkspaceRemove:h=>e.handleWorkspaceRemove(h),onSetAddingWorkspace:h=>{e.addingWorkspace=h},onSetNewWorkspaceName:h=>{e.newWorkspaceName=h},onSetNewWorkspacePath:h=>{e.newWorkspacePath=h},onSetWorkspaceRemoveConfirm:h=>{e.workspaceRemoveConfirm=h},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(h,v)=>e.handleWorkspaceRename(h,v),whatsappDmPolicy:(()=>{const h=oe(e),v=h==null?void 0:h.whatsappAccountId,k=v?p.find($=>$.accountId===v):p[0];return(k==null?void 0:k.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var T;const h=oe(e),v=h==null?void 0:h.whatsappAccountId,k=v?p.find(_=>_.accountId===v):p[0];if(!k)return;const A=k.dmPolicy!=null&&k.dmPolicy!=="disabled"?"disabled":"open",C=A==="open"?{dmPolicy:A,allowFrom:["*"]}:{dmPolicy:A};try{const _=await e.client.request("config.get"),R=_.config,O=(T=R==null?void 0:R.channels)==null?void 0:T.whatsapp,ye=((O==null?void 0:O.accounts)??{})[k.accountId]?{channels:{whatsapp:{accounts:{[k.accountId]:C}}}}:{channels:{whatsapp:C}};await e.client.request("config.patch",{raw:JSON.stringify(ye),baseHash:_.hash,note:`WhatsApp DM policy → ${A}`,skipRestart:!0}),await G(e,!1)}catch(_){console.error("DM toggle failed:",_)}},whatsappModel:(()=>{var T,_;const h=oe(e);if(!h)return null;const v=h.agents.find(R=>R.id.endsWith("-public")||R.id==="public");if(!v)return null;const k=(T=e.configSnapshot)==null?void 0:T.config,$=(_=k==null?void 0:k.agents)==null?void 0:_.list;if(!Array.isArray($))return null;const A=$.find(R=>R.id===v.id);if(!(A!=null&&A.model))return null;const C=typeof A.model=="string"?A.model:A.model.primary;return(C==null?void 0:C.trim())||null})(),whatsappModelCatalog:e.chatModelCatalog??[],onWhatsAppModelChange:async h=>{const v=oe(e);if(!v)return;const k=v.agents.find($=>$.id.endsWith("-public")||$.id==="public");if(k)try{const $=await e.client.request("config.get"),A=$.config,C=(A==null?void 0:A.agents)??{},T=Array.isArray(C.list)?[...C.list]:[],_=T.findIndex(O=>O.id===k.id);if(h)_>=0?T[_]={...T[_],model:h}:T.push({id:k.id,model:h});else if(_>=0){const{model:O,...ee}=T[_];Object.keys(ee).length<=1?T.splice(_,1):T[_]=ee}const R=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(R),baseHash:$.hash,note:`Public agent model → ${h||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch($){console.error("Model change failed:",$)}},whatsappThinkingLevel:(()=>{var C,T,_;const h=oe(e);if(!h)return null;const v=h.agents.find(R=>R.id.endsWith("-public")||R.id==="public");if(!v)return null;const k=(C=e.configSnapshot)==null?void 0:C.config,$=(T=k==null?void 0:k.agents)==null?void 0:T.list;if(!Array.isArray($))return null;const A=$.find(R=>R.id===v.id);return((_=A==null?void 0:A.thinkingLevel)==null?void 0:_.trim())||null})(),onWhatsAppThinkingChange:async h=>{const v=oe(e);if(!v)return;const k=v.agents.find($=>$.id.endsWith("-public")||$.id==="public");if(k)try{const $=await e.client.request("config.get"),A=$.config,C=(A==null?void 0:A.agents)??{},T=Array.isArray(C.list)?[...C.list]:[],_=T.findIndex(ee=>ee.id===k.id),R=h==="off"?void 0:h;if(R)_>=0?T[_]={...T[_],thinkingLevel:R}:T.push({id:k.id,thinkingLevel:R});else if(_>=0){const{thinkingLevel:ee,...ye}=T[_];Object.keys(ye).length<=1?T.splice(_,1):T[_]=ye}const O=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(O),baseHash:$.hash,note:`Public agent thinking → ${R||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch($){console.error("Thinking change failed:",$)}},whatsappGroupPolicy:(()=>{var _,R;const h=(_=e.configSnapshot)==null?void 0:_.config,v=(R=h==null?void 0:h.channels)==null?void 0:R.whatsapp,k=oe(e),$=k==null?void 0:k.whatsappAccountId,A=(v==null?void 0:v.accounts)??{},C=$?A[$]:void 0;return(C==null?void 0:C.groupPolicy)??(v==null?void 0:v.groupPolicy)??"allowlist"})(),whatsappGroupRequireMention:(()=>{var R,O;const h=(R=e.configSnapshot)==null?void 0:R.config,v=(O=h==null?void 0:h.channels)==null?void 0:O.whatsapp,k=oe(e),$=k==null?void 0:k.whatsappAccountId,A=(v==null?void 0:v.accounts)??{},C=$?A[$]:void 0,_=((C==null?void 0:C.groups)??(v==null?void 0:v.groups)??{})["*"];return(_==null?void 0:_.requireMention)!==!1})(),onWhatsAppGroupToggle:async()=>{var k;const h=oe(e),v=h==null?void 0:h.whatsappAccountId;try{const $=await e.client.request("config.get"),A=$.config,C=((k=A==null?void 0:A.channels)==null?void 0:k.whatsapp)??{},T=C.accounts??{},_=v?T[v]:void 0,R=(_==null?void 0:_.groupPolicy)??C.groupPolicy??"allowlist",O=R==="disabled"||R==="allowlist",ee=O?"open":"disabled",ye=O?{"*":{}}:void 0,Ve={groupPolicy:ee};ye&&(Ve.groups=ye);const X=_?{channels:{whatsapp:{accounts:{[v]:Ve}}}}:{channels:{whatsapp:Ve}};await e.client.request("config.patch",{raw:JSON.stringify(X),baseHash:$.hash,note:`WhatsApp groups → ${ee}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch($){console.error("Group toggle failed:",$)}},onWhatsAppGroupMentionChange:async h=>{var $;const v=oe(e),k=v==null?void 0:v.whatsappAccountId;try{const A=await e.client.request("config.get"),C=A.config,_=((($=C==null?void 0:C.channels)==null?void 0:$.whatsapp)??{}).accounts??{},R=k?_[k]:void 0,O={"*":{requireMention:h}},ee=R?{channels:{whatsapp:{accounts:{[k]:{groups:O}}}}}:{channels:{whatsapp:{groups:O}}};await e.client.request("config.patch",{raw:JSON.stringify(ee),baseHash:A.hash,note:`WhatsApp group mention → ${h?"when mentioned":"always"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Group mention change failed:",A)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:f.configured,imessageRunning:f.running,imessageConnected:f.connected,imessageLastError:f.lastError,imessageSelfChatMode:f.selfChatMode,imessageCliPath:f.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:b,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const h=await e.client.request("config.get"),v=h.config,k=(v==null?void 0:v.bindings)??[],$=oe(e),A=$==null?void 0:$.agents.find(O=>O.id.endsWith("-admin")||O.id==="admin"),C=(A==null?void 0:A.id)??"admin",T=k.filter(O=>{var ee;return((ee=O.match)==null?void 0:ee.channel)!=="imessage"}),_=[{agentId:C,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],R=[...T,..._];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:R}),baseHash:h.hash,note:"Enable iMessage (self-chat) for "+(($==null?void 0:$.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Re(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await G(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const h=await e.client.request("config.get"),v=h.config,$=((v==null?void 0:v.bindings)??[]).filter(A=>{var C;return((C=A.match)==null?void 0:C.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:$}),baseHash:h.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Re(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const h=await e.client.request("config.get"),v=h.config,k=(v==null?void 0:v.bindings)??[],$=oe(e),A=$==null?void 0:$.agents.find(R=>R.id.endsWith("-admin")||R.id==="admin"),C=(A==null?void 0:A.id)??"admin",T=k.filter(R=>{var O;return((O=R.match)==null?void 0:O.channel)!=="imessage"}),_=[{agentId:C,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:[...T,..._]}),baseHash:h.hash,note:"Reassign iMessage to "+(($==null?void 0:$.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Re(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:h=>{e.infoModalOpen=h},onInfoModalClose:()=>{e.infoModalOpen=null},isMaster:e.accessState.master,apiKeyProviders:e.apiKeyProviders,apiKeyModalOpen:e.apiKeyModalOpen,apiKeyBusy:e.apiKeyBusy,apiKeyError:e.apiKeyError,apiKeySuccess:e.apiKeySuccess,apiKeySavingProvider:e.apiKeySavingProvider,onApiKeyModalOpen:()=>{e.apiKeyModalOpen=!0,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeyModalClose:()=>{e.apiKeyModalOpen=!1,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeySave:async(h,v)=>{e.apiKeySavingProvider=h,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await tl(e.client,h,v);const k=`${h} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await ro(e.client)}catch{}h==="anthropic"&&await e.handleAuthStatusCheck(),setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:"Failed to save key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyRemove:async h=>{e.apiKeySavingProvider=h,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Lb(e.client,h);const v=`${h} key removed`;e.apiKeySuccess=v,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await ro(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===v&&(e.apiKeySuccess=null)},2500)}catch(v){e.apiKeyError=v instanceof Error?v.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},authApiKeyMode:e.authApiKeyMode,authApiKeyInput:e.authApiKeyInput,authApiKeyBusy:e.authApiKeyBusy,authApiKeyError:e.authApiKeyError,onAuthApiKeyToggle:()=>{e.authApiKeyMode=!e.authApiKeyMode,e.authApiKeyError=null},onAuthApiKeyChange:h=>{e.authApiKeyInput=h},onAuthApiKeySubmit:async()=>{const h=e.authApiKeyInput.trim();if(h){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await tl(e.client,"anthropic",h),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(v){e.authApiKeyError=v instanceof Error?v.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var v;const h=e.selectedWorkspace??((v=e.workspaces[0])==null?void 0:v.name);return h?e.accessState.accounts.some(k=>k.id===h):!1})(),accountPinModalOpen:e.accountPinModalOpen,accountPinBusy:e.accountPinBusy,accountPinError:e.accountPinError,accountPinSuccess:e.accountPinSuccess,onAccountPinModalOpen:()=>{e.accountPinModalOpen=!0,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinModalClose:()=>{e.accountPinModalOpen=!1,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinSave:(h,v)=>{var $;const k=e.selectedWorkspace??(($=e.workspaces[0])==null?void 0:$.name);k&&e.handleAccountPinSave(k,h,v)},publicChatEnabled:(()=>{var k;const h=(k=e.configSnapshot)==null?void 0:k.config,v=h==null?void 0:h.publicChat;return(v==null?void 0:v.enabled)===!0})(),publicChatAuthMode:(()=>{var $;const h=($=e.configSnapshot)==null?void 0:$.config,v=h==null?void 0:h.publicChat,k=v==null?void 0:v.auth;return k==="verified"||k==="choice"?k:"anonymous"})(),publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var h;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const v=await e.client.request("config.get"),k=v.config,$=((h=k==null?void 0:k.publicChat)==null?void 0:h.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!$}}),baseHash:v.hash,note:`Public chat → ${$?"disabled":"enabled"}`}),e.configSnapshot=await e.client.request("config.get")}catch(v){console.error("Public chat toggle failed:",v)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async h=>{if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const v=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{auth:h}}),baseHash:v.hash,note:`Public chat auth → ${h}`}),e.configSnapshot=await e.client.request("config.get")}catch(v){console.error("Public chat auth mode change failed:",v)}finally{e.publicChatToggleBusy=!1}}},brandAccentColor:(()=>{var k;const h=e.selectedWorkspace;return h?((k=Me()[h])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const h=e.selectedWorkspace;return h?((k=Me()[h])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const h=e.selectedWorkspace;return h?!!((k=Me()[h])!=null&&k.logoUrl):!1})(),brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async h=>{var k;const v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{const $=await e.client.request("config.get"),A=$.config,C=((k=A==null?void 0:A.workspaces)==null?void 0:k[v])??{},T=C.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[v]:{...C,brand:{...T,accentColor:h}}}}),baseHash:$.hash,note:`Brand accent → ${h}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const _=Me();_[v]||(_[v]={}),_[v].accentColor=h,hn(v)}catch($){console.error("Brand accent change failed:",$)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async h=>{var k;const v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{const $=await e.client.request("config.get"),A=$.config,C=((k=A==null?void 0:A.workspaces)==null?void 0:k[v])??{},T=C.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[v]:{...C,brand:{...T,backgroundColor:h}}}}),baseHash:$.hash,note:`Brand background → ${h}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const _=Me();_[v]||(_[v]={}),_[v].backgroundColor=h,hn(v)}catch($){console.error("Brand background change failed:",$)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async h=>{const v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{const k=await h.arrayBuffer(),$=new Uint8Array(k);let A="";for(let _=0;_<$.length;_++)A+=String.fromCharCode($[_]);const C=btoa(A);await e.client.request("brand.uploadLogo",{workspace:v,data:C,mimeType:h.type});const T=Me();T[v]||(T[v]={}),T[v].logoUrl=`/brand-logo/${encodeURIComponent(v)}`}catch(k){console.error("Brand logo upload failed:",k)}finally{e.brandingBusy=!1}}},onBrandLogoRemove:async()=>{const h=e.selectedWorkspace;if(!(!h||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:h});const v=Me();v[h]&&delete v[h].logoUrl}catch(v){console.error("Brand logo remove failed:",v)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var v;const h=e.selectedWorkspace;if(!(!h||e.brandingBusy)){e.brandingBusy=!0;try{const k=await e.client.request("config.get"),$=k.config,A=((v=$==null?void 0:$.workspaces)==null?void 0:v[h])??{},{brand:C,...T}=A;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[h]:{...T,brand:null}}}),baseHash:k.hash,note:"Brand reset to defaults",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");try{await e.client.request("brand.removeLogo",{workspace:h})}catch{}const _=Me();delete _[h],hn(h)}catch(k){console.error("Brand reset failed:",k)}finally{e.brandingBusy=!1}}},tailscaleStatus:e.tailscaleStatus,tailscaleBusy:e.tailscaleBusy,tailscaleAuthUrl:e.tailscaleAuthUrl,tailscaleError:e.tailscaleError,tailscaleFunnelEnableUrl:e.tailscaleFunnelEnableUrl,onTailscaleEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleAuthUrl=null;try{const h=await e.client.request("tailscale.enable");if(h.authUrl){e.tailscaleAuthUrl=h.authUrl;const v=setInterval(async()=>{try{const k=await e.client.request("tailscale.status");e.tailscaleStatus=k,k.loggedIn&&(clearInterval(v),e.tailscaleAuthUrl=null,e.tailscaleBusy=!1)}catch{}},3e3);setTimeout(()=>{clearInterval(v),e.tailscaleBusy&&(e.tailscaleBusy=!1)},3e5)}else h.alreadyLoggedIn&&(e.tailscaleStatus=await e.client.request("tailscale.status")),e.tailscaleBusy=!1}catch(h){console.error("Tailscale enable failed:",h),e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var h;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable")}catch(v){console.error("Tailscale funnel enable failed:",v);const k=v;(h=k.payload)!=null&&h.enableUrl&&(e.tailscaleFunnelEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Funnel",e.tailscaleBusy=!1}}},onTailscaleFunnelDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.funnel.disable")}catch(h){console.error("Tailscale funnel disable failed:",h),e.tailscaleBusy=!1}}},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[h,v]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);e.wifiNetworks=h.networks,e.wifiStatus=v}catch(h){console.error("WiFi scan failed:",h),e.wifiError=h.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{if(e.wifiBusy||!e.wifiSelectedSsid)return;const h=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const v=await e.client.request("wifi.connect",{ssid:h,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:v.connected,ssid:v.ssid,signal:null,ip:v.ip,savedSsid:v.ssid,autoconnect:!0},e.wifiBusy=!1;try{const k=await e.client.request("wifi.status");e.wifiStatus=k}catch{}}catch(v){console.error("WiFi connect failed:",v),e.wifiError=v.message||"Failed to connect",e.wifiBusy=!1}},onWifiDisconnect:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.disconnect"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const h=await e.client.request("wifi.status");e.wifiStatus=h}catch(h){console.error("WiFi disconnect failed:",h),e.wifiError=h.message||"Failed to disconnect"}finally{e.wifiBusy=!1}}},onWifiForget:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.forget"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const h=await e.client.request("wifi.status");e.wifiStatus=h}catch(h){console.error("WiFi forget failed:",h),e.wifiError=h.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:h=>{e.wifiSelectedSsid=h,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:h=>{e.wifiPassword=h},wsProps:iw(e)})}if(e.filesPage){const l=rw(e);return Af({connected:e.connected,wsProps:cn(e),loading:e.filesLoading,tree:e.filesTree,root:e.filesRoot,error:e.filesError,selectedPath:e.filesSelectedPath,selectedPaths:e.filesSelectedPaths,previewContent:e.filesPreviewContent,previewLoading:e.filesPreviewLoading,previewBinary:e.filesPreviewBinary,previewSize:e.filesPreviewSize,expandedDirs:e.filesExpandedDirs,currentDir:e.filesCurrentDir,message:e.filesMessage,uploadBusy:e.filesUploadBusy,reindexBusy:e.filesReindexBusy,memoryStatus:e.filesMemoryStatus,onRefresh:()=>Ht(e,l),onReindex:()=>Uh(e,l),onSelectFile:p=>{e.filesPendingDeletePath=null,Lh(e,p,l)},onToggleSelectFile:p=>Ih(e,p,l),onToggleDir:p=>Wh(e,p),onUpload:(p,f)=>Bh(e,p,f,l),onNewFolder:(p,f)=>Nh(e,p,f,l),onDownload:p=>_c(e,p,l),onBulkDownload:()=>Rh(e,l),onDelete:p=>{e.filesPendingDeletePath=null,Oh(e,p,l)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,f)=>Dh(e,p,f,l),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const f=e.filesSearchAgentId??l;Kh(e,p,f)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{zh(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return bf({connected:e.connected,active:e.browserScreencastActive,loading:e.browserLoading,error:e.browserError,inputMode:e.browserInputMode,fullscreen:e.browserFullscreen,handoffPending:e.browserHandoffPending,handoffReason:e.browserHandoffReason,onStart:()=>xb(e),onStop:()=>Ab(e),onToggleInput:()=>Cb(e),onToggleFullscreen:()=>Tb(e),onCompleteHandoff:()=>Eb(e),onCanvasMouseDown:l=>{const f=l.target.getBoundingClientRect(),h=bn().translateCoordinates(l.clientX-f.left,l.clientY-f.top);_s(e,"mousePressed",h.x,h.y,l.button===2?"right":l.button===1?"middle":"left")},onCanvasMouseUp:l=>{const f=l.target.getBoundingClientRect(),h=bn().translateCoordinates(l.clientX-f.left,l.clientY-f.top);_s(e,"mouseReleased",h.x,h.y)},onCanvasMouseMove:l=>{const p=bn();if(p.shouldThrottleMouseMove())return;const b=l.target.getBoundingClientRect(),h=p.translateCoordinates(l.clientX-b.left,l.clientY-b.top);_s(e,"mouseMoved",h.x,h.y)},onCanvasKeyDown:l=>{let p=0;l.altKey&&(p|=1),l.ctrlKey&&(p|=2),l.metaKey&&(p|=4),l.shiftKey&&(p|=8),Ms(e,"keyDown",l.key,{code:l.code,modifiers:p||void 0}),l.key.length===1&&Ms(e,"char",l.key,{text:l.key})},onCanvasKeyUp:l=>{Ms(e,"keyUp",l.key,{code:l.code})}});if(e.adminsPage){const l=sw(e),p=ow(e);return Kf({connected:e.connected,wsProps:cn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>Fi(e,l),onAdd:f=>{Gu(e,f,l,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:f=>Qu(e,f,l,p),onNewPhoneChange:f=>e.handleAdminsNewPhoneChange(f)})}if(e.contactsPage){const l=aw(e);return Gf({connected:e.connected,wsProps:cn(e),loading:e.contactsLoading,saving:e.contactsSaving,records:e.contactsRecords,error:e.contactsError,searchQuery:e.contactsSearchQuery,editingId:e.contactsEditingId,showAddForm:e.contactsShowAddForm,newRecordPhone:e.contactsNewPhone,newRecordName:e.contactsNewName,deleteConfirmId:e.contactsDeleteConfirmId,addFieldForId:e.contactsAddFieldForId,addFieldKey:e.contactsAddFieldKey,addFieldValue:e.contactsAddFieldValue,onSearch:p=>e.contactsSearchQuery=p,onSearchSubmit:()=>wt(e,l),onAdd:(p,f)=>Yu(e,p,f,l),onDelete:p=>Ju(e,p,l),onSetField:(p,f,b)=>ao(e,p,f,b,l),onDeleteField:(p,f)=>Xu(e,p,f,l),onToggleExpand:p=>{e.contactsEditingId=e.contactsEditingId===p?null:p},onShowAddForm:()=>e.contactsShowAddForm=!0,onCancelAddForm:()=>{e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName=""},onNewRecordPhoneChange:p=>e.handleContactsNewPhoneChange(p),onNewRecordNameChange:p=>e.handleContactsNewNameChange(p),onRefresh:()=>wt(e,l),onDeleteConfirmOpen:p=>e.contactsDeleteConfirmId=p,onDeleteConfirmClose:()=>e.contactsDeleteConfirmId=null,onAddFieldOpen:p=>{e.contactsAddFieldForId=p,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldClose:()=>{e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldKeyChange:p=>e.contactsAddFieldKey=p,onAddFieldValueChange:p=>e.contactsAddFieldValue=p,onAddFieldSubmit:()=>{const p=e.contactsAddFieldForId,f=e.contactsAddFieldKey.trim();!p||!f||(ao(e,p,f,e.contactsAddFieldValue,l),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const l=e.connected?null:"Disconnected from gateway.",p=cl(e),f=e.chatAvatarUrl??p??null,b=(()=>{var k;const h=(k=e.configSnapshot)==null?void 0:k.config,v=h==null?void 0:h.publicChat;return(v==null?void 0:v.enabled)===!0})();return Cv({connected:e.connected,wsProps:cn(e),publicChatEnabled:b,publicChatAccountId:e.selectedWorkspace??void 0,sessionKey:e.sessionKey,onSessionKeyChange:h=>{e.sessionKey=h,e.chatMessage="",e.chatAttachments=[],e.chatStream=null,e.chatInterimText=null,e.chatSuggestion=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:h,lastActiveSessionKey:h}),e.loadAssistantIdentity(),Le(e),Ks(e)},thinkingLevel:e.chatThinkingLevel,showThinking:e.settings.chatShowThinking??!1,modelProvider:e.chatModelProvider,model:e.chatModel,modelCatalog:e.chatModelCatalog,onModelChange:h=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{model:h}).then(()=>{Le(e,{limit:v})})},onThinkingLevelChange:h=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{thinkingLevel:h==="off"?null:h}).then(()=>{Le(e,{limit:v})})},verboseLevel:e.chatVerboseLevel,fillerEnabled:e.chatFillerEnabled,suggestion:e.chatSuggestion,onSuggestionClick:h=>{e.chatMessage=h,e.chatSuggestion=null,e.handleSendChat()},onVerboseChange:h=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{verboseLevel:h==="off"?null:h}).then(()=>{Le(e,{limit:v})})},onFillerChange:h=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{fillerEnabled:h}).then(()=>{Le(e,{limit:v})})},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:f,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,disabledReason:l,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const h=Math.max(e.chatMessages.length+10,Ie);return Promise.all([Le(e,{limit:h}),Ks(e)])},onToggleFocusMode:()=>{},onChatScroll:h=>e.handleChatScroll(h),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:h=>e.chatMessage=h,attachments:e.chatAttachments,onAttachmentsChange:h=>e.chatAttachments=h,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:h=>e.removeQueuedMessage(h),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:h=>e.handleOpenSidebar(h),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:h=>e.handleSplitRatioChange(h),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?db({connected:e.connected,wsProps:cn(e),activeTab:e.advancedTab,onTabChange:l=>{e.advancedTab=l,l==="cron"&&e.loadCron(),l==="skills"&&He(e,{clearMessages:!0}),l==="logs"&&(e.logsSubTab==="session"?mn(e,{reset:!0}):Rt(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(r=(o=e.channelsSnapshot)==null?void 0:o.channelMeta)!=null&&r.length?e.channelsSnapshot.channelMeta.map(l=>l.id):((a=e.channelsSnapshot)==null?void 0:a.channelOrder)??[],channelLabels:((u=e.channelsSnapshot)==null?void 0:u.channelLabels)??{},channelMeta:((c=e.channelsSnapshot)==null?void 0:c.channelMeta)??[],agentIds:(()=>{var p;const l=oe(e);return((p=l==null?void 0:l.agents)==null?void 0:p.map(f=>f.id))??[]})(),runsJobId:e.cronRunsJobId,runs:e.cronRuns,newEventModalOpen:e.cronNewEventModal,onNewEventModalOpen:()=>{e.cronNewEventModal=!0},onNewEventModalClose:()=>{e.cronNewEventModal=!1,e.cronEditJobId=null},detailJobId:e.cronDetailJobId,editJobId:e.cronEditJobId,onDetailOpen:l=>{e.cronDetailJobId=l.id,Ns(e,l.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:l=>{e.cronForm=Np(l),e.cronEditJobId=l.id,e.cronDetailJobId=null},onEditSave:()=>{const l=e.cronEditJobId;l&&Op(e,l).then(()=>{e.cronEditJobId=null})},onFormChange:l=>e.cronForm={...e.cronForm,...l},onRefresh:()=>e.loadCron(),onAdd:()=>{Ip(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(l,p)=>Rp(e,l,p),onRun:l=>Dp(e,l),onRemove:l=>{e.cronPendingDeleteId=null,Bp(e,l)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:l=>{e.cronPendingDeleteId=l||null},onLoadRuns:l=>Ns(e,l)},skillsProps:{loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,detail:e.skillDetail,detailTab:e.skillDetailTab,addModal:e.skillAddModal,drafts:e.skillDrafts,onFilterChange:l=>e.skillsFilter=l,onRefresh:()=>He(e,{clearMessages:!0}),onToggle:(l,p)=>uc(e,l,p),onEdit:(l,p)=>cc(e,l,p),onSaveKey:l=>dc(e,l),onInstall:(l,p,f)=>pc(e,l,p,f),onViewDetail:l=>hc(e,l),onDetailClose:()=>fc(e),onDetailTab:l=>gc(e,l),onAddOpen:()=>mc(e),onAddClose:()=>yc(e),onImportDraft:l=>vc(e,l),onDeleteDraft:l=>wc(e,l),onAddSave:()=>bc(e),onDelete:l=>Sc(e,l),onEditSkill:l=>kc(e,l)},logsProps:{logsSubTab:e.logsSubTab,onSubTabChange:l=>{e.logsSubTab=l,l==="session"?mn(e,{reset:!0}):Rt(e,{reset:!0})},sessionLogsProps:{loading:e.sessionLogsLoading,error:e.sessionLogsError,entries:e.sessionLogsEntries,agents:e.sessionLogsAgents,filterText:e.sessionLogsFilterText,typeFilters:e.sessionLogsTypeFilters,agentFilters:e.sessionLogsAgentFilters,autoFollow:e.sessionLogsAutoFollow,expandedIds:e.sessionLogsExpandedIds,onFilterTextChange:l=>e.sessionLogsFilterText=l,onTypeToggle:(l,p)=>{const f=e;f.sessionLogsTypeFilters={...f.sessionLogsTypeFilters,[l]:p}},onAgentToggle:(l,p)=>{const f=e;f.sessionLogsAgentFilters={...f.sessionLogsAgentFilters,[l]:p}},onToggleAutoFollow:l=>e.sessionLogsAutoFollow=l,onToggleExpand:l=>{const p=e,f=new Set(p.sessionLogsExpandedIds);f.has(l)?f.delete(l):f.add(l),p.sessionLogsExpandedIds=f,p.requestUpdate()},onRefresh:()=>{mn(e,{reset:!0})},onExport:(l,p)=>e.exportSessionLogs(l,p),onScroll:l=>e.handleSessionLogsScroll(l)},loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,truncated:e.logsTruncated,onFilterTextChange:l=>e.logsFilterText=l,onLevelToggle:(l,p)=>{e.logsLevelFilters={...e.logsLevelFilters,[l]:p}},onToggleAutoFollow:l=>e.logsAutoFollow=l,onRefresh:()=>Rt(e,{reset:!0}),onExport:(l,p)=>e.exportSessionLogs(l,p),onScroll:l=>e.handleLogsScroll(l)}}):(window.location.replace("/chat"),d``)}function fw(e){const t=new Date(e),n=t.toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),i=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return`${n} ${i}`}function ul(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function gw(e,t,n){return d`
3847
+ `;if(e.connected&&e.accessState.checked){const{accessState:l}=e;if(l.hasPins&&!l.authenticated)return Xa({show:!0,isFirstTime:!1,accounts:l.accounts,error:l.error,busy:l.busy,onSubmit:(p,h)=>{h!=null&&e.handlePinSubmit(p,h)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,h,b)=>e.handleChangePin(p,h,b)});if(!l.hasMasterPin&&!l.authenticated&&e.setup)return Xa({show:!0,isFirstTime:!0,accounts:[],error:l.error,busy:l.busy,onSubmit:p=>e.handleSetMasterPin(p)});if(!l.hasMasterPin&&!l.authenticated&&!e.setup)return window.location.href="/setup",S}if(e.setup){const l=gw(e.channelsSnapshot),p=((n=(t=e.channelsSnapshot)==null?void 0:t.channelAccounts)==null?void 0:n.whatsapp)??[],h=mw(e.channelsSnapshot),b=yw(e);return Uf({connected:e.connected,serverPlatform:((s=(i=e.hello)==null?void 0:i.server)==null?void 0:s.platform)??null,assistantName:e.assistantName,currentStep:e.setupStep,licenseKey:e.licenseKey,licenseBusy:e.licenseBusy,licenseValid:e.licenseValid,licenseMessage:e.licenseMessage,licenseTier:e.licenseTier,licenseDeviceId:e.licenseDeviceId,licenseStoredKey:e.licenseStoredKey,onLicenseKeyChange:f=>e.handleLicenseKeyChange(f),onLicenseActivate:()=>e.handleLicenseActivate(),onLicenseRemove:async()=>{await e.handleLicenseRemove(),e.licenseRemoveConfirm=!1},licenseRemoveConfirm:e.licenseRemoveConfirm,onLicenseRemoveConfirm:()=>{e.licenseRemoveConfirm=!0},onLicenseRemoveCancel:()=>{e.licenseRemoveConfirm=!1},authConnected:e.authConnected,authBusy:e.authBusy,authMessage:e.authMessage,authUrl:e.authUrl,authCodeInput:e.authCodeInput,authExpiresIn:e.authExpiresIn,whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:l,whatsappAccounts:p,whatsappActiveQrAccountId:e.whatsappActiveQrAccountId,whatsappAccountSaving:e.whatsappAccountSaving,gatewayHealthy:e.gatewayHealthy,gatewayHealthLoading:e.gatewayHealthLoading,gatewayHealthMessage:e.gatewayHealthMessage,gatewayRestartBusy:e.gatewayRestartBusy,updateAvailable:e.updateAvailable,currentVersion:e.currentVersion,latestVersion:e.latestVersion,updateChecking:e.updateChecking,updateRunning:e.updateRunning,updateMessage:e.updateMessage,updateProgressSteps:e.updateProgressSteps,updateLastResult:e.updateLastResult,onUpdateCheck:()=>e.handleUpdateCheck(),onUpdateRun:()=>e.handleUpdateRun(),onUpdateDismissResult:()=>e.handleUpdateDismissResult(),uninstallConfirm:e.uninstallConfirm,uninstallBusy:e.uninstallBusy,uninstallDone:e.uninstallDone,uninstallError:e.uninstallError,uninstallConfirmText:e.uninstallConfirmText,onUninstallConfirm:()=>e.handleUninstallConfirm(),onUninstallCancel:()=>e.handleUninstallCancel(),onUninstallConfirmTextChange:f=>e.handleUninstallConfirmTextChange(f),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:f=>e.handleAuthSubmitCode(f),onAuthCodeChange:f=>e.handleAuthCodeChange(f),onSkipToWhatsApp:()=>e.handleSkipToWhatsApp(),onWhatsAppRelink:async f=>{await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await G(e,!0),e.requestUpdate())},onWhatsAppUnlink:async f=>{await e.handleWhatsAppLogout(f)},onWhatsAppReset:async f=>{await e.handleWhatsAppLogout(f),await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await G(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await G(e,!0),await e.handleGatewayHealthCheck()},onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),G(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:f=>e.handleRemoveWhatsAppAccount(f),workspaces:e.workspaces,workspacesLoading:e.workspacesLoading,workspacesError:e.workspacesError,addingWorkspace:e.addingWorkspace,newWorkspaceName:e.newWorkspaceName,newWorkspacePath:e.newWorkspacePath,workspaceSaving:e.workspaceSaving,workspaceRemoveConfirm:e.workspaceRemoveConfirm,newWorkspacePin:e.newWorkspacePin,onSetNewWorkspacePin:f=>{e.newWorkspacePin=f},onWorkspaceCreate:async(f,v)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(f,v),k.match(/^\d{4,6}$/)&&(await iw(e,f,k),e.newWorkspacePin="")},onWorkspaceRemove:f=>e.handleWorkspaceRemove(f),onSetAddingWorkspace:f=>{e.addingWorkspace=f},onSetNewWorkspaceName:f=>{e.newWorkspaceName=f},onSetNewWorkspacePath:f=>{e.newWorkspacePath=f},onSetWorkspaceRemoveConfirm:f=>{e.workspaceRemoveConfirm=f},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(f,v)=>e.handleWorkspaceRename(f,v),whatsappDmPolicy:(()=>{const f=oe(e),v=f==null?void 0:f.whatsappAccountId,k=v?p.find($=>$.accountId===v):p[0];return(k==null?void 0:k.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var T;const f=oe(e),v=f==null?void 0:f.whatsappAccountId,k=v?p.find(_=>_.accountId===v):p[0];if(!k)return;const A=k.dmPolicy!=null&&k.dmPolicy!=="disabled"?"disabled":"open",C=A==="open"?{dmPolicy:A,allowFrom:["*"]}:{dmPolicy:A};try{const _=await e.client.request("config.get"),R=_.config,O=(T=R==null?void 0:R.channels)==null?void 0:T.whatsapp,ye=((O==null?void 0:O.accounts)??{})[k.accountId]?{channels:{whatsapp:{accounts:{[k.accountId]:C}}}}:{channels:{whatsapp:C}};await e.client.request("config.patch",{raw:JSON.stringify(ye),baseHash:_.hash,note:`WhatsApp DM policy → ${A}`,skipRestart:!0}),await G(e,!1)}catch(_){console.error("DM toggle failed:",_)}},whatsappModel:(()=>{var T,_;const f=oe(e);if(!f)return null;const v=f.agents.find(R=>R.id.endsWith("-public")||R.id==="public");if(!v)return null;const k=(T=e.configSnapshot)==null?void 0:T.config,$=(_=k==null?void 0:k.agents)==null?void 0:_.list;if(!Array.isArray($))return null;const A=$.find(R=>R.id===v.id);if(!(A!=null&&A.model))return null;const C=typeof A.model=="string"?A.model:A.model.primary;return(C==null?void 0:C.trim())||null})(),whatsappModelCatalog:e.chatModelCatalog??[],onWhatsAppModelChange:async f=>{const v=oe(e);if(!v)return;const k=v.agents.find($=>$.id.endsWith("-public")||$.id==="public");if(k)try{const $=await e.client.request("config.get"),A=$.config,C=(A==null?void 0:A.agents)??{},T=Array.isArray(C.list)?[...C.list]:[],_=T.findIndex(O=>O.id===k.id);if(f)_>=0?T[_]={...T[_],model:f}:T.push({id:k.id,model:f});else if(_>=0){const{model:O,...ee}=T[_];Object.keys(ee).length<=1?T.splice(_,1):T[_]=ee}const R=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(R),baseHash:$.hash,note:`Public agent model → ${f||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch($){console.error("Model change failed:",$)}},whatsappThinkingLevel:(()=>{var C,T,_;const f=oe(e);if(!f)return null;const v=f.agents.find(R=>R.id.endsWith("-public")||R.id==="public");if(!v)return null;const k=(C=e.configSnapshot)==null?void 0:C.config,$=(T=k==null?void 0:k.agents)==null?void 0:T.list;if(!Array.isArray($))return null;const A=$.find(R=>R.id===v.id);return((_=A==null?void 0:A.thinkingLevel)==null?void 0:_.trim())||null})(),onWhatsAppThinkingChange:async f=>{const v=oe(e);if(!v)return;const k=v.agents.find($=>$.id.endsWith("-public")||$.id==="public");if(k)try{const $=await e.client.request("config.get"),A=$.config,C=(A==null?void 0:A.agents)??{},T=Array.isArray(C.list)?[...C.list]:[],_=T.findIndex(ee=>ee.id===k.id),R=f==="off"?void 0:f;if(R)_>=0?T[_]={...T[_],thinkingLevel:R}:T.push({id:k.id,thinkingLevel:R});else if(_>=0){const{thinkingLevel:ee,...ye}=T[_];Object.keys(ye).length<=1?T.splice(_,1):T[_]=ye}const O=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(O),baseHash:$.hash,note:`Public agent thinking → ${R||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch($){console.error("Thinking change failed:",$)}},whatsappGroupPolicy:(()=>{var _,R;const f=(_=e.configSnapshot)==null?void 0:_.config,v=(R=f==null?void 0:f.channels)==null?void 0:R.whatsapp,k=oe(e),$=k==null?void 0:k.whatsappAccountId,A=(v==null?void 0:v.accounts)??{},C=$?A[$]:void 0;return(C==null?void 0:C.groupPolicy)??(v==null?void 0:v.groupPolicy)??"allowlist"})(),whatsappGroupRequireMention:(()=>{var R,O;const f=(R=e.configSnapshot)==null?void 0:R.config,v=(O=f==null?void 0:f.channels)==null?void 0:O.whatsapp,k=oe(e),$=k==null?void 0:k.whatsappAccountId,A=(v==null?void 0:v.accounts)??{},C=$?A[$]:void 0,_=((C==null?void 0:C.groups)??(v==null?void 0:v.groups)??{})["*"];return(_==null?void 0:_.requireMention)!==!1})(),onWhatsAppGroupToggle:async()=>{var k;const f=oe(e),v=f==null?void 0:f.whatsappAccountId;try{const $=await e.client.request("config.get"),A=$.config,C=((k=A==null?void 0:A.channels)==null?void 0:k.whatsapp)??{},T=C.accounts??{},_=v?T[v]:void 0,R=(_==null?void 0:_.groupPolicy)??C.groupPolicy??"allowlist",O=R==="disabled"||R==="allowlist",ee=O?"open":"disabled",ye=O?{"*":{}}:void 0,Ve={groupPolicy:ee};ye&&(Ve.groups=ye);const X=_?{channels:{whatsapp:{accounts:{[v]:Ve}}}}:{channels:{whatsapp:Ve}};await e.client.request("config.patch",{raw:JSON.stringify(X),baseHash:$.hash,note:`WhatsApp groups → ${ee}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch($){console.error("Group toggle failed:",$)}},onWhatsAppGroupMentionChange:async f=>{var $;const v=oe(e),k=v==null?void 0:v.whatsappAccountId;try{const A=await e.client.request("config.get"),C=A.config,_=((($=C==null?void 0:C.channels)==null?void 0:$.whatsapp)??{}).accounts??{},R=k?_[k]:void 0,O={"*":{requireMention:f}},ee=R?{channels:{whatsapp:{accounts:{[k]:{groups:O}}}}}:{channels:{whatsapp:{groups:O}}};await e.client.request("config.patch",{raw:JSON.stringify(ee),baseHash:A.hash,note:`WhatsApp group mention → ${f?"when mentioned":"always"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Group mention change failed:",A)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:h.configured,imessageRunning:h.running,imessageConnected:h.connected,imessageLastError:h.lastError,imessageSelfChatMode:h.selfChatMode,imessageCliPath:h.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:b,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),v=f.config,k=(v==null?void 0:v.bindings)??[],$=oe(e),A=$==null?void 0:$.agents.find(O=>O.id.endsWith("-admin")||O.id==="admin"),C=(A==null?void 0:A.id)??"admin",T=k.filter(O=>{var ee;return((ee=O.match)==null?void 0:ee.channel)!=="imessage"}),_=[{agentId:C,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],R=[...T,..._];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:R}),baseHash:f.hash,note:"Enable iMessage (self-chat) for "+(($==null?void 0:$.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Re(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await G(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),v=f.config,$=((v==null?void 0:v.bindings)??[]).filter(A=>{var C;return((C=A.match)==null?void 0:C.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:$}),baseHash:f.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Re(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),v=f.config,k=(v==null?void 0:v.bindings)??[],$=oe(e),A=$==null?void 0:$.agents.find(R=>R.id.endsWith("-admin")||R.id==="admin"),C=(A==null?void 0:A.id)??"admin",T=k.filter(R=>{var O;return((O=R.match)==null?void 0:O.channel)!=="imessage"}),_=[{agentId:C,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:[...T,..._]}),baseHash:f.hash,note:"Reassign iMessage to "+(($==null?void 0:$.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Re(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:f=>{e.infoModalOpen=f},onInfoModalClose:()=>{e.infoModalOpen=null},isMaster:e.accessState.master,apiKeyProviders:e.apiKeyProviders,apiKeyModalOpen:e.apiKeyModalOpen,apiKeyBusy:e.apiKeyBusy,apiKeyError:e.apiKeyError,apiKeySuccess:e.apiKeySuccess,apiKeySavingProvider:e.apiKeySavingProvider,onApiKeyModalOpen:()=>{e.apiKeyModalOpen=!0,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeyModalClose:()=>{e.apiKeyModalOpen=!1,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeySave:async(f,v)=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await tl(e.client,f,v);const k=`${f} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await ro(e.client)}catch{}f==="anthropic"&&await e.handleAuthStatusCheck(),setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:"Failed to save key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyRemove:async f=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Nb(e.client,f);const v=`${f} key removed`;e.apiKeySuccess=v,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await ro(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===v&&(e.apiKeySuccess=null)},2500)}catch(v){e.apiKeyError=v instanceof Error?v.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},authApiKeyMode:e.authApiKeyMode,authApiKeyInput:e.authApiKeyInput,authApiKeyBusy:e.authApiKeyBusy,authApiKeyError:e.authApiKeyError,onAuthApiKeyToggle:()=>{e.authApiKeyMode=!e.authApiKeyMode,e.authApiKeyError=null},onAuthApiKeyChange:f=>{e.authApiKeyInput=f},onAuthApiKeySubmit:async()=>{const f=e.authApiKeyInput.trim();if(f){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await tl(e.client,"anthropic",f),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(v){e.authApiKeyError=v instanceof Error?v.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var v;const f=e.selectedWorkspace??((v=e.workspaces[0])==null?void 0:v.name);return f?e.accessState.accounts.some(k=>k.id===f):!1})(),accountPinModalOpen:e.accountPinModalOpen,accountPinBusy:e.accountPinBusy,accountPinError:e.accountPinError,accountPinSuccess:e.accountPinSuccess,onAccountPinModalOpen:()=>{e.accountPinModalOpen=!0,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinModalClose:()=>{e.accountPinModalOpen=!1,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinSave:(f,v)=>{var $;const k=e.selectedWorkspace??(($=e.workspaces[0])==null?void 0:$.name);k&&e.handleAccountPinSave(k,f,v)},publicChatEnabled:(()=>{var k;const f=(k=e.configSnapshot)==null?void 0:k.config,v=f==null?void 0:f.publicChat;return(v==null?void 0:v.enabled)===!0})(),publicChatAuthMode:(()=>{var $;const f=($=e.configSnapshot)==null?void 0:$.config,v=f==null?void 0:f.publicChat,k=v==null?void 0:v.auth;return k==="verified"||k==="choice"?k:"anonymous"})(),publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var f;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const v=await e.client.request("config.get"),k=v.config,$=((f=k==null?void 0:k.publicChat)==null?void 0:f.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!$}}),baseHash:v.hash,note:`Public chat → ${$?"disabled":"enabled"}`}),e.configSnapshot=await e.client.request("config.get")}catch(v){console.error("Public chat toggle failed:",v)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async f=>{if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const v=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{auth:f}}),baseHash:v.hash,note:`Public chat auth → ${f}`}),e.configSnapshot=await e.client.request("config.get")}catch(v){console.error("Public chat auth mode change failed:",v)}finally{e.publicChatToggleBusy=!1}}},brandAccentColor:(()=>{var k;const f=e.selectedWorkspace;return f?((k=Me()[f])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const f=e.selectedWorkspace;return f?((k=Me()[f])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const f=e.selectedWorkspace;return f?!!((k=Me()[f])!=null&&k.logoUrl):!1})(),brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async f=>{var k;const v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{const $=await e.client.request("config.get"),A=$.config,C=((k=A==null?void 0:A.workspaces)==null?void 0:k[v])??{},T=C.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[v]:{...C,brand:{...T,accentColor:f}}}}),baseHash:$.hash,note:`Brand accent → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const _=Me();_[v]||(_[v]={}),_[v].accentColor=f,hn(v)}catch($){console.error("Brand accent change failed:",$)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async f=>{var k;const v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{const $=await e.client.request("config.get"),A=$.config,C=((k=A==null?void 0:A.workspaces)==null?void 0:k[v])??{},T=C.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[v]:{...C,brand:{...T,backgroundColor:f}}}}),baseHash:$.hash,note:`Brand background → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const _=Me();_[v]||(_[v]={}),_[v].backgroundColor=f,hn(v)}catch($){console.error("Brand background change failed:",$)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async f=>{const v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{const k=await f.arrayBuffer(),$=new Uint8Array(k);let A="";for(let _=0;_<$.length;_++)A+=String.fromCharCode($[_]);const C=btoa(A);await e.client.request("brand.uploadLogo",{workspace:v,data:C,mimeType:f.type});const T=Me();T[v]||(T[v]={}),T[v].logoUrl=`/brand-logo/${encodeURIComponent(v)}`}catch(k){console.error("Brand logo upload failed:",k)}finally{e.brandingBusy=!1}}},onBrandLogoRemove:async()=>{const f=e.selectedWorkspace;if(!(!f||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:f});const v=Me();v[f]&&delete v[f].logoUrl}catch(v){console.error("Brand logo remove failed:",v)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var v;const f=e.selectedWorkspace;if(!(!f||e.brandingBusy)){e.brandingBusy=!0;try{const k=await e.client.request("config.get"),$=k.config,A=((v=$==null?void 0:$.workspaces)==null?void 0:v[f])??{},{brand:C,...T}=A;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[f]:{...T,brand:null}}}),baseHash:k.hash,note:"Brand reset to defaults",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");try{await e.client.request("brand.removeLogo",{workspace:f})}catch{}const _=Me();delete _[f],hn(f)}catch(k){console.error("Brand reset failed:",k)}finally{e.brandingBusy=!1}}},tailscaleStatus:e.tailscaleStatus,tailscaleBusy:e.tailscaleBusy,tailscaleAuthUrl:e.tailscaleAuthUrl,tailscaleError:e.tailscaleError,tailscaleFunnelEnableUrl:e.tailscaleFunnelEnableUrl,onTailscaleEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleAuthUrl=null;try{const f=await e.client.request("tailscale.enable");if(f.authUrl){e.tailscaleAuthUrl=f.authUrl;const v=setInterval(async()=>{try{const k=await e.client.request("tailscale.status");e.tailscaleStatus=k,k.loggedIn&&(clearInterval(v),e.tailscaleAuthUrl=null,e.tailscaleBusy=!1)}catch{}},3e3);setTimeout(()=>{clearInterval(v),e.tailscaleBusy&&(e.tailscaleBusy=!1)},3e5)}else f.alreadyLoggedIn&&(e.tailscaleStatus=await e.client.request("tailscale.status")),e.tailscaleBusy=!1}catch(f){console.error("Tailscale enable failed:",f),e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var f;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable")}catch(v){console.error("Tailscale funnel enable failed:",v);const k=v;(f=k.payload)!=null&&f.enableUrl&&(e.tailscaleFunnelEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Funnel",e.tailscaleBusy=!1}}},onTailscaleFunnelDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.funnel.disable")}catch(f){console.error("Tailscale funnel disable failed:",f),e.tailscaleBusy=!1}}},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[f,v]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);e.wifiNetworks=f.networks,e.wifiStatus=v}catch(f){console.error("WiFi scan failed:",f),e.wifiError=f.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{if(e.wifiBusy||!e.wifiSelectedSsid)return;const f=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const v=await e.client.request("wifi.connect",{ssid:f,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:v.connected,ssid:v.ssid,signal:null,ip:v.ip,savedSsid:v.ssid,autoconnect:!0},e.wifiBusy=!1;try{const k=await e.client.request("wifi.status");e.wifiStatus=k}catch{}}catch(v){console.error("WiFi connect failed:",v),e.wifiError=v.message||"Failed to connect",e.wifiBusy=!1}},onWifiDisconnect:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.disconnect"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const f=await e.client.request("wifi.status");e.wifiStatus=f}catch(f){console.error("WiFi disconnect failed:",f),e.wifiError=f.message||"Failed to disconnect"}finally{e.wifiBusy=!1}}},onWifiForget:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.forget"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const f=await e.client.request("wifi.status");e.wifiStatus=f}catch(f){console.error("WiFi forget failed:",f),e.wifiError=f.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:f=>{e.wifiSelectedSsid=f,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:f=>{e.wifiPassword=f},wsProps:lw(e)})}if(e.filesPage){const l=dw(e);return xf({connected:e.connected,wsProps:cn(e),loading:e.filesLoading,tree:e.filesTree,root:e.filesRoot,error:e.filesError,selectedPath:e.filesSelectedPath,selectedPaths:e.filesSelectedPaths,previewContent:e.filesPreviewContent,previewLoading:e.filesPreviewLoading,previewBinary:e.filesPreviewBinary,previewSize:e.filesPreviewSize,expandedDirs:e.filesExpandedDirs,currentDir:e.filesCurrentDir,message:e.filesMessage,uploadBusy:e.filesUploadBusy,reindexBusy:e.filesReindexBusy,memoryStatus:e.filesMemoryStatus,onRefresh:()=>Ht(e,l),onReindex:()=>Uh(e,l),onSelectFile:p=>{e.filesPendingDeletePath=null,Lh(e,p,l)},onToggleSelectFile:p=>Ih(e,p,l),onToggleDir:p=>Wh(e,p),onUpload:(p,h)=>Bh(e,p,h,l),onNewFolder:(p,h)=>Nh(e,p,h,l),onDownload:p=>_c(e,p,l),onBulkDownload:()=>Rh(e,l),onDelete:p=>{e.filesPendingDeletePath=null,Oh(e,p,l)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,h)=>Dh(e,p,h,l),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const h=e.filesSearchAgentId??l;Kh(e,p,h)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{zh(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return bf({connected:e.connected,active:e.browserScreencastActive,loading:e.browserLoading,error:e.browserError,inputMode:e.browserInputMode,fullscreen:e.browserFullscreen,handoffPending:e.browserHandoffPending,handoffReason:e.browserHandoffReason,onStart:()=>_b(e),onStop:()=>Mb(e),onToggleInput:()=>Lb(e),onToggleFullscreen:()=>Ib(e),onCompleteHandoff:()=>Pb(e),onCanvasMouseDown:l=>{const h=l.target.getBoundingClientRect(),f=bn().translateCoordinates(l.clientX-h.left,l.clientY-h.top);_s(e,"mousePressed",f.x,f.y,l.button===2?"right":l.button===1?"middle":"left")},onCanvasMouseUp:l=>{const h=l.target.getBoundingClientRect(),f=bn().translateCoordinates(l.clientX-h.left,l.clientY-h.top);_s(e,"mouseReleased",f.x,f.y)},onCanvasMouseMove:l=>{const p=bn();if(p.shouldThrottleMouseMove())return;const b=l.target.getBoundingClientRect(),f=p.translateCoordinates(l.clientX-b.left,l.clientY-b.top);_s(e,"mouseMoved",f.x,f.y)},onCanvasKeyDown:l=>{let p=0;l.altKey&&(p|=1),l.ctrlKey&&(p|=2),l.metaKey&&(p|=4),l.shiftKey&&(p|=8),Ms(e,"keyDown",l.key,{code:l.code,modifiers:p||void 0}),l.key.length===1&&Ms(e,"char",l.key,{text:l.key})},onCanvasKeyUp:l=>{Ms(e,"keyUp",l.key,{code:l.code})}});if(e.adminsPage){const l=cw(e),p=uw(e);return Kf({connected:e.connected,wsProps:cn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>Fi(e,l),onAdd:h=>{Gu(e,h,l,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:h=>Qu(e,h,l,p),onNewPhoneChange:h=>e.handleAdminsNewPhoneChange(h)})}if(e.contactsPage){const l=pw(e);return Gf({connected:e.connected,wsProps:cn(e),loading:e.contactsLoading,saving:e.contactsSaving,records:e.contactsRecords,error:e.contactsError,searchQuery:e.contactsSearchQuery,editingId:e.contactsEditingId,showAddForm:e.contactsShowAddForm,newRecordPhone:e.contactsNewPhone,newRecordName:e.contactsNewName,deleteConfirmId:e.contactsDeleteConfirmId,addFieldForId:e.contactsAddFieldForId,addFieldKey:e.contactsAddFieldKey,addFieldValue:e.contactsAddFieldValue,onSearch:p=>e.contactsSearchQuery=p,onSearchSubmit:()=>wt(e,l),onAdd:(p,h)=>Yu(e,p,h,l),onDelete:p=>Ju(e,p,l),onSetField:(p,h,b)=>ao(e,p,h,b,l),onDeleteField:(p,h)=>Xu(e,p,h,l),onToggleExpand:p=>{e.contactsEditingId=e.contactsEditingId===p?null:p},onShowAddForm:()=>e.contactsShowAddForm=!0,onCancelAddForm:()=>{e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName=""},onNewRecordPhoneChange:p=>e.handleContactsNewPhoneChange(p),onNewRecordNameChange:p=>e.handleContactsNewNameChange(p),onRefresh:()=>wt(e,l),onDeleteConfirmOpen:p=>e.contactsDeleteConfirmId=p,onDeleteConfirmClose:()=>e.contactsDeleteConfirmId=null,onAddFieldOpen:p=>{e.contactsAddFieldForId=p,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldClose:()=>{e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldKeyChange:p=>e.contactsAddFieldKey=p,onAddFieldValueChange:p=>e.contactsAddFieldValue=p,onAddFieldSubmit:()=>{const p=e.contactsAddFieldForId,h=e.contactsAddFieldKey.trim();!p||!h||(ao(e,p,h,e.contactsAddFieldValue,l),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const l=e.connected?null:"Disconnected from gateway.",p=cl(e),h=e.chatAvatarUrl??p??null,b=(()=>{var k;const f=(k=e.configSnapshot)==null?void 0:k.config,v=f==null?void 0:f.publicChat;return(v==null?void 0:v.enabled)===!0})();return Lv({connected:e.connected,wsProps:cn(e),publicChatEnabled:b,publicChatAccountId:e.selectedWorkspace??void 0,sessionKey:e.sessionKey,onSessionKeyChange:f=>{e.sessionKey=f,e.chatMessage="",e.chatAttachments=[],e.chatStream=null,e.chatInterimText=null,e.chatSuggestion=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:f,lastActiveSessionKey:f}),e.loadAssistantIdentity(),Le(e),Ks(e)},thinkingLevel:e.chatThinkingLevel,showThinking:e.settings.chatShowThinking??!1,modelProvider:e.chatModelProvider,model:e.chatModel,modelCatalog:e.chatModelCatalog,onModelChange:f=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{model:f}).then(()=>{Le(e,{limit:v})})},onThinkingLevelChange:f=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{thinkingLevel:f==="off"?null:f}).then(()=>{Le(e,{limit:v})})},verboseLevel:e.chatVerboseLevel,fillerEnabled:e.chatFillerEnabled,suggestion:e.chatSuggestion,onSuggestionClick:f=>{e.chatMessage=f,e.chatSuggestion=null,e.handleSendChat()},onVerboseChange:f=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{verboseLevel:f==="off"?null:f}).then(()=>{Le(e,{limit:v})})},onFillerChange:f=>{const v=Math.max(e.chatMessages.length+10,Ie);Kn(e,e.sessionKey,{fillerEnabled:f}).then(()=>{Le(e,{limit:v})})},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:h,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,disabledReason:l,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const f=Math.max(e.chatMessages.length+10,Ie);return Promise.all([Le(e,{limit:f}),Ks(e)])},onToggleFocusMode:()=>{},onChatScroll:f=>e.handleChatScroll(f),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:f=>e.chatMessage=f,attachments:e.chatAttachments,onAttachmentsChange:f=>e.chatAttachments=f,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:f=>e.removeQueuedMessage(f),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:f=>e.handleOpenSidebar(f),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:f=>e.handleSplitRatioChange(f),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?mb({connected:e.connected,wsProps:cn(e),activeTab:e.advancedTab,onTabChange:l=>{e.advancedTab=l,l==="cron"&&e.loadCron(),l==="skills"&&He(e,{clearMessages:!0}),l==="logs"&&(e.logsSubTab==="session"?mn(e,{reset:!0}):Rt(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(r=(o=e.channelsSnapshot)==null?void 0:o.channelMeta)!=null&&r.length?e.channelsSnapshot.channelMeta.map(l=>l.id):((a=e.channelsSnapshot)==null?void 0:a.channelOrder)??[],channelLabels:((u=e.channelsSnapshot)==null?void 0:u.channelLabels)??{},channelMeta:((c=e.channelsSnapshot)==null?void 0:c.channelMeta)??[],agentIds:(()=>{var p;const l=oe(e);return((p=l==null?void 0:l.agents)==null?void 0:p.map(h=>h.id))??[]})(),runsJobId:e.cronRunsJobId,runs:e.cronRuns,newEventModalOpen:e.cronNewEventModal,onNewEventModalOpen:()=>{e.cronNewEventModal=!0},onNewEventModalClose:()=>{e.cronNewEventModal=!1,e.cronEditJobId=null},detailJobId:e.cronDetailJobId,editJobId:e.cronEditJobId,onDetailOpen:l=>{e.cronDetailJobId=l.id,Ns(e,l.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:l=>{e.cronForm=Np(l),e.cronEditJobId=l.id,e.cronDetailJobId=null},onEditSave:()=>{const l=e.cronEditJobId;l&&Op(e,l).then(()=>{e.cronEditJobId=null})},onFormChange:l=>e.cronForm={...e.cronForm,...l},onRefresh:()=>e.loadCron(),onAdd:()=>{Ip(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(l,p)=>Rp(e,l,p),onRun:l=>Dp(e,l),onRemove:l=>{e.cronPendingDeleteId=null,Bp(e,l)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:l=>{e.cronPendingDeleteId=l||null},onLoadRuns:l=>Ns(e,l)},skillsProps:{loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,detail:e.skillDetail,detailTab:e.skillDetailTab,addModal:e.skillAddModal,drafts:e.skillDrafts,onFilterChange:l=>e.skillsFilter=l,onRefresh:()=>He(e,{clearMessages:!0}),onToggle:(l,p)=>uc(e,l,p),onEdit:(l,p)=>cc(e,l,p),onSaveKey:l=>dc(e,l),onInstall:(l,p,h)=>pc(e,l,p,h),onViewDetail:l=>hc(e,l),onDetailClose:()=>fc(e),onDetailTab:l=>gc(e,l),onAddOpen:()=>mc(e),onAddClose:()=>yc(e),onImportDraft:l=>vc(e,l),onDeleteDraft:l=>wc(e,l),onAddSave:()=>bc(e),onDelete:l=>Sc(e,l),onEditSkill:l=>kc(e,l)},logsProps:{logsSubTab:e.logsSubTab,onSubTabChange:l=>{e.logsSubTab=l,l==="session"?mn(e,{reset:!0}):Rt(e,{reset:!0})},sessionLogsProps:{loading:e.sessionLogsLoading,error:e.sessionLogsError,entries:e.sessionLogsEntries,agents:e.sessionLogsAgents,filterText:e.sessionLogsFilterText,typeFilters:e.sessionLogsTypeFilters,agentFilters:e.sessionLogsAgentFilters,autoFollow:e.sessionLogsAutoFollow,expandedIds:e.sessionLogsExpandedIds,onFilterTextChange:l=>e.sessionLogsFilterText=l,onTypeToggle:(l,p)=>{const h=e;h.sessionLogsTypeFilters={...h.sessionLogsTypeFilters,[l]:p}},onAgentToggle:(l,p)=>{const h=e;h.sessionLogsAgentFilters={...h.sessionLogsAgentFilters,[l]:p}},onToggleAutoFollow:l=>e.sessionLogsAutoFollow=l,onToggleExpand:l=>{const p=e,h=new Set(p.sessionLogsExpandedIds);h.has(l)?h.delete(l):h.add(l),p.sessionLogsExpandedIds=h,p.requestUpdate()},onRefresh:()=>{mn(e,{reset:!0})},onExport:(l,p)=>e.exportSessionLogs(l,p),onScroll:l=>e.handleSessionLogsScroll(l)},loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,truncated:e.logsTruncated,onFilterTextChange:l=>e.logsFilterText=l,onLevelToggle:(l,p)=>{e.logsLevelFilters={...e.logsLevelFilters,[l]:p}},onToggleAutoFollow:l=>e.logsAutoFollow=l,onRefresh:()=>Rt(e,{reset:!0}),onExport:(l,p)=>e.exportSessionLogs(l,p),onScroll:l=>e.handleLogsScroll(l)}}):(window.location.replace("/chat"),d``)}function bw(e){const t=new Date(e),n=t.toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),i=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return`${n} ${i}`}function ul(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function ww(e,t,n){return d`
3819
3848
  <div class="audit-modal-overlay" @click=${s=>{s.target.classList.contains("audit-modal-overlay")&&n()}}>
3820
3849
  <div class="audit-modal-card">
3821
3850
  <div class="audit-modal-header">
@@ -3835,7 +3864,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3835
3864
  <a href="/files" class="audit-modal-path-link">${s.path}</a>
3836
3865
  </div>
3837
3866
  <div class="audit-modal-entry-meta">
3838
- ${fw(s.timestamp)}
3867
+ ${bw(s.timestamp)}
3839
3868
  <span class="audit-modal-agent">${s.agentId}</span>
3840
3869
  </div>
3841
3870
  </div>
@@ -3847,7 +3876,7 @@ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,messag
3847
3876
  `}
3848
3877
  </div>
3849
3878
  </div>
3850
- `}const mw={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},yw={name:"",description:"",agentId:"",enabled:!0,scheduleKind:"every",scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"0 7 * * *",cronTz:"",sessionTarget:"main",wakeMode:"next-heartbeat",payloadKind:"systemEvent",payloadText:"",deliver:!1,channel:"last",recipients:[],toAdmins:!1,timeoutSeconds:"",postToMainPrefix:""};function vw(e){e.basePath=Zh();const t=ze();if(kl(t.accentColor),Sl(t.backgroundColor),window.scrollTo(0,0),jh(e),e.publicChat){const n=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__,i=(n==null?void 0:n.accountId)??"",s=i?i.charAt(0).toUpperCase()+i.slice(1):"Assistant";document.title=`Chat with ${s}`,_e(e);return}if(e.setup){document.title=`${t.name} Setup`,_e(e);return}if(e.filesPage){document.title=`${t.name} Files`,Gh(e),_e(e);return}if(e.browserPage){document.title=`${t.name} Browser`,_e(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,_e(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,_e(e);return}if(e.chatPage){document.title=`${t.name} Chat`,_e(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,_e(e);return}sf(e,!0),ef(e),tf(e),window.addEventListener("popstate",e.popStateHandler),Yh(e),_e(e),Hh(e),e.tab==="logs"&&(e.logsSubTab==="session"?_o(e):Co(e)),e.tab==="debug"&&Po(e)}function bw(e){_p(e)}function ww(e){var t;window.removeEventListener("popstate",e.popStateHandler),qh(e),To(e),Mo(e),Lo(e),Vh(e),Qh(e),nf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function kw(e,t){if(!e.publicChat){if(e.filesPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleFilesLoad&&e.handleFilesLoad(),e.adminsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdminsLoad&&e.handleAdminsLoad(),e.contactsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleContactsLoad&&e.handleContactsLoad(),e.chatPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleChatLoad&&e.handleChatLoad(),e.advancedPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdvancedLoad&&e.handleAdvancedLoad(),e.setup&&e.connected){const n=t.has("connected")&&t.get("connected")===!1;n&&e.handleLicenseStatusCheck&&e.licenseValid===null&&!e.licenseBusy&&e.handleLicenseStatusCheck(),n&&e.handleUpdateCheck&&e.handleUpdateCheck();const i=t.has("setupStep")&&e.setupStep==="auth";(n||i)&&e.setupStep==="auth"&&e.handleAuthStatusCheck&&e.authConnected===null&&!e.authBusy&&e.handleAuthStatusCheck(),e.setupStep==="whatsapp"&&t.has("setupStep")&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(o=>{e.channelsSnapshot=o,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1})),t.has("whatsappLoginConnected")&&e.whatsappLoginConnected===!0&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(s=>{e.channelsSnapshot=s,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1}))}if(e.tab==="chat"&&!e.advancedPage&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),i=t.has("chatLoading")&&t.get("chatLoading")===!0&&e.chatLoading===!1;Wt(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&Bl(e,t.has("tab")||t.has("logsAutoFollow"))}}function Sw(e){const t={name:(e==null?void 0:e.name)??"",displayName:(e==null?void 0:e.displayName)??"",about:(e==null?void 0:e.about)??"",picture:(e==null?void 0:e.picture)??"",banner:(e==null?void 0:e.banner)??"",website:(e==null?void 0:e.website)??"",nip05:(e==null?void 0:e.nip05)??"",lud16:(e==null?void 0:e.lud16)??""};return{values:t,original:{...t},saving:!1,importing:!1,error:null,success:null,fieldErrors:{},showAdvanced:!!(e!=null&&e.banner||e!=null&&e.website||e!=null&&e.nip05||e!=null&&e.lud16)}}async function $w(e,t,n){await mo(e,t,n),await G(e,!0)}async function xw(e,t){await Wl(e,t),await G(e,!0)}async function Aw(e,t){await Kl(e,t),await G(e,!0)}async function Ew(e,t){await zl(e,t)}async function Cw(e,t){await Hl(e,t)}async function Tw(e){await Lp(e),await Re(e),await G(e,!0)}async function _w(e){await Re(e),await G(e,!0)}function Mw(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[i,...s]=n.split(":");if(!i||s.length===0)continue;const o=i.trim(),r=s.join(":").trim();o&&r&&(t[o]=r)}return t}function Zu(e){var n,i,s;return((s=(((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.nostr)??[])[0])==null?void 0:s.accountId)??e.nostrProfileAccountId??"default"}function ed(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function Pw(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Sw(n??void 0)}function Lw(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function Iw(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function Rw(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function Dw(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Zu(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(ed(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),s=await i.json().catch(()=>null);if(!i.ok||(s==null?void 0:s.ok)===!1||!s){const o=(s==null?void 0:s.error)??`Profile update failed (${i.status})`;e.nostrProfileFormState={...t,saving:!1,error:o,success:null,fieldErrors:Mw(s==null?void 0:s.details)};return}if(!s.persisted){e.nostrProfileFormState={...t,saving:!1,error:"Profile publish failed on all relays.",success:null};return}e.nostrProfileFormState={...t,saving:!1,error:null,success:"Profile published to relays.",fieldErrors:{},original:{...t.values}},await G(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function Bw(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Zu(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(ed(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),s=await i.json().catch(()=>null);if(!i.ok||(s==null?void 0:s.ok)===!1||!s){const u=(s==null?void 0:s.error)??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:u,success:null};return}const o=s.merged??s.imported??null,r=o?{...t.values,...o}:t.values,a=!!(r.banner||r.website||r.nip05||r.lud16);e.nostrProfileFormState={...t,importing:!1,values:r,error:null,success:s.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:a},s.saved&&await G(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function Nw(e){if(e.client){e.authBusy=!0,e.authMessage=null;try{const t=await e.client.request("auth.status",{});e.authConnected=t.connected,e.authExpiresIn=t.expiresIn??null,e.authMessage=t.message??null,t.connected&&(e.setupStep="whatsapp")}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to check auth status"}finally{e.authBusy=!1}}}async function Ow(e){if(e.client){e.authBusy=!0,e.authMessage=null,e.authUrl=null,e.authConnected=null;try{const t=await e.client.request("auth.oauth.start",{provider:"anthropic"});e.authUrl=t.authUrl,e.authMessage=t.message??"Sign in with your Claude Pro account"}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to start auth flow"}finally{e.authBusy=!1}}}async function Fw(e,t){if(e.client){e.authBusy=!0,e.authMessage="Verifying code...";try{await e.client.request("auth.oauth.code",{code:t});const n=await e.client.request("auth.oauth.wait",{timeoutMs:3e4});n.connected?(e.authConnected=!0,e.authMessage=n.message??"Connected to Claude!",e.authUrl=null,e.authCodeInput=""):e.authMessage=n.message??"Still waiting for authorization..."}catch(n){e.authConnected=!1,e.authMessage=n instanceof Error?n.message:"Verification failed"}finally{e.authBusy=!1}}}function Uw(e,t){e.authCodeInput=t}function Ww(e){e.setupStep="whatsapp"}async function Kw(e){if(e.client){e.licenseBusy=!0,e.licenseMessage=null;try{const t=await e.client.request("license.status",{});e.licenseDeviceId=t.deviceId??null,e.licenseStoredKey=t.key??null,t.licensed?(e.licenseValid=!0,e.licenseTier=t.tier??null,e.setupStep="auth"):(e.licenseValid=null,e.setupStep="license")}catch(t){const n=t instanceof Error?t.message:String(t);n.includes("unknown method")?(e.licenseValid=!0,e.setupStep="auth"):(e.licenseValid=null,e.licenseMessage=n,e.setupStep="license")}finally{e.licenseBusy=!1}}}async function zw(e){if(e.client&&e.licenseKey.trim()){e.licenseBusy=!0,e.licenseMessage=null,e.licenseValid=null;try{const t=await e.client.request("license.activate",{key:e.licenseKey.trim()});t.valid?(e.licenseValid=!0,e.licenseMessage=t.message??"License activated",e.licenseTier=t.tier??null,setTimeout(()=>{e.setupStep="auth"},1500)):(e.licenseValid=!1,e.licenseMessage=t.message??"Invalid license key")}catch(t){e.licenseValid=!1,e.licenseMessage=t instanceof Error?t.message:"Activation failed"}finally{e.licenseBusy=!1}}}async function Hw(e){if(e.client){e.licenseBusy=!0;try{await e.client.request("license.remove",{}),e.licenseValid=null,e.licenseKey="",e.licenseTier=null,e.licenseMessage=null,e.setupStep="license"}catch(t){e.licenseMessage=t instanceof Error?t.message:"Failed to remove license"}finally{e.licenseBusy=!1}}}function qw(e,t){e.licenseKey=t}async function jw(e){var t,n;if(!(!e.client||!e.connected)&&!e.gatewayHealthLoading){e.gatewayHealthLoading=!0,(t=e.requestUpdate)==null||t.call(e);try{const i=await e.client.request("health",{probe:!0});e.gatewayHealthy=i.ok===!0,e.gatewayHealthMessage=i.ok?`Healthy${i.durationMs?` (${i.durationMs}ms)`:""}`:"Unhealthy"}catch(i){e.gatewayHealthy=!1,e.gatewayHealthMessage=`Error: ${String(i)}`}finally{e.gatewayHealthLoading=!1,(n=e.requestUpdate)==null||n.call(e)}}}async function Vw(e){var t,n,i;if(!(!e.client||e.gatewayRestartBusy)){e.gatewayRestartBusy=!0,e.gatewayHealthMessage="Restarting...",(t=e.requestUpdate)==null||t.call(e);try{const s=await e.client.request("gateway.restart",{reason:"Manual restart from setup page",delayMs:1e3});if(s.ok&&((n=s.restart)!=null&&n.ok))e.gatewayHealthMessage="Restarting...",setTimeout(()=>{window.location.reload()},3e3);else throw new Error("Restart not scheduled")}catch(s){e.gatewayHealthMessage=`Restart failed: ${String(s)}`,e.gatewayRestartBusy=!1,(i=e.requestUpdate)==null||i.call(e)}}}var Gw=Object.defineProperty,Qw=Object.getOwnPropertyDescriptor,m=(e,t,n,i)=>{for(var s=i>1?void 0:i?Qw(t,n):t,o=e.length-1,r;o>=0;o--)(r=e[o])&&(s=(i?r(t,n,s):r(s))||s);return i&&s&&Gw(t,n,s),s};const Is=Fd();function Yw(){if(!window.location.search)return!1;const t=new URLSearchParams(window.location.search).get("onboarding");if(!t)return!1;const n=t.trim().toLowerCase();return n==="1"||n==="true"||n==="yes"||n==="on"}function Jw(){const e=window.location.pathname;if(e==="/setup"||e.endsWith("/setup"))return!0;if(!window.location.search)return!1;const n=new URLSearchParams(window.location.search).get("setup");if(!n)return!1;const i=n.trim().toLowerCase();return i==="1"||i==="true"||i==="yes"||i==="on"}function Xw(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function Zw(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function ek(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function tk(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function nk(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function ik(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let g=class extends It{constructor(){super(...arguments),this.settings=ns(),this.password="",this.tab="chat",this.onboarding=Yw(),this.setup=Jw(),this.filesPage=Xw(),this.browserPage=Zw(),this.adminsPage=ek(),this.contactsPage=tk(),this.chatPage=nk(),this.advancedPage=ik(),this.advancedTab="cron",this.publicChat=!!window.__TASKMASTER_PUBLIC_CHAT__,this.publicChatConfig=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__??{},this.publicChatSessionKey=null,this.publicChatAuthenticated=!1,this.publicChatAuthStep="idle",this.connected=!1,this.accessState=Hu,this.theme=this.settings.theme??"system",this.themeResolved="dark",this.hello=null,this.lastError=null,this.eventLog=[],this.eventLogBuffer=[],this.toolStreamSyncTimer=null,this.sidebarCloseTimer=null,this.assistantName=Is.name,this.assistantAvatar=Is.avatar,this.assistantAgentId=Is.agentId??null,this.sessionKey=this.settings.sessionKey,this.chatLoading=!1,this.chatSending=!1,this.chatMessage="",this.chatMessages=[],this.chatHistoryTotal=0,this.chatHistoryHasMore=!1,this.chatLoadingOlder=!1,this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestion=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatThinkingLevel=null,this.chatModelProvider=null,this.chatModel=null,this.chatModelCatalog=[],this.chatVerboseLevel=null,this.chatFillerEnabled=null,this.chatQueue=[],this.chatAttachments=[],this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.splitRatio=this.settings.splitRatio,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.configLoading=!1,this.configRaw=`{
3879
+ `}const kw={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},Sw={name:"",description:"",agentId:"",enabled:!0,scheduleKind:"every",scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"0 7 * * *",cronTz:"",sessionTarget:"main",wakeMode:"next-heartbeat",payloadKind:"systemEvent",payloadText:"",deliver:!1,channel:"last",recipients:[],toAdmins:!1,timeoutSeconds:"",postToMainPrefix:""};function $w(e){e.basePath=Zh();const t=ze();if(kl(t.accentColor),Sl(t.backgroundColor),window.scrollTo(0,0),jh(e),e.publicChat){const n=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__,i=(n==null?void 0:n.accountId)??"",s=i?i.charAt(0).toUpperCase()+i.slice(1):"Assistant";document.title=`Chat with ${s}`,_e(e);return}if(e.setup){document.title=`${t.name} Setup`,_e(e);return}if(e.filesPage){document.title=`${t.name} Files`,Gh(e),_e(e);return}if(e.browserPage){document.title=`${t.name} Browser`,_e(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,_e(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,_e(e);return}if(e.chatPage){document.title=`${t.name} Chat`,_e(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,_e(e);return}sf(e,!0),ef(e),tf(e),window.addEventListener("popstate",e.popStateHandler),Yh(e),_e(e),Hh(e),e.tab==="logs"&&(e.logsSubTab==="session"?_o(e):Co(e)),e.tab==="debug"&&Po(e)}function Aw(e){_p(e)}function xw(e){var t;window.removeEventListener("popstate",e.popStateHandler),qh(e),To(e),Mo(e),Lo(e),Vh(e),Qh(e),nf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function Ew(e,t){if(!e.publicChat){if(e.filesPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleFilesLoad&&e.handleFilesLoad(),e.adminsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdminsLoad&&e.handleAdminsLoad(),e.contactsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleContactsLoad&&e.handleContactsLoad(),e.chatPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleChatLoad&&e.handleChatLoad(),e.advancedPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdvancedLoad&&e.handleAdvancedLoad(),e.setup&&e.connected){const n=t.has("connected")&&t.get("connected")===!1;n&&e.handleLicenseStatusCheck&&e.licenseValid===null&&!e.licenseBusy&&e.handleLicenseStatusCheck(),n&&e.handleUpdateCheck&&e.handleUpdateCheck();const i=t.has("setupStep")&&e.setupStep==="auth";(n||i)&&e.setupStep==="auth"&&e.handleAuthStatusCheck&&e.authConnected===null&&!e.authBusy&&e.handleAuthStatusCheck(),e.setupStep==="whatsapp"&&t.has("setupStep")&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(o=>{e.channelsSnapshot=o,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1})),t.has("whatsappLoginConnected")&&e.whatsappLoginConnected===!0&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(s=>{e.channelsSnapshot=s,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1}))}if(e.tab==="chat"&&!e.advancedPage&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),i=t.has("chatLoading")&&t.get("chatLoading")===!0&&e.chatLoading===!1;Wt(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&Bl(e,t.has("tab")||t.has("logsAutoFollow"))}}function Cw(e){const t={name:(e==null?void 0:e.name)??"",displayName:(e==null?void 0:e.displayName)??"",about:(e==null?void 0:e.about)??"",picture:(e==null?void 0:e.picture)??"",banner:(e==null?void 0:e.banner)??"",website:(e==null?void 0:e.website)??"",nip05:(e==null?void 0:e.nip05)??"",lud16:(e==null?void 0:e.lud16)??""};return{values:t,original:{...t},saving:!1,importing:!1,error:null,success:null,fieldErrors:{},showAdvanced:!!(e!=null&&e.banner||e!=null&&e.website||e!=null&&e.nip05||e!=null&&e.lud16)}}async function Tw(e,t,n){await mo(e,t,n),await G(e,!0)}async function _w(e,t){await Wl(e,t),await G(e,!0)}async function Mw(e,t){await Kl(e,t),await G(e,!0)}async function Pw(e,t){await zl(e,t)}async function Lw(e,t){await Hl(e,t)}async function Iw(e){await Lp(e),await Re(e),await G(e,!0)}async function Rw(e){await Re(e),await G(e,!0)}function Dw(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[i,...s]=n.split(":");if(!i||s.length===0)continue;const o=i.trim(),r=s.join(":").trim();o&&r&&(t[o]=r)}return t}function Zu(e){var n,i,s;return((s=(((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.nostr)??[])[0])==null?void 0:s.accountId)??e.nostrProfileAccountId??"default"}function ed(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function Bw(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Cw(n??void 0)}function Nw(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function Ow(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function Fw(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function Uw(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Zu(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(ed(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),s=await i.json().catch(()=>null);if(!i.ok||(s==null?void 0:s.ok)===!1||!s){const o=(s==null?void 0:s.error)??`Profile update failed (${i.status})`;e.nostrProfileFormState={...t,saving:!1,error:o,success:null,fieldErrors:Dw(s==null?void 0:s.details)};return}if(!s.persisted){e.nostrProfileFormState={...t,saving:!1,error:"Profile publish failed on all relays.",success:null};return}e.nostrProfileFormState={...t,saving:!1,error:null,success:"Profile published to relays.",fieldErrors:{},original:{...t.values}},await G(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function Ww(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Zu(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(ed(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),s=await i.json().catch(()=>null);if(!i.ok||(s==null?void 0:s.ok)===!1||!s){const u=(s==null?void 0:s.error)??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:u,success:null};return}const o=s.merged??s.imported??null,r=o?{...t.values,...o}:t.values,a=!!(r.banner||r.website||r.nip05||r.lud16);e.nostrProfileFormState={...t,importing:!1,values:r,error:null,success:s.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:a},s.saved&&await G(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function Kw(e){if(e.client){e.authBusy=!0,e.authMessage=null;try{const t=await e.client.request("auth.status",{});e.authConnected=t.connected,e.authExpiresIn=t.expiresIn??null,e.authMessage=t.message??null,t.connected&&(e.setupStep="whatsapp")}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to check auth status"}finally{e.authBusy=!1}}}async function zw(e){if(e.client){e.authBusy=!0,e.authMessage=null,e.authUrl=null,e.authConnected=null;try{const t=await e.client.request("auth.oauth.start",{provider:"anthropic"});e.authUrl=t.authUrl,e.authMessage=t.message??"Sign in with your Claude Pro account"}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to start auth flow"}finally{e.authBusy=!1}}}async function Hw(e,t){if(e.client){e.authBusy=!0,e.authMessage="Verifying code...";try{await e.client.request("auth.oauth.code",{code:t});const n=await e.client.request("auth.oauth.wait",{timeoutMs:3e4});n.connected?(e.authConnected=!0,e.authMessage=n.message??"Connected to Claude!",e.authUrl=null,e.authCodeInput=""):e.authMessage=n.message??"Still waiting for authorization..."}catch(n){e.authConnected=!1,e.authMessage=n instanceof Error?n.message:"Verification failed"}finally{e.authBusy=!1}}}function qw(e,t){e.authCodeInput=t}function jw(e){e.setupStep="whatsapp"}async function Vw(e){if(e.client){e.licenseBusy=!0,e.licenseMessage=null;try{const t=await e.client.request("license.status",{});e.licenseDeviceId=t.deviceId??null,e.licenseStoredKey=t.key??null,t.licensed?(e.licenseValid=!0,e.licenseTier=t.tier??null,e.setupStep="auth"):(e.licenseValid=null,e.setupStep="license")}catch(t){const n=t instanceof Error?t.message:String(t);n.includes("unknown method")?(e.licenseValid=!0,e.setupStep="auth"):(e.licenseValid=null,e.licenseMessage=n,e.setupStep="license")}finally{e.licenseBusy=!1}}}async function Gw(e){if(e.client&&e.licenseKey.trim()){e.licenseBusy=!0,e.licenseMessage=null,e.licenseValid=null;try{const t=await e.client.request("license.activate",{key:e.licenseKey.trim()});t.valid?(e.licenseValid=!0,e.licenseMessage=t.message??"License activated",e.licenseTier=t.tier??null,setTimeout(()=>{e.setupStep="auth"},1500)):(e.licenseValid=!1,e.licenseMessage=t.message??"Invalid license key")}catch(t){e.licenseValid=!1,e.licenseMessage=t instanceof Error?t.message:"Activation failed"}finally{e.licenseBusy=!1}}}async function Qw(e){if(e.client){e.licenseBusy=!0;try{await e.client.request("license.remove",{}),e.licenseValid=null,e.licenseKey="",e.licenseTier=null,e.licenseMessage=null,e.setupStep="license"}catch(t){e.licenseMessage=t instanceof Error?t.message:"Failed to remove license"}finally{e.licenseBusy=!1}}}function Yw(e,t){e.licenseKey=t}async function Jw(e){var t,n;if(!(!e.client||!e.connected)&&!e.gatewayHealthLoading){e.gatewayHealthLoading=!0,(t=e.requestUpdate)==null||t.call(e);try{const i=await e.client.request("health",{probe:!0});e.gatewayHealthy=i.ok===!0,e.gatewayHealthMessage=i.ok?`Healthy${i.durationMs?` (${i.durationMs}ms)`:""}`:"Unhealthy"}catch(i){e.gatewayHealthy=!1,e.gatewayHealthMessage=`Error: ${String(i)}`}finally{e.gatewayHealthLoading=!1,(n=e.requestUpdate)==null||n.call(e)}}}async function Xw(e){var t,n,i;if(!(!e.client||e.gatewayRestartBusy)){e.gatewayRestartBusy=!0,e.gatewayHealthMessage="Restarting...",(t=e.requestUpdate)==null||t.call(e);try{const s=await e.client.request("gateway.restart",{reason:"Manual restart from setup page",delayMs:1e3});if(s.ok&&((n=s.restart)!=null&&n.ok))e.gatewayHealthMessage="Restarting...",setTimeout(()=>{window.location.reload()},3e3);else throw new Error("Restart not scheduled")}catch(s){e.gatewayHealthMessage=`Restart failed: ${String(s)}`,e.gatewayRestartBusy=!1,(i=e.requestUpdate)==null||i.call(e)}}}var Zw=Object.defineProperty,ek=Object.getOwnPropertyDescriptor,m=(e,t,n,i)=>{for(var s=i>1?void 0:i?ek(t,n):t,o=e.length-1,r;o>=0;o--)(r=e[o])&&(s=(i?r(t,n,s):r(s))||s);return i&&s&&Zw(t,n,s),s};const Is=Fd();function tk(){if(!window.location.search)return!1;const t=new URLSearchParams(window.location.search).get("onboarding");if(!t)return!1;const n=t.trim().toLowerCase();return n==="1"||n==="true"||n==="yes"||n==="on"}function nk(){const e=window.location.pathname;if(e==="/setup"||e.endsWith("/setup"))return!0;if(!window.location.search)return!1;const n=new URLSearchParams(window.location.search).get("setup");if(!n)return!1;const i=n.trim().toLowerCase();return i==="1"||i==="true"||i==="yes"||i==="on"}function ik(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function sk(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function ok(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function rk(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function ak(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function lk(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let g=class extends It{constructor(){super(...arguments),this.settings=ns(),this.password="",this.tab="chat",this.onboarding=tk(),this.setup=nk(),this.filesPage=ik(),this.browserPage=sk(),this.adminsPage=ok(),this.contactsPage=rk(),this.chatPage=ak(),this.advancedPage=lk(),this.advancedTab="cron",this.publicChat=!!window.__TASKMASTER_PUBLIC_CHAT__,this.publicChatConfig=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__??{},this.publicChatSessionKey=null,this.publicChatAuthenticated=!1,this.publicChatAuthStep="idle",this.connected=!1,this.accessState=Hu,this.theme=this.settings.theme??"system",this.themeResolved="dark",this.hello=null,this.lastError=null,this.eventLog=[],this.eventLogBuffer=[],this.toolStreamSyncTimer=null,this.sidebarCloseTimer=null,this.assistantName=Is.name,this.assistantAvatar=Is.avatar,this.assistantAgentId=Is.agentId??null,this.sessionKey=this.settings.sessionKey,this.chatLoading=!1,this.chatSending=!1,this.chatMessage="",this.chatMessages=[],this.chatHistoryTotal=0,this.chatHistoryHasMore=!1,this.chatLoadingOlder=!1,this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestion=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatThinkingLevel=null,this.chatModelProvider=null,this.chatModel=null,this.chatModelCatalog=[],this.chatVerboseLevel=null,this.chatFillerEnabled=null,this.chatQueue=[],this.chatAttachments=[],this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.splitRatio=this.settings.splitRatio,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.configLoading=!1,this.configRaw=`{
3851
3880
  }
3852
- `,this.configRawOriginal="",this.configValid=null,this.configIssues=[],this.configSaving=!1,this.configApplying=!1,this.updateRunning=!1,this.applySessionKey=this.settings.lastActiveSessionKey,this.configSnapshot=null,this.configSchema=null,this.configSchemaVersion=null,this.configSchemaLoading=!1,this.configUiHints={},this.configForm=null,this.configFormOriginal=null,this.configFormDirty=!1,this.configFormMode="form",this.configSearchQuery="",this.configActiveSection=null,this.configActiveSubsection=null,this.channelsLoading=!1,this.channelsSnapshot=null,this.channelsError=null,this.channelsLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.whatsappActiveQrAccountId=null,this.whatsappPairedPhone=null,this.addingWhatsAppAccount=!1,this.newWhatsAppAccountName="",this.whatsappAccountError=null,this.whatsappAccountSaving=!1,this.whatsappSettingsOpen=!1,this.publicChatToggleBusy=!1,this.brandingBusy=!1,this.brandingExpanded=!1,this.tailscaleStatus=null,this.tailscaleBusy=!1,this.tailscaleAuthUrl=null,this.tailscaleError=null,this.tailscaleFunnelEnableUrl=null,this.wifiStatus=null,this.wifiNetworks=[],this.wifiBusy=!1,this.wifiError=null,this.wifiPassword="",this.wifiSelectedSsid=null,this.licenseKey="",this.licenseBusy=!1,this.licenseValid=null,this.licenseMessage=null,this.licenseTier=null,this.licenseDeviceId=null,this.licenseStoredKey=null,this.licenseRemoveConfirm=!1,this.authConnected=null,this.authBusy=!1,this.authMessage=null,this.authUrl=null,this.authCodeInput="",this.authExpiresIn=null,this.setupStep="license",this.gatewayHealthy=null,this.gatewayHealthLoading=!1,this.gatewayHealthMessage=null,this.gatewayRestartBusy=!1,this.updateAvailable=null,this.currentVersion=null,this.latestVersion=null,this.updateChecking=!1,this.updateMessage=null,this.updateProgressSteps=[],this.updateLastResult=null,this.uninstallConfirm=!1,this.uninstallBusy=!1,this.uninstallDone=!1,this.uninstallError=null,this.uninstallConfirmText="",this.nostrProfileFormState=null,this.nostrProfileAccountId=null,this.presenceLoading=!1,this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.sessionsLoading=!1,this.sessionsResult=null,this.sessionsError=null,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...yw},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.cronNewEventModal=!1,this.cronDetailJobId=null,this.cronEditJobId=null,this.cronPendingDeleteId=null,this.browserScreencastActive=!1,this.browserScreencastFrame=null,this.browserScreencastMetadata=null,this.browserHandoffPending=!1,this.browserHandoffReason=null,this.browserHandoffId=null,this.browserInputMode=!1,this.browserFullscreen=!1,this.browserLoading=!1,this.browserError=null,this.filesLoading=!1,this.filesTree=[],this.filesRoot="",this.filesError=null,this.filesSelectedPath=null,this.filesSelectedPaths=new Set,this.filesPreviewContent=null,this.filesPreviewLoading=!1,this.filesPreviewBinary=!1,this.filesPreviewSize=null,this.filesExpandedDirs=new Set,this.filesCurrentDir=".",this.filesPendingDeletePath=null,this.filesMessage=null,this.filesUploadBusy=!1,this.filesReindexBusy=!1,this.filesMemoryStatus=null,this.embeddingDownloading=!1,this.embeddingPollTimer=null,this.filesSearchQuery="",this.filesSearchResults=null,this.filesSearchLoading=!1,this.filesSearchAgentId=null,this.filesResolvedAgentId=void 0,this.auditEntries=[],this.auditLoading=!1,this.auditModalOpen=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillDetail=null,this.skillDetailTab="",this.skillAddModal=!1,this.skillAddForm={name:"",skillContent:"",references:[]},this.skillDrafts=[],this.adminsLoading=!1,this.adminPhones=[],this.adminsError=null,this.adminsSaving=!1,this.adminsNewPhone="",this.contactsLoading=!1,this.contactsSaving=!1,this.contactsRecords=[],this.contactsError=null,this.contactsSearchQuery="",this.contactsEditingId=null,this.contactsShowAddForm=!1,this.contactsNewPhone="",this.contactsNewName="",this.contactsDeleteConfirmId=null,this.contactsAddFieldForId=null,this.contactsAddFieldKey="",this.contactsAddFieldValue="",this.imessageEnableConfirm=!1,this.imessageEnabling=!1,this.infoModalOpen=null,this.workspaces=[],this.workspacesLoading=!1,this.workspacesError=null,this.selectedWorkspace=null,this.addingWorkspace=!1,this.newWorkspaceName="",this.newWorkspacePath="",this.newWorkspacePin="",this.accountPinModalOpen=!1,this.accountPinBusy=!1,this.accountPinError=null,this.accountPinSuccess=null,this.apiKeyProviders=[],this.apiKeyModalOpen=!1,this.apiKeyBusy=!1,this.apiKeyError=null,this.apiKeySuccess=null,this.apiKeySavingProvider=null,this.authApiKeyMode=!1,this.authApiKeyInput="",this.authApiKeyBusy=!1,this.authApiKeyError=null,this.pinChanging=null,this.pinChangeBusy=!1,this.pinChangeError=null,this.loginChangePinMode=!1,this.changePinBusy=!1,this.changePinError=null,this.changePinSuccess=null,this.workspaceSaving=!1,this.workspaceRemoveConfirm=null,this.renamingWorkspace=!1,this.renameWorkspaceName="",this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...mw},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.logsSubTab="session",this.sessionLogsLoading=!1,this.sessionLogsError=null,this.sessionLogsEntries=[],this.sessionLogsFilterText="",this.sessionLogsTypeFilters={user:!0,assistant:!0,tool:!0,tool_call:!0,tool_result:!0,thinking:!0,error:!0,system:!0},this.sessionLogsAgentFilters={},this.sessionLogsAgents=[],this.sessionLogsAutoFollow=!0,this.sessionLogsExpandedIds=new Set,this.sessionLogsCursors={},this.sessionLogsLastFetchAt=null,this.sessionLogsAtBottom=!0,this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.chatUserNearBottom=!0,this.onLoadOlder=()=>this.handleLoadOlderChat(),this.nodesPollInterval=null,this.logsPollInterval=null,this.sessionLogsPollInterval=null,this.debugPollInterval=null,this.auditPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.basePath="",this.popStateHandler=()=>of(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),vw(this)}firstUpdated(){bw(this)}disconnectedCallback(){this.stopEmbeddingPoll(),ww(this),super.disconnectedCallback()}startEmbeddingPoll(){if(this.embeddingPollTimer!=null)return;const e=async()=>{if(!(!this.client||!this.connected)){try{const t=await this.client.request("memory.status",{});if((t==null?void 0:t.embeddingState)==="downloading")this.embeddingDownloading=!0;else{this.embeddingDownloading&&(this.embeddingDownloading=!1),this.stopEmbeddingPoll();return}}catch{this.embeddingDownloading=!1,this.stopEmbeddingPoll();return}this.embeddingPollTimer=window.setTimeout(e,3e3)}};e()}stopEmbeddingPoll(){this.embeddingPollTimer!=null&&(window.clearTimeout(this.embeddingPollTimer),this.embeddingPollTimer=null)}updated(e){kw(this,e)}connect(){_e(this)}handleChatScroll(e){Sp(this,e)}handleLogsScroll(e){xp(this,e)}handleSessionLogsScroll(e){Ap(this,e)}exportLogs(e,t){Cp(e,t)}exportSessionLogs(e,t){Tp(e,t)}resetToolStream(){go(this)}resetChatScroll(){Ep(this)}async loadAssistantIdentity(){await oo(this)}applySettings(e){Ze(this,e)}setTab(e){Jh(this,e)}setTheme(e,t){Xh(this,e,t)}async loadOverview(){await Ic(this)}async loadCron(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.cronForm={...this.cronForm,accountId:(e==null?void 0:e.whatsappAccountId)??void 0},await Io(this)}async handleAbortChat(){await Dc(this)}removeQueuedMessage(e){cf(this,e)}async handleSendChat(e,t){await uf(this,e,t)}async handleWhatsAppStart(e,t){await $w(this,e,t)}async handleWhatsAppWait(e){await xw(this,e)}async handleWhatsAppLogout(e){await Aw(this,e)}async handleAddWhatsAppAccount(e){await Ew(this,e)}async handleRemoveWhatsAppAccount(e){await Cw(this,e)}async handleAccessCheck(){await ll(this)}async handlePinSubmit(e,t){await Yb(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await Jb(this,e)}async handleLogout(){await Zb(this)}toggleChangePinMode(){this.loginChangePinMode=!this.loginChangePinMode,this.changePinError=null,this.changePinSuccess=null}async handleChangePin(e,t,n){if(this.client){this.changePinBusy=!0,this.changePinError=null,this.changePinSuccess=null;try{const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.changePinError=i.message??"Incorrect current PIN",this.changePinBusy=!1;return}e==="__master__"?await this.client.request("access.setMasterPin",{pin:n}):await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.changePinSuccess="PIN changed successfully",this.changePinBusy=!1,setTimeout(()=>{this.loginChangePinMode=!1,this.changePinSuccess=null},2e3)}catch{this.changePinError="Failed to change PIN",this.changePinBusy=!1}}}async handleAccountPinSave(e,t,n){if(this.client){this.accountPinBusy=!0,this.accountPinError=null,this.accountPinSuccess=null;try{if(t!==null){const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.accountPinError=i.message??"Incorrect current PIN",this.accountPinBusy=!1;return}}await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.accountPinSuccess="PIN saved",this.accountPinBusy=!1,await ll(this),setTimeout(()=>{this.accountPinModalOpen=!1,this.accountPinSuccess=null,this.accountPinError=null},1500)}catch{this.accountPinError="Failed to save PIN",this.accountPinBusy=!1}}}async handleLicenseStatusCheck(){await Kw(this)}async handleLicenseActivate(){await zw(this)}async handleLicenseRemove(){await Hw(this)}handleLicenseKeyChange(e){qw(this,e)}async handleAuthStatusCheck(){await Nw(this)}async handleAuthStart(){await Ow(this)}async handleAuthSubmitCode(e){await Fw(this,e)}handleAuthCodeChange(e){Uw(this,e)}handleSkipToWhatsApp(){Ww(this)}async handleGatewayHealthCheck(){await jw(this)}async handleGatewayRestart(){await Vw(this)}async handleUpdateCheck(){await Uu(this)}async handleUpdateRun(){await Ib(this)}handleUpdateDismissResult(){Bb(this)}handleUninstallConfirm(){this.uninstallConfirm=!0,this.uninstallConfirmText=""}handleUninstallCancel(){this.uninstallConfirm=!1,this.uninstallConfirmText="",this.uninstallError=null}handleUninstallConfirmTextChange(e){this.uninstallConfirmText=e}async handleUninstallRun(){const{runUninstall:e}=await ie(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>jr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){ie(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>jr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await Cc(this)}async clearAudit(){await Ph(this),this.auditModalOpen=!1}handleFilesLoad(){var n;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((n=e==null?void 0:e.agents)==null?void 0:n.map(i=>i.id))??void 0;const t=this.resolveFilesAgentId();this.filesResolvedAgentId=t,Ht(this,t),Eo(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();ie(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>tw);return{loadAdmins:t}},void 0,import.meta.url).then(({loadAdmins:t})=>{t(this,e)})}resolveAdminAgentId(){const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(n=>n.id.endsWith("-admin")||n.id==="admin");return t==null?void 0:t.id}resolveFilesAgentId(){var n;const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return(t==null?void 0:t.id)??((n=e.agents[0])==null?void 0:n.id)}handleChatLoad(){const e=this.resolveAdminAgentId();if(e){const t=`agent:${e}:main`;t!==this.sessionKey&&(this.sessionKey=t,this.chatMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestion=null,this.resetChatScroll(),this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity())}ie(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>pi);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this).then(()=>{Wt(this,!0)})})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=$p(this),{loadOlderChatHistory:t}=await ie(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>pi);return{loadOlderChatHistory:i}},void 0,import.meta.url);await t(this)&&e&&(await this.updateComplete,e())}handleAdvancedLoad(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.sessionLogsEntries=[],this.sessionLogsCursors={},this.sessionLogsAgents=[],this.advancedTab==="cron"&&this.loadCron(),this.advancedTab==="logs"&&(this.logsSubTab==="session"?ie(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>Ec);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):ie(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>Hp);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&ie(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>xh);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await Tw(this)}async handleChannelConfigReload(){await _w(this)}handleNostrProfileEdit(e,t){Pw(this,e,t)}handleNostrProfileCancel(){Lw(this)}handleNostrProfileFieldChange(e,t){Iw(this,e,t)}async handleNostrProfileSave(){await Dw(this)}async handleNostrProfileImport(){await Bw(this)}handleNostrProfileToggleAdvanced(){Rw(this)}async handleExecApprovalDecision(e){const t=this.execApprovalQueue[0];if(!(!t||!this.client||this.execApprovalBusy)){this.execApprovalBusy=!0,this.execApprovalError=null;try{await this.client.request("exec.approval.resolve",{id:t.id,decision:e}),this.execApprovalQueue=this.execApprovalQueue.filter(n=>n.id!==t.id)}catch(n){this.execApprovalError=`Exec approval failed: ${String(n)}`}finally{this.execApprovalBusy=!1}}}handleOpenSidebar(e){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarCloseTimer=null)},200)}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}handleAdminsNewPhoneChange(e){this.adminsNewPhone=e,this.adminsError&&(this.adminsError=null)}handleContactsLoad(){const e=this.selectedWorkspace??void 0;ie(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>nw);return{loadContacts:t}},void 0,import.meta.url).then(({loadContacts:t})=>{t(this,e)})}handleContactsNewPhoneChange(e){this.contactsNewPhone=e,this.contactsError&&(this.contactsError=null)}handleContactsNewNameChange(e){this.contactsNewName=e,this.contactsError&&(this.contactsError=null)}async handleWorkspacesLoad(){const{loadWorkspaces:e}=await ie(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>ei);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await ie(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>ei);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await ie(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>Fp);return{loadChannels:s}},void 0,import.meta.url);await n(this,{name:e,workspacePath:t,onCreated:s=>{if(!s.whatsappAccountId)return;const o=s.whatsappAccountId;this.handleWorkspaceSelect(e),setTimeout(async()=>{try{await i(this,!0),await this.handleWhatsAppStart(!0,o),this.whatsappLoginQrDataUrl&&(await this.handleWhatsAppWait(o),await i(this,!0),await this.handleWorkspacesLoad())}catch{}this.requestUpdate()},3e3)}})}async handleWorkspaceRemove(e){const{removeWorkspace:t}=await ie(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>ei);return{removeWorkspace:n}},void 0,import.meta.url);await t(this,e)}handleWorkspaceRenameStart(){const e=this.getSelectedWorkspaceInfo();this.renameWorkspaceName=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"",this.renamingWorkspace=!0}handleWorkspaceRenameCancel(){this.renamingWorkspace=!1,this.renameWorkspaceName=""}async handleWorkspaceRename(e,t){const{renameWorkspace:n}=await ie(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>ei);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){this.selectedWorkspace=e,localStorage.setItem("taskmaster-selected-workspace",e),hn(e),Ir(e),this.settings=ns(),this.chatMessage="",this.chatAttachments=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestion=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.chatQueue=[],this.lastError=null,this.reloadCurrentPageData()}getSelectedWorkspaceInfo(){return this.selectedWorkspace?this.workspaces.find(e=>e.name===this.selectedWorkspace)??null:null}reloadCurrentPageData(){this.loadAuditEntries(),this.adminsPage?this.handleAdminsLoad():this.contactsPage?this.handleContactsLoad():this.filesPage?this.handleFilesLoad():this.chatPage?this.handleChatLoad():this.advancedPage&&this.handleAdvancedLoad()}initWorkspaceSelection(){if(this.workspaces.length===0){this.reloadCurrentPageData();return}const e=localStorage.getItem("taskmaster-selected-workspace"),t=e?this.workspaces.find(n=>n.name===e):null;if(t)this.selectedWorkspace=t.name;else{const n=this.workspaces.find(i=>i.isDefault)??this.workspaces[0];this.selectedWorkspace=n.name,localStorage.setItem("taskmaster-selected-workspace",n.name)}hn(this.selectedWorkspace),Ir(this.selectedWorkspace),this.settings=ns(),this.reloadCurrentPageData()}render(){return d`${hw(this)}${this.auditModalOpen?gw(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):S}`}};m([y()],g.prototype,"settings",2);m([y()],g.prototype,"password",2);m([y()],g.prototype,"tab",2);m([y()],g.prototype,"onboarding",2);m([y()],g.prototype,"setup",2);m([y()],g.prototype,"filesPage",2);m([y()],g.prototype,"browserPage",2);m([y()],g.prototype,"adminsPage",2);m([y()],g.prototype,"contactsPage",2);m([y()],g.prototype,"chatPage",2);m([y()],g.prototype,"advancedPage",2);m([y()],g.prototype,"advancedTab",2);m([y()],g.prototype,"publicChat",2);m([y()],g.prototype,"publicChatConfig",2);m([y()],g.prototype,"publicChatSessionKey",2);m([y()],g.prototype,"publicChatAuthenticated",2);m([y()],g.prototype,"publicChatAuthStep",2);m([y()],g.prototype,"connected",2);m([y()],g.prototype,"accessState",2);m([y()],g.prototype,"theme",2);m([y()],g.prototype,"themeResolved",2);m([y()],g.prototype,"hello",2);m([y()],g.prototype,"lastError",2);m([y()],g.prototype,"eventLog",2);m([y()],g.prototype,"assistantName",2);m([y()],g.prototype,"assistantAvatar",2);m([y()],g.prototype,"assistantAgentId",2);m([y()],g.prototype,"sessionKey",2);m([y()],g.prototype,"chatLoading",2);m([y()],g.prototype,"chatSending",2);m([y()],g.prototype,"chatMessage",2);m([y()],g.prototype,"chatMessages",2);m([y()],g.prototype,"chatHistoryTotal",2);m([y()],g.prototype,"chatHistoryHasMore",2);m([y()],g.prototype,"chatLoadingOlder",2);m([y()],g.prototype,"chatToolMessages",2);m([y()],g.prototype,"chatStream",2);m([y()],g.prototype,"chatInterimText",2);m([y()],g.prototype,"chatSuggestion",2);m([y()],g.prototype,"chatStreamStartedAt",2);m([y()],g.prototype,"chatRunId",2);m([y()],g.prototype,"compactionStatus",2);m([y()],g.prototype,"chatAvatarUrl",2);m([y()],g.prototype,"chatThinkingLevel",2);m([y()],g.prototype,"chatModelProvider",2);m([y()],g.prototype,"chatModel",2);m([y()],g.prototype,"chatModelCatalog",2);m([y()],g.prototype,"chatVerboseLevel",2);m([y()],g.prototype,"chatFillerEnabled",2);m([y()],g.prototype,"chatQueue",2);m([y()],g.prototype,"chatAttachments",2);m([y()],g.prototype,"sidebarOpen",2);m([y()],g.prototype,"sidebarContent",2);m([y()],g.prototype,"sidebarError",2);m([y()],g.prototype,"splitRatio",2);m([y()],g.prototype,"nodesLoading",2);m([y()],g.prototype,"nodes",2);m([y()],g.prototype,"devicesLoading",2);m([y()],g.prototype,"devicesError",2);m([y()],g.prototype,"devicesList",2);m([y()],g.prototype,"execApprovalsLoading",2);m([y()],g.prototype,"execApprovalsSaving",2);m([y()],g.prototype,"execApprovalsDirty",2);m([y()],g.prototype,"execApprovalsSnapshot",2);m([y()],g.prototype,"execApprovalsForm",2);m([y()],g.prototype,"execApprovalsSelectedAgent",2);m([y()],g.prototype,"execApprovalsTarget",2);m([y()],g.prototype,"execApprovalsTargetNodeId",2);m([y()],g.prototype,"execApprovalQueue",2);m([y()],g.prototype,"execApprovalBusy",2);m([y()],g.prototype,"execApprovalError",2);m([y()],g.prototype,"configLoading",2);m([y()],g.prototype,"configRaw",2);m([y()],g.prototype,"configRawOriginal",2);m([y()],g.prototype,"configValid",2);m([y()],g.prototype,"configIssues",2);m([y()],g.prototype,"configSaving",2);m([y()],g.prototype,"configApplying",2);m([y()],g.prototype,"updateRunning",2);m([y()],g.prototype,"applySessionKey",2);m([y()],g.prototype,"configSnapshot",2);m([y()],g.prototype,"configSchema",2);m([y()],g.prototype,"configSchemaVersion",2);m([y()],g.prototype,"configSchemaLoading",2);m([y()],g.prototype,"configUiHints",2);m([y()],g.prototype,"configForm",2);m([y()],g.prototype,"configFormOriginal",2);m([y()],g.prototype,"configFormDirty",2);m([y()],g.prototype,"configFormMode",2);m([y()],g.prototype,"configSearchQuery",2);m([y()],g.prototype,"configActiveSection",2);m([y()],g.prototype,"configActiveSubsection",2);m([y()],g.prototype,"channelsLoading",2);m([y()],g.prototype,"channelsSnapshot",2);m([y()],g.prototype,"channelsError",2);m([y()],g.prototype,"channelsLastSuccess",2);m([y()],g.prototype,"whatsappLoginMessage",2);m([y()],g.prototype,"whatsappLoginQrDataUrl",2);m([y()],g.prototype,"whatsappLoginConnected",2);m([y()],g.prototype,"whatsappBusy",2);m([y()],g.prototype,"whatsappActiveQrAccountId",2);m([y()],g.prototype,"whatsappPairedPhone",2);m([y()],g.prototype,"addingWhatsAppAccount",2);m([y()],g.prototype,"newWhatsAppAccountName",2);m([y()],g.prototype,"whatsappAccountError",2);m([y()],g.prototype,"whatsappAccountSaving",2);m([y()],g.prototype,"whatsappSettingsOpen",2);m([y()],g.prototype,"publicChatToggleBusy",2);m([y()],g.prototype,"brandingBusy",2);m([y()],g.prototype,"brandingExpanded",2);m([y()],g.prototype,"tailscaleStatus",2);m([y()],g.prototype,"tailscaleBusy",2);m([y()],g.prototype,"tailscaleAuthUrl",2);m([y()],g.prototype,"tailscaleError",2);m([y()],g.prototype,"tailscaleFunnelEnableUrl",2);m([y()],g.prototype,"wifiStatus",2);m([y()],g.prototype,"wifiNetworks",2);m([y()],g.prototype,"wifiBusy",2);m([y()],g.prototype,"wifiError",2);m([y()],g.prototype,"wifiPassword",2);m([y()],g.prototype,"wifiSelectedSsid",2);m([y()],g.prototype,"licenseKey",2);m([y()],g.prototype,"licenseBusy",2);m([y()],g.prototype,"licenseValid",2);m([y()],g.prototype,"licenseMessage",2);m([y()],g.prototype,"licenseTier",2);m([y()],g.prototype,"licenseDeviceId",2);m([y()],g.prototype,"licenseStoredKey",2);m([y()],g.prototype,"licenseRemoveConfirm",2);m([y()],g.prototype,"authConnected",2);m([y()],g.prototype,"authBusy",2);m([y()],g.prototype,"authMessage",2);m([y()],g.prototype,"authUrl",2);m([y()],g.prototype,"authCodeInput",2);m([y()],g.prototype,"authExpiresIn",2);m([y()],g.prototype,"setupStep",2);m([y()],g.prototype,"gatewayHealthy",2);m([y()],g.prototype,"gatewayHealthLoading",2);m([y()],g.prototype,"gatewayHealthMessage",2);m([y()],g.prototype,"gatewayRestartBusy",2);m([y()],g.prototype,"updateAvailable",2);m([y()],g.prototype,"currentVersion",2);m([y()],g.prototype,"latestVersion",2);m([y()],g.prototype,"updateChecking",2);m([y()],g.prototype,"updateMessage",2);m([y()],g.prototype,"updateProgressSteps",2);m([y()],g.prototype,"updateLastResult",2);m([y()],g.prototype,"uninstallConfirm",2);m([y()],g.prototype,"uninstallBusy",2);m([y()],g.prototype,"uninstallDone",2);m([y()],g.prototype,"uninstallError",2);m([y()],g.prototype,"uninstallConfirmText",2);m([y()],g.prototype,"nostrProfileFormState",2);m([y()],g.prototype,"nostrProfileAccountId",2);m([y()],g.prototype,"presenceLoading",2);m([y()],g.prototype,"presenceEntries",2);m([y()],g.prototype,"presenceError",2);m([y()],g.prototype,"presenceStatus",2);m([y()],g.prototype,"agentsLoading",2);m([y()],g.prototype,"agentsList",2);m([y()],g.prototype,"agentsError",2);m([y()],g.prototype,"sessionsLoading",2);m([y()],g.prototype,"sessionsResult",2);m([y()],g.prototype,"sessionsError",2);m([y()],g.prototype,"cronLoading",2);m([y()],g.prototype,"cronJobs",2);m([y()],g.prototype,"cronStatus",2);m([y()],g.prototype,"cronError",2);m([y()],g.prototype,"cronForm",2);m([y()],g.prototype,"cronRunsJobId",2);m([y()],g.prototype,"cronRuns",2);m([y()],g.prototype,"cronBusy",2);m([y()],g.prototype,"cronNewEventModal",2);m([y()],g.prototype,"cronDetailJobId",2);m([y()],g.prototype,"cronEditJobId",2);m([y()],g.prototype,"cronPendingDeleteId",2);m([y()],g.prototype,"browserScreencastActive",2);m([y()],g.prototype,"browserScreencastFrame",2);m([y()],g.prototype,"browserScreencastMetadata",2);m([y()],g.prototype,"browserHandoffPending",2);m([y()],g.prototype,"browserHandoffReason",2);m([y()],g.prototype,"browserHandoffId",2);m([y()],g.prototype,"browserInputMode",2);m([y()],g.prototype,"browserFullscreen",2);m([y()],g.prototype,"browserLoading",2);m([y()],g.prototype,"browserError",2);m([y()],g.prototype,"filesLoading",2);m([y()],g.prototype,"filesTree",2);m([y()],g.prototype,"filesRoot",2);m([y()],g.prototype,"filesError",2);m([y()],g.prototype,"filesSelectedPath",2);m([y()],g.prototype,"filesSelectedPaths",2);m([y()],g.prototype,"filesPreviewContent",2);m([y()],g.prototype,"filesPreviewLoading",2);m([y()],g.prototype,"filesPreviewBinary",2);m([y()],g.prototype,"filesPreviewSize",2);m([y()],g.prototype,"filesExpandedDirs",2);m([y()],g.prototype,"filesCurrentDir",2);m([y()],g.prototype,"filesPendingDeletePath",2);m([y()],g.prototype,"filesMessage",2);m([y()],g.prototype,"filesUploadBusy",2);m([y()],g.prototype,"filesReindexBusy",2);m([y()],g.prototype,"filesMemoryStatus",2);m([y()],g.prototype,"embeddingDownloading",2);m([y()],g.prototype,"filesSearchQuery",2);m([y()],g.prototype,"filesSearchResults",2);m([y()],g.prototype,"filesSearchLoading",2);m([y()],g.prototype,"filesSearchAgentId",2);m([y()],g.prototype,"auditEntries",2);m([y()],g.prototype,"auditLoading",2);m([y()],g.prototype,"auditModalOpen",2);m([y()],g.prototype,"skillsLoading",2);m([y()],g.prototype,"skillsReport",2);m([y()],g.prototype,"skillsError",2);m([y()],g.prototype,"skillsFilter",2);m([y()],g.prototype,"skillEdits",2);m([y()],g.prototype,"skillsBusyKey",2);m([y()],g.prototype,"skillMessages",2);m([y()],g.prototype,"skillDetail",2);m([y()],g.prototype,"skillDetailTab",2);m([y()],g.prototype,"skillAddModal",2);m([y()],g.prototype,"skillAddForm",2);m([y()],g.prototype,"skillDrafts",2);m([y()],g.prototype,"adminsLoading",2);m([y()],g.prototype,"adminPhones",2);m([y()],g.prototype,"adminsError",2);m([y()],g.prototype,"adminsSaving",2);m([y()],g.prototype,"adminsNewPhone",2);m([y()],g.prototype,"contactsLoading",2);m([y()],g.prototype,"contactsSaving",2);m([y()],g.prototype,"contactsRecords",2);m([y()],g.prototype,"contactsError",2);m([y()],g.prototype,"contactsSearchQuery",2);m([y()],g.prototype,"contactsEditingId",2);m([y()],g.prototype,"contactsShowAddForm",2);m([y()],g.prototype,"contactsNewPhone",2);m([y()],g.prototype,"contactsNewName",2);m([y()],g.prototype,"contactsDeleteConfirmId",2);m([y()],g.prototype,"contactsAddFieldForId",2);m([y()],g.prototype,"contactsAddFieldKey",2);m([y()],g.prototype,"contactsAddFieldValue",2);m([y()],g.prototype,"imessageEnableConfirm",2);m([y()],g.prototype,"imessageEnabling",2);m([y()],g.prototype,"infoModalOpen",2);m([y()],g.prototype,"workspaces",2);m([y()],g.prototype,"workspacesLoading",2);m([y()],g.prototype,"workspacesError",2);m([y()],g.prototype,"selectedWorkspace",2);m([y()],g.prototype,"addingWorkspace",2);m([y()],g.prototype,"newWorkspaceName",2);m([y()],g.prototype,"newWorkspacePath",2);m([y()],g.prototype,"newWorkspacePin",2);m([y()],g.prototype,"accountPinModalOpen",2);m([y()],g.prototype,"accountPinBusy",2);m([y()],g.prototype,"accountPinError",2);m([y()],g.prototype,"accountPinSuccess",2);m([y()],g.prototype,"apiKeyProviders",2);m([y()],g.prototype,"apiKeyModalOpen",2);m([y()],g.prototype,"apiKeyBusy",2);m([y()],g.prototype,"apiKeyError",2);m([y()],g.prototype,"apiKeySuccess",2);m([y()],g.prototype,"apiKeySavingProvider",2);m([y()],g.prototype,"authApiKeyMode",2);m([y()],g.prototype,"authApiKeyInput",2);m([y()],g.prototype,"authApiKeyBusy",2);m([y()],g.prototype,"authApiKeyError",2);m([y()],g.prototype,"pinChanging",2);m([y()],g.prototype,"pinChangeBusy",2);m([y()],g.prototype,"pinChangeError",2);m([y()],g.prototype,"loginChangePinMode",2);m([y()],g.prototype,"changePinBusy",2);m([y()],g.prototype,"changePinError",2);m([y()],g.prototype,"changePinSuccess",2);m([y()],g.prototype,"workspaceSaving",2);m([y()],g.prototype,"workspaceRemoveConfirm",2);m([y()],g.prototype,"renamingWorkspace",2);m([y()],g.prototype,"renameWorkspaceName",2);m([y()],g.prototype,"debugLoading",2);m([y()],g.prototype,"debugStatus",2);m([y()],g.prototype,"debugHealth",2);m([y()],g.prototype,"debugModels",2);m([y()],g.prototype,"debugHeartbeat",2);m([y()],g.prototype,"debugCallMethod",2);m([y()],g.prototype,"debugCallParams",2);m([y()],g.prototype,"debugCallResult",2);m([y()],g.prototype,"debugCallError",2);m([y()],g.prototype,"logsLoading",2);m([y()],g.prototype,"logsError",2);m([y()],g.prototype,"logsFile",2);m([y()],g.prototype,"logsEntries",2);m([y()],g.prototype,"logsFilterText",2);m([y()],g.prototype,"logsLevelFilters",2);m([y()],g.prototype,"logsAutoFollow",2);m([y()],g.prototype,"logsTruncated",2);m([y()],g.prototype,"logsCursor",2);m([y()],g.prototype,"logsLastFetchAt",2);m([y()],g.prototype,"logsLimit",2);m([y()],g.prototype,"logsMaxBytes",2);m([y()],g.prototype,"logsAtBottom",2);m([y()],g.prototype,"logsSubTab",2);m([y()],g.prototype,"sessionLogsLoading",2);m([y()],g.prototype,"sessionLogsError",2);m([y()],g.prototype,"sessionLogsEntries",2);m([y()],g.prototype,"sessionLogsFilterText",2);m([y()],g.prototype,"sessionLogsTypeFilters",2);m([y()],g.prototype,"sessionLogsAgentFilters",2);m([y()],g.prototype,"sessionLogsAgents",2);m([y()],g.prototype,"sessionLogsAutoFollow",2);m([y()],g.prototype,"sessionLogsCursors",2);m([y()],g.prototype,"sessionLogsLastFetchAt",2);m([y()],g.prototype,"sessionLogsAtBottom",2);m([y()],g.prototype,"chatUserNearBottom",2);g=m([bl("taskmaster-app")],g);
3853
- //# sourceMappingURL=index-DzlEdl36.js.map
3881
+ `,this.configRawOriginal="",this.configValid=null,this.configIssues=[],this.configSaving=!1,this.configApplying=!1,this.updateRunning=!1,this.applySessionKey=this.settings.lastActiveSessionKey,this.configSnapshot=null,this.configSchema=null,this.configSchemaVersion=null,this.configSchemaLoading=!1,this.configUiHints={},this.configForm=null,this.configFormOriginal=null,this.configFormDirty=!1,this.configFormMode="form",this.configSearchQuery="",this.configActiveSection=null,this.configActiveSubsection=null,this.channelsLoading=!1,this.channelsSnapshot=null,this.channelsError=null,this.channelsLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.whatsappActiveQrAccountId=null,this.whatsappPairedPhone=null,this.addingWhatsAppAccount=!1,this.newWhatsAppAccountName="",this.whatsappAccountError=null,this.whatsappAccountSaving=!1,this.whatsappSettingsOpen=!1,this.publicChatToggleBusy=!1,this.brandingBusy=!1,this.brandingExpanded=!1,this.tailscaleStatus=null,this.tailscaleBusy=!1,this.tailscaleAuthUrl=null,this.tailscaleError=null,this.tailscaleFunnelEnableUrl=null,this.wifiStatus=null,this.wifiNetworks=[],this.wifiBusy=!1,this.wifiError=null,this.wifiPassword="",this.wifiSelectedSsid=null,this.licenseKey="",this.licenseBusy=!1,this.licenseValid=null,this.licenseMessage=null,this.licenseTier=null,this.licenseDeviceId=null,this.licenseStoredKey=null,this.licenseRemoveConfirm=!1,this.authConnected=null,this.authBusy=!1,this.authMessage=null,this.authUrl=null,this.authCodeInput="",this.authExpiresIn=null,this.setupStep="license",this.gatewayHealthy=null,this.gatewayHealthLoading=!1,this.gatewayHealthMessage=null,this.gatewayRestartBusy=!1,this.updateAvailable=null,this.currentVersion=null,this.latestVersion=null,this.updateChecking=!1,this.updateMessage=null,this.updateProgressSteps=[],this.updateLastResult=null,this.uninstallConfirm=!1,this.uninstallBusy=!1,this.uninstallDone=!1,this.uninstallError=null,this.uninstallConfirmText="",this.nostrProfileFormState=null,this.nostrProfileAccountId=null,this.presenceLoading=!1,this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.sessionsLoading=!1,this.sessionsResult=null,this.sessionsError=null,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...Sw},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.cronNewEventModal=!1,this.cronDetailJobId=null,this.cronEditJobId=null,this.cronPendingDeleteId=null,this.browserScreencastActive=!1,this.browserScreencastFrame=null,this.browserScreencastMetadata=null,this.browserHandoffPending=!1,this.browserHandoffReason=null,this.browserHandoffId=null,this.browserInputMode=!1,this.browserFullscreen=!1,this.browserLoading=!1,this.browserError=null,this.filesLoading=!1,this.filesTree=[],this.filesRoot="",this.filesError=null,this.filesSelectedPath=null,this.filesSelectedPaths=new Set,this.filesPreviewContent=null,this.filesPreviewLoading=!1,this.filesPreviewBinary=!1,this.filesPreviewSize=null,this.filesExpandedDirs=new Set,this.filesCurrentDir=".",this.filesPendingDeletePath=null,this.filesMessage=null,this.filesUploadBusy=!1,this.filesReindexBusy=!1,this.filesMemoryStatus=null,this.embeddingDownloading=!1,this.embeddingPollTimer=null,this.filesSearchQuery="",this.filesSearchResults=null,this.filesSearchLoading=!1,this.filesSearchAgentId=null,this.filesResolvedAgentId=void 0,this.auditEntries=[],this.auditLoading=!1,this.auditModalOpen=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillDetail=null,this.skillDetailTab="",this.skillAddModal=!1,this.skillAddForm={name:"",skillContent:"",references:[]},this.skillDrafts=[],this.adminsLoading=!1,this.adminPhones=[],this.adminsError=null,this.adminsSaving=!1,this.adminsNewPhone="",this.contactsLoading=!1,this.contactsSaving=!1,this.contactsRecords=[],this.contactsError=null,this.contactsSearchQuery="",this.contactsEditingId=null,this.contactsShowAddForm=!1,this.contactsNewPhone="",this.contactsNewName="",this.contactsDeleteConfirmId=null,this.contactsAddFieldForId=null,this.contactsAddFieldKey="",this.contactsAddFieldValue="",this.imessageEnableConfirm=!1,this.imessageEnabling=!1,this.infoModalOpen=null,this.workspaces=[],this.workspacesLoading=!1,this.workspacesError=null,this.selectedWorkspace=null,this.addingWorkspace=!1,this.newWorkspaceName="",this.newWorkspacePath="",this.newWorkspacePin="",this.accountPinModalOpen=!1,this.accountPinBusy=!1,this.accountPinError=null,this.accountPinSuccess=null,this.apiKeyProviders=[],this.apiKeyModalOpen=!1,this.apiKeyBusy=!1,this.apiKeyError=null,this.apiKeySuccess=null,this.apiKeySavingProvider=null,this.authApiKeyMode=!1,this.authApiKeyInput="",this.authApiKeyBusy=!1,this.authApiKeyError=null,this.pinChanging=null,this.pinChangeBusy=!1,this.pinChangeError=null,this.loginChangePinMode=!1,this.changePinBusy=!1,this.changePinError=null,this.changePinSuccess=null,this.workspaceSaving=!1,this.workspaceRemoveConfirm=null,this.renamingWorkspace=!1,this.renameWorkspaceName="",this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...kw},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.logsSubTab="session",this.sessionLogsLoading=!1,this.sessionLogsError=null,this.sessionLogsEntries=[],this.sessionLogsFilterText="",this.sessionLogsTypeFilters={user:!0,assistant:!0,tool:!0,tool_call:!0,tool_result:!0,thinking:!0,error:!0,system:!0},this.sessionLogsAgentFilters={},this.sessionLogsAgents=[],this.sessionLogsAutoFollow=!0,this.sessionLogsExpandedIds=new Set,this.sessionLogsCursors={},this.sessionLogsLastFetchAt=null,this.sessionLogsAtBottom=!0,this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.chatUserNearBottom=!0,this.onLoadOlder=()=>this.handleLoadOlderChat(),this.nodesPollInterval=null,this.logsPollInterval=null,this.sessionLogsPollInterval=null,this.debugPollInterval=null,this.auditPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.basePath="",this.popStateHandler=()=>of(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),$w(this)}firstUpdated(){Aw(this)}disconnectedCallback(){this.stopEmbeddingPoll(),xw(this),super.disconnectedCallback()}startEmbeddingPoll(){if(this.embeddingPollTimer!=null)return;const e=async()=>{if(!(!this.client||!this.connected)){try{const t=await this.client.request("memory.status",{});if((t==null?void 0:t.embeddingState)==="downloading")this.embeddingDownloading=!0;else{this.embeddingDownloading&&(this.embeddingDownloading=!1),this.stopEmbeddingPoll();return}}catch{this.embeddingDownloading=!1,this.stopEmbeddingPoll();return}this.embeddingPollTimer=window.setTimeout(e,3e3)}};e()}stopEmbeddingPoll(){this.embeddingPollTimer!=null&&(window.clearTimeout(this.embeddingPollTimer),this.embeddingPollTimer=null)}updated(e){Ew(this,e)}connect(){_e(this)}handleChatScroll(e){Sp(this,e)}handleLogsScroll(e){Ap(this,e)}handleSessionLogsScroll(e){xp(this,e)}exportLogs(e,t){Cp(e,t)}exportSessionLogs(e,t){Tp(e,t)}resetToolStream(){go(this)}resetChatScroll(){Ep(this)}async loadAssistantIdentity(){await oo(this)}applySettings(e){Ze(this,e)}setTab(e){Jh(this,e)}setTheme(e,t){Xh(this,e,t)}async loadOverview(){await Ic(this)}async loadCron(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.cronForm={...this.cronForm,accountId:(e==null?void 0:e.whatsappAccountId)??void 0},await Io(this)}async handleAbortChat(){await Dc(this)}removeQueuedMessage(e){cf(this,e)}async handleSendChat(e,t){await uf(this,e,t)}async handleWhatsAppStart(e,t){await Tw(this,e,t)}async handleWhatsAppWait(e){await _w(this,e)}async handleWhatsAppLogout(e){await Mw(this,e)}async handleAddWhatsAppAccount(e){await Pw(this,e)}async handleRemoveWhatsAppAccount(e){await Lw(this,e)}async handleAccessCheck(){await ll(this)}async handlePinSubmit(e,t){await tw(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await nw(this,e)}async handleLogout(){await sw(this)}toggleChangePinMode(){this.loginChangePinMode=!this.loginChangePinMode,this.changePinError=null,this.changePinSuccess=null}async handleChangePin(e,t,n){if(this.client){this.changePinBusy=!0,this.changePinError=null,this.changePinSuccess=null;try{const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.changePinError=i.message??"Incorrect current PIN",this.changePinBusy=!1;return}e==="__master__"?await this.client.request("access.setMasterPin",{pin:n}):await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.changePinSuccess="PIN changed successfully",this.changePinBusy=!1,setTimeout(()=>{this.loginChangePinMode=!1,this.changePinSuccess=null},2e3)}catch{this.changePinError="Failed to change PIN",this.changePinBusy=!1}}}async handleAccountPinSave(e,t,n){if(this.client){this.accountPinBusy=!0,this.accountPinError=null,this.accountPinSuccess=null;try{if(t!==null){const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.accountPinError=i.message??"Incorrect current PIN",this.accountPinBusy=!1;return}}await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.accountPinSuccess="PIN saved",this.accountPinBusy=!1,await ll(this),setTimeout(()=>{this.accountPinModalOpen=!1,this.accountPinSuccess=null,this.accountPinError=null},1500)}catch{this.accountPinError="Failed to save PIN",this.accountPinBusy=!1}}}async handleLicenseStatusCheck(){await Vw(this)}async handleLicenseActivate(){await Gw(this)}async handleLicenseRemove(){await Qw(this)}handleLicenseKeyChange(e){Yw(this,e)}async handleAuthStatusCheck(){await Kw(this)}async handleAuthStart(){await zw(this)}async handleAuthSubmitCode(e){await Hw(this,e)}handleAuthCodeChange(e){qw(this,e)}handleSkipToWhatsApp(){jw(this)}async handleGatewayHealthCheck(){await Jw(this)}async handleGatewayRestart(){await Xw(this)}async handleUpdateCheck(){await Uu(this)}async handleUpdateRun(){await Ob(this)}handleUpdateDismissResult(){Wb(this)}handleUninstallConfirm(){this.uninstallConfirm=!0,this.uninstallConfirmText=""}handleUninstallCancel(){this.uninstallConfirm=!1,this.uninstallConfirmText="",this.uninstallError=null}handleUninstallConfirmTextChange(e){this.uninstallConfirmText=e}async handleUninstallRun(){const{runUninstall:e}=await ie(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>jr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){ie(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>jr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await Cc(this)}async clearAudit(){await Ph(this),this.auditModalOpen=!1}handleFilesLoad(){var n;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((n=e==null?void 0:e.agents)==null?void 0:n.map(i=>i.id))??void 0;const t=this.resolveFilesAgentId();this.filesResolvedAgentId=t,Ht(this,t),Eo(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();ie(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>rw);return{loadAdmins:t}},void 0,import.meta.url).then(({loadAdmins:t})=>{t(this,e)})}resolveAdminAgentId(){const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(n=>n.id.endsWith("-admin")||n.id==="admin");return t==null?void 0:t.id}resolveFilesAgentId(){var n;const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return(t==null?void 0:t.id)??((n=e.agents[0])==null?void 0:n.id)}handleChatLoad(){const e=this.resolveAdminAgentId();if(e){const t=`agent:${e}:main`;t!==this.sessionKey&&(this.sessionKey=t,this.chatMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestion=null,this.resetChatScroll(),this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity())}ie(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>pi);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this).then(()=>{Wt(this,!0)})})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=$p(this),{loadOlderChatHistory:t}=await ie(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>pi);return{loadOlderChatHistory:i}},void 0,import.meta.url);await t(this)&&e&&(await this.updateComplete,e())}handleAdvancedLoad(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.sessionLogsEntries=[],this.sessionLogsCursors={},this.sessionLogsAgents=[],this.advancedTab==="cron"&&this.loadCron(),this.advancedTab==="logs"&&(this.logsSubTab==="session"?ie(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>Ec);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):ie(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>Hp);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&ie(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>Ah);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await Iw(this)}async handleChannelConfigReload(){await Rw(this)}handleNostrProfileEdit(e,t){Bw(this,e,t)}handleNostrProfileCancel(){Nw(this)}handleNostrProfileFieldChange(e,t){Ow(this,e,t)}async handleNostrProfileSave(){await Uw(this)}async handleNostrProfileImport(){await Ww(this)}handleNostrProfileToggleAdvanced(){Fw(this)}async handleExecApprovalDecision(e){const t=this.execApprovalQueue[0];if(!(!t||!this.client||this.execApprovalBusy)){this.execApprovalBusy=!0,this.execApprovalError=null;try{await this.client.request("exec.approval.resolve",{id:t.id,decision:e}),this.execApprovalQueue=this.execApprovalQueue.filter(n=>n.id!==t.id)}catch(n){this.execApprovalError=`Exec approval failed: ${String(n)}`}finally{this.execApprovalBusy=!1}}}handleOpenSidebar(e){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarCloseTimer=null)},200)}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}handleAdminsNewPhoneChange(e){this.adminsNewPhone=e,this.adminsError&&(this.adminsError=null)}handleContactsLoad(){const e=this.selectedWorkspace??void 0;ie(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>aw);return{loadContacts:t}},void 0,import.meta.url).then(({loadContacts:t})=>{t(this,e)})}handleContactsNewPhoneChange(e){this.contactsNewPhone=e,this.contactsError&&(this.contactsError=null)}handleContactsNewNameChange(e){this.contactsNewName=e,this.contactsError&&(this.contactsError=null)}async handleWorkspacesLoad(){const{loadWorkspaces:e}=await ie(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>ei);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await ie(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>ei);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await ie(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>Fp);return{loadChannels:s}},void 0,import.meta.url);await n(this,{name:e,workspacePath:t,onCreated:s=>{if(!s.whatsappAccountId)return;const o=s.whatsappAccountId;this.handleWorkspaceSelect(e),setTimeout(async()=>{try{await i(this,!0),await this.handleWhatsAppStart(!0,o),this.whatsappLoginQrDataUrl&&(await this.handleWhatsAppWait(o),await i(this,!0),await this.handleWorkspacesLoad())}catch{}this.requestUpdate()},3e3)}})}async handleWorkspaceRemove(e){const{removeWorkspace:t}=await ie(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>ei);return{removeWorkspace:n}},void 0,import.meta.url);await t(this,e)}handleWorkspaceRenameStart(){const e=this.getSelectedWorkspaceInfo();this.renameWorkspaceName=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"",this.renamingWorkspace=!0}handleWorkspaceRenameCancel(){this.renamingWorkspace=!1,this.renameWorkspaceName=""}async handleWorkspaceRename(e,t){const{renameWorkspace:n}=await ie(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>ei);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){this.selectedWorkspace=e,localStorage.setItem("taskmaster-selected-workspace",e),hn(e),Ir(e),this.settings=ns(),this.chatMessage="",this.chatAttachments=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestion=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.chatQueue=[],this.lastError=null,this.reloadCurrentPageData()}getSelectedWorkspaceInfo(){return this.selectedWorkspace?this.workspaces.find(e=>e.name===this.selectedWorkspace)??null:null}reloadCurrentPageData(){this.loadAuditEntries(),this.adminsPage?this.handleAdminsLoad():this.contactsPage?this.handleContactsLoad():this.filesPage?this.handleFilesLoad():this.chatPage?this.handleChatLoad():this.advancedPage&&this.handleAdvancedLoad()}initWorkspaceSelection(){if(this.workspaces.length===0){this.reloadCurrentPageData();return}const e=localStorage.getItem("taskmaster-selected-workspace"),t=e?this.workspaces.find(n=>n.name===e):null;if(t)this.selectedWorkspace=t.name;else{const n=this.workspaces.find(i=>i.isDefault)??this.workspaces[0];this.selectedWorkspace=n.name,localStorage.setItem("taskmaster-selected-workspace",n.name)}hn(this.selectedWorkspace),Ir(this.selectedWorkspace),this.settings=ns(),this.reloadCurrentPageData()}render(){return d`${vw(this)}${this.auditModalOpen?ww(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):S}`}};m([y()],g.prototype,"settings",2);m([y()],g.prototype,"password",2);m([y()],g.prototype,"tab",2);m([y()],g.prototype,"onboarding",2);m([y()],g.prototype,"setup",2);m([y()],g.prototype,"filesPage",2);m([y()],g.prototype,"browserPage",2);m([y()],g.prototype,"adminsPage",2);m([y()],g.prototype,"contactsPage",2);m([y()],g.prototype,"chatPage",2);m([y()],g.prototype,"advancedPage",2);m([y()],g.prototype,"advancedTab",2);m([y()],g.prototype,"publicChat",2);m([y()],g.prototype,"publicChatConfig",2);m([y()],g.prototype,"publicChatSessionKey",2);m([y()],g.prototype,"publicChatAuthenticated",2);m([y()],g.prototype,"publicChatAuthStep",2);m([y()],g.prototype,"connected",2);m([y()],g.prototype,"accessState",2);m([y()],g.prototype,"theme",2);m([y()],g.prototype,"themeResolved",2);m([y()],g.prototype,"hello",2);m([y()],g.prototype,"lastError",2);m([y()],g.prototype,"eventLog",2);m([y()],g.prototype,"assistantName",2);m([y()],g.prototype,"assistantAvatar",2);m([y()],g.prototype,"assistantAgentId",2);m([y()],g.prototype,"sessionKey",2);m([y()],g.prototype,"chatLoading",2);m([y()],g.prototype,"chatSending",2);m([y()],g.prototype,"chatMessage",2);m([y()],g.prototype,"chatMessages",2);m([y()],g.prototype,"chatHistoryTotal",2);m([y()],g.prototype,"chatHistoryHasMore",2);m([y()],g.prototype,"chatLoadingOlder",2);m([y()],g.prototype,"chatToolMessages",2);m([y()],g.prototype,"chatStream",2);m([y()],g.prototype,"chatInterimText",2);m([y()],g.prototype,"chatSuggestion",2);m([y()],g.prototype,"chatStreamStartedAt",2);m([y()],g.prototype,"chatRunId",2);m([y()],g.prototype,"compactionStatus",2);m([y()],g.prototype,"chatAvatarUrl",2);m([y()],g.prototype,"chatThinkingLevel",2);m([y()],g.prototype,"chatModelProvider",2);m([y()],g.prototype,"chatModel",2);m([y()],g.prototype,"chatModelCatalog",2);m([y()],g.prototype,"chatVerboseLevel",2);m([y()],g.prototype,"chatFillerEnabled",2);m([y()],g.prototype,"chatQueue",2);m([y()],g.prototype,"chatAttachments",2);m([y()],g.prototype,"sidebarOpen",2);m([y()],g.prototype,"sidebarContent",2);m([y()],g.prototype,"sidebarError",2);m([y()],g.prototype,"splitRatio",2);m([y()],g.prototype,"nodesLoading",2);m([y()],g.prototype,"nodes",2);m([y()],g.prototype,"devicesLoading",2);m([y()],g.prototype,"devicesError",2);m([y()],g.prototype,"devicesList",2);m([y()],g.prototype,"execApprovalsLoading",2);m([y()],g.prototype,"execApprovalsSaving",2);m([y()],g.prototype,"execApprovalsDirty",2);m([y()],g.prototype,"execApprovalsSnapshot",2);m([y()],g.prototype,"execApprovalsForm",2);m([y()],g.prototype,"execApprovalsSelectedAgent",2);m([y()],g.prototype,"execApprovalsTarget",2);m([y()],g.prototype,"execApprovalsTargetNodeId",2);m([y()],g.prototype,"execApprovalQueue",2);m([y()],g.prototype,"execApprovalBusy",2);m([y()],g.prototype,"execApprovalError",2);m([y()],g.prototype,"configLoading",2);m([y()],g.prototype,"configRaw",2);m([y()],g.prototype,"configRawOriginal",2);m([y()],g.prototype,"configValid",2);m([y()],g.prototype,"configIssues",2);m([y()],g.prototype,"configSaving",2);m([y()],g.prototype,"configApplying",2);m([y()],g.prototype,"updateRunning",2);m([y()],g.prototype,"applySessionKey",2);m([y()],g.prototype,"configSnapshot",2);m([y()],g.prototype,"configSchema",2);m([y()],g.prototype,"configSchemaVersion",2);m([y()],g.prototype,"configSchemaLoading",2);m([y()],g.prototype,"configUiHints",2);m([y()],g.prototype,"configForm",2);m([y()],g.prototype,"configFormOriginal",2);m([y()],g.prototype,"configFormDirty",2);m([y()],g.prototype,"configFormMode",2);m([y()],g.prototype,"configSearchQuery",2);m([y()],g.prototype,"configActiveSection",2);m([y()],g.prototype,"configActiveSubsection",2);m([y()],g.prototype,"channelsLoading",2);m([y()],g.prototype,"channelsSnapshot",2);m([y()],g.prototype,"channelsError",2);m([y()],g.prototype,"channelsLastSuccess",2);m([y()],g.prototype,"whatsappLoginMessage",2);m([y()],g.prototype,"whatsappLoginQrDataUrl",2);m([y()],g.prototype,"whatsappLoginConnected",2);m([y()],g.prototype,"whatsappBusy",2);m([y()],g.prototype,"whatsappActiveQrAccountId",2);m([y()],g.prototype,"whatsappPairedPhone",2);m([y()],g.prototype,"addingWhatsAppAccount",2);m([y()],g.prototype,"newWhatsAppAccountName",2);m([y()],g.prototype,"whatsappAccountError",2);m([y()],g.prototype,"whatsappAccountSaving",2);m([y()],g.prototype,"whatsappSettingsOpen",2);m([y()],g.prototype,"publicChatToggleBusy",2);m([y()],g.prototype,"brandingBusy",2);m([y()],g.prototype,"brandingExpanded",2);m([y()],g.prototype,"tailscaleStatus",2);m([y()],g.prototype,"tailscaleBusy",2);m([y()],g.prototype,"tailscaleAuthUrl",2);m([y()],g.prototype,"tailscaleError",2);m([y()],g.prototype,"tailscaleFunnelEnableUrl",2);m([y()],g.prototype,"wifiStatus",2);m([y()],g.prototype,"wifiNetworks",2);m([y()],g.prototype,"wifiBusy",2);m([y()],g.prototype,"wifiError",2);m([y()],g.prototype,"wifiPassword",2);m([y()],g.prototype,"wifiSelectedSsid",2);m([y()],g.prototype,"licenseKey",2);m([y()],g.prototype,"licenseBusy",2);m([y()],g.prototype,"licenseValid",2);m([y()],g.prototype,"licenseMessage",2);m([y()],g.prototype,"licenseTier",2);m([y()],g.prototype,"licenseDeviceId",2);m([y()],g.prototype,"licenseStoredKey",2);m([y()],g.prototype,"licenseRemoveConfirm",2);m([y()],g.prototype,"authConnected",2);m([y()],g.prototype,"authBusy",2);m([y()],g.prototype,"authMessage",2);m([y()],g.prototype,"authUrl",2);m([y()],g.prototype,"authCodeInput",2);m([y()],g.prototype,"authExpiresIn",2);m([y()],g.prototype,"setupStep",2);m([y()],g.prototype,"gatewayHealthy",2);m([y()],g.prototype,"gatewayHealthLoading",2);m([y()],g.prototype,"gatewayHealthMessage",2);m([y()],g.prototype,"gatewayRestartBusy",2);m([y()],g.prototype,"updateAvailable",2);m([y()],g.prototype,"currentVersion",2);m([y()],g.prototype,"latestVersion",2);m([y()],g.prototype,"updateChecking",2);m([y()],g.prototype,"updateMessage",2);m([y()],g.prototype,"updateProgressSteps",2);m([y()],g.prototype,"updateLastResult",2);m([y()],g.prototype,"uninstallConfirm",2);m([y()],g.prototype,"uninstallBusy",2);m([y()],g.prototype,"uninstallDone",2);m([y()],g.prototype,"uninstallError",2);m([y()],g.prototype,"uninstallConfirmText",2);m([y()],g.prototype,"nostrProfileFormState",2);m([y()],g.prototype,"nostrProfileAccountId",2);m([y()],g.prototype,"presenceLoading",2);m([y()],g.prototype,"presenceEntries",2);m([y()],g.prototype,"presenceError",2);m([y()],g.prototype,"presenceStatus",2);m([y()],g.prototype,"agentsLoading",2);m([y()],g.prototype,"agentsList",2);m([y()],g.prototype,"agentsError",2);m([y()],g.prototype,"sessionsLoading",2);m([y()],g.prototype,"sessionsResult",2);m([y()],g.prototype,"sessionsError",2);m([y()],g.prototype,"cronLoading",2);m([y()],g.prototype,"cronJobs",2);m([y()],g.prototype,"cronStatus",2);m([y()],g.prototype,"cronError",2);m([y()],g.prototype,"cronForm",2);m([y()],g.prototype,"cronRunsJobId",2);m([y()],g.prototype,"cronRuns",2);m([y()],g.prototype,"cronBusy",2);m([y()],g.prototype,"cronNewEventModal",2);m([y()],g.prototype,"cronDetailJobId",2);m([y()],g.prototype,"cronEditJobId",2);m([y()],g.prototype,"cronPendingDeleteId",2);m([y()],g.prototype,"browserScreencastActive",2);m([y()],g.prototype,"browserScreencastFrame",2);m([y()],g.prototype,"browserScreencastMetadata",2);m([y()],g.prototype,"browserHandoffPending",2);m([y()],g.prototype,"browserHandoffReason",2);m([y()],g.prototype,"browserHandoffId",2);m([y()],g.prototype,"browserInputMode",2);m([y()],g.prototype,"browserFullscreen",2);m([y()],g.prototype,"browserLoading",2);m([y()],g.prototype,"browserError",2);m([y()],g.prototype,"filesLoading",2);m([y()],g.prototype,"filesTree",2);m([y()],g.prototype,"filesRoot",2);m([y()],g.prototype,"filesError",2);m([y()],g.prototype,"filesSelectedPath",2);m([y()],g.prototype,"filesSelectedPaths",2);m([y()],g.prototype,"filesPreviewContent",2);m([y()],g.prototype,"filesPreviewLoading",2);m([y()],g.prototype,"filesPreviewBinary",2);m([y()],g.prototype,"filesPreviewSize",2);m([y()],g.prototype,"filesExpandedDirs",2);m([y()],g.prototype,"filesCurrentDir",2);m([y()],g.prototype,"filesPendingDeletePath",2);m([y()],g.prototype,"filesMessage",2);m([y()],g.prototype,"filesUploadBusy",2);m([y()],g.prototype,"filesReindexBusy",2);m([y()],g.prototype,"filesMemoryStatus",2);m([y()],g.prototype,"embeddingDownloading",2);m([y()],g.prototype,"filesSearchQuery",2);m([y()],g.prototype,"filesSearchResults",2);m([y()],g.prototype,"filesSearchLoading",2);m([y()],g.prototype,"filesSearchAgentId",2);m([y()],g.prototype,"auditEntries",2);m([y()],g.prototype,"auditLoading",2);m([y()],g.prototype,"auditModalOpen",2);m([y()],g.prototype,"skillsLoading",2);m([y()],g.prototype,"skillsReport",2);m([y()],g.prototype,"skillsError",2);m([y()],g.prototype,"skillsFilter",2);m([y()],g.prototype,"skillEdits",2);m([y()],g.prototype,"skillsBusyKey",2);m([y()],g.prototype,"skillMessages",2);m([y()],g.prototype,"skillDetail",2);m([y()],g.prototype,"skillDetailTab",2);m([y()],g.prototype,"skillAddModal",2);m([y()],g.prototype,"skillAddForm",2);m([y()],g.prototype,"skillDrafts",2);m([y()],g.prototype,"adminsLoading",2);m([y()],g.prototype,"adminPhones",2);m([y()],g.prototype,"adminsError",2);m([y()],g.prototype,"adminsSaving",2);m([y()],g.prototype,"adminsNewPhone",2);m([y()],g.prototype,"contactsLoading",2);m([y()],g.prototype,"contactsSaving",2);m([y()],g.prototype,"contactsRecords",2);m([y()],g.prototype,"contactsError",2);m([y()],g.prototype,"contactsSearchQuery",2);m([y()],g.prototype,"contactsEditingId",2);m([y()],g.prototype,"contactsShowAddForm",2);m([y()],g.prototype,"contactsNewPhone",2);m([y()],g.prototype,"contactsNewName",2);m([y()],g.prototype,"contactsDeleteConfirmId",2);m([y()],g.prototype,"contactsAddFieldForId",2);m([y()],g.prototype,"contactsAddFieldKey",2);m([y()],g.prototype,"contactsAddFieldValue",2);m([y()],g.prototype,"imessageEnableConfirm",2);m([y()],g.prototype,"imessageEnabling",2);m([y()],g.prototype,"infoModalOpen",2);m([y()],g.prototype,"workspaces",2);m([y()],g.prototype,"workspacesLoading",2);m([y()],g.prototype,"workspacesError",2);m([y()],g.prototype,"selectedWorkspace",2);m([y()],g.prototype,"addingWorkspace",2);m([y()],g.prototype,"newWorkspaceName",2);m([y()],g.prototype,"newWorkspacePath",2);m([y()],g.prototype,"newWorkspacePin",2);m([y()],g.prototype,"accountPinModalOpen",2);m([y()],g.prototype,"accountPinBusy",2);m([y()],g.prototype,"accountPinError",2);m([y()],g.prototype,"accountPinSuccess",2);m([y()],g.prototype,"apiKeyProviders",2);m([y()],g.prototype,"apiKeyModalOpen",2);m([y()],g.prototype,"apiKeyBusy",2);m([y()],g.prototype,"apiKeyError",2);m([y()],g.prototype,"apiKeySuccess",2);m([y()],g.prototype,"apiKeySavingProvider",2);m([y()],g.prototype,"authApiKeyMode",2);m([y()],g.prototype,"authApiKeyInput",2);m([y()],g.prototype,"authApiKeyBusy",2);m([y()],g.prototype,"authApiKeyError",2);m([y()],g.prototype,"pinChanging",2);m([y()],g.prototype,"pinChangeBusy",2);m([y()],g.prototype,"pinChangeError",2);m([y()],g.prototype,"loginChangePinMode",2);m([y()],g.prototype,"changePinBusy",2);m([y()],g.prototype,"changePinError",2);m([y()],g.prototype,"changePinSuccess",2);m([y()],g.prototype,"workspaceSaving",2);m([y()],g.prototype,"workspaceRemoveConfirm",2);m([y()],g.prototype,"renamingWorkspace",2);m([y()],g.prototype,"renameWorkspaceName",2);m([y()],g.prototype,"debugLoading",2);m([y()],g.prototype,"debugStatus",2);m([y()],g.prototype,"debugHealth",2);m([y()],g.prototype,"debugModels",2);m([y()],g.prototype,"debugHeartbeat",2);m([y()],g.prototype,"debugCallMethod",2);m([y()],g.prototype,"debugCallParams",2);m([y()],g.prototype,"debugCallResult",2);m([y()],g.prototype,"debugCallError",2);m([y()],g.prototype,"logsLoading",2);m([y()],g.prototype,"logsError",2);m([y()],g.prototype,"logsFile",2);m([y()],g.prototype,"logsEntries",2);m([y()],g.prototype,"logsFilterText",2);m([y()],g.prototype,"logsLevelFilters",2);m([y()],g.prototype,"logsAutoFollow",2);m([y()],g.prototype,"logsTruncated",2);m([y()],g.prototype,"logsCursor",2);m([y()],g.prototype,"logsLastFetchAt",2);m([y()],g.prototype,"logsLimit",2);m([y()],g.prototype,"logsMaxBytes",2);m([y()],g.prototype,"logsAtBottom",2);m([y()],g.prototype,"logsSubTab",2);m([y()],g.prototype,"sessionLogsLoading",2);m([y()],g.prototype,"sessionLogsError",2);m([y()],g.prototype,"sessionLogsEntries",2);m([y()],g.prototype,"sessionLogsFilterText",2);m([y()],g.prototype,"sessionLogsTypeFilters",2);m([y()],g.prototype,"sessionLogsAgentFilters",2);m([y()],g.prototype,"sessionLogsAgents",2);m([y()],g.prototype,"sessionLogsAutoFollow",2);m([y()],g.prototype,"sessionLogsCursors",2);m([y()],g.prototype,"sessionLogsLastFetchAt",2);m([y()],g.prototype,"sessionLogsAtBottom",2);m([y()],g.prototype,"chatUserNearBottom",2);g=m([bl("taskmaster-app")],g);
3882
+ //# sourceMappingURL=index-DwMopZij.js.map