@rubytech/taskmaster 1.29.1 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,23 @@
1
- var Vu=Object.defineProperty;var Qu=(e,t,n)=>t in e?Vu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var q=(e,t,n)=>Qu(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 Ju="modulepreload",Yu=function(e,t){return new URL(e,t).href},rr={},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]"),l=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));s=d(n.map(h=>{if(h=Yu(h,i),h in rr)return;rr[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 y=document.createElement("link");if(y.rel=u?"stylesheet":Ju,u||(y.as="script"),y.crossOrigin="",y.href=h,l&&y.setAttribute("nonce",l),document.head.appendChild(y),u)return new Promise(($,S)=>{y.addEventListener("load",$),y.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,Yo=Si.ShadowRoot&&(Si.ShadyCSS===void 0||Si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Xo=Symbol(),lr=new WeakMap;let Fl=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==Xo)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(Yo&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=lr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&lr.set(n,t))}return t}toString(){return this.cssText}};const Xu=e=>new Fl(typeof e=="string"?e:e+"",void 0,Xo),Zu=(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 Fl(n,e,Xo)},ep=(e,t)=>{if(Yo)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)}},cr=Yo?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Xu(n)})(e):e;const{is:tp,defineProperty:np,getOwnPropertyDescriptor:ip,getOwnPropertyNames:sp,getOwnPropertySymbols:op,getPrototypeOf:ap}=Object,ot=globalThis,dr=ot.trustedTypes,rp=dr?dr.emptyScript:"",Rs=ot.reactiveElementPolyfillSupport,Cn=(e,t)=>e,Ri={toAttribute(e,t){switch(t){case Boolean:e=e?rp: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}},Zo=(e,t)=>!tp(e,t),ur={attribute:!0,type:String,converter:Ri,reflect:!1,useDefault:!1,hasChanged:Zo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ot.litPropertyMetadata??(ot.litPropertyMetadata=new WeakMap);let Ht=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=ur){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&&np(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=ip(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)??ur}static _$Ei(){if(this.hasOwnProperty(Cn("elementProperties")))return;const t=ap(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=[...sp(n),...op(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(cr(s))}else t!==void 0&&n.push(cr(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 ep(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),l=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=l.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??Zo)(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,l=this[o];r!==!0||this._$AL.has(o)||l===void 0||this.C(o,void 0,a,l)}}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){}};Ht.elementStyles=[],Ht.shadowRootOptions={mode:"open"},Ht[Cn("elementProperties")]=new Map,Ht[Cn("finalized")]=new Map,Rs==null||Rs({ReactiveElement:Ht}),(ot.reactiveElementVersions??(ot.reactiveElementVersions=[])).push("2.1.2");const En=globalThis,pr=e=>e,Li=En.trustedTypes,hr=Li?Li.createPolicy("lit-html",{createHTML:e=>e}):void 0,Ul="$lit$",st=`lit$${Math.random().toFixed(9).slice(2)}$`,Wl="?"+st,lp=`<${Wl}>`,At=document,Fn=()=>At.createComment(""),Un=e=>e===null||typeof e!="object"&&typeof e!="function",ea=Array.isArray,cp=e=>ea(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ls=`[
1
+ var Qu=Object.defineProperty;var Ju=(e,t,n)=>t in e?Qu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var z=(e,t,n)=>Ju(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 Yu="modulepreload",Xu=function(e,t){return new URL(e,t).href},rr={},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]"),l=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));s=d(n.map(h=>{if(h=Xu(h,i),h in rr)return;rr[h]=!0;const u=h.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(i)for(let x=a.length-1;x>=0;x--){const S=a[x];if(S.href===h&&(!u||S.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${p}`))return;const y=document.createElement("link");if(y.rel=u?"stylesheet":Yu,u||(y.as="script"),y.crossOrigin="",y.href=h,l&&y.setAttribute("nonce",l),document.head.appendChild(y),u)return new Promise((x,S)=>{y.addEventListener("load",x),y.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,Yo=Si.ShadowRoot&&(Si.ShadyCSS===void 0||Si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Xo=Symbol(),lr=new WeakMap;let Fl=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==Xo)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(Yo&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=lr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&lr.set(n,t))}return t}toString(){return this.cssText}};const Zu=e=>new Fl(typeof e=="string"?e:e+"",void 0,Xo),ep=(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 Fl(n,e,Xo)},tp=(e,t)=>{if(Yo)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)}},cr=Yo?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Zu(n)})(e):e;const{is:np,defineProperty:ip,getOwnPropertyDescriptor:sp,getOwnPropertyNames:op,getOwnPropertySymbols:ap,getPrototypeOf:rp}=Object,it=globalThis,dr=it.trustedTypes,lp=dr?dr.emptyScript:"",Rs=it.reactiveElementPolyfillSupport,Cn=(e,t)=>e,Ri={toAttribute(e,t){switch(t){case Boolean:e=e?lp: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}},Zo=(e,t)=>!np(e,t),ur={attribute:!0,type:String,converter:Ri,reflect:!1,useDefault:!1,hasChanged:Zo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),it.litPropertyMetadata??(it.litPropertyMetadata=new WeakMap);let Ht=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=ur){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&&ip(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=sp(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)??ur}static _$Ei(){if(this.hasOwnProperty(Cn("elementProperties")))return;const t=rp(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=[...op(n),...ap(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(cr(s))}else t!==void 0&&n.push(cr(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 tp(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),l=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=l.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??Zo)(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,l=this[o];r!==!0||this._$AL.has(o)||l===void 0||this.C(o,void 0,a,l)}}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){}};Ht.elementStyles=[],Ht.shadowRootOptions={mode:"open"},Ht[Cn("elementProperties")]=new Map,Ht[Cn("finalized")]=new Map,Rs==null||Rs({ReactiveElement:Ht}),(it.reactiveElementVersions??(it.reactiveElementVersions=[])).push("2.1.2");const En=globalThis,pr=e=>e,Li=En.trustedTypes,hr=Li?Li.createPolicy("lit-html",{createHTML:e=>e}):void 0,Ul="$lit$",nt=`lit$${Math.random().toFixed(9).slice(2)}$`,Wl="?"+nt,cp=`<${Wl}>`,At=document,Fn=()=>At.createComment(""),Un=e=>e===null||typeof e!="object"&&typeof e!="function",ea=Array.isArray,dp=e=>ea(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ls=`[
2
2
  \f\r]`,hn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,fr=/-->/g,gr=/>/g,pt=RegExp(`>|${Ls}(?:([^\\s"'>=/]+)(${Ls}*=${Ls}*(?:[^
3
- \f\r"'\`<>=]|("|')|))|$)`,"g"),mr=/'/g,yr=/"/g,zl=/^(?:script|style|textarea|title)$/i,dp=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),c=dp(1),rt=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),vr=new WeakMap,yt=At.createTreeWalker(At,129);function Kl(e,t){if(!ea(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return hr!==void 0?hr.createHTML(t):t}const up=(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 l=e[r];let d,h,u=-1,p=0;for(;p<l.length&&(a.lastIndex=p,h=a.exec(l),h!==null);)p=a.lastIndex,a===hn?h[1]==="!--"?a=fr:h[1]!==void 0?a=gr:h[2]!==void 0?(zl.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]==='"'?yr:mr):a===yr||a===mr?a=pt:a===fr||a===gr?a=hn:(a=pt,s=void 0);const y=a===pt&&e[r+1].startsWith("/>")?" ":"";o+=a===hn?l+lp:u>=0?(i.push(d),l.slice(0,u)+Ul+l.slice(u)+st+y):l+st+(u===-2?r:y)}return[Kl(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let ko=class Hl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,l=this.parts,[d,h]=up(t,n);if(this.el=Hl.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&&l.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Ul)){const p=h[a++],y=s.getAttribute(u).split(st),$=/([.?@])?(.*)/.exec(p);l.push({type:1,index:o,name:$[2],strings:y,ctor:$[1]==="."?hp:$[1]==="?"?fp:$[1]==="@"?gp:os}),s.removeAttribute(u)}else u.startsWith(st)&&(l.push({type:6,index:o}),s.removeAttribute(u));if(zl.test(s.tagName)){const u=s.textContent.split(st),p=u.length-1;if(p>0){s.textContent=Li?Li.emptyScript:"";for(let y=0;y<p;y++)s.append(u[y],Fn()),yt.nextNode(),l.push({type:2,index:++o});s.append(u[p],Fn())}}}else if(s.nodeType===8)if(s.data===Wl)l.push({type:2,index:o});else{let u=-1;for(;(u=s.data.indexOf(st,u+1))!==-1;)l.push({type:7,index:o}),u+=st.length-1}o++}}static createElement(t,n){const i=At.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 pp{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)??At).importNode(n,!0);yt.currentNode=s;let o=yt.nextNode(),a=0,r=0,l=i[0];for(;l!==void 0;){if(a===l.index){let d;l.type===2?d=new ss(o,o.nextSibling,this,t):l.type===1?d=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(d=new mp(o,this,t)),this._$AV.push(d),l=i[++r]}a!==(l==null?void 0:l.index)&&(o=yt.nextNode(),a++)}return yt.currentNode=At,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 ss=class ql{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):cp(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(At.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=ko.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 pp(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=vr.get(t.strings);return n===void 0&&vr.set(t.strings,n=new ko(t)),n}k(t){ea(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 ql(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=pr(t).nextSibling;pr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class os{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 l,d;for(t=o[0],l=0;l<o.length-1;l++)d=Qt(this,r[i+l],n,l),d===rt&&(d=this._$AH[l]),a||(a=!Un(d)||d!==this._$AH[l]),d===w?t=w:t!==w&&(t+=(d??"")+o[l+1]),this._$AH[l]=d}a&&!s&&this.j(t)}j(t){t===w?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let hp=class extends os{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},fp=class extends os{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},gp=class extends os{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)}},mp=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 yp={I:ss},Ds=En.litHtmlPolyfillSupport;Ds==null||Ds(ko,ss),(En.litHtmlVersions??(En.litHtmlVersions=[])).push("3.3.2");const vp=(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 ss(t.insertBefore(Fn(),o),o,void 0,n??{})}return s._$AI(e),s};const xt=globalThis;let Gt=class extends Ht{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=vp(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 Ol;Gt._$litElement$=!0,Gt.finalized=!0,(Ol=xt.litElementHydrateSupport)==null||Ol.call(xt,{LitElement:Gt});const Bs=xt.litElementPolyfillSupport;Bs==null||Bs({LitElement:Gt});(xt.litElementVersions??(xt.litElementVersions=[])).push("4.2.2");const jl=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const bp={attribute:!0,type:String,converter:Ri,reflect:!1,hasChanged:Zo},wp=(e=bp,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 l=t.get.call(this);t.set.call(this,r),this.requestUpdate(a,l,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 l=this[a];t.call(this,r),this.requestUpdate(a,l,e,!0,r)}}throw Error("Unsupported decorator location: "+i)};function as(e){return(t,n)=>typeof n=="object"?wp(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 as({...e,state:!0,attribute:!1})}const kp=50,xp=200,$p="Assistant";function br(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function xo(e){const t=br(e==null?void 0:e.name,kp)??$p,n=br((e==null?void 0:e.avatar)??void 0,xp)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function Sp(){return xo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const Ap="Taskmaster",Cp="/taskmaster-icon.png",Ep="#00d4ff",Tp="";let ai=null;function Xe(){return ai||(ai={name:window.__TASKMASTER_BRAND_NAME__||Ap,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||Cp,accentColor:window.__TASKMASTER_ACCENT_COLOR__||Ep,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||Tp},ai)}function Fe(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function Gl(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 _p(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 Vl(e){const t=Gl(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=_p(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),l=o(3,3);return`#${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}const fn={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function Ql(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=Gl(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=Fe(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;Vl(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;Ql(o)}const Di="taskmaster.control.settings.v1",Jl="taskmaster.account.settings.";function _n(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const zt={gatewayUrl:_n(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},nt={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function Mp(){try{const e=localStorage.getItem(Di);if(!e)return{...zt,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:zt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:zt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:zt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:zt.navGroupsCollapsed}}catch{return{...zt,gatewayUrl:_n()}}}function Pp(e){if(!e)return{...nt};try{const t=localStorage.getItem(Jl+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 wr(e){Bi=e}function Ns(){return{...Mp(),...Pp(Bi)}}function Ip(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(Jl+Bi,JSON.stringify(n))}}const Rp="taskmaster.draft.";function ta(e,t){return Rp+e+"."+t}function Wn(e,t,n){try{const i=ta(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function zn(e,t){try{return localStorage.getItem(ta(e,t))??""}catch{return""}}function Lp(e,t){try{localStorage.removeItem(ta(e,t))}catch{}}let vt=null,Ce=null;function kr(e,t,n){Ce={workspace:e,sessionKey:t,text:n},vt!=null&&clearTimeout(vt),vt=setTimeout(()=>{Ce&&Wn(Ce.workspace,Ce.sessionKey,Ce.text),Ce=null,vt=null},300)}function $o(){vt!=null&&clearTimeout(vt),vt=null,Ce&&(Wn(Ce.workspace,Ce.sessionKey,Ce.text),Ce=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 Yl(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 Dp=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,li=/<\s*\/?\s*final\b[^>]*>/gi,xr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function Bp(e,t){return e.trimStart()}function Np(e,t){if(!e||!Dp.test(e))return e;let n=e;li.test(n)?(li.lastIndex=0,n=n.replace(li,"")):li.lastIndex=0,xr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(xr)){const r=a.index??0,l=a[1]==="/";o?l&&(o=!1):(i+=n.slice(s,r),l||(o=!0)),s=r+a[0].length}return i+=n.slice(s),Bp(i)}function Xl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function rs(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 l=Math.round(r/60);if(l<60)return`in ${l}m`;const d=Math.round(l/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 na(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 Op(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Zl(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 Os(e){return Np(e)}const Fp=/^\[([^\]]+)\]\s*/,Up=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Fs=new WeakMap,Us=new WeakMap;function Wp(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:Up.some(t=>e.startsWith(`${t} `))}function Ws(e){const t=e.match(Fp);if(!t)return e;const n=t[1]??"";return Wp(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"?Os(i):Ws(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(`
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),mr=/'/g,yr=/"/g,zl=/^(?:script|style|textarea|title)$/i,up=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),c=up(1),ot=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),vr=new WeakMap,yt=At.createTreeWalker(At,129);function Kl(e,t){if(!ea(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return hr!==void 0?hr.createHTML(t):t}const pp=(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 l=e[r];let d,h,u=-1,p=0;for(;p<l.length&&(a.lastIndex=p,h=a.exec(l),h!==null);)p=a.lastIndex,a===hn?h[1]==="!--"?a=fr:h[1]!==void 0?a=gr:h[2]!==void 0?(zl.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]==='"'?yr:mr):a===yr||a===mr?a=pt:a===fr||a===gr?a=hn:(a=pt,s=void 0);const y=a===pt&&e[r+1].startsWith("/>")?" ":"";o+=a===hn?l+cp:u>=0?(i.push(d),l.slice(0,u)+Ul+l.slice(u)+nt+y):l+nt+(u===-2?r:y)}return[Kl(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let ko=class Hl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,l=this.parts,[d,h]=pp(t,n);if(this.el=Hl.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&&l.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Ul)){const p=h[a++],y=s.getAttribute(u).split(nt),x=/([.?@])?(.*)/.exec(p);l.push({type:1,index:o,name:x[2],strings:y,ctor:x[1]==="."?fp:x[1]==="?"?gp:x[1]==="@"?mp:os}),s.removeAttribute(u)}else u.startsWith(nt)&&(l.push({type:6,index:o}),s.removeAttribute(u));if(zl.test(s.tagName)){const u=s.textContent.split(nt),p=u.length-1;if(p>0){s.textContent=Li?Li.emptyScript:"";for(let y=0;y<p;y++)s.append(u[y],Fn()),yt.nextNode(),l.push({type:2,index:++o});s.append(u[p],Fn())}}}else if(s.nodeType===8)if(s.data===Wl)l.push({type:2,index:o});else{let u=-1;for(;(u=s.data.indexOf(nt,u+1))!==-1;)l.push({type:7,index:o}),u+=nt.length-1}o++}}static createElement(t,n){const i=At.createElement("template");return i.innerHTML=t,i}};function Qt(e,t,n=e,i){var a,r;if(t===ot)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 hp{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)??At).importNode(n,!0);yt.currentNode=s;let o=yt.nextNode(),a=0,r=0,l=i[0];for(;l!==void 0;){if(a===l.index){let d;l.type===2?d=new ss(o,o.nextSibling,this,t):l.type===1?d=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(d=new yp(o,this,t)),this._$AV.push(d),l=i[++r]}a!==(l==null?void 0:l.index)&&(o=yt.nextNode(),a++)}return yt.currentNode=At,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 ss=class ql{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!==ot&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):dp(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(At.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=ko.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 hp(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=vr.get(t.strings);return n===void 0&&vr.set(t.strings,n=new ko(t)),n}k(t){ea(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 ql(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=pr(t).nextSibling;pr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class os{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!==ot,a&&(this._$AH=t);else{const r=t;let l,d;for(t=o[0],l=0;l<o.length-1;l++)d=Qt(this,r[i+l],n,l),d===ot&&(d=this._$AH[l]),a||(a=!Un(d)||d!==this._$AH[l]),d===w?t=w:t!==w&&(t+=(d??"")+o[l+1]),this._$AH[l]=d}a&&!s&&this.j(t)}j(t){t===w?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let fp=class extends os{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},gp=class extends os{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},mp=class extends os{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)===ot)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)}},yp=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 vp={I:ss},Ds=En.litHtmlPolyfillSupport;Ds==null||Ds(ko,ss),(En.litHtmlVersions??(En.litHtmlVersions=[])).push("3.3.2");const bp=(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 ss(t.insertBefore(Fn(),o),o,void 0,n??{})}return s._$AI(e),s};const xt=globalThis;let Vt=class extends Ht{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=bp(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 ot}};var Ol;Vt._$litElement$=!0,Vt.finalized=!0,(Ol=xt.litElementHydrateSupport)==null||Ol.call(xt,{LitElement:Vt});const Bs=xt.litElementPolyfillSupport;Bs==null||Bs({LitElement:Vt});(xt.litElementVersions??(xt.litElementVersions=[])).push("4.2.2");const jl=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const wp={attribute:!0,type:String,converter:Ri,reflect:!1,hasChanged:Zo},kp=(e=wp,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 l=t.get.call(this);t.set.call(this,r),this.requestUpdate(a,l,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 l=this[a];t.call(this,r),this.requestUpdate(a,l,e,!0,r)}}throw Error("Unsupported decorator location: "+i)};function as(e){return(t,n)=>typeof n=="object"?kp(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 as({...e,state:!0,attribute:!1})}const xp=50,$p=200,Sp="Assistant";function br(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function xo(e){const t=br(e==null?void 0:e.name,xp)??Sp,n=br((e==null?void 0:e.avatar)??void 0,$p)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function Ap(){return xo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const Cp="Taskmaster",Ep="/taskmaster-icon.png",Tp="#00d4ff",_p="";let ai=null;function Qe(){return ai||(ai={name:window.__TASKMASTER_BRAND_NAME__||Cp,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||Ep,accentColor:window.__TASKMASTER_ACCENT_COLOR__||Tp,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||_p},ai)}function Be(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function Vl(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 Mp(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=Vl(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=Mp(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),l=o(3,3);return`#${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}const fn={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function Ql(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=Vl(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=Qe(),n=Be(),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;Ql(o)}const Di="taskmaster.control.settings.v1",Jl="taskmaster.account.settings.";function _n(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const zt={gatewayUrl:_n(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},et={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function Pp(){try{const e=localStorage.getItem(Di);if(!e)return{...zt,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:zt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:zt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:zt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:zt.navGroupsCollapsed}}catch{return{...zt,gatewayUrl:_n()}}}function Ip(e){if(!e)return{...et};try{const t=localStorage.getItem(Jl+e);if(!t)return{...et};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():et.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||et.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:et.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:et.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:et.splitRatio}}catch{return{...et}}}let Bi=null;function wr(e){Bi=e}function Ns(){return{...Pp(),...Ip(Bi)}}function Rp(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(Jl+Bi,JSON.stringify(n))}}const Lp="taskmaster.draft.";function ta(e,t){return Lp+e+"."+t}function Wn(e,t,n){try{const i=ta(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function zn(e,t){try{return localStorage.getItem(ta(e,t))??""}catch{return""}}function Dp(e,t){try{localStorage.removeItem(ta(e,t))}catch{}}let vt=null,Se=null;function kr(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 $o(){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 Yl(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 Bp=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,li=/<\s*\/?\s*final\b[^>]*>/gi,xr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function Np(e,t){return e.trimStart()}function Op(e,t){if(!e||!Bp.test(e))return e;let n=e;li.test(n)?(li.lastIndex=0,n=n.replace(li,"")):li.lastIndex=0,xr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(xr)){const r=a.index??0,l=a[1]==="/";o?l&&(o=!1):(i+=n.slice(s,r),l||(o=!0)),s=r+a[0].length}return i+=n.slice(s),Np(i)}function Xl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function rs(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 l=Math.round(r/60);if(l<60)return`in ${l}m`;const d=Math.round(l/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 na(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 Fp(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Zl(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 Os(e){return Op(e)}const Up=/^\[([^\]]+)\]\s*/,Wp=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Fs=new WeakMap,Us=new WeakMap;function zp(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:Wp.some(t=>e.startsWith(`${t} `))}function Ws(e){const t=e.match(Up);if(!t)return e;const n=t[1]??"";return zp(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"?Os(i):Ws(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
4
  `);return n==="assistant"?Os(o):Ws(o)}}return typeof t.text=="string"?n==="assistant"?Os(t.text):Ws(t.text):null}function ec(e){if(!e||typeof e!="object")return Mn(e);const t=e;if(Fs.has(t))return Fs.get(t)??null;const n=Mn(e);return Fs.set(t,n),n}function $r(e){const n=e.content,i=[];if(Array.isArray(n))for(const r of n){const l=r;if(l.type==="thinking"&&typeof l.thinking=="string"){const d=l.thinking.trim();d&&i.push(d)}}if(i.length>0)return i.join(`
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
- `):null}function zp(e){if(!e||typeof e!="object")return $r(e);const t=e;if(Us.has(t))return Us.get(t)??null;const n=$r(e);return Us.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
- `)}return typeof t.text=="string"?t.text:null}function Hp(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 qp=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,jp=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,Gp=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Vp=/^A new session was started via \/new or \/reset\./;function Qp(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"&&qp.test(s)||n==="assistant"&&jp.test(s)||n==="user"&&Vp.test(s)||n==="assistant"&&Gp.test(s)):!1}function tc(e){return e.filter(t=>!Qp(t))}function nc(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 y=String(u.type??"").toLowerCase();return y==="toolresult"||y==="tool_result"}),r=typeof t.toolName=="string"||typeof t.tool_name=="string";(i||a||r)&&(n="toolResult");let l=[];typeof t.content=="string"?l=[{type:"text",text:t.content}]:Array.isArray(t.content)?l=t.content.map(u=>({type:u.type||"text",text:u.text,name:u.name,args:u.args||u.arguments})):typeof t.text=="string"&&(l=[{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:l,timestamp:d,id:h}}function ic(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 sc(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function Sr(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 Jp(){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 ls(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),Sr(t)}return Sr(Jp())}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=tc(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 Yp(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=tc(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 Xp(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function oc(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(y=>!y.fileName),r=(n??[]).filter(y=>y.fileName),l=[],d=r.map(y=>y.fileName).filter(Boolean);if(d.length>0){const y=i?`${d.join(", ")}
5
+ `);const s=Hp(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
+ `):null}function Kp(e){if(!e||typeof e!="object")return $r(e);const t=e;if(Us.has(t))return Us.get(t)??null;const n=$r(e);return Us.set(t,n),n}function Hp(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
+ `)}return typeof t.text=="string"?t.text:null}function qp(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 jp=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,Vp=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,Gp=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Qp=/^A new session was started via \/new or \/reset\./;function Jp(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"&&jp.test(s)||n==="assistant"&&Vp.test(s)||n==="user"&&Qp.test(s)||n==="assistant"&&Gp.test(s)):!1}function tc(e){return e.filter(t=>!Jp(t))}function nc(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 y=String(u.type??"").toLowerCase();return y==="toolresult"||y==="tool_result"}),r=typeof t.toolName=="string"||typeof t.tool_name=="string";(i||a||r)&&(n="toolResult");let l=[];typeof t.content=="string"?l=[{type:"text",text:t.content}]:Array.isArray(t.content)?l=t.content.map(u=>({type:u.type||"text",text:u.text,name:u.name,args:u.args||u.arguments})):typeof t.text=="string"&&(l=[{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:l,timestamp:d,id:h}}function ic(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 sc(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function Sr(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 Yp(){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 ls(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),Sr(t)}return Sr(Yp())}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=tc(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 Xp(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=tc(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 Zp(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function oc(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(y=>!y.fileName),r=(n??[]).filter(y=>y.fileName),l=[],d=r.map(y=>y.fileName).filter(Boolean);if(d.length>0){const y=i?`${d.join(", ")}
9
9
 
10
- ${i}`:d.join(", ");l.push({type:"text",text:y})}else i&&l.push({type:"text",text:i});for(const y of a)l.push({type:"image",source:{type:"base64",media_type:y.mimeType,data:y.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:l,timestamp:o}],e.chatSending=!0,e.lastError=null;const h=ls();e.chatRunId=h,e.chatStream="",e.chatStreamStartedAt=o;const u=[...a,...r],p=u.length>0?u.map(y=>{if(y.textContent)return{type:"document",mimeType:y.mimeType||"text/plain",fileName:y.fileName,content:btoa(unescape(encodeURIComponent(y.textContent)))};const $=Xp(y.dataUrl);return $?{type:y.fileName?"document":"image",mimeType:$.mimeType,fileName:y.fileName,content:$.content}:null}).filter(y=>y!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:h,attachments:p}),!0}catch(y){const $=String(y);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 ac(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 rc(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(", ");l.push({type:"text",text:y})}else i&&l.push({type:"text",text:i});for(const y of a)l.push({type:"image",source:{type:"base64",media_type:y.mimeType,data:y.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:l,timestamp:o}],e.chatSending=!0,e.lastError=null;const h=ls();e.chatRunId=h,e.chatStream="",e.chatStreamStartedAt=o;const u=[...a,...r],p=u.length>0?u.map(y=>{if(y.textContent)return{type:"document",mimeType:y.mimeType||"text/plain",fileName:y.fileName,content:btoa(unescape(encodeURIComponent(y.textContent)))};const x=Zp(y.dataUrl);return x?{type:y.fileName?"document":"image",mimeType:x.mimeType,fileName:y.fileName,content:x.content}:null}).filter(y=>y!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:h,attachments:p}),!0}catch(y){const x=String(y);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=x,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+x}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function ac(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 rc(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
- ${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:ac,handleChatEvent:rc,loadChatHistory:Jt,loadOlderChatHistory:Yp,sendChatMessage:oc},Symbol.toStringTag,{value:"Module"}));async function lc(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 Ar=50,Zp=80,eh=12e4;function th(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
- `)}function Cr(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=th(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=Zl(n,eh);return i.truncated?`${i.text}
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:ac,handleChatEvent:rc,loadChatHistory:Jt,loadOlderChatHistory:Xp,sendChatMessage:oc},Symbol.toStringTag,{value:"Module"}));async function lc(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 Ar=50,eh=80,th=12e4;function nh(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
+ `)}function Cr(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=nh(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=Zl(n,th);return i.truncated?`${i.text}
14
14
 
15
- … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function nh(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 ih(e){if(e.toolStreamOrder.length<=Ar)return;const t=e.toolStreamOrder.length-Ar,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function sh(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function So(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),sh(e)}function oh(e,t=!1){if(t){So(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>So(e),Zp))}function ia(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],So(e)}const ah=5e3;function rh(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},ah))}function lh(e,t){if(!t)return;if(t.stream==="compaction"){rh(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,l=a==="update"?Cr(i.partialResult):a==="result"?Cr(i.result):void 0,d=Date.now();let h=e.toolStreamById.get(s);h?(h.name=o,r!==void 0&&(h.args=r),l!==void 0&&(h.output=l),h.updatedAt=d):(h={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:r,output:l,startedAt:typeof t.ts=="number"?t.ts:d,updatedAt:d,message:{}},e.toolStreamById.set(s,h),e.toolStreamOrder.push(s)),h.message=nh(h),ih(e),oh(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 l=i();if(!l)return;const d=l.scrollHeight-l.scrollTop-l.clientHeight;(t||e.chatUserNearBottom||d<200)&&(l.scrollTop=l.scrollHeight,e.chatUserNearBottom=!0)},r)}))})}function Ao(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 ch(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 dh(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 uh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function ph(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function hh(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function fh(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 ih(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 sh(e){if(e.toolStreamOrder.length<=Ar)return;const t=e.toolStreamOrder.length-Ar,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function oh(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function So(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),oh(e)}function ah(e,t=!1){if(t){So(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>So(e),eh))}function ia(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],So(e)}const rh=5e3;function lh(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},rh))}function ch(e,t){if(!t)return;if(t.stream==="compaction"){lh(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,l=a==="update"?Cr(i.partialResult):a==="result"?Cr(i.result):void 0,d=Date.now();let h=e.toolStreamById.get(s);h?(h.name=o,r!==void 0&&(h.args=r),l!==void 0&&(h.output=l),h.updatedAt=d):(h={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:r,output:l,startedAt:typeof t.ts=="number"?t.ts:d,updatedAt:d,message:{}},e.toolStreamById.set(s,h),e.toolStreamOrder.push(s)),h.message=ih(h),sh(e),ah(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 l=i();if(!l)return;const d=l.scrollHeight-l.scrollTop-l.clientHeight;(t||e.chatUserNearBottom||d<200)&&(l.scrollTop=l.scrollHeight,e.chatUserNearBottom=!0)},r)}))})}function Ao(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 dh(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 uh(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 ph(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function hh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function fh(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function gh(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
16
16
  `)}
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 gh(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
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 mh(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
18
18
  `)}
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 mh(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 Ct(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 l=i;l[a]==null&&(l[a]=typeof r=="number"?[]:{}),i=l[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 We(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});vh(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",{});yh(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function yh(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function vh(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?Ct(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=Ct(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 bh(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?Ct(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 We(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 wh(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 kh(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 xh(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 Co(e,t.id)}catch(n){e.cronError=String(n),e.cronRunResult={status:"error",error:String(n)}}finally{e.cronBusy=!1}}}function $h(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 Sh(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 Ah(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 Ch(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 Co(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 Z(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 sa(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 l=r.accounts;if(l[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}l[i]={name:n,provider:"baileys"};const d=s.hash;if(!d){e.whatsappAccountError="Config hash missing; reload and retry.";return}const h=Ct(o);await e.client.request("config.set",{raw:h,baseHash:d}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await Z(e,!0),await sa(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 l=n.hash;if(!l){e.whatsappAccountError="Config hash missing; reload and retry.";return}const d=Ct(i);await e.client.request("config.set",{raw:d,baseHash:l}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await Z(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const Eh=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:gc,loadChannels:Z,logoutWhatsApp:fc,removeWhatsAppAccount:mc,startWhatsAppLogin:sa,waitWhatsAppLogin:hc},Symbol.toStringTag,{value:"Module"}));async function oa(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 aa="taskmaster-access-session",yc={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function cs(){try{return localStorage.getItem(aa)}catch{return null}}function vc(e){try{localStorage.setItem(aa,e)}catch{}}function Th(){try{localStorage.removeItem(aa)}catch{}}async function Er(e){if(e.client)try{const t=cs(),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 _h(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 Mh(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 Ph(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 Ih(e){const t=cs();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}Th(),e.accessState={...yc,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}const Rh=1e4,Lh=new Set(["trace","debug","info","warn","error","fatal"]);function Dh(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 Bh(e){if(typeof e!="string")return null;const t=e.toLowerCase();return Lh.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=Bh((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=Dh(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 l=null;return typeof t[1]=="string"?l=t[1]:!a&&typeof t[0]=="string"?l=t[0]:typeof t.message=="string"&&(l=t.message),{raw:e,time:i,level:s,subsystem:r,message:l??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function bt(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,date:e.logsDate??void 0,accessToken:cs()??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(-Rh),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),Array.isArray(i.availableDates)&&(e.logsAvailableDates=i.availableDates.filter(r=>typeof r=="string")),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t!=null&&t.quiet||(e.logsLoading=!1)}}}const Nh=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:bt,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:Tr,Gy:_r,a:zs,d:Ks,h:Oh}=wc,Et=32,ra=64,Fh=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},re=(e="")=>{const t=new Error(e);throw Fh(t,re),t},Uh=e=>typeof e=="bigint",Wh=e=>typeof e=="string",zh=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",ct=(e,t,n="")=>{const i=zh(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}`:"",l=i?`length=${s}`:`type=${typeof e}`;re(a+"expected Uint8Array"+r+", got "+l)}return e},ds=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},Mr=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(!Wh(e))return re(t);const n=e.length,i=n/2;if(n%2)return re(t);const s=ds(i);for(let o=0,a=0;o<i;o++,a+=2){const r=Mr(e.charCodeAt(a)),l=Mr(e.charCodeAt(a+1));if(r===void 0||l===void 0)return re(t);s[o]=r*16+l}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")},Kn=(...e)=>{const t=ds(e.reduce((i,s)=>i+ct(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Hh=(e=Et)=>Ac().getRandomValues(ds(e)),Fi=BigInt,gt=(e,t,n,i="bad number: out of range")=>Uh(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),qh=(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,l=s-o*a;i=n,n=r,s=o,o=l}return i===1n?L(s,t):re("no inverse")},jh=e=>{const t=Mc[e];return typeof t!="function"&&re("hashes."+e+" not set"),t},Hs=e=>e instanceof Tt?e:re("Point expected"),Eo=2n**256n,Ue=class Ue{constructor(t,n,i,s){q(this,"X");q(this,"Y");q(this,"Z");q(this,"T");const o=Eo;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 Ue(t.x,t.y,1n,L(t.x*t.y))}static fromBytes(t,n=!1){const i=Ks,s=kc(ct(t,Et)),o=t[31];s[31]=o&-129;const a=Tc(s);gt(a,0n,n?Eo:ue);const l=L(a*a),d=L(l-1n),h=L(i*l+1n);let{isValid:u,value:p}=Vh(d,h);u||re("bad point: y not sqrt");const y=(p&1n)===1n,$=(o&128)!==0;return!n&&p===0n&&$&&re("bad point: x==0, isLastByteOdd"),$!==y&&(p=L(-p)),new Ue(p,a,1n,L(p*a))}static fromHex(t,n){return Ue.fromBytes(Sc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=zs,n=Ks,i=this;if(i.is0())return re("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,l=L(s*s),d=L(o*o),h=L(a*a),u=L(h*h),p=L(l*t),y=L(h*L(p+d)),$=L(u+L(n*L(l*d)));if(y!==$)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}=Hs(t),l=L(n*r),d=L(o*s),h=L(i*r),u=L(a*s);return l===d&&h===u}is0(){return this.equals(jt)}negate(){return new Ue(L(-this.X),this.Y,this.Z,L(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=zs,o=L(t*t),a=L(n*n),r=L(2n*L(i*i)),l=L(s*o),d=t+n,h=L(L(d*d)-o-a),u=l+a,p=u-r,y=l-a,$=L(h*p),S=L(u*y),M=L(h*y),v=L(p*u);return new Ue($,S,v,M)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:l,T:d}=Hs(t),h=zs,u=Ks,p=L(n*a),y=L(i*r),$=L(o*u*d),S=L(s*l),M=L((n+i)*(a+r)-p-y),v=L(S-$),b=L(S+$),k=L(y-h*p),A=L(M*v),E=L(b*k),T=L(M*k),P=L(v*b);return new Ue(A,E,P,T)}subtract(t){return this.add(Hs(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return jt;if(gt(t,1n,Ai),t===1n)return this;if(this.equals(_t))return af(t).p;let i=jt,s=_t;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(jt))return{x:0n,y:1n};const s=qh(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(Oh),!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(Ue,"BASE"),q(Ue,"ZERO");let Tt=Ue;const _t=new Tt(Tr,_r,1n,L(Tr*_r)),jt=new Tt(0n,1n,1n,0n);Tt.BASE=_t;Tt.ZERO=jt;const Ec=e=>Sc(xc(gt(e,0n,Eo),ra)).reverse(),Tc=e=>Fi("0x"+$c(kc(ct(e)).reverse())),De=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ue;return n},Gh=e=>{const n=e*e%ue*e%ue,i=De(n,2n)*n%ue,s=De(i,1n)*e%ue,o=De(s,5n)*s%ue,a=De(o,10n)*o%ue,r=De(a,20n)*a%ue,l=De(r,40n)*r%ue,d=De(l,80n)*l%ue,h=De(d,80n)*l%ue,u=De(h,10n)*o%ue;return{pow_p_5_8:De(u,2n)*e%ue,b2:n}},Pr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Vh=(e,t)=>{const n=L(t*t*t),i=L(n*n*t),s=Gh(e*i).pow_p_5_8;let o=L(e*n*s);const a=L(t*o*o),r=o,l=L(o*Pr),d=a===e,h=a===L(-e),u=a===L(-e*Pr);return d&&(o=r),(h||u)&&(o=l),(L(o)&1n)===1n&&(o=L(-o)),{isValid:d||h,value:o}},To=e=>Cc(Tc(e)),la=(...e)=>Mc.sha512Async(Kn(...e)),Qh=(...e)=>jh("sha512")(Kn(...e)),_c=e=>{const t=e.slice(0,Et);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Et,ra),i=To(t),s=_t.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},ca=e=>la(ct(e,Et)).then(_c),Jh=e=>_c(Qh(ct(e,Et))),Yh=e=>ca(e).then(t=>t.pointBytes),Xh=e=>la(e.hashable).then(e.finish),Zh=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=To(t),a=_t.multiply(o).toBytes();return{hashable:Kn(a,i,n),finish:d=>{const h=Cc(o+To(d)*s);return ct(Kn(a,Ec(h)),ra)}}},ef=async(e,t)=>{const n=ct(e),i=await ca(t),s=await la(i.prefix,n);return Xh(Zh(i,s,n))},Mc={sha512Async:async e=>{const t=Kh(),n=Kn(e);return ds(await t.digest("SHA-512",n.buffer))},sha512:void 0},tf=(e=Hh(Et))=>e,nf={getExtendedPublicKeyAsync:ca,getExtendedPublicKey:Jh,randomSecretKey:tf},Ui=8,sf=256,Pc=Math.ceil(sf/Ui)+1,_o=2**(Ui-1),of=()=>{const e=[];let t=_t,n=t;for(let i=0;i<Pc;i++){n=t,e.push(n);for(let s=1;s<_o;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Ir;const Rr=(e,t)=>{const n=t.negate();return e?n:t},af=e=>{const t=Ir||(Ir=of());let n=jt,i=_t;const s=2**Ui,o=s,a=Fi(s-1),r=Fi(Ui);for(let l=0;l<Pc;l++){let d=Number(e&a);e>>=r,d>_o&&(d-=o,e+=1n);const h=l*_o,u=h,p=h+Math.abs(d)-1,y=l%2!==0,$=d<0;d===0?i=i.add(Rr(y,t[u])):n=n.add(Rr($,t[p]))}return e!==0n&&re("invalid wnaf"),{p:n,f:i}},qs="taskmaster-device-identity-v1";function Mo(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 rf(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 rf(new Uint8Array(t))}async function lf(){const e=nf.randomSecretKey(),t=await Yh(e);return{deviceId:await Rc(t),publicKey:Mo(t),privateKey:Mo(e)}}async function cf(){try{const n=localStorage.getItem(qs);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(qs,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 lf(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(qs,JSON.stringify(t)),e}async function df(e,t){const n=Ic(e),i=new TextEncoder().encode(t),s=await ef(i,n);return Mo(s)}const Lc="taskmaster.device.auth.v1";function da(e){return e.trim()}function uf(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 ua(){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 pf(e){const t=ua();if(!t||t.deviceId!==e.deviceId)return null;const n=da(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function hf(e){const t=da(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=ua();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:uf(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Dc(n),s}function ff(e){const t=ua();if(!t||t.deviceId!==e.deviceId)return;const n=da(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Dc(i)}async function pa(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 ha(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 gf(e){return{method:"exec.approvals.get",params:{}}}async function mf(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=gf(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);yf(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function yf(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 xe(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 Pe(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 Pe(e),xe(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=$e(i);e.skillsError=s,xe(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 Pe(e),xe(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=$e(n);e.skillsError=i,xe(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 Pe(e),xe(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=$e(s);e.skillsError=o,xe(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 zc(e){e.skillDetail=null,e.skillDetailTab=""}function Kc(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 fa(e)}async function fa(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 Pe(e),xe(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=[],xe(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 Pe(e),xe(e,t,{kind:"success",message:n?"Skill is now always active":"Skill loads on demand"})}catch(i){e.skillsError=$e(i),xe(e,t,{kind:"error",message:$e(i)})}finally{e.skillsBusyKey=null}}}async function ed(e,t,n){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.update",{skillKey:t,agents:n}),await Pe(e),xe(e,t,{kind:"success",message:"Agent access updated"})}catch(i){const s=$e(i);e.skillsError=s,xe(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function td(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await Pe(e)}catch(n){e.skillsError=$e(n)}finally{e.skillsBusyKey=null}}}const vf=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:qc,closeSkillDetail:zc,deleteDraft:Vc,deleteSkill:td,editDetailSkill:Jc,editSkill:Qc,emptyAddForm:Hn,importDraft:jc,installDraft:Gc,installSkill:Uc,loadSkills:Pe,openAddSkillModal:Hc,saveNewSkill:fa,saveSkillApiKey:Fc,setEditTab:Xc,setSkillDetailTab:Kc,toggleAlwaysActive:Zc,updateFormReference:Yc,updateSkillAgents:ed,updateSkillEdit:Nc,updateSkillEnabled:Oc,viewSkillDetail:Wc},Symbol.toStringTag,{value:"Module"})),nd={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},id=new Map(Object.entries(nd).map(([e,t])=>[t,e]));function us(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 bf(e,t=""){const n=us(t),i=nd[e];return n?`${n}${i}`:i}function sd(e,t=""){const n=us(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":id.get(s)??null}function wf(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(id.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function kf(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ga(e){return e==="system"?kf():e}const di=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,xf=()=>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")},$f=({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=xf();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)},Sf=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(-Sf),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 od=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:Pn},Symbol.toStringTag,{value:"Module"}));async function ad(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 Af(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function ze(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=ze(n)}finally{e.filesLoading=!1}}}}async function Cf(e,t,n){e.filesSelectedPaths=new Set([t]),await rd(e,t,n)}async function Ef(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 rd(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function Tf(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 ld(e,o,t),i++}catch(a){s=ze(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:an(e,`${i} file${i!==1?"s":""} downloaded`)}async function _f(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await Rf(e,t,o,i)}async function rd(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=ze(i)}finally{e.filesPreviewLoading=!1}}}async function ld(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),l=document.createElement("a");l.href=r,l.download=s.name??t.split("/").pop()??"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(r)}catch(i){e.filesMessage={kind:"error",text:ze(i)}}}async function Mf(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(),l=btoa(new Uint8Array(r).reduce((h,u)=>h+String.fromCharCode(u),"")),d={path:t,name:a.name,data:l};i&&(d.agentId=i),await e.client.request("files.upload",d),s++}catch(r){o=ze(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 Pf(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:ze(o)}}}async function If(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:ze(i)}}}}async function Rf(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:ze(s)}}}}async function ps(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 Lf(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 ps(e,t)}catch(n){e.filesMessage={kind:"error",text:ze(n)}}finally{e.filesReindexBusy=!1}}}function Df(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 Bf(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:ze(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function Nf(e){e.filesSearchQuery="",e.filesSearchResults=null}function Of(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{ha(e,{quiet:!0})},5e3))}function Ff(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Wi(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")&&e.logsSubTab!=="session"&&e.logsDate==null&&bt(e,{quiet:!0})},2e3))}function ma(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function zi(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||Pn(e,{quiet:!0,reset:!0})},3e3))}function ya(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function va(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&oa(e)},3e3))}function ba(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function Uf(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{ad(e)},3e4))}function Wf(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function zf(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{const t=e;t.filesPage&&ps(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,Ip(n),t.theme!==e.theme&&(e.theme=t.theme,hs(e,ga(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function cd(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&at(e,{...e.settings,lastActiveSessionKey:n})}function Hf(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 l=n.trim();l&&l!==e.settings.token&&at(e,{...e.settings,token:l}),t.delete("token"),a=!0}if(i!=null){const l=i.trim();l&&(e.password=l),t.delete("password"),a=!0}if(s!=null){const l=s.trim();l&&(e.sessionKey=l,at(e,{...e.settings,sessionKey:l,lastActiveSessionKey:l}))}if(o!=null){const l=o.trim();l&&l!==e.settings.gatewayUrl&&at(e,{...e.settings,gatewayUrl:l}),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 qf(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?zi(e):Wi(e):(ma(e),ya(e)),t==="debug"?va(e):ba(e),Ki(e),ud(e,t,!1)}function jf(e,t,n){$f({nextTheme:t,applyTheme:()=>{e.theme=t,at(e,{...e.settings,theme:t}),hs(e,ga(t))},context:n,currentTheme:e.theme})}async function Ki(e){if(e.tab==="overview"&&await pd(e),e.tab==="channels"&&await Zf(e),e.tab==="instances"&&await Bc(e),e.tab==="cron"&&await hd(e),e.tab==="skills"&&await Pe(e),e.tab==="nodes"&&(await ha(e),await pa(e),await We(e),await mf(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await sg(e),sn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await dc(e),await We(e)),e.tab==="debug"&&(await oa(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(()=>od);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await bt(e,{reset:!0});Ao(e,!0)}}function Gf(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?us(e):wf(window.location.pathname)}function Vf(e){e.theme=e.settings.theme??"system",hs(e,ga(e.theme))}function hs(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function Qf(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"&&hs(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Jf(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 Yf(e,t){if(typeof window>"u")return;const n=sd(window.location.pathname,e.basePath)??"chat";dd(e,n),ud(e,n,t)}function Xf(e){var s;if(typeof window>"u")return;const t=sd(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})),dd(e,t)}function dd(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?zi(e):Wi(e):(ma(e),ya(e)),t==="debug"?va(e):ba(e),e.connected&&Ki(e)}function ud(e,t,n){if(typeof window>"u")return;const i=qn(bf(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 pd(e){await Promise.all([Z(e,!1),Bc(e),lc(e),on(e),oa(e)])}async function Zf(e){await Promise.all([Z(e,!0),dc(e),We(e)])}async function hd(e){await Promise.all([Z(e,!1),on(e),jn(e)])}function fd(e){return e.chatSending||!!e.chatRunId}function eg(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 gd(e){e.connected&&(e.chatMessage="",await ac(e))}function tg(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:ls(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],sn(e))}async function md(e,t,n){var s,o;ia(e);const i=await oc(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&&cd(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&&yd(e),i}async function yd(e){if(!e.connected||fd(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await md(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function ng(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function ig(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(eg(s)){await gd(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],Lp(e.selectedWorkspace??"",e.sessionKey)),fd(e)){tg(e,s,a);return}await md(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 sg(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}),lc(t),Po(e)]),sn(e,!0)}const og=yd;function ag(e){var s,o,a;const t=Yl(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 rg(e,t){const n=us(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Po(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=ag(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=rg(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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:c`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:c`<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:c`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:c`<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:c`<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:c`<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:c`<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>`,refreshCw:c`<svg viewBox="0 0 24 24"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>`,download:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:c`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,chevronLeft:c`<svg viewBox="0 0 24 24"><path d="m15 18-6-6 6-6"/></svg>`,chevronRight:c`<svg viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></svg>`,film:c`<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:c`<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:c`<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:c`<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:c`<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>`},lg=c`<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>`,cg=c`<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>`,dg=c`<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 Lr=!1;function ug(){Lr||(Lr=!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 Rt(e,t){var u;const n=(p,y)=>p===e?c`<span class="sp-page-nav-current">${p}</span>`:c`<a href=${y}>${p}</a>`,i=c`
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 yh(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 Je(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 l=i;l[a]==null&&(l[a]=typeof r=="number"?[]:{}),i=l[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 Oe(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});bh(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",{});vh(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function vh(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function bh(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=Je(t.config??{}),e.configFormOriginal=Je(t.config??{}),e.configRawOriginal=n)}async function wh(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 Oe(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 kh(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 xh(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 $h(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 Co(e,t.id)}catch(n){e.cronError=String(n),e.cronRunResult={status:"error",error:String(n)}}finally{e.cronBusy=!1}}}function Sh(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 Ah(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 Ch(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 Eh(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 Co(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 Y(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 sa(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=Je(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 l=r.accounts;if(l[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}l[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 Y(e,!0),await sa(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function mc(e,t,n){if(!e.client||!e.connected||e.whatsappAccountSaving)return;const i=t.trim();if(!i){e.whatsappAccountError="Account name is required.";return}const s=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");if(!s){e.whatsappAccountError="Invalid account name.";return}if(!n.phoneNumberId.trim()){e.whatsappAccountError="Phone Number ID is required.";return}if(!n.accessToken.trim()){e.whatsappAccountError="Access Token is required.";return}if(!n.webhookVerifyToken.trim()){e.whatsappAccountError="Webhook Verify Token is required.";return}e.whatsappAccountSaving=!0,e.whatsappAccountError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const a=Je(o.config??{});(!a.channels||typeof a.channels!="object")&&(a.channels={});const r=a.channels;(!r.whatsapp||typeof r.whatsapp!="object")&&(r.whatsapp={});const l=r.whatsapp;(!l.accounts||typeof l.accounts!="object")&&(l.accounts={});const d=l.accounts;if(d[s]){e.whatsappAccountError=`Account "${s}" already exists.`;return}const h={name:i,provider:"cloud",phoneNumberId:n.phoneNumberId.trim(),accessToken:n.accessToken.trim(),webhookVerifyToken:n.webhookVerifyToken.trim()};n.businessAccountId.trim()&&(h.businessAccountId=n.businessAccountId.trim()),d[s]=h;const u=o.hash;if(!u){e.whatsappAccountError="Config hash missing; reload and retry.";return}const p=at(a);await e.client.request("config.set",{raw:p,baseHash:u}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",e.newWhatsAppAccountProvider="baileys",e.newCloudPhoneNumberId="",e.newCloudBusinessAccountId="",e.newCloudAccessToken="",e.newCloudWebhookVerifyToken="",await Y(e,!0)}catch(o){e.whatsappAccountError=String(o)}finally{e.whatsappAccountSaving=!1}}async function yc(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=Je(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 l=n.hash;if(!l){e.whatsappAccountError="Config hash missing; reload and retry.";return}const d=at(i);await e.client.request("config.set",{raw:d,baseHash:l}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await Y(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const Th=Object.freeze(Object.defineProperty({__proto__:null,addCloudApiAccount:mc,addWhatsAppAccount:gc,loadChannels:Y,logoutWhatsApp:fc,removeWhatsAppAccount:yc,startWhatsAppLogin:sa,waitWhatsAppLogin:hc},Symbol.toStringTag,{value:"Module"}));async function oa(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 aa="taskmaster-access-session",vc={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function cs(){try{return localStorage.getItem(aa)}catch{return null}}function bc(e){try{localStorage.setItem(aa,e)}catch{}}function _h(){try{localStorage.removeItem(aa)}catch{}}async function Er(e){if(e.client)try{const t=cs(),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 Mh(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?(bc(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 Ph(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?(bc(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 Ih(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 Rh(e){const t=cs();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}_h(),e.accessState={...vc,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}const Lh=1e4,Dh=new Set(["trace","debug","info","warn","error","fatal"]);function Bh(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 Nh(e){if(typeof e!="string")return null;const t=e.toLowerCase();return Dh.has(t)?t:null}function wc(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=Nh((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=Bh(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 l=null;return typeof t[1]=="string"?l=t[1]:!a&&typeof t[0]=="string"?l=t[0]:typeof t.message=="string"&&(l=t.message),{raw:e,time:i,level:s,subsystem:r,message:l??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function bt(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,date:e.logsDate??void 0,accessToken:cs()??void 0}),o=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(wc),a=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=a?o:[...e.logsEntries,...o].slice(-Lh),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),Array.isArray(i.availableDates)&&(e.logsAvailableDates=i.availableDates.filter(r=>typeof r=="string")),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t!=null&&t.quiet||(e.logsLoading=!1)}}}const Oh=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:bt,parseLogLine:wc},Symbol.toStringTag,{value:"Module"}));const kc={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:ue,n:Ai,Gx:Tr,Gy:_r,a:zs,d:Ks,h:Fh}=kc,Ct=32,ra=64,Uh=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},re=(e="")=>{const t=new Error(e);throw Uh(t,re),t},Wh=e=>typeof e=="bigint",zh=e=>typeof e=="string",Kh=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",rt=(e,t,n="")=>{const i=Kh(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}`:"",l=i?`length=${s}`:`type=${typeof e}`;re(a+"expected Uint8Array"+r+", got "+l)}return e},ds=e=>new Uint8Array(e),xc=e=>Uint8Array.from(e),$c=(e,t)=>e.toString(16).padStart(t,"0"),Sc=e=>Array.from(rt(e)).map(t=>$c(t,2)).join(""),Ke={_0:48,_9:57,A:65,F:70,a:97,f:102},Mr=e=>{if(e>=Ke._0&&e<=Ke._9)return e-Ke._0;if(e>=Ke.A&&e<=Ke.F)return e-(Ke.A-10);if(e>=Ke.a&&e<=Ke.f)return e-(Ke.a-10)},Ac=e=>{const t="hex invalid";if(!zh(e))return re(t);const n=e.length,i=n/2;if(n%2)return re(t);const s=ds(i);for(let o=0,a=0;o<i;o++,a+=2){const r=Mr(e.charCodeAt(a)),l=Mr(e.charCodeAt(a+1));if(r===void 0||l===void 0)return re(t);s[o]=r*16+l}return s},Cc=()=>globalThis==null?void 0:globalThis.crypto,Hh=()=>{var e;return((e=Cc())==null?void 0:e.subtle)??re("crypto.subtle must be defined, consider polyfill")},Kn=(...e)=>{const t=ds(e.reduce((i,s)=>i+rt(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},qh=(e=Ct)=>Cc().getRandomValues(ds(e)),Fi=BigInt,gt=(e,t,n,i="bad number: out of range")=>Wh(e)&&t<=e&&e<n?e:re(i),L=(e,t=ue)=>{const n=e%t;return n>=0n?n:t+n},Ec=e=>L(e,Ai),jh=(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,l=s-o*a;i=n,n=r,s=o,o=l}return i===1n?L(s,t):re("no inverse")},Vh=e=>{const t=Pc[e];return typeof t!="function"&&re("hashes."+e+" not set"),t},Hs=e=>e instanceof Et?e:re("Point expected"),Eo=2n**256n,Ne=class Ne{constructor(t,n,i,s){z(this,"X");z(this,"Y");z(this,"Z");z(this,"T");const o=Eo;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 kc}static fromAffine(t){return new Ne(t.x,t.y,1n,L(t.x*t.y))}static fromBytes(t,n=!1){const i=Ks,s=xc(rt(t,Ct)),o=t[31];s[31]=o&-129;const a=_c(s);gt(a,0n,n?Eo:ue);const l=L(a*a),d=L(l-1n),h=L(i*l+1n);let{isValid:u,value:p}=Qh(d,h);u||re("bad point: y not sqrt");const y=(p&1n)===1n,x=(o&128)!==0;return!n&&p===0n&&x&&re("bad point: x==0, isLastByteOdd"),x!==y&&(p=L(-p)),new Ne(p,a,1n,L(p*a))}static fromHex(t,n){return Ne.fromBytes(Ac(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=zs,n=Ks,i=this;if(i.is0())return re("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,l=L(s*s),d=L(o*o),h=L(a*a),u=L(h*h),p=L(l*t),y=L(h*L(p+d)),x=L(u+L(n*L(l*d)));if(y!==x)return re("bad point: equation left != right (1)");const S=L(s*o),_=L(a*r);return S!==_?re("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:a,Z:r}=Hs(t),l=L(n*r),d=L(o*s),h=L(i*r),u=L(a*s);return l===d&&h===u}is0(){return this.equals(jt)}negate(){return new Ne(L(-this.X),this.Y,this.Z,L(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=zs,o=L(t*t),a=L(n*n),r=L(2n*L(i*i)),l=L(s*o),d=t+n,h=L(L(d*d)-o-a),u=l+a,p=u-r,y=l-a,x=L(h*p),S=L(u*y),_=L(h*y),v=L(p*u);return new Ne(x,S,v,_)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:l,T:d}=Hs(t),h=zs,u=Ks,p=L(n*a),y=L(i*r),x=L(o*u*d),S=L(s*l),_=L((n+i)*(a+r)-p-y),v=L(S-x),b=L(S+x),k=L(y-h*p),A=L(_*v),E=L(b*k),M=L(_*k),P=L(v*b);return new Ne(A,E,P,M)}subtract(t){return this.add(Hs(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return jt;if(gt(t,1n,Ai),t===1n)return this;if(this.equals(Tt))return rf(t).p;let i=jt,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(jt))return{x:0n,y:1n};const s=jh(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=Tc(n);return i[31]|=t&1n?128:0,i}toHex(){return Sc(this.toBytes())}clearCofactor(){return this.multiply(Fi(Fh),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ai/2n,!1).double();return Ai%2n&&(t=t.add(this)),t.is0()}};z(Ne,"BASE"),z(Ne,"ZERO");let Et=Ne;const Tt=new Et(Tr,_r,1n,L(Tr*_r)),jt=new Et(0n,1n,1n,0n);Et.BASE=Tt;Et.ZERO=jt;const Tc=e=>Ac($c(gt(e,0n,Eo),ra)).reverse(),_c=e=>Fi("0x"+Sc(xc(rt(e)).reverse())),Ie=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ue;return n},Gh=e=>{const n=e*e%ue*e%ue,i=Ie(n,2n)*n%ue,s=Ie(i,1n)*e%ue,o=Ie(s,5n)*s%ue,a=Ie(o,10n)*o%ue,r=Ie(a,20n)*a%ue,l=Ie(r,40n)*r%ue,d=Ie(l,80n)*l%ue,h=Ie(d,80n)*l%ue,u=Ie(h,10n)*o%ue;return{pow_p_5_8:Ie(u,2n)*e%ue,b2:n}},Pr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Qh=(e,t)=>{const n=L(t*t*t),i=L(n*n*t),s=Gh(e*i).pow_p_5_8;let o=L(e*n*s);const a=L(t*o*o),r=o,l=L(o*Pr),d=a===e,h=a===L(-e),u=a===L(-e*Pr);return d&&(o=r),(h||u)&&(o=l),(L(o)&1n)===1n&&(o=L(-o)),{isValid:d||h,value:o}},To=e=>Ec(_c(e)),la=(...e)=>Pc.sha512Async(Kn(...e)),Jh=(...e)=>Vh("sha512")(Kn(...e)),Mc=e=>{const t=e.slice(0,Ct);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Ct,ra),i=To(t),s=Tt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},ca=e=>la(rt(e,Ct)).then(Mc),Yh=e=>Mc(Jh(rt(e,Ct))),Xh=e=>ca(e).then(t=>t.pointBytes),Zh=e=>la(e.hashable).then(e.finish),ef=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=To(t),a=Tt.multiply(o).toBytes();return{hashable:Kn(a,i,n),finish:d=>{const h=Ec(o+To(d)*s);return rt(Kn(a,Tc(h)),ra)}}},tf=async(e,t)=>{const n=rt(e),i=await ca(t),s=await la(i.prefix,n);return Zh(ef(i,s,n))},Pc={sha512Async:async e=>{const t=Hh(),n=Kn(e);return ds(await t.digest("SHA-512",n.buffer))},sha512:void 0},nf=(e=qh(Ct))=>e,sf={getExtendedPublicKeyAsync:ca,getExtendedPublicKey:Yh,randomSecretKey:nf},Ui=8,of=256,Ic=Math.ceil(of/Ui)+1,_o=2**(Ui-1),af=()=>{const e=[];let t=Tt,n=t;for(let i=0;i<Ic;i++){n=t,e.push(n);for(let s=1;s<_o;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Ir;const Rr=(e,t)=>{const n=t.negate();return e?n:t},rf=e=>{const t=Ir||(Ir=af());let n=jt,i=Tt;const s=2**Ui,o=s,a=Fi(s-1),r=Fi(Ui);for(let l=0;l<Ic;l++){let d=Number(e&a);e>>=r,d>_o&&(d-=o,e+=1n);const h=l*_o,u=h,p=h+Math.abs(d)-1,y=l%2!==0,x=d<0;d===0?i=i.add(Rr(y,t[u])):n=n.add(Rr(x,t[p]))}return e!==0n&&re("invalid wnaf"),{p:n,f:i}},qs="taskmaster-device-identity-v1";function Mo(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Rc(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 lf(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Lc(e){const t=await crypto.subtle.digest("SHA-256",e);return lf(new Uint8Array(t))}async function cf(){const e=sf.randomSecretKey(),t=await Xh(e);return{deviceId:await Lc(t),publicKey:Mo(t),privateKey:Mo(e)}}async function df(){try{const n=localStorage.getItem(qs);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 Lc(Rc(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(qs,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 cf(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(qs,JSON.stringify(t)),e}async function uf(e,t){const n=Rc(e),i=new TextEncoder().encode(t),s=await tf(i,n);return Mo(s)}const Dc="taskmaster.device.auth.v1";function da(e){return e.trim()}function pf(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 ua(){try{const e=window.localStorage.getItem(Dc);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 Bc(e){try{window.localStorage.setItem(Dc,JSON.stringify(e))}catch{}}function hf(e){const t=ua();if(!t||t.deviceId!==e.deviceId)return null;const n=da(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function ff(e){const t=da(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=ua();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:pf(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Bc(n),s}function gf(e){const t=ua();if(!t||t.deviceId!==e.deviceId)return;const n=da(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Bc(i)}async function pa(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 ha(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 mf(e){return{method:"exec.approvals.get",params:{}}}async function yf(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=mf(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);vf(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function vf(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=Je(t.file??{}))}async function Nc(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 we(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function ke(e){return e instanceof Error?e.message:String(e)}function Hn(){return{name:"",skillContent:"",references:[],alwaysActive:!1}}async function _e(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=ke(n)}finally{e.skillsLoading=!1}}}function Oc(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Fc(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 _e(e),we(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=ke(i);e.skillsError=s,we(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Uc(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 _e(e),we(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=ke(n);e.skillsError=i,we(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Wc(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 _e(e),we(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=ke(s);e.skillsError=o,we(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function zc(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=ke(n)}}function Kc(e){e.skillDetail=null,e.skillDetailTab=""}function Hc(e,t){e.skillDetailTab=t}async function qc(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 jc(e){e.skillAddModal=!1,e.skillAddForm=Hn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[]}function Vc(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 fa(e)}async function fa(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 _e(e),we(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=[],we(e,i,{kind:"success",message:"Draft saved"}))}catch(n){e.skillsError=ke(n)}finally{e.skillsBusyKey=null}}}async function Qc(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=ke(n)}}async function Jc(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=ke(n)}}function Yc(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 Xc(e,t,n){e.skillAddForm={...e.skillAddForm,references:e.skillAddForm.references.map(i=>i.name===t?{...i,content:n}:i)}}function Zc(e,t){e.skillEditTab=t}async function ed(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 _e(e),we(e,t,{kind:"success",message:n?"Skill is now always active":"Skill loads on demand"})}catch(i){e.skillsError=ke(i),we(e,t,{kind:"error",message:ke(i)})}finally{e.skillsBusyKey=null}}}async function td(e,t,n){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.update",{skillKey:t,agents:n}),await _e(e),we(e,t,{kind:"success",message:"Agent access updated"})}catch(i){const s=ke(i);e.skillsError=s,we(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function nd(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await _e(e)}catch(n){e.skillsError=ke(n)}finally{e.skillsBusyKey=null}}}const bf=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:jc,closeSkillDetail:Kc,deleteDraft:Qc,deleteSkill:nd,editDetailSkill:Yc,editSkill:Jc,emptyAddForm:Hn,importDraft:Vc,installDraft:Gc,installSkill:Wc,loadSkills:_e,openAddSkillModal:qc,saveNewSkill:fa,saveSkillApiKey:Uc,setEditTab:Zc,setSkillDetailTab:Hc,toggleAlwaysActive:ed,updateFormReference:Xc,updateSkillAgents:td,updateSkillEdit:Oc,updateSkillEnabled:Fc,viewSkillDetail:zc},Symbol.toStringTag,{value:"Module"})),id={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},sd=new Map(Object.entries(id).map(([e,t])=>[t,e]));function us(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 wf(e,t=""){const n=us(t),i=id[e];return n?`${n}${i}`:i}function od(e,t=""){const n=us(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":sd.get(s)??null}function kf(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(sd.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function xf(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ga(e){return e==="system"?xf():e}const di=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,$f=()=>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")},Sf=({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=$f();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)},Af=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(-Af),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 ad=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:Pn},Symbol.toStringTag,{value:"Module"}));async function rd(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 Cf(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function Fe(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=Fe(n)}finally{e.filesLoading=!1}}}}async function Ef(e,t,n){e.filesSelectedPaths=new Set([t]),await ld(e,t,n)}async function Tf(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 ld(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function _f(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 cd(e,o,t),i++}catch(a){s=Fe(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:an(e,`${i} file${i!==1?"s":""} downloaded`)}async function Mf(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await Lf(e,t,o,i)}async function ld(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=Fe(i)}finally{e.filesPreviewLoading=!1}}}async function cd(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),l=document.createElement("a");l.href=r,l.download=s.name??t.split("/").pop()??"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(r)}catch(i){e.filesMessage={kind:"error",text:Fe(i)}}}async function Pf(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(),l=btoa(new Uint8Array(r).reduce((h,u)=>h+String.fromCharCode(u),"")),d={path:t,name:a.name,data:l};i&&(d.agentId=i),await e.client.request("files.upload",d),s++}catch(r){o=Fe(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 If(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:Fe(o)}}}async function Rf(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:Fe(i)}}}}async function Lf(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:Fe(s)}}}}async function ps(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 Df(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 ps(e,t)}catch(n){e.filesMessage={kind:"error",text:Fe(n)}}finally{e.filesReindexBusy=!1}}}function Bf(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 Nf(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:Fe(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function Of(e){e.filesSearchQuery="",e.filesSearchResults=null}function Ff(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{ha(e,{quiet:!0})},5e3))}function Uf(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Wi(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")&&e.logsSubTab!=="session"&&e.logsDate==null&&bt(e,{quiet:!0})},2e3))}function ma(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function zi(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||Pn(e,{quiet:!0,reset:!0})},3e3))}function ya(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function va(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&oa(e)},3e3))}function ba(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function Wf(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{rd(e)},3e4))}function zf(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function Kf(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{const t=e;t.filesPage&&ps(t,t.filesResolvedAgentId)},3e3))}function Hf(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function st(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,Rp(n),t.theme!==e.theme&&(e.theme=t.theme,hs(e,ga(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function dd(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&st(e,{...e.settings,lastActiveSessionKey:n})}function qf(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 l=n.trim();l&&l!==e.settings.token&&st(e,{...e.settings,token:l}),t.delete("token"),a=!0}if(i!=null){const l=i.trim();l&&(e.password=l),t.delete("password"),a=!0}if(s!=null){const l=s.trim();l&&(e.sessionKey=l,st(e,{...e.settings,sessionKey:l,lastActiveSessionKey:l}))}if(o!=null){const l=o.trim();l&&l!==e.settings.gatewayUrl&&st(e,{...e.settings,gatewayUrl:l}),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 jf(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?zi(e):Wi(e):(ma(e),ya(e)),t==="debug"?va(e):ba(e),Ki(e),pd(e,t,!1)}function Vf(e,t,n){Sf({nextTheme:t,applyTheme:()=>{e.theme=t,st(e,{...e.settings,theme:t}),hs(e,ga(t))},context:n,currentTheme:e.theme})}async function Ki(e){if(e.tab==="overview"&&await hd(e),e.tab==="channels"&&await eg(e),e.tab==="instances"&&await Nc(e),e.tab==="cron"&&await fd(e),e.tab==="skills"&&await _e(e),e.tab==="nodes"&&(await ha(e),await pa(e),await Oe(e),await yf(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await og(e),sn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await dc(e),await Oe(e)),e.tab==="debug"&&(await oa(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(()=>ad);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await bt(e,{reset:!0});Ao(e,!0)}}function Gf(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?us(e):kf(window.location.pathname)}function Qf(e){e.theme=e.settings.theme??"system",hs(e,ga(e.theme))}function hs(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function Jf(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"&&hs(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Yf(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 Xf(e,t){if(typeof window>"u")return;const n=od(window.location.pathname,e.basePath)??"chat";ud(e,n),pd(e,n,t)}function Zf(e){var s;if(typeof window>"u")return;const t=od(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,st(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),ud(e,t)}function ud(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?zi(e):Wi(e):(ma(e),ya(e)),t==="debug"?va(e):ba(e),e.connected&&Ki(e)}function pd(e,t,n){if(typeof window>"u")return;const i=qn(wf(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 hd(e){await Promise.all([Y(e,!1),Nc(e),lc(e),on(e),oa(e)])}async function eg(e){await Promise.all([Y(e,!0),dc(e),Oe(e)])}async function fd(e){await Promise.all([Y(e,!1),on(e),jn(e)])}function gd(e){return e.chatSending||!!e.chatRunId}function tg(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 md(e){e.connected&&(e.chatMessage="",await ac(e))}function ng(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:ls(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],sn(e))}async function yd(e,t,n){var s,o;ia(e);const i=await oc(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&&dd(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&&vd(e),i}async function vd(e){if(!e.connected||gd(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await yd(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function ig(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function sg(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(tg(s)){await md(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],Dp(e.selectedWorkspace??"",e.sessionKey)),gd(e)){ng(e,s,a);return}await yd(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 og(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}),lc(t),Po(e)]),sn(e,!0)}const ag=vd;function rg(e){var s,o,a;const t=Yl(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 lg(e,t){const n=us(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Po(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=rg(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=lg(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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:c`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:c`<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:c`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:c`<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:c`<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:c`<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:c`<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>`,refreshCw:c`<svg viewBox="0 0 24 24"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>`,download:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:c`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:c`<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:c`<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:c`<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:c`<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:c`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,chevronLeft:c`<svg viewBox="0 0 24 24"><path d="m15 18-6-6 6-6"/></svg>`,chevronRight:c`<svg viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></svg>`,film:c`<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:c`<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:c`<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:c`<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:c`<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>`},cg=c`<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>`,dg=c`<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>`,ug=c`<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 Lr=!1;function pg(){Lr||(Lr=!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,y)=>p===e?c`<span class="sp-page-nav-current">${p}</span>`:c`<a href=${y}>${p}</a>`,i=c`
21
21
  ${n("Setup","/setup")}
22
22
  ${n("Chat","/chat")}
23
23
  ${n("Admins","/admins")}
@@ -25,14 +25,14 @@ ${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)?hg(t):w,a=t!=null&&t.hasPins&&t.onLogout?c`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${lg}</button>`:w,r=t!=null&&t.onRestartGateway?pg(t.onRestartGateway):w,l=(t==null?void 0:t.auditCount)??0,d=l>0&&(t!=null&&t.onAuditClick)?c`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
- ${cg}
28
+ `,o=t&&(t.isMaster!==!1||!t.hasPins)?fg(t):w,a=t!=null&&t.hasPins&&t.onLogout?c`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${cg}</button>`:w,r=t!=null&&t.onRestartGateway?hg(t.onRestartGateway):w,l=(t==null?void 0:t.auditCount)??0,d=l>0&&(t!=null&&t.onAuditClick)?c`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
+ ${dg}
30
30
  <span class="nav-audit-badge">${l>99?"99+":l}</span>
31
- </button>`:w,h=()=>{const p=document.getElementById("nav-burger-toggle");p&&(p.checked=!1)};return ug(),c`
31
+ </button>`:w,h=()=>{const p=document.getElementById("nav-burger-toggle");p&&(p.checked=!1)};return pg(),c`
32
32
  <div class="setup-header">
33
33
  <input type="checkbox" id="nav-burger-toggle" class="nav-burger-checkbox" />
34
34
  <div class="setup-header-inner">
35
- <img class="setup-header-logo" src="${(t==null?void 0:t.selectedWorkspace)&&((u=Fe()[t.selectedWorkspace])==null?void 0:u.logoUrl)||Xe().iconUrl}" alt="${Xe().name}" />
35
+ <img class="setup-header-logo" src="${(t==null?void 0:t.selectedWorkspace)&&((u=Be()[t.selectedWorkspace])==null?void 0:u.logoUrl)||Qe().iconUrl}" alt="${Qe().name}" />
36
36
  <nav class="setup-header-nav">
37
37
  ${i}
38
38
  </nav>
@@ -51,10 +51,10 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
51
51
  ${i}
52
52
  </nav>
53
53
  </div>
54
- `}function pg(e){let t=!1;return c`
54
+ `}function hg(e){let t=!1;return c`
55
55
  <span class="nav-restart-container" style="position: relative;">
56
56
  <button class="nav-restart-btn" @click=${o=>{const r=o.currentTarget.closest(".nav-restart-container");if(!r)return;const l=r.querySelector(".nav-restart-confirm");l&&(t=!t,l.style.display=t?"flex":"none")}} title="Restart gateway">
57
- ${dg}
57
+ ${ug}
58
58
  </button>
59
59
  <div class="nav-restart-confirm" style="display: none;">
60
60
  <p>Restart the gateway?</p>
@@ -64,7 +64,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
64
64
  </div>
65
65
  </div>
66
66
  </span>
67
- `}function hg(e){const{workspaces:t,selectedWorkspace:n,onWorkspaceSelect:i}=e;return c`
67
+ `}function fg(e){const{workspaces:t,selectedWorkspace:n,onWorkspaceSelect:i}=e;return c`
68
68
  <select
69
69
  class="sp-workspace-selector"
70
70
  .value=${n??""}
@@ -78,7 +78,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
78
78
  <option disabled>───</option>
79
79
  <option value="__add__">+ Add Account</option>
80
80
  </select>
81
- `}function fg(e){return e.connected?e.fullscreen&&e.active?c`
81
+ `}function gg(e){return e.connected?e.fullscreen&&e.active?c`
82
82
  <div class="sp-fullscreen-overlay">
83
83
  <div class="sp-fullscreen-toolbar">
84
84
  <button
@@ -120,7 +120,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
120
120
  </div>
121
121
  `:c`
122
122
  <div class="setup-container">
123
- ${Rt("Browser")}
123
+ ${It("Browser")}
124
124
  <div class="setup-card sp-card-wide">
125
125
  <h1>Remote Browser</h1>
126
126
  <p style="margin-bottom: 16px;">Live view of the headless Chrome instance.</p>
@@ -210,14 +210,14 @@ ${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 Hi="application/x-taskmaster-file-path";let ht=null;function vd(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function bd(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function gg(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(Hi);if(i){bd(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(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&n.onUpload(t,r)}}function wd(e,t,n){var l;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?c`
213
+ `}const Hi="application/x-taskmaster-file-path";let ht=null;function bd(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wd(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function mg(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(Hi);if(i){wd(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(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&n.onUpload(t,r)}}function kd(e,t,n){var l;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?c`
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
218
  @dragover=${d=>{d.preventDefault(),d.stopPropagation(),d.dataTransfer&&(d.dataTransfer.dropEffect="move"),d.currentTarget.classList.add("sp-drop-target")}}
219
219
  @dragleave=${d=>{d.currentTarget.classList.remove("sp-drop-target")}}
220
- @drop=${d=>gg(d,e.path,t)}
220
+ @drop=${d=>mg(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>
@@ -228,7 +228,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
228
228
  @click=${d=>{d.stopPropagation(),t.onDelete(e.path)}}
229
229
  >×</span>`:w}
230
230
  </div>
231
- ${s&&e.children?e.children.map(d=>wd(d,t,n+1)):w}
231
+ ${s&&e.children?e.children.map(d=>kd(d,t,n+1)):w}
232
232
  `:c`
233
233
  <div
234
234
  class="sp-tree-item sp-tree-file ${o?"selected":""}"
@@ -239,9 +239,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
239
239
  >
240
240
  <span class="sp-tree-icon">${I.fileText}</span>
241
241
  <span class="sp-tree-name">${e.name}</span>
242
- <span class="sp-tree-size">${vd(e.size)}</span>
242
+ <span class="sp-tree-size">${bd(e.size)}</span>
243
243
  </div>
244
- `}function mg(e){const t=e.selectedPaths.size;return t<2?w:c`
244
+ `}function yg(e){const t=e.selectedPaths.size;return t<2?w:c`
245
245
  <div class="sp-bulk-actions">
246
246
  <span style="color: var(--tasker-muted-grey); font-size: 13px;">${t} files selected</span>
247
247
  <button
@@ -252,7 +252,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
252
252
  Download ${t} files
253
253
  </button>
254
254
  </div>
255
- `}function yg(e){if(e.selectedPaths.size!==1||!e.selectedPath)return w;if(e.previewLoading)return c`
255
+ `}function vg(e){if(e.selectedPaths.size!==1||!e.selectedPath)return w;if(e.previewLoading)return c`
256
256
  <div class="sp-file-preview">
257
257
  <div class="setup-spinner" style="width: 32px; height: 32px; margin: 24px auto;"></div>
258
258
  </div>
@@ -262,7 +262,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
262
262
  <div>
263
263
  <strong>${t}</strong>
264
264
  <div class="sp-file-preview-meta">
265
- ${e.selectedPath}${e.previewSize!=null?` — ${vd(e.previewSize)}`:""}
265
+ ${e.selectedPath}${e.previewSize!=null?` — ${bd(e.previewSize)}`:""}
266
266
  </div>
267
267
  </div>
268
268
  <div class="sp-file-actions">
@@ -276,7 +276,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
276
276
  </div>
277
277
  ${e.previewBinary?c`<div class="sp-file-preview-body"><p style="color: var(--tasker-muted-grey);">Binary file — use Download to view.</p></div>`:e.previewContent!=null?c`<div class="sp-file-preview-body"><pre class="sp-file-code">${e.previewContent}</pre></div>`:c`<div class="sp-file-preview-body"><p style="color: var(--tasker-muted-grey);">File too large for preview — use Download.</p></div>`}
278
278
  </div>
279
- `}function vg(e){return c`
279
+ `}function bg(e){return c`
280
280
  <div class="sp-search-bar">
281
281
  <input
282
282
  type="text"
@@ -308,7 +308,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
308
308
  Clear
309
309
  </button>`:w}
310
310
  </div>
311
- `}function bg(e){return e.searchResults?e.searchResults.length===0?c`<div class="sp-search-results">
311
+ `}function wg(e){return e.searchResults?e.searchResults.length===0?c`<div class="sp-search-results">
312
312
  <div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No results found.</div>
313
313
  </div>`:c`
314
314
  <div class="sp-search-results">
@@ -328,57 +328,55 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
328
328
  </div>
329
329
  `)}
330
330
  </div>
331
- `:w}function wg(e){const t=e.currentDir;return e.connected?c`
331
+ `:w}function kg(e){const t=e.currentDir;return e.connected?c`
332
332
  <div class="setup-container setup-container--full">
333
- ${Rt("Files",e.wsProps)}
333
+ ${It("Files",e.wsProps)}
334
334
  <div class="sp-files-page">
335
+ <div class="sp-sticky-header">
335
336
  <div class="sp-toolbar">
336
- <label class="setup-button secondary" style="padding: 10px 20px; font-size: 14px; cursor: pointer;">
337
- Upload${t!=="."?c` to <em>${t}</em>`:w}
338
- <input
339
- type="file"
340
- multiple
341
- accept=".md"
342
- style="display: none;"
343
- @change=${n=>{const i=n.target;i.files&&i.files.length>0&&(e.onUpload(t,Array.from(i.files)),i.value="")}}
344
- />
337
+ <input type="checkbox" id="sp-files-actions" class="sp-actions-toggle" />
338
+ <label for="sp-files-actions" class="sp-actions-trigger">
339
+ Actions
340
+ <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>
345
341
  </label>
346
- <button
347
- class="setup-button secondary"
348
- style="padding: 10px 20px; font-size: 14px;"
349
- @click=${()=>{const n=prompt("Folder name:");n!=null&&n.trim()&&e.onNewFolder(t,n.trim())}}
350
- >
351
- New Folder${t!=="."?c` in <em>${t}</em>`:w}
352
- </button>
353
- <button
354
- class="setup-button secondary"
355
- style="padding: 10px 20px; font-size: 14px;"
356
- ?disabled=${e.loading}
357
- @click=${e.onRefresh}
358
- >
359
- ${e.loading?"Loading...":"Refresh"}
360
- </button>
361
- <button
362
- class="setup-button secondary"
363
- style="padding: 10px 20px; font-size: 14px;"
364
- ?disabled=${e.reindexBusy}
365
- @click=${e.onReindex}
366
- >
367
- ${e.reindexBusy?"Re-indexing...":"Re-index"}
368
- </button>
369
- ${e.memoryStatus?e.memoryStatus.embeddingState==="downloading"?c`<span style="display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--tasker-orange, #f59e0b);">
370
- <span
371
- class="setup-status-light"
372
- style="width: 10px; height: 10px; background: #f59e0b"
373
- ></span>
374
- Downloading embedding model\u2026
375
- </span>`:c`<span style="display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--tasker-text-grey);">
376
- <span
377
- class="setup-status-light"
378
- style="width: 10px; height: 10px; background: ${e.memoryStatus.syncing?"#f59e0b":e.memoryStatus.dirty?"#ef4444":"#22c55e"}"
379
- ></span>
380
- ${(()=>{var l;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=(l=e.memoryStatus)==null?void 0:l.model;if(!o)return s;const r=(o.includes("/")?o.split("/").pop():o).replace(/[-_]Q\d.*$/i,"").replace(/\.gguf$/i,"");return`${s} · ${r}`})()}
381
- </span>`:w}
342
+ <label for="sp-files-actions" class="sp-actions-backdrop"></label>
343
+ <div class="sp-actions-panel">
344
+ <label class="setup-button secondary" style="padding: 10px 20px; font-size: 14px; cursor: pointer;">
345
+ Upload${t!=="."?c` to <em>${t}</em>`:w}
346
+ <input
347
+ type="file"
348
+ multiple
349
+ accept=".md"
350
+ style="display: none;"
351
+ @change=${n=>{var s;const i=n.target;i.files&&i.files.length>0&&(e.onUpload(t,Array.from(i.files)),i.value="",(s=document.getElementById("sp-files-actions"))==null||s.dispatchEvent(new MouseEvent("click")))}}
352
+ />
353
+ </label>
354
+ <button
355
+ class="setup-button secondary"
356
+ style="padding: 10px 20px; font-size: 14px;"
357
+ @click=${()=>{const n=prompt("Folder name:");n!=null&&n.trim()&&e.onNewFolder(t,n.trim())}}
358
+ >
359
+ New Folder${t!=="."?c` in <em>${t}</em>`:w}
360
+ </button>
361
+ <button
362
+ class="setup-button secondary"
363
+ style="padding: 10px 20px; font-size: 14px;"
364
+ ?disabled=${e.loading}
365
+ @click=${e.onRefresh}
366
+ >
367
+ ${e.loading?"Loading...":"Refresh"}
368
+ </button>
369
+ <button
370
+ class="setup-button secondary"
371
+ style="padding: 10px 20px; font-size: 14px;"
372
+ ?disabled=${e.reindexBusy}
373
+ @click=${e.onReindex}
374
+ >
375
+ ${e.reindexBusy?"Re-indexing...":"Re-index"}
376
+ </button>
377
+ </div>
378
+ </div>
379
+ ${bg(e)}
382
380
  </div>
383
381
 
384
382
  ${e.error?c`<div class="setup-error" style="margin-top: 16px;">${e.error}</div>`:w}
@@ -389,18 +387,23 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
389
387
 
390
388
  ${e.uploadBusy?c`<div style="margin-top: 12px; color: var(--tasker-orange); font-weight: 600; font-size: 14px;">Uploading...</div>`:w}
391
389
 
392
- ${vg(e)}
393
-
394
- ${e.searchResults!==null?bg(e):c`<div
390
+ ${e.searchResults!==null?wg(e):c`<div
395
391
  class="sp-file-tree"
396
392
  @dragover=${n=>{n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(Hi)?"move":"copy")}}
397
- @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(Hi);if(i){bd(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(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&e.onUpload(t,r)}}}
393
+ @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(Hi);if(i){wd(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(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&e.onUpload(t,r)}}}
398
394
  >
399
- ${e.tree.length===0&&!e.loading?c`<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=>wd(n,e,0))}
395
+ ${e.tree.length===0&&!e.loading?c`<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=>kd(n,e,0))}
400
396
  </div>`}
401
397
 
402
- ${mg(e)}
403
398
  ${yg(e)}
399
+ ${vg(e)}
400
+ ${e.memoryStatus?e.memoryStatus.embeddingState==="downloading"?c`<div style="padding: 16px 0; display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--tasker-orange, #f59e0b);">
401
+ <span class="setup-status-light" style="width: 10px; height: 10px; background: #f59e0b"></span>
402
+ Downloading embedding model\u2026
403
+ </div>`:c`<div style="padding: 16px 0; display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--tasker-muted-grey);">
404
+ <span class="setup-status-light" style="width: 10px; height: 10px; background: ${e.memoryStatus.syncing?"#f59e0b":e.memoryStatus.dirty?"#ef4444":"#22c55e"}"></span>
405
+ ${(()=>{var l;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=(l=e.memoryStatus)==null?void 0:l.model;if(!o)return s;const r=(o.includes("/")?o.split("/").pop():o).replace(/[-_]Q\d.*$/i,"").replace(/\.gguf$/i,"");return`${s} · ${r}`})()}
406
+ </div>`:w}
404
407
  </div>
405
408
  </div>
406
409
  `:c`
@@ -410,7 +413,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
410
413
  <p>Connecting to gateway...</p>
411
414
  </div>
412
415
  </div>
413
- `}const wa="taskmaster_uninstall_done";async function kg(e){var t,n;if(!(!e.client||!e.connected)&&!e.uninstallBusy){e.uninstallBusy=!0,e.uninstallError=null,(t=e.requestUpdate)==null||t.call(e),xg();try{await e.client.request("system.uninstall",{scopes:["service","state","workspace"],purge:!0})}catch{}e.uninstallBusy=!1,e.uninstallDone=!0,(n=e.requestUpdate)==null||n.call(e)}}function qi(){try{return localStorage.getItem(wa)==="1"}catch{return!1}}function ka(){try{localStorage.removeItem(wa)}catch{}}function xg(){try{localStorage.setItem(wa,"1")}catch{}}const Dr=Object.freeze(Object.defineProperty({__proto__:null,checkUninstallDone:qi,clearUninstallDone:ka,runUninstall:kg},Symbol.toStringTag,{value:"Module"}));function Q(e){return c`
416
+ `}const wa="taskmaster_uninstall_done";async function xg(e){var t,n;if(!(!e.client||!e.connected)&&!e.uninstallBusy){e.uninstallBusy=!0,e.uninstallError=null,(t=e.requestUpdate)==null||t.call(e),$g();try{await e.client.request("system.uninstall",{scopes:["service","state","workspace"],purge:!0})}catch{}e.uninstallBusy=!1,e.uninstallDone=!0,(n=e.requestUpdate)==null||n.call(e)}}function qi(){try{return localStorage.getItem(wa)==="1"}catch{return!1}}function ka(){try{localStorage.removeItem(wa)}catch{}}function $g(){try{localStorage.setItem(wa,"1")}catch{}}const Dr=Object.freeze(Object.defineProperty({__proto__:null,checkUninstallDone:qi,clearUninstallDone:ka,runUninstall:xg},Symbol.toStringTag,{value:"Module"}));function G(e){return c`
414
417
  <span
415
418
  class="setup-status-light"
416
419
  style="background: ${{good:"#22c55e",bad:"#ef4444",partial:"#eab308",unknown:"#6b7280"}[e]}"
@@ -423,13 +426,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
423
426
  >
424
427
  ${I.info}
425
428
  </button>
426
- `}function $g(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),l=o%60;a=l>0?`${r}h ${l}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,l=r.length>20?`${r.slice(0,8)}...${r.slice(-8)}`:r;i=c`
429
+ `}function Sg(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),l=o%60;a=l>0?`${r}h ${l}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,l=r.length>20?`${r.slice(0,8)}...${r.slice(-8)}`:r;i=c`
427
430
  <div style="display: flex; align-items: center; gap: 6px; padding: 4px 0 8px; border-bottom: 1px solid rgba(255,255,255,0.08);">
428
431
  <span style="font-size: 12px; color: var(--tasker-text-grey); min-width: 90px;">Refresh Token</span>
429
432
  <code style="font-size: 12px; color: var(--tasker-white); word-break: break-all; flex: 1;">${l}</code>
430
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>
431
434
  </div>
432
- `}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=Lt(e),a=o?fs(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:xa(a.lastError)}]:[]];break}case"imessage":{const{thisWsOwns:o}=$a(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=c`
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?fs(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:xa(a.lastError)}]:[]];break}case"imessage":{const{thisWsOwns:o}=$a(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=c`
433
436
  ${e.remoteAccessQrDataUrl?c`<div style="text-align: center; padding: 12px 0;">
434
437
  <img src=${e.remoteAccessQrDataUrl} alt="QR code for remote access URL" style="width: 180px; height: 180px; image-rendering: pixelated; border-radius: 8px;" />
435
438
  </div>`:w}
@@ -439,7 +442,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
439
442
  >${r}</a>
440
443
  <button class="setup-info-btn" title="Copy URL" @click=${async l=>{const d=l.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>
441
444
  </div>
442
- `}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:Bg[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=c`
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:Fg[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=c`
443
446
  ${e.publicChatQrDataUrl?c`<div style="text-align: center; padding: 12px 0;">
444
447
  <img src=${e.publicChatQrDataUrl} alt="QR code for public chat URL" style="width: 180px; height: 180px; image-rendering: pixelated; border-radius: 8px;" />
445
448
  </div>`:w}
@@ -474,7 +477,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
474
477
  </button>
475
478
  </div>
476
479
  </div>
477
- `}function _e(e){const t=[{id:"license",label:"1. Activate License"},{id:"auth",label:"2. Connect Claude"},{id:"setup",label:"3. Link WhatsApp"}],n=["license","auth","setup"],i=n.indexOf(e);return c`
480
+ `}function Ee(e){const t=[{id:"license",label:"1. Activate License"},{id:"auth",label:"2. Connect Claude"},{id:"setup",label:"3. Link WhatsApp"}],n=["license","auth","setup"],i=n.indexOf(e);return c`
478
481
  <div class="setup-steps">
479
482
  ${t.map(s=>{const o=n.indexOf(s.id),a=e===s.id,r=i>o;return c`
480
483
  <div
@@ -488,9 +491,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
488
491
  `}function Br(e){const{licenseKey:t,licenseBusy:n,licenseValid:i,licenseMessage:s,licenseDeviceId:o,onLicenseKeyChange:a,onLicenseActivate:r}=e;return i===!0?c`
489
492
  <div class="setup-container">
490
493
  <div class="setup-card setup-success">
491
- ${_e("license")}
494
+ ${Ee("license")}
492
495
  <div class="setup-status-row">
493
- ${Q("good")}
496
+ ${G("good")}
494
497
  <span>License Activated</span>
495
498
  </div>
496
499
  <p>${s??"Your license is active."}</p>
@@ -499,7 +502,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
499
502
  `:n&&!t?c`
500
503
  <div class="setup-container">
501
504
  <div class="setup-card">
502
- ${_e("license")}
505
+ ${Ee("license")}
503
506
  <div class="setup-spinner"></div>
504
507
  <p>Checking license...</p>
505
508
  </div>
@@ -507,7 +510,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
507
510
  `:c`
508
511
  <div class="setup-container">
509
512
  <div class="setup-card">
510
- ${_e("license")}
513
+ ${Ee("license")}
511
514
  <h1>Activate License</h1>
512
515
  <p>Enter your license key to get started.</p>
513
516
  ${o?c`
@@ -542,7 +545,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
542
545
  </div>
543
546
  ${i===!1&&s?c`
544
547
  <div class="setup-status-row" style="margin-top: 12px;">
545
- ${Q("bad")}
548
+ ${G("bad")}
546
549
  <span class="setup-error">${s}</span>
547
550
  </div>
548
551
  `:w}
@@ -554,12 +557,12 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
554
557
  </p>
555
558
  </div>
556
559
  </div>
557
- `}function Sg(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:l,onAuthCodeChange:d}=e;return t===!0?c`
560
+ `}function Ag(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:l,onAuthCodeChange:d}=e;return t===!0?c`
558
561
  <div class="setup-container">
559
562
  <div class="setup-card setup-success">
560
- ${_e("auth")}
563
+ ${Ee("auth")}
561
564
  <div class="setup-status-row">
562
- ${Q("good")}
565
+ ${G("good")}
563
566
  <span>Claude Connected</span>
564
567
  </div>
565
568
  <p>
@@ -579,7 +582,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
579
582
  `:n&&!s?c`
580
583
  <div class="setup-container">
581
584
  <div class="setup-card">
582
- ${_e("auth")}
585
+ ${Ee("auth")}
583
586
  <div class="setup-spinner"></div>
584
587
  <p>Starting Claude connection...</p>
585
588
  </div>
@@ -587,7 +590,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
587
590
  `:s?c`
588
591
  <div class="setup-container">
589
592
  <div class="setup-card">
590
- ${_e("auth")}
593
+ ${Ee("auth")}
591
594
  <h1>Connect to Claude</h1>
592
595
  <p>Click the button below to sign in with your Claude Pro account.</p>
593
596
  <a
@@ -628,7 +631,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
628
631
  `:e.authApiKeyMode?c`
629
632
  <div class="setup-container">
630
633
  <div class="setup-card">
631
- ${_e("auth")}
634
+ ${Ee("auth")}
632
635
  <h1>Enter API Key</h1>
633
636
  <p>Paste your Anthropic API key below.</p>
634
637
  <div class="setup-code-input">
@@ -664,7 +667,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
664
667
  `:c`
665
668
  <div class="setup-container">
666
669
  <div class="setup-card">
667
- ${_e("auth")}
670
+ ${Ee("auth")}
668
671
  <h1>Connect to Claude</h1>
669
672
  ${t===!1&&i?c`<p class="setup-error">${i}</p>`:c`<p>
670
673
  First, let's connect your Claude Pro subscription.<br />
@@ -686,7 +689,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
686
689
  </p>
687
690
  </div>
688
691
  </div>
689
- `}function fs(e,t){const n=new Map(t.whatsappAccounts.map(i=>[i.accountId,i]));return e.whatsappAccountId?n.get(e.whatsappAccountId)??null:e.isDefault&&t.whatsappAccounts.length===1?t.whatsappAccounts[0]??null:null}function Lt(e){var n;const t=(n=e.wsProps)==null?void 0:n.selectedWorkspace;return t?e.workspaces.find(i=>i.name===t)??null:e.workspaces[0]??null}function Ag(e){const t=Lt(e),n=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??Xe().name;if(e.renamingWorkspace&&t){const i=()=>{const s=e.renameWorkspaceName.trim();s&&e.onWorkspaceRename(t.name,s)};return c`
692
+ `}function fs(e,t){const n=new Map(t.whatsappAccounts.map(i=>[i.accountId,i]));return e.whatsappAccountId?n.get(e.whatsappAccountId)??null:e.isDefault&&t.whatsappAccounts.length===1?t.whatsappAccounts[0]??null:null}function Rt(e){var n;const t=(n=e.wsProps)==null?void 0:n.selectedWorkspace;return t?e.workspaces.find(i=>i.name===t)??null:e.workspaces[0]??null}function Cg(e){const t=Rt(e),n=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??Qe().name;if(e.renamingWorkspace&&t){const i=()=>{const s=e.renameWorkspaceName.trim();s&&e.onWorkspaceRename(t.name,s)};return c`
690
693
  <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 4px;">
691
694
  <input
692
695
  type="text"
@@ -718,9 +721,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
718
721
  style="opacity: 0.5; transform: scale(0.8);"
719
722
  >${I.edit}</button>
720
723
  </div>
721
- `}function Cg(e){return c`
724
+ `}function Eg(e){return c`
722
725
  <div class="setup-status-item">
723
- ${Q(e.gatewayHealthy===!1?"bad":"good")}
726
+ ${G(e.gatewayHealthy===!1?"bad":"good")}
724
727
  <div class="setup-status-info">
725
728
  <strong>Gateway</strong>
726
729
  <span>${e.gatewayHealthMessage||"Running"}</span>
@@ -735,9 +738,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
735
738
  ${I.rotateCw}
736
739
  </button>
737
740
  </div>
738
- `}function Eg(e){const t=e.authConnected===!0;return c`
741
+ `}function Tg(e){const t=e.authConnected===!0;return c`
739
742
  <div class="setup-status-item">
740
- ${Q(t?"good":"bad")}
743
+ ${G(t?"good":"bad")}
741
744
  <div class="setup-status-info">
742
745
  <strong>Claude</strong>
743
746
  <span>
@@ -764,9 +767,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
764
767
  </button>
765
768
  `}
766
769
  </div>
767
- `}function Tg(e){return c`
770
+ `}function _g(e){return c`
768
771
  <div class="setup-status-item" style="flex-wrap: wrap;">
769
- ${Q("good")}
772
+ ${G("good")}
770
773
  <div class="setup-status-info">
771
774
  <strong>License</strong>
772
775
  <span>Active</span>
@@ -782,7 +785,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
782
785
  ${e.licenseRemoveConfirm?c`
783
786
  <div style="width: 100%; margin-top: 8px; margin-left: 30px;">
784
787
  <p style="color: var(--tasker-text-grey); font-size: 13px; margin: 0 0 8px;">
785
- Removing your license will disable ${Xe().name} until you enter a new key.
788
+ Removing your license will disable ${Qe().name} until you enter a new key.
786
789
  </p>
787
790
  <div style="display: flex; gap: 8px;">
788
791
  <button
@@ -804,9 +807,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
804
807
  </div>
805
808
  `:w}
806
809
  </div>
807
- `}function xa(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}function _g(e){var u;const t=Lt(e);if(!t)return w;const n=fs(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?xa(n.lastError):"Not connected":"Not paired",l=!(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 c`
810
+ `}function xa(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}function Mg(e){var u;const t=Rt(e);if(!t)return w;const n=fs(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?xa(n.lastError):"Not connected":"Not paired",l=!(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 c`
808
811
  <div class="setup-status-item" style="flex-wrap: wrap;">
809
- ${Q(a)}
812
+ ${G(a)}
810
813
  <div class="setup-status-info">
811
814
  <strong>WhatsApp</strong>
812
815
  <span>${r}</span>
@@ -835,10 +838,17 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
835
838
  </div>
836
839
  `:w}
837
840
  </div>
838
- `}function Mg(e){var h,u;if(!e.whatsappSettingsOpen)return w;const t=Lt(e);if(!t)return w;const n=fs(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;",l="color: var(--tasker-text-grey);",d="color: var(--tasker-white); text-align: right;";return c`
841
+ `}function Pg(e){var h,u;if(!e.whatsappSettingsOpen)return w;const t=Rt(e);if(!t)return w;const n=fs(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;",l="color: var(--tasker-text-grey);",d="color: var(--tasker-white); text-align: right;";return c`
839
842
  <div class="setup-info-overlay" @click=${p=>{p.target.classList.contains("setup-info-overlay")&&a()}}>
840
- <div class="setup-info-card" style="max-width: 360px;">
841
- <h3>WhatsApp</h3>
843
+ <div class="setup-info-card">
844
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0;">
845
+ <h3 style="margin: 0;">WhatsApp</h3>
846
+ <button
847
+ @click=${a}
848
+ style="background: none; border: none; color: var(--tasker-text-grey); font-size: 18px; line-height: 1; cursor: pointer; padding: 0 2px;"
849
+ title="Close"
850
+ >✕</button>
851
+ </div>
842
852
  <div style="display: flex; flex-direction: column; gap: 8px; margin-top: 12px;">
843
853
  <div style="${r}"><span style="${l}">Account</span><span style="${d}">${n.name||n.accountId||"Default"}</span></div>
844
854
  <div style="${r}"><span style="${l}">Phone</span><span style="${d}">${((u=n.self)==null?void 0:u.e164)||"Not paired"}</span></div>
@@ -862,64 +872,21 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
862
872
  `:w}
863
873
  ${i?c`
864
874
  <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
865
- <div style="display: flex; flex-direction: column; gap: 16px;">
866
- <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
867
- <input
868
- type="checkbox"
869
- .checked=${e.whatsappDmPolicy!=="disabled"&&e.whatsappDmPolicy!==null}
870
- @change=${e.onWhatsAppDmToggle}
871
- style="accent-color: #22c55e; margin-top: 2px;"
872
- />
873
- <div>
874
- <div style="font-size: 13px; color: var(--tasker-white);">Enabled</div>
875
- <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7;">Agent replies to 3rd party messages</div>
876
- </div>
877
- </label>
878
- <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 4px 0;"></div>
879
- <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
880
- <input
881
- type="checkbox"
882
- .checked=${e.whatsappGroupPolicy==="open"}
883
- @change=${e.onWhatsAppGroupToggle}
884
- style="accent-color: #22c55e; margin-top: 2px;"
885
- />
886
- <div>
887
- <div style="font-size: 13px; color: var(--tasker-white);">Group chats</div>
888
- <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7;">Agent responds in WhatsApp groups</div>
889
- </div>
890
- </label>
891
- ${e.whatsappGroupPolicy==="open"?c`
892
- <div style="display: flex; flex-direction: column; gap: 6px; padding-left: 24px;">
893
- <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
894
- <input
895
- type="radio"
896
- name="wa-group-mention"
897
- .checked=${e.whatsappGroupRequireMention}
898
- @change=${()=>e.onWhatsAppGroupMentionChange(!0)}
899
- style="accent-color: #22c55e;"
900
- />
901
- <div>
902
- <div style="font-size: 13px; color: var(--tasker-white);">When mentioned</div>
903
- <div style="font-size: 11px; color: var(--tasker-text-grey); opacity: 0.7;">Only responds when @mentioned</div>
904
- </div>
905
- </label>
906
- <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
907
- <input
908
- type="radio"
909
- name="wa-group-mention"
910
- .checked=${!e.whatsappGroupRequireMention}
911
- @change=${()=>e.onWhatsAppGroupMentionChange(!1)}
912
- style="accent-color: #22c55e;"
913
- />
914
- <div>
915
- <div style="font-size: 13px; color: var(--tasker-white);">Always respond</div>
916
- <div style="font-size: 11px; color: var(--tasker-text-grey); opacity: 0.7;">Responds to every message in groups</div>
917
- </div>
918
- </label>
919
- </div>
920
- `:w}
921
- </div>
875
+ <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
876
+ <input
877
+ type="checkbox"
878
+ .checked=${e.whatsappAgentEnabled}
879
+ @change=${e.onWhatsAppAgentEnabledToggle}
880
+ style="accent-color: #22c55e; margin-top: 2px;"
881
+ />
882
+ <div>
883
+ <div style="font-size: 13px; color: var(--tasker-white);">Agent responds</div>
884
+ <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7;">Master switch — configure per-chat activation in the chat view</div>
885
+ </div>
886
+ </label>
922
887
  `:w}
888
+ ${Ig(n,e)}
889
+ ${Rg(e)}
923
890
  <button
924
891
  class="setup-button secondary"
925
892
  style="margin-top: 20px; width: 100%; padding: 10px;"
@@ -929,9 +896,116 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
929
896
  </button>
930
897
  </div>
931
898
  </div>
932
- `}function $a(e){const t=Lt(e),n=e.imessageOwnerWorkspace,i=!!(t&&n===t.name),s=!!(n&&t&&n!==t.name);return{selectedWs:t,ownerWs:n,thisWsOwns:i,anotherWsOwns:s}}function Pg(e){const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=$a(e);let s,o;return i?(s="partial",o=`Connected to ${t}`):n&&e.imessageConnected?(s="good",o="Connected"):n&&e.imessageRunning?(s="partial",o="Running, not connected"):n?(s="bad",o="Not running"):e.imessageConfigured?(s="unknown",o="Not connected"):(s="bad",o="Not configured"),c`
899
+ `}function Ig(e,t){var s,o;if(!e||e.provider!=="cloud")return w;const n=((s=t.tailscaleStatus)==null?void 0:s.publicUrl)??((o=t.tailscaleStatus)==null?void 0:o.tailnetUrl)??null,i=n?`${n}/webhook/whatsapp`:"/webhook/whatsapp";return c`
900
+ <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
901
+ <div style="font-size: 12px; color: var(--tasker-text-grey); margin-bottom: 6px;">Webhook URL (Meta dashboard)</div>
902
+ <div style="display: flex; align-items: center; gap: 6px;">
903
+ <code style="font-size: 11px; background: rgba(255,255,255,0.06); padding: 4px 8px; border-radius: 4px; word-break: break-all; flex: 1;">${i}</code>
904
+ <button
905
+ class="setup-button secondary"
906
+ style="font-size: 11px; padding: 4px 8px; flex-shrink: 0;"
907
+ @click=${()=>navigator.clipboard.writeText(i)}
908
+ >Copy</button>
909
+ </div>
910
+ ${n?w:c`<p style="font-size: 11px; color: #eab308; margin: 6px 0 0;">No public URL detected — enable Tailscale Funnel for Meta to reach this endpoint.</p>`}
911
+ `}function Rg(e){var p,y;const{addingWhatsAppAccount:t,whatsappAccountSaving:n,whatsappAccountError:i}=e;if(!t)return c`
912
+ <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
913
+ <button
914
+ class="setup-button secondary"
915
+ style="width: 100%; padding: 8px; font-size: 12px;"
916
+ @click=${()=>e.onSetAddingWhatsAppAccount(!0)}
917
+ >+ Add WhatsApp Account</button>
918
+ `;const s=e.newWhatsAppAccountProvider==="cloud",o=((p=e.tailscaleStatus)==null?void 0:p.publicUrl)??((y=e.tailscaleStatus)==null?void 0:y.tailnetUrl)??null,a=o?`${o}/webhook/whatsapp`:"https://YOUR-PUBLIC-URL/webhook/whatsapp",r=e.whatsappAccounts.some(x=>!x.provider||x.provider==="baileys"),l="width: 100%; box-sizing: border-box; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.12); border-radius: 6px; color: var(--tasker-white); padding: 8px 10px; font-size: 12px; margin-top: 4px;",d="font-size: 12px; color: var(--tasker-text-grey); display: block; margin-top: 10px;",h=async()=>{const x=e.newWhatsAppAccountName.trim();x&&await e.onAddWhatsAppBaileysAccount(x)},u=async()=>{await e.onAddCloudApiAccount(e.newWhatsAppAccountName,{phoneNumberId:e.newCloudPhoneNumberId,businessAccountId:e.newCloudBusinessAccountId,accessToken:e.newCloudAccessToken,webhookVerifyToken:e.newCloudWebhookVerifyToken})};return c`
919
+ <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
920
+ <div style="font-size: 13px; color: var(--tasker-white); font-weight: 500; margin-bottom: 10px;">Add WhatsApp Account</div>
921
+
922
+ <div style="display: flex; gap: 6px; margin-bottom: 10px;">
923
+ <button
924
+ class="setup-button ${s?"secondary":"primary"}"
925
+ style="flex: 1; font-size: 12px; padding: 6px; ${r?"opacity: 0.4; cursor: not-allowed;":""}"
926
+ ?disabled=${r}
927
+ title=${r?"Only one QR-linked account is supported":""}
928
+ @click=${()=>!r&&e.onSetNewWhatsAppAccountProvider("baileys")}
929
+ >Baileys (QR)</button>
930
+ <button
931
+ class="setup-button ${s?"primary":"secondary"}"
932
+ style="flex: 1; font-size: 12px; padding: 6px; ${o?"":"opacity: 0.4; cursor: not-allowed;"}"
933
+ ?disabled=${!o}
934
+ title=${o?"":"Requires Remote Access (Tailscale Funnel) to be enabled first"}
935
+ @click=${()=>o&&e.onSetNewWhatsAppAccountProvider("cloud")}
936
+ >Cloud API</button>
937
+ </div>
938
+ ${s&&!o?c`<p style="font-size: 11px; color: #eab308; margin: 0 0 8px;">Cloud API requires Remote Access (Tailscale Funnel) so Meta can reach your webhook. Enable it in the Remote Access section first.</p>`:w}
939
+ ${!s&&r?c`<p style="font-size: 11px; color: #eab308; margin: 0 0 8px;">Only one QR-linked account is supported. Use Cloud API (Meta's official API) to add a second number.</p>`:w}
940
+
941
+ <label style="${d}">Account name</label>
942
+ <input
943
+ type="text"
944
+ style="${l}"
945
+ placeholder=${s?"e.g. Business Meta":"e.g. Business"}
946
+ .value=${e.newWhatsAppAccountName}
947
+ @input=${x=>e.onSetNewWhatsAppAccountName(x.target.value)}
948
+ @keydown=${x=>{x.key==="Enter"&&!s&&h()}}
949
+ />
950
+
951
+ ${s?c`
952
+ <label style="${d}">Phone Number ID</label>
953
+ <input
954
+ type="text"
955
+ style="${l}"
956
+ placeholder="12345678901234"
957
+ .value=${e.newCloudPhoneNumberId}
958
+ @input=${x=>e.onSetNewCloudPhoneNumberId(x.target.value)}
959
+ />
960
+ <label style="${d}">Business Account ID <span style="opacity:0.5;">(optional)</span></label>
961
+ <input
962
+ type="text"
963
+ style="${l}"
964
+ placeholder="98765432109876"
965
+ .value=${e.newCloudBusinessAccountId}
966
+ @input=${x=>e.onSetNewCloudBusinessAccountId(x.target.value)}
967
+ />
968
+ <label style="${d}">Access Token</label>
969
+ <input
970
+ type="password"
971
+ style="${l}"
972
+ placeholder="EAAxxxxxxxxxx..."
973
+ .value=${e.newCloudAccessToken}
974
+ @input=${x=>e.onSetNewCloudAccessToken(x.target.value)}
975
+ />
976
+ <label style="${d}">Webhook Verify Token</label>
977
+ <input
978
+ type="text"
979
+ style="${l}"
980
+ placeholder="e.g. tm-xk29mq7r"
981
+ .value=${e.newCloudWebhookVerifyToken}
982
+ @input=${x=>e.onSetNewCloudWebhookVerifyToken(x.target.value)}
983
+ />
984
+ <div style="font-size: 11px; color: var(--tasker-text-grey); margin-top: 8px; line-height: 1.4;">
985
+ Webhook URL for Meta dashboard:<br/>
986
+ <code style="font-size: 10px; background: rgba(255,255,255,0.06); padding: 2px 6px; border-radius: 3px; word-break: break-all;">${a}</code>
987
+ </div>
988
+ `:w}
989
+
990
+ ${i?c`<p style="font-size: 12px; color: #ef4444; margin: 8px 0 0;">${i}</p>`:w}
991
+
992
+ <div style="display: flex; gap: 8px; margin-top: 12px;">
993
+ <button
994
+ class="setup-button primary"
995
+ style="flex: 1; font-size: 12px; padding: 8px;"
996
+ ?disabled=${n||!e.newWhatsAppAccountName.trim()}
997
+ @click=${s?u:h}
998
+ >${n?"Saving…":s?"Add Account":"Add & Scan QR"}</button>
999
+ <button
1000
+ class="setup-button secondary"
1001
+ style="font-size: 12px; padding: 8px 12px;"
1002
+ ?disabled=${n}
1003
+ @click=${()=>e.onSetAddingWhatsAppAccount(!1)}
1004
+ >Cancel</button>
1005
+ </div>
1006
+ `}function $a(e){const t=Rt(e),n=e.imessageOwnerWorkspace,i=!!(t&&n===t.name),s=!!(n&&t&&n!==t.name);return{selectedWs:t,ownerWs:n,thisWsOwns:i,anotherWsOwns:s}}function Lg(e){const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=$a(e);let s,o;return i?(s="partial",o=`Connected to ${t}`):n&&e.imessageConnected?(s="good",o="Connected"):n&&e.imessageRunning?(s="partial",o="Running, not connected"):n?(s="bad",o="Not running"):e.imessageConfigured?(s="unknown",o="Not connected"):(s="bad",o="Not configured"),c`
933
1007
  <div class="setup-status-item" style="flex-wrap: wrap;">
934
- ${Q(s)}
1008
+ ${G(s)}
935
1009
  <div class="setup-status-info">
936
1010
  <strong>iMessage</strong>
937
1011
  <span>${o}</span>
@@ -947,7 +1021,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
947
1021
  </button>
948
1022
  ${w}
949
1023
  </div>
950
- `}function Ig(e){if(!e.imessageEnableConfirm)return w;const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=$a(e),s=()=>{e.onIMessageEnableCancel()};return n?c`
1024
+ `}function Dg(e){if(!e.imessageEnableConfirm)return w;const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=$a(e),s=()=>{e.onIMessageEnableCancel()};return n?c`
951
1025
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&s()}}>
952
1026
  <div class="setup-info-card" style="text-align: center;">
953
1027
  <h3>iMessage</h3>
@@ -1004,7 +1078,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1004
1078
  <div class="setup-info-card" style="text-align: center;">
1005
1079
  <h3>Enable iMessage</h3>
1006
1080
  <p style="color: var(--tasker-text-grey); font-size: 13px; margin: 8px 0 16px;">
1007
- ${Xe().name} will respond to messages in Messages.app for this business.
1081
+ ${Qe().name} will respond to messages in Messages.app for this business.
1008
1082
  </p>
1009
1083
  <button
1010
1084
  class="setup-button primary"
@@ -1023,10 +1097,10 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1023
1097
  </button>
1024
1098
  </div>
1025
1099
  </div>
1026
- `}function Rg(e){if(!e.isMaster)return w;const n=e.apiKeyProviders.filter(i=>i.hasKey).length;return c`
1100
+ `}function Bg(e){if(!e.isMaster)return w;const n=e.apiKeyProviders.filter(i=>i.hasKey).length;return c`
1027
1101
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1028
1102
  <div class="setup-status-item">
1029
- ${Q(n>0?"good":"bad")}
1103
+ ${G(n>0?"good":"bad")}
1030
1104
  <div class="setup-status-info">
1031
1105
  <strong>API Keys</strong>
1032
1106
  <span>${n} configured</span>
@@ -1038,8 +1112,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1038
1112
  >Manage</button>
1039
1113
  </div>
1040
1114
  </div>
1041
- ${Lg(e)}
1042
- `}function Lg(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"),y=p==null?void 0:p.value.trim();!y||y===n[d]||e.onApiKeySave(d,y)},s=d=>{const h=d.currentTarget,u=h.closest(".setup-apikey-input"),p=u==null?void 0:u.querySelector("input");if(!p)return;const y=p.type==="text";p.type=y?"password":"text",h.classList.toggle("active",!y)},o=(d,h)=>{const u=h.target,p=u.closest(".setup-apikey-input"),y=u.value.trim(),$=y.length>0&&y!==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=y.length>0?"":"none")},a=t.filter(d=>d.primary),r=t.filter(d=>!d.primary),l=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`,y=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} disabled`,$=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} enabled`;return c`
1115
+ ${Ng(e)}
1116
+ `}function Ng(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"),y=p==null?void 0:p.value.trim();!y||y===n[d]||e.onApiKeySave(d,y)},s=d=>{const h=d.currentTarget,u=h.closest(".setup-apikey-input"),p=u==null?void 0:u.querySelector("input");if(!p)return;const y=p.type==="text";p.type=y?"password":"text",h.classList.toggle("active",!y)},o=(d,h)=>{const u=h.target,p=u.closest(".setup-apikey-input"),y=u.value.trim(),x=y.length>0&&y!==n[d],S=p==null?void 0:p.querySelector(".setup-apikey-save");S&&(S.style.display=x?"":"none");const _=p==null?void 0:p.querySelector(".setup-apikey-eye");_&&(_.style.display=y.length>0?"":"none")},a=t.filter(d=>d.primary),r=t.filter(d=>!d.primary),l=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`,y=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} disabled`,x=!e.apiKeyBusy&&e.apiKeySuccess===`${d.id} enabled`;return c`
1043
1117
  <div class="setup-apikey-row ${d.disabled?"disabled":""}">
1044
1118
  <div class="setup-apikey-info">
1045
1119
  <strong>${d.name}</strong>
@@ -1047,8 +1121,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1047
1121
  ${u?c`<span class="setup-apikey-badge saved">Saved</span>`:w}
1048
1122
  ${p?c`<span class="setup-apikey-badge removed">Removed</span>`:w}
1049
1123
  ${y?c`<span class="setup-apikey-badge removed">Disabled</span>`:w}
1050
- ${$?c`<span class="setup-apikey-badge saved">Enabled</span>`:w}
1051
- ${d.disabled&&!$?c`<span class="setup-apikey-badge apikey-disabled">Off</span>`:w}
1124
+ ${x?c`<span class="setup-apikey-badge saved">Enabled</span>`:w}
1125
+ ${d.disabled&&!x?c`<span class="setup-apikey-badge apikey-disabled">Off</span>`:w}
1052
1126
  </div>
1053
1127
  <div class="setup-apikey-input">
1054
1128
  <input
@@ -1103,9 +1177,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1103
1177
  </div>
1104
1178
  </div>
1105
1179
  </div>
1106
- `}function Dg(e){const t=e.updateAvailable===null?"unknown":e.updateAvailable?"partial":"good",n=e.updateAvailable&&e.latestVersion?`v${e.currentVersion} → v${e.latestVersion}`:e.currentVersion?`v${e.currentVersion}`:"Unknown",i=e.updateChecking||e.updateRunning;return c`
1180
+ `}function Og(e){const t=e.updateAvailable===null?"unknown":e.updateAvailable?"partial":"good",n=e.updateAvailable&&e.latestVersion?`v${e.currentVersion} → v${e.latestVersion}`:e.currentVersion?`v${e.currentVersion}`:"Unknown",i=e.updateChecking||e.updateRunning;return c`
1107
1181
  <div class="setup-status-item">
1108
- ${Q(t)}
1182
+ ${G(t)}
1109
1183
  <div class="setup-status-info">
1110
1184
  <strong>Software</strong>
1111
1185
  <span>${n}</span>
@@ -1131,9 +1205,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1131
1205
  </button>
1132
1206
  `}
1133
1207
  </div>
1134
- `}const Bg={anonymous:"Open access",verified:"Phone OTP",choice:"Visitor chooses"};function Ng(e){const t=e.publicChatEnabled;return c`
1208
+ `}const Fg={anonymous:"Open access",verified:"Phone OTP",choice:"Visitor chooses"};function Ug(e){const t=e.publicChatEnabled;return c`
1135
1209
  <div class="setup-status-item">
1136
- ${Q(t?"good":"unknown")}
1210
+ ${G(t?"good":"unknown")}
1137
1211
  <div class="setup-status-info">
1138
1212
  <strong>Public Chat</strong>
1139
1213
  <span>${t?"Enabled":"Disabled"}</span>
@@ -1151,7 +1225,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1151
1225
  @click=${e.onPublicChatToggle}
1152
1226
  >${t?I.powerOff:I.power}</button>
1153
1227
  </div>
1154
- `}function Og(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"),l=Lt(e),d=l?fs(l,e):null,h=!!(d!=null&&d.connected);return c`
1228
+ `}function Wg(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"),l=Rt(e),d=l?fs(l,e):null,h=!!(d!=null&&d.connected);return c`
1155
1229
  <div class="setup-info-overlay" @click=${u=>{u.target.classList.contains("setup-info-overlay")&&t()}}>
1156
1230
  <div class="setup-info-card" style="max-width: 380px; max-height: 80vh; overflow-y: auto;">
1157
1231
  <h3 style="margin: 0 0 12px; display: flex; align-items: center; justify-content: space-between;">
@@ -1227,7 +1301,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1227
1301
  type="checkbox"
1228
1302
  .checked=${o&&h}
1229
1303
  ?disabled=${!h||e.publicChatEmailBusy||!a&&!r&&o}
1230
- @change=${u=>{const y=u.target.checked?[...s.filter($=>$!=="whatsapp"),"whatsapp"]:s.filter($=>$!=="whatsapp");y.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,y)}}
1304
+ @change=${u=>{const y=u.target.checked?[...s.filter(x=>x!=="whatsapp"),"whatsapp"]:s.filter(x=>x!=="whatsapp");y.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,y)}}
1231
1305
  style="accent-color: #22c55e; margin-top: 2px;"
1232
1306
  />
1233
1307
  <div>
@@ -1242,7 +1316,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1242
1316
  type="checkbox"
1243
1317
  .checked=${a}
1244
1318
  ?disabled=${e.publicChatEmailBusy||!o&&!r&&a}
1245
- @change=${u=>{const y=u.target.checked?[...s.filter($=>$!=="sms"),"sms"]:s.filter($=>$!=="sms");y.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,y)}}
1319
+ @change=${u=>{const y=u.target.checked?[...s.filter(x=>x!=="sms"),"sms"]:s.filter(x=>x!=="sms");y.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,y)}}
1246
1320
  style="accent-color: #22c55e; margin-top: 2px;"
1247
1321
  />
1248
1322
  <div>
@@ -1255,7 +1329,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1255
1329
  type="checkbox"
1256
1330
  .checked=${r}
1257
1331
  ?disabled=${e.publicChatEmailBusy||!o&&!a&&r}
1258
- @change=${u=>{const y=u.target.checked?[...s.filter($=>$!=="email"),"email"]:s.filter($=>$!=="email");y.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,y)}}
1332
+ @change=${u=>{const y=u.target.checked?[...s.filter(x=>x!=="email"),"email"]:s.filter(x=>x!=="email");y.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,y)}}
1259
1333
  style="accent-color: #22c55e; margin-top: 2px;"
1260
1334
  />
1261
1335
  <div>
@@ -1279,7 +1353,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1279
1353
  </div>
1280
1354
  </div>
1281
1355
  </div>
1282
- `}function Fg(e){var r,l;if(!e.publicChatWidgetModalOpen)return w;const t=((r=e.tailscaleStatus)==null?void 0:r.publicUrl)??((l=e.tailscaleStatus)==null?void 0:l.tailnetUrl)??null,n=e.publicChatAccountId??"your-account-id",i=t??"https://YOUR-PUBLIC-URL",s=`<script src="${i}/public/widget.js"><\/script>
1356
+ `}function zg(e){var r,l;if(!e.publicChatWidgetModalOpen)return w;const t=((r=e.tailscaleStatus)==null?void 0:r.publicUrl)??((l=e.tailscaleStatus)==null?void 0:l.tailnetUrl)??null,n=e.publicChatAccountId??"your-account-id",i=t??"https://YOUR-PUBLIC-URL",s=`<script src="${i}/public/widget.js"><\/script>
1283
1357
  <script>
1284
1358
  Taskmaster.init({
1285
1359
  server: "${i}",
@@ -1309,21 +1383,21 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1309
1383
  </div>
1310
1384
  </div>
1311
1385
  </div>
1312
- `}const kd=[{id:"claude-opus-4-6",shortName:"Opus",description:"Most capable"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet",description:"Fast & capable"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku",description:"Fastest"}],Ug=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],Wg="anthropic/claude-sonnet-4-5-20250929";function zg(e){const t=e.agentSettingsAgents??[],n=t.length>0?t.map(i=>{var o;return i.model?((o=kd.find(a=>i.model===`anthropic/${a.id}`))==null?void 0:o.shortName)??i.model.split("/").pop():"Sonnet"}).join(" / "):"Default";return c`
1386
+ `}const xd=[{id:"claude-opus-4-6",shortName:"Opus",description:"Most capable"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet",description:"Fast & capable"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku",description:"Fastest"}],Kg=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],Hg="anthropic/claude-sonnet-4-5-20250929";function qg(e){const t=e.agentSettingsAgents??[],n=t.length>0?t.map(i=>{var o;return i.model?((o=xd.find(a=>i.model===`anthropic/${a.id}`))==null?void 0:o.shortName)??i.model.split("/").pop():"Sonnet"}).join(" / "):"Default";return c`
1313
1387
  <div class="setup-status-item">
1314
- ${Q("good")}
1388
+ ${G("good")}
1315
1389
  <div class="setup-status-info">
1316
1390
  <strong>Agents</strong>
1317
1391
  <span>${n}</span>
1318
1392
  </div>
1319
1393
  <button class="setup-link-btn" @click=${e.onAgentSettingsToggle}>Edit</button>
1320
1394
  </div>
1321
- `}function Kg(e){if(!e.agentSettingsOpen)return w;const t=e.agentSettingsAgents??[];if(t.length===0)return w;const n=e.agentSettingsModelCatalog??[],i=new Set(n.filter(a=>a.provider==="anthropic").map(a=>a.id)),s=kd.filter(a=>i.has(a.id)),o=()=>e.onAgentSettingsToggle();return c`
1395
+ `}function jg(e){if(!e.agentSettingsOpen)return w;const t=e.agentSettingsAgents??[];if(t.length===0)return w;const n=e.agentSettingsModelCatalog??[],i=new Set(n.filter(a=>a.provider==="anthropic").map(a=>a.id)),s=xd.filter(a=>i.has(a.id)),o=()=>e.onAgentSettingsToggle();return c`
1322
1396
  <div class="setup-info-overlay" @click=${a=>{a.target.classList.contains("setup-info-overlay")&&o()}}>
1323
1397
  <div class="setup-info-card" style="max-width: 400px;">
1324
1398
  <h3>Agent Settings</h3>
1325
1399
  <div style="display: flex; flex-direction: column; gap: 20px; margin-top: 16px;">
1326
- ${t.map(a=>{const r=a.model??Wg,l=a.thinkingLevel??"off",d=a.id.endsWith("-admin")||a.id==="admin";return c`
1400
+ ${t.map(a=>{const r=a.model??Hg,l=a.thinkingLevel??"off",d=a.id.endsWith("-admin")||a.id==="admin";return c`
1327
1401
  <div style="display: flex; flex-direction: column; gap: 10px;">
1328
1402
  <div style="font-size: 14px; font-weight: 600; color: var(--tasker-white);">
1329
1403
  ${a.label||(d?"Admin":"Public")}
@@ -1353,7 +1427,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1353
1427
  .value=${l}
1354
1428
  @change=${h=>{e.onAgentThinkingChange(a.id,h.target.value)}}
1355
1429
  >
1356
- ${Ug.map(h=>c`
1430
+ ${Kg.map(h=>c`
1357
1431
  <option value=${h.value} ?selected=${l===h.value}>
1358
1432
  ${h.label}
1359
1433
  </option>
@@ -1406,9 +1480,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1406
1480
  </button>
1407
1481
  </div>
1408
1482
  </div>
1409
- `}function Hg(e){const t=!!(e.brandAccentColor||e.brandBackgroundColor||e.brandHasLogo),n=t?"good":"unknown",i=e.brandingBusy;return c`
1483
+ `}function Vg(e){const t=!!(e.brandAccentColor||e.brandBackgroundColor||e.brandHasLogo),n=t?"good":"unknown",i=e.brandingBusy;return c`
1410
1484
  <div class="setup-status-item">
1411
- ${Q(n)}
1485
+ ${G(n)}
1412
1486
  <div class="setup-status-info">
1413
1487
  <strong>Branding</strong>
1414
1488
  <span>${t?"Customised":"Default"}</span>
@@ -1420,7 +1494,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1420
1494
  @click=${e.onBrandingToggle}
1421
1495
  >${i?"...":"Edit"}</button>
1422
1496
  </div>
1423
- `}function qg(e){var s;if(!e.brandingExpanded)return w;const t=e.brandingBusy,n=(s=e.wsProps)==null?void 0:s.selectedWorkspace,i=e.brandHasLogo&&n?`/brand-logo/${encodeURIComponent(n)}`:"";return c`
1497
+ `}function Gg(e){var s;if(!e.brandingExpanded)return w;const t=e.brandingBusy,n=(s=e.wsProps)==null?void 0:s.selectedWorkspace,i=e.brandHasLogo&&n?`/brand-logo/${encodeURIComponent(n)}`:"";return c`
1424
1498
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onBrandingToggle()}}>
1425
1499
  <div class="setup-info-card" style="max-width: 400px; position: relative;">
1426
1500
  <h3 style="margin-right: 24px;">Branding</h3>
@@ -1501,7 +1575,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1501
1575
 
1502
1576
  </div>
1503
1577
  </div>
1504
- `}function jg(e){const t=e.tailscaleBusy,n=e.tailscaleAuthUrl,i=e.tailscaleError,s=e.tailscaleConnectSuccess,o=e.tailscaleConnectProgress,a=e.tailscaleConnectMessage;return!t&&!s&&!i?w:i&&!t?c`
1578
+ `}function Qg(e){const t=e.tailscaleBusy,n=e.tailscaleAuthUrl,i=e.tailscaleError,s=e.tailscaleConnectSuccess,o=e.tailscaleConnectProgress,a=e.tailscaleConnectMessage;return!t&&!s&&!i?w:i&&!t?c`
1505
1579
  <div class="setup-info-overlay" @click=${r=>{r.target.classList.contains("setup-info-overlay")&&e.onTailscaleErrorDismiss()}}>
1506
1580
  <div class="setup-info-card" style="max-width: 380px; text-align: center;">
1507
1581
  <h3>Remote Access</h3>
@@ -1568,9 +1642,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1568
1642
  <p style="font-size: 14px; color: var(--tasker-text-grey); margin: 12px 0 0;">${a}</p>
1569
1643
  </div>
1570
1644
  </div>
1571
- `}function Gg(e){if(!e.isMaster)return w;const t=e.tailscaleStatus,n=e.tailscaleBusy,i=e.tailscaleAuthUrl;if(!t)return c`
1645
+ `}function Jg(e){if(!e.isMaster)return w;const t=e.tailscaleStatus,n=e.tailscaleBusy,i=e.tailscaleAuthUrl;if(!t)return c`
1572
1646
  <div class="setup-status-item">
1573
- ${Q("unknown")}
1647
+ ${G("unknown")}
1574
1648
  <div class="setup-status-info">
1575
1649
  <strong>Remote Access</strong>
1576
1650
  <span>Checking...</span>
@@ -1579,7 +1653,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1579
1653
  </div>
1580
1654
  `;if(!t.installed)return c`
1581
1655
  <div class="setup-status-item">
1582
- ${Q("unknown")}
1656
+ ${G("unknown")}
1583
1657
  <div class="setup-status-info">
1584
1658
  <strong>Remote Access</strong>
1585
1659
  <span>Tailscale not installed</span>
@@ -1588,7 +1662,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1588
1662
  </div>
1589
1663
  `;if(i||!t.loggedIn)return c`
1590
1664
  <div class="setup-status-item">
1591
- ${Q("partial")}
1665
+ ${G("partial")}
1592
1666
  <div class="setup-status-info">
1593
1667
  <strong>Remote Access</strong>
1594
1668
  <span>${n?"Connecting...":"Not connected"}</span>
@@ -1602,7 +1676,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1602
1676
  </div>
1603
1677
  `;if(!t.serveEnabled){const a=e.tailscaleServeEnableUrl;return c`
1604
1678
  <div class="setup-status-item" style="flex-wrap: wrap;">
1605
- ${Q("partial")}
1679
+ ${G("partial")}
1606
1680
  <div class="setup-status-info">
1607
1681
  <strong>Remote Access</strong>
1608
1682
  <span>Connected (not enabled)</span>
@@ -1628,7 +1702,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1628
1702
  </div>
1629
1703
  `}if(!t.serveActive)return c`
1630
1704
  <div class="setup-status-item" style="flex-wrap: wrap;">
1631
- ${Q("bad")}
1705
+ ${G("bad")}
1632
1706
  <div class="setup-status-info">
1633
1707
  <strong>Remote Access</strong>
1634
1708
  <span>Enabled but not active</span>
@@ -1665,7 +1739,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1665
1739
  >Open Tailscale admin to enable Funnel &rarr;</a>
1666
1740
  </div>`:e.tailscaleError?c`<p style="flex-basis: 100%; margin: 6px 0 0; font-size: 13px; color: #ef4444;">${e.tailscaleError}</p>`:w;return c`
1667
1741
  <div class="setup-status-item" style="flex-wrap: wrap;">
1668
- ${Q("good")}
1742
+ ${G("good")}
1669
1743
  <div class="setup-status-info">
1670
1744
  <strong>Remote Access</strong>
1671
1745
  <span>Active</span>
@@ -1699,9 +1773,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1699
1773
  background: ${s<t?"var(--tasker-accent, #00e5ff)":"rgba(255,255,255,0.15)"};
1700
1774
  "></span>`)}
1701
1775
  </span>
1702
- `}function Vg(e){if(e.serverPlatform!=="linux")return w;const t=e.wifiStatus,n=e.wifiBusy;if(!t)return c`
1776
+ `}function Yg(e){if(e.serverPlatform!=="linux")return w;const t=e.wifiStatus,n=e.wifiBusy;if(!t)return c`
1703
1777
  <div class="setup-status-item">
1704
- ${Q("unknown")}
1778
+ ${G("unknown")}
1705
1779
  <div class="setup-status-info">
1706
1780
  <strong>WiFi</strong>
1707
1781
  <span>Checking...</span>
@@ -1709,7 +1783,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1709
1783
  </div>
1710
1784
  `;if(!t.available)return c`
1711
1785
  <div class="setup-status-item">
1712
- ${Q("unknown")}
1786
+ ${G("unknown")}
1713
1787
  <div class="setup-status-info">
1714
1788
  <strong>WiFi</strong>
1715
1789
  <span>NetworkManager not available</span>
@@ -1717,7 +1791,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1717
1791
  </div>
1718
1792
  `;const i=!!t.savedSsid&&!t.connected,s=t.connected?"good":"partial",o=t.connected?c`${t.ssid} ${t.signal!=null?c`<span style="margin-left: 4px;">${Io(t.signal)}</span>`:w}`:i?c`${t.savedSsid} <span style="opacity: 0.4;">\u2014 reconnecting\u2026</span>`:"Not connected";return c`
1719
1793
  <div class="setup-status-item">
1720
- ${Q(s)}
1794
+ ${G(s)}
1721
1795
  <div class="setup-status-info">
1722
1796
  <strong>WiFi</strong>
1723
1797
  <span>${o}</span>
@@ -1729,7 +1803,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1729
1803
  @click=${e.onWifiModalToggle}
1730
1804
  >${n?"...":"Edit"}</button>
1731
1805
  </div>
1732
- `}function Qg(e){if(!e.wifiModalOpen)return w;const t=e.wifiStatus,n=e.wifiBusy,i=e.wifiNetworks,s=e.wifiSelectedSsid;return c`
1806
+ `}function Xg(e){if(!e.wifiModalOpen)return w;const t=e.wifiStatus,n=e.wifiBusy,i=e.wifiNetworks,s=e.wifiSelectedSsid;return c`
1733
1807
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onWifiModalToggle()}}>
1734
1808
  <div class="setup-info-card" style="max-width: 420px; position: relative;">
1735
1809
  <h3 style="margin-right: 24px;">WiFi</h3>
@@ -1841,9 +1915,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1841
1915
  `:w}
1842
1916
  </div>
1843
1917
  </div>
1844
- `}function Jg(e){return e.isMaster?e.networkPort==null?c`
1918
+ `}function Zg(e){return e.isMaster?e.networkPort==null?c`
1845
1919
  <div class="setup-status-item">
1846
- ${Q("unknown")}
1920
+ ${G("unknown")}
1847
1921
  <div class="setup-status-info">
1848
1922
  <strong>Network</strong>
1849
1923
  <span>Loading...</span>
@@ -1851,7 +1925,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1851
1925
  </div>
1852
1926
  `:c`
1853
1927
  <div class="setup-status-item">
1854
- ${Q("good")}
1928
+ ${G("good")}
1855
1929
  <div class="setup-status-info">
1856
1930
  <strong>Network</strong>
1857
1931
  <span>${e.networkHostname}.local:${e.networkPort}</span>
@@ -1862,7 +1936,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1862
1936
  @click=${e.onNetworkModalToggle}
1863
1937
  >Edit</button>
1864
1938
  </div>
1865
- `:w}function Yg(e){if(!e.networkModalOpen)return w;const t=e.networkBusy,n=e.networkPortInput!==String(e.networkPort),i=e.networkHostnameInput!==e.networkHostname,s=n||i;return c`
1939
+ `:w}function em(e){if(!e.networkModalOpen)return w;const t=e.networkBusy,n=e.networkPortInput!==String(e.networkPort),i=e.networkHostnameInput!==e.networkHostname,s=n||i;return c`
1866
1940
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onNetworkModalToggle()}}>
1867
1941
  <div class="setup-info-card" style="max-width: 400px; position: relative;">
1868
1942
  <h3 style="margin-right: 24px;">Network</h3>
@@ -1932,7 +2006,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1932
2006
  </div>
1933
2007
  </div>
1934
2008
  </div>
1935
- `}function Xg(e){var i,s,o;const t=e.updateRunning,n=e.updateLastResult;if(!t&&!n)return w;if(t)return c`
2009
+ `}function tm(e){var i,s,o;const t=e.updateRunning,n=e.updateLastResult;if(!t&&!n)return w;if(t)return c`
1936
2010
  <div class="setup-info-overlay">
1937
2011
  <div class="setup-info-card" style="max-width: 400px;">
1938
2012
  <h3>Software Update</h3>
@@ -1972,9 +2046,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1972
2046
  </button>
1973
2047
  </div>
1974
2048
  </div>
1975
- `}return w}function Nr(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Zg(e){const t=e.accountHasPin;return c`
2049
+ `}return w}function Nr(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function nm(e){const t=e.accountHasPin;return c`
1976
2050
  <div class="setup-status-item">
1977
- ${Q(t?"good":"bad")}
2051
+ ${G(t?"good":"bad")}
1978
2052
  <div class="setup-status-info">
1979
2053
  <strong>Account PIN</strong>
1980
2054
  <span>${t?"Set":"Not set"}</span>
@@ -1985,7 +2059,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1985
2059
  @click=${()=>e.onAccountPinModalOpen()}
1986
2060
  >${t?"Change":"Set PIN"}</button>
1987
2061
  </div>
1988
- `}function em(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},l=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 c`
2062
+ `}function im(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},l=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 c`
1989
2063
  <div class="setup-info-overlay" @click=${d=>{d.target.classList.contains("setup-info-overlay")&&e.onAccountPinModalClose()}}>
1990
2064
  <div class="setup-info-card" style="max-width: 340px;">
1991
2065
  <div class="setup-info-header">
@@ -2042,7 +2116,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2042
2116
  </form>
2043
2117
  </div>
2044
2118
  </div>
2045
- `}function tm(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 l=r.type==="text";r.type=l?"password":"text",o.classList.toggle("active",!l)};return c`
2119
+ `}function sm(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 l=r.type==="text";r.type=l?"password":"text",o.classList.toggle("active",!l)};return c`
2046
2120
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
2047
2121
  <div class="setup-add-account">
2048
2122
  <strong>New Account</strong>
@@ -2105,7 +2179,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2105
2179
  </div>
2106
2180
  </div>
2107
2181
  </div>
2108
- `}function nm(e){const t=Lt(e);return!t||t.isDefault?w:e.workspaceRemoveConfirm===t.name?c`
2182
+ `}function om(e){const t=Rt(e);return!t||t.isDefault?w:e.workspaceRemoveConfirm===t.name?c`
2109
2183
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 12px;">
2110
2184
  <div style="font-size: 13px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
2111
2185
  <span style="color: var(--tasker-danger, #ef4444);">Remove "${t.displayName??t.name}" and its WhatsApp account?</span>
@@ -2134,7 +2208,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2134
2208
  @click=${i=>{i.preventDefault(),e.onSetWorkspaceRemoveConfirm(t.name)}}
2135
2209
  >Remove Account</a>
2136
2210
  </p>
2137
- `}function im(e){if(e.uninstallDone)return c`
2211
+ `}function am(e){if(e.uninstallDone)return c`
2138
2212
  <div style="margin-top: 24px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
2139
2213
  <p style="color: var(--tasker-danger, #ef4444); font-size: 13px; font-weight: 600; margin: 0 0 8px 0;">
2140
2214
  Taskmaster has been uninstalled.
@@ -2189,11 +2263,11 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2189
2263
  @click=${t=>{t.preventDefault(),e.onUninstallConfirm()}}
2190
2264
  >Uninstall Taskmaster</a>
2191
2265
  </p>
2192
- `}function sm(){return c`
2266
+ `}function rm(){return c`
2193
2267
  <p class="setup-hint" style="margin-top: 4px; font-size: 12px; opacity: 0.6;">
2194
2268
  Need help? <a href="https://wa.me/447591215452" target="_blank" rel="noopener" style="color: var(--tasker-orange);">Message Tuesday on WhatsApp</a>
2195
2269
  </p>
2196
- `}function om(e){const{whatsappBusy:t,whatsappLoginMessage:n,whatsappLoginQrDataUrl:i,whatsappLoginConnected:s,whatsappChannelStatus:o}=e;if(i)return c`
2270
+ `}function lm(e){const{whatsappBusy:t,whatsappLoginMessage:n,whatsappLoginQrDataUrl:i,whatsappLoginConnected:s,whatsappChannelStatus:o}=e;if(i)return c`
2197
2271
  <div class="setup-container">
2198
2272
  <div class="setup-card">
2199
2273
  <h1>Scan with WhatsApp</h1>
@@ -2207,7 +2281,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2207
2281
  Scan the code above with your phone
2208
2282
  </p>`}
2209
2283
  <p class="setup-hint" style="margin-top: 16px;">
2210
- <strong>Important:</strong> If you see "${Xe().name}" in your Linked
2284
+ <strong>Important:</strong> If you see "${Qe().name}" in your Linked
2211
2285
  Devices, remove it first before scanning.
2212
2286
  </p>
2213
2287
  <div class="setup-actions" style="margin-top: 24px;">
@@ -2230,44 +2304,44 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2230
2304
  `;const a=(o==null?void 0:o.running)&&(o==null?void 0:o.connected);if(o){const h=(e.whatsappAccounts.length>1?e.whatsappAccounts.every(u=>u.running&&u.connected):a)&&e.authConnected;return c`
2231
2305
  <div class="setup-container">
2232
2306
  <div class="setup-card ${h?"setup-success":""} setup-dashboard-wide">
2233
- ${Ag(e)}
2307
+ ${Cg(e)}
2234
2308
  <div class="setup-status-dashboard">
2235
- ${Cg(e)}
2236
2309
  ${Eg(e)}
2237
2310
  ${Tg(e)}
2238
2311
  ${_g(e)}
2239
- ${e.serverPlatform==="darwin"?Pg(e):w}
2240
- ${zg(e)}
2241
- ${Zg(e)}
2242
- ${Dg(e)}
2243
- ${Ng(e)}
2244
- ${Hg(e)}
2245
- ${Gg(e)}
2246
- ${Jg(e)}
2312
+ ${Mg(e)}
2313
+ ${e.serverPlatform==="darwin"?Lg(e):w}
2314
+ ${qg(e)}
2315
+ ${nm(e)}
2316
+ ${Og(e)}
2317
+ ${Ug(e)}
2247
2318
  ${Vg(e)}
2319
+ ${Jg(e)}
2320
+ ${Zg(e)}
2321
+ ${Yg(e)}
2248
2322
  </div>
2249
2323
 
2250
- ${Kg(e)}
2251
- ${em(e)}
2252
- ${qg(e)}
2253
- ${Og(e)}
2254
- ${Yg(e)}
2255
- ${Qg(e)}
2256
2324
  ${jg(e)}
2257
- ${Rg(e)}
2258
- ${tm(e)}
2259
- ${nm(e)}
2260
2325
  ${im(e)}
2261
- ${sm()}
2326
+ ${Gg(e)}
2327
+ ${Wg(e)}
2328
+ ${em(e)}
2329
+ ${Xg(e)}
2330
+ ${Qg(e)}
2331
+ ${Bg(e)}
2332
+ ${sm(e)}
2333
+ ${om(e)}
2334
+ ${am(e)}
2335
+ ${rm()}
2262
2336
  ${e.workspacesError?c`<p class="setup-error" style="margin-top: 8px;">${e.workspacesError}</p>`:w}
2263
2337
  </div>
2264
2338
  </div>
2265
2339
  `}return o?s===!1&&n&&!t?c`
2266
2340
  <div class="setup-container">
2267
2341
  <div class="setup-card">
2268
- ${_e("setup")}
2342
+ ${Ee("setup")}
2269
2343
  <div class="setup-status-row">
2270
- ${Q("bad")}
2344
+ ${G("bad")}
2271
2345
  <span>Connection Failed</span>
2272
2346
  </div>
2273
2347
  <p class="setup-error">${n}</p>
@@ -2283,7 +2357,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2283
2357
  `:c`
2284
2358
  <div class="setup-container">
2285
2359
  <div class="setup-card">
2286
- ${_e("setup")}
2360
+ ${Ee("setup")}
2287
2361
  ${n?c`<p class="setup-error">${n}</p>`:c`<div class="setup-spinner"></div>
2288
2362
  <p>Preparing...</p>`}
2289
2363
  </div>
@@ -2291,7 +2365,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2291
2365
  `:c`
2292
2366
  <div class="setup-container">
2293
2367
  <div class="setup-card">
2294
- ${_e("setup")}
2368
+ ${Ee("setup")}
2295
2369
  <div class="setup-spinner"></div>
2296
2370
  <p>Checking connection status...</p>
2297
2371
  <button
@@ -2303,7 +2377,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2303
2377
  </button>
2304
2378
  </div>
2305
2379
  </div>
2306
- `}function am(e){if(!e.claudeAuthModalOpen)return w;const t=()=>e.onClaudeAuthModalClose(),n=e.authConnected===!0;return c`
2380
+ `}function cm(e){if(!e.claudeAuthModalOpen)return w;const t=()=>e.onClaudeAuthModalClose(),n=e.authConnected===!0;return c`
2307
2381
  <div class="setup-info-overlay" @click=${i=>{i.target.classList.contains("setup-info-overlay")&&t()}}>
2308
2382
  <div class="setup-info-card" style="max-width: 420px;">
2309
2383
  <h3>${n?"Claude Connected":"Connect to Claude"}</h3>
@@ -2311,7 +2385,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2311
2385
  ${n?c`
2312
2386
  <div style="margin: 12px 0;">
2313
2387
  <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
2314
- ${Q("good")}
2388
+ ${G("good")}
2315
2389
  <span style="font-size: 14px;">Connected</span>
2316
2390
  ${e.authExpiresIn?c`<span style="color: var(--tasker-text-grey); font-size: 12px;">(expires in ${e.authExpiresIn}m)</span>`:w}
2317
2391
  </div>
@@ -2399,7 +2473,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2399
2473
  </button>
2400
2474
  </div>
2401
2475
  </div>
2402
- `}function rm(e){const{connected:t,currentStep:n}=e;if(t&&qi()&&ka(),e.uninstallDone||!t&&qi())return c`
2476
+ `}function dm(e){const{connected:t,currentStep:n}=e;if(t&&qi()&&ka(),e.uninstallDone||!t&&qi())return c`
2403
2477
  <div class="setup-container">
2404
2478
  <div class="setup-card">
2405
2479
  <p style="color: var(--tasker-danger, #ef4444); font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
@@ -2422,7 +2496,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2422
2496
  <p>${o?"Restarting gateway after update…":"Connecting to gateway..."}</p>
2423
2497
  </div>
2424
2498
  </div>
2425
- `}let i;switch(n){case"license":i=Br(e);break;case"auth":i=Sg(e);break;case"setup":i=om(e);break;default:i=Br(e)}const s=Rt("Setup",e.wsProps);return c`${i}${$g(e)}${am(e)}${Ig(e)}${Mg(e)}${Xg(e)}${Fg(e)}${s}`}function lm(e,t){const n=e.paired?"Paired phone (used to link WhatsApp)":"Admin access via WhatsApp DM";return c`
2499
+ `}let i;switch(n){case"license":i=Br(e);break;case"auth":i=Ag(e);break;case"setup":i=lm(e);break;default:i=Br(e)}const s=It("Setup",e.wsProps);return c`${i}${Sg(e)}${cm(e)}${Dg(e)}${Pg(e)}${tm(e)}${zg(e)}${s}`}function um(e,t){const n=e.paired?"Paired phone (used to link WhatsApp)":"Admin access via WhatsApp DM";return c`
2426
2500
  <div class="sp-list-item">
2427
2501
  <div class="sp-list-item-main">
2428
2502
  <div class="sp-list-item-title">${e.phone}</div>
@@ -2437,7 +2511,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2437
2511
  Remove
2438
2512
  </button>`}
2439
2513
  </div>
2440
- `}function cm(e){if(!e.connected)return c`
2514
+ `}function pm(e){if(!e.connected)return c`
2441
2515
  <div class="setup-container">
2442
2516
  <div class="setup-card">
2443
2517
  <div class="setup-spinner"></div>
@@ -2446,7 +2520,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2446
2520
  </div>
2447
2521
  `;const t=n=>{n.preventDefault(),e.newPhone.trim()&&e.onAdd(e.newPhone)};return c`
2448
2522
  <div class="setup-container">
2449
- ${Rt("Admins",e.wsProps)}
2523
+ ${It("Admins",e.wsProps)}
2450
2524
  <div class="setup-card" style="max-width: 520px;">
2451
2525
  <h1>Admin Phones</h1>
2452
2526
  <p style="margin-bottom: 16px;">
@@ -2486,7 +2560,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2486
2560
  </form>
2487
2561
 
2488
2562
  <div class="sp-list" style="margin-top: 20px;">
2489
- ${e.phones.length===0?c`<div class="sp-list-empty">No admin phones configured yet.</div>`:e.phones.map(n=>lm(n,e))}
2563
+ ${e.phones.length===0?c`<div class="sp-list-empty">No admin phones configured yet.</div>`:e.phones.map(n=>um(n,e))}
2490
2564
  </div>
2491
2565
 
2492
2566
  <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
@@ -2497,13 +2571,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2497
2571
 
2498
2572
  </div>
2499
2573
  </div>
2500
- `}const xd=c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`;function dm(e){return Object.keys(e.fields).length}function um(e,t){return c`
2574
+ `}const $d=c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`;function hm(e){return Object.keys(e.fields).length}function fm(e,t){return c`
2501
2575
  <div class="event-modal-overlay" @click=${t.onDeleteConfirmClose}>
2502
2576
  <div class="event-modal" style="width: min(400px, 100%);" @click=${n=>n.stopPropagation()}>
2503
2577
  <div class="event-modal__header">
2504
2578
  <div class="event-modal__title">Delete Contact</div>
2505
2579
  <button class="event-modal__close" @click=${t.onDeleteConfirmClose}>
2506
- ${xd}
2580
+ ${$d}
2507
2581
  </button>
2508
2582
  </div>
2509
2583
  <p style="margin: 0 0 8px; color: rgba(255,255,255,0.7); font-size: 14px; line-height: 1.5;">
@@ -2529,13 +2603,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2529
2603
  </div>
2530
2604
  </div>
2531
2605
  </div>
2532
- `}function pm(e,t){const n=t.addFieldKey.trim().length>0,i=s=>{s.preventDefault(),n&&t.onAddFieldSubmit()};return c`
2606
+ `}function gm(e,t){const n=t.addFieldKey.trim().length>0,i=s=>{s.preventDefault(),n&&t.onAddFieldSubmit()};return c`
2533
2607
  <div class="event-modal-overlay" @click=${t.onAddFieldClose}>
2534
2608
  <div class="event-modal" style="width: min(400px, 100%);" @click=${s=>s.stopPropagation()}>
2535
2609
  <div class="event-modal__header">
2536
2610
  <div class="event-modal__title">Add Field</div>
2537
2611
  <button class="event-modal__close" @click=${t.onAddFieldClose}>
2538
- ${xd}
2612
+ ${$d}
2539
2613
  </button>
2540
2614
  </div>
2541
2615
  <p style="margin: 0 0 16px; color: rgba(255,255,255,0.5); font-size: 13px;">
@@ -2580,7 +2654,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2580
2654
  </form>
2581
2655
  </div>
2582
2656
  </div>
2583
- `}function hm(e,t){const n=Object.entries(e.fields);return c`
2657
+ `}function mm(e,t){const n=Object.entries(e.fields);return c`
2584
2658
  <div class="contacts-record-fields">
2585
2659
  ${n.length===0?c`<div style="color: rgba(255,255,255,0.4); font-size: 13px; margin-top: 12px;">No fields yet. Add one below.</div>`:n.map(([i,s])=>c`
2586
2660
  <div class="contacts-field-row">
@@ -2627,7 +2701,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2627
2701
  </button>
2628
2702
  </div>
2629
2703
  </div>
2630
- `}function fm(e,t){const n=t.editingId===e.id,i=dm(e),s=i===0?"No fields":`${i} field${i>1?"s":""}`;return c`
2704
+ `}function ym(e,t){const n=t.editingId===e.id,i=hm(e),s=i===0?"No fields":`${i} field${i>1?"s":""}`;return c`
2631
2705
  <div class="contacts-record">
2632
2706
  <div
2633
2707
  class="contacts-record-header"
@@ -2639,9 +2713,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2639
2713
  </div>
2640
2714
  <span class="contacts-record-meta">${s}</span>
2641
2715
  </div>
2642
- ${n?hm(e,t):w}
2716
+ ${n?mm(e,t):w}
2643
2717
  </div>
2644
- `}function gm(e){if(!e.connected)return c`
2718
+ `}function vm(e){if(!e.connected)return c`
2645
2719
  <div class="setup-container">
2646
2720
  <div class="setup-card">
2647
2721
  <div class="setup-spinner"></div>
@@ -2650,7 +2724,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2650
2724
  </div>
2651
2725
  `;const t=o=>{o.preventDefault(),e.onSearchSubmit()},n=o=>{o.preventDefault(),e.newRecordPhone.trim()&&e.newRecordName.trim()&&e.onAdd(e.newRecordPhone,e.newRecordName)},i=e.deleteConfirmId?e.records.find(o=>o.id===e.deleteConfirmId):null,s=e.addFieldForId?e.records.find(o=>o.id===e.addFieldForId):null;return c`
2652
2726
  <div class="setup-container">
2653
- ${Rt("Contacts",e.wsProps)}
2727
+ ${It("Contacts",e.wsProps)}
2654
2728
  <div class="setup-card" style="max-width: 620px;">
2655
2729
  <h1>Contact Records</h1>
2656
2730
  <p style="margin-bottom: 16px;">
@@ -2737,7 +2811,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2737
2811
  <div style="margin-top: 16px;">
2738
2812
  ${e.records.length===0?c`<div class="contacts-empty">
2739
2813
  ${e.searchQuery.trim()?`No records matching "${e.searchQuery}".`:"No contact records yet. Add one to get started."}
2740
- </div>`:e.records.map(o=>fm(o,e))}
2814
+ </div>`:e.records.map(o=>ym(o,e))}
2741
2815
  </div>
2742
2816
 
2743
2817
  <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
@@ -2749,35 +2823,35 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2749
2823
  </div>
2750
2824
  </div>
2751
2825
 
2752
- ${i?um(i,e):w}
2753
- ${s?pm(s,e):w}
2754
- `}const $d={CHILD:2},Sd=e=>(...t)=>({_$litDirective$:e,values:t});let Ad=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:mm}=yp,Or=e=>e,Fr=()=>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(Fr(),s),r=i.insertBefore(Fr(),s);n=new mm(a,r,e,e.options)}else{const a=n._$AB.nextSibling,r=n._$AM,l=r!==e;if(l){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||l){let d=n._$AA;for(;d!==a;){const h=Or(d).nextSibling;Or(i).insertBefore(d,s),d=h}}}return n},ft=(e,t,n=e)=>(e._$AI(t,n),e),ym={},vm=(e,t=ym)=>e._$AH=t,bm=e=>e._$AH,js=e=>{e._$AR(),e._$AA.remove()};const Ur=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},wm=Sd(class extends Ad{constructor(e){if(super(e),e.type!==$d.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=bm(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=[]),l=[];let d,h,u=0,p=s.length-1,y=0,$=o.length-1;for(;u<=p&&y<=$;)if(s[u]===null)u++;else if(s[p]===null)p--;else if(r[u]===a[y])l[y]=ft(s[u],o[y]),u++,y++;else if(r[p]===a[$])l[$]=ft(s[p],o[$]),p--,$--;else if(r[u]===a[$])l[$]=ft(s[u],o[$]),gn(e,l[$+1],s[u]),u++,$--;else if(r[p]===a[y])l[y]=ft(s[p],o[y]),gn(e,s[u],s[p]),p--,y++;else if(d===void 0&&(d=Ur(a,y,$),h=Ur(r,u,p)),d.has(r[u]))if(d.has(r[p])){const S=h.get(a[y]),M=S!==void 0?s[S]:null;if(M===null){const v=gn(e,s[u]);ft(v,o[y]),l[y]=v}else l[y]=ft(M,o[y]),gn(e,s[u],M),s[S]=null;y++}else js(s[p]),p--;else js(s[u]),u++;for(;y<=$;){const S=gn(e,l[$+1]);ft(S,o[y]),l[y++]=S}for(;u<=p;){const S=s[u++];S!==null&&js(S)}return this.ut=a,vm(e,l),rt}});class Ro extends Ad{constructor(t){if(super(t),this.it=w,t.type!==$d.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:[]}}}Ro.directiveName="unsafeHTML",Ro.resultType=1;const ji=Sd(Ro);const{entries:Cd,setPrototypeOf:Wr,isFrozen:km,getPrototypeOf:xm,getOwnPropertyDescriptor:$m}=Object;let{freeze:me,seal:Se,create:Lo}=Object,{apply:Do,construct:Bo}=typeof Reflect<"u"&&Reflect;me||(me=function(t){return t});Se||(Se=function(t){return t});Do||(Do=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)});Bo||(Bo=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),Sm=ye(Array.prototype.lastIndexOf),zr=ye(Array.prototype.pop),mn=ye(Array.prototype.push),Am=ye(Array.prototype.splice),Ci=ye(String.prototype.toLowerCase),Gs=ye(String.prototype.toString),Vs=ye(String.prototype.match),yn=ye(String.prototype.replace),Cm=ye(String.prototype.indexOf),Em=ye(String.prototype.trim),Ae=ye(Object.prototype.hasOwnProperty),fe=ye(RegExp.prototype.test),vn=Tm(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 Do(e,t,i)}}function Tm(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Bo(e,n)}}function z(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ci;Wr&&Wr(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(km(t)||(t[i]=o),s=o)}e[s]=!0}return e}function _m(e){for(let t=0;t<e.length;t++)Ae(e,t)||(e[t]=null);return e}function Ne(e){const t=Lo(null);for(const[n,i]of Cd(e))Ae(e,n)&&(Array.isArray(i)?t[n]=_m(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Ne(i):t[n]=i);return t}function bn(e,t){for(;e!==null;){const i=$m(e,t);if(i){if(i.get)return ye(i.get);if(typeof i.value=="function")return ye(i.value)}e=xm(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"]),Qs=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"]),Js=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"]),Mm=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"]),Ys=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"]),Pm=me(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Hr=me(["#text"]),qr=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"]),Xs=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"]),jr=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"]),Im=Se(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Rm=Se(/<%[\w\W]*|[\w\W]*%>/gm),Lm=Se(/\$\{[\w\W]*/gm),Dm=Se(/^data-[\-\w.\u00B7-\uFFFF]+$/),Bm=Se(/^aria-[\-\w]+$/),Ed=Se(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Nm=Se(/^(?:\w+script|data):/i),Om=Se(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Td=Se(/^html$/i),Fm=Se(/^[a-z][.\w]*(-[.\w]+)+$/i);var Gr=Object.freeze({__proto__:null,ARIA_ATTR:Bm,ATTR_WHITESPACE:Om,CUSTOM_ELEMENT:Fm,DATA_ATTR:Dm,DOCTYPE_NAME:Td,ERB_EXPR:Rm,IS_ALLOWED_URI:Ed,IS_SCRIPT_OR_DATA:Nm,MUSTACHE_EXPR:Im,TMPLIT_EXPR:Lm});const wn={element:1,text:3,progressingInstruction:7,comment:8,document:9},Um=function(){return typeof window>"u"?null:window},Wm=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}},Vr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function _d(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Um();const t=N=>_d(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:l,NodeFilter:d,NamedNodeMap:h=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:y}=e,$=l.prototype,S=bn($,"cloneNode"),M=bn($,"remove"),v=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:K}=i;let H=Vr();t.isSupported=typeof Cd=="function"&&typeof k=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ke,ERB_EXPR:Ie,TMPLIT_EXPR:Ke,DATA_ATTR:ks,ARIA_ATTR:xs,IS_SCRIPT_OR_DATA:$s,ATTR_WHITESPACE:Qn,CUSTOM_ELEMENT:Ss}=Gr;let{IS_ALLOWED_URI:Jn}=Gr,te=null;const Yn=z({},[...Kr,...Qs,...Js,...Ys,...Hr]);let ne=null;const Xn=z({},[...qr,...Xs,...jr,...fi]);let X=Object.seal(Lo(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(Lo(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,ee=!0,J=!1,he=!1,tt=!1,Nt=!1,ei=!1,ti=!1,Ha=!0,qa=!1;const Uu="user-content-";let As=!0,un=!1,Ot={},Re=null;const Cs=z({},["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 ja=null;const Ga=z({},["audio","video","img","source","image","track"]);let Es=null;const Va=z({},["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 Ft=He,Ts=!1,_s=null;const Wu=z({},[ni,ii,He],Gs);let si=z({},["mi","mo","mn","ms","mtext"]),oi=z({},["annotation-xml"]);const zu=z({},["title","style","font","a","script"]);let pn=null;const Ku=["application/xhtml+xml","text/html"],Hu="text/html";let oe=null,Ut=null;const qu=n.createElement("form"),Qa=function(x){return x instanceof RegExp||x instanceof Function},Ms=function(){let x=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ut&&Ut===x)){if((!x||typeof x!="object")&&(x={}),x=Ne(x),pn=Ku.indexOf(x.PARSER_MEDIA_TYPE)===-1?Hu:x.PARSER_MEDIA_TYPE,oe=pn==="application/xhtml+xml"?Gs:Ci,te=Ae(x,"ALLOWED_TAGS")?z({},x.ALLOWED_TAGS,oe):Yn,ne=Ae(x,"ALLOWED_ATTR")?z({},x.ALLOWED_ATTR,oe):Xn,_s=Ae(x,"ALLOWED_NAMESPACES")?z({},x.ALLOWED_NAMESPACES,Gs):Wu,Es=Ae(x,"ADD_URI_SAFE_ATTR")?z(Ne(Va),x.ADD_URI_SAFE_ATTR,oe):Va,ja=Ae(x,"ADD_DATA_URI_TAGS")?z(Ne(Ga),x.ADD_DATA_URI_TAGS,oe):Ga,Re=Ae(x,"FORBID_CONTENTS")?z({},x.FORBID_CONTENTS,oe):Cs,dt=Ae(x,"FORBID_TAGS")?z({},x.FORBID_TAGS,oe):Ne({}),dn=Ae(x,"FORBID_ATTR")?z({},x.FORBID_ATTR,oe):Ne({}),Ot=Ae(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,ee=x.SAFE_FOR_XML!==!1,J=x.WHOLE_DOCUMENT||!1,Nt=x.RETURN_DOM||!1,ei=x.RETURN_DOM_FRAGMENT||!1,ti=x.RETURN_TRUSTED_TYPE||!1,tt=x.FORCE_BODY||!1,Ha=x.SANITIZE_DOM!==!1,qa=x.SANITIZE_NAMED_PROPS||!1,As=x.KEEP_CONTENT!==!1,un=x.IN_PLACE||!1,Jn=x.ALLOWED_URI_REGEXP||Ed,Ft=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&&Qa(x.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(X.tagNameCheck=x.CUSTOM_ELEMENT_HANDLING.tagNameCheck),x.CUSTOM_ELEMENT_HANDLING&&Qa(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&&(Nt=!0),Ot&&(te=z({},Hr),ne=[],Ot.html===!0&&(z(te,Kr),z(ne,qr)),Ot.svg===!0&&(z(te,Qs),z(ne,Xs),z(ne,fi)),Ot.svgFilters===!0&&(z(te,Js),z(ne,Xs),z(ne,fi)),Ot.mathMl===!0&&(z(te,Ys),z(ne,jr),z(ne,fi))),x.ADD_TAGS&&(typeof x.ADD_TAGS=="function"?et.tagCheck=x.ADD_TAGS:(te===Yn&&(te=Ne(te)),z(te,x.ADD_TAGS,oe))),x.ADD_ATTR&&(typeof x.ADD_ATTR=="function"?et.attributeCheck=x.ADD_ATTR:(ne===Xn&&(ne=Ne(ne)),z(ne,x.ADD_ATTR,oe))),x.ADD_URI_SAFE_ATTR&&z(Es,x.ADD_URI_SAFE_ATTR,oe),x.FORBID_CONTENTS&&(Re===Cs&&(Re=Ne(Re)),z(Re,x.FORBID_CONTENTS,oe)),x.ADD_FORBID_CONTENTS&&(Re===Cs&&(Re=Ne(Re)),z(Re,x.ADD_FORBID_CONTENTS,oe)),As&&(te["#text"]=!0),J&&z(te,["html","head","body"]),te.table&&(z(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=Wm(y,s)),A!==null&&typeof E=="string"&&(E=A.createHTML(""));me&&me(x),Ut=x}},Ja=z({},[...Qs,...Js,...Mm]),Ya=z({},[...Ys,...Pm]),ju=function(x){let _=k(x);(!_||!_.tagName)&&(_={namespaceURI:Ft,tagName:"template"});const B=Ci(x.tagName),Y=Ci(_.tagName);return _s[x.namespaceURI]?x.namespaceURI===ii?_.namespaceURI===He?B==="svg":_.namespaceURI===ni?B==="svg"&&(Y==="annotation-xml"||si[Y]):!!Ja[B]:x.namespaceURI===ni?_.namespaceURI===He?B==="math":_.namespaceURI===ii?B==="math"&&oi[Y]:!!Ya[B]:x.namespaceURI===He?_.namespaceURI===ii&&!oi[Y]||_.namespaceURI===ni&&!si[Y]?!1:!Ya[B]&&(zu[B]||!Ja[B]):!!(pn==="application/xhtml+xml"&&_s[x.namespaceURI]):!1},Le=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(Nt||ei)try{Le(_)}catch{}else try{_.setAttribute(x,"")}catch{}},Xa=function(x){let _=null,B=null;if(tt)x="<remove></remove>"+x;else{const se=Vs(x,/^[\r\n\t ]+/);B=se&&se[0]}pn==="application/xhtml+xml"&&Ft===He&&(x='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+x+"</body></html>");const Y=A?A.createHTML(x):x;if(Ft===He)try{_=new p().parseFromString(Y,pn)}catch{}if(!_||!_.documentElement){_=T.createDocument(Ft,"template",null);try{_.documentElement.innerHTML=Ts?E:Y}catch{}}const de=_.body||_.documentElement;return x&&B&&de.insertBefore(n.createTextNode(B),de.childNodes[0]||null),Ft===He?W.call(_,J?"html":"body")[0]:J?_.documentElement:de},Za=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)},Ps=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")},er=function(x){return typeof r=="function"&&x instanceof r};function qe(N,x,_){hi(N,B=>{B.call(t,x,_,Ut)})}const tr=function(x){let _=null;if(qe(H.beforeSanitizeElements,x,null),Ps(x))return Le(x),!0;const B=oe(x.nodeName);if(qe(H.uponSanitizeElement,x,{tagName:B,allowedTags:te}),ee&&x.hasChildNodes()&&!er(x.firstElementChild)&&fe(/<[/\w!]/g,x.innerHTML)&&fe(/<[/\w!]/g,x.textContent)||x.nodeType===wn.progressingInstruction||ee&&x.nodeType===wn.comment&&fe(/<[/\w]/g,x.data))return Le(x),!0;if(!(et.tagCheck instanceof Function&&et.tagCheck(B))&&(!te[B]||dt[B])){if(!dt[B]&&ir(B)&&(X.tagNameCheck instanceof RegExp&&fe(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B)))return!1;if(As&&!Re[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,v(x))}}}return Le(x),!0}return x instanceof l&&!ju(x)||(B==="noscript"||B==="noembed"||B==="noframes")&&fe(/<\/no(script|embed|frames)/i,x.innerHTML)?(Le(x),!0):(U&&x.nodeType===wn.text&&(_=x.textContent,hi([ke,Ie,Ke],Y=>{_=yn(_,Y," ")}),x.textContent!==_&&(mn(t.removed,{element:x.cloneNode()}),x.textContent=_)),qe(H.afterSanitizeElements,x,null),!1)},nr=function(x,_,B){if(Ha&&(_==="id"||_==="name")&&(B in n||B in qu))return!1;if(!(C&&!dn[_]&&fe(ks,_))){if(!(Zn&&fe(xs,_))){if(!(et.attributeCheck instanceof Function&&et.attributeCheck(_,x))){if(!ne[_]||dn[_]){if(!(ir(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(!Es[_]){if(!fe(Jn,yn(B,Qn,""))){if(!((_==="src"||_==="xlink:href"||_==="href")&&x!=="script"&&Cm(B,"data:")===0&&ja[x])){if(!(R&&!fe($s,yn(B,Qn,"")))){if(B)return!1}}}}}}}return!0},ir=function(x){return x!=="annotation-xml"&&Vs(x,Ss)},sr=function(x){qe(H.beforeSanitizeAttributes,x,null);const{attributes:_}=x;if(!_||Ps(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,Wt=oe(se),Is=je;let le=se==="value"?Is:Em(Is);if(B.attrName=Wt,B.attrValue=le,B.keepAttr=!0,B.forceKeepAttr=void 0,qe(H.uponSanitizeAttribute,x,B),le=B.attrValue,qa&&(Wt==="id"||Wt==="name")&&(ut(se,x),le=Uu+le),ee&&fe(/((--!?|])>)|<\/(style|title|textarea)/i,le)){ut(se,x);continue}if(Wt==="attributename"&&Vs(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,Ie,Ke],ar=>{le=yn(le,ar," ")});const or=oe(x.nodeName);if(!nr(or,Wt,le)){ut(se,x);continue}if(A&&typeof y=="object"&&typeof y.getAttributeType=="function"&&!ve)switch(y.getAttributeType(or,Wt)){case"TrustedHTML":{le=A.createHTML(le);break}case"TrustedScriptURL":{le=A.createScriptURL(le);break}}if(le!==Is)try{ve?x.setAttributeNS(ve,se,le):x.setAttribute(se,le),Ps(x)?Le(x):zr(t.removed)}catch{ut(se,x)}}qe(H.afterSanitizeAttributes,x,null)},Gu=function N(x){let _=null;const B=Za(x);for(qe(H.beforeSanitizeShadowDOM,x,null);_=B.nextNode();)qe(H.uponSanitizeShadowNode,_,null),tr(_),sr(_),_.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(Ts=!N,Ts&&(N="<!-->"),typeof N!="string"&&!er(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||Ms(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)_=Xa("<!---->"),B=_.ownerDocument.importNode(N,!0),B.nodeType===wn.element&&B.nodeName==="BODY"||B.nodeName==="HTML"?_=B:_.appendChild(B);else{if(!Nt&&!U&&!J&&N.indexOf("<")===-1)return A&&ti?A.createHTML(N):N;if(_=Xa(N),!_)return Nt?null:ti?E:""}_&&tt&&Le(_.firstChild);const se=Za(un?N:_);for(;Y=se.nextNode();)tr(Y),sr(Y),Y.content instanceof o&&Gu(Y.content);if(un)return N;if(Nt){if(ei)for(de=D.call(_.ownerDocument);_.firstChild;)de.appendChild(_.firstChild);else de=_;return(ne.shadowroot||ne.shadowrootmode)&&(de=K.call(i,de,!0)),de}let ve=J?_.outerHTML:_.innerHTML;return J&&te["!doctype"]&&_.ownerDocument&&_.ownerDocument.doctype&&_.ownerDocument.doctype.name&&fe(Td,_.ownerDocument.doctype.name)&&(ve="<!DOCTYPE "+_.ownerDocument.doctype.name+`>
2755
- `+ve),U&&hi([ke,Ie,Ke],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]:{};Ms(N),he=!0},t.clearConfig=function(){Ut=null,he=!1},t.isValidAttribute=function(N,x,_){Ut||Ms({});const B=oe(N),Y=oe(x);return nr(B,Y,_)},t.addHook=function(N,x){typeof x=="function"&&mn(H[N],x)},t.removeHook=function(N,x){if(x!==void 0){const _=Sm(H[N],x);return _===-1?void 0:Am(H[N],_,1)[0]}return zr(H[N])},t.removeHooks=function(N){H[N]=[]},t.removeAllHooks=function(){H=Vr()},t}var No=_d();function Sa(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Dt=Sa();function Md(e){Dt=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 zm=(()=>{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|$))+/,Hm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,qm=/^ {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+|$)/,jm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Aa=/(?:[*+-]|\d{1,9}[.)])/,Pd=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Id=j(Pd).replace(/bull/g,Aa).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(),Gm=j(Pd).replace(/bull/g,Aa).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(),Ca=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Vm=/^[^\n]+/,Ea=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Qm=j(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ea).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Jm=j(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Aa).getRegex(),gs="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",Ta=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ym=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",Ta).replace("tag",gs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Rd=j(Ca).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",gs).getRegex(),Xm=j(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Rd).getRegex(),_a={blockquote:Xm,code:Hm,def:Qm,fences:qm,heading:jm,hr:Gn,html:Ym,lheading:Id,list:Jm,newline:Km,paragraph:Rd,table:In,text:Vm},Qr=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",gs).getRegex(),Zm={..._a,lheading:Gm,table:Qr,paragraph:j(Ca).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Qr).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",gs).getRegex()},ey={..._a,html:j(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ta).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(Ca).replace("hr",Gn).replace("heading",` *#{1,6} *[^
2756
- ]`).replace("lheading",Id).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ty=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ny=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ld=/^( {2,}|\\)\n(?!\s*$)/,iy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ms=/[\p{P}\p{S}]/u,Ma=/[\s\p{P}\p{S}]/u,Dd=/[^\s\p{P}\p{S}]/u,sy=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ma).getRegex(),Bd=/(?!~)[\p{P}\p{S}]/u,oy=/(?!~)[\s\p{P}\p{S}]/u,ay=/(?:[^\s\p{P}\p{S}]|~)/u,ry=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",zm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Nd=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,ly=j(Nd,"u").replace(/punct/g,ms).getRegex(),cy=j(Nd,"u").replace(/punct/g,Bd).getRegex(),Od="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",dy=j(Od,"gu").replace(/notPunctSpace/g,Dd).replace(/punctSpace/g,Ma).replace(/punct/g,ms).getRegex(),uy=j(Od,"gu").replace(/notPunctSpace/g,ay).replace(/punctSpace/g,oy).replace(/punct/g,Bd).getRegex(),py=j("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Dd).replace(/punctSpace/g,Ma).replace(/punct/g,ms).getRegex(),hy=j(/\\(punct)/,"gu").replace(/punct/g,ms).getRegex(),fy=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(),gy=j(Ta).replace("(?:-->|$)","-->").getRegex(),my=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",gy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Gi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,yy=j(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Gi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Fd=j(/^!?\[(label)\]\[(ref)\]/).replace("label",Gi).replace("ref",Ea).getRegex(),Ud=j(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ea).getRegex(),vy=j("reflink|nolink(?!\\()","g").replace("reflink",Fd).replace("nolink",Ud).getRegex(),Jr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Pa={_backpedal:In,anyPunctuation:hy,autolink:fy,blockSkip:ry,br:Ld,code:ny,del:In,emStrongLDelim:ly,emStrongRDelimAst:dy,emStrongRDelimUnd:py,escape:ty,link:yy,nolink:Ud,punctuation:sy,reflink:Fd,reflinkSearch:vy,tag:my,text:iy,url:In},by={...Pa,link:j(/^!?\[(label)\]\((.*?)\)/).replace("label",Gi).getRegex(),reflink:j(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Gi).getRegex()},Oo={...Pa,emStrongRDelimAst:uy,emStrongLDelim:cy,url:j(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Jr).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",Jr).getRegex()},wy={...Oo,br:j(Ld).replace("{2,}","*").getRegex(),text:j(Oo.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},gi={normal:_a,gfm:Zm,pedantic:ey},kn={normal:Pa,gfm:Oo,breaks:wy,pedantic:by},ky={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Yr=e=>ky[e];function Qe(e,t){if(t){if(ge.escapeTest.test(e))return e.replace(ge.escapeReplace,Yr)}else if(ge.escapeTestNoEncode.test(e))return e.replace(ge.escapeReplaceNoEncode,Yr);return e}function Xr(e){try{e=encodeURI(e).replace(ge.percentDecode,"%")}catch{return null}return e}function Zr(e,t){var o;let n=e.replace(ge.findPipe,(a,r,l)=>{let d=!1,h=r;for(;--h>=0&&l[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 xy(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 el(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 l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:a,text:r,tokens:i.inlineTokens(r)};return i.state.inLink=!1,l}function $y(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2826
+ ${i?fm(i,e):w}
2827
+ ${s?gm(s,e):w}
2828
+ `}const Sd={CHILD:2},Ad=e=>(...t)=>({_$litDirective$:e,values:t});let Cd=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:bm}=vp,Or=e=>e,Fr=()=>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(Fr(),s),r=i.insertBefore(Fr(),s);n=new bm(a,r,e,e.options)}else{const a=n._$AB.nextSibling,r=n._$AM,l=r!==e;if(l){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||l){let d=n._$AA;for(;d!==a;){const h=Or(d).nextSibling;Or(i).insertBefore(d,s),d=h}}}return n},ft=(e,t,n=e)=>(e._$AI(t,n),e),wm={},km=(e,t=wm)=>e._$AH=t,xm=e=>e._$AH,js=e=>{e._$AR(),e._$AA.remove()};const Ur=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},$m=Ad(class extends Cd{constructor(e){if(super(e),e.type!==Sd.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=xm(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=[]),l=[];let d,h,u=0,p=s.length-1,y=0,x=o.length-1;for(;u<=p&&y<=x;)if(s[u]===null)u++;else if(s[p]===null)p--;else if(r[u]===a[y])l[y]=ft(s[u],o[y]),u++,y++;else if(r[p]===a[x])l[x]=ft(s[p],o[x]),p--,x--;else if(r[u]===a[x])l[x]=ft(s[u],o[x]),gn(e,l[x+1],s[u]),u++,x--;else if(r[p]===a[y])l[y]=ft(s[p],o[y]),gn(e,s[u],s[p]),p--,y++;else if(d===void 0&&(d=Ur(a,y,x),h=Ur(r,u,p)),d.has(r[u]))if(d.has(r[p])){const S=h.get(a[y]),_=S!==void 0?s[S]:null;if(_===null){const v=gn(e,s[u]);ft(v,o[y]),l[y]=v}else l[y]=ft(_,o[y]),gn(e,s[u],_),s[S]=null;y++}else js(s[p]),p--;else js(s[u]),u++;for(;y<=x;){const S=gn(e,l[x+1]);ft(S,o[y]),l[y++]=S}for(;u<=p;){const S=s[u++];S!==null&&js(S)}return this.ut=a,km(e,l),ot}});class Ro extends Cd{constructor(t){if(super(t),this.it=w,t.type!==Sd.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===ot)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:[]}}}Ro.directiveName="unsafeHTML",Ro.resultType=1;const ji=Ad(Ro);const{entries:Ed,setPrototypeOf:Wr,isFrozen:Sm,getPrototypeOf:Am,getOwnPropertyDescriptor:Cm}=Object;let{freeze:me,seal:xe,create:Lo}=Object,{apply:Do,construct:Bo}=typeof Reflect<"u"&&Reflect;me||(me=function(t){return t});xe||(xe=function(t){return t});Do||(Do=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)});Bo||(Bo=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),Em=ye(Array.prototype.lastIndexOf),zr=ye(Array.prototype.pop),mn=ye(Array.prototype.push),Tm=ye(Array.prototype.splice),Ci=ye(String.prototype.toLowerCase),Vs=ye(String.prototype.toString),Gs=ye(String.prototype.match),yn=ye(String.prototype.replace),_m=ye(String.prototype.indexOf),Mm=ye(String.prototype.trim),$e=ye(Object.prototype.hasOwnProperty),fe=ye(RegExp.prototype.test),vn=Pm(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 Do(e,t,i)}}function Pm(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Bo(e,n)}}function W(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ci;Wr&&Wr(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(Sm(t)||(t[i]=o),s=o)}e[s]=!0}return e}function Im(e){for(let t=0;t<e.length;t++)$e(e,t)||(e[t]=null);return e}function Le(e){const t=Lo(null);for(const[n,i]of Ed(e))$e(e,n)&&(Array.isArray(i)?t[n]=Im(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Le(i):t[n]=i);return t}function bn(e,t){for(;e!==null;){const i=Cm(e,t);if(i){if(i.get)return ye(i.get);if(typeof i.value=="function")return ye(i.value)}e=Am(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"]),Qs=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"]),Js=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"]),Rm=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"]),Ys=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"]),Lm=me(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Hr=me(["#text"]),qr=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"]),Xs=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"]),jr=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"]),Dm=xe(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Bm=xe(/<%[\w\W]*|[\w\W]*%>/gm),Nm=xe(/\$\{[\w\W]*/gm),Om=xe(/^data-[\-\w.\u00B7-\uFFFF]+$/),Fm=xe(/^aria-[\-\w]+$/),Td=xe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Um=xe(/^(?:\w+script|data):/i),Wm=xe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),_d=xe(/^html$/i),zm=xe(/^[a-z][.\w]*(-[.\w]+)+$/i);var Vr=Object.freeze({__proto__:null,ARIA_ATTR:Fm,ATTR_WHITESPACE:Wm,CUSTOM_ELEMENT:zm,DATA_ATTR:Om,DOCTYPE_NAME:_d,ERB_EXPR:Bm,IS_ALLOWED_URI:Td,IS_SCRIPT_OR_DATA:Um,MUSTACHE_EXPR:Dm,TMPLIT_EXPR:Nm});const wn={element:1,text:3,progressingInstruction:7,comment:8,document:9},Km=function(){return typeof window>"u"?null:window},Hm=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 Md(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Km();const t=B=>Md(B);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:l,NodeFilter:d,NamedNodeMap:h=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:p,trustedTypes:y}=e,x=l.prototype,S=bn(x,"cloneNode"),_=bn(x,"remove"),v=bn(x,"nextSibling"),b=bn(x,"childNodes"),k=bn(x,"parentNode");if(typeof a=="function"){const B=n.createElement("template");B.content&&B.content.ownerDocument&&(n=B.content.ownerDocument)}let A,E="";const{implementation:M,createNodeIterator:P,createDocumentFragment:F,getElementsByTagName:V}=n,{importNode:X}=i;let q=Gr();t.isSupported=typeof Ed=="function"&&typeof k=="function"&&M&&M.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:lt,ERB_EXPR:Bt,TMPLIT_EXPR:ct,DATA_ATTR:ks,ARIA_ATTR:xs,IS_SCRIPT_OR_DATA:$s,ATTR_WHITESPACE:Qn,CUSTOM_ELEMENT:Ss}=Vr;let{IS_ALLOWED_URI:Jn}=Vr,te=null;const Yn=W({},[...Kr,...Qs,...Js,...Ys,...Hr]);let ne=null;const Xn=W({},[...qr,...Xs,...jr,...fi]);let Z=Object.seal(Lo(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 Xe=Object.seal(Lo(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,O=!0,U=!1,ee=!0,Q=!1,he=!1,Ze=!1,Nt=!1,ei=!1,ti=!1,Ha=!0,qa=!1;const Wu="user-content-";let As=!0,un=!1,Ot={},Me=null;const Cs=W({},["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 ja=null;const Va=W({},["audio","video","img","source","image","track"]);let Es=null;const Ga=W({},["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",Ue="http://www.w3.org/1999/xhtml";let Ft=Ue,Ts=!1,_s=null;const zu=W({},[ni,ii,Ue],Vs);let si=W({},["mi","mo","mn","ms","mtext"]),oi=W({},["annotation-xml"]);const Ku=W({},["title","style","font","a","script"]);let pn=null;const Hu=["application/xhtml+xml","text/html"],qu="text/html";let oe=null,Ut=null;const ju=n.createElement("form"),Qa=function($){return $ instanceof RegExp||$ instanceof Function},Ms=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ut&&Ut===$)){if((!$||typeof $!="object")&&($={}),$=Le($),pn=Hu.indexOf($.PARSER_MEDIA_TYPE)===-1?qu:$.PARSER_MEDIA_TYPE,oe=pn==="application/xhtml+xml"?Vs:Ci,te=$e($,"ALLOWED_TAGS")?W({},$.ALLOWED_TAGS,oe):Yn,ne=$e($,"ALLOWED_ATTR")?W({},$.ALLOWED_ATTR,oe):Xn,_s=$e($,"ALLOWED_NAMESPACES")?W({},$.ALLOWED_NAMESPACES,Vs):zu,Es=$e($,"ADD_URI_SAFE_ATTR")?W(Le(Ga),$.ADD_URI_SAFE_ATTR,oe):Ga,ja=$e($,"ADD_DATA_URI_TAGS")?W(Le(Va),$.ADD_DATA_URI_TAGS,oe):Va,Me=$e($,"FORBID_CONTENTS")?W({},$.FORBID_CONTENTS,oe):Cs,dt=$e($,"FORBID_TAGS")?W({},$.FORBID_TAGS,oe):Le({}),dn=$e($,"FORBID_ATTR")?W({},$.FORBID_ATTR,oe):Le({}),Ot=$e($,"USE_PROFILES")?$.USE_PROFILES:!1,Zn=$.ALLOW_ARIA_ATTR!==!1,C=$.ALLOW_DATA_ATTR!==!1,R=$.ALLOW_UNKNOWN_PROTOCOLS||!1,O=$.ALLOW_SELF_CLOSE_IN_ATTR!==!1,U=$.SAFE_FOR_TEMPLATES||!1,ee=$.SAFE_FOR_XML!==!1,Q=$.WHOLE_DOCUMENT||!1,Nt=$.RETURN_DOM||!1,ei=$.RETURN_DOM_FRAGMENT||!1,ti=$.RETURN_TRUSTED_TYPE||!1,Ze=$.FORCE_BODY||!1,Ha=$.SANITIZE_DOM!==!1,qa=$.SANITIZE_NAMED_PROPS||!1,As=$.KEEP_CONTENT!==!1,un=$.IN_PLACE||!1,Jn=$.ALLOWED_URI_REGEXP||Td,Ft=$.NAMESPACE||Ue,si=$.MATHML_TEXT_INTEGRATION_POINTS||si,oi=$.HTML_INTEGRATION_POINTS||oi,Z=$.CUSTOM_ELEMENT_HANDLING||{},$.CUSTOM_ELEMENT_HANDLING&&Qa($.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=$.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$.CUSTOM_ELEMENT_HANDLING&&Qa($.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=$.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$.CUSTOM_ELEMENT_HANDLING&&typeof $.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Z.allowCustomizedBuiltInElements=$.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),U&&(C=!1),ei&&(Nt=!0),Ot&&(te=W({},Hr),ne=[],Ot.html===!0&&(W(te,Kr),W(ne,qr)),Ot.svg===!0&&(W(te,Qs),W(ne,Xs),W(ne,fi)),Ot.svgFilters===!0&&(W(te,Js),W(ne,Xs),W(ne,fi)),Ot.mathMl===!0&&(W(te,Ys),W(ne,jr),W(ne,fi))),$.ADD_TAGS&&(typeof $.ADD_TAGS=="function"?Xe.tagCheck=$.ADD_TAGS:(te===Yn&&(te=Le(te)),W(te,$.ADD_TAGS,oe))),$.ADD_ATTR&&(typeof $.ADD_ATTR=="function"?Xe.attributeCheck=$.ADD_ATTR:(ne===Xn&&(ne=Le(ne)),W(ne,$.ADD_ATTR,oe))),$.ADD_URI_SAFE_ATTR&&W(Es,$.ADD_URI_SAFE_ATTR,oe),$.FORBID_CONTENTS&&(Me===Cs&&(Me=Le(Me)),W(Me,$.FORBID_CONTENTS,oe)),$.ADD_FORBID_CONTENTS&&(Me===Cs&&(Me=Le(Me)),W(Me,$.ADD_FORBID_CONTENTS,oe)),As&&(te["#text"]=!0),Q&&W(te,["html","head","body"]),te.table&&(W(te,["tbody"]),delete dt.tbody),$.TRUSTED_TYPES_POLICY){if(typeof $.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=$.TRUSTED_TYPES_POLICY,E=A.createHTML("")}else A===void 0&&(A=Hm(y,s)),A!==null&&typeof E=="string"&&(E=A.createHTML(""));me&&me($),Ut=$}},Ja=W({},[...Qs,...Js,...Rm]),Ya=W({},[...Ys,...Lm]),Vu=function($){let T=k($);(!T||!T.tagName)&&(T={namespaceURI:Ft,tagName:"template"});const D=Ci($.tagName),J=Ci(T.tagName);return _s[$.namespaceURI]?$.namespaceURI===ii?T.namespaceURI===Ue?D==="svg":T.namespaceURI===ni?D==="svg"&&(J==="annotation-xml"||si[J]):!!Ja[D]:$.namespaceURI===ni?T.namespaceURI===Ue?D==="math":T.namespaceURI===ii?D==="math"&&oi[J]:!!Ya[D]:$.namespaceURI===Ue?T.namespaceURI===ii&&!oi[J]||T.namespaceURI===ni&&!si[J]?!1:!Ya[D]&&(Ku[D]||!Ja[D]):!!(pn==="application/xhtml+xml"&&_s[$.namespaceURI]):!1},Pe=function($){mn(t.removed,{element:$});try{k($).removeChild($)}catch{_($)}},ut=function($,T){try{mn(t.removed,{attribute:T.getAttributeNode($),from:T})}catch{mn(t.removed,{attribute:null,from:T})}if(T.removeAttribute($),$==="is")if(Nt||ei)try{Pe(T)}catch{}else try{T.setAttribute($,"")}catch{}},Xa=function($){let T=null,D=null;if(Ze)$="<remove></remove>"+$;else{const se=Gs($,/^[\r\n\t ]+/);D=se&&se[0]}pn==="application/xhtml+xml"&&Ft===Ue&&($='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$+"</body></html>");const J=A?A.createHTML($):$;if(Ft===Ue)try{T=new p().parseFromString(J,pn)}catch{}if(!T||!T.documentElement){T=M.createDocument(Ft,"template",null);try{T.documentElement.innerHTML=Ts?E:J}catch{}}const de=T.body||T.documentElement;return $&&D&&de.insertBefore(n.createTextNode(D),de.childNodes[0]||null),Ft===Ue?V.call(T,Q?"html":"body")[0]:Q?T.documentElement:de},Za=function($){return P.call($.ownerDocument||$,$,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Ps=function($){return $ instanceof u&&(typeof $.nodeName!="string"||typeof $.textContent!="string"||typeof $.removeChild!="function"||!($.attributes instanceof h)||typeof $.removeAttribute!="function"||typeof $.setAttribute!="function"||typeof $.namespaceURI!="string"||typeof $.insertBefore!="function"||typeof $.hasChildNodes!="function")},er=function($){return typeof r=="function"&&$ instanceof r};function We(B,$,T){hi(B,D=>{D.call(t,$,T,Ut)})}const tr=function($){let T=null;if(We(q.beforeSanitizeElements,$,null),Ps($))return Pe($),!0;const D=oe($.nodeName);if(We(q.uponSanitizeElement,$,{tagName:D,allowedTags:te}),ee&&$.hasChildNodes()&&!er($.firstElementChild)&&fe(/<[/\w!]/g,$.innerHTML)&&fe(/<[/\w!]/g,$.textContent)||$.nodeType===wn.progressingInstruction||ee&&$.nodeType===wn.comment&&fe(/<[/\w]/g,$.data))return Pe($),!0;if(!(Xe.tagCheck instanceof Function&&Xe.tagCheck(D))&&(!te[D]||dt[D])){if(!dt[D]&&ir(D)&&(Z.tagNameCheck instanceof RegExp&&fe(Z.tagNameCheck,D)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(D)))return!1;if(As&&!Me[D]){const J=k($)||$.parentNode,de=b($)||$.childNodes;if(de&&J){const se=de.length;for(let ve=se-1;ve>=0;--ve){const ze=S(de[ve],!0);ze.__removalCount=($.__removalCount||0)+1,J.insertBefore(ze,v($))}}}return Pe($),!0}return $ instanceof l&&!Vu($)||(D==="noscript"||D==="noembed"||D==="noframes")&&fe(/<\/no(script|embed|frames)/i,$.innerHTML)?(Pe($),!0):(U&&$.nodeType===wn.text&&(T=$.textContent,hi([lt,Bt,ct],J=>{T=yn(T,J," ")}),$.textContent!==T&&(mn(t.removed,{element:$.cloneNode()}),$.textContent=T)),We(q.afterSanitizeElements,$,null),!1)},nr=function($,T,D){if(Ha&&(T==="id"||T==="name")&&(D in n||D in ju))return!1;if(!(C&&!dn[T]&&fe(ks,T))){if(!(Zn&&fe(xs,T))){if(!(Xe.attributeCheck instanceof Function&&Xe.attributeCheck(T,$))){if(!ne[T]||dn[T]){if(!(ir($)&&(Z.tagNameCheck instanceof RegExp&&fe(Z.tagNameCheck,$)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck($))&&(Z.attributeNameCheck instanceof RegExp&&fe(Z.attributeNameCheck,T)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(T,$))||T==="is"&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&fe(Z.tagNameCheck,D)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(D))))return!1}else if(!Es[T]){if(!fe(Jn,yn(D,Qn,""))){if(!((T==="src"||T==="xlink:href"||T==="href")&&$!=="script"&&_m(D,"data:")===0&&ja[$])){if(!(R&&!fe($s,yn(D,Qn,"")))){if(D)return!1}}}}}}}return!0},ir=function($){return $!=="annotation-xml"&&Gs($,Ss)},sr=function($){We(q.beforeSanitizeAttributes,$,null);const{attributes:T}=$;if(!T||Ps($))return;const D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let J=T.length;for(;J--;){const de=T[J],{name:se,namespaceURI:ve,value:ze}=de,Wt=oe(se),Is=ze;let le=se==="value"?Is:Mm(Is);if(D.attrName=Wt,D.attrValue=le,D.keepAttr=!0,D.forceKeepAttr=void 0,We(q.uponSanitizeAttribute,$,D),le=D.attrValue,qa&&(Wt==="id"||Wt==="name")&&(ut(se,$),le=Wu+le),ee&&fe(/((--!?|])>)|<\/(style|title|textarea)/i,le)){ut(se,$);continue}if(Wt==="attributename"&&Gs(le,"href")){ut(se,$);continue}if(D.forceKeepAttr)continue;if(!D.keepAttr){ut(se,$);continue}if(!O&&fe(/\/>/i,le)){ut(se,$);continue}U&&hi([lt,Bt,ct],ar=>{le=yn(le,ar," ")});const or=oe($.nodeName);if(!nr(or,Wt,le)){ut(se,$);continue}if(A&&typeof y=="object"&&typeof y.getAttributeType=="function"&&!ve)switch(y.getAttributeType(or,Wt)){case"TrustedHTML":{le=A.createHTML(le);break}case"TrustedScriptURL":{le=A.createScriptURL(le);break}}if(le!==Is)try{ve?$.setAttributeNS(ve,se,le):$.setAttribute(se,le),Ps($)?Pe($):zr(t.removed)}catch{ut(se,$)}}We(q.afterSanitizeAttributes,$,null)},Gu=function B($){let T=null;const D=Za($);for(We(q.beforeSanitizeShadowDOM,$,null);T=D.nextNode();)We(q.uponSanitizeShadowNode,T,null),tr(T),sr(T),T.content instanceof o&&B(T.content);We(q.afterSanitizeShadowDOM,$,null)};return t.sanitize=function(B){let $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},T=null,D=null,J=null,de=null;if(Ts=!B,Ts&&(B="<!-->"),typeof B!="string"&&!er(B))if(typeof B.toString=="function"){if(B=B.toString(),typeof B!="string")throw vn("dirty is not a string, aborting")}else throw vn("toString is not a function");if(!t.isSupported)return B;if(he||Ms($),t.removed=[],typeof B=="string"&&(un=!1),un){if(B.nodeName){const ze=oe(B.nodeName);if(!te[ze]||dt[ze])throw vn("root node is forbidden and cannot be sanitized in-place")}}else if(B instanceof r)T=Xa("<!---->"),D=T.ownerDocument.importNode(B,!0),D.nodeType===wn.element&&D.nodeName==="BODY"||D.nodeName==="HTML"?T=D:T.appendChild(D);else{if(!Nt&&!U&&!Q&&B.indexOf("<")===-1)return A&&ti?A.createHTML(B):B;if(T=Xa(B),!T)return Nt?null:ti?E:""}T&&Ze&&Pe(T.firstChild);const se=Za(un?B:T);for(;J=se.nextNode();)tr(J),sr(J),J.content instanceof o&&Gu(J.content);if(un)return B;if(Nt){if(ei)for(de=F.call(T.ownerDocument);T.firstChild;)de.appendChild(T.firstChild);else de=T;return(ne.shadowroot||ne.shadowrootmode)&&(de=X.call(i,de,!0)),de}let ve=Q?T.outerHTML:T.innerHTML;return Q&&te["!doctype"]&&T.ownerDocument&&T.ownerDocument.doctype&&T.ownerDocument.doctype.name&&fe(_d,T.ownerDocument.doctype.name)&&(ve="<!DOCTYPE "+T.ownerDocument.doctype.name+`>
2829
+ `+ve),U&&hi([lt,Bt,ct],ze=>{ve=yn(ve,ze," ")}),A&&ti?A.createHTML(ve):ve},t.setConfig=function(){let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ms(B),he=!0},t.clearConfig=function(){Ut=null,he=!1},t.isValidAttribute=function(B,$,T){Ut||Ms({});const D=oe(B),J=oe($);return nr(D,J,T)},t.addHook=function(B,$){typeof $=="function"&&mn(q[B],$)},t.removeHook=function(B,$){if($!==void 0){const T=Em(q[B],$);return T===-1?void 0:Tm(q[B],T,1)[0]}return zr(q[B])},t.removeHooks=function(B){q[B]=[]},t.removeAllHooks=function(){q=Gr()},t}var No=Md();function Sa(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Lt=Sa();function Pd(e){Lt=e}var In={exec:()=>null};function K(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 qm=(()=>{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")},jm=/^(?:[ \t]*(?:\n|$))+/,Vm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Gm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Vn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Qm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Aa=/(?:[*+-]|\d{1,9}[.)])/,Id=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Rd=K(Id).replace(/bull/g,Aa).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=K(Id).replace(/bull/g,Aa).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(),Ca=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ym=/^[^\n]+/,Ea=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Xm=K(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ea).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Zm=K(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Aa).getRegex(),gs="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",Ta=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ey=K("^ {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",Ta).replace("tag",gs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ld=K(Ca).replace("hr",Vn).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",gs).getRegex(),ty=K(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ld).getRegex(),_a={blockquote:ty,code:Vm,def:Xm,fences:Gm,heading:Qm,hr:Vn,html:ey,lheading:Rd,list:Zm,newline:jm,paragraph:Ld,table:In,text:Ym},Qr=K("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Vn).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",gs).getRegex(),ny={..._a,lheading:Jm,table:Qr,paragraph:K(Ca).replace("hr",Vn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Qr).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",gs).getRegex()},iy={..._a,html:K(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ta).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:K(Ca).replace("hr",Vn).replace("heading",` *#{1,6} *[^
2830
+ ]`).replace("lheading",Rd).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},sy=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,oy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Dd=/^( {2,}|\\)\n(?!\s*$)/,ay=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ms=/[\p{P}\p{S}]/u,Ma=/[\s\p{P}\p{S}]/u,Bd=/[^\s\p{P}\p{S}]/u,ry=K(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ma).getRegex(),Nd=/(?!~)[\p{P}\p{S}]/u,ly=/(?!~)[\s\p{P}\p{S}]/u,cy=/(?:[^\s\p{P}\p{S}]|~)/u,dy=K(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",qm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Od=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,uy=K(Od,"u").replace(/punct/g,ms).getRegex(),py=K(Od,"u").replace(/punct/g,Nd).getRegex(),Fd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",hy=K(Fd,"gu").replace(/notPunctSpace/g,Bd).replace(/punctSpace/g,Ma).replace(/punct/g,ms).getRegex(),fy=K(Fd,"gu").replace(/notPunctSpace/g,cy).replace(/punctSpace/g,ly).replace(/punct/g,Nd).getRegex(),gy=K("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Bd).replace(/punctSpace/g,Ma).replace(/punct/g,ms).getRegex(),my=K(/\\(punct)/,"gu").replace(/punct/g,ms).getRegex(),yy=K(/^<(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(),vy=K(Ta).replace("(?:-->|$)","-->").getRegex(),by=K("^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",vy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Vi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,wy=K(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Vi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ud=K(/^!?\[(label)\]\[(ref)\]/).replace("label",Vi).replace("ref",Ea).getRegex(),Wd=K(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ea).getRegex(),ky=K("reflink|nolink(?!\\()","g").replace("reflink",Ud).replace("nolink",Wd).getRegex(),Jr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Pa={_backpedal:In,anyPunctuation:my,autolink:yy,blockSkip:dy,br:Dd,code:oy,del:In,emStrongLDelim:uy,emStrongRDelimAst:hy,emStrongRDelimUnd:gy,escape:sy,link:wy,nolink:Wd,punctuation:ry,reflink:Ud,reflinkSearch:ky,tag:by,text:ay,url:In},xy={...Pa,link:K(/^!?\[(label)\]\((.*?)\)/).replace("label",Vi).getRegex(),reflink:K(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Vi).getRegex()},Oo={...Pa,emStrongRDelimAst:fy,emStrongLDelim:py,url:K(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Jr).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:K(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Jr).getRegex()},$y={...Oo,br:K(Dd).replace("{2,}","*").getRegex(),text:K(Oo.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},gi={normal:_a,gfm:ny,pedantic:iy},kn={normal:Pa,gfm:Oo,breaks:$y,pedantic:xy},Sy={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Yr=e=>Sy[e];function qe(e,t){if(t){if(ge.escapeTest.test(e))return e.replace(ge.escapeReplace,Yr)}else if(ge.escapeTestNoEncode.test(e))return e.replace(ge.escapeReplaceNoEncode,Yr);return e}function Xr(e){try{e=encodeURI(e).replace(ge.percentDecode,"%")}catch{return null}return e}function Zr(e,t){var o;let n=e.replace(ge.findPipe,(a,r,l)=>{let d=!1,h=r;for(;--h>=0&&l[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 Ay(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 el(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 l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:a,text:r,tokens:i.inlineTokens(r)};return i.state.inLink=!1,l}function Cy(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2757
2831
  `).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(`
2758
- `)}var Vi=class{constructor(e){q(this,"options");q(this,"rules");q(this,"lexer");this.options=e||Dt}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,`
2759
- `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=$y(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],`
2832
+ `)}var Gi=class{constructor(e){z(this,"options");z(this,"rules");z(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,`
2833
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=Cy(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],`
2760
2834
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=xn(t[0],`
2761
2835
  `).split(`
2762
2836
  `),i="",s="",o=[];for(;n.length>0;){let a=!1,r=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))r.push(n[l]),a=!0;else if(!a)r.push(n[l]);else break;n=n.slice(l);let d=r.join(`
2763
2837
  `),h=d.replace(this.rules.other.blockquoteSetextReplace,`
2764
2838
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
2765
2839
  ${d}`:d,s=s?`${s}
2766
- ${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 y=p,$=y.raw+`
2840
+ ${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 y=p,x=y.raw+`
2767
2841
  `+n.join(`
2768
- `),S=this.blockquote($);o[o.length-1]=S,i=i.substring(0,i.length-y.raw.length)+S.raw,s=s.substring(0,s.length-y.text.length)+S.text;break}else if((p==null?void 0:p.type)==="list"){let y=p,$=y.raw+`
2842
+ `),S=this.blockquote(x);o[o.length-1]=S,i=i.substring(0,i.length-y.raw.length)+S.raw,s=s.substring(0,s.length-y.text.length)+S.text;break}else if((p==null?void 0:p.type)==="list"){let y=p,x=y.raw+`
2769
2843
  `+n.join(`
2770
- `),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-y.raw.length)+S.raw,n=$.substring(o.at(-1).raw.length).split(`
2844
+ `),S=this.list(x);o[o.length-1]=S,i=i.substring(0,i.length-p.raw.length)+S.raw,s=s.substring(0,s.length-y.raw.length)+S.raw,n=x.substring(o.at(-1).raw.length).split(`
2771
2845
  `);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),l=!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 y=t[2].split(`
2772
- `,1)[0].replace(this.rules.other.listReplaceTabs,v=>" ".repeat(3*v.length)),$=e.split(`
2773
- `,1)[0],S=!y.trim(),M=0;if(this.options.pedantic?(M=2,p=y.trimStart()):S?M=t[1].length+1:(M=t[2].search(this.rules.other.nonSpaceChar),M=M>4?1:M,p=y.slice(M),M+=t[1].length),S&&this.rules.other.blankLine.test($)&&(u+=$+`
2774
- `,e=e.substring($.length+1),h=!0),!h){let v=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(`
2775
- `,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($)||v.test($)||b.test($))break;if(P.search(this.rules.other.nonSpaceChar)>=M||!$.trim())p+=`
2776
- `+P.slice(M);else{if(S||y.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||k.test(y)||A.test(y)||b.test(y))break;p+=`
2777
- `+$}!S&&!$.trim()&&(S=!0),u+=T+`
2778
- `,e=e.substring(T.length+1),y=P.slice(M)}}a.loose||(l?a.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(l=!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(y=>y.type==="space"),p=u.length>0&&u.some(y=>this.rules.other.anyLine.test(y.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=Zr(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(`
2846
+ `,1)[0].replace(this.rules.other.listReplaceTabs,v=>" ".repeat(3*v.length)),x=e.split(`
2847
+ `,1)[0],S=!y.trim(),_=0;if(this.options.pedantic?(_=2,p=y.trimStart()):S?_=t[1].length+1:(_=t[2].search(this.rules.other.nonSpaceChar),_=_>4?1:_,p=y.slice(_),_+=t[1].length),S&&this.rules.other.blankLine.test(x)&&(u+=x+`
2848
+ `,e=e.substring(x.length+1),h=!0),!h){let v=this.rules.other.nextBulletRegex(_),b=this.rules.other.hrRegex(_),k=this.rules.other.fencesBeginRegex(_),A=this.rules.other.headingBeginRegex(_),E=this.rules.other.htmlBeginRegex(_);for(;e;){let M=e.split(`
2849
+ `,1)[0],P;if(x=M,this.options.pedantic?(x=x.replace(this.rules.other.listReplaceNesting," "),P=x):P=x.replace(this.rules.other.tabCharGlobal," "),k.test(x)||A.test(x)||E.test(x)||v.test(x)||b.test(x))break;if(P.search(this.rules.other.nonSpaceChar)>=_||!x.trim())p+=`
2850
+ `+P.slice(_);else{if(S||y.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||k.test(y)||A.test(y)||b.test(y))break;p+=`
2851
+ `+x}!S&&!x.trim()&&(S=!0),u+=M+`
2852
+ `,e=e.substring(M.length+1),y=P.slice(_)}}a.loose||(l?a.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(l=!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(y=>y.type==="space"),p=u.length>0&&u.some(y=>this.rules.other.anyLine.test(y.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=Zr(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(`
2779
2853
  `):[],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(Zr(r,o.header.length).map((l,d)=>({text:l,tokens:this.lexer.inline(l),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)===`
2780
- `?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=xy(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)),el(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 el(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,l=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)){l+=a;continue}if(r-=a,r>0)continue;a=Math.min(a,a+r+l);let h=[...i[0]][0].length,u=e.slice(0,s+i.index+h+a);if(Math.min(s,a)%2){let y=u.slice(1,-1);return{type:"em",raw:u,text:y,tokens:this.lexer.inlineTokens(y)}}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}}}},Ee=class Fo{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||Dt,this.options.tokenizer=this.options.tokenizer||new Vi,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 Fo(n).lex(t)}static lexInline(t,n){return new Fo(n).inlineTokens(t)}lex(t){t=t.replace(ge.carriageReturn,`
2854
+ `?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=Ay(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)),el(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 el(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,l=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)){l+=a;continue}if(r-=a,r>0)continue;a=Math.min(a,a+r+l);let h=[...i[0]][0].length,u=e.slice(0,s+i.index+h+a);if(Math.min(s,a)%2){let y=u.slice(1,-1);return{type:"em",raw:u,text:y,tokens:this.lexer.inlineTokens(y)}}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 Fo{constructor(t){z(this,"tokens");z(this,"options");z(this,"state");z(this,"inlineQueue");z(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Lt,this.options.tokenizer=this.options.tokenizer||new Gi,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 Fo(n).lex(t)}static lexInline(t,n){return new Fo(n).inlineTokens(t)}lex(t){t=t.replace(ge.carriageReturn,`
2781
2855
  `),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+=`
2782
2856
  `: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(`
2783
2857
  `)?"":`
@@ -2791,9 +2865,9 @@ ${h}`:h;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
2791
2865
  `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=d.text):n.push(r),i=l.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(`
2792
2866
  `)?"":`
2793
2867
  `)+r.raw,d.text+=`
2794
- `+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 l,d,h,u,p;let i=t,s=null;if(this.tokens.links){let y=Object.keys(this.tokens.links);if(y.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)y.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=(l=this.options.hooks)==null?void 0:l.emStrongMask)==null?void 0:d.call({lexer:this},i))??i;let a=!1,r="";for(;t;){a||(r=""),a=!1;let y;if((u=(h=this.options.extensions)==null?void 0:h.inline)!=null&&u.some(S=>(y=S.call({lexer:this},t,n))?(t=t.substring(y.raw.length),n.push(y),!0):!1))continue;if(y=this.tokenizer.escape(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.tag(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.link(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(y.raw.length);let S=n.at(-1);y.type==="text"&&(S==null?void 0:S.type)==="text"?(S.raw+=y.raw,S.text+=y.text):n.push(y);continue}if(y=this.tokenizer.emStrong(t,i,r)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.codespan(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.br(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.del(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.autolink(t)){t=t.substring(y.raw.length),n.push(y);continue}if(!this.state.inLink&&(y=this.tokenizer.url(t))){t=t.substring(y.raw.length),n.push(y);continue}let $=t;if((p=this.options.extensions)!=null&&p.startInline){let S=1/0,M=t.slice(1),v;this.options.extensions.startInline.forEach(b=>{v=b.call({lexer:this},M),typeof v=="number"&&v>=0&&(S=Math.min(S,v))}),S<1/0&&S>=0&&($=t.substring(0,S+1))}if(y=this.tokenizer.inlineText($)){t=t.substring(y.raw.length),y.raw.slice(-1)!=="_"&&(r=y.raw.slice(-1)),a=!0;let S=n.at(-1);(S==null?void 0:S.type)==="text"?(S.raw+=y.raw,S.text+=y.text):n.push(y);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}},Qi=class{constructor(e){q(this,"options");q(this,"parser");this.options=e||Dt}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,"")+`
2795
- `;return i?'<pre><code class="language-'+Qe(i)+'">'+(n?s:Qe(s,!0))+`</code></pre>
2796
- `:"<pre><code>"+(n?s:Qe(s,!0))+`</code></pre>
2868
+ `+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 l,d,h,u,p;let i=t,s=null;if(this.tokens.links){let y=Object.keys(this.tokens.links);if(y.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)y.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=(l=this.options.hooks)==null?void 0:l.emStrongMask)==null?void 0:d.call({lexer:this},i))??i;let a=!1,r="";for(;t;){a||(r=""),a=!1;let y;if((u=(h=this.options.extensions)==null?void 0:h.inline)!=null&&u.some(S=>(y=S.call({lexer:this},t,n))?(t=t.substring(y.raw.length),n.push(y),!0):!1))continue;if(y=this.tokenizer.escape(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.tag(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.link(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(y.raw.length);let S=n.at(-1);y.type==="text"&&(S==null?void 0:S.type)==="text"?(S.raw+=y.raw,S.text+=y.text):n.push(y);continue}if(y=this.tokenizer.emStrong(t,i,r)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.codespan(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.br(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.del(t)){t=t.substring(y.raw.length),n.push(y);continue}if(y=this.tokenizer.autolink(t)){t=t.substring(y.raw.length),n.push(y);continue}if(!this.state.inLink&&(y=this.tokenizer.url(t))){t=t.substring(y.raw.length),n.push(y);continue}let x=t;if((p=this.options.extensions)!=null&&p.startInline){let S=1/0,_=t.slice(1),v;this.options.extensions.startInline.forEach(b=>{v=b.call({lexer:this},_),typeof v=="number"&&v>=0&&(S=Math.min(S,v))}),S<1/0&&S>=0&&(x=t.substring(0,S+1))}if(y=this.tokenizer.inlineText(x)){t=t.substring(y.raw.length),y.raw.slice(-1)!=="_"&&(r=y.raw.slice(-1)),a=!0;let S=n.at(-1);(S==null?void 0:S.type)==="text"?(S.raw+=y.raw,S.text+=y.text):n.push(y);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}},Qi=class{constructor(e){z(this,"options");z(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,"")+`
2869
+ `;return i?'<pre><code class="language-'+qe(i)+'">'+(n?s:qe(s,!0))+`</code></pre>
2870
+ `:"<pre><code>"+(n?s:qe(s,!0))+`</code></pre>
2797
2871
  `}blockquote({tokens:e}){return`<blockquote>
2798
2872
  ${this.parser.parse(e)}</blockquote>
2799
2873
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -2809,26 +2883,26 @@ ${this.parser.parse(e)}</blockquote>
2809
2883
  `}tablerow({text:e}){return`<tr>
2810
2884
  ${e}</tr>
2811
2885
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
2812
- `}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=Xr(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=Xr(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)}},Ia=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}},Te=class Uo{constructor(t){q(this,"options");q(this,"renderer");q(this,"textRenderer");this.options=t||Dt,this.options.renderer=this.options.renderer||new Qi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ia}static parse(t,n){return new Uo(n).parse(t)}static parseInline(t,n){return new Uo(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 l=a,d=this.options.extensions.renderers[l.type].call({parser:this},l);if(d!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.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 l='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}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 l=r;switch(l.type){case"escape":{i+=n.text(l);break}case"html":{i+=n.html(l);break}case"link":{i+=n.link(l);break}case"image":{i+=n.image(l);break}case"checkbox":{i+=n.checkbox(l);break}case"strong":{i+=n.strong(l);break}case"em":{i+=n.em(l);break}case"codespan":{i+=n.codespan(l);break}case"br":{i+=n.br(l);break}case"del":{i+=n.del(l);break}case"text":{i+=n.text(l);break}default:{let d='Token with "'+l.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||Dt}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Ee.lex:Ee.lexInline}provideParser(){return this.block?Te.parse:Te.parseInline}},q($i,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),q($i,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),$i),Sy=class{constructor(...e){q(this,"defaults",Sa());q(this,"options",this.setOptions);q(this,"parse",this.parseMarkdown(!0));q(this,"parseInline",this.parseMarkdown(!1));q(this,"Parser",Te);q(this,"Renderer",Qi);q(this,"TextRenderer",Ia);q(this,"Lexer",Ee);q(this,"Tokenizer",Vi);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 l of r)n=n.concat(this.walkTokens(l.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 l=a[r].flat(1/0);n=n.concat(this.walkTokens(l,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 Qi(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],l=s[a];s[a]=(...d)=>{let h=r.apply(s,d);return h===!1&&(h=l.apply(s,d)),h||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Vi(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],l=s[a];s[a]=(...d)=>{let h=r.apply(s,d);return h===!1&&(h=l.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],l=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 l.call(s,u)})();let h=r.call(s,d);return l.call(s,h)}:s[a]=(...d)=>{if(this.defaults.async)return(async()=>{let u=await r.apply(s,d);return u===!1&&(u=await l.apply(s,d)),u})();let h=r.apply(s,d);return h===!1&&(h=l.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 Ee.lex(e,t??this.defaults)}parser(e,t){return Te.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?Ee.lex:Ee.lexInline)(a,s),l=s.hooks?await s.hooks.processAllTokens(r):r;s.walkTokens&&await Promise.all(this.walkTokens(l,s.walkTokens));let d=await(s.hooks?await s.hooks.provideParser():e?Te.parse:Te.parseInline)(l,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?Ee.lex:Ee.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?Te.parse:Te.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+=`
2813
- 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}}},Mt=new Sy;function V(e,t){return Mt.parse(e,t)}V.options=V.setOptions=function(e){return Mt.setOptions(e),V.defaults=Mt.defaults,Md(V.defaults),V};V.getDefaults=Sa;V.defaults=Dt;V.use=function(...e){return Mt.use(...e),V.defaults=Mt.defaults,Md(V.defaults),V};V.walkTokens=function(e,t){return Mt.walkTokens(e,t)};V.parseInline=Mt.parseInline;V.Parser=Te;V.parser=Te.parse;V.Renderer=Qi;V.TextRenderer=Ia;V.Lexer=Ee;V.lexer=Ee.lex;V.Tokenizer=Vi;V.Hooks=An;V.parse=V;V.options;V.setOptions;V.use;V.walkTokens;V.parseInline;Te.parse;Ee.lex;V.setOptions({gfm:!0,breaks:!0,mangle:!1});const tl=["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"],nl=["class","href","rel","target","title","start"];let il=!1;const Ay=14e4,Cy=4e4,Ey=200,Zs=5e4,wt=new Map;function Ty(e){const t=wt.get(e);return t===void 0?null:(wt.delete(e),wt.set(e,t),t)}function sl(e,t){if(wt.set(e,t),wt.size<=Ey)return;const n=wt.keys().next().value;n&&wt.delete(n)}function _y(){il||(il=!0,No.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function Ji(e){const t=e.trim();if(!t)return"";if(_y(),t.length<=Zs){const a=Ty(t);if(a!==null)return a}const n=Zl(t,Ay),i=n.truncated?`
2886
+ `}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=Xr(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=Xr(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)}},Ia=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 Uo{constructor(t){z(this,"options");z(this,"renderer");z(this,"textRenderer");this.options=t||Lt,this.options.renderer=this.options.renderer||new Qi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ia}static parse(t,n){return new Uo(n).parse(t)}static parseInline(t,n){return new Uo(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 l=a,d=this.options.extensions.renderers[l.type].call({parser:this},l);if(d!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.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 l='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}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 l=r;switch(l.type){case"escape":{i+=n.text(l);break}case"html":{i+=n.html(l);break}case"link":{i+=n.link(l);break}case"image":{i+=n.image(l);break}case"checkbox":{i+=n.checkbox(l);break}case"strong":{i+=n.strong(l);break}case"em":{i+=n.em(l);break}case"codespan":{i+=n.codespan(l);break}case"br":{i+=n.br(l);break}case"del":{i+=n.del(l);break}case"text":{i+=n.text(l);break}default:{let d='Token with "'+l.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){z(this,"options");z(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}},z($i,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),z($i,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),$i),Ey=class{constructor(...e){z(this,"defaults",Sa());z(this,"options",this.setOptions);z(this,"parse",this.parseMarkdown(!0));z(this,"parseInline",this.parseMarkdown(!1));z(this,"Parser",Ce);z(this,"Renderer",Qi);z(this,"TextRenderer",Ia);z(this,"Lexer",Ae);z(this,"Tokenizer",Gi);z(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 l of r)n=n.concat(this.walkTokens(l.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 l=a[r].flat(1/0);n=n.concat(this.walkTokens(l,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 Qi(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],l=s[a];s[a]=(...d)=>{let h=r.apply(s,d);return h===!1&&(h=l.apply(s,d)),h||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Gi(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],l=s[a];s[a]=(...d)=>{let h=r.apply(s,d);return h===!1&&(h=l.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],l=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 l.call(s,u)})();let h=r.call(s,d);return l.call(s,h)}:s[a]=(...d)=>{if(this.defaults.async)return(async()=>{let u=await r.apply(s,d);return u===!1&&(u=await l.apply(s,d)),u})();let h=r.apply(s,d);return h===!1&&(h=l.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),l=s.hooks?await s.hooks.processAllTokens(r):r;s.walkTokens&&await Promise.all(this.walkTokens(l,s.walkTokens));let d=await(s.hooks?await s.hooks.provideParser():e?Ce.parse:Ce.parseInline)(l,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+=`
2887
+ 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 Ey;function j(e,t){return _t.parse(e,t)}j.options=j.setOptions=function(e){return _t.setOptions(e),j.defaults=_t.defaults,Pd(j.defaults),j};j.getDefaults=Sa;j.defaults=Lt;j.use=function(...e){return _t.use(...e),j.defaults=_t.defaults,Pd(j.defaults),j};j.walkTokens=function(e,t){return _t.walkTokens(e,t)};j.parseInline=_t.parseInline;j.Parser=Ce;j.parser=Ce.parse;j.Renderer=Qi;j.TextRenderer=Ia;j.Lexer=Ae;j.lexer=Ae.lex;j.Tokenizer=Gi;j.Hooks=An;j.parse=j;j.options;j.setOptions;j.use;j.walkTokens;j.parseInline;Ce.parse;Ae.lex;j.setOptions({gfm:!0,breaks:!0,mangle:!1});const tl=["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"],nl=["class","href","rel","target","title","start"];let il=!1;const Ty=14e4,_y=4e4,My=200,Zs=5e4,wt=new Map;function Py(e){const t=wt.get(e);return t===void 0?null:(wt.delete(e),wt.set(e,t),t)}function sl(e,t){if(wt.set(e,t),wt.size<=My)return;const n=wt.keys().next().value;n&&wt.delete(n)}function Iy(){il||(il=!0,No.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function Ji(e){const t=e.trim();if(!t)return"";if(Iy(),t.length<=Zs){const a=Py(t);if(a!==null)return a}const n=Zl(t,Ty),i=n.truncated?`
2814
2888
 
2815
- … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>Cy){const r=`<pre class="code-block">${My(`${n.text}${i}`)}</pre>`,l=No.sanitize(r,{ALLOWED_TAGS:tl,ALLOWED_ATTR:nl});return t.length<=Zs&&sl(t,l),l}const s=V.parse(`${n.text}${i}`),o=No.sanitize(s,{ALLOWED_TAGS:tl,ALLOWED_ATTR:nl});return t.length<=Zs&&sl(t,o),o}function My(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const Py=1500,Iy=2e3,Wd="Copy as markdown",Ry="Copied",Ly="Copy failed";async function Dy(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 By(e){const t=e.label??Wd;return c`
2889
+ … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>_y){const r=`<pre class="code-block">${Ry(`${n.text}${i}`)}</pre>`,l=No.sanitize(r,{ALLOWED_TAGS:tl,ALLOWED_ATTR:nl});return t.length<=Zs&&sl(t,l),l}const s=j.parse(`${n.text}${i}`),o=No.sanitize(s,{ALLOWED_TAGS:tl,ALLOWED_ATTR:nl});return t.length<=Zs&&sl(t,o),o}function Ry(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const Ly=1500,Dy=2e3,zd="Copy as markdown",By="Copied",Ny="Copy failed";async function Oy(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 Fy(e){const t=e.label??zd;return c`
2816
2890
  <button
2817
2891
  class="chat-copy-btn"
2818
2892
  type="button"
2819
2893
  title=${t}
2820
2894
  aria-label=${t}
2821
- @click=${async n=>{const i=n.currentTarget;if(i==null||i.querySelector(".chat-copy-btn__icon"),!i||i.dataset.copying==="1")return;i.dataset.copying="1",i.setAttribute("aria-busy","true"),i.disabled=!0;const s=await Dy(e.text());if(i.isConnected){if(delete i.dataset.copying,i.removeAttribute("aria-busy"),i.disabled=!1,!s){i.dataset.error="1",mi(i,Ly),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.error,mi(i,t))},Iy);return}i.dataset.copied="1",mi(i,Ry),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.copied,mi(i,t))},Py)}}}
2895
+ @click=${async n=>{const i=n.currentTarget;if(i==null||i.querySelector(".chat-copy-btn__icon"),!i||i.dataset.copying==="1")return;i.dataset.copying="1",i.setAttribute("aria-busy","true"),i.disabled=!0;const s=await Oy(e.text());if(i.isConnected){if(delete i.dataset.copying,i.removeAttribute("aria-busy"),i.disabled=!1,!s){i.dataset.error="1",mi(i,Ny),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.error,mi(i,t))},Dy);return}i.dataset.copied="1",mi(i,By),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.copied,mi(i,t))},Ly)}}}
2822
2896
  >
2823
2897
  <span class="chat-copy-btn__icon" aria-hidden="true">
2824
2898
  <span class="chat-copy-btn__icon-copy">${I.copy}</span>
2825
2899
  <span class="chat-copy-btn__icon-check">${I.check}</span>
2826
2900
  </span>
2827
2901
  </button>
2828
- `}function Ny(e){return By({text:()=>e,label:Wd})}function Oy(e){const t=e,n=Fy(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:Uy(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=Wy(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(sc(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=ec(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function Fy(e){return Array.isArray(e)?e.filter(Boolean):[]}function Uy(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 Wy(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const eo=40,to=new Map;async function zy(e){const t=to.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/eo),l=[];for(let u=0;u<eo;u++){let p=0;const y=u*r,$=Math.min(y+r,a.length);for(let S=y;S<$;S++){const M=Math.abs(a[S]);M>p&&(p=M)}l.push(p)}const d=Math.max(...l,.01),h=l.map(u=>Math.max(u/d,.08));return to.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<eo;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return to.set(e,i),i}}const no=[1,1.5,2],Yi=new Map;function Ky(e){let t=Yi.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:[]},Yi.set(e,t),zy(e).then(i=>{t.waveform=i,zd(e)}),t}const Rn="http://www.w3.org/2000/svg";function Hy(){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 qy(){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 qt(e){return document.querySelector(`.vnp[data-url="${CSS.escape(e)}"]`)}function zd(e){const t=qt(e);if(!t)return;const n=Yi.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?Xi(t.currentTime):Xi(t.duration))}function io(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?qy():Hy();i?n.replaceChild(s,i):n.appendChild(s)}function Xi(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 ol=new Set;function jy(e){if(ol.has(e))return;ol.add(e);const t=Yi.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=qt(e);i&&Ln(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=qt(e);i&&Ln(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=qt(e);i&&(Ln(i,t),io(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=qt(e);i&&io(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=qt(e);i&&io(i,!0)})}function Gy(e,t){const n=Ky(e);jy(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const l=no.indexOf(n.speed),d=no[(l+1)%no.length];n.speed=d,n.audio.playbackRate=d;const h=r.target.closest(".vnp__speed");h&&(h.textContent=`${d}×`)},o=r=>{r.stopPropagation();const l=r.target.closest(".vnp__waveform");if(!l)return;const d=l.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=l.closest(".vnp");u&&Ln(u,n)}},a=n.playing||n.currentTime>0?Xi(n.currentTime):Xi(n.duration);return queueMicrotask(()=>zd(e)),c`
2902
+ `}function Uy(e){return Fy({text:()=>e,label:zd})}function Wy(e){const t=e,n=zy(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:Ky(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=Hy(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(sc(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=ec(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function zy(e){return Array.isArray(e)?e.filter(Boolean):[]}function Ky(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 Hy(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const eo=40,to=new Map;async function qy(e){const t=to.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/eo),l=[];for(let u=0;u<eo;u++){let p=0;const y=u*r,x=Math.min(y+r,a.length);for(let S=y;S<x;S++){const _=Math.abs(a[S]);_>p&&(p=_)}l.push(p)}const d=Math.max(...l,.01),h=l.map(u=>Math.max(u/d,.08));return to.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<eo;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return to.set(e,i),i}}const no=[1,1.5,2],Yi=new Map;function jy(e){let t=Yi.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:[]},Yi.set(e,t),qy(e).then(i=>{t.waveform=i,Kd(e)}),t}const Rn="http://www.w3.org/2000/svg";function Vy(){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 Gy(){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 qt(e){return document.querySelector(`.vnp[data-url="${CSS.escape(e)}"]`)}function Kd(e){const t=qt(e);if(!t)return;const n=Yi.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?Xi(t.currentTime):Xi(t.duration))}function io(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?Gy():Vy();i?n.replaceChild(s,i):n.appendChild(s)}function Xi(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 ol=new Set;function Qy(e){if(ol.has(e))return;ol.add(e);const t=Yi.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=qt(e);i&&Ln(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=qt(e);i&&Ln(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=qt(e);i&&(Ln(i,t),io(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=qt(e);i&&io(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=qt(e);i&&io(i,!0)})}function Jy(e,t){const n=jy(e);Qy(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const l=no.indexOf(n.speed),d=no[(l+1)%no.length];n.speed=d,n.audio.playbackRate=d;const h=r.target.closest(".vnp__speed");h&&(h.textContent=`${d}×`)},o=r=>{r.stopPropagation();const l=r.target.closest(".vnp__waveform");if(!l)return;const d=l.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=l.closest(".vnp");u&&Ln(u,n)}},a=n.playing||n.currentTime>0?Xi(n.currentTime):Xi(n.duration);return queueMicrotask(()=>Kd(e)),c`
2829
2903
  <div class="vnp" data-url=${e} @click=${r=>r.stopPropagation()}>
2830
2904
  <button class="vnp__play" @click=${i} aria-label=${n.playing?"Pause":"Play"}>
2831
- ${n.playing?Qy():Vy()}
2905
+ ${n.playing?Xy():Yy()}
2832
2906
  </button>
2833
2907
 
2834
2908
  <div class="vnp__body">
@@ -2841,7 +2915,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2841
2915
  </div>
2842
2916
  </div>
2843
2917
  </div>
2844
- `}function Vy(){return c`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function Qy(){return c`<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 Jy(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,l=r.data,d=r.media_type||"image/png",h=l.startsWith("data:")?l:`data:${d};base64,${l}`;i.push({url:h})}else if(typeof a.data=="string"&&a.data){const r=a.data,l=a.mimeType||a.media_type||"image/png",d=r.startsWith("data:")?r:`data:${l};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 Yy(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 Xy(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Zy(e){return c`
2918
+ `}function Yy(){return c`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function Xy(){return c`<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 Zy(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,l=r.data,d=r.media_type||"image/png",h=l.startsWith("data:")?l:`data:${d};base64,${l}`;i.push({url:h})}else if(typeof a.data=="string"&&a.data){const r=a.data,l=a.mimeType||a.media_type||"image/png",d=r.startsWith("data:")?r:`data:${l};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 ev(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 tv(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function nv(e){return c`
2845
2919
  <div class="chat-group assistant">
2846
2920
  <div class="chat-group-messages">
2847
2921
  <div class="chat-bubble chat-reading-indicator" aria-hidden="true">
@@ -2851,7 +2925,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2851
2925
  </div>
2852
2926
  </div>
2853
2927
  </div>
2854
- `}function ev(e){return c`
2928
+ `}function iv(e){return c`
2855
2929
  <div class="chat-group assistant">
2856
2930
  <div class="chat-group-messages">
2857
2931
  <div class="chat-interim fade-in">
@@ -2859,13 +2933,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2859
2933
  </div>
2860
2934
  </div>
2861
2935
  </div>
2862
- `}function tv(e,t,n,i){return c`
2936
+ `}function sv(e,t,n,i){return c`
2863
2937
  <div class="chat-group assistant">
2864
2938
  <div class="chat-group-messages">
2865
- ${Kd({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
2939
+ ${Hd({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
2866
2940
  </div>
2867
2941
  </div>
2868
- `}function nv(e,t){const n=ic(e.role),i=n==="user"?"user":n==="assistant"?"assistant":"other",s=new Date(e.timestamp).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"}),o=e.messages.map((a,r)=>Kd(a.message,{isStreaming:e.isStreaming&&r===e.messages.length-1,showReasoning:t.showReasoning}));return o.every(a=>a===w)?w:c`
2942
+ `}function ov(e,t){const n=ic(e.role),i=n==="user"?"user":n==="assistant"?"assistant":"other",s=new Date(e.timestamp).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"}),o=e.messages.map((a,r)=>Hd(a.message,{isStreaming:e.isStreaming&&r===e.messages.length-1,showReasoning:t.showReasoning}));return o.every(a=>a===w)?w:c`
2869
2943
  <div class="chat-group ${i}">
2870
2944
  <div class="chat-group-messages">
2871
2945
  ${o}
@@ -2874,7 +2948,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2874
2948
  </div>
2875
2949
  </div>
2876
2950
  </div>
2877
- `}function iv(e){return e.length===0?w:c`
2951
+ `}function av(e){return e.length===0?w:c`
2878
2952
  <div class="chat-message-images">
2879
2953
  ${e.map(t=>c`
2880
2954
  <img
@@ -2885,12 +2959,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2885
2959
  />
2886
2960
  `)}
2887
2961
  </div>
2888
- `}function sv(e){return e.length===0?w:c`
2962
+ `}function rv(e){return e.length===0?w:c`
2889
2963
  <div class="chat-message-files">
2890
- ${e.map(t=>t.mimeType==="application/pdf"?av(t):t.mimeType.startsWith("audio/")?Gy(t.url,t.name):rv(t))}
2964
+ ${e.map(t=>t.mimeType==="application/pdf"?cv(t):t.mimeType.startsWith("audio/")?Jy(t.url,t.name):dv(t))}
2891
2965
  </div>
2892
- `}function ov(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 l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.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"),l.append(d,h),r.appendChild(l),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 av(e){return c`
2893
- <div class="chat-pdf-preview" @click=${()=>ov(e.url,e.name)}>
2966
+ `}function lv(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 l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.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"),l.append(d,h),r.appendChild(l),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 cv(e){return c`
2967
+ <div class="chat-pdf-preview" @click=${()=>lv(e.url,e.name)}>
2894
2968
  <iframe
2895
2969
  src=${e.url}
2896
2970
  class="chat-pdf-preview__frame"
@@ -2904,39 +2978,39 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2904
2978
  @click=${t=>t.stopPropagation()}
2905
2979
  >${e.name}</a>
2906
2980
  </div>
2907
- `}function rv(e){return c`
2981
+ `}function dv(e){return c`
2908
2982
  <a
2909
2983
  class="chat-file-card"
2910
2984
  href=${e.url}
2911
2985
  target="_blank"
2912
2986
  rel="noreferrer noopener"
2913
2987
  >
2914
- <span class="chat-file-card__icon">${Xy(e.mimeType)}</span>
2988
+ <span class="chat-file-card__icon">${tv(e.mimeType)}</span>
2915
2989
  <span class="chat-file-card__name">${e.name}</span>
2916
2990
  </a>
2917
- `}function Kd(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=sc(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=Oy(e).length>0,l=Jy(e),d=l.length>0,h=Yy(e),u=h.length>0,p=ec(e),y=t.showReasoning&&s==="assistant"?zp(e):null,$=p!=null&&p.trim()?p:null,S=y?Hp(y):null,M=$,v=(s==="assistant"||s==="user")&&!!(M!=null&&M.trim()),b=["chat-bubble",v?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!M&&(r||o)||!M&&!d&&!u?w:c`
2991
+ `}function Hd(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=sc(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=Wy(e).length>0,l=Zy(e),d=l.length>0,h=ev(e),u=h.length>0,p=ec(e),y=t.showReasoning&&s==="assistant"?Kp(e):null,x=p!=null&&p.trim()?p:null,S=y?qp(y):null,_=x,v=(s==="assistant"||s==="user")&&!!(_!=null&&_.trim()),b=["chat-bubble",v?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!_&&(r||o)||!_&&!d&&!u?w:c`
2918
2992
  <div class="${b}">
2919
- ${v?Ny(M):w}
2920
- ${iv(l)}
2921
- ${sv(h)}
2993
+ ${v?Uy(_):w}
2994
+ ${av(l)}
2995
+ ${rv(h)}
2922
2996
  ${S?c`<div class="chat-thinking">${ji(Ji(S))}</div>`:w}
2923
- ${M?c`<div class="chat-text">${ji(Ji(M))}</div>`:w}
2997
+ ${_?c`<div class="chat-text">${ji(Ji(_))}</div>`:w}
2924
2998
  </div>
2925
- `}const O={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let G=null,$t=null,St=!1;function al(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}$t&&(clearTimeout($t),$t=null),Zi(),O.mediaRecorder=null,O.audioChunks=[],O.active=!1,O.cancelled=!1,St=!1}async function Hd(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,l=s.mimeType.includes("mp4")?"m4a":"webm",d={id:ls(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${l}`};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 qd(){!O.active||!O.mediaRecorder||(O.cancelled=!1,O.mediaRecorder.state==="recording"&&O.mediaRecorder.stop())}function jd(){!O.active||!O.mediaRecorder||(O.cancelled=!0,O.mediaRecorder.state==="recording"?O.mediaRecorder.stop():(mt(),G==null||G.onRequestRender()))}function lv(){document.addEventListener("pointerup",Gd)}function Zi(){document.removeEventListener("pointerup",Gd)}function Gd(e){if(!St&&!O.active){Zi();return}if(St=!1,Zi(),$t&&(clearTimeout($t),$t=null,!O.active)){Hd("tap");return}O.active&&O.mode==="hold"&&(O.cancelled?jd():qd()),e.preventDefault()}function cv(e){O.active||(St=!0,O.startX=e.clientX,lv(),$t=setTimeout(async()=>{if(!St)return;await Hd("hold")||(St=!1,Zi())},300))}function rl(e){if(!O.active||O.mode!=="hold"||!St)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 dv(){return O.active}function uv(e){G=e}function pv(e){return c`
2999
+ `}const N={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let H=null,$t=null,St=!1;function al(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}function mt(){if(N.timerId&&(clearInterval(N.timerId),N.timerId=null),N.stream){for(const e of N.stream.getTracks())e.stop();N.stream=null}$t&&(clearTimeout($t),$t=null),Zi(),N.mediaRecorder=null,N.audioChunks=[],N.active=!1,N.cancelled=!1,St=!1}async function qd(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});N.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 N.mediaRecorder=s,N.audioChunks=[],N.mode=e,N.startTime=Date.now(),N.elapsed=0,N.active=!0,N.cancelled=!1,s.ondataavailable=o=>{o.data.size>0&&N.audioChunks.push(o.data)},s.onstop=()=>{if(N.cancelled){mt(),H==null||H.onRequestRender();return}const o=new Blob(N.audioChunks,{type:s.mimeType});if(o.size===0){mt(),H==null||H.onRequestRender();return}const a=new FileReader;a.onload=()=>{const r=a.result,l=s.mimeType.includes("mp4")?"m4a":"webm",d={id:ls(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${l}`};mt(),H==null||H.onSend(d),H==null||H.onRequestRender()},a.onerror=()=>{mt(),H==null||H.onRequestRender()},a.readAsDataURL(o)},s.start(250),N.timerId=setInterval(()=>{N.elapsed=Math.floor((Date.now()-N.startTime)/1e3),H==null||H.onRequestRender()},1e3),H==null||H.onRequestRender(),!0}catch(n){return console.warn("[voice] startRecording failed:",n),mt(),!1}}function jd(){!N.active||!N.mediaRecorder||(N.cancelled=!1,N.mediaRecorder.state==="recording"&&N.mediaRecorder.stop())}function Vd(){!N.active||!N.mediaRecorder||(N.cancelled=!0,N.mediaRecorder.state==="recording"?N.mediaRecorder.stop():(mt(),H==null||H.onRequestRender()))}function uv(){document.addEventListener("pointerup",Gd)}function Zi(){document.removeEventListener("pointerup",Gd)}function Gd(e){if(!St&&!N.active){Zi();return}if(St=!1,Zi(),$t&&(clearTimeout($t),$t=null,!N.active)){qd("tap");return}N.active&&N.mode==="hold"&&(N.cancelled?Vd():jd()),e.preventDefault()}function pv(e){N.active||(St=!0,N.startX=e.clientX,uv(),$t=setTimeout(async()=>{if(!St)return;await qd("hold")||(St=!1,Zi())},300))}function rl(e){if(!N.active||N.mode!=="hold"||!St)return;const t=N.startX-e.clientX;t>80?(N.cancelled=!0,H==null||H.onRequestRender()):N.cancelled&&t<=60&&(N.cancelled=!1,H==null||H.onRequestRender())}function hv(){return N.active}function fv(e){H=e}function gv(e){return c`
2926
3000
  <button
2927
3001
  class="btn btn--icon chat-compose__mic"
2928
3002
  ?disabled=${!e}
2929
- @pointerdown=${cv}
3003
+ @pointerdown=${pv}
2930
3004
  aria-label="Record voice note"
2931
3005
  title="Tap to record, hold to send on release"
2932
3006
  >
2933
3007
  ${I.mic}
2934
3008
  </button>
2935
- `}function hv(){return O.active?O.mode==="tap"?c`
3009
+ `}function mv(){return N.active?N.mode==="tap"?c`
2936
3010
  <div class="chat-voice-recording" @pointermove=${rl}>
2937
3011
  <button
2938
3012
  class="btn btn--icon chat-voice-recording__trash"
2939
- @click=${jd}
3013
+ @click=${Vd}
2940
3014
  aria-label="Cancel recording"
2941
3015
  title="Discard"
2942
3016
  >
@@ -2944,11 +3018,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2944
3018
  </button>
2945
3019
  <div class="chat-voice-recording__indicator">
2946
3020
  <span class="chat-voice-recording__dot"></span>
2947
- <span class="chat-voice-recording__timer">${al(O.elapsed)}</span>
3021
+ <span class="chat-voice-recording__timer">${al(N.elapsed)}</span>
2948
3022
  </div>
2949
3023
  <button
2950
3024
  class="btn btn--icon chat-voice-recording__send primary"
2951
- @click=${qd}
3025
+ @click=${jd}
2952
3026
  aria-label="Send voice note"
2953
3027
  title="Send"
2954
3028
  >
@@ -2959,13 +3033,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2959
3033
  <div class="chat-voice-recording hold" @pointermove=${rl}>
2960
3034
  <div class="chat-voice-recording__indicator">
2961
3035
  <span class="chat-voice-recording__dot"></span>
2962
- <span class="chat-voice-recording__timer">${al(O.elapsed)}</span>
2963
- <span class="chat-voice-recording__slide ${O.cancelled?"cancelled":""}">
2964
- ${O.cancelled?"Release to cancel":"← Slide to cancel"}
3036
+ <span class="chat-voice-recording__timer">${al(N.elapsed)}</span>
3037
+ <span class="chat-voice-recording__slide ${N.cancelled?"cancelled":""}">
3038
+ ${N.cancelled?"Release to cancel":"← Slide to cancel"}
2965
3039
  </span>
2966
3040
  </div>
2967
3041
  </div>
2968
- `:w}function fv(e){return c`
3042
+ `:w}function yv(e){return c`
2969
3043
  <div class="sidebar-panel">
2970
3044
  <div class="sidebar-header">
2971
3045
  <div class="sidebar-title">Tool Output</div>
@@ -2982,7 +3056,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2982
3056
  `:e.content?c`<div class="sidebar-markdown">${ji(Ji(e.content))}</div>`:c`<div class="muted">No content available</div>`}
2983
3057
  </div>
2984
3058
  </div>
2985
- `}var gv=Object.defineProperty,mv=Object.getOwnPropertyDescriptor,ys=(e,t,n,i)=>{for(var s=i>1?void 0:i?mv(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&&gv(t,n,s),s};let Yt=class extends Gt{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,s=(e.clientX-this.startX)/n;let o=this.startRatio+s;o=Math.max(this.minRatio,Math.min(this.maxRatio,o)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:o},bubbles:!0,composed:!0}))},this.handleMouseUp=()=>{this.isDragging=!1,this.classList.remove("dragging"),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}render(){return c``}connectedCallback(){super.connectedCallback(),this.addEventListener("mousedown",this.handleMouseDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}};Yt.styles=Zu`
3059
+ `}var vv=Object.defineProperty,bv=Object.getOwnPropertyDescriptor,ys=(e,t,n,i)=>{for(var s=i>1?void 0:i?bv(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&&vv(t,n,s),s};let Yt=class extends Vt{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,s=(e.clientX-this.startX)/n;let o=this.startRatio+s;o=Math.max(this.minRatio,Math.min(this.maxRatio,o)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:o},bubbles:!0,composed:!0}))},this.handleMouseUp=()=>{this.isDragging=!1,this.classList.remove("dragging"),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}render(){return c``}connectedCallback(){super.connectedCallback(),this.addEventListener("mousedown",this.handleMouseDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}};Yt.styles=ep`
2986
3060
  :host {
2987
3061
  width: 4px;
2988
3062
  cursor: col-resize;
@@ -3008,21 +3082,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3008
3082
  :host(.dragging) {
3009
3083
  background: var(--accent, #007bff);
3010
3084
  }
3011
- `;ys([as({type:Number})],Yt.prototype,"splitRatio",2);ys([as({type:Number})],Yt.prototype,"minRatio",2);ys([as({type:Number})],Yt.prototype,"maxRatio",2);Yt=ys([jl("resizable-divider")],Yt);function yi(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function so(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const yv=1,vv=1,Bt="emoji",Xt="keyvalue",Ra="favorites",bv="tokens",Vd="tokens",wv="unicode",Qd="count",kv="group",xv="order",Jd="group-order",Wo="eTag",es="url",ll="skinTone",ln="readonly",La="readwrite",Yd="skinUnicodes",$v="skinUnicodes",Sv="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Av="en";function Cv(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 cl(e){return Cv(e,t=>t.unicode)}function Ev(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[a,[r,l]]of Object.entries(s))o.createIndex(a,r,{multiEntry:l});return o}t(Xt),t(Bt,wv,{[Vd]:[bv,!0],[Jd]:[[kv,xv]],[Yd]:[$v,!0]}),t(Ra,void 0,{[Qd]:[""]})}const zo={},Ei={},ts={};function Xd(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function Tv(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,yv);zo[e]=s,s.onupgradeneeded=o=>{o.oldVersion<vv&&Ev(s.result)},Xd(n,i,s)});return t.onclose=()=>Da(e),t}function _v(e){return Ei[e]||(Ei[e]=Tv(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 l;i(r,a,d=>{l=d}),a.oncomplete=()=>s(l),a.onerror=()=>o(a.error)})}function Da(e){const t=zo[e],n=t&&t.result;if(n){n.close();const i=ts[e];if(i)for(const s of i)s()}delete zo[e],delete Ei[e],delete ts[e]}function Mv(e){return new Promise((t,n)=>{Da(e);const i=indexedDB.deleteDatabase(e);Xd(t,n,i)})}function Pv(e,t){let n=ts[e];n||(n=ts[e]=[]),n.push(t)}const Iv=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/)||Iv.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const Rv=2;function Zd(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=Rv)}function Lv(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:l,emoji:d,version:h})=>{const u=[...new Set(Zd([...(a||[]).map(Vt).flat(),...(l||[]).map(Vt).flat(),...Vt(n),i]))].sort(),p={annotation:n,group:s,order:o,tags:l,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:y,emoji:$,version:S}of r)p.skinTones.push(y),p.skinUnicodes.push($),p.skinVersions.push(S)}return p})}function eu(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function Pt(e,t,n){eu(e,"get",t,n)}function tu(e,t,n){eu(e,"getAll",t,n)}function Ba(e){e.commit&&e.commit()}function Dv(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 nu(e,t){const n=Dv(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 Bv(e){return!await Na(e,Xt,es)}async function Nv(e,t,n){const[i,s]=await Promise.all([Wo,es].map(o=>Na(e,Xt,o)));return i===n&&s===t}async function Ov(e,t){return Ze(e,Bt,ln,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=l=>{const d=l.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 iu(e,t,n,i){{const s=Lv(t);await Ze(e,[Bt,Xt],La,([o,a],r)=>{let l,d,h=0;function u(){++h===2&&p()}function p(){if(!(l===i&&d===n)){o.clear();for(const y of s)o.put(y);a.put(i,Wo),a.put(n,es),Ba(r)}}Pt(a,Wo,y=>{l=y,u()}),Pt(a,es,y=>{d=y,u()})})}}async function Fv(e,t){return Ze(e,Bt,ln,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);tu(n.index(Jd),o,s)})}async function su(e,t){const n=Zd(Vt(t));return n.length?Ze(e,Bt,ln,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&l()},l=()=>{const d=nu(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);tu(i.index(Vd),u,p=>{a.push(p),r()})}}):[]}async function Uv(e,t){const n=await su(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await Ov(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function Wv(e,t){return Ze(e,Bt,ln,(n,i,s)=>Pt(n,t,o=>{if(o)return s(o);Pt(n.index(Yd),t,a=>s(a||null))}))}function Na(e,t,n){return Ze(e,t,ln,(i,s,o)=>Pt(i,n,o))}function zv(e,t,n,i){return Ze(e,t,La,(s,o)=>{s.put(i,n),Ba(o)})}function Kv(e,t){return Ze(e,Ra,La,(n,i)=>Pt(n,t,s=>{n.put((s||0)+1,t),Ba(i)}))}function Hv(e,t,n){return n===0?[]:Ze(e,[Ra,Bt],ln,([i,s],o,a)=>{const r=[];i.index(Qd).openCursor(void 0,"prev").onsuccess=l=>{const d=l.target.result;if(!d)return a(r);function h(y){if(r.push(y),r.length===n)return a(r);d.continue()}const u=d.primaryKey,p=t.byName(u);if(p)return h(p);Pt(s,u,y=>{if(y)return h(y);d.continue()})}})}const vi="";function qv(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 l=r.get(vi);l||(l=[],r.set(vi,l)),l.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=[],l=[a];for(;l.length;){const h=[...l.shift().entries()].sort((u,p)=>u[0]<p[0]?-1:1);for(const[u,p]of h)u===vi?r.push(...p):l.push(p)}return r}}const jv=["name","url"];function Gv(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||jv.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function dl(e){Gv(e);const t=(p,y)=>p.name.toLowerCase()<y.name.toLowerCase()?-1:1,n=e.sort(t),s=qv(e,p=>{const y=new Set;if(p.shortcodes)for(const $ of p.shortcodes)for(const S of Vt($))y.add(S);return y}),o=p=>s(p,!0),a=p=>s(p,!1),r=p=>{const y=Vt(p),$=y.map((S,M)=>(M<y.length-1?o:a)(S));return nu($,S=>S.name).sort(t)},l=new Map,d=new Map;for(const p of e){d.set(p.name.toLowerCase(),p);for(const y of p.shortcodes||[])l.set(y.toLowerCase(),p)}return{all:n,search:r,byShortcode:p=>l.get(p.toLowerCase()),byName:p=>d.get(p.toLowerCase())}}const Vv=typeof wrappedJSObject<"u";function $n(e){if(!e)return e;if(Vv&&(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 ou(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Qv=["annotation","emoji","group","order","version"];function Jv(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Qv.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function au(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Yv(e){const t=await fetch(e,{method:"HEAD"});au(t,e);const n=t.headers.get("etag");return ou(n),n}async function Ko(e){const t=await fetch(e);au(t,e);const n=t.headers.get("etag");ou(n);const i=await t.json();return Jv(i),[n,i]}function Xv(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Zv(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 ru(e){const t=JSON.stringify(e);let n=Zv(t);const i=await crypto.subtle.digest("SHA-1",n),s=Xv(i);return btoa(s)}async function eb(e,t){let n,i=await Yv(t);if(!i){const s=await Ko(t);i=s[0],n=s[1],i||(i=await ru(n))}await Nv(e,t,i)||(n||(n=(await Ko(t))[1]),await iu(e,n,t,i))}async function tb(e,t){let[n,i]=await Ko(t);n||(n=await ru(i)),await iu(e,i,t,n)}async function nb(e,t){try{await eb(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class ib{constructor({dataSource:t=Sv,locale:n=Av,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=dl(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await _v(this._dbName);Pv(this._dbName,this._clear);const n=this.dataSource;await Bv(t)?await tb(t,n):this._lazyUpdate=nb(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 so(t),await this.ready(),cl(await Fv(this._db,t)).map($n)}async getEmojiBySearchQuery(t){yi(t),await this.ready();const n=this._custom.search(t),i=cl(await su(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 Uv(this._db,t))}async getEmojiByUnicodeOrName(t){yi(t),await this.ready();const n=this._custom.byName(t);return n||$n(await Wv(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Na(this._db,Xt,ll)||0}async setPreferredSkinTone(t){return so(t),await this.ready(),zv(this._db,Xt,ll,t)}async incrementFavoriteEmojiCount(t){return yi(t),await this.ready(),Kv(this._db,t)}async getTopFavoriteEmoji(t){return so(t),await this.ready(),(await Hv(this._db,this._custom,t)).map($n)}set customEmoji(t){this._custom=dl(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 Da(this._dbName)}async delete(){await this._shutdown(),await Mv(this._dbName)}}const Ho=[[-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})),oo=Ho.slice(1),sb=2,ul=6,lu=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function pl(e){return e.unicode.includes("‍")}const ob={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},ab=1e3,rb="🖐️",lb=8,cb=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],cu='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',db=(e,t)=>e<t?-1:e>t?1:0,hl=(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 ${cu}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},ub=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function pb(e){const t=hl(e,"#000"),n=hl(e,"#fff");return t&&n&&ub(t,n)}function hb(){const e=Object.entries(ob);try{for(const[t,n]of e)if(pb(t))return n}catch{}return e[0][1]}let ao;const ro=()=>(ao||(ao=new Promise(e=>lu(()=>e(hb())))),ao),qo=new Map,fb="️",gb="\uD83C",mb="‍",yb=127995,vb=57339;function bb(e,t){if(t===0)return e;const n=e.indexOf(mb);return n!==-1?e.substring(0,n)+String.fromCodePoint(yb+t-1)+e.substring(n):(e.endsWith(fb)&&(e=e.substring(0,e.length-1)),e+gb+String.fromCodePoint(vb+t-1))}function Be(e){e.preventDefault(),e.stopPropagation()}function lo(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function du(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 wb(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:l,annotation:d})=>({unicode:i,name:r,shortcodes:o,url:a,category:l,annotation:d,id:i||r,skins:s&&n(s)}))}const Ti=requestAnimationFrame;let kb=typeof ResizeObserver=="function";function xb(e,t,n){let i;kb?(i=new ResizeObserver(n),i.observe(e)):Ti(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function fl(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let co;function $b(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=fl(a);r===0&&(s=!0),typeof co>"u"&&(co=fl(t));const l=r/1.8<co;qo.set(o.unicode,l),l||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
3085
+ `;ys([as({type:Number})],Yt.prototype,"splitRatio",2);ys([as({type:Number})],Yt.prototype,"minRatio",2);ys([as({type:Number})],Yt.prototype,"maxRatio",2);Yt=ys([jl("resizable-divider")],Yt);function yi(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function so(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const wv=1,kv=1,Dt="emoji",Xt="keyvalue",Ra="favorites",xv="tokens",Qd="tokens",$v="unicode",Jd="count",Sv="group",Av="order",Yd="group-order",Wo="eTag",es="url",ll="skinTone",ln="readonly",La="readwrite",Xd="skinUnicodes",Cv="skinUnicodes",Ev="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Tv="en";function _v(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 cl(e){return _v(e,t=>t.unicode)}function Mv(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[a,[r,l]]of Object.entries(s))o.createIndex(a,r,{multiEntry:l});return o}t(Xt),t(Dt,$v,{[Qd]:[xv,!0],[Yd]:[[Sv,Av]],[Xd]:[Cv,!0]}),t(Ra,void 0,{[Jd]:[""]})}const zo={},Ei={},ts={};function Zd(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function Pv(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,wv);zo[e]=s,s.onupgradeneeded=o=>{o.oldVersion<kv&&Mv(s.result)},Zd(n,i,s)});return t.onclose=()=>Da(e),t}function Iv(e){return Ei[e]||(Ei[e]=Pv(e)),Ei[e]}function Ye(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 l;i(r,a,d=>{l=d}),a.oncomplete=()=>s(l),a.onerror=()=>o(a.error)})}function Da(e){const t=zo[e],n=t&&t.result;if(n){n.close();const i=ts[e];if(i)for(const s of i)s()}delete zo[e],delete Ei[e],delete ts[e]}function Rv(e){return new Promise((t,n)=>{Da(e);const i=indexedDB.deleteDatabase(e);Zd(t,n,i)})}function Lv(e,t){let n=ts[e];n||(n=ts[e]=[]),n.push(t)}const Dv=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 Gt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||Dv.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const Bv=2;function eu(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=Bv)}function Nv(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:l,emoji:d,version:h})=>{const u=[...new Set(eu([...(a||[]).map(Gt).flat(),...(l||[]).map(Gt).flat(),...Gt(n),i]))].sort(),p={annotation:n,group:s,order:o,tags:l,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:y,emoji:x,version:S}of r)p.skinTones.push(y),p.skinUnicodes.push(x),p.skinVersions.push(S)}return p})}function tu(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function Mt(e,t,n){tu(e,"get",t,n)}function nu(e,t,n){tu(e,"getAll",t,n)}function Ba(e){e.commit&&e.commit()}function Ov(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 iu(e,t){const n=Ov(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 Fv(e){return!await Na(e,Xt,es)}async function Uv(e,t,n){const[i,s]=await Promise.all([Wo,es].map(o=>Na(e,Xt,o)));return i===n&&s===t}async function Wv(e,t){return Ye(e,Dt,ln,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=l=>{const d=l.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 su(e,t,n,i){{const s=Nv(t);await Ye(e,[Dt,Xt],La,([o,a],r)=>{let l,d,h=0;function u(){++h===2&&p()}function p(){if(!(l===i&&d===n)){o.clear();for(const y of s)o.put(y);a.put(i,Wo),a.put(n,es),Ba(r)}}Mt(a,Wo,y=>{l=y,u()}),Mt(a,es,y=>{d=y,u()})})}}async function zv(e,t){return Ye(e,Dt,ln,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);nu(n.index(Yd),o,s)})}async function ou(e,t){const n=eu(Gt(t));return n.length?Ye(e,Dt,ln,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&l()},l=()=>{const d=iu(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);nu(i.index(Qd),u,p=>{a.push(p),r()})}}):[]}async function Kv(e,t){const n=await ou(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await Wv(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function Hv(e,t){return Ye(e,Dt,ln,(n,i,s)=>Mt(n,t,o=>{if(o)return s(o);Mt(n.index(Xd),t,a=>s(a||null))}))}function Na(e,t,n){return Ye(e,t,ln,(i,s,o)=>Mt(i,n,o))}function qv(e,t,n,i){return Ye(e,t,La,(s,o)=>{s.put(i,n),Ba(o)})}function jv(e,t){return Ye(e,Ra,La,(n,i)=>Mt(n,t,s=>{n.put((s||0)+1,t),Ba(i)}))}function Vv(e,t,n){return n===0?[]:Ye(e,[Ra,Dt],ln,([i,s],o,a)=>{const r=[];i.index(Jd).openCursor(void 0,"prev").onsuccess=l=>{const d=l.target.result;if(!d)return a(r);function h(y){if(r.push(y),r.length===n)return a(r);d.continue()}const u=d.primaryKey,p=t.byName(u);if(p)return h(p);Mt(s,u,y=>{if(y)return h(y);d.continue()})}})}const vi="";function Gv(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 l=r.get(vi);l||(l=[],r.set(vi,l)),l.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=[],l=[a];for(;l.length;){const h=[...l.shift().entries()].sort((u,p)=>u[0]<p[0]?-1:1);for(const[u,p]of h)u===vi?r.push(...p):l.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 dl(e){Jv(e);const t=(p,y)=>p.name.toLowerCase()<y.name.toLowerCase()?-1:1,n=e.sort(t),s=Gv(e,p=>{const y=new Set;if(p.shortcodes)for(const x of p.shortcodes)for(const S of Gt(x))y.add(S);return y}),o=p=>s(p,!0),a=p=>s(p,!1),r=p=>{const y=Gt(p),x=y.map((S,_)=>(_<y.length-1?o:a)(S));return iu(x,S=>S.name).sort(t)},l=new Map,d=new Map;for(const p of e){d.set(p.name.toLowerCase(),p);for(const y of p.shortcodes||[])l.set(y.toLowerCase(),p)}return{all:n,search:r,byShortcode:p=>l.get(p.toLowerCase()),byName:p=>d.get(p.toLowerCase())}}const Yv=typeof wrappedJSObject<"u";function $n(e){if(!e)return e;if(Yv&&(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 au(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Xv=["annotation","emoji","group","order","version"];function Zv(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Xv.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function ru(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function eb(e){const t=await fetch(e,{method:"HEAD"});ru(t,e);const n=t.headers.get("etag");return au(n),n}async function Ko(e){const t=await fetch(e);ru(t,e);const n=t.headers.get("etag");au(n);const i=await t.json();return Zv(i),[n,i]}function tb(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function nb(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 lu(e){const t=JSON.stringify(e);let n=nb(t);const i=await crypto.subtle.digest("SHA-1",n),s=tb(i);return btoa(s)}async function ib(e,t){let n,i=await eb(t);if(!i){const s=await Ko(t);i=s[0],n=s[1],i||(i=await lu(n))}await Uv(e,t,i)||(n||(n=(await Ko(t))[1]),await su(e,n,t,i))}async function sb(e,t){let[n,i]=await Ko(t);n||(n=await lu(i)),await su(e,i,t,n)}async function ob(e,t){try{await ib(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class ab{constructor({dataSource:t=Ev,locale:n=Tv,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=dl(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await Iv(this._dbName);Lv(this._dbName,this._clear);const n=this.dataSource;await Fv(t)?await sb(t,n):this._lazyUpdate=ob(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 so(t),await this.ready(),cl(await zv(this._db,t)).map($n)}async getEmojiBySearchQuery(t){yi(t),await this.ready();const n=this._custom.search(t),i=cl(await ou(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 Kv(this._db,t))}async getEmojiByUnicodeOrName(t){yi(t),await this.ready();const n=this._custom.byName(t);return n||$n(await Hv(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Na(this._db,Xt,ll)||0}async setPreferredSkinTone(t){return so(t),await this.ready(),qv(this._db,Xt,ll,t)}async incrementFavoriteEmojiCount(t){return yi(t),await this.ready(),jv(this._db,t)}async getTopFavoriteEmoji(t){return so(t),await this.ready(),(await Vv(this._db,this._custom,t)).map($n)}set customEmoji(t){this._custom=dl(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 Da(this._dbName)}async delete(){await this._shutdown(),await Rv(this._dbName)}}const Ho=[[-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})),oo=Ho.slice(1),rb=2,ul=6,cu=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function pl(e){return e.unicode.includes("‍")}const lb={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},cb=1e3,db="🖐️",ub=8,pb=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],du='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',hb=(e,t)=>e<t?-1:e>t?1:0,hl=(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 ${du}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},fb=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function gb(e){const t=hl(e,"#000"),n=hl(e,"#fff");return t&&n&&fb(t,n)}function mb(){const e=Object.entries(lb);try{for(const[t,n]of e)if(gb(t))return n}catch{}return e[0][1]}let ao;const ro=()=>(ao||(ao=new Promise(e=>cu(()=>e(mb())))),ao),qo=new Map,yb="️",vb="\uD83C",bb="‍",wb=127995,kb=57339;function xb(e,t){if(t===0)return e;const n=e.indexOf(bb);return n!==-1?e.substring(0,n)+String.fromCodePoint(wb+t-1)+e.substring(n):(e.endsWith(yb)&&(e=e.substring(0,e.length-1)),e+vb+String.fromCodePoint(kb+t-1))}function Re(e){e.preventDefault(),e.stopPropagation()}function lo(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function uu(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 $b(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:l,annotation:d})=>({unicode:i,name:r,shortcodes:o,url:a,category:l,annotation:d,id:i||r,skins:s&&n(s)}))}const Ti=requestAnimationFrame;let Sb=typeof ResizeObserver=="function";function Ab(e,t,n){let i;Sb?(i=new ResizeObserver(n),i.observe(e)):Ti(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function fl(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let co;function Cb(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=fl(a);r===0&&(s=!0),typeof co>"u"&&(co=fl(t));const l=r/1.8<co;qo.set(o.unicode,l),l||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
3012
3086
  This is likely due to using \`display:none\` which is unsupported.
3013
3087
  If this is a Jest/Vitest environment, you can ignore this warning.
3014
- For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function Sb(e){return du(e,t=>t)}function Ab(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 gl(e){return""+e}function Cb(e){const t=document.createElement("template");return t.innerHTML=e,t}const Eb=new WeakMap,Tb=new WeakMap,_b=Symbol("un-keyed"),Mb="replaceChildren"in Element.prototype;function Pb(e,t){Mb?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function Ib(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 Rb(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=Ib(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&Pb(i,e)}function Lb(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:a,attributeValuePre:r,attributeValuePost:l}}=n,d=e[o];if(s!==d)if(n.currentExpression=d,a)if(d===null)i.removeAttribute(a);else{const h=r+gl(d)+l;i.setAttribute(a,h)}else{let h;Array.isArray(d)?Rb(d,n):d instanceof Element?(h=d,i.replaceWith(h)):i.nodeValue=gl(d),h&&(n.targetNode=h)}}}function Db(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],y=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 v={attributeName:$,attributeValuePre:S,attributeValuePost:M,expressionIndex:d};y.push(v),!n&&!i&&(t+=" ")}return{template:Cb(t),elementsToBindings:o}}function ml(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 Bb(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))ml(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&ml(r,o,n)}while(o=s.nextNode())}return n}function Nb(e){const{template:t,elementsToBindings:n}=Dn(Eb,e,()=>Db(e)),i=t.cloneNode(!0).content.firstElementChild,s=Bb(i,n);return function(a){return Lb(a,s),i}}function Ob(e){const t=Dn(Tb,e,()=>new Map);let n=_b;function i(o,...a){const r=Dn(t,o,()=>new Map);return Dn(r,n,()=>Nb(o))(a)}function s(o,a,r){return o.map((l,d)=>{const h=n;n=r(l);try{return a(l,d)}finally{n=h}})}return{map:s,html:i}}function Fb(e,t,n,i,s,o,a,r,l){const{labelWithSkin:d,titleForEmoji:h,unicodeWithSkin:u}=n,{html:p,map:y}=Ob(t);function $(b,k,A){return y(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">${y(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">${y(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">${y(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>`,v=(b,k)=>{for(const A of e.querySelectorAll(`[${b}]`))k(A,A.getAttribute(b))};if(l){e.appendChild(M);for(const b of["click","focusout","input","keydown","keyup"])v(`data-on-${b}`,(k,A)=>{k.addEventListener(b,i[A])});v("data-ref",(b,k)=>{o[k]=b}),a.addEventListener("abort",()=>{e.removeChild(M)})}v("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 ns=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function Ub(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,ns(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 y of p)s.add(y);o||(o=!0,ns(a))}}return!0}}),l=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:l}}function uo(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 yl=new WeakMap;function Wb(e,t,n){{const i=e.closest(".tabpanel");let s=yl.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),yl.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const po=[],{assign:bi}=Object;function zb(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=Ub(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:lb,isRtl:!1,currentGroupIndex:0,groups:oo,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const l=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:ee,emojis:J}=R;return F!==ee?!1:uo(U,J,u)},y=C=>{uo(o.currentEmojis,C,u)||(o.currentEmojis=C)},$=C=>{o.searchMode!==C&&(o.searchMode=C)},S=C=>{uo(o.currentEmojisWithCategories,C,p)||(o.currentEmojisWithCategories=C)},M=(C,R)=>R&&C.skins&&C.skins[R]||C.unicode,k={labelWithSkin:(C,R)=>Sb([C.name||M(C,R),C.annotation,...C.shortcodes||po].filter(Boolean)).join(", "),titleForEmoji:C=>C.annotation||(C.shortcodes||po).join(", "),unicodeWithSkin:M},A={onClickSkinToneButton:X,onEmojiClick:Yn,onNavClick:Qn,onNavKeydown:Ss,onSearchKeydown:$s,onSkinToneOptionsClick:Xn,onSkinToneOptionsFocusOut:et,onSkinToneOptionsKeydown:dt,onSkinToneOptionsKeyup:dn,onSearchInput:Zn},E={calculateEmojiGridStyle:D,updateOnIntersection:W};let T=!0;a(()=>{Fb(e,o,k,A,E,n,s,r,T),T=!1}),o.emojiVersion||ro().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},ab);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=`
3088
+ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function Eb(e){return uu(e,t=>t)}function Tb(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 gl(e){return""+e}function _b(e){const t=document.createElement("template");return t.innerHTML=e,t}const Mb=new WeakMap,Pb=new WeakMap,Ib=Symbol("un-keyed"),Rb="replaceChildren"in Element.prototype;function Lb(e,t){Rb?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function Db(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 Bb(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=Db(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&Lb(i,e)}function Nb(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:a,attributeValuePre:r,attributeValuePost:l}}=n,d=e[o];if(s!==d)if(n.currentExpression=d,a)if(d===null)i.removeAttribute(a);else{const h=r+gl(d)+l;i.setAttribute(a,h)}else{let h;Array.isArray(d)?Bb(d,n):d instanceof Element?(h=d,i.replaceWith(h)):i.nodeValue=gl(d),h&&(n.targetNode=h)}}}function Ob(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],y=Dn(o,p,()=>[]);let x,S,_;if(i){const b=/(\S+)="?([^"=]*)$/.exec(u);x=b[1],S=b[2];const k=/^([^">]*)("?)/.exec(e[d+1]);_=k[1],t=t.slice(0,-1*b[0].length),r=k[0].length}else r=0;const v={attributeName:x,attributeValuePre:S,attributeValuePost:_,expressionIndex:d};y.push(v),!n&&!i&&(t+=" ")}return{template:_b(t),elementsToBindings:o}}function ml(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 Fb(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))ml(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&ml(r,o,n)}while(o=s.nextNode())}return n}function Ub(e){const{template:t,elementsToBindings:n}=Dn(Mb,e,()=>Ob(e)),i=t.cloneNode(!0).content.firstElementChild,s=Fb(i,n);return function(a){return Nb(a,s),i}}function Wb(e){const t=Dn(Pb,e,()=>new Map);let n=Ib;function i(o,...a){const r=Dn(t,o,()=>new Map);return Dn(r,n,()=>Ub(o))(a)}function s(o,a,r){return o.map((l,d)=>{const h=n;n=r(l);try{return a(l,d)}finally{n=h}})}return{map:s,html:i}}function zb(e,t,n,i,s,o,a,r,l){const{labelWithSkin:d,titleForEmoji:h,unicodeWithSkin:u}=n,{html:p,map:y}=Wb(t);function x(b,k,A){return y(b,(E,M)=>p`<button role="${k?"option":"menuitem"}" aria-selected="${k?M===t.activeSearchItem:null}" aria-label="${d(E,t.currentSkinTone)}" title="${h(E)}" class="${"emoji"+(k&&M===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 _=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">${y(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">${y(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">${y(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}">${x(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">${x(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,v=(b,k)=>{for(const A of e.querySelectorAll(`[${b}]`))k(A,A.getAttribute(b))};if(l){e.appendChild(_);for(const b of["click","focusout","input","keydown","keyup"])v(`data-on-${b}`,(k,A)=>{k.addEventListener(b,i[A])});v("data-ref",(b,k)=>{o[k]=b}),a.addEventListener("abort",()=>{e.removeChild(_)})}v("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 ns=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function Kb(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,ns(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 y of p)s.add(y);o||(o=!0,ns(a))}}return!0}}),l=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:l}}function uo(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 yl=new WeakMap;function Hb(e,t,n){{const i=e.closest(".tabpanel");let s=yl.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),yl.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const po=[],{assign:bi}=Object;function qb(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=Kb(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:ub,isRtl:!1,currentGroupIndex:0,groups:oo,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const l=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:O,emojis:U}=C,{category:ee,emojis:Q}=R;return O!==ee?!1:uo(U,Q,u)},y=C=>{uo(o.currentEmojis,C,u)||(o.currentEmojis=C)},x=C=>{o.searchMode!==C&&(o.searchMode=C)},S=C=>{uo(o.currentEmojisWithCategories,C,p)||(o.currentEmojisWithCategories=C)},_=(C,R)=>R&&C.skins&&C.skins[R]||C.unicode,k={labelWithSkin:(C,R)=>Eb([C.name||_(C,R),C.annotation,...C.shortcodes||po].filter(Boolean)).join(", "),titleForEmoji:C=>C.annotation||(C.shortcodes||po).join(", "),unicodeWithSkin:_},A={onClickSkinToneButton:Z,onEmojiClick:Yn,onNavClick:Qn,onNavKeydown:Ss,onSearchKeydown:$s,onSkinToneOptionsClick:Xn,onSkinToneOptionsFocusOut:Xe,onSkinToneOptionsKeydown:dt,onSkinToneOptionsKeyup:dn,onSearchInput:Zn},E={calculateEmojiGridStyle:F,updateOnIntersection:V};let M=!0;a(()=>{zb(e,o,k,A,E,n,s,r,M),M=!1}),o.emojiVersion||ro().then(C=>{C||(o.message=o.i18n.emojiUnsupportedMessage)}),a(()=>{async function C(){let R=!1;const O=setTimeout(()=>{R=!0,o.message=o.i18n.loadingMessage},cb);try{await o.database.ready(),o.databaseLoaded=!0}catch(U){console.error(U),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(O),R&&(R=!1,o.message="")}}o.database&&C()}),a(()=>{o.pickerStyle=`
3015
3089
  --num-groups: ${o.groups.length};
3016
3090
  --indicator-opacity: ${o.searchMode?0:1};
3017
- --num-skintones: ${ul};`}),a(()=>{o.customEmoji&&o.database&&P()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==Ho&&(o.groups=Ho):o.groups!==oo&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=oo)}),a(()=>{async function C(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}C()}),a(()=>{o.skinTones=Array(ul).fill().map((C,R)=>bb(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(cb.map(U=>R.getEmojiByUnicodeOrName(U)))).filter(Boolean);o.defaultFavoriteEmojis=F}o.databaseLoaded&&C()});function P(){const{customEmoji:C,database:R}=o,F=C||po;R.customEmoji!==F&&(R.customEmoji=F)}a(()=>{async function C(){P();const{database:R,defaultFavoriteEmojis:F,numColumns:U}=o,ee=await R.getTopFavoriteEmoji(U),J=await Ke(du([...ee,...F],he=>he.unicode||he.name).slice(0,U));o.currentFavorites=J}o.databaseLoaded&&o.defaultFavoriteEmojis&&C()});function D(C){xb(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){Wb(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:ee}=o;if(!U)o.currentEmojis=[],o.searchMode=!1;else if(R.length>=sb){const J=await xs(R);o.searchText===R&&(y(J),$(!0))}else{const{id:J}=F;if(J!==-1||ee&&ee.length){const he=await ks(J);o.currentGroup.id===J&&(y(he),$(!1))}}}C()});const K=()=>{Ti(()=>Ab(n.tabpanelElement))};a(()=>{const{currentEmojis:C,emojiVersion:R}=o,F=C.filter(U=>U.unicode).filter(U=>pl(U)&&!qo.has(U.unicode));if(!R&&F.length)y(C),Ti(()=>H(F));else{const U=R?C:C.filter(ke);y(U),K()}});function H(C){$b(C,n.baselineEmoji,d)?K():o.currentEmojis=[...o.currentEmojis]}function ke(C){return!C.unicode||!pl(C)||qo.get(C.unicode)}async function Ie(C){const R=o.emojiVersion||await ro();return C.filter(({version:F})=>!F||F<=R)}async function Ke(C){return wb(C,o.emojiVersion||await ro())}async function ks(C){const R=C===-1?o.customEmoji:await o.database.getEmojiByGroup(C);return Ke(await Ie(R))}async function xs(C){return Ke(await Ie(await o.database.getEmojiBySearchQuery(C)))}a(()=>{}),a(()=>{function C(){const{searchMode:F,currentEmojis:U}=o;if(F)return[{category:"",emojis:U}];const ee=new Map;for(const J of U){const he=J.category||"";let tt=ee.get(he);tt||(tt=[],ee.set(he,tt)),tt.push(J)}return[...ee.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;lu(()=>{o.searchText=(C||"").trim(),o.activeSearchItem=-1})});function $s(C){if(!o.searchMode||!o.currentEmojis.length)return;const R=F=>{Be(C),o.activeSearchItem=lo(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 Be(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(ee=>ee.id===U)}function Ss(C){const{target:R,key:F}=C,U=ee=>{ee&&(Be(C),ee.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(ee=>ee.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;Be(C);const F=R.id.substring(4);te(F)}function ne(C){o.currentSkinTone=C,o.skinTonePickerExpanded=!1,l("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;Be(C);const U=parseInt(F[1],10);ne(U)}function X(C){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Be(C),Ti(()=>l("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=>{Be(C),o.activeSkinTone=F};switch(C.key){case"ArrowUp":return R(lo(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return R(lo(!1,o.activeSkinTone,o.skinTones));case"Home":return R(0);case"End":return R(o.skinTones.length-1);case"Enter":return Be(C),ne(o.activeSkinTone);case"Escape":return Be(C),o.skinTonePickerExpanded=!1,l("skintone-button")}}function dn(C){if(o.skinTonePickerExpanded&&C.key===" ")return Be(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",Hb="en";var qb={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"}},jb=':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 uu=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],Gb=`:host{--emoji-font-family:${cu}}`;class Oa extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=jb+Gb,this.shadowRoot.appendChild(n),this._ctx={locale:Hb,dataSource:Kb,skinToneEmoji:rb,customCategorySorting:db,customEmoji:null,i18n:qb,emojiVersion:null,...t};for(const i of uu)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){vl(this),this._cmp||(this._cmp=zb(this.shadowRoot,this._ctx))}disconnectedCallback(){vl(this),ns(()=>{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 ib({locale:t,dataSource:n}))}_dbFlush(){ns(()=>this._dbCreate())}}const pu={};for(const e of uu)pu[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(Oa.prototype,pu);function vl(e){e instanceof Oa||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Oa);function Vb(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 bl(e){e.style.height="44px",e.style.overflowY="hidden"}const Qb=5e3;function Jb(e){return e?e.active?c`
3091
+ --num-skintones: ${ul};`}),a(()=>{o.customEmoji&&o.database&&P()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==Ho&&(o.groups=Ho):o.groups!==oo&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=oo)}),a(()=>{async function C(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}C()}),a(()=>{o.skinTones=Array(ul).fill().map((C,R)=>xb(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,O=(await Promise.all(pb.map(U=>R.getEmojiByUnicodeOrName(U)))).filter(Boolean);o.defaultFavoriteEmojis=O}o.databaseLoaded&&C()});function P(){const{customEmoji:C,database:R}=o,O=C||po;R.customEmoji!==O&&(R.customEmoji=O)}a(()=>{async function C(){P();const{database:R,defaultFavoriteEmojis:O,numColumns:U}=o,ee=await R.getTopFavoriteEmoji(U),Q=await ct(uu([...ee,...O],he=>he.unicode||he.name).slice(0,U));o.currentFavorites=Q}o.databaseLoaded&&o.defaultFavoriteEmojis&&C()});function F(C){Ab(C,s,()=>{{const R=getComputedStyle(n.rootElement),O=parseInt(R.getPropertyValue("--num-columns"),10),U=R.getPropertyValue("direction")==="rtl";o.numColumns=O,o.isRtl=U}})}function V(C){Hb(C,s,R=>{for(const{target:O,isIntersecting:U}of R)O.classList.toggle("onscreen",U)})}a(()=>{async function C(){const{searchText:R,currentGroup:O,databaseLoaded:U,customEmoji:ee}=o;if(!U)o.currentEmojis=[],o.searchMode=!1;else if(R.length>=rb){const Q=await xs(R);o.searchText===R&&(y(Q),x(!0))}else{const{id:Q}=O;if(Q!==-1||ee&&ee.length){const he=await ks(Q);o.currentGroup.id===Q&&(y(he),x(!1))}}}C()});const X=()=>{Ti(()=>Tb(n.tabpanelElement))};a(()=>{const{currentEmojis:C,emojiVersion:R}=o,O=C.filter(U=>U.unicode).filter(U=>pl(U)&&!qo.has(U.unicode));if(!R&&O.length)y(C),Ti(()=>q(O));else{const U=R?C:C.filter(lt);y(U),X()}});function q(C){Cb(C,n.baselineEmoji,d)?X():o.currentEmojis=[...o.currentEmojis]}function lt(C){return!C.unicode||!pl(C)||qo.get(C.unicode)}async function Bt(C){const R=o.emojiVersion||await ro();return C.filter(({version:O})=>!O||O<=R)}async function ct(C){return $b(C,o.emojiVersion||await ro())}async function ks(C){const R=C===-1?o.customEmoji:await o.database.getEmojiByGroup(C);return ct(await Bt(R))}async function xs(C){return ct(await Bt(await o.database.getEmojiBySearchQuery(C)))}a(()=>{}),a(()=>{function C(){const{searchMode:O,currentEmojis:U}=o;if(O)return[{category:"",emojis:U}];const ee=new Map;for(const Q of U){const he=Q.category||"";let Ze=ee.get(he);Ze||(Ze=[],ee.set(he,Ze)),Ze.push(Q)}return[...ee.entries()].map(([Q,he])=>({category:Q,emojis:he})).sort((Q,he)=>o.customCategorySorting(Q.category,he.category))}const R=C();S(R)}),a(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),a(()=>{const{rawSearchText:C}=o;cu(()=>{o.searchText=(C||"").trim(),o.activeSearchItem=-1})});function $s(C){if(!o.searchMode||!o.currentEmojis.length)return;const R=O=>{Re(C),o.activeSearchItem=lo(O,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 Re(C),te(o.currentEmojis[o.activeSearchItem].id)}}function Qn(C){const{target:R}=C,O=R.closest(".nav-button");if(!O)return;const U=parseInt(O.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(ee=>ee.id===U)}function Ss(C){const{target:R,key:O}=C,U=ee=>{ee&&(Re(C),ee.focus())};switch(O){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),O=[...o.currentEmojis,...o.currentFavorites].find(ee=>ee.id===C),U=O.unicode&&_(O,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(C),{emoji:R,skinTone:o.currentSkinTone,...U&&{unicode:U},...O.name&&{name:O.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;Re(C);const O=R.id.substring(4);te(O)}function ne(C){o.currentSkinTone=C,o.skinTonePickerExpanded=!1,l("skintone-button"),h("skin-tone-change",{skinTone:C}),o.database.setPreferredSkinTone(C)}function Xn(C){const{target:{id:R}}=C,O=R&&R.match(/^skintone-(\d)/);if(!O)return;Re(C);const U=parseInt(O[1],10);ne(U)}function Z(C){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Re(C),Ti(()=>l("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 O=>{Re(C),o.activeSkinTone=O};switch(C.key){case"ArrowUp":return R(lo(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return R(lo(!1,o.activeSkinTone,o.skinTones));case"Home":return R(0);case"End":return R(o.skinTones.length-1);case"Enter":return Re(C),ne(o.activeSkinTone);case"Escape":return Re(C),o.skinTonePickerExpanded=!1,l("skintone-button")}}function dn(C){if(o.skinTonePickerExpanded&&C.key===" ")return Re(C),ne(o.activeSkinTone)}async function Xe(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 jb="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Vb="en";var Gb={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 pu=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],Jb=`:host{--emoji-font-family:${du}}`;class Oa 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:Vb,dataSource:jb,skinToneEmoji:db,customCategorySorting:hb,customEmoji:null,i18n:Gb,emojiVersion:null,...t};for(const i of pu)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){vl(this),this._cmp||(this._cmp=qb(this.shadowRoot,this._ctx))}disconnectedCallback(){vl(this),ns(()=>{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 ab({locale:t,dataSource:n}))}_dbFlush(){ns(()=>this._dbCreate())}}const hu={};for(const e of pu)hu[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(Oa.prototype,hu);function vl(e){e instanceof Oa||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Oa);function Yb(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 bl(e){e.style.height="44px",e.style.overflowY="hidden"}const Xb=5e3;function Zb(e){return e?e.active?c`
3018
3092
  <div class="callout info compaction-indicator compaction-indicator--active">
3019
3093
  ${I.loader} Compacting context...
3020
3094
  </div>
3021
- `:e.completedAt&&Date.now()-e.completedAt<Qb?c`
3095
+ `:e.completedAt&&Date.now()-e.completedAt<Xb?c`
3022
3096
  <div class="callout success compaction-indicator compaction-indicator--complete">
3023
3097
  ${I.check} Context compacted
3024
3098
  </div>
3025
- `:w:w}const Je=5*1024*1024;function Ye(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Me(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 Yb=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function hu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function fu(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Yb.test(e.name)}function gu(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function mu(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function Xb(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(hu(e)){if(e.size>Je){n&&Me(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(fu(e)){if(e.size>Je){n&&Me(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(gu(e)){if(e.size>Je){n&&Me(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(mu(e)){if(e.size>Je){n&&Me(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&&Me(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Zb(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(hu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Me(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 l=r.result,d={id:Ye(),dataUrl:l,mimeType:a.type},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsDataURL(a)}else if(fu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Me(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 l=r.result,d={id:Ye(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:l},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsText(a)}else if(gu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Me(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 l=r.result,d={id:Ye(),dataUrl:l,mimeType:"application/pdf",fileName:a.name},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsDataURL(a)}else if(mu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Je){Me(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 l=r.result,d={id:Ye(),dataUrl:l,mimeType:a.type||"video/mp4",fileName:a.name},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsDataURL(a)}else Me(n,`Unsupported file type: ${a.name}. Use the Files page to upload to workspace.`)}}function ew(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function tw(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function nw(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 l=n[r];(l.type.startsWith("image/")||l.type.startsWith("video/"))&&i.push(l)}if(i.length!==0){e.preventDefault();for(const r of i){const l=r.getAsFile();if(!l)continue;const d=l.type.startsWith("video/")?"Video":"Image";if(l.size>Je){const u=((a=(o=e.target)==null?void 0:o.closest)==null?void 0:a.call(o,".chat"))??document.querySelector(".chat");u&&Me(u,`${d} too large (${(l.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const h=new FileReader;h.onload=()=>{var S;const u=h.result,p=l.type.startsWith("video/"),y={id:Ye(),dataUrl:u,mimeType:l.type,fileName:p?l.name||"video.mp4":void 0},$=t.attachments??[];(S=t.onAttachmentsChange)==null||S.call(t,[...$,y])},h.readAsDataURL(l)}}}function iw(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 sw(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,l=t.draft.slice(0,a),d=t.draft.slice(r);t.onDraftChange(l+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 ow(e){const t=e.attachments??[];return t.length===0?w:c`
3099
+ `:w:w}const Ve=5*1024*1024;function Ge(){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 ew=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function fu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function gu(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||ew.test(e.name)}function mu(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function yu(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function tw(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(fu(e)){if(e.size>Ve){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:Ge(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(gu(e)){if(e.size>Ve){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:Ge(),dataUrl:"",mimeType:e.type||"text/plain",fileName:e.name,textContent:i.result};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsText(e)}else if(mu(e)){if(e.size>Ve){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:Ge(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(yu(e)){if(e.size>Ve){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:Ge(),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 nw(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(fu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Ve){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 l=r.result,d={id:Ge(),dataUrl:l,mimeType:a.type},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>Ve){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 l=r.result,d={id:Ge(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:l},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsText(a)}else if(mu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Ve){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 l=r.result,d={id:Ge(),dataUrl:l,mimeType:"application/pdf",fileName:a.name},h=t.attachments??[];(u=t.onAttachmentsChange)==null||u.call(t,[...h,d])},r.readAsDataURL(a)}else if(yu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Ve){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 l=r.result,d={id:Ge(),dataUrl:l,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 iw(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function sw(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function ow(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 l=n[r];(l.type.startsWith("image/")||l.type.startsWith("video/"))&&i.push(l)}if(i.length!==0){e.preventDefault();for(const r of i){const l=r.getAsFile();if(!l)continue;const d=l.type.startsWith("video/")?"Video":"Image";if(l.size>Ve){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 (${(l.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const h=new FileReader;h.onload=()=>{var S;const u=h.result,p=l.type.startsWith("video/"),y={id:Ge(),dataUrl:u,mimeType:l.type,fileName:p?l.name||"video.mp4":void 0},x=t.attachments??[];(S=t.onAttachmentsChange)==null||S.call(t,[...x,y])},h.readAsDataURL(l)}}}function aw(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 rw(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,l=t.draft.slice(0,a),d=t.draft.slice(r);t.onDraftChange(l+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 lw(e){const t=e.attachments??[];return t.length===0?w:c`
3026
3100
  <div class="chat-attachments">
3027
3101
  ${t.map(n=>{var i;return n.fileName?c`
3028
3102
  <div class="chat-attachment chat-attachment--file">
@@ -3055,7 +3129,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3055
3129
  </div>
3056
3130
  `})}
3057
3131
  </div>
3058
- `}function yu(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(v=>v.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,l=e.connected?r?"Add a message...":"Message...":"Connecting…";uv({onSend:v=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],v]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var v;(v=e.requestUpdate)==null||v.call(e)}});const d=dv(),h=!d&&!e.draft.trim()&&!r&&!n,u=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),y=c`
3132
+ `}function vu(e){var x,S,_;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(S=(x=e.sessions)==null?void 0:x.sessions)==null?void 0:S.find(v=>v.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",a=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const r=(((_=e.attachments)==null?void 0:_.length)??0)>0,l=e.connected?r?"Add a message...":"Message...":"Connecting…";fv({onSend:v=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],v]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var v;(v=e.requestUpdate)==null||v.call(e)}});const d=hv(),h=!d&&!e.draft.trim()&&!r&&!n,u=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),y=c`
3059
3133
  <div
3060
3134
  class="chat-thread"
3061
3135
  role="log"
@@ -3066,20 +3140,20 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3066
3140
  ${e.loadingOlder?c`<span class="chat-load-more__spinner">${I.loader}</span> Loading older messages…`:c`<button class="chat-load-more__btn" type="button" @click=${e.onLoadOlder}>Load older messages</button>`}
3067
3141
  </div>`:w}
3068
3142
  ${e.loading?c`<div class="muted">Loading chat…</div>`:w}
3069
- ${wm(rw(e),v=>v.key,v=>v.kind==="interim"?ev(v.text):v.kind==="reading-indicator"?Zy():v.kind==="stream"?tv(v.text,v.startedAt,e.onOpenSidebar):v.kind==="group"?nv(v,{onOpenSidebar:e.onOpenSidebar,showReasoning:a,assistantName:e.assistantName}):w)}
3143
+ ${$m(dw(e),v=>v.key,v=>v.kind==="interim"?iv(v.text):v.kind==="reading-indicator"?nv():v.kind==="stream"?sv(v.text,v.startedAt,e.onOpenSidebar):v.kind==="group"?ov(v,{onOpenSidebar:e.onOpenSidebar,showReasoning:a,assistantName:e.assistantName}):w)}
3070
3144
  </div>
3071
3145
  `;return c`
3072
3146
  <section
3073
3147
  class="card chat"
3074
- @drop=${v=>Zb(v,e)}
3075
- @dragover=${ew}
3076
- @dragleave=${tw}
3148
+ @drop=${v=>nw(v,e)}
3149
+ @dragover=${iw}
3150
+ @dragleave=${sw}
3077
3151
  >
3078
3152
  ${e.disabledReason?c`<div class="callout">${e.disabledReason}</div>`:w}
3079
3153
 
3080
3154
  ${e.error?c`<div class="callout danger">${e.error}</div>`:w}
3081
3155
 
3082
- ${Jb(e.compactionStatus)}
3156
+ ${Zb(e.compactionStatus)}
3083
3157
 
3084
3158
  ${e.focusMode?c`
3085
3159
  <button
@@ -3120,7 +3194,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3120
3194
  @resize=${v=>{var b;return(b=e.onSplitRatioChange)==null?void 0:b.call(e,v.detail.splitRatio)}}
3121
3195
  ></resizable-divider>
3122
3196
  <div class="chat-sidebar">
3123
- ${fv({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
3197
+ ${yv({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
3124
3198
  ${e.sidebarContent}
3125
3199
  \`\`\``)}})}
3126
3200
  </div>
@@ -3142,13 +3216,13 @@ ${e.sidebarContent}
3142
3216
  `:w}
3143
3217
 
3144
3218
  <div class="chat-compose">
3145
- ${ow(e)}
3146
- ${d?hv():c`
3219
+ ${lw(e)}
3220
+ ${d?mv():c`
3147
3221
  <div class="chat-compose__row">
3148
3222
  <button
3149
3223
  class="chat-compose__emoji"
3150
3224
  type="button"
3151
- @click=${iw}
3225
+ @click=${aw}
3152
3226
  aria-label="Emoji"
3153
3227
  title="Emoji"
3154
3228
  >
@@ -3169,7 +3243,7 @@ ${e.sidebarContent}
3169
3243
  multiple
3170
3244
  accept="image/*,video/*,.pdf,.md,.txt,.csv,.json,.xml,.html,.css,.js,.ts,.py,.sh,.yaml,.yml,.toml,.ini,.cfg,.log,.sql"
3171
3245
  style="display:none"
3172
- @change=${v=>{const b=v.target,k=b.files;if(!(!k||k.length===0||!e.onAttachmentsChange)){for(let A=0;A<k.length;A++)Xb(k[A],e);b.value=""}}}
3246
+ @change=${v=>{const b=v.target,k=b.files;if(!(!k||k.length===0||!e.onAttachmentsChange)){for(let A=0;A<k.length;A++)tw(k[A],e);b.value=""}}}
3173
3247
  />
3174
3248
  <label class="field chat-compose__field">
3175
3249
  <span>Message</span>
@@ -3177,8 +3251,8 @@ ${e.sidebarContent}
3177
3251
  .value=${e.draft}
3178
3252
  ?disabled=${!e.connected}
3179
3253
  @keydown=${v=>{v.key==="Enter"&&(v.isComposing||v.keyCode===229||v.shiftKey||e.connected&&(v.preventDefault(),t&&(e.onSend(),bl(v.target))))}}
3180
- @input=${v=>{const b=v.target;e.onDraftChange(b.value),Vb(b)}}
3181
- @paste=${v=>nw(v,e)}
3254
+ @input=${v=>{const b=v.target;e.onDraftChange(b.value),Yb(b)}}
3255
+ @paste=${v=>ow(v,e)}
3182
3256
  placeholder=${l}
3183
3257
  ></textarea>
3184
3258
  </label>
@@ -3192,7 +3266,7 @@ ${e.sidebarContent}
3192
3266
  ${I.square}
3193
3267
  </button>
3194
3268
  `:w}
3195
- ${h?pv(e.connected):c`
3269
+ ${h?gv(e.connected):c`
3196
3270
  <button
3197
3271
  class="btn btn--icon chat-compose__send primary"
3198
3272
  ?disabled=${!e.connected}
@@ -3205,14 +3279,14 @@ ${e.sidebarContent}
3205
3279
  </div>`}
3206
3280
  <div class="emoji-picker-popup">
3207
3281
  <emoji-picker
3208
- @emoji-click=${v=>sw(v,e)}
3282
+ @emoji-click=${v=>rw(v,e)}
3209
3283
  ></emoji-picker>
3210
3284
  </div>
3211
3285
  </div>
3212
3286
  </section>
3213
- `}function aw(e){return e.map(t=>{if(t.kind!=="message")return t;const n=nc(t.message),i=ic(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 rw(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],l=nc(r);if(!s&&l.role.toLowerCase()==="toolresult"){const d=r,u=(Array.isArray(d.content)?d.content:[]).filter(p=>{const y=p.type;return y==="image"||y==="file"});u.length>0&&t.push({kind:"message",key:ho(r,a),message:{role:"assistant",content:u,timestamp:l.timestamp}});continue}t.push({kind:"message",key:ho(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:ho(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))??[],l=r.length>0?a.text?`${r.join(", ")}
3287
+ `}function cw(e){return e.map(t=>{if(t.kind!=="message")return t;const n=nc(t.message),i=ic(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 dw(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],l=nc(r);if(!s&&l.role.toLowerCase()==="toolresult"){const d=r,u=(Array.isArray(d.content)?d.content:[]).filter(p=>{const y=p.type;return y==="image"||y==="file"});u.length>0&&t.push({kind:"message",key:ho(r,a),message:{role:"assistant",content:u,timestamp:l.timestamp}});continue}t.push({kind:"message",key:ho(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:ho(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))??[],l=r.length>0?a.text?`${r.join(", ")}
3214
3288
 
3215
- ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,message:{role:"user",content:[{type:"text",text:l}],timestamp:a.createdAt}})}return aw(t)}function ho(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 lw(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 vu(e){return e.replace(/@s\.whatsapp\.net$/,"").replace(/@g\.us$/,"")}function cw(e){const t=e.searchQuery.toLowerCase(),n=t?e.conversations.filter(i=>i.name.toLowerCase().includes(t)||i.jid.includes(t)):e.conversations;return c`
3289
+ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,message:{role:"user",content:[{type:"text",text:l}],timestamp:a.createdAt}})}return cw(t)}function ho(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 uw(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 bu(e){return e.replace(/@s\.whatsapp\.net$/,"").replace(/@g\.us$/,"")}function pw(e){const t=e.searchQuery.toLowerCase(),n=t?e.conversations.filter(i=>i.name.toLowerCase().includes(t)||i.jid.includes(t)):e.conversations;return c`
3216
3290
  <div class="wa-list">
3217
3291
  <div class="wa-list__header">
3218
3292
  <input
@@ -3227,29 +3301,29 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3227
3301
  </button>
3228
3302
  </div>
3229
3303
  <div class="wa-list__items">
3230
- ${e.loading?c`<div class="wa-list__empty">Loading...</div>`:n.length===0?c`<div class="wa-list__empty">${e.conversations.length===0?"No conversations yet":"No matches"}</div>`:n.map(i=>dw(i,i.jid===e.selectedJid,()=>e.onSelectConversation(i.jid)))}
3304
+ ${e.loading?c`<div class="wa-list__empty">Loading...</div>`:n.length===0?c`<div class="wa-list__empty">${e.conversations.length===0?"No conversations yet":"No matches"}</div>`:n.map(i=>hw(i,i.jid===e.selectedJid,()=>e.onSelectConversation(i.jid)))}
3231
3305
  </div>
3232
3306
  </div>
3233
- `}function dw(e,t,n){const i=e.type==="group"&&e.activation?c`<span class="wa-badge wa-badge--${e.activation}">${e.activation}</span>`:w;return c`
3307
+ `}function hw(e,t,n){const i=e.type==="group"&&e.activation?c`<span class="wa-badge wa-badge--${e.activation}">${e.activation}</span>`:w;return c`
3234
3308
  <button class="wa-list__item ${t?"wa-list__item--selected":""}" @click=${n}>
3235
3309
  <span class="wa-list__icon ${e.type==="group"?"wa-list__icon--group":""}">${e.type==="group"?I.users:I.user}</span>
3236
3310
  <div class="wa-list__info">
3237
3311
  <span class="wa-list__name">${e.name}</span>
3238
- <span class="wa-list__jid">${vu(e.jid)}</span>
3312
+ <span class="wa-list__jid">${bu(e.jid)}</span>
3239
3313
  </div>
3240
3314
  ${i}
3241
3315
  </button>
3242
- `}function uw(e){const t=e.conversations.find(n=>n.jid===e.selectedJid);return t?c`
3316
+ `}function fw(e){const t=e.conversations.find(n=>n.jid===e.selectedJid);return t?c`
3243
3317
  <div class="wa-header">
3244
3318
  <button class="wa-header__back" @click=${e.onBack} title="Back to conversations">
3245
3319
  <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"><polyline points="15 18 9 12 15 6"></polyline></svg>
3246
3320
  </button>
3247
3321
  <div class="wa-header__info">
3248
3322
  <span class="wa-header__name">${t.name}</span>
3249
- <span class="wa-header__jid">${vu(t.jid)}</span>
3323
+ <span class="wa-header__jid">${bu(t.jid)}</span>
3250
3324
  </div>
3251
3325
  </div>
3252
- `:c``}function pw(e){var n;const t=e.groupInfo;return!t||!((n=e.selectedJid)!=null&&n.endsWith("@g.us"))?c``:c`
3326
+ `:c``}function gw(e){var n;const t=e.groupInfo;return!t||!((n=e.selectedJid)!=null&&n.endsWith("@g.us"))?c``:c`
3253
3327
  <div class="wa-group-settings">
3254
3328
  <div class="wa-group-settings__row">
3255
3329
  <label class="wa-group-settings__label">Activation</label>
@@ -3268,29 +3342,29 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3268
3342
  ${t.desc?c` · ${t.desc}`:w}
3269
3343
  </div>
3270
3344
  </div>
3271
- `}function hw(e){return e.length===0?c`<div class="wa-messages__empty">No messages available</div>`:c`
3345
+ `}function mw(e){return e.length===0?c`<div class="wa-messages__empty">No messages available</div>`:c`
3272
3346
  ${e.map(t=>c`
3273
3347
  <div class="wa-bubble ${t.fromMe?"wa-bubble--me":""}">
3274
3348
  ${!t.fromMe&&t.senderName?c`<div class="wa-bubble__sender">${t.senderName}</div>`:w}
3275
3349
  ${t.quoted?c`<div class="wa-bubble__quoted">${t.quoted.body}</div>`:w}
3276
3350
  <div class="wa-bubble__body">${t.body}</div>
3277
- <div class="wa-bubble__time">${lw(t.timestamp)}</div>
3351
+ <div class="wa-bubble__time">${uw(t.timestamp)}</div>
3278
3352
  </div>
3279
3353
  `)}
3280
- `}function fw(e){return c`
3354
+ `}function yw(e){return c`
3281
3355
  <div class="wa-container ${e.selectedJid?"wa-container--detail":""}">
3282
- ${cw(e)}
3356
+ ${pw(e)}
3283
3357
  <div class="wa-view">
3284
3358
  ${e.selectedJid?c`
3285
- ${uw(e)}
3286
- ${pw(e)}
3359
+ ${fw(e)}
3360
+ ${gw(e)}
3287
3361
  <div class="wa-messages">
3288
- ${e.messagesLoading?c`<div class="wa-messages__empty">Loading messages...</div>`:hw(e.messages)}
3362
+ ${e.messagesLoading?c`<div class="wa-messages__empty">Loading messages...</div>`:mw(e.messages)}
3289
3363
  </div>
3290
3364
  `:c`<div class="wa-view__empty">Select a conversation</div>`}
3291
3365
  </div>
3292
3366
  </div>
3293
- `}const gw=c`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`;function mw(e){if(!e.connected)return c`
3367
+ `}const vw=c`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`;function bw(e){if(!e.connected)return c`
3294
3368
  <div class="setup-container">
3295
3369
  <div class="setup-card">
3296
3370
  <div class="setup-spinner"></div>
@@ -3303,7 +3377,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3303
3377
  target="_blank"
3304
3378
  rel="noopener"
3305
3379
  title="Open public chat in new tab"
3306
- >Public ${gw}</a>`:w,i=e.whatsappProps?c`
3380
+ >Public ${vw}</a>`:w,i=e.whatsappProps?c`
3307
3381
  <div class="chat-page-tabs">
3308
3382
  <button
3309
3383
  class="chat-page-tab ${t==="chat"?"active":""}"
@@ -3316,20 +3390,20 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3316
3390
  </div>
3317
3391
  `:w;return c`
3318
3392
  <div class="setup-container setup-container--full chat-page">
3319
- ${Rt("Chat",e.wsProps)}
3393
+ ${It("Chat",e.wsProps)}
3320
3394
  ${n}
3321
3395
  ${i}
3322
3396
  <div class="chat-viewport">
3323
- ${t==="whatsapp"&&e.whatsappProps?fw(e.whatsappProps):yu(e)}
3397
+ ${t==="whatsapp"&&e.whatsappProps?yw(e.whatsappProps):vu(e)}
3324
3398
  </div>
3325
3399
  </div>
3326
- `}async function bu(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 yw(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 vw(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 bw(e){return e?`${Xl(e)} (${rs(e)})`:"n/a"}function wu(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?rs(t.lastRunAtMs):"never";return`${n} · last ${i}`}function ku(e){const t=e.schedule;return t.kind==="at"?`One-time: ${Xl(t.atMs)}`:t.kind==="every"?`Every ${na(t.everyMs)}`:ww(t.expr,t.tz)}function ww(e,t){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[i,s,o,a,r]=n,l=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=wl(s);if(h===null||!u)return`${e}${t?` (${t})`:""}`;const p=u.map(S=>d(S,h)),y=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 ${y}${l}`;if(r==="1-5")return`Weekdays at ${y}${l}`;if(r==="0,6"||r==="6,0")return`Weekends at ${y}${l}`;const S=wl(r);if(S)return`${S.map(v=>$[v%7]??String(v)).join(", ")} at ${y}${l}`}return`${e}${t?` (${t})`:""}`}function wl(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 kw(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 kl(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 xw(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 $w(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 Sw(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function Aw(e){return e||"Default"}const Cw=c`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,Ew=c`<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>`,Tw=c`<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>`,vs=c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,_w=c`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,xu=c`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,Mw=c`<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 xl(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return c`
3327
- ${Pw(e)}
3328
- ${Iw(e)}
3329
- ${n?Lw(e):w}
3330
- ${t?Nw(t,e):w}
3331
- ${e.runModalJobId?Ow(e):w}
3332
- `}function Pw(e){const t=e.status,n=(t==null?void 0:t.enabled)??!1,i=e.jobs.length,s=t==null?void 0:t.nextWakeAtMs;return c`
3400
+ `}async function wu(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 ww(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 kw(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 xw(e){return e?`${Xl(e)} (${rs(e)})`:"n/a"}function ku(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?rs(t.lastRunAtMs):"never";return`${n} · last ${i}`}function xu(e){const t=e.schedule;return t.kind==="at"?`One-time: ${Xl(t.atMs)}`:t.kind==="every"?`Every ${na(t.everyMs)}`:$w(t.expr,t.tz)}function $w(e,t){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[i,s,o,a,r]=n,l=t?` (${t.replace(/^.*\//,"").replace(/_/g," ")})`:"",d=(S,_)=>new Date(2e3,0,1,S,_).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),h=/^\d{1,2}$/.test(i)?parseInt(i,10):null,u=wl(s);if(h===null||!u)return`${e}${t?` (${t})`:""}`;const p=u.map(S=>d(S,h)),y=p.length<=3?p.join(" & "):`${p.slice(0,-1).join(", ")} & ${p[p.length-1]}`,x=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&a==="*"){if(r==="*")return`Daily at ${y}${l}`;if(r==="1-5")return`Weekdays at ${y}${l}`;if(r==="0,6"||r==="6,0")return`Weekends at ${y}${l}`;const S=wl(r);if(S)return`${S.map(v=>x[v%7]??String(v)).join(", ")} at ${y}${l}`}return`${e}${t?` (${t})`:""}`}function wl(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 Sw(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 kl(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 Aw(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 Cw(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 Ew(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function Tw(e){return e||"Default"}const _w=c`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,Mw=c`<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>`,Pw=c`<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>`,vs=c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,Iw=c`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,$u=c`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,Rw=c`<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 xl(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return c`
3401
+ ${Lw(e)}
3402
+ ${Dw(e)}
3403
+ ${n?Nw(e):w}
3404
+ ${t?Uw(t,e):w}
3405
+ ${e.runModalJobId?Ww(e):w}
3406
+ `}function Lw(e){const t=e.status,n=(t==null?void 0:t.enabled)??!1,i=e.jobs.length,s=t==null?void 0:t.nextWakeAtMs;return c`
3333
3407
  <div class="event-status-bar">
3334
3408
  <div class="event-status-bar__info">
3335
3409
  <span class="statusDot ${n?"ok":""}"></span>
@@ -3351,14 +3425,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3351
3425
  ${e.error?c`<span class="muted">${e.error}</span>`:w}
3352
3426
  </div>
3353
3427
  <button class="btn primary btn--sm" @click=${e.onNewEventModalOpen}>
3354
- ${xu} New Event
3428
+ ${$u} New Event
3355
3429
  </button>
3356
3430
  </div>
3357
- `}function Iw(e){return e.jobs.length===0?c`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:c`
3431
+ `}function Dw(e){return e.jobs.length===0?c`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:c`
3358
3432
  <div class="event-grid">
3359
- ${e.jobs.map(t=>Rw(t,e))}
3433
+ ${e.jobs.map(t=>Bw(t,e))}
3360
3434
  </div>
3361
- `}function Rw(e,t){return c`
3435
+ `}function Bw(e,t){return c`
3362
3436
  <div
3363
3437
  class="event-card ${e.enabled?"":"disabled"}"
3364
3438
  @click=${()=>t.onDetailOpen(e)}
@@ -3369,12 +3443,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3369
3443
  ${e.enabled?"On":"Off"}
3370
3444
  </span>
3371
3445
  </div>
3372
- <div class="event-card__schedule">${ku(e)}</div>
3373
- ${e.agentId?c`<div class="event-card__agent">${Aw(e.agentId)}</div>`:w}
3446
+ <div class="event-card__schedule">${xu(e)}</div>
3447
+ ${e.agentId?c`<div class="event-card__agent">${Tw(e.agentId)}</div>`:w}
3374
3448
  ${kl(e)?c`<div class="event-card__agent muted" style="font-size: 11px;">\u2192 ${kl(e)}</div>`:w}
3375
3449
  <div class="event-card__footer">
3376
3450
  <div class="event-card__status">
3377
- <span class="muted" style="font-size: 11px;">${wu(e)}</span>
3451
+ <span class="muted" style="font-size: 11px;">${ku(e)}</span>
3378
3452
  </div>
3379
3453
  <div class="event-card__actions" @click=${n=>n.stopPropagation()}>
3380
3454
  <button
@@ -3383,7 +3457,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3383
3457
  ?disabled=${t.busy}
3384
3458
  @click=${()=>t.onToggle(e,!e.enabled)}
3385
3459
  >
3386
- ${e.enabled?Ew:Cw}
3460
+ ${e.enabled?Mw:_w}
3387
3461
  </button>
3388
3462
  <button
3389
3463
  class="btn-icon"
@@ -3391,7 +3465,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3391
3465
  ?disabled=${t.busy}
3392
3466
  @click=${()=>t.onRun(e)}
3393
3467
  >
3394
- ${_w}
3468
+ ${Iw}
3395
3469
  </button>
3396
3470
  ${t.pendingDeleteId===e.id?c`<button
3397
3471
  class="btn danger btn--sm"
@@ -3402,11 +3476,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3402
3476
  title="Delete"
3403
3477
  ?disabled=${t.busy}
3404
3478
  @click=${()=>{t.onArmDelete(e.id),be&&clearTimeout(be),be=setTimeout(()=>{t.onArmDelete(""),be=null},3e3)}}
3405
- >${Tw}</button>`}
3479
+ >${Pw}</button>`}
3406
3480
  </div>
3407
3481
  </div>
3408
3482
  </div>
3409
- `}function Lw(e){const t=!!e.editJobId,n=xw(e),i=()=>{e.onNewEventModalClose()};return c`
3483
+ `}function Nw(e){const t=!!e.editJobId,n=Aw(e),i=()=>{e.onNewEventModalClose()};return c`
3410
3484
  <div class="event-modal-overlay" @click=${i}>
3411
3485
  <div class="event-modal" @click=${s=>s.stopPropagation()}>
3412
3486
  <div class="event-modal__header">
@@ -3464,7 +3538,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3464
3538
  </label>
3465
3539
  </div>
3466
3540
 
3467
- ${Bw(e)}
3541
+ ${Fw(e)}
3468
3542
 
3469
3543
  <div class="form-grid" style="margin-top: 12px;">
3470
3544
  <label class="field">
@@ -3526,7 +3600,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3526
3600
  @change=${s=>e.onFormChange({channel:s.target.value})}
3527
3601
  >
3528
3602
  ${n.map(s=>c`<option value=${s}>
3529
- ${$w(e,s)}
3603
+ ${Cw(e,s)}
3530
3604
  </option>`)}
3531
3605
  </select>
3532
3606
  </label>
@@ -3539,7 +3613,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3539
3613
  />
3540
3614
  </label>
3541
3615
  </div>
3542
- ${Dw(e)}
3616
+ ${Ow(e)}
3543
3617
  <div class="form-grid" style="margin-top: 12px;">
3544
3618
  <label class="field">
3545
3619
  <span>Timeout (seconds)</span>
@@ -3570,7 +3644,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3570
3644
  </div>
3571
3645
  </div>
3572
3646
  </div>
3573
- `}function Dw(e){const t=e.form.recipients;return c`
3647
+ `}function Ow(e){const t=e.form.recipients;return c`
3574
3648
  <div style="margin-top: 8px;">
3575
3649
  <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
3576
3650
  <span style="font-size: 13px; color: var(--muted);">Recipients</span>
@@ -3578,7 +3652,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3578
3652
  class="btn btn--sm"
3579
3653
  @click=${()=>{e.onFormChange({recipients:[...t,""]})}}
3580
3654
  >
3581
- ${xu} Add
3655
+ ${$u} Add
3582
3656
  </button>
3583
3657
  </div>
3584
3658
  ${t.length===0&&!e.form.toAdmins?c`<div class="muted" style="font-size: 12px; padding: 4px 0;">No recipients. Add a phone number or enable "All admins".</div>`:w}
@@ -3600,7 +3674,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3600
3674
  </div>
3601
3675
  `)}
3602
3676
  </div>
3603
- `}function Bw(e){const t=e.form;return t.scheduleKind==="at"?c`
3677
+ `}function Fw(e){const t=e.form;return t.scheduleKind==="at"?c`
3604
3678
  <label class="field" style="margin-top: 12px;">
3605
3679
  <span>Run at</span>
3606
3680
  <input
@@ -3649,7 +3723,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3649
3723
  />
3650
3724
  </label>
3651
3725
  </div>
3652
- `}function Nw(e,t){var n;return c`
3726
+ `}function Uw(e,t){var n;return c`
3653
3727
  <div class="event-modal-overlay" @click=${t.onDetailClose}>
3654
3728
  <div class="event-modal" @click=${i=>i.stopPropagation()}>
3655
3729
  <div class="event-modal__header">
@@ -3667,7 +3741,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3667
3741
  ?disabled=${t.busy}
3668
3742
  @click=${()=>t.onEdit(e)}
3669
3743
  >
3670
- ${Mw} Edit
3744
+ ${Rw} Edit
3671
3745
  </button>
3672
3746
  <button
3673
3747
  class="btn"
@@ -3703,7 +3777,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3703
3777
  </div>
3704
3778
  <div class="event-detail-row">
3705
3779
  <span class="event-detail-label">Schedule</span>
3706
- <span class="event-detail-value">${ku(e)}</span>
3780
+ <span class="event-detail-value">${xu(e)}</span>
3707
3781
  </div>
3708
3782
  ${e.agentId?c`
3709
3783
  <div class="event-detail-row">
@@ -3725,12 +3799,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3725
3799
  </div>
3726
3800
  <div class="event-detail-row" style="flex-direction: column; align-items: stretch; gap: 4px;">
3727
3801
  <span class="event-detail-label">Action</span>
3728
- <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${kw(e,!1)}</span>
3802
+ <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${Sw(e,!1)}</span>
3729
3803
  </div>
3730
3804
  ${e.payload.kind==="agentTurn"&&e.payload.to?c`
3731
3805
  <div class="event-detail-row">
3732
3806
  <span class="event-detail-label">Send to</span>
3733
- <span class="event-detail-value mono">${Sw(e.payload.to)}</span>
3807
+ <span class="event-detail-value mono">${Ew(e.payload.to)}</span>
3734
3808
  </div>
3735
3809
  `:w}
3736
3810
  ${e.payload.kind==="agentTurn"&&(e.payload.channel??e.payload.provider)?c`
@@ -3750,12 +3824,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3750
3824
  <div class="event-detail-section">
3751
3825
  <div class="event-detail-row">
3752
3826
  <span class="event-detail-label">Last run</span>
3753
- <span class="event-detail-value">${wu(e)}</span>
3827
+ <span class="event-detail-value">${ku(e)}</span>
3754
3828
  </div>
3755
3829
  ${(n=e.state)!=null&&n.nextRunAtMs?c`
3756
3830
  <div class="event-detail-row">
3757
3831
  <span class="event-detail-label">Next run</span>
3758
- <span class="event-detail-value">${bw(e.state.nextRunAtMs)}</span>
3832
+ <span class="event-detail-value">${xw(e.state.nextRunAtMs)}</span>
3759
3833
  </div>
3760
3834
  `:w}
3761
3835
  </div>
@@ -3766,14 +3840,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3766
3840
  </div>
3767
3841
  ${t.runs.length===0?c`<div class="muted" style="font-size: 13px;">No runs recorded yet.</div>`:c`
3768
3842
  <div class="list">
3769
- ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>Uw(i))}
3843
+ ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>Kw(i))}
3770
3844
  </div>
3771
3845
  `}
3772
3846
  </div>
3773
3847
 
3774
3848
  </div>
3775
3849
  </div>
3776
- `}function Ow(e){const t=e.runResult,n=!t,i=(t==null?void 0:t.status)==="ok"?"Completed":(t==null?void 0:t.status)==="error"?"Error":(t==null?void 0:t.status)==="skipped"?"Skipped":(t==null?void 0:t.status)??"";return c`
3850
+ `}function Ww(e){const t=e.runResult,n=!t,i=(t==null?void 0:t.status)==="ok"?"Completed":(t==null?void 0:t.status)==="error"?"Error":(t==null?void 0:t.status)==="skipped"?"Skipped":(t==null?void 0:t.status)??"";return c`
3777
3851
  <div class="event-modal-overlay" @click=${e.onRunModalClose}>
3778
3852
  <div class="event-modal" style="max-width: 480px;" @click=${s=>s.stopPropagation()}>
3779
3853
  <div class="event-modal__header">
@@ -3818,10 +3892,10 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3818
3892
  `}
3819
3893
  </div>
3820
3894
  </div>
3821
- `}function Fw(e){const t=e.toLowerCase();return t==="ok"||t==="success"?"chip chip-ok":t==="error"||t==="fail"||t==="failed"||t==="skipped"?"chip chip-warn":"chip"}function Uw(e){return c`
3895
+ `}function zw(e){const t=e.toLowerCase();return t==="ok"||t==="success"?"chip chip-ok":t==="error"||t==="fail"||t==="failed"||t==="skipped"?"chip chip-warn":"chip"}function Kw(e){return c`
3822
3896
  <div class="list-item" style="grid-template-columns: 1fr; gap: 6px;">
3823
3897
  <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
3824
- <span class=${Fw(e.status)} style="font-size: 11px; padding: 2px 8px;">
3898
+ <span class=${zw(e.status)} style="font-size: 11px; padding: 2px 8px;">
3825
3899
  ${e.status}
3826
3900
  </span>
3827
3901
  <span class="muted" style="font-size: 12px;">${rs(e.ts)}</span>
@@ -3835,7 +3909,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3835
3909
  </details>
3836
3910
  `:w}
3837
3911
  </div>
3838
- `}function Ww(e){var l;const t=((l=e.report)==null?void 0:l.skills)??[],n=e.filter.trim().toLowerCase(),i=e.typeFilter,s=e.agentFilter,o=t.filter(d=>{var h;return i==="preloaded"&&!d.preloaded||i==="user"&&(d.preloaded||d.marketplace)||i==="licensed"&&!d.marketplace||s!=="all"&&!((h=d.agents)!=null&&h.includes(s))?!1:n?[d.name,d.description].join(" ").toLowerCase().includes(n):!0}),a=(d,h)=>c`
3912
+ `}function Hw(e){var l;const t=((l=e.report)==null?void 0:l.skills)??[],n=e.filter.trim().toLowerCase(),i=e.typeFilter,s=e.agentFilter,o=t.filter(d=>{var h;return i==="preloaded"&&!d.preloaded||i==="user"&&(d.preloaded||d.marketplace)||i==="licensed"&&!d.marketplace||s!=="all"&&!((h=d.agents)!=null&&h.includes(s))?!1:n?[d.name,d.description].join(" ").toLowerCase().includes(n):!0}),a=(d,h)=>c`
3839
3913
  <button
3840
3914
  class="chip ${i===h?"chip-ok":""}"
3841
3915
  style="cursor: pointer; border: none; background: ${i===h?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${i===h?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
@@ -3889,20 +3963,20 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3889
3963
 
3890
3964
  ${o.length===0?c`<div class="muted" style="margin-top: 16px;">No skills found.</div>`:c`
3891
3965
  <div class="list" style="margin-top: 16px;">
3892
- ${o.map(d=>zw(d,e))}
3966
+ ${o.map(d=>qw(d,e))}
3893
3967
  </div>
3894
3968
  `}
3895
3969
  </section>
3896
3970
 
3897
- ${e.detail?Hw(e):w}
3898
- ${e.addModal?qw(e):w}
3899
- `}function zw(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(l=>`bin:${l}`),...e.missing.env.map(l=>`env:${l}`),...e.missing.config.map(l=>`config:${l}`),...e.missing.os.map(l=>`os:${l}`)],r=[];return e.disabled&&r.push("disabled"),e.blockedByAllowlist&&r.push("blocked by allowlist"),c`
3971
+ ${e.detail?Vw(e):w}
3972
+ ${e.addModal?Gw(e):w}
3973
+ `}function qw(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(l=>`bin:${l}`),...e.missing.env.map(l=>`env:${l}`),...e.missing.config.map(l=>`config:${l}`),...e.missing.os.map(l=>`os:${l}`)],r=[];return e.disabled&&r.push("disabled"),e.blockedByAllowlist&&r.push("blocked by allowlist"),c`
3900
3974
  <div class="list-item" style="cursor: pointer;" @click=${()=>t.onViewDetail(e.name)}>
3901
3975
  <div class="list-main">
3902
3976
  <div class="list-title">
3903
3977
  ${e.emoji?`${e.emoji} `:""}${e.name}
3904
3978
  </div>
3905
- <div class="list-sub">${Op(e.description,140)}</div>
3979
+ <div class="list-sub">${Fp(e.description,140)}</div>
3906
3980
  <div class="chip-row" style="margin-top: 6px;">
3907
3981
  <span class="chip ${e.preloaded?"chip-ok":""}">
3908
3982
  ${e.marketplace?"Licensed":e.preloaded?"Preloaded":"User"}
@@ -3915,7 +3989,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3915
3989
  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."}
3916
3990
  @click=${l=>{l.stopPropagation(),t.onAlwaysActiveToggle(e.name,!e.alwaysActive)}}
3917
3991
  >${e.alwaysActive?"Always active":"On demand"}</span>`}
3918
- ${Kw(e,t)}
3992
+ ${jw(e,t)}
3919
3993
  </div>
3920
3994
  ${a.length>0?c`
3921
3995
  <div class="muted" style="margin-top: 6px;">
@@ -3985,7 +4059,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3985
4059
  `:w}
3986
4060
  </div>
3987
4061
  </div>
3988
- `}function Kw(e,t){const n=e.agents??["admin","public"],i=e.agentsLocked,s=n.includes("admin"),o=n.includes("public"),a=(r,l)=>{const d=l?[...n,r]:n.filter(h=>h!==r);d.length!==0&&t.onAgentsChange(e.skillKey,d)};return c`
4062
+ `}function jw(e,t){const n=e.agents??["admin","public"],i=e.agentsLocked,s=n.includes("admin"),o=n.includes("public"),a=(r,l)=>{const d=l?[...n,r]:n.filter(h=>h!==r);d.length!==0&&t.onAgentsChange(e.skillKey,d)};return c`
3989
4063
  <span
3990
4064
  style="display: inline-flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-muted, #888); margin-left: 4px; opacity: ${i?.6:1};"
3991
4065
  @click=${r=>r.stopPropagation()}
@@ -4011,7 +4085,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4011
4085
  Public
4012
4086
  </label>
4013
4087
  </span>
4014
- `}function Hw(e){var l,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:((l=t.references.find(u=>u.name===i))==null?void 0:l.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 c`
4088
+ `}function Vw(e){var l,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:((l=t.references.find(u=>u.name===i))==null?void 0:l.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 c`
4015
4089
  <div class="event-modal-overlay" @click=${o}>
4016
4090
  <div class="event-modal" style="width: min(720px, 100%);" @click=${u=>u.stopPropagation()}>
4017
4091
  <div class="event-modal__header">
@@ -4037,7 +4111,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4037
4111
  <pre style="white-space: pre-wrap; word-break: break-word; font-size: 12px; line-height: 1.5; max-height: 60vh; overflow-y: auto; background: var(--bg, #111); padding: 16px; border-radius: 8px; border: 1px solid var(--border);">${s}</pre>
4038
4112
  </div>
4039
4113
  </div>
4040
- `}function qw(e){const t=e.drafts.length>0,n=e.busyKey==="__add__",i=e.addForm.name.trim()!=="",s=e.formSource==="installed",o=r=>{r.target.classList.contains("event-modal-overlay")&&e.onAddClose()},a=i?s?`Edit Skill: ${e.addForm.name}`:`Edit Draft: ${e.addForm.name}`:"Skill Drafts";return c`
4114
+ `}function Gw(e){const t=e.drafts.length>0,n=e.busyKey==="__add__",i=e.addForm.name.trim()!=="",s=e.formSource==="installed",o=r=>{r.target.classList.contains("event-modal-overlay")&&e.onAddClose()},a=i?s?`Edit Skill: ${e.addForm.name}`:`Edit Draft: ${e.addForm.name}`:"Skill Drafts";return c`
4041
4115
  <div class="event-modal-overlay" @click=${o}>
4042
4116
  <div class="event-modal" style="width: min(620px, 100%);" @click=${r=>r.stopPropagation()}>
4043
4117
  <div class="event-modal__header">
@@ -4045,14 +4119,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4045
4119
  <button class="event-modal__close" @click=${e.onAddClose}>&times;</button>
4046
4120
  </div>
4047
4121
 
4048
- ${i?jw(e,n):t?Gw(e,n):c`
4122
+ ${i?Qw(e,n):t?Jw(e,n):c`
4049
4123
  <div class="muted" style="text-align: center; padding: 32px 16px;">
4050
4124
  No drafts available. Ask your assistant to create a skill and it will appear here.
4051
4125
  </div>
4052
4126
  `}
4053
4127
  </div>
4054
4128
  </div>
4055
- `}function jw(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),l=d=>c`
4129
+ `}function Qw(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),l=d=>c`
4056
4130
  <button
4057
4131
  class="chip ${d===a?"chip-ok":""}"
4058
4132
  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;"
@@ -4103,7 +4177,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4103
4177
  ${t?"Saving…":s}
4104
4178
  </button>
4105
4179
  </div>
4106
- `}function Gw(e,t){return c`
4180
+ `}function Jw(e,t){return c`
4107
4181
  <div class="card-sub" style="margin-bottom: 16px;">
4108
4182
  Skills prepared by your assistant. Review, install, or delete.
4109
4183
  </div>
@@ -4144,7 +4218,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4144
4218
  </div>
4145
4219
  `})}
4146
4220
  </div>
4147
- `}const Vw=["user","assistant","tool_call","tool_result","thinking","error"],$l={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function $u(e,t){return e==="tool"?"tool_call":e==="tool_result"&&typeof t=="string"&&t.startsWith("[error]")?"error":e}function Qw(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Jw(e){return e.split(":").slice(2).join(":")||e}function Yw(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Xw(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const Sl=300;function Zw(e,t){const n=$u(e.type,e.content);return t[n]??!0}function ek(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!Zw(i,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:Yw(i,t));return c`
4221
+ `}const Yw=["user","assistant","tool_call","tool_result","thinking","error"],$l={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function Su(e,t){return e==="tool"?"tool_call":e==="tool_result"&&typeof t=="string"&&t.startsWith("[error]")?"error":e}function Xw(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Zw(e){return e.split(":").slice(2).join(":")||e}function ek(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function tk(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const Sl=300;function nk(e,t){const n=Su(e.type,e.content);return t[n]??!0}function ik(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!nk(i,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:ek(i,t));return c`
4148
4222
  <div>
4149
4223
  <button class="chips-toggle" style="margin-top: 10px;" @click=${e.onToggleChips}>
4150
4224
  <span class="chips-toggle-icon ${e.chipsExpanded?"expanded":""}">${I.chevronDown}</span>
@@ -4152,7 +4226,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4152
4226
  </button>
4153
4227
  ${e.chipsExpanded?c`
4154
4228
  <div class="chip-row" style="margin-top: 6px;">
4155
- ${Vw.map(i=>c`
4229
+ ${Yw.map(i=>c`
4156
4230
  <label class="chip session-log-chip ${i}">
4157
4231
  <input
4158
4232
  type="checkbox"
@@ -4186,13 +4260,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4186
4260
  ${e.error?c`<div class="callout danger" style="margin-top: 10px;">${e.error}</div>`:w}
4187
4261
 
4188
4262
  <div class="log-stream" style="margin-top: 10px;" @scroll=${e.onScroll}>
4189
- ${n.length===0?c`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=$u(i.type,i.content),a=Xw(i,s),r=e.expandedIds.has(a),l=i.content.length>Sl,d=r||!l?i.content:i.content.slice(0,Sl)+"…";return c`
4263
+ ${n.length===0?c`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=Su(i.type,i.content),a=tk(i,s),r=e.expandedIds.has(a),l=i.content.length>Sl,d=r||!l?i.content:i.content.slice(0,Sl)+"…";return c`
4190
4264
  <div class="log-row session-entry ${o}">
4191
4265
  <div class="log-row-header">
4192
- <span class="log-time mono">${Qw(i.timestamp)}</span>
4266
+ <span class="log-time mono">${Xw(i.timestamp)}</span>
4193
4267
  <span class="session-log-type ${o}">${$l[o]}</span>
4194
4268
  <span class="log-subsystem mono">${i.agentId}</span>
4195
- <span class="session-label mono">${Jw(i.sessionKey)}</span>
4269
+ <span class="session-label mono">${Zw(i.sessionKey)}</span>
4196
4270
  ${i.toolName?c`<span class="session-tool mono">${i.toolName}</span>`:w}
4197
4271
  ${i.toolCallId?c`<span class="session-call-id mono">${i.toolCallId.slice(0,12)}</span>`:w}
4198
4272
  ${i.model?c`<span class="session-model mono">${i.model}</span>`:w}
@@ -4206,7 +4280,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4206
4280
  `})}
4207
4281
  </div>
4208
4282
  </div>
4209
- `}const jo=["trace","debug","info","warn","error","fatal"];function tk(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function Su(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function nk(e){const t=!e.isAdmin||e.logsSubTab==="session";return c`
4283
+ `}const jo=["trace","debug","info","warn","error","fatal"];function sk(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function Au(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function ok(e){const t=!e.isAdmin||e.logsSubTab==="session";return c`
4210
4284
  <section class="card">
4211
4285
  <div class="logs-toolbar">
4212
4286
  <div class="sp-tabs" style="margin: 0;">
@@ -4257,7 +4331,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4257
4331
  <button
4258
4332
  class="btn btn-sm"
4259
4333
  ?disabled=${e.entries.length===0}
4260
- @click=${()=>{const n=e.filterText.trim().toLowerCase(),i=jo.some(a=>!e.levelFilters[a]),s=e.entries.filter(a=>a.level&&!e.levelFilters[a.level]?!1:Su(a,n)),o=n||i?"filtered":"visible";e.onExport(s.map(a=>a.raw),o)}}
4334
+ @click=${()=>{const n=e.filterText.trim().toLowerCase(),i=jo.some(a=>!e.levelFilters[a]),s=e.entries.filter(a=>a.level&&!e.levelFilters[a.level]?!1:Au(a,n)),o=n||i?"filtered":"visible";e.onExport(s.map(a=>a.raw),o)}}
4261
4335
  >
4262
4336
  Export
4263
4337
  </button>
@@ -4271,9 +4345,9 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4271
4345
  </div>
4272
4346
  </div>
4273
4347
 
4274
- ${t?ek(e.sessionLogsProps):ik(e)}
4348
+ ${t?ik(e.sessionLogsProps):ak(e)}
4275
4349
  </section>
4276
- `}function ik(e){const t=e.filterText.trim().toLowerCase();jo.some(l=>!e.levelFilters[l]);const n=e.entries.filter(l=>l.level&&!e.levelFilters[l.level]?!1:Su(l,t)),i=e.availableDates,s=e.selectedDate??(i.length>0?i[0]:null),o=s?i.indexOf(s):0,a=o>0||e.selectedDate!=null,r=o>=0&&o<i.length-1;return c`
4350
+ `}function ak(e){const t=e.filterText.trim().toLowerCase();jo.some(l=>!e.levelFilters[l]);const n=e.entries.filter(l=>l.level&&!e.levelFilters[l.level]?!1:Au(l,t)),i=e.availableDates,s=e.selectedDate??(i.length>0?i[0]:null),o=s?i.indexOf(s):0,a=o>0||e.selectedDate!=null,r=o>=0&&o<i.length-1;return c`
4277
4351
  ${i.length>1?c`
4278
4352
  <div class="logs-date-nav">
4279
4353
  <button class="btn btn-sm" ?disabled=${!r}
@@ -4326,7 +4400,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4326
4400
  ${n.length===0?c`<div class="muted" style="padding: 12px;">No log entries.</div>`:[...n].reverse().map(l=>c`
4327
4401
  <div class="log-row">
4328
4402
  <div class="log-row-header">
4329
- <span class="log-time mono">${tk(l.time)}</span>
4403
+ <span class="log-time mono">${sk(l.time)}</span>
4330
4404
  <span class="log-level ${l.level??""}">${l.level??""}</span>
4331
4405
  <span class="log-subsystem mono">${l.subsystem??""}</span>
4332
4406
  </div>
@@ -4334,13 +4408,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4334
4408
  </div>
4335
4409
  `)}
4336
4410
  </div>
4337
- `}const sk=[{key:"monday",label:"Monday"},{key:"tuesday",label:"Tuesday"},{key:"wednesday",label:"Wednesday"},{key:"thursday",label:"Thursday"},{key:"friday",label:"Friday"},{key:"saturday",label:"Saturday"},{key:"sunday",label:"Sunday"}],ok=c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,ak=c`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`;function rk(e){return c`
4338
- ${lk(e)}
4339
- ${ck(e)}
4340
- ${dk(e)}
4411
+ `}const rk=[{key:"monday",label:"Monday"},{key:"tuesday",label:"Tuesday"},{key:"wednesday",label:"Wednesday"},{key:"thursday",label:"Thursday"},{key:"friday",label:"Friday"},{key:"saturday",label:"Saturday"},{key:"sunday",label:"Sunday"}],lk=c`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,ck=c`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`;function dk(e){return c`
4412
+ ${uk(e)}
4341
4413
  ${pk(e)}
4342
4414
  ${hk(e)}
4343
- `}function lk(e){return c`
4415
+ ${gk(e)}
4416
+ ${mk(e)}
4417
+ `}function uk(e){return c`
4344
4418
  <label class="field checkbox" style="margin: 16px 0;">
4345
4419
  <input
4346
4420
  type="checkbox"
@@ -4354,7 +4428,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4354
4428
  </span>
4355
4429
  </span>
4356
4430
  </label>
4357
- `}function ck(e){const t=e.form.enabled;return c`
4431
+ `}function pk(e){const t=e.form.enabled;return c`
4358
4432
  <label
4359
4433
  class="field checkbox"
4360
4434
  style="margin: 0 0 16px; ${t?"":"opacity: 0.4; pointer-events: none;"}"
@@ -4372,14 +4446,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4372
4446
  </span>
4373
4447
  </span>
4374
4448
  </label>
4375
- `}function dk(e){return c`
4449
+ `}function hk(e){return c`
4376
4450
  <div style="margin-bottom: 20px;">
4377
4451
  <div style="font-size: 14px; font-weight: 500; margin-bottom: 12px;">Weekly Schedule</div>
4378
4452
  <div class="oh-schedule">
4379
- ${sk.map(t=>uk(t,e))}
4453
+ ${rk.map(t=>fk(t,e))}
4380
4454
  </div>
4381
4455
  </div>
4382
- `}function uk(e,t){const n=t.form.days[e.key];if(!n)return w;const i=n.closed;return c`
4456
+ `}function fk(e,t){const n=t.form.days[e.key];if(!n)return w;const i=n.closed;return c`
4383
4457
  <div class="oh-day-row">
4384
4458
  <div class="oh-day-label">${e.label}</div>
4385
4459
  <div class="oh-day-times" style="${i?"opacity: 0.35; pointer-events: none;":""}">
@@ -4404,7 +4478,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4404
4478
  <span>Closed</span>
4405
4479
  </label>
4406
4480
  </div>
4407
- `}let wi="";function pk(e){const t=e.form.closedDates;return c`
4481
+ `}let wi="";function gk(e){const t=e.form.closedDates;return c`
4408
4482
  <div style="margin-bottom: 20px;">
4409
4483
  <div style="font-size: 14px; font-weight: 500; margin-bottom: 10px;">Closed Dates</div>
4410
4484
  <div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">
@@ -4416,7 +4490,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4416
4490
  style="width: 16px; height: 16px; padding: 0;"
4417
4491
  @click=${()=>e.onRemoveClosedDate(n)}
4418
4492
  >
4419
- ${ok}
4493
+ ${lk}
4420
4494
  </button>
4421
4495
  </span>
4422
4496
  `)}
@@ -4432,11 +4506,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4432
4506
  class="btn btn--sm"
4433
4507
  @click=${()=>{if(wi){e.onAddClosedDate(wi);const n=document.getElementById("oh-new-closed-date");n&&(n.value=""),wi=""}}}
4434
4508
  >
4435
- ${ak} Add
4509
+ ${ck} Add
4436
4510
  </button>
4437
4511
  </div>
4438
4512
  </div>
4439
- `}function hk(e){return c`
4513
+ `}function mk(e){return c`
4440
4514
  <div style="display: flex; justify-content: flex-end; padding-top: 8px;">
4441
4515
  <button
4442
4516
  class="btn primary"
@@ -4446,12 +4520,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4446
4520
  ${e.busy?"Saving…":"Save"}
4447
4521
  </button>
4448
4522
  </div>
4449
- `}const fk=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"opening-hours",label:"Opening Hours"},{id:"logs",label:"Logs"}];function gk(e){switch(e.activeTab){case"cron":return xl(e.cronProps);case"skills":return Ww(e.skillsProps);case"opening-hours":return rk(e.openingHoursProps);case"logs":return nk(e.logsProps);default:return xl(e.cronProps)}}function mk(e){return e.connected?c`
4523
+ `}const yk=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"opening-hours",label:"Opening Hours"},{id:"logs",label:"Logs"}];function vk(e){switch(e.activeTab){case"cron":return xl(e.cronProps);case"skills":return Hw(e.skillsProps);case"opening-hours":return dk(e.openingHoursProps);case"logs":return ok(e.logsProps);default:return xl(e.cronProps)}}function bk(e){return e.connected?c`
4450
4524
  <div class="setup-container">
4451
- ${Rt("Advanced",e.wsProps)}
4525
+ ${It("Advanced",e.wsProps)}
4452
4526
  <div class="setup-card sp-card-advanced" style="text-align: left;">
4453
4527
  <div class="sp-tabs">
4454
- ${fk.map(t=>c`
4528
+ ${yk.map(t=>c`
4455
4529
  <button
4456
4530
  class="sp-tab ${e.activeTab===t.id?"active":""}"
4457
4531
  @click=${()=>e.onTabChange(t.id)}
@@ -4460,7 +4534,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4460
4534
  </button>
4461
4535
  `)}
4462
4536
  </div>
4463
- ${gk(e)}
4537
+ ${vk(e)}
4464
4538
  </div>
4465
4539
  </div>
4466
4540
  `:c`
@@ -4470,25 +4544,25 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4470
4544
  <p>Connecting to gateway...</p>
4471
4545
  </div>
4472
4546
  </div>
4473
- `}function Al(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=y=>{var S;o=y.target.value;const $=(S=y.target.closest(".login-card"))==null?void 0:S.querySelector(".login-change-pin");$&&($.style.display=o==="__master__"?"":"none")},r=y=>$=>{const S=$.target;S.value=S.value.replace(/\D/g,"").slice(0,6),y(S.value)},l=y=>{const $=y.currentTarget,S=$.closest(".login-pin-wrapper"),M=S==null?void 0:S.querySelector("input");if(!M)return;const v=M.type==="text";M.type=v?"password":"text",$.classList.toggle("active",!v)},d=!n&&e.accounts.length>1?c`
4547
+ `}function Al(e){if(!e.show)return w;const t=Qe(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const a=y=>{var S;o=y.target.value;const x=(S=y.target.closest(".login-card"))==null?void 0:S.querySelector(".login-change-pin");x&&(x.style.display=o==="__master__"?"":"none")},r=y=>x=>{const S=x.target;S.value=S.value.replace(/\D/g,"").slice(0,6),y(S.value)},l=y=>{const x=y.currentTarget,S=x.closest(".login-pin-wrapper"),_=S==null?void 0:S.querySelector("input");if(!_)return;const v=_.type==="text";_.type=v?"password":"text",x.classList.toggle("active",!v)},d=!n&&e.accounts.length>1?c`
4474
4548
  <select
4475
4549
  class="login-account-select"
4476
4550
  @change=${a}
4477
4551
  ?disabled=${e.busy||s}
4478
4552
  >
4479
- ${e.accounts.map((y,$)=>c`
4480
- <option value=${y.id} ?selected=${$===0}>
4553
+ ${e.accounts.map((y,x)=>c`
4554
+ <option value=${y.id} ?selected=${x===0}>
4481
4555
  ${y.displayName}
4482
4556
  </option>
4483
4557
  `)}
4484
4558
  </select>
4485
- `:w;if(i){let y="",$="",S="";const M=v=>{var b;v.preventDefault(),!s&&(!y||!$||!S||$===S&&o&&((b=e.onChangePin)==null||b.call(e,o,y,$)))};return c`
4559
+ `:w;if(i){let y="",x="",S="";const _=v=>{var b;v.preventDefault(),!s&&(!y||!x||!S||x===S&&o&&((b=e.onChangePin)==null||b.call(e,o,y,x)))};return c`
4486
4560
  <div class="login-overlay">
4487
4561
  <div class="login-card">
4488
4562
  <img class="login-logo" src="${t.iconUrl}" alt="${t.name}" />
4489
4563
  <h2 class="login-title">Change PIN</h2>
4490
4564
  <p class="login-subtitle">Enter your current PIN, then choose a new one</p>
4491
- <form class="login-form" @submit=${M}>
4565
+ <form class="login-form" @submit=${_}>
4492
4566
  ${d}
4493
4567
  <div class="login-pin-wrapper">
4494
4568
  <input
@@ -4518,7 +4592,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4518
4592
  maxlength="6"
4519
4593
  placeholder="New PIN (4-6 digits)"
4520
4594
  ?disabled=${s}
4521
- @input=${r(v=>{$=v})}
4595
+ @input=${r(v=>{x=v})}
4522
4596
  />
4523
4597
  <button class="login-pin-toggle" type="button" @click=${l}>
4524
4598
  <span class="pin-eye-show">${I.eye}</span>
@@ -4619,12 +4693,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4619
4693
  <a
4620
4694
  class="login-link"
4621
4695
  href="#"
4622
- @click=${y=>{var $;y.preventDefault(),($=e.onToggleChangePinMode)==null||$.call(e)}}
4696
+ @click=${y=>{var x;y.preventDefault(),(x=e.onToggleChangePinMode)==null||x.call(e)}}
4623
4697
  >Change PIN</a>
4624
4698
  </p>`:w}
4625
4699
  </div>
4626
4700
  </div>
4627
- `}function yk(e){if(!e.connected)return c`
4701
+ `}function wk(e){if(!e.connected)return c`
4628
4702
  <div class="setup-container">
4629
4703
  <div class="setup-card">
4630
4704
  <div class="setup-spinner"></div>
@@ -4637,10 +4711,10 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4637
4711
  <span class="public-chat-header__name">${n}</span>
4638
4712
  </div>
4639
4713
  <div class="chat-viewport">
4640
- ${yu(t)}
4714
+ ${vu(t)}
4641
4715
  </div>
4642
4716
  </div>
4643
- `}async function vk(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 bk(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 l=await e.client.request("workspaces.create",r);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Vn(e),(s=t.onCreated)==null||s.call(t,l)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function wk(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 kk(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:bk,loadWorkspaces:Vn,removeWorkspace:wk,renameWorkspace:kk},Symbol.toStringTag,{value:"Module"})),Au={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"},Cl=Au,Go={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Au));new Set(Object.values(Go));function xk(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 $k=4008;class Sk{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 cf();const p=(u=pf({deviceId:o.deviceId,role:t}))==null?void 0:u.token;r=p??this.opts.token,a=!!(p&&this.opts.token)}const l=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let d;if(s&&o){const p=Date.now(),y=this.connectNonce??void 0,$=xk({deviceId:o.deviceId,clientId:this.opts.clientName??Cl.CONTROL_UI,clientMode:this.opts.mode??Go.WEBCHAT,role:t,scopes:n,signedAtMs:p,token:r??null,nonce:y}),S=await df(o.privateKey,$);d={id:o.deviceId,publicKey:o.publicKey,signature:S,signedAt:p,nonce:y}}const h={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Cl.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Go.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:d,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",h).then(p=>{var y,$,S;(y=p==null?void 0:p.auth)!=null&&y.deviceToken&&o&&hf({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&&ff({deviceId:o.deviceId,role:t}),(p=this.ws)==null||p.close($k,"connect failed")})}handleMessage(t){var s,o,a,r,l,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,y=p&&typeof p.nonce=="string"?p.nonce:null;y&&(this.connectNonce=y,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(((l=h.error)==null?void 0:l.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=ls(),s={type:"req",id:i,method:t,params:n},o=new Promise((a,r)=>{this.pending.set(i,{resolve:l=>a(l),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 Vo(e){return typeof e=="object"&&e!==null}function Ak(e){if(!Vo(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Vo(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 Ck(e){if(!Vo(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 Cu(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Ek(e,t){const n=Cu(e).filter(i=>i.id!==t.id);return n.push(t),n}function El(e,t){return Cu(e).filter(n=>n.id!==t)}class Tk{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 fo=null;function Bn(){return fo||(fo=new Tk),fo}function Fa(e){return e instanceof Error?e.message:String(e)}async function _k(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=Fa(t)}finally{e.browserLoading=!1}}async function Mk(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=Fa(t)}finally{e.browserLoading=!1}}}async function go(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 mo(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 Pk(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=Fa(t)}}function Ik(e){e.browserInputMode=!e.browserInputMode}function Rk(e){e.browserFullscreen=!e.browserFullscreen,Bn().detach()}function Lk(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,Bn().updateFrame(t.data,t.metadata)}function Dk(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Bk(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=xo(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 Tl(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Nk(e,t){await e.request("apikeys.remove",{provider:t})}async function Ok(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const is="taskmaster_update_pending";async function Eu(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 Fk(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(is,String(Date.now())),localStorage.removeItem(Ua)}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 Uk(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const a=t.name,r=t.index,l=t.total;e.updateMessage=`Updating: ${a} (${r+1}/${l})`;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:l,status:"running"}],(i=e.requestUpdate)==null||i.call(e)}else if(n==="step-done"){const a=t.name,r=t.index,l=t.total,d=t.ok,h=t.durationMs,u=e.updateProgressSteps.find(y=>y.index===r);u?(u.status=d?"done":"failed",u.durationMs=h):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:l,status:d?"done":"failed",durationMs:h}];const p=!d&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=d?`Updating: ${a} done (${r+1}/${l})`:`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 Wk(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=Kk();Nn();try{const a=await e.client.request("update.lastResult",{});if(!a.ok||!a.result)return;const r=5*6e4,l=Date.now()-a.result.ts<r;if(!t&&!l||Hk(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 Ua="taskmaster_update_dismissed";function zk(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Ua,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function Kk(){try{const e=localStorage.getItem(is);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(is),!1):!0:!1}catch{return!1}}function Nn(){try{localStorage.removeItem(is)}catch{}}function Hk(e){try{const t=localStorage.getItem(Ua);return t?Number(t)>=e:!1}catch{return!1}}const _l="notification-banner";function qk(e){const t=document.getElementById(_l);if(!e){t==null||t.remove();return}t&&t.remove();const n=document.createElement("div");n.id=_l,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 yo(e,t){var r,l,d;const n=(e??"").trim(),i=(r=t.mainSessionKey)==null?void 0:r.trim();if(!i)return n;if(!n)return i;const s=((l=t.mainKey)==null?void 0:l.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 jk(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=yo(e.sessionKey,t),i=yo(e.settings.sessionKey,t),s=yo(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 Oe(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 Sk({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 l,d;const r=((l=a.server)==null?void 0:l.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){Ml(e,a),Qo(e),(((d=e.publicChatConfig)==null?void 0:d.auth)??"anonymous")==="anonymous"&&e0(e);return}qi()&&(ka(),e.uninstallDone=!1),Ml(e,a),e.handleAccessCheck(),Wk(e).then(()=>{Eu(e)}),Qo(e),vk(e),(e.chatPage||e.setup)&&Qk(e),ha(e,{quiet:!0}),pa(e,{quiet:!0}),Vn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&We(e),e.setup&&(Jk(e),Yk(e),Xk(e),Zk(e)),Ki(e)},onClose:({code:a,reason:r})=>{e.connected=!1,a!==1012&&(e.lastError=`disconnected (${a}): ${r||"no reason"}`)},onEvent:a=>Gk(e,a),onGap:({expected:a,received:r})=>{console.warn(`[gateway] event gap: expected seq ${a}, got ${r}`),Ki(e)}}),e.client.start()}function Gk(e,t){try{Vk(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function Vk(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;lh(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&cd(e,i.sessionKey);const s=rc(e,i);if((s==="final"||s==="error"||s==="aborted")&&(ia(e),og(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&&$h(e,i),e.tab==="cron"&&e.loadCron()}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&pa(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=Ak(t.payload);if(i){e.execApprovalQueue=Ek(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=El(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){Lk(e,t.payload);return}if(t.event==="browser.handoff"){Dk(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Bk(e);return}if(t.event==="exec.approval.resolved"){const i=Ck(t.payload);i&&(e.execApprovalQueue=El(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){Uk(e,t.payload);return}if(t.event==="notification"){const i=t.payload;(i==null?void 0:i.category)==="model-fallback"&&qk(i);return}}function Ml(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&&jk(e,n.sessionDefaults)}async function Qk(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 Jk(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await _i(e.client)}catch{}}async function Yk(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function Xk(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 Zk(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 Pl="taskmaster_public_id";function Tu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${Pl}=`));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=`${Pl}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function e0(e){var n,i,s;if(!e.client||!e.connected)return;const t=Tu((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=zn(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="",bs="",cn="phone",On="";function _u(e){return e.replace(/[\s\-()]/g,"")}function it(){pe=!1,ie=null,Zt="",en="",tn="",bs="",cn="phone",On=""}async function t0(e){if(!e.client||!e.connected)return;const t=Tu(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 Il(e){if(!e.client||pe)return;const t=_u(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?(bs=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 Rl(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?(bs=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 Ll(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():_u(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 c`
4717
+ `}async function kk(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 Gn(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 xk(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 l=await e.client.request("workspaces.create",r);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Gn(e),(s=t.onCreated)==null||s.call(t,l)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function $k(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 Gn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function Sk(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 Gn(e)}catch(i){e.workspacesError=String(i)}}}const ki=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:xk,loadWorkspaces:Gn,removeWorkspace:$k,renameWorkspace:Sk},Symbol.toStringTag,{value:"Module"})),Cu={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"},Cl=Cu,Vo={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Cu));new Set(Object.values(Vo));function Ak(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 Ck=4008;class Ek{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 df();const p=(u=hf({deviceId:o.deviceId,role:t}))==null?void 0:u.token;r=p??this.opts.token,a=!!(p&&this.opts.token)}const l=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let d;if(s&&o){const p=Date.now(),y=this.connectNonce??void 0,x=Ak({deviceId:o.deviceId,clientId:this.opts.clientName??Cl.CONTROL_UI,clientMode:this.opts.mode??Vo.WEBCHAT,role:t,scopes:n,signedAtMs:p,token:r??null,nonce:y}),S=await uf(o.privateKey,x);d={id:o.deviceId,publicKey:o.publicKey,signature:S,signedAt:p,nonce:y}}const h={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Cl.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Vo.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:d,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",h).then(p=>{var y,x,S;(y=p==null?void 0:p.auth)!=null&&y.deviceToken&&o&&ff({deviceId:o.deviceId,role:p.auth.role??t,token:p.auth.deviceToken,scopes:p.auth.scopes??[]}),this.backoffMs=800,(S=(x=this.opts).onHello)==null||S.call(x,p)}).catch(()=>{var p;a&&o&&gf({deviceId:o.deviceId,role:t}),(p=this.ws)==null||p.close(Ck,"connect failed")})}handleMessage(t){var s,o,a,r,l,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,y=p&&typeof p.nonce=="string"?p.nonce:null;y&&(this.connectNonce=y,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(((l=h.error)==null?void 0:l.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=ls(),s={type:"req",id:i,method:t,params:n},o=new Promise((a,r)=>{this.pending.set(i,{resolve:l=>a(l),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 Go(e){return typeof e=="object"&&e!==null}function Tk(e){if(!Go(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Go(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 _k(e){if(!Go(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 Eu(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Mk(e,t){const n=Eu(e).filter(i=>i.id!==t.id);return n.push(t),n}function El(e,t){return Eu(e).filter(n=>n.id!==t)}class Pk{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 fo=null;function Bn(){return fo||(fo=new Pk),fo}function Fa(e){return e instanceof Error?e.message:String(e)}async function Ik(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=Fa(t)}finally{e.browserLoading=!1}}async function Rk(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=Fa(t)}finally{e.browserLoading=!1}}}async function go(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 mo(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 Lk(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=Fa(t)}}function Dk(e){e.browserInputMode=!e.browserInputMode}function Bk(e){e.browserFullscreen=!e.browserFullscreen,Bn().detach()}function Nk(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,Bn().updateFrame(t.data,t.metadata)}function Ok(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Fk(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=xo(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 Tl(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Uk(e,t){await e.request("apikeys.remove",{provider:t})}async function Wk(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const is="taskmaster_update_pending";async function Tu(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 zk(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(is,String(Date.now())),localStorage.removeItem(Ua)}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 Kk(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const a=t.name,r=t.index,l=t.total;e.updateMessage=`Updating: ${a} (${r+1}/${l})`;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:l,status:"running"}],(i=e.requestUpdate)==null||i.call(e)}else if(n==="step-done"){const a=t.name,r=t.index,l=t.total,d=t.ok,h=t.durationMs,u=e.updateProgressSteps.find(y=>y.index===r);u?(u.status=d?"done":"failed",u.durationMs=h):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:l,status:d?"done":"failed",durationMs:h}];const p=!d&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=d?`Updating: ${a} done (${r+1}/${l})`:`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 Hk(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=jk();Nn();try{const a=await e.client.request("update.lastResult",{});if(!a.ok||!a.result)return;const r=5*6e4,l=Date.now()-a.result.ts<r;if(!t&&!l||Vk(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 Ua="taskmaster_update_dismissed";function qk(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Ua,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function jk(){try{const e=localStorage.getItem(is);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(is),!1):!0:!1}catch{return!1}}function Nn(){try{localStorage.removeItem(is)}catch{}}function Vk(e){try{const t=localStorage.getItem(Ua);return t?Number(t)>=e:!1}catch{return!1}}const _l="notification-banner";function Gk(e){const t=document.getElementById(_l);if(!e){t==null||t.remove();return}t&&t.remove();const n=document.createElement("div");n.id=_l,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 yo(e,t){var r,l,d;const n=(e??"").trim(),i=(r=t.mainSessionKey)==null?void 0:r.trim();if(!i)return n;if(!n)return i;const s=((l=t.mainKey)==null?void 0:l.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 Qk(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=yo(e.sessionKey,t),i=yo(e.settings.sessionKey,t),s=yo(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&&st(e,a)}function De(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 Ek({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 l,d;const r=((l=a.server)==null?void 0:l.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){Ml(e,a),Qo(e),(((d=e.publicChatConfig)==null?void 0:d.auth)??"anonymous")==="anonymous"&&i0(e);return}qi()&&(ka(),e.uninstallDone=!1),Ml(e,a),e.handleAccessCheck(),Hk(e).then(()=>{Tu(e)}),Qo(e),kk(e),(e.chatPage||e.setup)&&Xk(e),ha(e,{quiet:!0}),pa(e,{quiet:!0}),Gn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Oe(e),e.setup&&(Zk(e),e0(e),t0(e),n0(e)),Ki(e)},onClose:({code:a,reason:r})=>{e.connected=!1,a!==1012&&(e.lastError=`disconnected (${a}): ${r||"no reason"}`)},onEvent:a=>Jk(e,a),onGap:({expected:a,received:r})=>{console.warn(`[gateway] event gap: expected seq ${a}, got ${r}`),Ki(e)}}),e.client.start()}function Jk(e,t){try{Yk(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function Yk(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;ch(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&dd(e,i.sessionKey);const s=rc(e,i);if((s==="final"||s==="error"||s==="aborted")&&(ia(e),ag(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&&Sh(e,i),e.tab==="cron"&&e.loadCron()}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&pa(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=Tk(t.payload);if(i){e.execApprovalQueue=Mk(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=El(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){Nk(e,t.payload);return}if(t.event==="browser.handoff"){Ok(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Fk(e);return}if(t.event==="exec.approval.resolved"){const i=_k(t.payload);i&&(e.execApprovalQueue=El(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){Kk(e,t.payload);return}if(t.event==="notification"){const i=t.payload;(i==null?void 0:i.category)==="model-fallback"&&Gk(i);return}}function Ml(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&&Qk(e,n.sessionDefaults)}async function Xk(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 Zk(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await _i(e.client)}catch{}}async function e0(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function t0(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 n0(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 Pl="taskmaster_public_id";function _u(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${Pl}=`));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=`${Pl}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function i0(e){var n,i,s;if(!e.client||!e.connected)return;const t=_u((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=zn(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="",bs="",cn="phone",On="";function Mu(e){return e.replace(/[\s\-()]/g,"")}function tt(){pe=!1,ie=null,Zt="",en="",tn="",bs="",cn="phone",On=""}async function s0(e){if(!e.client||!e.connected)return;const t=_u(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 Il(e){if(!e.client||pe)return;const t=Mu(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?(bs=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 Rl(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?(bs=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 Ll(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():Mu(Zt),i=await e.client.request("public.otp.verify",{identifier:n,code:t.trim(),accountId:e.accountId});i!=null&&i.ok&&i.sessionKey?(tt(),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 He(e){return w}function xi(e){return c`
4644
4718
  <div class="public-auth__form">
4645
4719
  <label class="field public-auth__field">
4646
4720
  <span>Your name (optional)</span>
@@ -4734,7 +4808,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4734
4808
  ${n?"Use a different email":"Use a different number"}
4735
4809
  </button>
4736
4810
  </div>
4737
- `}function n0(e){const{authMode:t,authStep:n}=e,i=!e.otpChannels||e.otpChannels.length>0;if(t==="anonymous")return c`
4811
+ `}function o0(e){const{authMode:t,authStep:n}=e,i=!e.otpChannels||e.otpChannels.length>0;if(t==="anonymous")return c`
4738
4812
  <div class="setup-container">
4739
4813
  <div class="setup-card">
4740
4814
  <div class="setup-spinner"></div>
@@ -4744,7 +4818,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4744
4818
  `;if(t==="verified"){const h=e.verifyMethods??["whatsapp","sms"],u=h.includes("whatsapp")||h.includes("sms")||h.includes("phone"),p=h.includes("email");return!i&&!p?c`
4745
4819
  <div class="setup-container">
4746
4820
  <div class="public-auth">
4747
- ${Ve()}
4821
+ ${He()}
4748
4822
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4749
4823
  <p class="public-auth__subtitle">Verification is not available right now.</p>
4750
4824
  </div>
@@ -4752,7 +4826,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4752
4826
  `:n==="otp"?c`
4753
4827
  <div class="setup-container">
4754
4828
  <div class="public-auth">
4755
- ${Ve()}
4829
+ ${He()}
4756
4830
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4757
4831
  ${Dl(e)}
4758
4832
  </div>
@@ -4760,13 +4834,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4760
4834
  `:n==="email"?c`
4761
4835
  <div class="setup-container">
4762
4836
  <div class="public-auth">
4763
- ${Ve()}
4837
+ ${He()}
4764
4838
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4765
4839
  <p class="public-auth__subtitle">Verify your email address to get started.</p>
4766
4840
  ${vo(e)}
4767
4841
  ${u?c`
4768
4842
  <button class="btn public-auth__btn public-auth__btn--link"
4769
- @click=${()=>{it(),e.onAuthStepChange("phone")}}>
4843
+ @click=${()=>{tt(),e.onAuthStepChange("phone")}}>
4770
4844
  Use phone number instead
4771
4845
  </button>
4772
4846
  `:w}
@@ -4775,13 +4849,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4775
4849
  `:n==="phone"?c`
4776
4850
  <div class="setup-container">
4777
4851
  <div class="public-auth">
4778
- ${Ve()}
4852
+ ${He()}
4779
4853
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4780
4854
  <p class="public-auth__subtitle">Verify your phone number to get started.</p>
4781
4855
  ${xi(e)}
4782
4856
  ${p?c`
4783
4857
  <button class="btn public-auth__btn public-auth__btn--link"
4784
- @click=${()=>{it(),e.onAuthStepChange("email")}}>
4858
+ @click=${()=>{tt(),e.onAuthStepChange("email")}}>
4785
4859
  Use email instead
4786
4860
  </button>
4787
4861
  `:w}
@@ -4790,12 +4864,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4790
4864
  `:u&&p?c`
4791
4865
  <div class="setup-container">
4792
4866
  <div class="public-auth">
4793
- ${Ve()}
4867
+ ${He()}
4794
4868
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4795
4869
  <p class="public-auth__subtitle">Authenticate to get started.</p>
4796
4870
  ${xi(e)}
4797
4871
  <button class="btn public-auth__btn public-auth__btn--link"
4798
- @click=${()=>{it(),e.onAuthStepChange("email")}}>
4872
+ @click=${()=>{tt(),e.onAuthStepChange("email")}}>
4799
4873
  Use email instead
4800
4874
  </button>
4801
4875
  </div>
@@ -4803,7 +4877,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4803
4877
  `:p?c`
4804
4878
  <div class="setup-container">
4805
4879
  <div class="public-auth">
4806
- ${Ve()}
4880
+ ${He()}
4807
4881
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4808
4882
  <p class="public-auth__subtitle">Verify your email address to get started.</p>
4809
4883
  ${vo(e)}
@@ -4812,7 +4886,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4812
4886
  `:c`
4813
4887
  <div class="setup-container">
4814
4888
  <div class="public-auth">
4815
- ${Ve()}
4889
+ ${He()}
4816
4890
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4817
4891
  <p class="public-auth__subtitle">Verify your phone number to get started.</p>
4818
4892
  ${xi(e)}
@@ -4821,13 +4895,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4821
4895
  `}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 c`
4822
4896
  <div class="setup-container">
4823
4897
  <div class="public-auth">
4824
- ${Ve()}
4898
+ ${He()}
4825
4899
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4826
4900
  <p class="public-auth__subtitle">${p}</p>
4827
4901
  ${n==="otp"?Dl(e):n==="email"?vo(e):xi(e)}
4828
4902
  ${n!=="otp"?c`
4829
4903
  <button class="btn public-auth__btn public-auth__btn--link"
4830
- @click=${()=>{it(),e.onAuthStepChange("idle")}}>
4904
+ @click=${()=>{tt(),e.onAuthStepChange("idle")}}>
4831
4905
  Back
4832
4906
  </button>
4833
4907
  `:w}
@@ -4836,20 +4910,20 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4836
4910
  `}return c`
4837
4911
  <div class="setup-container">
4838
4912
  <div class="public-auth">
4839
- ${Ve()}
4913
+ ${He()}
4840
4914
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4841
4915
  <p class="public-auth__subtitle">How would you like to get started?</p>
4842
4916
  <div class="public-auth__choices">
4843
4917
  <button
4844
4918
  class="btn primary public-auth__btn"
4845
- @click=${()=>{t0(e)}}
4919
+ @click=${()=>{s0(e)}}
4846
4920
  >
4847
4921
  Chat now
4848
4922
  </button>
4849
4923
  ${o?c`
4850
4924
  <button
4851
4925
  class="btn public-auth__btn"
4852
- @click=${()=>{it(),On="whatsapp",e.onAuthStepChange("phone")}}
4926
+ @click=${()=>{tt(),On="whatsapp",e.onAuthStepChange("phone")}}
4853
4927
  >
4854
4928
  Authenticate with WhatsApp
4855
4929
  </button>
@@ -4857,7 +4931,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4857
4931
  ${a?c`
4858
4932
  <button
4859
4933
  class="btn public-auth__btn"
4860
- @click=${()=>{it(),On="sms",e.onAuthStepChange("phone")}}
4934
+ @click=${()=>{tt(),On="sms",e.onAuthStepChange("phone")}}
4861
4935
  >
4862
4936
  Authenticate with SMS
4863
4937
  </button>
@@ -4865,7 +4939,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4865
4939
  ${r?c`
4866
4940
  <button
4867
4941
  class="btn public-auth__btn"
4868
- @click=${()=>{it(),e.onAuthStepChange("email")}}
4942
+ @click=${()=>{tt(),e.onAuthStepChange("email")}}
4869
4943
  >
4870
4944
  Authenticate with email
4871
4945
  </button>
@@ -4878,7 +4952,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4878
4952
  `:w}
4879
4953
  </div>
4880
4954
  </div>
4881
- `}function Wa(){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 Mu=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];async function za(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 Mu){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=Wa();n.publicAgentEnabled=t.publicAgentEnabled,e.openingHoursForm=n}}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursLoading=!1}}}async function Pu(e){if(!(!e.client||!e.connected||e.openingHoursBusy)){e.openingHoursBusy=!0,e.openingHoursError=null;try{const t=e.openingHoursForm,n={};for(const a of Mu){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 za(e)}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursBusy=!1}}}const i0=Object.freeze(Object.defineProperty({__proto__:null,defaultOpeningHoursForm:Wa,loadOpeningHours:za,saveOpeningHours:Pu},Symbol.toStringTag,{value:"Module"}));function s0(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 l=a.peer;if(!l||typeof l!="object"||l.kind!=="dm")continue;const d=l.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 Iu(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 y=p.id??"";y&&(d.meta&&o.set(y,d.meta),h.accountId&&a.set(y,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"}),l=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},y=o.get(d.phone);return y?p.meta=y:d.paired&&(p.meta={paired:!0}),p});return[...r,...l]}async function ws(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=s0(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!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;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(l=>l.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const l=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),d=l.bindings??[],h=[...e.adminPhones,{phone:o}],u=Iu(d,h,s,i);cc(l,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const y=Ct(l);await e.client.request("config.set",{raw:y,baseHash:p}),await ws(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function Lu(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(l=>l.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 l=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),d=l.bindings??[],h=e.adminPhones.filter($=>$.phone!==t),u=Iu(d,h,s,i);cc(l,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const y=Ct(l);await e.client.request("config.set",{raw:y,baseHash:p}),await ws(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}const o0=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:Ru,loadAdmins:ws,removeAdmin:Lu},Symbol.toStringTag,{value:"Module"}));async function It(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 Du(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 It(e,i)}catch(a){e.contactsError=String(a)}finally{e.contactsSaving=!1}}async function Bu(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 It(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 It(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Nu(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 It(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const a0=Object.freeze(Object.defineProperty({__proto__:null,addContact:Du,deleteContact:Bu,deleteContactField:Nu,loadContacts:It,setContactField:Jo},Symbol.toStringTag,{value:"Module"}));let kt=null,Mi=null,Pi=null;const bo=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function Kt(){kt&&(clearInterval(kt),kt=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 r0(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 l0(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 c0(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 d0(e){return e.selectedWorkspace??void 0}function we(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const u0=/^data:/i,p0=/^https?:\/\//i;function Bl(e){var r,l;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=Yl(e.sessionKey),i=(n==null?void 0:n.agentId)??((l=e.agentsList)==null?void 0:l.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 u0.test(a)||p0.test(a)?a:o==null?void 0:o.avatarUrl}function h0(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 f0(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 g0(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 l,d;return((l=r.match)==null?void 0:l.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(l=>l.id===s))return r.name;if(s==="admin"||s==="public"){const r=e.workspaces.find(l=>l.isDefault);return(r==null?void 0:r.name)??null}const o=s.replace(/-(admin|public)$/,"");if(o!==s){const r=e.workspaces.find(l=>l.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 m0(){requestAnimationFrame(()=>{const e=document.querySelector(".wa-messages");e&&(e.scrollTop=e.scrollHeight)})}function y0(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);yw(n,t).then(()=>{e.requestUpdate(),m0()})},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);vw(i,t,n).then(()=>e.requestUpdate())},onRefresh:()=>{const t=Ii(e);bu(t).then(()=>e.requestUpdate())},requestUpdate:()=>e.requestUpdate()}}function v0(e){var t,n,i,s,o,a,r,l,d,h;if(e.embeddingDownloading&&!e.publicChat)return c`
4955
+ `}function Wa(){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 Pu=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];async function za(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 Pu){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=Wa();n.publicAgentEnabled=t.publicAgentEnabled,e.openingHoursForm=n}}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursLoading=!1}}}async function Iu(e){if(!(!e.client||!e.connected||e.openingHoursBusy)){e.openingHoursBusy=!0,e.openingHoursError=null;try{const t=e.openingHoursForm,n={};for(const a of Pu){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 za(e)}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursBusy=!1}}}const a0=Object.freeze(Object.defineProperty({__proto__:null,defaultOpeningHoursForm:Wa,loadOpeningHours:za,saveOpeningHours:Iu},Symbol.toStringTag,{value:"Module"}));function r0(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 l=a.peer;if(!l||typeof l!="object"||l.kind!=="dm")continue;const d=l.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 Ru(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 y=p.id??"";y&&(d.meta&&o.set(y,d.meta),h.accountId&&a.set(y,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"}),l=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},y=o.get(d.phone);return y?p.meta=y:d.paired&&(p.meta={paired:!0}),p});return[...r,...l]}async function ws(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=Je(s??{}),e.adminPhones=r0(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function Lu(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(l=>l.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const l=Je(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),d=l.bindings??[],h=[...e.adminPhones,{phone:o}],u=Ru(d,h,s,i);cc(l,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const y=at(l);await e.client.request("config.set",{raw:y,baseHash:p}),await ws(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function Du(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(l=>l.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 l=Je(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),d=l.bindings??[],h=e.adminPhones.filter(x=>x.phone!==t),u=Ru(d,h,s,i);cc(l,["bindings"],u);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const y=at(l);await e.client.request("config.set",{raw:y,baseHash:p}),await ws(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}const l0=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:Lu,loadAdmins:ws,removeAdmin:Du},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 Bu(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 Nu(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 Ou(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 c0=Object.freeze(Object.defineProperty({__proto__:null,addContact:Bu,deleteContact:Nu,deleteContactField:Ou,loadContacts:Pt,setContactField:Jo},Symbol.toStringTag,{value:"Module"}));let kt=null,Mi=null,Pi=null;const bo=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function Kt(){kt&&(clearInterval(kt),kt=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 d0(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 u0(e){const t=je(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=je(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function p0(e){var i;const t=je(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 h0(e){return e.selectedWorkspace??void 0}function je(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const f0=/^data:/i,g0=/^https?:\/\//i;function Bl(e){var r,l;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=Yl(e.sessionKey),i=(n==null?void 0:n.agentId)??((l=e.agentsList)==null?void 0:l.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 f0.test(a)||g0.test(a)?a:o==null?void 0:o.avatarUrl}function m0(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 y0(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 v0(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 l,d;return((l=r.match)==null?void 0:l.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(l=>l.id===s))return r.name;if(s==="admin"||s==="public"){const r=e.workspaces.find(l=>l.isDefault);return(r==null?void 0:r.name)??null}const o=s.replace(/-(admin|public)$/,"");if(o!==s){const r=e.workspaces.find(l=>l.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 b0(){requestAnimationFrame(()=>{const e=document.querySelector(".wa-messages");e&&(e.scrollTop=e.scrollHeight)})}function w0(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);ww(n,t).then(()=>{e.requestUpdate(),b0()})},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);kw(i,t,n).then(()=>e.requestUpdate())},onRefresh:()=>{const t=Ii(e);wu(t).then(()=>e.requestUpdate())},requestUpdate:()=>e.requestUpdate()}}function k0(e){var t,n,i,s,o,a,r,l,d,h;if(e.embeddingDownloading&&!e.publicChat)return c`
4882
4956
  <div class="setup-container">
4883
4957
  <div class="setup-card" style="text-align:center; max-width:420px;">
4884
4958
  <div class="setup-spinner"></div>
@@ -4899,7 +4973,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4899
4973
  <p>Connecting...</p>
4900
4974
  </div>
4901
4975
  </div>
4902
- `;if(!e.publicChatAuthenticated)return n0({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=zn(S,$),ae(async()=>{const{loadChatHistory:v}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:v}},void 0,import.meta.url).then(({loadChatHistory:v})=>{v(e)})},onAuthStepChange:$=>{e.publicChatAuthStep=$},requestUpdate:()=>{e.requestUpdate()}});const u=(t=e.publicChatConfig)==null?void 0:t.greeting,p=e.chatMessages,y=!e.chatLoading&&u?[{role:"assistant",content:[{type:"text",text:u}],timestamp:0},...Array.isArray(p)?p:[]]:p;return yk({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:y,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Bl(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)??"";kr(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 Al({show:!0,isFirstTime:!1,accounts:u.accounts,error:u.error,busy:u.busy,onSubmit:(p,y)=>{y!=null&&e.handlePinSubmit(p,y)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,y,$)=>e.handleChangePin(p,y,$)});if(!u.hasMasterPin&&!u.authenticated&&e.setup)return Al({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=h0(e.channelsSnapshot),p=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],y=f0(e.channelsSnapshot),$=g0(e),S=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},M=()=>{const v=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=bo[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,Kt(),kt=setInterval(()=>{const b=(Date.now()-v)/1e3,k=Math.min(95,95*(1-Math.exp(-b/30)));e.tailscaleConnectProgress=Math.round(k);let A=bo[0][1];for(const[E,T]of bo)b>=E&&(A=T);e.tailscaleConnectMessage=A},500)};return rm({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:v=>e.handleLicenseKeyChange(v),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:v=>{e.authRefreshTokenInput=v},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:v=>e.handleUninstallConfirmTextChange(v),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:v=>e.handleAuthSubmitCode(v),onAuthCodeChange:v=>e.handleAuthCodeChange(v),onWhatsAppRelink:async v=>{await e.handleWhatsAppStart(!0,v),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(v),await Z(e,!0),e.requestUpdate())},onWhatsAppUnlink:async v=>{await e.handleWhatsAppLogout(v)},onWhatsAppReset:async v=>{await e.handleWhatsAppLogout(v),await e.handleWhatsAppStart(!0,v),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(v),await Z(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await Z(e,!0),await e.handleGatewayHealthCheck()},onRefreshGatewayStatus:()=>e.handleGatewayHealthCheck(),onRefreshWhatsAppStatus:()=>Z(e,!0),onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),Z(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:v=>e.handleRemoveWhatsAppAccount(v),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:v=>{e.newWorkspacePin=v},onWorkspaceCreate:async(v,b)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(v,b),k.match(/^\d{4,6}$/)&&(await Ph(e,v,k),e.newWorkspacePin="")},onWorkspaceRemove:v=>e.handleWorkspaceRemove(v),onSetAddingWorkspace:v=>{e.addingWorkspace=v},onSetNewWorkspaceName:v=>{e.newWorkspaceName=v},onSetNewWorkspacePath:v=>{e.newWorkspacePath=v},onSetWorkspaceRemoveConfirm:v=>{e.workspaceRemoveConfirm=v},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(v,b)=>e.handleWorkspaceRename(v,b),whatsappDmPolicy:(()=>{const v=we(e),b=v==null?void 0:v.whatsappAccountId,k=b?p.find(A=>A.accountId===b):p[0];return(k==null?void 0:k.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var P;const v=we(e),b=v==null?void 0:v.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,K=(P=W==null?void 0:W.channels)==null?void 0:P.whatsapp,ke=((K==null?void 0:K.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 Z(e,!1)}catch(D){console.error("DM toggle failed:",D)}},whatsappGroupPolicy:(()=>{var D,W;const v=(D=e.configSnapshot)==null?void 0:D.config,b=(W=v==null?void 0:v.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,K;const v=(W=e.configSnapshot)==null?void 0:W.config,b=(K=v==null?void 0:v.channels)==null?void 0:K.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 v=we(e),b=v==null?void 0:v.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",K=W==="disabled"||W==="allowlist",H=K?"open":"disabled",ke=K?{"*":{}}:void 0,Ie={groupPolicy:H};ke&&(Ie.groups=ke);const Ke=D?{channels:{whatsapp:{accounts:{[b]:Ie}}}}:{channels:{whatsapp:Ie}};await e.client.request("config.patch",{raw:JSON.stringify(Ke),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 v=>{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,K={"*":{requireMention:v}},H=W?{channels:{whatsapp:{accounts:{[k]:{groups:K}}}}}:{channels:{whatsapp:{groups:K}}};await e.client.request("config.patch",{raw:JSON.stringify(H),baseHash:E.hash,note:`WhatsApp group mention → ${v?"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:y.configured,imessageRunning:y.running,imessageConnected:y.connected,imessageLastError:y.lastError,imessageSelfChatMode:y.selfChatMode,imessageCliPath:y.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:$,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const v=await e.client.request("config.get"),b=v.config,k=(b==null?void 0:b.bindings)??[],A=we(e),E=A==null?void 0:A.agents.find(K=>K.id.endsWith("-admin")||K.id==="admin"),T=(E==null?void 0:E.id)??"admin",P=k.filter(K=>{var H;return((H=K.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:v.hash,note:"Enable iMessage (self-chat) for "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Z(e,!0),We(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await Z(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const v=await e.client.request("config.get"),b=v.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:v.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Z(e,!0),We(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const v=await e.client.request("config.get"),b=v.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 K;return((K=W.match)==null?void 0:K.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:v.hash,note:"Reassign iMessage to "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Z(e,!0),We(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:v=>{var b,k,A,E;if(e.infoModalOpen=v,v==="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(v==="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 v=((k=e.tailscaleStatus)==null?void 0:k.publicUrl)??((A=e.tailscaleStatus)==null?void 0:A.tailnetUrl)??null,b=e.selectedWorkspace??null;return!v||!b?null:`${v}/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(v,b)=>{e.apiKeySavingProvider=v,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Tl(e.client,v,b);const k=`${v} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}v==="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 v=>{e.apiKeySavingProvider=v,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Nk(e.client,v);const b=`${v} 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(v,b)=>{e.apiKeySavingProvider=v,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Ok(e.client,v,b);const k=`${v} ${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:v=>{e.authApiKeyInput=v},onAuthApiKeySubmit:async()=>{const v=e.authApiKeyInput.trim();if(v){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await Tl(e.client,"anthropic",v),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 v=e.selectedWorkspace??((b=e.workspaces[0])==null?void 0:b.name);return v?e.accessState.accounts.some(k=>k.id===v):!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:(v,b)=>{var A;const k=e.selectedWorkspace??((A=e.workspaces[0])==null?void 0:A.name);k&&e.handleAccountPinSave(k,v,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 v=(k=e.configSnapshot)==null?void 0:k.config,b=v==null?void 0:v.publicChat;return(b==null?void 0:b.enabled)===!0})(),publicChatAuthMode:(()=>{var T,P;const v=(T=e.configSnapshot)==null?void 0:T.config,b=v==null?void 0:v.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 v=(E=e.configSnapshot)==null?void 0:E.config,b=v==null?void 0:v.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 v=e.selectedWorkspace??"";if(v){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[v]){const P={publicChat:{greetings:{[v]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(P),baseHash:k.hash,note:`Public chat greeting → disabled (${v})`,skipRestart:!0})}else{const P=await e.client.request("public.greeting.generate",{accountId:v});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:{[v]:P.greeting}}}),baseHash:D.hash,note:`Public chat greeting → enabled (${v})`,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 v=>{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]:v}}}),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 v=e.selectedWorkspace??"";if(v){e.publicChatGreetingBusy=!0;try{const b=await e.client.request("public.greeting.generate",{accountId:v});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:{[v]:b.greeting}}}),baseHash:k.hash,note:`Public chat greeting regenerated (${v})`,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 v;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get"),k=b.config,A=((v=k==null?void 0:k.publicChat)==null?void 0:v.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 v=>{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:v}}}}),baseHash:k.hash,note:`Public chat auth → ${v}`,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 v=(k=e.configSnapshot)==null?void 0:k.config,b=(A=v==null?void 0:v.publicChat)==null?void 0:A.email;return(b==null?void 0:b.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var T,P;const v=(T=e.configSnapshot)==null?void 0:T.config,b=v==null?void 0:v.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(v,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:v||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 v=e.selectedWorkspace;return v?((k=Fe()[v])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const v=e.selectedWorkspace;return v?((k=Fe()[v])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const v=e.selectedWorkspace;return v?!!((k=Fe()[v])!=null&&k.logoUrl):!1})(),agentSettingsOpen:e.agentSettingsOpen,agentSettingsAgents:(()=>{var A,E;const v=we(e);if(!v)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 v.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,K=T.id.endsWith("-admin")||T.id==="admin";return{id:T.id,label:K?"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 v=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=v==null?void 0:v.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 v=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=v==null?void 0:v.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(v,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===v);if(b)P>=0?T[P]={...T[P],model:b}:T.push({id:v,model:b});else if(P>=0){const{model:W,...K}=T[P];Object.keys(K).length<=1?T.splice(P,1):T[P]=K}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 ${v} model → ${b||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent model change failed:",k)}},onAgentThinkingChange:async(v,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(K=>K.id===v),D=b==="off"?void 0:b;if(D)P>=0?T[P]={...T[P],thinkingLevel:D}:T.push({id:v,thinkingLevel:D});else if(P>=0){const{thinkingLevel:K,...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 ${v} thinking → ${D||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent thinking change failed:",k)}},onMemoryProviderChange:async v=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{provider:v}}}}),baseHash:b.hash,note:`Memory search provider → ${v}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Memory provider change failed:",b)}},onMemoryFallbackChange:async v=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{fallback:v}}}}),baseHash:b.hash,note:`Memory search fallback → ${v}`,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 v=>{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:v}}}}),baseHash:A.hash,note:`Brand accent → ${v}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const D=Fe();D[b]||(D[b]={}),D[b].accentColor=v,Tn(b)}catch(A){console.error("Brand accent change failed:",A)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async v=>{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:v}}}}),baseHash:A.hash,note:`Brand background → ${v}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const D=Fe();D[b]||(D[b]={}),D[b].backgroundColor=v,Tn(b)}catch(A){console.error("Brand background change failed:",A)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async v=>{const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const k=await v.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:v.type});const P=Fe();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 v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:v});const b=Fe();b[v]&&delete b[v].logoUrl}catch(b){console.error("Brand logo remove failed:",b)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var b;const v=e.selectedWorkspace;if(!(!v||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[v])??{},{brand:T,...P}=E;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[v]:{...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:v})}catch{}const D=Fe();delete D[v],Tn(v)}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 v=await e.client.request("tailscale.enable");v.authUrl?(kt&&(clearInterval(kt),kt=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=v.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)):v.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(v){console.error("Tailscale enable failed:",v),Kt(),e.tailscaleError=v.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{var v;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;(v=k.payload)!=null&&v.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(v){console.error("Tailscale serve disable failed:",v)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var v;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;(v=k.payload)!=null&&v.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(v){console.error("Tailscale funnel disable failed:",v)}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 v;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&&((v=b.networks)!=null&&v.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 v=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const k=await e.client.request("wifi.connect",{ssid:v,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 v=await e.client.request("wifi.status");e.wifiStatus=v}catch(v){console.error("WiFi disconnect failed:",v),e.wifiError=v.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 v=await e.client.request("wifi.status");e.wifiStatus=v}catch(v){console.error("WiFi forget failed:",v),e.wifiError=v.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:v=>{e.wifiSelectedSsid=v,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:v=>{e.wifiPassword=v},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:v=>{e.networkPortInput=v,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:v=>{e.networkHostnameInput=v,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const v=e.networkPortInput.trim(),b=Number.parseInt(v,10),k=e.networkHostnameInput.trim();if(!v||!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,K=A?b:e.networkPort,H=`${D}//${W}:${K}/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:r0(e)})}if(e.filesPage){const u=c0(e);return wg({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),ps(e,u)},onReindex:()=>Lf(e,u),onSelectFile:p=>{e.filesPendingDeletePath=null,Cf(e,p,u)},onToggleSelectFile:p=>Ef(e,p,u),onToggleDir:p=>Df(e,p),onUpload:(p,y)=>Mf(e,p,y,u),onNewFolder:(p,y)=>Pf(e,p,y,u),onDownload:p=>ld(e,p,u),onBulkDownload:()=>Tf(e,u),onDelete:p=>{e.filesPendingDeletePath=null,If(e,p,u)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,y)=>_f(e,p,y,u),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const y=e.filesSearchAgentId??u;Bf(e,p,y)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{Nf(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return fg({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:()=>_k(e),onStop:()=>Mk(e),onToggleInput:()=>Ik(e),onToggleFullscreen:()=>Rk(e),onCompleteHandoff:()=>Pk(e),onCanvasMouseDown:u=>{const y=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-y.left,u.clientY-y.top);go(e,"mousePressed",S.x,S.y,u.button===2?"right":u.button===1?"middle":"left")},onCanvasMouseUp:u=>{const y=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-y.left,u.clientY-y.top);go(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);go(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),mo(e,"keyDown",u.key,{code:u.code,modifiers:p||void 0}),u.key.length===1&&mo(e,"char",u.key,{text:u.key})},onCanvasKeyUp:u=>{mo(e,"keyUp",u.key,{code:u.code})}});if(e.adminsPage){const u=l0(e),p=Ka(e);return cm({connected:e.connected,wsProps:Sn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>ws(e,u),onAdd:y=>{Ru(e,y,u,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:y=>Lu(e,y,u,p),onNewPhoneChange:y=>e.handleAdminsNewPhoneChange(y)})}if(e.contactsPage){const u=d0(e);return gm({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:()=>It(e,u),onAdd:(p,y)=>Du(e,p,y,u),onDelete:p=>Bu(e,p,u),onSetField:(p,y,$)=>Jo(e,p,y,$,u),onDeleteField:(p,y)=>Nu(e,p,y,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:()=>It(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,y=e.contactsAddFieldKey.trim();!p||!y||(Jo(e,p,y,e.contactsAddFieldValue,u),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const u=e.connected?null:"Disconnected from gateway.",p=Bl(e),y=e.chatAvatarUrl??p??null,$=(()=>{var v;const S=(v=e.configSnapshot)==null?void 0:v.config,M=S==null?void 0:S.publicChat;return(M==null?void 0:M.enabled)===!0})();return mw({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);bu(M).then(()=>e.requestUpdate())}},whatsappProps:y0(e),sessionKey:e.sessionKey,onSessionKeyChange:S=>{const M=e.selectedWorkspace??"";$o(),Wn(M,e.sessionKey,e.chatMessage),e.sessionKey=S,e.chatMessage=zn(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),Po(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:y,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}),Po(e)])},onToggleFocusMode:()=>{},onChatScroll:S=>e.handleChatScroll(S),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:S=>{e.chatMessage=S,kr(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?mk({connected:e.connected,wsProps:Sn(e),activeTab:e.advancedTab,onTabChange:u=>{e.advancedTab=u,u==="cron"&&e.loadCron(),u==="skills"&&Pe(e,{clearMessages:!0}),u==="opening-hours"&&za(e),u==="logs"&&(e.logsSubTab==="session"?Pn(e,{reset:!0}):bt(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):((l=e.channelsSnapshot)==null?void 0:l.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(y=>y.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,Co(e,u.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:u=>{e.cronForm=Ah(u),e.cronEditJobId=u.id,e.cronDetailJobId=null},onEditSave:()=>{const u=e.cronEditJobId;u&&Ch(e,u).then(()=>{e.cronEditJobId=null})},onFormChange:u=>e.cronForm={...e.cronForm,...u},onRefresh:()=>e.loadCron(),onAdd:()=>{wh(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(u,p)=>kh(e,u,p),onRun:u=>xh(e,u),onRemove:u=>{e.cronPendingDeleteId=null,Sh(e,u)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:u=>{e.cronPendingDeleteId=u||null},onLoadRuns:u=>Co(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:()=>Pe(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,y)=>Uc(e,u,p,y),onViewDetail:u=>Wc(e,u),onDetailClose:()=>zc(e),onDetailTab:u=>Kc(e,u),onAddOpen:()=>Hc(e),onAddClose:()=>qc(e),onImportDraft:u=>jc(e,u),onInstallDraft:u=>Gc(e,u),onDeleteDraft:u=>Vc(e,u),onAddSave:()=>fa(e),onAddFormUpdate:(u,p)=>{e.skillAddForm={...e.skillAddForm,[u]:p}},onAlwaysActiveToggle:(u,p)=>Zc(e,u,p),onDelete:u=>td(e,u),onEditSkill:u=>Qc(e,u),onEditDetail:u=>Jc(e,u),onRefUpdate:(u,p)=>Yc(e,u,p),onEditTab:u=>Xc(e,u),agentFilter:e.skillsAgentFilter,onAgentFilterChange:u=>e.skillsAgentFilter=u,onAgentsChange:(u,p)=>ed(e,u,p)},logsProps:{logsSubTab:e.logsSubTab,isAdmin:e.accessState.master||!e.accessState.hasPins,onSubTabChange:u=>{e.logsSubTab=u,u==="session"?Pn(e,{reset:!0}):bt(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 y=e;y.sessionLogsTypeFilters={...y.sessionLogsTypeFilters,[u]:p}},onAgentToggle:(u,p)=>{const y=e;y.sessionLogsAgentFilters={...y.sessionLogsAgentFilters,[u]:p}},onToggleAutoFollow:u=>e.sessionLogsAutoFollow=u,onToggleChips:()=>{const u=e;u.sessionLogsChipsExpanded=!u.sessionLogsChipsExpanded},onToggleExpand:u=>{const p=e,y=new Set(p.sessionLogsExpandedIds);y.has(u)?y.delete(u):y.add(u),p.sessionLogsExpandedIds=y,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,selectedDate:e.logsDate,availableDates:e.logsAvailableDates,onDateChange:u=>{e.logsDate=u,bt(e,{reset:!0})},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:()=>bt(e,{reset:!0}),onExport:(u,p)=>e.exportSessionLogs(u,p),onDownloadFull:u=>{const p=new URLSearchParams;u&&p.set("date",u);const y=cs();y&&p.set("token",y);const $=p.toString();window.open(`/logs/download${$?`?${$}`:""}`,"_blank")},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,y)=>{const $=e,S={...$.openingHoursForm.days};S[u]={...S[u],[p]:y},$.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(y=>y!==u)}},onSave:()=>{Pu(e)}}}):(window.location.replace("/chat"),c``)}function b0(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 Nl(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function w0(e,t,n){return c`
4976
+ `;if(!e.publicChatAuthenticated)return o0({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:x=>{var _;e.publicChatSessionKey=x,e.sessionKey=x,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const S=((_=e.publicChatConfig)==null?void 0:_.accountId)??"";e.chatMessage=zn(S,x),ae(async()=>{const{loadChatHistory:v}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:v}},void 0,import.meta.url).then(({loadChatHistory:v})=>{v(e)})},onAuthStepChange:x=>{e.publicChatAuthStep=x},requestUpdate:()=>{e.requestUpdate()}});const u=(t=e.publicChatConfig)==null?void 0:t.greeting,p=e.chatMessages,y=!e.chatLoading&&u?[{role:"assistant",content:[{type:"text",text:u}],timestamp:0},...Array.isArray(p)?p:[]]:p;return wk({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:y,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Bl(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:x=>{e.chatMessage=x,e.chatSuggestions=[],e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),ae(async()=>{const{loadChatHistory:x}=await Promise.resolve().then(()=>Oi);return{loadChatHistory:x}},void 0,import.meta.url).then(({loadChatHistory:x})=>{x(e)})),onDraftChange:x=>{var _;e.chatMessage=x;const S=((_=e.publicChatConfig)==null?void 0:_.accountId)??"";kr(S,e.sessionKey,x)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:x=>e.chatAttachments=x,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:x=>e.removeQueuedMessage(x),onChatScroll:x=>e.handleChatScroll(x),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 Al({show:!0,isFirstTime:!1,accounts:u.accounts,error:u.error,busy:u.busy,onSubmit:(p,y)=>{y!=null&&e.handlePinSubmit(p,y)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,y,x)=>e.handleChangePin(p,y,x)});if(!u.hasMasterPin&&!u.authenticated&&e.setup)return Al({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=m0(e.channelsSnapshot),p=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],y=y0(e.channelsSnapshot),x=v0(e),S=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},_=()=>{const v=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=bo[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,Kt(),kt=setInterval(()=>{const b=(Date.now()-v)/1e3,k=Math.min(95,95*(1-Math.exp(-b/30)));e.tailscaleConnectProgress=Math.round(k);let A=bo[0][1];for(const[E,M]of bo)b>=E&&(A=M);e.tailscaleConnectMessage=A},500)};return dm({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:v=>e.handleLicenseKeyChange(v),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:v=>{e.authRefreshTokenInput=v},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,addingWhatsAppAccount:e.addingWhatsAppAccount,newWhatsAppAccountName:e.newWhatsAppAccountName,newWhatsAppAccountProvider:e.newWhatsAppAccountProvider,newCloudPhoneNumberId:e.newCloudPhoneNumberId,newCloudBusinessAccountId:e.newCloudBusinessAccountId,newCloudAccessToken:e.newCloudAccessToken,newCloudWebhookVerifyToken:e.newCloudWebhookVerifyToken,whatsappAccountError:e.whatsappAccountError,onSetAddingWhatsAppAccount:v=>{e.addingWhatsAppAccount=v,e.whatsappAccountError=null},onSetNewWhatsAppAccountName:v=>{e.newWhatsAppAccountName=v},onSetNewWhatsAppAccountProvider:v=>{e.newWhatsAppAccountProvider=v,e.whatsappAccountError=null},onSetNewCloudPhoneNumberId:v=>{e.newCloudPhoneNumberId=v},onSetNewCloudBusinessAccountId:v=>{e.newCloudBusinessAccountId=v},onSetNewCloudAccessToken:v=>{e.newCloudAccessToken=v},onSetNewCloudWebhookVerifyToken:v=>{e.newCloudWebhookVerifyToken=v},onAddWhatsAppBaileysAccount:async v=>{await e.handleAddWhatsAppAccount(v)},onAddCloudApiAccount:async(v,b)=>{await e.handleAddCloudApiAccount(v,b)},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:v=>e.handleUninstallConfirmTextChange(v),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:v=>e.handleAuthSubmitCode(v),onAuthCodeChange:v=>e.handleAuthCodeChange(v),onWhatsAppRelink:async v=>{await e.handleWhatsAppStart(!0,v),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(v),await Y(e,!0),e.requestUpdate())},onWhatsAppUnlink:async v=>{await e.handleWhatsAppLogout(v)},onWhatsAppReset:async v=>{await e.handleWhatsAppLogout(v),await e.handleWhatsAppStart(!0,v),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(v),await Y(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await Y(e,!0),await e.handleGatewayHealthCheck()},onRefreshGatewayStatus:()=>e.handleGatewayHealthCheck(),onRefreshWhatsAppStatus:()=>Y(e,!0),onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),Y(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:v=>e.handleRemoveWhatsAppAccount(v),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:v=>{e.newWorkspacePin=v},onWorkspaceCreate:async(v,b)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(v,b),k.match(/^\d{4,6}$/)&&(await Ih(e,v,k),e.newWorkspacePin="")},onWorkspaceRemove:v=>e.handleWorkspaceRemove(v),onSetAddingWorkspace:v=>{e.addingWorkspace=v},onSetNewWorkspaceName:v=>{e.newWorkspaceName=v},onSetNewWorkspacePath:v=>{e.newWorkspacePath=v},onSetWorkspaceRemoveConfirm:v=>{e.workspaceRemoveConfirm=v},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(v,b)=>e.handleWorkspaceRename(v,b),whatsappAgentEnabled:(()=>{const v=je(e),b=v==null?void 0:v.whatsappAccountId,k=b?p.find(A=>A.accountId===b):p[0];return(k==null?void 0:k.dmPolicy)!=="disabled"})(),onWhatsAppAgentEnabledToggle:async()=>{var M;const v=je(e),b=v==null?void 0:v.whatsappAccountId,k=b?p.find(P=>P.accountId===b):p[0];if(!k)return;const A=k.dmPolicy!=="disabled",E=A?{dmPolicy:"disabled",groupPolicy:"disabled"}:{dmPolicy:"open",allowFrom:["*"],groupPolicy:"open"};try{const P=await e.client.request("config.get"),F=P.config,V=(M=F==null?void 0:F.channels)==null?void 0:M.whatsapp,q=((V==null?void 0:V.accounts)??{})[k.accountId]?{channels:{whatsapp:{accounts:{[k.accountId]:E}}}}:{channels:{whatsapp:E}};await e.client.request("config.patch",{raw:JSON.stringify(q),baseHash:P.hash,note:`WhatsApp agent → ${A?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),await Y(e,!1)}catch(P){console.error("Agent enabled toggle failed:",P)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:y.configured,imessageRunning:y.running,imessageConnected:y.connected,imessageLastError:y.lastError,imessageSelfChatMode:y.selfChatMode,imessageCliPath:y.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:x,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const v=await e.client.request("config.get"),b=v.config,k=(b==null?void 0:b.bindings)??[],A=je(e),E=A==null?void 0:A.agents.find(X=>X.id.endsWith("-admin")||X.id==="admin"),M=(E==null?void 0:E.id)??"admin",P=k.filter(X=>{var q;return((q=X.match)==null?void 0:q.channel)!=="imessage"}),F=[{agentId:M,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],V=[...P,...F];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:V}),baseHash:v.hash,note:"Enable iMessage (self-chat) for "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Y(e,!0),Oe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await Y(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const v=await e.client.request("config.get"),b=v.config,A=((b==null?void 0:b.bindings)??[]).filter(E=>{var M;return((M=E.match)==null?void 0:M.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:A}),baseHash:v.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Y(e,!0),Oe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const v=await e.client.request("config.get"),b=v.config,k=(b==null?void 0:b.bindings)??[],A=je(e),E=A==null?void 0:A.agents.find(V=>V.id.endsWith("-admin")||V.id==="admin"),M=(E==null?void 0:E.id)??"admin",P=k.filter(V=>{var X;return((X=V.match)==null?void 0:X.channel)!=="imessage"}),F=[{agentId:M,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,...F]}),baseHash:v.hash,note:"Reassign iMessage to "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Y(e,!0),Oe(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:v=>{var b,k,A,E;if(e.infoModalOpen=v,v==="remote-access"){const M=((b=e.tailscaleStatus)==null?void 0:b.tailnetUrl)??((k=e.tailscaleStatus)!=null&&k.hostname?`https://${e.tailscaleStatus.hostname}`:null);M&&!e.remoteAccessQrDataUrl&&e.client.request("qr.generate",{url:M}).then(P=>{e.remoteAccessQrDataUrl=(P==null?void 0:P.dataUrl)??null}).catch(()=>{})}else if(v==="public-chat"){const M=((A=e.tailscaleStatus)==null?void 0:A.publicUrl)??((E=e.tailscaleStatus)==null?void 0:E.tailnetUrl)??null,P=e.selectedWorkspace??null;if(M&&P){const F=`${M}/public/chat/${encodeURIComponent(P)}`;e.publicChatQrDataUrl||e.client.request("qr.generate",{url:F}).then(V=>{e.publicChatQrDataUrl=(V==null?void 0:V.dataUrl)??null}).catch(()=>{})}}},onInfoModalClose:()=>{e.infoModalOpen=null},remoteAccessQrDataUrl:e.remoteAccessQrDataUrl??null,publicChatQrDataUrl:e.publicChatQrDataUrl??null,publicChatFullUrl:(()=>{var k,A;const v=((k=e.tailscaleStatus)==null?void 0:k.publicUrl)??((A=e.tailscaleStatus)==null?void 0:A.tailnetUrl)??null,b=e.selectedWorkspace??null;return!v||!b?null:`${v}/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(v,b)=>{e.apiKeySavingProvider=v,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Tl(e.client,v,b);const k=`${v} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}v==="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 v=>{e.apiKeySavingProvider=v,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Uk(e.client,v);const b=`${v} 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(v,b)=>{e.apiKeySavingProvider=v,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Wk(e.client,v,b);const k=`${v} ${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:v=>{e.authApiKeyInput=v},onAuthApiKeySubmit:async()=>{const v=e.authApiKeyInput.trim();if(v){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await Tl(e.client,"anthropic",v),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 v=e.selectedWorkspace??((b=e.workspaces[0])==null?void 0:b.name);return v?e.accessState.accounts.some(k=>k.id===v):!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:(v,b)=>{var A;const k=e.selectedWorkspace??((A=e.workspaces[0])==null?void 0:A.name);k&&e.handleAccountPinSave(k,v,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 v=(k=e.configSnapshot)==null?void 0:k.config,b=v==null?void 0:v.publicChat;return(b==null?void 0:b.enabled)===!0})(),publicChatAuthMode:(()=>{var M,P;const v=(M=e.configSnapshot)==null?void 0:M.config,b=v==null?void 0:v.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 v=(E=e.configSnapshot)==null?void 0:E.config,b=v==null?void 0:v.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 v=e.selectedWorkspace??"";if(v){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[v]){const P={publicChat:{greetings:{[v]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(P),baseHash:k.hash,note:`Public chat greeting → disabled (${v})`,skipRestart:!0})}else{const P=await e.client.request("public.greeting.generate",{accountId:v});if(P!=null&&P.ok&&P.greeting){const F=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[v]:P.greeting}}}),baseHash:F.hash,note:`Public chat greeting → enabled (${v})`,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 v=>{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]:v}}}),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 v=e.selectedWorkspace??"";if(v){e.publicChatGreetingBusy=!0;try{const b=await e.client.request("public.greeting.generate",{accountId:v});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:{[v]:b.greeting}}}),baseHash:k.hash,note:`Public chat greeting regenerated (${v})`,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 v;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get"),k=b.config,A=((v=k==null?void 0:k.publicChat)==null?void 0:v.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 v=>{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:v}}}}),baseHash:k.hash,note:`Public chat auth → ${v}`,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 v=(k=e.configSnapshot)==null?void 0:k.config,b=(A=v==null?void 0:v.publicChat)==null?void 0:A.email;return(b==null?void 0:b.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var M,P;const v=(M=e.configSnapshot)==null?void 0:M.config,b=v==null?void 0:v.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(v,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:v||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 v=e.selectedWorkspace;return v?((k=Be()[v])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const v=e.selectedWorkspace;return v?((k=Be()[v])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const v=e.selectedWorkspace;return v?!!((k=Be()[v])!=null&&k.logoUrl):!1})(),agentSettingsOpen:e.agentSettingsOpen,agentSettingsAgents:(()=>{var A,E;const v=je(e);if(!v)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 v.agents.map(M=>{var q;const P=Array.isArray(k)?k.find(lt=>lt.id===M.id):void 0,F=P==null?void 0:P.model,V=typeof F=="string"?F:(F==null?void 0:F.primary)??null,X=M.id.endsWith("-admin")||M.id==="admin";return{id:M.id,label:X?"Admin":"Public",model:(V==null?void 0:V.trim())||null,thinkingLevel:((q=P==null?void 0:P.thinkingLevel)==null?void 0:q.trim())||null}})})(),agentSettingsModelCatalog:e.chatModelCatalog??[],memoryProvider:(()=>{var k,A,E;const v=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=v==null?void 0:v.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 v=(k=e.configSnapshot)==null?void 0:k.config,b=(E=(A=v==null?void 0:v.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(v,b)=>{try{const k=await e.client.request("config.get"),A=k.config,E=(A==null?void 0:A.agents)??{},M=Array.isArray(E.list)?[...E.list]:[],P=M.findIndex(V=>V.id===v);if(b)P>=0?M[P]={...M[P],model:b}:M.push({id:v,model:b});else if(P>=0){const{model:V,...X}=M[P];Object.keys(X).length<=1?M.splice(P,1):M[P]=X}const F=M.length>0?{agents:{list:M}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(F),baseHash:k.hash,note:`Agent ${v} model → ${b||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent model change failed:",k)}},onAgentThinkingChange:async(v,b)=>{try{const k=await e.client.request("config.get"),A=k.config,E=(A==null?void 0:A.agents)??{},M=Array.isArray(E.list)?[...E.list]:[],P=M.findIndex(X=>X.id===v),F=b==="off"?void 0:b;if(F)P>=0?M[P]={...M[P],thinkingLevel:F}:M.push({id:v,thinkingLevel:F});else if(P>=0){const{thinkingLevel:X,...q}=M[P];Object.keys(q).length<=1?M.splice(P,1):M[P]=q}const V=M.length>0?{agents:{list:M}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(V),baseHash:k.hash,note:`Agent ${v} thinking → ${F||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Agent thinking change failed:",k)}},onMemoryProviderChange:async v=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{provider:v}}}}),baseHash:b.hash,note:`Memory search provider → ${v}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Memory provider change failed:",b)}},onMemoryFallbackChange:async v=>{try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{fallback:v}}}}),baseHash:b.hash,note:`Memory search fallback → ${v}`,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 v=>{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,M=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=M.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...M,brand:{...P,accentColor:v}}}}),baseHash:A.hash,note:`Brand accent → ${v}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const F=Be();F[b]||(F[b]={}),F[b].accentColor=v,Tn(b)}catch(A){console.error("Brand accent change failed:",A)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async v=>{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,M=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=M.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...M,brand:{...P,backgroundColor:v}}}}),baseHash:A.hash,note:`Brand background → ${v}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const F=Be();F[b]||(F[b]={}),F[b].backgroundColor=v,Tn(b)}catch(A){console.error("Brand background change failed:",A)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async v=>{const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const k=await v.arrayBuffer(),A=new Uint8Array(k);let E="";for(let F=0;F<A.length;F++)E+=String.fromCharCode(A[F]);const M=btoa(E);await e.client.request("brand.uploadLogo",{workspace:b,data:M,mimeType:v.type});const P=Be();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 v=e.selectedWorkspace;if(!(!v||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:v});const b=Be();b[v]&&delete b[v].logoUrl}catch(b){console.error("Brand logo remove failed:",b)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var b;const v=e.selectedWorkspace;if(!(!v||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[v])??{},{brand:M,...P}=E;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[v]:{...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:v})}catch{}const F=Be();delete F[v],Tn(v)}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,_();try{const v=await e.client.request("tailscale.enable");v.authUrl?(kt&&(clearInterval(kt),kt=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=v.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)):v.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(v){console.error("Tailscale enable failed:",v),Kt(),e.tailscaleError=v.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{var v;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;(v=k.payload)!=null&&v.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(v){console.error("Tailscale serve disable failed:",v)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var v;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;(v=k.payload)!=null&&v.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(v){console.error("Tailscale funnel disable failed:",v)}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 v;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&&((v=b.networks)!=null&&v.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 v=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const k=await e.client.request("wifi.connect",{ssid:v,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 M=A.networks.find(P=>P.active)||A.networks.find(P=>P.ssid===E.ssid);M&&(E.signal=M.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 v=await e.client.request("wifi.status");e.wifiStatus=v}catch(v){console.error("WiFi disconnect failed:",v),e.wifiError=v.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 v=await e.client.request("wifi.status");e.wifiStatus=v}catch(v){console.error("WiFi forget failed:",v),e.wifiError=v.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:v=>{e.wifiSelectedSsid=v,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:v=>{e.wifiPassword=v},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:v=>{e.networkPortInput=v,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:v=>{e.networkHostnameInput=v,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const v=e.networkPortInput.trim(),b=Number.parseInt(v,10),k=e.networkHostnameInput.trim();if(!v||!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 M={};A&&(M.gateway={port:b}),E&&(M.discovery={bonjourHostname:k});const P=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify(M),baseHash:P.hash,note:[A?`Port → ${b}`:null,E?`Hostname → ${k}`:null].filter(Boolean).join(", "),restartDelayMs:2e3}),e.networkSuccess="Saved — redirecting...";const F=window.location.protocol,V=E?`${k}.local`:window.location.hostname,X=A?b:e.networkPort,q=`${F}//${V}:${X}/setup`;setTimeout(()=>{window.location.href=q},1500)}catch(M){console.error("Network save failed:",M),e.networkError=M.message||"Failed to save network settings",e.networkBusy=!1}},wsProps:d0(e)})}if(e.filesPage){const u=p0(e);return kg({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),ps(e,u)},onReindex:()=>Df(e,u),onSelectFile:p=>{e.filesPendingDeletePath=null,Ef(e,p,u)},onToggleSelectFile:p=>Tf(e,p,u),onToggleDir:p=>Bf(e,p),onUpload:(p,y)=>Pf(e,p,y,u),onNewFolder:(p,y)=>If(e,p,y,u),onDownload:p=>cd(e,p,u),onBulkDownload:()=>_f(e,u),onDelete:p=>{e.filesPendingDeletePath=null,Rf(e,p,u)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,y)=>Mf(e,p,y,u),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const y=e.filesSearchAgentId??u;Nf(e,p,y)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{Of(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return gg({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:()=>Ik(e),onStop:()=>Rk(e),onToggleInput:()=>Dk(e),onToggleFullscreen:()=>Bk(e),onCompleteHandoff:()=>Lk(e),onCanvasMouseDown:u=>{const y=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-y.left,u.clientY-y.top);go(e,"mousePressed",S.x,S.y,u.button===2?"right":u.button===1?"middle":"left")},onCanvasMouseUp:u=>{const y=u.target.getBoundingClientRect(),S=Bn().translateCoordinates(u.clientX-y.left,u.clientY-y.top);go(e,"mouseReleased",S.x,S.y)},onCanvasMouseMove:u=>{const p=Bn();if(p.shouldThrottleMouseMove())return;const x=u.target.getBoundingClientRect(),S=p.translateCoordinates(u.clientX-x.left,u.clientY-x.top);go(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),mo(e,"keyDown",u.key,{code:u.code,modifiers:p||void 0}),u.key.length===1&&mo(e,"char",u.key,{text:u.key})},onCanvasKeyUp:u=>{mo(e,"keyUp",u.key,{code:u.code})}});if(e.adminsPage){const u=u0(e),p=Ka(e);return pm({connected:e.connected,wsProps:Sn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>ws(e,u),onAdd:y=>{Lu(e,y,u,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:y=>Du(e,y,u,p),onNewPhoneChange:y=>e.handleAdminsNewPhoneChange(y)})}if(e.contactsPage){const u=h0(e);return vm({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,y)=>Bu(e,p,y,u),onDelete:p=>Nu(e,p,u),onSetField:(p,y,x)=>Jo(e,p,y,x,u),onDeleteField:(p,y)=>Ou(e,p,y,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,y=e.contactsAddFieldKey.trim();!p||!y||(Jo(e,p,y,e.contactsAddFieldValue,u),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const u=e.connected?null:"Disconnected from gateway.",p=Bl(e),y=e.chatAvatarUrl??p??null,x=(()=>{var v;const S=(v=e.configSnapshot)==null?void 0:v.config,_=S==null?void 0:S.publicChat;return(_==null?void 0:_.enabled)===!0})();return bw({connected:e.connected,wsProps:Sn(e),publicChatEnabled:x,publicChatAccountId:e.selectedWorkspace??void 0,chatPageTab:e.chatPageTab??"chat",onChatPageTabChange:S=>{if(e.chatPageTab=S,S==="whatsapp"&&!e.waLoading&&e.waConversations.length===0){const _=Ii(e);wu(_).then(()=>e.requestUpdate())}},whatsappProps:w0(e),sessionKey:e.sessionKey,onSessionKeyChange:S=>{const _=e.selectedWorkspace??"";$o(),Wn(_,e.sessionKey,e.chatMessage),e.sessionKey=S,e.chatMessage=zn(_,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),Po(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:y,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}),Po(e)])},onToggleFocusMode:()=>{},onChatScroll:S=>e.handleChatScroll(S),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:S=>{e.chatMessage=S,kr(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?bk({connected:e.connected,wsProps:Sn(e),activeTab:e.advancedTab,onTabChange:u=>{e.advancedTab=u,u==="cron"&&e.loadCron(),u==="skills"&&_e(e,{clearMessages:!0}),u==="opening-hours"&&za(e),u==="logs"&&(e.logsSubTab==="session"?Pn(e,{reset:!0}):bt(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):((l=e.channelsSnapshot)==null?void 0:l.channelOrder)??[],channelLabels:((d=e.channelsSnapshot)==null?void 0:d.channelLabels)??{},channelMeta:((h=e.channelsSnapshot)==null?void 0:h.channelMeta)??[],agentIds:(()=>{var p;const u=je(e);return((p=u==null?void 0:u.agents)==null?void 0:p.map(y=>y.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,Co(e,u.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:u=>{e.cronForm=Ch(u),e.cronEditJobId=u.id,e.cronDetailJobId=null},onEditSave:()=>{const u=e.cronEditJobId;u&&Eh(e,u).then(()=>{e.cronEditJobId=null})},onFormChange:u=>e.cronForm={...e.cronForm,...u},onRefresh:()=>e.loadCron(),onAdd:()=>{kh(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(u,p)=>xh(e,u,p),onRun:u=>$h(e,u),onRemove:u=>{e.cronPendingDeleteId=null,Ah(e,u)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:u=>{e.cronPendingDeleteId=u||null},onLoadRuns:u=>Co(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:()=>_e(e,{clearMessages:!0}),onToggle:(u,p)=>Fc(e,u,p),onEdit:(u,p)=>Oc(e,u,p),onSaveKey:u=>Uc(e,u),onInstall:(u,p,y)=>Wc(e,u,p,y),onViewDetail:u=>zc(e,u),onDetailClose:()=>Kc(e),onDetailTab:u=>Hc(e,u),onAddOpen:()=>qc(e),onAddClose:()=>jc(e),onImportDraft:u=>Vc(e,u),onInstallDraft:u=>Gc(e,u),onDeleteDraft:u=>Qc(e,u),onAddSave:()=>fa(e),onAddFormUpdate:(u,p)=>{e.skillAddForm={...e.skillAddForm,[u]:p}},onAlwaysActiveToggle:(u,p)=>ed(e,u,p),onDelete:u=>nd(e,u),onEditSkill:u=>Jc(e,u),onEditDetail:u=>Yc(e,u),onRefUpdate:(u,p)=>Xc(e,u,p),onEditTab:u=>Zc(e,u),agentFilter:e.skillsAgentFilter,onAgentFilterChange:u=>e.skillsAgentFilter=u,onAgentsChange:(u,p)=>td(e,u,p)},logsProps:{logsSubTab:e.logsSubTab,isAdmin:e.accessState.master||!e.accessState.hasPins,onSubTabChange:u=>{e.logsSubTab=u,u==="session"?Pn(e,{reset:!0}):bt(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 y=e;y.sessionLogsTypeFilters={...y.sessionLogsTypeFilters,[u]:p}},onAgentToggle:(u,p)=>{const y=e;y.sessionLogsAgentFilters={...y.sessionLogsAgentFilters,[u]:p}},onToggleAutoFollow:u=>e.sessionLogsAutoFollow=u,onToggleChips:()=>{const u=e;u.sessionLogsChipsExpanded=!u.sessionLogsChipsExpanded},onToggleExpand:u=>{const p=e,y=new Set(p.sessionLogsExpandedIds);y.has(u)?y.delete(u):y.add(u),p.sessionLogsExpandedIds=y,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,selectedDate:e.logsDate,availableDates:e.logsAvailableDates,onDateChange:u=>{e.logsDate=u,bt(e,{reset:!0})},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:()=>bt(e,{reset:!0}),onExport:(u,p)=>e.exportSessionLogs(u,p),onDownloadFull:u=>{const p=new URLSearchParams;u&&p.set("date",u);const y=cs();y&&p.set("token",y);const x=p.toString();window.open(`/logs/download${x?`?${x}`:""}`,"_blank")},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,y)=>{const x=e,S={...x.openingHoursForm.days};S[u]={...S[u],[p]:y},x.openingHoursForm={...x.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(y=>y!==u)}},onSave:()=>{Iu(e)}}}):(window.location.replace("/chat"),c``)}function x0(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 Nl(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function $0(e,t,n){return c`
4903
4977
  <div class="audit-modal-overlay" @click=${s=>{s.target.classList.contains("audit-modal-overlay")&&n()}}>
4904
4978
  <div class="audit-modal-card">
4905
4979
  <div class="audit-modal-header">
@@ -4919,7 +4993,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4919
4993
  <a href="/files" class="audit-modal-path-link">${s.path}</a>
4920
4994
  </div>
4921
4995
  <div class="audit-modal-entry-meta">
4922
- ${b0(s.timestamp)}
4996
+ ${x0(s.timestamp)}
4923
4997
  <span class="audit-modal-agent">${s.agentId}</span>
4924
4998
  </div>
4925
4999
  </div>
@@ -4931,7 +5005,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4931
5005
  `}
4932
5006
  </div>
4933
5007
  </div>
4934
- `}const k0={trace:!1,debug:!1,info:!0,warn:!0,error:!0,fatal:!0},x0={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 $0(e){e.basePath=Gf();const t=Xe();Vl(t.accentColor),Ql(t.backgroundColor);const n=document.querySelector('link[rel="icon"]');if(n&&(n.href=t.iconUrl),window.scrollTo(0,0),Uf(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}`,Oe(e);return}if(e.setup){document.title=`${t.name} Setup`,Oe(e);return}if(e.filesPage){document.title=`${t.name} Files`,zf(e),Oe(e);return}if(e.browserPage){document.title=`${t.name} Browser`,Oe(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,Oe(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,Oe(e);return}if(e.chatPage){document.title=`${t.name} Chat`,Oe(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,Oe(e),zi(e),Wi(e);return}Yf(e,!0),Vf(e),Qf(e),window.addEventListener("popstate",e.popStateHandler),Hf(e),Oe(e),Of(e),e.tab==="logs"&&(e.logsSubTab==="session"?zi(e):Wi(e)),e.tab==="debug"&&va(e)}function S0(e){mh(e)}function A0(e){var t;window.removeEventListener("popstate",e.popStateHandler),Ff(e),ma(e),ya(e),ba(e),Wf(e),Kf(e),Jf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function C0(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&&Ao(e,t.has("tab")||t.has("logsAutoFollow")),(t.has("sessionLogsEntries")||t.has("sessionLogsAutoFollow"))&&e.sessionLogsAutoFollow&&e.logsAtBottom&&Ao(e,t.has("sessionLogsAutoFollow"))}}function E0(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 T0(e,t,n){await sa(e,t,n),await Z(e,!0)}async function _0(e,t){await hc(e,t),await Z(e,!0)}async function M0(e,t){await fc(e,t),await Z(e,!0)}async function P0(e,t){await gc(e,t)}async function I0(e,t){await mc(e,t)}async function R0(e){await bh(e),await We(e),await Z(e,!0)}async function L0(e){await We(e),await Z(e,!0)}function D0(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 Ou(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 Fu(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function B0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=E0(n??void 0)}function N0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function O0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function F0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function U0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Ou(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(Fu(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:D0(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 Z(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function W0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Ou(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(Fu(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 l=(s==null?void 0:s.error)??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:l,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 Z(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function z0(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 K0(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 H0(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 q0(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 j0(e,t){e.authCodeInput=t}async function G0(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 V0(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 Q0(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 J0(e,t){e.licenseKey=t}async function Y0(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 X0(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 Z0=Object.defineProperty,ex=Object.getOwnPropertyDescriptor,g=(e,t,n,i)=>{for(var s=i>1?void 0:i?ex(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&&Z0(t,n,s),s};const wo=Sp();function tx(){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 nx(){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 ix(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function sx(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function ox(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function ax(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function rx(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function lx(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let f=class extends Gt{constructor(){super(...arguments),this.settings=Ns(),this.password="",this.tab="chat",this.onboarding=tx(),this.setup=nx(),this.filesPage=ix(),this.browserPage=sx(),this.adminsPage=ox(),this.contactsPage=ax(),this.chatPage=rx(),this.advancedPage=lx(),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=wo.name,this.assistantAvatar=wo.avatar,this.assistantAgentId=wo.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=`{
5008
+ `}const S0={trace:!1,debug:!1,info:!0,warn:!0,error:!0,fatal:!0},A0={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 C0(e){e.basePath=Gf();const t=Qe();Gl(t.accentColor),Ql(t.backgroundColor);const n=document.querySelector('link[rel="icon"]');if(n&&(n.href=t.iconUrl),window.scrollTo(0,0),Wf(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}`,De(e);return}if(e.setup){document.title=`${t.name} Setup`,De(e);return}if(e.filesPage){document.title=`${t.name} Files`,Kf(e),De(e);return}if(e.browserPage){document.title=`${t.name} Browser`,De(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,De(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,De(e);return}if(e.chatPage){document.title=`${t.name} Chat`,De(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,De(e),zi(e),Wi(e);return}Xf(e,!0),Qf(e),Jf(e),window.addEventListener("popstate",e.popStateHandler),qf(e),De(e),Ff(e),e.tab==="logs"&&(e.logsSubTab==="session"?zi(e):Wi(e)),e.tab==="debug"&&va(e)}function E0(e){yh(e)}function T0(e){var t;window.removeEventListener("popstate",e.popStateHandler),Uf(e),ma(e),ya(e),ba(e),zf(e),Hf(e),Yf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function _0(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&&Ao(e,t.has("tab")||t.has("logsAutoFollow")),(t.has("sessionLogsEntries")||t.has("sessionLogsAutoFollow"))&&e.sessionLogsAutoFollow&&e.logsAtBottom&&Ao(e,t.has("sessionLogsAutoFollow"))}}function M0(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 P0(e,t,n){await sa(e,t,n),await Y(e,!0)}async function I0(e,t){await hc(e,t),await Y(e,!0)}async function R0(e,t){await fc(e,t),await Y(e,!0)}async function L0(e,t){await gc(e,t)}async function D0(e,t,n){await mc(e,t,n)}async function B0(e,t){await yc(e,t)}async function N0(e){await wh(e),await Oe(e),await Y(e,!0)}async function O0(e){await Oe(e),await Y(e,!0)}function F0(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 Fu(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 Uu(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function U0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=M0(n??void 0)}function W0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function z0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function K0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function H0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Fu(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(Uu(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:F0(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 Y(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function q0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Fu(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(Uu(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 l=(s==null?void 0:s.error)??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:l,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 Y(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function j0(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 V0(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 G0(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 Q0(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 J0(e,t){e.authCodeInput=t}async function Y0(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 X0(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 Z0(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 ex(e,t){e.licenseKey=t}async function tx(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 nx(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 ix=Object.defineProperty,sx=Object.getOwnPropertyDescriptor,g=(e,t,n,i)=>{for(var s=i>1?void 0:i?sx(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&&ix(t,n,s),s};const wo=Ap();function ox(){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 ax(){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 rx(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function lx(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function cx(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function dx(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function ux(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function px(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let f=class extends Vt{constructor(){super(...arguments),this.settings=Ns(),this.password="",this.tab="chat",this.onboarding=ox(),this.setup=ax(),this.filesPage=rx(),this.browserPage=lx(),this.adminsPage=cx(),this.contactsPage=dx(),this.chatPage=ux(),this.advancedPage=px(),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=vc,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=wo.name,this.assistantAvatar=wo.avatar,this.assistantAgentId=wo.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=`{
4935
5009
  }
4936
- `,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={...x0},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=Wa(),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.skillsAgentFilter="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={...k0},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=5e3,this.logsMaxBytes=5e6,this.logsAtBottom=!0,this.logsDate=null,this.logsAvailableDates=[],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=()=>Xf(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._beforeUnloadHandler=()=>{var t;$o();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(),$0(this),window.addEventListener("beforeunload",this._beforeUnloadHandler)}firstUpdated(){S0(this)}disconnectedCallback(){window.removeEventListener("beforeunload",this._beforeUnloadHandler),this.stopEmbeddingPoll(),A0(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){C0(this,e)}connect(){Oe(this)}handleChatScroll(e){ch(this,e)}handleLogsScroll(e){uh(this,e)}handleSessionLogsScroll(e){ph(this,e)}exportLogs(e,t){fh(e,t)}exportSessionLogs(e,t){gh(e,t)}resetToolStream(){ia(this)}resetChatScroll(){hh(this)}async loadAssistantIdentity(){await Qo(this)}applySettings(e){at(this,e)}setTab(e){qf(this,e)}setTheme(e,t){jf(this,e,t)}async loadOverview(){await pd(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 hd(this)}async handleAbortChat(){await gd(this)}removeQueuedMessage(e){ng(this,e)}async handleSendChat(e,t){await ig(this,e,t)}async handleWhatsAppStart(e,t){await T0(this,e,t)}async handleWhatsAppWait(e){await _0(this,e)}async handleWhatsAppLogout(e){await M0(this,e)}async handleAddWhatsAppAccount(e){await P0(this,e)}async handleRemoveWhatsAppAccount(e){await I0(this,e)}async handleAccessCheck(){await Er(this)}async handlePinSubmit(e,t){await _h(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await Mh(this,e)}async handleLogout(){await Ih(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 Er(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 G0(this)}async handleLicenseActivate(){await V0(this)}async handleLicenseRemove(){await Q0(this)}handleLicenseKeyChange(e){J0(this,e)}async handleAuthStatusCheck(){await K0(this)}async handleAuthStart(){await H0(this)}async handleAuthSubmitCode(e){await q0(this,e)}handleAuthCodeChange(e){j0(this,e)}handleClaudeAuthModalOpen(){this.claudeAuthModalOpen=!0}handleClaudeAuthModalClose(){this.claudeAuthModalOpen=!1,this.authUrl=null,this.authRefreshTokenInput="",this.authRefreshTokenError=null}async handleImportRefreshToken(){await z0(this)}async handleGatewayHealthCheck(){await Y0(this)}async handleGatewayRestart(){await X0(this)}async handleUpdateCheck(){await Eu(this)}async handleUpdateRun(){await Fk(this)}handleUpdateDismissResult(){zk(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(()=>Dr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){ae(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>Dr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await ad(this)}async clearAudit(){await Af(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),ps(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();ae(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>o0);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=dh(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(()=>i0);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(()=>od);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):ae(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>Nh);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(()=>vf);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await R0(this)}async handleChannelConfigReload(){await L0(this)}handleNostrProfileEdit(e,t){B0(this,e,t)}handleNostrProfileCancel(){N0(this)}handleNostrProfileFieldChange(e,t){O0(this,e,t)}async handleNostrProfileSave(){await U0(this)}async handleNostrProfileImport(){await W0(this)}handleNostrProfileToggleAdvanced(){F0(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(()=>a0);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(()=>Eh);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){$o(),this.selectedWorkspace&&Wn(this.selectedWorkspace,this.sessionKey,this.chatMessage),this.selectedWorkspace=e,this.publicChatQrDataUrl=null,localStorage.setItem("taskmaster-selected-workspace",e),Tn(e),wr(e),this.settings=Ns(),this.chatMessage=zn(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),wr(this.selectedWorkspace),this.settings=Ns(),this.chatMessage=zn(this.selectedWorkspace,this.settings.sessionKey),this.reloadCurrentPageData()}render(){return c`${v0(this)}${this.auditModalOpen?w0(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,"skillsAgentFilter",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,"logsDate",2);g([m()],f.prototype,"logsAvailableDates",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([jl("taskmaster-app")],f);
4937
- //# sourceMappingURL=index-B_QfEVs7.js.map
5010
+ `,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.newWhatsAppAccountProvider="baileys",this.newCloudPhoneNumberId="",this.newCloudBusinessAccountId="",this.newCloudAccessToken="",this.newCloudWebhookVerifyToken="",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={...A0},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=Wa(),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.skillsAgentFilter="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={...S0},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=5e3,this.logsMaxBytes=5e6,this.logsAtBottom=!0,this.logsDate=null,this.logsAvailableDates=[],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=()=>Zf(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._beforeUnloadHandler=()=>{var t;$o();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(),C0(this),window.addEventListener("beforeunload",this._beforeUnloadHandler)}firstUpdated(){E0(this)}disconnectedCallback(){window.removeEventListener("beforeunload",this._beforeUnloadHandler),this.stopEmbeddingPoll(),T0(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){_0(this,e)}connect(){De(this)}handleChatScroll(e){dh(this,e)}handleLogsScroll(e){ph(this,e)}handleSessionLogsScroll(e){hh(this,e)}exportLogs(e,t){gh(e,t)}exportSessionLogs(e,t){mh(e,t)}resetToolStream(){ia(this)}resetChatScroll(){fh(this)}async loadAssistantIdentity(){await Qo(this)}applySettings(e){st(this,e)}setTab(e){jf(this,e)}setTheme(e,t){Vf(this,e,t)}async loadOverview(){await hd(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 fd(this)}async handleAbortChat(){await md(this)}removeQueuedMessage(e){ig(this,e)}async handleSendChat(e,t){await sg(this,e,t)}async handleWhatsAppStart(e,t){await P0(this,e,t)}async handleWhatsAppWait(e){await I0(this,e)}async handleWhatsAppLogout(e){await R0(this,e)}async handleAddWhatsAppAccount(e){await L0(this,e)}async handleAddCloudApiAccount(e,t){await D0(this,e,t)}async handleRemoveWhatsAppAccount(e){await B0(this,e)}async handleAccessCheck(){await Er(this)}async handlePinSubmit(e,t){await Mh(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await Ph(this,e)}async handleLogout(){await Rh(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 Er(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 Y0(this)}async handleLicenseActivate(){await X0(this)}async handleLicenseRemove(){await Z0(this)}handleLicenseKeyChange(e){ex(this,e)}async handleAuthStatusCheck(){await V0(this)}async handleAuthStart(){await G0(this)}async handleAuthSubmitCode(e){await Q0(this,e)}handleAuthCodeChange(e){J0(this,e)}handleClaudeAuthModalOpen(){this.claudeAuthModalOpen=!0}handleClaudeAuthModalClose(){this.claudeAuthModalOpen=!1,this.authUrl=null,this.authRefreshTokenInput="",this.authRefreshTokenError=null}async handleImportRefreshToken(){await j0(this)}async handleGatewayHealthCheck(){await tx(this)}async handleGatewayRestart(){await nx(this)}async handleUpdateCheck(){await Tu(this)}async handleUpdateRun(){await zk(this)}handleUpdateDismissResult(){qk(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(()=>Dr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){ae(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>Dr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await rd(this)}async clearAudit(){await Cf(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),ps(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();ae(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>l0);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=uh(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(()=>a0);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(()=>ad);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):ae(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>Oh);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(()=>bf);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await N0(this)}async handleChannelConfigReload(){await O0(this)}handleNostrProfileEdit(e,t){U0(this,e,t)}handleNostrProfileCancel(){W0(this)}handleNostrProfileFieldChange(e,t){z0(this,e,t)}async handleNostrProfileSave(){await H0(this)}async handleNostrProfileImport(){await q0(this)}handleNostrProfileToggleAdvanced(){K0(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(()=>c0);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(()=>Th);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){$o(),this.selectedWorkspace&&Wn(this.selectedWorkspace,this.sessionKey,this.chatMessage),this.selectedWorkspace=e,this.publicChatQrDataUrl=null,localStorage.setItem("taskmaster-selected-workspace",e),Tn(e),wr(e),this.settings=Ns(),this.chatMessage=zn(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),wr(this.selectedWorkspace),this.settings=Ns(),this.chatMessage=zn(this.selectedWorkspace,this.settings.sessionKey),this.reloadCurrentPageData()}render(){return c`${k0(this)}${this.auditModalOpen?$0(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,"newWhatsAppAccountProvider",2);g([m()],f.prototype,"newCloudPhoneNumberId",2);g([m()],f.prototype,"newCloudBusinessAccountId",2);g([m()],f.prototype,"newCloudAccessToken",2);g([m()],f.prototype,"newCloudWebhookVerifyToken",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,"skillsAgentFilter",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,"logsDate",2);g([m()],f.prototype,"logsAvailableDates",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([jl("taskmaster-app")],f);
5011
+ //# sourceMappingURL=index-CkGA_2Sq.js.map