@rubytech/taskmaster 1.20.2 → 1.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,23 @@
1
- var Gu=Object.defineProperty;var Vu=(e,t,n)=>t in e?Gu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var q=(e,t,n)=>Vu(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 a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).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 Qu="modulepreload",Ju=function(e,t){return new URL(e,t).href},ar={},ae=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};const a=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),d=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));s=c(n.map(h=>{if(h=Ju(h,i),h in ar)return;ar[h]=!0;const u=h.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(i)for(let $=a.length-1;$>=0;$--){const S=a[$];if(S.href===h&&(!u||S.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${p}`))return;const v=document.createElement("link");if(v.rel=u?"stylesheet":Qu,u||(v.as="script"),v.crossOrigin="",v.href=h,d&&v.setAttribute("nonce",d),document.head.appendChild(v),u)return new Promise(($,S)=>{v.addEventListener("load",$),v.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${h}`)))})}))}function o(a){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=a,window.dispatchEvent(r),!r.defaultPrevented)throw a}return s.then(a=>{for(const r of a||[])r.status==="rejected"&&o(r.reason);return t().catch(o)})};const Si=globalThis,Go=Si.ShadowRoot&&(Si.ShadyCSS===void 0||Si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Vo=Symbol(),rr=new WeakMap;let Ol=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==Vo)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(Go&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=rr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&rr.set(n,t))}return t}toString(){return this.cssText}};const Yu=e=>new Ol(typeof e=="string"?e:e+"",void 0,Vo),Xu=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((i,s,o)=>i+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[o+1],e[0]);return new Ol(n,e,Vo)},Zu=(e,t)=>{if(Go)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=Si.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},lr=Go?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Yu(n)})(e):e;const{is:ep,defineProperty:tp,getOwnPropertyDescriptor:np,getOwnPropertyNames:ip,getOwnPropertySymbols:sp,getPrototypeOf:op}=Object,ot=globalThis,cr=ot.trustedTypes,ap=cr?cr.emptyScript:"",Ms=ot.reactiveElementPolyfillSupport,Cn=(e,t)=>e,Ri={toAttribute(e,t){switch(t){case Boolean:e=e?ap: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}},Qo=(e,t)=>!ep(e,t),dr={attribute:!0,type:String,converter:Ri,reflect:!1,useDefault:!1,hasChanged:Qo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ot.litPropertyMetadata??(ot.litPropertyMetadata=new WeakMap);let zt=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=dr){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&&tp(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=np(this.prototype,t)??{get(){return this[n]},set(a){this[n]=a}};return{get:s,set(a){const r=s==null?void 0:s.call(this);o==null||o.call(this,a),this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??dr}static _$Ei(){if(this.hasOwnProperty(Cn("elementProperties")))return;const t=op(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Cn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Cn("properties"))){const n=this.properties,i=[...ip(n),...sp(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(lr(s))}else t!==void 0&&n.push(lr(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 Zu(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 a=(((o=i.converter)==null?void 0:o.toAttribute)!==void 0?i.converter:Ri).toAttribute(n,i.type);this._$Em=t,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(t,n){var o,a;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const r=i.getPropertyOptions(s),d=typeof r.converter=="function"?{fromAttribute:r.converter}:((o=r.converter)==null?void 0:o.fromAttribute)!==void 0?r.converter:Ri;this._$Em=s;const c=d.fromAttribute(n,r.type);this[s]=c??((a=this._$Ej)==null?void 0:a.get(s))??c,this._$Em=null}}requestUpdate(t,n,i,s=!1,o){var a;if(t!==void 0){const r=this.constructor;if(s===!1&&(o=this[t]),i??(i=r.getPropertyOptions(t)),!((i.hasChanged??Qo)(o,n)||i.useDefault&&i.reflect&&o===((a=this._$Ej)==null?void 0:a.get(t))&&!this.hasAttribute(r._$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},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,a??n??this[t]),o!==!0||a!==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,a]of this._$Ep)this[o]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,a]of s){const{wrapped:r}=a,d=this[o];r!==!0||this._$AL.has(o)||d===void 0||this.C(o,void 0,a,d)}}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){}};zt.elementStyles=[],zt.shadowRootOptions={mode:"open"},zt[Cn("elementProperties")]=new Map,zt[Cn("finalized")]=new Map,Ms==null||Ms({ReactiveElement:zt}),(ot.reactiveElementVersions??(ot.reactiveElementVersions=[])).push("2.1.2");const En=globalThis,ur=e=>e,Li=En.trustedTypes,pr=Li?Li.createPolicy("lit-html",{createHTML:e=>e}):void 0,Fl="$lit$",st=`lit$${Math.random().toFixed(9).slice(2)}$`,Ul="?"+st,rp=`<${Ul}>`,St=document,Fn=()=>St.createComment(""),Un=e=>e===null||typeof e!="object"&&typeof e!="function",Jo=Array.isArray,lp=e=>Jo(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ps=`[
1
+ var Gu=Object.defineProperty;var Vu=(e,t,n)=>t in e?Gu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var q=(e,t,n)=>Vu(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 a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).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 Qu="modulepreload",Ju=function(e,t){return new URL(e,t).href},ar={},ae=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let d=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};const a=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),c=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));s=d(n.map(h=>{if(h=Ju(h,i),h in ar)return;ar[h]=!0;const u=h.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(i)for(let $=a.length-1;$>=0;$--){const S=a[$];if(S.href===h&&(!u||S.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${p}`))return;const v=document.createElement("link");if(v.rel=u?"stylesheet":Qu,u||(v.as="script"),v.crossOrigin="",v.href=h,c&&v.setAttribute("nonce",c),document.head.appendChild(v),u)return new Promise(($,S)=>{v.addEventListener("load",$),v.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${h}`)))})}))}function o(a){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=a,window.dispatchEvent(r),!r.defaultPrevented)throw a}return s.then(a=>{for(const r of a||[])r.status==="rejected"&&o(r.reason);return t().catch(o)})};const Si=globalThis,Go=Si.ShadowRoot&&(Si.ShadyCSS===void 0||Si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Vo=Symbol(),rr=new WeakMap;let Ol=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==Vo)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(Go&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=rr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&rr.set(n,t))}return t}toString(){return this.cssText}};const Yu=e=>new Ol(typeof e=="string"?e:e+"",void 0,Vo),Xu=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((i,s,o)=>i+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[o+1],e[0]);return new Ol(n,e,Vo)},Zu=(e,t)=>{if(Go)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=Si.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},lr=Go?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Yu(n)})(e):e;const{is:ep,defineProperty:tp,getOwnPropertyDescriptor:np,getOwnPropertyNames:ip,getOwnPropertySymbols:sp,getPrototypeOf:op}=Object,ot=globalThis,cr=ot.trustedTypes,ap=cr?cr.emptyScript:"",Ms=ot.reactiveElementPolyfillSupport,Cn=(e,t)=>e,Ri={toAttribute(e,t){switch(t){case Boolean:e=e?ap: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}},Qo=(e,t)=>!ep(e,t),dr={attribute:!0,type:String,converter:Ri,reflect:!1,useDefault:!1,hasChanged:Qo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ot.litPropertyMetadata??(ot.litPropertyMetadata=new WeakMap);let zt=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=dr){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&&tp(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=np(this.prototype,t)??{get(){return this[n]},set(a){this[n]=a}};return{get:s,set(a){const r=s==null?void 0:s.call(this);o==null||o.call(this,a),this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??dr}static _$Ei(){if(this.hasOwnProperty(Cn("elementProperties")))return;const t=op(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Cn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Cn("properties"))){const n=this.properties,i=[...ip(n),...sp(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(lr(s))}else t!==void 0&&n.push(lr(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 Zu(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 a=(((o=i.converter)==null?void 0:o.toAttribute)!==void 0?i.converter:Ri).toAttribute(n,i.type);this._$Em=t,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(t,n){var o,a;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const r=i.getPropertyOptions(s),c=typeof r.converter=="function"?{fromAttribute:r.converter}:((o=r.converter)==null?void 0:o.fromAttribute)!==void 0?r.converter:Ri;this._$Em=s;const d=c.fromAttribute(n,r.type);this[s]=d??((a=this._$Ej)==null?void 0:a.get(s))??d,this._$Em=null}}requestUpdate(t,n,i,s=!1,o){var a;if(t!==void 0){const r=this.constructor;if(s===!1&&(o=this[t]),i??(i=r.getPropertyOptions(t)),!((i.hasChanged??Qo)(o,n)||i.useDefault&&i.reflect&&o===((a=this._$Ej)==null?void 0:a.get(t))&&!this.hasAttribute(r._$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},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,a??n??this[t]),o!==!0||a!==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,a]of this._$Ep)this[o]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,a]of s){const{wrapped:r}=a,c=this[o];r!==!0||this._$AL.has(o)||c===void 0||this.C(o,void 0,a,c)}}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){}};zt.elementStyles=[],zt.shadowRootOptions={mode:"open"},zt[Cn("elementProperties")]=new Map,zt[Cn("finalized")]=new Map,Ms==null||Ms({ReactiveElement:zt}),(ot.reactiveElementVersions??(ot.reactiveElementVersions=[])).push("2.1.2");const En=globalThis,ur=e=>e,Li=En.trustedTypes,pr=Li?Li.createPolicy("lit-html",{createHTML:e=>e}):void 0,Fl="$lit$",st=`lit$${Math.random().toFixed(9).slice(2)}$`,Ul="?"+st,rp=`<${Ul}>`,St=document,Fn=()=>St.createComment(""),Un=e=>e===null||typeof e!="object"&&typeof e!="function",Jo=Array.isArray,lp=e=>Jo(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ps=`[
2
2
  \f\r]`,hn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,hr=/-->/g,fr=/>/g,pt=RegExp(`>|${Ps}(?:([^\\s"'>=/]+)(${Ps}*=${Ps}*(?:[^
3
- \f\r"'\`<>=]|("|')|))|$)`,"g"),gr=/'/g,mr=/"/g,Wl=/^(?:script|style|textarea|title)$/i,cp=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),l=cp(1),rt=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),yr=new WeakMap,yt=St.createTreeWalker(St,129);function Kl(e,t){if(!Jo(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return pr!==void 0?pr.createHTML(t):t}const dp=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",a=hn;for(let r=0;r<n;r++){const d=e[r];let c,h,u=-1,p=0;for(;p<d.length&&(a.lastIndex=p,h=a.exec(d),h!==null);)p=a.lastIndex,a===hn?h[1]==="!--"?a=hr:h[1]!==void 0?a=fr:h[2]!==void 0?(Wl.test(h[2])&&(s=RegExp("</"+h[2],"g")),a=pt):h[3]!==void 0&&(a=pt):a===pt?h[0]===">"?(a=s??hn,u=-1):h[1]===void 0?u=-2:(u=a.lastIndex-h[2].length,c=h[1],a=h[3]===void 0?pt:h[3]==='"'?mr:gr):a===mr||a===gr?a=pt:a===hr||a===fr?a=hn:(a=pt,s=void 0);const v=a===pt&&e[r+1].startsWith("/>")?" ":"";o+=a===hn?d+rp:u>=0?(i.push(c),d.slice(0,u)+Fl+d.slice(u)+st+v):d+st+(u===-2?r:v)}return[Kl(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let vo=class zl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,d=this.parts,[c,h]=dp(t,n);if(this.el=zl.createElement(c,i),yt.currentNode=this.el.content,n===2||n===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=yt.nextNode())!==null&&d.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Fl)){const p=h[a++],v=s.getAttribute(u).split(st),$=/([.?@])?(.*)/.exec(p);d.push({type:1,index:o,name:$[2],strings:v,ctor:$[1]==="."?pp:$[1]==="?"?hp:$[1]==="@"?fp:is}),s.removeAttribute(u)}else u.startsWith(st)&&(d.push({type:6,index:o}),s.removeAttribute(u));if(Wl.test(s.tagName)){const u=s.textContent.split(st),p=u.length-1;if(p>0){s.textContent=Li?Li.emptyScript:"";for(let v=0;v<p;v++)s.append(u[v],Fn()),yt.nextNode(),d.push({type:2,index:++o});s.append(u[p],Fn())}}}else if(s.nodeType===8)if(s.data===Ul)d.push({type:2,index:o});else{let u=-1;for(;(u=s.data.indexOf(st,u+1))!==-1;)d.push({type:7,index:o}),u+=st.length-1}o++}}static createElement(t,n){const i=St.createElement("template");return i.innerHTML=t,i}};function Qt(e,t,n=e,i){var a,r;if(t===rt)return t;let s=i!==void 0?(a=n._$Co)==null?void 0:a[i]:n._$Cl;const o=Un(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==o&&((r=s==null?void 0:s._$AO)==null||r.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=Qt(e,s._$AS(e,t.values),s,i)),t}class up{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)??St).importNode(n,!0);yt.currentNode=s;let o=yt.nextNode(),a=0,r=0,d=i[0];for(;d!==void 0;){if(a===d.index){let c;d.type===2?c=new ns(o,o.nextSibling,this,t):d.type===1?c=new d.ctor(o,d.name,d.strings,this,t):d.type===6&&(c=new gp(o,this,t)),this._$AV.push(c),d=i[++r]}a!==(d==null?void 0:d.index)&&(o=yt.nextNode(),a++)}return yt.currentNode=St,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 ns=class Hl{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=w,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=Qt(this,t,n),Un(t)?t===w||t==null||t===""?(this._$AH!==w&&this._$AR(),this._$AH=w):t!==this._$AH&&t!==rt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):lp(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!==w&&Un(this._$AH)?this._$AA.nextSibling.data=t:this.T(St.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=vo.createElement(Kl(i.h,i.h[0]),this.options)),i);if(((o=this._$AH)==null?void 0:o._$AD)===s)this._$AH.p(n);else{const a=new up(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=yr.get(t.strings);return n===void 0&&yr.set(t.strings,n=new vo(t)),n}k(t){Jo(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 Hl(this.O(Fn()),this.O(Fn()),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=ur(t).nextSibling;ur(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class is{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,s,o){this.type=1,this._$AH=w,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=w}_$AI(t,n=this,i,s){const o=this.strings;let a=!1;if(o===void 0)t=Qt(this,t,n,0),a=!Un(t)||t!==this._$AH&&t!==rt,a&&(this._$AH=t);else{const r=t;let d,c;for(t=o[0],d=0;d<o.length-1;d++)c=Qt(this,r[i+d],n,d),c===rt&&(c=this._$AH[d]),a||(a=!Un(c)||c!==this._$AH[d]),c===w?t=w:t!==w&&(t+=(c??"")+o[d+1]),this._$AH[d]=c}a&&!s&&this.j(t)}j(t){t===w?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let pp=class extends is{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},hp=class extends is{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},fp=class extends is{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=Qt(this,t,n,0)??w)===rt)return;const i=this._$AH,s=t===w&&i!==w||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==w&&(i===w||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)}},gp=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){Qt(this,t)}};const mp={I:ns},Is=En.litHtmlPolyfillSupport;Is==null||Is(vo,ns),(En.litHtmlVersions??(En.litHtmlVersions=[])).push("3.3.2");const yp=(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 ns(t.insertBefore(Fn(),o),o,void 0,n??{})}return s._$AI(e),s};const kt=globalThis;let jt=class extends zt{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=yp(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 rt}};var Nl;jt._$litElement$=!0,jt.finalized=!0,(Nl=kt.litElementHydrateSupport)==null||Nl.call(kt,{LitElement:jt});const Rs=kt.litElementPolyfillSupport;Rs==null||Rs({LitElement:jt});(kt.litElementVersions??(kt.litElementVersions=[])).push("4.2.2");const ql=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const vp={attribute:!0,type:String,converter:Ri,reflect:!1,hasChanged:Qo},bp=(e=vp,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:a}=n;return{set(r){const d=t.get.call(this);t.set.call(this,r),this.requestUpdate(a,d,e,!0,r)},init(r){return r!==void 0&&this.C(a,void 0,e,r),r}}}if(i==="setter"){const{name:a}=n;return function(r){const d=this[a];t.call(this,r),this.requestUpdate(a,d,e,!0,r)}}throw Error("Unsupported decorator location: "+i)};function ss(e){return(t,n)=>typeof n=="object"?bp(e,t,n):((i,s,o)=>{const a=s.hasOwnProperty(o);return s.constructor.createProperty(o,i),a?Object.getOwnPropertyDescriptor(s,o):void 0})(e,t,n)}function m(e){return ss({...e,state:!0,attribute:!1})}const wp=50,kp=200,xp="Assistant";function vr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function bo(e){const t=vr(e==null?void 0:e.name,wp)??xp,n=vr((e==null?void 0:e.avatar)??void 0,kp)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function $p(){return bo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const Sp="Taskmaster",Ap="/taskmaster-icon.png",Cp="#00d4ff",Ep="";let ai=null;function Xe(){return ai||(ai={name:window.__TASKMASTER_BRAND_NAME__||Sp,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||Ap,accentColor:window.__TASKMASTER_ACCENT_COLOR__||Cp,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||Ep},ai)}function Ne(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function jl(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 Tp(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 a=parseInt(o,16)/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)});return .2126*n+.7152*i+.0722*s}function Gl(e){const t=jl(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=Tp(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function ri(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,h)=>Math.round(parseInt(i[c],16)*(1-n)+parseInt(s[h],16)*n),a=o(1,1),r=o(2,2),d=o(3,3);return`#${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${d.toString(16).padStart(2,"0")}`}const fn={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function Vl(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries(fn))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=jl(e);n&&(t.style.setProperty("--bg",ri(fn["--bg"],e,.08)),t.style.setProperty("--bg-muted",ri(fn["--bg-muted"],e,.1)),t.style.setProperty("--card",ri(fn["--card"],e,.12)),t.style.setProperty("--secondary",ri(fn["--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 Tn(e){const t=Xe(),n=Ne(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;Gl(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;Vl(o)}const Di="taskmaster.control.settings.v1",Ql="taskmaster.account.settings.";function _n(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const Wt={gatewayUrl:_n(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},nt={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function _p(){try{const e=localStorage.getItem(Di);if(!e)return{...Wt,gatewayUrl:_n()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():_n(),token:typeof t.token=="string"?t.token:Wt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:Wt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:Wt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:Wt.navGroupsCollapsed}}catch{return{...Wt,gatewayUrl:_n()}}}function Mp(e){if(!e)return{...nt};try{const t=localStorage.getItem(Ql+e);if(!t)return{...nt};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():nt.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||nt.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:nt.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:nt.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:nt.splitRatio}}catch{return{...nt}}}let Bi=null;function br(e){Bi=e}function Ls(){return{..._p(),...Mp(Bi)}}function Pp(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(Di,JSON.stringify(t)),Bi){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem(Ql+Bi,JSON.stringify(n))}}const Ip="taskmaster.draft.";function Yo(e,t){return Ip+e+"."+t}function Wn(e,t,n){try{const i=Yo(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function Kn(e,t){try{return localStorage.getItem(Yo(e,t))??""}catch{return""}}function Rp(e,t){try{localStorage.removeItem(Yo(e,t))}catch{}}let vt=null,Se=null;function wr(e,t,n){Se={workspace:e,sessionKey:t,text:n},vt!=null&&clearTimeout(vt),vt=setTimeout(()=>{Se&&Wn(Se.workspace,Se.sessionKey,Se.text),Se=null,vt=null},300)}function wo(){vt!=null&&clearTimeout(vt),vt=null,Se&&(Wn(Se.workspace,Se.sessionKey,Se.text),Se=null)}(function(){try{const t=localStorage.getItem(Di);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:_n(),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(Di,JSON.stringify(i))}catch{}})();function Jl(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 Lp=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,li=/<\s*\/?\s*final\b[^>]*>/gi,kr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function Dp(e,t){return e.trimStart()}function Bp(e,t){if(!e||!Lp.test(e))return e;let n=e;li.test(n)?(li.lastIndex=0,n=n.replace(li,"")):li.lastIndex=0,kr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(kr)){const r=a.index??0,d=a[1]==="/";o?d&&(o=!1):(i+=n.slice(s,r),d||(o=!0)),s=r+a[0].length}return i+=n.slice(s),Dp(i)}function Yl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function os(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0){const a=-t,r=Math.round(a/1e3);if(r<60)return`in ${r}s`;const d=Math.round(r/60);if(d<60)return`in ${d}m`;const c=Math.round(d/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 Xo(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 Np(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Xl(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 Ni(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Ds(e){return Bp(e)}const Op=/^\[([^\]]+)\]\s*/,Fp=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Bs=new WeakMap,Ns=new WeakMap;function Up(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:Fp.some(t=>e.startsWith(`${t} `))}function Os(e){const t=e.match(Op);if(!t)return e;const n=t[1]??"";return Up(n)?e.slice(t[0].length):e}function Mn(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?Ds(i):Os(i);if(Array.isArray(i)){const s=i.map(o=>{const a=o;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(o=>typeof o=="string");if(s.length>0){const o=s.join(`
4
- `);return n==="assistant"?Ds(o):Os(o)}}return typeof t.text=="string"?n==="assistant"?Ds(t.text):Os(t.text):null}function Zl(e){if(!e||typeof e!="object")return Mn(e);const t=e;if(Bs.has(t))return Bs.get(t)??null;const n=Mn(e);return Bs.set(t,n),n}function xr(e){const n=e.content,i=[];if(Array.isArray(n))for(const r of n){const d=r;if(d.type==="thinking"&&typeof d.thinking=="string"){const c=d.thinking.trim();c&&i.push(c)}}if(i.length>0)return i.join(`
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),gr=/'/g,mr=/"/g,Wl=/^(?:script|style|textarea|title)$/i,cp=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),l=cp(1),rt=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),yr=new WeakMap,yt=St.createTreeWalker(St,129);function Kl(e,t){if(!Jo(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return pr!==void 0?pr.createHTML(t):t}const dp=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",a=hn;for(let r=0;r<n;r++){const c=e[r];let d,h,u=-1,p=0;for(;p<c.length&&(a.lastIndex=p,h=a.exec(c),h!==null);)p=a.lastIndex,a===hn?h[1]==="!--"?a=hr:h[1]!==void 0?a=fr:h[2]!==void 0?(Wl.test(h[2])&&(s=RegExp("</"+h[2],"g")),a=pt):h[3]!==void 0&&(a=pt):a===pt?h[0]===">"?(a=s??hn,u=-1):h[1]===void 0?u=-2:(u=a.lastIndex-h[2].length,d=h[1],a=h[3]===void 0?pt:h[3]==='"'?mr:gr):a===mr||a===gr?a=pt:a===hr||a===fr?a=hn:(a=pt,s=void 0);const v=a===pt&&e[r+1].startsWith("/>")?" ":"";o+=a===hn?c+rp:u>=0?(i.push(d),c.slice(0,u)+Fl+c.slice(u)+st+v):c+st+(u===-2?r:v)}return[Kl(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let vo=class zl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,c=this.parts,[d,h]=dp(t,n);if(this.el=zl.createElement(d,i),yt.currentNode=this.el.content,n===2||n===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=yt.nextNode())!==null&&c.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Fl)){const p=h[a++],v=s.getAttribute(u).split(st),$=/([.?@])?(.*)/.exec(p);c.push({type:1,index:o,name:$[2],strings:v,ctor:$[1]==="."?pp:$[1]==="?"?hp:$[1]==="@"?fp:is}),s.removeAttribute(u)}else u.startsWith(st)&&(c.push({type:6,index:o}),s.removeAttribute(u));if(Wl.test(s.tagName)){const u=s.textContent.split(st),p=u.length-1;if(p>0){s.textContent=Li?Li.emptyScript:"";for(let v=0;v<p;v++)s.append(u[v],Fn()),yt.nextNode(),c.push({type:2,index:++o});s.append(u[p],Fn())}}}else if(s.nodeType===8)if(s.data===Ul)c.push({type:2,index:o});else{let u=-1;for(;(u=s.data.indexOf(st,u+1))!==-1;)c.push({type:7,index:o}),u+=st.length-1}o++}}static createElement(t,n){const i=St.createElement("template");return i.innerHTML=t,i}};function Qt(e,t,n=e,i){var a,r;if(t===rt)return t;let s=i!==void 0?(a=n._$Co)==null?void 0:a[i]:n._$Cl;const o=Un(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==o&&((r=s==null?void 0:s._$AO)==null||r.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=Qt(e,s._$AS(e,t.values),s,i)),t}class up{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)??St).importNode(n,!0);yt.currentNode=s;let o=yt.nextNode(),a=0,r=0,c=i[0];for(;c!==void 0;){if(a===c.index){let d;c.type===2?d=new ns(o,o.nextSibling,this,t):c.type===1?d=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(d=new gp(o,this,t)),this._$AV.push(d),c=i[++r]}a!==(c==null?void 0:c.index)&&(o=yt.nextNode(),a++)}return yt.currentNode=St,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 ns=class Hl{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=w,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=Qt(this,t,n),Un(t)?t===w||t==null||t===""?(this._$AH!==w&&this._$AR(),this._$AH=w):t!==this._$AH&&t!==rt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):lp(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!==w&&Un(this._$AH)?this._$AA.nextSibling.data=t:this.T(St.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=vo.createElement(Kl(i.h,i.h[0]),this.options)),i);if(((o=this._$AH)==null?void 0:o._$AD)===s)this._$AH.p(n);else{const a=new up(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=yr.get(t.strings);return n===void 0&&yr.set(t.strings,n=new vo(t)),n}k(t){Jo(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 Hl(this.O(Fn()),this.O(Fn()),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=ur(t).nextSibling;ur(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class is{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,s,o){this.type=1,this._$AH=w,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=w}_$AI(t,n=this,i,s){const o=this.strings;let a=!1;if(o===void 0)t=Qt(this,t,n,0),a=!Un(t)||t!==this._$AH&&t!==rt,a&&(this._$AH=t);else{const r=t;let c,d;for(t=o[0],c=0;c<o.length-1;c++)d=Qt(this,r[i+c],n,c),d===rt&&(d=this._$AH[c]),a||(a=!Un(d)||d!==this._$AH[c]),d===w?t=w:t!==w&&(t+=(d??"")+o[c+1]),this._$AH[c]=d}a&&!s&&this.j(t)}j(t){t===w?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let pp=class extends is{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},hp=class extends is{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},fp=class extends is{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=Qt(this,t,n,0)??w)===rt)return;const i=this._$AH,s=t===w&&i!==w||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==w&&(i===w||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)}},gp=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){Qt(this,t)}};const mp={I:ns},Is=En.litHtmlPolyfillSupport;Is==null||Is(vo,ns),(En.litHtmlVersions??(En.litHtmlVersions=[])).push("3.3.2");const yp=(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 ns(t.insertBefore(Fn(),o),o,void 0,n??{})}return s._$AI(e),s};const kt=globalThis;let jt=class extends zt{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=yp(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 rt}};var Nl;jt._$litElement$=!0,jt.finalized=!0,(Nl=kt.litElementHydrateSupport)==null||Nl.call(kt,{LitElement:jt});const Rs=kt.litElementPolyfillSupport;Rs==null||Rs({LitElement:jt});(kt.litElementVersions??(kt.litElementVersions=[])).push("4.2.2");const ql=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const vp={attribute:!0,type:String,converter:Ri,reflect:!1,hasChanged:Qo},bp=(e=vp,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:a}=n;return{set(r){const c=t.get.call(this);t.set.call(this,r),this.requestUpdate(a,c,e,!0,r)},init(r){return r!==void 0&&this.C(a,void 0,e,r),r}}}if(i==="setter"){const{name:a}=n;return function(r){const c=this[a];t.call(this,r),this.requestUpdate(a,c,e,!0,r)}}throw Error("Unsupported decorator location: "+i)};function ss(e){return(t,n)=>typeof n=="object"?bp(e,t,n):((i,s,o)=>{const a=s.hasOwnProperty(o);return s.constructor.createProperty(o,i),a?Object.getOwnPropertyDescriptor(s,o):void 0})(e,t,n)}function m(e){return ss({...e,state:!0,attribute:!1})}const wp=50,kp=200,xp="Assistant";function vr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function bo(e){const t=vr(e==null?void 0:e.name,wp)??xp,n=vr((e==null?void 0:e.avatar)??void 0,kp)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function $p(){return bo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const Sp="Taskmaster",Ap="/taskmaster-icon.png",Cp="#00d4ff",Ep="";let ai=null;function Xe(){return ai||(ai={name:window.__TASKMASTER_BRAND_NAME__||Sp,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||Ap,accentColor:window.__TASKMASTER_ACCENT_COLOR__||Cp,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||Ep},ai)}function Ne(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function jl(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 Tp(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 a=parseInt(o,16)/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)});return .2126*n+.7152*i+.0722*s}function Gl(e){const t=jl(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=Tp(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function ri(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=(d,h)=>Math.round(parseInt(i[d],16)*(1-n)+parseInt(s[h],16)*n),a=o(1,1),r=o(2,2),c=o(3,3);return`#${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${c.toString(16).padStart(2,"0")}`}const fn={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function Vl(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries(fn))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=jl(e);n&&(t.style.setProperty("--bg",ri(fn["--bg"],e,.08)),t.style.setProperty("--bg-muted",ri(fn["--bg-muted"],e,.1)),t.style.setProperty("--card",ri(fn["--card"],e,.12)),t.style.setProperty("--secondary",ri(fn["--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 Tn(e){const t=Xe(),n=Ne(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;Gl(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;Vl(o)}const Di="taskmaster.control.settings.v1",Ql="taskmaster.account.settings.";function _n(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const Wt={gatewayUrl:_n(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},nt={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function _p(){try{const e=localStorage.getItem(Di);if(!e)return{...Wt,gatewayUrl:_n()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():_n(),token:typeof t.token=="string"?t.token:Wt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:Wt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:Wt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:Wt.navGroupsCollapsed}}catch{return{...Wt,gatewayUrl:_n()}}}function Mp(e){if(!e)return{...nt};try{const t=localStorage.getItem(Ql+e);if(!t)return{...nt};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():nt.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||nt.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:nt.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:nt.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:nt.splitRatio}}catch{return{...nt}}}let Bi=null;function br(e){Bi=e}function Ls(){return{..._p(),...Mp(Bi)}}function Pp(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(Di,JSON.stringify(t)),Bi){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem(Ql+Bi,JSON.stringify(n))}}const Ip="taskmaster.draft.";function Yo(e,t){return Ip+e+"."+t}function Wn(e,t,n){try{const i=Yo(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function Kn(e,t){try{return localStorage.getItem(Yo(e,t))??""}catch{return""}}function Rp(e,t){try{localStorage.removeItem(Yo(e,t))}catch{}}let vt=null,Se=null;function wr(e,t,n){Se={workspace:e,sessionKey:t,text:n},vt!=null&&clearTimeout(vt),vt=setTimeout(()=>{Se&&Wn(Se.workspace,Se.sessionKey,Se.text),Se=null,vt=null},300)}function wo(){vt!=null&&clearTimeout(vt),vt=null,Se&&(Wn(Se.workspace,Se.sessionKey,Se.text),Se=null)}(function(){try{const t=localStorage.getItem(Di);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:_n(),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(Di,JSON.stringify(i))}catch{}})();function Jl(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 Lp=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,li=/<\s*\/?\s*final\b[^>]*>/gi,kr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function Dp(e,t){return e.trimStart()}function Bp(e,t){if(!e||!Lp.test(e))return e;let n=e;li.test(n)?(li.lastIndex=0,n=n.replace(li,"")):li.lastIndex=0,kr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(kr)){const r=a.index??0,c=a[1]==="/";o?c&&(o=!1):(i+=n.slice(s,r),c||(o=!0)),s=r+a[0].length}return i+=n.slice(s),Dp(i)}function Yl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function os(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0){const a=-t,r=Math.round(a/1e3);if(r<60)return`in ${r}s`;const c=Math.round(r/60);if(c<60)return`in ${c}m`;const d=Math.round(c/60);return d<48?`in ${d}h`:`in ${Math.round(d/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 Xo(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 Np(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Xl(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 Ni(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Ds(e){return Bp(e)}const Op=/^\[([^\]]+)\]\s*/,Fp=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Bs=new WeakMap,Ns=new WeakMap;function Up(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:Fp.some(t=>e.startsWith(`${t} `))}function Os(e){const t=e.match(Op);if(!t)return e;const n=t[1]??"";return Up(n)?e.slice(t[0].length):e}function Mn(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?Ds(i):Os(i);if(Array.isArray(i)){const s=i.map(o=>{const a=o;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(o=>typeof o=="string");if(s.length>0){const o=s.join(`
4
+ `);return n==="assistant"?Ds(o):Os(o)}}return typeof t.text=="string"?n==="assistant"?Ds(t.text):Os(t.text):null}function Zl(e){if(!e||typeof e!="object")return Mn(e);const t=e;if(Bs.has(t))return Bs.get(t)??null;const n=Mn(e);return Bs.set(t,n),n}function xr(e){const n=e.content,i=[];if(Array.isArray(n))for(const r of n){const c=r;if(c.type==="thinking"&&typeof c.thinking=="string"){const d=c.thinking.trim();d&&i.push(d)}}if(i.length>0)return i.join(`
5
5
  `);const s=Kp(e);if(!s)return null;const a=[...s.matchAll(/<\s*think(?:ing)?\s*>([\s\S]*?)<\s*\/\s*think(?:ing)?\s*>/gi)].map(r=>(r[1]??"").trim()).filter(Boolean);return a.length>0?a.join(`
6
6
  `):null}function Wp(e){if(!e||typeof e!="object")return xr(e);const t=e;if(Ns.has(t))return Ns.get(t)??null;const n=xr(e);return Ns.set(t,n),n}function Kp(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 zp(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
- `):""}const Hp=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,qp=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,jp=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Gp=/^A new session was started via \/new or \/reset\./;function Vp(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"&&Hp.test(s)||n==="assistant"&&qp.test(s)||n==="user"&&Gp.test(s)||n==="assistant"&&jp.test(s)):!1}function ec(e){return e.filter(t=>!Vp(t))}function tc(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,a=Array.isArray(o)&&o.some(u=>{const v=String(u.type??"").toLowerCase();return v==="toolresult"||v==="tool_result"}),r=typeof t.toolName=="string"||typeof t.tool_name=="string";(i||a||r)&&(n="toolResult");let d=[];typeof t.content=="string"?d=[{type:"text",text:t.content}]:Array.isArray(t.content)?d=t.content.map(u=>({type:u.type||"text",text:u.text,name:u.name,args:u.args||u.arguments})):typeof t.text=="string"&&(d=[{type:"text",text:t.text}]);const c=typeof t.timestamp=="number"?t.timestamp:Date.now(),h=typeof t.id=="string"?t.id:void 0;return{role:n,content:d,timestamp:c,id:h}}function nc(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 ic(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function $r(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 Qp(){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 as(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),$r(t)}return $r(Qp())}const nn=50;async function Jt(e,t){if(!e.client||!e.connected)return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??nn;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,a=ec(s);e.chatMessages=a,e.chatHistoryTotal=o,e.chatHistoryHasMore=o>s.length,e.chatVerboseLevel=typeof i.verboseLevel=="string"?i.verboseLevel:null}catch(i){e.lastError=String(i)}finally{e.chatLoading=!1}}async function Jp(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:nn,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=ec(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 Yp(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function sc(e,t,n){if(e.chatSuggestions=[],!e.client||!e.connected)return!1;const i=t.trim(),s=n&&n.length>0;if(!i&&!s)return!1;const o=Date.now(),a=(n??[]).filter(v=>!v.fileName),r=(n??[]).filter(v=>v.fileName),d=[],c=r.map(v=>v.fileName).filter(Boolean);if(c.length>0){const v=i?`${c.join(", ")}
8
+ `):""}const Hp=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,qp=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,jp=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Gp=/^A new session was started via \/new or \/reset\./;function Vp(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"&&Hp.test(s)||n==="assistant"&&qp.test(s)||n==="user"&&Gp.test(s)||n==="assistant"&&jp.test(s)):!1}function ec(e){return e.filter(t=>!Vp(t))}function tc(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,a=Array.isArray(o)&&o.some(u=>{const v=String(u.type??"").toLowerCase();return v==="toolresult"||v==="tool_result"}),r=typeof t.toolName=="string"||typeof t.tool_name=="string";(i||a||r)&&(n="toolResult");let c=[];typeof t.content=="string"?c=[{type:"text",text:t.content}]:Array.isArray(t.content)?c=t.content.map(u=>({type:u.type||"text",text:u.text,name:u.name,args:u.args||u.arguments})):typeof t.text=="string"&&(c=[{type:"text",text:t.text}]);const d=typeof t.timestamp=="number"?t.timestamp:Date.now(),h=typeof t.id=="string"?t.id:void 0;return{role:n,content:c,timestamp:d,id:h}}function nc(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 ic(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function $r(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 Qp(){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 as(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),$r(t)}return $r(Qp())}const nn=50;async function Jt(e,t){if(!e.client||!e.connected)return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??nn;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,a=ec(s);e.chatMessages=a,e.chatHistoryTotal=o,e.chatHistoryHasMore=o>s.length,e.chatVerboseLevel=typeof i.verboseLevel=="string"?i.verboseLevel:null}catch(i){e.lastError=String(i)}finally{e.chatLoading=!1}}async function Jp(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:nn,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=ec(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 Yp(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function sc(e,t,n){if(e.chatSuggestions=[],!e.client||!e.connected)return!1;const i=t.trim(),s=n&&n.length>0;if(!i&&!s)return!1;const o=Date.now(),a=(n??[]).filter(v=>!v.fileName),r=(n??[]).filter(v=>v.fileName),c=[],d=r.map(v=>v.fileName).filter(Boolean);if(d.length>0){const v=i?`${d.join(", ")}
9
9
 
10
- ${i}`:c.join(", ");d.push({type:"text",text:v})}else i&&d.push({type:"text",text:i});for(const v of a)d.push({type:"image",source:{type:"base64",media_type:v.mimeType,data:v.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:d,timestamp:o}],e.chatSending=!0,e.lastError=null;const h=as();e.chatRunId=h,e.chatStream="",e.chatStreamStartedAt=o;const u=[...a,...r],p=u.length>0?u.map(v=>{if(v.textContent)return{type:"document",mimeType:v.mimeType||"text/plain",fileName:v.fileName,content:btoa(unescape(encodeURIComponent(v.textContent)))};const $=Yp(v.dataUrl);return $?{type:v.fileName?"document":"image",mimeType:$.mimeType,fileName:v.fileName,content:$.content}:null}).filter(v=>v!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:h,attachments:p}),!0}catch(v){const $=String(v);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=$,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+$}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function oc(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 ac(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=Mn(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 a=o.trim(),r=e.chatInterimText.trim();a===r||r.endsWith(a)||(a.startsWith(r)?e.chatInterimText=o:e.chatInterimText=`${e.chatInterimText}
10
+ ${i}`:d.join(", ");c.push({type:"text",text:v})}else i&&c.push({type:"text",text:i});for(const v of a)c.push({type:"image",source:{type:"base64",media_type:v.mimeType,data:v.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:c,timestamp:o}],e.chatSending=!0,e.lastError=null;const h=as();e.chatRunId=h,e.chatStream="",e.chatStreamStartedAt=o;const u=[...a,...r],p=u.length>0?u.map(v=>{if(v.textContent)return{type:"document",mimeType:v.mimeType||"text/plain",fileName:v.fileName,content:btoa(unescape(encodeURIComponent(v.textContent)))};const $=Yp(v.dataUrl);return $?{type:v.fileName?"document":"image",mimeType:$.mimeType,fileName:v.fileName,content:$.content}:null}).filter(v=>v!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:h,attachments:p}),!0}catch(v){const $=String(v);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=$,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+$}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function oc(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 ac(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=Mn(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 a=o.trim(),r=e.chatInterimText.trim();a===r||r.endsWith(a)||(a.startsWith(r)?e.chatInterimText=o:e.chatInterimText=`${e.chatInterimText}
11
11
 
12
12
  ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(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.chatSuggestions=[];const s=Mn(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 Oi=Object.freeze(Object.defineProperty({__proto__:null,CHAT_PAGE_SIZE:nn,abortChatRun:oc,handleChatEvent:ac,loadChatHistory:Jt,loadOlderChatHistory:Jp,sendChatMessage:sc},Symbol.toStringTag,{value:"Module"}));async function rc(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=Ni(e.sessionsFilterActive??"",0),i=Ni(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}}}const Sr=50,Xp=80,Zp=12e4;function eh(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(`
13
13
  `)}function Ar(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=eh(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=Xl(n,Zp);return i.truncated?`${i.text}
14
14
 
15
- … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function th(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 nh(e){if(e.toolStreamOrder.length<=Sr)return;const t=e.toolStreamOrder.length-Sr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function ih(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function ko(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),ih(e)}function sh(e,t=!1){if(t){ko(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>ko(e),Xp))}function Zo(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],ko(e)}const oh=5e3;function ah(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},oh))}function rh(e,t){if(!t)return;if(t.stream==="compaction"){ah(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",a=typeof i.phase=="string"?i.phase:"",r=a==="start"?i.args:void 0,d=a==="update"?Ar(i.partialResult):a==="result"?Ar(i.result):void 0,c=Date.now();let h=e.toolStreamById.get(s);h?(h.name=o,r!==void 0&&(h.args=r),d!==void 0&&(h.output=d),h.updatedAt=c):(h={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:r,output:d,startedAt:typeof t.ts=="number"?t.ts:c,updatedAt:c,message:{}},e.toolStreamById.set(s,h),e.toolStreamOrder.push(s)),h.message=th(h),nh(e),sh(e,a==="result")}let ci=0;function sn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++ci,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===ci&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==ci)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 r=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{if(e.chatScrollTimeout=null,n!==ci)return;const d=i();if(!d)return;const c=d.scrollHeight-d.scrollTop-d.clientHeight;(t||e.chatUserNearBottom||c<200)&&(d.scrollTop=d.scrollHeight,e.chatUserNearBottom=!0)},r)}))})}function lc(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 lh(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 ch(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 dh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function uh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function ph(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function hh(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
15
+ … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function th(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 nh(e){if(e.toolStreamOrder.length<=Sr)return;const t=e.toolStreamOrder.length-Sr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function ih(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function ko(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),ih(e)}function sh(e,t=!1){if(t){ko(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>ko(e),Xp))}function Zo(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],ko(e)}const oh=5e3;function ah(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},oh))}function rh(e,t){if(!t)return;if(t.stream==="compaction"){ah(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",a=typeof i.phase=="string"?i.phase:"",r=a==="start"?i.args:void 0,c=a==="update"?Ar(i.partialResult):a==="result"?Ar(i.result):void 0,d=Date.now();let h=e.toolStreamById.get(s);h?(h.name=o,r!==void 0&&(h.args=r),c!==void 0&&(h.output=c),h.updatedAt=d):(h={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:r,output:c,startedAt:typeof t.ts=="number"?t.ts:d,updatedAt:d,message:{}},e.toolStreamById.set(s,h),e.toolStreamOrder.push(s)),h.message=th(h),nh(e),sh(e,a==="result")}let ci=0;function sn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++ci,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===ci&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==ci)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 r=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{if(e.chatScrollTimeout=null,n!==ci)return;const c=i();if(!c)return;const d=c.scrollHeight-c.scrollTop-c.clientHeight;(t||e.chatUserNearBottom||d<200)&&(c.scrollTop=c.scrollHeight,e.chatUserNearBottom=!0)},r)}))})}function lc(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 lh(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 ch(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 dh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function uh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function ph(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function hh(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
16
16
  `)}
17
17
  `],{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 fh(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-session-logs-${t}-${o}.log`,s.click(),URL.revokeObjectURL(i)}function gh(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 lt(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function At(e){return`${JSON.stringify(e,null,2).trimEnd()}
20
- `}function cc(e,t,n){if(t.length===0)return;let i=e;for(let o=0;o<t.length-1;o+=1){const a=t[o],r=t[o+1];if(typeof a=="number"){if(!Array.isArray(i))return;i[a]==null&&(i[a]=typeof r=="number"?[]:{}),i=i[a]}else{if(typeof i!="object"||i==null)return;const d=i;d[a]==null&&(d[a]=typeof r=="number"?[]:{}),i=d[a]}}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 Fe(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});yh(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function dc(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});mh(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function mh(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function yh(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?At(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=At(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=lt(t.config??{}),e.configFormOriginal=lt(t.config??{}),e.configRawOriginal=n)}async function vh(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?At(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 Fe(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function on(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 jn(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),e.accountId&&(t.accountId=e.accountId);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 uc(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=Ni(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 pc(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 a=o.trim();a&&i.push(a)}i.length>0&&(n.to=i.join(","));const s=Ni(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function bh(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=uc(e.cronForm),i=pc(e.cronForm),s=e.cronForm.agentId.trim(),o=(t=e.cronForm.accountId)==null?void 0:t.trim(),a={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(!a.name)throw new Error("Name required.");await e.client.request("cron.add",a),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await jn(e),await on(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function wh(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 jn(e),await on(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function kh(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null,e.cronRunModalJobId=t.id,e.cronRunModalJobName=t.name||"Untitled",e.cronRunResult=null;try{await e.client.request("cron.run",{id:t.id,mode:"force"}),await xo(e,t.id)}catch(n){e.cronError=String(n),e.cronRunResult={status:"error",error:String(n)}}finally{e.cronBusy=!1}}}function xh(e,t){e.cronRunModalJobId&&t.jobId===e.cronRunModalJobId&&t.action==="finished"&&(e.cronRunResult={status:t.status??"unknown",durationMs:t.durationMs,summary:t.summary,outputText:t.outputText,error:t.error})}async function $h(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 jn(e),await on(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function Sh(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(a=>a.trim()).filter(Boolean);t.toAdmins=o.some(a=>a.toLowerCase()==="admins"),t.recipients=o.filter(a=>a.toLowerCase()!=="admins")}}return(n=e.isolation)!=null&&n.postToMainPrefix&&(t.postToMainPrefix=e.isolation.postToMainPrefix),t}async function Ah(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=uc(e.cronForm),i=pc(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 jn(e),await on(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function xo(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 ee(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 ea(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 hc(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 fc(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 gc(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=lt(s.config??{});(!o.channels||typeof o.channels!="object")&&(o.channels={});const a=o.channels;(!a.whatsapp||typeof a.whatsapp!="object")&&(a.whatsapp={});const r=a.whatsapp;(!r.accounts||typeof r.accounts!="object")&&(r.accounts={});const d=r.accounts;if(d[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}d[i]={name:n,provider:"baileys"};const c=s.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const h=At(o);await e.client.request("config.set",{raw:h,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await ee(e,!0),await ea(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function mc(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=lt(n.config??{}),s=i.channels,o=s==null?void 0:s.whatsapp,a=o==null?void 0:o.accounts;if(!a){e.whatsappAccountError="No accounts found in config.";return}if(Object.keys(a).length<=1){e.whatsappAccountError="Cannot remove the last account.";return}if(!a[t]){e.whatsappAccountError=`Account "${t}" not found.`;return}try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t})}catch{}delete a[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(h=>{const u=h.match;return!u||u.channel!=="whatsapp"?!0:u.accountId!==t}));const d=n.hash;if(!d){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=At(i);await e.client.request("config.set",{raw:c,baseHash:d}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await ee(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const Ch=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:gc,loadChannels:ee,logoutWhatsApp:fc,removeWhatsAppAccount:mc,startWhatsAppLogin:ea,waitWhatsAppLogin:hc},Symbol.toStringTag,{value:"Module"}));async function ta(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 na="taskmaster-access-session",yc={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function ia(){try{return localStorage.getItem(na)}catch{return null}}function vc(e){try{localStorage.setItem(na,e)}catch{}}function Eh(){try{localStorage.removeItem(na)}catch{}}async function Cr(e){if(e.client)try{const t=ia(),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 Th(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?(vc(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 _h(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?(vc(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 Mh(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 Ph(e){const t=ia();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}Eh(),e.accessState={...yc,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}const Ih=2e3,Rh=new Set(["trace","debug","info","warn","error","fatal"]);function Lh(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 Dh(e){if(typeof e!="string")return null;const t=e.toLowerCase();return Rh.has(t)?t:null}function bc(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=Dh((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,a=Lh(o);let r=null;a&&(typeof a.subsystem=="string"?r=a.subsystem:typeof a.module=="string"&&(r=a.module)),!r&&o&&o.length<120&&(r=o);let d=null;return typeof t[1]=="string"?d=t[1]:!a&&typeof t[0]=="string"?d=t[0]:typeof t.message=="string"&&(d=t.message),{raw:e,time:i,level:s,subsystem:r,message:d??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function Gt(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,accessToken:ia()??void 0}),o=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(bc),a=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=a?o:[...e.logsEntries,...o].slice(-Ih),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 Bh=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:Gt,parseLogLine:bc},Symbol.toStringTag,{value:"Module"}));const wc={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:ue,n:Ai,Gx:Er,Gy:Tr,a:Fs,d:Us,h:Nh}=wc,Ct=32,sa=64,Oh=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},re=(e="")=>{const t=new Error(e);throw Oh(t,re),t},Fh=e=>typeof e=="bigint",Uh=e=>typeof e=="string",Wh=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",ct=(e,t,n="")=>{const i=Wh(e),s=e==null?void 0:e.length,o=t!==void 0;if(!i||o&&s!==t){const a=n&&`"${n}" `,r=o?` of length ${t}`:"",d=i?`length=${s}`:`type=${typeof e}`;re(a+"expected Uint8Array"+r+", got "+d)}return e},rs=e=>new Uint8Array(e),kc=e=>Uint8Array.from(e),xc=(e,t)=>e.toString(16).padStart(t,"0"),$c=e=>Array.from(ct(e)).map(t=>xc(t,2)).join(""),Ge={_0:48,_9:57,A:65,F:70,a:97,f:102},_r=e=>{if(e>=Ge._0&&e<=Ge._9)return e-Ge._0;if(e>=Ge.A&&e<=Ge.F)return e-(Ge.A-10);if(e>=Ge.a&&e<=Ge.f)return e-(Ge.a-10)},Sc=e=>{const t="hex invalid";if(!Uh(e))return re(t);const n=e.length,i=n/2;if(n%2)return re(t);const s=rs(i);for(let o=0,a=0;o<i;o++,a+=2){const r=_r(e.charCodeAt(a)),d=_r(e.charCodeAt(a+1));if(r===void 0||d===void 0)return re(t);s[o]=r*16+d}return s},Ac=()=>globalThis==null?void 0:globalThis.crypto,Kh=()=>{var e;return((e=Ac())==null?void 0:e.subtle)??re("crypto.subtle must be defined, consider polyfill")},zn=(...e)=>{const t=rs(e.reduce((i,s)=>i+ct(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},zh=(e=Ct)=>Ac().getRandomValues(rs(e)),Fi=BigInt,gt=(e,t,n,i="bad number: out of range")=>Fh(e)&&t<=e&&e<n?e:re(i),L=(e,t=ue)=>{const n=e%t;return n>=0n?n:t+n},Cc=e=>L(e,Ai),Hh=(e,t)=>{(e===0n||t<=0n)&&re("no inverse n="+e+" mod="+t);let n=L(e,t),i=t,s=0n,o=1n;for(;n!==0n;){const a=i/n,r=i%n,d=s-o*a;i=n,n=r,s=o,o=d}return i===1n?L(s,t):re("no inverse")},qh=e=>{const t=Mc[e];return typeof t!="function"&&re("hashes."+e+" not set"),t},Ws=e=>e instanceof Et?e:re("Point expected"),$o=2n**256n,Oe=class Oe{constructor(t,n,i,s){q(this,"X");q(this,"Y");q(this,"Z");q(this,"T");const o=$o;this.X=gt(t,0n,o),this.Y=gt(n,0n,o),this.Z=gt(i,1n,o),this.T=gt(s,0n,o),Object.freeze(this)}static CURVE(){return wc}static fromAffine(t){return new Oe(t.x,t.y,1n,L(t.x*t.y))}static fromBytes(t,n=!1){const i=Us,s=kc(ct(t,Ct)),o=t[31];s[31]=o&-129;const a=Tc(s);gt(a,0n,n?$o:ue);const d=L(a*a),c=L(d-1n),h=L(i*d+1n);let{isValid:u,value:p}=Gh(c,h);u||re("bad point: y not sqrt");const v=(p&1n)===1n,$=(o&128)!==0;return!n&&p===0n&&$&&re("bad point: x==0, isLastByteOdd"),$!==v&&(p=L(-p)),new Oe(p,a,1n,L(p*a))}static fromHex(t,n){return Oe.fromBytes(Sc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Fs,n=Us,i=this;if(i.is0())return re("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,d=L(s*s),c=L(o*o),h=L(a*a),u=L(h*h),p=L(d*t),v=L(h*L(p+c)),$=L(u+L(n*L(d*c)));if(v!==$)return re("bad point: equation left != right (1)");const S=L(s*o),M=L(a*r);return S!==M?re("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:a,Z:r}=Ws(t),d=L(n*r),c=L(o*s),h=L(i*r),u=L(a*s);return d===c&&h===u}is0(){return this.equals(qt)}negate(){return new Oe(L(-this.X),this.Y,this.Z,L(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=Fs,o=L(t*t),a=L(n*n),r=L(2n*L(i*i)),d=L(s*o),c=t+n,h=L(L(c*c)-o-a),u=d+a,p=u-r,v=d-a,$=L(h*p),S=L(u*v),M=L(h*v),y=L(p*u);return new Oe($,S,y,M)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:d,T:c}=Ws(t),h=Fs,u=Us,p=L(n*a),v=L(i*r),$=L(o*u*c),S=L(s*d),M=L((n+i)*(a+r)-p-v),y=L(S-$),b=L(S+$),k=L(v-h*p),A=L(M*y),E=L(b*k),T=L(M*k),P=L(y*b);return new Oe(A,E,P,T)}subtract(t){return this.add(Ws(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return qt;if(gt(t,1n,Ai),t===1n)return this;if(this.equals(Tt))return of(t).p;let i=qt,s=Tt;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(qt))return{x:0n,y:1n};const s=Hh(i,ue);L(i*s)!==1n&&re("invalid inverse");const o=L(t*s),a=L(n*s);return{x:o,y:a}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=Ec(n);return i[31]|=t&1n?128:0,i}toHex(){return $c(this.toBytes())}clearCofactor(){return this.multiply(Fi(Nh),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ai/2n,!1).double();return Ai%2n&&(t=t.add(this)),t.is0()}};q(Oe,"BASE"),q(Oe,"ZERO");let Et=Oe;const Tt=new Et(Er,Tr,1n,L(Er*Tr)),qt=new Et(0n,1n,1n,0n);Et.BASE=Tt;Et.ZERO=qt;const Ec=e=>Sc(xc(gt(e,0n,$o),sa)).reverse(),Tc=e=>Fi("0x"+$c(kc(ct(e)).reverse())),Re=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ue;return n},jh=e=>{const n=e*e%ue*e%ue,i=Re(n,2n)*n%ue,s=Re(i,1n)*e%ue,o=Re(s,5n)*s%ue,a=Re(o,10n)*o%ue,r=Re(a,20n)*a%ue,d=Re(r,40n)*r%ue,c=Re(d,80n)*d%ue,h=Re(c,80n)*d%ue,u=Re(h,10n)*o%ue;return{pow_p_5_8:Re(u,2n)*e%ue,b2:n}},Mr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Gh=(e,t)=>{const n=L(t*t*t),i=L(n*n*t),s=jh(e*i).pow_p_5_8;let o=L(e*n*s);const a=L(t*o*o),r=o,d=L(o*Mr),c=a===e,h=a===L(-e),u=a===L(-e*Mr);return c&&(o=r),(h||u)&&(o=d),(L(o)&1n)===1n&&(o=L(-o)),{isValid:c||h,value:o}},So=e=>Cc(Tc(e)),oa=(...e)=>Mc.sha512Async(zn(...e)),Vh=(...e)=>qh("sha512")(zn(...e)),_c=e=>{const t=e.slice(0,Ct);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Ct,sa),i=So(t),s=Tt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},aa=e=>oa(ct(e,Ct)).then(_c),Qh=e=>_c(Vh(ct(e,Ct))),Jh=e=>aa(e).then(t=>t.pointBytes),Yh=e=>oa(e.hashable).then(e.finish),Xh=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=So(t),a=Tt.multiply(o).toBytes();return{hashable:zn(a,i,n),finish:c=>{const h=Cc(o+So(c)*s);return ct(zn(a,Ec(h)),sa)}}},Zh=async(e,t)=>{const n=ct(e),i=await aa(t),s=await oa(i.prefix,n);return Yh(Xh(i,s,n))},Mc={sha512Async:async e=>{const t=Kh(),n=zn(e);return rs(await t.digest("SHA-512",n.buffer))},sha512:void 0},ef=(e=zh(Ct))=>e,tf={getExtendedPublicKeyAsync:aa,getExtendedPublicKey:Qh,randomSecretKey:ef},Ui=8,nf=256,Pc=Math.ceil(nf/Ui)+1,Ao=2**(Ui-1),sf=()=>{const e=[];let t=Tt,n=t;for(let i=0;i<Pc;i++){n=t,e.push(n);for(let s=1;s<Ao;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Pr;const Ir=(e,t)=>{const n=t.negate();return e?n:t},of=e=>{const t=Pr||(Pr=sf());let n=qt,i=Tt;const s=2**Ui,o=s,a=Fi(s-1),r=Fi(Ui);for(let d=0;d<Pc;d++){let c=Number(e&a);e>>=r,c>Ao&&(c-=o,e+=1n);const h=d*Ao,u=h,p=h+Math.abs(c)-1,v=d%2!==0,$=c<0;c===0?i=i.add(Ir(v,t[u])):n=n.add(Ir($,t[p]))}return e!==0n&&re("invalid wnaf"),{p:n,f:i}},Ks="taskmaster-device-identity-v1";function Co(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Ic(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 af(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Rc(e){const t=await crypto.subtle.digest("SHA-256",e);return af(new Uint8Array(t))}async function rf(){const e=tf.randomSecretKey(),t=await Jh(e);return{deviceId:await Rc(t),publicKey:Co(t),privateKey:Co(e)}}async function lf(){try{const n=localStorage.getItem(Ks);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 Rc(Ic(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(Ks,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 rf(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Ks,JSON.stringify(t)),e}async function cf(e,t){const n=Ic(e),i=new TextEncoder().encode(t),s=await Zh(i,n);return Co(s)}const Lc="taskmaster.device.auth.v1";function ra(e){return e.trim()}function df(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 la(){try{const e=window.localStorage.getItem(Lc);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 Dc(e){try{window.localStorage.setItem(Lc,JSON.stringify(e))}catch{}}function uf(e){const t=la();if(!t||t.deviceId!==e.deviceId)return null;const n=ra(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function pf(e){const t=ra(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=la();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:df(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Dc(n),s}function hf(e){const t=la();if(!t||t.deviceId!==e.deviceId)return;const n=ra(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Dc(i)}async function ca(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 da(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 ff(e){return{method:"exec.approvals.get",params:{}}}async function gf(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=ff(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);mf(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function mf(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=lt(t.file??{}))}async function Bc(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 Ue(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function _e(e){return e instanceof Error?e.message:String(e)}function Hn(){return{name:"",skillContent:"",references:[],alwaysActive:!1}}async function We(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=_e(n)}finally{e.skillsLoading=!1}}}function Nc(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Oc(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 We(e),Ue(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=_e(i);e.skillsError=s,Ue(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Fc(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 We(e),Ue(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=_e(n);e.skillsError=i,Ue(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Uc(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 We(e),Ue(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=_e(s);e.skillsError=o,Ue(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function Wc(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=_e(n)}}function Kc(e){e.skillDetail=null,e.skillDetailTab=""}function zc(e,t){e.skillDetailTab=t}async function Hc(e){if(e.skillAddModal=!0,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[],!(!e.client||!e.connected))try{const t=await e.client.request("skills.drafts",{});t&&(e.skillDrafts=t.drafts)}catch{}}function qc(e){e.skillAddModal=!1,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[]}function jc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="draft"}async function Gc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="installed",await ua(e)}async function ua(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(s=>s.name.trim()&&s.content.trim()).map(s=>({name:s.name.trim(),content:s.content})),i=t.name.trim();e.skillAddFormSource==="installed"?(await e.client.request("skills.create",{name:i,skillContent:t.skillContent,references:n.length>0?n:void 0,alwaysActive:t.alwaysActive}),e.skillAddModal=!1,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillDrafts=[],await We(e),Ue(e,i,{kind:"success",message:"Skill saved — active on next message"})):(await e.client.request("skills.saveDraft",{name:i,skillContent:t.skillContent,references:n.length>0?n:void 0}),e.skillAddModal=!1,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillDrafts=[],Ue(e,i,{kind:"success",message:"Draft saved"}))}catch(n){e.skillsError=_e(n)}finally{e.skillsBusyKey=null}}}async function Vc(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=_e(n)}}async function Qc(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})),alwaysActive:n.alwaysActive??!1},e.skillAddFormSource="installed",e.skillAddModal=!0,e.skillDrafts=[]}catch(n){e.skillsError=_e(n)}}function Jc(e,t){const n=e.skillDetail;n&&(e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i})),alwaysActive:n.alwaysActive??!1},e.skillAddFormSource="installed",e.skillEditTab=t&&t!=="SKILL.md"?t:"SKILL.md",e.skillDetail=null,e.skillDetailTab="",e.skillAddModal=!0,e.skillDrafts=[])}function Yc(e,t,n){e.skillAddForm={...e.skillAddForm,references:e.skillAddForm.references.map(i=>i.name===t?{...i,content:n}:i)}}function Xc(e,t){e.skillEditTab=t}async function Zc(e,t,n){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const i=await e.client.request("skills.read",{name:t});if(!i)return;const s=i.references.filter(o=>o.name.trim()&&o.content.trim()).map(o=>({name:o.name.trim(),content:o.content}));await e.client.request("skills.create",{name:t,skillContent:i.content,references:s.length>0?s:void 0,alwaysActive:n}),await We(e),Ue(e,t,{kind:"success",message:n?"Skill is now always active":"Skill loads on demand"})}catch(i){e.skillsError=_e(i),Ue(e,t,{kind:"error",message:_e(i)})}finally{e.skillsBusyKey=null}}}async function ed(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await We(e)}catch(n){e.skillsError=_e(n)}finally{e.skillsBusyKey=null}}}const yf=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:qc,closeSkillDetail:Kc,deleteDraft:Vc,deleteSkill:ed,editDetailSkill:Jc,editSkill:Qc,emptyAddForm:Hn,importDraft:jc,installDraft:Gc,installSkill:Uc,loadSkills:We,openAddSkillModal:Hc,saveNewSkill:ua,saveSkillApiKey:Fc,setEditTab:Xc,setSkillDetailTab:zc,toggleAlwaysActive:Zc,updateFormReference:Yc,updateSkillEdit:Nc,updateSkillEnabled:Oc,viewSkillDetail:Wc},Symbol.toStringTag,{value:"Module"})),td={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},nd=new Map(Object.entries(td).map(([e,t])=>[t,e]));function ls(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function qn(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 vf(e,t=""){const n=ls(t),i=td[e];return n?`${n}${i}`:i}function id(e,t=""){const n=ls(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=qn(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":nd.get(s)??null}function bf(e){let t=qn(e);if(t.endsWith("/index.html")&&(t=qn(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(nd.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function wf(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function pa(e){return e==="system"?wf():e}const di=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,kf=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,ui=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},xf=({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,a=s,r=kf();if(!!a.startViewTransition&&!r){let h=.5,u=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")h=di(n.pointerClientX/window.innerWidth),u=di(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const p=n.element.getBoundingClientRect();p.width>0&&p.height>0&&typeof window<"u"&&(h=di((p.left+p.width/2)/window.innerWidth),u=di((p.top+p.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${h*100}%`),o.style.setProperty("--theme-switch-y",`${u*100}%`),o.classList.add("theme-transition");try{const p=(c=a.startViewTransition)==null?void 0:c.call(a,()=>{t()});p!=null&&p.finished?p.finished.finally(()=>ui(o)):ui(o)}catch{ui(o),t()}return}t(),ui(o)},$f=2e3;async function Pn(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:[],a=!!(t!=null&&t.reset||Object.keys(e.sessionLogsCursors).length===0);e.sessionLogsEntries=a?o:[...e.sessionLogsEntries,...o].slice(-$f),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 sd=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:Pn},Symbol.toStringTag,{value:"Module"}));async function od(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 Sf(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function Ke(e){return e instanceof Error?e.message:String(e)}let pi=null;function an(e,t){pi&&clearTimeout(pi),e.filesMessage={kind:"success",text:t},pi=setTimeout(()=>{e.filesMessage=null,pi=null},3e3)}async function rn(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=Ke(n)}finally{e.filesLoading=!1}}}}async function Af(e,t,n){e.filesSelectedPaths=new Set([t]),await ad(e,t,n)}async function Cf(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 ad(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function Ef(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 rd(e,o,t),i++}catch(a){s=Ke(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:an(e,`${i} file${i!==1?"s":""} downloaded`)}async function Tf(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await If(e,t,o,i)}async function ad(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=Ke(i)}finally{e.filesPreviewLoading=!1}}}async function rd(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)),a=new Blob([o]),r=URL.createObjectURL(a),d=document.createElement("a");d.href=r,d.download=s.name??t.split("/").pop()??"download",document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(r)}catch(i){e.filesMessage={kind:"error",text:Ke(i)}}}async function _f(e,t,n,i){if(!e.client||!e.connected)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="";for(const a of n)try{const r=await a.arrayBuffer(),d=btoa(new Uint8Array(r).reduce((h,u)=>h+String.fromCharCode(u),"")),c={path:t,name:a.name,data:d};i&&(c.agentId=i),await e.client.request("files.upload",c),s++}catch(r){o=Ke(r)}e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:an(e,`${s} file${s!==1?"s":""} uploaded`),await rn(e,i)}async function Mf(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),an(e,`Created ${s}`),await rn(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:Ke(o)}}}async function Pf(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),an(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await rn(e,n)}catch(i){e.filesMessage={kind:"error",text:Ke(i)}}}}async function If(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),an(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await rn(e,i)}catch(s){e.filesMessage={kind:"error",text:Ke(s)}}}}async function cs(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 Rf(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;an(e,`Re-indexed: ${s} files, ${o} chunks`),await cs(e,t)}catch(n){e.filesMessage={kind:"error",text:Ke(n)}}finally{e.filesReindexBusy=!1}}}function Lf(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 Df(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:Ke(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function Bf(e){e.filesSearchQuery="",e.filesSearchResults=null}function Nf(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{da(e,{quiet:!0})},5e3))}function Of(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function ha(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Gt(e,{quiet:!0})},2e3))}function fa(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function ga(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||Pn(e,{quiet:!0})},2e3))}function ma(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function ya(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&ta(e)},3e3))}function va(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function Ff(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{od(e)},3e4))}function Uf(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function Wf(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{const t=e;t.filesPage&&cs(t,t.filesResolvedAgentId)},3e3))}function Kf(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function at(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,Pp(n),t.theme!==e.theme&&(e.theme=t.theme,ds(e,pa(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function ld(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&at(e,{...e.settings,lastActiveSessionKey:n})}function zf(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 a=!1;if(n!=null){const d=n.trim();d&&d!==e.settings.token&&at(e,{...e.settings,token:d}),t.delete("token"),a=!0}if(i!=null){const d=i.trim();d&&(e.password=d),t.delete("password"),a=!0}if(s!=null){const d=s.trim();d&&(e.sessionKey=d,at(e,{...e.settings,sessionKey:d,lastActiveSessionKey:d}))}if(o!=null){const d=o.trim();d&&d!==e.settings.gatewayUrl&&at(e,{...e.settings,gatewayUrl:d}),t.delete("gatewayUrl"),a=!0}if(!a)return;const r=new URL(window.location.href);r.search=t.toString(),window.history.replaceState({},"",r.toString())}function Hf(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?ga(e):ha(e):(fa(e),ma(e)),t==="debug"?ya(e):va(e),Wi(e),dd(e,t,!1)}function qf(e,t,n){xf({nextTheme:t,applyTheme:()=>{e.theme=t,at(e,{...e.settings,theme:t}),ds(e,pa(t))},context:n,currentTheme:e.theme})}async function Wi(e){if(e.tab==="overview"&&await ud(e),e.tab==="channels"&&await Xf(e),e.tab==="instances"&&await Bc(e),e.tab==="cron"&&await pd(e),e.tab==="skills"&&await We(e),e.tab==="nodes"&&(await da(e),await ca(e),await Fe(e),await gf(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await ig(e),sn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await dc(e),await Fe(e)),e.tab==="debug"&&(await ta(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await ae(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>sd);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await Gt(e,{reset:!0});lc(e,!0)}}function jf(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?ls(e):bf(window.location.pathname)}function Gf(e){e.theme=e.settings.theme??"system",ds(e,pa(e.theme))}function ds(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function Vf(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"&&ds(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Qf(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 Jf(e,t){if(typeof window>"u")return;const n=id(window.location.pathname,e.basePath)??"chat";cd(e,n),dd(e,n,t)}function Yf(e){var s;if(typeof window>"u")return;const t=id(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,at(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),cd(e,t)}function cd(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?ga(e):ha(e):(fa(e),ma(e)),t==="debug"?ya(e):va(e),e.connected&&Wi(e)}function dd(e,t,n){if(typeof window>"u")return;const i=qn(vf(t,e.basePath)),s=qn(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 ud(e){await Promise.all([ee(e,!1),Bc(e),rc(e),on(e),ta(e)])}async function Xf(e){await Promise.all([ee(e,!0),dc(e),Fe(e)])}async function pd(e){await Promise.all([ee(e,!1),on(e),jn(e)])}function hd(e){return e.chatSending||!!e.chatRunId}function Zf(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 fd(e){e.connected&&(e.chatMessage="",await oc(e))}function eg(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:as(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],sn(e))}async function gd(e,t,n){var s,o;Zo(e);const i=await sc(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&&ld(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),sn(e),i&&!e.chatRunId&&md(e),i}async function md(e){if(!e.connected||hd(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await gd(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function tg(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function ng(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),o=e.chatAttachments??[],a=t==null?o:[],r=a.length>0;if(!(!s&&!r)){if(Zf(s)){await fd(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],Rp(e.selectedWorkspace??"",e.sessionKey)),hd(e)){eg(e,s,a);return}await gd(e,s,{previousDraft:t==null?i:void 0,restoreDraft:!!(t&&(n!=null&&n.restoreDraft)),attachments:r?a:void 0,previousAttachments:t==null?o:void 0,restoreAttachments:!!(t&&(n!=null&&n.restoreDraft))})}}async function ig(e){var i;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,nn);await Promise.all([Jt(t,{limit:n}),rc(t),Eo(e)]),sn(e,!0)}const sg=md;function og(e){var s,o,a;const t=Jl(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(s=e.hello)==null?void 0:s.snapshot;return((a=(o=n==null?void 0:n.sessionDefaults)==null?void 0:o.defaultAgentId)==null?void 0:a.trim())||"main"}function ag(e,t){const n=ls(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Eo(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=og(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=ag(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 I={messageSquare:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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>`,user:l`<svg viewBox="0 0 24 24"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>`,menu:l`<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:l`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:l`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:l`<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:l`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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>`,globeOff:l`<svg viewBox="0 0 24 24"><path d="M21.54 15H17"/><path d="M7 3.34V5a3 3 0 0 0 3 3 2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17"/><path d="M11 21.95V18a2 2 0 0 0-2-2 2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05"/><circle cx="12" cy="12" r="10"/><line x1="2" x2="22" y1="2" y2="22"/></svg>`,image:l`<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:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:l`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:l`<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:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:l`<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:l`<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:l`<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>`,mic:l`<svg viewBox="0 0 24 24"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/></svg>`,chevronDown:l`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,film:l`<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:l`<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:l`<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>`,power:l`<svg viewBox="0 0 24 24"><path d="M18.36 6.64a9 9 0 1 1-12.73 0"/><line x1="12" x2="12" y1="2" y2="12"/></svg>`,powerOff:l`<svg viewBox="0 0 24 24"><path d="M18.36 6.64A9 9 0 0 1 20.77 15"/><path d="M6.16 6.16a9 9 0 1 0 12.68 12.68"/><path d="M12 2v4"/><path d="m2 2 20 20"/></svg>`},rg=l`<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>`,lg=l`<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>`,cg=l`<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.36 6.64a9 9 0 1 1-12.73 0"></path><line x1="12" y1="2" x2="12" y2="12"></line></svg>`;let Rr=!1;function dg(){Rr||(Rr=!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 It(e,t){var u;const n=(p,v)=>p===e?l`<span class="sp-page-nav-current">${p}</span>`:l`<a href=${v}>${p}</a>`,i=l`
20
+ `}function cc(e,t,n){if(t.length===0)return;let i=e;for(let o=0;o<t.length-1;o+=1){const a=t[o],r=t[o+1];if(typeof a=="number"){if(!Array.isArray(i))return;i[a]==null&&(i[a]=typeof r=="number"?[]:{}),i=i[a]}else{if(typeof i!="object"||i==null)return;const c=i;c[a]==null&&(c[a]=typeof r=="number"?[]:{}),i=c[a]}}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 Fe(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});yh(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function dc(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});mh(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function mh(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function yh(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?At(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=At(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=lt(t.config??{}),e.configFormOriginal=lt(t.config??{}),e.configRawOriginal=n)}async function vh(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?At(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 Fe(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function on(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 jn(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),e.accountId&&(t.accountId=e.accountId);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 uc(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=Ni(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 pc(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 a=o.trim();a&&i.push(a)}i.length>0&&(n.to=i.join(","));const s=Ni(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function bh(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=uc(e.cronForm),i=pc(e.cronForm),s=e.cronForm.agentId.trim(),o=(t=e.cronForm.accountId)==null?void 0:t.trim(),a={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(!a.name)throw new Error("Name required.");await e.client.request("cron.add",a),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await jn(e),await on(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function wh(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 jn(e),await on(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function kh(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null,e.cronRunModalJobId=t.id,e.cronRunModalJobName=t.name||"Untitled",e.cronRunResult=null;try{await e.client.request("cron.run",{id:t.id,mode:"force"}),await xo(e,t.id)}catch(n){e.cronError=String(n),e.cronRunResult={status:"error",error:String(n)}}finally{e.cronBusy=!1}}}function xh(e,t){e.cronRunModalJobId&&t.jobId===e.cronRunModalJobId&&t.action==="finished"&&(e.cronRunResult={status:t.status??"unknown",durationMs:t.durationMs,summary:t.summary,outputText:t.outputText,error:t.error})}async function $h(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 jn(e),await on(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function Sh(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(a=>a.trim()).filter(Boolean);t.toAdmins=o.some(a=>a.toLowerCase()==="admins"),t.recipients=o.filter(a=>a.toLowerCase()!=="admins")}}return(n=e.isolation)!=null&&n.postToMainPrefix&&(t.postToMainPrefix=e.isolation.postToMainPrefix),t}async function Ah(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=uc(e.cronForm),i=pc(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 jn(e),await on(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function xo(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 ee(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 ea(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 hc(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 fc(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 gc(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=lt(s.config??{});(!o.channels||typeof o.channels!="object")&&(o.channels={});const a=o.channels;(!a.whatsapp||typeof a.whatsapp!="object")&&(a.whatsapp={});const r=a.whatsapp;(!r.accounts||typeof r.accounts!="object")&&(r.accounts={});const c=r.accounts;if(c[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}c[i]={name:n,provider:"baileys"};const d=s.hash;if(!d){e.whatsappAccountError="Config hash missing; reload and retry.";return}const h=At(o);await e.client.request("config.set",{raw:h,baseHash:d}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await ee(e,!0),await ea(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function mc(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=lt(n.config??{}),s=i.channels,o=s==null?void 0:s.whatsapp,a=o==null?void 0:o.accounts;if(!a){e.whatsappAccountError="No accounts found in config.";return}if(Object.keys(a).length<=1){e.whatsappAccountError="Cannot remove the last account.";return}if(!a[t]){e.whatsappAccountError=`Account "${t}" not found.`;return}try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t})}catch{}delete a[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(h=>{const u=h.match;return!u||u.channel!=="whatsapp"?!0:u.accountId!==t}));const c=n.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const d=At(i);await e.client.request("config.set",{raw:d,baseHash:c}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await ee(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const Ch=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:gc,loadChannels:ee,logoutWhatsApp:fc,removeWhatsAppAccount:mc,startWhatsAppLogin:ea,waitWhatsAppLogin:hc},Symbol.toStringTag,{value:"Module"}));async function ta(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 na="taskmaster-access-session",yc={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function ia(){try{return localStorage.getItem(na)}catch{return null}}function vc(e){try{localStorage.setItem(na,e)}catch{}}function Eh(){try{localStorage.removeItem(na)}catch{}}async function Cr(e){if(e.client)try{const t=ia(),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 Th(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?(vc(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 _h(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?(vc(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 Mh(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 Ph(e){const t=ia();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}Eh(),e.accessState={...yc,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}const Ih=2e3,Rh=new Set(["trace","debug","info","warn","error","fatal"]);function Lh(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 Dh(e){if(typeof e!="string")return null;const t=e.toLowerCase();return Rh.has(t)?t:null}function bc(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=Dh((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,a=Lh(o);let r=null;a&&(typeof a.subsystem=="string"?r=a.subsystem:typeof a.module=="string"&&(r=a.module)),!r&&o&&o.length<120&&(r=o);let c=null;return typeof t[1]=="string"?c=t[1]:!a&&typeof t[0]=="string"?c=t[0]:typeof t.message=="string"&&(c=t.message),{raw:e,time:i,level:s,subsystem:r,message:c??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function Gt(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,accessToken:ia()??void 0}),o=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(bc),a=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=a?o:[...e.logsEntries,...o].slice(-Ih),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 Bh=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:Gt,parseLogLine:bc},Symbol.toStringTag,{value:"Module"}));const wc={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:ue,n:Ai,Gx:Er,Gy:Tr,a:Fs,d:Us,h:Nh}=wc,Ct=32,sa=64,Oh=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},re=(e="")=>{const t=new Error(e);throw Oh(t,re),t},Fh=e=>typeof e=="bigint",Uh=e=>typeof e=="string",Wh=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",ct=(e,t,n="")=>{const i=Wh(e),s=e==null?void 0:e.length,o=t!==void 0;if(!i||o&&s!==t){const a=n&&`"${n}" `,r=o?` of length ${t}`:"",c=i?`length=${s}`:`type=${typeof e}`;re(a+"expected Uint8Array"+r+", got "+c)}return e},rs=e=>new Uint8Array(e),kc=e=>Uint8Array.from(e),xc=(e,t)=>e.toString(16).padStart(t,"0"),$c=e=>Array.from(ct(e)).map(t=>xc(t,2)).join(""),Ge={_0:48,_9:57,A:65,F:70,a:97,f:102},_r=e=>{if(e>=Ge._0&&e<=Ge._9)return e-Ge._0;if(e>=Ge.A&&e<=Ge.F)return e-(Ge.A-10);if(e>=Ge.a&&e<=Ge.f)return e-(Ge.a-10)},Sc=e=>{const t="hex invalid";if(!Uh(e))return re(t);const n=e.length,i=n/2;if(n%2)return re(t);const s=rs(i);for(let o=0,a=0;o<i;o++,a+=2){const r=_r(e.charCodeAt(a)),c=_r(e.charCodeAt(a+1));if(r===void 0||c===void 0)return re(t);s[o]=r*16+c}return s},Ac=()=>globalThis==null?void 0:globalThis.crypto,Kh=()=>{var e;return((e=Ac())==null?void 0:e.subtle)??re("crypto.subtle must be defined, consider polyfill")},zn=(...e)=>{const t=rs(e.reduce((i,s)=>i+ct(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},zh=(e=Ct)=>Ac().getRandomValues(rs(e)),Fi=BigInt,gt=(e,t,n,i="bad number: out of range")=>Fh(e)&&t<=e&&e<n?e:re(i),L=(e,t=ue)=>{const n=e%t;return n>=0n?n:t+n},Cc=e=>L(e,Ai),Hh=(e,t)=>{(e===0n||t<=0n)&&re("no inverse n="+e+" mod="+t);let n=L(e,t),i=t,s=0n,o=1n;for(;n!==0n;){const a=i/n,r=i%n,c=s-o*a;i=n,n=r,s=o,o=c}return i===1n?L(s,t):re("no inverse")},qh=e=>{const t=Mc[e];return typeof t!="function"&&re("hashes."+e+" not set"),t},Ws=e=>e instanceof Et?e:re("Point expected"),$o=2n**256n,Oe=class Oe{constructor(t,n,i,s){q(this,"X");q(this,"Y");q(this,"Z");q(this,"T");const o=$o;this.X=gt(t,0n,o),this.Y=gt(n,0n,o),this.Z=gt(i,1n,o),this.T=gt(s,0n,o),Object.freeze(this)}static CURVE(){return wc}static fromAffine(t){return new Oe(t.x,t.y,1n,L(t.x*t.y))}static fromBytes(t,n=!1){const i=Us,s=kc(ct(t,Ct)),o=t[31];s[31]=o&-129;const a=Tc(s);gt(a,0n,n?$o:ue);const c=L(a*a),d=L(c-1n),h=L(i*c+1n);let{isValid:u,value:p}=Gh(d,h);u||re("bad point: y not sqrt");const v=(p&1n)===1n,$=(o&128)!==0;return!n&&p===0n&&$&&re("bad point: x==0, isLastByteOdd"),$!==v&&(p=L(-p)),new Oe(p,a,1n,L(p*a))}static fromHex(t,n){return Oe.fromBytes(Sc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Fs,n=Us,i=this;if(i.is0())return re("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,c=L(s*s),d=L(o*o),h=L(a*a),u=L(h*h),p=L(c*t),v=L(h*L(p+d)),$=L(u+L(n*L(c*d)));if(v!==$)return re("bad point: equation left != right (1)");const S=L(s*o),M=L(a*r);return S!==M?re("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:a,Z:r}=Ws(t),c=L(n*r),d=L(o*s),h=L(i*r),u=L(a*s);return c===d&&h===u}is0(){return this.equals(qt)}negate(){return new Oe(L(-this.X),this.Y,this.Z,L(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=Fs,o=L(t*t),a=L(n*n),r=L(2n*L(i*i)),c=L(s*o),d=t+n,h=L(L(d*d)-o-a),u=c+a,p=u-r,v=c-a,$=L(h*p),S=L(u*v),M=L(h*v),y=L(p*u);return new Oe($,S,y,M)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:c,T:d}=Ws(t),h=Fs,u=Us,p=L(n*a),v=L(i*r),$=L(o*u*d),S=L(s*c),M=L((n+i)*(a+r)-p-v),y=L(S-$),b=L(S+$),k=L(v-h*p),A=L(M*y),E=L(b*k),T=L(M*k),P=L(y*b);return new Oe(A,E,P,T)}subtract(t){return this.add(Ws(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return qt;if(gt(t,1n,Ai),t===1n)return this;if(this.equals(Tt))return of(t).p;let i=qt,s=Tt;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(qt))return{x:0n,y:1n};const s=Hh(i,ue);L(i*s)!==1n&&re("invalid inverse");const o=L(t*s),a=L(n*s);return{x:o,y:a}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=Ec(n);return i[31]|=t&1n?128:0,i}toHex(){return $c(this.toBytes())}clearCofactor(){return this.multiply(Fi(Nh),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ai/2n,!1).double();return Ai%2n&&(t=t.add(this)),t.is0()}};q(Oe,"BASE"),q(Oe,"ZERO");let Et=Oe;const Tt=new Et(Er,Tr,1n,L(Er*Tr)),qt=new Et(0n,1n,1n,0n);Et.BASE=Tt;Et.ZERO=qt;const Ec=e=>Sc(xc(gt(e,0n,$o),sa)).reverse(),Tc=e=>Fi("0x"+$c(kc(ct(e)).reverse())),Re=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ue;return n},jh=e=>{const n=e*e%ue*e%ue,i=Re(n,2n)*n%ue,s=Re(i,1n)*e%ue,o=Re(s,5n)*s%ue,a=Re(o,10n)*o%ue,r=Re(a,20n)*a%ue,c=Re(r,40n)*r%ue,d=Re(c,80n)*c%ue,h=Re(d,80n)*c%ue,u=Re(h,10n)*o%ue;return{pow_p_5_8:Re(u,2n)*e%ue,b2:n}},Mr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Gh=(e,t)=>{const n=L(t*t*t),i=L(n*n*t),s=jh(e*i).pow_p_5_8;let o=L(e*n*s);const a=L(t*o*o),r=o,c=L(o*Mr),d=a===e,h=a===L(-e),u=a===L(-e*Mr);return d&&(o=r),(h||u)&&(o=c),(L(o)&1n)===1n&&(o=L(-o)),{isValid:d||h,value:o}},So=e=>Cc(Tc(e)),oa=(...e)=>Mc.sha512Async(zn(...e)),Vh=(...e)=>qh("sha512")(zn(...e)),_c=e=>{const t=e.slice(0,Ct);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Ct,sa),i=So(t),s=Tt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},aa=e=>oa(ct(e,Ct)).then(_c),Qh=e=>_c(Vh(ct(e,Ct))),Jh=e=>aa(e).then(t=>t.pointBytes),Yh=e=>oa(e.hashable).then(e.finish),Xh=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=So(t),a=Tt.multiply(o).toBytes();return{hashable:zn(a,i,n),finish:d=>{const h=Cc(o+So(d)*s);return ct(zn(a,Ec(h)),sa)}}},Zh=async(e,t)=>{const n=ct(e),i=await aa(t),s=await oa(i.prefix,n);return Yh(Xh(i,s,n))},Mc={sha512Async:async e=>{const t=Kh(),n=zn(e);return rs(await t.digest("SHA-512",n.buffer))},sha512:void 0},ef=(e=zh(Ct))=>e,tf={getExtendedPublicKeyAsync:aa,getExtendedPublicKey:Qh,randomSecretKey:ef},Ui=8,nf=256,Pc=Math.ceil(nf/Ui)+1,Ao=2**(Ui-1),sf=()=>{const e=[];let t=Tt,n=t;for(let i=0;i<Pc;i++){n=t,e.push(n);for(let s=1;s<Ao;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Pr;const Ir=(e,t)=>{const n=t.negate();return e?n:t},of=e=>{const t=Pr||(Pr=sf());let n=qt,i=Tt;const s=2**Ui,o=s,a=Fi(s-1),r=Fi(Ui);for(let c=0;c<Pc;c++){let d=Number(e&a);e>>=r,d>Ao&&(d-=o,e+=1n);const h=c*Ao,u=h,p=h+Math.abs(d)-1,v=c%2!==0,$=d<0;d===0?i=i.add(Ir(v,t[u])):n=n.add(Ir($,t[p]))}return e!==0n&&re("invalid wnaf"),{p:n,f:i}},Ks="taskmaster-device-identity-v1";function Co(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Ic(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 af(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Rc(e){const t=await crypto.subtle.digest("SHA-256",e);return af(new Uint8Array(t))}async function rf(){const e=tf.randomSecretKey(),t=await Jh(e);return{deviceId:await Rc(t),publicKey:Co(t),privateKey:Co(e)}}async function lf(){try{const n=localStorage.getItem(Ks);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 Rc(Ic(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(Ks,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 rf(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Ks,JSON.stringify(t)),e}async function cf(e,t){const n=Ic(e),i=new TextEncoder().encode(t),s=await Zh(i,n);return Co(s)}const Lc="taskmaster.device.auth.v1";function ra(e){return e.trim()}function df(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 la(){try{const e=window.localStorage.getItem(Lc);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 Dc(e){try{window.localStorage.setItem(Lc,JSON.stringify(e))}catch{}}function uf(e){const t=la();if(!t||t.deviceId!==e.deviceId)return null;const n=ra(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function pf(e){const t=ra(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=la();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:df(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Dc(n),s}function hf(e){const t=la();if(!t||t.deviceId!==e.deviceId)return;const n=ra(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Dc(i)}async function ca(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 da(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 ff(e){return{method:"exec.approvals.get",params:{}}}async function gf(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=ff(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);mf(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function mf(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=lt(t.file??{}))}async function Bc(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 Ue(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function _e(e){return e instanceof Error?e.message:String(e)}function Hn(){return{name:"",skillContent:"",references:[],alwaysActive:!1}}async function We(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=_e(n)}finally{e.skillsLoading=!1}}}function Nc(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Oc(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 We(e),Ue(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=_e(i);e.skillsError=s,Ue(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Fc(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 We(e),Ue(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=_e(n);e.skillsError=i,Ue(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Uc(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 We(e),Ue(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=_e(s);e.skillsError=o,Ue(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function Wc(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=_e(n)}}function Kc(e){e.skillDetail=null,e.skillDetailTab=""}function zc(e,t){e.skillDetailTab=t}async function Hc(e){if(e.skillAddModal=!0,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[],!(!e.client||!e.connected))try{const t=await e.client.request("skills.drafts",{});t&&(e.skillDrafts=t.drafts)}catch{}}function qc(e){e.skillAddModal=!1,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[]}function jc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="draft"}async function Gc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="installed",await ua(e)}async function ua(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(s=>s.name.trim()&&s.content.trim()).map(s=>({name:s.name.trim(),content:s.content})),i=t.name.trim();e.skillAddFormSource==="installed"?(await e.client.request("skills.create",{name:i,skillContent:t.skillContent,references:n.length>0?n:void 0,alwaysActive:t.alwaysActive}),e.skillAddModal=!1,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillDrafts=[],await We(e),Ue(e,i,{kind:"success",message:"Skill saved — active on next message"})):(await e.client.request("skills.saveDraft",{name:i,skillContent:t.skillContent,references:n.length>0?n:void 0}),e.skillAddModal=!1,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillDrafts=[],Ue(e,i,{kind:"success",message:"Draft saved"}))}catch(n){e.skillsError=_e(n)}finally{e.skillsBusyKey=null}}}async function Vc(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=_e(n)}}async function Qc(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})),alwaysActive:n.alwaysActive??!1},e.skillAddFormSource="installed",e.skillAddModal=!0,e.skillDrafts=[]}catch(n){e.skillsError=_e(n)}}function Jc(e,t){const n=e.skillDetail;n&&(e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i})),alwaysActive:n.alwaysActive??!1},e.skillAddFormSource="installed",e.skillEditTab=t&&t!=="SKILL.md"?t:"SKILL.md",e.skillDetail=null,e.skillDetailTab="",e.skillAddModal=!0,e.skillDrafts=[])}function Yc(e,t,n){e.skillAddForm={...e.skillAddForm,references:e.skillAddForm.references.map(i=>i.name===t?{...i,content:n}:i)}}function Xc(e,t){e.skillEditTab=t}async function Zc(e,t,n){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const i=await e.client.request("skills.read",{name:t});if(!i)return;const s=i.references.filter(o=>o.name.trim()&&o.content.trim()).map(o=>({name:o.name.trim(),content:o.content}));await e.client.request("skills.create",{name:t,skillContent:i.content,references:s.length>0?s:void 0,alwaysActive:n}),await We(e),Ue(e,t,{kind:"success",message:n?"Skill is now always active":"Skill loads on demand"})}catch(i){e.skillsError=_e(i),Ue(e,t,{kind:"error",message:_e(i)})}finally{e.skillsBusyKey=null}}}async function ed(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await We(e)}catch(n){e.skillsError=_e(n)}finally{e.skillsBusyKey=null}}}const yf=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:qc,closeSkillDetail:Kc,deleteDraft:Vc,deleteSkill:ed,editDetailSkill:Jc,editSkill:Qc,emptyAddForm:Hn,importDraft:jc,installDraft:Gc,installSkill:Uc,loadSkills:We,openAddSkillModal:Hc,saveNewSkill:ua,saveSkillApiKey:Fc,setEditTab:Xc,setSkillDetailTab:zc,toggleAlwaysActive:Zc,updateFormReference:Yc,updateSkillEdit:Nc,updateSkillEnabled:Oc,viewSkillDetail:Wc},Symbol.toStringTag,{value:"Module"})),td={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},nd=new Map(Object.entries(td).map(([e,t])=>[t,e]));function ls(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function qn(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 vf(e,t=""){const n=ls(t),i=td[e];return n?`${n}${i}`:i}function id(e,t=""){const n=ls(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=qn(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":nd.get(s)??null}function bf(e){let t=qn(e);if(t.endsWith("/index.html")&&(t=qn(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(nd.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function wf(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function pa(e){return e==="system"?wf():e}const di=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,kf=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,ui=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},xf=({nextTheme:e,applyTheme:t,context:n,currentTheme:i})=>{var d;if(i===e)return;const s=globalThis.document??null;if(!s){t();return}const o=s.documentElement,a=s,r=kf();if(!!a.startViewTransition&&!r){let h=.5,u=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")h=di(n.pointerClientX/window.innerWidth),u=di(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const p=n.element.getBoundingClientRect();p.width>0&&p.height>0&&typeof window<"u"&&(h=di((p.left+p.width/2)/window.innerWidth),u=di((p.top+p.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${h*100}%`),o.style.setProperty("--theme-switch-y",`${u*100}%`),o.classList.add("theme-transition");try{const p=(d=a.startViewTransition)==null?void 0:d.call(a,()=>{t()});p!=null&&p.finished?p.finished.finally(()=>ui(o)):ui(o)}catch{ui(o),t()}return}t(),ui(o)},$f=2e3;async function Pn(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:[],a=!!(t!=null&&t.reset||Object.keys(e.sessionLogsCursors).length===0);e.sessionLogsEntries=a?o:[...e.sessionLogsEntries,...o].slice(-$f),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 sd=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:Pn},Symbol.toStringTag,{value:"Module"}));async function od(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 Sf(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function Ke(e){return e instanceof Error?e.message:String(e)}let pi=null;function an(e,t){pi&&clearTimeout(pi),e.filesMessage={kind:"success",text:t},pi=setTimeout(()=>{e.filesMessage=null,pi=null},3e3)}async function rn(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=Ke(n)}finally{e.filesLoading=!1}}}}async function Af(e,t,n){e.filesSelectedPaths=new Set([t]),await ad(e,t,n)}async function Cf(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 ad(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function Ef(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 rd(e,o,t),i++}catch(a){s=Ke(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:an(e,`${i} file${i!==1?"s":""} downloaded`)}async function Tf(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await If(e,t,o,i)}async function ad(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=Ke(i)}finally{e.filesPreviewLoading=!1}}}async function rd(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),d=>d.charCodeAt(0)),a=new Blob([o]),r=URL.createObjectURL(a),c=document.createElement("a");c.href=r,c.download=s.name??t.split("/").pop()??"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(r)}catch(i){e.filesMessage={kind:"error",text:Ke(i)}}}async function _f(e,t,n,i){if(!e.client||!e.connected)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="";for(const a of n)try{const r=await a.arrayBuffer(),c=btoa(new Uint8Array(r).reduce((h,u)=>h+String.fromCharCode(u),"")),d={path:t,name:a.name,data:c};i&&(d.agentId=i),await e.client.request("files.upload",d),s++}catch(r){o=Ke(r)}e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:an(e,`${s} file${s!==1?"s":""} uploaded`),await rn(e,i)}async function Mf(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),an(e,`Created ${s}`),await rn(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:Ke(o)}}}async function Pf(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),an(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await rn(e,n)}catch(i){e.filesMessage={kind:"error",text:Ke(i)}}}}async function If(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),an(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await rn(e,i)}catch(s){e.filesMessage={kind:"error",text:Ke(s)}}}}async function cs(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 Rf(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;an(e,`Re-indexed: ${s} files, ${o} chunks`),await cs(e,t)}catch(n){e.filesMessage={kind:"error",text:Ke(n)}}finally{e.filesReindexBusy=!1}}}function Lf(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 Df(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:Ke(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function Bf(e){e.filesSearchQuery="",e.filesSearchResults=null}function Nf(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{da(e,{quiet:!0})},5e3))}function Of(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function ha(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Gt(e,{quiet:!0})},2e3))}function fa(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function ga(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||Pn(e,{quiet:!0})},2e3))}function ma(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function ya(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&ta(e)},3e3))}function va(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function Ff(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{od(e)},3e4))}function Uf(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function Wf(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{const t=e;t.filesPage&&cs(t,t.filesResolvedAgentId)},3e3))}function Kf(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function at(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,Pp(n),t.theme!==e.theme&&(e.theme=t.theme,ds(e,pa(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function ld(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&at(e,{...e.settings,lastActiveSessionKey:n})}function zf(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 a=!1;if(n!=null){const c=n.trim();c&&c!==e.settings.token&&at(e,{...e.settings,token:c}),t.delete("token"),a=!0}if(i!=null){const c=i.trim();c&&(e.password=c),t.delete("password"),a=!0}if(s!=null){const c=s.trim();c&&(e.sessionKey=c,at(e,{...e.settings,sessionKey:c,lastActiveSessionKey:c}))}if(o!=null){const c=o.trim();c&&c!==e.settings.gatewayUrl&&at(e,{...e.settings,gatewayUrl:c}),t.delete("gatewayUrl"),a=!0}if(!a)return;const r=new URL(window.location.href);r.search=t.toString(),window.history.replaceState({},"",r.toString())}function Hf(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?ga(e):ha(e):(fa(e),ma(e)),t==="debug"?ya(e):va(e),Wi(e),dd(e,t,!1)}function qf(e,t,n){xf({nextTheme:t,applyTheme:()=>{e.theme=t,at(e,{...e.settings,theme:t}),ds(e,pa(t))},context:n,currentTheme:e.theme})}async function Wi(e){if(e.tab==="overview"&&await ud(e),e.tab==="channels"&&await Xf(e),e.tab==="instances"&&await Bc(e),e.tab==="cron"&&await pd(e),e.tab==="skills"&&await We(e),e.tab==="nodes"&&(await da(e),await ca(e),await Fe(e),await gf(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await ig(e),sn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await dc(e),await Fe(e)),e.tab==="debug"&&(await ta(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await ae(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>sd);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await Gt(e,{reset:!0});lc(e,!0)}}function jf(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?ls(e):bf(window.location.pathname)}function Gf(e){e.theme=e.settings.theme??"system",ds(e,pa(e.theme))}function ds(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function Vf(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"&&ds(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Qf(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 Jf(e,t){if(typeof window>"u")return;const n=id(window.location.pathname,e.basePath)??"chat";cd(e,n),dd(e,n,t)}function Yf(e){var s;if(typeof window>"u")return;const t=id(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,at(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),cd(e,t)}function cd(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?ga(e):ha(e):(fa(e),ma(e)),t==="debug"?ya(e):va(e),e.connected&&Wi(e)}function dd(e,t,n){if(typeof window>"u")return;const i=qn(vf(t,e.basePath)),s=qn(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 ud(e){await Promise.all([ee(e,!1),Bc(e),rc(e),on(e),ta(e)])}async function Xf(e){await Promise.all([ee(e,!0),dc(e),Fe(e)])}async function pd(e){await Promise.all([ee(e,!1),on(e),jn(e)])}function hd(e){return e.chatSending||!!e.chatRunId}function Zf(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 fd(e){e.connected&&(e.chatMessage="",await oc(e))}function eg(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:as(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],sn(e))}async function gd(e,t,n){var s,o;Zo(e);const i=await sc(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&&ld(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),sn(e),i&&!e.chatRunId&&md(e),i}async function md(e){if(!e.connected||hd(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await gd(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function tg(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function ng(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),o=e.chatAttachments??[],a=t==null?o:[],r=a.length>0;if(!(!s&&!r)){if(Zf(s)){await fd(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],Rp(e.selectedWorkspace??"",e.sessionKey)),hd(e)){eg(e,s,a);return}await gd(e,s,{previousDraft:t==null?i:void 0,restoreDraft:!!(t&&(n!=null&&n.restoreDraft)),attachments:r?a:void 0,previousAttachments:t==null?o:void 0,restoreAttachments:!!(t&&(n!=null&&n.restoreDraft))})}}async function ig(e){var i;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,nn);await Promise.all([Jt(t,{limit:n}),rc(t),Eo(e)]),sn(e,!0)}const sg=md;function og(e){var s,o,a;const t=Jl(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(s=e.hello)==null?void 0:s.snapshot;return((a=(o=n==null?void 0:n.sessionDefaults)==null?void 0:o.defaultAgentId)==null?void 0:a.trim())||"main"}function ag(e,t){const n=ls(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Eo(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=og(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=ag(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 I={messageSquare:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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>`,user:l`<svg viewBox="0 0 24 24"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>`,menu:l`<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:l`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:l`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:l`<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:l`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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:l`<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>`,globeOff:l`<svg viewBox="0 0 24 24"><path d="M21.54 15H17"/><path d="M7 3.34V5a3 3 0 0 0 3 3 2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17"/><path d="M11 21.95V18a2 2 0 0 0-2-2 2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05"/><circle cx="12" cy="12" r="10"/><line x1="2" x2="22" y1="2" y2="22"/></svg>`,image:l`<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:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:l`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:l`<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:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:l`<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:l`<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:l`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:l`<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:l`<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:l`<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>`,mic:l`<svg viewBox="0 0 24 24"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/></svg>`,chevronDown:l`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,film:l`<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:l`<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:l`<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>`,power:l`<svg viewBox="0 0 24 24"><path d="M18.36 6.64a9 9 0 1 1-12.73 0"/><line x1="12" x2="12" y1="2" y2="12"/></svg>`,powerOff:l`<svg viewBox="0 0 24 24"><path d="M18.36 6.64A9 9 0 0 1 20.77 15"/><path d="M6.16 6.16a9 9 0 1 0 12.68 12.68"/><path d="M12 2v4"/><path d="m2 2 20 20"/></svg>`},rg=l`<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>`,lg=l`<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>`,cg=l`<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.36 6.64a9 9 0 1 1-12.73 0"></path><line x1="12" y1="2" x2="12" y2="12"></line></svg>`;let Rr=!1;function dg(){Rr||(Rr=!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 It(e,t){var u;const n=(p,v)=>p===e?l`<span class="sp-page-nav-current">${p}</span>`:l`<a href=${v}>${p}</a>`,i=l`
21
21
  ${n("Setup","/setup")}
22
22
  ${n("Chat","/chat")}
23
23
  ${n("Admins","/admins")}
@@ -25,9 +25,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
25
25
  ${n("Files","/files")}
26
26
  ${n("Browser","/browser")}
27
27
  ${n("Advanced","/advanced")}
28
- `,o=t&&(t.isMaster!==!1||!t.hasPins)?pg(t):w,a=t!=null&&t.hasPins&&t.onLogout?l`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${rg}</button>`:w,r=t!=null&&t.onRestartGateway?ug(t.onRestartGateway):w,d=(t==null?void 0:t.auditCount)??0,c=d>0&&(t!=null&&t.onAuditClick)?l`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
28
+ `,o=t&&(t.isMaster!==!1||!t.hasPins)?pg(t):w,a=t!=null&&t.hasPins&&t.onLogout?l`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${rg}</button>`:w,r=t!=null&&t.onRestartGateway?ug(t.onRestartGateway):w,c=(t==null?void 0:t.auditCount)??0,d=c>0&&(t!=null&&t.onAuditClick)?l`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
29
  ${lg}
30
- <span class="nav-audit-badge">${d>99?"99+":d}</span>
30
+ <span class="nav-audit-badge">${c>99?"99+":c}</span>
31
31
  </button>`:w,h=()=>{const p=document.getElementById("nav-burger-toggle");p&&(p.checked=!1)};return dg(),l`
32
32
  <div class="setup-header">
33
33
  <input type="checkbox" id="nav-burger-toggle" class="nav-burger-checkbox" />
@@ -38,7 +38,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
38
38
  </nav>
39
39
  <div class="setup-header-right">
40
40
  ${o!==w?l`<span class="nav-selector-inline">${o}</span>`:w}
41
- ${c}
41
+ ${d}
42
42
  ${a}
43
43
  ${r}
44
44
  <label for="nav-burger-toggle" class="nav-burger-button" aria-label="Toggle menu">
@@ -53,7 +53,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
53
53
  </div>
54
54
  `}function ug(e){let t=!1;return l`
55
55
  <span class="nav-restart-container" style="position: relative;">
56
- <button class="nav-restart-btn" @click=${o=>{const r=o.currentTarget.closest(".nav-restart-container");if(!r)return;const d=r.querySelector(".nav-restart-confirm");d&&(t=!t,d.style.display=t?"flex":"none")}} title="Restart gateway">
56
+ <button class="nav-restart-btn" @click=${o=>{const r=o.currentTarget.closest(".nav-restart-container");if(!r)return;const c=r.querySelector(".nav-restart-confirm");c&&(t=!t,c.style.display=t?"flex":"none")}} title="Restart gateway">
57
57
  ${cg}
58
58
  </button>
59
59
  <div class="nav-restart-confirm" style="display: none;">
@@ -210,32 +210,32 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
210
210
  <p>Connecting to gateway...</p>
211
211
  </div>
212
212
  </div>
213
- `}const Ki="application/x-taskmaster-file-path";let ht=null;function yd(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function vd(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function fg(e,t,n){var o,a;e.preventDefault(),e.stopPropagation(),e.currentTarget.classList.remove("sp-drop-target");const i=(o=e.dataTransfer)==null?void 0:o.getData(Ki);if(i){vd(i)!==t&&n.onMoveToDir(i,t);return}const s=(a=e.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(d=>d.name.toLowerCase().endsWith(".md"));r.length>0&&n.onUpload(t,r)}}function bd(e,t,n){var d;const i=e.type==="directory"||e.type==="symlink"&&e.children!=null,s=t.expandedDirs.has(e.path),o=t.selectedPaths.has(e.path),a=t.currentDir===e.path,r=n*20+12;return i?l`
213
+ `}const Ki="application/x-taskmaster-file-path";let ht=null;function yd(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function vd(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function fg(e,t,n){var o,a;e.preventDefault(),e.stopPropagation(),e.currentTarget.classList.remove("sp-drop-target");const i=(o=e.dataTransfer)==null?void 0:o.getData(Ki);if(i){vd(i)!==t&&n.onMoveToDir(i,t);return}const s=(a=e.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(c=>c.name.toLowerCase().endsWith(".md"));r.length>0&&n.onUpload(t,r)}}function bd(e,t,n){var c;const i=e.type==="directory"||e.type==="symlink"&&e.children!=null,s=t.expandedDirs.has(e.path),o=t.selectedPaths.has(e.path),a=t.currentDir===e.path,r=n*20+12;return i?l`
214
214
  <div
215
215
  class="sp-tree-item sp-tree-dir ${s?"expanded":""} ${a?"current":""}"
216
216
  style="padding-left: ${r}px;"
217
217
  @click=${()=>t.onToggleDir(e.path)}
218
- @dragover=${c=>{c.preventDefault(),c.stopPropagation(),c.dataTransfer&&(c.dataTransfer.dropEffect="move"),c.currentTarget.classList.add("sp-drop-target")}}
219
- @dragleave=${c=>{c.currentTarget.classList.remove("sp-drop-target")}}
220
- @drop=${c=>fg(c,e.path,t)}
218
+ @dragover=${d=>{d.preventDefault(),d.stopPropagation(),d.dataTransfer&&(d.dataTransfer.dropEffect="move"),d.currentTarget.classList.add("sp-drop-target")}}
219
+ @dragleave=${d=>{d.currentTarget.classList.remove("sp-drop-target")}}
220
+ @drop=${d=>fg(d,e.path,t)}
221
221
  >
222
222
  <span class="sp-tree-chevron">${s?"−":"+"}</span>
223
223
  <span class="sp-tree-icon">${I.folder}</span>
224
224
  <span class="sp-tree-name">${e.name}</span>
225
- ${s&&((d=e.children)==null?void 0:d.length)===0?l`<span
225
+ ${s&&((c=e.children)==null?void 0:c.length)===0?l`<span
226
226
  class="sp-tree-dir-delete"
227
227
  title="Delete empty folder"
228
- @click=${c=>{c.stopPropagation(),t.onDelete(e.path)}}
228
+ @click=${d=>{d.stopPropagation(),t.onDelete(e.path)}}
229
229
  >×</span>`:w}
230
230
  </div>
231
- ${s&&e.children?e.children.map(c=>bd(c,t,n+1)):w}
231
+ ${s&&e.children?e.children.map(d=>bd(d,t,n+1)):w}
232
232
  `:l`
233
233
  <div
234
234
  class="sp-tree-item sp-tree-file ${o?"selected":""}"
235
235
  style="padding-left: ${r}px;"
236
236
  draggable="true"
237
- @click=${c=>{c.metaKey||c.ctrlKey?t.onToggleSelectFile(e.path):t.onSelectFile(e.path)}}
238
- @dragstart=${c=>{c.dataTransfer&&(c.dataTransfer.effectAllowed="move",c.dataTransfer.setData(Ki,e.path),c.dataTransfer.setData("text/plain",e.name))}}
237
+ @click=${d=>{d.metaKey||d.ctrlKey?t.onToggleSelectFile(e.path):t.onSelectFile(e.path)}}
238
+ @dragstart=${d=>{d.dataTransfer&&(d.dataTransfer.effectAllowed="move",d.dataTransfer.setData(Ki,e.path),d.dataTransfer.setData("text/plain",e.name))}}
239
239
  >
240
240
  <span class="sp-tree-icon">${I.fileText}</span>
241
241
  <span class="sp-tree-name">${e.name}</span>
@@ -380,7 +380,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
380
380
  class="setup-status-light"
381
381
  style="width: 10px; height: 10px; background: ${e.memoryStatus.syncing?"#f59e0b":e.memoryStatus.dirty?"#ef4444":"#22c55e"}"
382
382
  ></span>
383
- ${(()=>{var d;if(e.memoryStatus.syncing&&e.memoryStatus.syncProgress){const{completed:c,total:h,label:u}=e.memoryStatus.syncProgress;return u||(h>0?`Indexing ${c}/${h} files…`:"Indexing…")}const n=e.memoryStatus.files,i=e.memoryStatus.chunks,s=`${n} file${n!==1?"s":""}, ${i} chunks`,o=(d=e.memoryStatus)==null?void 0:d.model;if(!o)return s;const r=(o.includes("/")?o.split("/").pop():o).replace(/[-_]Q\d.*$/i,"").replace(/\.gguf$/i,"");return`${s} · ${r}`})()}
383
+ ${(()=>{var c;if(e.memoryStatus.syncing&&e.memoryStatus.syncProgress){const{completed:d,total:h,label:u}=e.memoryStatus.syncProgress;return u||(h>0?`Indexing ${d}/${h} files…`:"Indexing…")}const n=e.memoryStatus.files,i=e.memoryStatus.chunks,s=`${n} file${n!==1?"s":""}, ${i} chunks`,o=(c=e.memoryStatus)==null?void 0:c.model;if(!o)return s;const r=(o.includes("/")?o.split("/").pop():o).replace(/[-_]Q\d.*$/i,"").replace(/\.gguf$/i,"");return`${s} · ${r}`})()}
384
384
  </span>`:w}
385
385
  </div>
386
386
 
@@ -397,7 +397,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
397
397
  ${e.searchResults!==null?vg(e):l`<div
398
398
  class="sp-file-tree"
399
399
  @dragover=${n=>{n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(Ki)?"move":"copy")}}
400
- @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(Ki);if(i){vd(i)!=="."&&e.onMoveToDir(i,".");return}const s=(a=n.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(d=>d.name.toLowerCase().endsWith(".md"));r.length>0&&e.onUpload(t,r)}}}
400
+ @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(Ki);if(i){vd(i)!=="."&&e.onMoveToDir(i,".");return}const s=(a=n.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(c=>c.name.toLowerCase().endsWith(".md"));r.length>0&&e.onUpload(t,r)}}}
401
401
  >
402
402
  ${e.tree.length===0&&!e.loading?l`<div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No files found. Drop .md files here to upload.</div>`:e.tree.map(n=>bd(n,e,0))}
403
403
  </div>`}
@@ -426,13 +426,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
426
426
  >
427
427
  ${I.info}
428
428
  </button>
429
- `}function xg(e){var s;if(!e.infoModalOpen)return w;let t="",n=[],i=w;switch(e.infoModalOpen){case"gateway":{const o=typeof window<"u"?window.location.host:"unknown";t="Gateway",n=[{label:"Status",value:e.gatewayHealthy===!1?"Stopped":"Running"},{label:"What",value:"The core service that powers Taskmaster — handles AI conversations, message routing, and all connected channels"},{label:"Address",value:o},{label:"Health",value:e.gatewayHealthMessage||"OK"}];break}case"claude":{const o=e.authExpiresIn;let a="N/A";if(o!=null&&o>0)if(o>60){const r=Math.floor(o/60),d=o%60;a=d>0?`${r}h ${d}m`:`${r}h`}else a=`${o}m`;if(t="Claude",n=[{label:"Status",value:e.authConnected?"Connected":"Disconnected"},{label:"What",value:"Connection to Claude, the AI that powers natural conversation and tool use"},{label:"How",value:"Authenticated via OAuth — tokens refresh automatically when they expire"},{label:"Token Expiry",value:a},...e.authMessage?[{label:"Message",value:e.authMessage}]:[]],e.authRefreshToken){const r=e.authRefreshToken,d=r.length>20?`${r.slice(0,8)}...${r.slice(-8)}`:r;i=l`
429
+ `}function xg(e){var s;if(!e.infoModalOpen)return w;let t="",n=[],i=w;switch(e.infoModalOpen){case"gateway":{const o=typeof window<"u"?window.location.host:"unknown";t="Gateway",n=[{label:"Status",value:e.gatewayHealthy===!1?"Stopped":"Running"},{label:"What",value:"The core service that powers Taskmaster — handles AI conversations, message routing, and all connected channels"},{label:"Address",value:o},{label:"Health",value:e.gatewayHealthMessage||"OK"}];break}case"claude":{const o=e.authExpiresIn;let a="N/A";if(o!=null&&o>0)if(o>60){const r=Math.floor(o/60),c=o%60;a=c>0?`${r}h ${c}m`:`${r}h`}else a=`${o}m`;if(t="Claude",n=[{label:"Status",value:e.authConnected?"Connected":"Disconnected"},{label:"What",value:"Connection to Claude, the AI that powers natural conversation and tool use"},{label:"How",value:"Authenticated via OAuth — tokens refresh automatically when they expire"},{label:"Token Expiry",value:a},...e.authMessage?[{label:"Message",value:e.authMessage}]:[]],e.authRefreshToken){const r=e.authRefreshToken,c=r.length>20?`${r.slice(0,8)}...${r.slice(-8)}`:r;i=l`
430
430
  <div style="display: flex; align-items: center; gap: 6px; padding: 4px 0 8px; border-bottom: 1px solid rgba(255,255,255,0.08);">
431
431
  <span style="font-size: 12px; color: var(--tasker-text-grey); min-width: 90px;">Refresh Token</span>
432
- <code style="font-size: 12px; color: var(--tasker-white); word-break: break-all; flex: 1;">${d}</code>
433
- <button class="setup-info-btn" title="Copy refresh token" @click=${async c=>{const h=c.currentTarget;try{await navigator.clipboard.writeText(r)}catch{const u=document.createElement("textarea");u.value=r,u.style.position="fixed",u.style.opacity="0",document.body.appendChild(u),u.select(),document.execCommand("copy"),document.body.removeChild(u)}h.classList.add("copied"),setTimeout(()=>h.classList.remove("copied"),1500)}}>${I.copy}</button>
432
+ <code style="font-size: 12px; color: var(--tasker-white); word-break: break-all; flex: 1;">${c}</code>
433
+ <button class="setup-info-btn" title="Copy refresh token" @click=${async d=>{const h=d.currentTarget;try{await navigator.clipboard.writeText(r)}catch{const u=document.createElement("textarea");u.value=r,u.style.position="fixed",u.style.opacity="0",document.body.appendChild(u),u.select(),document.execCommand("copy"),document.body.removeChild(u)}h.classList.add("copied"),setTimeout(()=>h.classList.remove("copied"),1500)}}>${I.copy}</button>
434
434
  </div>
435
- `}break}case"license":{const o=e.licenseStoredKey?`…${e.licenseStoredKey.slice(-12)}`:"N/A";t="License",n=[{label:"Status",value:e.licenseValid?"Active":"Inactive"},{label:"What",value:"Your Taskmaster license key, tied to this specific device"},{label:"Key",value:o},{label:"Tier",value:e.licenseTier||"Standard"},{label:"Device ID",value:e.licenseDeviceId||"N/A"}];break}case"whatsapp":{const o=Rt(e),a=o?us(o,e):null;t="WhatsApp",n=[{label:"Status",value:a!=null&&a.connected?"Connected":"Disconnected"},{label:"What",value:"WhatsApp integration — receive and respond to customer messages through WhatsApp"},{label:"How",value:"Links to your WhatsApp account by scanning a QR code, then routes messages to your AI assistant"},{label:"Account",value:(a==null?void 0:a.name)||(a==null?void 0:a.accountId)||"Default"},{label:"Phone",value:((s=a==null?void 0:a.self)==null?void 0:s.e164)||"Not paired"},{label:"Linked",value:a!=null&&a.linked?"Yes":"No"},...a!=null&&a.lastError?[{label:"Last Error",value:ka(a.lastError)}]:[]];break}case"imessage":{const{thisWsOwns:o}=xa(e);t="iMessage",n=[{label:"Status",value:o&&e.imessageConnected?"Connected":"Disconnected"},{label:"What",value:"iMessage integration — communicate with your AI assistant through Apple Messages"},{label:"How",value:"Uses the Mac's built-in Messages app; only one account can own the iMessage channel at a time"},{label:"Assigned To",value:e.imessageOwnerWorkspace??"Not assigned"},{label:"Mode",value:"Self-chat only"},...e.imessageLastError?[{label:"Last Error",value:e.imessageLastError}]:[]];break}case"update":{t="Software Update",n=[{label:"Status",value:e.updateAvailable===null?"Not checked":e.updateAvailable?"Update available":"Up to date"},{label:"What",value:"Checks for new versions of Taskmaster and lets you update from the control panel"},{label:"Current",value:e.currentVersion?`v${e.currentVersion}`:"Unknown"},{label:"Latest",value:e.latestVersion?`v${e.latestVersion}`:"Unknown"},...e.updateMessage?[{label:"Message",value:e.updateMessage}]:[]];break}case"remote-access":{const o=e.tailscaleStatus,a=o?o.installed?o.loggedIn?o.serveEnabled&&o.serveActive?"Active":o.serveEnabled&&!o.serveActive?"Enabled but not active":"Off":"Not connected":"Not installed":"Checking...";if(t="Remote Access",n=[{label:"Status",value:a},{label:"What",value:"Access this control panel from anywhere — your phone, another computer, or while away from home"},{label:"How",value:"Uses Tailscale to create a private, encrypted connection with a trusted HTTPS certificate (no browser warnings)"},{label:"Requires",value:"Tailscale installed on this device and on any device you want to access the control panel from, all logged into the same Tailscale account"},{label:"Internet Access",value:"Enable internet access (globe icon) to make Public Chat reachable from the web"},{label:"Cost",value:"Tailscale is free for personal use (up to 100 devices)"}],o!=null&&o.tailnetUrl){const r=o.tailnetUrl;i=l`
435
+ `}break}case"license":{const o=e.licenseStoredKey?`…${e.licenseStoredKey.slice(-12)}`:"N/A";t="License",n=[{label:"Status",value:e.licenseValid?"Active":"Inactive"},{label:"What",value:"Your Taskmaster license key, tied to this specific device"},{label:"Key",value:o},{label:"Tier",value:e.licenseTier||"Standard"},{label:"Device ID",value:e.licenseDeviceId||"N/A",copyable:!!e.licenseDeviceId}];break}case"whatsapp":{const o=Rt(e),a=o?us(o,e):null;t="WhatsApp",n=[{label:"Status",value:a!=null&&a.connected?"Connected":"Disconnected"},{label:"What",value:"WhatsApp integration — receive and respond to customer messages through WhatsApp"},{label:"How",value:"Links to your WhatsApp account by scanning a QR code, then routes messages to your AI assistant"},{label:"Account",value:(a==null?void 0:a.name)||(a==null?void 0:a.accountId)||"Default"},{label:"Phone",value:((s=a==null?void 0:a.self)==null?void 0:s.e164)||"Not paired"},{label:"Linked",value:a!=null&&a.linked?"Yes":"No"},...a!=null&&a.lastError?[{label:"Last Error",value:ka(a.lastError)}]:[]];break}case"imessage":{const{thisWsOwns:o}=xa(e);t="iMessage",n=[{label:"Status",value:o&&e.imessageConnected?"Connected":"Disconnected"},{label:"What",value:"iMessage integration — communicate with your AI assistant through Apple Messages"},{label:"How",value:"Uses the Mac's built-in Messages app; only one account can own the iMessage channel at a time"},{label:"Assigned To",value:e.imessageOwnerWorkspace??"Not assigned"},{label:"Mode",value:"Self-chat only"},...e.imessageLastError?[{label:"Last Error",value:e.imessageLastError}]:[]];break}case"update":{t="Software Update",n=[{label:"Status",value:e.updateAvailable===null?"Not checked":e.updateAvailable?"Update available":"Up to date"},{label:"What",value:"Checks for new versions of Taskmaster and lets you update from the control panel"},{label:"Current",value:e.currentVersion?`v${e.currentVersion}`:"Unknown"},{label:"Latest",value:e.latestVersion?`v${e.latestVersion}`:"Unknown"},...e.updateMessage?[{label:"Message",value:e.updateMessage}]:[]];break}case"remote-access":{const o=e.tailscaleStatus,a=o?o.installed?o.loggedIn?o.serveEnabled&&o.serveActive?"Active":o.serveEnabled&&!o.serveActive?"Enabled but not active":"Off":"Not connected":"Not installed":"Checking...";if(t="Remote Access",n=[{label:"Status",value:a},{label:"What",value:"Access this control panel from anywhere — your phone, another computer, or while away from home"},{label:"How",value:"Uses Tailscale to create a private, encrypted connection with a trusted HTTPS certificate (no browser warnings)"},{label:"Requires",value:"Tailscale installed on this device and on any device you want to access the control panel from, all logged into the same Tailscale account"},{label:"Internet Access",value:"Enable internet access (globe icon) to make Public Chat reachable from the web"},{label:"Cost",value:"Tailscale is free for personal use (up to 100 devices)"}],o!=null&&o.tailnetUrl){const r=o.tailnetUrl;i=l`
436
436
  ${e.remoteAccessQrDataUrl?l`<div style="text-align: center; padding: 12px 0;">
437
437
  <img src=${e.remoteAccessQrDataUrl} alt="QR code for remote access URL" style="width: 180px; height: 180px; image-rendering: pixelated; border-radius: 8px;" />
438
438
  </div>`:w}
@@ -440,7 +440,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
440
440
  <a href="${r}" target="_blank" rel="noopener"
441
441
  style="color: var(--tasker-link, #60a5fa); font-size: 13px; word-break: break-all;"
442
442
  >${r}</a>
443
- <button class="setup-info-btn" title="Copy URL" @click=${async d=>{const c=d.currentTarget;try{await navigator.clipboard.writeText(r)}catch{const h=document.createElement("textarea");h.value=r,h.style.position="fixed",h.style.opacity="0",document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h)}c.classList.add("copied"),setTimeout(()=>c.classList.remove("copied"),1500)}}>${I.copy}</button>
443
+ <button class="setup-info-btn" title="Copy URL" @click=${async c=>{const d=c.currentTarget;try{await navigator.clipboard.writeText(r)}catch{const h=document.createElement("textarea");h.value=r,h.style.position="fixed",h.style.opacity="0",document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h)}d.classList.add("copied"),setTimeout(()=>d.classList.remove("copied"),1500)}}>${I.copy}</button>
444
444
  </div>
445
445
  `}break}case"public-chat":{if(t="Public Chat",n=[{label:"Status",value:e.publicChatEnabled?"Enabled":"Disabled"},{label:"What",value:"A chat widget anyone can use to message your business from a web browser"},{label:"Requires",value:"Remote Access with internet access enabled — this gives your device a public URL that visitors can reach"},{label:"Access mode",value:Dg[e.publicChatAuthMode]??"Open access"},{label:"WhatsApp",value:"Sends verification codes via WhatsApp. Requires a connected WhatsApp account."},{label:"SMS",value:"Sends verification codes via text message. Uses Brevo — same API key as email. Requires prepaid SMS credits in your Brevo account."},{label:"Email",value:"Sends verification codes via email. Uses Brevo (free, 300 emails/day). Sender address is auto-detected from your verified sender in Brevo."},{label:"Provider",value:"SMS and email both use Brevo — one API key, configured in API Keys above. WhatsApp uses your connected account."}],e.publicChatEnabled&&e.publicChatFullUrl){const o=e.publicChatFullUrl;i=l`
446
446
  ${e.publicChatQrDataUrl?l`<div style="text-align: center; padding: 12px 0;">
@@ -450,7 +450,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
450
450
  <a href="${o}" target="_blank" rel="noopener"
451
451
  style="color: var(--tasker-link, #60a5fa); font-size: 13px; word-break: break-all;"
452
452
  >${o}</a>
453
- <button class="setup-info-btn" title="Copy URL" @click=${async a=>{const r=a.currentTarget;try{await navigator.clipboard.writeText(o)}catch{const d=document.createElement("textarea");d.value=o,d.style.position="fixed",d.style.opacity="0",document.body.appendChild(d),d.select(),document.execCommand("copy"),document.body.removeChild(d)}r.classList.add("copied"),setTimeout(()=>r.classList.remove("copied"),1500)}}>${I.copy}</button>
453
+ <button class="setup-info-btn" title="Copy URL" @click=${async a=>{const r=a.currentTarget;try{await navigator.clipboard.writeText(o)}catch{const c=document.createElement("textarea");c.value=o,c.style.position="fixed",c.style.opacity="0",document.body.appendChild(c),c.select(),document.execCommand("copy"),document.body.removeChild(c)}r.classList.add("copied"),setTimeout(()=>r.classList.remove("copied"),1500)}}>${I.copy}</button>
454
454
  </div>
455
455
  `}break}case"sms-fallback":{t="SMS Fallback",n=[{label:"What",value:"When WhatsApp is not connected, verification codes are sent via SMS instead"},{label:"Provider",value:"Brevo — uses the same API key as email verification"},{label:"When used",value:"Only when a visitor requests phone verification and WhatsApp is unavailable"},{label:"Setup",value:"Add your Brevo API key in API Keys above, then purchase SMS credits in the Brevo dashboard"}];break}case"account-pin":{t="Account PIN",n=[{label:"Status",value:e.accountHasPin?"Set":"Not set"},{label:"What",value:"A numeric PIN that protects this account on the control panel"},{label:"When needed",value:"Required when switching to this account or after the session expires"},{label:"Format",value:"4 to 6 digits"}];break}case"branding":{const o=!!(e.brandAccentColor||e.brandBackgroundColor||e.brandHasLogo);t="Branding",n=[{label:"Status",value:o?"Customised":"Default"},{label:"What",value:"Your business logo and colour scheme, displayed on the control panel and public chat pages"},{label:"Logo",value:"Shown on public chat pages alongside your business name"},{label:"Accent colour",value:"Used for buttons, links, and interactive elements"},{label:"Background tint",value:"A subtle colour wash applied to page and card backgrounds"},{label:"Scope",value:"Each account has its own branding — switch accounts to customise each one separately"}];break}case"api-keys":{const a=e.apiKeyProviders.filter(r=>r.hasKey).length;t="API Keys",n=[{label:"Status",value:a>0?`${a} configured`:"None configured"},{label:"What",value:"API keys let Taskmaster connect to AI providers (Google, OpenAI, etc.) and services (Tavily search, Brave search)"},{label:"Required",value:"At least one AI provider key is needed for the assistant to work"},{label:"Scope",value:"API keys are shared across all accounts on this device"}];break}case"network":{t="Network",n=[{label:"Address",value:e.networkHostname?`${e.networkHostname}.local:${e.networkPort}`:`Port ${e.networkPort}`},{label:"What",value:"The hostname and port this device uses on your local network"},{label:"When to change",value:"If you have multiple devices on the same network, give each a unique hostname and port so they don't conflict"},{label:"After saving",value:"The gateway restarts and your browser redirects to the new address"}];break}default:return w}return l`
456
456
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onInfoModalClose()}}>
@@ -461,6 +461,11 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
461
461
  <div class="setup-info-row">
462
462
  <span class="setup-info-label">${o.label}</span>
463
463
  <span class="setup-info-value">${o.value}</span>
464
+ ${o.copyable?l`<button
465
+ class="setup-info-btn"
466
+ title="Copy ${o.label}"
467
+ @click=${async a=>{const r=a.currentTarget;try{await navigator.clipboard.writeText(o.value),r.textContent="Copied!",setTimeout(()=>{r.textContent="Copy"},1500)}catch{const c=document.createElement("textarea");c.value=o.value,c.style.position="fixed",c.style.opacity="0",document.body.appendChild(c),c.select(),document.execCommand("copy"),document.body.removeChild(c),r.textContent="Copied!",setTimeout(()=>{r.textContent="Copy"},1500)}}}
468
+ >Copy</button>`:w}
464
469
  </div>
465
470
  `)}
466
471
  <button
@@ -518,7 +523,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
518
523
  <button
519
524
  class="setup-device-id-copy"
520
525
  title="Copy Device ID"
521
- @click=${async d=>{const c=d.currentTarget;try{await navigator.clipboard.writeText(o),c.textContent="Copied!",setTimeout(()=>{c.textContent="Copy"},1500)}catch{const h=document.createElement("textarea");h.value=o,h.style.position="fixed",h.style.opacity="0",document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h),c.textContent="Copied!",setTimeout(()=>{c.textContent="Copy"},1500)}}}
526
+ @click=${async c=>{const d=c.currentTarget;try{await navigator.clipboard.writeText(o),d.textContent="Copied!",setTimeout(()=>{d.textContent="Copy"},1500)}catch{const h=document.createElement("textarea");h.value=o,h.style.position="fixed",h.style.opacity="0",document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h),d.textContent="Copied!",setTimeout(()=>{d.textContent="Copy"},1500)}}}
522
527
  >Copy</button>
523
528
  </div>
524
529
  `:w}
@@ -527,8 +532,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
527
532
  type="text"
528
533
  placeholder="Paste your license key here"
529
534
  .value=${t}
530
- @input=${d=>a(d.target.value)}
531
- @keydown=${d=>{d.key==="Enter"&&t.trim()&&r()}}
535
+ @input=${c=>a(c.target.value)}
536
+ @keydown=${c=>{c.key==="Enter"&&t.trim()&&r()}}
532
537
  />
533
538
  <button
534
539
  class="setup-button"
@@ -552,7 +557,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
552
557
  </p>
553
558
  </div>
554
559
  </div>
555
- `}function $g(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:d,onAuthCodeChange:c}=e;return t===!0?l`
560
+ `}function $g(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:c,onAuthCodeChange:d}=e;return t===!0?l`
556
561
  <div class="setup-container">
557
562
  <div class="setup-card setup-success">
558
563
  ${Ee("auth")}
@@ -604,13 +609,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
604
609
  type="text"
605
610
  placeholder="Enter authorization code"
606
611
  .value=${o}
607
- @input=${h=>c(h.target.value)}
608
- @keydown=${h=>{h.key==="Enter"&&o.trim()&&d(o.trim())}}
612
+ @input=${h=>d(h.target.value)}
613
+ @keydown=${h=>{h.key==="Enter"&&o.trim()&&c(o.trim())}}
609
614
  />
610
615
  <button
611
616
  class="setup-button"
612
617
  ?disabled=${!o.trim()||n}
613
- @click=${()=>d(o.trim())}
618
+ @click=${()=>c(o.trim())}
614
619
  >
615
620
  ${n?"Verifying...":"Submit"}
616
621
  </button>
@@ -812,7 +817,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
812
817
  </div>
813
818
  `:w}
814
819
  </div>
815
- `}function ka(e){var t,n;try{const i=JSON.parse(e),s=(i==null?void 0:i.error)??i,o=((n=(t=s==null?void 0:s.output)==null?void 0:t.payload)==null?void 0:n.message)??(s==null?void 0:s.message)??(i==null?void 0:i.message);if(o&&typeof o=="string")return o}catch{}return e.length>80?e.slice(0,77)+"…":e}function Tg(e){var u;const t=Rt(e);if(!t)return w;const n=us(t,e),i=(n==null?void 0:n.running)&&(n==null?void 0:n.connected),s=(n==null?void 0:n.linked)&&!i,o=!!n,a=i?"good":s?"partial":o?"bad":"unknown",r=i?"Connected":s?"Linked, not connected":o?n!=null&&n.lastError?ka(n.lastError):"Not connected":"Not paired",d=!(n!=null&&n.provider)||(n==null?void 0:n.provider)==="baileys",c=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(u=e.whatsappAccounts[0])==null?void 0:u.accountId:void 0),h=c!=null&&e.whatsappActiveQrAccountId===c;return l`
820
+ `}function ka(e){var t,n;try{const i=JSON.parse(e),s=(i==null?void 0:i.error)??i,o=((n=(t=s==null?void 0:s.output)==null?void 0:t.payload)==null?void 0:n.message)??(s==null?void 0:s.message)??(i==null?void 0:i.message);if(o&&typeof o=="string")return o}catch{}return e.length>80?e.slice(0,77)+"…":e}function Tg(e){var u;const t=Rt(e);if(!t)return w;const n=us(t,e),i=(n==null?void 0:n.running)&&(n==null?void 0:n.connected),s=(n==null?void 0:n.linked)&&!i,o=!!n,a=i?"good":s?"partial":o?"bad":"unknown",r=i?"Connected":s?"Linked, not connected":o?n!=null&&n.lastError?ka(n.lastError):"Not connected":"Not paired",c=!(n!=null&&n.provider)||(n==null?void 0:n.provider)==="baileys",d=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(u=e.whatsappAccounts[0])==null?void 0:u.accountId:void 0),h=d!=null&&e.whatsappActiveQrAccountId===d;return l`
816
821
  <div class="setup-status-item" style="flex-wrap: wrap;">
817
822
  ${Q(a)}
818
823
  <div class="setup-status-info">
@@ -825,7 +830,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
825
830
  @click=${e.onWhatsAppSettingsOpen}
826
831
  title="WhatsApp settings"
827
832
  >${I.settings}</button>`:w}
828
- ${d&&c?l`<button
833
+ ${c&&d?l`<button
829
834
  class="setup-status-action"
830
835
  @click=${e.onRefreshStatus}
831
836
  title="Refresh status"
@@ -843,16 +848,16 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
843
848
  </div>
844
849
  `:w}
845
850
  </div>
846
- `}function _g(e){var h,u;if(!e.whatsappSettingsOpen)return w;const t=Rt(e);if(!t)return w;const n=us(t,e);if(!n)return w;const i=n.running&&n.connected,s=!n.provider||n.provider==="baileys",o=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(h=e.whatsappAccounts[0])==null?void 0:h.accountId:void 0),a=()=>e.onWhatsAppSettingsClose(),r="display: flex; justify-content: space-between; font-size: 13px;",d="color: var(--tasker-text-grey);",c="color: var(--tasker-white); text-align: right;";return l`
851
+ `}function _g(e){var h,u;if(!e.whatsappSettingsOpen)return w;const t=Rt(e);if(!t)return w;const n=us(t,e);if(!n)return w;const i=n.running&&n.connected,s=!n.provider||n.provider==="baileys",o=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(h=e.whatsappAccounts[0])==null?void 0:h.accountId:void 0),a=()=>e.onWhatsAppSettingsClose(),r="display: flex; justify-content: space-between; font-size: 13px;",c="color: var(--tasker-text-grey);",d="color: var(--tasker-white); text-align: right;";return l`
847
852
  <div class="setup-info-overlay" @click=${p=>{p.target.classList.contains("setup-info-overlay")&&a()}}>
848
853
  <div class="setup-info-card" style="max-width: 360px;">
849
854
  <h3>WhatsApp</h3>
850
855
  <div style="display: flex; flex-direction: column; gap: 8px; margin-top: 12px;">
851
- <div style="${r}"><span style="${d}">Account</span><span style="${c}">${n.name||n.accountId||"Default"}</span></div>
852
- <div style="${r}"><span style="${d}">Phone</span><span style="${c}">${((u=n.self)==null?void 0:u.e164)||"Not paired"}</span></div>
853
- <div style="${r}"><span style="${d}">Connected</span><span style="${c}">${i?"Yes":"No"}</span></div>
854
- <div style="${r}"><span style="${d}">Linked</span><span style="${c}">${n.linked?"Yes":"No"}</span></div>
855
- ${n.lastError?l`<div style="${r}"><span style="${d}">Error</span><span style="${c}; color: #ef4444;">${ka(n.lastError)}</span></div>`:w}
856
+ <div style="${r}"><span style="${c}">Account</span><span style="${d}">${n.name||n.accountId||"Default"}</span></div>
857
+ <div style="${r}"><span style="${c}">Phone</span><span style="${d}">${((u=n.self)==null?void 0:u.e164)||"Not paired"}</span></div>
858
+ <div style="${r}"><span style="${c}">Connected</span><span style="${d}">${i?"Yes":"No"}</span></div>
859
+ <div style="${r}"><span style="${c}">Linked</span><span style="${d}">${n.linked?"Yes":"No"}</span></div>
860
+ ${n.lastError?l`<div style="${r}"><span style="${c}">Error</span><span style="${d}; color: #ef4444;">${ka(n.lastError)}</span></div>`:w}
856
861
  </div>
857
862
  ${s&&o?l`
858
863
  <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
@@ -1047,29 +1052,29 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1047
1052
  </div>
1048
1053
  </div>
1049
1054
  ${Rg(e)}
1050
- `}function Rg(e){if(!e.apiKeyModalOpen)return w;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,h)=>{const u=h==null?void 0:h.closest(".setup-apikey-input"),p=u==null?void 0:u.querySelector("input"),v=p==null?void 0:p.value.trim();!v||v===n[c]||e.onApiKeySave(c,v)},s=c=>{const h=c.currentTarget,u=h.closest(".setup-apikey-input"),p=u==null?void 0:u.querySelector("input");if(!p)return;const v=p.type==="text";p.type=v?"password":"text",h.classList.toggle("active",!v)},o=(c,h)=>{const u=h.target,p=u.closest(".setup-apikey-input"),v=u.value.trim(),$=v.length>0&&v!==n[c],S=p==null?void 0:p.querySelector(".setup-apikey-save");S&&(S.style.display=$?"":"none");const M=p==null?void 0:p.querySelector(".setup-apikey-eye");M&&(M.style.display=v.length>0?"":"none")},a=t.filter(c=>c.primary),r=t.filter(c=>!c.primary),d=c=>{const h=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,u=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,p=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`,v=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} disabled`,$=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} enabled`;return l`
1051
- <div class="setup-apikey-row ${c.disabled?"disabled":""}">
1055
+ `}function Rg(e){if(!e.apiKeyModalOpen)return w;const t=e.apiKeyProviders,n={};for(const d of t)d.key&&(n[d.id]=d.key);const i=(d,h)=>{const u=h==null?void 0:h.closest(".setup-apikey-input"),p=u==null?void 0:u.querySelector("input"),v=p==null?void 0:p.value.trim();!v||v===n[d]||e.onApiKeySave(d,v)},s=d=>{const h=d.currentTarget,u=h.closest(".setup-apikey-input"),p=u==null?void 0:u.querySelector("input");if(!p)return;const v=p.type==="text";p.type=v?"password":"text",h.classList.toggle("active",!v)},o=(d,h)=>{const u=h.target,p=u.closest(".setup-apikey-input"),v=u.value.trim(),$=v.length>0&&v!==n[d],S=p==null?void 0:p.querySelector(".setup-apikey-save");S&&(S.style.display=$?"":"none");const M=p==null?void 0:p.querySelector(".setup-apikey-eye");M&&(M.style.display=v.length>0?"":"none")},a=t.filter(d=>d.primary),r=t.filter(d=>!d.primary),c=d=>{const h=e.apiKeySavingProvider===d.id&&e.apiKeyBusy,u=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} key saved`,p=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} key removed`,v=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} disabled`,$=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} enabled`;return l`
1056
+ <div class="setup-apikey-row ${d.disabled?"disabled":""}">
1052
1057
  <div class="setup-apikey-info">
1053
- <strong>${c.name}</strong>
1054
- <span class="setup-apikey-category">${c.category}</span>
1058
+ <strong>${d.name}</strong>
1059
+ <span class="setup-apikey-category">${d.category}</span>
1055
1060
  ${u?l`<span class="setup-apikey-badge saved">Saved</span>`:w}
1056
1061
  ${p?l`<span class="setup-apikey-badge removed">Removed</span>`:w}
1057
1062
  ${v?l`<span class="setup-apikey-badge removed">Disabled</span>`:w}
1058
1063
  ${$?l`<span class="setup-apikey-badge saved">Enabled</span>`:w}
1059
- ${c.disabled&&!$?l`<span class="setup-apikey-badge apikey-disabled">Off</span>`:w}
1064
+ ${d.disabled&&!$?l`<span class="setup-apikey-badge apikey-disabled">Off</span>`:w}
1060
1065
  </div>
1061
1066
  <div class="setup-apikey-input">
1062
1067
  <input
1063
1068
  type="password"
1064
- .value=${c.key??""}
1069
+ .value=${d.key??""}
1065
1070
  placeholder="Enter key"
1066
- ?disabled=${e.apiKeyBusy||c.disabled}
1067
- @input=${S=>o(c.id,S)}
1068
- @keydown=${S=>{S.key==="Enter"&&i(c.id,S.target)}}
1071
+ ?disabled=${e.apiKeyBusy||d.disabled}
1072
+ @input=${S=>o(d.id,S)}
1073
+ @keydown=${S=>{S.key==="Enter"&&i(d.id,S.target)}}
1069
1074
  />
1070
1075
  <button
1071
1076
  class="setup-apikey-icon-btn setup-apikey-eye"
1072
- style=${c.hasKey?"":"display: none;"}
1077
+ style=${d.hasKey?"":"display: none;"}
1073
1078
  title="Toggle visibility"
1074
1079
  @click=${s}
1075
1080
  >${I.eye}</button>
@@ -1077,35 +1082,35 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1077
1082
  class="setup-apikey-save setup-button"
1078
1083
  style="display: none;"
1079
1084
  ?disabled=${e.apiKeyBusy}
1080
- @click=${S=>i(c.id,S.currentTarget)}
1085
+ @click=${S=>i(d.id,S.currentTarget)}
1081
1086
  >Save</button>`}
1082
- ${c.hasKey&&!h?l`
1087
+ ${d.hasKey&&!h?l`
1083
1088
  <button
1084
- class="setup-apikey-icon-btn ${c.disabled?"":"active"}"
1085
- title="${c.disabled?"Enable":"Disable"}"
1089
+ class="setup-apikey-icon-btn ${d.disabled?"":"active"}"
1090
+ title="${d.disabled?"Enable":"Disable"}"
1086
1091
  ?disabled=${e.apiKeyBusy}
1087
- @click=${()=>e.onApiKeyDisable(c.id,!c.disabled)}
1092
+ @click=${()=>e.onApiKeyDisable(d.id,!d.disabled)}
1088
1093
  >${I.power}</button>
1089
1094
  <button
1090
1095
  class="setup-apikey-icon-btn danger"
1091
1096
  title="Remove key"
1092
1097
  ?disabled=${e.apiKeyBusy}
1093
- @click=${()=>e.onApiKeyRemove(c.id)}
1098
+ @click=${()=>e.onApiKeyRemove(d.id)}
1094
1099
  >${I.trash}</button>
1095
1100
  `:w}
1096
1101
  </div>
1097
1102
  </div>
1098
1103
  `};return l`
1099
- <div class="setup-info-overlay" style="align-items: flex-start; padding-top: 72px;" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onApiKeyModalClose()}}>
1104
+ <div class="setup-info-overlay" style="align-items: flex-start; padding-top: 72px;" @click=${d=>{d.target.classList.contains("setup-info-overlay")&&e.onApiKeyModalClose()}}>
1100
1105
  <div class="setup-info-card" style="max-width: 480px;">
1101
1106
  <h3 style="margin: 0 0 4px; text-align: center;">API Keys</h3>
1102
1107
  <div class="setup-apikey-list">
1103
1108
  ${e.apiKeyError?l`<p class="setup-error" style="margin: 0;">${e.apiKeyError}</p>`:w}
1104
- ${a.map(d)}
1109
+ ${a.map(c)}
1105
1110
  ${r.length>0?l`
1106
1111
  <details class="setup-apikey-advanced">
1107
1112
  <summary>Additional keys</summary>
1108
- ${r.map(d)}
1113
+ ${r.map(c)}
1109
1114
  </details>
1110
1115
  `:w}
1111
1116
  </div>
@@ -1159,7 +1164,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1159
1164
  @click=${e.onPublicChatToggle}
1160
1165
  >${t?I.powerOff:I.power}</button>
1161
1166
  </div>
1162
- `}function Ng(e){if(!e.publicChatSettingsOpen)return w;const t=()=>e.onPublicChatSettingsClose(),n=!!e.publicChatGreeting,i=e.publicChatAuthMode==="verified"||e.publicChatAuthMode==="choice",s=e.publicChatVerifyMethods.length>0?e.publicChatVerifyMethods:["whatsapp","sms"],o=s.includes("whatsapp"),a=s.includes("sms"),r=s.includes("email"),d=Rt(e),c=d?us(d,e):null,h=!!(c!=null&&c.connected);return l`
1167
+ `}function Ng(e){if(!e.publicChatSettingsOpen)return w;const t=()=>e.onPublicChatSettingsClose(),n=!!e.publicChatGreeting,i=e.publicChatAuthMode==="verified"||e.publicChatAuthMode==="choice",s=e.publicChatVerifyMethods.length>0?e.publicChatVerifyMethods:["whatsapp","sms"],o=s.includes("whatsapp"),a=s.includes("sms"),r=s.includes("email"),c=Rt(e),d=c?us(c,e):null,h=!!(d!=null&&d.connected);return l`
1163
1168
  <div class="setup-info-overlay" @click=${u=>{u.target.classList.contains("setup-info-overlay")&&t()}}>
1164
1169
  <div class="setup-info-card" style="max-width: 380px; max-height: 80vh; overflow-y: auto;">
1165
1170
  <h3 style="margin: 0 0 12px; display: flex; align-items: center; justify-content: space-between;">
@@ -1287,14 +1292,14 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1287
1292
  </div>
1288
1293
  </div>
1289
1294
  </div>
1290
- `}function Og(e){var r,d;if(!e.publicChatWidgetModalOpen)return w;const t=((r=e.tailscaleStatus)==null?void 0:r.publicUrl)??((d=e.tailscaleStatus)==null?void 0:d.tailnetUrl)??null,n=e.publicChatAccountId??"your-account-id",i=t??"https://YOUR-PUBLIC-URL",s=`<script src="${i}/public/widget.js"><\/script>
1295
+ `}function Og(e){var r,c;if(!e.publicChatWidgetModalOpen)return w;const t=((r=e.tailscaleStatus)==null?void 0:r.publicUrl)??((c=e.tailscaleStatus)==null?void 0:c.tailnetUrl)??null,n=e.publicChatAccountId??"your-account-id",i=t??"https://YOUR-PUBLIC-URL",s=`<script src="${i}/public/widget.js"><\/script>
1291
1296
  <script>
1292
1297
  Taskmaster.init({
1293
1298
  server: "${i}",
1294
1299
  accountId: "${n}"
1295
1300
  });
1296
- <\/script>`,o=async c=>{const h=c.currentTarget;try{await navigator.clipboard.writeText(s)}catch{const p=document.createElement("textarea");p.value=s,p.style.position="fixed",p.style.opacity="0",document.body.appendChild(p),p.select(),document.execCommand("copy"),document.body.removeChild(p)}const u=h.textContent;h.textContent="Copied!",setTimeout(()=>{h.textContent=u},1500)},a=()=>{const c=document.createElement("a");c.href="data:text/plain;charset=utf-8,"+encodeURIComponent(s),c.download="taskmaster-widget.txt",c.click()};return l`
1297
- <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onPublicChatWidgetModalClose()}}>
1301
+ <\/script>`,o=async d=>{const h=d.currentTarget;try{await navigator.clipboard.writeText(s)}catch{const p=document.createElement("textarea");p.value=s,p.style.position="fixed",p.style.opacity="0",document.body.appendChild(p),p.select(),document.execCommand("copy"),document.body.removeChild(p)}const u=h.textContent;h.textContent="Copied!",setTimeout(()=>{h.textContent=u},1500)},a=()=>{const d=document.createElement("a");d.href="data:text/plain;charset=utf-8,"+encodeURIComponent(s),d.download="taskmaster-widget.txt",d.click()};return l`
1302
+ <div class="setup-info-overlay" @click=${d=>{d.target.classList.contains("setup-info-overlay")&&e.onPublicChatWidgetModalClose()}}>
1298
1303
  <div class="setup-info-card" style="max-width: 480px; position: relative;">
1299
1304
  <h3 style="margin: 0 0 12px; display: flex; align-items: center; justify-content: space-between;">
1300
1305
  Widget Code Snippet
@@ -1331,10 +1336,10 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1331
1336
  <div class="setup-info-card" style="max-width: 400px;">
1332
1337
  <h3>Agent Settings</h3>
1333
1338
  <div style="display: flex; flex-direction: column; gap: 20px; margin-top: 16px;">
1334
- ${t.map(a=>{const r=a.model??Ug,d=a.thinkingLevel??"off",c=a.id.endsWith("-admin")||a.id==="admin";return l`
1339
+ ${t.map(a=>{const r=a.model??Ug,c=a.thinkingLevel??"off",d=a.id.endsWith("-admin")||a.id==="admin";return l`
1335
1340
  <div style="display: flex; flex-direction: column; gap: 10px;">
1336
1341
  <div style="font-size: 14px; font-weight: 600; color: var(--tasker-white);">
1337
- ${a.label||(c?"Admin":"Public")}
1342
+ ${a.label||(d?"Admin":"Public")}
1338
1343
  </div>
1339
1344
  ${s.length>0?l`
1340
1345
  <div style="display: flex; align-items: center; gap: 8px;">
@@ -1358,11 +1363,11 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1358
1363
  <select
1359
1364
  class="setup-model-select"
1360
1365
  style="flex: 1;"
1361
- .value=${d}
1366
+ .value=${c}
1362
1367
  @change=${h=>{e.onAgentThinkingChange(a.id,h.target.value)}}
1363
1368
  >
1364
1369
  ${Fg.map(h=>l`
1365
- <option value=${h.value} ?selected=${d===h.value}>
1370
+ <option value=${h.value} ?selected=${c===h.value}>
1366
1371
  ${h.label}
1367
1372
  </option>
1368
1373
  `)}
@@ -1449,7 +1454,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1449
1454
  accept="image/png,image/jpeg,image/svg+xml,image/webp"
1450
1455
  style="display: none;"
1451
1456
  ?disabled=${t}
1452
- @change=${o=>{var d;const a=o.target,r=(d=a.files)==null?void 0:d[0];r&&e.onBrandLogoUpload(r),a.value=""}}
1457
+ @change=${o=>{var c;const a=o.target,r=(c=a.files)==null?void 0:c[0];r&&e.onBrandLogoUpload(r),a.value=""}}
1453
1458
  />
1454
1459
  </label>
1455
1460
  </div>
@@ -1813,13 +1818,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1813
1818
 
1814
1819
  ${s&&!i.find(o=>o.ssid===s&&o.active)?l`
1815
1820
  <div style="display: flex; gap: 8px; align-items: center;">
1816
- ${(()=>{const o=i.find(d=>d.ssid===s),a=(o==null?void 0:o.security)!=="Open",r=(t==null?void 0:t.savedSsid)===s;return a&&!r?l`
1821
+ ${(()=>{const o=i.find(c=>c.ssid===s),a=(o==null?void 0:o.security)!=="Open",r=(t==null?void 0:t.savedSsid)===s;return a&&!r?l`
1817
1822
  <input
1818
1823
  type="password"
1819
1824
  placeholder="Password"
1820
1825
  .value=${e.wifiPassword}
1821
- @input=${d=>e.onWifiPasswordChange(d.target.value)}
1822
- @keydown=${d=>{d.key==="Enter"&&e.onWifiConnect()}}
1826
+ @input=${c=>e.onWifiPasswordChange(c.target.value)}
1827
+ @keydown=${c=>{c.key==="Enter"&&e.onWifiConnect()}}
1823
1828
  ?disabled=${n}
1824
1829
  style="
1825
1830
  flex: 1;
@@ -1960,8 +1965,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1960
1965
  ${e.updateMessage?l`<p style="text-align: center; color: var(--tasker-text-grey); font-size: 13px; margin: 12px 0 0;">${e.updateMessage}</p>`:w}
1961
1966
  </div>
1962
1967
  </div>
1963
- `;if(n){const a=n.status==="ok";let r;if(a){const c=(i=n.before)==null?void 0:i.version,h=((s=n.after)==null?void 0:s.version)??n.currentVersion;r=c?`v${c} → v${h}`:`Updated to v${h}`}else r=n.reason??((o=n.failedStep)==null?void 0:o.name)??"unknown error";const d=n.durationMs!=null?Br(n.durationMs):null;return l`
1964
- <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onUpdateDismissResult()}}>
1968
+ `;if(n){const a=n.status==="ok";let r;if(a){const d=(i=n.before)==null?void 0:i.version,h=((s=n.after)==null?void 0:s.version)??n.currentVersion;r=d?`v${d} → v${h}`:`Updated to v${h}`}else r=n.reason??((o=n.failedStep)==null?void 0:o.name)??"unknown error";const c=n.durationMs!=null?Br(n.durationMs):null;return l`
1969
+ <div class="setup-info-overlay" @click=${d=>{d.target.classList.contains("setup-info-overlay")&&e.onUpdateDismissResult()}}>
1965
1970
  <div class="setup-info-card" style="max-width: 360px; text-align: center;">
1966
1971
  <div class="setup-update-result-icon ${a?"ok":"fail"}">${a?I.circleCheck:I.circleX}</div>
1967
1972
  <h3 style="color: ${a?"#22c55e":"#ef4444"};">
@@ -1970,7 +1975,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1970
1975
  <p style="color: var(--tasker-text-grey); font-size: 14px; margin: 8px 0;">
1971
1976
  ${r}
1972
1977
  </p>
1973
- ${d?l`<p style="color: rgba(255,255,255,0.3); font-size: 12px; margin: 4px 0 0;">${d}</p>`:w}
1978
+ ${c?l`<p style="color: rgba(255,255,255,0.3); font-size: 12px; margin: 4px 0 0;">${c}</p>`:w}
1974
1979
  <button
1975
1980
  class="setup-button secondary"
1976
1981
  style="margin-top: 20px; width: 100%; padding: 10px;"
@@ -1993,8 +1998,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1993
1998
  @click=${()=>e.onAccountPinModalOpen()}
1994
1999
  >${t?"Change":"Set PIN"}</button>
1995
2000
  </div>
1996
- `}function Zg(e){if(!e.accountPinModalOpen)return w;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const a=c=>h=>{const u=h.target;u.value=u.value.replace(/\D/g,"").slice(0,6),c(u.value)},r=(c,h)=>{var p;let u=c.querySelector(".pin-modal-validation");u||(u=document.createElement("p"),u.className="login-error pin-modal-validation",(p=c.querySelector("button[type=submit]"))==null||p.before(u)),u.textContent=h},d=c=>{c.preventDefault();const h=c.target;if(!n){if(t&&!i){r(h,"Enter your current PIN");return}if(!s){r(h,"Enter a new PIN");return}if(!o){r(h,"Confirm your new PIN");return}if(s!==o){r(h,"PINs do not match");return}if(s.length<4){r(h,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return l`
1997
- <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onAccountPinModalClose()}}>
2001
+ `}function Zg(e){if(!e.accountPinModalOpen)return w;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const a=d=>h=>{const u=h.target;u.value=u.value.replace(/\D/g,"").slice(0,6),d(u.value)},r=(d,h)=>{var p;let u=d.querySelector(".pin-modal-validation");u||(u=document.createElement("p"),u.className="login-error pin-modal-validation",(p=d.querySelector("button[type=submit]"))==null||p.before(u)),u.textContent=h},c=d=>{d.preventDefault();const h=d.target;if(!n){if(t&&!i){r(h,"Enter your current PIN");return}if(!s){r(h,"Enter a new PIN");return}if(!o){r(h,"Confirm your new PIN");return}if(s!==o){r(h,"PINs do not match");return}if(s.length<4){r(h,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return l`
2002
+ <div class="setup-info-overlay" @click=${d=>{d.target.classList.contains("setup-info-overlay")&&e.onAccountPinModalClose()}}>
1998
2003
  <div class="setup-info-card" style="max-width: 340px;">
1999
2004
  <div class="setup-info-header">
2000
2005
  <h3>${t?"Change Account PIN":"Set Account PIN"}</h3>
@@ -2002,7 +2007,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2002
2007
  ${I.close}
2003
2008
  </button>
2004
2009
  </div>
2005
- <form @submit=${d} style="display: flex; flex-direction: column; gap: 12px; padding: 16px 0 8px;">
2010
+ <form @submit=${c} style="display: flex; flex-direction: column; gap: 12px; padding: 16px 0 8px;">
2006
2011
  ${t?l`
2007
2012
  <input
2008
2013
  class="login-pin-input"
@@ -2013,7 +2018,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2013
2018
  maxlength="6"
2014
2019
  placeholder="Current PIN"
2015
2020
  ?disabled=${n}
2016
- @input=${a(c=>{i=c})}
2021
+ @input=${a(d=>{i=d})}
2017
2022
  autofocus
2018
2023
  />
2019
2024
  `:w}
@@ -2026,7 +2031,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2026
2031
  maxlength="6"
2027
2032
  placeholder="New PIN (4–6 digits)"
2028
2033
  ?disabled=${n}
2029
- @input=${a(c=>{s=c})}
2034
+ @input=${a(d=>{s=d})}
2030
2035
  ${t?w:l`autofocus`}
2031
2036
  />
2032
2037
  <input
@@ -2038,7 +2043,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2038
2043
  maxlength="6"
2039
2044
  placeholder="Confirm PIN"
2040
2045
  ?disabled=${n}
2041
- @input=${a(c=>{o=c})}
2046
+ @input=${a(d=>{o=d})}
2042
2047
  />
2043
2048
  ${e.accountPinError?l`<p class="login-error">${e.accountPinError}</p>`:w}
2044
2049
  ${e.accountPinSuccess?l`<p class="login-success">${e.accountPinSuccess}</p>`:w}
@@ -2050,7 +2055,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2050
2055
  </form>
2051
2056
  </div>
2052
2057
  </div>
2053
- `}function em(e){if(!e.addingWorkspace)return w;const{workspaceSaving:t}=e,n=()=>{e.newWorkspaceName.trim()&&e.newWorkspacePin.match(/^\d{4,6}$/)&&e.onWorkspaceCreate(e.newWorkspaceName,e.newWorkspacePath||void 0)},i=s=>{const o=s.currentTarget,a=o.closest(".login-pin-wrapper"),r=a==null?void 0:a.querySelector("input");if(!r)return;const d=r.type==="text";r.type=d?"password":"text",o.classList.toggle("active",!d)};return l`
2058
+ `}function em(e){if(!e.addingWorkspace)return w;const{workspaceSaving:t}=e,n=()=>{e.newWorkspaceName.trim()&&e.newWorkspacePin.match(/^\d{4,6}$/)&&e.onWorkspaceCreate(e.newWorkspaceName,e.newWorkspacePath||void 0)},i=s=>{const o=s.currentTarget,a=o.closest(".login-pin-wrapper"),r=a==null?void 0:a.querySelector("input");if(!r)return;const c=r.type==="text";r.type=c?"password":"text",o.classList.toggle("active",!c)};return l`
2054
2059
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
2055
2060
  <div class="setup-add-account">
2056
2061
  <strong>New Account</strong>
@@ -2759,47 +2764,47 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2759
2764
 
2760
2765
  ${i?dm(i,e):w}
2761
2766
  ${s?um(s,e):w}
2762
- `}const xd={CHILD:2},$d=e=>(...t)=>({_$litDirective$:e,values:t});let Sd=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:gm}=mp,Nr=e=>e,Or=()=>document.createComment(""),gn=(e,t,n)=>{var o;const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const a=i.insertBefore(Or(),s),r=i.insertBefore(Or(),s);n=new gm(a,r,e,e.options)}else{const a=n._$AB.nextSibling,r=n._$AM,d=r!==e;if(d){let c;(o=n._$AQ)==null||o.call(n,e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==r._$AU&&n._$AP(c)}if(a!==s||d){let c=n._$AA;for(;c!==a;){const h=Nr(c).nextSibling;Nr(i).insertBefore(c,s),c=h}}}return n},ft=(e,t,n=e)=>(e._$AI(t,n),e),mm={},ym=(e,t=mm)=>e._$AH=t,vm=e=>e._$AH,zs=e=>{e._$AR(),e._$AA.remove()};const Fr=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},bm=$d(class extends Sd{constructor(e){if(super(e),e.type!==xd.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 a=0;for(const r of e)s[a]=i?i(r,a):a,o[a]=n(r,a),a++;return{values:o,keys:s}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,i]){const s=vm(e),{values:o,keys:a}=this.dt(t,n,i);if(!Array.isArray(s))return this.ut=a,o;const r=this.ut??(this.ut=[]),d=[];let c,h,u=0,p=s.length-1,v=0,$=o.length-1;for(;u<=p&&v<=$;)if(s[u]===null)u++;else if(s[p]===null)p--;else if(r[u]===a[v])d[v]=ft(s[u],o[v]),u++,v++;else if(r[p]===a[$])d[$]=ft(s[p],o[$]),p--,$--;else if(r[u]===a[$])d[$]=ft(s[u],o[$]),gn(e,d[$+1],s[u]),u++,$--;else if(r[p]===a[v])d[v]=ft(s[p],o[v]),gn(e,s[u],s[p]),p--,v++;else if(c===void 0&&(c=Fr(a,v,$),h=Fr(r,u,p)),c.has(r[u]))if(c.has(r[p])){const S=h.get(a[v]),M=S!==void 0?s[S]:null;if(M===null){const y=gn(e,s[u]);ft(y,o[v]),d[v]=y}else d[v]=ft(M,o[v]),gn(e,s[u],M),s[S]=null;v++}else zs(s[p]),p--;else zs(s[u]),u++;for(;v<=$;){const S=gn(e,d[$+1]);ft(S,o[v]),d[v++]=S}for(;u<=p;){const S=s[u++];S!==null&&zs(S)}return this.ut=a,ym(e,d),rt}});class _o extends Sd{constructor(t){if(super(t),this.it=w,t.type!==xd.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===w||t==null)return this._t=void 0,this.it=t;if(t===rt)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:[]}}}_o.directiveName="unsafeHTML",_o.resultType=1;const Hi=$d(_o);const{entries:Ad,setPrototypeOf:Ur,isFrozen:wm,getPrototypeOf:km,getOwnPropertyDescriptor:xm}=Object;let{freeze:me,seal:xe,create:Mo}=Object,{apply:Po,construct:Io}=typeof Reflect<"u"&&Reflect;me||(me=function(t){return t});xe||(xe=function(t){return t});Po||(Po=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)});Io||(Io=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 hi=ye(Array.prototype.forEach),$m=ye(Array.prototype.lastIndexOf),Wr=ye(Array.prototype.pop),mn=ye(Array.prototype.push),Sm=ye(Array.prototype.splice),Ci=ye(String.prototype.toLowerCase),Hs=ye(String.prototype.toString),qs=ye(String.prototype.match),yn=ye(String.prototype.replace),Am=ye(String.prototype.indexOf),Cm=ye(String.prototype.trim),$e=ye(Object.prototype.hasOwnProperty),fe=ye(RegExp.prototype.test),vn=Em(TypeError);function ye(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 Po(e,t,i)}}function Em(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Io(e,n)}}function K(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ci;Ur&&Ur(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(wm(t)||(t[i]=o),s=o)}e[s]=!0}return e}function Tm(e){for(let t=0;t<e.length;t++)$e(e,t)||(e[t]=null);return e}function De(e){const t=Mo(null);for(const[n,i]of Ad(e))$e(e,n)&&(Array.isArray(i)?t[n]=Tm(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=De(i):t[n]=i);return t}function bn(e,t){for(;e!==null;){const i=xm(e,t);if(i){if(i.get)return ye(i.get);if(typeof i.value=="function")return ye(i.value)}e=km(e)}function n(){return null}return n}const Kr=me(["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"]),js=me(["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=me(["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"]),_m=me(["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"]),Vs=me(["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"]),Mm=me(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),zr=me(["#text"]),Hr=me(["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"]),Qs=me(["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"]),qr=me(["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"]),fi=me(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Pm=xe(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Im=xe(/<%[\w\W]*|[\w\W]*%>/gm),Rm=xe(/\$\{[\w\W]*/gm),Lm=xe(/^data-[\-\w.\u00B7-\uFFFF]+$/),Dm=xe(/^aria-[\-\w]+$/),Cd=xe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Bm=xe(/^(?:\w+script|data):/i),Nm=xe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ed=xe(/^html$/i),Om=xe(/^[a-z][.\w]*(-[.\w]+)+$/i);var jr=Object.freeze({__proto__:null,ARIA_ATTR:Dm,ATTR_WHITESPACE:Nm,CUSTOM_ELEMENT:Om,DATA_ATTR:Lm,DOCTYPE_NAME:Ed,ERB_EXPR:Im,IS_ALLOWED_URI:Cd,IS_SCRIPT_OR_DATA:Bm,MUSTACHE_EXPR:Pm,TMPLIT_EXPR:Rm});const wn={element:1,text:3,progressingInstruction:7,comment:8,document:9},Fm=function(){return typeof window>"u"?null:window},Um=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(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},Gr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Td(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Fm();const t=N=>Td(N);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==wn.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,s=i.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:r,Element:d,NodeFilter:c,NamedNodeMap:h=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:v}=e,$=d.prototype,S=bn($,"cloneNode"),M=bn($,"remove"),y=bn($,"nextSibling"),b=bn($,"childNodes"),k=bn($,"parentNode");if(typeof a=="function"){const N=n.createElement("template");N.content&&N.content.ownerDocument&&(n=N.content.ownerDocument)}let A,E="";const{implementation:T,createNodeIterator:P,createDocumentFragment:D,getElementsByTagName:W}=n,{importNode:z}=i;let H=Gr();t.isSupported=typeof Ad=="function"&&typeof k=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ke,ERB_EXPR:Me,TMPLIT_EXPR:ze,DATA_ATTR:vs,ARIA_ATTR:bs,IS_SCRIPT_OR_DATA:ws,ATTR_WHITESPACE:Qn,CUSTOM_ELEMENT:ks}=jr;let{IS_ALLOWED_URI:Jn}=jr,te=null;const Yn=K({},[...Kr,...js,...Gs,...Vs,...zr]);let ne=null;const Xn=K({},[...Hr,...Qs,...qr,...fi]);let X=Object.seal(Mo(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}})),dt=null,dn=null;const et=Object.seal(Mo(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Zn=!0,C=!0,R=!1,F=!0,U=!1,Z=!0,J=!1,he=!1,tt=!1,Bt=!1,ei=!1,ti=!1,za=!0,Ha=!1;const Fu="user-content-";let xs=!0,un=!1,Nt={},Pe=null;const $s=K({},["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 qa=null;const ja=K({},["audio","video","img","source","image","track"]);let Ss=null;const Ga=K({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ni="http://www.w3.org/1998/Math/MathML",ii="http://www.w3.org/2000/svg",He="http://www.w3.org/1999/xhtml";let Ot=He,As=!1,Cs=null;const Uu=K({},[ni,ii,He],Hs);let si=K({},["mi","mo","mn","ms","mtext"]),oi=K({},["annotation-xml"]);const Wu=K({},["title","style","font","a","script"]);let pn=null;const Ku=["application/xhtml+xml","text/html"],zu="text/html";let oe=null,Ft=null;const Hu=n.createElement("form"),Va=function(x){return x instanceof RegExp||x instanceof Function},Es=function(){let x=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ft&&Ft===x)){if((!x||typeof x!="object")&&(x={}),x=De(x),pn=Ku.indexOf(x.PARSER_MEDIA_TYPE)===-1?zu:x.PARSER_MEDIA_TYPE,oe=pn==="application/xhtml+xml"?Hs:Ci,te=$e(x,"ALLOWED_TAGS")?K({},x.ALLOWED_TAGS,oe):Yn,ne=$e(x,"ALLOWED_ATTR")?K({},x.ALLOWED_ATTR,oe):Xn,Cs=$e(x,"ALLOWED_NAMESPACES")?K({},x.ALLOWED_NAMESPACES,Hs):Uu,Ss=$e(x,"ADD_URI_SAFE_ATTR")?K(De(Ga),x.ADD_URI_SAFE_ATTR,oe):Ga,qa=$e(x,"ADD_DATA_URI_TAGS")?K(De(ja),x.ADD_DATA_URI_TAGS,oe):ja,Pe=$e(x,"FORBID_CONTENTS")?K({},x.FORBID_CONTENTS,oe):$s,dt=$e(x,"FORBID_TAGS")?K({},x.FORBID_TAGS,oe):De({}),dn=$e(x,"FORBID_ATTR")?K({},x.FORBID_ATTR,oe):De({}),Nt=$e(x,"USE_PROFILES")?x.USE_PROFILES:!1,Zn=x.ALLOW_ARIA_ATTR!==!1,C=x.ALLOW_DATA_ATTR!==!1,R=x.ALLOW_UNKNOWN_PROTOCOLS||!1,F=x.ALLOW_SELF_CLOSE_IN_ATTR!==!1,U=x.SAFE_FOR_TEMPLATES||!1,Z=x.SAFE_FOR_XML!==!1,J=x.WHOLE_DOCUMENT||!1,Bt=x.RETURN_DOM||!1,ei=x.RETURN_DOM_FRAGMENT||!1,ti=x.RETURN_TRUSTED_TYPE||!1,tt=x.FORCE_BODY||!1,za=x.SANITIZE_DOM!==!1,Ha=x.SANITIZE_NAMED_PROPS||!1,xs=x.KEEP_CONTENT!==!1,un=x.IN_PLACE||!1,Jn=x.ALLOWED_URI_REGEXP||Cd,Ot=x.NAMESPACE||He,si=x.MATHML_TEXT_INTEGRATION_POINTS||si,oi=x.HTML_INTEGRATION_POINTS||oi,X=x.CUSTOM_ELEMENT_HANDLING||{},x.CUSTOM_ELEMENT_HANDLING&&Va(x.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(X.tagNameCheck=x.CUSTOM_ELEMENT_HANDLING.tagNameCheck),x.CUSTOM_ELEMENT_HANDLING&&Va(x.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(X.attributeNameCheck=x.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),x.CUSTOM_ELEMENT_HANDLING&&typeof x.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(X.allowCustomizedBuiltInElements=x.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),U&&(C=!1),ei&&(Bt=!0),Nt&&(te=K({},zr),ne=[],Nt.html===!0&&(K(te,Kr),K(ne,Hr)),Nt.svg===!0&&(K(te,js),K(ne,Qs),K(ne,fi)),Nt.svgFilters===!0&&(K(te,Gs),K(ne,Qs),K(ne,fi)),Nt.mathMl===!0&&(K(te,Vs),K(ne,qr),K(ne,fi))),x.ADD_TAGS&&(typeof x.ADD_TAGS=="function"?et.tagCheck=x.ADD_TAGS:(te===Yn&&(te=De(te)),K(te,x.ADD_TAGS,oe))),x.ADD_ATTR&&(typeof x.ADD_ATTR=="function"?et.attributeCheck=x.ADD_ATTR:(ne===Xn&&(ne=De(ne)),K(ne,x.ADD_ATTR,oe))),x.ADD_URI_SAFE_ATTR&&K(Ss,x.ADD_URI_SAFE_ATTR,oe),x.FORBID_CONTENTS&&(Pe===$s&&(Pe=De(Pe)),K(Pe,x.FORBID_CONTENTS,oe)),x.ADD_FORBID_CONTENTS&&(Pe===$s&&(Pe=De(Pe)),K(Pe,x.ADD_FORBID_CONTENTS,oe)),xs&&(te["#text"]=!0),J&&K(te,["html","head","body"]),te.table&&(K(te,["tbody"]),delete dt.tbody),x.TRUSTED_TYPES_POLICY){if(typeof x.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof x.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=x.TRUSTED_TYPES_POLICY,E=A.createHTML("")}else A===void 0&&(A=Um(v,s)),A!==null&&typeof E=="string"&&(E=A.createHTML(""));me&&me(x),Ft=x}},Qa=K({},[...js,...Gs,..._m]),Ja=K({},[...Vs,...Mm]),qu=function(x){let _=k(x);(!_||!_.tagName)&&(_={namespaceURI:Ot,tagName:"template"});const B=Ci(x.tagName),Y=Ci(_.tagName);return Cs[x.namespaceURI]?x.namespaceURI===ii?_.namespaceURI===He?B==="svg":_.namespaceURI===ni?B==="svg"&&(Y==="annotation-xml"||si[Y]):!!Qa[B]:x.namespaceURI===ni?_.namespaceURI===He?B==="math":_.namespaceURI===ii?B==="math"&&oi[Y]:!!Ja[B]:x.namespaceURI===He?_.namespaceURI===ii&&!oi[Y]||_.namespaceURI===ni&&!si[Y]?!1:!Ja[B]&&(Wu[B]||!Qa[B]):!!(pn==="application/xhtml+xml"&&Cs[x.namespaceURI]):!1},Ie=function(x){mn(t.removed,{element:x});try{k(x).removeChild(x)}catch{M(x)}},ut=function(x,_){try{mn(t.removed,{attribute:_.getAttributeNode(x),from:_})}catch{mn(t.removed,{attribute:null,from:_})}if(_.removeAttribute(x),x==="is")if(Bt||ei)try{Ie(_)}catch{}else try{_.setAttribute(x,"")}catch{}},Ya=function(x){let _=null,B=null;if(tt)x="<remove></remove>"+x;else{const se=qs(x,/^[\r\n\t ]+/);B=se&&se[0]}pn==="application/xhtml+xml"&&Ot===He&&(x='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+x+"</body></html>");const Y=A?A.createHTML(x):x;if(Ot===He)try{_=new p().parseFromString(Y,pn)}catch{}if(!_||!_.documentElement){_=T.createDocument(Ot,"template",null);try{_.documentElement.innerHTML=As?E:Y}catch{}}const de=_.body||_.documentElement;return x&&B&&de.insertBefore(n.createTextNode(B),de.childNodes[0]||null),Ot===He?W.call(_,J?"html":"body")[0]:J?_.documentElement:de},Xa=function(x){return P.call(x.ownerDocument||x,x,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Ts=function(x){return x instanceof u&&(typeof x.nodeName!="string"||typeof x.textContent!="string"||typeof x.removeChild!="function"||!(x.attributes instanceof h)||typeof x.removeAttribute!="function"||typeof x.setAttribute!="function"||typeof x.namespaceURI!="string"||typeof x.insertBefore!="function"||typeof x.hasChildNodes!="function")},Za=function(x){return typeof r=="function"&&x instanceof r};function qe(N,x,_){hi(N,B=>{B.call(t,x,_,Ft)})}const er=function(x){let _=null;if(qe(H.beforeSanitizeElements,x,null),Ts(x))return Ie(x),!0;const B=oe(x.nodeName);if(qe(H.uponSanitizeElement,x,{tagName:B,allowedTags:te}),Z&&x.hasChildNodes()&&!Za(x.firstElementChild)&&fe(/<[/\w!]/g,x.innerHTML)&&fe(/<[/\w!]/g,x.textContent)||x.nodeType===wn.progressingInstruction||Z&&x.nodeType===wn.comment&&fe(/<[/\w]/g,x.data))return Ie(x),!0;if(!(et.tagCheck instanceof Function&&et.tagCheck(B))&&(!te[B]||dt[B])){if(!dt[B]&&nr(B)&&(X.tagNameCheck instanceof RegExp&&fe(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B)))return!1;if(xs&&!Pe[B]){const Y=k(x)||x.parentNode,de=b(x)||x.childNodes;if(de&&Y){const se=de.length;for(let ve=se-1;ve>=0;--ve){const je=S(de[ve],!0);je.__removalCount=(x.__removalCount||0)+1,Y.insertBefore(je,y(x))}}}return Ie(x),!0}return x instanceof d&&!qu(x)||(B==="noscript"||B==="noembed"||B==="noframes")&&fe(/<\/no(script|embed|frames)/i,x.innerHTML)?(Ie(x),!0):(U&&x.nodeType===wn.text&&(_=x.textContent,hi([ke,Me,ze],Y=>{_=yn(_,Y," ")}),x.textContent!==_&&(mn(t.removed,{element:x.cloneNode()}),x.textContent=_)),qe(H.afterSanitizeElements,x,null),!1)},tr=function(x,_,B){if(za&&(_==="id"||_==="name")&&(B in n||B in Hu))return!1;if(!(C&&!dn[_]&&fe(vs,_))){if(!(Zn&&fe(bs,_))){if(!(et.attributeCheck instanceof Function&&et.attributeCheck(_,x))){if(!ne[_]||dn[_]){if(!(nr(x)&&(X.tagNameCheck instanceof RegExp&&fe(X.tagNameCheck,x)||X.tagNameCheck instanceof Function&&X.tagNameCheck(x))&&(X.attributeNameCheck instanceof RegExp&&fe(X.attributeNameCheck,_)||X.attributeNameCheck instanceof Function&&X.attributeNameCheck(_,x))||_==="is"&&X.allowCustomizedBuiltInElements&&(X.tagNameCheck instanceof RegExp&&fe(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B))))return!1}else if(!Ss[_]){if(!fe(Jn,yn(B,Qn,""))){if(!((_==="src"||_==="xlink:href"||_==="href")&&x!=="script"&&Am(B,"data:")===0&&qa[x])){if(!(R&&!fe(ws,yn(B,Qn,"")))){if(B)return!1}}}}}}}return!0},nr=function(x){return x!=="annotation-xml"&&qs(x,ks)},ir=function(x){qe(H.beforeSanitizeAttributes,x,null);const{attributes:_}=x;if(!_||Ts(x))return;const B={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let Y=_.length;for(;Y--;){const de=_[Y],{name:se,namespaceURI:ve,value:je}=de,Ut=oe(se),_s=je;let le=se==="value"?_s:Cm(_s);if(B.attrName=Ut,B.attrValue=le,B.keepAttr=!0,B.forceKeepAttr=void 0,qe(H.uponSanitizeAttribute,x,B),le=B.attrValue,Ha&&(Ut==="id"||Ut==="name")&&(ut(se,x),le=Fu+le),Z&&fe(/((--!?|])>)|<\/(style|title|textarea)/i,le)){ut(se,x);continue}if(Ut==="attributename"&&qs(le,"href")){ut(se,x);continue}if(B.forceKeepAttr)continue;if(!B.keepAttr){ut(se,x);continue}if(!F&&fe(/\/>/i,le)){ut(se,x);continue}U&&hi([ke,Me,ze],or=>{le=yn(le,or," ")});const sr=oe(x.nodeName);if(!tr(sr,Ut,le)){ut(se,x);continue}if(A&&typeof v=="object"&&typeof v.getAttributeType=="function"&&!ve)switch(v.getAttributeType(sr,Ut)){case"TrustedHTML":{le=A.createHTML(le);break}case"TrustedScriptURL":{le=A.createScriptURL(le);break}}if(le!==_s)try{ve?x.setAttributeNS(ve,se,le):x.setAttribute(se,le),Ts(x)?Ie(x):Wr(t.removed)}catch{ut(se,x)}}qe(H.afterSanitizeAttributes,x,null)},ju=function N(x){let _=null;const B=Xa(x);for(qe(H.beforeSanitizeShadowDOM,x,null);_=B.nextNode();)qe(H.uponSanitizeShadowNode,_,null),er(_),ir(_),_.content instanceof o&&N(_.content);qe(H.afterSanitizeShadowDOM,x,null)};return t.sanitize=function(N){let x=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},_=null,B=null,Y=null,de=null;if(As=!N,As&&(N="<!-->"),typeof N!="string"&&!Za(N))if(typeof N.toString=="function"){if(N=N.toString(),typeof N!="string")throw vn("dirty is not a string, aborting")}else throw vn("toString is not a function");if(!t.isSupported)return N;if(he||Es(x),t.removed=[],typeof N=="string"&&(un=!1),un){if(N.nodeName){const je=oe(N.nodeName);if(!te[je]||dt[je])throw vn("root node is forbidden and cannot be sanitized in-place")}}else if(N instanceof r)_=Ya("<!---->"),B=_.ownerDocument.importNode(N,!0),B.nodeType===wn.element&&B.nodeName==="BODY"||B.nodeName==="HTML"?_=B:_.appendChild(B);else{if(!Bt&&!U&&!J&&N.indexOf("<")===-1)return A&&ti?A.createHTML(N):N;if(_=Ya(N),!_)return Bt?null:ti?E:""}_&&tt&&Ie(_.firstChild);const se=Xa(un?N:_);for(;Y=se.nextNode();)er(Y),ir(Y),Y.content instanceof o&&ju(Y.content);if(un)return N;if(Bt){if(ei)for(de=D.call(_.ownerDocument);_.firstChild;)de.appendChild(_.firstChild);else de=_;return(ne.shadowroot||ne.shadowrootmode)&&(de=z.call(i,de,!0)),de}let ve=J?_.outerHTML:_.innerHTML;return J&&te["!doctype"]&&_.ownerDocument&&_.ownerDocument.doctype&&_.ownerDocument.doctype.name&&fe(Ed,_.ownerDocument.doctype.name)&&(ve="<!DOCTYPE "+_.ownerDocument.doctype.name+`>
2767
+ `}const xd={CHILD:2},$d=e=>(...t)=>({_$litDirective$:e,values:t});let Sd=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:gm}=mp,Nr=e=>e,Or=()=>document.createComment(""),gn=(e,t,n)=>{var o;const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const a=i.insertBefore(Or(),s),r=i.insertBefore(Or(),s);n=new gm(a,r,e,e.options)}else{const a=n._$AB.nextSibling,r=n._$AM,c=r!==e;if(c){let d;(o=n._$AQ)==null||o.call(n,e),n._$AM=e,n._$AP!==void 0&&(d=e._$AU)!==r._$AU&&n._$AP(d)}if(a!==s||c){let d=n._$AA;for(;d!==a;){const h=Nr(d).nextSibling;Nr(i).insertBefore(d,s),d=h}}}return n},ft=(e,t,n=e)=>(e._$AI(t,n),e),mm={},ym=(e,t=mm)=>e._$AH=t,vm=e=>e._$AH,zs=e=>{e._$AR(),e._$AA.remove()};const Fr=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},bm=$d(class extends Sd{constructor(e){if(super(e),e.type!==xd.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 a=0;for(const r of e)s[a]=i?i(r,a):a,o[a]=n(r,a),a++;return{values:o,keys:s}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,i]){const s=vm(e),{values:o,keys:a}=this.dt(t,n,i);if(!Array.isArray(s))return this.ut=a,o;const r=this.ut??(this.ut=[]),c=[];let d,h,u=0,p=s.length-1,v=0,$=o.length-1;for(;u<=p&&v<=$;)if(s[u]===null)u++;else if(s[p]===null)p--;else if(r[u]===a[v])c[v]=ft(s[u],o[v]),u++,v++;else if(r[p]===a[$])c[$]=ft(s[p],o[$]),p--,$--;else if(r[u]===a[$])c[$]=ft(s[u],o[$]),gn(e,c[$+1],s[u]),u++,$--;else if(r[p]===a[v])c[v]=ft(s[p],o[v]),gn(e,s[u],s[p]),p--,v++;else if(d===void 0&&(d=Fr(a,v,$),h=Fr(r,u,p)),d.has(r[u]))if(d.has(r[p])){const S=h.get(a[v]),M=S!==void 0?s[S]:null;if(M===null){const y=gn(e,s[u]);ft(y,o[v]),c[v]=y}else c[v]=ft(M,o[v]),gn(e,s[u],M),s[S]=null;v++}else zs(s[p]),p--;else zs(s[u]),u++;for(;v<=$;){const S=gn(e,c[$+1]);ft(S,o[v]),c[v++]=S}for(;u<=p;){const S=s[u++];S!==null&&zs(S)}return this.ut=a,ym(e,c),rt}});class _o extends Sd{constructor(t){if(super(t),this.it=w,t.type!==xd.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===w||t==null)return this._t=void 0,this.it=t;if(t===rt)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:[]}}}_o.directiveName="unsafeHTML",_o.resultType=1;const Hi=$d(_o);const{entries:Ad,setPrototypeOf:Ur,isFrozen:wm,getPrototypeOf:km,getOwnPropertyDescriptor:xm}=Object;let{freeze:me,seal:xe,create:Mo}=Object,{apply:Po,construct:Io}=typeof Reflect<"u"&&Reflect;me||(me=function(t){return t});xe||(xe=function(t){return t});Po||(Po=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)});Io||(Io=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 hi=ye(Array.prototype.forEach),$m=ye(Array.prototype.lastIndexOf),Wr=ye(Array.prototype.pop),mn=ye(Array.prototype.push),Sm=ye(Array.prototype.splice),Ci=ye(String.prototype.toLowerCase),Hs=ye(String.prototype.toString),qs=ye(String.prototype.match),yn=ye(String.prototype.replace),Am=ye(String.prototype.indexOf),Cm=ye(String.prototype.trim),$e=ye(Object.prototype.hasOwnProperty),fe=ye(RegExp.prototype.test),vn=Em(TypeError);function ye(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 Po(e,t,i)}}function Em(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Io(e,n)}}function K(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ci;Ur&&Ur(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(wm(t)||(t[i]=o),s=o)}e[s]=!0}return e}function Tm(e){for(let t=0;t<e.length;t++)$e(e,t)||(e[t]=null);return e}function De(e){const t=Mo(null);for(const[n,i]of Ad(e))$e(e,n)&&(Array.isArray(i)?t[n]=Tm(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=De(i):t[n]=i);return t}function bn(e,t){for(;e!==null;){const i=xm(e,t);if(i){if(i.get)return ye(i.get);if(typeof i.value=="function")return ye(i.value)}e=km(e)}function n(){return null}return n}const Kr=me(["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"]),js=me(["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=me(["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"]),_m=me(["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"]),Vs=me(["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"]),Mm=me(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),zr=me(["#text"]),Hr=me(["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"]),Qs=me(["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"]),qr=me(["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"]),fi=me(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Pm=xe(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Im=xe(/<%[\w\W]*|[\w\W]*%>/gm),Rm=xe(/\$\{[\w\W]*/gm),Lm=xe(/^data-[\-\w.\u00B7-\uFFFF]+$/),Dm=xe(/^aria-[\-\w]+$/),Cd=xe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Bm=xe(/^(?:\w+script|data):/i),Nm=xe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ed=xe(/^html$/i),Om=xe(/^[a-z][.\w]*(-[.\w]+)+$/i);var jr=Object.freeze({__proto__:null,ARIA_ATTR:Dm,ATTR_WHITESPACE:Nm,CUSTOM_ELEMENT:Om,DATA_ATTR:Lm,DOCTYPE_NAME:Ed,ERB_EXPR:Im,IS_ALLOWED_URI:Cd,IS_SCRIPT_OR_DATA:Bm,MUSTACHE_EXPR:Pm,TMPLIT_EXPR:Rm});const wn={element:1,text:3,progressingInstruction:7,comment:8,document:9},Fm=function(){return typeof window>"u"?null:window},Um=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(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},Gr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Td(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Fm();const t=N=>Td(N);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==wn.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,s=i.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:r,Element:c,NodeFilter:d,NamedNodeMap:h=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:v}=e,$=c.prototype,S=bn($,"cloneNode"),M=bn($,"remove"),y=bn($,"nextSibling"),b=bn($,"childNodes"),k=bn($,"parentNode");if(typeof a=="function"){const N=n.createElement("template");N.content&&N.content.ownerDocument&&(n=N.content.ownerDocument)}let A,E="";const{implementation:T,createNodeIterator:P,createDocumentFragment:D,getElementsByTagName:W}=n,{importNode:z}=i;let H=Gr();t.isSupported=typeof Ad=="function"&&typeof k=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ke,ERB_EXPR:Me,TMPLIT_EXPR:ze,DATA_ATTR:vs,ARIA_ATTR:bs,IS_SCRIPT_OR_DATA:ws,ATTR_WHITESPACE:Qn,CUSTOM_ELEMENT:ks}=jr;let{IS_ALLOWED_URI:Jn}=jr,te=null;const Yn=K({},[...Kr,...js,...Gs,...Vs,...zr]);let ne=null;const Xn=K({},[...Hr,...Qs,...qr,...fi]);let X=Object.seal(Mo(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}})),dt=null,dn=null;const et=Object.seal(Mo(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Zn=!0,C=!0,R=!1,F=!0,U=!1,Z=!0,J=!1,he=!1,tt=!1,Bt=!1,ei=!1,ti=!1,za=!0,Ha=!1;const Fu="user-content-";let xs=!0,un=!1,Nt={},Pe=null;const $s=K({},["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 qa=null;const ja=K({},["audio","video","img","source","image","track"]);let Ss=null;const Ga=K({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ni="http://www.w3.org/1998/Math/MathML",ii="http://www.w3.org/2000/svg",He="http://www.w3.org/1999/xhtml";let Ot=He,As=!1,Cs=null;const Uu=K({},[ni,ii,He],Hs);let si=K({},["mi","mo","mn","ms","mtext"]),oi=K({},["annotation-xml"]);const Wu=K({},["title","style","font","a","script"]);let pn=null;const Ku=["application/xhtml+xml","text/html"],zu="text/html";let oe=null,Ft=null;const Hu=n.createElement("form"),Va=function(x){return x instanceof RegExp||x instanceof Function},Es=function(){let x=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ft&&Ft===x)){if((!x||typeof x!="object")&&(x={}),x=De(x),pn=Ku.indexOf(x.PARSER_MEDIA_TYPE)===-1?zu:x.PARSER_MEDIA_TYPE,oe=pn==="application/xhtml+xml"?Hs:Ci,te=$e(x,"ALLOWED_TAGS")?K({},x.ALLOWED_TAGS,oe):Yn,ne=$e(x,"ALLOWED_ATTR")?K({},x.ALLOWED_ATTR,oe):Xn,Cs=$e(x,"ALLOWED_NAMESPACES")?K({},x.ALLOWED_NAMESPACES,Hs):Uu,Ss=$e(x,"ADD_URI_SAFE_ATTR")?K(De(Ga),x.ADD_URI_SAFE_ATTR,oe):Ga,qa=$e(x,"ADD_DATA_URI_TAGS")?K(De(ja),x.ADD_DATA_URI_TAGS,oe):ja,Pe=$e(x,"FORBID_CONTENTS")?K({},x.FORBID_CONTENTS,oe):$s,dt=$e(x,"FORBID_TAGS")?K({},x.FORBID_TAGS,oe):De({}),dn=$e(x,"FORBID_ATTR")?K({},x.FORBID_ATTR,oe):De({}),Nt=$e(x,"USE_PROFILES")?x.USE_PROFILES:!1,Zn=x.ALLOW_ARIA_ATTR!==!1,C=x.ALLOW_DATA_ATTR!==!1,R=x.ALLOW_UNKNOWN_PROTOCOLS||!1,F=x.ALLOW_SELF_CLOSE_IN_ATTR!==!1,U=x.SAFE_FOR_TEMPLATES||!1,Z=x.SAFE_FOR_XML!==!1,J=x.WHOLE_DOCUMENT||!1,Bt=x.RETURN_DOM||!1,ei=x.RETURN_DOM_FRAGMENT||!1,ti=x.RETURN_TRUSTED_TYPE||!1,tt=x.FORCE_BODY||!1,za=x.SANITIZE_DOM!==!1,Ha=x.SANITIZE_NAMED_PROPS||!1,xs=x.KEEP_CONTENT!==!1,un=x.IN_PLACE||!1,Jn=x.ALLOWED_URI_REGEXP||Cd,Ot=x.NAMESPACE||He,si=x.MATHML_TEXT_INTEGRATION_POINTS||si,oi=x.HTML_INTEGRATION_POINTS||oi,X=x.CUSTOM_ELEMENT_HANDLING||{},x.CUSTOM_ELEMENT_HANDLING&&Va(x.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(X.tagNameCheck=x.CUSTOM_ELEMENT_HANDLING.tagNameCheck),x.CUSTOM_ELEMENT_HANDLING&&Va(x.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(X.attributeNameCheck=x.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),x.CUSTOM_ELEMENT_HANDLING&&typeof x.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(X.allowCustomizedBuiltInElements=x.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),U&&(C=!1),ei&&(Bt=!0),Nt&&(te=K({},zr),ne=[],Nt.html===!0&&(K(te,Kr),K(ne,Hr)),Nt.svg===!0&&(K(te,js),K(ne,Qs),K(ne,fi)),Nt.svgFilters===!0&&(K(te,Gs),K(ne,Qs),K(ne,fi)),Nt.mathMl===!0&&(K(te,Vs),K(ne,qr),K(ne,fi))),x.ADD_TAGS&&(typeof x.ADD_TAGS=="function"?et.tagCheck=x.ADD_TAGS:(te===Yn&&(te=De(te)),K(te,x.ADD_TAGS,oe))),x.ADD_ATTR&&(typeof x.ADD_ATTR=="function"?et.attributeCheck=x.ADD_ATTR:(ne===Xn&&(ne=De(ne)),K(ne,x.ADD_ATTR,oe))),x.ADD_URI_SAFE_ATTR&&K(Ss,x.ADD_URI_SAFE_ATTR,oe),x.FORBID_CONTENTS&&(Pe===$s&&(Pe=De(Pe)),K(Pe,x.FORBID_CONTENTS,oe)),x.ADD_FORBID_CONTENTS&&(Pe===$s&&(Pe=De(Pe)),K(Pe,x.ADD_FORBID_CONTENTS,oe)),xs&&(te["#text"]=!0),J&&K(te,["html","head","body"]),te.table&&(K(te,["tbody"]),delete dt.tbody),x.TRUSTED_TYPES_POLICY){if(typeof x.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof x.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=x.TRUSTED_TYPES_POLICY,E=A.createHTML("")}else A===void 0&&(A=Um(v,s)),A!==null&&typeof E=="string"&&(E=A.createHTML(""));me&&me(x),Ft=x}},Qa=K({},[...js,...Gs,..._m]),Ja=K({},[...Vs,...Mm]),qu=function(x){let _=k(x);(!_||!_.tagName)&&(_={namespaceURI:Ot,tagName:"template"});const B=Ci(x.tagName),Y=Ci(_.tagName);return Cs[x.namespaceURI]?x.namespaceURI===ii?_.namespaceURI===He?B==="svg":_.namespaceURI===ni?B==="svg"&&(Y==="annotation-xml"||si[Y]):!!Qa[B]:x.namespaceURI===ni?_.namespaceURI===He?B==="math":_.namespaceURI===ii?B==="math"&&oi[Y]:!!Ja[B]:x.namespaceURI===He?_.namespaceURI===ii&&!oi[Y]||_.namespaceURI===ni&&!si[Y]?!1:!Ja[B]&&(Wu[B]||!Qa[B]):!!(pn==="application/xhtml+xml"&&Cs[x.namespaceURI]):!1},Ie=function(x){mn(t.removed,{element:x});try{k(x).removeChild(x)}catch{M(x)}},ut=function(x,_){try{mn(t.removed,{attribute:_.getAttributeNode(x),from:_})}catch{mn(t.removed,{attribute:null,from:_})}if(_.removeAttribute(x),x==="is")if(Bt||ei)try{Ie(_)}catch{}else try{_.setAttribute(x,"")}catch{}},Ya=function(x){let _=null,B=null;if(tt)x="<remove></remove>"+x;else{const se=qs(x,/^[\r\n\t ]+/);B=se&&se[0]}pn==="application/xhtml+xml"&&Ot===He&&(x='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+x+"</body></html>");const Y=A?A.createHTML(x):x;if(Ot===He)try{_=new p().parseFromString(Y,pn)}catch{}if(!_||!_.documentElement){_=T.createDocument(Ot,"template",null);try{_.documentElement.innerHTML=As?E:Y}catch{}}const de=_.body||_.documentElement;return x&&B&&de.insertBefore(n.createTextNode(B),de.childNodes[0]||null),Ot===He?W.call(_,J?"html":"body")[0]:J?_.documentElement:de},Xa=function(x){return P.call(x.ownerDocument||x,x,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Ts=function(x){return x instanceof u&&(typeof x.nodeName!="string"||typeof x.textContent!="string"||typeof x.removeChild!="function"||!(x.attributes instanceof h)||typeof x.removeAttribute!="function"||typeof x.setAttribute!="function"||typeof x.namespaceURI!="string"||typeof x.insertBefore!="function"||typeof x.hasChildNodes!="function")},Za=function(x){return typeof r=="function"&&x instanceof r};function qe(N,x,_){hi(N,B=>{B.call(t,x,_,Ft)})}const er=function(x){let _=null;if(qe(H.beforeSanitizeElements,x,null),Ts(x))return Ie(x),!0;const B=oe(x.nodeName);if(qe(H.uponSanitizeElement,x,{tagName:B,allowedTags:te}),Z&&x.hasChildNodes()&&!Za(x.firstElementChild)&&fe(/<[/\w!]/g,x.innerHTML)&&fe(/<[/\w!]/g,x.textContent)||x.nodeType===wn.progressingInstruction||Z&&x.nodeType===wn.comment&&fe(/<[/\w]/g,x.data))return Ie(x),!0;if(!(et.tagCheck instanceof Function&&et.tagCheck(B))&&(!te[B]||dt[B])){if(!dt[B]&&nr(B)&&(X.tagNameCheck instanceof RegExp&&fe(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B)))return!1;if(xs&&!Pe[B]){const Y=k(x)||x.parentNode,de=b(x)||x.childNodes;if(de&&Y){const se=de.length;for(let ve=se-1;ve>=0;--ve){const je=S(de[ve],!0);je.__removalCount=(x.__removalCount||0)+1,Y.insertBefore(je,y(x))}}}return Ie(x),!0}return x instanceof c&&!qu(x)||(B==="noscript"||B==="noembed"||B==="noframes")&&fe(/<\/no(script|embed|frames)/i,x.innerHTML)?(Ie(x),!0):(U&&x.nodeType===wn.text&&(_=x.textContent,hi([ke,Me,ze],Y=>{_=yn(_,Y," ")}),x.textContent!==_&&(mn(t.removed,{element:x.cloneNode()}),x.textContent=_)),qe(H.afterSanitizeElements,x,null),!1)},tr=function(x,_,B){if(za&&(_==="id"||_==="name")&&(B in n||B in Hu))return!1;if(!(C&&!dn[_]&&fe(vs,_))){if(!(Zn&&fe(bs,_))){if(!(et.attributeCheck instanceof Function&&et.attributeCheck(_,x))){if(!ne[_]||dn[_]){if(!(nr(x)&&(X.tagNameCheck instanceof RegExp&&fe(X.tagNameCheck,x)||X.tagNameCheck instanceof Function&&X.tagNameCheck(x))&&(X.attributeNameCheck instanceof RegExp&&fe(X.attributeNameCheck,_)||X.attributeNameCheck instanceof Function&&X.attributeNameCheck(_,x))||_==="is"&&X.allowCustomizedBuiltInElements&&(X.tagNameCheck instanceof RegExp&&fe(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B))))return!1}else if(!Ss[_]){if(!fe(Jn,yn(B,Qn,""))){if(!((_==="src"||_==="xlink:href"||_==="href")&&x!=="script"&&Am(B,"data:")===0&&qa[x])){if(!(R&&!fe(ws,yn(B,Qn,"")))){if(B)return!1}}}}}}}return!0},nr=function(x){return x!=="annotation-xml"&&qs(x,ks)},ir=function(x){qe(H.beforeSanitizeAttributes,x,null);const{attributes:_}=x;if(!_||Ts(x))return;const B={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let Y=_.length;for(;Y--;){const de=_[Y],{name:se,namespaceURI:ve,value:je}=de,Ut=oe(se),_s=je;let le=se==="value"?_s:Cm(_s);if(B.attrName=Ut,B.attrValue=le,B.keepAttr=!0,B.forceKeepAttr=void 0,qe(H.uponSanitizeAttribute,x,B),le=B.attrValue,Ha&&(Ut==="id"||Ut==="name")&&(ut(se,x),le=Fu+le),Z&&fe(/((--!?|])>)|<\/(style|title|textarea)/i,le)){ut(se,x);continue}if(Ut==="attributename"&&qs(le,"href")){ut(se,x);continue}if(B.forceKeepAttr)continue;if(!B.keepAttr){ut(se,x);continue}if(!F&&fe(/\/>/i,le)){ut(se,x);continue}U&&hi([ke,Me,ze],or=>{le=yn(le,or," ")});const sr=oe(x.nodeName);if(!tr(sr,Ut,le)){ut(se,x);continue}if(A&&typeof v=="object"&&typeof v.getAttributeType=="function"&&!ve)switch(v.getAttributeType(sr,Ut)){case"TrustedHTML":{le=A.createHTML(le);break}case"TrustedScriptURL":{le=A.createScriptURL(le);break}}if(le!==_s)try{ve?x.setAttributeNS(ve,se,le):x.setAttribute(se,le),Ts(x)?Ie(x):Wr(t.removed)}catch{ut(se,x)}}qe(H.afterSanitizeAttributes,x,null)},ju=function N(x){let _=null;const B=Xa(x);for(qe(H.beforeSanitizeShadowDOM,x,null);_=B.nextNode();)qe(H.uponSanitizeShadowNode,_,null),er(_),ir(_),_.content instanceof o&&N(_.content);qe(H.afterSanitizeShadowDOM,x,null)};return t.sanitize=function(N){let x=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},_=null,B=null,Y=null,de=null;if(As=!N,As&&(N="<!-->"),typeof N!="string"&&!Za(N))if(typeof N.toString=="function"){if(N=N.toString(),typeof N!="string")throw vn("dirty is not a string, aborting")}else throw vn("toString is not a function");if(!t.isSupported)return N;if(he||Es(x),t.removed=[],typeof N=="string"&&(un=!1),un){if(N.nodeName){const je=oe(N.nodeName);if(!te[je]||dt[je])throw vn("root node is forbidden and cannot be sanitized in-place")}}else if(N instanceof r)_=Ya("<!---->"),B=_.ownerDocument.importNode(N,!0),B.nodeType===wn.element&&B.nodeName==="BODY"||B.nodeName==="HTML"?_=B:_.appendChild(B);else{if(!Bt&&!U&&!J&&N.indexOf("<")===-1)return A&&ti?A.createHTML(N):N;if(_=Ya(N),!_)return Bt?null:ti?E:""}_&&tt&&Ie(_.firstChild);const se=Xa(un?N:_);for(;Y=se.nextNode();)er(Y),ir(Y),Y.content instanceof o&&ju(Y.content);if(un)return N;if(Bt){if(ei)for(de=D.call(_.ownerDocument);_.firstChild;)de.appendChild(_.firstChild);else de=_;return(ne.shadowroot||ne.shadowrootmode)&&(de=z.call(i,de,!0)),de}let ve=J?_.outerHTML:_.innerHTML;return J&&te["!doctype"]&&_.ownerDocument&&_.ownerDocument.doctype&&_.ownerDocument.doctype.name&&fe(Ed,_.ownerDocument.doctype.name)&&(ve="<!DOCTYPE "+_.ownerDocument.doctype.name+`>
2763
2768
  `+ve),U&&hi([ke,Me,ze],je=>{ve=yn(ve,je," ")}),A&&ti?A.createHTML(ve):ve},t.setConfig=function(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Es(N),he=!0},t.clearConfig=function(){Ft=null,he=!1},t.isValidAttribute=function(N,x,_){Ft||Es({});const B=oe(N),Y=oe(x);return tr(B,Y,_)},t.addHook=function(N,x){typeof x=="function"&&mn(H[N],x)},t.removeHook=function(N,x){if(x!==void 0){const _=$m(H[N],x);return _===-1?void 0:Sm(H[N],_,1)[0]}return Wr(H[N])},t.removeHooks=function(N){H[N]=[]},t.removeAllHooks=function(){H=Gr()},t}var Ro=Td();function $a(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Lt=$a();function _d(e){Lt=e}var In={exec:()=>null};function j(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(s,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(ge.caret,"$1"),n=n.replace(s,a),i},getRegex:()=>new RegExp(n,t)};return i}var Wm=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),ge={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")},Km=/^(?:[ \t]*(?:\n|$))+/,zm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Hm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Gn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,qm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Sa=/(?:[*+-]|\d{1,9}[.)])/,Md=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Pd=j(Md).replace(/bull/g,Sa).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(),jm=j(Md).replace(/bull/g,Sa).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(),Aa=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Gm=/^[^\n]+/,Ca=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Vm=j(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ca).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Qm=j(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Sa).getRegex(),ps="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",Ea=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Jm=j("^ {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",Ea).replace("tag",ps).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Id=j(Aa).replace("hr",Gn).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",ps).getRegex(),Ym=j(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Id).getRegex(),Ta={blockquote:Ym,code:zm,def:Vm,fences:Hm,heading:qm,hr:Gn,html:Jm,lheading:Pd,list:Qm,newline:Km,paragraph:Id,table:In,text:Gm},Vr=j("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Gn).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",ps).getRegex(),Xm={...Ta,lheading:jm,table:Vr,paragraph:j(Aa).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Vr).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",ps).getRegex()},Zm={...Ta,html:j(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ea).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:In,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:j(Aa).replace("hr",Gn).replace("heading",` *#{1,6} *[^
2764
- ]`).replace("lheading",Pd).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ey=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ty=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Rd=/^( {2,}|\\)\n(?!\s*$)/,ny=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,hs=/[\p{P}\p{S}]/u,_a=/[\s\p{P}\p{S}]/u,Ld=/[^\s\p{P}\p{S}]/u,iy=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_a).getRegex(),Dd=/(?!~)[\p{P}\p{S}]/u,sy=/(?!~)[\s\p{P}\p{S}]/u,oy=/(?:[^\s\p{P}\p{S}]|~)/u,ay=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Wm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Bd=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,ry=j(Bd,"u").replace(/punct/g,hs).getRegex(),ly=j(Bd,"u").replace(/punct/g,Dd).getRegex(),Nd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",cy=j(Nd,"gu").replace(/notPunctSpace/g,Ld).replace(/punctSpace/g,_a).replace(/punct/g,hs).getRegex(),dy=j(Nd,"gu").replace(/notPunctSpace/g,oy).replace(/punctSpace/g,sy).replace(/punct/g,Dd).getRegex(),uy=j("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ld).replace(/punctSpace/g,_a).replace(/punct/g,hs).getRegex(),py=j(/\\(punct)/,"gu").replace(/punct/g,hs).getRegex(),hy=j(/^<(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(),fy=j(Ea).replace("(?:-->|$)","-->").getRegex(),gy=j("^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",fy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),qi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,my=j(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",qi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Od=j(/^!?\[(label)\]\[(ref)\]/).replace("label",qi).replace("ref",Ca).getRegex(),Fd=j(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ca).getRegex(),yy=j("reflink|nolink(?!\\()","g").replace("reflink",Od).replace("nolink",Fd).getRegex(),Qr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ma={_backpedal:In,anyPunctuation:py,autolink:hy,blockSkip:ay,br:Rd,code:ty,del:In,emStrongLDelim:ry,emStrongRDelimAst:cy,emStrongRDelimUnd:uy,escape:ey,link:my,nolink:Fd,punctuation:iy,reflink:Od,reflinkSearch:yy,tag:gy,text:ny,url:In},vy={...Ma,link:j(/^!?\[(label)\]\((.*?)\)/).replace("label",qi).getRegex(),reflink:j(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",qi).getRegex()},Lo={...Ma,emStrongRDelimAst:dy,emStrongLDelim:ly,url:j(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Qr).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:j(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Qr).getRegex()},by={...Lo,br:j(Rd).replace("{2,}","*").getRegex(),text:j(Lo.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},gi={normal:Ta,gfm:Xm,pedantic:Zm},kn={normal:Ma,gfm:Lo,breaks:by,pedantic:vy},wy={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Jr=e=>wy[e];function Qe(e,t){if(t){if(ge.escapeTest.test(e))return e.replace(ge.escapeReplace,Jr)}else if(ge.escapeTestNoEncode.test(e))return e.replace(ge.escapeReplaceNoEncode,Jr);return e}function Yr(e){try{e=encodeURI(e).replace(ge.percentDecode,"%")}catch{return null}return e}function Xr(e,t){var o;let n=e.replace(ge.findPipe,(a,r,d)=>{let c=!1,h=r;for(;--h>=0&&d[h]==="\\";)c=!c;return c?"|":" |"}),i=n.split(ge.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(ge.slashPipe,"|");return i}function xn(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 ky(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 Zr(e,t,n,i,s){let o=t.href,a=t.title||null,r=e[1].replace(s.other.outputLinkReplace,"$1");i.state.inLink=!0;let d={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:a,text:r,tokens:i.inlineTokens(r)};return i.state.inLink=!1,d}function xy(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2769
+ ]`).replace("lheading",Pd).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ey=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ty=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Rd=/^( {2,}|\\)\n(?!\s*$)/,ny=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,hs=/[\p{P}\p{S}]/u,_a=/[\s\p{P}\p{S}]/u,Ld=/[^\s\p{P}\p{S}]/u,iy=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_a).getRegex(),Dd=/(?!~)[\p{P}\p{S}]/u,sy=/(?!~)[\s\p{P}\p{S}]/u,oy=/(?:[^\s\p{P}\p{S}]|~)/u,ay=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Wm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Bd=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,ry=j(Bd,"u").replace(/punct/g,hs).getRegex(),ly=j(Bd,"u").replace(/punct/g,Dd).getRegex(),Nd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",cy=j(Nd,"gu").replace(/notPunctSpace/g,Ld).replace(/punctSpace/g,_a).replace(/punct/g,hs).getRegex(),dy=j(Nd,"gu").replace(/notPunctSpace/g,oy).replace(/punctSpace/g,sy).replace(/punct/g,Dd).getRegex(),uy=j("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ld).replace(/punctSpace/g,_a).replace(/punct/g,hs).getRegex(),py=j(/\\(punct)/,"gu").replace(/punct/g,hs).getRegex(),hy=j(/^<(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(),fy=j(Ea).replace("(?:-->|$)","-->").getRegex(),gy=j("^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",fy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),qi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,my=j(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",qi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Od=j(/^!?\[(label)\]\[(ref)\]/).replace("label",qi).replace("ref",Ca).getRegex(),Fd=j(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ca).getRegex(),yy=j("reflink|nolink(?!\\()","g").replace("reflink",Od).replace("nolink",Fd).getRegex(),Qr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ma={_backpedal:In,anyPunctuation:py,autolink:hy,blockSkip:ay,br:Rd,code:ty,del:In,emStrongLDelim:ry,emStrongRDelimAst:cy,emStrongRDelimUnd:uy,escape:ey,link:my,nolink:Fd,punctuation:iy,reflink:Od,reflinkSearch:yy,tag:gy,text:ny,url:In},vy={...Ma,link:j(/^!?\[(label)\]\((.*?)\)/).replace("label",qi).getRegex(),reflink:j(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",qi).getRegex()},Lo={...Ma,emStrongRDelimAst:dy,emStrongLDelim:ly,url:j(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Qr).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:j(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Qr).getRegex()},by={...Lo,br:j(Rd).replace("{2,}","*").getRegex(),text:j(Lo.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},gi={normal:Ta,gfm:Xm,pedantic:Zm},kn={normal:Ma,gfm:Lo,breaks:by,pedantic:vy},wy={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Jr=e=>wy[e];function Qe(e,t){if(t){if(ge.escapeTest.test(e))return e.replace(ge.escapeReplace,Jr)}else if(ge.escapeTestNoEncode.test(e))return e.replace(ge.escapeReplaceNoEncode,Jr);return e}function Yr(e){try{e=encodeURI(e).replace(ge.percentDecode,"%")}catch{return null}return e}function Xr(e,t){var o;let n=e.replace(ge.findPipe,(a,r,c)=>{let d=!1,h=r;for(;--h>=0&&c[h]==="\\";)d=!d;return d?"|":" |"}),i=n.split(ge.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(ge.slashPipe,"|");return i}function xn(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 ky(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 Zr(e,t,n,i,s){let o=t.href,a=t.title||null,r=e[1].replace(s.other.outputLinkReplace,"$1");i.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:a,text:r,tokens:i.inlineTokens(r)};return i.state.inLink=!1,c}function xy(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2765
2770
  `).map(o=>{let a=o.match(n.other.beginningSpace);if(a===null)return o;let[r]=a;return r.length>=s.length?o.slice(s.length):o}).join(`
2766
2771
  `)}var ji=class{constructor(e){q(this,"options");q(this,"rules");q(this,"lexer");this.options=e||Lt}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:xn(n,`
2767
2772
  `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=xy(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let i=xn(n,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(n=i.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:xn(t[0],`
2768
2773
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=xn(t[0],`
2769
2774
  `).split(`
2770
- `),i="",s="",o=[];for(;n.length>0;){let a=!1,r=[],d;for(d=0;d<n.length;d++)if(this.rules.other.blockquoteStart.test(n[d]))r.push(n[d]),a=!0;else if(!a)r.push(n[d]);else break;n=n.slice(d);let c=r.join(`
2771
- `),h=c.replace(this.rules.other.blockquoteSetextReplace,`
2775
+ `),i="",s="",o=[];for(;n.length>0;){let a=!1,r=[],c;for(c=0;c<n.length;c++)if(this.rules.other.blockquoteStart.test(n[c]))r.push(n[c]),a=!0;else if(!a)r.push(n[c]);else break;n=n.slice(c);let d=r.join(`
2776
+ `),h=d.replace(this.rules.other.blockquoteSetextReplace,`
2772
2777
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
2773
- ${c}`:c,s=s?`${s}
2778
+ ${d}`:d,s=s?`${s}
2774
2779
  ${h}`:h;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,o,!0),this.lexer.state.top=u,n.length===0)break;let p=o.at(-1);if((p==null?void 0:p.type)==="code")break;if((p==null?void 0:p.type)==="blockquote"){let v=p,$=v.raw+`
2775
2780
  `+n.join(`
2776
2781
  `),S=this.blockquote($);o[o.length-1]=S,i=i.substring(0,i.length-v.raw.length)+S.raw,s=s.substring(0,s.length-v.text.length)+S.text;break}else if((p==null?void 0:p.type)==="list"){let v=p,$=v.raw+`
2777
2782
  `+n.join(`
2778
2783
  `),S=this.list($);o[o.length-1]=S,i=i.substring(0,i.length-p.raw.length)+S.raw,s=s.substring(0,s.length-v.raw.length)+S.raw,n=$.substring(o.at(-1).raw.length).split(`
2779
- `);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,a={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 r=this.rules.other.listItemRegex(s),d=!1;for(;e;){let h=!1,u="",p="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let v=t[2].split(`
2784
+ `);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,a={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 r=this.rules.other.listItemRegex(s),c=!1;for(;e;){let h=!1,u="",p="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let v=t[2].split(`
2780
2785
  `,1)[0].replace(this.rules.other.listReplaceTabs,y=>" ".repeat(3*y.length)),$=e.split(`
2781
2786
  `,1)[0],S=!v.trim(),M=0;if(this.options.pedantic?(M=2,p=v.trimStart()):S?M=t[1].length+1:(M=t[2].search(this.rules.other.nonSpaceChar),M=M>4?1:M,p=v.slice(M),M+=t[1].length),S&&this.rules.other.blankLine.test($)&&(u+=$+`
2782
2787
  `,e=e.substring($.length+1),h=!0),!h){let y=this.rules.other.nextBulletRegex(M),b=this.rules.other.hrRegex(M),k=this.rules.other.fencesBeginRegex(M),A=this.rules.other.headingBeginRegex(M),E=this.rules.other.htmlBeginRegex(M);for(;e;){let T=e.split(`
2783
2788
  `,1)[0],P;if($=T,this.options.pedantic?($=$.replace(this.rules.other.listReplaceNesting," "),P=$):P=$.replace(this.rules.other.tabCharGlobal," "),k.test($)||A.test($)||E.test($)||y.test($)||b.test($))break;if(P.search(this.rules.other.nonSpaceChar)>=M||!$.trim())p+=`
2784
2789
  `+P.slice(M);else{if(S||v.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||k.test(v)||A.test(v)||b.test(v))break;p+=`
2785
2790
  `+$}!S&&!$.trim()&&(S=!0),u+=T+`
2786
- `,e=e.substring(T.length+1),v=P.slice(M)}}a.loose||(d?a.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(d=!0)),a.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),a.raw+=u}let c=a.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;a.raw=a.raw.trimEnd();for(let h of a.items){if(this.lexer.state.top=!1,h.tokens=this.lexer.blockTokens(h.text,[]),h.task){if(h.text=h.text.replace(this.rules.other.listReplaceTask,""),((n=h.tokens[0])==null?void 0:n.type)==="text"||((i=h.tokens[0])==null?void 0:i.type)==="paragraph"){h.tokens[0].raw=h.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),h.tokens[0].text=h.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}}let u=this.rules.other.listTaskCheckbox.exec(h.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};h.checked=p.checked,a.loose?h.tokens[0]&&["paragraph","text"].includes(h.tokens[0].type)&&"tokens"in h.tokens[0]&&h.tokens[0].tokens?(h.tokens[0].raw=p.raw+h.tokens[0].raw,h.tokens[0].text=p.raw+h.tokens[0].text,h.tokens[0].tokens.unshift(p)):h.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):h.tokens.unshift(p)}}if(!a.loose){let u=h.tokens.filter(v=>v.type==="space"),p=u.length>0&&u.some(v=>this.rules.other.anyLine.test(v.raw));a.loose=p}}if(a.loose)for(let h of a.items){h.loose=!0;for(let u of h.tokens)u.type==="text"&&(u.type="paragraph")}return a}}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 a;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Xr(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=(a=t[3])!=null&&a.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
2787
- `):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===i.length){for(let r of i)this.rules.other.tableAlignRight.test(r)?o.align.push("right"):this.rules.other.tableAlignCenter.test(r)?o.align.push("center"):this.rules.other.tableAlignLeft.test(r)?o.align.push("left"):o.align.push(null);for(let r=0;r<n.length;r++)o.header.push({text:n[r],tokens:this.lexer.inline(n[r]),header:!0,align:o.align[r]});for(let r of s)o.rows.push(Xr(r,o.header.length).map((d,c)=>({text:d,tokens:this.lexer.inline(d),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)===`
2788
- `?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=xn(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=ky(t[2],"()");if(o===-2)return;if(o>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,a).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)),Zr(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 Zr(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,a,r=s,d=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(a=[...o].length,i[3]||i[4]){r+=a;continue}else if((i[5]||i[6])&&s%3&&!((s+a)%3)){d+=a;continue}if(r-=a,r>0)continue;a=Math.min(a,a+r+d);let h=[...i[0]][0].length,u=e.slice(0,s+i.index+h+a);if(Math.min(s,a)%2){let v=u.slice(1,-1);return{type:"em",raw:u,text:v,tokens:this.lexer.inlineTokens(v)}}let p=u.slice(2,-2);return{type:"strong",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}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}}}},Ae=class Do{constructor(t){q(this,"tokens");q(this,"options");q(this,"state");q(this,"inlineQueue");q(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Lt,this.options.tokenizer=this.options.tokenizer||new ji,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:ge,block:gi.normal,inline:kn.normal};this.options.pedantic?(n.block=gi.pedantic,n.inline=kn.pedantic):this.options.gfm&&(n.block=gi.gfm,this.options.breaks?n.inline=kn.breaks:n.inline=kn.gfm),this.tokenizer.rules=n}static get rules(){return{block:gi,inline:kn}}static lex(t,n){return new Do(n).lex(t)}static lexInline(t,n){return new Do(n).inlineTokens(t)}lex(t){t=t.replace(ge.carriageReturn,`
2789
- `),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,a;for(this.options.pedantic&&(t=t.replace(ge.tabCharGlobal," ").replace(ge.spaceLine,""));t;){let r;if((o=(s=this.options.extensions)==null?void 0:s.block)!=null&&o.some(c=>(r=c.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let c=n.at(-1);r.raw.length===1&&c!==void 0?c.raw+=`
2790
- `:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.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(`
2791
+ `,e=e.substring(T.length+1),v=P.slice(M)}}a.loose||(c?a.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(c=!0)),a.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),a.raw+=u}let d=a.items.at(-1);if(d)d.raw=d.raw.trimEnd(),d.text=d.text.trimEnd();else return;a.raw=a.raw.trimEnd();for(let h of a.items){if(this.lexer.state.top=!1,h.tokens=this.lexer.blockTokens(h.text,[]),h.task){if(h.text=h.text.replace(this.rules.other.listReplaceTask,""),((n=h.tokens[0])==null?void 0:n.type)==="text"||((i=h.tokens[0])==null?void 0:i.type)==="paragraph"){h.tokens[0].raw=h.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),h.tokens[0].text=h.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}}let u=this.rules.other.listTaskCheckbox.exec(h.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};h.checked=p.checked,a.loose?h.tokens[0]&&["paragraph","text"].includes(h.tokens[0].type)&&"tokens"in h.tokens[0]&&h.tokens[0].tokens?(h.tokens[0].raw=p.raw+h.tokens[0].raw,h.tokens[0].text=p.raw+h.tokens[0].text,h.tokens[0].tokens.unshift(p)):h.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):h.tokens.unshift(p)}}if(!a.loose){let u=h.tokens.filter(v=>v.type==="space"),p=u.length>0&&u.some(v=>this.rules.other.anyLine.test(v.raw));a.loose=p}}if(a.loose)for(let h of a.items){h.loose=!0;for(let u of h.tokens)u.type==="text"&&(u.type="paragraph")}return a}}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 a;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Xr(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=(a=t[3])!=null&&a.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
2792
+ `):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===i.length){for(let r of i)this.rules.other.tableAlignRight.test(r)?o.align.push("right"):this.rules.other.tableAlignCenter.test(r)?o.align.push("center"):this.rules.other.tableAlignLeft.test(r)?o.align.push("left"):o.align.push(null);for(let r=0;r<n.length;r++)o.header.push({text:n[r],tokens:this.lexer.inline(n[r]),header:!0,align:o.align[r]});for(let r of s)o.rows.push(Xr(r,o.header.length).map((c,d)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:o.align[d]})));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)===`
2793
+ `?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=xn(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=ky(t[2],"()");if(o===-2)return;if(o>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,a).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)),Zr(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 Zr(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,a,r=s,c=0,d=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+s);(i=d.exec(t))!=null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o)continue;if(a=[...o].length,i[3]||i[4]){r+=a;continue}else if((i[5]||i[6])&&s%3&&!((s+a)%3)){c+=a;continue}if(r-=a,r>0)continue;a=Math.min(a,a+r+c);let h=[...i[0]][0].length,u=e.slice(0,s+i.index+h+a);if(Math.min(s,a)%2){let v=u.slice(1,-1);return{type:"em",raw:u,text:v,tokens:this.lexer.inlineTokens(v)}}let p=u.slice(2,-2);return{type:"strong",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}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}}}},Ae=class Do{constructor(t){q(this,"tokens");q(this,"options");q(this,"state");q(this,"inlineQueue");q(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Lt,this.options.tokenizer=this.options.tokenizer||new ji,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:ge,block:gi.normal,inline:kn.normal};this.options.pedantic?(n.block=gi.pedantic,n.inline=kn.pedantic):this.options.gfm&&(n.block=gi.gfm,this.options.breaks?n.inline=kn.breaks:n.inline=kn.gfm),this.tokenizer.rules=n}static get rules(){return{block:gi,inline:kn}}static lex(t,n){return new Do(n).lex(t)}static lexInline(t,n){return new Do(n).inlineTokens(t)}lex(t){t=t.replace(ge.carriageReturn,`
2794
+ `),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,a;for(this.options.pedantic&&(t=t.replace(ge.tabCharGlobal," ").replace(ge.spaceLine,""));t;){let r;if((o=(s=this.options.extensions)==null?void 0:s.block)!=null&&o.some(d=>(r=d.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let d=n.at(-1);r.raw.length===1&&d!==void 0?d.raw+=`
2795
+ `:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let d=n.at(-1);(d==null?void 0:d.type)==="paragraph"||(d==null?void 0:d.type)==="text"?(d.raw+=(d.raw.endsWith(`
2791
2796
  `)?"":`
2792
- `)+r.raw,c.text+=`
2793
- `+r.text,this.inlineQueue.at(-1).src=c.text):n.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.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(`
2797
+ `)+r.raw,d.text+=`
2798
+ `+r.text,this.inlineQueue.at(-1).src=d.text):n.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let d=n.at(-1);(d==null?void 0:d.type)==="paragraph"||(d==null?void 0:d.type)==="text"?(d.raw+=(d.raw.endsWith(`
2794
2799
  `)?"":`
2795
- `)+r.raw,c.text+=`
2796
- `+r.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},n.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),n.push(r);continue}let d=t;if((a=this.options.extensions)!=null&&a.startBlock){let c=1/0,h=t.slice(1),u;this.options.extensions.startBlock.forEach(p=>{u=p.call({lexer:this},h),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(d=t.substring(0,c+1))}if(this.state.top&&(r=this.tokenizer.paragraph(d))){let c=n.at(-1);i&&(c==null?void 0:c.type)==="paragraph"?(c.raw+=(c.raw.endsWith(`
2800
+ `)+r.raw,d.text+=`
2801
+ `+r.raw,this.inlineQueue.at(-1).src=d.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},n.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),n.push(r);continue}let c=t;if((a=this.options.extensions)!=null&&a.startBlock){let d=1/0,h=t.slice(1),u;this.options.extensions.startBlock.forEach(p=>{u=p.call({lexer:this},h),typeof u=="number"&&u>=0&&(d=Math.min(d,u))}),d<1/0&&d>=0&&(c=t.substring(0,d+1))}if(this.state.top&&(r=this.tokenizer.paragraph(c))){let d=n.at(-1);i&&(d==null?void 0:d.type)==="paragraph"?(d.raw+=(d.raw.endsWith(`
2797
2802
  `)?"":`
2798
- `)+r.raw,c.text+=`
2799
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(r),i=d.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2803
+ `)+r.raw,d.text+=`
2804
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=d.text):n.push(r),i=c.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let d=n.at(-1);(d==null?void 0:d.type)==="text"?(d.raw+=(d.raw.endsWith(`
2800
2805
  `)?"":`
2801
- `)+r.raw,c.text+=`
2802
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(r);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 d,c,h,u,p;let i=t,s=null;if(this.tokens.links){let v=Object.keys(this.tokens.links);if(v.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)v.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=(d=this.options.hooks)==null?void 0:d.emStrongMask)==null?void 0:c.call({lexer:this},i))??i;let a=!1,r="";for(;t;){a||(r=""),a=!1;let v;if((u=(h=this.options.extensions)==null?void 0:h.inline)!=null&&u.some(S=>(v=S.call({lexer:this},t,n))?(t=t.substring(v.raw.length),n.push(v),!0):!1))continue;if(v=this.tokenizer.escape(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.tag(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.link(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(v.raw.length);let S=n.at(-1);v.type==="text"&&(S==null?void 0:S.type)==="text"?(S.raw+=v.raw,S.text+=v.text):n.push(v);continue}if(v=this.tokenizer.emStrong(t,i,r)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.codespan(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.br(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.del(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.autolink(t)){t=t.substring(v.raw.length),n.push(v);continue}if(!this.state.inLink&&(v=this.tokenizer.url(t))){t=t.substring(v.raw.length),n.push(v);continue}let $=t;if((p=this.options.extensions)!=null&&p.startInline){let S=1/0,M=t.slice(1),y;this.options.extensions.startInline.forEach(b=>{y=b.call({lexer:this},M),typeof y=="number"&&y>=0&&(S=Math.min(S,y))}),S<1/0&&S>=0&&($=t.substring(0,S+1))}if(v=this.tokenizer.inlineText($)){t=t.substring(v.raw.length),v.raw.slice(-1)!=="_"&&(r=v.raw.slice(-1)),a=!0;let S=n.at(-1);(S==null?void 0:S.type)==="text"?(S.raw+=v.raw,S.text+=v.text):n.push(v);continue}if(t){let S="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(S);break}else throw new Error(S)}}return n}},Gi=class{constructor(e){q(this,"options");q(this,"parser");this.options=e||Lt}space(e){return""}code({text:e,lang:t,escaped:n}){var o;let i=(o=(t||"").match(ge.notSpaceStart))==null?void 0:o[0],s=e.replace(ge.endingNewline,"")+`
2806
+ `)+r.raw,d.text+=`
2807
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=d.text):n.push(r);continue}if(t){let d="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var c,d,h,u,p;let i=t,s=null;if(this.tokens.links){let v=Object.keys(this.tokens.links);if(v.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)v.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=((d=(c=this.options.hooks)==null?void 0:c.emStrongMask)==null?void 0:d.call({lexer:this},i))??i;let a=!1,r="";for(;t;){a||(r=""),a=!1;let v;if((u=(h=this.options.extensions)==null?void 0:h.inline)!=null&&u.some(S=>(v=S.call({lexer:this},t,n))?(t=t.substring(v.raw.length),n.push(v),!0):!1))continue;if(v=this.tokenizer.escape(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.tag(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.link(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(v.raw.length);let S=n.at(-1);v.type==="text"&&(S==null?void 0:S.type)==="text"?(S.raw+=v.raw,S.text+=v.text):n.push(v);continue}if(v=this.tokenizer.emStrong(t,i,r)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.codespan(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.br(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.del(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.autolink(t)){t=t.substring(v.raw.length),n.push(v);continue}if(!this.state.inLink&&(v=this.tokenizer.url(t))){t=t.substring(v.raw.length),n.push(v);continue}let $=t;if((p=this.options.extensions)!=null&&p.startInline){let S=1/0,M=t.slice(1),y;this.options.extensions.startInline.forEach(b=>{y=b.call({lexer:this},M),typeof y=="number"&&y>=0&&(S=Math.min(S,y))}),S<1/0&&S>=0&&($=t.substring(0,S+1))}if(v=this.tokenizer.inlineText($)){t=t.substring(v.raw.length),v.raw.slice(-1)!=="_"&&(r=v.raw.slice(-1)),a=!0;let S=n.at(-1);(S==null?void 0:S.type)==="text"?(S.raw+=v.raw,S.text+=v.text):n.push(v);continue}if(t){let S="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(S);break}else throw new Error(S)}}return n}},Gi=class{constructor(e){q(this,"options");q(this,"parser");this.options=e||Lt}space(e){return""}code({text:e,lang:t,escaped:n}){var o;let i=(o=(t||"").match(ge.notSpaceStart))==null?void 0:o[0],s=e.replace(ge.endingNewline,"")+`
2803
2808
  `;return i?'<pre><code class="language-'+Qe(i)+'">'+(n?s:Qe(s,!0))+`</code></pre>
2804
2809
  `:"<pre><code>"+(n?s:Qe(s,!0))+`</code></pre>
2805
2810
  `}blockquote({tokens:e}){return`<blockquote>
@@ -2817,10 +2822,10 @@ ${this.parser.parse(e)}</blockquote>
2817
2822
  `}tablerow({text:e}){return`<tr>
2818
2823
  ${e}</tr>
2819
2824
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
2820
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Qe(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let i=this.parser.parseInline(n),s=Yr(e);if(s===null)return i;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+Qe(t)+'"'),o+=">"+i+"</a>",o}image({href:e,title:t,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let s=Yr(e);if(s===null)return Qe(n);e=s;let o=`<img src="${e}" alt="${n}"`;return t&&(o+=` title="${Qe(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Qe(e.text)}},Pa=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ce=class Bo{constructor(t){q(this,"options");q(this,"renderer");q(this,"textRenderer");this.options=t||Lt,this.options.renderer=this.options.renderer||new Gi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Pa}static parse(t,n){return new Bo(n).parse(t)}static parseInline(t,n){return new Bo(n).parseInline(t)}parse(t){var i,s;let n="";for(let o=0;o<t.length;o++){let a=t[o];if((s=(i=this.options.extensions)==null?void 0:i.renderers)!=null&&s[a.type]){let d=a,c=this.options.extensions.renderers[d.type].call({parser:this},d);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(d.type)){n+=c||"";continue}}let r=a;switch(r.type){case"space":{n+=this.renderer.space(r);break}case"hr":{n+=this.renderer.hr(r);break}case"heading":{n+=this.renderer.heading(r);break}case"code":{n+=this.renderer.code(r);break}case"table":{n+=this.renderer.table(r);break}case"blockquote":{n+=this.renderer.blockquote(r);break}case"list":{n+=this.renderer.list(r);break}case"checkbox":{n+=this.renderer.checkbox(r);break}case"html":{n+=this.renderer.html(r);break}case"def":{n+=this.renderer.def(r);break}case"paragraph":{n+=this.renderer.paragraph(r);break}case"text":{n+=this.renderer.text(r);break}default:{let d='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(d),"";throw new Error(d)}}}return n}parseInline(t,n=this.renderer){var s,o;let i="";for(let a=0;a<t.length;a++){let r=t[a];if((o=(s=this.options.extensions)==null?void 0:s.renderers)!=null&&o[r.type]){let c=this.options.extensions.renderers[r.type].call({parser:this},r);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){i+=c||"";continue}}let d=r;switch(d.type){case"escape":{i+=n.text(d);break}case"html":{i+=n.html(d);break}case"link":{i+=n.link(d);break}case"image":{i+=n.image(d);break}case"checkbox":{i+=n.checkbox(d);break}case"strong":{i+=n.strong(d);break}case"em":{i+=n.em(d);break}case"codespan":{i+=n.codespan(d);break}case"br":{i+=n.br(d);break}case"del":{i+=n.del(d);break}case"text":{i+=n.text(d);break}default:{let c='Token with "'+d.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return i}},$i,An=($i=class{constructor(e){q(this,"options");q(this,"block");this.options=e||Lt}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Ae.lex:Ae.lexInline}provideParser(){return this.block?Ce.parse:Ce.parseInline}},q($i,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),q($i,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),$i),$y=class{constructor(...e){q(this,"defaults",$a());q(this,"options",this.setOptions);q(this,"parse",this.parseMarkdown(!0));q(this,"parseInline",this.parseMarkdown(!1));q(this,"Parser",Ce);q(this,"Renderer",Gi);q(this,"TextRenderer",Pa);q(this,"Lexer",Ae);q(this,"Tokenizer",ji);q(this,"Hooks",An);this.use(...e)}walkTokens(e,t){var i,s;let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let a=o;for(let r of a.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of a.rows)for(let d of r)n=n.concat(this.walkTokens(d.tokens,t));break}case"list":{let a=o;n=n.concat(this.walkTokens(a.items,t));break}default:{let a=o;(s=(i=this.defaults.extensions)==null?void 0:i.childTokens)!=null&&s[a.type]?this.defaults.extensions.childTokens[a.type].forEach(r=>{let d=a[r].flat(1/0);n=n.concat(this.walkTokens(d,t))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let o=t.renderers[s.name];o?t.renderers[s.name]=function(...a){let r=s.renderer.apply(this,a);return r===!1&&(r=o.apply(this,a)),r}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[s.level];o?o.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),i.extensions=t),n.renderer){let s=this.defaults.renderer||new Gi(this.defaults);for(let o in n.renderer){if(!(o in s))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let a=o,r=n.renderer[a],d=s[a];s[a]=(...c)=>{let h=r.apply(s,c);return h===!1&&(h=d.apply(s,c)),h||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new ji(this.defaults);for(let o in n.tokenizer){if(!(o in s))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let a=o,r=n.tokenizer[a],d=s[a];s[a]=(...c)=>{let h=r.apply(s,c);return h===!1&&(h=d.apply(s,c)),h}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new An;for(let o in n.hooks){if(!(o in s))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,r=n.hooks[a],d=s[a];An.passThroughHooks.has(o)?s[a]=c=>{if(this.defaults.async&&An.passThroughHooksRespectAsync.has(o))return(async()=>{let u=await r.call(s,c);return d.call(s,u)})();let h=r.call(s,c);return d.call(s,h)}:s[a]=(...c)=>{if(this.defaults.async)return(async()=>{let u=await r.apply(s,c);return u===!1&&(u=await d.apply(s,c)),u})();let h=r.apply(s,c);return h===!1&&(h=d.apply(s,c)),h}}i.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(a){let r=[];return r.push(o.call(this,a)),s&&(r=r.concat(s.call(this,a))),r}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ae.lex(e,t??this.defaults)}parser(e,t){return Ce.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let i={...n},s={...this.defaults,...i},o=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let a=s.hooks?await s.hooks.preprocess(t):t,r=await(s.hooks?await s.hooks.provideLexer():e?Ae.lex:Ae.lexInline)(a,s),d=s.hooks?await s.hooks.processAllTokens(r):r;s.walkTokens&&await Promise.all(this.walkTokens(d,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser():e?Ce.parse:Ce.parseInline)(d,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(o);try{s.hooks&&(t=s.hooks.preprocess(t));let a=(s.hooks?s.hooks.provideLexer():e?Ae.lex:Ae.lexInline)(t,s);s.hooks&&(a=s.hooks.processAllTokens(a)),s.walkTokens&&this.walkTokens(a,s.walkTokens);let r=(s.hooks?s.hooks.provideParser():e?Ce.parse:Ce.parseInline)(a,s);return s.hooks&&(r=s.hooks.postprocess(r)),r}catch(a){return o(a)}}}onError(e,t){return n=>{if(n.message+=`
2825
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Qe(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let i=this.parser.parseInline(n),s=Yr(e);if(s===null)return i;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+Qe(t)+'"'),o+=">"+i+"</a>",o}image({href:e,title:t,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let s=Yr(e);if(s===null)return Qe(n);e=s;let o=`<img src="${e}" alt="${n}"`;return t&&(o+=` title="${Qe(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Qe(e.text)}},Pa=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ce=class Bo{constructor(t){q(this,"options");q(this,"renderer");q(this,"textRenderer");this.options=t||Lt,this.options.renderer=this.options.renderer||new Gi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Pa}static parse(t,n){return new Bo(n).parse(t)}static parseInline(t,n){return new Bo(n).parseInline(t)}parse(t){var i,s;let n="";for(let o=0;o<t.length;o++){let a=t[o];if((s=(i=this.options.extensions)==null?void 0:i.renderers)!=null&&s[a.type]){let c=a,d=this.options.extensions.renderers[c.type].call({parser:this},c);if(d!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(c.type)){n+=d||"";continue}}let r=a;switch(r.type){case"space":{n+=this.renderer.space(r);break}case"hr":{n+=this.renderer.hr(r);break}case"heading":{n+=this.renderer.heading(r);break}case"code":{n+=this.renderer.code(r);break}case"table":{n+=this.renderer.table(r);break}case"blockquote":{n+=this.renderer.blockquote(r);break}case"list":{n+=this.renderer.list(r);break}case"checkbox":{n+=this.renderer.checkbox(r);break}case"html":{n+=this.renderer.html(r);break}case"def":{n+=this.renderer.def(r);break}case"paragraph":{n+=this.renderer.paragraph(r);break}case"text":{n+=this.renderer.text(r);break}default:{let c='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return n}parseInline(t,n=this.renderer){var s,o;let i="";for(let a=0;a<t.length;a++){let r=t[a];if((o=(s=this.options.extensions)==null?void 0:s.renderers)!=null&&o[r.type]){let d=this.options.extensions.renderers[r.type].call({parser:this},r);if(d!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){i+=d||"";continue}}let c=r;switch(c.type){case"escape":{i+=n.text(c);break}case"html":{i+=n.html(c);break}case"link":{i+=n.link(c);break}case"image":{i+=n.image(c);break}case"checkbox":{i+=n.checkbox(c);break}case"strong":{i+=n.strong(c);break}case"em":{i+=n.em(c);break}case"codespan":{i+=n.codespan(c);break}case"br":{i+=n.br(c);break}case"del":{i+=n.del(c);break}case"text":{i+=n.text(c);break}default:{let d='Token with "'+c.type+'" type was not found.';if(this.options.silent)return console.error(d),"";throw new Error(d)}}}return i}},$i,An=($i=class{constructor(e){q(this,"options");q(this,"block");this.options=e||Lt}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Ae.lex:Ae.lexInline}provideParser(){return this.block?Ce.parse:Ce.parseInline}},q($i,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),q($i,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),$i),$y=class{constructor(...e){q(this,"defaults",$a());q(this,"options",this.setOptions);q(this,"parse",this.parseMarkdown(!0));q(this,"parseInline",this.parseMarkdown(!1));q(this,"Parser",Ce);q(this,"Renderer",Gi);q(this,"TextRenderer",Pa);q(this,"Lexer",Ae);q(this,"Tokenizer",ji);q(this,"Hooks",An);this.use(...e)}walkTokens(e,t){var i,s;let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let a=o;for(let r of a.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of a.rows)for(let c of r)n=n.concat(this.walkTokens(c.tokens,t));break}case"list":{let a=o;n=n.concat(this.walkTokens(a.items,t));break}default:{let a=o;(s=(i=this.defaults.extensions)==null?void 0:i.childTokens)!=null&&s[a.type]?this.defaults.extensions.childTokens[a.type].forEach(r=>{let c=a[r].flat(1/0);n=n.concat(this.walkTokens(c,t))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let o=t.renderers[s.name];o?t.renderers[s.name]=function(...a){let r=s.renderer.apply(this,a);return r===!1&&(r=o.apply(this,a)),r}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[s.level];o?o.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),i.extensions=t),n.renderer){let s=this.defaults.renderer||new Gi(this.defaults);for(let o in n.renderer){if(!(o in s))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let a=o,r=n.renderer[a],c=s[a];s[a]=(...d)=>{let h=r.apply(s,d);return h===!1&&(h=c.apply(s,d)),h||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new ji(this.defaults);for(let o in n.tokenizer){if(!(o in s))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let a=o,r=n.tokenizer[a],c=s[a];s[a]=(...d)=>{let h=r.apply(s,d);return h===!1&&(h=c.apply(s,d)),h}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new An;for(let o in n.hooks){if(!(o in s))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,r=n.hooks[a],c=s[a];An.passThroughHooks.has(o)?s[a]=d=>{if(this.defaults.async&&An.passThroughHooksRespectAsync.has(o))return(async()=>{let u=await r.call(s,d);return c.call(s,u)})();let h=r.call(s,d);return c.call(s,h)}:s[a]=(...d)=>{if(this.defaults.async)return(async()=>{let u=await r.apply(s,d);return u===!1&&(u=await c.apply(s,d)),u})();let h=r.apply(s,d);return h===!1&&(h=c.apply(s,d)),h}}i.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(a){let r=[];return r.push(o.call(this,a)),s&&(r=r.concat(s.call(this,a))),r}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ae.lex(e,t??this.defaults)}parser(e,t){return Ce.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let i={...n},s={...this.defaults,...i},o=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let a=s.hooks?await s.hooks.preprocess(t):t,r=await(s.hooks?await s.hooks.provideLexer():e?Ae.lex:Ae.lexInline)(a,s),c=s.hooks?await s.hooks.processAllTokens(r):r;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let d=await(s.hooks?await s.hooks.provideParser():e?Ce.parse:Ce.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(d):d})().catch(o);try{s.hooks&&(t=s.hooks.preprocess(t));let a=(s.hooks?s.hooks.provideLexer():e?Ae.lex:Ae.lexInline)(t,s);s.hooks&&(a=s.hooks.processAllTokens(a)),s.walkTokens&&this.walkTokens(a,s.walkTokens);let r=(s.hooks?s.hooks.provideParser():e?Ce.parse:Ce.parseInline)(a,s);return s.hooks&&(r=s.hooks.postprocess(r)),r}catch(a){return o(a)}}}onError(e,t){return n=>{if(n.message+=`
2821
2826
  Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Qe(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},_t=new $y;function V(e,t){return _t.parse(e,t)}V.options=V.setOptions=function(e){return _t.setOptions(e),V.defaults=_t.defaults,_d(V.defaults),V};V.getDefaults=$a;V.defaults=Lt;V.use=function(...e){return _t.use(...e),V.defaults=_t.defaults,_d(V.defaults),V};V.walkTokens=function(e,t){return _t.walkTokens(e,t)};V.parseInline=_t.parseInline;V.Parser=Ce;V.parser=Ce.parse;V.Renderer=Gi;V.TextRenderer=Pa;V.Lexer=Ae;V.lexer=Ae.lex;V.Tokenizer=ji;V.Hooks=An;V.parse=V;V.options;V.setOptions;V.use;V.walkTokens;V.parseInline;Ce.parse;Ae.lex;V.setOptions({gfm:!0,breaks:!0,mangle:!1});const el=["a","b","blockquote","br","code","del","em","h1","h2","h3","h4","hr","i","li","ol","p","pre","strong","table","tbody","td","th","thead","tr","ul"],tl=["class","href","rel","target","title","start"];let nl=!1;const Sy=14e4,Ay=4e4,Cy=200,Js=5e4,bt=new Map;function Ey(e){const t=bt.get(e);return t===void 0?null:(bt.delete(e),bt.set(e,t),t)}function il(e,t){if(bt.set(e,t),bt.size<=Cy)return;const n=bt.keys().next().value;n&&bt.delete(n)}function Ty(){nl||(nl=!0,Ro.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function Vi(e){const t=e.trim();if(!t)return"";if(Ty(),t.length<=Js){const a=Ey(t);if(a!==null)return a}const n=Xl(t,Sy),i=n.truncated?`
2822
2827
 
2823
- … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>Ay){const r=`<pre class="code-block">${_y(`${n.text}${i}`)}</pre>`,d=Ro.sanitize(r,{ALLOWED_TAGS:el,ALLOWED_ATTR:tl});return t.length<=Js&&il(t,d),d}const s=V.parse(`${n.text}${i}`),o=Ro.sanitize(s,{ALLOWED_TAGS:el,ALLOWED_ATTR:tl});return t.length<=Js&&il(t,o),o}function _y(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const My=1500,Py=2e3,Ud="Copy as markdown",Iy="Copied",Ry="Copy failed";async function Ly(e){if(!e)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return!1}}}function mi(e,t){e.title=t,e.setAttribute("aria-label",t)}function Dy(e){const t=e.label??Ud;return l`
2828
+ … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>Ay){const r=`<pre class="code-block">${_y(`${n.text}${i}`)}</pre>`,c=Ro.sanitize(r,{ALLOWED_TAGS:el,ALLOWED_ATTR:tl});return t.length<=Js&&il(t,c),c}const s=V.parse(`${n.text}${i}`),o=Ro.sanitize(s,{ALLOWED_TAGS:el,ALLOWED_ATTR:tl});return t.length<=Js&&il(t,o),o}function _y(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const My=1500,Py=2e3,Ud="Copy as markdown",Iy="Copied",Ry="Copy failed";async function Ly(e){if(!e)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return!1}}}function mi(e,t){e.title=t,e.setAttribute("aria-label",t)}function Dy(e){const t=e.label??Ud;return l`
2824
2829
  <button
2825
2830
  class="chat-copy-btn"
2826
2831
  type="button"
@@ -2833,7 +2838,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2833
2838
  <span class="chat-copy-btn__icon-check">${I.check}</span>
2834
2839
  </span>
2835
2840
  </button>
2836
- `}function By(e){return Dy({text:()=>e,label:Ud})}function Ny(e){const t=e,n=Oy(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:Fy(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=Uy(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(ic(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=Zl(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function Oy(e){return Array.isArray(e)?e.filter(Boolean):[]}function Fy(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 Uy(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const Ys=40,Xs=new Map;async function Wy(e){const t=Xs.get(e);if(t)return t;try{const n=new(window.AudioContext||window.webkitAudioContext),s=await(await fetch(e)).arrayBuffer(),a=(await n.decodeAudioData(s)).getChannelData(0),r=Math.floor(a.length/Ys),d=[];for(let u=0;u<Ys;u++){let p=0;const v=u*r,$=Math.min(v+r,a.length);for(let S=v;S<$;S++){const M=Math.abs(a[S]);M>p&&(p=M)}d.push(p)}const c=Math.max(...d,.01),h=d.map(u=>Math.max(u/c,.08));return Xs.set(e,h),n.close(),h}catch{const n=Array.from(e).reduce((s,o)=>(s<<5)-s+o.charCodeAt(0)|0,0),i=[];for(let s=0;s<Ys;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return Xs.set(e,i),i}}const Zs=[1,1.5,2],Qi=new Map;function Ky(e){let t=Qi.get(e);if(t)return t;const n=new Audio;return n.preload="metadata",n.src=e,t={audio:n,playing:!1,currentTime:0,duration:0,speed:1,waveform:[]},Qi.set(e,t),Wy(e).then(i=>{t.waveform=i,Wd(e)}),t}const Rn="http://www.w3.org/2000/svg";function zy(){const e=document.createElementNS(Rn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Rn,"polygon");return t.setAttribute("points","6,3 20,12 6,21"),e.appendChild(t),e}function Hy(){const e=document.createElementNS(Rn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Rn,"rect");t.setAttribute("x","5"),t.setAttribute("y","3"),t.setAttribute("width","4"),t.setAttribute("height","18"),t.setAttribute("rx","1");const n=document.createElementNS(Rn,"rect");return n.setAttribute("x","15"),n.setAttribute("y","3"),n.setAttribute("width","4"),n.setAttribute("height","18"),n.setAttribute("rx","1"),e.append(t,n),e}function Ht(e){return document.querySelector(`.vnp[data-url="${CSS.escape(e)}"]`)}function Wd(e){const t=Ht(e);if(!t)return;const n=Qi.get(e);if(!n||n.waveform.length===0)return;const i=t.querySelector(".vnp__waveform");if(i){if(i.children.length===0){const s=document.createDocumentFragment();for(const o of n.waveform){const a=document.createElement("span");a.className="vnp__bar",a.style.height=`${Math.round(o*100)}%`,s.appendChild(a)}i.appendChild(s)}Ln(t,n)}}function Ln(e,t){const n=t.duration>0?t.currentTime/t.duration:0,i=e.querySelectorAll(".vnp__bar"),s=i.length;i.forEach((a,r)=>{a.classList.toggle("vnp__bar--active",r/s<n)});const o=e.querySelector(".vnp__time");o&&(o.textContent=t.playing||t.currentTime>0?Ji(t.currentTime):Ji(t.duration))}function eo(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?Hy():zy();i?n.replaceChild(s,i):n.appendChild(s)}function Ji(e){if(!isFinite(e)||e<0)return"0:00";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const sl=new Set;function qy(e){if(sl.has(e))return;sl.add(e);const t=Qi.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=Ht(e);i&&Ln(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=Ht(e);i&&Ln(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=Ht(e);i&&(Ln(i,t),eo(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=Ht(e);i&&eo(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=Ht(e);i&&eo(i,!0)})}function jy(e,t){const n=Ky(e);qy(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const d=Zs.indexOf(n.speed),c=Zs[(d+1)%Zs.length];n.speed=c,n.audio.playbackRate=c;const h=r.target.closest(".vnp__speed");h&&(h.textContent=`${c}×`)},o=r=>{r.stopPropagation();const d=r.target.closest(".vnp__waveform");if(!d)return;const c=d.getBoundingClientRect(),h=Math.max(0,Math.min(1,(r.clientX-c.left)/c.width));if(n.duration>0){n.audio.currentTime=h*n.duration,n.currentTime=n.audio.currentTime;const u=d.closest(".vnp");u&&Ln(u,n)}},a=n.playing||n.currentTime>0?Ji(n.currentTime):Ji(n.duration);return queueMicrotask(()=>Wd(e)),l`
2841
+ `}function By(e){return Dy({text:()=>e,label:Ud})}function Ny(e){const t=e,n=Oy(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:Fy(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=Uy(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(ic(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=Zl(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function Oy(e){return Array.isArray(e)?e.filter(Boolean):[]}function Fy(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 Uy(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const Ys=40,Xs=new Map;async function Wy(e){const t=Xs.get(e);if(t)return t;try{const n=new(window.AudioContext||window.webkitAudioContext),s=await(await fetch(e)).arrayBuffer(),a=(await n.decodeAudioData(s)).getChannelData(0),r=Math.floor(a.length/Ys),c=[];for(let u=0;u<Ys;u++){let p=0;const v=u*r,$=Math.min(v+r,a.length);for(let S=v;S<$;S++){const M=Math.abs(a[S]);M>p&&(p=M)}c.push(p)}const d=Math.max(...c,.01),h=c.map(u=>Math.max(u/d,.08));return Xs.set(e,h),n.close(),h}catch{const n=Array.from(e).reduce((s,o)=>(s<<5)-s+o.charCodeAt(0)|0,0),i=[];for(let s=0;s<Ys;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return Xs.set(e,i),i}}const Zs=[1,1.5,2],Qi=new Map;function Ky(e){let t=Qi.get(e);if(t)return t;const n=new Audio;return n.preload="metadata",n.src=e,t={audio:n,playing:!1,currentTime:0,duration:0,speed:1,waveform:[]},Qi.set(e,t),Wy(e).then(i=>{t.waveform=i,Wd(e)}),t}const Rn="http://www.w3.org/2000/svg";function zy(){const e=document.createElementNS(Rn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Rn,"polygon");return t.setAttribute("points","6,3 20,12 6,21"),e.appendChild(t),e}function Hy(){const e=document.createElementNS(Rn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Rn,"rect");t.setAttribute("x","5"),t.setAttribute("y","3"),t.setAttribute("width","4"),t.setAttribute("height","18"),t.setAttribute("rx","1");const n=document.createElementNS(Rn,"rect");return n.setAttribute("x","15"),n.setAttribute("y","3"),n.setAttribute("width","4"),n.setAttribute("height","18"),n.setAttribute("rx","1"),e.append(t,n),e}function Ht(e){return document.querySelector(`.vnp[data-url="${CSS.escape(e)}"]`)}function Wd(e){const t=Ht(e);if(!t)return;const n=Qi.get(e);if(!n||n.waveform.length===0)return;const i=t.querySelector(".vnp__waveform");if(i){if(i.children.length===0){const s=document.createDocumentFragment();for(const o of n.waveform){const a=document.createElement("span");a.className="vnp__bar",a.style.height=`${Math.round(o*100)}%`,s.appendChild(a)}i.appendChild(s)}Ln(t,n)}}function Ln(e,t){const n=t.duration>0?t.currentTime/t.duration:0,i=e.querySelectorAll(".vnp__bar"),s=i.length;i.forEach((a,r)=>{a.classList.toggle("vnp__bar--active",r/s<n)});const o=e.querySelector(".vnp__time");o&&(o.textContent=t.playing||t.currentTime>0?Ji(t.currentTime):Ji(t.duration))}function eo(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?Hy():zy();i?n.replaceChild(s,i):n.appendChild(s)}function Ji(e){if(!isFinite(e)||e<0)return"0:00";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const sl=new Set;function qy(e){if(sl.has(e))return;sl.add(e);const t=Qi.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=Ht(e);i&&Ln(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=Ht(e);i&&Ln(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=Ht(e);i&&(Ln(i,t),eo(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=Ht(e);i&&eo(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=Ht(e);i&&eo(i,!0)})}function jy(e,t){const n=Ky(e);qy(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const c=Zs.indexOf(n.speed),d=Zs[(c+1)%Zs.length];n.speed=d,n.audio.playbackRate=d;const h=r.target.closest(".vnp__speed");h&&(h.textContent=`${d}×`)},o=r=>{r.stopPropagation();const c=r.target.closest(".vnp__waveform");if(!c)return;const d=c.getBoundingClientRect(),h=Math.max(0,Math.min(1,(r.clientX-d.left)/d.width));if(n.duration>0){n.audio.currentTime=h*n.duration,n.currentTime=n.audio.currentTime;const u=c.closest(".vnp");u&&Ln(u,n)}},a=n.playing||n.currentTime>0?Ji(n.currentTime):Ji(n.duration);return queueMicrotask(()=>Wd(e)),l`
2837
2842
  <div class="vnp" data-url=${e} @click=${r=>r.stopPropagation()}>
2838
2843
  <button class="vnp__play" @click=${i} aria-label=${n.playing?"Pause":"Play"}>
2839
2844
  ${n.playing?Vy():Gy()}
@@ -2849,7 +2854,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2849
2854
  </div>
2850
2855
  </div>
2851
2856
  </div>
2852
- `}function Gy(){return l`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function Vy(){return l`<svg viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="3" width="4" height="18" rx="1"/><rect x="15" y="3" width="4" height="18" rx="1"/></svg>`}function Qy(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 a=o;if(a.type==="image")if(((s=a.source)==null?void 0:s.type)==="base64"){const r=a.source,d=r.data,c=r.media_type||"image/png",h=d.startsWith("data:")?d:`data:${c};base64,${d}`;i.push({url:h})}else if(typeof a.data=="string"&&a.data){const r=a.data,d=a.mimeType||a.media_type||"image/png",c=r.startsWith("data:")?r:`data:${d};base64,${r}`;i.push({url:c})}else typeof a.url=="string"&&i.push({url:a.url});else if(a.type==="image_url"){const r=a.image_url;typeof(r==null?void 0:r.url)=="string"&&i.push({url:r.url})}}return i}function Jy(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 Yy(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Xy(e){return l`
2857
+ `}function Gy(){return l`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function Vy(){return l`<svg viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="3" width="4" height="18" rx="1"/><rect x="15" y="3" width="4" height="18" rx="1"/></svg>`}function Qy(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 a=o;if(a.type==="image")if(((s=a.source)==null?void 0:s.type)==="base64"){const r=a.source,c=r.data,d=r.media_type||"image/png",h=c.startsWith("data:")?c:`data:${d};base64,${c}`;i.push({url:h})}else if(typeof a.data=="string"&&a.data){const r=a.data,c=a.mimeType||a.media_type||"image/png",d=r.startsWith("data:")?r:`data:${c};base64,${r}`;i.push({url:d})}else typeof a.url=="string"&&i.push({url:a.url});else if(a.type==="image_url"){const r=a.image_url;typeof(r==null?void 0:r.url)=="string"&&i.push({url:r.url})}}return i}function Jy(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 Yy(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Xy(e){return l`
2853
2858
  <div class="chat-group assistant">
2854
2859
  <div class="chat-group-messages">
2855
2860
  <div class="chat-bubble chat-reading-indicator" aria-hidden="true">
@@ -2897,7 +2902,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2897
2902
  <div class="chat-message-files">
2898
2903
  ${e.map(t=>t.mimeType==="application/pdf"?ov(t):t.mimeType.startsWith("audio/")?jy(t.url,t.name):av(t))}
2899
2904
  </div>
2900
- `}function sv(e,t){const n=document.createElement("div");n.className="chat-pdf-modal-overlay";const i=document.createElement("div");i.className="chat-pdf-modal";const s=document.createElement("div");s.className="chat-pdf-modal__header";const o=document.createElement("span");o.className="chat-pdf-modal__title",o.textContent=t;const a=document.createElement("a");a.className="chat-pdf-modal__open",a.href=e,a.target="_blank",a.rel="noreferrer noopener",a.textContent="Open in new tab";const r=document.createElement("button");r.className="chat-pdf-modal__close",r.setAttribute("aria-label","Close");const d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox","0 0 24 24");const c=document.createElementNS("http://www.w3.org/2000/svg","line");c.setAttribute("x1","18"),c.setAttribute("y1","6"),c.setAttribute("x2","6"),c.setAttribute("y2","18");const h=document.createElementNS("http://www.w3.org/2000/svg","line");h.setAttribute("x1","6"),h.setAttribute("y1","6"),h.setAttribute("x2","18"),h.setAttribute("y2","18"),d.append(c,h),r.appendChild(d),s.append(o,a,r);const u=document.createElement("iframe");u.className="chat-pdf-modal__frame",u.src=e,u.title=t,i.append(s,u),n.appendChild(i),n.addEventListener("click",p=>{p.target===n&&n.remove()}),r.addEventListener("click",()=>n.remove()),document.body.appendChild(n)}function ov(e){return l`
2905
+ `}function sv(e,t){const n=document.createElement("div");n.className="chat-pdf-modal-overlay";const i=document.createElement("div");i.className="chat-pdf-modal";const s=document.createElement("div");s.className="chat-pdf-modal__header";const o=document.createElement("span");o.className="chat-pdf-modal__title",o.textContent=t;const a=document.createElement("a");a.className="chat-pdf-modal__open",a.href=e,a.target="_blank",a.rel="noreferrer noopener",a.textContent="Open in new tab";const r=document.createElement("button");r.className="chat-pdf-modal__close",r.setAttribute("aria-label","Close");const c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("viewBox","0 0 24 24");const d=document.createElementNS("http://www.w3.org/2000/svg","line");d.setAttribute("x1","18"),d.setAttribute("y1","6"),d.setAttribute("x2","6"),d.setAttribute("y2","18");const h=document.createElementNS("http://www.w3.org/2000/svg","line");h.setAttribute("x1","6"),h.setAttribute("y1","6"),h.setAttribute("x2","18"),h.setAttribute("y2","18"),c.append(d,h),r.appendChild(c),s.append(o,a,r);const u=document.createElement("iframe");u.className="chat-pdf-modal__frame",u.src=e,u.title=t,i.append(s,u),n.appendChild(i),n.addEventListener("click",p=>{p.target===n&&n.remove()}),r.addEventListener("click",()=>n.remove()),document.body.appendChild(n)}function ov(e){return l`
2901
2906
  <div class="chat-pdf-preview" @click=${()=>sv(e.url,e.name)}>
2902
2907
  <iframe
2903
2908
  src=${e.url}
@@ -2922,15 +2927,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2922
2927
  <span class="chat-file-card__icon">${Yy(e.mimeType)}</span>
2923
2928
  <span class="chat-file-card__name">${e.name}</span>
2924
2929
  </a>
2925
- `}function Kd(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=ic(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=Ny(e).length>0,d=Qy(e),c=d.length>0,h=Jy(e),u=h.length>0,p=Zl(e),v=t.showReasoning&&s==="assistant"?Wp(e):null,$=p!=null&&p.trim()?p:null,S=v?zp(v):null,M=$,y=(s==="assistant"||s==="user")&&!!(M!=null&&M.trim()),b=["chat-bubble",y?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!M&&(r||o)||!M&&!c&&!u?w:l`
2930
+ `}function Kd(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=ic(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=Ny(e).length>0,c=Qy(e),d=c.length>0,h=Jy(e),u=h.length>0,p=Zl(e),v=t.showReasoning&&s==="assistant"?Wp(e):null,$=p!=null&&p.trim()?p:null,S=v?zp(v):null,M=$,y=(s==="assistant"||s==="user")&&!!(M!=null&&M.trim()),b=["chat-bubble",y?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!M&&(r||o)||!M&&!d&&!u?w:l`
2926
2931
  <div class="${b}">
2927
2932
  ${y?By(M):w}
2928
- ${nv(d)}
2933
+ ${nv(c)}
2929
2934
  ${iv(h)}
2930
2935
  ${S?l`<div class="chat-thinking">${Hi(Vi(S))}</div>`:w}
2931
2936
  ${M?l`<div class="chat-text">${Hi(Vi(M))}</div>`:w}
2932
2937
  </div>
2933
- `}const O={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let G=null,xt=null,$t=!1;function ol(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}function mt(){if(O.timerId&&(clearInterval(O.timerId),O.timerId=null),O.stream){for(const e of O.stream.getTracks())e.stop();O.stream=null}xt&&(clearTimeout(xt),xt=null),Yi(),O.mediaRecorder=null,O.audioChunks=[],O.active=!1,O.cancelled=!1,$t=!1}async function zd(e){var t;try{if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))return console.warn("[voice] getUserMedia unavailable (requires secure context)"),mt(),!1;const n=await navigator.mediaDevices.getUserMedia({audio:!0});O.stream=n;const i=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"",s=i?new MediaRecorder(n,{mimeType:i}):new MediaRecorder(n);return O.mediaRecorder=s,O.audioChunks=[],O.mode=e,O.startTime=Date.now(),O.elapsed=0,O.active=!0,O.cancelled=!1,s.ondataavailable=o=>{o.data.size>0&&O.audioChunks.push(o.data)},s.onstop=()=>{if(O.cancelled){mt(),G==null||G.onRequestRender();return}const o=new Blob(O.audioChunks,{type:s.mimeType});if(o.size===0){mt(),G==null||G.onRequestRender();return}const a=new FileReader;a.onload=()=>{const r=a.result,d=s.mimeType.includes("mp4")?"m4a":"webm",c={id:as(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${d}`};mt(),G==null||G.onSend(c),G==null||G.onRequestRender()},a.onerror=()=>{mt(),G==null||G.onRequestRender()},a.readAsDataURL(o)},s.start(250),O.timerId=setInterval(()=>{O.elapsed=Math.floor((Date.now()-O.startTime)/1e3),G==null||G.onRequestRender()},1e3),G==null||G.onRequestRender(),!0}catch(n){return console.warn("[voice] startRecording failed:",n),mt(),!1}}function Hd(){!O.active||!O.mediaRecorder||(O.cancelled=!1,O.mediaRecorder.state==="recording"&&O.mediaRecorder.stop())}function qd(){!O.active||!O.mediaRecorder||(O.cancelled=!0,O.mediaRecorder.state==="recording"?O.mediaRecorder.stop():(mt(),G==null||G.onRequestRender()))}function rv(){document.addEventListener("pointerup",jd)}function Yi(){document.removeEventListener("pointerup",jd)}function jd(e){if(!$t&&!O.active){Yi();return}if($t=!1,Yi(),xt&&(clearTimeout(xt),xt=null,!O.active)){zd("tap");return}O.active&&O.mode==="hold"&&(O.cancelled?qd():Hd()),e.preventDefault()}function lv(e){O.active||($t=!0,O.startX=e.clientX,rv(),xt=setTimeout(async()=>{if(!$t)return;await zd("hold")||($t=!1,Yi())},300))}function al(e){if(!O.active||O.mode!=="hold"||!$t)return;const t=O.startX-e.clientX;t>80?(O.cancelled=!0,G==null||G.onRequestRender()):O.cancelled&&t<=60&&(O.cancelled=!1,G==null||G.onRequestRender())}function cv(){return O.active}function dv(e){G=e}function uv(e){return l`
2938
+ `}const O={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let G=null,xt=null,$t=!1;function ol(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}function mt(){if(O.timerId&&(clearInterval(O.timerId),O.timerId=null),O.stream){for(const e of O.stream.getTracks())e.stop();O.stream=null}xt&&(clearTimeout(xt),xt=null),Yi(),O.mediaRecorder=null,O.audioChunks=[],O.active=!1,O.cancelled=!1,$t=!1}async function zd(e){var t;try{if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))return console.warn("[voice] getUserMedia unavailable (requires secure context)"),mt(),!1;const n=await navigator.mediaDevices.getUserMedia({audio:!0});O.stream=n;const i=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"",s=i?new MediaRecorder(n,{mimeType:i}):new MediaRecorder(n);return O.mediaRecorder=s,O.audioChunks=[],O.mode=e,O.startTime=Date.now(),O.elapsed=0,O.active=!0,O.cancelled=!1,s.ondataavailable=o=>{o.data.size>0&&O.audioChunks.push(o.data)},s.onstop=()=>{if(O.cancelled){mt(),G==null||G.onRequestRender();return}const o=new Blob(O.audioChunks,{type:s.mimeType});if(o.size===0){mt(),G==null||G.onRequestRender();return}const a=new FileReader;a.onload=()=>{const r=a.result,c=s.mimeType.includes("mp4")?"m4a":"webm",d={id:as(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${c}`};mt(),G==null||G.onSend(d),G==null||G.onRequestRender()},a.onerror=()=>{mt(),G==null||G.onRequestRender()},a.readAsDataURL(o)},s.start(250),O.timerId=setInterval(()=>{O.elapsed=Math.floor((Date.now()-O.startTime)/1e3),G==null||G.onRequestRender()},1e3),G==null||G.onRequestRender(),!0}catch(n){return console.warn("[voice] startRecording failed:",n),mt(),!1}}function Hd(){!O.active||!O.mediaRecorder||(O.cancelled=!1,O.mediaRecorder.state==="recording"&&O.mediaRecorder.stop())}function qd(){!O.active||!O.mediaRecorder||(O.cancelled=!0,O.mediaRecorder.state==="recording"?O.mediaRecorder.stop():(mt(),G==null||G.onRequestRender()))}function rv(){document.addEventListener("pointerup",jd)}function Yi(){document.removeEventListener("pointerup",jd)}function jd(e){if(!$t&&!O.active){Yi();return}if($t=!1,Yi(),xt&&(clearTimeout(xt),xt=null,!O.active)){zd("tap");return}O.active&&O.mode==="hold"&&(O.cancelled?qd():Hd()),e.preventDefault()}function lv(e){O.active||($t=!0,O.startX=e.clientX,rv(),xt=setTimeout(async()=>{if(!$t)return;await zd("hold")||($t=!1,Yi())},300))}function al(e){if(!O.active||O.mode!=="hold"||!$t)return;const t=O.startX-e.clientX;t>80?(O.cancelled=!0,G==null||G.onRequestRender()):O.cancelled&&t<=60&&(O.cancelled=!1,G==null||G.onRequestRender())}function cv(){return O.active}function dv(e){G=e}function uv(e){return l`
2934
2939
  <button
2935
2940
  class="btn btn--icon chat-compose__mic"
2936
2941
  ?disabled=${!e}
@@ -3016,13 +3021,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3016
3021
  :host(.dragging) {
3017
3022
  background: var(--accent, #007bff);
3018
3023
  }
3019
- `;fs([ss({type:Number})],Yt.prototype,"splitRatio",2);fs([ss({type:Number})],Yt.prototype,"minRatio",2);fs([ss({type:Number})],Yt.prototype,"maxRatio",2);Yt=fs([ql("resizable-divider")],Yt);function yi(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function to(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const mv=1,yv=1,Dt="emoji",Xt="keyvalue",Ia="favorites",vv="tokens",Gd="tokens",bv="unicode",Vd="count",wv="group",kv="order",Qd="group-order",No="eTag",Xi="url",rl="skinTone",ln="readonly",Ra="readwrite",Jd="skinUnicodes",xv="skinUnicodes",$v="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Sv="en";function Av(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 ll(e){return Av(e,t=>t.unicode)}function Cv(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[a,[r,d]]of Object.entries(s))o.createIndex(a,r,{multiEntry:d});return o}t(Xt),t(Dt,bv,{[Gd]:[vv,!0],[Qd]:[[wv,kv]],[Jd]:[xv,!0]}),t(Ia,void 0,{[Vd]:[""]})}const Oo={},Ei={},Zi={};function Yd(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function Ev(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,mv);Oo[e]=s,s.onupgradeneeded=o=>{o.oldVersion<yv&&Cv(s.result)},Yd(n,i,s)});return t.onclose=()=>La(e),t}function Tv(e){return Ei[e]||(Ei[e]=Ev(e)),Ei[e]}function Ze(e,t,n,i){return new Promise((s,o)=>{const a=e.transaction(t,n,{durability:"relaxed"}),r=typeof t=="string"?a.objectStore(t):t.map(c=>a.objectStore(c));let d;i(r,a,c=>{d=c}),a.oncomplete=()=>s(d),a.onerror=()=>o(a.error)})}function La(e){const t=Oo[e],n=t&&t.result;if(n){n.close();const i=Zi[e];if(i)for(const s of i)s()}delete Oo[e],delete Ei[e],delete Zi[e]}function _v(e){return new Promise((t,n)=>{La(e);const i=indexedDB.deleteDatabase(e);Yd(t,n,i)})}function Mv(e,t){let n=Zi[e];n||(n=Zi[e]=[]),n.push(t)}const Pv=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 Vt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||Pv.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const Iv=2;function Xd(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=Iv)}function Rv(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:d,emoji:c,version:h})=>{const u=[...new Set(Xd([...(a||[]).map(Vt).flat(),...(d||[]).map(Vt).flat(),...Vt(n),i]))].sort(),p={annotation:n,group:s,order:o,tags:d,tokens:u,unicode:c,version:h};if(i&&(p.emoticon=i),a&&(p.shortcodes=a),r){p.skinTones=[],p.skinUnicodes=[],p.skinVersions=[];for(const{tone:v,emoji:$,version:S}of r)p.skinTones.push(v),p.skinUnicodes.push($),p.skinVersions.push(S)}return p})}function Zd(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function Mt(e,t,n){Zd(e,"get",t,n)}function eu(e,t,n){Zd(e,"getAll",t,n)}function Da(e){e.commit&&e.commit()}function Lv(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 tu(e,t){const n=Lv(e,s=>s.length),i=[];for(const s of n)e.some(o=>o.findIndex(a=>t(a)===t(s))===-1)||i.push(s);return i}async function Dv(e){return!await Ba(e,Xt,Xi)}async function Bv(e,t,n){const[i,s]=await Promise.all([No,Xi].map(o=>Ba(e,Xt,o)));return i===n&&s===t}async function Nv(e,t){return Ze(e,Dt,ln,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=d=>{const c=d.target.result;for(const h of c)if(a=h.unicode,t(h))return o(h);if(c.length<50)return o();r()}};r()})}async function nu(e,t,n,i){{const s=Rv(t);await Ze(e,[Dt,Xt],Ra,([o,a],r)=>{let d,c,h=0;function u(){++h===2&&p()}function p(){if(!(d===i&&c===n)){o.clear();for(const v of s)o.put(v);a.put(i,No),a.put(n,Xi),Da(r)}}Mt(a,No,v=>{d=v,u()}),Mt(a,Xi,v=>{c=v,u()})})}}async function Ov(e,t){return Ze(e,Dt,ln,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);eu(n.index(Qd),o,s)})}async function iu(e,t){const n=Xd(Vt(t));return n.length?Ze(e,Dt,ln,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&d()},d=()=>{const c=tu(a,h=>h.unicode);o(c.sort((h,u)=>h.order<u.order?-1:1))};for(let c=0;c<n.length;c++){const h=n[c],u=c===n.length-1?IDBKeyRange.bound(h,h+"￿",!1,!0):IDBKeyRange.only(h);eu(i.index(Gd),u,p=>{a.push(p),r()})}}):[]}async function Fv(e,t){const n=await iu(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await Nv(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function Uv(e,t){return Ze(e,Dt,ln,(n,i,s)=>Mt(n,t,o=>{if(o)return s(o);Mt(n.index(Jd),t,a=>s(a||null))}))}function Ba(e,t,n){return Ze(e,t,ln,(i,s,o)=>Mt(i,n,o))}function Wv(e,t,n,i){return Ze(e,t,Ra,(s,o)=>{s.put(i,n),Da(o)})}function Kv(e,t){return Ze(e,Ia,Ra,(n,i)=>Mt(n,t,s=>{n.put((s||0)+1,t),Da(i)}))}function zv(e,t,n){return n===0?[]:Ze(e,[Ia,Dt],ln,([i,s],o,a)=>{const r=[];i.index(Vd).openCursor(void 0,"prev").onsuccess=d=>{const c=d.target.result;if(!c)return a(r);function h(v){if(r.push(v),r.length===n)return a(r);c.continue()}const u=c.primaryKey,p=t.byName(u);if(p)return h(p);Mt(s,u,v=>{if(v)return h(v);c.continue()})}})}const vi="";function Hv(e,t){const n=new Map;for(const s of e){const o=t(s);for(const a of o){let r=n;for(let c=0;c<a.length;c++){const h=a.charAt(c);let u=r.get(h);u||(u=new Map,r.set(h,u)),r=u}let d=r.get(vi);d||(d=[],r.set(vi,d)),d.push(s)}}return(s,o)=>{let a=n;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=a.get(h);if(u)a=u;else return[]}if(o)return a.get(vi)||[];const r=[],d=[a];for(;d.length;){const h=[...d.shift().entries()].sort((u,p)=>u[0]<p[0]?-1:1);for(const[u,p]of h)u===vi?r.push(...p):d.push(p)}return r}}const qv=["name","url"];function jv(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||qv.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function cl(e){jv(e);const t=(p,v)=>p.name.toLowerCase()<v.name.toLowerCase()?-1:1,n=e.sort(t),s=Hv(e,p=>{const v=new Set;if(p.shortcodes)for(const $ of p.shortcodes)for(const S of Vt($))v.add(S);return v}),o=p=>s(p,!0),a=p=>s(p,!1),r=p=>{const v=Vt(p),$=v.map((S,M)=>(M<v.length-1?o:a)(S));return tu($,S=>S.name).sort(t)},d=new Map,c=new Map;for(const p of e){c.set(p.name.toLowerCase(),p);for(const v of p.shortcodes||[])d.set(v.toLowerCase(),p)}return{all:n,search:r,byShortcode:p=>d.get(p.toLowerCase()),byName:p=>c.get(p.toLowerCase())}}const Gv=typeof wrappedJSObject<"u";function $n(e){if(!e)return e;if(Gv&&(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 su(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Vv=["annotation","emoji","group","order","version"];function Qv(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Vv.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function ou(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Jv(e){const t=await fetch(e,{method:"HEAD"});ou(t,e);const n=t.headers.get("etag");return su(n),n}async function Fo(e){const t=await fetch(e);ou(t,e);const n=t.headers.get("etag");su(n);const i=await t.json();return Qv(i),[n,i]}function Yv(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Xv(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 au(e){const t=JSON.stringify(e);let n=Xv(t);const i=await crypto.subtle.digest("SHA-1",n),s=Yv(i);return btoa(s)}async function Zv(e,t){let n,i=await Jv(t);if(!i){const s=await Fo(t);i=s[0],n=s[1],i||(i=await au(n))}await Bv(e,t,i)||(n||(n=(await Fo(t))[1]),await nu(e,n,t,i))}async function eb(e,t){let[n,i]=await Fo(t);n||(n=await au(i)),await nu(e,i,t,n)}async function tb(e,t){try{await Zv(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class nb{constructor({dataSource:t=$v,locale:n=Sv,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=cl(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await Tv(this._dbName);Mv(this._dbName,this._clear);const n=this.dataSource;await Dv(t)?await eb(t,n):this._lazyUpdate=tb(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 to(t),await this.ready(),ll(await Ov(this._db,t)).map($n)}async getEmojiBySearchQuery(t){yi(t),await this.ready();const n=this._custom.search(t),i=ll(await iu(this._db,t)).map($n);return[...n,...i]}async getEmojiByShortcode(t){yi(t),await this.ready();const n=this._custom.byShortcode(t);return n||$n(await Fv(this._db,t))}async getEmojiByUnicodeOrName(t){yi(t),await this.ready();const n=this._custom.byName(t);return n||$n(await Uv(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Ba(this._db,Xt,rl)||0}async setPreferredSkinTone(t){return to(t),await this.ready(),Wv(this._db,Xt,rl,t)}async incrementFavoriteEmojiCount(t){return yi(t),await this.ready(),Kv(this._db,t)}async getTopFavoriteEmoji(t){return to(t),await this.ready(),(await zv(this._db,this._custom,t)).map($n)}set customEmoji(t){this._custom=cl(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 La(this._dbName)}async delete(){await this._shutdown(),await _v(this._dbName)}}const Uo=[[-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})),no=Uo.slice(1),ib=2,dl=6,ru=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function ul(e){return e.unicode.includes("‍")}const sb={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},ob=1e3,ab="🖐️",rb=8,lb=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],lu='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',cb=(e,t)=>e<t?-1:e>t?1:0,pl=(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 ${lu}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},db=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function ub(e){const t=pl(e,"#000"),n=pl(e,"#fff");return t&&n&&db(t,n)}function pb(){const e=Object.entries(sb);try{for(const[t,n]of e)if(ub(t))return n}catch{}return e[0][1]}let io;const so=()=>(io||(io=new Promise(e=>ru(()=>e(pb())))),io),Wo=new Map,hb="️",fb="\uD83C",gb="‍",mb=127995,yb=57339;function vb(e,t){if(t===0)return e;const n=e.indexOf(gb);return n!==-1?e.substring(0,n)+String.fromCodePoint(mb+t-1)+e.substring(n):(e.endsWith(hb)&&(e=e.substring(0,e.length-1)),e+fb+String.fromCodePoint(yb+t-1))}function Le(e){e.preventDefault(),e.stopPropagation()}function oo(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function cu(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 bb(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:a,name:r,category:d,annotation:c})=>({unicode:i,name:r,shortcodes:o,url:a,category:d,annotation:c,id:i||r,skins:s&&n(s)}))}const Ti=requestAnimationFrame;let wb=typeof ResizeObserver=="function";function kb(e,t,n){let i;wb?(i=new ResizeObserver(n),i.observe(e)):Ti(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function hl(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let ao;function xb(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=hl(a);r===0&&(s=!0),typeof ao>"u"&&(ao=hl(t));const d=r/1.8<ao;Wo.set(o.unicode,d),d||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
3024
+ `;fs([ss({type:Number})],Yt.prototype,"splitRatio",2);fs([ss({type:Number})],Yt.prototype,"minRatio",2);fs([ss({type:Number})],Yt.prototype,"maxRatio",2);Yt=fs([ql("resizable-divider")],Yt);function yi(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function to(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const mv=1,yv=1,Dt="emoji",Xt="keyvalue",Ia="favorites",vv="tokens",Gd="tokens",bv="unicode",Vd="count",wv="group",kv="order",Qd="group-order",No="eTag",Xi="url",rl="skinTone",ln="readonly",Ra="readwrite",Jd="skinUnicodes",xv="skinUnicodes",$v="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Sv="en";function Av(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 ll(e){return Av(e,t=>t.unicode)}function Cv(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[a,[r,c]]of Object.entries(s))o.createIndex(a,r,{multiEntry:c});return o}t(Xt),t(Dt,bv,{[Gd]:[vv,!0],[Qd]:[[wv,kv]],[Jd]:[xv,!0]}),t(Ia,void 0,{[Vd]:[""]})}const Oo={},Ei={},Zi={};function Yd(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function Ev(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,mv);Oo[e]=s,s.onupgradeneeded=o=>{o.oldVersion<yv&&Cv(s.result)},Yd(n,i,s)});return t.onclose=()=>La(e),t}function Tv(e){return Ei[e]||(Ei[e]=Ev(e)),Ei[e]}function Ze(e,t,n,i){return new Promise((s,o)=>{const a=e.transaction(t,n,{durability:"relaxed"}),r=typeof t=="string"?a.objectStore(t):t.map(d=>a.objectStore(d));let c;i(r,a,d=>{c=d}),a.oncomplete=()=>s(c),a.onerror=()=>o(a.error)})}function La(e){const t=Oo[e],n=t&&t.result;if(n){n.close();const i=Zi[e];if(i)for(const s of i)s()}delete Oo[e],delete Ei[e],delete Zi[e]}function _v(e){return new Promise((t,n)=>{La(e);const i=indexedDB.deleteDatabase(e);Yd(t,n,i)})}function Mv(e,t){let n=Zi[e];n||(n=Zi[e]=[]),n.push(t)}const Pv=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 Vt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||Pv.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const Iv=2;function Xd(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=Iv)}function Rv(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:c,emoji:d,version:h})=>{const u=[...new Set(Xd([...(a||[]).map(Vt).flat(),...(c||[]).map(Vt).flat(),...Vt(n),i]))].sort(),p={annotation:n,group:s,order:o,tags:c,tokens:u,unicode:d,version:h};if(i&&(p.emoticon=i),a&&(p.shortcodes=a),r){p.skinTones=[],p.skinUnicodes=[],p.skinVersions=[];for(const{tone:v,emoji:$,version:S}of r)p.skinTones.push(v),p.skinUnicodes.push($),p.skinVersions.push(S)}return p})}function Zd(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function Mt(e,t,n){Zd(e,"get",t,n)}function eu(e,t,n){Zd(e,"getAll",t,n)}function Da(e){e.commit&&e.commit()}function Lv(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 tu(e,t){const n=Lv(e,s=>s.length),i=[];for(const s of n)e.some(o=>o.findIndex(a=>t(a)===t(s))===-1)||i.push(s);return i}async function Dv(e){return!await Ba(e,Xt,Xi)}async function Bv(e,t,n){const[i,s]=await Promise.all([No,Xi].map(o=>Ba(e,Xt,o)));return i===n&&s===t}async function Nv(e,t){return Ze(e,Dt,ln,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=c=>{const d=c.target.result;for(const h of d)if(a=h.unicode,t(h))return o(h);if(d.length<50)return o();r()}};r()})}async function nu(e,t,n,i){{const s=Rv(t);await Ze(e,[Dt,Xt],Ra,([o,a],r)=>{let c,d,h=0;function u(){++h===2&&p()}function p(){if(!(c===i&&d===n)){o.clear();for(const v of s)o.put(v);a.put(i,No),a.put(n,Xi),Da(r)}}Mt(a,No,v=>{c=v,u()}),Mt(a,Xi,v=>{d=v,u()})})}}async function Ov(e,t){return Ze(e,Dt,ln,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);eu(n.index(Qd),o,s)})}async function iu(e,t){const n=Xd(Vt(t));return n.length?Ze(e,Dt,ln,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&c()},c=()=>{const d=tu(a,h=>h.unicode);o(d.sort((h,u)=>h.order<u.order?-1:1))};for(let d=0;d<n.length;d++){const h=n[d],u=d===n.length-1?IDBKeyRange.bound(h,h+"￿",!1,!0):IDBKeyRange.only(h);eu(i.index(Gd),u,p=>{a.push(p),r()})}}):[]}async function Fv(e,t){const n=await iu(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await Nv(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function Uv(e,t){return Ze(e,Dt,ln,(n,i,s)=>Mt(n,t,o=>{if(o)return s(o);Mt(n.index(Jd),t,a=>s(a||null))}))}function Ba(e,t,n){return Ze(e,t,ln,(i,s,o)=>Mt(i,n,o))}function Wv(e,t,n,i){return Ze(e,t,Ra,(s,o)=>{s.put(i,n),Da(o)})}function Kv(e,t){return Ze(e,Ia,Ra,(n,i)=>Mt(n,t,s=>{n.put((s||0)+1,t),Da(i)}))}function zv(e,t,n){return n===0?[]:Ze(e,[Ia,Dt],ln,([i,s],o,a)=>{const r=[];i.index(Vd).openCursor(void 0,"prev").onsuccess=c=>{const d=c.target.result;if(!d)return a(r);function h(v){if(r.push(v),r.length===n)return a(r);d.continue()}const u=d.primaryKey,p=t.byName(u);if(p)return h(p);Mt(s,u,v=>{if(v)return h(v);d.continue()})}})}const vi="";function Hv(e,t){const n=new Map;for(const s of e){const o=t(s);for(const a of o){let r=n;for(let d=0;d<a.length;d++){const h=a.charAt(d);let u=r.get(h);u||(u=new Map,r.set(h,u)),r=u}let c=r.get(vi);c||(c=[],r.set(vi,c)),c.push(s)}}return(s,o)=>{let a=n;for(let d=0;d<s.length;d++){const h=s.charAt(d),u=a.get(h);if(u)a=u;else return[]}if(o)return a.get(vi)||[];const r=[],c=[a];for(;c.length;){const h=[...c.shift().entries()].sort((u,p)=>u[0]<p[0]?-1:1);for(const[u,p]of h)u===vi?r.push(...p):c.push(p)}return r}}const qv=["name","url"];function jv(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||qv.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function cl(e){jv(e);const t=(p,v)=>p.name.toLowerCase()<v.name.toLowerCase()?-1:1,n=e.sort(t),s=Hv(e,p=>{const v=new Set;if(p.shortcodes)for(const $ of p.shortcodes)for(const S of Vt($))v.add(S);return v}),o=p=>s(p,!0),a=p=>s(p,!1),r=p=>{const v=Vt(p),$=v.map((S,M)=>(M<v.length-1?o:a)(S));return tu($,S=>S.name).sort(t)},c=new Map,d=new Map;for(const p of e){d.set(p.name.toLowerCase(),p);for(const v of p.shortcodes||[])c.set(v.toLowerCase(),p)}return{all:n,search:r,byShortcode:p=>c.get(p.toLowerCase()),byName:p=>d.get(p.toLowerCase())}}const Gv=typeof wrappedJSObject<"u";function $n(e){if(!e)return e;if(Gv&&(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 su(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Vv=["annotation","emoji","group","order","version"];function Qv(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Vv.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function ou(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Jv(e){const t=await fetch(e,{method:"HEAD"});ou(t,e);const n=t.headers.get("etag");return su(n),n}async function Fo(e){const t=await fetch(e);ou(t,e);const n=t.headers.get("etag");su(n);const i=await t.json();return Qv(i),[n,i]}function Yv(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Xv(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 au(e){const t=JSON.stringify(e);let n=Xv(t);const i=await crypto.subtle.digest("SHA-1",n),s=Yv(i);return btoa(s)}async function Zv(e,t){let n,i=await Jv(t);if(!i){const s=await Fo(t);i=s[0],n=s[1],i||(i=await au(n))}await Bv(e,t,i)||(n||(n=(await Fo(t))[1]),await nu(e,n,t,i))}async function eb(e,t){let[n,i]=await Fo(t);n||(n=await au(i)),await nu(e,i,t,n)}async function tb(e,t){try{await Zv(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class nb{constructor({dataSource:t=$v,locale:n=Sv,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=cl(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await Tv(this._dbName);Mv(this._dbName,this._clear);const n=this.dataSource;await Dv(t)?await eb(t,n):this._lazyUpdate=tb(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 to(t),await this.ready(),ll(await Ov(this._db,t)).map($n)}async getEmojiBySearchQuery(t){yi(t),await this.ready();const n=this._custom.search(t),i=ll(await iu(this._db,t)).map($n);return[...n,...i]}async getEmojiByShortcode(t){yi(t),await this.ready();const n=this._custom.byShortcode(t);return n||$n(await Fv(this._db,t))}async getEmojiByUnicodeOrName(t){yi(t),await this.ready();const n=this._custom.byName(t);return n||$n(await Uv(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Ba(this._db,Xt,rl)||0}async setPreferredSkinTone(t){return to(t),await this.ready(),Wv(this._db,Xt,rl,t)}async incrementFavoriteEmojiCount(t){return yi(t),await this.ready(),Kv(this._db,t)}async getTopFavoriteEmoji(t){return to(t),await this.ready(),(await zv(this._db,this._custom,t)).map($n)}set customEmoji(t){this._custom=cl(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 La(this._dbName)}async delete(){await this._shutdown(),await _v(this._dbName)}}const Uo=[[-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})),no=Uo.slice(1),ib=2,dl=6,ru=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function ul(e){return e.unicode.includes("‍")}const sb={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},ob=1e3,ab="🖐️",rb=8,lb=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],lu='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',cb=(e,t)=>e<t?-1:e>t?1:0,pl=(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 ${lu}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},db=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function ub(e){const t=pl(e,"#000"),n=pl(e,"#fff");return t&&n&&db(t,n)}function pb(){const e=Object.entries(sb);try{for(const[t,n]of e)if(ub(t))return n}catch{}return e[0][1]}let io;const so=()=>(io||(io=new Promise(e=>ru(()=>e(pb())))),io),Wo=new Map,hb="️",fb="\uD83C",gb="‍",mb=127995,yb=57339;function vb(e,t){if(t===0)return e;const n=e.indexOf(gb);return n!==-1?e.substring(0,n)+String.fromCodePoint(mb+t-1)+e.substring(n):(e.endsWith(hb)&&(e=e.substring(0,e.length-1)),e+fb+String.fromCodePoint(yb+t-1))}function Le(e){e.preventDefault(),e.stopPropagation()}function oo(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function cu(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 bb(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:a,name:r,category:c,annotation:d})=>({unicode:i,name:r,shortcodes:o,url:a,category:c,annotation:d,id:i||r,skins:s&&n(s)}))}const Ti=requestAnimationFrame;let wb=typeof ResizeObserver=="function";function kb(e,t,n){let i;wb?(i=new ResizeObserver(n),i.observe(e)):Ti(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function hl(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let ao;function xb(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=hl(a);r===0&&(s=!0),typeof ao>"u"&&(ao=hl(t));const c=r/1.8<ao;Wo.set(o.unicode,c),c||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
3020
3025
  This is likely due to using \`display:none\` which is unsupported.
3021
3026
  If this is a Jest/Vitest environment, you can ignore this warning.
3022
- For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function $b(e){return cu(e,t=>t)}function Sb(e){e&&(e.scrollTop=0)}function Dn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function fl(e){return""+e}function Ab(e){const t=document.createElement("template");return t.innerHTML=e,t}const Cb=new WeakMap,Eb=new WeakMap,Tb=Symbol("un-keyed"),_b="replaceChildren"in Element.prototype;function Mb(e,t){_b?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function Pb(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 Ib(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=Pb(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&Mb(i,e)}function Rb(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:a,attributeValuePre:r,attributeValuePost:d}}=n,c=e[o];if(s!==c)if(n.currentExpression=c,a)if(c===null)i.removeAttribute(a);else{const h=r+fl(c)+d;i.setAttribute(a,h)}else{let h;Array.isArray(c)?Ib(c,n):c instanceof Element?(h=c,i.replaceWith(h)):i.nodeValue=fl(c),h&&(n.targetNode=h)}}}function Lb(e){let t="",n=!1,i=!1,s=-1;const o=new Map,a=[];let r=0;for(let c=0,h=e.length;c<h;c++){const u=e[c];if(t+=u.slice(r),c===h-1)break;for(let b=0;b<u.length;b++)switch(u.charAt(b)){case"<":{u.charAt(b+1)==="/"?a.pop():(n=!0,a.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const p=a[a.length-1],v=Dn(o,p,()=>[]);let $,S,M;if(i){const b=/(\S+)="?([^"=]*)$/.exec(u);$=b[1],S=b[2];const k=/^([^">]*)("?)/.exec(e[c+1]);M=k[1],t=t.slice(0,-1*b[0].length),r=k[0].length}else r=0;const y={attributeName:$,attributeValuePre:S,attributeValuePost:M,expressionIndex:c};v.push(y),!n&&!i&&(t+=" ")}return{template:Ab(t),elementsToBindings:o}}function gl(e,t,n){for(let i=0;i<e.length;i++){const s=e[i],o=s.attributeName?t:t.firstChild,a={binding:s,targetNode:o,targetParentNode:void 0,currentExpression:void 0};n.push(a)}}function Db(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))gl(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&gl(r,o,n)}while(o=s.nextNode())}return n}function Bb(e){const{template:t,elementsToBindings:n}=Dn(Cb,e,()=>Lb(e)),i=t.cloneNode(!0).content.firstElementChild,s=Db(i,n);return function(a){return Rb(a,s),i}}function Nb(e){const t=Dn(Eb,e,()=>new Map);let n=Tb;function i(o,...a){const r=Dn(t,o,()=>new Map);return Dn(r,n,()=>Bb(o))(a)}function s(o,a,r){return o.map((d,c)=>{const h=n;n=r(d);try{return a(d,c)}finally{n=h}})}return{map:s,html:i}}function Ob(e,t,n,i,s,o,a,r,d){const{labelWithSkin:c,titleForEmoji:h,unicodeWithSkin:u}=n,{html:p,map:v}=Nb(t);function $(b,k,A){return v(b,(E,T)=>p`<button role="${k?"option":"menuitem"}" aria-selected="${k?T===t.activeSearchItem:null}" aria-label="${c(E,t.currentSkinTone)}" title="${h(E)}" class="${"emoji"+(k&&T===t.activeSearchItem?" active":"")+(E.unicode?"":" custom-emoji")}" id="${`${A}-${E.id}`}" style="${E.unicode?null:`--custom-emoji-background: url(${JSON.stringify(E.url)})`}">${E.unicode?u(E,t.currentSkinTone):""}</button>`,E=>`${A}-${E.id}`)}const M=p`<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">${v(t.skinTones,(b,k)=>p`<div id="skintone-${k}" class="emoji ${k===t.activeSkinTone?"active":""}" aria-selected="${k===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[k]}" aria-label="${t.i18n.skinTones[k]}">${b}</div>`,b=>b)}</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">${v(t.groups,b=>p`<button role="tab" class="nav-button" aria-controls="tab-${b.id}" aria-label="${t.i18n.categories[b.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===b.id}" title="${t.i18n.categories[b.name]}" data-group-id="${b.id}"><div class="nav-emoji emoji">${b.emoji}</div></button>`,b=>b.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">${v(t.currentEmojisWithCategories,(b,k)=>p`<div><div id="menu-label-${k}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:b.category?b.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${k!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(b.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${k}" id="${t.searchMode?"search-results":null}">${$(b.emojis,t.searchMode,"emo")}</div></div>`,b=>b.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${$(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,y=(b,k)=>{for(const A of e.querySelectorAll(`[${b}]`))k(A,A.getAttribute(b))};if(d){e.appendChild(M);for(const b of["click","focusout","input","keydown","keyup"])y(`data-on-${b}`,(k,A)=>{k.addEventListener(b,i[A])});y("data-ref",(b,k)=>{o[k]=b}),a.addEventListener("abort",()=>{e.removeChild(M)})}y("data-action",(b,k)=>{let A=r.get(k);A||r.set(k,A=new WeakSet),A.has(b)||(A.add(b),s[k](b))})}const es=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function Fb(e){let t=!1,n;const i=new Map,s=new Set;let o;const a=()=>{if(t)return;const c=[...s];s.clear();try{for(const h of c)h()}finally{o=!1,s.size&&(o=!0,es(a))}},r=new Proxy({},{get(c,h){if(n){let u=i.get(h);u||(u=new Set,i.set(h,u)),u.add(n)}return c[h]},set(c,h,u){if(c[h]!==u){c[h]=u;const p=i.get(h);if(p){for(const v of p)s.add(v);o||(o=!0,es(a))}}return!0}}),d=c=>{const h=()=>{const u=n;n=h;try{return c()}finally{n=u}};return h()};return e.addEventListener("abort",()=>{t=!0}),{state:r,createEffect:d}}function ro(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 ml=new WeakMap;function Ub(e,t,n){{const i=e.closest(".tabpanel");let s=ml.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),ml.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const lo=[],{assign:bi}=Object;function Wb(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=Fb(s),r=new Map;bi(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),bi(o,t),bi(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:rb,isRtl:!1,currentGroupIndex:0,groups:no,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const d=C=>{e.getElementById(C).focus()},c=C=>e.getElementById(`emo-${C.id}`),h=(C,R)=>{n.rootElement.dispatchEvent(new CustomEvent(C,{detail:R,bubbles:!0,composed:!0}))},u=(C,R)=>C.id===R.id,p=(C,R)=>{const{category:F,emojis:U}=C,{category:Z,emojis:J}=R;return F!==Z?!1:ro(U,J,u)},v=C=>{ro(o.currentEmojis,C,u)||(o.currentEmojis=C)},$=C=>{o.searchMode!==C&&(o.searchMode=C)},S=C=>{ro(o.currentEmojisWithCategories,C,p)||(o.currentEmojisWithCategories=C)},M=(C,R)=>R&&C.skins&&C.skins[R]||C.unicode,k={labelWithSkin:(C,R)=>$b([C.name||M(C,R),C.annotation,...C.shortcodes||lo].filter(Boolean)).join(", "),titleForEmoji:C=>C.annotation||(C.shortcodes||lo).join(", "),unicodeWithSkin:M},A={onClickSkinToneButton:X,onEmojiClick:Yn,onNavClick:Qn,onNavKeydown:ks,onSearchKeydown:ws,onSkinToneOptionsClick:Xn,onSkinToneOptionsFocusOut:et,onSkinToneOptionsKeydown:dt,onSkinToneOptionsKeyup:dn,onSearchInput:Zn},E={calculateEmojiGridStyle:D,updateOnIntersection:W};let T=!0;a(()=>{Ob(e,o,k,A,E,n,s,r,T),T=!1}),o.emojiVersion||so().then(C=>{C||(o.message=o.i18n.emojiUnsupportedMessage)}),a(()=>{async function C(){let R=!1;const F=setTimeout(()=>{R=!0,o.message=o.i18n.loadingMessage},ob);try{await o.database.ready(),o.databaseLoaded=!0}catch(U){console.error(U),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(F),R&&(R=!1,o.message="")}}o.database&&C()}),a(()=>{o.pickerStyle=`
3027
+ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function $b(e){return cu(e,t=>t)}function Sb(e){e&&(e.scrollTop=0)}function Dn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function fl(e){return""+e}function Ab(e){const t=document.createElement("template");return t.innerHTML=e,t}const Cb=new WeakMap,Eb=new WeakMap,Tb=Symbol("un-keyed"),_b="replaceChildren"in Element.prototype;function Mb(e,t){_b?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function Pb(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 Ib(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=Pb(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&Mb(i,e)}function Rb(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:a,attributeValuePre:r,attributeValuePost:c}}=n,d=e[o];if(s!==d)if(n.currentExpression=d,a)if(d===null)i.removeAttribute(a);else{const h=r+fl(d)+c;i.setAttribute(a,h)}else{let h;Array.isArray(d)?Ib(d,n):d instanceof Element?(h=d,i.replaceWith(h)):i.nodeValue=fl(d),h&&(n.targetNode=h)}}}function Lb(e){let t="",n=!1,i=!1,s=-1;const o=new Map,a=[];let r=0;for(let d=0,h=e.length;d<h;d++){const u=e[d];if(t+=u.slice(r),d===h-1)break;for(let b=0;b<u.length;b++)switch(u.charAt(b)){case"<":{u.charAt(b+1)==="/"?a.pop():(n=!0,a.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const p=a[a.length-1],v=Dn(o,p,()=>[]);let $,S,M;if(i){const b=/(\S+)="?([^"=]*)$/.exec(u);$=b[1],S=b[2];const k=/^([^">]*)("?)/.exec(e[d+1]);M=k[1],t=t.slice(0,-1*b[0].length),r=k[0].length}else r=0;const y={attributeName:$,attributeValuePre:S,attributeValuePost:M,expressionIndex:d};v.push(y),!n&&!i&&(t+=" ")}return{template:Ab(t),elementsToBindings:o}}function gl(e,t,n){for(let i=0;i<e.length;i++){const s=e[i],o=s.attributeName?t:t.firstChild,a={binding:s,targetNode:o,targetParentNode:void 0,currentExpression:void 0};n.push(a)}}function Db(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))gl(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&gl(r,o,n)}while(o=s.nextNode())}return n}function Bb(e){const{template:t,elementsToBindings:n}=Dn(Cb,e,()=>Lb(e)),i=t.cloneNode(!0).content.firstElementChild,s=Db(i,n);return function(a){return Rb(a,s),i}}function Nb(e){const t=Dn(Eb,e,()=>new Map);let n=Tb;function i(o,...a){const r=Dn(t,o,()=>new Map);return Dn(r,n,()=>Bb(o))(a)}function s(o,a,r){return o.map((c,d)=>{const h=n;n=r(c);try{return a(c,d)}finally{n=h}})}return{map:s,html:i}}function Ob(e,t,n,i,s,o,a,r,c){const{labelWithSkin:d,titleForEmoji:h,unicodeWithSkin:u}=n,{html:p,map:v}=Nb(t);function $(b,k,A){return v(b,(E,T)=>p`<button role="${k?"option":"menuitem"}" aria-selected="${k?T===t.activeSearchItem:null}" aria-label="${d(E,t.currentSkinTone)}" title="${h(E)}" class="${"emoji"+(k&&T===t.activeSearchItem?" active":"")+(E.unicode?"":" custom-emoji")}" id="${`${A}-${E.id}`}" style="${E.unicode?null:`--custom-emoji-background: url(${JSON.stringify(E.url)})`}">${E.unicode?u(E,t.currentSkinTone):""}</button>`,E=>`${A}-${E.id}`)}const M=p`<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">${v(t.skinTones,(b,k)=>p`<div id="skintone-${k}" class="emoji ${k===t.activeSkinTone?"active":""}" aria-selected="${k===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[k]}" aria-label="${t.i18n.skinTones[k]}">${b}</div>`,b=>b)}</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">${v(t.groups,b=>p`<button role="tab" class="nav-button" aria-controls="tab-${b.id}" aria-label="${t.i18n.categories[b.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===b.id}" title="${t.i18n.categories[b.name]}" data-group-id="${b.id}"><div class="nav-emoji emoji">${b.emoji}</div></button>`,b=>b.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">${v(t.currentEmojisWithCategories,(b,k)=>p`<div><div id="menu-label-${k}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:b.category?b.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${k!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(b.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${k}" id="${t.searchMode?"search-results":null}">${$(b.emojis,t.searchMode,"emo")}</div></div>`,b=>b.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${$(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,y=(b,k)=>{for(const A of e.querySelectorAll(`[${b}]`))k(A,A.getAttribute(b))};if(c){e.appendChild(M);for(const b of["click","focusout","input","keydown","keyup"])y(`data-on-${b}`,(k,A)=>{k.addEventListener(b,i[A])});y("data-ref",(b,k)=>{o[k]=b}),a.addEventListener("abort",()=>{e.removeChild(M)})}y("data-action",(b,k)=>{let A=r.get(k);A||r.set(k,A=new WeakSet),A.has(b)||(A.add(b),s[k](b))})}const es=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function Fb(e){let t=!1,n;const i=new Map,s=new Set;let o;const a=()=>{if(t)return;const d=[...s];s.clear();try{for(const h of d)h()}finally{o=!1,s.size&&(o=!0,es(a))}},r=new Proxy({},{get(d,h){if(n){let u=i.get(h);u||(u=new Set,i.set(h,u)),u.add(n)}return d[h]},set(d,h,u){if(d[h]!==u){d[h]=u;const p=i.get(h);if(p){for(const v of p)s.add(v);o||(o=!0,es(a))}}return!0}}),c=d=>{const h=()=>{const u=n;n=h;try{return d()}finally{n=u}};return h()};return e.addEventListener("abort",()=>{t=!0}),{state:r,createEffect:c}}function ro(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 ml=new WeakMap;function Ub(e,t,n){{const i=e.closest(".tabpanel");let s=ml.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),ml.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const lo=[],{assign:bi}=Object;function Wb(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=Fb(s),r=new Map;bi(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),bi(o,t),bi(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:rb,isRtl:!1,currentGroupIndex:0,groups:no,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const c=C=>{e.getElementById(C).focus()},d=C=>e.getElementById(`emo-${C.id}`),h=(C,R)=>{n.rootElement.dispatchEvent(new CustomEvent(C,{detail:R,bubbles:!0,composed:!0}))},u=(C,R)=>C.id===R.id,p=(C,R)=>{const{category:F,emojis:U}=C,{category:Z,emojis:J}=R;return F!==Z?!1:ro(U,J,u)},v=C=>{ro(o.currentEmojis,C,u)||(o.currentEmojis=C)},$=C=>{o.searchMode!==C&&(o.searchMode=C)},S=C=>{ro(o.currentEmojisWithCategories,C,p)||(o.currentEmojisWithCategories=C)},M=(C,R)=>R&&C.skins&&C.skins[R]||C.unicode,k={labelWithSkin:(C,R)=>$b([C.name||M(C,R),C.annotation,...C.shortcodes||lo].filter(Boolean)).join(", "),titleForEmoji:C=>C.annotation||(C.shortcodes||lo).join(", "),unicodeWithSkin:M},A={onClickSkinToneButton:X,onEmojiClick:Yn,onNavClick:Qn,onNavKeydown:ks,onSearchKeydown:ws,onSkinToneOptionsClick:Xn,onSkinToneOptionsFocusOut:et,onSkinToneOptionsKeydown:dt,onSkinToneOptionsKeyup:dn,onSearchInput:Zn},E={calculateEmojiGridStyle:D,updateOnIntersection:W};let T=!0;a(()=>{Ob(e,o,k,A,E,n,s,r,T),T=!1}),o.emojiVersion||so().then(C=>{C||(o.message=o.i18n.emojiUnsupportedMessage)}),a(()=>{async function C(){let R=!1;const F=setTimeout(()=>{R=!0,o.message=o.i18n.loadingMessage},ob);try{await o.database.ready(),o.databaseLoaded=!0}catch(U){console.error(U),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(F),R&&(R=!1,o.message="")}}o.database&&C()}),a(()=>{o.pickerStyle=`
3023
3028
  --num-groups: ${o.groups.length};
3024
3029
  --indicator-opacity: ${o.searchMode?0:1};
3025
- --num-skintones: ${dl};`}),a(()=>{o.customEmoji&&o.database&&P()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==Uo&&(o.groups=Uo):o.groups!==no&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=no)}),a(()=>{async function C(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}C()}),a(()=>{o.skinTones=Array(dl).fill().map((C,R)=>vb(o.skinToneEmoji,R))}),a(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),a(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),a(()=>{async function C(){const{database:R}=o,F=(await Promise.all(lb.map(U=>R.getEmojiByUnicodeOrName(U)))).filter(Boolean);o.defaultFavoriteEmojis=F}o.databaseLoaded&&C()});function P(){const{customEmoji:C,database:R}=o,F=C||lo;R.customEmoji!==F&&(R.customEmoji=F)}a(()=>{async function C(){P();const{database:R,defaultFavoriteEmojis:F,numColumns:U}=o,Z=await R.getTopFavoriteEmoji(U),J=await ze(cu([...Z,...F],he=>he.unicode||he.name).slice(0,U));o.currentFavorites=J}o.databaseLoaded&&o.defaultFavoriteEmojis&&C()});function D(C){kb(C,s,()=>{{const R=getComputedStyle(n.rootElement),F=parseInt(R.getPropertyValue("--num-columns"),10),U=R.getPropertyValue("direction")==="rtl";o.numColumns=F,o.isRtl=U}})}function W(C){Ub(C,s,R=>{for(const{target:F,isIntersecting:U}of R)F.classList.toggle("onscreen",U)})}a(()=>{async function C(){const{searchText:R,currentGroup:F,databaseLoaded:U,customEmoji:Z}=o;if(!U)o.currentEmojis=[],o.searchMode=!1;else if(R.length>=ib){const J=await bs(R);o.searchText===R&&(v(J),$(!0))}else{const{id:J}=F;if(J!==-1||Z&&Z.length){const he=await vs(J);o.currentGroup.id===J&&(v(he),$(!1))}}}C()});const z=()=>{Ti(()=>Sb(n.tabpanelElement))};a(()=>{const{currentEmojis:C,emojiVersion:R}=o,F=C.filter(U=>U.unicode).filter(U=>ul(U)&&!Wo.has(U.unicode));if(!R&&F.length)v(C),Ti(()=>H(F));else{const U=R?C:C.filter(ke);v(U),z()}});function H(C){xb(C,n.baselineEmoji,c)?z():o.currentEmojis=[...o.currentEmojis]}function ke(C){return!C.unicode||!ul(C)||Wo.get(C.unicode)}async function Me(C){const R=o.emojiVersion||await so();return C.filter(({version:F})=>!F||F<=R)}async function ze(C){return bb(C,o.emojiVersion||await so())}async function vs(C){const R=C===-1?o.customEmoji:await o.database.getEmojiByGroup(C);return ze(await Me(R))}async function bs(C){return ze(await Me(await o.database.getEmojiBySearchQuery(C)))}a(()=>{}),a(()=>{function C(){const{searchMode:F,currentEmojis:U}=o;if(F)return[{category:"",emojis:U}];const Z=new Map;for(const J of U){const he=J.category||"";let tt=Z.get(he);tt||(tt=[],Z.set(he,tt)),tt.push(J)}return[...Z.entries()].map(([J,he])=>({category:J,emojis:he})).sort((J,he)=>o.customCategorySorting(J.category,he.category))}const R=C();S(R)}),a(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),a(()=>{const{rawSearchText:C}=o;ru(()=>{o.searchText=(C||"").trim(),o.activeSearchItem=-1})});function ws(C){if(!o.searchMode||!o.currentEmojis.length)return;const R=F=>{Le(C),o.activeSearchItem=oo(F,o.activeSearchItem,o.currentEmojis)};switch(C.key){case"ArrowDown":return R(!1);case"ArrowUp":return R(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Le(C),te(o.currentEmojis[o.activeSearchItem].id)}}function Qn(C){const{target:R}=C,F=R.closest(".nav-button");if(!F)return;const U=parseInt(F.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(Z=>Z.id===U)}function ks(C){const{target:R,key:F}=C,U=Z=>{Z&&(Le(C),Z.focus())};switch(F){case"ArrowLeft":return U(R.previousElementSibling);case"ArrowRight":return U(R.nextElementSibling);case"Home":return U(R.parentElement.firstElementChild);case"End":return U(R.parentElement.lastElementChild)}}async function Jn(C){const R=await o.database.getEmojiByUnicodeOrName(C),F=[...o.currentEmojis,...o.currentFavorites].find(Z=>Z.id===C),U=F.unicode&&M(F,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(C),{emoji:R,skinTone:o.currentSkinTone,...U&&{unicode:U},...F.name&&{name:F.name}}}async function te(C){const R=Jn(C);h("emoji-click-sync",R),h("emoji-click",await R)}function Yn(C){const{target:R}=C;if(!R.classList.contains("emoji"))return;Le(C);const F=R.id.substring(4);te(F)}function ne(C){o.currentSkinTone=C,o.skinTonePickerExpanded=!1,d("skintone-button"),h("skin-tone-change",{skinTone:C}),o.database.setPreferredSkinTone(C)}function Xn(C){const{target:{id:R}}=C,F=R&&R.match(/^skintone-(\d)/);if(!F)return;Le(C);const U=parseInt(F[1],10);ne(U)}function X(C){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Le(C),Ti(()=>d("skintone-list")))}a(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function dt(C){if(!o.skinTonePickerExpanded)return;const R=async F=>{Le(C),o.activeSkinTone=F};switch(C.key){case"ArrowUp":return R(oo(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return R(oo(!1,o.activeSkinTone,o.skinTones));case"Home":return R(0);case"End":return R(o.skinTones.length-1);case"Enter":return Le(C),ne(o.activeSkinTone);case"Escape":return Le(C),o.skinTonePickerExpanded=!1,d("skintone-button")}}function dn(C){if(o.skinTonePickerExpanded&&C.key===" ")return Le(C),ne(o.activeSkinTone)}async function et(C){const{relatedTarget:R}=C;(!R||R.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function Zn(C){o.rawSearchText=C.target.value}return{$set(C){bi(o,C)},$destroy(){i.abort()}}}const Kb="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",zb="en";var Hb={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"}},qb=':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 du=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],jb=`:host{--emoji-font-family:${lu}}`;class Na extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=qb+jb,this.shadowRoot.appendChild(n),this._ctx={locale:zb,dataSource:Kb,skinToneEmoji:ab,customCategorySorting:cb,customEmoji:null,i18n:Hb,emojiVersion:null,...t};for(const i of du)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){yl(this),this._cmp||(this._cmp=Wb(this.shadowRoot,this._ctx))}disconnectedCallback(){yl(this),es(()=>{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 nb({locale:t,dataSource:n}))}_dbFlush(){es(()=>this._dbCreate())}}const uu={};for(const e of du)uu[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(Na.prototype,uu);function yl(e){e instanceof Na||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Na);function Gb(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 vl(e){e.style.height="44px",e.style.overflowY="hidden"}const Vb=5e3;function Qb(e){return e?e.active?l`
3030
+ --num-skintones: ${dl};`}),a(()=>{o.customEmoji&&o.database&&P()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==Uo&&(o.groups=Uo):o.groups!==no&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=no)}),a(()=>{async function C(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}C()}),a(()=>{o.skinTones=Array(dl).fill().map((C,R)=>vb(o.skinToneEmoji,R))}),a(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),a(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),a(()=>{async function C(){const{database:R}=o,F=(await Promise.all(lb.map(U=>R.getEmojiByUnicodeOrName(U)))).filter(Boolean);o.defaultFavoriteEmojis=F}o.databaseLoaded&&C()});function P(){const{customEmoji:C,database:R}=o,F=C||lo;R.customEmoji!==F&&(R.customEmoji=F)}a(()=>{async function C(){P();const{database:R,defaultFavoriteEmojis:F,numColumns:U}=o,Z=await R.getTopFavoriteEmoji(U),J=await ze(cu([...Z,...F],he=>he.unicode||he.name).slice(0,U));o.currentFavorites=J}o.databaseLoaded&&o.defaultFavoriteEmojis&&C()});function D(C){kb(C,s,()=>{{const R=getComputedStyle(n.rootElement),F=parseInt(R.getPropertyValue("--num-columns"),10),U=R.getPropertyValue("direction")==="rtl";o.numColumns=F,o.isRtl=U}})}function W(C){Ub(C,s,R=>{for(const{target:F,isIntersecting:U}of R)F.classList.toggle("onscreen",U)})}a(()=>{async function C(){const{searchText:R,currentGroup:F,databaseLoaded:U,customEmoji:Z}=o;if(!U)o.currentEmojis=[],o.searchMode=!1;else if(R.length>=ib){const J=await bs(R);o.searchText===R&&(v(J),$(!0))}else{const{id:J}=F;if(J!==-1||Z&&Z.length){const he=await vs(J);o.currentGroup.id===J&&(v(he),$(!1))}}}C()});const z=()=>{Ti(()=>Sb(n.tabpanelElement))};a(()=>{const{currentEmojis:C,emojiVersion:R}=o,F=C.filter(U=>U.unicode).filter(U=>ul(U)&&!Wo.has(U.unicode));if(!R&&F.length)v(C),Ti(()=>H(F));else{const U=R?C:C.filter(ke);v(U),z()}});function H(C){xb(C,n.baselineEmoji,d)?z():o.currentEmojis=[...o.currentEmojis]}function ke(C){return!C.unicode||!ul(C)||Wo.get(C.unicode)}async function Me(C){const R=o.emojiVersion||await so();return C.filter(({version:F})=>!F||F<=R)}async function ze(C){return bb(C,o.emojiVersion||await so())}async function vs(C){const R=C===-1?o.customEmoji:await o.database.getEmojiByGroup(C);return ze(await Me(R))}async function bs(C){return ze(await Me(await o.database.getEmojiBySearchQuery(C)))}a(()=>{}),a(()=>{function C(){const{searchMode:F,currentEmojis:U}=o;if(F)return[{category:"",emojis:U}];const Z=new Map;for(const J of U){const he=J.category||"";let tt=Z.get(he);tt||(tt=[],Z.set(he,tt)),tt.push(J)}return[...Z.entries()].map(([J,he])=>({category:J,emojis:he})).sort((J,he)=>o.customCategorySorting(J.category,he.category))}const R=C();S(R)}),a(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),a(()=>{const{rawSearchText:C}=o;ru(()=>{o.searchText=(C||"").trim(),o.activeSearchItem=-1})});function ws(C){if(!o.searchMode||!o.currentEmojis.length)return;const R=F=>{Le(C),o.activeSearchItem=oo(F,o.activeSearchItem,o.currentEmojis)};switch(C.key){case"ArrowDown":return R(!1);case"ArrowUp":return R(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Le(C),te(o.currentEmojis[o.activeSearchItem].id)}}function Qn(C){const{target:R}=C,F=R.closest(".nav-button");if(!F)return;const U=parseInt(F.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(Z=>Z.id===U)}function ks(C){const{target:R,key:F}=C,U=Z=>{Z&&(Le(C),Z.focus())};switch(F){case"ArrowLeft":return U(R.previousElementSibling);case"ArrowRight":return U(R.nextElementSibling);case"Home":return U(R.parentElement.firstElementChild);case"End":return U(R.parentElement.lastElementChild)}}async function Jn(C){const R=await o.database.getEmojiByUnicodeOrName(C),F=[...o.currentEmojis,...o.currentFavorites].find(Z=>Z.id===C),U=F.unicode&&M(F,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(C),{emoji:R,skinTone:o.currentSkinTone,...U&&{unicode:U},...F.name&&{name:F.name}}}async function te(C){const R=Jn(C);h("emoji-click-sync",R),h("emoji-click",await R)}function Yn(C){const{target:R}=C;if(!R.classList.contains("emoji"))return;Le(C);const F=R.id.substring(4);te(F)}function ne(C){o.currentSkinTone=C,o.skinTonePickerExpanded=!1,c("skintone-button"),h("skin-tone-change",{skinTone:C}),o.database.setPreferredSkinTone(C)}function Xn(C){const{target:{id:R}}=C,F=R&&R.match(/^skintone-(\d)/);if(!F)return;Le(C);const U=parseInt(F[1],10);ne(U)}function X(C){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Le(C),Ti(()=>c("skintone-list")))}a(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function dt(C){if(!o.skinTonePickerExpanded)return;const R=async F=>{Le(C),o.activeSkinTone=F};switch(C.key){case"ArrowUp":return R(oo(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return R(oo(!1,o.activeSkinTone,o.skinTones));case"Home":return R(0);case"End":return R(o.skinTones.length-1);case"Enter":return Le(C),ne(o.activeSkinTone);case"Escape":return Le(C),o.skinTonePickerExpanded=!1,c("skintone-button")}}function dn(C){if(o.skinTonePickerExpanded&&C.key===" ")return Le(C),ne(o.activeSkinTone)}async function et(C){const{relatedTarget:R}=C;(!R||R.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function Zn(C){o.rawSearchText=C.target.value}return{$set(C){bi(o,C)},$destroy(){i.abort()}}}const Kb="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",zb="en";var Hb={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"}},qb=':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 du=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],jb=`:host{--emoji-font-family:${lu}}`;class Na extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=qb+jb,this.shadowRoot.appendChild(n),this._ctx={locale:zb,dataSource:Kb,skinToneEmoji:ab,customCategorySorting:cb,customEmoji:null,i18n:Hb,emojiVersion:null,...t};for(const i of du)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){yl(this),this._cmp||(this._cmp=Wb(this.shadowRoot,this._ctx))}disconnectedCallback(){yl(this),es(()=>{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 nb({locale:t,dataSource:n}))}_dbFlush(){es(()=>this._dbCreate())}}const uu={};for(const e of du)uu[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(Na.prototype,uu);function yl(e){e instanceof Na||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Na);function Gb(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 vl(e){e.style.height="44px",e.style.overflowY="hidden"}const Vb=5e3;function Qb(e){return e?e.active?l`
3026
3031
  <div class="callout info compaction-indicator compaction-indicator--active">
3027
3032
  ${I.loader} Compacting context...
3028
3033
  </div>
@@ -3030,7 +3035,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3030
3035
  <div class="callout success compaction-indicator compaction-indicator--complete">
3031
3036
  ${I.check} Context compacted
3032
3037
  </div>
3033
- `:w:w}const Je=5*1024*1024;function Ye(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Te(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 a=(s=e.closest(".chat"))==null?void 0:s.querySelector(".chat-compose");(o=a==null?void 0:a.parentElement)==null||o.insertBefore(n,a)}n.textContent=t,setTimeout(()=>n==null?void 0:n.remove(),4e3)}const Jb=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function pu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function hu(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Jb.test(e.name)}function fu(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function gu(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function Yb(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(pu(e)){if(e.size>Je){n&&Te(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:Ye(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(hu(e)){if(e.size>Je){n&&Te(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:Ye(),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(fu(e)){if(e.size>Je){n&&Te(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:Ye(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(gu(e)){if(e.size>Je){n&&Te(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:Ye(),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&&Te(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Xb(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 a=i[o];if(pu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`Image too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const d=r.result,c={id:Ye(),dataUrl:d,mimeType:a.type},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,c])},r.readAsDataURL(a)}else if(hu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`File too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const d=r.result,c={id:Ye(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:d},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,c])},r.readAsText(a)}else if(fu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`PDF too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const d=r.result,c={id:Ye(),dataUrl:d,mimeType:"application/pdf",fileName:a.name},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,c])},r.readAsDataURL(a)}else if(gu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`Video too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const d=r.result,c={id:Ye(),dataUrl:d,mimeType:a.type||"video/mp4",fileName:a.name},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,c])},r.readAsDataURL(a)}else Te(n,`Unsupported file type: ${a.name}. Use the Files page to upload to workspace.`)}}function Zb(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function ew(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function tw(e,t){var s,o,a;const n=(s=e.clipboardData)==null?void 0:s.items;if(!n||!t.onAttachmentsChange)return;const i=[];for(let r=0;r<n.length;r++){const d=n[r];(d.type.startsWith("image/")||d.type.startsWith("video/"))&&i.push(d)}if(i.length!==0){e.preventDefault();for(const r of i){const d=r.getAsFile();if(!d)continue;const c=d.type.startsWith("video/")?"Video":"Image";if(d.size>Je){const u=((a=(o=e.target)==null?void 0:o.closest)==null?void 0:a.call(o,".chat"))??document.querySelector(".chat");u&&Te(u,`${c} too large (${(d.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const h=new FileReader;h.onload=()=>{var S;const u=h.result,p=d.type.startsWith("video/"),v={id:Ye(),dataUrl:u,mimeType:d.type,fileName:p?d.name||"video.mp4":void 0},$=t.attachments??[];(S=t.onAttachmentsChange)==null||S.call(t,[...$,v])},h.readAsDataURL(d)}}}function nw(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=a=>{i.contains(a.target)||t.contains(a.target)||(i.classList.remove("active"),t.classList.remove("active"),document.removeEventListener("click",o,!0))};requestAnimationFrame(()=>document.addEventListener("click",o,!0))}}function iw(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 a=o.selectionStart??t.draft.length,r=o.selectionEnd??a,d=t.draft.slice(0,a),c=t.draft.slice(r);t.onDraftChange(d+i+c);const h=s==null?void 0:s.querySelector(".emoji-picker-popup"),u=s==null?void 0:s.querySelector(".chat-compose__emoji");h==null||h.classList.remove("active"),u==null||u.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const p=a+i.length;o.setSelectionRange(p,p)})}function sw(e){const t=e.attachments??[];return t.length===0?w:l`
3038
+ `:w:w}const Je=5*1024*1024;function Ye(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Te(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 a=(s=e.closest(".chat"))==null?void 0:s.querySelector(".chat-compose");(o=a==null?void 0:a.parentElement)==null||o.insertBefore(n,a)}n.textContent=t,setTimeout(()=>n==null?void 0:n.remove(),4e3)}const Jb=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function pu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function hu(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Jb.test(e.name)}function fu(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function gu(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function Yb(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(pu(e)){if(e.size>Je){n&&Te(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:Ye(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(hu(e)){if(e.size>Je){n&&Te(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:Ye(),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(fu(e)){if(e.size>Je){n&&Te(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:Ye(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(gu(e)){if(e.size>Je){n&&Te(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:Ye(),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&&Te(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Xb(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 a=i[o];if(pu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`Image too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const c=r.result,d={id:Ye(),dataUrl:c,mimeType:a.type},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsDataURL(a)}else if(hu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`File too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const c=r.result,d={id:Ye(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:c},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsText(a)}else if(fu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`PDF too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const c=r.result,d={id:Ye(),dataUrl:c,mimeType:"application/pdf",fileName:a.name},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsDataURL(a)}else if(gu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Te(n,`Video too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var u;const c=r.result,d={id:Ye(),dataUrl:c,mimeType:a.type||"video/mp4",fileName:a.name},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsDataURL(a)}else Te(n,`Unsupported file type: ${a.name}. Use the Files page to upload to workspace.`)}}function Zb(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function ew(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function tw(e,t){var s,o,a;const n=(s=e.clipboardData)==null?void 0:s.items;if(!n||!t.onAttachmentsChange)return;const i=[];for(let r=0;r<n.length;r++){const c=n[r];(c.type.startsWith("image/")||c.type.startsWith("video/"))&&i.push(c)}if(i.length!==0){e.preventDefault();for(const r of i){const c=r.getAsFile();if(!c)continue;const d=c.type.startsWith("video/")?"Video":"Image";if(c.size>Je){const u=((a=(o=e.target)==null?void 0:o.closest)==null?void 0:a.call(o,".chat"))??document.querySelector(".chat");u&&Te(u,`${d} too large (${(c.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const h=new FileReader;h.onload=()=>{var S;const u=h.result,p=c.type.startsWith("video/"),v={id:Ye(),dataUrl:u,mimeType:c.type,fileName:p?c.name||"video.mp4":void 0},$=t.attachments??[];(S=t.onAttachmentsChange)==null||S.call(t,[...$,v])},h.readAsDataURL(c)}}}function nw(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=a=>{i.contains(a.target)||t.contains(a.target)||(i.classList.remove("active"),t.classList.remove("active"),document.removeEventListener("click",o,!0))};requestAnimationFrame(()=>document.addEventListener("click",o,!0))}}function iw(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 a=o.selectionStart??t.draft.length,r=o.selectionEnd??a,c=t.draft.slice(0,a),d=t.draft.slice(r);t.onDraftChange(c+i+d);const h=s==null?void 0:s.querySelector(".emoji-picker-popup"),u=s==null?void 0:s.querySelector(".chat-compose__emoji");h==null||h.classList.remove("active"),u==null||u.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const p=a+i.length;o.setSelectionRange(p,p)})}function sw(e){const t=e.attachments??[];return t.length===0?w:l`
3034
3039
  <div class="chat-attachments">
3035
3040
  ${t.map(n=>{var i;return n.fileName?l`
3036
3041
  <div class="chat-attachment chat-attachment--file">
@@ -3063,7 +3068,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3063
3068
  </div>
3064
3069
  `})}
3065
3070
  </div>
3066
- `}function mu(e){var $,S,M;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(S=($=e.sessions)==null?void 0:$.sessions)==null?void 0:S.find(y=>y.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",a=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const r=(((M=e.attachments)==null?void 0:M.length)??0)>0,d=e.connected?r?"Add a message...":"Message...":"Connecting…";dv({onSend:y=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],y]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var y;(y=e.requestUpdate)==null||y.call(e)}});const c=cv(),h=!c&&!e.draft.trim()&&!r&&!n,u=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),v=l`
3071
+ `}function mu(e){var $,S,M;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(S=($=e.sessions)==null?void 0:$.sessions)==null?void 0:S.find(y=>y.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",a=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const r=(((M=e.attachments)==null?void 0:M.length)??0)>0,c=e.connected?r?"Add a message...":"Message...":"Connecting…";dv({onSend:y=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],y]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var y;(y=e.requestUpdate)==null||y.call(e)}});const d=cv(),h=!d&&!e.draft.trim()&&!r&&!n,u=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),v=l`
3067
3072
  <div
3068
3073
  class="chat-thread"
3069
3074
  role="log"
@@ -3151,7 +3156,7 @@ ${e.sidebarContent}
3151
3156
 
3152
3157
  <div class="chat-compose">
3153
3158
  ${sw(e)}
3154
- ${c?pv():l`
3159
+ ${d?pv():l`
3155
3160
  <div class="chat-compose__row">
3156
3161
  <button
3157
3162
  class="chat-compose__emoji"
@@ -3187,7 +3192,7 @@ ${e.sidebarContent}
3187
3192
  @keydown=${y=>{y.key==="Enter"&&(y.isComposing||y.keyCode===229||y.shiftKey||e.connected&&(y.preventDefault(),t&&(e.onSend(),vl(y.target))))}}
3188
3193
  @input=${y=>{const b=y.target;e.onDraftChange(b.value),Gb(b)}}
3189
3194
  @paste=${y=>tw(y,e)}
3190
- placeholder=${d}
3195
+ placeholder=${c}
3191
3196
  ></textarea>
3192
3197
  </label>
3193
3198
  ${i?l`
@@ -3218,9 +3223,9 @@ ${e.sidebarContent}
3218
3223
  </div>
3219
3224
  </div>
3220
3225
  </section>
3221
- `}function ow(e){return e.map(t=>{if(t.kind!=="message")return t;const n=tc(t.message),i=nc(n.role),s=n.timestamp||Date.now();return{kind:"group",key:`group:${i}:${t.key}`,role:i,messages:[{message:t.message,key:t.key}],timestamp:s,isStreaming:!1}})}function aw(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 a=0;a<n.length;a++){const r=n[a],d=tc(r);if(!s&&d.role.toLowerCase()==="toolresult"){const c=r,u=(Array.isArray(c.content)?c.content:[]).filter(p=>{const v=p.type;return v==="image"||v==="file"});u.length>0&&t.push({kind:"message",key:co(r,a),message:{role:"assistant",content:u,timestamp:d.timestamp}});continue}t.push({kind:"message",key:co(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:co(i[a],a+n.length),message:i[a]});if(e.interimText&&t.push({kind:"interim",key:"interim:thinking",text:e.interimText}),e.stream!==null){const a=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:a,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:a})}for(const a of e.queue){const r=((o=a.attachments)==null?void 0:o.filter(c=>c.fileName).map(c=>c.fileName))??[],d=r.length>0?a.text?`${r.join(", ")}
3226
+ `}function ow(e){return e.map(t=>{if(t.kind!=="message")return t;const n=tc(t.message),i=nc(n.role),s=n.timestamp||Date.now();return{kind:"group",key:`group:${i}:${t.key}`,role:i,messages:[{message:t.message,key:t.key}],timestamp:s,isStreaming:!1}})}function aw(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 a=0;a<n.length;a++){const r=n[a],c=tc(r);if(!s&&c.role.toLowerCase()==="toolresult"){const d=r,u=(Array.isArray(d.content)?d.content:[]).filter(p=>{const v=p.type;return v==="image"||v==="file"});u.length>0&&t.push({kind:"message",key:co(r,a),message:{role:"assistant",content:u,timestamp:c.timestamp}});continue}t.push({kind:"message",key:co(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:co(i[a],a+n.length),message:i[a]});if(e.interimText&&t.push({kind:"interim",key:"interim:thinking",text:e.interimText}),e.stream!==null){const a=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:a,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:a})}for(const a of e.queue){const r=((o=a.attachments)==null?void 0:o.filter(d=>d.fileName).map(d=>d.fileName))??[],c=r.length>0?a.text?`${r.join(", ")}
3222
3227
 
3223
- ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,message:{role:"user",content:[{type:"text",text:d}],timestamp:a.createdAt}})}return ow(t)}function co(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 a=typeof n.timestamp=="number"?n.timestamp:null,r=typeof n.role=="string"?n.role:"unknown";return a!=null?`msg:${r}:${a}:${t}`:`msg:${r}:${t}`}function rw(e){if(!e)return"";const t=new Date(e*1e3);return t.toLocaleDateString([],{year:"numeric",month:"short",day:"numeric"})+" "+t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function yu(e){return e.replace(/@s\.whatsapp\.net$/,"").replace(/@g\.us$/,"")}function lw(e){const t=e.searchQuery.toLowerCase(),n=t?e.conversations.filter(i=>i.name.toLowerCase().includes(t)||i.jid.includes(t)):e.conversations;return l`
3228
+ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,message:{role:"user",content:[{type:"text",text:c}],timestamp:a.createdAt}})}return ow(t)}function co(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 a=typeof n.timestamp=="number"?n.timestamp:null,r=typeof n.role=="string"?n.role:"unknown";return a!=null?`msg:${r}:${a}:${t}`:`msg:${r}:${t}`}function rw(e){if(!e)return"";const t=new Date(e*1e3);return t.toLocaleDateString([],{year:"numeric",month:"short",day:"numeric"})+" "+t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function yu(e){return e.replace(/@s\.whatsapp\.net$/,"").replace(/@g\.us$/,"")}function lw(e){const t=e.searchQuery.toLowerCase(),n=t?e.conversations.filter(i=>i.name.toLowerCase().includes(t)||i.jid.includes(t)):e.conversations;return l`
3224
3229
  <div class="wa-list">
3225
3230
  <div class="wa-list__header">
3226
3231
  <input
@@ -3331,7 +3336,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3331
3336
  ${t==="whatsapp"&&e.whatsappProps?hw(e.whatsappProps):mu(e)}
3332
3337
  </div>
3333
3338
  </div>
3334
- `}async function vu(e){if(!(!e.client||!e.connected)){e.loading=!0,e.lastError=null;try{const t=await e.client.request("whatsapp.conversations",{accountId:e.accountId});e.conversations=t.conversations}catch(t){e.lastError=String(t)}finally{e.loading=!1}}}async function mw(e,t){if(!(!e.client||!e.connected)){e.selectedJid=t,e.messagesLoading=!0,e.messages=[],e.groupInfo=null,e.lastError=null;try{const n=await e.client.request("whatsapp.messages",{jid:t,limit:100,accountId:e.accountId});e.messages=n.messages}catch(n){e.lastError=String(n)}if(t.endsWith("@g.us"))try{const n=await e.client.request("whatsapp.groupInfo",{jid:t,accountId:e.accountId});e.groupInfo=n}catch{}e.messagesLoading=!1}}async function yw(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("whatsapp.setActivation",{jid:t,activation:n,accountId:e.accountId}),e.groupInfo&&(e.groupInfo.activation=n);const i=e.conversations.find(s=>s.jid===t);i&&(i.activation=n)}catch(i){e.lastError=String(i)}}function vw(e){return e?`${Yl(e)} (${os(e)})`:"n/a"}function bu(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?os(t.lastRunAtMs):"never";return`${n} · last ${i}`}function wu(e){const t=e.schedule;return t.kind==="at"?`One-time: ${Yl(t.atMs)}`:t.kind==="every"?`Every ${Xo(t.everyMs)}`:bw(t.expr,t.tz)}function bw(e,t){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[i,s,o,a,r]=n,d=t?` (${t.replace(/^.*\//,"").replace(/_/g," ")})`:"",c=(S,M)=>new Date(2e3,0,1,S,M).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),h=/^\d{1,2}$/.test(i)?parseInt(i,10):null,u=bl(s);if(h===null||!u)return`${e}${t?` (${t})`:""}`;const p=u.map(S=>c(S,h)),v=p.length<=3?p.join(" & "):`${p.slice(0,-1).join(", ")} & ${p[p.length-1]}`,$=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&a==="*"){if(r==="*")return`Daily at ${v}${d}`;if(r==="1-5")return`Weekdays at ${v}${d}`;if(r==="0,6"||r==="6,0")return`Weekends at ${v}${d}`;const S=bl(r);if(S)return`${S.map(y=>$[y%7]??String(y)).join(", ")} at ${v}${d}`}return`${e}${t?` (${t})`:""}`}function bl(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 ww(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 wl(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 a=i.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.toLowerCase()==="admins"?"All admins":r);s.push(a.join(", "))}return n&&n!=="last"&&s.push(`via ${n}`),s.join(" ")||null}let be=null;function kw(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 xw(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 $w(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function Sw(e){return e||"Default"}const Aw=l`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,Cw=l`<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>`,Ew=l`<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>`,gs=l`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,Tw=l`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,ku=l`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,_w=l`<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 kl(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return l`
3339
+ `}async function vu(e){if(!(!e.client||!e.connected)){e.loading=!0,e.lastError=null;try{const t=await e.client.request("whatsapp.conversations",{accountId:e.accountId});e.conversations=t.conversations}catch(t){e.lastError=String(t)}finally{e.loading=!1}}}async function mw(e,t){if(!(!e.client||!e.connected)){e.selectedJid=t,e.messagesLoading=!0,e.messages=[],e.groupInfo=null,e.lastError=null;try{const n=await e.client.request("whatsapp.messages",{jid:t,limit:100,accountId:e.accountId});e.messages=n.messages}catch(n){e.lastError=String(n)}if(t.endsWith("@g.us"))try{const n=await e.client.request("whatsapp.groupInfo",{jid:t,accountId:e.accountId});e.groupInfo=n}catch{}e.messagesLoading=!1}}async function yw(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("whatsapp.setActivation",{jid:t,activation:n,accountId:e.accountId}),e.groupInfo&&(e.groupInfo.activation=n);const i=e.conversations.find(s=>s.jid===t);i&&(i.activation=n)}catch(i){e.lastError=String(i)}}function vw(e){return e?`${Yl(e)} (${os(e)})`:"n/a"}function bu(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?os(t.lastRunAtMs):"never";return`${n} · last ${i}`}function wu(e){const t=e.schedule;return t.kind==="at"?`One-time: ${Yl(t.atMs)}`:t.kind==="every"?`Every ${Xo(t.everyMs)}`:bw(t.expr,t.tz)}function bw(e,t){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[i,s,o,a,r]=n,c=t?` (${t.replace(/^.*\//,"").replace(/_/g," ")})`:"",d=(S,M)=>new Date(2e3,0,1,S,M).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),h=/^\d{1,2}$/.test(i)?parseInt(i,10):null,u=bl(s);if(h===null||!u)return`${e}${t?` (${t})`:""}`;const p=u.map(S=>d(S,h)),v=p.length<=3?p.join(" & "):`${p.slice(0,-1).join(", ")} & ${p[p.length-1]}`,$=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&a==="*"){if(r==="*")return`Daily at ${v}${c}`;if(r==="1-5")return`Weekdays at ${v}${c}`;if(r==="0,6"||r==="6,0")return`Weekends at ${v}${c}`;const S=bl(r);if(S)return`${S.map(y=>$[y%7]??String(y)).join(", ")} at ${v}${c}`}return`${e}${t?` (${t})`:""}`}function bl(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 ww(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 wl(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 a=i.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.toLowerCase()==="admins"?"All admins":r);s.push(a.join(", "))}return n&&n!=="last"&&s.push(`via ${n}`),s.join(" ")||null}let be=null;function kw(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 xw(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 $w(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function Sw(e){return e||"Default"}const Aw=l`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,Cw=l`<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>`,Ew=l`<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>`,gs=l`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,Tw=l`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,ku=l`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,_w=l`<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 kl(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return l`
3335
3340
  ${Mw(e)}
3336
3341
  ${Pw(e)}
3337
3342
  ${n?Rw(e):w}
@@ -3843,11 +3848,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3843
3848
  </details>
3844
3849
  `:w}
3845
3850
  </div>
3846
- `}function Uw(e){var a;const t=((a=e.report)==null?void 0:a.skills)??[],n=e.filter.trim().toLowerCase(),i=e.typeFilter,s=t.filter(r=>i==="preloaded"&&!r.preloaded||i==="user"&&(r.preloaded||r.marketplace)||i==="licensed"&&!r.marketplace?!1:n?[r.name,r.description].join(" ").toLowerCase().includes(n):!0),o=(r,d)=>l`
3851
+ `}function Uw(e){var a;const t=((a=e.report)==null?void 0:a.skills)??[],n=e.filter.trim().toLowerCase(),i=e.typeFilter,s=t.filter(r=>i==="preloaded"&&!r.preloaded||i==="user"&&(r.preloaded||r.marketplace)||i==="licensed"&&!r.marketplace?!1:n?[r.name,r.description].join(" ").toLowerCase().includes(n):!0),o=(r,c)=>l`
3847
3852
  <button
3848
- class="chip ${i===d?"chip-ok":""}"
3849
- style="cursor: pointer; border: none; background: ${i===d?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${i===d?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
3850
- @click=${()=>e.onTypeFilterChange(d)}
3853
+ class="chip ${i===c?"chip-ok":""}"
3854
+ style="cursor: pointer; border: none; background: ${i===c?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${i===c?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
3855
+ @click=${()=>e.onTypeFilterChange(c)}
3851
3856
  >${r}</button>
3852
3857
  `;return l`
3853
3858
  <section class="card">
@@ -3893,7 +3898,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3893
3898
 
3894
3899
  ${e.detail?Kw(e):w}
3895
3900
  ${e.addModal?zw(e):w}
3896
- `}function Ww(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,a=[...e.missing.bins.map(d=>`bin:${d}`),...e.missing.env.map(d=>`env:${d}`),...e.missing.config.map(d=>`config:${d}`),...e.missing.os.map(d=>`os:${d}`)],r=[];return e.disabled&&r.push("disabled"),e.blockedByAllowlist&&r.push("blocked by allowlist"),l`
3901
+ `}function Ww(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,a=[...e.missing.bins.map(c=>`bin:${c}`),...e.missing.env.map(c=>`env:${c}`),...e.missing.config.map(c=>`config:${c}`),...e.missing.os.map(c=>`os:${c}`)],r=[];return e.disabled&&r.push("disabled"),e.blockedByAllowlist&&r.push("blocked by allowlist"),l`
3897
3902
  <div class="list-item" style="cursor: pointer;" @click=${()=>t.onViewDetail(e.name)}>
3898
3903
  <div class="list-main">
3899
3904
  <div class="list-title">
@@ -3910,7 +3915,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3910
3915
  class="chip ${e.alwaysActive?"chip-ok":""}"
3911
3916
  style="cursor: pointer; user-select: none;"
3912
3917
  title=${e.alwaysActive?"This skill is part of every conversation. Click to switch to on-demand.":"This skill loads only when relevant. Click to make it always active."}
3913
- @click=${d=>{d.stopPropagation(),t.onAlwaysActiveToggle(e.name,!e.alwaysActive)}}
3918
+ @click=${c=>{c.stopPropagation(),t.onAlwaysActiveToggle(e.name,!e.alwaysActive)}}
3914
3919
  >${e.alwaysActive?"Always active":"On demand"}</span>`}
3915
3920
  </div>
3916
3921
  ${a.length>0?l`
@@ -3924,7 +3929,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3924
3929
  </div>
3925
3930
  `:w}
3926
3931
  </div>
3927
- <div class="list-meta" @click=${d=>d.stopPropagation()}>
3932
+ <div class="list-meta" @click=${c=>c.stopPropagation()}>
3928
3933
  <div class="row" style="justify-content: flex-end; flex-wrap: wrap; gap: 6px;">
3929
3934
  ${e.preloaded?w:l`<button
3930
3935
  class="btn"
@@ -3967,7 +3972,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3967
3972
  <input
3968
3973
  type="password"
3969
3974
  .value=${i}
3970
- @input=${d=>t.onEdit(e.skillKey,d.target.value)}
3975
+ @input=${c=>t.onEdit(e.skillKey,c.target.value)}
3971
3976
  />
3972
3977
  </div>
3973
3978
  <button
@@ -3981,7 +3986,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3981
3986
  `:w}
3982
3987
  </div>
3983
3988
  </div>
3984
- `}function Kw(e){var d,c,h;const t=e.detail,n=["SKILL.md",...t.references.map(u=>u.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((d=t.references.find(u=>u.name===i))==null?void 0:d.content)??"",o=u=>{u.target.classList.contains("event-modal-overlay")&&e.onDetailClose()},a=(h=(c=e.report)==null?void 0:c.skills)==null?void 0:h.find(u=>u.name===t.name),r=a?!a.preloaded:!1;return l`
3989
+ `}function Kw(e){var c,d,h;const t=e.detail,n=["SKILL.md",...t.references.map(u=>u.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((c=t.references.find(u=>u.name===i))==null?void 0:c.content)??"",o=u=>{u.target.classList.contains("event-modal-overlay")&&e.onDetailClose()},a=(h=(d=e.report)==null?void 0:d.skills)==null?void 0:h.find(u=>u.name===t.name),r=a?!a.preloaded:!1;return l`
3985
3990
  <div class="event-modal-overlay" @click=${o}>
3986
3991
  <div class="event-modal" style="width: min(720px, 100%);" @click=${u=>u.stopPropagation()}>
3987
3992
  <div class="event-modal__header">
@@ -4022,25 +4027,25 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4022
4027
  `}
4023
4028
  </div>
4024
4029
  </div>
4025
- `}function Hw(e,t){const n=e.addForm,s=e.formSource==="installed"?"Save Skill":"Save Draft",o=n.references.length>0,a=e.editTab||"SKILL.md",r=n.references.find(c=>c.name===a),d=c=>l`
4030
+ `}function Hw(e,t){const n=e.addForm,s=e.formSource==="installed"?"Save Skill":"Save Draft",o=n.references.length>0,a=e.editTab||"SKILL.md",r=n.references.find(d=>d.name===a),c=d=>l`
4026
4031
  <button
4027
- class="chip ${c===a?"chip-ok":""}"
4028
- style="cursor: pointer; border: none; background: ${c===a?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${c===a?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
4029
- @click=${()=>e.onEditTab(c)}
4030
- >${c}</button>
4032
+ class="chip ${d===a?"chip-ok":""}"
4033
+ style="cursor: pointer; border: none; background: ${d===a?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${d===a?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
4034
+ @click=${()=>e.onEditTab(d)}
4035
+ >${d}</button>
4031
4036
  `;return l`
4032
4037
  <label class="field" style="margin-bottom: 12px;">
4033
4038
  <span>Name</span>
4034
4039
  <input
4035
4040
  .value=${n.name}
4036
- @input=${c=>e.onAddFormUpdate("name",c.target.value)}
4041
+ @input=${d=>e.onAddFormUpdate("name",d.target.value)}
4037
4042
  placeholder="my-skill"
4038
4043
  />
4039
4044
  </label>
4040
4045
  ${o?l`
4041
4046
  <div class="chip-row" style="margin-bottom: 12px; flex-wrap: wrap; gap: 4px;">
4042
- ${d("SKILL.md")}
4043
- ${n.references.map(c=>d(c.name))}
4047
+ ${c("SKILL.md")}
4048
+ ${n.references.map(d=>c(d.name))}
4044
4049
  </div>
4045
4050
  `:w}
4046
4051
  ${r?l`
@@ -4048,7 +4053,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4048
4053
  <span>${r.name}</span>
4049
4054
  <textarea
4050
4055
  .value=${r.content}
4051
- @input=${c=>e.onRefUpdate(r.name,c.target.value)}
4056
+ @input=${d=>e.onRefUpdate(r.name,d.target.value)}
4052
4057
  style="min-height: 260px; font-family: monospace; font-size: 12px; line-height: 1.5; resize: vertical; overflow-wrap: break-word; white-space: pre-wrap;"
4053
4058
  ></textarea>
4054
4059
  </label>
@@ -4057,7 +4062,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4057
4062
  <span>SKILL.md</span>
4058
4063
  <textarea
4059
4064
  .value=${n.skillContent}
4060
- @input=${c=>e.onAddFormUpdate("skillContent",c.target.value)}
4065
+ @input=${d=>e.onAddFormUpdate("skillContent",d.target.value)}
4061
4066
  style="min-height: 260px; font-family: monospace; font-size: 12px; line-height: 1.5; resize: vertical; overflow-wrap: break-word; white-space: pre-wrap;"
4062
4067
  placeholder="---\nname: my-skill\ndescription: What this skill does\n---\n\n# My Skill\n..."
4063
4068
  ></textarea>
@@ -4156,7 +4161,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4156
4161
  ${e.error?l`<div class="callout danger" style="margin-top: 10px;">${e.error}</div>`:w}
4157
4162
 
4158
4163
  <div class="log-stream" style="margin-top: 10px;" @scroll=${e.onScroll}>
4159
- ${n.length===0?l`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=xu(i.type,i.content),a=Jw(i,s),r=e.expandedIds.has(a),d=i.content.length>$l,c=r||!d?i.content:i.content.slice(0,$l)+"…";return l`
4164
+ ${n.length===0?l`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=xu(i.type,i.content),a=Jw(i,s),r=e.expandedIds.has(a),c=i.content.length>$l,d=r||!c?i.content:i.content.slice(0,$l)+"…";return l`
4160
4165
  <div class="log-row session-entry ${o}">
4161
4166
  <div class="log-row-header">
4162
4167
  <span class="log-time mono">${Gw(i.timestamp)}</span>
@@ -4167,8 +4172,8 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4167
4172
  ${i.toolCallId?l`<span class="session-call-id mono">${i.toolCallId.slice(0,12)}</span>`:w}
4168
4173
  ${i.model?l`<span class="session-model mono">${i.model}</span>`:w}
4169
4174
  </div>
4170
- <div class="log-message mono">${c}</div>
4171
- ${d?l`<button
4175
+ <div class="log-message mono">${d}</div>
4176
+ ${c?l`<button
4172
4177
  class="log-expand-btn"
4173
4178
  @click=${()=>e.onToggleExpand(a)}
4174
4179
  >${r?"Collapse":"Expand"}</button>`:w}
@@ -4419,7 +4424,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4419
4424
  <p>Connecting to gateway...</p>
4420
4425
  </div>
4421
4426
  </div>
4422
- `}function Sl(e){if(!e.show)return w;const t=Xe(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const a=v=>{var S;o=v.target.value;const $=(S=v.target.closest(".login-card"))==null?void 0:S.querySelector(".login-change-pin");$&&($.style.display=o==="__master__"?"":"none")},r=v=>$=>{const S=$.target;S.value=S.value.replace(/\D/g,"").slice(0,6),v(S.value)},d=v=>{const $=v.currentTarget,S=$.closest(".login-pin-wrapper"),M=S==null?void 0:S.querySelector("input");if(!M)return;const y=M.type==="text";M.type=y?"password":"text",$.classList.toggle("active",!y)},c=!n&&e.accounts.length>1?l`
4427
+ `}function Sl(e){if(!e.show)return w;const t=Xe(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const a=v=>{var S;o=v.target.value;const $=(S=v.target.closest(".login-card"))==null?void 0:S.querySelector(".login-change-pin");$&&($.style.display=o==="__master__"?"":"none")},r=v=>$=>{const S=$.target;S.value=S.value.replace(/\D/g,"").slice(0,6),v(S.value)},c=v=>{const $=v.currentTarget,S=$.closest(".login-pin-wrapper"),M=S==null?void 0:S.querySelector("input");if(!M)return;const y=M.type==="text";M.type=y?"password":"text",$.classList.toggle("active",!y)},d=!n&&e.accounts.length>1?l`
4423
4428
  <select
4424
4429
  class="login-account-select"
4425
4430
  @change=${a}
@@ -4438,7 +4443,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4438
4443
  <h2 class="login-title">Change PIN</h2>
4439
4444
  <p class="login-subtitle">Enter your current PIN, then choose a new one</p>
4440
4445
  <form class="login-form" @submit=${M}>
4441
- ${c}
4446
+ ${d}
4442
4447
  <div class="login-pin-wrapper">
4443
4448
  <input
4444
4449
  class="login-pin-input"
@@ -4452,7 +4457,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4452
4457
  @input=${r(y=>{v=y})}
4453
4458
  autofocus
4454
4459
  />
4455
- <button class="login-pin-toggle" type="button" @click=${d}>
4460
+ <button class="login-pin-toggle" type="button" @click=${c}>
4456
4461
  <span class="pin-eye-show">${I.eye}</span>
4457
4462
  <span class="pin-eye-hide">${I.eyeOff}</span>
4458
4463
  </button>
@@ -4469,7 +4474,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4469
4474
  ?disabled=${s}
4470
4475
  @input=${r(y=>{$=y})}
4471
4476
  />
4472
- <button class="login-pin-toggle" type="button" @click=${d}>
4477
+ <button class="login-pin-toggle" type="button" @click=${c}>
4473
4478
  <span class="pin-eye-show">${I.eye}</span>
4474
4479
  <span class="pin-eye-hide">${I.eyeOff}</span>
4475
4480
  </button>
@@ -4486,7 +4491,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4486
4491
  ?disabled=${s}
4487
4492
  @input=${r(y=>{S=y})}
4488
4493
  />
4489
- <button class="login-pin-toggle" type="button" @click=${d}>
4494
+ <button class="login-pin-toggle" type="button" @click=${c}>
4490
4495
  <span class="pin-eye-show">${I.eye}</span>
4491
4496
  <span class="pin-eye-hide">${I.eyeOff}</span>
4492
4497
  </button>
@@ -4517,7 +4522,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4517
4522
  ${n?"Set a PIN to protect this device":"Enter your PIN to continue"}
4518
4523
  </p>
4519
4524
  <form class="login-form" @submit=${p}>
4520
- ${c}
4525
+ ${d}
4521
4526
  <div class="login-pin-wrapper">
4522
4527
  <input
4523
4528
  class="login-pin-input"
@@ -4531,7 +4536,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4531
4536
  @input=${r(v=>{h=v})}
4532
4537
  autofocus
4533
4538
  />
4534
- <button class="login-pin-toggle" type="button" @click=${d}>
4539
+ <button class="login-pin-toggle" type="button" @click=${c}>
4535
4540
  <span class="pin-eye-show">${I.eye}</span>
4536
4541
  <span class="pin-eye-hide">${I.eyeOff}</span>
4537
4542
  </button>
@@ -4549,7 +4554,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4549
4554
  ?disabled=${e.busy}
4550
4555
  @input=${r(v=>{u=v})}
4551
4556
  />
4552
- <button class="login-pin-toggle" type="button" @click=${d}>
4557
+ <button class="login-pin-toggle" type="button" @click=${c}>
4553
4558
  <span class="pin-eye-show">${I.eye}</span>
4554
4559
  <span class="pin-eye-hide">${I.eyeOff}</span>
4555
4560
  </button>
@@ -4589,7 +4594,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4589
4594
  ${mu(t)}
4590
4595
  </div>
4591
4596
  </div>
4592
- `}async function mk(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 Vn(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 yk(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 a=o.hash;if(!a){e.workspacesError="Config hash missing; reload and retry.";return}const r={name:n,baseHash:a,whatsappAccountName:n};(i=t.workspacePath)!=null&&i.trim()&&(r.workspaceDir=t.workspacePath.trim());const d=await e.client.request("workspaces.create",r);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Vn(e),(s=t.onCreated)==null||s.call(t,d)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function vk(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 Vn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function bk(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 Vn(e)}catch(i){e.workspacesError=String(i)}}}const ki=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:yk,loadWorkspaces:Vn,removeWorkspace:vk,renameWorkspace:bk},Symbol.toStringTag,{value:"Module"})),Su={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"},Al=Su,zo={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Su));new Set(Object.values(zo));function wk(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 kk=4008;class xk{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 u;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,a=!1,r=this.opts.token;if(s){o=await lf();const p=(u=uf({deviceId:o.deviceId,role:t}))==null?void 0:u.token;r=p??this.opts.token,a=!!(p&&this.opts.token)}const d=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let c;if(s&&o){const p=Date.now(),v=this.connectNonce??void 0,$=wk({deviceId:o.deviceId,clientId:this.opts.clientName??Al.CONTROL_UI,clientMode:this.opts.mode??zo.WEBCHAT,role:t,scopes:n,signedAtMs:p,token:r??null,nonce:v}),S=await cf(o.privateKey,$);c={id:o.deviceId,publicKey:o.publicKey,signature:S,signedAt:p,nonce:v}}const h={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Al.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??zo.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:d,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",h).then(p=>{var v,$,S;(v=p==null?void 0:p.auth)!=null&&v.deviceToken&&o&&pf({deviceId:o.deviceId,role:p.auth.role??t,token:p.auth.deviceToken,scopes:p.auth.scopes??[]}),this.backoffMs=800,(S=($=this.opts).onHello)==null||S.call($,p)}).catch(()=>{var p;a&&o&&hf({deviceId:o.deviceId,role:t}),(p=this.ws)==null||p.close(kk,"connect failed")})}handleMessage(t){var s,o,a,r,d,c;let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const h=n;if(h.event==="connect.challenge"){const p=h.payload,v=p&&typeof p.nonce=="string"?p.nonce:null;v&&(this.connectNonce=v,this.sendConnect());return}const u=typeof h.seq=="number"?h.seq:null;u!==null&&(this.lastSeq!==null&&u>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:u})),this.lastSeq=u);try{(r=(a=this.opts).onEvent)==null||r.call(a,h)}catch(p){console.error("[gateway] event handler error:",p)}return}if(i.type==="res"){const h=n,u=this.pending.get(h.id);if(!u)return;if(this.pending.delete(h.id),h.ok)u.resolve(h.payload);else{const p=new Error(((d=h.error)==null?void 0:d.message)??"request failed");p.payload=h.payload,p.details=(c=h.error)==null?void 0:c.details,u.reject(p)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=as(),s={type:"req",id:i,method:t,params:n},o=new Promise((a,r)=>{this.pending.set(i,{resolve:d=>a(d),reject:r})});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 Ho(e){return typeof e=="object"&&e!==null}function $k(e){if(!Ho(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Ho(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 Sk(e){if(!Ho(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 Au(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Ak(e,t){const n=Au(e).filter(i=>i.id!==t.id);return n.push(t),n}function Cl(e,t){return Au(e).filter(n=>n.id!==t)}class Ck{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,a=this.deviceWidth/this.canvas.width,r=this.deviceHeight/this.canvas.height;return{x:Math.round(t*s*a),y:Math.round(n*o*r)}}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 uo=null;function Bn(){return uo||(uo=new Ck),uo}function Oa(e){return e instanceof Error?e.message:String(e)}async function Ek(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=Oa(t)}finally{e.browserLoading=!1}}async function Tk(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=Oa(t)}finally{e.browserLoading=!1}}}async function po(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 ho(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 _k(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=Oa(t)}}function Mk(e){e.browserInputMode=!e.browserInputMode}function Pk(e){e.browserFullscreen=!e.browserFullscreen,Bn().detach()}function Ik(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,Bn().updateFrame(t.data,t.metadata)}function Rk(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Lk(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function qo(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=bo(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function _i(e){return(await e.request("apikeys.list")).providers??[]}async function El(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Dk(e,t){await e.request("apikeys.remove",{provider:t})}async function Bk(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const ts="taskmaster_update_pending";async function Cu(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 Nk(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(ts,String(Date.now())),localStorage.removeItem(Fa)}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")Nn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw Nn(),new Error(o.result.reason||"Update failed")}catch(o){Nn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function Ok(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const a=t.name,r=t.index,d=t.total;e.updateMessage=`Updating: ${a} (${r+1}/${d})`;const c=e.updateProgressSteps.find(h=>h.index===r);c?(c.status="running",c.name=a):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:d,status:"running"}],(i=e.requestUpdate)==null||i.call(e)}else if(n==="step-done"){const a=t.name,r=t.index,d=t.total,c=t.ok,h=t.durationMs,u=e.updateProgressSteps.find(v=>v.index===r);u?(u.status=c?"done":"failed",u.durationMs=h):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:d,status:c?"done":"failed",durationMs:h}];const p=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${a} done (${r+1}/${d})`:`Update step failed: ${a}${p}`,(s=e.requestUpdate)==null||s.call(e)}else if(n==="complete"){if(t.status==="ok")e.updateMessage="Update complete — restarting gateway...";else{const r=t.reason;e.updateMessage=r?`Update failed: ${r}`:"Update failed",e.updateRunning=!1,Nn()}(o=e.requestUpdate)==null||o.call(e)}}async function Fk(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=Wk();Nn();try{const a=await e.client.request("update.lastResult",{});if(!a.ok||!a.result)return;const r=5*6e4,d=Date.now()-a.result.ts<r;if(!t&&!d||Kk(a.result.ts))return;e.updateLastResult=a.result;const c=(n=a.result.after)==null?void 0:n.version;if(a.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,a.result.status==="ok"){const h=(i=a.result.before)==null?void 0:i.version,u=c??a.result.currentVersion;e.updateMessage=h?`Updated: v${h} → v${u}`:`Updated to v${u}`}else{const h=a.result.reason??((s=a.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${h}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const Fa="taskmaster_update_dismissed";function Uk(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Fa,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function Wk(){try{const e=localStorage.getItem(ts);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(ts),!1):!0:!1}catch{return!1}}function Nn(){try{localStorage.removeItem(ts)}catch{}}function Kk(e){try{const t=localStorage.getItem(Fa);return t?Number(t)>=e:!1}catch{return!1}}const Tl="notification-banner";function zk(e){const t=document.getElementById(Tl);if(!e){t==null||t.remove();return}t&&t.remove();const n=document.createElement("div");n.id=Tl,Object.assign(n.style,{background:"rgba(255, 180, 50, 0.15)",border:"1px solid rgba(255, 180, 50, 0.3)",borderRadius:"8px",padding:"12px 16px",margin:"0 0 16px 0",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",color:"rgba(255, 255, 255, 0.9)",fontSize:"14px"});const i=document.createElement("span");i.textContent=e.message,n.appendChild(i);const s=document.createElement("button");s.setAttribute("aria-label","Dismiss"),s.textContent="×",Object.assign(s.style,{background:"none",border:"none",color:"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"18px",padding:"0 4px"}),s.addEventListener("click",()=>n.remove()),n.appendChild(s),(document.querySelector("main")??document.body).prepend(n)}function fo(e,t){var r,d,c;const n=(e??"").trim(),i=(r=t.mainSessionKey)==null?void 0:r.trim();if(!i)return n;if(!n)return i;const s=((d=t.mainKey)==null?void 0:d.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 Hk(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=fo(e.sessionKey,t),i=fo(e.settings.sessionKey,t),s=fo(e.settings.lastActiveSessionKey,t),o=n||i||e.sessionKey,a={...e.settings,sessionKey:i||o,lastActiveSessionKey:s||o},r=a.sessionKey!==e.settings.sessionKey||a.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),r&&at(e,a)}function Be(e){var o;e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;let t=null;const n=!!e.publicChat,i=e.setup||e.filesPage||e.browserPage||e.chatPage||e.adminsPage||e.contactsPage||e.advancedPage,s=n?"public-chat":i?"setup-ui":"taskmaster-control-ui";(o=e.client)==null||o.stop(),e.client=new xk({url:e.settings.gatewayUrl,token:n?void 0:e.settings.token.trim()?e.settings.token:void 0,password:n?void 0:e.password.trim()?e.password:void 0,clientName:s,mode:"webchat",role:n?"public":void 0,scopes:n?[]:void 0,onHello:a=>{var d,c;const r=((d=a.server)==null?void 0:d.version)??null;if(t!==null&&r!==null&&r!==t){window.location.reload();return}if(t===null&&(t=r),e.connected=!0,e.lastError=null,e.hello=a,n){_l(e,a),qo(e),(((c=e.publicChatConfig)==null?void 0:c.auth)??"anonymous")==="anonymous"&&Xk(e);return}zi()&&(wa(),e.uninstallDone=!1),_l(e,a),e.handleAccessCheck(),Fk(e).then(()=>{Cu(e)}),qo(e),mk(e),(e.chatPage||e.setup)&&Gk(e),da(e,{quiet:!0}),ca(e,{quiet:!0}),Vn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Fe(e),e.setup&&(Vk(e),Qk(e),Jk(e),Yk(e)),Wi(e)},onClose:({code:a,reason:r})=>{e.connected=!1,a!==1012&&(e.lastError=`disconnected (${a}): ${r||"no reason"}`)},onEvent:a=>qk(e,a),onGap:({expected:a,received:r})=>{console.warn(`[gateway] event gap: expected seq ${a}, got ${r}`),Wi(e)}}),e.client.start()}function qk(e,t){try{jk(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function jk(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;rh(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&ld(e,i.sessionKey);const s=ac(e,i);if((s==="final"||s==="error"||s==="aborted")&&(Zo(e),sg(e)),s==="final"){const o=e,a=Math.max((((n=o.chatMessages)==null?void 0:n.length)??0)+10,nn);Jt(o,{limit:a})}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.chatSuggestions=i.suggestions);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"){const i=t.payload;i&&xh(e,i),e.tab==="cron"&&e.loadCron()}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&ca(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=$k(t.payload);if(i){e.execApprovalQueue=Ak(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Cl(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){Ik(e,t.payload);return}if(t.event==="browser.handoff"){Rk(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Lk(e);return}if(t.event==="exec.approval.resolved"){const i=Sk(t.payload);i&&(e.execApprovalQueue=Cl(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){Ok(e,t.payload);return}if(t.event==="notification"){const i=t.payload;(i==null?void 0:i.category)==="model-fallback"&&zk(i);return}}function _l(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&&Hk(e,n.sessionDefaults)}async function Gk(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 Vk(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await _i(e.client)}catch{}}async function Qk(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function Jk(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("wifi.status");if(e.wifiStatus=t,t!=null&&t.connected&&t.signal==null)try{const[n,i]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiStatus=i,i.signal==null&&n.networks){const s=n.networks.find(o=>o.active);s&&(e.wifiStatus={...i,signal:s.signal})}}catch{}}catch{}}async function Yk(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("network.status");e.networkPort=t.port,e.networkHostname=t.hostname,e.networkPortInput=String(t.port),e.networkHostnameInput=t.hostname}catch{}}const Ml="taskmaster_public_id";function Eu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${Ml}=`));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=`${Ml}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function Xk(e){var n,i,s;if(!e.client||!e.connected)return;const t=Eu((n=e.publicChatConfig)==null?void 0:n.cookieTtlDays);try{const o=(i=e.publicChatConfig)==null?void 0:i.accountId,a=await e.client.request("public.session",{cookieId:t,accountId:o});if(a!=null&&a.sessionKey){e.publicChatSessionKey=a.sessionKey,e.sessionKey=a.sessionKey,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const r=((s=e.publicChatConfig)==null?void 0:s.accountId)??"";e.chatMessage=Kn(r,a.sessionKey),Jt(e)}}catch(o){console.error("[public-chat] failed to resolve anonymous session:",o),e.lastError="Failed to start chat session"}}let pe=!1,ie=null,Zt="",en="",tn="",ms="",cn="phone",On="";function Tu(e){return e.replace(/[\s\-()]/g,"")}function it(){pe=!1,ie=null,Zt="",en="",tn="",ms="",cn="phone",On=""}async function Zk(e){if(!e.client||!e.connected)return;const t=Eu(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){ie=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function Pl(e){if(!e.client||pe)return;const t=Tu(Zt);if(!t){ie="Please enter your phone number",e.requestUpdate();return}pe=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:tn.trim()||void 0,accountId:e.accountId,channel:On||void 0});n!=null&&n.ok?(ms=n.channel??"",cn="phone",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{pe=!1,e.requestUpdate()}}async function Il(e){if(!e.client||pe)return;const t=en.trim().toLowerCase();if(!t||!t.includes("@")){ie="Please enter a valid email address",e.requestUpdate();return}pe=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{identifier:t,accountId:e.accountId});n!=null&&n.ok?(ms=n.channel??"email",cn="email",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{pe=!1,e.requestUpdate()}}async function Rl(e,t){if(!(!e.client||pe)){if(!t.trim()){ie="Please enter the verification code",e.requestUpdate();return}pe=!0,ie=null,e.requestUpdate();try{const n=cn==="email"?en.trim().toLowerCase():Tu(Zt),i=await e.client.request("public.otp.verify",{identifier:n,code:t.trim(),accountId:e.accountId});i!=null&&i.ok&&i.sessionKey?(it(),e.onAuthenticated(i.sessionKey)):ie=(i==null?void 0:i.error)??"Invalid verification code"}catch(n){ie=n instanceof Error?n.message:"Verification failed"}finally{pe=!1,e.requestUpdate()}}}function Ve(e){return w}function xi(e){return l`
4597
+ `}async function mk(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 Vn(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 yk(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 a=o.hash;if(!a){e.workspacesError="Config hash missing; reload and retry.";return}const r={name:n,baseHash:a,whatsappAccountName:n};(i=t.workspacePath)!=null&&i.trim()&&(r.workspaceDir=t.workspacePath.trim());const c=await e.client.request("workspaces.create",r);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Vn(e),(s=t.onCreated)==null||s.call(t,c)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function vk(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 Vn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function bk(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 Vn(e)}catch(i){e.workspacesError=String(i)}}}const ki=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:yk,loadWorkspaces:Vn,removeWorkspace:vk,renameWorkspace:bk},Symbol.toStringTag,{value:"Module"})),Su={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"},Al=Su,zo={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Su));new Set(Object.values(zo));function wk(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 kk=4008;class xk{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 u;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,a=!1,r=this.opts.token;if(s){o=await lf();const p=(u=uf({deviceId:o.deviceId,role:t}))==null?void 0:u.token;r=p??this.opts.token,a=!!(p&&this.opts.token)}const c=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let d;if(s&&o){const p=Date.now(),v=this.connectNonce??void 0,$=wk({deviceId:o.deviceId,clientId:this.opts.clientName??Al.CONTROL_UI,clientMode:this.opts.mode??zo.WEBCHAT,role:t,scopes:n,signedAtMs:p,token:r??null,nonce:v}),S=await cf(o.privateKey,$);d={id:o.deviceId,publicKey:o.publicKey,signature:S,signedAt:p,nonce:v}}const h={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Al.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??zo.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:d,caps:[],auth:c,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",h).then(p=>{var v,$,S;(v=p==null?void 0:p.auth)!=null&&v.deviceToken&&o&&pf({deviceId:o.deviceId,role:p.auth.role??t,token:p.auth.deviceToken,scopes:p.auth.scopes??[]}),this.backoffMs=800,(S=($=this.opts).onHello)==null||S.call($,p)}).catch(()=>{var p;a&&o&&hf({deviceId:o.deviceId,role:t}),(p=this.ws)==null||p.close(kk,"connect failed")})}handleMessage(t){var s,o,a,r,c,d;let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const h=n;if(h.event==="connect.challenge"){const p=h.payload,v=p&&typeof p.nonce=="string"?p.nonce:null;v&&(this.connectNonce=v,this.sendConnect());return}const u=typeof h.seq=="number"?h.seq:null;u!==null&&(this.lastSeq!==null&&u>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:u})),this.lastSeq=u);try{(r=(a=this.opts).onEvent)==null||r.call(a,h)}catch(p){console.error("[gateway] event handler error:",p)}return}if(i.type==="res"){const h=n,u=this.pending.get(h.id);if(!u)return;if(this.pending.delete(h.id),h.ok)u.resolve(h.payload);else{const p=new Error(((c=h.error)==null?void 0:c.message)??"request failed");p.payload=h.payload,p.details=(d=h.error)==null?void 0:d.details,u.reject(p)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=as(),s={type:"req",id:i,method:t,params:n},o=new Promise((a,r)=>{this.pending.set(i,{resolve:c=>a(c),reject:r})});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 Ho(e){return typeof e=="object"&&e!==null}function $k(e){if(!Ho(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Ho(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 Sk(e){if(!Ho(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 Au(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Ak(e,t){const n=Au(e).filter(i=>i.id!==t.id);return n.push(t),n}function Cl(e,t){return Au(e).filter(n=>n.id!==t)}class Ck{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,a=this.deviceWidth/this.canvas.width,r=this.deviceHeight/this.canvas.height;return{x:Math.round(t*s*a),y:Math.round(n*o*r)}}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 uo=null;function Bn(){return uo||(uo=new Ck),uo}function Oa(e){return e instanceof Error?e.message:String(e)}async function Ek(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=Oa(t)}finally{e.browserLoading=!1}}async function Tk(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=Oa(t)}finally{e.browserLoading=!1}}}async function po(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 ho(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 _k(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=Oa(t)}}function Mk(e){e.browserInputMode=!e.browserInputMode}function Pk(e){e.browserFullscreen=!e.browserFullscreen,Bn().detach()}function Ik(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,Bn().updateFrame(t.data,t.metadata)}function Rk(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Lk(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function qo(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=bo(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function _i(e){return(await e.request("apikeys.list")).providers??[]}async function El(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Dk(e,t){await e.request("apikeys.remove",{provider:t})}async function Bk(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const ts="taskmaster_update_pending";async function Cu(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 Nk(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(ts,String(Date.now())),localStorage.removeItem(Fa)}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")Nn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw Nn(),new Error(o.result.reason||"Update failed")}catch(o){Nn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function Ok(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const a=t.name,r=t.index,c=t.total;e.updateMessage=`Updating: ${a} (${r+1}/${c})`;const d=e.updateProgressSteps.find(h=>h.index===r);d?(d.status="running",d.name=a):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:c,status:"running"}],(i=e.requestUpdate)==null||i.call(e)}else if(n==="step-done"){const a=t.name,r=t.index,c=t.total,d=t.ok,h=t.durationMs,u=e.updateProgressSteps.find(v=>v.index===r);u?(u.status=d?"done":"failed",u.durationMs=h):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:c,status:d?"done":"failed",durationMs:h}];const p=!d&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=d?`Updating: ${a} done (${r+1}/${c})`:`Update step failed: ${a}${p}`,(s=e.requestUpdate)==null||s.call(e)}else if(n==="complete"){if(t.status==="ok")e.updateMessage="Update complete — restarting gateway...";else{const r=t.reason;e.updateMessage=r?`Update failed: ${r}`:"Update failed",e.updateRunning=!1,Nn()}(o=e.requestUpdate)==null||o.call(e)}}async function Fk(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=Wk();Nn();try{const a=await e.client.request("update.lastResult",{});if(!a.ok||!a.result)return;const r=5*6e4,c=Date.now()-a.result.ts<r;if(!t&&!c||Kk(a.result.ts))return;e.updateLastResult=a.result;const d=(n=a.result.after)==null?void 0:n.version;if(a.result.status==="ok"&&d&&(e.currentVersion=d),e.updateAvailable=!1,a.result.status==="ok"){const h=(i=a.result.before)==null?void 0:i.version,u=d??a.result.currentVersion;e.updateMessage=h?`Updated: v${h} → v${u}`:`Updated to v${u}`}else{const h=a.result.reason??((s=a.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${h}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const Fa="taskmaster_update_dismissed";function Uk(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Fa,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function Wk(){try{const e=localStorage.getItem(ts);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(ts),!1):!0:!1}catch{return!1}}function Nn(){try{localStorage.removeItem(ts)}catch{}}function Kk(e){try{const t=localStorage.getItem(Fa);return t?Number(t)>=e:!1}catch{return!1}}const Tl="notification-banner";function zk(e){const t=document.getElementById(Tl);if(!e){t==null||t.remove();return}t&&t.remove();const n=document.createElement("div");n.id=Tl,Object.assign(n.style,{background:"rgba(255, 180, 50, 0.15)",border:"1px solid rgba(255, 180, 50, 0.3)",borderRadius:"8px",padding:"12px 16px",margin:"0 0 16px 0",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",color:"rgba(255, 255, 255, 0.9)",fontSize:"14px"});const i=document.createElement("span");i.textContent=e.message,n.appendChild(i);const s=document.createElement("button");s.setAttribute("aria-label","Dismiss"),s.textContent="×",Object.assign(s.style,{background:"none",border:"none",color:"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"18px",padding:"0 4px"}),s.addEventListener("click",()=>n.remove()),n.appendChild(s),(document.querySelector("main")??document.body).prepend(n)}function fo(e,t){var r,c,d;const n=(e??"").trim(),i=(r=t.mainSessionKey)==null?void 0:r.trim();if(!i)return n;if(!n)return i;const s=((c=t.mainKey)==null?void 0:c.trim())||"main",o=(d=t.defaultAgentId)==null?void 0:d.trim();return n==="main"||n===s||o&&(n===`agent:${o}:main`||n===`agent:${o}:${s}`)?i:n}function Hk(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=fo(e.sessionKey,t),i=fo(e.settings.sessionKey,t),s=fo(e.settings.lastActiveSessionKey,t),o=n||i||e.sessionKey,a={...e.settings,sessionKey:i||o,lastActiveSessionKey:s||o},r=a.sessionKey!==e.settings.sessionKey||a.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),r&&at(e,a)}function Be(e){var o;e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;let t=null;const n=!!e.publicChat,i=e.setup||e.filesPage||e.browserPage||e.chatPage||e.adminsPage||e.contactsPage||e.advancedPage,s=n?"public-chat":i?"setup-ui":"taskmaster-control-ui";(o=e.client)==null||o.stop(),e.client=new xk({url:e.settings.gatewayUrl,token:n?void 0:e.settings.token.trim()?e.settings.token:void 0,password:n?void 0:e.password.trim()?e.password:void 0,clientName:s,mode:"webchat",role:n?"public":void 0,scopes:n?[]:void 0,onHello:a=>{var c,d;const r=((c=a.server)==null?void 0:c.version)??null;if(t!==null&&r!==null&&r!==t){window.location.reload();return}if(t===null&&(t=r),e.connected=!0,e.lastError=null,e.hello=a,n){_l(e,a),qo(e),(((d=e.publicChatConfig)==null?void 0:d.auth)??"anonymous")==="anonymous"&&Xk(e);return}zi()&&(wa(),e.uninstallDone=!1),_l(e,a),e.handleAccessCheck(),Fk(e).then(()=>{Cu(e)}),qo(e),mk(e),(e.chatPage||e.setup)&&Gk(e),da(e,{quiet:!0}),ca(e,{quiet:!0}),Vn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Fe(e),e.setup&&(Vk(e),Qk(e),Jk(e),Yk(e)),Wi(e)},onClose:({code:a,reason:r})=>{e.connected=!1,a!==1012&&(e.lastError=`disconnected (${a}): ${r||"no reason"}`)},onEvent:a=>qk(e,a),onGap:({expected:a,received:r})=>{console.warn(`[gateway] event gap: expected seq ${a}, got ${r}`),Wi(e)}}),e.client.start()}function qk(e,t){try{jk(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function jk(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;rh(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&ld(e,i.sessionKey);const s=ac(e,i);if((s==="final"||s==="error"||s==="aborted")&&(Zo(e),sg(e)),s==="final"){const o=e,a=Math.max((((n=o.chatMessages)==null?void 0:n.length)??0)+10,nn);Jt(o,{limit:a})}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.chatSuggestions=i.suggestions);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"){const i=t.payload;i&&xh(e,i),e.tab==="cron"&&e.loadCron()}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&ca(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=$k(t.payload);if(i){e.execApprovalQueue=Ak(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Cl(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){Ik(e,t.payload);return}if(t.event==="browser.handoff"){Rk(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Lk(e);return}if(t.event==="exec.approval.resolved"){const i=Sk(t.payload);i&&(e.execApprovalQueue=Cl(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){Ok(e,t.payload);return}if(t.event==="notification"){const i=t.payload;(i==null?void 0:i.category)==="model-fallback"&&zk(i);return}}function _l(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&&Hk(e,n.sessionDefaults)}async function Gk(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 Vk(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await _i(e.client)}catch{}}async function Qk(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function Jk(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("wifi.status");if(e.wifiStatus=t,t!=null&&t.connected&&t.signal==null)try{const[n,i]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiStatus=i,i.signal==null&&n.networks){const s=n.networks.find(o=>o.active);s&&(e.wifiStatus={...i,signal:s.signal})}}catch{}}catch{}}async function Yk(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("network.status");e.networkPort=t.port,e.networkHostname=t.hostname,e.networkPortInput=String(t.port),e.networkHostnameInput=t.hostname}catch{}}const Ml="taskmaster_public_id";function Eu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${Ml}=`));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=`${Ml}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function Xk(e){var n,i,s;if(!e.client||!e.connected)return;const t=Eu((n=e.publicChatConfig)==null?void 0:n.cookieTtlDays);try{const o=(i=e.publicChatConfig)==null?void 0:i.accountId,a=await e.client.request("public.session",{cookieId:t,accountId:o});if(a!=null&&a.sessionKey){e.publicChatSessionKey=a.sessionKey,e.sessionKey=a.sessionKey,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const r=((s=e.publicChatConfig)==null?void 0:s.accountId)??"";e.chatMessage=Kn(r,a.sessionKey),Jt(e)}}catch(o){console.error("[public-chat] failed to resolve anonymous session:",o),e.lastError="Failed to start chat session"}}let pe=!1,ie=null,Zt="",en="",tn="",ms="",cn="phone",On="";function Tu(e){return e.replace(/[\s\-()]/g,"")}function it(){pe=!1,ie=null,Zt="",en="",tn="",ms="",cn="phone",On=""}async function Zk(e){if(!e.client||!e.connected)return;const t=Eu(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){ie=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function Pl(e){if(!e.client||pe)return;const t=Tu(Zt);if(!t){ie="Please enter your phone number",e.requestUpdate();return}pe=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:tn.trim()||void 0,accountId:e.accountId,channel:On||void 0});n!=null&&n.ok?(ms=n.channel??"",cn="phone",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{pe=!1,e.requestUpdate()}}async function Il(e){if(!e.client||pe)return;const t=en.trim().toLowerCase();if(!t||!t.includes("@")){ie="Please enter a valid email address",e.requestUpdate();return}pe=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{identifier:t,accountId:e.accountId});n!=null&&n.ok?(ms=n.channel??"email",cn="email",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{pe=!1,e.requestUpdate()}}async function Rl(e,t){if(!(!e.client||pe)){if(!t.trim()){ie="Please enter the verification code",e.requestUpdate();return}pe=!0,ie=null,e.requestUpdate();try{const n=cn==="email"?en.trim().toLowerCase():Tu(Zt),i=await e.client.request("public.otp.verify",{identifier:n,code:t.trim(),accountId:e.accountId});i!=null&&i.ok&&i.sessionKey?(it(),e.onAuthenticated(i.sessionKey)):ie=(i==null?void 0:i.error)??"Invalid verification code"}catch(n){ie=n instanceof Error?n.message:"Verification failed"}finally{pe=!1,e.requestUpdate()}}}function Ve(e){return w}function xi(e){return l`
4593
4598
  <div class="public-auth__form">
4594
4599
  <label class="field public-auth__field">
4595
4600
  <span>Your name (optional)</span>
@@ -4767,7 +4772,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4767
4772
  ${xi(e)}
4768
4773
  </div>
4769
4774
  </div>
4770
- `}const s=e.verifyMethods??["whatsapp","sms"],o=s.includes("whatsapp")&&(!e.otpChannels||e.otpChannels.includes("whatsapp")),a=s.includes("sms"),r=s.includes("email"),c=o||a||s.includes("phone")||r;if(n==="phone"||n==="email"||n==="otp"){const h=n==="email"||n==="otp"&&cn==="email",p=h?"Verify your email address to continue your conversation across devices.":`Verify your phone number to receive a code via ${h?"email":On==="sms"?"SMS":"WhatsApp"}.`;return l`
4775
+ `}const s=e.verifyMethods??["whatsapp","sms"],o=s.includes("whatsapp")&&(!e.otpChannels||e.otpChannels.includes("whatsapp")),a=s.includes("sms"),r=s.includes("email"),d=o||a||s.includes("phone")||r;if(n==="phone"||n==="email"||n==="otp"){const h=n==="email"||n==="otp"&&cn==="email",p=h?"Verify your email address to continue your conversation across devices.":`Verify your phone number to receive a code via ${h?"email":On==="sms"?"SMS":"WhatsApp"}.`;return l`
4771
4776
  <div class="setup-container">
4772
4777
  <div class="public-auth">
4773
4778
  ${Ve()}
@@ -4820,14 +4825,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4820
4825
  </button>
4821
4826
  `:w}
4822
4827
  </div>
4823
- ${c?l`
4828
+ ${d?l`
4824
4829
  <p class="public-auth__hint">
4825
4830
  Authenticating lets you continue your conversation across devices.
4826
4831
  </p>
4827
4832
  `:w}
4828
4833
  </div>
4829
4834
  </div>
4830
- `}function Ua(){return{enabled:!1,publicAgentEnabled:!0,days:{monday:{start:"09:00",end:"17:00",closed:!1},tuesday:{start:"09:00",end:"17:00",closed:!1},wednesday:{start:"09:00",end:"17:00",closed:!1},thursday:{start:"09:00",end:"17:00",closed:!1},friday:{start:"09:00",end:"17:00",closed:!1},saturday:{start:"09:00",end:"17:00",closed:!0},sunday:{start:"09:00",end:"17:00",closed:!0}},closedDates:[]}}const _u=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];async function Wa(e){if(!(!e.client||!e.connected)&&!e.openingHoursLoading){e.openingHoursLoading=!0,e.openingHoursError=null;try{const t=await e.client.request("business.openingHours.get",{});if(t.openingHours){const n=t.openingHours,i={};for(const s of _u){const o=n.schedule[s];o==null?i[s]={start:"09:00",end:"17:00",closed:!0}:i[s]={start:o.start,end:o.end,closed:!1}}e.openingHoursForm={enabled:n.enabled,publicAgentEnabled:t.publicAgentEnabled,days:i,closedDates:[...n.closedDates??[]].sort()}}else{const n=Ua();n.publicAgentEnabled=t.publicAgentEnabled,e.openingHoursForm=n}}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursLoading=!1}}}async function Mu(e){if(!(!e.client||!e.connected||e.openingHoursBusy)){e.openingHoursBusy=!0,e.openingHoursError=null;try{const t=e.openingHoursForm,n={};for(const a of _u){const r=t.days[a];n[a]=r!=null&&r.closed?null:{start:r.start,end:r.end}}const i=Intl.DateTimeFormat().resolvedOptions().timeZone,s={enabled:t.enabled,timezone:i,schedule:n,closedDates:t.closedDates.length>0?[...t.closedDates].sort():void 0},o=await e.client.request("config.get",{});await e.client.request("config.patch",{raw:JSON.stringify({business:{openingHours:s,publicAgentEnabled:t.publicAgentEnabled}}),baseHash:o.hash,note:"Opening hours updated"}),await Wa(e)}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursBusy=!1}}}const t0=Object.freeze(Object.defineProperty({__proto__:null,defaultOpeningHoursForm:Ua,loadOpeningHours:Wa,saveOpeningHours:Mu},Symbol.toStringTag,{value:"Module"}));function n0(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 a=o.match;if(!a||typeof a!="object"||(a.channel??"").toLowerCase()!=="whatsapp")continue;const d=a.peer;if(!d||typeof d!="object"||d.kind!=="dm")continue;const c=d.id??"";c&&i.push({phone:c,paired:((s=o.meta)==null?void 0:s.paired)===!0})}return i.sort((o,a)=>o.paired&&!a.paired?-1:!o.paired&&a.paired?1:0),i}function Pu(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,a=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const h=c.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")continue;const p=h.peer;if(!p||typeof p!="object"||p.kind!=="dm")continue;const v=p.id??"";v&&(c.meta&&o.set(v,c.meta),h.accountId&&a.set(v,h.accountId))}const r=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const h=c.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")return!0;const p=h.peer;return!p||typeof p!="object"?!0:p.kind!=="dm"}),d=t.map(c=>{const h=i??a.get(c.phone),u={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};h&&(u.accountId=h);const p={agentId:n,match:u},v=o.get(c.phone);return v?p.meta=v:c.paired&&(p.meta={paired:!0}),p});return[...r,...d]}async function ys(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=lt(s??{}),e.adminPhones=n0(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function Iu(e,t,n,i){var a,r;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(d=>d.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const d=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=d.bindings??[],h=[...e.adminPhones,{phone:o}],u=Pu(c,h,s,i);cc(d,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const v=At(d);await e.client.request("config.set",{raw:v,baseHash:p}),await ys(e,n)}catch(d){e.adminsError=String(d)}finally{e.adminsSaving=!1}}async function Ru(e,t,n,i){var a,r;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(d=>d.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 d=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=d.bindings??[],h=e.adminPhones.filter($=>$.phone!==t),u=Pu(c,h,s,i);cc(d,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const v=At(d);await e.client.request("config.set",{raw:v,baseHash:p}),await ys(e,n)}catch(d){e.adminsError=String(d)}finally{e.adminsSaving=!1}}const i0=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:Iu,loadAdmins:ys,removeAdmin:Ru},Symbol.toStringTag,{value:"Module"}));async function Pt(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 Lu(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 Pt(e,i)}catch(a){e.contactsError=String(a)}finally{e.contactsSaving=!1}}async function Du(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 Pt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function jo(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 Pt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Bu(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 Pt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const s0=Object.freeze(Object.defineProperty({__proto__:null,addContact:Lu,deleteContact:Du,deleteContactField:Bu,loadContacts:Pt,setContactField:jo},Symbol.toStringTag,{value:"Module"}));let wt=null,Mi=null,Pi=null;const mo=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function Kt(){wt&&(clearInterval(wt),wt=null),Mi&&(clearInterval(Mi),Mi=null),Pi&&(clearTimeout(Pi),Pi=null)}function Sn(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},onRestartGateway:()=>e.handleGatewayRestart()}}function o0(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},onRestartGateway:()=>e.handleGatewayRestart()}}function a0(e){const t=we(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 Ka(e){const t=we(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function r0(e){var i;const t=we(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 l0(e){return e.selectedWorkspace??void 0}function we(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const c0=/^data:/i,d0=/^https?:\/\//i;function Dl(e){var r,d;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=Jl(e.sessionKey),i=(n==null?void 0:n.agentId)??((d=e.agentsList)==null?void 0:d.defaultId)??"main",s=t.find(c=>c.id===i),o=s==null?void 0:s.identity,a=(o==null?void 0:o.avatarUrl)??(o==null?void 0:o.avatar);if(a)return c0.test(a)||d0.test(a)?a:o==null?void 0:o.avatarUrl}function u0(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 p0(e){var a;if(!e)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const t=(a=e.channelAccounts)==null?void 0:a.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 h0(e){var a;const t=(a=e.configSnapshot)==null?void 0:a.config;if(!t)return null;const n=t.bindings;if(!Array.isArray(n))return null;const i=n.find(r=>{var d,c;return((d=r.match)==null?void 0:d.channel)==="imessage"&&((c=r.meta)==null?void 0:c.imessageOwner)});if(!i)return null;const s=i.agentId;for(const r of e.workspaces)if(r.agents.some(d=>d.id===s))return r.name;if(s==="admin"||s==="public"){const r=e.workspaces.find(d=>d.isDefault);return(r==null?void 0:r.name)??null}const o=s.replace(/-(admin|public)$/,"");if(o!==s){const r=e.workspaces.find(d=>d.name===o);return(r==null?void 0:r.name)??null}return null}function Ii(e){const t=Object.create(null);return Object.defineProperties(t,{client:{get:()=>e.client,set:()=>{}},connected:{get:()=>e.connected,set:()=>{}},conversations:{get:()=>e.waConversations,set:n=>{e.waConversations=n}},selectedJid:{get:()=>e.waSelectedJid,set:n=>{e.waSelectedJid=n}},messages:{get:()=>e.waMessages,set:n=>{e.waMessages=n}},groupInfo:{get:()=>e.waGroupInfo,set:n=>{e.waGroupInfo=n}},loading:{get:()=>e.waLoading,set:n=>{e.waLoading=n}},messagesLoading:{get:()=>e.waMessagesLoading,set:n=>{e.waMessagesLoading=n}},searchQuery:{get:()=>e.waSearchQuery,set:n=>{e.waSearchQuery=n}},composeDraft:{get:()=>e.waComposeDraft,set:n=>{e.waComposeDraft=n}},sending:{get:()=>e.waSending,set:n=>{e.waSending=n}},lastError:{get:()=>e.waLastError,set:n=>{e.waLastError=n}},accountId:{get:()=>Ka(e),set:()=>{}}}),t}function f0(){requestAnimationFrame(()=>{const e=document.querySelector(".wa-messages");e&&(e.scrollTop=e.scrollHeight)})}function g0(e){return{client:e.client,connected:e.connected,conversations:e.waConversations??[],selectedJid:e.waSelectedJid??null,messages:e.waMessages??[],groupInfo:e.waGroupInfo??null,loading:e.waLoading??!1,messagesLoading:e.waMessagesLoading??!1,searchQuery:e.waSearchQuery??"",composeDraft:e.waComposeDraft??"",sending:e.waSending??!1,lastError:e.waLastError??null,accountId:Ka(e),onSelectConversation:t=>{const n=Ii(e);mw(n,t).then(()=>{e.requestUpdate(),f0()})},onBack:()=>{e.waSelectedJid=null,e.waMessages=[],e.waGroupInfo=null,e.requestUpdate()},onSearchChange:t=>{e.waSearchQuery=t,e.requestUpdate()},onActivationChange:(t,n)=>{const i=Ii(e);yw(i,t,n).then(()=>e.requestUpdate())},onRefresh:()=>{const t=Ii(e);vu(t).then(()=>e.requestUpdate())},requestUpdate:()=>e.requestUpdate()}}function m0(e){var t,n,i,s,o,a,r,d,c,h;if(e.embeddingDownloading&&!e.publicChat)return l`
4835
+ `}function Ua(){return{enabled:!1,publicAgentEnabled:!0,days:{monday:{start:"09:00",end:"17:00",closed:!1},tuesday:{start:"09:00",end:"17:00",closed:!1},wednesday:{start:"09:00",end:"17:00",closed:!1},thursday:{start:"09:00",end:"17:00",closed:!1},friday:{start:"09:00",end:"17:00",closed:!1},saturday:{start:"09:00",end:"17:00",closed:!0},sunday:{start:"09:00",end:"17:00",closed:!0}},closedDates:[]}}const _u=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];async function Wa(e){if(!(!e.client||!e.connected)&&!e.openingHoursLoading){e.openingHoursLoading=!0,e.openingHoursError=null;try{const t=await e.client.request("business.openingHours.get",{});if(t.openingHours){const n=t.openingHours,i={};for(const s of _u){const o=n.schedule[s];o==null?i[s]={start:"09:00",end:"17:00",closed:!0}:i[s]={start:o.start,end:o.end,closed:!1}}e.openingHoursForm={enabled:n.enabled,publicAgentEnabled:t.publicAgentEnabled,days:i,closedDates:[...n.closedDates??[]].sort()}}else{const n=Ua();n.publicAgentEnabled=t.publicAgentEnabled,e.openingHoursForm=n}}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursLoading=!1}}}async function Mu(e){if(!(!e.client||!e.connected||e.openingHoursBusy)){e.openingHoursBusy=!0,e.openingHoursError=null;try{const t=e.openingHoursForm,n={};for(const a of _u){const r=t.days[a];n[a]=r!=null&&r.closed?null:{start:r.start,end:r.end}}const i=Intl.DateTimeFormat().resolvedOptions().timeZone,s={enabled:t.enabled,timezone:i,schedule:n,closedDates:t.closedDates.length>0?[...t.closedDates].sort():void 0},o=await e.client.request("config.get",{});await e.client.request("config.patch",{raw:JSON.stringify({business:{openingHours:s,publicAgentEnabled:t.publicAgentEnabled}}),baseHash:o.hash,note:"Opening hours updated"}),await Wa(e)}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursBusy=!1}}}const t0=Object.freeze(Object.defineProperty({__proto__:null,defaultOpeningHoursForm:Ua,loadOpeningHours:Wa,saveOpeningHours:Mu},Symbol.toStringTag,{value:"Module"}));function n0(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 a=o.match;if(!a||typeof a!="object"||(a.channel??"").toLowerCase()!=="whatsapp")continue;const c=a.peer;if(!c||typeof c!="object"||c.kind!=="dm")continue;const d=c.id??"";d&&i.push({phone:d,paired:((s=o.meta)==null?void 0:s.paired)===!0})}return i.sort((o,a)=>o.paired&&!a.paired?-1:!o.paired&&a.paired?1:0),i}function Pu(e,t,n="admin",i){const s=d=>d===n||d==="management",o=new Map,a=new Map;for(const d of e){if(!d||typeof d!="object"||!s(d.agentId))continue;const h=d.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")continue;const p=h.peer;if(!p||typeof p!="object"||p.kind!=="dm")continue;const v=p.id??"";v&&(d.meta&&o.set(v,d.meta),h.accountId&&a.set(v,h.accountId))}const r=e.filter(d=>{if(!d||typeof d!="object"||!s(d.agentId))return!0;const h=d.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")return!0;const p=h.peer;return!p||typeof p!="object"?!0:p.kind!=="dm"}),c=t.map(d=>{const h=i??a.get(d.phone),u={channel:"whatsapp",peer:{kind:"dm",id:d.phone}};h&&(u.accountId=h);const p={agentId:n,match:u},v=o.get(d.phone);return v?p.meta=v:d.paired&&(p.meta={paired:!0}),p});return[...r,...c]}async function ys(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=lt(s??{}),e.adminPhones=n0(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function Iu(e,t,n,i){var a,r;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(c=>c.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const c=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),d=c.bindings??[],h=[...e.adminPhones,{phone:o}],u=Pu(d,h,s,i);cc(c,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const v=At(c);await e.client.request("config.set",{raw:v,baseHash:p}),await ys(e,n)}catch(c){e.adminsError=String(c)}finally{e.adminsSaving=!1}}async function Ru(e,t,n,i){var a,r;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(c=>c.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 c=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),d=c.bindings??[],h=e.adminPhones.filter($=>$.phone!==t),u=Pu(d,h,s,i);cc(c,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const v=At(c);await e.client.request("config.set",{raw:v,baseHash:p}),await ys(e,n)}catch(c){e.adminsError=String(c)}finally{e.adminsSaving=!1}}const i0=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:Iu,loadAdmins:ys,removeAdmin:Ru},Symbol.toStringTag,{value:"Module"}));async function Pt(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 Lu(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 Pt(e,i)}catch(a){e.contactsError=String(a)}finally{e.contactsSaving=!1}}async function Du(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 Pt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function jo(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 Pt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Bu(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 Pt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const s0=Object.freeze(Object.defineProperty({__proto__:null,addContact:Lu,deleteContact:Du,deleteContactField:Bu,loadContacts:Pt,setContactField:jo},Symbol.toStringTag,{value:"Module"}));let wt=null,Mi=null,Pi=null;const mo=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function Kt(){wt&&(clearInterval(wt),wt=null),Mi&&(clearInterval(Mi),Mi=null),Pi&&(clearTimeout(Pi),Pi=null)}function Sn(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},onRestartGateway:()=>e.handleGatewayRestart()}}function o0(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},onRestartGateway:()=>e.handleGatewayRestart()}}function a0(e){const t=we(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 Ka(e){const t=we(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function r0(e){var i;const t=we(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 l0(e){return e.selectedWorkspace??void 0}function we(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const c0=/^data:/i,d0=/^https?:\/\//i;function Dl(e){var r,c;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=Jl(e.sessionKey),i=(n==null?void 0:n.agentId)??((c=e.agentsList)==null?void 0:c.defaultId)??"main",s=t.find(d=>d.id===i),o=s==null?void 0:s.identity,a=(o==null?void 0:o.avatarUrl)??(o==null?void 0:o.avatar);if(a)return c0.test(a)||d0.test(a)?a:o==null?void 0:o.avatarUrl}function u0(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 p0(e){var a;if(!e)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const t=(a=e.channelAccounts)==null?void 0:a.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 h0(e){var a;const t=(a=e.configSnapshot)==null?void 0:a.config;if(!t)return null;const n=t.bindings;if(!Array.isArray(n))return null;const i=n.find(r=>{var c,d;return((c=r.match)==null?void 0:c.channel)==="imessage"&&((d=r.meta)==null?void 0:d.imessageOwner)});if(!i)return null;const s=i.agentId;for(const r of e.workspaces)if(r.agents.some(c=>c.id===s))return r.name;if(s==="admin"||s==="public"){const r=e.workspaces.find(c=>c.isDefault);return(r==null?void 0:r.name)??null}const o=s.replace(/-(admin|public)$/,"");if(o!==s){const r=e.workspaces.find(c=>c.name===o);return(r==null?void 0:r.name)??null}return null}function Ii(e){const t=Object.create(null);return Object.defineProperties(t,{client:{get:()=>e.client,set:()=>{}},connected:{get:()=>e.connected,set:()=>{}},conversations:{get:()=>e.waConversations,set:n=>{e.waConversations=n}},selectedJid:{get:()=>e.waSelectedJid,set:n=>{e.waSelectedJid=n}},messages:{get:()=>e.waMessages,set:n=>{e.waMessages=n}},groupInfo:{get:()=>e.waGroupInfo,set:n=>{e.waGroupInfo=n}},loading:{get:()=>e.waLoading,set:n=>{e.waLoading=n}},messagesLoading:{get:()=>e.waMessagesLoading,set:n=>{e.waMessagesLoading=n}},searchQuery:{get:()=>e.waSearchQuery,set:n=>{e.waSearchQuery=n}},composeDraft:{get:()=>e.waComposeDraft,set:n=>{e.waComposeDraft=n}},sending:{get:()=>e.waSending,set:n=>{e.waSending=n}},lastError:{get:()=>e.waLastError,set:n=>{e.waLastError=n}},accountId:{get:()=>Ka(e),set:()=>{}}}),t}function f0(){requestAnimationFrame(()=>{const e=document.querySelector(".wa-messages");e&&(e.scrollTop=e.scrollHeight)})}function g0(e){return{client:e.client,connected:e.connected,conversations:e.waConversations??[],selectedJid:e.waSelectedJid??null,messages:e.waMessages??[],groupInfo:e.waGroupInfo??null,loading:e.waLoading??!1,messagesLoading:e.waMessagesLoading??!1,searchQuery:e.waSearchQuery??"",composeDraft:e.waComposeDraft??"",sending:e.waSending??!1,lastError:e.waLastError??null,accountId:Ka(e),onSelectConversation:t=>{const n=Ii(e);mw(n,t).then(()=>{e.requestUpdate(),f0()})},onBack:()=>{e.waSelectedJid=null,e.waMessages=[],e.waGroupInfo=null,e.requestUpdate()},onSearchChange:t=>{e.waSearchQuery=t,e.requestUpdate()},onActivationChange:(t,n)=>{const i=Ii(e);yw(i,t,n).then(()=>e.requestUpdate())},onRefresh:()=>{const t=Ii(e);vu(t).then(()=>e.requestUpdate())},requestUpdate:()=>e.requestUpdate()}}function m0(e){var t,n,i,s,o,a,r,c,d,h;if(e.embeddingDownloading&&!e.publicChat)return l`
4831
4836
  <div class="setup-container">
4832
4837
  <div class="setup-card" style="text-align:center; max-width:420px;">
4833
4838
  <div class="setup-spinner"></div>
@@ -4848,7 +4853,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4848
4853
  <p>Connecting...</p>
4849
4854
  </div>
4850
4855
  </div>
4851
- `;if(!e.publicChatAuthenticated)return e0({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,otpChannels:e.publicChatConfig.otpChannels,verifyMethods:e.publicChatConfig.verifyMethods,onAuthenticated:$=>{var M;e.publicChatSessionKey=$,e.sessionKey=$,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const S=((M=e.publicChatConfig)==null?void 0:M.accountId)??"";e.chatMessage=Kn(S,$),ae(async()=>{const{loadChatHistory:y}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:y}},void 0,import.meta.url).then(({loadChatHistory:y})=>{y(e)})},onAuthStepChange:$=>{e.publicChatAuthStep=$},requestUpdate:()=>{e.requestUpdate()}});const u=(t=e.publicChatConfig)==null?void 0:t.greeting,p=e.chatMessages,v=!e.chatLoading&&u?[{role:"assistant",content:[{type:"text",text:u}],timestamp:0},...Array.isArray(p)?p:[]]:p;return gk({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:v,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Dl(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,suggestions:e.chatSuggestions,onSuggestionClick:$=>{e.chatMessage=$,e.chatSuggestions=[],e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),ae(async()=>{const{loadChatHistory:$}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:$}},void 0,import.meta.url).then(({loadChatHistory:$})=>{$(e)})),onDraftChange:$=>{var M;e.chatMessage=$;const S=((M=e.publicChatConfig)==null?void 0:M.accountId)??"";wr(S,e.sessionKey,$)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:$=>e.chatAttachments=$,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:$=>e.removeQueuedMessage($),onChatScroll:$=>e.handleChatScroll($),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}})}if(e.connected&&e.accessState.checked){const{accessState:u}=e;if(u.hasPins&&!u.authenticated)return Sl({show:!0,isFirstTime:!1,accounts:u.accounts,error:u.error,busy:u.busy,onSubmit:(p,v)=>{v!=null&&e.handlePinSubmit(p,v)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,v,$)=>e.handleChangePin(p,v,$)});if(!u.hasMasterPin&&!u.authenticated&&e.setup)return Sl({show:!0,isFirstTime:!0,accounts:[],error:u.error,busy:u.busy,onSubmit:p=>e.handleSetMasterPin(p)});if(!u.hasMasterPin&&!u.authenticated&&!e.setup)return window.location.href="/setup",w}if(e.setup){const u=u0(e.channelsSnapshot),p=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],v=p0(e.channelsSnapshot),$=h0(e),S=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},M=()=>{const y=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=mo[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,Kt(),wt=setInterval(()=>{const b=(Date.now()-y)/1e3,k=Math.min(95,95*(1-Math.exp(-b/30)));e.tailscaleConnectProgress=Math.round(k);let A=mo[0][1];for(const[E,T]of mo)b>=E&&(A=T);e.tailscaleConnectMessage=A},500)};return am({connected:e.connected,serverPlatform:((o=(s=e.hello)==null?void 0:s.server)==null?void 0:o.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:y=>e.handleLicenseKeyChange(y),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,authRefreshToken:e.authRefreshToken,claudeAuthModalOpen:e.claudeAuthModalOpen,authRefreshTokenInput:e.authRefreshTokenInput,authRefreshTokenBusy:e.authRefreshTokenBusy,authRefreshTokenError:e.authRefreshTokenError,onClaudeAuthModalOpen:()=>e.handleClaudeAuthModalOpen(),onClaudeAuthModalClose:()=>e.handleClaudeAuthModalClose(),onRefreshTokenInputChange:y=>{e.authRefreshTokenInput=y},onImportRefreshToken:()=>e.handleImportRefreshToken(),whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:u,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:y=>e.handleUninstallConfirmTextChange(y),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:y=>e.handleAuthSubmitCode(y),onAuthCodeChange:y=>e.handleAuthCodeChange(y),onWhatsAppRelink:async y=>{await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await ee(e,!0),e.requestUpdate())},onWhatsAppUnlink:async y=>{await e.handleWhatsAppLogout(y)},onWhatsAppReset:async y=>{await e.handleWhatsAppLogout(y),await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await ee(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await ee(e,!0),await e.handleGatewayHealthCheck()},onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),ee(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:y=>e.handleRemoveWhatsAppAccount(y),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:y=>{e.newWorkspacePin=y},onWorkspaceCreate:async(y,b)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(y,b),k.match(/^\d{4,6}$/)&&(await Mh(e,y,k),e.newWorkspacePin="")},onWorkspaceRemove:y=>e.handleWorkspaceRemove(y),onSetAddingWorkspace:y=>{e.addingWorkspace=y},onSetNewWorkspaceName:y=>{e.newWorkspaceName=y},onSetNewWorkspacePath:y=>{e.newWorkspacePath=y},onSetWorkspaceRemoveConfirm:y=>{e.workspaceRemoveConfirm=y},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(y,b)=>e.handleWorkspaceRename(y,b),whatsappDmPolicy:(()=>{const y=we(e),b=y==null?void 0:y.whatsappAccountId,k=b?p.find(A=>A.accountId===b):p[0];return(k==null?void 0:k.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var P;const y=we(e),b=y==null?void 0:y.whatsappAccountId,k=b?p.find(D=>D.accountId===b):p[0];if(!k)return;const E=k.dmPolicy!=null&&k.dmPolicy!=="disabled"?"disabled":"open",T=E==="open"?{dmPolicy:E,allowFrom:["*"]}:{dmPolicy:E};try{const D=await e.client.request("config.get"),W=D.config,z=(P=W==null?void 0:W.channels)==null?void 0:P.whatsapp,ke=((z==null?void 0:z.accounts)??{})[k.accountId]?{channels:{whatsapp:{accounts:{[k.accountId]:T}}}}:{channels:{whatsapp:T}};await e.client.request("config.patch",{raw:JSON.stringify(ke),baseHash:D.hash,note:`WhatsApp DM policy → ${E}`,skipRestart:!0}),await ee(e,!1)}catch(D){console.error("DM toggle failed:",D)}},whatsappGroupPolicy:(()=>{var D,W;const y=(D=e.configSnapshot)==null?void 0:D.config,b=(W=y==null?void 0:y.channels)==null?void 0:W.whatsapp,k=we(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},T=A?E[A]:void 0;return(T==null?void 0:T.groupPolicy)??(b==null?void 0:b.groupPolicy)??"allowlist"})(),whatsappGroupRequireMention:(()=>{var W,z;const y=(W=e.configSnapshot)==null?void 0:W.config,b=(z=y==null?void 0:y.channels)==null?void 0:z.whatsapp,k=we(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},T=A?E[A]:void 0,D=((T==null?void 0:T.groups)??(b==null?void 0:b.groups)??{})["*"];return(D==null?void 0:D.requireMention)!==!1})(),onWhatsAppGroupToggle:async()=>{var k;const y=we(e),b=y==null?void 0:y.whatsappAccountId;try{const A=await e.client.request("config.get"),E=A.config,T=((k=E==null?void 0:E.channels)==null?void 0:k.whatsapp)??{},P=T.accounts??{},D=b?P[b]:void 0,W=(D==null?void 0:D.groupPolicy)??T.groupPolicy??"allowlist",z=W==="disabled"||W==="allowlist",H=z?"open":"disabled",ke=z?{"*":{}}:void 0,Me={groupPolicy:H};ke&&(Me.groups=ke);const ze=D?{channels:{whatsapp:{accounts:{[b]:Me}}}}:{channels:{whatsapp:Me}};await e.client.request("config.patch",{raw:JSON.stringify(ze),baseHash:A.hash,note:`WhatsApp groups → ${H}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Group toggle failed:",A)}},onWhatsAppGroupMentionChange:async y=>{var A;const b=we(e),k=b==null?void 0:b.whatsappAccountId;try{const E=await e.client.request("config.get"),T=E.config,D=(((A=T==null?void 0:T.channels)==null?void 0:A.whatsapp)??{}).accounts??{},W=k?D[k]:void 0,z={"*":{requireMention:y}},H=W?{channels:{whatsapp:{accounts:{[k]:{groups:z}}}}}:{channels:{whatsapp:{groups:z}}};await e.client.request("config.patch",{raw:JSON.stringify(H),baseHash:E.hash,note:`WhatsApp group mention → ${y?"when mentioned":"always"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(E){console.error("Group mention change failed:",E)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:v.configured,imessageRunning:v.running,imessageConnected:v.connected,imessageLastError:v.lastError,imessageSelfChatMode:v.selfChatMode,imessageCliPath:v.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:$,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),b=y.config,k=(b==null?void 0:b.bindings)??[],A=we(e),E=A==null?void 0:A.agents.find(z=>z.id.endsWith("-admin")||z.id==="admin"),T=(E==null?void 0:E.id)??"admin",P=k.filter(z=>{var H;return((H=z.match)==null?void 0:H.channel)!=="imessage"}),D=[{agentId:T,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],W=[...P,...D];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:W}),baseHash:y.hash,note:"Enable iMessage (self-chat) for "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Fe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await ee(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),b=y.config,A=((b==null?void 0:b.bindings)??[]).filter(E=>{var T;return((T=E.match)==null?void 0:T.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:A}),baseHash:y.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Fe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),b=y.config,k=(b==null?void 0:b.bindings)??[],A=we(e),E=A==null?void 0:A.agents.find(W=>W.id.endsWith("-admin")||W.id==="admin"),T=(E==null?void 0:E.id)??"admin",P=k.filter(W=>{var z;return((z=W.match)==null?void 0:z.channel)!=="imessage"}),D=[{agentId:T,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:[...P,...D]}),baseHash:y.hash,note:"Reassign iMessage to "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Fe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:y=>{var b,k,A,E;if(e.infoModalOpen=y,y==="remote-access"){const T=((b=e.tailscaleStatus)==null?void 0:b.tailnetUrl)??((k=e.tailscaleStatus)!=null&&k.hostname?`https://${e.tailscaleStatus.hostname}`:null);T&&!e.remoteAccessQrDataUrl&&e.client.request("qr.generate",{url:T}).then(P=>{e.remoteAccessQrDataUrl=(P==null?void 0:P.dataUrl)??null}).catch(()=>{})}else if(y==="public-chat"){const T=((A=e.tailscaleStatus)==null?void 0:A.publicUrl)??((E=e.tailscaleStatus)==null?void 0:E.tailnetUrl)??null,P=e.selectedWorkspace??null;if(T&&P){const D=`${T}/public/chat/${encodeURIComponent(P)}`;e.publicChatQrDataUrl||e.client.request("qr.generate",{url:D}).then(W=>{e.publicChatQrDataUrl=(W==null?void 0:W.dataUrl)??null}).catch(()=>{})}}},onInfoModalClose:()=>{e.infoModalOpen=null},remoteAccessQrDataUrl:e.remoteAccessQrDataUrl??null,publicChatQrDataUrl:e.publicChatQrDataUrl??null,publicChatFullUrl:(()=>{var k,A;const y=((k=e.tailscaleStatus)==null?void 0:k.publicUrl)??((A=e.tailscaleStatus)==null?void 0:A.tailnetUrl)??null,b=e.selectedWorkspace??null;return!y||!b?null:`${y}/public/chat/${encodeURIComponent(b)}`})(),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(y,b)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await El(e.client,y,b);const k=`${y} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}y==="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 y=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Dk(e.client,y);const b=`${y} key removed`;e.apiKeySuccess=b,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===b&&(e.apiKeySuccess=null)},2500)}catch(b){e.apiKeyError=b instanceof Error?b.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyDisable:async(y,b)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Bk(e.client,y,b);const k=`${y} ${b?"disabled":"enabled"}`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:`Failed to ${b?"disable":"enable"} 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:y=>{e.authApiKeyInput=y},onAuthApiKeySubmit:async()=>{const y=e.authApiKeyInput.trim();if(y){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await El(e.client,"anthropic",y),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(b){e.authApiKeyError=b instanceof Error?b.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var b;const y=e.selectedWorkspace??((b=e.workspaces[0])==null?void 0:b.name);return y?e.accessState.accounts.some(k=>k.id===y):!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:(y,b)=>{var A;const k=e.selectedWorkspace??((A=e.workspaces[0])==null?void 0:A.name);k&&e.handleAccountPinSave(k,y,b)},publicChatAccountId:e.selectedWorkspace??null,publicChatSettingsOpen:e.publicChatSettingsOpen,onPublicChatSettingsOpen:()=>{e.publicChatSettingsOpen=!0},onPublicChatSettingsClose:()=>{e.publicChatSettingsOpen=!1},publicChatWidgetModalOpen:e.publicChatWidgetModalOpen,onPublicChatWidgetModalOpen:()=>{e.publicChatWidgetModalOpen=!0},onPublicChatWidgetModalClose:()=>{e.publicChatWidgetModalOpen=!1},publicChatEnabled:(()=>{var k;const y=(k=e.configSnapshot)==null?void 0:k.config,b=y==null?void 0:y.publicChat;return(b==null?void 0:b.enabled)===!0})(),publicChatAuthMode:(()=>{var T,P;const y=(T=e.configSnapshot)==null?void 0:T.config,b=y==null?void 0:y.publicChat,k=e.selectedWorkspace??"",A=b==null?void 0:b.accountSettings,E=((P=A==null?void 0:A[k])==null?void 0:P.auth)??(b==null?void 0:b.auth);return E==="verified"||E==="choice"?E:"anonymous"})(),publicChatGreeting:(()=>{var E;const y=(E=e.configSnapshot)==null?void 0:E.config,b=y==null?void 0:y.publicChat,k=b==null?void 0:b.greetings,A=e.selectedWorkspace??"";return(A&&(k==null?void 0:k[A]))??""})(),publicChatGreetingBusy:e.publicChatGreetingBusy,onPublicChatGreetingToggle:async()=>{var b;if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=(b=A==null?void 0:A.publicChat)==null?void 0:b.greetings;if(E==null?void 0:E[y]){const P={publicChat:{greetings:{[y]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(P),baseHash:k.hash,note:`Public chat greeting → disabled (${y})`,skipRestart:!0})}else{const P=await e.client.request("public.greeting.generate",{accountId:y});if(P!=null&&P.ok&&P.greeting){const D=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:P.greeting}}}),baseHash:D.hash,note:`Public chat greeting → enabled (${y})`,skipRestart:!0})}}e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting toggle failed:",k)}finally{e.publicChatGreetingBusy=!1}}},onPublicChatGreetingSave:async y=>{const b=e.selectedWorkspace??"";if(b)try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[b]:y}}}),baseHash:k.hash,note:`Public chat greeting text updated (${b})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting save failed:",k)}},onPublicChatGreetingRegenerate:async()=>{if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const b=await e.client.request("public.greeting.generate",{accountId:y});if(b!=null&&b.ok&&b.greeting){const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:b.greeting}}}),baseHash:k.hash,note:`Public chat greeting regenerated (${y})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}}catch(b){console.error("Public chat greeting regeneration failed:",b)}finally{e.publicChatGreetingBusy=!1}}},publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var y;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get"),k=b.config,A=((y=k==null?void 0:k.publicChat)==null?void 0:y.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!A}}),baseHash:b.hash,note:`Public chat → ${A?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),e.publicChatQrDataUrl=null}catch(b){console.error("Public chat toggle failed:",b)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async y=>{if(e.publicChatToggleBusy)return;const b=e.selectedWorkspace??"";if(b){e.publicChatToggleBusy=!0;try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{accountSettings:{[b]:{auth:y}}}}),baseHash:k.hash,note:`Public chat auth → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat auth mode change failed:",k)}finally{e.publicChatToggleBusy=!1}}},publicChatEmailFrom:(()=>{var k,A;const y=(k=e.configSnapshot)==null?void 0:k.config,b=(A=y==null?void 0:y.publicChat)==null?void 0:A.email;return(b==null?void 0:b.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var T,P;const y=(T=e.configSnapshot)==null?void 0:T.config,b=y==null?void 0:y.publicChat,k=e.selectedWorkspace??"",A=b==null?void 0:b.accountSettings,E=((P=A==null?void 0:A[k])==null?void 0:P.verifyMethods)??(b==null?void 0:b.verifyMethods);return Array.isArray(E)?E:["whatsapp","sms"]})(),onPublicChatEmailSave:async(y,b)=>{if(e.publicChatEmailBusy)return;const k=e.selectedWorkspace??"";if(k){e.publicChatEmailBusy=!0;try{const A=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{email:{from:y||void 0},accountSettings:{[k]:{verifyMethods:b}}}}),baseHash:A.hash,note:"Update email verification settings for public chat",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Email verification save failed:",A)}finally{e.publicChatEmailBusy=!1}}},brandAccentColor:(()=>{var k;const y=e.selectedWorkspace;return y?((k=Ne()[y])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const y=e.selectedWorkspace;return y?((k=Ne()[y])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const y=e.selectedWorkspace;return y?!!((k=Ne()[y])!=null&&k.logoUrl):!1})(),agentSettingsOpen:e.agentSettingsOpen,agentSettingsAgents:(()=>{var A,E;const y=we(e);if(!y)return[];const b=(A=e.configSnapshot)==null?void 0:A.config,k=(E=b==null?void 0:b.agents)==null?void 0:E.list;return y.agents.map(T=>{var H;const P=Array.isArray(k)?k.find(ke=>ke.id===T.id):void 0,D=P==null?void 0:P.model,W=typeof D=="string"?D:(D==null?void 0:D.primary)??null,z=T.id.endsWith("-admin")||T.id==="admin";return{id:T.id,label:z?"Admin":"Public",model:(W==null?void 0:W.trim())||null,thinkingLevel:((H=P==null?void 0:P.thinkingLevel)==null?void 0:H.trim())||null}})})(),agentSettingsModelCatalog:e.chatModelCatalog??[],memoryProvider:(()=>{var k,A,E;const y=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=y==null?void 0:y.agents)==null?void 0:A.defaults)==null?void 0:E.memorySearch;return typeof(b==null?void 0:b.provider)=="string"&&b.provider?b.provider:"local"})(),memoryFallback:(()=>{var k,A,E;const y=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=y==null?void 0:y.agents)==null?void 0:A.defaults)==null?void 0:E.memorySearch;return typeof(b==null?void 0:b.fallback)=="string"&&b.fallback?b.fallback:"none"})(),onAgentSettingsToggle:()=>{e.agentSettingsOpen=!e.agentSettingsOpen},onAgentModelChange:async(y,b)=>{try{const k=await e.client.request("config.get"),A=k.config,E=(A==null?void 0:A.agents)??{},T=Array.isArray(E.list)?[...E.list]:[],P=T.findIndex(W=>W.id===y);if(b)P>=0?T[P]={...T[P],model:b}:T.push({id:y,model:b});else if(P>=0){const{model:W,...z}=T[P];Object.keys(z).length<=1?T.splice(P,1):T[P]=z}const D=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(D),baseHash:k.hash,note:`Agent ${y} model → ${b||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent model change failed:",k)}},onAgentThinkingChange:async(y,b)=>{try{const k=await e.client.request("config.get"),A=k.config,E=(A==null?void 0:A.agents)??{},T=Array.isArray(E.list)?[...E.list]:[],P=T.findIndex(z=>z.id===y),D=b==="off"?void 0:b;if(D)P>=0?T[P]={...T[P],thinkingLevel:D}:T.push({id:y,thinkingLevel:D});else if(P>=0){const{thinkingLevel:z,...H}=T[P];Object.keys(H).length<=1?T.splice(P,1):T[P]=H}const W=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(W),baseHash:k.hash,note:`Agent ${y} thinking → ${D||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent thinking change failed:",k)}},onMemoryProviderChange:async y=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{provider:y}}}}),baseHash:b.hash,note:`Memory search provider → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Memory provider change failed:",b)}},onMemoryFallbackChange:async y=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{fallback:y}}}}),baseHash:b.hash,note:`Memory search fallback → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Memory fallback change failed:",b)}},brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async y=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,T=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=T.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...T,brand:{...P,accentColor:y}}}}),baseHash:A.hash,note:`Brand accent → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const D=Ne();D[b]||(D[b]={}),D[b].accentColor=y,Tn(b)}catch(A){console.error("Brand accent change failed:",A)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async y=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,T=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=T.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...T,brand:{...P,backgroundColor:y}}}}),baseHash:A.hash,note:`Brand background → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const D=Ne();D[b]||(D[b]={}),D[b].backgroundColor=y,Tn(b)}catch(A){console.error("Brand background change failed:",A)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async y=>{const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const k=await y.arrayBuffer(),A=new Uint8Array(k);let E="";for(let D=0;D<A.length;D++)E+=String.fromCharCode(A[D]);const T=btoa(E);await e.client.request("brand.uploadLogo",{workspace:b,data:T,mimeType:y.type});const P=Ne();P[b]||(P[b]={}),P[b].logoUrl=`/brand-logo/${encodeURIComponent(b)}`}catch(k){console.error("Brand logo upload failed:",k)}finally{e.brandingBusy=!1}}},onBrandLogoRemove:async()=>{const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:y});const b=Ne();b[y]&&delete b[y].logoUrl}catch(b){console.error("Brand logo remove failed:",b)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var b;const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=((b=A==null?void 0:A.workspaces)==null?void 0:b[y])??{},{brand:T,...P}=E;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[y]:{...P,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:y})}catch{}const D=Ne();delete D[y],Tn(y)}catch(k){console.error("Brand reset failed:",k)}finally{e.brandingBusy=!1}}},tailscaleStatus:e.tailscaleStatus,tailscaleBusy:e.tailscaleBusy,tailscaleAuthUrl:e.tailscaleAuthUrl,tailscaleError:e.tailscaleError,tailscaleServeEnableUrl:e.tailscaleServeEnableUrl,tailscaleFunnelEnableUrl:e.tailscaleFunnelEnableUrl,tailscaleDisableConfirm:e.tailscaleDisableConfirm,tailscaleConnectProgress:e.tailscaleConnectProgress,tailscaleConnectMessage:e.tailscaleConnectMessage,tailscaleConnectSuccess:e.tailscaleConnectSuccess,onTailscaleEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleAuthUrl=null,M();try{const y=await e.client.request("tailscale.enable");y.authUrl?(wt&&(clearInterval(wt),wt=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=y.authUrl,Mi=setInterval(async()=>{try{const b=await e.client.request("tailscale.status");e.tailscaleStatus=b,e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,b.loggedIn&&(Kt(),e.tailscaleAuthUrl=null,e.tailscaleConnectSuccess=!0,e.tailscaleConnectMessage="Connected!",setTimeout(()=>{e.tailscaleConnectSuccess=!1,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1},1500))}catch{}},3e3),Pi=setTimeout(()=>{Kt(),e.tailscaleBusy&&(e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)},3e5)):y.alreadyLoggedIn?(Kt(),e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1):(Kt(),e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)}catch(y){console.error("Tailscale enable failed:",y),Kt(),e.tailscaleError=y.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleServeEnableUrl=null;try{await e.client.request("tailscale.serve.enable"),await S()}catch(b){console.error("Tailscale serve enable failed:",b);const k=b;(y=k.payload)!=null&&y.enableUrl&&(e.tailscaleServeEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Remote Access"}finally{e.tailscaleBusy=!1}}},onTailscaleServeDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.serve.disable"),await S()}catch(y){console.error("Tailscale serve disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable"),await S()}catch(b){console.error("Tailscale funnel enable failed:",b);const k=b;(y=k.payload)!=null&&y.enableUrl&&(e.tailscaleFunnelEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Funnel"}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.funnel.disable"),await S()}catch(y){console.error("Tailscale funnel disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleDisableConfirmToggle:()=>{e.tailscaleDisableConfirm=!e.tailscaleDisableConfirm},wifiModalOpen:e.wifiModalOpen,onWifiModalToggle:()=>{e.wifiModalOpen=!e.wifiModalOpen,e.wifiModalOpen||(e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null)},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{var y;if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[b,k]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiNetworks=b.networks,k.connected&&k.signal==null&&((y=b.networks)!=null&&y.length)){const A=b.networks.find(E=>E.active)||b.networks.find(E=>E.ssid===k.ssid);A&&(k.signal=A.signal)}e.wifiStatus=k}catch(b){console.error("WiFi scan failed:",b),e.wifiError=b.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{var b;if(e.wifiBusy||!e.wifiSelectedSsid)return;const y=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const k=await e.client.request("wifi.connect",{ssid:y,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:k.connected,ssid:k.ssid,signal:null,ip:k.ip,savedSsid:k.ssid,autoconnect:!0},e.wifiBusy=!1;try{const[A,E]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(E.connected&&E.signal==null&&((b=A.networks)!=null&&b.length)){const T=A.networks.find(P=>P.active)||A.networks.find(P=>P.ssid===E.ssid);T&&(E.signal=T.signal)}e.wifiStatus=E}catch{}}catch(k){console.error("WiFi connect failed:",k),e.wifiError=k.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 y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi disconnect failed:",y),e.wifiError=y.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 y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi forget failed:",y),e.wifiError=y.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:y=>{e.wifiSelectedSsid=y,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:y=>{e.wifiPassword=y},networkPort:e.networkPort,networkHostname:e.networkHostname,networkPortInput:e.networkPortInput,networkHostnameInput:e.networkHostnameInput,networkModalOpen:e.networkModalOpen,networkBusy:e.networkBusy,networkError:e.networkError,networkSuccess:e.networkSuccess,onNetworkModalToggle:()=>{e.networkModalOpen=!e.networkModalOpen,e.networkModalOpen&&(e.networkPortInput=String(e.networkPort??""),e.networkHostnameInput=e.networkHostname,e.networkError=null,e.networkSuccess=null)},onNetworkPortChange:y=>{e.networkPortInput=y,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:y=>{e.networkHostnameInput=y,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const y=e.networkPortInput.trim(),b=Number.parseInt(y,10),k=e.networkHostnameInput.trim();if(!y||!Number.isFinite(b)||b<1024||b>65535){e.networkError="Port must be a number between 1024 and 65535",e.networkBusy=!1;return}const A=b!==e.networkPort,E=k!==e.networkHostname;if(!A&&!E){e.networkBusy=!1;return}try{E&&await e.client.request("network.setHostname",{hostname:k});const T={};A&&(T.gateway={port:b}),E&&(T.discovery={bonjourHostname:k});const P=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify(T),baseHash:P.hash,note:[A?`Port → ${b}`:null,E?`Hostname → ${k}`:null].filter(Boolean).join(", "),restartDelayMs:2e3}),e.networkSuccess="Saved — redirecting...";const D=window.location.protocol,W=E?`${k}.local`:window.location.hostname,z=A?b:e.networkPort,H=`${D}//${W}:${z}/setup`;setTimeout(()=>{window.location.href=H},1500)}catch(T){console.error("Network save failed:",T),e.networkError=T.message||"Failed to save network settings",e.networkBusy=!1}},wsProps:o0(e)})}if(e.filesPage){const u=r0(e);return bg({connected:e.connected,wsProps:Sn(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:()=>{rn(e,u),cs(e,u)},onReindex:()=>Rf(e,u),onSelectFile:p=>{e.filesPendingDeletePath=null,Af(e,p,u)},onToggleSelectFile:p=>Cf(e,p,u),onToggleDir:p=>Lf(e,p),onUpload:(p,v)=>_f(e,p,v,u),onNewFolder:(p,v)=>Mf(e,p,v,u),onDownload:p=>rd(e,p,u),onBulkDownload:()=>Ef(e,u),onDelete:p=>{e.filesPendingDeletePath=null,Pf(e,p,u)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,v)=>Tf(e,p,v,u),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const v=e.filesSearchAgentId??u;Df(e,p,v)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{Bf(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return hg({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:()=>Ek(e),onStop:()=>Tk(e),onToggleInput:()=>Mk(e),onToggleFullscreen:()=>Pk(e),onCompleteHandoff:()=>_k(e),onCanvasMouseDown:u=>{const v=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-v.left,u.clientY-v.top);po(e,"mousePressed",S.x,S.y,u.button===2?"right":u.button===1?"middle":"left")},onCanvasMouseUp:u=>{const v=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-v.left,u.clientY-v.top);po(e,"mouseReleased",S.x,S.y)},onCanvasMouseMove:u=>{const p=Bn();if(p.shouldThrottleMouseMove())return;const $=u.target.getBoundingClientRect(),S=p.translateCoordinates(u.clientX-$.left,u.clientY-$.top);po(e,"mouseMoved",S.x,S.y)},onCanvasKeyDown:u=>{let p=0;u.altKey&&(p|=1),u.ctrlKey&&(p|=2),u.metaKey&&(p|=4),u.shiftKey&&(p|=8),ho(e,"keyDown",u.key,{code:u.code,modifiers:p||void 0}),u.key.length===1&&ho(e,"char",u.key,{text:u.key})},onCanvasKeyUp:u=>{ho(e,"keyUp",u.key,{code:u.code})}});if(e.adminsPage){const u=a0(e),p=Ka(e);return lm({connected:e.connected,wsProps:Sn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>ys(e,u),onAdd:v=>{Iu(e,v,u,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:v=>Ru(e,v,u,p),onNewPhoneChange:v=>e.handleAdminsNewPhoneChange(v)})}if(e.contactsPage){const u=l0(e);return fm({connected:e.connected,wsProps:Sn(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:()=>Pt(e,u),onAdd:(p,v)=>Lu(e,p,v,u),onDelete:p=>Du(e,p,u),onSetField:(p,v,$)=>jo(e,p,v,$,u),onDeleteField:(p,v)=>Bu(e,p,v,u),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:()=>Pt(e,u),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,v=e.contactsAddFieldKey.trim();!p||!v||(jo(e,p,v,e.contactsAddFieldValue,u),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const u=e.connected?null:"Disconnected from gateway.",p=Dl(e),v=e.chatAvatarUrl??p??null,$=(()=>{var y;const S=(y=e.configSnapshot)==null?void 0:y.config,M=S==null?void 0:S.publicChat;return(M==null?void 0:M.enabled)===!0})();return gw({connected:e.connected,wsProps:Sn(e),publicChatEnabled:$,publicChatAccountId:e.selectedWorkspace??void 0,chatPageTab:e.chatPageTab??"chat",onChatPageTabChange:S=>{if(e.chatPageTab=S,S==="whatsapp"&&!e.waLoading&&e.waConversations.length===0){const M=Ii(e);vu(M).then(()=>e.requestUpdate())}},whatsappProps:g0(e),sessionKey:e.sessionKey,onSessionKeyChange:S=>{const M=e.selectedWorkspace??"";wo(),Wn(M,e.sessionKey,e.chatMessage),e.sessionKey=S,e.chatMessage=Kn(M,S),e.chatAttachments=[],e.chatStream=null,e.chatInterimText=null,e.chatSuggestions=[],e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:S,lastActiveSessionKey:S}),e.loadAssistantIdentity(),Jt(e),Eo(e)},showThinking:e.settings.chatShowThinking??!1,verboseLevel:e.chatVerboseLevel,suggestions:e.chatSuggestions,onSuggestionClick:S=>{e.chatMessage=S,e.chatSuggestions=[],e.handleSendChat()},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:v,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:u,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const S=Math.max(e.chatMessages.length+10,nn);return Promise.all([Jt(e,{limit:S}),Eo(e)])},onToggleFocusMode:()=>{},onChatScroll:S=>e.handleChatScroll(S),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:S=>{e.chatMessage=S,wr(e.selectedWorkspace??"",e.sessionKey,S)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:S=>e.chatAttachments=S,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:S=>e.removeQueuedMessage(S),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:S=>e.handleOpenSidebar(S),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:S=>e.handleSplitRatioChange(S),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?fk({connected:e.connected,wsProps:Sn(e),activeTab:e.advancedTab,onTabChange:u=>{e.advancedTab=u,u==="cron"&&e.loadCron(),u==="skills"&&We(e,{clearMessages:!0}),u==="opening-hours"&&Wa(e),u==="logs"&&(e.logsSubTab==="session"?Pn(e,{reset:!0}):Gt(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(r=(a=e.channelsSnapshot)==null?void 0:a.channelMeta)!=null&&r.length?e.channelsSnapshot.channelMeta.map(u=>u.id):((d=e.channelsSnapshot)==null?void 0:d.channelOrder)??[],channelLabels:((c=e.channelsSnapshot)==null?void 0:c.channelLabels)??{},channelMeta:((h=e.channelsSnapshot)==null?void 0:h.channelMeta)??[],agentIds:(()=>{var p;const u=we(e);return((p=u==null?void 0:u.agents)==null?void 0:p.map(v=>v.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:u=>{e.cronDetailJobId=u.id,xo(e,u.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:u=>{e.cronForm=Sh(u),e.cronEditJobId=u.id,e.cronDetailJobId=null},onEditSave:()=>{const u=e.cronEditJobId;u&&Ah(e,u).then(()=>{e.cronEditJobId=null})},onFormChange:u=>e.cronForm={...e.cronForm,...u},onRefresh:()=>e.loadCron(),onAdd:()=>{bh(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(u,p)=>wh(e,u,p),onRun:u=>kh(e,u),onRemove:u=>{e.cronPendingDeleteId=null,$h(e,u)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:u=>{e.cronPendingDeleteId=u||null},onLoadRuns:u=>xo(e,u),runModalJobId:e.cronRunModalJobId,runModalJobName:e.cronRunModalJobName,runResult:e.cronRunResult,onRunModalClose:()=>{e.cronRunModalJobId=null,e.cronRunModalJobName="",e.cronRunResult=null}},skillsProps:{loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,typeFilter:e.skillsTypeFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,detail:e.skillDetail,detailTab:e.skillDetailTab,addModal:e.skillAddModal,addForm:e.skillAddForm,formSource:e.skillAddFormSource,editTab:e.skillEditTab,drafts:e.skillDrafts,onFilterChange:u=>e.skillsFilter=u,onTypeFilterChange:u=>e.skillsTypeFilter=u,onRefresh:()=>We(e,{clearMessages:!0}),onToggle:(u,p)=>Oc(e,u,p),onEdit:(u,p)=>Nc(e,u,p),onSaveKey:u=>Fc(e,u),onInstall:(u,p,v)=>Uc(e,u,p,v),onViewDetail:u=>Wc(e,u),onDetailClose:()=>Kc(e),onDetailTab:u=>zc(e,u),onAddOpen:()=>Hc(e),onAddClose:()=>qc(e),onImportDraft:u=>jc(e,u),onInstallDraft:u=>Gc(e,u),onDeleteDraft:u=>Vc(e,u),onAddSave:()=>ua(e),onAddFormUpdate:(u,p)=>{e.skillAddForm={...e.skillAddForm,[u]:p}},onAlwaysActiveToggle:(u,p)=>Zc(e,u,p),onDelete:u=>ed(e,u),onEditSkill:u=>Qc(e,u),onEditDetail:u=>Jc(e,u),onRefUpdate:(u,p)=>Yc(e,u,p),onEditTab:u=>Xc(e,u)},logsProps:{logsSubTab:e.logsSubTab,isAdmin:e.accessState.master||!e.accessState.hasPins,onSubTabChange:u=>{e.logsSubTab=u,u==="session"?Pn(e,{reset:!0}):Gt(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,chipsExpanded:e.sessionLogsChipsExpanded,expandedIds:e.sessionLogsExpandedIds,onFilterTextChange:u=>e.sessionLogsFilterText=u,onTypeToggle:(u,p)=>{const v=e;v.sessionLogsTypeFilters={...v.sessionLogsTypeFilters,[u]:p}},onAgentToggle:(u,p)=>{const v=e;v.sessionLogsAgentFilters={...v.sessionLogsAgentFilters,[u]:p}},onToggleAutoFollow:u=>e.sessionLogsAutoFollow=u,onToggleChips:()=>{const u=e;u.sessionLogsChipsExpanded=!u.sessionLogsChipsExpanded},onToggleExpand:u=>{const p=e,v=new Set(p.sessionLogsExpandedIds);v.has(u)?v.delete(u):v.add(u),p.sessionLogsExpandedIds=v,p.requestUpdate()},onRefresh:()=>{Pn(e,{reset:!0})},onExport:(u,p)=>e.exportSessionLogs(u,p),onScroll:u=>e.handleSessionLogsScroll(u)},loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,chipsExpanded:e.logsChipsExpanded,truncated:e.logsTruncated,onFilterTextChange:u=>e.logsFilterText=u,onLevelToggle:(u,p)=>{e.logsLevelFilters={...e.logsLevelFilters,[u]:p}},onToggleAutoFollow:u=>e.logsAutoFollow=u,onToggleChips:()=>{const u=e;u.logsChipsExpanded=!u.logsChipsExpanded},onRefresh:()=>Gt(e,{reset:!0}),onExport:(u,p)=>e.exportSessionLogs(u,p),onScroll:u=>e.handleLogsScroll(u)},openingHoursProps:{loading:e.openingHoursLoading,error:e.openingHoursError,busy:e.openingHoursBusy,form:e.openingHoursForm,onFormChange:u=>{const p=e;p.openingHoursForm={...p.openingHoursForm,...u}},onDayChange:(u,p,v)=>{const $=e,S={...$.openingHoursForm.days};S[u]={...S[u],[p]:v},$.openingHoursForm={...$.openingHoursForm,days:S}},onAddClosedDate:u=>{const p=e;p.openingHoursForm.closedDates.includes(u)||(p.openingHoursForm={...p.openingHoursForm,closedDates:[...p.openingHoursForm.closedDates,u].sort()})},onRemoveClosedDate:u=>{const p=e;p.openingHoursForm={...p.openingHoursForm,closedDates:p.openingHoursForm.closedDates.filter(v=>v!==u)}},onSave:()=>{Mu(e)}}}):(window.location.replace("/chat"),l``)}function y0(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 Bl(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function v0(e,t,n){return l`
4856
+ `;if(!e.publicChatAuthenticated)return e0({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,otpChannels:e.publicChatConfig.otpChannels,verifyMethods:e.publicChatConfig.verifyMethods,onAuthenticated:$=>{var M;e.publicChatSessionKey=$,e.sessionKey=$,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const S=((M=e.publicChatConfig)==null?void 0:M.accountId)??"";e.chatMessage=Kn(S,$),ae(async()=>{const{loadChatHistory:y}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:y}},void 0,import.meta.url).then(({loadChatHistory:y})=>{y(e)})},onAuthStepChange:$=>{e.publicChatAuthStep=$},requestUpdate:()=>{e.requestUpdate()}});const u=(t=e.publicChatConfig)==null?void 0:t.greeting,p=e.chatMessages,v=!e.chatLoading&&u?[{role:"assistant",content:[{type:"text",text:u}],timestamp:0},...Array.isArray(p)?p:[]]:p;return gk({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:v,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Dl(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,suggestions:e.chatSuggestions,onSuggestionClick:$=>{e.chatMessage=$,e.chatSuggestions=[],e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),ae(async()=>{const{loadChatHistory:$}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:$}},void 0,import.meta.url).then(({loadChatHistory:$})=>{$(e)})),onDraftChange:$=>{var M;e.chatMessage=$;const S=((M=e.publicChatConfig)==null?void 0:M.accountId)??"";wr(S,e.sessionKey,$)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:$=>e.chatAttachments=$,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:$=>e.removeQueuedMessage($),onChatScroll:$=>e.handleChatScroll($),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}})}if(e.connected&&e.accessState.checked){const{accessState:u}=e;if(u.hasPins&&!u.authenticated)return Sl({show:!0,isFirstTime:!1,accounts:u.accounts,error:u.error,busy:u.busy,onSubmit:(p,v)=>{v!=null&&e.handlePinSubmit(p,v)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,v,$)=>e.handleChangePin(p,v,$)});if(!u.hasMasterPin&&!u.authenticated&&e.setup)return Sl({show:!0,isFirstTime:!0,accounts:[],error:u.error,busy:u.busy,onSubmit:p=>e.handleSetMasterPin(p)});if(!u.hasMasterPin&&!u.authenticated&&!e.setup)return window.location.href="/setup",w}if(e.setup){const u=u0(e.channelsSnapshot),p=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],v=p0(e.channelsSnapshot),$=h0(e),S=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},M=()=>{const y=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=mo[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,Kt(),wt=setInterval(()=>{const b=(Date.now()-y)/1e3,k=Math.min(95,95*(1-Math.exp(-b/30)));e.tailscaleConnectProgress=Math.round(k);let A=mo[0][1];for(const[E,T]of mo)b>=E&&(A=T);e.tailscaleConnectMessage=A},500)};return am({connected:e.connected,serverPlatform:((o=(s=e.hello)==null?void 0:s.server)==null?void 0:o.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:y=>e.handleLicenseKeyChange(y),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,authRefreshToken:e.authRefreshToken,claudeAuthModalOpen:e.claudeAuthModalOpen,authRefreshTokenInput:e.authRefreshTokenInput,authRefreshTokenBusy:e.authRefreshTokenBusy,authRefreshTokenError:e.authRefreshTokenError,onClaudeAuthModalOpen:()=>e.handleClaudeAuthModalOpen(),onClaudeAuthModalClose:()=>e.handleClaudeAuthModalClose(),onRefreshTokenInputChange:y=>{e.authRefreshTokenInput=y},onImportRefreshToken:()=>e.handleImportRefreshToken(),whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:u,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:y=>e.handleUninstallConfirmTextChange(y),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:y=>e.handleAuthSubmitCode(y),onAuthCodeChange:y=>e.handleAuthCodeChange(y),onWhatsAppRelink:async y=>{await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await ee(e,!0),e.requestUpdate())},onWhatsAppUnlink:async y=>{await e.handleWhatsAppLogout(y)},onWhatsAppReset:async y=>{await e.handleWhatsAppLogout(y),await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await ee(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await ee(e,!0),await e.handleGatewayHealthCheck()},onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),ee(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:y=>e.handleRemoveWhatsAppAccount(y),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:y=>{e.newWorkspacePin=y},onWorkspaceCreate:async(y,b)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(y,b),k.match(/^\d{4,6}$/)&&(await Mh(e,y,k),e.newWorkspacePin="")},onWorkspaceRemove:y=>e.handleWorkspaceRemove(y),onSetAddingWorkspace:y=>{e.addingWorkspace=y},onSetNewWorkspaceName:y=>{e.newWorkspaceName=y},onSetNewWorkspacePath:y=>{e.newWorkspacePath=y},onSetWorkspaceRemoveConfirm:y=>{e.workspaceRemoveConfirm=y},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(y,b)=>e.handleWorkspaceRename(y,b),whatsappDmPolicy:(()=>{const y=we(e),b=y==null?void 0:y.whatsappAccountId,k=b?p.find(A=>A.accountId===b):p[0];return(k==null?void 0:k.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var P;const y=we(e),b=y==null?void 0:y.whatsappAccountId,k=b?p.find(D=>D.accountId===b):p[0];if(!k)return;const E=k.dmPolicy!=null&&k.dmPolicy!=="disabled"?"disabled":"open",T=E==="open"?{dmPolicy:E,allowFrom:["*"]}:{dmPolicy:E};try{const D=await e.client.request("config.get"),W=D.config,z=(P=W==null?void 0:W.channels)==null?void 0:P.whatsapp,ke=((z==null?void 0:z.accounts)??{})[k.accountId]?{channels:{whatsapp:{accounts:{[k.accountId]:T}}}}:{channels:{whatsapp:T}};await e.client.request("config.patch",{raw:JSON.stringify(ke),baseHash:D.hash,note:`WhatsApp DM policy → ${E}`,skipRestart:!0}),await ee(e,!1)}catch(D){console.error("DM toggle failed:",D)}},whatsappGroupPolicy:(()=>{var D,W;const y=(D=e.configSnapshot)==null?void 0:D.config,b=(W=y==null?void 0:y.channels)==null?void 0:W.whatsapp,k=we(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},T=A?E[A]:void 0;return(T==null?void 0:T.groupPolicy)??(b==null?void 0:b.groupPolicy)??"allowlist"})(),whatsappGroupRequireMention:(()=>{var W,z;const y=(W=e.configSnapshot)==null?void 0:W.config,b=(z=y==null?void 0:y.channels)==null?void 0:z.whatsapp,k=we(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},T=A?E[A]:void 0,D=((T==null?void 0:T.groups)??(b==null?void 0:b.groups)??{})["*"];return(D==null?void 0:D.requireMention)!==!1})(),onWhatsAppGroupToggle:async()=>{var k;const y=we(e),b=y==null?void 0:y.whatsappAccountId;try{const A=await e.client.request("config.get"),E=A.config,T=((k=E==null?void 0:E.channels)==null?void 0:k.whatsapp)??{},P=T.accounts??{},D=b?P[b]:void 0,W=(D==null?void 0:D.groupPolicy)??T.groupPolicy??"allowlist",z=W==="disabled"||W==="allowlist",H=z?"open":"disabled",ke=z?{"*":{}}:void 0,Me={groupPolicy:H};ke&&(Me.groups=ke);const ze=D?{channels:{whatsapp:{accounts:{[b]:Me}}}}:{channels:{whatsapp:Me}};await e.client.request("config.patch",{raw:JSON.stringify(ze),baseHash:A.hash,note:`WhatsApp groups → ${H}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Group toggle failed:",A)}},onWhatsAppGroupMentionChange:async y=>{var A;const b=we(e),k=b==null?void 0:b.whatsappAccountId;try{const E=await e.client.request("config.get"),T=E.config,D=(((A=T==null?void 0:T.channels)==null?void 0:A.whatsapp)??{}).accounts??{},W=k?D[k]:void 0,z={"*":{requireMention:y}},H=W?{channels:{whatsapp:{accounts:{[k]:{groups:z}}}}}:{channels:{whatsapp:{groups:z}}};await e.client.request("config.patch",{raw:JSON.stringify(H),baseHash:E.hash,note:`WhatsApp group mention → ${y?"when mentioned":"always"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(E){console.error("Group mention change failed:",E)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:v.configured,imessageRunning:v.running,imessageConnected:v.connected,imessageLastError:v.lastError,imessageSelfChatMode:v.selfChatMode,imessageCliPath:v.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:$,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),b=y.config,k=(b==null?void 0:b.bindings)??[],A=we(e),E=A==null?void 0:A.agents.find(z=>z.id.endsWith("-admin")||z.id==="admin"),T=(E==null?void 0:E.id)??"admin",P=k.filter(z=>{var H;return((H=z.match)==null?void 0:H.channel)!=="imessage"}),D=[{agentId:T,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],W=[...P,...D];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:W}),baseHash:y.hash,note:"Enable iMessage (self-chat) for "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Fe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await ee(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),b=y.config,A=((b==null?void 0:b.bindings)??[]).filter(E=>{var T;return((T=E.match)==null?void 0:T.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:A}),baseHash:y.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Fe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),b=y.config,k=(b==null?void 0:b.bindings)??[],A=we(e),E=A==null?void 0:A.agents.find(W=>W.id.endsWith("-admin")||W.id==="admin"),T=(E==null?void 0:E.id)??"admin",P=k.filter(W=>{var z;return((z=W.match)==null?void 0:z.channel)!=="imessage"}),D=[{agentId:T,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:[...P,...D]}),baseHash:y.hash,note:"Reassign iMessage to "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Fe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:y=>{var b,k,A,E;if(e.infoModalOpen=y,y==="remote-access"){const T=((b=e.tailscaleStatus)==null?void 0:b.tailnetUrl)??((k=e.tailscaleStatus)!=null&&k.hostname?`https://${e.tailscaleStatus.hostname}`:null);T&&!e.remoteAccessQrDataUrl&&e.client.request("qr.generate",{url:T}).then(P=>{e.remoteAccessQrDataUrl=(P==null?void 0:P.dataUrl)??null}).catch(()=>{})}else if(y==="public-chat"){const T=((A=e.tailscaleStatus)==null?void 0:A.publicUrl)??((E=e.tailscaleStatus)==null?void 0:E.tailnetUrl)??null,P=e.selectedWorkspace??null;if(T&&P){const D=`${T}/public/chat/${encodeURIComponent(P)}`;e.publicChatQrDataUrl||e.client.request("qr.generate",{url:D}).then(W=>{e.publicChatQrDataUrl=(W==null?void 0:W.dataUrl)??null}).catch(()=>{})}}},onInfoModalClose:()=>{e.infoModalOpen=null},remoteAccessQrDataUrl:e.remoteAccessQrDataUrl??null,publicChatQrDataUrl:e.publicChatQrDataUrl??null,publicChatFullUrl:(()=>{var k,A;const y=((k=e.tailscaleStatus)==null?void 0:k.publicUrl)??((A=e.tailscaleStatus)==null?void 0:A.tailnetUrl)??null,b=e.selectedWorkspace??null;return!y||!b?null:`${y}/public/chat/${encodeURIComponent(b)}`})(),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(y,b)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await El(e.client,y,b);const k=`${y} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}y==="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 y=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Dk(e.client,y);const b=`${y} key removed`;e.apiKeySuccess=b,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===b&&(e.apiKeySuccess=null)},2500)}catch(b){e.apiKeyError=b instanceof Error?b.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyDisable:async(y,b)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Bk(e.client,y,b);const k=`${y} ${b?"disabled":"enabled"}`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:`Failed to ${b?"disable":"enable"} 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:y=>{e.authApiKeyInput=y},onAuthApiKeySubmit:async()=>{const y=e.authApiKeyInput.trim();if(y){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await El(e.client,"anthropic",y),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(b){e.authApiKeyError=b instanceof Error?b.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var b;const y=e.selectedWorkspace??((b=e.workspaces[0])==null?void 0:b.name);return y?e.accessState.accounts.some(k=>k.id===y):!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:(y,b)=>{var A;const k=e.selectedWorkspace??((A=e.workspaces[0])==null?void 0:A.name);k&&e.handleAccountPinSave(k,y,b)},publicChatAccountId:e.selectedWorkspace??null,publicChatSettingsOpen:e.publicChatSettingsOpen,onPublicChatSettingsOpen:()=>{e.publicChatSettingsOpen=!0},onPublicChatSettingsClose:()=>{e.publicChatSettingsOpen=!1},publicChatWidgetModalOpen:e.publicChatWidgetModalOpen,onPublicChatWidgetModalOpen:()=>{e.publicChatWidgetModalOpen=!0},onPublicChatWidgetModalClose:()=>{e.publicChatWidgetModalOpen=!1},publicChatEnabled:(()=>{var k;const y=(k=e.configSnapshot)==null?void 0:k.config,b=y==null?void 0:y.publicChat;return(b==null?void 0:b.enabled)===!0})(),publicChatAuthMode:(()=>{var T,P;const y=(T=e.configSnapshot)==null?void 0:T.config,b=y==null?void 0:y.publicChat,k=e.selectedWorkspace??"",A=b==null?void 0:b.accountSettings,E=((P=A==null?void 0:A[k])==null?void 0:P.auth)??(b==null?void 0:b.auth);return E==="verified"||E==="choice"?E:"anonymous"})(),publicChatGreeting:(()=>{var E;const y=(E=e.configSnapshot)==null?void 0:E.config,b=y==null?void 0:y.publicChat,k=b==null?void 0:b.greetings,A=e.selectedWorkspace??"";return(A&&(k==null?void 0:k[A]))??""})(),publicChatGreetingBusy:e.publicChatGreetingBusy,onPublicChatGreetingToggle:async()=>{var b;if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=(b=A==null?void 0:A.publicChat)==null?void 0:b.greetings;if(E==null?void 0:E[y]){const P={publicChat:{greetings:{[y]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(P),baseHash:k.hash,note:`Public chat greeting → disabled (${y})`,skipRestart:!0})}else{const P=await e.client.request("public.greeting.generate",{accountId:y});if(P!=null&&P.ok&&P.greeting){const D=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:P.greeting}}}),baseHash:D.hash,note:`Public chat greeting → enabled (${y})`,skipRestart:!0})}}e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting toggle failed:",k)}finally{e.publicChatGreetingBusy=!1}}},onPublicChatGreetingSave:async y=>{const b=e.selectedWorkspace??"";if(b)try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[b]:y}}}),baseHash:k.hash,note:`Public chat greeting text updated (${b})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting save failed:",k)}},onPublicChatGreetingRegenerate:async()=>{if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const b=await e.client.request("public.greeting.generate",{accountId:y});if(b!=null&&b.ok&&b.greeting){const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:b.greeting}}}),baseHash:k.hash,note:`Public chat greeting regenerated (${y})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}}catch(b){console.error("Public chat greeting regeneration failed:",b)}finally{e.publicChatGreetingBusy=!1}}},publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var y;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get"),k=b.config,A=((y=k==null?void 0:k.publicChat)==null?void 0:y.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!A}}),baseHash:b.hash,note:`Public chat → ${A?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),e.publicChatQrDataUrl=null}catch(b){console.error("Public chat toggle failed:",b)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async y=>{if(e.publicChatToggleBusy)return;const b=e.selectedWorkspace??"";if(b){e.publicChatToggleBusy=!0;try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{accountSettings:{[b]:{auth:y}}}}),baseHash:k.hash,note:`Public chat auth → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat auth mode change failed:",k)}finally{e.publicChatToggleBusy=!1}}},publicChatEmailFrom:(()=>{var k,A;const y=(k=e.configSnapshot)==null?void 0:k.config,b=(A=y==null?void 0:y.publicChat)==null?void 0:A.email;return(b==null?void 0:b.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var T,P;const y=(T=e.configSnapshot)==null?void 0:T.config,b=y==null?void 0:y.publicChat,k=e.selectedWorkspace??"",A=b==null?void 0:b.accountSettings,E=((P=A==null?void 0:A[k])==null?void 0:P.verifyMethods)??(b==null?void 0:b.verifyMethods);return Array.isArray(E)?E:["whatsapp","sms"]})(),onPublicChatEmailSave:async(y,b)=>{if(e.publicChatEmailBusy)return;const k=e.selectedWorkspace??"";if(k){e.publicChatEmailBusy=!0;try{const A=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{email:{from:y||void 0},accountSettings:{[k]:{verifyMethods:b}}}}),baseHash:A.hash,note:"Update email verification settings for public chat",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Email verification save failed:",A)}finally{e.publicChatEmailBusy=!1}}},brandAccentColor:(()=>{var k;const y=e.selectedWorkspace;return y?((k=Ne()[y])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const y=e.selectedWorkspace;return y?((k=Ne()[y])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const y=e.selectedWorkspace;return y?!!((k=Ne()[y])!=null&&k.logoUrl):!1})(),agentSettingsOpen:e.agentSettingsOpen,agentSettingsAgents:(()=>{var A,E;const y=we(e);if(!y)return[];const b=(A=e.configSnapshot)==null?void 0:A.config,k=(E=b==null?void 0:b.agents)==null?void 0:E.list;return y.agents.map(T=>{var H;const P=Array.isArray(k)?k.find(ke=>ke.id===T.id):void 0,D=P==null?void 0:P.model,W=typeof D=="string"?D:(D==null?void 0:D.primary)??null,z=T.id.endsWith("-admin")||T.id==="admin";return{id:T.id,label:z?"Admin":"Public",model:(W==null?void 0:W.trim())||null,thinkingLevel:((H=P==null?void 0:P.thinkingLevel)==null?void 0:H.trim())||null}})})(),agentSettingsModelCatalog:e.chatModelCatalog??[],memoryProvider:(()=>{var k,A,E;const y=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=y==null?void 0:y.agents)==null?void 0:A.defaults)==null?void 0:E.memorySearch;return typeof(b==null?void 0:b.provider)=="string"&&b.provider?b.provider:"local"})(),memoryFallback:(()=>{var k,A,E;const y=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=y==null?void 0:y.agents)==null?void 0:A.defaults)==null?void 0:E.memorySearch;return typeof(b==null?void 0:b.fallback)=="string"&&b.fallback?b.fallback:"none"})(),onAgentSettingsToggle:()=>{e.agentSettingsOpen=!e.agentSettingsOpen},onAgentModelChange:async(y,b)=>{try{const k=await e.client.request("config.get"),A=k.config,E=(A==null?void 0:A.agents)??{},T=Array.isArray(E.list)?[...E.list]:[],P=T.findIndex(W=>W.id===y);if(b)P>=0?T[P]={...T[P],model:b}:T.push({id:y,model:b});else if(P>=0){const{model:W,...z}=T[P];Object.keys(z).length<=1?T.splice(P,1):T[P]=z}const D=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(D),baseHash:k.hash,note:`Agent ${y} model → ${b||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent model change failed:",k)}},onAgentThinkingChange:async(y,b)=>{try{const k=await e.client.request("config.get"),A=k.config,E=(A==null?void 0:A.agents)??{},T=Array.isArray(E.list)?[...E.list]:[],P=T.findIndex(z=>z.id===y),D=b==="off"?void 0:b;if(D)P>=0?T[P]={...T[P],thinkingLevel:D}:T.push({id:y,thinkingLevel:D});else if(P>=0){const{thinkingLevel:z,...H}=T[P];Object.keys(H).length<=1?T.splice(P,1):T[P]=H}const W=T.length>0?{agents:{list:T}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(W),baseHash:k.hash,note:`Agent ${y} thinking → ${D||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent thinking change failed:",k)}},onMemoryProviderChange:async y=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{provider:y}}}}),baseHash:b.hash,note:`Memory search provider → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Memory provider change failed:",b)}},onMemoryFallbackChange:async y=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{fallback:y}}}}),baseHash:b.hash,note:`Memory search fallback → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Memory fallback change failed:",b)}},brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async y=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,T=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=T.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...T,brand:{...P,accentColor:y}}}}),baseHash:A.hash,note:`Brand accent → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const D=Ne();D[b]||(D[b]={}),D[b].accentColor=y,Tn(b)}catch(A){console.error("Brand accent change failed:",A)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async y=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,T=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=T.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...T,brand:{...P,backgroundColor:y}}}}),baseHash:A.hash,note:`Brand background → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const D=Ne();D[b]||(D[b]={}),D[b].backgroundColor=y,Tn(b)}catch(A){console.error("Brand background change failed:",A)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async y=>{const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const k=await y.arrayBuffer(),A=new Uint8Array(k);let E="";for(let D=0;D<A.length;D++)E+=String.fromCharCode(A[D]);const T=btoa(E);await e.client.request("brand.uploadLogo",{workspace:b,data:T,mimeType:y.type});const P=Ne();P[b]||(P[b]={}),P[b].logoUrl=`/brand-logo/${encodeURIComponent(b)}`}catch(k){console.error("Brand logo upload failed:",k)}finally{e.brandingBusy=!1}}},onBrandLogoRemove:async()=>{const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:y});const b=Ne();b[y]&&delete b[y].logoUrl}catch(b){console.error("Brand logo remove failed:",b)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var b;const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=((b=A==null?void 0:A.workspaces)==null?void 0:b[y])??{},{brand:T,...P}=E;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[y]:{...P,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:y})}catch{}const D=Ne();delete D[y],Tn(y)}catch(k){console.error("Brand reset failed:",k)}finally{e.brandingBusy=!1}}},tailscaleStatus:e.tailscaleStatus,tailscaleBusy:e.tailscaleBusy,tailscaleAuthUrl:e.tailscaleAuthUrl,tailscaleError:e.tailscaleError,tailscaleServeEnableUrl:e.tailscaleServeEnableUrl,tailscaleFunnelEnableUrl:e.tailscaleFunnelEnableUrl,tailscaleDisableConfirm:e.tailscaleDisableConfirm,tailscaleConnectProgress:e.tailscaleConnectProgress,tailscaleConnectMessage:e.tailscaleConnectMessage,tailscaleConnectSuccess:e.tailscaleConnectSuccess,onTailscaleEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleAuthUrl=null,M();try{const y=await e.client.request("tailscale.enable");y.authUrl?(wt&&(clearInterval(wt),wt=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=y.authUrl,Mi=setInterval(async()=>{try{const b=await e.client.request("tailscale.status");e.tailscaleStatus=b,e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,b.loggedIn&&(Kt(),e.tailscaleAuthUrl=null,e.tailscaleConnectSuccess=!0,e.tailscaleConnectMessage="Connected!",setTimeout(()=>{e.tailscaleConnectSuccess=!1,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1},1500))}catch{}},3e3),Pi=setTimeout(()=>{Kt(),e.tailscaleBusy&&(e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)},3e5)):y.alreadyLoggedIn?(Kt(),e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1):(Kt(),e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)}catch(y){console.error("Tailscale enable failed:",y),Kt(),e.tailscaleError=y.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleServeEnableUrl=null;try{await e.client.request("tailscale.serve.enable"),await S()}catch(b){console.error("Tailscale serve enable failed:",b);const k=b;(y=k.payload)!=null&&y.enableUrl&&(e.tailscaleServeEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Remote Access"}finally{e.tailscaleBusy=!1}}},onTailscaleServeDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.serve.disable"),await S()}catch(y){console.error("Tailscale serve disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable"),await S()}catch(b){console.error("Tailscale funnel enable failed:",b);const k=b;(y=k.payload)!=null&&y.enableUrl&&(e.tailscaleFunnelEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Funnel"}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.funnel.disable"),await S()}catch(y){console.error("Tailscale funnel disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleDisableConfirmToggle:()=>{e.tailscaleDisableConfirm=!e.tailscaleDisableConfirm},wifiModalOpen:e.wifiModalOpen,onWifiModalToggle:()=>{e.wifiModalOpen=!e.wifiModalOpen,e.wifiModalOpen||(e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null)},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{var y;if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[b,k]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiNetworks=b.networks,k.connected&&k.signal==null&&((y=b.networks)!=null&&y.length)){const A=b.networks.find(E=>E.active)||b.networks.find(E=>E.ssid===k.ssid);A&&(k.signal=A.signal)}e.wifiStatus=k}catch(b){console.error("WiFi scan failed:",b),e.wifiError=b.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{var b;if(e.wifiBusy||!e.wifiSelectedSsid)return;const y=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const k=await e.client.request("wifi.connect",{ssid:y,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:k.connected,ssid:k.ssid,signal:null,ip:k.ip,savedSsid:k.ssid,autoconnect:!0},e.wifiBusy=!1;try{const[A,E]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(E.connected&&E.signal==null&&((b=A.networks)!=null&&b.length)){const T=A.networks.find(P=>P.active)||A.networks.find(P=>P.ssid===E.ssid);T&&(E.signal=T.signal)}e.wifiStatus=E}catch{}}catch(k){console.error("WiFi connect failed:",k),e.wifiError=k.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 y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi disconnect failed:",y),e.wifiError=y.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 y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi forget failed:",y),e.wifiError=y.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:y=>{e.wifiSelectedSsid=y,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:y=>{e.wifiPassword=y},networkPort:e.networkPort,networkHostname:e.networkHostname,networkPortInput:e.networkPortInput,networkHostnameInput:e.networkHostnameInput,networkModalOpen:e.networkModalOpen,networkBusy:e.networkBusy,networkError:e.networkError,networkSuccess:e.networkSuccess,onNetworkModalToggle:()=>{e.networkModalOpen=!e.networkModalOpen,e.networkModalOpen&&(e.networkPortInput=String(e.networkPort??""),e.networkHostnameInput=e.networkHostname,e.networkError=null,e.networkSuccess=null)},onNetworkPortChange:y=>{e.networkPortInput=y,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:y=>{e.networkHostnameInput=y,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const y=e.networkPortInput.trim(),b=Number.parseInt(y,10),k=e.networkHostnameInput.trim();if(!y||!Number.isFinite(b)||b<1024||b>65535){e.networkError="Port must be a number between 1024 and 65535",e.networkBusy=!1;return}const A=b!==e.networkPort,E=k!==e.networkHostname;if(!A&&!E){e.networkBusy=!1;return}try{E&&await e.client.request("network.setHostname",{hostname:k});const T={};A&&(T.gateway={port:b}),E&&(T.discovery={bonjourHostname:k});const P=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify(T),baseHash:P.hash,note:[A?`Port → ${b}`:null,E?`Hostname → ${k}`:null].filter(Boolean).join(", "),restartDelayMs:2e3}),e.networkSuccess="Saved — redirecting...";const D=window.location.protocol,W=E?`${k}.local`:window.location.hostname,z=A?b:e.networkPort,H=`${D}//${W}:${z}/setup`;setTimeout(()=>{window.location.href=H},1500)}catch(T){console.error("Network save failed:",T),e.networkError=T.message||"Failed to save network settings",e.networkBusy=!1}},wsProps:o0(e)})}if(e.filesPage){const u=r0(e);return bg({connected:e.connected,wsProps:Sn(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:()=>{rn(e,u),cs(e,u)},onReindex:()=>Rf(e,u),onSelectFile:p=>{e.filesPendingDeletePath=null,Af(e,p,u)},onToggleSelectFile:p=>Cf(e,p,u),onToggleDir:p=>Lf(e,p),onUpload:(p,v)=>_f(e,p,v,u),onNewFolder:(p,v)=>Mf(e,p,v,u),onDownload:p=>rd(e,p,u),onBulkDownload:()=>Ef(e,u),onDelete:p=>{e.filesPendingDeletePath=null,Pf(e,p,u)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,v)=>Tf(e,p,v,u),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const v=e.filesSearchAgentId??u;Df(e,p,v)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{Bf(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return hg({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:()=>Ek(e),onStop:()=>Tk(e),onToggleInput:()=>Mk(e),onToggleFullscreen:()=>Pk(e),onCompleteHandoff:()=>_k(e),onCanvasMouseDown:u=>{const v=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-v.left,u.clientY-v.top);po(e,"mousePressed",S.x,S.y,u.button===2?"right":u.button===1?"middle":"left")},onCanvasMouseUp:u=>{const v=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-v.left,u.clientY-v.top);po(e,"mouseReleased",S.x,S.y)},onCanvasMouseMove:u=>{const p=Bn();if(p.shouldThrottleMouseMove())return;const $=u.target.getBoundingClientRect(),S=p.translateCoordinates(u.clientX-$.left,u.clientY-$.top);po(e,"mouseMoved",S.x,S.y)},onCanvasKeyDown:u=>{let p=0;u.altKey&&(p|=1),u.ctrlKey&&(p|=2),u.metaKey&&(p|=4),u.shiftKey&&(p|=8),ho(e,"keyDown",u.key,{code:u.code,modifiers:p||void 0}),u.key.length===1&&ho(e,"char",u.key,{text:u.key})},onCanvasKeyUp:u=>{ho(e,"keyUp",u.key,{code:u.code})}});if(e.adminsPage){const u=a0(e),p=Ka(e);return lm({connected:e.connected,wsProps:Sn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>ys(e,u),onAdd:v=>{Iu(e,v,u,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:v=>Ru(e,v,u,p),onNewPhoneChange:v=>e.handleAdminsNewPhoneChange(v)})}if(e.contactsPage){const u=l0(e);return fm({connected:e.connected,wsProps:Sn(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:()=>Pt(e,u),onAdd:(p,v)=>Lu(e,p,v,u),onDelete:p=>Du(e,p,u),onSetField:(p,v,$)=>jo(e,p,v,$,u),onDeleteField:(p,v)=>Bu(e,p,v,u),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:()=>Pt(e,u),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,v=e.contactsAddFieldKey.trim();!p||!v||(jo(e,p,v,e.contactsAddFieldValue,u),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const u=e.connected?null:"Disconnected from gateway.",p=Dl(e),v=e.chatAvatarUrl??p??null,$=(()=>{var y;const S=(y=e.configSnapshot)==null?void 0:y.config,M=S==null?void 0:S.publicChat;return(M==null?void 0:M.enabled)===!0})();return gw({connected:e.connected,wsProps:Sn(e),publicChatEnabled:$,publicChatAccountId:e.selectedWorkspace??void 0,chatPageTab:e.chatPageTab??"chat",onChatPageTabChange:S=>{if(e.chatPageTab=S,S==="whatsapp"&&!e.waLoading&&e.waConversations.length===0){const M=Ii(e);vu(M).then(()=>e.requestUpdate())}},whatsappProps:g0(e),sessionKey:e.sessionKey,onSessionKeyChange:S=>{const M=e.selectedWorkspace??"";wo(),Wn(M,e.sessionKey,e.chatMessage),e.sessionKey=S,e.chatMessage=Kn(M,S),e.chatAttachments=[],e.chatStream=null,e.chatInterimText=null,e.chatSuggestions=[],e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:S,lastActiveSessionKey:S}),e.loadAssistantIdentity(),Jt(e),Eo(e)},showThinking:e.settings.chatShowThinking??!1,verboseLevel:e.chatVerboseLevel,suggestions:e.chatSuggestions,onSuggestionClick:S=>{e.chatMessage=S,e.chatSuggestions=[],e.handleSendChat()},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:v,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:u,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const S=Math.max(e.chatMessages.length+10,nn);return Promise.all([Jt(e,{limit:S}),Eo(e)])},onToggleFocusMode:()=>{},onChatScroll:S=>e.handleChatScroll(S),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:S=>{e.chatMessage=S,wr(e.selectedWorkspace??"",e.sessionKey,S)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:S=>e.chatAttachments=S,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:S=>e.removeQueuedMessage(S),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:S=>e.handleOpenSidebar(S),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:S=>e.handleSplitRatioChange(S),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?fk({connected:e.connected,wsProps:Sn(e),activeTab:e.advancedTab,onTabChange:u=>{e.advancedTab=u,u==="cron"&&e.loadCron(),u==="skills"&&We(e,{clearMessages:!0}),u==="opening-hours"&&Wa(e),u==="logs"&&(e.logsSubTab==="session"?Pn(e,{reset:!0}):Gt(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(r=(a=e.channelsSnapshot)==null?void 0:a.channelMeta)!=null&&r.length?e.channelsSnapshot.channelMeta.map(u=>u.id):((c=e.channelsSnapshot)==null?void 0:c.channelOrder)??[],channelLabels:((d=e.channelsSnapshot)==null?void 0:d.channelLabels)??{},channelMeta:((h=e.channelsSnapshot)==null?void 0:h.channelMeta)??[],agentIds:(()=>{var p;const u=we(e);return((p=u==null?void 0:u.agents)==null?void 0:p.map(v=>v.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:u=>{e.cronDetailJobId=u.id,xo(e,u.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:u=>{e.cronForm=Sh(u),e.cronEditJobId=u.id,e.cronDetailJobId=null},onEditSave:()=>{const u=e.cronEditJobId;u&&Ah(e,u).then(()=>{e.cronEditJobId=null})},onFormChange:u=>e.cronForm={...e.cronForm,...u},onRefresh:()=>e.loadCron(),onAdd:()=>{bh(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(u,p)=>wh(e,u,p),onRun:u=>kh(e,u),onRemove:u=>{e.cronPendingDeleteId=null,$h(e,u)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:u=>{e.cronPendingDeleteId=u||null},onLoadRuns:u=>xo(e,u),runModalJobId:e.cronRunModalJobId,runModalJobName:e.cronRunModalJobName,runResult:e.cronRunResult,onRunModalClose:()=>{e.cronRunModalJobId=null,e.cronRunModalJobName="",e.cronRunResult=null}},skillsProps:{loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,typeFilter:e.skillsTypeFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,detail:e.skillDetail,detailTab:e.skillDetailTab,addModal:e.skillAddModal,addForm:e.skillAddForm,formSource:e.skillAddFormSource,editTab:e.skillEditTab,drafts:e.skillDrafts,onFilterChange:u=>e.skillsFilter=u,onTypeFilterChange:u=>e.skillsTypeFilter=u,onRefresh:()=>We(e,{clearMessages:!0}),onToggle:(u,p)=>Oc(e,u,p),onEdit:(u,p)=>Nc(e,u,p),onSaveKey:u=>Fc(e,u),onInstall:(u,p,v)=>Uc(e,u,p,v),onViewDetail:u=>Wc(e,u),onDetailClose:()=>Kc(e),onDetailTab:u=>zc(e,u),onAddOpen:()=>Hc(e),onAddClose:()=>qc(e),onImportDraft:u=>jc(e,u),onInstallDraft:u=>Gc(e,u),onDeleteDraft:u=>Vc(e,u),onAddSave:()=>ua(e),onAddFormUpdate:(u,p)=>{e.skillAddForm={...e.skillAddForm,[u]:p}},onAlwaysActiveToggle:(u,p)=>Zc(e,u,p),onDelete:u=>ed(e,u),onEditSkill:u=>Qc(e,u),onEditDetail:u=>Jc(e,u),onRefUpdate:(u,p)=>Yc(e,u,p),onEditTab:u=>Xc(e,u)},logsProps:{logsSubTab:e.logsSubTab,isAdmin:e.accessState.master||!e.accessState.hasPins,onSubTabChange:u=>{e.logsSubTab=u,u==="session"?Pn(e,{reset:!0}):Gt(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,chipsExpanded:e.sessionLogsChipsExpanded,expandedIds:e.sessionLogsExpandedIds,onFilterTextChange:u=>e.sessionLogsFilterText=u,onTypeToggle:(u,p)=>{const v=e;v.sessionLogsTypeFilters={...v.sessionLogsTypeFilters,[u]:p}},onAgentToggle:(u,p)=>{const v=e;v.sessionLogsAgentFilters={...v.sessionLogsAgentFilters,[u]:p}},onToggleAutoFollow:u=>e.sessionLogsAutoFollow=u,onToggleChips:()=>{const u=e;u.sessionLogsChipsExpanded=!u.sessionLogsChipsExpanded},onToggleExpand:u=>{const p=e,v=new Set(p.sessionLogsExpandedIds);v.has(u)?v.delete(u):v.add(u),p.sessionLogsExpandedIds=v,p.requestUpdate()},onRefresh:()=>{Pn(e,{reset:!0})},onExport:(u,p)=>e.exportSessionLogs(u,p),onScroll:u=>e.handleSessionLogsScroll(u)},loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,chipsExpanded:e.logsChipsExpanded,truncated:e.logsTruncated,onFilterTextChange:u=>e.logsFilterText=u,onLevelToggle:(u,p)=>{e.logsLevelFilters={...e.logsLevelFilters,[u]:p}},onToggleAutoFollow:u=>e.logsAutoFollow=u,onToggleChips:()=>{const u=e;u.logsChipsExpanded=!u.logsChipsExpanded},onRefresh:()=>Gt(e,{reset:!0}),onExport:(u,p)=>e.exportSessionLogs(u,p),onScroll:u=>e.handleLogsScroll(u)},openingHoursProps:{loading:e.openingHoursLoading,error:e.openingHoursError,busy:e.openingHoursBusy,form:e.openingHoursForm,onFormChange:u=>{const p=e;p.openingHoursForm={...p.openingHoursForm,...u}},onDayChange:(u,p,v)=>{const $=e,S={...$.openingHoursForm.days};S[u]={...S[u],[p]:v},$.openingHoursForm={...$.openingHoursForm,days:S}},onAddClosedDate:u=>{const p=e;p.openingHoursForm.closedDates.includes(u)||(p.openingHoursForm={...p.openingHoursForm,closedDates:[...p.openingHoursForm.closedDates,u].sort()})},onRemoveClosedDate:u=>{const p=e;p.openingHoursForm={...p.openingHoursForm,closedDates:p.openingHoursForm.closedDates.filter(v=>v!==u)}},onSave:()=>{Mu(e)}}}):(window.location.replace("/chat"),l``)}function y0(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 Bl(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function v0(e,t,n){return l`
4852
4857
  <div class="audit-modal-overlay" @click=${s=>{s.target.classList.contains("audit-modal-overlay")&&n()}}>
4853
4858
  <div class="audit-modal-card">
4854
4859
  <div class="audit-modal-header">
@@ -4880,7 +4885,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4880
4885
  `}
4881
4886
  </div>
4882
4887
  </div>
4883
- `}const b0={trace:!1,debug:!1,info:!0,warn:!0,error:!0,fatal:!0},w0={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 k0(e){e.basePath=jf();const t=Xe();Gl(t.accentColor),Vl(t.backgroundColor);const n=document.querySelector('link[rel="icon"]');if(n&&(n.href=t.iconUrl),window.scrollTo(0,0),Ff(e),e.publicChat){const i=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__,s=(i==null?void 0:i.accountId)??"",o=s?s.charAt(0).toUpperCase()+s.slice(1):"Assistant";document.title=`Chat with ${o}`,Be(e);return}if(e.setup){document.title=`${t.name} Setup`,Be(e);return}if(e.filesPage){document.title=`${t.name} Files`,Wf(e),Be(e);return}if(e.browserPage){document.title=`${t.name} Browser`,Be(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,Be(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,Be(e);return}if(e.chatPage){document.title=`${t.name} Chat`,Be(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,Be(e);return}Jf(e,!0),Gf(e),Vf(e),window.addEventListener("popstate",e.popStateHandler),zf(e),Be(e),Nf(e),e.tab==="logs"&&(e.logsSubTab==="session"?ga(e):ha(e)),e.tab==="debug"&&ya(e)}function x0(e){gh(e)}function $0(e){var t;window.removeEventListener("popstate",e.popStateHandler),Of(e),fa(e),ma(e),va(e),Uf(e),Kf(e),Qf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function S0(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",s=t.has("setupStep")&&e.setupStep==="setup";(n||i||s)&&e.handleAuthStatusCheck&&e.authConnected===null&&!e.authBusy&&e.handleAuthStatusCheck(),e.setupStep==="setup"&&t.has("setupStep")&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(a=>{e.channelsSnapshot=a,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(o=>{e.channelsSnapshot=o,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;sn(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&lc(e,t.has("tab")||t.has("logsAutoFollow"))}}function A0(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 C0(e,t,n){await ea(e,t,n),await ee(e,!0)}async function E0(e,t){await hc(e,t),await ee(e,!0)}async function T0(e,t){await fc(e,t),await ee(e,!0)}async function _0(e,t){await gc(e,t)}async function M0(e,t){await mc(e,t)}async function P0(e){await vh(e),await Fe(e),await ee(e,!0)}async function I0(e){await Fe(e),await ee(e,!0)}function R0(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(),a=s.join(":").trim();o&&a&&(t[o]=a)}return t}function Nu(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 Ou(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function L0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=A0(n??void 0)}function D0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function B0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function N0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function O0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Nu(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(Ou(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:R0(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 ee(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function F0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Nu(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(Ou(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 d=(s==null?void 0:s.error)??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:d,success:null};return}const o=s.merged??s.imported??null,a=o?{...t.values,...o}:t.values,r=!!(a.banner||a.website||a.nip05||a.lud16);e.nostrProfileFormState={...t,importing:!1,values:a,error:null,success:s.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:r},s.saved&&await ee(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function U0(e){if(!e.client)return;const t=e.authRefreshTokenInput.trim();if(t){e.authRefreshTokenBusy=!0,e.authRefreshTokenError=null;try{const n=await e.client.request("auth.importRefreshToken",{refreshToken:t});e.authConnected=n.connected,e.authExpiresIn=n.expiresIn??null,e.authMessage=n.message??null,e.authRefreshToken=t,e.authRefreshTokenInput="",e.claudeAuthModalOpen=!1}catch(n){e.authRefreshTokenError=n instanceof Error?n.message:"Failed to import token"}finally{e.authRefreshTokenBusy=!1}}}async function W0(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,e.authRefreshToken=t.refreshToken??null}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to check auth status"}finally{e.authBusy=!1}}}async function K0(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 z0(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 H0(e,t){e.authCodeInput=t}async function q0(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="setup"):(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="setup"):(e.licenseValid=null,e.licenseMessage=n,e.setupStep="license")}finally{e.licenseBusy=!1}}}async function j0(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="setup"},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 G0(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 V0(e,t){e.licenseKey=t}async function Q0(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 J0(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 Y0=Object.defineProperty,X0=Object.getOwnPropertyDescriptor,g=(e,t,n,i)=>{for(var s=i>1?void 0:i?X0(t,n):t,o=e.length-1,a;o>=0;o--)(a=e[o])&&(s=(i?a(t,n,s):a(s))||s);return i&&s&&Y0(t,n,s),s};const yo=$p();function Z0(){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 ex(){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 tx(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function nx(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function ix(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function sx(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function ox(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function ax(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let f=class extends jt{constructor(){super(...arguments),this.settings=Ls(),this.password="",this.tab="chat",this.onboarding=Z0(),this.setup=ex(),this.filesPage=tx(),this.browserPage=nx(),this.adminsPage=ix(),this.contactsPage=sx(),this.chatPage=ox(),this.advancedPage=ax(),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=yc,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=yo.name,this.assistantAvatar=yo.avatar,this.assistantAgentId=yo.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.chatSuggestions=[],this.chatStreamStartedAt=null,this.chatRunId=null,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatModelCatalog=[],this.chatVerboseLevel=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=`{
4888
+ `}const b0={trace:!1,debug:!1,info:!0,warn:!0,error:!0,fatal:!0},w0={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 k0(e){e.basePath=jf();const t=Xe();Gl(t.accentColor),Vl(t.backgroundColor);const n=document.querySelector('link[rel="icon"]');if(n&&(n.href=t.iconUrl),window.scrollTo(0,0),Ff(e),e.publicChat){const i=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__,s=(i==null?void 0:i.accountId)??"",o=s?s.charAt(0).toUpperCase()+s.slice(1):"Assistant";document.title=`Chat with ${o}`,Be(e);return}if(e.setup){document.title=`${t.name} Setup`,Be(e);return}if(e.filesPage){document.title=`${t.name} Files`,Wf(e),Be(e);return}if(e.browserPage){document.title=`${t.name} Browser`,Be(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,Be(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,Be(e);return}if(e.chatPage){document.title=`${t.name} Chat`,Be(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,Be(e);return}Jf(e,!0),Gf(e),Vf(e),window.addEventListener("popstate",e.popStateHandler),zf(e),Be(e),Nf(e),e.tab==="logs"&&(e.logsSubTab==="session"?ga(e):ha(e)),e.tab==="debug"&&ya(e)}function x0(e){gh(e)}function $0(e){var t;window.removeEventListener("popstate",e.popStateHandler),Of(e),fa(e),ma(e),va(e),Uf(e),Kf(e),Qf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function S0(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",s=t.has("setupStep")&&e.setupStep==="setup";(n||i||s)&&e.handleAuthStatusCheck&&e.authConnected===null&&!e.authBusy&&e.handleAuthStatusCheck(),e.setupStep==="setup"&&t.has("setupStep")&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(a=>{e.channelsSnapshot=a,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(o=>{e.channelsSnapshot=o,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;sn(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&lc(e,t.has("tab")||t.has("logsAutoFollow"))}}function A0(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 C0(e,t,n){await ea(e,t,n),await ee(e,!0)}async function E0(e,t){await hc(e,t),await ee(e,!0)}async function T0(e,t){await fc(e,t),await ee(e,!0)}async function _0(e,t){await gc(e,t)}async function M0(e,t){await mc(e,t)}async function P0(e){await vh(e),await Fe(e),await ee(e,!0)}async function I0(e){await Fe(e),await ee(e,!0)}function R0(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(),a=s.join(":").trim();o&&a&&(t[o]=a)}return t}function Nu(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 Ou(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function L0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=A0(n??void 0)}function D0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function B0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function N0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function O0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Nu(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(Ou(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:R0(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 ee(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function F0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Nu(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(Ou(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 c=(s==null?void 0:s.error)??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:c,success:null};return}const o=s.merged??s.imported??null,a=o?{...t.values,...o}:t.values,r=!!(a.banner||a.website||a.nip05||a.lud16);e.nostrProfileFormState={...t,importing:!1,values:a,error:null,success:s.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:r},s.saved&&await ee(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function U0(e){if(!e.client)return;const t=e.authRefreshTokenInput.trim();if(t){e.authRefreshTokenBusy=!0,e.authRefreshTokenError=null;try{const n=await e.client.request("auth.importRefreshToken",{refreshToken:t});e.authConnected=n.connected,e.authExpiresIn=n.expiresIn??null,e.authMessage=n.message??null,e.authRefreshToken=t,e.authRefreshTokenInput="",e.claudeAuthModalOpen=!1}catch(n){e.authRefreshTokenError=n instanceof Error?n.message:"Failed to import token"}finally{e.authRefreshTokenBusy=!1}}}async function W0(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,e.authRefreshToken=t.refreshToken??null}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to check auth status"}finally{e.authBusy=!1}}}async function K0(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 z0(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 H0(e,t){e.authCodeInput=t}async function q0(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="setup"):(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="setup"):(e.licenseValid=null,e.licenseMessage=n,e.setupStep="license")}finally{e.licenseBusy=!1}}}async function j0(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="setup"},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 G0(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 V0(e,t){e.licenseKey=t}async function Q0(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 J0(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 Y0=Object.defineProperty,X0=Object.getOwnPropertyDescriptor,g=(e,t,n,i)=>{for(var s=i>1?void 0:i?X0(t,n):t,o=e.length-1,a;o>=0;o--)(a=e[o])&&(s=(i?a(t,n,s):a(s))||s);return i&&s&&Y0(t,n,s),s};const yo=$p();function Z0(){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 ex(){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 tx(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function nx(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function ix(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function sx(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function ox(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function ax(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let f=class extends jt{constructor(){super(...arguments),this.settings=Ls(),this.password="",this.tab="chat",this.onboarding=Z0(),this.setup=ex(),this.filesPage=tx(),this.browserPage=nx(),this.adminsPage=ix(),this.contactsPage=sx(),this.chatPage=ox(),this.advancedPage=ax(),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=yc,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=yo.name,this.assistantAvatar=yo.avatar,this.assistantAgentId=yo.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.chatSuggestions=[],this.chatStreamStartedAt=null,this.chatRunId=null,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatModelCatalog=[],this.chatVerboseLevel=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=`{
4884
4889
  }
4885
4890
  `,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.publicChatGreetingBusy=!1,this.publicChatEmailBusy=!1,this.publicChatSettingsOpen=!1,this.publicChatWidgetModalOpen=!1,this.brandingBusy=!1,this.agentSettingsOpen=!1,this.brandingExpanded=!1,this.tailscaleStatus=null,this.tailscaleBusy=!1,this.tailscaleAuthUrl=null,this.tailscaleError=null,this.tailscaleServeEnableUrl=null,this.tailscaleFunnelEnableUrl=null,this.tailscaleDisableConfirm=!1,this.tailscaleConnectProgress=0,this.tailscaleConnectMessage="",this.tailscaleConnectSuccess=!1,this.wifiStatus=null,this.wifiNetworks=[],this.wifiBusy=!1,this.wifiError=null,this.wifiPassword="",this.wifiSelectedSsid=null,this.networkPort=null,this.networkHostname="",this.networkPortInput="",this.networkHostnameInput="",this.networkModalOpen=!1,this.networkBusy=!1,this.networkError=null,this.networkSuccess=null,this.wifiModalOpen=!1,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.authRefreshToken=null,this.claudeAuthModalOpen=!1,this.authRefreshTokenInput="",this.authRefreshTokenBusy=!1,this.authRefreshTokenError=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={...w0},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.cronNewEventModal=!1,this.cronDetailJobId=null,this.cronEditJobId=null,this.cronPendingDeleteId=null,this.cronRunModalJobId=null,this.cronRunModalJobName="",this.cronRunResult=null,this.openingHoursLoading=!1,this.openingHoursError=null,this.openingHoursBusy=!1,this.openingHoursForm=Ua(),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.skillsTypeFilter="all",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillDetail=null,this.skillDetailTab="",this.skillAddModal=!1,this.skillAddForm={name:"",skillContent:"",references:[]},this.skillAddFormSource="draft",this.skillEditTab="SKILL.md",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.chatPageTab="chat",this.waConversations=[],this.waSelectedJid=null,this.waMessages=[],this.waGroupInfo=null,this.waLoading=!1,this.waMessagesLoading=!1,this.waSearchQuery="",this.waComposeDraft="",this.waSending=!1,this.waLastError=null,this.infoModalOpen=null,this.remoteAccessQrDataUrl=null,this.publicChatQrDataUrl=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={...b0},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.logsChipsExpanded=!1,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.sessionLogsChipsExpanded=!1,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=()=>Yf(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._beforeUnloadHandler=()=>{var t;wo();const e=this.selectedWorkspace??((t=this.publicChatConfig)==null?void 0:t.accountId)??"";e&&Wn(e,this.sessionKey,this.chatMessage)}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),k0(this),window.addEventListener("beforeunload",this._beforeUnloadHandler)}firstUpdated(){x0(this)}disconnectedCallback(){window.removeEventListener("beforeunload",this._beforeUnloadHandler),this.stopEmbeddingPoll(),$0(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){S0(this,e)}connect(){Be(this)}handleChatScroll(e){lh(this,e)}handleLogsScroll(e){dh(this,e)}handleSessionLogsScroll(e){uh(this,e)}exportLogs(e,t){hh(e,t)}exportSessionLogs(e,t){fh(e,t)}resetToolStream(){Zo(this)}resetChatScroll(){ph(this)}async loadAssistantIdentity(){await qo(this)}applySettings(e){at(this,e)}setTab(e){Hf(this,e)}setTheme(e,t){qf(this,e,t)}async loadOverview(){await ud(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.accountId=this.selectedWorkspace??void 0,this.cronForm={...this.cronForm,accountId:this.selectedWorkspace??void 0},await pd(this)}async handleAbortChat(){await fd(this)}removeQueuedMessage(e){tg(this,e)}async handleSendChat(e,t){await ng(this,e,t)}async handleWhatsAppStart(e,t){await C0(this,e,t)}async handleWhatsAppWait(e){await E0(this,e)}async handleWhatsAppLogout(e){await T0(this,e)}async handleAddWhatsAppAccount(e){await _0(this,e)}async handleRemoveWhatsAppAccount(e){await M0(this,e)}async handleAccessCheck(){await Cr(this)}async handlePinSubmit(e,t){await Th(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await _h(this,e)}async handleLogout(){await Ph(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 Cr(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 q0(this)}async handleLicenseActivate(){await j0(this)}async handleLicenseRemove(){await G0(this)}handleLicenseKeyChange(e){V0(this,e)}async handleAuthStatusCheck(){await W0(this)}async handleAuthStart(){await K0(this)}async handleAuthSubmitCode(e){await z0(this,e)}handleAuthCodeChange(e){H0(this,e)}handleClaudeAuthModalOpen(){this.claudeAuthModalOpen=!0}handleClaudeAuthModalClose(){this.claudeAuthModalOpen=!1,this.authUrl=null,this.authRefreshTokenInput="",this.authRefreshTokenError=null}async handleImportRefreshToken(){await U0(this)}async handleGatewayHealthCheck(){await Q0(this)}async handleGatewayRestart(){await J0(this)}async handleUpdateCheck(){await Cu(this)}async handleUpdateRun(){await Nk(this)}handleUpdateDismissResult(){Uk(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 ae(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>Lr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){ae(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>Lr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await od(this)}async clearAudit(){await Sf(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,rn(this,t),cs(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();ae(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>i0);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.chatSuggestions=[],this.resetChatScroll(),this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity())}ae(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this).then(()=>{sn(this,!0)})})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=ch(this),{loadOlderChatHistory:t}=await ae(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>Oi);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.selectedWorkspace&&this.loadCron(),this.advancedTab==="opening-hours"&&ae(async()=>{const{loadOpeningHours:n}=await Promise.resolve().then(()=>t0);return{loadOpeningHours:n}},void 0,import.meta.url).then(({loadOpeningHours:n})=>{n(this)}),this.advancedTab==="logs"&&(this.logsSubTab==="session"?ae(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>sd);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):ae(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>Bh);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&ae(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>yf);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await P0(this)}async handleChannelConfigReload(){await I0(this)}handleNostrProfileEdit(e,t){L0(this,e,t)}handleNostrProfileCancel(){D0(this)}handleNostrProfileFieldChange(e,t){B0(this,e,t)}async handleNostrProfileSave(){await O0(this)}async handleNostrProfileImport(){await F0(this)}handleNostrProfileToggleAdvanced(){N0(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;ae(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>s0);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 ae(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>ki);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await ae(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>ki);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await ae(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>Ch);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 ae(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>ki);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 ae(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>ki);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){wo(),this.selectedWorkspace&&Wn(this.selectedWorkspace,this.sessionKey,this.chatMessage),this.selectedWorkspace=e,this.publicChatQrDataUrl=null,localStorage.setItem("taskmaster-selected-workspace",e),Tn(e),br(e),this.settings=Ls(),this.chatMessage=Kn(e,this.settings.sessionKey),this.chatAttachments=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.chatRunId=null,this.chatQueue=[],this.lastError=null,this.waConversations=[],this.waSelectedJid=null,this.waMessages=[],this.waGroupInfo=null,this.waLastError=null,this.waSearchQuery="",this.waComposeDraft="",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.chatPageTab==="whatsapp"&&!this.waLoading&&this.waConversations.length===0&&this.reloadWhatsAppConversations()):this.advancedPage&&this.handleAdvancedLoad()}async reloadWhatsAppConversations(){if(!(!this.client||!this.connected)){this.waLoading=!0,this.waLastError=null;try{const e=this.getSelectedWorkspaceInfo(),t=e==null?void 0:e.whatsappAccountId,n=await this.client.request("whatsapp.conversations",{accountId:t});this.waConversations=n.conversations}catch(e){this.waLastError=String(e)}finally{this.waLoading=!1}}}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)}Tn(this.selectedWorkspace),br(this.selectedWorkspace),this.settings=Ls(),this.chatMessage=Kn(this.selectedWorkspace,this.settings.sessionKey),this.reloadCurrentPageData()}render(){return l`${m0(this)}${this.auditModalOpen?v0(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):w}`}};g([m()],f.prototype,"settings",2);g([m()],f.prototype,"password",2);g([m()],f.prototype,"tab",2);g([m()],f.prototype,"onboarding",2);g([m()],f.prototype,"setup",2);g([m()],f.prototype,"filesPage",2);g([m()],f.prototype,"browserPage",2);g([m()],f.prototype,"adminsPage",2);g([m()],f.prototype,"contactsPage",2);g([m()],f.prototype,"chatPage",2);g([m()],f.prototype,"advancedPage",2);g([m()],f.prototype,"advancedTab",2);g([m()],f.prototype,"publicChat",2);g([m()],f.prototype,"publicChatConfig",2);g([m()],f.prototype,"publicChatSessionKey",2);g([m()],f.prototype,"publicChatAuthenticated",2);g([m()],f.prototype,"publicChatAuthStep",2);g([m()],f.prototype,"connected",2);g([m()],f.prototype,"accessState",2);g([m()],f.prototype,"theme",2);g([m()],f.prototype,"themeResolved",2);g([m()],f.prototype,"hello",2);g([m()],f.prototype,"lastError",2);g([m()],f.prototype,"eventLog",2);g([m()],f.prototype,"assistantName",2);g([m()],f.prototype,"assistantAvatar",2);g([m()],f.prototype,"assistantAgentId",2);g([m()],f.prototype,"sessionKey",2);g([m()],f.prototype,"chatLoading",2);g([m()],f.prototype,"chatSending",2);g([m()],f.prototype,"chatMessage",2);g([m()],f.prototype,"chatMessages",2);g([m()],f.prototype,"chatHistoryTotal",2);g([m()],f.prototype,"chatHistoryHasMore",2);g([m()],f.prototype,"chatLoadingOlder",2);g([m()],f.prototype,"chatToolMessages",2);g([m()],f.prototype,"chatStream",2);g([m()],f.prototype,"chatInterimText",2);g([m()],f.prototype,"chatSuggestions",2);g([m()],f.prototype,"chatStreamStartedAt",2);g([m()],f.prototype,"chatRunId",2);g([m()],f.prototype,"compactionStatus",2);g([m()],f.prototype,"chatAvatarUrl",2);g([m()],f.prototype,"chatModelCatalog",2);g([m()],f.prototype,"chatVerboseLevel",2);g([m()],f.prototype,"chatQueue",2);g([m()],f.prototype,"chatAttachments",2);g([m()],f.prototype,"sidebarOpen",2);g([m()],f.prototype,"sidebarContent",2);g([m()],f.prototype,"sidebarError",2);g([m()],f.prototype,"splitRatio",2);g([m()],f.prototype,"nodesLoading",2);g([m()],f.prototype,"nodes",2);g([m()],f.prototype,"devicesLoading",2);g([m()],f.prototype,"devicesError",2);g([m()],f.prototype,"devicesList",2);g([m()],f.prototype,"execApprovalsLoading",2);g([m()],f.prototype,"execApprovalsSaving",2);g([m()],f.prototype,"execApprovalsDirty",2);g([m()],f.prototype,"execApprovalsSnapshot",2);g([m()],f.prototype,"execApprovalsForm",2);g([m()],f.prototype,"execApprovalsSelectedAgent",2);g([m()],f.prototype,"execApprovalsTarget",2);g([m()],f.prototype,"execApprovalsTargetNodeId",2);g([m()],f.prototype,"execApprovalQueue",2);g([m()],f.prototype,"execApprovalBusy",2);g([m()],f.prototype,"execApprovalError",2);g([m()],f.prototype,"configLoading",2);g([m()],f.prototype,"configRaw",2);g([m()],f.prototype,"configRawOriginal",2);g([m()],f.prototype,"configValid",2);g([m()],f.prototype,"configIssues",2);g([m()],f.prototype,"configSaving",2);g([m()],f.prototype,"configApplying",2);g([m()],f.prototype,"updateRunning",2);g([m()],f.prototype,"applySessionKey",2);g([m()],f.prototype,"configSnapshot",2);g([m()],f.prototype,"configSchema",2);g([m()],f.prototype,"configSchemaVersion",2);g([m()],f.prototype,"configSchemaLoading",2);g([m()],f.prototype,"configUiHints",2);g([m()],f.prototype,"configForm",2);g([m()],f.prototype,"configFormOriginal",2);g([m()],f.prototype,"configFormDirty",2);g([m()],f.prototype,"configFormMode",2);g([m()],f.prototype,"configSearchQuery",2);g([m()],f.prototype,"configActiveSection",2);g([m()],f.prototype,"configActiveSubsection",2);g([m()],f.prototype,"channelsLoading",2);g([m()],f.prototype,"channelsSnapshot",2);g([m()],f.prototype,"channelsError",2);g([m()],f.prototype,"channelsLastSuccess",2);g([m()],f.prototype,"whatsappLoginMessage",2);g([m()],f.prototype,"whatsappLoginQrDataUrl",2);g([m()],f.prototype,"whatsappLoginConnected",2);g([m()],f.prototype,"whatsappBusy",2);g([m()],f.prototype,"whatsappActiveQrAccountId",2);g([m()],f.prototype,"whatsappPairedPhone",2);g([m()],f.prototype,"addingWhatsAppAccount",2);g([m()],f.prototype,"newWhatsAppAccountName",2);g([m()],f.prototype,"whatsappAccountError",2);g([m()],f.prototype,"whatsappAccountSaving",2);g([m()],f.prototype,"whatsappSettingsOpen",2);g([m()],f.prototype,"publicChatToggleBusy",2);g([m()],f.prototype,"publicChatGreetingBusy",2);g([m()],f.prototype,"publicChatEmailBusy",2);g([m()],f.prototype,"publicChatSettingsOpen",2);g([m()],f.prototype,"publicChatWidgetModalOpen",2);g([m()],f.prototype,"brandingBusy",2);g([m()],f.prototype,"agentSettingsOpen",2);g([m()],f.prototype,"brandingExpanded",2);g([m()],f.prototype,"tailscaleStatus",2);g([m()],f.prototype,"tailscaleBusy",2);g([m()],f.prototype,"tailscaleAuthUrl",2);g([m()],f.prototype,"tailscaleError",2);g([m()],f.prototype,"tailscaleServeEnableUrl",2);g([m()],f.prototype,"tailscaleFunnelEnableUrl",2);g([m()],f.prototype,"tailscaleDisableConfirm",2);g([m()],f.prototype,"tailscaleConnectProgress",2);g([m()],f.prototype,"tailscaleConnectMessage",2);g([m()],f.prototype,"tailscaleConnectSuccess",2);g([m()],f.prototype,"wifiStatus",2);g([m()],f.prototype,"wifiNetworks",2);g([m()],f.prototype,"wifiBusy",2);g([m()],f.prototype,"wifiError",2);g([m()],f.prototype,"wifiPassword",2);g([m()],f.prototype,"wifiSelectedSsid",2);g([m()],f.prototype,"networkPort",2);g([m()],f.prototype,"networkHostname",2);g([m()],f.prototype,"networkPortInput",2);g([m()],f.prototype,"networkHostnameInput",2);g([m()],f.prototype,"networkModalOpen",2);g([m()],f.prototype,"networkBusy",2);g([m()],f.prototype,"networkError",2);g([m()],f.prototype,"networkSuccess",2);g([m()],f.prototype,"wifiModalOpen",2);g([m()],f.prototype,"licenseKey",2);g([m()],f.prototype,"licenseBusy",2);g([m()],f.prototype,"licenseValid",2);g([m()],f.prototype,"licenseMessage",2);g([m()],f.prototype,"licenseTier",2);g([m()],f.prototype,"licenseDeviceId",2);g([m()],f.prototype,"licenseStoredKey",2);g([m()],f.prototype,"licenseRemoveConfirm",2);g([m()],f.prototype,"authConnected",2);g([m()],f.prototype,"authBusy",2);g([m()],f.prototype,"authMessage",2);g([m()],f.prototype,"authUrl",2);g([m()],f.prototype,"authCodeInput",2);g([m()],f.prototype,"authExpiresIn",2);g([m()],f.prototype,"authRefreshToken",2);g([m()],f.prototype,"claudeAuthModalOpen",2);g([m()],f.prototype,"authRefreshTokenInput",2);g([m()],f.prototype,"authRefreshTokenBusy",2);g([m()],f.prototype,"authRefreshTokenError",2);g([m()],f.prototype,"setupStep",2);g([m()],f.prototype,"gatewayHealthy",2);g([m()],f.prototype,"gatewayHealthLoading",2);g([m()],f.prototype,"gatewayHealthMessage",2);g([m()],f.prototype,"gatewayRestartBusy",2);g([m()],f.prototype,"updateAvailable",2);g([m()],f.prototype,"currentVersion",2);g([m()],f.prototype,"latestVersion",2);g([m()],f.prototype,"updateChecking",2);g([m()],f.prototype,"updateMessage",2);g([m()],f.prototype,"updateProgressSteps",2);g([m()],f.prototype,"updateLastResult",2);g([m()],f.prototype,"uninstallConfirm",2);g([m()],f.prototype,"uninstallBusy",2);g([m()],f.prototype,"uninstallDone",2);g([m()],f.prototype,"uninstallError",2);g([m()],f.prototype,"uninstallConfirmText",2);g([m()],f.prototype,"nostrProfileFormState",2);g([m()],f.prototype,"nostrProfileAccountId",2);g([m()],f.prototype,"presenceLoading",2);g([m()],f.prototype,"presenceEntries",2);g([m()],f.prototype,"presenceError",2);g([m()],f.prototype,"presenceStatus",2);g([m()],f.prototype,"agentsLoading",2);g([m()],f.prototype,"agentsList",2);g([m()],f.prototype,"agentsError",2);g([m()],f.prototype,"sessionsLoading",2);g([m()],f.prototype,"sessionsResult",2);g([m()],f.prototype,"sessionsError",2);g([m()],f.prototype,"cronLoading",2);g([m()],f.prototype,"cronJobs",2);g([m()],f.prototype,"cronStatus",2);g([m()],f.prototype,"cronError",2);g([m()],f.prototype,"cronForm",2);g([m()],f.prototype,"cronRunsJobId",2);g([m()],f.prototype,"cronRuns",2);g([m()],f.prototype,"cronBusy",2);g([m()],f.prototype,"cronNewEventModal",2);g([m()],f.prototype,"cronDetailJobId",2);g([m()],f.prototype,"cronEditJobId",2);g([m()],f.prototype,"cronPendingDeleteId",2);g([m()],f.prototype,"cronRunModalJobId",2);g([m()],f.prototype,"cronRunModalJobName",2);g([m()],f.prototype,"cronRunResult",2);g([m()],f.prototype,"openingHoursLoading",2);g([m()],f.prototype,"openingHoursError",2);g([m()],f.prototype,"openingHoursBusy",2);g([m()],f.prototype,"openingHoursForm",2);g([m()],f.prototype,"browserScreencastActive",2);g([m()],f.prototype,"browserScreencastFrame",2);g([m()],f.prototype,"browserScreencastMetadata",2);g([m()],f.prototype,"browserHandoffPending",2);g([m()],f.prototype,"browserHandoffReason",2);g([m()],f.prototype,"browserHandoffId",2);g([m()],f.prototype,"browserInputMode",2);g([m()],f.prototype,"browserFullscreen",2);g([m()],f.prototype,"browserLoading",2);g([m()],f.prototype,"browserError",2);g([m()],f.prototype,"filesLoading",2);g([m()],f.prototype,"filesTree",2);g([m()],f.prototype,"filesRoot",2);g([m()],f.prototype,"filesError",2);g([m()],f.prototype,"filesSelectedPath",2);g([m()],f.prototype,"filesSelectedPaths",2);g([m()],f.prototype,"filesPreviewContent",2);g([m()],f.prototype,"filesPreviewLoading",2);g([m()],f.prototype,"filesPreviewBinary",2);g([m()],f.prototype,"filesPreviewSize",2);g([m()],f.prototype,"filesExpandedDirs",2);g([m()],f.prototype,"filesCurrentDir",2);g([m()],f.prototype,"filesPendingDeletePath",2);g([m()],f.prototype,"filesMessage",2);g([m()],f.prototype,"filesUploadBusy",2);g([m()],f.prototype,"filesReindexBusy",2);g([m()],f.prototype,"filesMemoryStatus",2);g([m()],f.prototype,"embeddingDownloading",2);g([m()],f.prototype,"filesSearchQuery",2);g([m()],f.prototype,"filesSearchResults",2);g([m()],f.prototype,"filesSearchLoading",2);g([m()],f.prototype,"filesSearchAgentId",2);g([m()],f.prototype,"auditEntries",2);g([m()],f.prototype,"auditLoading",2);g([m()],f.prototype,"auditModalOpen",2);g([m()],f.prototype,"skillsLoading",2);g([m()],f.prototype,"skillsReport",2);g([m()],f.prototype,"skillsError",2);g([m()],f.prototype,"skillsFilter",2);g([m()],f.prototype,"skillsTypeFilter",2);g([m()],f.prototype,"skillEdits",2);g([m()],f.prototype,"skillsBusyKey",2);g([m()],f.prototype,"skillMessages",2);g([m()],f.prototype,"skillDetail",2);g([m()],f.prototype,"skillDetailTab",2);g([m()],f.prototype,"skillAddModal",2);g([m()],f.prototype,"skillAddForm",2);g([m()],f.prototype,"skillAddFormSource",2);g([m()],f.prototype,"skillEditTab",2);g([m()],f.prototype,"skillDrafts",2);g([m()],f.prototype,"adminsLoading",2);g([m()],f.prototype,"adminPhones",2);g([m()],f.prototype,"adminsError",2);g([m()],f.prototype,"adminsSaving",2);g([m()],f.prototype,"adminsNewPhone",2);g([m()],f.prototype,"contactsLoading",2);g([m()],f.prototype,"contactsSaving",2);g([m()],f.prototype,"contactsRecords",2);g([m()],f.prototype,"contactsError",2);g([m()],f.prototype,"contactsSearchQuery",2);g([m()],f.prototype,"contactsEditingId",2);g([m()],f.prototype,"contactsShowAddForm",2);g([m()],f.prototype,"contactsNewPhone",2);g([m()],f.prototype,"contactsNewName",2);g([m()],f.prototype,"contactsDeleteConfirmId",2);g([m()],f.prototype,"contactsAddFieldForId",2);g([m()],f.prototype,"contactsAddFieldKey",2);g([m()],f.prototype,"contactsAddFieldValue",2);g([m()],f.prototype,"imessageEnableConfirm",2);g([m()],f.prototype,"imessageEnabling",2);g([m()],f.prototype,"chatPageTab",2);g([m()],f.prototype,"waConversations",2);g([m()],f.prototype,"waSelectedJid",2);g([m()],f.prototype,"waMessages",2);g([m()],f.prototype,"waGroupInfo",2);g([m()],f.prototype,"waLoading",2);g([m()],f.prototype,"waMessagesLoading",2);g([m()],f.prototype,"waSearchQuery",2);g([m()],f.prototype,"waComposeDraft",2);g([m()],f.prototype,"waSending",2);g([m()],f.prototype,"waLastError",2);g([m()],f.prototype,"infoModalOpen",2);g([m()],f.prototype,"remoteAccessQrDataUrl",2);g([m()],f.prototype,"publicChatQrDataUrl",2);g([m()],f.prototype,"workspaces",2);g([m()],f.prototype,"workspacesLoading",2);g([m()],f.prototype,"workspacesError",2);g([m()],f.prototype,"selectedWorkspace",2);g([m()],f.prototype,"addingWorkspace",2);g([m()],f.prototype,"newWorkspaceName",2);g([m()],f.prototype,"newWorkspacePath",2);g([m()],f.prototype,"newWorkspacePin",2);g([m()],f.prototype,"accountPinModalOpen",2);g([m()],f.prototype,"accountPinBusy",2);g([m()],f.prototype,"accountPinError",2);g([m()],f.prototype,"accountPinSuccess",2);g([m()],f.prototype,"apiKeyProviders",2);g([m()],f.prototype,"apiKeyModalOpen",2);g([m()],f.prototype,"apiKeyBusy",2);g([m()],f.prototype,"apiKeyError",2);g([m()],f.prototype,"apiKeySuccess",2);g([m()],f.prototype,"apiKeySavingProvider",2);g([m()],f.prototype,"authApiKeyMode",2);g([m()],f.prototype,"authApiKeyInput",2);g([m()],f.prototype,"authApiKeyBusy",2);g([m()],f.prototype,"authApiKeyError",2);g([m()],f.prototype,"pinChanging",2);g([m()],f.prototype,"pinChangeBusy",2);g([m()],f.prototype,"pinChangeError",2);g([m()],f.prototype,"loginChangePinMode",2);g([m()],f.prototype,"changePinBusy",2);g([m()],f.prototype,"changePinError",2);g([m()],f.prototype,"changePinSuccess",2);g([m()],f.prototype,"workspaceSaving",2);g([m()],f.prototype,"workspaceRemoveConfirm",2);g([m()],f.prototype,"renamingWorkspace",2);g([m()],f.prototype,"renameWorkspaceName",2);g([m()],f.prototype,"debugLoading",2);g([m()],f.prototype,"debugStatus",2);g([m()],f.prototype,"debugHealth",2);g([m()],f.prototype,"debugModels",2);g([m()],f.prototype,"debugHeartbeat",2);g([m()],f.prototype,"debugCallMethod",2);g([m()],f.prototype,"debugCallParams",2);g([m()],f.prototype,"debugCallResult",2);g([m()],f.prototype,"debugCallError",2);g([m()],f.prototype,"logsLoading",2);g([m()],f.prototype,"logsError",2);g([m()],f.prototype,"logsFile",2);g([m()],f.prototype,"logsEntries",2);g([m()],f.prototype,"logsFilterText",2);g([m()],f.prototype,"logsLevelFilters",2);g([m()],f.prototype,"logsAutoFollow",2);g([m()],f.prototype,"logsTruncated",2);g([m()],f.prototype,"logsCursor",2);g([m()],f.prototype,"logsLastFetchAt",2);g([m()],f.prototype,"logsLimit",2);g([m()],f.prototype,"logsMaxBytes",2);g([m()],f.prototype,"logsAtBottom",2);g([m()],f.prototype,"logsSubTab",2);g([m()],f.prototype,"logsChipsExpanded",2);g([m()],f.prototype,"sessionLogsLoading",2);g([m()],f.prototype,"sessionLogsError",2);g([m()],f.prototype,"sessionLogsEntries",2);g([m()],f.prototype,"sessionLogsFilterText",2);g([m()],f.prototype,"sessionLogsTypeFilters",2);g([m()],f.prototype,"sessionLogsAgentFilters",2);g([m()],f.prototype,"sessionLogsAgents",2);g([m()],f.prototype,"sessionLogsAutoFollow",2);g([m()],f.prototype,"sessionLogsChipsExpanded",2);g([m()],f.prototype,"sessionLogsCursors",2);g([m()],f.prototype,"sessionLogsLastFetchAt",2);g([m()],f.prototype,"sessionLogsAtBottom",2);g([m()],f.prototype,"chatUserNearBottom",2);f=g([ql("taskmaster-app")],f);
4886
- //# sourceMappingURL=index-DbeiXb7c.js.map
4891
+ //# sourceMappingURL=index-fP8Y5Vwq.js.map