@rubytech/taskmaster 1.42.1 → 1.44.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 Tp=Object.defineProperty;var Pp=(e,t,n)=>t in e?Tp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var G=(e,t,n)=>Pp(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 _p="modulepreload",Mp=function(e,t){return new URL(e,t).href},br={},se=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(v=>({status:"fulfilled",value:v}),v=>({status:"rejected",reason:v}))))};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=c(n.map(d=>{if(d=Mp(d,i),d in br)return;br[d]=!0;const m=d.endsWith(".css"),v=m?'[rel="stylesheet"]':"";if(i)for(let b=a.length-1;b>=0;b--){const x=a[b];if(x.href===d&&(!m||x.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${d}"]${v}`))return;const p=document.createElement("link");if(p.rel=m?"stylesheet":_p,m||(p.as="script"),p.crossOrigin="",p.href=d,l&&p.setAttribute("nonce",l),document.head.appendChild(p),m)return new Promise((b,x)=>{p.addEventListener("load",b),p.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}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 Di=globalThis,la=Di.ShadowRoot&&(Di.ShadyCSS===void 0||Di.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ca=Symbol(),wr=new WeakMap;let ec=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==ca)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(la&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=wr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&wr.set(n,t))}return t}toString(){return this.cssText}};const Ip=e=>new ec(typeof e=="string"?e:e+"",void 0,ca),Rp=(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 ec(n,e,ca)},Lp=(e,t)=>{if(la)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=Di.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},kr=la?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Ip(n)})(e):e;const{is:Bp,defineProperty:Dp,getOwnPropertyDescriptor:Np,getOwnPropertyNames:Up,getOwnPropertySymbols:Op,getPrototypeOf:Fp}=Object,ct=globalThis,xr=ct.trustedTypes,Wp=xr?xr.emptyScript:"",Fs=ct.reactiveElementPolyfillSupport,Bn=(e,t)=>e,Hi={toAttribute(e,t){switch(t){case Boolean:e=e?Wp: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}},ua=(e,t)=>!Bp(e,t),$r={attribute:!0,type:String,converter:Hi,reflect:!1,useDefault:!1,hasChanged:ua};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ct.litPropertyMetadata??(ct.litPropertyMetadata=new WeakMap);let Gt=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=$r){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&&Dp(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=Np(this.prototype,t)??{get(){return this[n]},set(a){this[n]=a}};return{get:s,set(a){const r=s==null?void 0:s.call(this);o==null||o.call(this,a),this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??$r}static _$Ei(){if(this.hasOwnProperty(Bn("elementProperties")))return;const t=Fp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Bn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Bn("properties"))){const n=this.properties,i=[...Up(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(kr(s))}else t!==void 0&&n.push(kr(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 Lp(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:Hi).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:Hi;this._$Em=s;const c=l.fromAttribute(n,r.type);this[s]=c??((a=this._$Ej)==null?void 0:a.get(s))??c,this._$Em=null}}requestUpdate(t,n,i,s=!1,o){var a;if(t!==void 0){const r=this.constructor;if(s===!1&&(o=this[t]),i??(i=r.getPropertyOptions(t)),!((i.hasChanged??ua)(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){}};Gt.elementStyles=[],Gt.shadowRootOptions={mode:"open"},Gt[Bn("elementProperties")]=new Map,Gt[Bn("finalized")]=new Map,Fs==null||Fs({ReactiveElement:Gt}),(ct.reactiveElementVersions??(ct.reactiveElementVersions=[])).push("2.1.2");const Dn=globalThis,Sr=e=>e,ji=Dn.trustedTypes,Ar=ji?ji.createPolicy("lit-html",{createHTML:e=>e}):void 0,tc="$lit$",lt=`lit$${Math.random().toFixed(9).slice(2)}$`,nc="?"+lt,zp=`<${nc}>`,Mt=document,Gn=()=>Mt.createComment(""),Qn=e=>e===null||typeof e!="object"&&typeof e!="function",da=Array.isArray,Kp=e=>da(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ws=`[
1
+ var _p=Object.defineProperty;var Mp=(e,t,n)=>t in e?_p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var G=(e,t,n)=>Mp(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 Ip="modulepreload",Rp=function(e,t){return new URL(e,t).href},br={},se=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(v=>({status:"fulfilled",value:v}),v=>({status:"rejected",reason:v}))))};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=c(n.map(d=>{if(d=Rp(d,i),d in br)return;br[d]=!0;const m=d.endsWith(".css"),v=m?'[rel="stylesheet"]':"";if(i)for(let b=a.length-1;b>=0;b--){const x=a[b];if(x.href===d&&(!m||x.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${d}"]${v}`))return;const p=document.createElement("link");if(p.rel=m?"stylesheet":Ip,m||(p.as="script"),p.crossOrigin="",p.href=d,l&&p.setAttribute("nonce",l),document.head.appendChild(p),m)return new Promise((b,x)=>{p.addEventListener("load",b),p.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}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 Di=globalThis,la=Di.ShadowRoot&&(Di.ShadyCSS===void 0||Di.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ca=Symbol(),wr=new WeakMap;let nc=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==ca)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(la&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=wr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&wr.set(n,t))}return t}toString(){return this.cssText}};const Lp=e=>new nc(typeof e=="string"?e:e+"",void 0,ca),Bp=(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 nc(n,e,ca)},Dp=(e,t)=>{if(la)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=Di.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},kr=la?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Lp(n)})(e):e;const{is:Np,defineProperty:Up,getOwnPropertyDescriptor:Op,getOwnPropertyNames:Fp,getOwnPropertySymbols:Wp,getPrototypeOf:zp}=Object,ct=globalThis,xr=ct.trustedTypes,Kp=xr?xr.emptyScript:"",Fs=ct.reactiveElementPolyfillSupport,Bn=(e,t)=>e,Hi={toAttribute(e,t){switch(t){case Boolean:e=e?Kp: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}},ua=(e,t)=>!Np(e,t),$r={attribute:!0,type:String,converter:Hi,reflect:!1,useDefault:!1,hasChanged:ua};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ct.litPropertyMetadata??(ct.litPropertyMetadata=new WeakMap);let Gt=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=$r){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&&Up(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=Op(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)??$r}static _$Ei(){if(this.hasOwnProperty(Bn("elementProperties")))return;const t=zp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Bn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Bn("properties"))){const n=this.properties,i=[...Fp(n),...Wp(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(kr(s))}else t!==void 0&&n.push(kr(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 Dp(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:Hi).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:Hi;this._$Em=s;const c=l.fromAttribute(n,r.type);this[s]=c??((a=this._$Ej)==null?void 0:a.get(s))??c,this._$Em=null}}requestUpdate(t,n,i,s=!1,o){var a;if(t!==void 0){const r=this.constructor;if(s===!1&&(o=this[t]),i??(i=r.getPropertyOptions(t)),!((i.hasChanged??ua)(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){}};Gt.elementStyles=[],Gt.shadowRootOptions={mode:"open"},Gt[Bn("elementProperties")]=new Map,Gt[Bn("finalized")]=new Map,Fs==null||Fs({ReactiveElement:Gt}),(ct.reactiveElementVersions??(ct.reactiveElementVersions=[])).push("2.1.2");const Dn=globalThis,Sr=e=>e,ji=Dn.trustedTypes,Ar=ji?ji.createPolicy("lit-html",{createHTML:e=>e}):void 0,ic="$lit$",lt=`lit$${Math.random().toFixed(9).slice(2)}$`,sc="?"+lt,qp=`<${sc}>`,Mt=document,Gn=()=>Mt.createComment(""),Qn=e=>e===null||typeof e!="object"&&typeof e!="function",da=Array.isArray,Hp=e=>da(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ws=`[
2
2
  \f\r]`,xn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Cr=/-->/g,Er=/>/g,yt=RegExp(`>|${Ws}(?:([^\\s"'>=/]+)(${Ws}*=${Ws}*(?:[^
3
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Tr=/'/g,Pr=/"/g,ic=/^(?:script|style|textarea|title)$/i,qp=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),u=qp(1),pt=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),_r=new WeakMap,xt=Mt.createTreeWalker(Mt,129);function sc(e,t){if(!da(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ar!==void 0?Ar.createHTML(t):t}const Hp=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",a=xn;for(let r=0;r<n;r++){const l=e[r];let c,d,m=-1,v=0;for(;v<l.length&&(a.lastIndex=v,d=a.exec(l),d!==null);)v=a.lastIndex,a===xn?d[1]==="!--"?a=Cr:d[1]!==void 0?a=Er:d[2]!==void 0?(ic.test(d[2])&&(s=RegExp("</"+d[2],"g")),a=yt):d[3]!==void 0&&(a=yt):a===yt?d[0]===">"?(a=s??xn,m=-1):d[1]===void 0?m=-2:(m=a.lastIndex-d[2].length,c=d[1],a=d[3]===void 0?yt:d[3]==='"'?Pr:Tr):a===Pr||a===Tr?a=yt:a===Cr||a===Er?a=xn:(a=yt,s=void 0);const p=a===yt&&e[r+1].startsWith("/>")?" ":"";o+=a===xn?l+zp:m>=0?(i.push(c),l.slice(0,m)+tc+l.slice(m)+lt+p):l+lt+(m===-2?r:p)}return[sc(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let _o=class oc{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,l=this.parts,[c,d]=Hp(t,n);if(this.el=oc.createElement(c,i),xt.currentNode=this.el.content,n===2||n===3){const m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(s=xt.nextNode())!==null&&l.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const m of s.getAttributeNames())if(m.endsWith(tc)){const v=d[a++],p=s.getAttribute(m).split(lt),b=/([.?@])?(.*)/.exec(v);l.push({type:1,index:o,name:b[2],strings:p,ctor:b[1]==="."?Vp:b[1]==="?"?Gp:b[1]==="@"?Qp:ms}),s.removeAttribute(m)}else m.startsWith(lt)&&(l.push({type:6,index:o}),s.removeAttribute(m));if(ic.test(s.tagName)){const m=s.textContent.split(lt),v=m.length-1;if(v>0){s.textContent=ji?ji.emptyScript:"";for(let p=0;p<v;p++)s.append(m[p],Gn()),xt.nextNode(),l.push({type:2,index:++o});s.append(m[v],Gn())}}}else if(s.nodeType===8)if(s.data===nc)l.push({type:2,index:o});else{let m=-1;for(;(m=s.data.indexOf(lt,m+1))!==-1;)l.push({type:7,index:o}),m+=lt.length-1}o++}}static createElement(t,n){const i=Mt.createElement("template");return i.innerHTML=t,i}};function tn(e,t,n=e,i){var a,r;if(t===pt)return t;let s=i!==void 0?(a=n._$Co)==null?void 0:a[i]:n._$Cl;const o=Qn(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=tn(e,s._$AS(e,t.values),s,i)),t}class jp{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)??Mt).importNode(n,!0);xt.currentNode=s;let o=xt.nextNode(),a=0,r=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new fs(o,o.nextSibling,this,t):l.type===1?c=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(c=new Jp(o,this,t)),this._$AV.push(c),l=i[++r]}a!==(l==null?void 0:l.index)&&(o=xt.nextNode(),a++)}return xt.currentNode=Mt,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 fs=class ac{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=tn(this,t,n),Qn(t)?t===w||t==null||t===""?(this._$AH!==w&&this._$AR(),this._$AH=w):t!==this._$AH&&t!==pt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Kp(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&&Qn(this._$AH)?this._$AA.nextSibling.data=t:this.T(Mt.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=_o.createElement(sc(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 jp(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=_r.get(t.strings);return n===void 0&&_r.set(t.strings,n=new _o(t)),n}k(t){da(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 ac(this.O(Gn()),this.O(Gn()),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=Sr(t).nextSibling;Sr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class ms{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=tn(this,t,n,0),a=!Qn(t)||t!==this._$AH&&t!==pt,a&&(this._$AH=t);else{const r=t;let l,c;for(t=o[0],l=0;l<o.length-1;l++)c=tn(this,r[i+l],n,l),c===pt&&(c=this._$AH[l]),a||(a=!Qn(c)||c!==this._$AH[l]),c===w?t=w:t!==w&&(t+=(c??"")+o[l+1]),this._$AH[l]=c}a&&!s&&this.j(t)}j(t){t===w?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let Vp=class extends ms{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},Gp=class extends ms{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},Qp=class extends ms{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=tn(this,t,n,0)??w)===pt)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)}},Jp=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){tn(this,t)}};const Yp={I:fs},zs=Dn.litHtmlPolyfillSupport;zs==null||zs(_o,fs),(Dn.litHtmlVersions??(Dn.litHtmlVersions=[])).push("3.3.2");const Xp=(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 fs(t.insertBefore(Gn(),o),o,void 0,n??{})}return s._$AI(e),s};const Et=globalThis;let Zt=class extends Gt{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=Xp(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 pt}};var Zl;Zt._$litElement$=!0,Zt.finalized=!0,(Zl=Et.litElementHydrateSupport)==null||Zl.call(Et,{LitElement:Zt});const Ks=Et.litElementPolyfillSupport;Ks==null||Ks({LitElement:Zt});(Et.litElementVersions??(Et.litElementVersions=[])).push("4.2.2");const rc=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Zp={attribute:!0,type:String,converter:Hi,reflect:!1,hasChanged:ua},eh=(e=Zp,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 ys(e){return(t,n)=>typeof n=="object"?eh(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 f(e){return ys({...e,state:!0,attribute:!1})}const th=50,nh=200,ih="Assistant";function Mr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function Mo(e){const t=Mr(e==null?void 0:e.name,th)??ih,n=Mr((e==null?void 0:e.avatar)??void 0,nh)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function sh(){return Mo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const oh="Taskmaster",ah="/taskmaster-icon.png",rh="#00d4ff",lh="";let fi=null;function nt(){return fi||(fi={name:window.__TASKMASTER_BRAND_NAME__||oh,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||ah,accentColor:window.__TASKMASTER_ACCENT_COLOR__||rh,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||lh},fi)}function Ke(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function lc(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 ch(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 cc(e){const t=lc(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=ch(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function mi(e,t,n){const i=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!i||!s)return e;const o=(c,d)=>Math.round(parseInt(i[c],16)*(1-n)+parseInt(s[d],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 $n={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function uc(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries($n))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=lc(e);n&&(t.style.setProperty("--bg",mi($n["--bg"],e,.08)),t.style.setProperty("--bg-muted",mi($n["--bg-muted"],e,.1)),t.style.setProperty("--card",mi($n["--card"],e,.12)),t.style.setProperty("--secondary",mi($n["--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 Nn(e){const t=nt(),n=Ke(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;cc(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;uc(o)}const Vi="taskmaster.control.settings.v1",dc="taskmaster.account.settings.";function Un(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const jt={gatewayUrl:Un(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},at={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function uh(){try{const e=localStorage.getItem(Vi);if(!e)return{...jt,gatewayUrl:Un()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():Un(),token:typeof t.token=="string"?t.token:jt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:jt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:jt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:jt.navGroupsCollapsed}}catch{return{...jt,gatewayUrl:Un()}}}function dh(e){if(!e)return{...at};try{const t=localStorage.getItem(dc+e);if(!t)return{...at};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():at.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||at.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:at.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:at.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:at.splitRatio}}catch{return{...at}}}let Gi=null;function Ir(e){Gi=e}function qs(){return{...uh(),...dh(Gi)}}function ph(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(Vi,JSON.stringify(t)),Gi){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem(dc+Gi,JSON.stringify(n))}}const hh="taskmaster.draft.";function pa(e,t){return hh+e+"."+t}function Jn(e,t,n){try{const i=pa(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function Yn(e,t){try{return localStorage.getItem(pa(e,t))??""}catch{return""}}function gh(e,t){try{localStorage.removeItem(pa(e,t))}catch{}}let $t=null,Ie=null;function Rr(e,t,n){Ie={workspace:e,sessionKey:t,text:n},$t!=null&&clearTimeout($t),$t=setTimeout(()=>{Ie&&Jn(Ie.workspace,Ie.sessionKey,Ie.text),Ie=null,$t=null},300)}function Io(){$t!=null&&clearTimeout($t),$t=null,Ie&&(Jn(Ie.workspace,Ie.sessionKey,Ie.text),Ie=null)}(function(){try{const t=localStorage.getItem(Vi);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:Un(),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(Vi,JSON.stringify(i))}catch{}})();function ha(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 fh=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,yi=/<\s*\/?\s*final\b[^>]*>/gi,Lr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function mh(e,t){return e.trimStart()}function yh(e,t){if(!e||!fh.test(e))return e;let n=e;yi.test(n)?(yi.lastIndex=0,n=n.replace(yi,"")):yi.lastIndex=0,Lr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(Lr)){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),mh(i)}function pc(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function un(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 c=Math.round(l/60);return c<48?`in ${c}h`:`in ${Math.round(c/24)}d`}const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const i=Math.round(n/60);if(i<60)return`${i}m ago`;const s=Math.round(i/60);return s<48?`${s}h ago`:`${Math.round(s/24)}d ago`}function ga(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 vh(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function hc(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 Qi(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Hs(e){return yh(e)}const bh=/^\[([^\]]+)\]\s*/,wh=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],js=new WeakMap,Vs=new WeakMap;function kh(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:wh.some(t=>e.startsWith(`${t} `))}function Gs(e){const t=e.match(bh);if(!t)return e;const n=t[1]??"";return kh(n)?e.slice(t[0].length):e}function Jt(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?Hs(i):Gs(i);if(Array.isArray(i)){const s=i.map(o=>{const a=o;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(o=>typeof o=="string");if(s.length>0){const o=s.join(`
4
- `);return n==="assistant"?Hs(o):Gs(o)}}return typeof t.text=="string"?n==="assistant"?Hs(t.text):Gs(t.text):null}function gc(e){if(!e||typeof e!="object")return Jt(e);const t=e;if(js.has(t))return js.get(t)??null;const n=Jt(e);return js.set(t,n),n}function Br(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 c=l.thinking.trim();c&&i.push(c)}}if(i.length>0)return i.join(`
5
- `);const s=$h(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 xh(e){if(!e||typeof e!="object")return Br(e);const t=e;if(Vs.has(t))return Vs.get(t)??null;const n=Br(e);return Vs.set(t,n),n}function $h(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 Sh(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 Ah=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,Ch=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,Eh=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Th=/^A new session was started via \/new or \/reset\./;function Ph(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"&&Ah.test(s)||n==="assistant"&&Ch.test(s)||n==="user"&&Th.test(s)||n==="assistant"&&Eh.test(s)):!1}function fc(e){return e.filter(t=>!Ph(t))}function mc(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(m=>{const p=String(m.type??"").toLowerCase();return p==="toolresult"||p==="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(m=>({type:m.type||"text",text:m.text,name:m.name,args:m.args||m.arguments})):typeof t.text=="string"&&(l=[{type:"text",text:t.text}]);const c=typeof t.timestamp=="number"?t.timestamp:Date.now(),d=typeof t.id=="string"?t.id:void 0;return{role:n,content:l,timestamp:c,id:d}}function yc(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 vc(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function Dr(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 _h(){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 vs(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),Dr(t)}return Dr(_h())}const dn=50;async function nn(e,t){var i;if(!e.client||!e.connected||!((i=e.sessionKey)!=null&&i.trim()))return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??dn;try{const s=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:n}),o=Array.isArray(s.messages)?s.messages:[],a=typeof s.totalMessages=="number"?s.totalMessages:o.length,r=fc(o);e.chatMessages=r,e.chatHistoryTotal=a,e.chatHistoryHasMore=a>o.length,e.chatVerboseLevel=typeof s.verboseLevel=="string"?s.verboseLevel:null}catch(s){e.lastError=String(s)}finally{e.chatLoading=!1}}async function Mh(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:dn,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=fc(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 Ih(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function bc(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(p=>!p.fileName),r=(n??[]).filter(p=>p.fileName),l=[],c=r.map(p=>p.fileName).filter(Boolean);if(c.length>0){const p=i?`${c.join(", ")}
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Tr=/'/g,Pr=/"/g,oc=/^(?:script|style|textarea|title)$/i,jp=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),u=jp(1),pt=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),_r=new WeakMap,xt=Mt.createTreeWalker(Mt,129);function ac(e,t){if(!da(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ar!==void 0?Ar.createHTML(t):t}const Vp=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",a=xn;for(let r=0;r<n;r++){const l=e[r];let c,d,m=-1,v=0;for(;v<l.length&&(a.lastIndex=v,d=a.exec(l),d!==null);)v=a.lastIndex,a===xn?d[1]==="!--"?a=Cr:d[1]!==void 0?a=Er:d[2]!==void 0?(oc.test(d[2])&&(s=RegExp("</"+d[2],"g")),a=yt):d[3]!==void 0&&(a=yt):a===yt?d[0]===">"?(a=s??xn,m=-1):d[1]===void 0?m=-2:(m=a.lastIndex-d[2].length,c=d[1],a=d[3]===void 0?yt:d[3]==='"'?Pr:Tr):a===Pr||a===Tr?a=yt:a===Cr||a===Er?a=xn:(a=yt,s=void 0);const p=a===yt&&e[r+1].startsWith("/>")?" ":"";o+=a===xn?l+qp:m>=0?(i.push(c),l.slice(0,m)+ic+l.slice(m)+lt+p):l+lt+(m===-2?r:p)}return[ac(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let _o=class rc{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,l=this.parts,[c,d]=Vp(t,n);if(this.el=rc.createElement(c,i),xt.currentNode=this.el.content,n===2||n===3){const m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(s=xt.nextNode())!==null&&l.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const m of s.getAttributeNames())if(m.endsWith(ic)){const v=d[a++],p=s.getAttribute(m).split(lt),b=/([.?@])?(.*)/.exec(v);l.push({type:1,index:o,name:b[2],strings:p,ctor:b[1]==="."?Qp:b[1]==="?"?Jp:b[1]==="@"?Yp:ms}),s.removeAttribute(m)}else m.startsWith(lt)&&(l.push({type:6,index:o}),s.removeAttribute(m));if(oc.test(s.tagName)){const m=s.textContent.split(lt),v=m.length-1;if(v>0){s.textContent=ji?ji.emptyScript:"";for(let p=0;p<v;p++)s.append(m[p],Gn()),xt.nextNode(),l.push({type:2,index:++o});s.append(m[v],Gn())}}}else if(s.nodeType===8)if(s.data===sc)l.push({type:2,index:o});else{let m=-1;for(;(m=s.data.indexOf(lt,m+1))!==-1;)l.push({type:7,index:o}),m+=lt.length-1}o++}}static createElement(t,n){const i=Mt.createElement("template");return i.innerHTML=t,i}};function tn(e,t,n=e,i){var a,r;if(t===pt)return t;let s=i!==void 0?(a=n._$Co)==null?void 0:a[i]:n._$Cl;const o=Qn(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=tn(e,s._$AS(e,t.values),s,i)),t}class Gp{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)??Mt).importNode(n,!0);xt.currentNode=s;let o=xt.nextNode(),a=0,r=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new fs(o,o.nextSibling,this,t):l.type===1?c=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(c=new Xp(o,this,t)),this._$AV.push(c),l=i[++r]}a!==(l==null?void 0:l.index)&&(o=xt.nextNode(),a++)}return xt.currentNode=Mt,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 fs=class lc{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=tn(this,t,n),Qn(t)?t===w||t==null||t===""?(this._$AH!==w&&this._$AR(),this._$AH=w):t!==this._$AH&&t!==pt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Hp(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&&Qn(this._$AH)?this._$AA.nextSibling.data=t:this.T(Mt.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=_o.createElement(ac(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 Gp(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=_r.get(t.strings);return n===void 0&&_r.set(t.strings,n=new _o(t)),n}k(t){da(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 lc(this.O(Gn()),this.O(Gn()),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=Sr(t).nextSibling;Sr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class ms{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=tn(this,t,n,0),a=!Qn(t)||t!==this._$AH&&t!==pt,a&&(this._$AH=t);else{const r=t;let l,c;for(t=o[0],l=0;l<o.length-1;l++)c=tn(this,r[i+l],n,l),c===pt&&(c=this._$AH[l]),a||(a=!Qn(c)||c!==this._$AH[l]),c===w?t=w:t!==w&&(t+=(c??"")+o[l+1]),this._$AH[l]=c}a&&!s&&this.j(t)}j(t){t===w?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let Qp=class extends ms{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},Jp=class extends ms{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},Yp=class extends ms{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=tn(this,t,n,0)??w)===pt)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)}},Xp=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){tn(this,t)}};const Zp={I:fs},zs=Dn.litHtmlPolyfillSupport;zs==null||zs(_o,fs),(Dn.litHtmlVersions??(Dn.litHtmlVersions=[])).push("3.3.2");const eh=(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 fs(t.insertBefore(Gn(),o),o,void 0,n??{})}return s._$AI(e),s};const Et=globalThis;let Zt=class extends Gt{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=eh(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 pt}};var tc;Zt._$litElement$=!0,Zt.finalized=!0,(tc=Et.litElementHydrateSupport)==null||tc.call(Et,{LitElement:Zt});const Ks=Et.litElementPolyfillSupport;Ks==null||Ks({LitElement:Zt});(Et.litElementVersions??(Et.litElementVersions=[])).push("4.2.2");const cc=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const th={attribute:!0,type:String,converter:Hi,reflect:!1,hasChanged:ua},nh=(e=th,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 ys(e){return(t,n)=>typeof n=="object"?nh(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 f(e){return ys({...e,state:!0,attribute:!1})}const ih=50,sh=200,oh="Assistant";function Mr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function Mo(e){const t=Mr(e==null?void 0:e.name,ih)??oh,n=Mr((e==null?void 0:e.avatar)??void 0,sh)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function ah(){return Mo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const rh="Taskmaster",lh="/taskmaster-icon.png",ch="#00d4ff",uh="";let fi=null;function nt(){return fi||(fi={name:window.__TASKMASTER_BRAND_NAME__||rh,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||lh,accentColor:window.__TASKMASTER_ACCENT_COLOR__||ch,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||uh},fi)}function Ke(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function uc(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 dh(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 dc(e){const t=uc(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=dh(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function mi(e,t,n){const i=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!i||!s)return e;const o=(c,d)=>Math.round(parseInt(i[c],16)*(1-n)+parseInt(s[d],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 $n={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function pc(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries($n))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=uc(e);n&&(t.style.setProperty("--bg",mi($n["--bg"],e,.08)),t.style.setProperty("--bg-muted",mi($n["--bg-muted"],e,.1)),t.style.setProperty("--card",mi($n["--card"],e,.12)),t.style.setProperty("--secondary",mi($n["--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 Nn(e){const t=nt(),n=Ke(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;dc(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;pc(o)}const Vi="taskmaster.control.settings.v1",hc="taskmaster.account.settings.";function Un(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const jt={gatewayUrl:Un(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},at={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function ph(){try{const e=localStorage.getItem(Vi);if(!e)return{...jt,gatewayUrl:Un()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():Un(),token:typeof t.token=="string"?t.token:jt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:jt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:jt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:jt.navGroupsCollapsed}}catch{return{...jt,gatewayUrl:Un()}}}function hh(e){if(!e)return{...at};try{const t=localStorage.getItem(hc+e);if(!t)return{...at};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():at.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||at.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:at.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:at.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:at.splitRatio}}catch{return{...at}}}let Gi=null;function Ir(e){Gi=e}function qs(){return{...ph(),...hh(Gi)}}function gh(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(Vi,JSON.stringify(t)),Gi){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem(hc+Gi,JSON.stringify(n))}}const fh="taskmaster.draft.";function pa(e,t){return fh+e+"."+t}function Jn(e,t,n){try{const i=pa(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function Yn(e,t){try{return localStorage.getItem(pa(e,t))??""}catch{return""}}function mh(e,t){try{localStorage.removeItem(pa(e,t))}catch{}}let $t=null,Ie=null;function Rr(e,t,n){Ie={workspace:e,sessionKey:t,text:n},$t!=null&&clearTimeout($t),$t=setTimeout(()=>{Ie&&Jn(Ie.workspace,Ie.sessionKey,Ie.text),Ie=null,$t=null},300)}function Io(){$t!=null&&clearTimeout($t),$t=null,Ie&&(Jn(Ie.workspace,Ie.sessionKey,Ie.text),Ie=null)}(function(){try{const t=localStorage.getItem(Vi);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:Un(),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(Vi,JSON.stringify(i))}catch{}})();function ha(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 yh=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,yi=/<\s*\/?\s*final\b[^>]*>/gi,Lr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function vh(e,t){return e.trimStart()}function bh(e,t){if(!e||!yh.test(e))return e;let n=e;yi.test(n)?(yi.lastIndex=0,n=n.replace(yi,"")):yi.lastIndex=0,Lr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(Lr)){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),vh(i)}function gc(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function un(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 c=Math.round(l/60);return c<48?`in ${c}h`:`in ${Math.round(c/24)}d`}const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const i=Math.round(n/60);if(i<60)return`${i}m ago`;const s=Math.round(i/60);return s<48?`${s}h ago`:`${Math.round(s/24)}d ago`}function ga(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 wh(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function fc(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 Qi(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Hs(e){return bh(e)}const kh=/^\[([^\]]+)\]\s*/,xh=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],js=new WeakMap,Vs=new WeakMap;function $h(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:xh.some(t=>e.startsWith(`${t} `))}function Gs(e){const t=e.match(kh);if(!t)return e;const n=t[1]??"";return $h(n)?e.slice(t[0].length):e}function Jt(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?Hs(i):Gs(i);if(Array.isArray(i)){const s=i.map(o=>{const a=o;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(o=>typeof o=="string");if(s.length>0){const o=s.join(`
4
+ `);return n==="assistant"?Hs(o):Gs(o)}}return typeof t.text=="string"?n==="assistant"?Hs(t.text):Gs(t.text):null}function mc(e){if(!e||typeof e!="object")return Jt(e);const t=e;if(js.has(t))return js.get(t)??null;const n=Jt(e);return js.set(t,n),n}function Br(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 c=l.thinking.trim();c&&i.push(c)}}if(i.length>0)return i.join(`
5
+ `);const s=Ah(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 Sh(e){if(!e||typeof e!="object")return Br(e);const t=e;if(Vs.has(t))return Vs.get(t)??null;const n=Br(e);return Vs.set(t,n),n}function Ah(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 Ch(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 Eh=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,Th=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,Ph=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,_h=/^A new session was started via \/new or \/reset\./;function Mh(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"&&Eh.test(s)||n==="assistant"&&Th.test(s)||n==="user"&&_h.test(s)||n==="assistant"&&Ph.test(s)):!1}function yc(e){return e.filter(t=>!Mh(t))}function vc(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(m=>{const p=String(m.type??"").toLowerCase();return p==="toolresult"||p==="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(m=>({type:m.type||"text",text:m.text,name:m.name,args:m.args||m.arguments})):typeof t.text=="string"&&(l=[{type:"text",text:t.text}]);const c=typeof t.timestamp=="number"?t.timestamp:Date.now(),d=typeof t.id=="string"?t.id:void 0;return{role:n,content:l,timestamp:c,id:d}}function bc(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 wc(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function Dr(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 Ih(){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 vs(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),Dr(t)}return Dr(Ih())}const dn=50;async function nn(e,t){var i;if(!e.client||!e.connected||!((i=e.sessionKey)!=null&&i.trim()))return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??dn;try{const s=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:n}),o=Array.isArray(s.messages)?s.messages:[],a=typeof s.totalMessages=="number"?s.totalMessages:o.length,r=yc(o);e.chatMessages=r,e.chatHistoryTotal=a,e.chatHistoryHasMore=a>o.length,e.chatVerboseLevel=typeof s.verboseLevel=="string"?s.verboseLevel:null}catch(s){e.lastError=String(s)}finally{e.chatLoading=!1}}async function Rh(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:dn,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=yc(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 Lh(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function kc(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(p=>!p.fileName),r=(n??[]).filter(p=>p.fileName),l=[],c=r.map(p=>p.fileName).filter(Boolean);if(c.length>0){const p=i?`${c.join(", ")}
9
9
 
10
- ${i}`:c.join(", ");l.push({type:"text",text:p})}else i&&l.push({type:"text",text:i});for(const p of a)l.push({type:"image",source:{type:"base64",media_type:p.mimeType,data:p.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:l,timestamp:o}],e.chatSending=!0,e.lastError=null;const d=vs();e.chatRunId=d,e.chatStream="",e.chatStreamStartedAt=o;const m=[...a,...r],v=m.length>0?m.map(p=>{if(p.textContent)return{type:"document",mimeType:p.mimeType||"text/plain",fileName:p.fileName,content:btoa(unescape(encodeURIComponent(p.textContent)))};const b=Ih(p.dataUrl);return b?{type:p.fileName?"document":"image",mimeType:b.mimeType,fileName:p.fileName,content:b.content}:null}).filter(p=>p!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:d,attachments:v}),!0}catch(p){const b=String(p);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=b,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+b}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function wc(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 kc(e,t){var n,i,s,o;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 r=(t.message?(n=Jt(t.message))==null?void 0:n.trim():void 0)||((i=e.chatStream)==null?void 0:i.trim());if(r)if(!e.chatInterimText)e.chatInterimText=r;else{const l=r.trim(),c=e.chatInterimText.trim();l===c||c.endsWith(l)||(l.startsWith(c)?e.chatInterimText=r:e.chatInterimText=`${e.chatInterimText}
10
+ ${i}`:c.join(", ");l.push({type:"text",text:p})}else i&&l.push({type:"text",text:i});for(const p of a)l.push({type:"image",source:{type:"base64",media_type:p.mimeType,data:p.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:l,timestamp:o}],e.chatSending=!0,e.lastError=null;const d=vs();e.chatRunId=d,e.chatStream="",e.chatStreamStartedAt=o;const m=[...a,...r],v=m.length>0?m.map(p=>{if(p.textContent)return{type:"document",mimeType:p.mimeType||"text/plain",fileName:p.fileName,content:btoa(unescape(encodeURIComponent(p.textContent)))};const b=Lh(p.dataUrl);return b?{type:p.fileName?"document":"image",mimeType:b.mimeType,fileName:p.fileName,content:b.content}:null}).filter(p=>p!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:d,attachments:v}),!0}catch(p){const b=String(p);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=b,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+b}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function xc(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 $c(e,t){var n,i,s,o;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 r=(t.message?(n=Jt(t.message))==null?void 0:n.trim():void 0)||((i=e.chatStream)==null?void 0:i.trim());if(r)if(!e.chatInterimText)e.chatInterimText=r;else{const l=r.trim(),c=e.chatInterimText.trim();l===c||c.endsWith(l)||(l.startsWith(c)?e.chatInterimText=r:e.chatInterimText=`${e.chatInterimText}
11
11
 
12
- ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.message);return typeof a=="string"&&a.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:a.trim()}],timestamp:Date.now(),filler:!0}]),"block"}else if(t.state==="delta"){e.chatSuggestions=[];const a=Jt(t.message);if(typeof a=="string"){if(a.trim()==="NO_REPLY")return null;const r=e.chatStream??"";(!r||a.length>=r.length)&&(e.chatStream=a)}}else if(t.state==="final"){const a=Jt(t.message);typeof a=="string"&&a.trim()&&a.trim()!=="NO_REPLY"&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:Array.isArray((s=t.message)==null?void 0:s.content)?t.message.content:[{type:"text",text:a}],timestamp:((o=t.message)==null?void 0:o.timestamp)??Date.now()}]),e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null}else 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 Yt=Object.freeze(Object.defineProperty({__proto__:null,CHAT_PAGE_SIZE:dn,abortChatRun:wc,handleChatEvent:kc,loadChatHistory:nn,loadOlderChatHistory:Mh,sendChatMessage:bc},Symbol.toStringTag,{value:"Module"}));async function ht(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:!1,includeUnknown:e.sessionsIncludeUnknown??!1};e.selectedWorkspace&&(t.accountId=e.selectedWorkspace);const n=Qi(e.sessionsFilterActive??"",0),i=Qi(e.sessionsFilterLimit??"",0);n>0&&(t.activeMinutes=n),i>0&&(t.limit=i);const s=await e.client.request("sessions.list",t);s&&(e.sessionsResult=s)}catch(t){e.sessionsError=String(t)}finally{e.sessionsLoading=!1}}}async function xc(e,t,n){if(!e.client||!e.connected)return;const i={key:t};"label"in n&&(i.label=n.label),"thinkingLevel"in n&&(i.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(i.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(i.reasoningLevel=n.reasoningLevel),"model"in n&&(i.model=n.model),"fillerEnabled"in n&&(i.fillerEnabled=n.fillerEnabled);try{await e.client.request("sessions.patch",i),await ht(e)}catch(s){e.sessionsError=String(s)}}async function $c(e,t){if(!(!e.client||!e.connected)){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.reset",{key:t}),await ht(e)}catch(n){e.sessionsError=String(n)}finally{e.sessionsLoading=!1}}}async function Sc(e,t){if(!(!e.client||!e.connected)){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.delete",{key:t,deleteTranscript:!0})}catch(n){e.sessionsError=String(n)}finally{e.sessionsLoading=!1,await ht(e)}}}const Qs=Object.freeze(Object.defineProperty({__proto__:null,deleteSession:Sc,loadSessions:ht,patchSession:xc,resetSession:$c},Symbol.toStringTag,{value:"Module"})),Nr=50,Rh=80,Lh=12e4;function Bh(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 Ur(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=Bh(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=hc(n,Lh);return i.truncated?`${i.text}
12
+ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.message);return typeof a=="string"&&a.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:a.trim()}],timestamp:Date.now(),filler:!0}]),"block"}else if(t.state==="delta"){e.chatSuggestions=[];const a=Jt(t.message);if(typeof a=="string"){if(a.trim()==="NO_REPLY")return null;const r=e.chatStream??"";(!r||a.length>=r.length)&&(e.chatStream=a)}}else if(t.state==="final"){const a=Jt(t.message);typeof a=="string"&&a.trim()&&a.trim()!=="NO_REPLY"&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:Array.isArray((s=t.message)==null?void 0:s.content)?t.message.content:[{type:"text",text:a}],timestamp:((o=t.message)==null?void 0:o.timestamp)??Date.now()}]),e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null}else 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 Yt=Object.freeze(Object.defineProperty({__proto__:null,CHAT_PAGE_SIZE:dn,abortChatRun:xc,handleChatEvent:$c,loadChatHistory:nn,loadOlderChatHistory:Rh,sendChatMessage:kc},Symbol.toStringTag,{value:"Module"}));async function ht(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:!1,includeUnknown:e.sessionsIncludeUnknown??!1};e.selectedWorkspace&&(t.accountId=e.selectedWorkspace);const n=Qi(e.sessionsFilterActive??"",0),i=Qi(e.sessionsFilterLimit??"",0);n>0&&(t.activeMinutes=n),i>0&&(t.limit=i);const s=await e.client.request("sessions.list",t);s&&(e.sessionsResult=s)}catch(t){e.sessionsError=String(t)}finally{e.sessionsLoading=!1}}}async function Sc(e,t,n){if(!e.client||!e.connected)return;const i={key:t};"label"in n&&(i.label=n.label),"thinkingLevel"in n&&(i.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(i.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(i.reasoningLevel=n.reasoningLevel),"model"in n&&(i.model=n.model),"fillerEnabled"in n&&(i.fillerEnabled=n.fillerEnabled);try{await e.client.request("sessions.patch",i),await ht(e)}catch(s){e.sessionsError=String(s)}}async function Ac(e,t){if(!(!e.client||!e.connected)){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.reset",{key:t}),await ht(e)}catch(n){e.sessionsError=String(n)}finally{e.sessionsLoading=!1}}}async function Cc(e,t){if(!(!e.client||!e.connected)){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.delete",{key:t,deleteTranscript:!0})}catch(n){e.sessionsError=String(n)}finally{e.sessionsLoading=!1,await ht(e)}}}const Qs=Object.freeze(Object.defineProperty({__proto__:null,deleteSession:Cc,loadSessions:ht,patchSession:Sc,resetSession:Ac},Symbol.toStringTag,{value:"Module"})),Nr=50,Bh=80,Dh=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 Ur(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=fc(n,Dh);return i.truncated?`${i.text}
14
14
 
15
- … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function Dh(e){const t=[];return t.push({type:"toolcall",name:e.name,arguments:e.args??{}}),e.output&&t.push({type:"toolresult",name:e.name,text:e.output}),{role:"assistant",toolCallId:e.toolCallId,runId:e.runId,content:t,timestamp:e.startedAt}}function Nh(e){if(e.toolStreamOrder.length<=Nr)return;const t=e.toolStreamOrder.length-Nr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function Uh(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function Ro(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Uh(e)}function Oh(e,t=!1){if(t){Ro(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>Ro(e),Rh))}function fa(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],Ro(e)}const Fh=5e3;function Wh(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},Fh))}function zh(e,t){if(!t)return;if(t.stream==="compaction"){Wh(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"?Ur(i.partialResult):a==="result"?Ur(i.result):void 0,c=Date.now();let d=e.toolStreamById.get(s);d?(d.name=o,r!==void 0&&(d.args=r),l!==void 0&&(d.output=l),d.updatedAt=c):(d={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:r,output:l,startedAt:typeof t.ts=="number"?t.ts:c,updatedAt:c,message:{}},e.toolStreamById.set(s,d),e.toolStreamOrder.push(s)),d.message=Dh(d),Nh(e),Oh(e,a==="result")}let vi=0;function pn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++vi,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===vi&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==vi)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!==vi)return;const l=i();if(!l)return;const c=l.scrollHeight-l.scrollTop-l.clientHeight;(t||e.chatUserNearBottom||c<200)&&(l.scrollTop=l.scrollHeight,e.chatUserNearBottom=!0)},r)}))})}function Lo(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 Kh(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 qh(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 Hh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function jh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Vh(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function Gh(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 Uh(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 Oh(e){if(e.toolStreamOrder.length<=Nr)return;const t=e.toolStreamOrder.length-Nr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function Fh(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function Ro(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Fh(e)}function Wh(e,t=!1){if(t){Ro(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>Ro(e),Bh))}function fa(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],Ro(e)}const zh=5e3;function Kh(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},zh))}function qh(e,t){if(!t)return;if(t.stream==="compaction"){Kh(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"?Ur(i.partialResult):a==="result"?Ur(i.result):void 0,c=Date.now();let d=e.toolStreamById.get(s);d?(d.name=o,r!==void 0&&(d.args=r),l!==void 0&&(d.output=l),d.updatedAt=c):(d={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:r,output:l,startedAt:typeof t.ts=="number"?t.ts:c,updatedAt:c,message:{}},e.toolStreamById.set(s,d),e.toolStreamOrder.push(s)),d.message=Uh(d),Oh(e),Wh(e,a==="result")}let vi=0;function pn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++vi,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===vi&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==vi)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!==vi)return;const l=i();if(!l)return;const c=l.scrollHeight-l.scrollTop-l.clientHeight;(t||e.chatUserNearBottom||c<200)&&(l.scrollTop=l.scrollHeight,e.chatUserNearBottom=!0)},r)}))})}function Lo(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 Hh(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 jh(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 Vh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Gh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Qh(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function Jh(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 Qh(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 Yh(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 Jh(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 he(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function fe(e){return`${JSON.stringify(e,null,2).trimEnd()}
20
- `}function bs(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 He(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});Xh(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function Ac(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 Xh(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?fe(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=fe(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=he(t.config??{}),e.configFormOriginal=he(t.config??{}),e.configRawOriginal=n)}async function Zh(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?fe(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 He(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function hn(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 ti(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 Cc(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=Qi(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 Ec(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=Qi(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function eg(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Cc(e.cronForm),i=Ec(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 ti(e),await hn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function tg(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 ti(e),await hn(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function ng(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 Bo(e,t.id)}catch(n){e.cronError=String(n),e.cronRunResult={status:"error",error:String(n)}}finally{e.cronBusy=!1}}}function ig(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 sg(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 ti(e),await hn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function og(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 ag(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Cc(e.cronForm),i=Ec(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 ti(e),await hn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Bo(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 Q(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 ma(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 Tc(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 Pc(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 _c(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=he(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 c=s.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const d=fe(o);await e.client.request("config.set",{raw:d,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await Q(e,!0),await ma(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=he(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 c=l.accounts;if(c[s]){e.whatsappAccountError=`Account "${s}" already exists.`;return}const d={name:i,provider:"cloud",phoneNumberId:n.phoneNumberId.trim(),accessToken:n.accessToken.trim(),webhookVerifyToken:n.webhookVerifyToken.trim()};n.businessAccountId.trim()&&(d.businessAccountId=n.businessAccountId.trim()),c[s]=d;const m=o.hash;if(!m){e.whatsappAccountError="Config hash missing; reload and retry.";return}const v=fe(a);await e.client.request("config.set",{raw:v,baseHash:m}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",e.newWhatsAppAccountProvider="baileys",e.newCloudPhoneNumberId="",e.newCloudBusinessAccountId="",e.newCloudAccessToken="",e.newCloudWebhookVerifyToken="",await Q(e,!0)}catch(o){e.whatsappAccountError=String(o)}finally{e.whatsappAccountSaving=!1}}async function Ic(e){var n;if(!e.client||!e.connected||e.telegramProbing)return;const t=e.telegramConnectToken.trim();if(!t){e.telegramError="Please enter a bot token.";return}e.telegramProbing=!0,e.telegramProbeResult=null,e.telegramError=null;try{const i=await e.client.request("channels.probeToken",{channel:"telegram",token:t});e.telegramProbeResult={ok:i.ok,username:((n=i.bot)==null?void 0:n.username)??void 0,error:i.error??void 0},i.ok||(e.telegramError=i.error??"Invalid token.")}catch(i){e.telegramError=String(i),e.telegramProbeResult=null}finally{e.telegramProbing=!1}}async function Rc(e,t){if(!e.client||!e.connected||e.telegramBusy)return;const n=e.telegramConnectToken.trim();if(n){e.telegramBusy=!0,e.telegramError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{});(!s.channels||typeof s.channels!="object")&&(s.channels={});const o=s.channels;(!o.telegram||typeof o.telegram!="object")&&(o.telegram={});const a=o.telegram;t||(a.botToken=n,a.enabled=!0);const r=i.hash;if(!r){e.telegramError="Config hash missing; reload and retry.";return}const l=fe(s);await e.client.request("config.set",{raw:l,baseHash:r}),e.telegramConnectOpen=!1,e.telegramConnectToken="",e.telegramProbeResult=null,setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramError=String(i)}finally{e.telegramBusy=!1}}}async function Lc(e,t){if(!(!e.client||!e.connected)&&!e.telegramBusy){e.telegramBusy=!0,e.telegramError=null;try{await e.client.request("channels.logout",{channel:"telegram",accountId:t}),e.telegramSettingsOpen=!1,setTimeout(()=>{Q(e,!0)},2500)}catch(n){e.telegramError=String(n)}finally{e.telegramBusy=!1}}}async function Bc(e,t,n,i="open",s=!0){if(!e.client||!e.connected||e.telegramBotSaving)return;const o=t.trim(),a=n.trim();if(!o){e.telegramBotError="Bot name is required.";return}if(!a){e.telegramBotError="Bot token is required.";return}const r=a.split(":")[0];if(!r||!/^\d+$/.test(r)){e.telegramBotError="Invalid bot token format.";return}e.telegramBotSaving=!0,e.telegramBotError=null;try{const l=await e.client.request("config.get",{});e.configSnapshot=l;const c=he(l.config??{});(!c.channels||typeof c.channels!="object")&&(c.channels={});const d=c.channels;(!d.telegram||typeof d.telegram!="object")&&(d.telegram={});const m=d.telegram;(!m.accounts||typeof m.accounts!="object")&&(m.accounts={});const v=m.accounts;if(typeof m.botToken=="string"&&Object.keys(v).length===0&&(v.default={name:"Default",botToken:m.botToken,enabled:m.enabled!==!1},delete m.botToken,delete m.enabled),v[r]){e.telegramBotError=`Bot "${r}" already exists.`;return}const p={name:o,botToken:a,enabled:!0,dmPolicy:i,adminRouting:s};!s&&i==="open"&&(p.allowFrom=["*"]),v[r]=p;const b=l.hash;if(!b){e.telegramBotError="Config hash missing; reload and retry.";return}const x=fe(c);await e.client.request("config.set",{raw:x,baseHash:b}),e.telegramAddingBot=!1,e.telegramConnectOpen=!1,e.telegramNewBotName="",e.telegramConnectToken="",e.telegramProbeResult=null,e.telegramError=null,e.telegramBotError=null,setTimeout(()=>{Q(e,!0)},2500)}catch(l){e.telegramBotError=String(l)}finally{e.telegramBotSaving=!1}}async function Dc(e,t){if(!(!e.client||!e.connected)&&!e.telegramBotSaving){e.telegramBotSaving=!0,e.telegramBotError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=he(n.config??{}),s=i.channels,o=s==null?void 0:s.telegram,a=o==null?void 0:o.accounts;if(!a){e.telegramBotError="No bot accounts found in config.";return}if(!a[t]){e.telegramBotError=`Bot "${t}" not found.`;return}if(Object.keys(a).length<=1){e.telegramBotError="Cannot remove the last bot.";return}delete a[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(c=>{const d=c.match;return!d||d.channel!=="telegram"?!0:d.accountId!==t}));const r=n.hash;if(!r){e.telegramBotError="Config hash missing; reload and retry.";return}const l=fe(i);await e.client.request("config.set",{raw:l,baseHash:r}),setTimeout(()=>{Q(e,!0)},2500)}catch(n){e.telegramBotError=String(n)}finally{e.telegramBotSaving=!1}}}async function Nc(e,t,n){if(!(!e.client||!e.connected)&&!e.telegramDmPolicySaving){e.telegramDmPolicySaving=!0;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{}),o=s.channels,a=o==null?void 0:o.telegram,r=a==null?void 0:a.accounts,l=r==null?void 0:r[t];if(!l){e.telegramError=`Bot "${t}" not found.`;return}l.dmPolicy=n,l.adminRouting!==!0&&n==="open"&&(!Array.isArray(l.allowFrom)||!l.allowFrom.includes("*"))&&(l.allowFrom=["*"]);const c=i.hash;if(!c){e.telegramError="Config hash missing; reload and retry.";return}const d=fe(s);await e.client.request("config.set",{raw:d,baseHash:c}),setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramError=String(i)}finally{e.telegramDmPolicySaving=!1}}}async function Uc(e,t,n){if(!(!e.client||!e.connected)&&!e.telegramBotSaving){e.telegramBotSaving=!0,e.telegramBotError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{}),o=s.channels,a=o==null?void 0:o.telegram,r=a==null?void 0:a.accounts,l=r==null?void 0:r[t];if(!l){e.telegramBotError=`Bot "${t}" not found.`;return}l.adminRouting=n,!n&&l.dmPolicy==="open"&&(!Array.isArray(l.allowFrom)||!l.allowFrom.includes("*"))&&(l.allowFrom=["*"]);const c=i.hash;if(!c){e.telegramBotError="Config hash missing; reload and retry.";return}const d=fe(s);await e.client.request("config.set",{raw:d,baseHash:c}),e.telegramBotError=null,setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramBotError=String(i)}finally{e.telegramBotSaving=!1}}}async function Oc(e,t,n){if(!e.client||!e.connected||e.telegramWhitelistSaving)return;let i=n.trim().toLowerCase();if(!i){e.telegramWhitelistError="Username is required.";return}i.startsWith("@")||(i="@"+i);const s=i.slice(1);if(s.length<5||s.length>32){e.telegramWhitelistError="Username must be 5–32 characters (excluding @).";return}e.telegramWhitelistSaving=!0,e.telegramWhitelistError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const a=he(o.config??{}),r=a.channels,l=r==null?void 0:r.telegram,c=l==null?void 0:l.accounts,d=c==null?void 0:c[t];if(!d){e.telegramWhitelistError=`Bot "${t}" not found.`;return}Array.isArray(d.allowFrom)||(d.allowFrom=[]);const m=d.allowFrom;if(m.some(b=>b.toLowerCase()===i)){e.telegramWhitelistError=`"${i}" is already in the whitelist.`;return}m.push(i);const v=o.hash;if(!v){e.telegramWhitelistError="Config hash missing; reload and retry.";return}const p=fe(a);await e.client.request("config.set",{raw:p,baseHash:v}),e.telegramNewWhitelistUsername="",setTimeout(()=>{Q(e,!0)},2500)}catch(o){e.telegramWhitelistError=String(o)}finally{e.telegramWhitelistSaving=!1}}async function Fc(e,t,n){if(!(!e.client||!e.connected)&&!e.telegramWhitelistSaving){e.telegramWhitelistSaving=!0,e.telegramWhitelistError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{}),o=s.channels,a=o==null?void 0:o.telegram,r=a==null?void 0:a.accounts,l=r==null?void 0:r[t];if(!l){e.telegramWhitelistError=`Bot "${t}" not found.`;return}if(!Array.isArray(l.allowFrom)){e.telegramWhitelistError="No whitelist entries to remove.";return}const c=n.toLowerCase();l.allowFrom=l.allowFrom.filter(v=>v.toLowerCase()!==c);const d=i.hash;if(!d){e.telegramWhitelistError="Config hash missing; reload and retry.";return}const m=fe(s);await e.client.request("config.set",{raw:m,baseHash:d}),setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramWhitelistError=String(i)}finally{e.telegramWhitelistSaving=!1}}}async function Wc(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=he(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(d=>{const m=d.match;return!m||m.channel!=="whatsapp"?!0:m.accountId!==t}));const l=n.hash;if(!l){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=fe(i);await e.client.request("config.set",{raw:c,baseHash:l}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await Q(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const rg=Object.freeze(Object.defineProperty({__proto__:null,addCloudApiAccount:Mc,addTelegramBot:Bc,addTelegramWhitelistEntry:Oc,addWhatsAppAccount:_c,disconnectTelegram:Lc,loadChannels:Q,logoutWhatsApp:Pc,probeTelegramToken:Ic,removeTelegramBot:Dc,removeTelegramWhitelistEntry:Fc,removeWhatsAppAccount:Wc,saveTelegramToken:Rc,setTelegramAdminRouting:Uc,setTelegramDmPolicy:Nc,startWhatsAppLogin:ma,waitWhatsAppLogin:Tc},Symbol.toStringTag,{value:"Module"}));async function ya(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 va="taskmaster-access-session",zc={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,adminUsername:null,accounts:[],error:null,busy:!1};function Tt(){try{return localStorage.getItem(va)}catch{return null}}function Kc(e){try{localStorage.setItem(va,e)}catch{}}function lg(){try{localStorage.removeItem(va)}catch{}}async function bi(e){if(e.client)try{const t=Tt(),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,adminUsername:n.adminUsername??null,error:null}}catch{e.accessState={...e.accessState,checked:!0,hasPins:!1,hasMasterPin:!1,accounts:[],authenticated:!0,error:null}}}async function cg(e,t,n){if(!e.client){console.warn("[access] verifyPin aborted: no gateway client");return}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?(Kc(i.token),e.accessState={...e.accessState,authenticated:!0,workspace:i.workspace??null,master:i.master??!1,adminUsername:i.adminUsername??null,busy:!1,error:null}):(console.warn("[access] verifyPin: rejected",{message:i.message}),e.accessState={...e.accessState,busy:!1,error:i.message??"Incorrect PIN"})}catch(i){console.error("[access] verifyPin: error",i),e.accessState={...e.accessState,busy:!1,error:"Failed to verify PIN"}}}async function ug(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?(Kc(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 dg(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 pg(e){const t=Tt();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}lg(),e.accessState={...zc,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts,adminUsername:null}}const hg=1e4,gg=new Set(["trace","debug","info","warn","error","fatal"]);function fg(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 mg(e){if(typeof e!="string")return null;const t=e.toLowerCase();return gg.has(t)?t:null}function qc(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=mg((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=fg(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 St(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:Tt()??void 0}),o=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(qc),a=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=a?o:[...e.logsEntries,...o].slice(-hg),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 yg=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:St,parseLogLine:qc},Symbol.toStringTag,{value:"Module"}));const Hc={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:ye,n:Ni,Gx:Or,Gy:Fr,a:Js,d:Ys,h:vg}=Hc,It=32,ba=64,bg=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},pe=(e="")=>{const t=new Error(e);throw bg(t,pe),t},wg=e=>typeof e=="bigint",kg=e=>typeof e=="string",xg=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",gt=(e,t,n="")=>{const i=xg(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}`;pe(a+"expected Uint8Array"+r+", got "+l)}return e},ws=e=>new Uint8Array(e),jc=e=>Uint8Array.from(e),Vc=(e,t)=>e.toString(16).padStart(t,"0"),Gc=e=>Array.from(gt(e)).map(t=>Vc(t,2)).join(""),Ye={_0:48,_9:57,A:65,F:70,a:97,f:102},Wr=e=>{if(e>=Ye._0&&e<=Ye._9)return e-Ye._0;if(e>=Ye.A&&e<=Ye.F)return e-(Ye.A-10);if(e>=Ye.a&&e<=Ye.f)return e-(Ye.a-10)},Qc=e=>{const t="hex invalid";if(!kg(e))return pe(t);const n=e.length,i=n/2;if(n%2)return pe(t);const s=ws(i);for(let o=0,a=0;o<i;o++,a+=2){const r=Wr(e.charCodeAt(a)),l=Wr(e.charCodeAt(a+1));if(r===void 0||l===void 0)return pe(t);s[o]=r*16+l}return s},Jc=()=>globalThis==null?void 0:globalThis.crypto,$g=()=>{var e;return((e=Jc())==null?void 0:e.subtle)??pe("crypto.subtle must be defined, consider polyfill")},Xn=(...e)=>{const t=ws(e.reduce((i,s)=>i+gt(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Sg=(e=It)=>Jc().getRandomValues(ws(e)),Ji=BigInt,wt=(e,t,n,i="bad number: out of range")=>wg(e)&&t<=e&&e<n?e:pe(i),U=(e,t=ye)=>{const n=e%t;return n>=0n?n:t+n},Yc=e=>U(e,Ni),Ag=(e,t)=>{(e===0n||t<=0n)&&pe("no inverse n="+e+" mod="+t);let n=U(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?U(s,t):pe("no inverse")},Cg=e=>{const t=tu[e];return typeof t!="function"&&pe("hashes."+e+" not set"),t},Xs=e=>e instanceof Rt?e:pe("Point expected"),Do=2n**256n,qe=class qe{constructor(t,n,i,s){G(this,"X");G(this,"Y");G(this,"Z");G(this,"T");const o=Do;this.X=wt(t,0n,o),this.Y=wt(n,0n,o),this.Z=wt(i,1n,o),this.T=wt(s,0n,o),Object.freeze(this)}static CURVE(){return Hc}static fromAffine(t){return new qe(t.x,t.y,1n,U(t.x*t.y))}static fromBytes(t,n=!1){const i=Ys,s=jc(gt(t,It)),o=t[31];s[31]=o&-129;const a=Zc(s);wt(a,0n,n?Do:ye);const l=U(a*a),c=U(l-1n),d=U(i*l+1n);let{isValid:m,value:v}=Tg(c,d);m||pe("bad point: y not sqrt");const p=(v&1n)===1n,b=(o&128)!==0;return!n&&v===0n&&b&&pe("bad point: x==0, isLastByteOdd"),b!==p&&(v=U(-v)),new qe(v,a,1n,U(v*a))}static fromHex(t,n){return qe.fromBytes(Qc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Js,n=Ys,i=this;if(i.is0())return pe("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,l=U(s*s),c=U(o*o),d=U(a*a),m=U(d*d),v=U(l*t),p=U(d*U(v+c)),b=U(m+U(n*U(l*c)));if(p!==b)return pe("bad point: equation left != right (1)");const x=U(s*o),C=U(a*r);return x!==C?pe("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:a,Z:r}=Xs(t),l=U(n*r),c=U(o*s),d=U(i*r),m=U(a*s);return l===c&&d===m}is0(){return this.equals(Xt)}negate(){return new qe(U(-this.X),this.Y,this.Z,U(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=Js,o=U(t*t),a=U(n*n),r=U(2n*U(i*i)),l=U(s*o),c=t+n,d=U(U(c*c)-o-a),m=l+a,v=m-r,p=l-a,b=U(d*v),x=U(m*p),C=U(d*p),A=U(v*m);return new qe(b,x,A,C)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:l,T:c}=Xs(t),d=Js,m=Ys,v=U(n*a),p=U(i*r),b=U(o*m*c),x=U(s*l),C=U((n+i)*(a+r)-v-p),A=U(x-b),T=U(x+b),M=U(p-d*v),N=U(C*A),y=U(T*M),k=U(C*M),S=U(A*T);return new qe(N,y,S,k)}subtract(t){return this.add(Xs(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return Xt;if(wt(t,1n,Ni),t===1n)return this;if(this.equals(Lt))return Og(t).p;let i=Xt,s=Lt;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(Xt))return{x:0n,y:1n};const s=Ag(i,ye);U(i*s)!==1n&&pe("invalid inverse");const o=U(t*s),a=U(n*s);return{x:o,y:a}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=Xc(n);return i[31]|=t&1n?128:0,i}toHex(){return Gc(this.toBytes())}clearCofactor(){return this.multiply(Ji(vg),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ni/2n,!1).double();return Ni%2n&&(t=t.add(this)),t.is0()}};G(qe,"BASE"),G(qe,"ZERO");let Rt=qe;const Lt=new Rt(Or,Fr,1n,U(Or*Fr)),Xt=new Rt(0n,1n,1n,0n);Rt.BASE=Lt;Rt.ZERO=Xt;const Xc=e=>Qc(Vc(wt(e,0n,Do),ba)).reverse(),Zc=e=>Ji("0x"+Gc(jc(gt(e)).reverse())),Oe=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ye;return n},Eg=e=>{const n=e*e%ye*e%ye,i=Oe(n,2n)*n%ye,s=Oe(i,1n)*e%ye,o=Oe(s,5n)*s%ye,a=Oe(o,10n)*o%ye,r=Oe(a,20n)*a%ye,l=Oe(r,40n)*r%ye,c=Oe(l,80n)*l%ye,d=Oe(c,80n)*l%ye,m=Oe(d,10n)*o%ye;return{pow_p_5_8:Oe(m,2n)*e%ye,b2:n}},zr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Tg=(e,t)=>{const n=U(t*t*t),i=U(n*n*t),s=Eg(e*i).pow_p_5_8;let o=U(e*n*s);const a=U(t*o*o),r=o,l=U(o*zr),c=a===e,d=a===U(-e),m=a===U(-e*zr);return c&&(o=r),(d||m)&&(o=l),(U(o)&1n)===1n&&(o=U(-o)),{isValid:c||d,value:o}},No=e=>Yc(Zc(e)),wa=(...e)=>tu.sha512Async(Xn(...e)),Pg=(...e)=>Cg("sha512")(Xn(...e)),eu=e=>{const t=e.slice(0,It);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(It,ba),i=No(t),s=Lt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},ka=e=>wa(gt(e,It)).then(eu),_g=e=>eu(Pg(gt(e,It))),Mg=e=>ka(e).then(t=>t.pointBytes),Ig=e=>wa(e.hashable).then(e.finish),Rg=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=No(t),a=Lt.multiply(o).toBytes();return{hashable:Xn(a,i,n),finish:c=>{const d=Yc(o+No(c)*s);return gt(Xn(a,Xc(d)),ba)}}},Lg=async(e,t)=>{const n=gt(e),i=await ka(t),s=await wa(i.prefix,n);return Ig(Rg(i,s,n))},tu={sha512Async:async e=>{const t=$g(),n=Xn(e);return ws(await t.digest("SHA-512",n.buffer))},sha512:void 0},Bg=(e=Sg(It))=>e,Dg={getExtendedPublicKeyAsync:ka,getExtendedPublicKey:_g,randomSecretKey:Bg},Yi=8,Ng=256,nu=Math.ceil(Ng/Yi)+1,Uo=2**(Yi-1),Ug=()=>{const e=[];let t=Lt,n=t;for(let i=0;i<nu;i++){n=t,e.push(n);for(let s=1;s<Uo;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Kr;const qr=(e,t)=>{const n=t.negate();return e?n:t},Og=e=>{const t=Kr||(Kr=Ug());let n=Xt,i=Lt;const s=2**Yi,o=s,a=Ji(s-1),r=Ji(Yi);for(let l=0;l<nu;l++){let c=Number(e&a);e>>=r,c>Uo&&(c-=o,e+=1n);const d=l*Uo,m=d,v=d+Math.abs(c)-1,p=l%2!==0,b=c<0;c===0?i=i.add(qr(p,t[m])):n=n.add(qr(b,t[v]))}return e!==0n&&pe("invalid wnaf"),{p:n,f:i}},Zs="taskmaster-device-identity-v1";function Oo(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function iu(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 Fg(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function su(e){const t=await crypto.subtle.digest("SHA-256",e);return Fg(new Uint8Array(t))}async function Wg(){const e=Dg.randomSecretKey(),t=await Mg(e);return{deviceId:await su(t),publicKey:Oo(t),privateKey:Oo(e)}}async function zg(){try{const n=localStorage.getItem(Zs);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 su(iu(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(Zs,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 Wg(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Zs,JSON.stringify(t)),e}async function Kg(e,t){const n=iu(e),i=new TextEncoder().encode(t),s=await Lg(i,n);return Oo(s)}const ou="taskmaster.device.auth.v1";function xa(e){return e.trim()}function qg(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 $a(){try{const e=window.localStorage.getItem(ou);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 au(e){try{window.localStorage.setItem(ou,JSON.stringify(e))}catch{}}function Hg(e){const t=$a();if(!t||t.deviceId!==e.deviceId)return null;const n=xa(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function jg(e){const t=xa(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=$a();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:qg(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,au(n),s}function Vg(e){const t=$a();if(!t||t.deviceId!==e.deviceId)return;const n=xa(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],au(i)}async function Sa(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 Aa(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 Gg(e){return{method:"exec.approvals.get",params:{}}}async function Qg(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=Gg(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);Jg(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function Jg(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=he(t.file??{}))}async function ru(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 Ee(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function Te(e){return e instanceof Error?e.message:String(e)}function Zn(){return{name:"",skillContent:"",references:[],alwaysActive:!1}}async function Ce(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=Te(n)}finally{e.skillsLoading=!1}}}function lu(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function cu(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 Ce(e),Ee(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=Te(i);e.skillsError=s,Ee(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function uu(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 Ce(e),Ee(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=Te(n);e.skillsError=i,Ee(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function du(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 Ce(e),Ee(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=Te(s);e.skillsError=o,Ee(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function pu(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=Te(n)}}function hu(e){e.skillDetail=null,e.skillDetailTab=""}function gu(e,t){e.skillDetailTab=t}async function fu(e){if(e.skillAddModal=!0,e.skillAddForm=Zn(),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 mu(e){e.skillAddModal=!1,e.skillAddForm=Zn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[]}function yu(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="draft"}async function vu(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="installed",await Ca(e)}async function Ca(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=Zn(),e.skillAddFormSource="draft",e.skillDrafts=[],await Ce(e),Ee(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=Zn(),e.skillAddFormSource="draft",e.skillDrafts=[],Ee(e,i,{kind:"success",message:"Draft saved"}))}catch(n){e.skillsError=Te(n)}finally{e.skillsBusyKey=null}}}async function bu(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=Te(n)}}async function Fo(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=Te(n)}}function wu(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 ku(e,t,n){e.skillAddForm={...e.skillAddForm,references:e.skillAddForm.references.map(i=>i.name===t?{...i,content:n}:i)}}function xu(e,t){e.skillEditTab=t}async function $u(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 Ce(e),Ee(e,t,{kind:"success",message:n?"Skill is now always active":"Skill loads on demand"})}catch(i){e.skillsError=Te(i),Ee(e,t,{kind:"error",message:Te(i)})}finally{e.skillsBusyKey=null}}}async function Su(e){return!e.client||!e.connected?[]:(await e.client.request("tools.list",{})).tools??[]}async function Wo(e,t,n){!e.client||!e.connected||await e.client.request("skills.patch",{name:t,...n})}async function Au(e,t,n,i){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.update",{skillKey:t,agents:n}),i&&n.includes("subagent"),await Ce(e),Ee(e,t,{kind:"success",message:"Agent access updated"})}catch(s){const o=Te(s);e.skillsError=o,Ee(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function Cu(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await Ce(e)}catch(n){e.skillsError=Te(n)}finally{e.skillsBusyKey=null}}}const Yg=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:mu,closeSkillDetail:hu,deleteDraft:bu,deleteSkill:Cu,editDetailSkill:wu,editSkill:Fo,emptyAddForm:Zn,fetchSelectableTools:Su,importDraft:yu,installDraft:vu,installSkill:du,loadSkills:Ce,openAddSkillModal:fu,patchSkillMetadata:Wo,saveNewSkill:Ca,saveSkillApiKey:uu,setEditTab:xu,setSkillDetailTab:gu,toggleAlwaysActive:$u,updateFormReference:ku,updateSkillAgents:Au,updateSkillEdit:lu,updateSkillEnabled:cu,viewSkillDetail:pu},Symbol.toStringTag,{value:"Module"})),Eu={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},Tu=new Map(Object.entries(Eu).map(([e,t])=>[t,e]));function ks(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function ei(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 Xg(e,t=""){const n=ks(t),i=Eu[e];return n?`${n}${i}`:i}function Pu(e,t=""){const n=ks(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=ei(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":Tu.get(s)??null}function Zg(e){let t=ei(e);if(t.endsWith("/index.html")&&(t=ei(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(Tu.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function ef(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Ea(e){return e==="system"?ef():e}const wi=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,tf=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,ki=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},nf=({nextTheme:e,applyTheme:t,context:n,currentTheme:i})=>{var c;if(i===e)return;const s=globalThis.document??null;if(!s){t();return}const o=s.documentElement,a=s,r=tf();if(!!a.startViewTransition&&!r){let d=.5,m=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")d=wi(n.pointerClientX/window.innerWidth),m=wi(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const v=n.element.getBoundingClientRect();v.width>0&&v.height>0&&typeof window<"u"&&(d=wi((v.left+v.width/2)/window.innerWidth),m=wi((v.top+v.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${d*100}%`),o.style.setProperty("--theme-switch-y",`${m*100}%`),o.classList.add("theme-transition");try{const v=(c=a.startViewTransition)==null?void 0:c.call(a,()=>{t()});v!=null&&v.finished?v.finished.finally(()=>ki(o)):ki(o)}catch{ki(o),t()}return}t(),ki(o)},sf=2e3;async function On(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 _u=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:On},Symbol.toStringTag,{value:"Module"}));async function Mu(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 of(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function je(e){return e instanceof Error?e.message:String(e)}let xi=null;function gn(e,t){xi&&clearTimeout(xi),e.filesMessage={kind:"success",text:t},xi=setTimeout(()=>{e.filesMessage=null,xi=null},3e3)}async function fn(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=je(n)}finally{e.filesLoading=!1}}}}async function Iu(e,t,n){e.filesSelectedPaths=new Set([t]),await Ru(e,t,n)}async function af(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 Ru(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function rf(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 Lu(e,o,t),i++}catch(a){s=je(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:gn(e,`${i} file${i!==1?"s":""} downloaded`)}async function lf(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await pf(e,t,o,i)}async function Ru(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=je(i)}finally{e.filesPreviewLoading=!1}}}async function Lu(e,t,n){if(!(!e.client||!e.connected))try{const i={path:t};n&&(i.agentId=n);const s=await e.client.request("files.download",i);if(!(s!=null&&s.base64)){e.filesMessage={kind:"error",text:"Download failed: no data"};return}const o=Uint8Array.from(atob(s.base64),c=>c.charCodeAt(0)),a=new Blob([o]),r=URL.createObjectURL(a),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:je(i)}}}async function cf(e,t,n,i){if(!e.client||!e.connected||n.length===0)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="",a="";for(const r of n)try{const l=await r.arrayBuffer(),c=btoa(new Uint8Array(l).reduce((m,v)=>m+String.fromCharCode(v),"")),d={path:t,name:r.name,data:c};i&&(d.agentId=i),await e.client.request("files.upload",d),s++,a=r.name}catch(l){o=je(l)}if(e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:gn(e,`${s} file${s!==1?"s":""} uploaded`),await fn(e,i),a){const r=t==="."?a:`${t}/${a}`,l=r.split("/");for(let c=1;c<l.length;c++){const d=l.slice(0,c).join("/");e.filesExpandedDirs=new Set([...e.filesExpandedDirs,d])}e.filesCurrentDir=t,await Iu(e,r,i)}}async function uf(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),gn(e,`Created ${s}`),await fn(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:je(o)}}}async function df(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),gn(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await fn(e,n)}catch(i){e.filesMessage={kind:"error",text:je(i)}}}}async function pf(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),gn(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await fn(e,i)}catch(s){e.filesMessage={kind:"error",text:je(s)}}}}async function xs(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 hf(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;gn(e,`Re-indexed: ${s} files, ${o} chunks`),await xs(e,t)}catch(n){e.filesMessage={kind:"error",text:je(n)}}finally{e.filesReindexBusy=!1}}}function gf(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 ff(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:je(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function mf(e){e.filesSearchQuery="",e.filesSearchResults=null}function yf(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{Aa(e,{quiet:!0})},15e3))}function vf(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Xi(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")&&e.logsSubTab!=="session"&&e.logsDate==null&&St(e,{quiet:!0})},5e3))}function Ta(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"||On(e,{quiet:!0,reset:!0})},5e3))}function Pa(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function _a(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&ya(e)},1e4))}function Ma(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function bf(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{Mu(e)},3e4))}function wf(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&&xs(t,t.filesResolvedAgentId)},1e4))}function xf(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function ut(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,ph(n),t.theme!==e.theme&&(e.theme=t.theme,$s(e,Ea(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Bu(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&ut(e,{...e.settings,lastActiveSessionKey:n})}function $f(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&&ut(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,ut(e,{...e.settings,sessionKey:l,lastActiveSessionKey:l}))}if(o!=null){const l=o.trim();l&&l!==e.settings.gatewayUrl&&ut(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 Sf(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?Zi(e):Xi(e):(Ta(e),Pa(e)),t==="debug"?_a(e):Ma(e),es(e),Nu(e,t,!1)}function Af(e,t,n){nf({nextTheme:t,applyTheme:()=>{e.theme=t,ut(e,{...e.settings,theme:t}),$s(e,Ea(t))},context:n,currentTheme:e.theme})}async function es(e){if(e.tab==="overview"&&await Uu(e),e.tab==="channels"&&await If(e),e.tab==="instances"&&await ru(e),e.tab==="cron"&&await Ou(e),e.tab==="skills"&&await Ce(e),e.tab==="nodes"&&(await Aa(e),await Sa(e),await He(e),await Qg(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await Nf(e),pn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await Ac(e),await He(e)),e.tab==="debug"&&(await ya(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await se(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>_u);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await St(e,{reset:!0});Lo(e,!0)}}function Cf(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?ks(e):Zg(window.location.pathname)}function Ef(e){e.theme=e.settings.theme??"system",$s(e,Ea(e.theme))}function $s(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function Tf(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;if(e.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),e.themeMediaHandler=n=>{e.theme==="system"&&$s(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Pf(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 _f(e,t){if(typeof window>"u")return;const n=Pu(window.location.pathname,e.basePath)??"chat";Du(e,n),Nu(e,n,t)}function Mf(e){var s;if(typeof window>"u")return;const t=Pu(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,ut(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),Du(e,t)}function Du(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?Zi(e):Xi(e):(Ta(e),Pa(e)),t==="debug"?_a(e):Ma(e),e.connected&&es(e)}function Nu(e,t,n){if(typeof window>"u")return;const i=ei(Xg(t,e.basePath)),s=ei(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 Uu(e){await Promise.all([Q(e,!1),ru(e),ht(e),hn(e),ya(e)])}async function If(e){await Promise.all([Q(e,!0),Ac(e),He(e)])}async function Ou(e){await Promise.all([Q(e,!1),hn(e),ti(e)])}function Fu(e){return e.chatSending||!!e.chatRunId}function Rf(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 Wu(e){e.connected&&(e.chatMessage="",await wc(e))}function Lf(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:vs(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],pn(e))}async function zu(e,t,n){var s,o;fa(e);const i=await bc(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&&Bu(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),pn(e),i&&!e.chatRunId&&Ku(e),i}async function Ku(e){if(!e.connected||Fu(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await zu(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function Bf(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function Df(e,t,n){var l;if(!e.connected||!((l=e.sessionKey)!=null&&l.trim()))return;if((t??e.chatMessage).trim()==="/new"){e.newSession();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(Rf(s)){await Wu(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],gh(e.selectedWorkspace??"",e.sessionKey)),Fu(e)){Lf(e,s,a);return}await zu(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 Nf(e){var i,s;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,dn);await Promise.all([nn(t,{limit:n}),ht(t),zo(e),(s=e.loadChatSessions)==null?void 0:s.call(e)]),pn(e,!0)}const Uf=Ku;function Of(e){var s,o,a,r;if(e.sessionKey.startsWith("webchat:")){const l=(s=e.sessionKey.split(":")[1])==null?void 0:s.trim();if(l)return l}const t=ha(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(o=e.hello)==null?void 0:o.snapshot;return((r=(a=n==null?void 0:n.sessionDefaults)==null?void 0:a.defaultAgentId)==null?void 0:r.trim())||"main"}function Ff(e,t){const n=ks(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function zo(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=Of(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=Ff(e.basePath,t);try{const i=await fetch(n,{method:"GET"});if(!i.ok){e.chatAvatarUrl=null;return}const s=await i.json(),o=typeof s.avatarUrl=="string"?s.avatarUrl.trim():"";e.chatAvatarUrl=o||null}catch{e.chatAvatarUrl=null}}const E={messageSquare:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:u`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:u`<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:u`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:u`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,chevronLeft:u`<svg viewBox="0 0 24 24"><path d="m15 18-6-6 6-6"/></svg>`,chevronRight:u`<svg viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></svg>`,film:u`<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:u`<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:u`<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:u`<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:u`<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>`,cloud:u`<svg viewBox="0 0 24 24"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>`,plus:u`<svg viewBox="0 0 24 24"><path d="M5 12h14"/><path d="M12 5v14"/></svg>`},Wf=u`<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>`,zf=u`<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>`,Kf=u`<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 Hr=!1;function qf(){Hr||(Hr=!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 Nt(e,t,n){var p;const i=(b,x)=>b===e?u`<span class="sp-page-nav-current">${b}</span>`:u`<a href=${x}>${b}</a>`,s=u`
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 Xh(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 he(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function fe(e){return`${JSON.stringify(e,null,2).trimEnd()}
20
+ `}function bs(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 He(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});eg(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function Ec(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});Zh(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function Zh(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function eg(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?fe(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=fe(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=he(t.config??{}),e.configFormOriginal=he(t.config??{}),e.configRawOriginal=n)}async function tg(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?fe(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 He(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function hn(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 ti(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 Tc(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=Qi(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=Qi(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function ng(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Tc(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 ti(e),await hn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function ig(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 ti(e),await hn(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function sg(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 Bo(e,t.id)}catch(n){e.cronError=String(n),e.cronRunResult={status:"error",error:String(n)}}finally{e.cronBusy=!1}}}function og(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 ag(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 ti(e),await hn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function rg(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 lg(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=Tc(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 ti(e),await hn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Bo(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 Q(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 ma(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 _c(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 Mc(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 Ic(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=he(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 c=s.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const d=fe(o);await e.client.request("config.set",{raw:d,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await Q(e,!0),await ma(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function Rc(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=he(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 c=l.accounts;if(c[s]){e.whatsappAccountError=`Account "${s}" already exists.`;return}const d={name:i,provider:"cloud",phoneNumberId:n.phoneNumberId.trim(),accessToken:n.accessToken.trim(),webhookVerifyToken:n.webhookVerifyToken.trim()};n.businessAccountId.trim()&&(d.businessAccountId=n.businessAccountId.trim()),c[s]=d;const m=o.hash;if(!m){e.whatsappAccountError="Config hash missing; reload and retry.";return}const v=fe(a);await e.client.request("config.set",{raw:v,baseHash:m}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",e.newWhatsAppAccountProvider="baileys",e.newCloudPhoneNumberId="",e.newCloudBusinessAccountId="",e.newCloudAccessToken="",e.newCloudWebhookVerifyToken="",await Q(e,!0)}catch(o){e.whatsappAccountError=String(o)}finally{e.whatsappAccountSaving=!1}}async function Lc(e){var n;if(!e.client||!e.connected||e.telegramProbing)return;const t=e.telegramConnectToken.trim();if(!t){e.telegramError="Please enter a bot token.";return}e.telegramProbing=!0,e.telegramProbeResult=null,e.telegramError=null;try{const i=await e.client.request("channels.probeToken",{channel:"telegram",token:t});e.telegramProbeResult={ok:i.ok,username:((n=i.bot)==null?void 0:n.username)??void 0,error:i.error??void 0},i.ok||(e.telegramError=i.error??"Invalid token.")}catch(i){e.telegramError=String(i),e.telegramProbeResult=null}finally{e.telegramProbing=!1}}async function Bc(e,t){if(!e.client||!e.connected||e.telegramBusy)return;const n=e.telegramConnectToken.trim();if(n){e.telegramBusy=!0,e.telegramError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{});(!s.channels||typeof s.channels!="object")&&(s.channels={});const o=s.channels;(!o.telegram||typeof o.telegram!="object")&&(o.telegram={});const a=o.telegram;t||(a.botToken=n,a.enabled=!0);const r=i.hash;if(!r){e.telegramError="Config hash missing; reload and retry.";return}const l=fe(s);await e.client.request("config.set",{raw:l,baseHash:r}),e.telegramConnectOpen=!1,e.telegramConnectToken="",e.telegramProbeResult=null,setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramError=String(i)}finally{e.telegramBusy=!1}}}async function Dc(e,t){if(!(!e.client||!e.connected)&&!e.telegramBusy){e.telegramBusy=!0,e.telegramError=null;try{await e.client.request("channels.logout",{channel:"telegram",accountId:t}),e.telegramSettingsOpen=!1,setTimeout(()=>{Q(e,!0)},2500)}catch(n){e.telegramError=String(n)}finally{e.telegramBusy=!1}}}async function Nc(e,t,n,i="open",s=!0){if(!e.client||!e.connected||e.telegramBotSaving)return;const o=t.trim(),a=n.trim();if(!o){e.telegramBotError="Bot name is required.";return}if(!a){e.telegramBotError="Bot token is required.";return}const r=a.split(":")[0];if(!r||!/^\d+$/.test(r)){e.telegramBotError="Invalid bot token format.";return}e.telegramBotSaving=!0,e.telegramBotError=null;try{const l=await e.client.request("config.get",{});e.configSnapshot=l;const c=he(l.config??{});(!c.channels||typeof c.channels!="object")&&(c.channels={});const d=c.channels;(!d.telegram||typeof d.telegram!="object")&&(d.telegram={});const m=d.telegram;(!m.accounts||typeof m.accounts!="object")&&(m.accounts={});const v=m.accounts;if(typeof m.botToken=="string"&&Object.keys(v).length===0&&(v.default={name:"Default",botToken:m.botToken,enabled:m.enabled!==!1},delete m.botToken,delete m.enabled),v[r]){e.telegramBotError=`Bot "${r}" already exists.`;return}const p={name:o,botToken:a,enabled:!0,dmPolicy:i,adminRouting:s};!s&&i==="open"&&(p.allowFrom=["*"]),v[r]=p;const b=l.hash;if(!b){e.telegramBotError="Config hash missing; reload and retry.";return}const x=fe(c);await e.client.request("config.set",{raw:x,baseHash:b}),e.telegramAddingBot=!1,e.telegramConnectOpen=!1,e.telegramNewBotName="",e.telegramConnectToken="",e.telegramProbeResult=null,e.telegramError=null,e.telegramBotError=null,setTimeout(()=>{Q(e,!0)},2500)}catch(l){e.telegramBotError=String(l)}finally{e.telegramBotSaving=!1}}async function Uc(e,t){if(!(!e.client||!e.connected)&&!e.telegramBotSaving){e.telegramBotSaving=!0,e.telegramBotError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=he(n.config??{}),s=i.channels,o=s==null?void 0:s.telegram,a=o==null?void 0:o.accounts;if(!a){e.telegramBotError="No bot accounts found in config.";return}if(!a[t]){e.telegramBotError=`Bot "${t}" not found.`;return}if(Object.keys(a).length<=1){e.telegramBotError="Cannot remove the last bot.";return}delete a[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(c=>{const d=c.match;return!d||d.channel!=="telegram"?!0:d.accountId!==t}));const r=n.hash;if(!r){e.telegramBotError="Config hash missing; reload and retry.";return}const l=fe(i);await e.client.request("config.set",{raw:l,baseHash:r}),setTimeout(()=>{Q(e,!0)},2500)}catch(n){e.telegramBotError=String(n)}finally{e.telegramBotSaving=!1}}}async function Oc(e,t,n){if(!(!e.client||!e.connected)&&!e.telegramDmPolicySaving){e.telegramDmPolicySaving=!0;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{}),o=s.channels,a=o==null?void 0:o.telegram,r=a==null?void 0:a.accounts,l=r==null?void 0:r[t];if(!l){e.telegramError=`Bot "${t}" not found.`;return}l.dmPolicy=n,l.adminRouting!==!0&&n==="open"&&(!Array.isArray(l.allowFrom)||!l.allowFrom.includes("*"))&&(l.allowFrom=["*"]);const c=i.hash;if(!c){e.telegramError="Config hash missing; reload and retry.";return}const d=fe(s);await e.client.request("config.set",{raw:d,baseHash:c}),setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramError=String(i)}finally{e.telegramDmPolicySaving=!1}}}async function Fc(e,t,n){if(!(!e.client||!e.connected)&&!e.telegramBotSaving){e.telegramBotSaving=!0,e.telegramBotError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{}),o=s.channels,a=o==null?void 0:o.telegram,r=a==null?void 0:a.accounts,l=r==null?void 0:r[t];if(!l){e.telegramBotError=`Bot "${t}" not found.`;return}l.adminRouting=n,!n&&l.dmPolicy==="open"&&(!Array.isArray(l.allowFrom)||!l.allowFrom.includes("*"))&&(l.allowFrom=["*"]);const c=i.hash;if(!c){e.telegramBotError="Config hash missing; reload and retry.";return}const d=fe(s);await e.client.request("config.set",{raw:d,baseHash:c}),e.telegramBotError=null,setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramBotError=String(i)}finally{e.telegramBotSaving=!1}}}async function Wc(e,t,n){if(!e.client||!e.connected||e.telegramWhitelistSaving)return;let i=n.trim().toLowerCase();if(!i){e.telegramWhitelistError="Username is required.";return}i.startsWith("@")||(i="@"+i);const s=i.slice(1);if(s.length<5||s.length>32){e.telegramWhitelistError="Username must be 5–32 characters (excluding @).";return}e.telegramWhitelistSaving=!0,e.telegramWhitelistError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const a=he(o.config??{}),r=a.channels,l=r==null?void 0:r.telegram,c=l==null?void 0:l.accounts,d=c==null?void 0:c[t];if(!d){e.telegramWhitelistError=`Bot "${t}" not found.`;return}Array.isArray(d.allowFrom)||(d.allowFrom=[]);const m=d.allowFrom;if(m.some(b=>b.toLowerCase()===i)){e.telegramWhitelistError=`"${i}" is already in the whitelist.`;return}m.push(i);const v=o.hash;if(!v){e.telegramWhitelistError="Config hash missing; reload and retry.";return}const p=fe(a);await e.client.request("config.set",{raw:p,baseHash:v}),e.telegramNewWhitelistUsername="",setTimeout(()=>{Q(e,!0)},2500)}catch(o){e.telegramWhitelistError=String(o)}finally{e.telegramWhitelistSaving=!1}}async function zc(e,t,n){if(!(!e.client||!e.connected)&&!e.telegramWhitelistSaving){e.telegramWhitelistSaving=!0,e.telegramWhitelistError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=he(i.config??{}),o=s.channels,a=o==null?void 0:o.telegram,r=a==null?void 0:a.accounts,l=r==null?void 0:r[t];if(!l){e.telegramWhitelistError=`Bot "${t}" not found.`;return}if(!Array.isArray(l.allowFrom)){e.telegramWhitelistError="No whitelist entries to remove.";return}const c=n.toLowerCase();l.allowFrom=l.allowFrom.filter(v=>v.toLowerCase()!==c);const d=i.hash;if(!d){e.telegramWhitelistError="Config hash missing; reload and retry.";return}const m=fe(s);await e.client.request("config.set",{raw:m,baseHash:d}),setTimeout(()=>{Q(e,!0)},2500)}catch(i){e.telegramWhitelistError=String(i)}finally{e.telegramWhitelistSaving=!1}}}async function Kc(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=he(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(d=>{const m=d.match;return!m||m.channel!=="whatsapp"?!0:m.accountId!==t}));const l=n.hash;if(!l){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=fe(i);await e.client.request("config.set",{raw:c,baseHash:l}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await Q(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const cg=Object.freeze(Object.defineProperty({__proto__:null,addCloudApiAccount:Rc,addTelegramBot:Nc,addTelegramWhitelistEntry:Wc,addWhatsAppAccount:Ic,disconnectTelegram:Dc,loadChannels:Q,logoutWhatsApp:Mc,probeTelegramToken:Lc,removeTelegramBot:Uc,removeTelegramWhitelistEntry:zc,removeWhatsAppAccount:Kc,saveTelegramToken:Bc,setTelegramAdminRouting:Fc,setTelegramDmPolicy:Oc,startWhatsAppLogin:ma,waitWhatsAppLogin:_c},Symbol.toStringTag,{value:"Module"}));async function ya(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 va="taskmaster-access-session",qc={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,adminUsername:null,accounts:[],error:null,busy:!1};function Tt(){try{return localStorage.getItem(va)}catch{return null}}function Hc(e){try{localStorage.setItem(va,e)}catch{}}function ug(){try{localStorage.removeItem(va)}catch{}}async function bi(e){if(e.client)try{const t=Tt(),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,adminUsername:n.adminUsername??null,error:null}}catch{e.accessState={...e.accessState,checked:!0,hasPins:!1,hasMasterPin:!1,accounts:[],authenticated:!0,error:null}}}async function dg(e,t,n){if(!e.client){console.warn("[access] verifyPin aborted: no gateway client");return}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?(Hc(i.token),e.accessState={...e.accessState,authenticated:!0,workspace:i.workspace??null,master:i.master??!1,adminUsername:i.adminUsername??null,busy:!1,error:null}):(console.warn("[access] verifyPin: rejected",{message:i.message}),e.accessState={...e.accessState,busy:!1,error:i.message??"Incorrect PIN"})}catch(i){console.error("[access] verifyPin: error",i),e.accessState={...e.accessState,busy:!1,error:"Failed to verify PIN"}}}async function pg(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?(Hc(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 hg(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 gg(e){const t=Tt();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}ug(),e.accessState={...qc,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts,adminUsername:null}}const fg=1e4,mg=new Set(["trace","debug","info","warn","error","fatal"]);function yg(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 vg(e){if(typeof e!="string")return null;const t=e.toLowerCase();return mg.has(t)?t:null}function jc(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=vg((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=yg(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 St(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:Tt()??void 0}),o=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(jc),a=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=a?o:[...e.logsEntries,...o].slice(-fg),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 bg=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:St,parseLogLine:jc},Symbol.toStringTag,{value:"Module"}));const Vc={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:ye,n:Ni,Gx:Or,Gy:Fr,a:Js,d:Ys,h:wg}=Vc,It=32,ba=64,kg=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},pe=(e="")=>{const t=new Error(e);throw kg(t,pe),t},xg=e=>typeof e=="bigint",$g=e=>typeof e=="string",Sg=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",gt=(e,t,n="")=>{const i=Sg(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}`;pe(a+"expected Uint8Array"+r+", got "+l)}return e},ws=e=>new Uint8Array(e),Gc=e=>Uint8Array.from(e),Qc=(e,t)=>e.toString(16).padStart(t,"0"),Jc=e=>Array.from(gt(e)).map(t=>Qc(t,2)).join(""),Ye={_0:48,_9:57,A:65,F:70,a:97,f:102},Wr=e=>{if(e>=Ye._0&&e<=Ye._9)return e-Ye._0;if(e>=Ye.A&&e<=Ye.F)return e-(Ye.A-10);if(e>=Ye.a&&e<=Ye.f)return e-(Ye.a-10)},Yc=e=>{const t="hex invalid";if(!$g(e))return pe(t);const n=e.length,i=n/2;if(n%2)return pe(t);const s=ws(i);for(let o=0,a=0;o<i;o++,a+=2){const r=Wr(e.charCodeAt(a)),l=Wr(e.charCodeAt(a+1));if(r===void 0||l===void 0)return pe(t);s[o]=r*16+l}return s},Xc=()=>globalThis==null?void 0:globalThis.crypto,Ag=()=>{var e;return((e=Xc())==null?void 0:e.subtle)??pe("crypto.subtle must be defined, consider polyfill")},Xn=(...e)=>{const t=ws(e.reduce((i,s)=>i+gt(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Cg=(e=It)=>Xc().getRandomValues(ws(e)),Ji=BigInt,wt=(e,t,n,i="bad number: out of range")=>xg(e)&&t<=e&&e<n?e:pe(i),U=(e,t=ye)=>{const n=e%t;return n>=0n?n:t+n},Zc=e=>U(e,Ni),Eg=(e,t)=>{(e===0n||t<=0n)&&pe("no inverse n="+e+" mod="+t);let n=U(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?U(s,t):pe("no inverse")},Tg=e=>{const t=iu[e];return typeof t!="function"&&pe("hashes."+e+" not set"),t},Xs=e=>e instanceof Rt?e:pe("Point expected"),Do=2n**256n,qe=class qe{constructor(t,n,i,s){G(this,"X");G(this,"Y");G(this,"Z");G(this,"T");const o=Do;this.X=wt(t,0n,o),this.Y=wt(n,0n,o),this.Z=wt(i,1n,o),this.T=wt(s,0n,o),Object.freeze(this)}static CURVE(){return Vc}static fromAffine(t){return new qe(t.x,t.y,1n,U(t.x*t.y))}static fromBytes(t,n=!1){const i=Ys,s=Gc(gt(t,It)),o=t[31];s[31]=o&-129;const a=tu(s);wt(a,0n,n?Do:ye);const l=U(a*a),c=U(l-1n),d=U(i*l+1n);let{isValid:m,value:v}=_g(c,d);m||pe("bad point: y not sqrt");const p=(v&1n)===1n,b=(o&128)!==0;return!n&&v===0n&&b&&pe("bad point: x==0, isLastByteOdd"),b!==p&&(v=U(-v)),new qe(v,a,1n,U(v*a))}static fromHex(t,n){return qe.fromBytes(Yc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Js,n=Ys,i=this;if(i.is0())return pe("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,l=U(s*s),c=U(o*o),d=U(a*a),m=U(d*d),v=U(l*t),p=U(d*U(v+c)),b=U(m+U(n*U(l*c)));if(p!==b)return pe("bad point: equation left != right (1)");const x=U(s*o),C=U(a*r);return x!==C?pe("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:a,Z:r}=Xs(t),l=U(n*r),c=U(o*s),d=U(i*r),m=U(a*s);return l===c&&d===m}is0(){return this.equals(Xt)}negate(){return new qe(U(-this.X),this.Y,this.Z,U(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=Js,o=U(t*t),a=U(n*n),r=U(2n*U(i*i)),l=U(s*o),c=t+n,d=U(U(c*c)-o-a),m=l+a,v=m-r,p=l-a,b=U(d*v),x=U(m*p),C=U(d*p),A=U(v*m);return new qe(b,x,A,C)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:l,T:c}=Xs(t),d=Js,m=Ys,v=U(n*a),p=U(i*r),b=U(o*m*c),x=U(s*l),C=U((n+i)*(a+r)-v-p),A=U(x-b),T=U(x+b),M=U(p-d*v),N=U(C*A),y=U(T*M),k=U(C*M),S=U(A*T);return new qe(N,y,S,k)}subtract(t){return this.add(Xs(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return Xt;if(wt(t,1n,Ni),t===1n)return this;if(this.equals(Lt))return Wg(t).p;let i=Xt,s=Lt;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(Xt))return{x:0n,y:1n};const s=Eg(i,ye);U(i*s)!==1n&&pe("invalid inverse");const o=U(t*s),a=U(n*s);return{x:o,y:a}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=eu(n);return i[31]|=t&1n?128:0,i}toHex(){return Jc(this.toBytes())}clearCofactor(){return this.multiply(Ji(wg),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ni/2n,!1).double();return Ni%2n&&(t=t.add(this)),t.is0()}};G(qe,"BASE"),G(qe,"ZERO");let Rt=qe;const Lt=new Rt(Or,Fr,1n,U(Or*Fr)),Xt=new Rt(0n,1n,1n,0n);Rt.BASE=Lt;Rt.ZERO=Xt;const eu=e=>Yc(Qc(wt(e,0n,Do),ba)).reverse(),tu=e=>Ji("0x"+Jc(Gc(gt(e)).reverse())),Oe=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ye;return n},Pg=e=>{const n=e*e%ye*e%ye,i=Oe(n,2n)*n%ye,s=Oe(i,1n)*e%ye,o=Oe(s,5n)*s%ye,a=Oe(o,10n)*o%ye,r=Oe(a,20n)*a%ye,l=Oe(r,40n)*r%ye,c=Oe(l,80n)*l%ye,d=Oe(c,80n)*l%ye,m=Oe(d,10n)*o%ye;return{pow_p_5_8:Oe(m,2n)*e%ye,b2:n}},zr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,_g=(e,t)=>{const n=U(t*t*t),i=U(n*n*t),s=Pg(e*i).pow_p_5_8;let o=U(e*n*s);const a=U(t*o*o),r=o,l=U(o*zr),c=a===e,d=a===U(-e),m=a===U(-e*zr);return c&&(o=r),(d||m)&&(o=l),(U(o)&1n)===1n&&(o=U(-o)),{isValid:c||d,value:o}},No=e=>Zc(tu(e)),wa=(...e)=>iu.sha512Async(Xn(...e)),Mg=(...e)=>Tg("sha512")(Xn(...e)),nu=e=>{const t=e.slice(0,It);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(It,ba),i=No(t),s=Lt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},ka=e=>wa(gt(e,It)).then(nu),Ig=e=>nu(Mg(gt(e,It))),Rg=e=>ka(e).then(t=>t.pointBytes),Lg=e=>wa(e.hashable).then(e.finish),Bg=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=No(t),a=Lt.multiply(o).toBytes();return{hashable:Xn(a,i,n),finish:c=>{const d=Zc(o+No(c)*s);return gt(Xn(a,eu(d)),ba)}}},Dg=async(e,t)=>{const n=gt(e),i=await ka(t),s=await wa(i.prefix,n);return Lg(Bg(i,s,n))},iu={sha512Async:async e=>{const t=Ag(),n=Xn(e);return ws(await t.digest("SHA-512",n.buffer))},sha512:void 0},Ng=(e=Cg(It))=>e,Ug={getExtendedPublicKeyAsync:ka,getExtendedPublicKey:Ig,randomSecretKey:Ng},Yi=8,Og=256,su=Math.ceil(Og/Yi)+1,Uo=2**(Yi-1),Fg=()=>{const e=[];let t=Lt,n=t;for(let i=0;i<su;i++){n=t,e.push(n);for(let s=1;s<Uo;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Kr;const qr=(e,t)=>{const n=t.negate();return e?n:t},Wg=e=>{const t=Kr||(Kr=Fg());let n=Xt,i=Lt;const s=2**Yi,o=s,a=Ji(s-1),r=Ji(Yi);for(let l=0;l<su;l++){let c=Number(e&a);e>>=r,c>Uo&&(c-=o,e+=1n);const d=l*Uo,m=d,v=d+Math.abs(c)-1,p=l%2!==0,b=c<0;c===0?i=i.add(qr(p,t[m])):n=n.add(qr(b,t[v]))}return e!==0n&&pe("invalid wnaf"),{p:n,f:i}},Zs="taskmaster-device-identity-v1";function Oo(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function ou(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 zg(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function au(e){const t=await crypto.subtle.digest("SHA-256",e);return zg(new Uint8Array(t))}async function Kg(){const e=Ug.randomSecretKey(),t=await Rg(e);return{deviceId:await au(t),publicKey:Oo(t),privateKey:Oo(e)}}async function qg(){try{const n=localStorage.getItem(Zs);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 au(ou(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(Zs,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 Kg(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Zs,JSON.stringify(t)),e}async function Hg(e,t){const n=ou(e),i=new TextEncoder().encode(t),s=await Dg(i,n);return Oo(s)}const ru="taskmaster.device.auth.v1";function xa(e){return e.trim()}function jg(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 $a(){try{const e=window.localStorage.getItem(ru);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 lu(e){try{window.localStorage.setItem(ru,JSON.stringify(e))}catch{}}function Vg(e){const t=$a();if(!t||t.deviceId!==e.deviceId)return null;const n=xa(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function Gg(e){const t=xa(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=$a();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:jg(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,lu(n),s}function Qg(e){const t=$a();if(!t||t.deviceId!==e.deviceId)return;const n=xa(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],lu(i)}async function Sa(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 Aa(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 Jg(e){return{method:"exec.approvals.get",params:{}}}async function Yg(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=Jg(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);Xg(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function Xg(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=he(t.file??{}))}async function cu(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 Ee(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function Te(e){return e instanceof Error?e.message:String(e)}function Zn(){return{name:"",skillContent:"",references:[],alwaysActive:!1}}async function Ce(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=Te(n)}finally{e.skillsLoading=!1}}}function uu(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function du(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 Ce(e),Ee(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=Te(i);e.skillsError=s,Ee(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function pu(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 Ce(e),Ee(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=Te(n);e.skillsError=i,Ee(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function hu(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 Ce(e),Ee(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=Te(s);e.skillsError=o,Ee(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function gu(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=Te(n)}}function fu(e){e.skillDetail=null,e.skillDetailTab=""}function mu(e,t){e.skillDetailTab=t}async function yu(e){if(e.skillAddModal=!0,e.skillAddForm=Zn(),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 vu(e){e.skillAddModal=!1,e.skillAddForm=Zn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[]}function bu(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="draft"}async function wu(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n})),alwaysActive:!1},e.skillAddFormSource="installed",await Ca(e)}async function Ca(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=Zn(),e.skillAddFormSource="draft",e.skillDrafts=[],await Ce(e),Ee(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=Zn(),e.skillAddFormSource="draft",e.skillDrafts=[],Ee(e,i,{kind:"success",message:"Draft saved"}))}catch(n){e.skillsError=Te(n)}finally{e.skillsBusyKey=null}}}async function ku(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=Te(n)}}async function Fo(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=Te(n)}}function xu(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 $u(e,t,n){e.skillAddForm={...e.skillAddForm,references:e.skillAddForm.references.map(i=>i.name===t?{...i,content:n}:i)}}function Su(e,t){e.skillEditTab=t}async function Au(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 Ce(e),Ee(e,t,{kind:"success",message:n?"Skill is now always active":"Skill loads on demand"})}catch(i){e.skillsError=Te(i),Ee(e,t,{kind:"error",message:Te(i)})}finally{e.skillsBusyKey=null}}}async function Cu(e){return!e.client||!e.connected?[]:(await e.client.request("tools.list",{})).tools??[]}async function Wo(e,t,n){!e.client||!e.connected||await e.client.request("skills.patch",{name:t,...n})}async function Eu(e,t,n,i){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.update",{skillKey:t,agents:n}),i&&n.includes("subagent"),await Ce(e),Ee(e,t,{kind:"success",message:"Agent access updated"})}catch(s){const o=Te(s);e.skillsError=o,Ee(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function Tu(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await Ce(e)}catch(n){e.skillsError=Te(n)}finally{e.skillsBusyKey=null}}}const Zg=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:vu,closeSkillDetail:fu,deleteDraft:ku,deleteSkill:Tu,editDetailSkill:xu,editSkill:Fo,emptyAddForm:Zn,fetchSelectableTools:Cu,importDraft:bu,installDraft:wu,installSkill:hu,loadSkills:Ce,openAddSkillModal:yu,patchSkillMetadata:Wo,saveNewSkill:Ca,saveSkillApiKey:pu,setEditTab:Su,setSkillDetailTab:mu,toggleAlwaysActive:Au,updateFormReference:$u,updateSkillAgents:Eu,updateSkillEdit:uu,updateSkillEnabled:du,viewSkillDetail:gu},Symbol.toStringTag,{value:"Module"})),Pu={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},_u=new Map(Object.entries(Pu).map(([e,t])=>[t,e]));function ks(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function ei(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 ef(e,t=""){const n=ks(t),i=Pu[e];return n?`${n}${i}`:i}function Mu(e,t=""){const n=ks(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=ei(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":_u.get(s)??null}function tf(e){let t=ei(e);if(t.endsWith("/index.html")&&(t=ei(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(_u.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function nf(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Ea(e){return e==="system"?nf():e}const wi=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,sf=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,ki=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},of=({nextTheme:e,applyTheme:t,context:n,currentTheme:i})=>{var c;if(i===e)return;const s=globalThis.document??null;if(!s){t();return}const o=s.documentElement,a=s,r=sf();if(!!a.startViewTransition&&!r){let d=.5,m=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")d=wi(n.pointerClientX/window.innerWidth),m=wi(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const v=n.element.getBoundingClientRect();v.width>0&&v.height>0&&typeof window<"u"&&(d=wi((v.left+v.width/2)/window.innerWidth),m=wi((v.top+v.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${d*100}%`),o.style.setProperty("--theme-switch-y",`${m*100}%`),o.classList.add("theme-transition");try{const v=(c=a.startViewTransition)==null?void 0:c.call(a,()=>{t()});v!=null&&v.finished?v.finished.finally(()=>ki(o)):ki(o)}catch{ki(o),t()}return}t(),ki(o)},af=2e3;async function On(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 Iu=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:On},Symbol.toStringTag,{value:"Module"}));async function Ru(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 rf(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function je(e){return e instanceof Error?e.message:String(e)}let xi=null;function gn(e,t){xi&&clearTimeout(xi),e.filesMessage={kind:"success",text:t},xi=setTimeout(()=>{e.filesMessage=null,xi=null},3e3)}async function fn(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=je(n)}finally{e.filesLoading=!1}}}}async function Lu(e,t,n){e.filesSelectedPaths=new Set([t]),await Bu(e,t,n)}async function lf(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 Bu(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function cf(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 Du(e,o,t),i++}catch(a){s=je(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:gn(e,`${i} file${i!==1?"s":""} downloaded`)}async function uf(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await gf(e,t,o,i)}async function Bu(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=je(i)}finally{e.filesPreviewLoading=!1}}}async function Du(e,t,n){if(!(!e.client||!e.connected))try{const i={path:t};n&&(i.agentId=n);const s=await e.client.request("files.download",i);if(!(s!=null&&s.base64)){e.filesMessage={kind:"error",text:"Download failed: no data"};return}const o=Uint8Array.from(atob(s.base64),c=>c.charCodeAt(0)),a=new Blob([o]),r=URL.createObjectURL(a),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:je(i)}}}async function df(e,t,n,i){if(!e.client||!e.connected||n.length===0)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="",a="";for(const r of n)try{const l=await r.arrayBuffer(),c=btoa(new Uint8Array(l).reduce((m,v)=>m+String.fromCharCode(v),"")),d={path:t,name:r.name,data:c};i&&(d.agentId=i),await e.client.request("files.upload",d),s++,a=r.name}catch(l){o=je(l)}if(e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:gn(e,`${s} file${s!==1?"s":""} uploaded`),await fn(e,i),a){const r=t==="."?a:`${t}/${a}`,l=r.split("/");for(let c=1;c<l.length;c++){const d=l.slice(0,c).join("/");e.filesExpandedDirs=new Set([...e.filesExpandedDirs,d])}e.filesCurrentDir=t,await Lu(e,r,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),gn(e,`Created ${s}`),await fn(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:je(o)}}}async function hf(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),gn(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await fn(e,n)}catch(i){e.filesMessage={kind:"error",text:je(i)}}}}async function gf(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),gn(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await fn(e,i)}catch(s){e.filesMessage={kind:"error",text:je(s)}}}}async function xs(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 ff(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;gn(e,`Re-indexed: ${s} files, ${o} chunks`),await xs(e,t)}catch(n){e.filesMessage={kind:"error",text:je(n)}}finally{e.filesReindexBusy=!1}}}function mf(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 yf(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:je(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function vf(e){e.filesSearchQuery="",e.filesSearchResults=null}function bf(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{Aa(e,{quiet:!0})},15e3))}function wf(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Xi(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")&&e.logsSubTab!=="session"&&e.logsDate==null&&St(e,{quiet:!0})},5e3))}function Ta(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"||On(e,{quiet:!0,reset:!0})},5e3))}function Pa(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function _a(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&ya(e)},1e4))}function Ma(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function kf(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{Ru(e)},3e4))}function xf(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function $f(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{const t=e;t.filesPage&&xs(t,t.filesResolvedAgentId)},1e4))}function Sf(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function ut(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,gh(n),t.theme!==e.theme&&(e.theme=t.theme,$s(e,Ea(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Nu(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&ut(e,{...e.settings,lastActiveSessionKey:n})}function Af(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&&ut(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,ut(e,{...e.settings,sessionKey:l,lastActiveSessionKey:l}))}if(o!=null){const l=o.trim();l&&l!==e.settings.gatewayUrl&&ut(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 Cf(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?Zi(e):Xi(e):(Ta(e),Pa(e)),t==="debug"?_a(e):Ma(e),es(e),Ou(e,t,!1)}function Ef(e,t,n){of({nextTheme:t,applyTheme:()=>{e.theme=t,ut(e,{...e.settings,theme:t}),$s(e,Ea(t))},context:n,currentTheme:e.theme})}async function es(e){if(e.tab==="overview"&&await Fu(e),e.tab==="channels"&&await Lf(e),e.tab==="instances"&&await cu(e),e.tab==="cron"&&await Wu(e),e.tab==="skills"&&await Ce(e),e.tab==="nodes"&&(await Aa(e),await Sa(e),await He(e),await Yg(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await Of(e),pn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await Ec(e),await He(e)),e.tab==="debug"&&(await ya(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await se(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>Iu);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await St(e,{reset:!0});Lo(e,!0)}}function Tf(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?ks(e):tf(window.location.pathname)}function Pf(e){e.theme=e.settings.theme??"system",$s(e,Ea(e.theme))}function $s(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function _f(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"&&$s(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Mf(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 If(e,t){if(typeof window>"u")return;const n=Mu(window.location.pathname,e.basePath)??"chat";Uu(e,n),Ou(e,n,t)}function Rf(e){var s;if(typeof window>"u")return;const t=Mu(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,ut(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),Uu(e,t)}function Uu(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?Zi(e):Xi(e):(Ta(e),Pa(e)),t==="debug"?_a(e):Ma(e),e.connected&&es(e)}function Ou(e,t,n){if(typeof window>"u")return;const i=ei(ef(t,e.basePath)),s=ei(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 Fu(e){await Promise.all([Q(e,!1),cu(e),ht(e),hn(e),ya(e)])}async function Lf(e){await Promise.all([Q(e,!0),Ec(e),He(e)])}async function Wu(e){await Promise.all([Q(e,!1),hn(e),ti(e)])}function zu(e){return e.chatSending||!!e.chatRunId}function Bf(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 Ku(e){e.connected&&(e.chatMessage="",await xc(e))}function Df(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:vs(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],pn(e))}async function qu(e,t,n){var s,o;fa(e);const i=await kc(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&&Nu(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),pn(e),i&&!e.chatRunId&&Hu(e),i}async function Hu(e){if(!e.connected||zu(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await qu(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function Nf(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function Uf(e,t,n){var l;if(!e.connected||!((l=e.sessionKey)!=null&&l.trim()))return;if((t??e.chatMessage).trim()==="/new"){e.newSession();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(Bf(s)){await Ku(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],mh(e.selectedWorkspace??"",e.sessionKey)),zu(e)){Df(e,s,a);return}await qu(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 Of(e){var i,s;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,dn);await Promise.all([nn(t,{limit:n}),ht(t),zo(e),(s=e.loadChatSessions)==null?void 0:s.call(e)]),pn(e,!0)}const Ff=Hu;function Wf(e){var s,o,a,r;if(e.sessionKey.startsWith("webchat:")){const l=(s=e.sessionKey.split(":")[1])==null?void 0:s.trim();if(l)return l}const t=ha(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(o=e.hello)==null?void 0:o.snapshot;return((r=(a=n==null?void 0:n.sessionDefaults)==null?void 0:a.defaultAgentId)==null?void 0:r.trim())||"main"}function zf(e,t){const n=ks(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function zo(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=Wf(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=zf(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 E={messageSquare:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:u`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:u`<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:u`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:u`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:u`<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:u`<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:u`<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:u`<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:u`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,chevronLeft:u`<svg viewBox="0 0 24 24"><path d="m15 18-6-6 6-6"/></svg>`,chevronRight:u`<svg viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></svg>`,film:u`<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:u`<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:u`<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:u`<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:u`<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>`,cloud:u`<svg viewBox="0 0 24 24"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>`,plus:u`<svg viewBox="0 0 24 24"><path d="M5 12h14"/><path d="M12 5v14"/></svg>`},Kf=u`<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>`,qf=u`<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>`,Hf=u`<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 Hr=!1;function jf(){Hr||(Hr=!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 Nt(e,t,n){var p;const i=(b,x)=>b===e?u`<span class="sp-page-nav-current">${b}</span>`:u`<a href=${x}>${b}</a>`,s=u`
21
21
  ${i("Setup","/setup")}
22
22
  ${i("Chat","/chat")}
23
23
  ${i("Admins","/admins")}
@@ -25,10 +25,10 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
25
25
  ${i("Files","/files")}
26
26
  ${i("Browser","/browser")}
27
27
  ${i("Advanced","/advanced")}
28
- `,a=t&&(t.isMaster!==!1||!t.hasPins)?jf(t):w,r=t!=null&&t.loggedInAs?u`<span class="nav-user-label">${t.loggedInAs}</span>`:w,l=t!=null&&t.hasPins&&t.onLogout?u`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${Wf}</button>`:w,c=t!=null&&t.onRestartGateway?Hf(t.onRestartGateway):w,d=(t==null?void 0:t.auditCount)??0,m=d>0&&(t!=null&&t.onAuditClick)?u`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
- ${zf}
28
+ `,a=t&&(t.isMaster!==!1||!t.hasPins)?Gf(t):w,r=t!=null&&t.loggedInAs?u`<span class="nav-user-label">${t.loggedInAs}</span>`:w,l=t!=null&&t.hasPins&&t.onLogout?u`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${Kf}</button>`:w,c=t!=null&&t.onRestartGateway?Vf(t.onRestartGateway):w,d=(t==null?void 0:t.auditCount)??0,m=d>0&&(t!=null&&t.onAuditClick)?u`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
+ ${qf}
30
30
  <span class="nav-audit-badge">${d>99?"99+":d}</span>
31
- </button>`:w,v=()=>{const b=document.getElementById("nav-burger-toggle");b&&(b.checked=!1)};return qf(),u`
31
+ </button>`:w,v=()=>{const b=document.getElementById("nav-burger-toggle");b&&(b.checked=!1)};return jf(),u`
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">
@@ -53,10 +53,10 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
53
53
  ${n??w}
54
54
  </nav>
55
55
  </div>
56
- `}function Hf(e){let t=!1;return u`
56
+ `}function Vf(e){let t=!1;return u`
57
57
  <span class="nav-restart-container" style="position: relative;">
58
58
  <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">
59
- ${Kf}
59
+ ${Hf}
60
60
  </button>
61
61
  <div class="nav-restart-confirm" style="display: none;">
62
62
  <p>Restart the gateway?</p>
@@ -66,7 +66,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
66
66
  </div>
67
67
  </div>
68
68
  </span>
69
- `}function jf(e){const{workspaces:t,selectedWorkspace:n,onWorkspaceSelect:i}=e;return u`
69
+ `}function Gf(e){const{workspaces:t,selectedWorkspace:n,onWorkspaceSelect:i}=e;return u`
70
70
  <select
71
71
  class="sp-workspace-selector"
72
72
  .value=${n??""}
@@ -80,7 +80,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
80
80
  <option disabled>───</option>
81
81
  <option value="__add__">+ Add Account</option>
82
82
  </select>
83
- `}function Vf(e){return e.connected?e.fullscreen&&e.active?u`
83
+ `}function Qf(e){return e.connected?e.fullscreen&&e.active?u`
84
84
  <div class="sp-fullscreen-overlay">
85
85
  <div class="sp-fullscreen-toolbar">
86
86
  <button
@@ -212,14 +212,14 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
212
212
  <p>Connecting to gateway...</p>
213
213
  </div>
214
214
  </div>
215
- `}const ts="application/x-taskmaster-file-path",qu=".md,.txt,.csv,.tsv,.json,.yaml,.yml,.toml,.ini,.cfg,.conf,.log,.env,.xml,.svg,.html,.css,.js,.ts,.jsx,.tsx,.sh,.bash,.zsh,.fish,.ps1,.bat,.cmd,.py,.rb,.go,.rs,.java,.c,.cpp,.h,.pdf,.gitignore,.makefile,.dockerfile",Hu=new Set(qu.split(","));let vt=null;function ju(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Vu(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function Gf(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(ts);if(i){Vu(i)!==t&&n.onMoveToDir(i,t);return}const s=(a=e.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=[],l=[];for(const c of Array.from(s)){const d=c.name.includes(".")?`.${c.name.split(".").pop().toLowerCase()}`:"";Hu.has(d)?r.push(c):l.push(c.name)}l.length>0&&alert(`Unsupported file type${l.length>1?"s":""}: ${l.join(", ")}`),r.length>0&&n.onUpload(t,r)}}function Gu(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?u`
215
+ `}const ts="application/x-taskmaster-file-path",ju=".md,.txt,.csv,.tsv,.json,.yaml,.yml,.toml,.ini,.cfg,.conf,.log,.env,.xml,.svg,.html,.css,.js,.ts,.jsx,.tsx,.sh,.bash,.zsh,.fish,.ps1,.bat,.cmd,.py,.rb,.go,.rs,.java,.c,.cpp,.h,.pdf,.gitignore,.makefile,.dockerfile",Vu=new Set(ju.split(","));let vt=null;function Gu(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Qu(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function Jf(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(ts);if(i){Qu(i)!==t&&n.onMoveToDir(i,t);return}const s=(a=e.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=[],l=[];for(const c of Array.from(s)){const d=c.name.includes(".")?`.${c.name.split(".").pop().toLowerCase()}`:"";Vu.has(d)?r.push(c):l.push(c.name)}l.length>0&&alert(`Unsupported file type${l.length>1?"s":""}: ${l.join(", ")}`),r.length>0&&n.onUpload(t,r)}}function Ju(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?u`
216
216
  <div
217
217
  class="sp-tree-item sp-tree-dir ${s?"expanded":""} ${a?"current":""}"
218
218
  style="padding-left: ${r}px;"
219
219
  @click=${()=>t.onToggleDir(e.path)}
220
220
  @dragover=${c=>{c.preventDefault(),c.stopPropagation(),c.dataTransfer&&(c.dataTransfer.dropEffect="move"),c.currentTarget.classList.add("sp-drop-target")}}
221
221
  @dragleave=${c=>{c.currentTarget.classList.remove("sp-drop-target")}}
222
- @drop=${c=>Gf(c,e.path,t)}
222
+ @drop=${c=>Jf(c,e.path,t)}
223
223
  >
224
224
  <span class="sp-tree-chevron">${s?"−":"+"}</span>
225
225
  <span class="sp-tree-icon">${E.folder}</span>
@@ -230,7 +230,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
230
230
  @click=${c=>{c.stopPropagation(),t.onDelete(e.path)}}
231
231
  >×</span>`:w}
232
232
  </div>
233
- ${s&&e.children?e.children.map(c=>Gu(c,t,n+1)):w}
233
+ ${s&&e.children?e.children.map(c=>Ju(c,t,n+1)):w}
234
234
  `:u`
235
235
  <div
236
236
  class="sp-tree-item sp-tree-file ${o?"selected":""}"
@@ -241,9 +241,9 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
241
241
  >
242
242
  <span class="sp-tree-icon">${E.fileText}</span>
243
243
  <span class="sp-tree-name">${e.name}</span>
244
- <span class="sp-tree-size">${ju(e.size)}</span>
244
+ <span class="sp-tree-size">${Gu(e.size)}</span>
245
245
  </div>
246
- `}function Qf(e){const t=e.selectedPaths.size;return t<2?w:u`
246
+ `}function Yf(e){const t=e.selectedPaths.size;return t<2?w:u`
247
247
  <div class="sp-bulk-actions">
248
248
  <span style="color: var(--tasker-muted-grey); font-size: 13px;">${t} files selected</span>
249
249
  <button
@@ -254,7 +254,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
254
254
  Download ${t} files
255
255
  </button>
256
256
  </div>
257
- `}function Jf(e){if(e.selectedPaths.size!==1||!e.selectedPath)return w;if(e.previewLoading)return u`
257
+ `}function Xf(e){if(e.selectedPaths.size!==1||!e.selectedPath)return w;if(e.previewLoading)return u`
258
258
  <div class="sp-file-preview">
259
259
  <div class="setup-spinner" style="width: 32px; height: 32px; margin: 24px auto;"></div>
260
260
  </div>
@@ -264,7 +264,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
264
264
  <div>
265
265
  <strong>${t}</strong>
266
266
  <div class="sp-file-preview-meta">
267
- ${e.selectedPath}${e.previewSize!=null?` — ${ju(e.previewSize)}`:""}
267
+ ${e.selectedPath}${e.previewSize!=null?` — ${Gu(e.previewSize)}`:""}
268
268
  </div>
269
269
  </div>
270
270
  <div class="sp-file-actions">
@@ -278,7 +278,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
278
278
  </div>
279
279
  ${e.previewBinary?u`<div class="sp-file-preview-body"><p style="color: var(--tasker-muted-grey);">Binary file — use Download to view.</p></div>`:e.previewContent!=null?u`<div class="sp-file-preview-body"><pre class="sp-file-code">${e.previewContent}</pre></div>`:u`<div class="sp-file-preview-body"><p style="color: var(--tasker-muted-grey);">File too large for preview — use Download.</p></div>`}
280
280
  </div>
281
- `}function Yf(e){return u`
281
+ `}function Zf(e){return u`
282
282
  <div class="sp-search-bar">
283
283
  <input
284
284
  type="text"
@@ -310,7 +310,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
310
310
  Clear
311
311
  </button>`:w}
312
312
  </div>
313
- `}function Xf(e){return e.searchResults?e.searchResults.length===0?u`<div class="sp-search-results">
313
+ `}function em(e){return e.searchResults?e.searchResults.length===0?u`<div class="sp-search-results">
314
314
  <div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No results found.</div>
315
315
  </div>`:u`
316
316
  <div class="sp-search-results">
@@ -330,7 +330,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
330
330
  </div>
331
331
  `)}
332
332
  </div>
333
- `:w}function Zf(e){const t=e.currentDir;return e.connected?u`
333
+ `:w}function tm(e){const t=e.currentDir;return e.connected?u`
334
334
  <div class="setup-container setup-container--full">
335
335
  ${Nt("Files",e.wsProps)}
336
336
  <div class="sp-files-page">
@@ -348,7 +348,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
348
348
  <input
349
349
  type="file"
350
350
  multiple
351
- accept=${qu}
351
+ accept=${ju}
352
352
  style="display: none;"
353
353
  @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")))}}
354
354
  />
@@ -379,7 +379,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
379
379
  </div>
380
380
  ${t!=="."?u`<div style="font-size: 12px; color: var(--tasker-muted-grey); padding: 4px 2px 0;"><em>${t}</em></div>`:w}
381
381
  </div>
382
- ${Yf(e)}
382
+ ${Zf(e)}
383
383
  </div>
384
384
 
385
385
  ${e.error?u`<div class="setup-error" style="margin-top: 16px;">${e.error}</div>`:w}
@@ -390,16 +390,16 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
390
390
 
391
391
  ${e.uploadBusy?u`<div style="margin-top: 12px; color: var(--tasker-orange); font-weight: 600; font-size: 14px;">Uploading...</div>`:w}
392
392
 
393
- ${e.searchResults!==null?Xf(e):u`<div
393
+ ${e.searchResults!==null?em(e):u`<div
394
394
  class="sp-file-tree"
395
395
  @dragover=${n=>{n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(ts)?"move":"copy")}}
396
- @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(ts);if(i){Vu(i)!=="."&&e.onMoveToDir(i,".");return}const s=(a=n.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=[],l=[];for(const c of Array.from(s)){const d=c.name.includes(".")?`.${c.name.split(".").pop().toLowerCase()}`:"";Hu.has(d)?r.push(c):l.push(c.name)}l.length>0&&alert(`Unsupported file type${l.length>1?"s":""}: ${l.join(", ")}`),r.length>0&&e.onUpload(t,r)}}}
396
+ @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(ts);if(i){Qu(i)!=="."&&e.onMoveToDir(i,".");return}const s=(a=n.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=[],l=[];for(const c of Array.from(s)){const d=c.name.includes(".")?`.${c.name.split(".").pop().toLowerCase()}`:"";Vu.has(d)?r.push(c):l.push(c.name)}l.length>0&&alert(`Unsupported file type${l.length>1?"s":""}: ${l.join(", ")}`),r.length>0&&e.onUpload(t,r)}}}
397
397
  >
398
- ${e.tree.length===0&&!e.loading?u`<div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No files found. Drop files here to upload.</div>`:e.tree.map(n=>Gu(n,e,0))}
398
+ ${e.tree.length===0&&!e.loading?u`<div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No files found. Drop files here to upload.</div>`:e.tree.map(n=>Ju(n,e,0))}
399
399
  </div>`}
400
400
 
401
- ${Qf(e)}
402
- ${Jf(e)}
401
+ ${Yf(e)}
402
+ ${Xf(e)}
403
403
  ${e.memoryStatus?e.memoryStatus.embeddingState==="downloading"?u`<div style="padding: 16px 0; display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--tasker-orange, #f59e0b);">
404
404
  <span class="setup-status-light" style="width: 10px; height: 10px; background: #f59e0b"></span>
405
405
  Downloading embedding model\u2026
@@ -416,7 +416,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
416
416
  <p>Connecting to gateway...</p>
417
417
  </div>
418
418
  </div>
419
- `}const Ia="taskmaster_uninstall_done";async function em(e){var t,n;if(!(!e.client||!e.connected)&&!e.uninstallBusy){e.uninstallBusy=!0,e.uninstallError=null,(t=e.requestUpdate)==null||t.call(e),tm();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 ns(){try{return localStorage.getItem(Ia)==="1"}catch{return!1}}function Ra(){try{localStorage.removeItem(Ia)}catch{}}function tm(){try{localStorage.setItem(Ia,"1")}catch{}}const jr=Object.freeze(Object.defineProperty({__proto__:null,checkUninstallDone:ns,clearUninstallDone:Ra,runUninstall:em},Symbol.toStringTag,{value:"Module"}));function nm(e){const t=Date.now()-new Date(e).getTime();return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function V(e){return u`
419
+ `}const Ia="taskmaster_uninstall_done";async function nm(e){var t,n;if(!(!e.client||!e.connected)&&!e.uninstallBusy){e.uninstallBusy=!0,e.uninstallError=null,(t=e.requestUpdate)==null||t.call(e),im();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 ns(){try{return localStorage.getItem(Ia)==="1"}catch{return!1}}function Ra(){try{localStorage.removeItem(Ia)}catch{}}function im(){try{localStorage.setItem(Ia,"1")}catch{}}const jr=Object.freeze(Object.defineProperty({__proto__:null,checkUninstallDone:ns,clearUninstallDone:Ra,runUninstall:nm},Symbol.toStringTag,{value:"Module"}));function sm(e){const t=Date.now()-new Date(e).getTime();return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function V(e){return u`
420
420
  <span
421
421
  class="setup-status-light"
422
422
  style="background: ${{good:"#22c55e",bad:"#ef4444",partial:"#eab308",unknown:"#6b7280"}[e]}"
@@ -429,7 +429,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
429
429
  >
430
430
  ${E.info}
431
431
  </button>
432
- `}function im(e){var o;if(!e.infoModalOpen)return w;let t="",n=[],i=w,s=w;switch(e.infoModalOpen){case"gateway":{const a=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:a},{label:"Health",value:e.gatewayHealthMessage||"OK"}];break}case"claude":{const a=e.authExpiresIn;let r="N/A";if(a!=null&&a>0)if(a>60){const l=Math.floor(a/60),c=a%60;r=c>0?`${l}h ${c}m`:`${l}h`}else r=`${a}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:r},...e.authMessage?[{label:"Message",value:e.authMessage}]:[]],e.authRefreshToken){const l=e.authRefreshToken,c=l.length>20?`${l.slice(0,8)}...${l.slice(-8)}`:l;i=u`
432
+ `}function om(e){var o;if(!e.infoModalOpen)return w;let t="",n=[],i=w,s=w;switch(e.infoModalOpen){case"gateway":{const a=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:a},{label:"Health",value:e.gatewayHealthMessage||"OK"}];break}case"claude":{const a=e.authExpiresIn;let r="N/A";if(a!=null&&a>0)if(a>60){const l=Math.floor(a/60),c=a%60;r=c>0?`${l}h ${c}m`:`${l}h`}else r=`${a}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:r},...e.authMessage?[{label:"Message",value:e.authMessage}]:[]],e.authRefreshToken){const l=e.authRefreshToken,c=l.length>20?`${l.slice(0,8)}...${l.slice(-8)}`:l;i=u`
433
433
  <div style="display: flex; align-items: center; gap: 6px; padding: 4px 0 8px; border-bottom: 1px solid rgba(255,255,255,0.08);">
434
434
  <span style="font-size: 12px; color: var(--tasker-text-grey); min-width: 90px;">Refresh Token</span>
435
435
  <code style="font-size: 12px; color: var(--tasker-white); word-break: break-all; flex: 1;">${c}</code>
@@ -445,7 +445,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
445
445
  >${l}</a>
446
446
  <button class="setup-info-btn" title="Copy URL" @click=${async c=>{const d=c.currentTarget;try{await navigator.clipboard.writeText(l)}catch{const m=document.createElement("textarea");m.value=l,m.style.position="fixed",m.style.opacity="0",document.body.appendChild(m),m.select(),document.execCommand("copy"),document.body.removeChild(m)}d.classList.add("copied"),setTimeout(()=>d.classList.remove("copied"),1500)}}>${E.copy}</button>
447
447
  </div>
448
- `}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:km[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 a=e.publicChatFullUrl;i=u`
448
+ `}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:$m[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 a=e.publicChatFullUrl;i=u`
449
449
  ${e.publicChatQrDataUrl?u`<div style="text-align: center; padding: 12px 0;">
450
450
  <img src=${e.publicChatQrDataUrl} alt="QR code for public chat URL" style="width: 180px; height: 180px; image-rendering: pixelated; border-radius: 8px;" />
451
451
  </div>`:w}
@@ -579,7 +579,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
579
579
  </p>
580
580
  </div>
581
581
  </div>
582
- `}function sm(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:l,onAuthCodeChange:c}=e;return t===!0?u`
582
+ `}function am(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:l,onAuthCodeChange:c}=e;return t===!0?u`
583
583
  <div class="setup-container">
584
584
  <div class="setup-card setup-success">
585
585
  ${Be("auth")}
@@ -711,7 +711,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
711
711
  </p>
712
712
  </div>
713
713
  </div>
714
- `}function Ss(e,t){const n=new Map(t.whatsappAccounts.map(i=>[i.accountId,i]));return e.accountId?n.get(e.accountId)??null:e.isDefault&&t.whatsappAccounts.length===1?t.whatsappAccounts[0]??null:null}function Ut(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 om(e){const t=Ut(e),n=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??nt().name;if(e.renamingWorkspace&&t){const i=()=>{const s=e.renameWorkspaceName.trim();s&&e.onWorkspaceRename(t.name,s)};return u`
714
+ `}function Ss(e,t){const n=new Map(t.whatsappAccounts.map(i=>[i.accountId,i]));return e.accountId?n.get(e.accountId)??null:e.isDefault&&t.whatsappAccounts.length===1?t.whatsappAccounts[0]??null:null}function Ut(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 rm(e){const t=Ut(e),n=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??nt().name;if(e.renamingWorkspace&&t){const i=()=>{const s=e.renameWorkspaceName.trim();s&&e.onWorkspaceRename(t.name,s)};return u`
715
715
  <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 4px;">
716
716
  <input
717
717
  type="text"
@@ -743,7 +743,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
743
743
  style="opacity: 0.5; transform: scale(0.8);"
744
744
  >${E.edit}</button>
745
745
  </div>
746
- `}function am(e){return u`
746
+ `}function lm(e){return u`
747
747
  <div class="setup-status-item">
748
748
  ${V(e.gatewayHealthy===!1?"bad":"good")}
749
749
  <div class="setup-status-info">
@@ -760,7 +760,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
760
760
  ${E.rotateCw}
761
761
  </button>
762
762
  </div>
763
- `}function rm(e){var a;const t=e.authConnected===!0,n=((a=e.apiKeyProviders)==null?void 0:a.some(r=>r.id==="anthropic"&&r.hasKey))??!1,i=!t&&n,s=t?u`In use${e.authExpiresIn?u` <span style="color: var(--tasker-text-grey); font-size: 12px;">(${e.authExpiresIn>60?`${Math.floor(e.authExpiresIn/60)}h ${e.authExpiresIn%60}m`:`${e.authExpiresIn}m`})</span>`:w}`:u`Not connected`,o=n?i?"In use":"Configured · standby":"Not configured";return u`
763
+ `}function cm(e){var a;const t=e.authConnected===!0,n=((a=e.apiKeyProviders)==null?void 0:a.some(r=>r.id==="anthropic"&&r.hasKey))??!1,i=!t&&n,s=t?u`In use${e.authExpiresIn?u` <span style="color: var(--tasker-text-grey); font-size: 12px;">(${e.authExpiresIn>60?`${Math.floor(e.authExpiresIn/60)}h ${e.authExpiresIn%60}m`:`${e.authExpiresIn}m`})</span>`:w}`:u`Not connected`,o=n?i?"In use":"Configured · standby":"Not configured";return u`
764
764
  <div class="setup-status-item">
765
765
  ${V(t?"good":"bad")}
766
766
  <div class="setup-status-info">
@@ -791,7 +791,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
791
791
  ${E.refreshCw}
792
792
  </button>
793
793
  </div>
794
- `}function lm(e){return u`
794
+ `}function um(e){return u`
795
795
  <div class="setup-status-item" style="flex-wrap: wrap;">
796
796
  ${V("good")}
797
797
  <div class="setup-status-info">
@@ -831,7 +831,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
831
831
  </div>
832
832
  `:w}
833
833
  </div>
834
- `}function sn(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 cm(e){var m;const t=Ut(e);if(!t)return w;const n=Ss(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?sn(n.lastError):"Not connected":"Not paired",l=!(n!=null&&n.provider)||(n==null?void 0:n.provider)==="baileys",c=t.accountId??(t.isDefault&&e.whatsappAccounts.length===1?(m=e.whatsappAccounts[0])==null?void 0:m.accountId:void 0),d=c!=null&&e.whatsappActiveQrAccountId===c;return u`
834
+ `}function sn(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 dm(e){var m;const t=Ut(e);if(!t)return w;const n=Ss(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?sn(n.lastError):"Not connected":"Not paired",l=!(n!=null&&n.provider)||(n==null?void 0:n.provider)==="baileys",c=t.accountId??(t.isDefault&&e.whatsappAccounts.length===1?(m=e.whatsappAccounts[0])==null?void 0:m.accountId:void 0),d=c!=null&&e.whatsappActiveQrAccountId===c;return u`
835
835
  <div class="setup-status-item" style="flex-wrap: wrap;">
836
836
  ${V(a)}
837
837
  <div class="setup-status-info">
@@ -862,7 +862,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
862
862
  </div>
863
863
  `:w}
864
864
  </div>
865
- `}function um(e){var d,m;if(!e.whatsappSettingsOpen)return w;const t=Ut(e);if(!t)return w;const n=Ss(t,e);if(!n)return w;const i=n.running&&n.connected,s=!n.provider||n.provider==="baileys",o=t.accountId??(t.isDefault&&e.whatsappAccounts.length===1?(d=e.whatsappAccounts[0])==null?void 0:d.accountId:void 0),a=()=>e.onWhatsAppSettingsClose(),r="display: flex; justify-content: space-between; font-size: 13px;",l="color: var(--tasker-text-grey);",c="color: var(--tasker-white); text-align: right;";return u`
865
+ `}function pm(e){var d,m;if(!e.whatsappSettingsOpen)return w;const t=Ut(e);if(!t)return w;const n=Ss(t,e);if(!n)return w;const i=n.running&&n.connected,s=!n.provider||n.provider==="baileys",o=t.accountId??(t.isDefault&&e.whatsappAccounts.length===1?(d=e.whatsappAccounts[0])==null?void 0:d.accountId:void 0),a=()=>e.onWhatsAppSettingsClose(),r="display: flex; justify-content: space-between; font-size: 13px;",l="color: var(--tasker-text-grey);",c="color: var(--tasker-white); text-align: right;";return u`
866
866
  <div class="setup-info-overlay" @click=${v=>{v.target.classList.contains("setup-info-overlay")&&a()}}>
867
867
  <div class="setup-info-card">
868
868
  <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0;">
@@ -909,8 +909,8 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
909
909
  </div>
910
910
  </label>
911
911
  `:w}
912
- ${dm(n,e)}
913
- ${pm(e)}
912
+ ${hm(n,e)}
913
+ ${gm(e)}
914
914
  <button
915
915
  class="setup-button secondary"
916
916
  style="margin-top: 20px; width: 100%; padding: 10px;"
@@ -920,7 +920,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
920
920
  </button>
921
921
  </div>
922
922
  </div>
923
- `}function dm(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 u`
923
+ `}function hm(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 u`
924
924
  <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
925
925
  <div style="font-size: 12px; color: var(--tasker-text-grey); margin-bottom: 6px;">Webhook URL (Meta dashboard)</div>
926
926
  <div style="display: flex; align-items: center; gap: 6px;">
@@ -932,7 +932,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
932
932
  >Copy</button>
933
933
  </div>
934
934
  ${n?w:u`<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>`}
935
- `}function pm(e){var v,p;const{addingWhatsAppAccount:t,whatsappAccountSaving:n,whatsappAccountError:i}=e;if(!t)return u`
935
+ `}function gm(e){var v,p;const{addingWhatsAppAccount:t,whatsappAccountSaving:n,whatsappAccountError:i}=e;if(!t)return u`
936
936
  <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
937
937
  <button
938
938
  class="setup-button secondary"
@@ -1027,7 +1027,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1027
1027
  @click=${()=>e.onSetAddingWhatsAppAccount(!1)}
1028
1028
  >Cancel</button>
1029
1029
  </div>
1030
- `}function La(e){const t=Ut(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 hm(e){const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=La(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"),u`
1030
+ `}function La(e){const t=Ut(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 fm(e){const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=La(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"),u`
1031
1031
  <div class="setup-status-item" style="flex-wrap: wrap;">
1032
1032
  ${V(s)}
1033
1033
  <div class="setup-status-info">
@@ -1045,7 +1045,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1045
1045
  </button>
1046
1046
  ${w}
1047
1047
  </div>
1048
- `}function gm(e){if(!e.imessageEnableConfirm)return w;const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=La(e),s=()=>{e.onIMessageEnableCancel()};return n?u`
1048
+ `}function mm(e){if(!e.imessageEnableConfirm)return w;const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=La(e),s=()=>{e.onIMessageEnableCancel()};return n?u`
1049
1049
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&s()}}>
1050
1050
  <div class="setup-info-card" style="text-align: center;">
1051
1051
  <h3>iMessage</h3>
@@ -1121,7 +1121,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1121
1121
  </button>
1122
1122
  </div>
1123
1123
  </div>
1124
- `}function fm(e){const t=e.telegramConfigured,n=e.telegramAccounts.length,i=e.telegramAccounts.filter(a=>a.running).length;let s,o;return t?n>0&&i===n?(s="good",o=n===1?"1 bot connected":`${n} bots connected`):i>0?(s="partial",o=`${i}/${n} bots connected`):e.telegramLastError?(s="bad",o=sn(e.telegramLastError)):(s="bad",o="Not running"):(s="unknown",o="Not configured"),u`
1124
+ `}function ym(e){const t=e.telegramConfigured,n=e.telegramAccounts.length,i=e.telegramAccounts.filter(a=>a.running).length;let s,o;return t?n>0&&i===n?(s="good",o=n===1?"1 bot connected":`${n} bots connected`):i>0?(s="partial",o=`${i}/${n} bots connected`):e.telegramLastError?(s="bad",o=sn(e.telegramLastError)):(s="bad",o="Not running"):(s="unknown",o="Not configured"),u`
1125
1125
  <div class="setup-status-item" style="flex-wrap: wrap;">
1126
1126
  ${V(s)}
1127
1127
  <div class="setup-status-info">
@@ -1142,7 +1142,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1142
1142
  ${t?E.rotateCw:E.plus}
1143
1143
  </button>
1144
1144
  </div>
1145
- `}function mm(e){var a,r;if(!e.telegramConnectOpen)return w;const t=()=>{e.onTelegramConnectClose()},n=((a=e.telegramProbeResult)==null?void 0:a.ok)===!0,i=(r=e.telegramProbeResult)==null?void 0:r.username,s=e.telegramAddingBot,o="width: 100%; padding: 10px; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.12); border-radius: 6px; color: var(--tasker-white); font-size: 13px; box-sizing: border-box;";return u`
1145
+ `}function vm(e){var a,r;if(!e.telegramConnectOpen)return w;const t=()=>{e.onTelegramConnectClose()},n=((a=e.telegramProbeResult)==null?void 0:a.ok)===!0,i=(r=e.telegramProbeResult)==null?void 0:r.username,s=e.telegramAddingBot,o="width: 100%; padding: 10px; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.12); border-radius: 6px; color: var(--tasker-white); font-size: 13px; box-sizing: border-box;";return u`
1146
1146
  <div class="setup-info-overlay" @click=${l=>{l.target.classList.contains("setup-info-overlay")&&t()}}>
1147
1147
  <div class="setup-info-card">
1148
1148
  <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0;">
@@ -1234,7 +1234,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1234
1234
  </div>
1235
1235
  </div>
1236
1236
  </div>
1237
- `}function ym(e){if(!e.telegramSettingsOpen)return w;const t=()=>e.onTelegramSettingsClose(),n=e.telegramAccounts,i=e.telegramExpandedBotId,s={open:"Respond to everyone",pairing:"Require approval",allowlist:"Whitelist only",disabled:"Disabled"},o="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;";return u`
1237
+ `}function bm(e){if(!e.telegramSettingsOpen)return w;const t=()=>e.onTelegramSettingsClose(),n=e.telegramAccounts,i=e.telegramExpandedBotId,s={open:"Respond to everyone",pairing:"Require approval",allowlist:"Whitelist only",disabled:"Disabled"},o="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;";return u`
1238
1238
  <div class="setup-info-overlay" @click=${a=>{a.target.classList.contains("setup-info-overlay")&&t()}}>
1239
1239
  <div class="setup-info-card">
1240
1240
  <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0;">
@@ -1268,7 +1268,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1268
1268
  </span>
1269
1269
  <span style="font-size: 11px; color: var(--tasker-text-grey);">
1270
1270
  ${a.botActive?a.botUsername?`@${a.botUsername}`:"via Telegram":"Bot removed"}
1271
- · ${nm(a.createdAt)}
1271
+ · ${sm(a.createdAt)}
1272
1272
  </span>
1273
1273
  </div>
1274
1274
  <div style="display: flex; gap: 6px; flex-shrink: 0; margin-left: 8px;">
@@ -1427,7 +1427,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1427
1427
  </button>
1428
1428
  </div>
1429
1429
  </div>
1430
- `}function vm(e){if(!e.isMaster)return w;const n=e.apiKeyProviders.filter(i=>i.hasKey).length;return u`
1430
+ `}function wm(e){if(!e.isMaster)return w;const n=e.apiKeyProviders.filter(i=>i.hasKey).length;return u`
1431
1431
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1432
1432
  <div class="setup-status-item">
1433
1433
  ${V(n>0?"good":"bad")}
@@ -1442,8 +1442,8 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1442
1442
  >Manage</button>
1443
1443
  </div>
1444
1444
  </div>
1445
- ${bm(e)}
1446
- `}function bm(e){if(!e.apiKeyModalOpen)return w;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,d)=>{const m=d==null?void 0:d.closest(".setup-apikey-input"),v=m==null?void 0:m.querySelector("input"),p=v==null?void 0:v.value.trim();!p||p===n[c]||e.onApiKeySave(c,p)},s=c=>{const d=c.currentTarget,m=d.closest(".setup-apikey-input"),v=m==null?void 0:m.querySelector("input");if(!v)return;const p=v.type==="text";v.type=p?"password":"text",d.classList.toggle("active",!p)},o=(c,d)=>{const m=d.target,v=m.closest(".setup-apikey-input"),p=m.value.trim(),b=p.length>0&&p!==n[c],x=v==null?void 0:v.querySelector(".setup-apikey-save");x&&(x.style.display=b?"":"none");const C=v==null?void 0:v.querySelector(".setup-apikey-eye");C&&(C.style.display=p.length>0?"":"none")},a=t.filter(c=>c.primary),r=t.filter(c=>!c.primary),l=c=>{const d=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,m=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,v=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`,p=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} disabled`,b=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} enabled`;return u`
1445
+ ${km(e)}
1446
+ `}function km(e){if(!e.apiKeyModalOpen)return w;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,d)=>{const m=d==null?void 0:d.closest(".setup-apikey-input"),v=m==null?void 0:m.querySelector("input"),p=v==null?void 0:v.value.trim();!p||p===n[c]||e.onApiKeySave(c,p)},s=c=>{const d=c.currentTarget,m=d.closest(".setup-apikey-input"),v=m==null?void 0:m.querySelector("input");if(!v)return;const p=v.type==="text";v.type=p?"password":"text",d.classList.toggle("active",!p)},o=(c,d)=>{const m=d.target,v=m.closest(".setup-apikey-input"),p=m.value.trim(),b=p.length>0&&p!==n[c],x=v==null?void 0:v.querySelector(".setup-apikey-save");x&&(x.style.display=b?"":"none");const C=v==null?void 0:v.querySelector(".setup-apikey-eye");C&&(C.style.display=p.length>0?"":"none")},a=t.filter(c=>c.primary),r=t.filter(c=>!c.primary),l=c=>{const d=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,m=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,v=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`,p=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} disabled`,b=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} enabled`;return u`
1447
1447
  <div class="setup-apikey-row ${c.disabled?"disabled":""}">
1448
1448
  <div class="setup-apikey-info">
1449
1449
  <strong>${c.name}</strong>
@@ -1507,7 +1507,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1507
1507
  </div>
1508
1508
  </div>
1509
1509
  </div>
1510
- `}function wm(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 u`
1510
+ `}function xm(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 u`
1511
1511
  <div class="setup-status-item">
1512
1512
  ${V(t)}
1513
1513
  <div class="setup-status-info">
@@ -1535,7 +1535,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1535
1535
  </button>
1536
1536
  `}
1537
1537
  </div>
1538
- `}const km={anonymous:"Open access",verified:"Phone OTP",choice:"Visitor chooses"};function xm(e){const t=e.publicChatEnabled;return u`
1538
+ `}const $m={anonymous:"Open access",verified:"Phone OTP",choice:"Visitor chooses"};function Sm(e){const t=e.publicChatEnabled;return u`
1539
1539
  <div class="setup-status-item">
1540
1540
  ${V(t?"good":"unknown")}
1541
1541
  <div class="setup-status-info">
@@ -1555,7 +1555,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1555
1555
  @click=${e.onPublicChatToggle}
1556
1556
  >${t?E.powerOff:E.power}</button>
1557
1557
  </div>
1558
- `}function $m(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=Ut(e),c=l?Ss(l,e):null,d=!!(c!=null&&c.connected);return u`
1558
+ `}function Am(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=Ut(e),c=l?Ss(l,e):null,d=!!(c!=null&&c.connected);return u`
1559
1559
  <div class="setup-info-overlay" @click=${m=>{m.target.classList.contains("setup-info-overlay")&&t()}}>
1560
1560
  <div class="setup-info-card" style="max-width: 380px; max-height: 80vh; overflow-y: auto;">
1561
1561
  <h3 style="margin: 0 0 12px; display: flex; align-items: center; justify-content: space-between;">
@@ -1683,7 +1683,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1683
1683
  </div>
1684
1684
  </div>
1685
1685
  </div>
1686
- `}function Sm(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>
1686
+ `}function Cm(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>
1687
1687
  <script>
1688
1688
  Taskmaster.init({
1689
1689
  server: "${i}",
@@ -1713,7 +1713,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1713
1713
  </div>
1714
1714
  </div>
1715
1715
  </div>
1716
- `}const Qu=[{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"}],Am=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],Cm="anthropic/claude-sonnet-4-5-20250929";function Em(e){const t=e.agentSettingsAgents??[],n=t.length>0?t.map(i=>{var o;return i.model?((o=Qu.find(a=>i.model===`anthropic/${a.id}`))==null?void 0:o.shortName)??i.model.split("/").pop():"Sonnet"}).join(" / "):"Default";return u`
1716
+ `}const Yu=[{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"}],Em=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],Tm="anthropic/claude-sonnet-4-5-20250929";function Pm(e){const t=e.agentSettingsAgents??[],n=t.length>0?t.map(i=>{var o;return i.model?((o=Yu.find(a=>i.model===`anthropic/${a.id}`))==null?void 0:o.shortName)??i.model.split("/").pop():"Sonnet"}).join(" / "):"Default";return u`
1717
1717
  <div class="setup-status-item">
1718
1718
  ${V("good")}
1719
1719
  <div class="setup-status-info">
@@ -1722,12 +1722,12 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1722
1722
  </div>
1723
1723
  <button class="setup-status-action" @click=${e.onAgentSettingsToggle} title="Edit">${E.penLine}</button>
1724
1724
  </div>
1725
- `}function Tm(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=Qu.filter(a=>i.has(a.id)),o=()=>e.onAgentSettingsToggle();return u`
1725
+ `}function _m(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=Yu.filter(a=>i.has(a.id)),o=()=>e.onAgentSettingsToggle();return u`
1726
1726
  <div class="setup-info-overlay" @click=${a=>{a.target.classList.contains("setup-info-overlay")&&o()}}>
1727
1727
  <div class="setup-info-card" style="max-width: 400px;">
1728
1728
  <h3>Agent Settings</h3>
1729
1729
  <div style="display: flex; flex-direction: column; gap: 20px; margin-top: 16px;">
1730
- ${t.map(a=>{const r=a.model??Cm,l=a.thinkingLevel??"off",c=a.id.endsWith("-admin")||a.id==="admin";return u`
1730
+ ${t.map(a=>{const r=a.model??Tm,l=a.thinkingLevel??"off",c=a.id.endsWith("-admin")||a.id==="admin";return u`
1731
1731
  <div style="display: flex; flex-direction: column; gap: 10px;">
1732
1732
  <div style="font-size: 14px; font-weight: 600; color: var(--tasker-white);">
1733
1733
  ${a.label||(c?"Admin":"Public")}
@@ -1757,7 +1757,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1757
1757
  .value=${l}
1758
1758
  @change=${d=>{e.onAgentThinkingChange(a.id,d.target.value)}}
1759
1759
  >
1760
- ${Am.map(d=>u`
1760
+ ${Em.map(d=>u`
1761
1761
  <option value=${d.value} ?selected=${l===d.value}>
1762
1762
  ${d.label}
1763
1763
  </option>
@@ -1810,7 +1810,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1810
1810
  </button>
1811
1811
  </div>
1812
1812
  </div>
1813
- `}function Pm(e){const t=!!(e.brandAccentColor||e.brandBackgroundColor||e.brandHasLogo),n=t?"good":"unknown",i=e.brandingBusy;return u`
1813
+ `}function Mm(e){const t=!!(e.brandAccentColor||e.brandBackgroundColor||e.brandHasLogo),n=t?"good":"unknown",i=e.brandingBusy;return u`
1814
1814
  <div class="setup-status-item">
1815
1815
  ${V(n)}
1816
1816
  <div class="setup-status-info">
@@ -1825,7 +1825,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1825
1825
  title="Edit"
1826
1826
  >${E.penLine}</button>
1827
1827
  </div>
1828
- `}function _m(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 u`
1828
+ `}function Im(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 u`
1829
1829
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onBrandingToggle()}}>
1830
1830
  <div class="setup-info-card" style="max-width: 400px; position: relative;">
1831
1831
  <h3 style="margin-right: 24px;">Branding</h3>
@@ -1906,7 +1906,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1906
1906
 
1907
1907
  </div>
1908
1908
  </div>
1909
- `}function Mm(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?u`
1909
+ `}function Rm(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?u`
1910
1910
  <div class="setup-info-overlay" @click=${r=>{r.target.classList.contains("setup-info-overlay")&&e.onTailscaleErrorDismiss()}}>
1911
1911
  <div class="setup-info-card" style="max-width: 380px; text-align: center;">
1912
1912
  <h3>Remote Access</h3>
@@ -1973,7 +1973,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
1973
1973
  <p style="font-size: 14px; color: var(--tasker-text-grey); margin: 12px 0 0;">${a}</p>
1974
1974
  </div>
1975
1975
  </div>
1976
- `}function Im(e){if(!e.isMaster)return w;const t=e.tailscaleStatus,n=e.tailscaleBusy,i=e.tailscaleAuthUrl;if(!t)return u`
1976
+ `}function Lm(e){if(!e.isMaster)return w;const t=e.tailscaleStatus,n=e.tailscaleBusy,i=e.tailscaleAuthUrl;if(!t)return u`
1977
1977
  <div class="setup-status-item">
1978
1978
  ${V("unknown")}
1979
1979
  <div class="setup-status-info">
@@ -2107,7 +2107,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2107
2107
  >${E.powerOff}</button>
2108
2108
  ${o}
2109
2109
  </div>
2110
- `}function Rm(e){if(!e.isMaster)return w;const t=e.tunnelStatus,n=e.tunnelBusy;if(!t)return u`
2110
+ `}function Bm(e){if(!e.isMaster)return w;const t=e.tunnelStatus,n=e.tunnelBusy;if(!t)return u`
2111
2111
  <div class="setup-status-item">
2112
2112
  ${V("unknown")}
2113
2113
  <div class="setup-status-info">
@@ -2217,7 +2217,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2217
2217
  <button class="setup-info-btn" title="Dismiss" @click=${e.onTunnelErrorDismiss}>${E.x}</button>
2218
2218
  </p>`:w}
2219
2219
  </div>
2220
- `}function Lm(e){if(!e.tunnelAuthUrl)return w;const t=()=>e.onTunnelLoginCancel();return u`
2220
+ `}function Dm(e){if(!e.tunnelAuthUrl)return w;const t=()=>e.onTunnelLoginCancel();return u`
2221
2221
  <div class="setup-info-overlay" @click=${n=>{n.target.classList.contains("setup-info-overlay")&&t()}}>
2222
2222
  <div class="setup-info-card" style="max-width: 380px; text-align: center; position: relative;">
2223
2223
  <button class="setup-info-btn" title="Close" style="position: absolute; top: 8px; right: 8px;"
@@ -2243,7 +2243,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2243
2243
  </p>
2244
2244
  </div>
2245
2245
  </div>
2246
- `}function Bm(e){var o;if(e.tunnelSetupStep===0)return w;const t=e.tunnelBusy,n=e.tunnelError,i=e.tunnelSetupStep,s=()=>e.onTunnelSetupStepChange(0);if(i===3){const a=(o=e.tunnelStatus)==null?void 0:o.authorizedDomain,r=a?`admin.${a}`:null,l=a?`public.${a}`:null;return u`
2246
+ `}function Nm(e){var o;if(e.tunnelSetupStep===0)return w;const t=e.tunnelBusy,n=e.tunnelError,i=e.tunnelSetupStep,s=()=>e.onTunnelSetupStepChange(0);if(i===3){const a=(o=e.tunnelStatus)==null?void 0:o.authorizedDomain,r=a?`admin.${a}`:null,l=a?`public.${a}`:null;return u`
2247
2247
  <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&s()}}>
2248
2248
  <div class="setup-info-card" style="max-width: 420px; position: relative;">
2249
2249
  <button class="setup-info-btn" style="position: absolute; top: 12px; right: 12px;" title="Close" @click=${s}>${E.x}</button>
@@ -2385,7 +2385,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2385
2385
  background: ${s<t?"var(--tasker-accent, #00e5ff)":"rgba(255,255,255,0.15)"};
2386
2386
  "></span>`)}
2387
2387
  </span>
2388
- `}function Dm(e){if(e.serverPlatform!=="linux")return w;const t=e.wifiStatus,n=e.wifiBusy;if(!t)return u`
2388
+ `}function Um(e){if(e.serverPlatform!=="linux")return w;const t=e.wifiStatus,n=e.wifiBusy;if(!t)return u`
2389
2389
  <div class="setup-status-item">
2390
2390
  ${V("unknown")}
2391
2391
  <div class="setup-status-info">
@@ -2415,7 +2415,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2415
2415
  @click=${e.onWifiModalToggle}
2416
2416
  >${n?"...":"Edit"}</button>
2417
2417
  </div>
2418
- `}function Nm(e){if(!e.wifiModalOpen)return w;const t=e.wifiStatus,n=e.wifiBusy,i=e.wifiNetworks,s=e.wifiSelectedSsid;return u`
2418
+ `}function Om(e){if(!e.wifiModalOpen)return w;const t=e.wifiStatus,n=e.wifiBusy,i=e.wifiNetworks,s=e.wifiSelectedSsid;return u`
2419
2419
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onWifiModalToggle()}}>
2420
2420
  <div class="setup-info-card" style="max-width: 420px; position: relative;">
2421
2421
  <h3 style="margin-right: 24px;">WiFi</h3>
@@ -2541,7 +2541,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2541
2541
  `:w}
2542
2542
  </div>
2543
2543
  </div>
2544
- `}function Um(e){return e.isMaster?e.networkPort==null?u`
2544
+ `}function Fm(e){return e.isMaster?e.networkPort==null?u`
2545
2545
  <div class="setup-status-item">
2546
2546
  ${V("unknown")}
2547
2547
  <div class="setup-status-info">
@@ -2563,7 +2563,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2563
2563
  title="Edit"
2564
2564
  >${E.penLine}</button>
2565
2565
  </div>
2566
- `:w}function Om(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 u`
2566
+ `:w}function Wm(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 u`
2567
2567
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onNetworkModalToggle()}}>
2568
2568
  <div class="setup-info-card" style="max-width: 400px; position: relative;">
2569
2569
  <h3 style="margin-right: 24px;">Network</h3>
@@ -2633,7 +2633,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2633
2633
  </div>
2634
2634
  </div>
2635
2635
  </div>
2636
- `}function Fm(e){var i,s,o,a;const t=e.updateRunning,n=e.updateLastResult;if(!t&&!n)return w;if(t){const r=((i=e.updateProgressSteps[0])==null?void 0:i.total)??0,l=e.updateProgressSteps.filter(m=>m.status==="done"||m.status==="failed").length,c=r>0?Math.round(l/r*100):0,d=e.updateProgressSteps.some(m=>m.status==="running");return u`
2636
+ `}function zm(e){var i,s,o,a;const t=e.updateRunning,n=e.updateLastResult;if(!t&&!n)return w;if(t){const r=((i=e.updateProgressSteps[0])==null?void 0:i.total)??0,l=e.updateProgressSteps.filter(m=>m.status==="done"||m.status==="failed").length,c=r>0?Math.round(l/r*100):0,d=e.updateProgressSteps.some(m=>m.status==="running");return u`
2637
2637
  <div class="setup-info-overlay">
2638
2638
  <div class="setup-info-card" style="max-width: 400px;">
2639
2639
  <h3>Software Update</h3>
@@ -2676,7 +2676,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2676
2676
  </button>
2677
2677
  </div>
2678
2678
  </div>
2679
- `}return w}function Gr(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 Wm(e){const t=e.accountHasPin;return u`
2679
+ `}return w}function Gr(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 Km(e){const t=e.accountHasPin;return u`
2680
2680
  <div class="setup-status-item">
2681
2681
  ${V(t?"good":"bad")}
2682
2682
  <div class="setup-status-info">
@@ -2690,7 +2690,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2690
2690
  title="${t?"Change PIN":"Set PIN"}"
2691
2691
  >${E.refreshCw}</button>
2692
2692
  </div>
2693
- `}function zm(e){if(!e.accountPinModalOpen)return w;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const a=c=>d=>{const m=d.target;m.value=m.value.replace(/\D/g,"").slice(0,6),c(m.value)},r=(c,d)=>{var v;let m=c.querySelector(".pin-modal-validation");m||(m=document.createElement("p"),m.className="login-error pin-modal-validation",(v=c.querySelector("button[type=submit]"))==null||v.before(m)),m.textContent=d},l=c=>{c.preventDefault();const d=c.target;if(!n){if(t&&!i){r(d,"Enter your current PIN");return}if(!s){r(d,"Enter a new PIN");return}if(!o){r(d,"Confirm your new PIN");return}if(s!==o){r(d,"PINs do not match");return}if(s.length<4){r(d,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return u`
2693
+ `}function qm(e){if(!e.accountPinModalOpen)return w;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const a=c=>d=>{const m=d.target;m.value=m.value.replace(/\D/g,"").slice(0,6),c(m.value)},r=(c,d)=>{var v;let m=c.querySelector(".pin-modal-validation");m||(m=document.createElement("p"),m.className="login-error pin-modal-validation",(v=c.querySelector("button[type=submit]"))==null||v.before(m)),m.textContent=d},l=c=>{c.preventDefault();const d=c.target;if(!n){if(t&&!i){r(d,"Enter your current PIN");return}if(!s){r(d,"Enter a new PIN");return}if(!o){r(d,"Confirm your new PIN");return}if(s!==o){r(d,"PINs do not match");return}if(s.length<4){r(d,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return u`
2694
2694
  <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onAccountPinModalClose()}}>
2695
2695
  <div class="setup-info-card" style="max-width: 340px;">
2696
2696
  <div class="setup-info-header">
@@ -2747,7 +2747,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2747
2747
  </form>
2748
2748
  </div>
2749
2749
  </div>
2750
- `}function Km(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 u`
2750
+ `}function Hm(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 u`
2751
2751
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
2752
2752
  <div class="setup-add-account">
2753
2753
  <strong>New Account</strong>
@@ -2810,7 +2810,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2810
2810
  </div>
2811
2811
  </div>
2812
2812
  </div>
2813
- `}function qm(e){const t=Ut(e);return!t||t.isDefault?w:e.workspaceRemoveConfirm===t.name?u`
2813
+ `}function jm(e){const t=Ut(e);return!t||t.isDefault?w:e.workspaceRemoveConfirm===t.name?u`
2814
2814
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 12px;">
2815
2815
  <div style="font-size: 13px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
2816
2816
  <span style="color: var(--tasker-danger, #ef4444);">Remove "${t.displayName??t.name}" and its WhatsApp account?</span>
@@ -2839,7 +2839,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2839
2839
  @click=${i=>{i.preventDefault(),e.onSetWorkspaceRemoveConfirm(t.name)}}
2840
2840
  >Remove Account</a>
2841
2841
  </p>
2842
- `}function Hm(e){if(e.uninstallDone)return u`
2842
+ `}function Vm(e){if(e.uninstallDone)return u`
2843
2843
  <div style="margin-top: 24px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
2844
2844
  <p style="color: var(--tasker-danger, #ef4444); font-size: 13px; font-weight: 600; margin: 0 0 8px 0;">
2845
2845
  Taskmaster has been uninstalled.
@@ -2894,11 +2894,11 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2894
2894
  @click=${t=>{t.preventDefault(),e.onUninstallConfirm()}}
2895
2895
  >Uninstall Taskmaster</a>
2896
2896
  </p>
2897
- `}function jm(){return u`
2897
+ `}function Gm(){return u`
2898
2898
  <p class="setup-hint" style="margin-top: 4px; font-size: 12px; opacity: 0.6;">
2899
2899
  Need help? <a href="https://wa.me/447591215452" target="_blank" rel="noopener" style="color: var(--tasker-orange);">Message Tuesday on WhatsApp</a>
2900
2900
  </p>
2901
- `}function Vm(e){const{whatsappBusy:t,whatsappLoginMessage:n,whatsappLoginQrDataUrl:i,whatsappLoginConnected:s,whatsappChannelStatus:o}=e;if(i)return u`
2901
+ `}function Qm(e){const{whatsappBusy:t,whatsappLoginMessage:n,whatsappLoginQrDataUrl:i,whatsappLoginConnected:s,whatsappChannelStatus:o}=e;if(i)return u`
2902
2902
  <div class="setup-container">
2903
2903
  <div class="setup-card">
2904
2904
  <h1>Scan with WhatsApp</h1>
@@ -2935,39 +2935,39 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
2935
2935
  `;const a=(o==null?void 0:o.running)&&(o==null?void 0:o.connected);if(o){const d=(e.whatsappAccounts.length>1?e.whatsappAccounts.every(m=>m.running&&m.connected):a)&&e.authConnected;return u`
2936
2936
  <div class="setup-container">
2937
2937
  <div class="setup-card ${d?"setup-success":""} setup-dashboard-wide">
2938
- ${om(e)}
2938
+ ${rm(e)}
2939
2939
  <div class="setup-status-dashboard">
2940
- ${am(e)}
2941
- ${rm(e)}
2942
2940
  ${lm(e)}
2943
2941
  ${cm(e)}
2944
- ${e.serverPlatform==="darwin"?hm(e):w}
2945
- ${fm(e)}
2946
- ${Em(e)}
2947
- ${Wm(e)}
2948
- ${wm(e)}
2949
- ${xm(e)}
2942
+ ${um(e)}
2943
+ ${dm(e)}
2944
+ ${e.serverPlatform==="darwin"?fm(e):w}
2945
+ ${ym(e)}
2950
2946
  ${Pm(e)}
2951
- ${Im(e)}
2952
- ${Rm(e)}
2947
+ ${Km(e)}
2948
+ ${xm(e)}
2949
+ ${Sm(e)}
2950
+ ${Mm(e)}
2951
+ ${Lm(e)}
2952
+ ${Bm(e)}
2953
+ ${Fm(e)}
2953
2954
  ${Um(e)}
2954
- ${Dm(e)}
2955
2955
  </div>
2956
2956
 
2957
- ${Tm(e)}
2958
- ${zm(e)}
2959
2957
  ${_m(e)}
2960
- ${$m(e)}
2958
+ ${qm(e)}
2959
+ ${Im(e)}
2960
+ ${Am(e)}
2961
+ ${Wm(e)}
2961
2962
  ${Om(e)}
2963
+ ${Rm(e)}
2964
+ ${Dm(e)}
2962
2965
  ${Nm(e)}
2963
- ${Mm(e)}
2964
- ${Lm(e)}
2965
- ${Bm(e)}
2966
- ${vm(e)}
2967
- ${Km(e)}
2968
- ${qm(e)}
2966
+ ${wm(e)}
2969
2967
  ${Hm(e)}
2970
- ${jm()}
2968
+ ${jm(e)}
2969
+ ${Vm(e)}
2970
+ ${Gm()}
2971
2971
  ${e.workspacesError?u`<p class="setup-error" style="margin-top: 8px;">${e.workspacesError}</p>`:w}
2972
2972
  </div>
2973
2973
  </div>
@@ -3012,7 +3012,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3012
3012
  </button>
3013
3013
  </div>
3014
3014
  </div>
3015
- `}function Gm(e){if(!e.claudeAuthModalOpen)return w;const t=()=>e.onClaudeAuthModalClose(),n=e.authConnected===!0;return u`
3015
+ `}function Jm(e){if(!e.claudeAuthModalOpen)return w;const t=()=>e.onClaudeAuthModalClose(),n=e.authConnected===!0;return u`
3016
3016
  <div class="setup-info-overlay" @click=${i=>{i.target.classList.contains("setup-info-overlay")&&t()}}>
3017
3017
  <div class="setup-info-card" style="max-width: 420px; position: relative;">
3018
3018
  <h3>${n?"Claude Connected":"Connect to Claude"}</h3>
@@ -3117,7 +3117,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3117
3117
  </button>
3118
3118
  </div>
3119
3119
  </div>
3120
- `}function Qm(e){const{connected:t,currentStep:n}=e;if(t&&ns()&&Ra(),e.uninstallDone||!t&&ns())return u`
3120
+ `}function Ym(e){const{connected:t,currentStep:n}=e;if(t&&ns()&&Ra(),e.uninstallDone||!t&&ns())return u`
3121
3121
  <div class="setup-container">
3122
3122
  <div class="setup-card">
3123
3123
  <p style="color: var(--tasker-danger, #ef4444); font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
@@ -3140,7 +3140,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3140
3140
  <p>${o?"Restarting gateway after update…":"Connecting to gateway..."}</p>
3141
3141
  </div>
3142
3142
  </div>
3143
- `}let i;switch(n){case"license":i=Vr(e);break;case"auth":i=sm(e);break;case"setup":i=Vm(e);break;default:i=Vr(e)}const s=Nt("Setup",e.wsProps);return u`${i}${im(e)}${Gm(e)}${gm(e)}${um(e)}${mm(e)}${ym(e)}${Fm(e)}${Sm(e)}${s}`}function Jm(e,t){const n=e.paired?"Paired phone (used to link WhatsApp)":"Admin access via WhatsApp DM";return u`
3143
+ `}let i;switch(n){case"license":i=Vr(e);break;case"auth":i=am(e);break;case"setup":i=Qm(e);break;default:i=Vr(e)}const s=Nt("Setup",e.wsProps);return u`${i}${om(e)}${Jm(e)}${mm(e)}${pm(e)}${vm(e)}${bm(e)}${zm(e)}${Cm(e)}${s}`}function Xm(e,t){const n=e.paired?"Paired phone (used to link WhatsApp)":"Admin access via WhatsApp DM";return u`
3144
3144
  <div class="sp-list-item">
3145
3145
  <div class="sp-list-item-main">
3146
3146
  <div class="sp-list-item-title">${e.phone}</div>
@@ -3155,7 +3155,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3155
3155
  Remove
3156
3156
  </button>`}
3157
3157
  </div>
3158
- `}function Ym(e,t){return u`
3158
+ `}function Zm(e,t){return u`
3159
3159
  <div class="sp-list-item">
3160
3160
  <div class="sp-list-item-main">
3161
3161
  <div class="sp-list-item-title">${e.username}</div>
@@ -3170,7 +3170,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3170
3170
  Remove
3171
3171
  </button>
3172
3172
  </div>
3173
- `}function Xm(e){if(!e.isMaster)return w;const t=e.namedAdmins??[],n=!!(e.adminUsersAddBusy||e.adminUsersRemoveBusy||e.adminUsersChangePinBusy),i=l=>{const c=l.target;c.value=c.value.replace(/\D/g,"").slice(0,6)},s=l=>{const c=l.target;c.value=c.value.toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32)},o=l=>{var b;if(l.preventDefault(),e.adminUsersAddBusy)return;const c=l.target,d=c.querySelector(".admin-add-username"),m=c.querySelector(".admin-add-pin"),v=(d==null?void 0:d.value.trim())??"",p=(m==null?void 0:m.value.trim())??"";!v||!p||((b=e.onAdminUsersAdd)==null||b.call(e,v,p),d&&(d.value=""),m&&(m.value=""))},a=l=>{const c=l.currentTarget,d=c.closest(".login-pin-wrapper"),m=d==null?void 0:d.querySelector("input");if(!m)return;const v=m.type==="text";m.type=v?"password":"text",c.classList.toggle("active",!v)},r=(l,c)=>{var p;if(l.preventDefault(),e.adminUsersChangePinBusy)return;const m=l.target.querySelector(".admin-change-pin"),v=(m==null?void 0:m.value.trim())??"";v&&((p=e.onAdminUsersUpdatePin)==null||p.call(e,c,v))};return u`
3173
+ `}function ey(e){if(!e.isMaster)return w;const t=e.namedAdmins??[],n=!!(e.adminUsersAddBusy||e.adminUsersRemoveBusy||e.adminUsersChangePinBusy),i=l=>{const c=l.target;c.value=c.value.replace(/\D/g,"").slice(0,6)},s=l=>{const c=l.target;c.value=c.value.toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32)},o=l=>{var b;if(l.preventDefault(),e.adminUsersAddBusy)return;const c=l.target,d=c.querySelector(".admin-add-username"),m=c.querySelector(".admin-add-pin"),v=(d==null?void 0:d.value.trim())??"",p=(m==null?void 0:m.value.trim())??"";!v||!p||((b=e.onAdminUsersAdd)==null||b.call(e,v,p),d&&(d.value=""),m&&(m.value=""))},a=l=>{const c=l.currentTarget,d=c.closest(".login-pin-wrapper"),m=d==null?void 0:d.querySelector("input");if(!m)return;const v=m.type==="text";m.type=v?"password":"text",c.classList.toggle("active",!v)},r=(l,c)=>{var p;if(l.preventDefault(),e.adminUsersChangePinBusy)return;const m=l.target.querySelector(".admin-change-pin"),v=(m==null?void 0:m.value.trim())??"";v&&((p=e.onAdminUsersUpdatePin)==null||p.call(e,c,v))};return u`
3174
3174
  <div>
3175
3175
  <p style="margin-bottom: 20px; color: rgba(255,255,255,0.6); font-size: 14px;">
3176
3176
  Each login user has their own PIN and separate chat history in the control panel.
@@ -3268,7 +3268,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3268
3268
  </button>
3269
3269
  </form>
3270
3270
  </div>
3271
- `}function Zm(e){if(!e.connected)return u`
3271
+ `}function ty(e){if(!e.connected)return u`
3272
3272
  <div class="setup-container">
3273
3273
  <div class="setup-card">
3274
3274
  <div class="setup-spinner"></div>
@@ -3336,7 +3336,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3336
3336
  </form>
3337
3337
 
3338
3338
  <div class="sp-list" style="margin-top: 20px;">
3339
- ${e.phones.length===0?u`<div class="sp-list-empty">No admin phones configured yet.</div>`:e.phones.map(r=>Jm(r,e))}
3339
+ ${e.phones.length===0?u`<div class="sp-list-empty">No admin phones configured yet.</div>`:e.phones.map(r=>Xm(r,e))}
3340
3340
  </div>
3341
3341
 
3342
3342
  <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
@@ -3365,24 +3365,24 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3365
3365
  </form>
3366
3366
 
3367
3367
  <div class="sp-list" style="margin-top: 20px;">
3368
- ${e.telegramAdmins.length===0?u`<div class="sp-list-empty">No Telegram admins configured.</div>`:e.telegramAdmins.map(r=>Ym(r,e))}
3368
+ ${e.telegramAdmins.length===0?u`<div class="sp-list-empty">No Telegram admins configured.</div>`:e.telegramAdmins.map(r=>Zm(r,e))}
3369
3369
  </div>
3370
3370
 
3371
3371
  <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
3372
3372
  Telegram user IDs that route to the admin agent. Admin bots only accept messages from these users. Find your ID by messaging @userinfobot on Telegram.
3373
3373
  </div>
3374
3374
  `}
3375
- `:Xm(e)}
3375
+ `:ey(e)}
3376
3376
 
3377
3377
  </div>
3378
3378
  </div>
3379
- `}const Ju=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`;function ey(e){return Object.keys(e.fields).length}function ty(e,t){return u`
3379
+ `}const Xu=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`;function ny(e){return Object.keys(e.fields).length}function iy(e,t){return u`
3380
3380
  <div class="event-modal-overlay" @click=${t.onDeleteConfirmClose}>
3381
3381
  <div class="event-modal" style="width: min(400px, 100%);" @click=${n=>n.stopPropagation()}>
3382
3382
  <div class="event-modal__header">
3383
3383
  <div class="event-modal__title">Delete Contact</div>
3384
3384
  <button class="event-modal__close" @click=${t.onDeleteConfirmClose}>
3385
- ${Ju}
3385
+ ${Xu}
3386
3386
  </button>
3387
3387
  </div>
3388
3388
  <p style="margin: 0 0 8px; color: rgba(255,255,255,0.7); font-size: 14px; line-height: 1.5;">
@@ -3408,13 +3408,13 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3408
3408
  </div>
3409
3409
  </div>
3410
3410
  </div>
3411
- `}function ny(e,t){const n=t.addFieldKey.trim().length>0,i=s=>{s.preventDefault(),n&&t.onAddFieldSubmit()};return u`
3411
+ `}function sy(e,t){const n=t.addFieldKey.trim().length>0,i=s=>{s.preventDefault(),n&&t.onAddFieldSubmit()};return u`
3412
3412
  <div class="event-modal-overlay" @click=${t.onAddFieldClose}>
3413
3413
  <div class="event-modal" style="width: min(400px, 100%);" @click=${s=>s.stopPropagation()}>
3414
3414
  <div class="event-modal__header">
3415
3415
  <div class="event-modal__title">Add Field</div>
3416
3416
  <button class="event-modal__close" @click=${t.onAddFieldClose}>
3417
- ${Ju}
3417
+ ${Xu}
3418
3418
  </button>
3419
3419
  </div>
3420
3420
  <p style="margin: 0 0 16px; color: rgba(255,255,255,0.5); font-size: 13px;">
@@ -3459,7 +3459,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3459
3459
  </form>
3460
3460
  </div>
3461
3461
  </div>
3462
- `}function iy(e,t){const n=Object.entries(e.fields);return u`
3462
+ `}function oy(e,t){const n=Object.entries(e.fields);return u`
3463
3463
  <div class="contacts-record-fields">
3464
3464
  ${n.length===0?u`<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])=>u`
3465
3465
  <div class="contacts-field-row">
@@ -3506,7 +3506,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3506
3506
  </button>
3507
3507
  </div>
3508
3508
  </div>
3509
- `}function sy(e,t){const n=t.editingId===e.id,i=ey(e),s=i===0?"No fields":`${i} field${i>1?"s":""}`;return u`
3509
+ `}function ay(e,t){const n=t.editingId===e.id,i=ny(e),s=i===0?"No fields":`${i} field${i>1?"s":""}`;return u`
3510
3510
  <div class="contacts-record">
3511
3511
  <div
3512
3512
  class="contacts-record-header"
@@ -3518,9 +3518,9 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3518
3518
  </div>
3519
3519
  <span class="contacts-record-meta">${s}</span>
3520
3520
  </div>
3521
- ${n?iy(e,t):w}
3521
+ ${n?oy(e,t):w}
3522
3522
  </div>
3523
- `}function oy(e){if(!e.connected)return u`
3523
+ `}function ry(e){if(!e.connected)return u`
3524
3524
  <div class="setup-container">
3525
3525
  <div class="setup-card">
3526
3526
  <div class="setup-spinner"></div>
@@ -3616,7 +3616,7 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3616
3616
  <div style="margin-top: 16px;">
3617
3617
  ${e.records.length===0?u`<div class="contacts-empty">
3618
3618
  ${e.searchQuery.trim()?`No records matching "${e.searchQuery}".`:"No contact records yet. Add one to get started."}
3619
- </div>`:e.records.map(o=>sy(o,e))}
3619
+ </div>`:e.records.map(o=>ay(o,e))}
3620
3620
  </div>
3621
3621
 
3622
3622
  <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
@@ -3628,14 +3628,14 @@ ${r}`)}return e.chatStream="","working"}else if(t.state==="block"){const a=Jt(t.
3628
3628
  </div>
3629
3629
  </div>
3630
3630
 
3631
- ${i?ty(i,e):w}
3632
- ${s?ny(s,e):w}
3633
- `}const Yu={CHILD:2},Xu=e=>(...t)=>({_$litDirective$:e,values:t});let Zu=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:ay}=Yp,Qr=e=>e,Jr=()=>document.createComment(""),Sn=(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(Jr(),s),r=i.insertBefore(Jr(),s);n=new ay(a,r,e,e.options)}else{const a=n._$AB.nextSibling,r=n._$AM,l=r!==e;if(l){let c;(o=n._$AQ)==null||o.call(n,e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==r._$AU&&n._$AP(c)}if(a!==s||l){let c=n._$AA;for(;c!==a;){const d=Qr(c).nextSibling;Qr(i).insertBefore(c,s),c=d}}}return n},bt=(e,t,n=e)=>(e._$AI(t,n),e),ry={},ly=(e,t=ry)=>e._$AH=t,cy=e=>e._$AH,eo=e=>{e._$AR(),e._$AA.remove()};const Yr=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},uy=Xu(class extends Zu{constructor(e){if(super(e),e.type!==Yu.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=cy(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 c,d,m=0,v=s.length-1,p=0,b=o.length-1;for(;m<=v&&p<=b;)if(s[m]===null)m++;else if(s[v]===null)v--;else if(r[m]===a[p])l[p]=bt(s[m],o[p]),m++,p++;else if(r[v]===a[b])l[b]=bt(s[v],o[b]),v--,b--;else if(r[m]===a[b])l[b]=bt(s[m],o[b]),Sn(e,l[b+1],s[m]),m++,b--;else if(r[v]===a[p])l[p]=bt(s[v],o[p]),Sn(e,s[m],s[v]),v--,p++;else if(c===void 0&&(c=Yr(a,p,b),d=Yr(r,m,v)),c.has(r[m]))if(c.has(r[v])){const x=d.get(a[p]),C=x!==void 0?s[x]:null;if(C===null){const A=Sn(e,s[m]);bt(A,o[p]),l[p]=A}else l[p]=bt(C,o[p]),Sn(e,s[m],C),s[x]=null;p++}else eo(s[v]),v--;else eo(s[m]),m++;for(;p<=b;){const x=Sn(e,l[b+1]);bt(x,o[p]),l[p++]=x}for(;m<=v;){const x=s[m++];x!==null&&eo(x)}return this.ut=a,ly(e,l),pt}});class qo extends Zu{constructor(t){if(super(t),this.it=w,t.type!==Yu.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===pt)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:[]}}}qo.directiveName="unsafeHTML",qo.resultType=1;const is=Xu(qo);const{entries:ed,setPrototypeOf:Xr,isFrozen:dy,getPrototypeOf:py,getOwnPropertyDescriptor:hy}=Object;let{freeze:xe,seal:Pe,create:Ho}=Object,{apply:jo,construct:Vo}=typeof Reflect<"u"&&Reflect;xe||(xe=function(t){return t});Pe||(Pe=function(t){return t});jo||(jo=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)});Vo||(Vo=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 $i=$e(Array.prototype.forEach),gy=$e(Array.prototype.lastIndexOf),Zr=$e(Array.prototype.pop),An=$e(Array.prototype.push),fy=$e(Array.prototype.splice),Ui=$e(String.prototype.toLowerCase),to=$e(String.prototype.toString),no=$e(String.prototype.match),Cn=$e(String.prototype.replace),my=$e(String.prototype.indexOf),yy=$e(String.prototype.trim),_e=$e(Object.prototype.hasOwnProperty),we=$e(RegExp.prototype.test),En=vy(TypeError);function $e(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 jo(e,t,i)}}function vy(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Vo(e,n)}}function j(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ui;Xr&&Xr(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(dy(t)||(t[i]=o),s=o)}e[s]=!0}return e}function by(e){for(let t=0;t<e.length;t++)_e(e,t)||(e[t]=null);return e}function We(e){const t=Ho(null);for(const[n,i]of ed(e))_e(e,n)&&(Array.isArray(i)?t[n]=by(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=We(i):t[n]=i);return t}function Tn(e,t){for(;e!==null;){const i=hy(e,t);if(i){if(i.get)return $e(i.get);if(typeof i.value=="function")return $e(i.value)}e=py(e)}function n(){return null}return n}const el=xe(["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"]),io=xe(["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"]),so=xe(["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"]),wy=xe(["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"]),oo=xe(["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"]),ky=xe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),tl=xe(["#text"]),nl=xe(["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"]),ao=xe(["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"]),il=xe(["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"]),Si=xe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),xy=Pe(/\{\{[\w\W]*|[\w\W]*\}\}/gm),$y=Pe(/<%[\w\W]*|[\w\W]*%>/gm),Sy=Pe(/\$\{[\w\W]*/gm),Ay=Pe(/^data-[\-\w.\u00B7-\uFFFF]+$/),Cy=Pe(/^aria-[\-\w]+$/),td=Pe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ey=Pe(/^(?:\w+script|data):/i),Ty=Pe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nd=Pe(/^html$/i),Py=Pe(/^[a-z][.\w]*(-[.\w]+)+$/i);var sl=Object.freeze({__proto__:null,ARIA_ATTR:Cy,ATTR_WHITESPACE:Ty,CUSTOM_ELEMENT:Py,DATA_ATTR:Ay,DOCTYPE_NAME:nd,ERB_EXPR:$y,IS_ALLOWED_URI:td,IS_SCRIPT_OR_DATA:Ey,MUSTACHE_EXPR:xy,TMPLIT_EXPR:Sy});const Pn={element:1,text:3,progressingInstruction:7,comment:8,document:9},_y=function(){return typeof window>"u"?null:window},My=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}},ol=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function id(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_y();const t=W=>id(W);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==Pn.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:c,NamedNodeMap:d=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:m,DOMParser:v,trustedTypes:p}=e,b=l.prototype,x=Tn(b,"cloneNode"),C=Tn(b,"remove"),A=Tn(b,"nextSibling"),T=Tn(b,"childNodes"),M=Tn(b,"parentNode");if(typeof a=="function"){const W=n.createElement("template");W.content&&W.content.ownerDocument&&(n=W.content.ownerDocument)}let N,y="";const{implementation:k,createNodeIterator:S,createDocumentFragment:P,getElementsByTagName:I}=n,{importNode:B}=i;let L=ol();t.isSupported=typeof ed=="function"&&typeof M=="function"&&k&&k.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:F,ERB_EXPR:q,TMPLIT_EXPR:Y,DATA_ATTR:ue,ARIA_ATTR:Ve,IS_SCRIPT_OR_DATA:_s,ATTR_WHITESPACE:si,CUSTOM_ELEMENT:Ms}=sl;let{IS_ALLOWED_URI:oi}=sl,ae=null;const ai=j({},[...el,...io,...so,...oo,...tl]);let re=null;const ri=j({},[...nl,...ao,...il,...Si]);let ie=Object.seal(Ho(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}})),ft=null,bn=null;const st=Object.seal(Ho(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let li=!0,_=!0,D=!1,K=!0,H=!1,oe=!0,te=!1,be=!1,ot=!1,Wt=!1,ci=!1,ui=!1,nr=!0,ir=!1;const wp="user-content-";let Is=!0,wn=!1,zt={},Ne=null;const Rs=j({},["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 sr=null;const or=j({},["audio","video","img","source","image","track"]);let Ls=null;const ar=j({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),di="http://www.w3.org/1998/Math/MathML",pi="http://www.w3.org/2000/svg",Ge="http://www.w3.org/1999/xhtml";let Kt=Ge,Bs=!1,Ds=null;const kp=j({},[di,pi,Ge],to);let hi=j({},["mi","mo","mn","ms","mtext"]),gi=j({},["annotation-xml"]);const xp=j({},["title","style","font","a","script"]);let kn=null;const $p=["application/xhtml+xml","text/html"],Sp="text/html";let de=null,qt=null;const Ap=n.createElement("form"),rr=function($){return $ instanceof RegExp||$ instanceof Function},Ns=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(qt&&qt===$)){if((!$||typeof $!="object")&&($={}),$=We($),kn=$p.indexOf($.PARSER_MEDIA_TYPE)===-1?Sp:$.PARSER_MEDIA_TYPE,de=kn==="application/xhtml+xml"?to:Ui,ae=_e($,"ALLOWED_TAGS")?j({},$.ALLOWED_TAGS,de):ai,re=_e($,"ALLOWED_ATTR")?j({},$.ALLOWED_ATTR,de):ri,Ds=_e($,"ALLOWED_NAMESPACES")?j({},$.ALLOWED_NAMESPACES,to):kp,Ls=_e($,"ADD_URI_SAFE_ATTR")?j(We(ar),$.ADD_URI_SAFE_ATTR,de):ar,sr=_e($,"ADD_DATA_URI_TAGS")?j(We(or),$.ADD_DATA_URI_TAGS,de):or,Ne=_e($,"FORBID_CONTENTS")?j({},$.FORBID_CONTENTS,de):Rs,ft=_e($,"FORBID_TAGS")?j({},$.FORBID_TAGS,de):We({}),bn=_e($,"FORBID_ATTR")?j({},$.FORBID_ATTR,de):We({}),zt=_e($,"USE_PROFILES")?$.USE_PROFILES:!1,li=$.ALLOW_ARIA_ATTR!==!1,_=$.ALLOW_DATA_ATTR!==!1,D=$.ALLOW_UNKNOWN_PROTOCOLS||!1,K=$.ALLOW_SELF_CLOSE_IN_ATTR!==!1,H=$.SAFE_FOR_TEMPLATES||!1,oe=$.SAFE_FOR_XML!==!1,te=$.WHOLE_DOCUMENT||!1,Wt=$.RETURN_DOM||!1,ci=$.RETURN_DOM_FRAGMENT||!1,ui=$.RETURN_TRUSTED_TYPE||!1,ot=$.FORCE_BODY||!1,nr=$.SANITIZE_DOM!==!1,ir=$.SANITIZE_NAMED_PROPS||!1,Is=$.KEEP_CONTENT!==!1,wn=$.IN_PLACE||!1,oi=$.ALLOWED_URI_REGEXP||td,Kt=$.NAMESPACE||Ge,hi=$.MATHML_TEXT_INTEGRATION_POINTS||hi,gi=$.HTML_INTEGRATION_POINTS||gi,ie=$.CUSTOM_ELEMENT_HANDLING||{},$.CUSTOM_ELEMENT_HANDLING&&rr($.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(ie.tagNameCheck=$.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$.CUSTOM_ELEMENT_HANDLING&&rr($.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(ie.attributeNameCheck=$.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$.CUSTOM_ELEMENT_HANDLING&&typeof $.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(ie.allowCustomizedBuiltInElements=$.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),H&&(_=!1),ci&&(Wt=!0),zt&&(ae=j({},tl),re=[],zt.html===!0&&(j(ae,el),j(re,nl)),zt.svg===!0&&(j(ae,io),j(re,ao),j(re,Si)),zt.svgFilters===!0&&(j(ae,so),j(re,ao),j(re,Si)),zt.mathMl===!0&&(j(ae,oo),j(re,il),j(re,Si))),$.ADD_TAGS&&(typeof $.ADD_TAGS=="function"?st.tagCheck=$.ADD_TAGS:(ae===ai&&(ae=We(ae)),j(ae,$.ADD_TAGS,de))),$.ADD_ATTR&&(typeof $.ADD_ATTR=="function"?st.attributeCheck=$.ADD_ATTR:(re===ri&&(re=We(re)),j(re,$.ADD_ATTR,de))),$.ADD_URI_SAFE_ATTR&&j(Ls,$.ADD_URI_SAFE_ATTR,de),$.FORBID_CONTENTS&&(Ne===Rs&&(Ne=We(Ne)),j(Ne,$.FORBID_CONTENTS,de)),$.ADD_FORBID_CONTENTS&&(Ne===Rs&&(Ne=We(Ne)),j(Ne,$.ADD_FORBID_CONTENTS,de)),Is&&(ae["#text"]=!0),te&&j(ae,["html","head","body"]),ae.table&&(j(ae,["tbody"]),delete ft.tbody),$.TRUSTED_TYPES_POLICY){if(typeof $.TRUSTED_TYPES_POLICY.createHTML!="function")throw En('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw En('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');N=$.TRUSTED_TYPES_POLICY,y=N.createHTML("")}else N===void 0&&(N=My(p,s)),N!==null&&typeof y=="string"&&(y=N.createHTML(""));xe&&xe($),qt=$}},lr=j({},[...io,...so,...wy]),cr=j({},[...oo,...ky]),Cp=function($){let R=M($);(!R||!R.tagName)&&(R={namespaceURI:Kt,tagName:"template"});const O=Ui($.tagName),ne=Ui(R.tagName);return Ds[$.namespaceURI]?$.namespaceURI===pi?R.namespaceURI===Ge?O==="svg":R.namespaceURI===di?O==="svg"&&(ne==="annotation-xml"||hi[ne]):!!lr[O]:$.namespaceURI===di?R.namespaceURI===Ge?O==="math":R.namespaceURI===pi?O==="math"&&gi[ne]:!!cr[O]:$.namespaceURI===Ge?R.namespaceURI===pi&&!gi[ne]||R.namespaceURI===di&&!hi[ne]?!1:!cr[O]&&(xp[O]||!lr[O]):!!(kn==="application/xhtml+xml"&&Ds[$.namespaceURI]):!1},Ue=function($){An(t.removed,{element:$});try{M($).removeChild($)}catch{C($)}},mt=function($,R){try{An(t.removed,{attribute:R.getAttributeNode($),from:R})}catch{An(t.removed,{attribute:null,from:R})}if(R.removeAttribute($),$==="is")if(Wt||ci)try{Ue(R)}catch{}else try{R.setAttribute($,"")}catch{}},ur=function($){let R=null,O=null;if(ot)$="<remove></remove>"+$;else{const ce=no($,/^[\r\n\t ]+/);O=ce&&ce[0]}kn==="application/xhtml+xml"&&Kt===Ge&&($='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$+"</body></html>");const ne=N?N.createHTML($):$;if(Kt===Ge)try{R=new v().parseFromString(ne,kn)}catch{}if(!R||!R.documentElement){R=k.createDocument(Kt,"template",null);try{R.documentElement.innerHTML=Bs?y:ne}catch{}}const me=R.body||R.documentElement;return $&&O&&me.insertBefore(n.createTextNode(O),me.childNodes[0]||null),Kt===Ge?I.call(R,te?"html":"body")[0]:te?R.documentElement:me},dr=function($){return S.call($.ownerDocument||$,$,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Us=function($){return $ instanceof m&&(typeof $.nodeName!="string"||typeof $.textContent!="string"||typeof $.removeChild!="function"||!($.attributes instanceof d)||typeof $.removeAttribute!="function"||typeof $.setAttribute!="function"||typeof $.namespaceURI!="string"||typeof $.insertBefore!="function"||typeof $.hasChildNodes!="function")},pr=function($){return typeof r=="function"&&$ instanceof r};function Qe(W,$,R){$i(W,O=>{O.call(t,$,R,qt)})}const hr=function($){let R=null;if(Qe(L.beforeSanitizeElements,$,null),Us($))return Ue($),!0;const O=de($.nodeName);if(Qe(L.uponSanitizeElement,$,{tagName:O,allowedTags:ae}),oe&&$.hasChildNodes()&&!pr($.firstElementChild)&&we(/<[/\w!]/g,$.innerHTML)&&we(/<[/\w!]/g,$.textContent)||$.nodeType===Pn.progressingInstruction||oe&&$.nodeType===Pn.comment&&we(/<[/\w]/g,$.data))return Ue($),!0;if(!(st.tagCheck instanceof Function&&st.tagCheck(O))&&(!ae[O]||ft[O])){if(!ft[O]&&fr(O)&&(ie.tagNameCheck instanceof RegExp&&we(ie.tagNameCheck,O)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck(O)))return!1;if(Is&&!Ne[O]){const ne=M($)||$.parentNode,me=T($)||$.childNodes;if(me&&ne){const ce=me.length;for(let Se=ce-1;Se>=0;--Se){const Je=x(me[Se],!0);Je.__removalCount=($.__removalCount||0)+1,ne.insertBefore(Je,A($))}}}return Ue($),!0}return $ instanceof l&&!Cp($)||(O==="noscript"||O==="noembed"||O==="noframes")&&we(/<\/no(script|embed|frames)/i,$.innerHTML)?(Ue($),!0):(H&&$.nodeType===Pn.text&&(R=$.textContent,$i([F,q,Y],ne=>{R=Cn(R,ne," ")}),$.textContent!==R&&(An(t.removed,{element:$.cloneNode()}),$.textContent=R)),Qe(L.afterSanitizeElements,$,null),!1)},gr=function($,R,O){if(nr&&(R==="id"||R==="name")&&(O in n||O in Ap))return!1;if(!(_&&!bn[R]&&we(ue,R))){if(!(li&&we(Ve,R))){if(!(st.attributeCheck instanceof Function&&st.attributeCheck(R,$))){if(!re[R]||bn[R]){if(!(fr($)&&(ie.tagNameCheck instanceof RegExp&&we(ie.tagNameCheck,$)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck($))&&(ie.attributeNameCheck instanceof RegExp&&we(ie.attributeNameCheck,R)||ie.attributeNameCheck instanceof Function&&ie.attributeNameCheck(R,$))||R==="is"&&ie.allowCustomizedBuiltInElements&&(ie.tagNameCheck instanceof RegExp&&we(ie.tagNameCheck,O)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck(O))))return!1}else if(!Ls[R]){if(!we(oi,Cn(O,si,""))){if(!((R==="src"||R==="xlink:href"||R==="href")&&$!=="script"&&my(O,"data:")===0&&sr[$])){if(!(D&&!we(_s,Cn(O,si,"")))){if(O)return!1}}}}}}}return!0},fr=function($){return $!=="annotation-xml"&&no($,Ms)},mr=function($){Qe(L.beforeSanitizeAttributes,$,null);const{attributes:R}=$;if(!R||Us($))return;const O={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:re,forceKeepAttr:void 0};let ne=R.length;for(;ne--;){const me=R[ne],{name:ce,namespaceURI:Se,value:Je}=me,Ht=de(ce),Os=Je;let ge=ce==="value"?Os:yy(Os);if(O.attrName=Ht,O.attrValue=ge,O.keepAttr=!0,O.forceKeepAttr=void 0,Qe(L.uponSanitizeAttribute,$,O),ge=O.attrValue,ir&&(Ht==="id"||Ht==="name")&&(mt(ce,$),ge=wp+ge),oe&&we(/((--!?|])>)|<\/(style|title|textarea)/i,ge)){mt(ce,$);continue}if(Ht==="attributename"&&no(ge,"href")){mt(ce,$);continue}if(O.forceKeepAttr)continue;if(!O.keepAttr){mt(ce,$);continue}if(!K&&we(/\/>/i,ge)){mt(ce,$);continue}H&&$i([F,q,Y],vr=>{ge=Cn(ge,vr," ")});const yr=de($.nodeName);if(!gr(yr,Ht,ge)){mt(ce,$);continue}if(N&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Se)switch(p.getAttributeType(yr,Ht)){case"TrustedHTML":{ge=N.createHTML(ge);break}case"TrustedScriptURL":{ge=N.createScriptURL(ge);break}}if(ge!==Os)try{Se?$.setAttributeNS(Se,ce,ge):$.setAttribute(ce,ge),Us($)?Ue($):Zr(t.removed)}catch{mt(ce,$)}}Qe(L.afterSanitizeAttributes,$,null)},Ep=function W($){let R=null;const O=dr($);for(Qe(L.beforeSanitizeShadowDOM,$,null);R=O.nextNode();)Qe(L.uponSanitizeShadowNode,R,null),hr(R),mr(R),R.content instanceof o&&W(R.content);Qe(L.afterSanitizeShadowDOM,$,null)};return t.sanitize=function(W){let $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},R=null,O=null,ne=null,me=null;if(Bs=!W,Bs&&(W="<!-->"),typeof W!="string"&&!pr(W))if(typeof W.toString=="function"){if(W=W.toString(),typeof W!="string")throw En("dirty is not a string, aborting")}else throw En("toString is not a function");if(!t.isSupported)return W;if(be||Ns($),t.removed=[],typeof W=="string"&&(wn=!1),wn){if(W.nodeName){const Je=de(W.nodeName);if(!ae[Je]||ft[Je])throw En("root node is forbidden and cannot be sanitized in-place")}}else if(W instanceof r)R=ur("<!---->"),O=R.ownerDocument.importNode(W,!0),O.nodeType===Pn.element&&O.nodeName==="BODY"||O.nodeName==="HTML"?R=O:R.appendChild(O);else{if(!Wt&&!H&&!te&&W.indexOf("<")===-1)return N&&ui?N.createHTML(W):W;if(R=ur(W),!R)return Wt?null:ui?y:""}R&&ot&&Ue(R.firstChild);const ce=dr(wn?W:R);for(;ne=ce.nextNode();)hr(ne),mr(ne),ne.content instanceof o&&Ep(ne.content);if(wn)return W;if(Wt){if(ci)for(me=P.call(R.ownerDocument);R.firstChild;)me.appendChild(R.firstChild);else me=R;return(re.shadowroot||re.shadowrootmode)&&(me=B.call(i,me,!0)),me}let Se=te?R.outerHTML:R.innerHTML;return te&&ae["!doctype"]&&R.ownerDocument&&R.ownerDocument.doctype&&R.ownerDocument.doctype.name&&we(nd,R.ownerDocument.doctype.name)&&(Se="<!DOCTYPE "+R.ownerDocument.doctype.name+`>
3634
- `+Se),H&&$i([F,q,Y],Je=>{Se=Cn(Se,Je," ")}),N&&ui?N.createHTML(Se):Se},t.setConfig=function(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ns(W),be=!0},t.clearConfig=function(){qt=null,be=!1},t.isValidAttribute=function(W,$,R){qt||Ns({});const O=de(W),ne=de($);return gr(O,ne,R)},t.addHook=function(W,$){typeof $=="function"&&An(L[W],$)},t.removeHook=function(W,$){if($!==void 0){const R=gy(L[W],$);return R===-1?void 0:fy(L[W],R,1)[0]}return Zr(L[W])},t.removeHooks=function(W){L[W]=[]},t.removeAllHooks=function(){L=ol()},t}var Go=id();function Ba(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ot=Ba();function sd(e){Ot=e}var Fn={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(ke.caret,"$1"),n=n.replace(s,a),i},getRegex:()=>new RegExp(n,t)};return i}var Iy=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),ke={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")},Ry=/^(?:[ \t]*(?:\n|$))+/,Ly=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,By=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ni=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Dy=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Da=/(?:[*+-]|\d{1,9}[.)])/,od=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ad=J(od).replace(/bull/g,Da).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(),Ny=J(od).replace(/bull/g,Da).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(),Na=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Uy=/^[^\n]+/,Ua=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Oy=J(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ua).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Fy=J(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Da).getRegex(),As="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",Oa=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Wy=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",Oa).replace("tag",As).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),rd=J(Na).replace("hr",ni).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",As).getRegex(),zy=J(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",rd).getRegex(),Fa={blockquote:zy,code:Ly,def:Oy,fences:By,heading:Dy,hr:ni,html:Wy,lheading:ad,list:Fy,newline:Ry,paragraph:rd,table:Fn,text:Uy},al=J("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ni).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",As).getRegex(),Ky={...Fa,lheading:Ny,table:al,paragraph:J(Na).replace("hr",ni).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",al).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",As).getRegex()},qy={...Fa,html:J(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Oa).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:Fn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:J(Na).replace("hr",ni).replace("heading",` *#{1,6} *[^
3635
- ]`).replace("lheading",ad).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Hy=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,jy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ld=/^( {2,}|\\)\n(?!\s*$)/,Vy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Cs=/[\p{P}\p{S}]/u,Wa=/[\s\p{P}\p{S}]/u,cd=/[^\s\p{P}\p{S}]/u,Gy=J(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Wa).getRegex(),ud=/(?!~)[\p{P}\p{S}]/u,Qy=/(?!~)[\s\p{P}\p{S}]/u,Jy=/(?:[^\s\p{P}\p{S}]|~)/u,Yy=J(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Iy?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),dd=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Xy=J(dd,"u").replace(/punct/g,Cs).getRegex(),Zy=J(dd,"u").replace(/punct/g,ud).getRegex(),pd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",ev=J(pd,"gu").replace(/notPunctSpace/g,cd).replace(/punctSpace/g,Wa).replace(/punct/g,Cs).getRegex(),tv=J(pd,"gu").replace(/notPunctSpace/g,Jy).replace(/punctSpace/g,Qy).replace(/punct/g,ud).getRegex(),nv=J("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,cd).replace(/punctSpace/g,Wa).replace(/punct/g,Cs).getRegex(),iv=J(/\\(punct)/,"gu").replace(/punct/g,Cs).getRegex(),sv=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(),ov=J(Oa).replace("(?:-->|$)","-->").getRegex(),av=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",ov).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ss=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,rv=J(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",ss).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),hd=J(/^!?\[(label)\]\[(ref)\]/).replace("label",ss).replace("ref",Ua).getRegex(),gd=J(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ua).getRegex(),lv=J("reflink|nolink(?!\\()","g").replace("reflink",hd).replace("nolink",gd).getRegex(),rl=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,za={_backpedal:Fn,anyPunctuation:iv,autolink:sv,blockSkip:Yy,br:ld,code:jy,del:Fn,emStrongLDelim:Xy,emStrongRDelimAst:ev,emStrongRDelimUnd:nv,escape:Hy,link:rv,nolink:gd,punctuation:Gy,reflink:hd,reflinkSearch:lv,tag:av,text:Vy,url:Fn},cv={...za,link:J(/^!?\[(label)\]\((.*?)\)/).replace("label",ss).getRegex(),reflink:J(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ss).getRegex()},Qo={...za,emStrongRDelimAst:tv,emStrongLDelim:Zy,url:J(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",rl).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",rl).getRegex()},uv={...Qo,br:J(ld).replace("{2,}","*").getRegex(),text:J(Qo.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ai={normal:Fa,gfm:Ky,pedantic:qy},_n={normal:za,gfm:Qo,breaks:uv,pedantic:cv},dv={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ll=e=>dv[e];function Ze(e,t){if(t){if(ke.escapeTest.test(e))return e.replace(ke.escapeReplace,ll)}else if(ke.escapeTestNoEncode.test(e))return e.replace(ke.escapeReplaceNoEncode,ll);return e}function cl(e){try{e=encodeURI(e).replace(ke.percentDecode,"%")}catch{return null}return e}function ul(e,t){var o;let n=e.replace(ke.findPipe,(a,r,l)=>{let c=!1,d=r;for(;--d>=0&&l[d]==="\\";)c=!c;return c?"|":" |"}),i=n.split(ke.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(ke.slashPipe,"|");return i}function Mn(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 pv(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 dl(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 hv(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
3631
+ ${i?iy(i,e):w}
3632
+ ${s?sy(s,e):w}
3633
+ `}const Zu={CHILD:2},ed=e=>(...t)=>({_$litDirective$:e,values:t});let td=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:ly}=Zp,Qr=e=>e,Jr=()=>document.createComment(""),Sn=(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(Jr(),s),r=i.insertBefore(Jr(),s);n=new ly(a,r,e,e.options)}else{const a=n._$AB.nextSibling,r=n._$AM,l=r!==e;if(l){let c;(o=n._$AQ)==null||o.call(n,e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==r._$AU&&n._$AP(c)}if(a!==s||l){let c=n._$AA;for(;c!==a;){const d=Qr(c).nextSibling;Qr(i).insertBefore(c,s),c=d}}}return n},bt=(e,t,n=e)=>(e._$AI(t,n),e),cy={},uy=(e,t=cy)=>e._$AH=t,dy=e=>e._$AH,eo=e=>{e._$AR(),e._$AA.remove()};const Yr=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},py=ed(class extends td{constructor(e){if(super(e),e.type!==Zu.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=dy(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 c,d,m=0,v=s.length-1,p=0,b=o.length-1;for(;m<=v&&p<=b;)if(s[m]===null)m++;else if(s[v]===null)v--;else if(r[m]===a[p])l[p]=bt(s[m],o[p]),m++,p++;else if(r[v]===a[b])l[b]=bt(s[v],o[b]),v--,b--;else if(r[m]===a[b])l[b]=bt(s[m],o[b]),Sn(e,l[b+1],s[m]),m++,b--;else if(r[v]===a[p])l[p]=bt(s[v],o[p]),Sn(e,s[m],s[v]),v--,p++;else if(c===void 0&&(c=Yr(a,p,b),d=Yr(r,m,v)),c.has(r[m]))if(c.has(r[v])){const x=d.get(a[p]),C=x!==void 0?s[x]:null;if(C===null){const A=Sn(e,s[m]);bt(A,o[p]),l[p]=A}else l[p]=bt(C,o[p]),Sn(e,s[m],C),s[x]=null;p++}else eo(s[v]),v--;else eo(s[m]),m++;for(;p<=b;){const x=Sn(e,l[b+1]);bt(x,o[p]),l[p++]=x}for(;m<=v;){const x=s[m++];x!==null&&eo(x)}return this.ut=a,uy(e,l),pt}});class qo extends td{constructor(t){if(super(t),this.it=w,t.type!==Zu.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===pt)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:[]}}}qo.directiveName="unsafeHTML",qo.resultType=1;const is=ed(qo);const{entries:nd,setPrototypeOf:Xr,isFrozen:hy,getPrototypeOf:gy,getOwnPropertyDescriptor:fy}=Object;let{freeze:xe,seal:Pe,create:Ho}=Object,{apply:jo,construct:Vo}=typeof Reflect<"u"&&Reflect;xe||(xe=function(t){return t});Pe||(Pe=function(t){return t});jo||(jo=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)});Vo||(Vo=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 $i=$e(Array.prototype.forEach),my=$e(Array.prototype.lastIndexOf),Zr=$e(Array.prototype.pop),An=$e(Array.prototype.push),yy=$e(Array.prototype.splice),Ui=$e(String.prototype.toLowerCase),to=$e(String.prototype.toString),no=$e(String.prototype.match),Cn=$e(String.prototype.replace),vy=$e(String.prototype.indexOf),by=$e(String.prototype.trim),_e=$e(Object.prototype.hasOwnProperty),we=$e(RegExp.prototype.test),En=wy(TypeError);function $e(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 jo(e,t,i)}}function wy(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Vo(e,n)}}function j(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ui;Xr&&Xr(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(hy(t)||(t[i]=o),s=o)}e[s]=!0}return e}function ky(e){for(let t=0;t<e.length;t++)_e(e,t)||(e[t]=null);return e}function We(e){const t=Ho(null);for(const[n,i]of nd(e))_e(e,n)&&(Array.isArray(i)?t[n]=ky(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=We(i):t[n]=i);return t}function Tn(e,t){for(;e!==null;){const i=fy(e,t);if(i){if(i.get)return $e(i.get);if(typeof i.value=="function")return $e(i.value)}e=gy(e)}function n(){return null}return n}const el=xe(["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"]),io=xe(["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"]),so=xe(["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"]),xy=xe(["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"]),oo=xe(["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"]),$y=xe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),tl=xe(["#text"]),nl=xe(["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"]),ao=xe(["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"]),il=xe(["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"]),Si=xe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Sy=Pe(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Ay=Pe(/<%[\w\W]*|[\w\W]*%>/gm),Cy=Pe(/\$\{[\w\W]*/gm),Ey=Pe(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ty=Pe(/^aria-[\-\w]+$/),id=Pe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Py=Pe(/^(?:\w+script|data):/i),_y=Pe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),sd=Pe(/^html$/i),My=Pe(/^[a-z][.\w]*(-[.\w]+)+$/i);var sl=Object.freeze({__proto__:null,ARIA_ATTR:Ty,ATTR_WHITESPACE:_y,CUSTOM_ELEMENT:My,DATA_ATTR:Ey,DOCTYPE_NAME:sd,ERB_EXPR:Ay,IS_ALLOWED_URI:id,IS_SCRIPT_OR_DATA:Py,MUSTACHE_EXPR:Sy,TMPLIT_EXPR:Cy});const Pn={element:1,text:3,progressingInstruction:7,comment:8,document:9},Iy=function(){return typeof window>"u"?null:window},Ry=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}},ol=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function od(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Iy();const t=W=>od(W);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==Pn.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:c,NamedNodeMap:d=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:m,DOMParser:v,trustedTypes:p}=e,b=l.prototype,x=Tn(b,"cloneNode"),C=Tn(b,"remove"),A=Tn(b,"nextSibling"),T=Tn(b,"childNodes"),M=Tn(b,"parentNode");if(typeof a=="function"){const W=n.createElement("template");W.content&&W.content.ownerDocument&&(n=W.content.ownerDocument)}let N,y="";const{implementation:k,createNodeIterator:S,createDocumentFragment:P,getElementsByTagName:I}=n,{importNode:B}=i;let L=ol();t.isSupported=typeof nd=="function"&&typeof M=="function"&&k&&k.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:F,ERB_EXPR:q,TMPLIT_EXPR:Y,DATA_ATTR:ue,ARIA_ATTR:Ve,IS_SCRIPT_OR_DATA:_s,ATTR_WHITESPACE:si,CUSTOM_ELEMENT:Ms}=sl;let{IS_ALLOWED_URI:oi}=sl,ae=null;const ai=j({},[...el,...io,...so,...oo,...tl]);let re=null;const ri=j({},[...nl,...ao,...il,...Si]);let ie=Object.seal(Ho(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}})),ft=null,bn=null;const st=Object.seal(Ho(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let li=!0,_=!0,D=!1,K=!0,H=!1,oe=!0,te=!1,be=!1,ot=!1,Wt=!1,ci=!1,ui=!1,nr=!0,ir=!1;const xp="user-content-";let Is=!0,wn=!1,zt={},Ne=null;const Rs=j({},["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 sr=null;const or=j({},["audio","video","img","source","image","track"]);let Ls=null;const ar=j({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),di="http://www.w3.org/1998/Math/MathML",pi="http://www.w3.org/2000/svg",Ge="http://www.w3.org/1999/xhtml";let Kt=Ge,Bs=!1,Ds=null;const $p=j({},[di,pi,Ge],to);let hi=j({},["mi","mo","mn","ms","mtext"]),gi=j({},["annotation-xml"]);const Sp=j({},["title","style","font","a","script"]);let kn=null;const Ap=["application/xhtml+xml","text/html"],Cp="text/html";let de=null,qt=null;const Ep=n.createElement("form"),rr=function($){return $ instanceof RegExp||$ instanceof Function},Ns=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(qt&&qt===$)){if((!$||typeof $!="object")&&($={}),$=We($),kn=Ap.indexOf($.PARSER_MEDIA_TYPE)===-1?Cp:$.PARSER_MEDIA_TYPE,de=kn==="application/xhtml+xml"?to:Ui,ae=_e($,"ALLOWED_TAGS")?j({},$.ALLOWED_TAGS,de):ai,re=_e($,"ALLOWED_ATTR")?j({},$.ALLOWED_ATTR,de):ri,Ds=_e($,"ALLOWED_NAMESPACES")?j({},$.ALLOWED_NAMESPACES,to):$p,Ls=_e($,"ADD_URI_SAFE_ATTR")?j(We(ar),$.ADD_URI_SAFE_ATTR,de):ar,sr=_e($,"ADD_DATA_URI_TAGS")?j(We(or),$.ADD_DATA_URI_TAGS,de):or,Ne=_e($,"FORBID_CONTENTS")?j({},$.FORBID_CONTENTS,de):Rs,ft=_e($,"FORBID_TAGS")?j({},$.FORBID_TAGS,de):We({}),bn=_e($,"FORBID_ATTR")?j({},$.FORBID_ATTR,de):We({}),zt=_e($,"USE_PROFILES")?$.USE_PROFILES:!1,li=$.ALLOW_ARIA_ATTR!==!1,_=$.ALLOW_DATA_ATTR!==!1,D=$.ALLOW_UNKNOWN_PROTOCOLS||!1,K=$.ALLOW_SELF_CLOSE_IN_ATTR!==!1,H=$.SAFE_FOR_TEMPLATES||!1,oe=$.SAFE_FOR_XML!==!1,te=$.WHOLE_DOCUMENT||!1,Wt=$.RETURN_DOM||!1,ci=$.RETURN_DOM_FRAGMENT||!1,ui=$.RETURN_TRUSTED_TYPE||!1,ot=$.FORCE_BODY||!1,nr=$.SANITIZE_DOM!==!1,ir=$.SANITIZE_NAMED_PROPS||!1,Is=$.KEEP_CONTENT!==!1,wn=$.IN_PLACE||!1,oi=$.ALLOWED_URI_REGEXP||id,Kt=$.NAMESPACE||Ge,hi=$.MATHML_TEXT_INTEGRATION_POINTS||hi,gi=$.HTML_INTEGRATION_POINTS||gi,ie=$.CUSTOM_ELEMENT_HANDLING||{},$.CUSTOM_ELEMENT_HANDLING&&rr($.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(ie.tagNameCheck=$.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$.CUSTOM_ELEMENT_HANDLING&&rr($.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(ie.attributeNameCheck=$.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$.CUSTOM_ELEMENT_HANDLING&&typeof $.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(ie.allowCustomizedBuiltInElements=$.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),H&&(_=!1),ci&&(Wt=!0),zt&&(ae=j({},tl),re=[],zt.html===!0&&(j(ae,el),j(re,nl)),zt.svg===!0&&(j(ae,io),j(re,ao),j(re,Si)),zt.svgFilters===!0&&(j(ae,so),j(re,ao),j(re,Si)),zt.mathMl===!0&&(j(ae,oo),j(re,il),j(re,Si))),$.ADD_TAGS&&(typeof $.ADD_TAGS=="function"?st.tagCheck=$.ADD_TAGS:(ae===ai&&(ae=We(ae)),j(ae,$.ADD_TAGS,de))),$.ADD_ATTR&&(typeof $.ADD_ATTR=="function"?st.attributeCheck=$.ADD_ATTR:(re===ri&&(re=We(re)),j(re,$.ADD_ATTR,de))),$.ADD_URI_SAFE_ATTR&&j(Ls,$.ADD_URI_SAFE_ATTR,de),$.FORBID_CONTENTS&&(Ne===Rs&&(Ne=We(Ne)),j(Ne,$.FORBID_CONTENTS,de)),$.ADD_FORBID_CONTENTS&&(Ne===Rs&&(Ne=We(Ne)),j(Ne,$.ADD_FORBID_CONTENTS,de)),Is&&(ae["#text"]=!0),te&&j(ae,["html","head","body"]),ae.table&&(j(ae,["tbody"]),delete ft.tbody),$.TRUSTED_TYPES_POLICY){if(typeof $.TRUSTED_TYPES_POLICY.createHTML!="function")throw En('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw En('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');N=$.TRUSTED_TYPES_POLICY,y=N.createHTML("")}else N===void 0&&(N=Ry(p,s)),N!==null&&typeof y=="string"&&(y=N.createHTML(""));xe&&xe($),qt=$}},lr=j({},[...io,...so,...xy]),cr=j({},[...oo,...$y]),Tp=function($){let R=M($);(!R||!R.tagName)&&(R={namespaceURI:Kt,tagName:"template"});const O=Ui($.tagName),ne=Ui(R.tagName);return Ds[$.namespaceURI]?$.namespaceURI===pi?R.namespaceURI===Ge?O==="svg":R.namespaceURI===di?O==="svg"&&(ne==="annotation-xml"||hi[ne]):!!lr[O]:$.namespaceURI===di?R.namespaceURI===Ge?O==="math":R.namespaceURI===pi?O==="math"&&gi[ne]:!!cr[O]:$.namespaceURI===Ge?R.namespaceURI===pi&&!gi[ne]||R.namespaceURI===di&&!hi[ne]?!1:!cr[O]&&(Sp[O]||!lr[O]):!!(kn==="application/xhtml+xml"&&Ds[$.namespaceURI]):!1},Ue=function($){An(t.removed,{element:$});try{M($).removeChild($)}catch{C($)}},mt=function($,R){try{An(t.removed,{attribute:R.getAttributeNode($),from:R})}catch{An(t.removed,{attribute:null,from:R})}if(R.removeAttribute($),$==="is")if(Wt||ci)try{Ue(R)}catch{}else try{R.setAttribute($,"")}catch{}},ur=function($){let R=null,O=null;if(ot)$="<remove></remove>"+$;else{const ce=no($,/^[\r\n\t ]+/);O=ce&&ce[0]}kn==="application/xhtml+xml"&&Kt===Ge&&($='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$+"</body></html>");const ne=N?N.createHTML($):$;if(Kt===Ge)try{R=new v().parseFromString(ne,kn)}catch{}if(!R||!R.documentElement){R=k.createDocument(Kt,"template",null);try{R.documentElement.innerHTML=Bs?y:ne}catch{}}const me=R.body||R.documentElement;return $&&O&&me.insertBefore(n.createTextNode(O),me.childNodes[0]||null),Kt===Ge?I.call(R,te?"html":"body")[0]:te?R.documentElement:me},dr=function($){return S.call($.ownerDocument||$,$,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Us=function($){return $ instanceof m&&(typeof $.nodeName!="string"||typeof $.textContent!="string"||typeof $.removeChild!="function"||!($.attributes instanceof d)||typeof $.removeAttribute!="function"||typeof $.setAttribute!="function"||typeof $.namespaceURI!="string"||typeof $.insertBefore!="function"||typeof $.hasChildNodes!="function")},pr=function($){return typeof r=="function"&&$ instanceof r};function Qe(W,$,R){$i(W,O=>{O.call(t,$,R,qt)})}const hr=function($){let R=null;if(Qe(L.beforeSanitizeElements,$,null),Us($))return Ue($),!0;const O=de($.nodeName);if(Qe(L.uponSanitizeElement,$,{tagName:O,allowedTags:ae}),oe&&$.hasChildNodes()&&!pr($.firstElementChild)&&we(/<[/\w!]/g,$.innerHTML)&&we(/<[/\w!]/g,$.textContent)||$.nodeType===Pn.progressingInstruction||oe&&$.nodeType===Pn.comment&&we(/<[/\w]/g,$.data))return Ue($),!0;if(!(st.tagCheck instanceof Function&&st.tagCheck(O))&&(!ae[O]||ft[O])){if(!ft[O]&&fr(O)&&(ie.tagNameCheck instanceof RegExp&&we(ie.tagNameCheck,O)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck(O)))return!1;if(Is&&!Ne[O]){const ne=M($)||$.parentNode,me=T($)||$.childNodes;if(me&&ne){const ce=me.length;for(let Se=ce-1;Se>=0;--Se){const Je=x(me[Se],!0);Je.__removalCount=($.__removalCount||0)+1,ne.insertBefore(Je,A($))}}}return Ue($),!0}return $ instanceof l&&!Tp($)||(O==="noscript"||O==="noembed"||O==="noframes")&&we(/<\/no(script|embed|frames)/i,$.innerHTML)?(Ue($),!0):(H&&$.nodeType===Pn.text&&(R=$.textContent,$i([F,q,Y],ne=>{R=Cn(R,ne," ")}),$.textContent!==R&&(An(t.removed,{element:$.cloneNode()}),$.textContent=R)),Qe(L.afterSanitizeElements,$,null),!1)},gr=function($,R,O){if(nr&&(R==="id"||R==="name")&&(O in n||O in Ep))return!1;if(!(_&&!bn[R]&&we(ue,R))){if(!(li&&we(Ve,R))){if(!(st.attributeCheck instanceof Function&&st.attributeCheck(R,$))){if(!re[R]||bn[R]){if(!(fr($)&&(ie.tagNameCheck instanceof RegExp&&we(ie.tagNameCheck,$)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck($))&&(ie.attributeNameCheck instanceof RegExp&&we(ie.attributeNameCheck,R)||ie.attributeNameCheck instanceof Function&&ie.attributeNameCheck(R,$))||R==="is"&&ie.allowCustomizedBuiltInElements&&(ie.tagNameCheck instanceof RegExp&&we(ie.tagNameCheck,O)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck(O))))return!1}else if(!Ls[R]){if(!we(oi,Cn(O,si,""))){if(!((R==="src"||R==="xlink:href"||R==="href")&&$!=="script"&&vy(O,"data:")===0&&sr[$])){if(!(D&&!we(_s,Cn(O,si,"")))){if(O)return!1}}}}}}}return!0},fr=function($){return $!=="annotation-xml"&&no($,Ms)},mr=function($){Qe(L.beforeSanitizeAttributes,$,null);const{attributes:R}=$;if(!R||Us($))return;const O={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:re,forceKeepAttr:void 0};let ne=R.length;for(;ne--;){const me=R[ne],{name:ce,namespaceURI:Se,value:Je}=me,Ht=de(ce),Os=Je;let ge=ce==="value"?Os:by(Os);if(O.attrName=Ht,O.attrValue=ge,O.keepAttr=!0,O.forceKeepAttr=void 0,Qe(L.uponSanitizeAttribute,$,O),ge=O.attrValue,ir&&(Ht==="id"||Ht==="name")&&(mt(ce,$),ge=xp+ge),oe&&we(/((--!?|])>)|<\/(style|title|textarea)/i,ge)){mt(ce,$);continue}if(Ht==="attributename"&&no(ge,"href")){mt(ce,$);continue}if(O.forceKeepAttr)continue;if(!O.keepAttr){mt(ce,$);continue}if(!K&&we(/\/>/i,ge)){mt(ce,$);continue}H&&$i([F,q,Y],vr=>{ge=Cn(ge,vr," ")});const yr=de($.nodeName);if(!gr(yr,Ht,ge)){mt(ce,$);continue}if(N&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Se)switch(p.getAttributeType(yr,Ht)){case"TrustedHTML":{ge=N.createHTML(ge);break}case"TrustedScriptURL":{ge=N.createScriptURL(ge);break}}if(ge!==Os)try{Se?$.setAttributeNS(Se,ce,ge):$.setAttribute(ce,ge),Us($)?Ue($):Zr(t.removed)}catch{mt(ce,$)}}Qe(L.afterSanitizeAttributes,$,null)},Pp=function W($){let R=null;const O=dr($);for(Qe(L.beforeSanitizeShadowDOM,$,null);R=O.nextNode();)Qe(L.uponSanitizeShadowNode,R,null),hr(R),mr(R),R.content instanceof o&&W(R.content);Qe(L.afterSanitizeShadowDOM,$,null)};return t.sanitize=function(W){let $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},R=null,O=null,ne=null,me=null;if(Bs=!W,Bs&&(W="<!-->"),typeof W!="string"&&!pr(W))if(typeof W.toString=="function"){if(W=W.toString(),typeof W!="string")throw En("dirty is not a string, aborting")}else throw En("toString is not a function");if(!t.isSupported)return W;if(be||Ns($),t.removed=[],typeof W=="string"&&(wn=!1),wn){if(W.nodeName){const Je=de(W.nodeName);if(!ae[Je]||ft[Je])throw En("root node is forbidden and cannot be sanitized in-place")}}else if(W instanceof r)R=ur("<!---->"),O=R.ownerDocument.importNode(W,!0),O.nodeType===Pn.element&&O.nodeName==="BODY"||O.nodeName==="HTML"?R=O:R.appendChild(O);else{if(!Wt&&!H&&!te&&W.indexOf("<")===-1)return N&&ui?N.createHTML(W):W;if(R=ur(W),!R)return Wt?null:ui?y:""}R&&ot&&Ue(R.firstChild);const ce=dr(wn?W:R);for(;ne=ce.nextNode();)hr(ne),mr(ne),ne.content instanceof o&&Pp(ne.content);if(wn)return W;if(Wt){if(ci)for(me=P.call(R.ownerDocument);R.firstChild;)me.appendChild(R.firstChild);else me=R;return(re.shadowroot||re.shadowrootmode)&&(me=B.call(i,me,!0)),me}let Se=te?R.outerHTML:R.innerHTML;return te&&ae["!doctype"]&&R.ownerDocument&&R.ownerDocument.doctype&&R.ownerDocument.doctype.name&&we(sd,R.ownerDocument.doctype.name)&&(Se="<!DOCTYPE "+R.ownerDocument.doctype.name+`>
3634
+ `+Se),H&&$i([F,q,Y],Je=>{Se=Cn(Se,Je," ")}),N&&ui?N.createHTML(Se):Se},t.setConfig=function(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ns(W),be=!0},t.clearConfig=function(){qt=null,be=!1},t.isValidAttribute=function(W,$,R){qt||Ns({});const O=de(W),ne=de($);return gr(O,ne,R)},t.addHook=function(W,$){typeof $=="function"&&An(L[W],$)},t.removeHook=function(W,$){if($!==void 0){const R=my(L[W],$);return R===-1?void 0:yy(L[W],R,1)[0]}return Zr(L[W])},t.removeHooks=function(W){L[W]=[]},t.removeAllHooks=function(){L=ol()},t}var Go=od();function Ba(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ot=Ba();function ad(e){Ot=e}var Fn={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(ke.caret,"$1"),n=n.replace(s,a),i},getRegex:()=>new RegExp(n,t)};return i}var Ly=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),ke={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")},By=/^(?:[ \t]*(?:\n|$))+/,Dy=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ny=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ni=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Uy=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Da=/(?:[*+-]|\d{1,9}[.)])/,rd=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ld=J(rd).replace(/bull/g,Da).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(),Oy=J(rd).replace(/bull/g,Da).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(),Na=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Fy=/^[^\n]+/,Ua=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Wy=J(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ua).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),zy=J(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Da).getRegex(),As="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",Oa=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ky=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",Oa).replace("tag",As).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),cd=J(Na).replace("hr",ni).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",As).getRegex(),qy=J(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",cd).getRegex(),Fa={blockquote:qy,code:Dy,def:Wy,fences:Ny,heading:Uy,hr:ni,html:Ky,lheading:ld,list:zy,newline:By,paragraph:cd,table:Fn,text:Fy},al=J("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ni).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",As).getRegex(),Hy={...Fa,lheading:Oy,table:al,paragraph:J(Na).replace("hr",ni).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",al).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",As).getRegex()},jy={...Fa,html:J(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Oa).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:Fn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:J(Na).replace("hr",ni).replace("heading",` *#{1,6} *[^
3635
+ ]`).replace("lheading",ld).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Vy=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Gy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ud=/^( {2,}|\\)\n(?!\s*$)/,Qy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Cs=/[\p{P}\p{S}]/u,Wa=/[\s\p{P}\p{S}]/u,dd=/[^\s\p{P}\p{S}]/u,Jy=J(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Wa).getRegex(),pd=/(?!~)[\p{P}\p{S}]/u,Yy=/(?!~)[\s\p{P}\p{S}]/u,Xy=/(?:[^\s\p{P}\p{S}]|~)/u,Zy=J(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ly?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),hd=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,ev=J(hd,"u").replace(/punct/g,Cs).getRegex(),tv=J(hd,"u").replace(/punct/g,pd).getRegex(),gd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",nv=J(gd,"gu").replace(/notPunctSpace/g,dd).replace(/punctSpace/g,Wa).replace(/punct/g,Cs).getRegex(),iv=J(gd,"gu").replace(/notPunctSpace/g,Xy).replace(/punctSpace/g,Yy).replace(/punct/g,pd).getRegex(),sv=J("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,dd).replace(/punctSpace/g,Wa).replace(/punct/g,Cs).getRegex(),ov=J(/\\(punct)/,"gu").replace(/punct/g,Cs).getRegex(),av=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(),rv=J(Oa).replace("(?:-->|$)","-->").getRegex(),lv=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",rv).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ss=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,cv=J(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",ss).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),fd=J(/^!?\[(label)\]\[(ref)\]/).replace("label",ss).replace("ref",Ua).getRegex(),md=J(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ua).getRegex(),uv=J("reflink|nolink(?!\\()","g").replace("reflink",fd).replace("nolink",md).getRegex(),rl=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,za={_backpedal:Fn,anyPunctuation:ov,autolink:av,blockSkip:Zy,br:ud,code:Gy,del:Fn,emStrongLDelim:ev,emStrongRDelimAst:nv,emStrongRDelimUnd:sv,escape:Vy,link:cv,nolink:md,punctuation:Jy,reflink:fd,reflinkSearch:uv,tag:lv,text:Qy,url:Fn},dv={...za,link:J(/^!?\[(label)\]\((.*?)\)/).replace("label",ss).getRegex(),reflink:J(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ss).getRegex()},Qo={...za,emStrongRDelimAst:iv,emStrongLDelim:tv,url:J(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",rl).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",rl).getRegex()},pv={...Qo,br:J(ud).replace("{2,}","*").getRegex(),text:J(Qo.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ai={normal:Fa,gfm:Hy,pedantic:jy},_n={normal:za,gfm:Qo,breaks:pv,pedantic:dv},hv={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ll=e=>hv[e];function Ze(e,t){if(t){if(ke.escapeTest.test(e))return e.replace(ke.escapeReplace,ll)}else if(ke.escapeTestNoEncode.test(e))return e.replace(ke.escapeReplaceNoEncode,ll);return e}function cl(e){try{e=encodeURI(e).replace(ke.percentDecode,"%")}catch{return null}return e}function ul(e,t){var o;let n=e.replace(ke.findPipe,(a,r,l)=>{let c=!1,d=r;for(;--d>=0&&l[d]==="\\";)c=!c;return c?"|":" |"}),i=n.split(ke.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(ke.slashPipe,"|");return i}function Mn(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 gv(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 dl(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 fv(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
3636
3636
  `).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(`
3637
3637
  `)}var os=class{constructor(e){G(this,"options");G(this,"rules");G(this,"lexer");this.options=e||Ot}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:Mn(n,`
3638
- `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=hv(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=Mn(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:Mn(t[0],`
3638
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=fv(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=Mn(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:Mn(t[0],`
3639
3639
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Mn(t[0],`
3640
3640
  `).split(`
3641
3641
  `),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 c=r.join(`
@@ -3656,7 +3656,7 @@ ${d}`:d;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
3656
3656
  `+b}!x&&!b.trim()&&(x=!0),m+=k+`
3657
3657
  `,e=e.substring(k.length+1),p=S.slice(C)}}a.loose||(l?a.loose=!0:this.rules.other.doubleBlankLine.test(m)&&(l=!0)),a.items.push({type:"list_item",raw:m,task:!!this.options.gfm&&this.rules.other.listIsTask.test(v),loose:!1,text:v,tokens:[]}),a.raw+=m}let c=a.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;a.raw=a.raw.trimEnd();for(let d of a.items){if(this.lexer.state.top=!1,d.tokens=this.lexer.blockTokens(d.text,[]),d.task){if(d.text=d.text.replace(this.rules.other.listReplaceTask,""),((n=d.tokens[0])==null?void 0:n.type)==="text"||((i=d.tokens[0])==null?void 0:i.type)==="paragraph"){d.tokens[0].raw=d.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),d.tokens[0].text=d.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let v=this.lexer.inlineQueue.length-1;v>=0;v--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[v].src)){this.lexer.inlineQueue[v].src=this.lexer.inlineQueue[v].src.replace(this.rules.other.listReplaceTask,"");break}}let m=this.rules.other.listTaskCheckbox.exec(d.raw);if(m){let v={type:"checkbox",raw:m[0]+" ",checked:m[0]!=="[ ]"};d.checked=v.checked,a.loose?d.tokens[0]&&["paragraph","text"].includes(d.tokens[0].type)&&"tokens"in d.tokens[0]&&d.tokens[0].tokens?(d.tokens[0].raw=v.raw+d.tokens[0].raw,d.tokens[0].text=v.raw+d.tokens[0].text,d.tokens[0].tokens.unshift(v)):d.tokens.unshift({type:"paragraph",raw:v.raw,text:v.raw,tokens:[v]}):d.tokens.unshift(v)}}if(!a.loose){let m=d.tokens.filter(p=>p.type==="space"),v=m.length>0&&m.some(p=>this.rules.other.anyLine.test(p.raw));a.loose=v}}if(a.loose)for(let d of a.items){d.loose=!0;for(let m of d.tokens)m.type==="text"&&(m.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=ul(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(`
3658
3658
  `):[],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(ul(r,o.header.length).map((l,c)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
3659
- `?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=Mn(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=pv(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)),dl(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 dl(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,c=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(i=c.exec(t))!=null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o)continue;if(a=[...o].length,i[3]||i[4]){r+=a;continue}else if((i[5]||i[6])&&s%3&&!((s+a)%3)){l+=a;continue}if(r-=a,r>0)continue;a=Math.min(a,a+r+l);let d=[...i[0]][0].length,m=e.slice(0,s+i.index+d+a);if(Math.min(s,a)%2){let p=m.slice(1,-1);return{type:"em",raw:m,text:p,tokens:this.lexer.inlineTokens(p)}}let v=m.slice(2,-2);return{type:"strong",raw:m,text:v,tokens:this.lexer.inlineTokens(v)}}}}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}}}},Re=class Jo{constructor(t){G(this,"tokens");G(this,"options");G(this,"state");G(this,"inlineQueue");G(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ot,this.options.tokenizer=this.options.tokenizer||new os,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:ke,block:Ai.normal,inline:_n.normal};this.options.pedantic?(n.block=Ai.pedantic,n.inline=_n.pedantic):this.options.gfm&&(n.block=Ai.gfm,this.options.breaks?n.inline=_n.breaks:n.inline=_n.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ai,inline:_n}}static lex(t,n){return new Jo(n).lex(t)}static lexInline(t,n){return new Jo(n).inlineTokens(t)}lex(t){t=t.replace(ke.carriageReturn,`
3659
+ `?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=Mn(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=gv(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)),dl(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 dl(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,c=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(i=c.exec(t))!=null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o)continue;if(a=[...o].length,i[3]||i[4]){r+=a;continue}else if((i[5]||i[6])&&s%3&&!((s+a)%3)){l+=a;continue}if(r-=a,r>0)continue;a=Math.min(a,a+r+l);let d=[...i[0]][0].length,m=e.slice(0,s+i.index+d+a);if(Math.min(s,a)%2){let p=m.slice(1,-1);return{type:"em",raw:m,text:p,tokens:this.lexer.inlineTokens(p)}}let v=m.slice(2,-2);return{type:"strong",raw:m,text:v,tokens:this.lexer.inlineTokens(v)}}}}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}}}},Re=class Jo{constructor(t){G(this,"tokens");G(this,"options");G(this,"state");G(this,"inlineQueue");G(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ot,this.options.tokenizer=this.options.tokenizer||new os,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:ke,block:Ai.normal,inline:_n.normal};this.options.pedantic?(n.block=Ai.pedantic,n.inline=_n.pedantic):this.options.gfm&&(n.block=Ai.gfm,this.options.breaks?n.inline=_n.breaks:n.inline=_n.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ai,inline:_n}}static lex(t,n){return new Jo(n).lex(t)}static lexInline(t,n){return new Jo(n).inlineTokens(t)}lex(t){t=t.replace(ke.carriageReturn,`
3660
3660
  `),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(ke.tabCharGlobal," ").replace(ke.spaceLine,""));t;){let r;if((o=(s=this.options.extensions)==null?void 0:s.block)!=null&&o.some(c=>(r=c.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let c=n.at(-1);r.raw.length===1&&c!==void 0?c.raw+=`
3661
3661
  `:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
3662
3662
  `)?"":`
@@ -3688,26 +3688,26 @@ ${this.parser.parse(e)}</blockquote>
3688
3688
  `}tablerow({text:e}){return`<tr>
3689
3689
  ${e}</tr>
3690
3690
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
3691
- `}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>${Ze(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=cl(e);if(s===null)return i;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+Ze(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=cl(e);if(s===null)return Ze(n);e=s;let o=`<img src="${e}" alt="${n}"`;return t&&(o+=` title="${Ze(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ze(e.text)}},Ka=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}},Le=class Yo{constructor(t){G(this,"options");G(this,"renderer");G(this,"textRenderer");this.options=t||Ot,this.options.renderer=this.options.renderer||new as,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ka}static parse(t,n){return new Yo(n).parse(t)}static parseInline(t,n){return new Yo(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,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){n+=c||"";continue}}let r=a;switch(r.type){case"space":{n+=this.renderer.space(r);break}case"hr":{n+=this.renderer.hr(r);break}case"heading":{n+=this.renderer.heading(r);break}case"code":{n+=this.renderer.code(r);break}case"table":{n+=this.renderer.table(r);break}case"blockquote":{n+=this.renderer.blockquote(r);break}case"list":{n+=this.renderer.list(r);break}case"checkbox":{n+=this.renderer.checkbox(r);break}case"html":{n+=this.renderer.html(r);break}case"def":{n+=this.renderer.def(r);break}case"paragraph":{n+=this.renderer.paragraph(r);break}case"text":{n+=this.renderer.text(r);break}default:{let 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 c=this.options.extensions.renderers[r.type].call({parser:this},r);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){i+=c||"";continue}}let 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 c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return i}},Bi,Ln=(Bi=class{constructor(e){G(this,"options");G(this,"block");this.options=e||Ot}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Re.lex:Re.lexInline}provideParser(){return this.block?Le.parse:Le.parseInline}},G(Bi,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),G(Bi,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),Bi),gv=class{constructor(...e){G(this,"defaults",Ba());G(this,"options",this.setOptions);G(this,"parse",this.parseMarkdown(!0));G(this,"parseInline",this.parseMarkdown(!1));G(this,"Parser",Le);G(this,"Renderer",as);G(this,"TextRenderer",Ka);G(this,"Lexer",Re);G(this,"Tokenizer",os);G(this,"Hooks",Ln);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 as(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]=(...c)=>{let d=r.apply(s,c);return d===!1&&(d=l.apply(s,c)),d||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new os(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]=(...c)=>{let d=r.apply(s,c);return d===!1&&(d=l.apply(s,c)),d}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new Ln;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];Ln.passThroughHooks.has(o)?s[a]=c=>{if(this.defaults.async&&Ln.passThroughHooksRespectAsync.has(o))return(async()=>{let m=await r.call(s,c);return l.call(s,m)})();let d=r.call(s,c);return l.call(s,d)}:s[a]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await r.apply(s,c);return m===!1&&(m=await l.apply(s,c)),m})();let d=r.apply(s,c);return d===!1&&(d=l.apply(s,c)),d}}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 Re.lex(e,t??this.defaults)}parser(e,t){return Le.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?Re.lex:Re.lexInline)(a,s),l=s.hooks?await s.hooks.processAllTokens(r):r;s.walkTokens&&await Promise.all(this.walkTokens(l,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser():e?Le.parse:Le.parseInline)(l,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(o);try{s.hooks&&(t=s.hooks.preprocess(t));let a=(s.hooks?s.hooks.provideLexer():e?Re.lex:Re.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?Le.parse:Le.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+=`
3692
- Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Ze(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},Bt=new gv;function Z(e,t){return Bt.parse(e,t)}Z.options=Z.setOptions=function(e){return Bt.setOptions(e),Z.defaults=Bt.defaults,sd(Z.defaults),Z};Z.getDefaults=Ba;Z.defaults=Ot;Z.use=function(...e){return Bt.use(...e),Z.defaults=Bt.defaults,sd(Z.defaults),Z};Z.walkTokens=function(e,t){return Bt.walkTokens(e,t)};Z.parseInline=Bt.parseInline;Z.Parser=Le;Z.parser=Le.parse;Z.Renderer=as;Z.TextRenderer=Ka;Z.Lexer=Re;Z.lexer=Re.lex;Z.Tokenizer=os;Z.Hooks=Ln;Z.parse=Z;Z.options;Z.setOptions;Z.use;Z.walkTokens;Z.parseInline;Le.parse;Re.lex;Z.setOptions({gfm:!0,breaks:!0,mangle:!1});const pl=["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"],hl=["class","href","rel","target","title","start"];let gl=!1;const fv=14e4,mv=4e4,yv=200,ro=5e4,At=new Map;function vv(e){const t=At.get(e);return t===void 0?null:(At.delete(e),At.set(e,t),t)}function fl(e,t){if(At.set(e,t),At.size<=yv)return;const n=At.keys().next().value;n&&At.delete(n)}function bv(){gl||(gl=!0,Go.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function rs(e){const t=e.trim();if(!t)return"";if(bv(),t.length<=ro){const a=vv(t);if(a!==null)return a}const n=hc(t,fv),i=n.truncated?`
3691
+ `}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>${Ze(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=cl(e);if(s===null)return i;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+Ze(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=cl(e);if(s===null)return Ze(n);e=s;let o=`<img src="${e}" alt="${n}"`;return t&&(o+=` title="${Ze(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ze(e.text)}},Ka=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}},Le=class Yo{constructor(t){G(this,"options");G(this,"renderer");G(this,"textRenderer");this.options=t||Ot,this.options.renderer=this.options.renderer||new as,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ka}static parse(t,n){return new Yo(n).parse(t)}static parseInline(t,n){return new Yo(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,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){n+=c||"";continue}}let r=a;switch(r.type){case"space":{n+=this.renderer.space(r);break}case"hr":{n+=this.renderer.hr(r);break}case"heading":{n+=this.renderer.heading(r);break}case"code":{n+=this.renderer.code(r);break}case"table":{n+=this.renderer.table(r);break}case"blockquote":{n+=this.renderer.blockquote(r);break}case"list":{n+=this.renderer.list(r);break}case"checkbox":{n+=this.renderer.checkbox(r);break}case"html":{n+=this.renderer.html(r);break}case"def":{n+=this.renderer.def(r);break}case"paragraph":{n+=this.renderer.paragraph(r);break}case"text":{n+=this.renderer.text(r);break}default:{let 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 c=this.options.extensions.renderers[r.type].call({parser:this},r);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){i+=c||"";continue}}let 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 c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return i}},Bi,Ln=(Bi=class{constructor(e){G(this,"options");G(this,"block");this.options=e||Ot}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Re.lex:Re.lexInline}provideParser(){return this.block?Le.parse:Le.parseInline}},G(Bi,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),G(Bi,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),Bi),mv=class{constructor(...e){G(this,"defaults",Ba());G(this,"options",this.setOptions);G(this,"parse",this.parseMarkdown(!0));G(this,"parseInline",this.parseMarkdown(!1));G(this,"Parser",Le);G(this,"Renderer",as);G(this,"TextRenderer",Ka);G(this,"Lexer",Re);G(this,"Tokenizer",os);G(this,"Hooks",Ln);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 as(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]=(...c)=>{let d=r.apply(s,c);return d===!1&&(d=l.apply(s,c)),d||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new os(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]=(...c)=>{let d=r.apply(s,c);return d===!1&&(d=l.apply(s,c)),d}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new Ln;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];Ln.passThroughHooks.has(o)?s[a]=c=>{if(this.defaults.async&&Ln.passThroughHooksRespectAsync.has(o))return(async()=>{let m=await r.call(s,c);return l.call(s,m)})();let d=r.call(s,c);return l.call(s,d)}:s[a]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await r.apply(s,c);return m===!1&&(m=await l.apply(s,c)),m})();let d=r.apply(s,c);return d===!1&&(d=l.apply(s,c)),d}}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 Re.lex(e,t??this.defaults)}parser(e,t){return Le.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?Re.lex:Re.lexInline)(a,s),l=s.hooks?await s.hooks.processAllTokens(r):r;s.walkTokens&&await Promise.all(this.walkTokens(l,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser():e?Le.parse:Le.parseInline)(l,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(o);try{s.hooks&&(t=s.hooks.preprocess(t));let a=(s.hooks?s.hooks.provideLexer():e?Re.lex:Re.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?Le.parse:Le.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+=`
3692
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Ze(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},Bt=new mv;function Z(e,t){return Bt.parse(e,t)}Z.options=Z.setOptions=function(e){return Bt.setOptions(e),Z.defaults=Bt.defaults,ad(Z.defaults),Z};Z.getDefaults=Ba;Z.defaults=Ot;Z.use=function(...e){return Bt.use(...e),Z.defaults=Bt.defaults,ad(Z.defaults),Z};Z.walkTokens=function(e,t){return Bt.walkTokens(e,t)};Z.parseInline=Bt.parseInline;Z.Parser=Le;Z.parser=Le.parse;Z.Renderer=as;Z.TextRenderer=Ka;Z.Lexer=Re;Z.lexer=Re.lex;Z.Tokenizer=os;Z.Hooks=Ln;Z.parse=Z;Z.options;Z.setOptions;Z.use;Z.walkTokens;Z.parseInline;Le.parse;Re.lex;Z.setOptions({gfm:!0,breaks:!0,mangle:!1});const pl=["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"],hl=["class","href","rel","target","title","start"];let gl=!1;const yv=14e4,vv=4e4,bv=200,ro=5e4,At=new Map;function wv(e){const t=At.get(e);return t===void 0?null:(At.delete(e),At.set(e,t),t)}function fl(e,t){if(At.set(e,t),At.size<=bv)return;const n=At.keys().next().value;n&&At.delete(n)}function kv(){gl||(gl=!0,Go.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function rs(e){const t=e.trim();if(!t)return"";if(kv(),t.length<=ro){const a=wv(t);if(a!==null)return a}const n=fc(t,yv),i=n.truncated?`
3693
3693
 
3694
- … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>mv){const r=`<pre class="code-block">${wv(`${n.text}${i}`)}</pre>`,l=Go.sanitize(r,{ALLOWED_TAGS:pl,ALLOWED_ATTR:hl});return t.length<=ro&&fl(t,l),l}const s=Z.parse(`${n.text}${i}`),o=Go.sanitize(s,{ALLOWED_TAGS:pl,ALLOWED_ATTR:hl});return t.length<=ro&&fl(t,o),o}function wv(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const kv=1500,xv=2e3,fd="Copy as markdown",$v="Copied",Sv="Copy failed";async function Av(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 Ci(e,t){e.title=t,e.setAttribute("aria-label",t)}function Cv(e){const t=e.label??fd;return u`
3694
+ … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>vv){const r=`<pre class="code-block">${xv(`${n.text}${i}`)}</pre>`,l=Go.sanitize(r,{ALLOWED_TAGS:pl,ALLOWED_ATTR:hl});return t.length<=ro&&fl(t,l),l}const s=Z.parse(`${n.text}${i}`),o=Go.sanitize(s,{ALLOWED_TAGS:pl,ALLOWED_ATTR:hl});return t.length<=ro&&fl(t,o),o}function xv(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const $v=1500,Sv=2e3,yd="Copy as markdown",Av="Copied",Cv="Copy failed";async function Ev(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 Ci(e,t){e.title=t,e.setAttribute("aria-label",t)}function Tv(e){const t=e.label??yd;return u`
3695
3695
  <button
3696
3696
  class="chat-copy-btn"
3697
3697
  type="button"
3698
3698
  title=${t}
3699
3699
  aria-label=${t}
3700
- @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 Av(e.text());if(i.isConnected){if(delete i.dataset.copying,i.removeAttribute("aria-busy"),i.disabled=!1,!s){i.dataset.error="1",Ci(i,Sv),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.error,Ci(i,t))},xv);return}i.dataset.copied="1",Ci(i,$v),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.copied,Ci(i,t))},kv)}}}
3700
+ @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 Ev(e.text());if(i.isConnected){if(delete i.dataset.copying,i.removeAttribute("aria-busy"),i.disabled=!1,!s){i.dataset.error="1",Ci(i,Cv),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.error,Ci(i,t))},Sv);return}i.dataset.copied="1",Ci(i,Av),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.copied,Ci(i,t))},$v)}}}
3701
3701
  >
3702
3702
  <span class="chat-copy-btn__icon" aria-hidden="true">
3703
3703
  <span class="chat-copy-btn__icon-copy">${E.copy}</span>
3704
3704
  <span class="chat-copy-btn__icon-check">${E.check}</span>
3705
3705
  </span>
3706
3706
  </button>
3707
- `}function Ev(e){return Cv({text:()=>e,label:fd})}function Tv(e){const t=e,n=Pv(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:_v(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=Mv(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(vc(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=gc(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function Pv(e){return Array.isArray(e)?e.filter(Boolean):[]}function _v(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 Mv(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const lo=40,co=new Map;async function Iv(e){const t=co.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/lo),l=[];for(let m=0;m<lo;m++){let v=0;const p=m*r,b=Math.min(p+r,a.length);for(let x=p;x<b;x++){const C=Math.abs(a[x]);C>v&&(v=C)}l.push(v)}const c=Math.max(...l,.01),d=l.map(m=>Math.max(m/c,.08));return co.set(e,d),n.close(),d}catch{const n=Array.from(e).reduce((s,o)=>(s<<5)-s+o.charCodeAt(0)|0,0),i=[];for(let s=0;s<lo;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return co.set(e,i),i}}const uo=[1,1.5,2],ls=new Map;function Rv(e){let t=ls.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:[]},ls.set(e,t),Iv(e).then(i=>{t.waveform=i,md(e)}),t}const Wn="http://www.w3.org/2000/svg";function Lv(){const e=document.createElementNS(Wn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Wn,"polygon");return t.setAttribute("points","6,3 20,12 6,21"),e.appendChild(t),e}function Bv(){const e=document.createElementNS(Wn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Wn,"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(Wn,"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 md(e){const t=Qt(e);if(!t)return;const n=ls.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)}zn(t,n)}}function zn(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?cs(t.currentTime):cs(t.duration))}function po(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?Bv():Lv();i?n.replaceChild(s,i):n.appendChild(s)}function cs(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 ml=new Set;function Dv(e){if(ml.has(e))return;ml.add(e);const t=ls.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=Qt(e);i&&zn(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=Qt(e);i&&zn(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=Qt(e);i&&(zn(i,t),po(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=Qt(e);i&&po(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=Qt(e);i&&po(i,!0)})}function Nv(e,t){const n=Rv(e);Dv(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const l=uo.indexOf(n.speed),c=uo[(l+1)%uo.length];n.speed=c,n.audio.playbackRate=c;const d=r.target.closest(".vnp__speed");d&&(d.textContent=`${c}×`)},o=r=>{r.stopPropagation();const l=r.target.closest(".vnp__waveform");if(!l)return;const c=l.getBoundingClientRect(),d=Math.max(0,Math.min(1,(r.clientX-c.left)/c.width));if(n.duration>0){n.audio.currentTime=d*n.duration,n.currentTime=n.audio.currentTime;const m=l.closest(".vnp");m&&zn(m,n)}},a=n.playing||n.currentTime>0?cs(n.currentTime):cs(n.duration);return queueMicrotask(()=>md(e)),u`
3707
+ `}function Pv(e){return Tv({text:()=>e,label:yd})}function _v(e){const t=e,n=Mv(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:Iv(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=Rv(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(wc(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=mc(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function Mv(e){return Array.isArray(e)?e.filter(Boolean):[]}function Iv(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 Rv(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const lo=40,co=new Map;async function Lv(e){const t=co.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/lo),l=[];for(let m=0;m<lo;m++){let v=0;const p=m*r,b=Math.min(p+r,a.length);for(let x=p;x<b;x++){const C=Math.abs(a[x]);C>v&&(v=C)}l.push(v)}const c=Math.max(...l,.01),d=l.map(m=>Math.max(m/c,.08));return co.set(e,d),n.close(),d}catch{const n=Array.from(e).reduce((s,o)=>(s<<5)-s+o.charCodeAt(0)|0,0),i=[];for(let s=0;s<lo;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return co.set(e,i),i}}const uo=[1,1.5,2],ls=new Map;function Bv(e){let t=ls.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:[]},ls.set(e,t),Lv(e).then(i=>{t.waveform=i,vd(e)}),t}const Wn="http://www.w3.org/2000/svg";function Dv(){const e=document.createElementNS(Wn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Wn,"polygon");return t.setAttribute("points","6,3 20,12 6,21"),e.appendChild(t),e}function Nv(){const e=document.createElementNS(Wn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Wn,"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(Wn,"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 vd(e){const t=Qt(e);if(!t)return;const n=ls.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)}zn(t,n)}}function zn(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?cs(t.currentTime):cs(t.duration))}function po(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?Nv():Dv();i?n.replaceChild(s,i):n.appendChild(s)}function cs(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 ml=new Set;function Uv(e){if(ml.has(e))return;ml.add(e);const t=ls.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=Qt(e);i&&zn(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=Qt(e);i&&zn(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=Qt(e);i&&(zn(i,t),po(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=Qt(e);i&&po(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=Qt(e);i&&po(i,!0)})}function Ov(e,t){const n=Bv(e);Uv(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const l=uo.indexOf(n.speed),c=uo[(l+1)%uo.length];n.speed=c,n.audio.playbackRate=c;const d=r.target.closest(".vnp__speed");d&&(d.textContent=`${c}×`)},o=r=>{r.stopPropagation();const l=r.target.closest(".vnp__waveform");if(!l)return;const c=l.getBoundingClientRect(),d=Math.max(0,Math.min(1,(r.clientX-c.left)/c.width));if(n.duration>0){n.audio.currentTime=d*n.duration,n.currentTime=n.audio.currentTime;const m=l.closest(".vnp");m&&zn(m,n)}},a=n.playing||n.currentTime>0?cs(n.currentTime):cs(n.duration);return queueMicrotask(()=>vd(e)),u`
3708
3708
  <div class="vnp" data-url=${e} @click=${r=>r.stopPropagation()}>
3709
3709
  <button class="vnp__play" @click=${i} aria-label=${n.playing?"Pause":"Play"}>
3710
- ${n.playing?Ov():Uv()}
3710
+ ${n.playing?Wv():Fv()}
3711
3711
  </button>
3712
3712
 
3713
3713
  <div class="vnp__body">
@@ -3720,7 +3720,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3720
3720
  </div>
3721
3721
  </div>
3722
3722
  </div>
3723
- `}function Uv(){return u`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function Ov(){return u`<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 Fv(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,c=r.media_type||"image/png",d=l.startsWith("data:")?l:`data:${c};base64,${l}`;i.push({url:d})}else if(typeof a.data=="string"&&a.data){const r=a.data,l=a.mimeType||a.media_type||"image/png",c=r.startsWith("data:")?r:`data:${l};base64,${r}`;i.push({url:c})}else typeof a.url=="string"&&i.push({url:a.url});else if(a.type==="image_url"){const r=a.image_url;typeof(r==null?void 0:r.url)=="string"&&i.push({url:r.url})}}return i}function Wv(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 zv(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Kv(e){return u`
3723
+ `}function Fv(){return u`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function Wv(){return u`<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 zv(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,c=r.media_type||"image/png",d=l.startsWith("data:")?l:`data:${c};base64,${l}`;i.push({url:d})}else if(typeof a.data=="string"&&a.data){const r=a.data,l=a.mimeType||a.media_type||"image/png",c=r.startsWith("data:")?r:`data:${l};base64,${r}`;i.push({url:c})}else typeof a.url=="string"&&i.push({url:a.url});else if(a.type==="image_url"){const r=a.image_url;typeof(r==null?void 0:r.url)=="string"&&i.push({url:r.url})}}return i}function Kv(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 qv(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Hv(e){return u`
3724
3724
  <div class="chat-group assistant">
3725
3725
  <div class="chat-group-messages">
3726
3726
  <div class="chat-bubble chat-reading-indicator" aria-hidden="true">
@@ -3730,7 +3730,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3730
3730
  </div>
3731
3731
  </div>
3732
3732
  </div>
3733
- `}function qv(e){return u`
3733
+ `}function jv(e){return u`
3734
3734
  <div class="chat-group assistant">
3735
3735
  <div class="chat-group-messages">
3736
3736
  <div class="chat-interim fade-in">
@@ -3738,13 +3738,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3738
3738
  </div>
3739
3739
  </div>
3740
3740
  </div>
3741
- `}function Hv(e,t,n,i){return u`
3741
+ `}function Vv(e,t,n,i){return u`
3742
3742
  <div class="chat-group assistant">
3743
3743
  <div class="chat-group-messages">
3744
- ${yd({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
3744
+ ${bd({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
3745
3745
  </div>
3746
3746
  </div>
3747
- `}function jv(e,t){const n=yc(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)=>yd(a.message,{isStreaming:e.isStreaming&&r===e.messages.length-1,showReasoning:t.showReasoning}));return o.every(a=>a===w)?w:u`
3747
+ `}function Gv(e,t){const n=bc(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)=>bd(a.message,{isStreaming:e.isStreaming&&r===e.messages.length-1,showReasoning:t.showReasoning}));return o.every(a=>a===w)?w:u`
3748
3748
  <div class="chat-group ${i}">
3749
3749
  <div class="chat-group-messages">
3750
3750
  ${o}
@@ -3753,7 +3753,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3753
3753
  </div>
3754
3754
  </div>
3755
3755
  </div>
3756
- `}function Vv(e){return e.length===0?w:u`
3756
+ `}function Qv(e){return e.length===0?w:u`
3757
3757
  <div class="chat-message-images">
3758
3758
  ${e.map(t=>u`
3759
3759
  <img
@@ -3764,12 +3764,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3764
3764
  />
3765
3765
  `)}
3766
3766
  </div>
3767
- `}function Gv(e){return e.length===0?w:u`
3767
+ `}function Jv(e){return e.length===0?w:u`
3768
3768
  <div class="chat-message-files">
3769
- ${e.map(t=>t.mimeType==="application/pdf"?Jv(t):t.mimeType.startsWith("audio/")?Nv(t.url,t.name):Yv(t))}
3769
+ ${e.map(t=>t.mimeType==="application/pdf"?Xv(t):t.mimeType.startsWith("audio/")?Ov(t.url,t.name):Zv(t))}
3770
3770
  </div>
3771
- `}function Qv(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 c=document.createElementNS("http://www.w3.org/2000/svg","line");c.setAttribute("x1","18"),c.setAttribute("y1","6"),c.setAttribute("x2","6"),c.setAttribute("y2","18");const d=document.createElementNS("http://www.w3.org/2000/svg","line");d.setAttribute("x1","6"),d.setAttribute("y1","6"),d.setAttribute("x2","18"),d.setAttribute("y2","18"),l.append(c,d),r.appendChild(l),s.append(o,a,r);const m=document.createElement("iframe");m.className="chat-pdf-modal__frame",m.src=e,m.title=t,i.append(s,m),n.appendChild(i),n.addEventListener("click",v=>{v.target===n&&n.remove()}),r.addEventListener("click",()=>n.remove()),document.body.appendChild(n)}function Jv(e){return u`
3772
- <div class="chat-pdf-preview" @click=${()=>Qv(e.url,e.name)}>
3771
+ `}function Yv(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 c=document.createElementNS("http://www.w3.org/2000/svg","line");c.setAttribute("x1","18"),c.setAttribute("y1","6"),c.setAttribute("x2","6"),c.setAttribute("y2","18");const d=document.createElementNS("http://www.w3.org/2000/svg","line");d.setAttribute("x1","6"),d.setAttribute("y1","6"),d.setAttribute("x2","18"),d.setAttribute("y2","18"),l.append(c,d),r.appendChild(l),s.append(o,a,r);const m=document.createElement("iframe");m.className="chat-pdf-modal__frame",m.src=e,m.title=t,i.append(s,m),n.appendChild(i),n.addEventListener("click",v=>{v.target===n&&n.remove()}),r.addEventListener("click",()=>n.remove()),document.body.appendChild(n)}function Xv(e){return u`
3772
+ <div class="chat-pdf-preview" @click=${()=>Yv(e.url,e.name)}>
3773
3773
  <iframe
3774
3774
  src=${e.url}
3775
3775
  class="chat-pdf-preview__frame"
@@ -3783,39 +3783,39 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3783
3783
  @click=${t=>t.stopPropagation()}
3784
3784
  >${e.name}</a>
3785
3785
  </div>
3786
- `}function Yv(e){return u`
3786
+ `}function Zv(e){return u`
3787
3787
  <a
3788
3788
  class="chat-file-card"
3789
3789
  href=${e.url}
3790
3790
  target="_blank"
3791
3791
  rel="noreferrer noopener"
3792
3792
  >
3793
- <span class="chat-file-card__icon">${zv(e.mimeType)}</span>
3793
+ <span class="chat-file-card__icon">${qv(e.mimeType)}</span>
3794
3794
  <span class="chat-file-card__name">${e.name}</span>
3795
3795
  </a>
3796
- `}function yd(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=vc(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=Tv(e).length>0,l=Fv(e),c=l.length>0,d=Wv(e),m=d.length>0,v=gc(e),p=t.showReasoning&&s==="assistant"?xh(e):null,b=v!=null&&v.trim()?v:null,x=p?Sh(p):null,C=b,A=(s==="assistant"||s==="user")&&!!(C!=null&&C.trim()),T=["chat-bubble",A?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!C&&(r||o)||!C&&!c&&!m?w:u`
3796
+ `}function bd(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=wc(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=_v(e).length>0,l=zv(e),c=l.length>0,d=Kv(e),m=d.length>0,v=mc(e),p=t.showReasoning&&s==="assistant"?Sh(e):null,b=v!=null&&v.trim()?v:null,x=p?Ch(p):null,C=b,A=(s==="assistant"||s==="user")&&!!(C!=null&&C.trim()),T=["chat-bubble",A?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!C&&(r||o)||!C&&!c&&!m?w:u`
3797
3797
  <div class="${T}">
3798
- ${A?Ev(C):w}
3799
- ${Vv(l)}
3800
- ${Gv(d)}
3798
+ ${A?Pv(C):w}
3799
+ ${Qv(l)}
3800
+ ${Jv(d)}
3801
3801
  ${x?u`<div class="chat-thinking">${is(rs(x))}</div>`:w}
3802
3802
  ${C?u`<div class="chat-text">${is(rs(C))}</div>`:w}
3803
3803
  </div>
3804
- `}const z={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let X=null,Pt=null,_t=!1;function yl(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}function kt(){if(z.timerId&&(clearInterval(z.timerId),z.timerId=null),z.stream){for(const e of z.stream.getTracks())e.stop();z.stream=null}Pt&&(clearTimeout(Pt),Pt=null),us(),z.mediaRecorder=null,z.audioChunks=[],z.active=!1,z.cancelled=!1,_t=!1}async function vd(e){var t;try{if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))return console.warn("[voice] getUserMedia unavailable (requires secure context)"),kt(),!1;const n=await navigator.mediaDevices.getUserMedia({audio:!0});z.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 z.mediaRecorder=s,z.audioChunks=[],z.mode=e,z.startTime=Date.now(),z.elapsed=0,z.active=!0,z.cancelled=!1,s.ondataavailable=o=>{o.data.size>0&&z.audioChunks.push(o.data)},s.onstop=()=>{if(z.cancelled){kt(),X==null||X.onRequestRender();return}const o=new Blob(z.audioChunks,{type:s.mimeType});if(o.size===0){kt(),X==null||X.onRequestRender();return}const a=new FileReader;a.onload=()=>{const r=a.result,l=s.mimeType.includes("mp4")?"m4a":"webm",c={id:vs(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${l}`};kt(),X==null||X.onSend(c),X==null||X.onRequestRender()},a.onerror=()=>{kt(),X==null||X.onRequestRender()},a.readAsDataURL(o)},s.start(250),z.timerId=setInterval(()=>{z.elapsed=Math.floor((Date.now()-z.startTime)/1e3),X==null||X.onRequestRender()},1e3),X==null||X.onRequestRender(),!0}catch(n){return console.warn("[voice] startRecording failed:",n),kt(),!1}}function bd(){!z.active||!z.mediaRecorder||(z.cancelled=!1,z.mediaRecorder.state==="recording"&&z.mediaRecorder.stop())}function wd(){!z.active||!z.mediaRecorder||(z.cancelled=!0,z.mediaRecorder.state==="recording"?z.mediaRecorder.stop():(kt(),X==null||X.onRequestRender()))}function Xv(){document.addEventListener("pointerup",kd)}function us(){document.removeEventListener("pointerup",kd)}function kd(e){if(!_t&&!z.active){us();return}if(_t=!1,us(),Pt&&(clearTimeout(Pt),Pt=null,!z.active)){vd("tap");return}z.active&&z.mode==="hold"&&(z.cancelled?wd():bd()),e.preventDefault()}function Zv(e){z.active||(_t=!0,z.startX=e.clientX,Xv(),Pt=setTimeout(async()=>{if(!_t)return;await vd("hold")||(_t=!1,us())},300))}function vl(e){if(!z.active||z.mode!=="hold"||!_t)return;const t=z.startX-e.clientX;t>80?(z.cancelled=!0,X==null||X.onRequestRender()):z.cancelled&&t<=60&&(z.cancelled=!1,X==null||X.onRequestRender())}function eb(){return z.active}function tb(e){X=e}function nb(e){return u`
3804
+ `}const z={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let X=null,Pt=null,_t=!1;function yl(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}function kt(){if(z.timerId&&(clearInterval(z.timerId),z.timerId=null),z.stream){for(const e of z.stream.getTracks())e.stop();z.stream=null}Pt&&(clearTimeout(Pt),Pt=null),us(),z.mediaRecorder=null,z.audioChunks=[],z.active=!1,z.cancelled=!1,_t=!1}async function wd(e){var t;try{if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))return console.warn("[voice] getUserMedia unavailable (requires secure context)"),kt(),!1;const n=await navigator.mediaDevices.getUserMedia({audio:!0});z.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 z.mediaRecorder=s,z.audioChunks=[],z.mode=e,z.startTime=Date.now(),z.elapsed=0,z.active=!0,z.cancelled=!1,s.ondataavailable=o=>{o.data.size>0&&z.audioChunks.push(o.data)},s.onstop=()=>{if(z.cancelled){kt(),X==null||X.onRequestRender();return}const o=new Blob(z.audioChunks,{type:s.mimeType});if(o.size===0){kt(),X==null||X.onRequestRender();return}const a=new FileReader;a.onload=()=>{const r=a.result,l=s.mimeType.includes("mp4")?"m4a":"webm",c={id:vs(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${l}`};kt(),X==null||X.onSend(c),X==null||X.onRequestRender()},a.onerror=()=>{kt(),X==null||X.onRequestRender()},a.readAsDataURL(o)},s.start(250),z.timerId=setInterval(()=>{z.elapsed=Math.floor((Date.now()-z.startTime)/1e3),X==null||X.onRequestRender()},1e3),X==null||X.onRequestRender(),!0}catch(n){return console.warn("[voice] startRecording failed:",n),kt(),!1}}function kd(){!z.active||!z.mediaRecorder||(z.cancelled=!1,z.mediaRecorder.state==="recording"&&z.mediaRecorder.stop())}function xd(){!z.active||!z.mediaRecorder||(z.cancelled=!0,z.mediaRecorder.state==="recording"?z.mediaRecorder.stop():(kt(),X==null||X.onRequestRender()))}function eb(){document.addEventListener("pointerup",$d)}function us(){document.removeEventListener("pointerup",$d)}function $d(e){if(!_t&&!z.active){us();return}if(_t=!1,us(),Pt&&(clearTimeout(Pt),Pt=null,!z.active)){wd("tap");return}z.active&&z.mode==="hold"&&(z.cancelled?xd():kd()),e.preventDefault()}function tb(e){z.active||(_t=!0,z.startX=e.clientX,eb(),Pt=setTimeout(async()=>{if(!_t)return;await wd("hold")||(_t=!1,us())},300))}function vl(e){if(!z.active||z.mode!=="hold"||!_t)return;const t=z.startX-e.clientX;t>80?(z.cancelled=!0,X==null||X.onRequestRender()):z.cancelled&&t<=60&&(z.cancelled=!1,X==null||X.onRequestRender())}function nb(){return z.active}function ib(e){X=e}function sb(e){return u`
3805
3805
  <button
3806
3806
  class="chat-compose__mic"
3807
3807
  ?disabled=${!e}
3808
- @pointerdown=${Zv}
3808
+ @pointerdown=${tb}
3809
3809
  aria-label="Record voice note"
3810
3810
  title="Tap to record, hold to send on release"
3811
3811
  >
3812
3812
  ${E.mic}
3813
3813
  </button>
3814
- `}function ib(){return z.active?z.mode==="tap"?u`
3814
+ `}function ob(){return z.active?z.mode==="tap"?u`
3815
3815
  <div class="chat-voice-recording" @pointermove=${vl}>
3816
3816
  <button
3817
3817
  class="btn btn--icon chat-voice-recording__trash"
3818
- @click=${wd}
3818
+ @click=${xd}
3819
3819
  aria-label="Cancel recording"
3820
3820
  title="Discard"
3821
3821
  >
@@ -3827,7 +3827,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3827
3827
  </div>
3828
3828
  <button
3829
3829
  class="btn btn--icon chat-voice-recording__send primary"
3830
- @click=${bd}
3830
+ @click=${kd}
3831
3831
  aria-label="Send voice note"
3832
3832
  title="Send"
3833
3833
  >
@@ -3844,7 +3844,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3844
3844
  </span>
3845
3845
  </div>
3846
3846
  </div>
3847
- `:w}function sb(e){return u`
3847
+ `:w}function ab(e){return u`
3848
3848
  <div class="sidebar-panel">
3849
3849
  <div class="sidebar-header">
3850
3850
  <div class="sidebar-title">Tool Output</div>
@@ -3861,7 +3861,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3861
3861
  `:e.content?u`<div class="sidebar-markdown">${is(rs(e.content))}</div>`:u`<div class="muted">No content available</div>`}
3862
3862
  </div>
3863
3863
  </div>
3864
- `}var ob=Object.defineProperty,ab=Object.getOwnPropertyDescriptor,Es=(e,t,n,i)=>{for(var s=i>1?void 0:i?ab(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&&ob(t,n,s),s};let on=class extends Zt{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 u``}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)}};on.styles=Rp`
3864
+ `}var rb=Object.defineProperty,lb=Object.getOwnPropertyDescriptor,Es=(e,t,n,i)=>{for(var s=i>1?void 0:i?lb(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&&rb(t,n,s),s};let on=class extends Zt{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 u``}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)}};on.styles=Bp`
3865
3865
  :host {
3866
3866
  width: 4px;
3867
3867
  cursor: col-resize;
@@ -3887,21 +3887,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
3887
3887
  :host(.dragging) {
3888
3888
  background: var(--accent, #007bff);
3889
3889
  }
3890
- `;Es([ys({type:Number})],on.prototype,"splitRatio",2);Es([ys({type:Number})],on.prototype,"minRatio",2);Es([ys({type:Number})],on.prototype,"maxRatio",2);on=Es([rc("resizable-divider")],on);function Ei(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function ho(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const rb=1,lb=1,Ft="emoji",an="keyvalue",qa="favorites",cb="tokens",xd="tokens",ub="unicode",$d="count",db="group",pb="order",Sd="group-order",Xo="eTag",ds="url",bl="skinTone",mn="readonly",Ha="readwrite",Ad="skinUnicodes",hb="skinUnicodes",gb="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",fb="en";function mb(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 wl(e){return mb(e,t=>t.unicode)}function yb(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(an),t(Ft,ub,{[xd]:[cb,!0],[Sd]:[[db,pb]],[Ad]:[hb,!0]}),t(qa,void 0,{[$d]:[""]})}const Zo={},Oi={},ps={};function Cd(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function vb(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,rb);Zo[e]=s,s.onupgradeneeded=o=>{o.oldVersion<lb&&yb(s.result)},Cd(n,i,s)});return t.onclose=()=>ja(e),t}function bb(e){return Oi[e]||(Oi[e]=vb(e)),Oi[e]}function it(e,t,n,i){return new Promise((s,o)=>{const a=e.transaction(t,n,{durability:"relaxed"}),r=typeof t=="string"?a.objectStore(t):t.map(c=>a.objectStore(c));let l;i(r,a,c=>{l=c}),a.oncomplete=()=>s(l),a.onerror=()=>o(a.error)})}function ja(e){const t=Zo[e],n=t&&t.result;if(n){n.close();const i=ps[e];if(i)for(const s of i)s()}delete Zo[e],delete Oi[e],delete ps[e]}function wb(e){return new Promise((t,n)=>{ja(e);const i=indexedDB.deleteDatabase(e);Cd(t,n,i)})}function kb(e,t){let n=ps[e];n||(n=ps[e]=[]),n.push(t)}const xb=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 en(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||xb.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const $b=2;function Ed(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=$b)}function Sb(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:l,emoji:c,version:d})=>{const m=[...new Set(Ed([...(a||[]).map(en).flat(),...(l||[]).map(en).flat(),...en(n),i]))].sort(),v={annotation:n,group:s,order:o,tags:l,tokens:m,unicode:c,version:d};if(i&&(v.emoticon=i),a&&(v.shortcodes=a),r){v.skinTones=[],v.skinUnicodes=[],v.skinVersions=[];for(const{tone:p,emoji:b,version:x}of r)v.skinTones.push(p),v.skinUnicodes.push(b),v.skinVersions.push(x)}return v})}function Td(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function Dt(e,t,n){Td(e,"get",t,n)}function Pd(e,t,n){Td(e,"getAll",t,n)}function Va(e){e.commit&&e.commit()}function Ab(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 _d(e,t){const n=Ab(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 Cb(e){return!await Ga(e,an,ds)}async function Eb(e,t,n){const[i,s]=await Promise.all([Xo,ds].map(o=>Ga(e,an,o)));return i===n&&s===t}async function Tb(e,t){return it(e,Ft,mn,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=l=>{const c=l.target.result;for(const d of c)if(a=d.unicode,t(d))return o(d);if(c.length<50)return o();r()}};r()})}async function Md(e,t,n,i){{const s=Sb(t);await it(e,[Ft,an],Ha,([o,a],r)=>{let l,c,d=0;function m(){++d===2&&v()}function v(){if(!(l===i&&c===n)){o.clear();for(const p of s)o.put(p);a.put(i,Xo),a.put(n,ds),Va(r)}}Dt(a,Xo,p=>{l=p,m()}),Dt(a,ds,p=>{c=p,m()})})}}async function Pb(e,t){return it(e,Ft,mn,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);Pd(n.index(Sd),o,s)})}async function Id(e,t){const n=Ed(en(t));return n.length?it(e,Ft,mn,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&l()},l=()=>{const c=_d(a,d=>d.unicode);o(c.sort((d,m)=>d.order<m.order?-1:1))};for(let c=0;c<n.length;c++){const d=n[c],m=c===n.length-1?IDBKeyRange.bound(d,d+"￿",!1,!0):IDBKeyRange.only(d);Pd(i.index(xd),m,v=>{a.push(v),r()})}}):[]}async function _b(e,t){const n=await Id(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await Tb(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function Mb(e,t){return it(e,Ft,mn,(n,i,s)=>Dt(n,t,o=>{if(o)return s(o);Dt(n.index(Ad),t,a=>s(a||null))}))}function Ga(e,t,n){return it(e,t,mn,(i,s,o)=>Dt(i,n,o))}function Ib(e,t,n,i){return it(e,t,Ha,(s,o)=>{s.put(i,n),Va(o)})}function Rb(e,t){return it(e,qa,Ha,(n,i)=>Dt(n,t,s=>{n.put((s||0)+1,t),Va(i)}))}function Lb(e,t,n){return n===0?[]:it(e,[qa,Ft],mn,([i,s],o,a)=>{const r=[];i.index($d).openCursor(void 0,"prev").onsuccess=l=>{const c=l.target.result;if(!c)return a(r);function d(p){if(r.push(p),r.length===n)return a(r);c.continue()}const m=c.primaryKey,v=t.byName(m);if(v)return d(v);Dt(s,m,p=>{if(p)return d(p);c.continue()})}})}const Ti="";function Bb(e,t){const n=new Map;for(const s of e){const o=t(s);for(const a of o){let r=n;for(let c=0;c<a.length;c++){const d=a.charAt(c);let m=r.get(d);m||(m=new Map,r.set(d,m)),r=m}let l=r.get(Ti);l||(l=[],r.set(Ti,l)),l.push(s)}}return(s,o)=>{let a=n;for(let c=0;c<s.length;c++){const d=s.charAt(c),m=a.get(d);if(m)a=m;else return[]}if(o)return a.get(Ti)||[];const r=[],l=[a];for(;l.length;){const d=[...l.shift().entries()].sort((m,v)=>m[0]<v[0]?-1:1);for(const[m,v]of d)m===Ti?r.push(...v):l.push(v)}return r}}const Db=["name","url"];function Nb(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||Db.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function kl(e){Nb(e);const t=(v,p)=>v.name.toLowerCase()<p.name.toLowerCase()?-1:1,n=e.sort(t),s=Bb(e,v=>{const p=new Set;if(v.shortcodes)for(const b of v.shortcodes)for(const x of en(b))p.add(x);return p}),o=v=>s(v,!0),a=v=>s(v,!1),r=v=>{const p=en(v),b=p.map((x,C)=>(C<p.length-1?o:a)(x));return _d(b,x=>x.name).sort(t)},l=new Map,c=new Map;for(const v of e){c.set(v.name.toLowerCase(),v);for(const p of v.shortcodes||[])l.set(p.toLowerCase(),v)}return{all:n,search:r,byShortcode:v=>l.get(v.toLowerCase()),byName:v=>c.get(v.toLowerCase())}}const Ub=typeof wrappedJSObject<"u";function In(e){if(!e)return e;if(Ub&&(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 Rd(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Ob=["annotation","emoji","group","order","version"];function Fb(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Ob.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function Ld(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Wb(e){const t=await fetch(e,{method:"HEAD"});Ld(t,e);const n=t.headers.get("etag");return Rd(n),n}async function ea(e){const t=await fetch(e);Ld(t,e);const n=t.headers.get("etag");Rd(n);const i=await t.json();return Fb(i),[n,i]}function zb(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Kb(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 Bd(e){const t=JSON.stringify(e);let n=Kb(t);const i=await crypto.subtle.digest("SHA-1",n),s=zb(i);return btoa(s)}async function qb(e,t){let n,i=await Wb(t);if(!i){const s=await ea(t);i=s[0],n=s[1],i||(i=await Bd(n))}await Eb(e,t,i)||(n||(n=(await ea(t))[1]),await Md(e,n,t,i))}async function Hb(e,t){let[n,i]=await ea(t);n||(n=await Bd(i)),await Md(e,i,t,n)}async function jb(e,t){try{await qb(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class Vb{constructor({dataSource:t=gb,locale:n=fb,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=kl(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await bb(this._dbName);kb(this._dbName,this._clear);const n=this.dataSource;await Cb(t)?await Hb(t,n):this._lazyUpdate=jb(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 ho(t),await this.ready(),wl(await Pb(this._db,t)).map(In)}async getEmojiBySearchQuery(t){Ei(t),await this.ready();const n=this._custom.search(t),i=wl(await Id(this._db,t)).map(In);return[...n,...i]}async getEmojiByShortcode(t){Ei(t),await this.ready();const n=this._custom.byShortcode(t);return n||In(await _b(this._db,t))}async getEmojiByUnicodeOrName(t){Ei(t),await this.ready();const n=this._custom.byName(t);return n||In(await Mb(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Ga(this._db,an,bl)||0}async setPreferredSkinTone(t){return ho(t),await this.ready(),Ib(this._db,an,bl,t)}async incrementFavoriteEmojiCount(t){return Ei(t),await this.ready(),Rb(this._db,t)}async getTopFavoriteEmoji(t){return ho(t),await this.ready(),(await Lb(this._db,this._custom,t)).map(In)}set customEmoji(t){this._custom=kl(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 ja(this._dbName)}async delete(){await this._shutdown(),await wb(this._dbName)}}const ta=[[-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})),go=ta.slice(1),Gb=2,xl=6,Dd=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function $l(e){return e.unicode.includes("‍")}const Qb={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},Jb=1e3,Yb="🖐️",Xb=8,Zb=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],Nd='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',ew=(e,t)=>e<t?-1:e>t?1:0,Sl=(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 ${Nd}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},tw=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function nw(e){const t=Sl(e,"#000"),n=Sl(e,"#fff");return t&&n&&tw(t,n)}function iw(){const e=Object.entries(Qb);try{for(const[t,n]of e)if(nw(t))return n}catch{}return e[0][1]}let fo;const mo=()=>(fo||(fo=new Promise(e=>Dd(()=>e(iw())))),fo),na=new Map,sw="️",ow="\uD83C",aw="‍",rw=127995,lw=57339;function cw(e,t){if(t===0)return e;const n=e.indexOf(aw);return n!==-1?e.substring(0,n)+String.fromCodePoint(rw+t-1)+e.substring(n):(e.endsWith(sw)&&(e=e.substring(0,e.length-1)),e+ow+String.fromCodePoint(lw+t-1))}function Fe(e){e.preventDefault(),e.stopPropagation()}function yo(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function Ud(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 uw(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:c})=>({unicode:i,name:r,shortcodes:o,url:a,category:l,annotation:c,id:i||r,skins:s&&n(s)}))}const Fi=requestAnimationFrame;let dw=typeof ResizeObserver=="function";function pw(e,t,n){let i;dw?(i=new ResizeObserver(n),i.observe(e)):Fi(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function Al(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let vo;function hw(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=Al(a);r===0&&(s=!0),typeof vo>"u"&&(vo=Al(t));const l=r/1.8<vo;na.set(o.unicode,l),l||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
3890
+ `;Es([ys({type:Number})],on.prototype,"splitRatio",2);Es([ys({type:Number})],on.prototype,"minRatio",2);Es([ys({type:Number})],on.prototype,"maxRatio",2);on=Es([cc("resizable-divider")],on);function Ei(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function ho(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const cb=1,ub=1,Ft="emoji",an="keyvalue",qa="favorites",db="tokens",Sd="tokens",pb="unicode",Ad="count",hb="group",gb="order",Cd="group-order",Xo="eTag",ds="url",bl="skinTone",mn="readonly",Ha="readwrite",Ed="skinUnicodes",fb="skinUnicodes",mb="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",yb="en";function vb(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 wl(e){return vb(e,t=>t.unicode)}function bb(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(an),t(Ft,pb,{[Sd]:[db,!0],[Cd]:[[hb,gb]],[Ed]:[fb,!0]}),t(qa,void 0,{[Ad]:[""]})}const Zo={},Oi={},ps={};function Td(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function wb(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,cb);Zo[e]=s,s.onupgradeneeded=o=>{o.oldVersion<ub&&bb(s.result)},Td(n,i,s)});return t.onclose=()=>ja(e),t}function kb(e){return Oi[e]||(Oi[e]=wb(e)),Oi[e]}function it(e,t,n,i){return new Promise((s,o)=>{const a=e.transaction(t,n,{durability:"relaxed"}),r=typeof t=="string"?a.objectStore(t):t.map(c=>a.objectStore(c));let l;i(r,a,c=>{l=c}),a.oncomplete=()=>s(l),a.onerror=()=>o(a.error)})}function ja(e){const t=Zo[e],n=t&&t.result;if(n){n.close();const i=ps[e];if(i)for(const s of i)s()}delete Zo[e],delete Oi[e],delete ps[e]}function xb(e){return new Promise((t,n)=>{ja(e);const i=indexedDB.deleteDatabase(e);Td(t,n,i)})}function $b(e,t){let n=ps[e];n||(n=ps[e]=[]),n.push(t)}const Sb=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 en(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||Sb.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const Ab=2;function Pd(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=Ab)}function Cb(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:l,emoji:c,version:d})=>{const m=[...new Set(Pd([...(a||[]).map(en).flat(),...(l||[]).map(en).flat(),...en(n),i]))].sort(),v={annotation:n,group:s,order:o,tags:l,tokens:m,unicode:c,version:d};if(i&&(v.emoticon=i),a&&(v.shortcodes=a),r){v.skinTones=[],v.skinUnicodes=[],v.skinVersions=[];for(const{tone:p,emoji:b,version:x}of r)v.skinTones.push(p),v.skinUnicodes.push(b),v.skinVersions.push(x)}return v})}function _d(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function Dt(e,t,n){_d(e,"get",t,n)}function Md(e,t,n){_d(e,"getAll",t,n)}function Va(e){e.commit&&e.commit()}function Eb(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 Id(e,t){const n=Eb(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 Tb(e){return!await Ga(e,an,ds)}async function Pb(e,t,n){const[i,s]=await Promise.all([Xo,ds].map(o=>Ga(e,an,o)));return i===n&&s===t}async function _b(e,t){return it(e,Ft,mn,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=l=>{const c=l.target.result;for(const d of c)if(a=d.unicode,t(d))return o(d);if(c.length<50)return o();r()}};r()})}async function Rd(e,t,n,i){{const s=Cb(t);await it(e,[Ft,an],Ha,([o,a],r)=>{let l,c,d=0;function m(){++d===2&&v()}function v(){if(!(l===i&&c===n)){o.clear();for(const p of s)o.put(p);a.put(i,Xo),a.put(n,ds),Va(r)}}Dt(a,Xo,p=>{l=p,m()}),Dt(a,ds,p=>{c=p,m()})})}}async function Mb(e,t){return it(e,Ft,mn,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);Md(n.index(Cd),o,s)})}async function Ld(e,t){const n=Pd(en(t));return n.length?it(e,Ft,mn,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&l()},l=()=>{const c=Id(a,d=>d.unicode);o(c.sort((d,m)=>d.order<m.order?-1:1))};for(let c=0;c<n.length;c++){const d=n[c],m=c===n.length-1?IDBKeyRange.bound(d,d+"￿",!1,!0):IDBKeyRange.only(d);Md(i.index(Sd),m,v=>{a.push(v),r()})}}):[]}async function Ib(e,t){const n=await Ld(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await _b(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function Rb(e,t){return it(e,Ft,mn,(n,i,s)=>Dt(n,t,o=>{if(o)return s(o);Dt(n.index(Ed),t,a=>s(a||null))}))}function Ga(e,t,n){return it(e,t,mn,(i,s,o)=>Dt(i,n,o))}function Lb(e,t,n,i){return it(e,t,Ha,(s,o)=>{s.put(i,n),Va(o)})}function Bb(e,t){return it(e,qa,Ha,(n,i)=>Dt(n,t,s=>{n.put((s||0)+1,t),Va(i)}))}function Db(e,t,n){return n===0?[]:it(e,[qa,Ft],mn,([i,s],o,a)=>{const r=[];i.index(Ad).openCursor(void 0,"prev").onsuccess=l=>{const c=l.target.result;if(!c)return a(r);function d(p){if(r.push(p),r.length===n)return a(r);c.continue()}const m=c.primaryKey,v=t.byName(m);if(v)return d(v);Dt(s,m,p=>{if(p)return d(p);c.continue()})}})}const Ti="";function Nb(e,t){const n=new Map;for(const s of e){const o=t(s);for(const a of o){let r=n;for(let c=0;c<a.length;c++){const d=a.charAt(c);let m=r.get(d);m||(m=new Map,r.set(d,m)),r=m}let l=r.get(Ti);l||(l=[],r.set(Ti,l)),l.push(s)}}return(s,o)=>{let a=n;for(let c=0;c<s.length;c++){const d=s.charAt(c),m=a.get(d);if(m)a=m;else return[]}if(o)return a.get(Ti)||[];const r=[],l=[a];for(;l.length;){const d=[...l.shift().entries()].sort((m,v)=>m[0]<v[0]?-1:1);for(const[m,v]of d)m===Ti?r.push(...v):l.push(v)}return r}}const Ub=["name","url"];function Ob(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||Ub.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function kl(e){Ob(e);const t=(v,p)=>v.name.toLowerCase()<p.name.toLowerCase()?-1:1,n=e.sort(t),s=Nb(e,v=>{const p=new Set;if(v.shortcodes)for(const b of v.shortcodes)for(const x of en(b))p.add(x);return p}),o=v=>s(v,!0),a=v=>s(v,!1),r=v=>{const p=en(v),b=p.map((x,C)=>(C<p.length-1?o:a)(x));return Id(b,x=>x.name).sort(t)},l=new Map,c=new Map;for(const v of e){c.set(v.name.toLowerCase(),v);for(const p of v.shortcodes||[])l.set(p.toLowerCase(),v)}return{all:n,search:r,byShortcode:v=>l.get(v.toLowerCase()),byName:v=>c.get(v.toLowerCase())}}const Fb=typeof wrappedJSObject<"u";function In(e){if(!e)return e;if(Fb&&(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 Bd(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Wb=["annotation","emoji","group","order","version"];function zb(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Wb.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function Dd(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Kb(e){const t=await fetch(e,{method:"HEAD"});Dd(t,e);const n=t.headers.get("etag");return Bd(n),n}async function ea(e){const t=await fetch(e);Dd(t,e);const n=t.headers.get("etag");Bd(n);const i=await t.json();return zb(i),[n,i]}function qb(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Hb(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 Nd(e){const t=JSON.stringify(e);let n=Hb(t);const i=await crypto.subtle.digest("SHA-1",n),s=qb(i);return btoa(s)}async function jb(e,t){let n,i=await Kb(t);if(!i){const s=await ea(t);i=s[0],n=s[1],i||(i=await Nd(n))}await Pb(e,t,i)||(n||(n=(await ea(t))[1]),await Rd(e,n,t,i))}async function Vb(e,t){let[n,i]=await ea(t);n||(n=await Nd(i)),await Rd(e,i,t,n)}async function Gb(e,t){try{await jb(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class Qb{constructor({dataSource:t=mb,locale:n=yb,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=kl(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await kb(this._dbName);$b(this._dbName,this._clear);const n=this.dataSource;await Tb(t)?await Vb(t,n):this._lazyUpdate=Gb(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 ho(t),await this.ready(),wl(await Mb(this._db,t)).map(In)}async getEmojiBySearchQuery(t){Ei(t),await this.ready();const n=this._custom.search(t),i=wl(await Ld(this._db,t)).map(In);return[...n,...i]}async getEmojiByShortcode(t){Ei(t),await this.ready();const n=this._custom.byShortcode(t);return n||In(await Ib(this._db,t))}async getEmojiByUnicodeOrName(t){Ei(t),await this.ready();const n=this._custom.byName(t);return n||In(await Rb(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Ga(this._db,an,bl)||0}async setPreferredSkinTone(t){return ho(t),await this.ready(),Lb(this._db,an,bl,t)}async incrementFavoriteEmojiCount(t){return Ei(t),await this.ready(),Bb(this._db,t)}async getTopFavoriteEmoji(t){return ho(t),await this.ready(),(await Db(this._db,this._custom,t)).map(In)}set customEmoji(t){this._custom=kl(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 ja(this._dbName)}async delete(){await this._shutdown(),await xb(this._dbName)}}const ta=[[-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})),go=ta.slice(1),Jb=2,xl=6,Ud=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function $l(e){return e.unicode.includes("‍")}const Yb={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},Xb=1e3,Zb="🖐️",ew=8,tw=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],Od='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',nw=(e,t)=>e<t?-1:e>t?1:0,Sl=(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 ${Od}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},iw=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function sw(e){const t=Sl(e,"#000"),n=Sl(e,"#fff");return t&&n&&iw(t,n)}function ow(){const e=Object.entries(Yb);try{for(const[t,n]of e)if(sw(t))return n}catch{}return e[0][1]}let fo;const mo=()=>(fo||(fo=new Promise(e=>Ud(()=>e(ow())))),fo),na=new Map,aw="️",rw="\uD83C",lw="‍",cw=127995,uw=57339;function dw(e,t){if(t===0)return e;const n=e.indexOf(lw);return n!==-1?e.substring(0,n)+String.fromCodePoint(cw+t-1)+e.substring(n):(e.endsWith(aw)&&(e=e.substring(0,e.length-1)),e+rw+String.fromCodePoint(uw+t-1))}function Fe(e){e.preventDefault(),e.stopPropagation()}function yo(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function Fd(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 pw(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:c})=>({unicode:i,name:r,shortcodes:o,url:a,category:l,annotation:c,id:i||r,skins:s&&n(s)}))}const Fi=requestAnimationFrame;let hw=typeof ResizeObserver=="function";function gw(e,t,n){let i;hw?(i=new ResizeObserver(n),i.observe(e)):Fi(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function Al(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let vo;function fw(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=Al(a);r===0&&(s=!0),typeof vo>"u"&&(vo=Al(t));const l=r/1.8<vo;na.set(o.unicode,l),l||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
3891
3891
  This is likely due to using \`display:none\` which is unsupported.
3892
3892
  If this is a Jest/Vitest environment, you can ignore this warning.
3893
- For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function gw(e){return Ud(e,t=>t)}function fw(e){e&&(e.scrollTop=0)}function Kn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function Cl(e){return""+e}function mw(e){const t=document.createElement("template");return t.innerHTML=e,t}const yw=new WeakMap,vw=new WeakMap,bw=Symbol("un-keyed"),ww="replaceChildren"in Element.prototype;function kw(e,t){ww?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function xw(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 $w(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=xw(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&kw(i,e)}function Sw(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:a,attributeValuePre:r,attributeValuePost:l}}=n,c=e[o];if(s!==c)if(n.currentExpression=c,a)if(c===null)i.removeAttribute(a);else{const d=r+Cl(c)+l;i.setAttribute(a,d)}else{let d;Array.isArray(c)?$w(c,n):c instanceof Element?(d=c,i.replaceWith(d)):i.nodeValue=Cl(c),d&&(n.targetNode=d)}}}function Aw(e){let t="",n=!1,i=!1,s=-1;const o=new Map,a=[];let r=0;for(let c=0,d=e.length;c<d;c++){const m=e[c];if(t+=m.slice(r),c===d-1)break;for(let T=0;T<m.length;T++)switch(m.charAt(T)){case"<":{m.charAt(T+1)==="/"?a.pop():(n=!0,a.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const v=a[a.length-1],p=Kn(o,v,()=>[]);let b,x,C;if(i){const T=/(\S+)="?([^"=]*)$/.exec(m);b=T[1],x=T[2];const M=/^([^">]*)("?)/.exec(e[c+1]);C=M[1],t=t.slice(0,-1*T[0].length),r=M[0].length}else r=0;const A={attributeName:b,attributeValuePre:x,attributeValuePost:C,expressionIndex:c};p.push(A),!n&&!i&&(t+=" ")}return{template:mw(t),elementsToBindings:o}}function El(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 Cw(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))El(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&El(r,o,n)}while(o=s.nextNode())}return n}function Ew(e){const{template:t,elementsToBindings:n}=Kn(yw,e,()=>Aw(e)),i=t.cloneNode(!0).content.firstElementChild,s=Cw(i,n);return function(a){return Sw(a,s),i}}function Tw(e){const t=Kn(vw,e,()=>new Map);let n=bw;function i(o,...a){const r=Kn(t,o,()=>new Map);return Kn(r,n,()=>Ew(o))(a)}function s(o,a,r){return o.map((l,c)=>{const d=n;n=r(l);try{return a(l,c)}finally{n=d}})}return{map:s,html:i}}function Pw(e,t,n,i,s,o,a,r,l){const{labelWithSkin:c,titleForEmoji:d,unicodeWithSkin:m}=n,{html:v,map:p}=Tw(t);function b(T,M,N){return p(T,(y,k)=>v`<button role="${M?"option":"menuitem"}" aria-selected="${M?k===t.activeSearchItem:null}" aria-label="${c(y,t.currentSkinTone)}" title="${d(y)}" class="${"emoji"+(M&&k===t.activeSearchItem?" active":"")+(y.unicode?"":" custom-emoji")}" id="${`${N}-${y.id}`}" style="${y.unicode?null:`--custom-emoji-background: url(${JSON.stringify(y.url)})`}">${y.unicode?m(y,t.currentSkinTone):""}</button>`,y=>`${N}-${y.id}`)}const C=v`<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">${p(t.skinTones,(T,M)=>v`<div id="skintone-${M}" class="emoji ${M===t.activeSkinTone?"active":""}" aria-selected="${M===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[M]}" aria-label="${t.i18n.skinTones[M]}">${T}</div>`,T=>T)}</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">${p(t.groups,T=>v`<button role="tab" class="nav-button" aria-controls="tab-${T.id}" aria-label="${t.i18n.categories[T.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===T.id}" title="${t.i18n.categories[T.name]}" data-group-id="${T.id}"><div class="nav-emoji emoji">${T.emoji}</div></button>`,T=>T.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">${p(t.currentEmojisWithCategories,(T,M)=>v`<div><div id="menu-label-${M}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:T.category?T.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${M!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(T.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${M}" id="${t.searchMode?"search-results":null}">${b(T.emojis,t.searchMode,"emo")}</div></div>`,T=>T.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${b(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,A=(T,M)=>{for(const N of e.querySelectorAll(`[${T}]`))M(N,N.getAttribute(T))};if(l){e.appendChild(C);for(const T of["click","focusout","input","keydown","keyup"])A(`data-on-${T}`,(M,N)=>{M.addEventListener(T,i[N])});A("data-ref",(T,M)=>{o[M]=T}),a.addEventListener("abort",()=>{e.removeChild(C)})}A("data-action",(T,M)=>{let N=r.get(M);N||r.set(M,N=new WeakSet),N.has(T)||(N.add(T),s[M](T))})}const hs=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function _w(e){let t=!1,n;const i=new Map,s=new Set;let o;const a=()=>{if(t)return;const c=[...s];s.clear();try{for(const d of c)d()}finally{o=!1,s.size&&(o=!0,hs(a))}},r=new Proxy({},{get(c,d){if(n){let m=i.get(d);m||(m=new Set,i.set(d,m)),m.add(n)}return c[d]},set(c,d,m){if(c[d]!==m){c[d]=m;const v=i.get(d);if(v){for(const p of v)s.add(p);o||(o=!0,hs(a))}}return!0}}),l=c=>{const d=()=>{const m=n;n=d;try{return c()}finally{n=m}};return d()};return e.addEventListener("abort",()=>{t=!0}),{state:r,createEffect:l}}function bo(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 Tl=new WeakMap;function Mw(e,t,n){{const i=e.closest(".tabpanel");let s=Tl.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),Tl.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const wo=[],{assign:Pi}=Object;function Iw(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=_w(s),r=new Map;Pi(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),Pi(o,t),Pi(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:Xb,isRtl:!1,currentGroupIndex:0,groups:go,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const l=_=>{e.getElementById(_).focus()},c=_=>e.getElementById(`emo-${_.id}`),d=(_,D)=>{n.rootElement.dispatchEvent(new CustomEvent(_,{detail:D,bubbles:!0,composed:!0}))},m=(_,D)=>_.id===D.id,v=(_,D)=>{const{category:K,emojis:H}=_,{category:oe,emojis:te}=D;return K!==oe?!1:bo(H,te,m)},p=_=>{bo(o.currentEmojis,_,m)||(o.currentEmojis=_)},b=_=>{o.searchMode!==_&&(o.searchMode=_)},x=_=>{bo(o.currentEmojisWithCategories,_,v)||(o.currentEmojisWithCategories=_)},C=(_,D)=>D&&_.skins&&_.skins[D]||_.unicode,M={labelWithSkin:(_,D)=>gw([_.name||C(_,D),_.annotation,..._.shortcodes||wo].filter(Boolean)).join(", "),titleForEmoji:_=>_.annotation||(_.shortcodes||wo).join(", "),unicodeWithSkin:C},N={onClickSkinToneButton:ie,onEmojiClick:ai,onNavClick:si,onNavKeydown:Ms,onSearchKeydown:_s,onSkinToneOptionsClick:ri,onSkinToneOptionsFocusOut:st,onSkinToneOptionsKeydown:ft,onSkinToneOptionsKeyup:bn,onSearchInput:li},y={calculateEmojiGridStyle:P,updateOnIntersection:I};let k=!0;a(()=>{Pw(e,o,M,N,y,n,s,r,k),k=!1}),o.emojiVersion||mo().then(_=>{_||(o.message=o.i18n.emojiUnsupportedMessage)}),a(()=>{async function _(){let D=!1;const K=setTimeout(()=>{D=!0,o.message=o.i18n.loadingMessage},Jb);try{await o.database.ready(),o.databaseLoaded=!0}catch(H){console.error(H),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(K),D&&(D=!1,o.message="")}}o.database&&_()}),a(()=>{o.pickerStyle=`
3893
+ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function mw(e){return Fd(e,t=>t)}function yw(e){e&&(e.scrollTop=0)}function Kn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function Cl(e){return""+e}function vw(e){const t=document.createElement("template");return t.innerHTML=e,t}const bw=new WeakMap,ww=new WeakMap,kw=Symbol("un-keyed"),xw="replaceChildren"in Element.prototype;function $w(e,t){xw?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function Sw(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 Aw(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=Sw(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&$w(i,e)}function Cw(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:a,attributeValuePre:r,attributeValuePost:l}}=n,c=e[o];if(s!==c)if(n.currentExpression=c,a)if(c===null)i.removeAttribute(a);else{const d=r+Cl(c)+l;i.setAttribute(a,d)}else{let d;Array.isArray(c)?Aw(c,n):c instanceof Element?(d=c,i.replaceWith(d)):i.nodeValue=Cl(c),d&&(n.targetNode=d)}}}function Ew(e){let t="",n=!1,i=!1,s=-1;const o=new Map,a=[];let r=0;for(let c=0,d=e.length;c<d;c++){const m=e[c];if(t+=m.slice(r),c===d-1)break;for(let T=0;T<m.length;T++)switch(m.charAt(T)){case"<":{m.charAt(T+1)==="/"?a.pop():(n=!0,a.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const v=a[a.length-1],p=Kn(o,v,()=>[]);let b,x,C;if(i){const T=/(\S+)="?([^"=]*)$/.exec(m);b=T[1],x=T[2];const M=/^([^">]*)("?)/.exec(e[c+1]);C=M[1],t=t.slice(0,-1*T[0].length),r=M[0].length}else r=0;const A={attributeName:b,attributeValuePre:x,attributeValuePost:C,expressionIndex:c};p.push(A),!n&&!i&&(t+=" ")}return{template:vw(t),elementsToBindings:o}}function El(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 Tw(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))El(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&El(r,o,n)}while(o=s.nextNode())}return n}function Pw(e){const{template:t,elementsToBindings:n}=Kn(bw,e,()=>Ew(e)),i=t.cloneNode(!0).content.firstElementChild,s=Tw(i,n);return function(a){return Cw(a,s),i}}function _w(e){const t=Kn(ww,e,()=>new Map);let n=kw;function i(o,...a){const r=Kn(t,o,()=>new Map);return Kn(r,n,()=>Pw(o))(a)}function s(o,a,r){return o.map((l,c)=>{const d=n;n=r(l);try{return a(l,c)}finally{n=d}})}return{map:s,html:i}}function Mw(e,t,n,i,s,o,a,r,l){const{labelWithSkin:c,titleForEmoji:d,unicodeWithSkin:m}=n,{html:v,map:p}=_w(t);function b(T,M,N){return p(T,(y,k)=>v`<button role="${M?"option":"menuitem"}" aria-selected="${M?k===t.activeSearchItem:null}" aria-label="${c(y,t.currentSkinTone)}" title="${d(y)}" class="${"emoji"+(M&&k===t.activeSearchItem?" active":"")+(y.unicode?"":" custom-emoji")}" id="${`${N}-${y.id}`}" style="${y.unicode?null:`--custom-emoji-background: url(${JSON.stringify(y.url)})`}">${y.unicode?m(y,t.currentSkinTone):""}</button>`,y=>`${N}-${y.id}`)}const C=v`<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">${p(t.skinTones,(T,M)=>v`<div id="skintone-${M}" class="emoji ${M===t.activeSkinTone?"active":""}" aria-selected="${M===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[M]}" aria-label="${t.i18n.skinTones[M]}">${T}</div>`,T=>T)}</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">${p(t.groups,T=>v`<button role="tab" class="nav-button" aria-controls="tab-${T.id}" aria-label="${t.i18n.categories[T.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===T.id}" title="${t.i18n.categories[T.name]}" data-group-id="${T.id}"><div class="nav-emoji emoji">${T.emoji}</div></button>`,T=>T.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">${p(t.currentEmojisWithCategories,(T,M)=>v`<div><div id="menu-label-${M}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:T.category?T.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${M!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(T.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${M}" id="${t.searchMode?"search-results":null}">${b(T.emojis,t.searchMode,"emo")}</div></div>`,T=>T.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${b(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,A=(T,M)=>{for(const N of e.querySelectorAll(`[${T}]`))M(N,N.getAttribute(T))};if(l){e.appendChild(C);for(const T of["click","focusout","input","keydown","keyup"])A(`data-on-${T}`,(M,N)=>{M.addEventListener(T,i[N])});A("data-ref",(T,M)=>{o[M]=T}),a.addEventListener("abort",()=>{e.removeChild(C)})}A("data-action",(T,M)=>{let N=r.get(M);N||r.set(M,N=new WeakSet),N.has(T)||(N.add(T),s[M](T))})}const hs=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function Iw(e){let t=!1,n;const i=new Map,s=new Set;let o;const a=()=>{if(t)return;const c=[...s];s.clear();try{for(const d of c)d()}finally{o=!1,s.size&&(o=!0,hs(a))}},r=new Proxy({},{get(c,d){if(n){let m=i.get(d);m||(m=new Set,i.set(d,m)),m.add(n)}return c[d]},set(c,d,m){if(c[d]!==m){c[d]=m;const v=i.get(d);if(v){for(const p of v)s.add(p);o||(o=!0,hs(a))}}return!0}}),l=c=>{const d=()=>{const m=n;n=d;try{return c()}finally{n=m}};return d()};return e.addEventListener("abort",()=>{t=!0}),{state:r,createEffect:l}}function bo(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 Tl=new WeakMap;function Rw(e,t,n){{const i=e.closest(".tabpanel");let s=Tl.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),Tl.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const wo=[],{assign:Pi}=Object;function Lw(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=Iw(s),r=new Map;Pi(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),Pi(o,t),Pi(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:ew,isRtl:!1,currentGroupIndex:0,groups:go,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const l=_=>{e.getElementById(_).focus()},c=_=>e.getElementById(`emo-${_.id}`),d=(_,D)=>{n.rootElement.dispatchEvent(new CustomEvent(_,{detail:D,bubbles:!0,composed:!0}))},m=(_,D)=>_.id===D.id,v=(_,D)=>{const{category:K,emojis:H}=_,{category:oe,emojis:te}=D;return K!==oe?!1:bo(H,te,m)},p=_=>{bo(o.currentEmojis,_,m)||(o.currentEmojis=_)},b=_=>{o.searchMode!==_&&(o.searchMode=_)},x=_=>{bo(o.currentEmojisWithCategories,_,v)||(o.currentEmojisWithCategories=_)},C=(_,D)=>D&&_.skins&&_.skins[D]||_.unicode,M={labelWithSkin:(_,D)=>mw([_.name||C(_,D),_.annotation,..._.shortcodes||wo].filter(Boolean)).join(", "),titleForEmoji:_=>_.annotation||(_.shortcodes||wo).join(", "),unicodeWithSkin:C},N={onClickSkinToneButton:ie,onEmojiClick:ai,onNavClick:si,onNavKeydown:Ms,onSearchKeydown:_s,onSkinToneOptionsClick:ri,onSkinToneOptionsFocusOut:st,onSkinToneOptionsKeydown:ft,onSkinToneOptionsKeyup:bn,onSearchInput:li},y={calculateEmojiGridStyle:P,updateOnIntersection:I};let k=!0;a(()=>{Mw(e,o,M,N,y,n,s,r,k),k=!1}),o.emojiVersion||mo().then(_=>{_||(o.message=o.i18n.emojiUnsupportedMessage)}),a(()=>{async function _(){let D=!1;const K=setTimeout(()=>{D=!0,o.message=o.i18n.loadingMessage},Xb);try{await o.database.ready(),o.databaseLoaded=!0}catch(H){console.error(H),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(K),D&&(D=!1,o.message="")}}o.database&&_()}),a(()=>{o.pickerStyle=`
3894
3894
  --num-groups: ${o.groups.length};
3895
3895
  --indicator-opacity: ${o.searchMode?0:1};
3896
- --num-skintones: ${xl};`}),a(()=>{o.customEmoji&&o.database&&S()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==ta&&(o.groups=ta):o.groups!==go&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=go)}),a(()=>{async function _(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}_()}),a(()=>{o.skinTones=Array(xl).fill().map((_,D)=>cw(o.skinToneEmoji,D))}),a(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),a(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),a(()=>{async function _(){const{database:D}=o,K=(await Promise.all(Zb.map(H=>D.getEmojiByUnicodeOrName(H)))).filter(Boolean);o.defaultFavoriteEmojis=K}o.databaseLoaded&&_()});function S(){const{customEmoji:_,database:D}=o,K=_||wo;D.customEmoji!==K&&(D.customEmoji=K)}a(()=>{async function _(){S();const{database:D,defaultFavoriteEmojis:K,numColumns:H}=o,oe=await D.getTopFavoriteEmoji(H),te=await Y(Ud([...oe,...K],be=>be.unicode||be.name).slice(0,H));o.currentFavorites=te}o.databaseLoaded&&o.defaultFavoriteEmojis&&_()});function P(_){pw(_,s,()=>{{const D=getComputedStyle(n.rootElement),K=parseInt(D.getPropertyValue("--num-columns"),10),H=D.getPropertyValue("direction")==="rtl";o.numColumns=K,o.isRtl=H}})}function I(_){Mw(_,s,D=>{for(const{target:K,isIntersecting:H}of D)K.classList.toggle("onscreen",H)})}a(()=>{async function _(){const{searchText:D,currentGroup:K,databaseLoaded:H,customEmoji:oe}=o;if(!H)o.currentEmojis=[],o.searchMode=!1;else if(D.length>=Gb){const te=await Ve(D);o.searchText===D&&(p(te),b(!0))}else{const{id:te}=K;if(te!==-1||oe&&oe.length){const be=await ue(te);o.currentGroup.id===te&&(p(be),b(!1))}}}_()});const B=()=>{Fi(()=>fw(n.tabpanelElement))};a(()=>{const{currentEmojis:_,emojiVersion:D}=o,K=_.filter(H=>H.unicode).filter(H=>$l(H)&&!na.has(H.unicode));if(!D&&K.length)p(_),Fi(()=>L(K));else{const H=D?_:_.filter(F);p(H),B()}});function L(_){hw(_,n.baselineEmoji,c)?B():o.currentEmojis=[...o.currentEmojis]}function F(_){return!_.unicode||!$l(_)||na.get(_.unicode)}async function q(_){const D=o.emojiVersion||await mo();return _.filter(({version:K})=>!K||K<=D)}async function Y(_){return uw(_,o.emojiVersion||await mo())}async function ue(_){const D=_===-1?o.customEmoji:await o.database.getEmojiByGroup(_);return Y(await q(D))}async function Ve(_){return Y(await q(await o.database.getEmojiBySearchQuery(_)))}a(()=>{}),a(()=>{function _(){const{searchMode:K,currentEmojis:H}=o;if(K)return[{category:"",emojis:H}];const oe=new Map;for(const te of H){const be=te.category||"";let ot=oe.get(be);ot||(ot=[],oe.set(be,ot)),ot.push(te)}return[...oe.entries()].map(([te,be])=>({category:te,emojis:be})).sort((te,be)=>o.customCategorySorting(te.category,be.category))}const D=_();x(D)}),a(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),a(()=>{const{rawSearchText:_}=o;Dd(()=>{o.searchText=(_||"").trim(),o.activeSearchItem=-1})});function _s(_){if(!o.searchMode||!o.currentEmojis.length)return;const D=K=>{Fe(_),o.activeSearchItem=yo(K,o.activeSearchItem,o.currentEmojis)};switch(_.key){case"ArrowDown":return D(!1);case"ArrowUp":return D(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Fe(_),ae(o.currentEmojis[o.activeSearchItem].id)}}function si(_){const{target:D}=_,K=D.closest(".nav-button");if(!K)return;const H=parseInt(K.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(oe=>oe.id===H)}function Ms(_){const{target:D,key:K}=_,H=oe=>{oe&&(Fe(_),oe.focus())};switch(K){case"ArrowLeft":return H(D.previousElementSibling);case"ArrowRight":return H(D.nextElementSibling);case"Home":return H(D.parentElement.firstElementChild);case"End":return H(D.parentElement.lastElementChild)}}async function oi(_){const D=await o.database.getEmojiByUnicodeOrName(_),K=[...o.currentEmojis,...o.currentFavorites].find(oe=>oe.id===_),H=K.unicode&&C(K,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(_),{emoji:D,skinTone:o.currentSkinTone,...H&&{unicode:H},...K.name&&{name:K.name}}}async function ae(_){const D=oi(_);d("emoji-click-sync",D),d("emoji-click",await D)}function ai(_){const{target:D}=_;if(!D.classList.contains("emoji"))return;Fe(_);const K=D.id.substring(4);ae(K)}function re(_){o.currentSkinTone=_,o.skinTonePickerExpanded=!1,l("skintone-button"),d("skin-tone-change",{skinTone:_}),o.database.setPreferredSkinTone(_)}function ri(_){const{target:{id:D}}=_,K=D&&D.match(/^skintone-(\d)/);if(!K)return;Fe(_);const H=parseInt(K[1],10);re(H)}function ie(_){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Fe(_),Fi(()=>l("skintone-list")))}a(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function ft(_){if(!o.skinTonePickerExpanded)return;const D=async K=>{Fe(_),o.activeSkinTone=K};switch(_.key){case"ArrowUp":return D(yo(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return D(yo(!1,o.activeSkinTone,o.skinTones));case"Home":return D(0);case"End":return D(o.skinTones.length-1);case"Enter":return Fe(_),re(o.activeSkinTone);case"Escape":return Fe(_),o.skinTonePickerExpanded=!1,l("skintone-button")}}function bn(_){if(o.skinTonePickerExpanded&&_.key===" ")return Fe(_),re(o.activeSkinTone)}async function st(_){const{relatedTarget:D}=_;(!D||D.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function li(_){o.rawSearchText=_.target.value}return{$set(_){Pi(o,_)},$destroy(){i.abort()}}}const Rw="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Lw="en";var Bw={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"}},Dw=':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 Od=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],Nw=`:host{--emoji-font-family:${Nd}}`;class Qa extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=Dw+Nw,this.shadowRoot.appendChild(n),this._ctx={locale:Lw,dataSource:Rw,skinToneEmoji:Yb,customCategorySorting:ew,customEmoji:null,i18n:Bw,emojiVersion:null,...t};for(const i of Od)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){Pl(this),this._cmp||(this._cmp=Iw(this.shadowRoot,this._ctx))}disconnectedCallback(){Pl(this),hs(()=>{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 Vb({locale:t,dataSource:n}))}_dbFlush(){hs(()=>this._dbCreate())}}const Fd={};for(const e of Od)Fd[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(Qa.prototype,Fd);function Pl(e){e instanceof Qa||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Qa);function Uw(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 _l(e){e.style.height="44px",e.style.overflowY="hidden"}const Ow=5e3;function Fw(e){return e?e.active?u`
3896
+ --num-skintones: ${xl};`}),a(()=>{o.customEmoji&&o.database&&S()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==ta&&(o.groups=ta):o.groups!==go&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=go)}),a(()=>{async function _(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}_()}),a(()=>{o.skinTones=Array(xl).fill().map((_,D)=>dw(o.skinToneEmoji,D))}),a(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),a(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),a(()=>{async function _(){const{database:D}=o,K=(await Promise.all(tw.map(H=>D.getEmojiByUnicodeOrName(H)))).filter(Boolean);o.defaultFavoriteEmojis=K}o.databaseLoaded&&_()});function S(){const{customEmoji:_,database:D}=o,K=_||wo;D.customEmoji!==K&&(D.customEmoji=K)}a(()=>{async function _(){S();const{database:D,defaultFavoriteEmojis:K,numColumns:H}=o,oe=await D.getTopFavoriteEmoji(H),te=await Y(Fd([...oe,...K],be=>be.unicode||be.name).slice(0,H));o.currentFavorites=te}o.databaseLoaded&&o.defaultFavoriteEmojis&&_()});function P(_){gw(_,s,()=>{{const D=getComputedStyle(n.rootElement),K=parseInt(D.getPropertyValue("--num-columns"),10),H=D.getPropertyValue("direction")==="rtl";o.numColumns=K,o.isRtl=H}})}function I(_){Rw(_,s,D=>{for(const{target:K,isIntersecting:H}of D)K.classList.toggle("onscreen",H)})}a(()=>{async function _(){const{searchText:D,currentGroup:K,databaseLoaded:H,customEmoji:oe}=o;if(!H)o.currentEmojis=[],o.searchMode=!1;else if(D.length>=Jb){const te=await Ve(D);o.searchText===D&&(p(te),b(!0))}else{const{id:te}=K;if(te!==-1||oe&&oe.length){const be=await ue(te);o.currentGroup.id===te&&(p(be),b(!1))}}}_()});const B=()=>{Fi(()=>yw(n.tabpanelElement))};a(()=>{const{currentEmojis:_,emojiVersion:D}=o,K=_.filter(H=>H.unicode).filter(H=>$l(H)&&!na.has(H.unicode));if(!D&&K.length)p(_),Fi(()=>L(K));else{const H=D?_:_.filter(F);p(H),B()}});function L(_){fw(_,n.baselineEmoji,c)?B():o.currentEmojis=[...o.currentEmojis]}function F(_){return!_.unicode||!$l(_)||na.get(_.unicode)}async function q(_){const D=o.emojiVersion||await mo();return _.filter(({version:K})=>!K||K<=D)}async function Y(_){return pw(_,o.emojiVersion||await mo())}async function ue(_){const D=_===-1?o.customEmoji:await o.database.getEmojiByGroup(_);return Y(await q(D))}async function Ve(_){return Y(await q(await o.database.getEmojiBySearchQuery(_)))}a(()=>{}),a(()=>{function _(){const{searchMode:K,currentEmojis:H}=o;if(K)return[{category:"",emojis:H}];const oe=new Map;for(const te of H){const be=te.category||"";let ot=oe.get(be);ot||(ot=[],oe.set(be,ot)),ot.push(te)}return[...oe.entries()].map(([te,be])=>({category:te,emojis:be})).sort((te,be)=>o.customCategorySorting(te.category,be.category))}const D=_();x(D)}),a(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),a(()=>{const{rawSearchText:_}=o;Ud(()=>{o.searchText=(_||"").trim(),o.activeSearchItem=-1})});function _s(_){if(!o.searchMode||!o.currentEmojis.length)return;const D=K=>{Fe(_),o.activeSearchItem=yo(K,o.activeSearchItem,o.currentEmojis)};switch(_.key){case"ArrowDown":return D(!1);case"ArrowUp":return D(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Fe(_),ae(o.currentEmojis[o.activeSearchItem].id)}}function si(_){const{target:D}=_,K=D.closest(".nav-button");if(!K)return;const H=parseInt(K.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(oe=>oe.id===H)}function Ms(_){const{target:D,key:K}=_,H=oe=>{oe&&(Fe(_),oe.focus())};switch(K){case"ArrowLeft":return H(D.previousElementSibling);case"ArrowRight":return H(D.nextElementSibling);case"Home":return H(D.parentElement.firstElementChild);case"End":return H(D.parentElement.lastElementChild)}}async function oi(_){const D=await o.database.getEmojiByUnicodeOrName(_),K=[...o.currentEmojis,...o.currentFavorites].find(oe=>oe.id===_),H=K.unicode&&C(K,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(_),{emoji:D,skinTone:o.currentSkinTone,...H&&{unicode:H},...K.name&&{name:K.name}}}async function ae(_){const D=oi(_);d("emoji-click-sync",D),d("emoji-click",await D)}function ai(_){const{target:D}=_;if(!D.classList.contains("emoji"))return;Fe(_);const K=D.id.substring(4);ae(K)}function re(_){o.currentSkinTone=_,o.skinTonePickerExpanded=!1,l("skintone-button"),d("skin-tone-change",{skinTone:_}),o.database.setPreferredSkinTone(_)}function ri(_){const{target:{id:D}}=_,K=D&&D.match(/^skintone-(\d)/);if(!K)return;Fe(_);const H=parseInt(K[1],10);re(H)}function ie(_){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Fe(_),Fi(()=>l("skintone-list")))}a(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function ft(_){if(!o.skinTonePickerExpanded)return;const D=async K=>{Fe(_),o.activeSkinTone=K};switch(_.key){case"ArrowUp":return D(yo(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return D(yo(!1,o.activeSkinTone,o.skinTones));case"Home":return D(0);case"End":return D(o.skinTones.length-1);case"Enter":return Fe(_),re(o.activeSkinTone);case"Escape":return Fe(_),o.skinTonePickerExpanded=!1,l("skintone-button")}}function bn(_){if(o.skinTonePickerExpanded&&_.key===" ")return Fe(_),re(o.activeSkinTone)}async function st(_){const{relatedTarget:D}=_;(!D||D.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function li(_){o.rawSearchText=_.target.value}return{$set(_){Pi(o,_)},$destroy(){i.abort()}}}const Bw="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Dw="en";var Nw={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"}},Uw=':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 Wd=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],Ow=`:host{--emoji-font-family:${Od}}`;class Qa extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=Uw+Ow,this.shadowRoot.appendChild(n),this._ctx={locale:Dw,dataSource:Bw,skinToneEmoji:Zb,customCategorySorting:nw,customEmoji:null,i18n:Nw,emojiVersion:null,...t};for(const i of Wd)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){Pl(this),this._cmp||(this._cmp=Lw(this.shadowRoot,this._ctx))}disconnectedCallback(){Pl(this),hs(()=>{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 Qb({locale:t,dataSource:n}))}_dbFlush(){hs(()=>this._dbCreate())}}const zd={};for(const e of Wd)zd[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(Qa.prototype,zd);function Pl(e){e instanceof Qa||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Qa);function Fw(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 _l(e){e.style.height="44px",e.style.overflowY="hidden"}const Ww=5e3;function zw(e){return e?e.active?u`
3897
3897
  <div class="callout info compaction-indicator compaction-indicator--active">
3898
3898
  ${E.loader} Compacting context...
3899
3899
  </div>
3900
- `:e.completedAt&&Date.now()-e.completedAt<Ow?u`
3900
+ `:e.completedAt&&Date.now()-e.completedAt<Ww?u`
3901
3901
  <div class="callout success compaction-indicator compaction-indicator--complete">
3902
3902
  ${E.check} Context compacted
3903
3903
  </div>
3904
- `:w:w}const et=5*1024*1024;function tt(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function De(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 Ww=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function Wd(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function zd(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Ww.test(e.name)}function Kd(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function qd(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function zw(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(Wd(e)){if(e.size>et){n&&De(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:tt(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(zd(e)){if(e.size>et){n&&De(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:tt(),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(Kd(e)){if(e.size>et){n&&De(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:tt(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(qd(e)){if(e.size>et){n&&De(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:tt(),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&&De(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Kw(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(Wd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`Image too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:l,mimeType:a.type},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsDataURL(a)}else if(zd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`File too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:l},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsText(a)}else if(Kd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`PDF too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:l,mimeType:"application/pdf",fileName:a.name},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsDataURL(a)}else if(qd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`Video too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:l,mimeType:a.type||"video/mp4",fileName:a.name},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsDataURL(a)}else De(n,`Unsupported file type: ${a.name}. Use the Files page to upload to workspace.`)}}function qw(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function Hw(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function jw(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 c=l.type.startsWith("video/")?"Video":"Image";if(l.size>et){const m=((a=(o=e.target)==null?void 0:o.closest)==null?void 0:a.call(o,".chat"))??document.querySelector(".chat");m&&De(m,`${c} too large (${(l.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const d=new FileReader;d.onload=()=>{var x;const m=d.result,v=l.type.startsWith("video/"),p={id:tt(),dataUrl:m,mimeType:l.type,fileName:v?l.name||"video.mp4":void 0},b=t.attachments??[];(x=t.onAttachmentsChange)==null||x.call(t,[...b,p])},d.readAsDataURL(l)}}}function Vw(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 Gw(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),c=t.draft.slice(r);t.onDraftChange(l+i+c);const d=s==null?void 0:s.querySelector(".emoji-picker-popup"),m=s==null?void 0:s.querySelector(".chat-compose__emoji");d==null||d.classList.remove("active"),m==null||m.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const v=a+i.length;o.setSelectionRange(v,v)})}function Qw(e){const t=e.attachments??[];return t.length===0?w:u`
3904
+ `:w:w}const et=5*1024*1024;function tt(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function De(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 Kw=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function Kd(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function qd(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Kw.test(e.name)}function Hd(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function jd(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function qw(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(Kd(e)){if(e.size>et){n&&De(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:tt(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(qd(e)){if(e.size>et){n&&De(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:tt(),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(Hd(e)){if(e.size>et){n&&De(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:tt(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(jd(e)){if(e.size>et){n&&De(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:tt(),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&&De(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Hw(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(Kd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`Image too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:l,mimeType:a.type},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsDataURL(a)}else if(qd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`File too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:l},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsText(a)}else if(Hd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`PDF too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:l,mimeType:"application/pdf",fileName:a.name},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsDataURL(a)}else if(jd(a)){if(!t.onAttachmentsChange)continue;if(a.size>et){De(n,`Video too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var m;const l=r.result,c={id:tt(),dataUrl:l,mimeType:a.type||"video/mp4",fileName:a.name},d=t.attachments??[];(m=t.onAttachmentsChange)==null||m.call(t,[...d,c])},r.readAsDataURL(a)}else De(n,`Unsupported file type: ${a.name}. Use the Files page to upload to workspace.`)}}function jw(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function Vw(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function Gw(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 c=l.type.startsWith("video/")?"Video":"Image";if(l.size>et){const m=((a=(o=e.target)==null?void 0:o.closest)==null?void 0:a.call(o,".chat"))??document.querySelector(".chat");m&&De(m,`${c} too large (${(l.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const d=new FileReader;d.onload=()=>{var x;const m=d.result,v=l.type.startsWith("video/"),p={id:tt(),dataUrl:m,mimeType:l.type,fileName:v?l.name||"video.mp4":void 0},b=t.attachments??[];(x=t.onAttachmentsChange)==null||x.call(t,[...b,p])},d.readAsDataURL(l)}}}function Qw(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 Jw(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),c=t.draft.slice(r);t.onDraftChange(l+i+c);const d=s==null?void 0:s.querySelector(".emoji-picker-popup"),m=s==null?void 0:s.querySelector(".chat-compose__emoji");d==null||d.classList.remove("active"),m==null||m.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const v=a+i.length;o.setSelectionRange(v,v)})}function Yw(e){const t=e.attachments??[];return t.length===0?w:u`
3905
3905
  <div class="chat-attachments">
3906
3906
  ${t.map(n=>{var i;return n.fileName?u`
3907
3907
  <div class="chat-attachment chat-attachment--file">
@@ -3934,7 +3934,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3934
3934
  </div>
3935
3935
  `})}
3936
3936
  </div>
3937
- `}function Hd(e){var b,x,C;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(x=(b=e.sessions)==null?void 0:b.sessions)==null?void 0:x.find(A=>A.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",a=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const r=(((C=e.attachments)==null?void 0:C.length)??0)>0,l=e.connected?r?"Add a message...":"Message...":"Connecting…";tb({onSend:A=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],A]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var A;(A=e.requestUpdate)==null||A.call(e)}});const c=eb(),d=!c&&!e.draft.trim()&&!r&&!n,m=e.splitRatio??.6,v=!!(e.sidebarOpen&&e.onCloseSidebar),p=u`
3937
+ `}function Vd(e){var b,x,C;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(x=(b=e.sessions)==null?void 0:b.sessions)==null?void 0:x.find(A=>A.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",a=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const r=(((C=e.attachments)==null?void 0:C.length)??0)>0,l=e.connected?r?"Add a message...":"Message...":"Connecting…";ib({onSend:A=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],A]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var A;(A=e.requestUpdate)==null||A.call(e)}});const c=nb(),d=!c&&!e.draft.trim()&&!r&&!n,m=e.splitRatio??.6,v=!!(e.sidebarOpen&&e.onCloseSidebar),p=u`
3938
3938
  <div
3939
3939
  class="chat-thread"
3940
3940
  role="log"
@@ -3945,20 +3945,20 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3945
3945
  ${e.loadingOlder?u`<span class="chat-load-more__spinner">${E.loader}</span> Loading older messages…`:u`<button class="chat-load-more__btn" type="button" @click=${e.onLoadOlder}>Load older messages</button>`}
3946
3946
  </div>`:w}
3947
3947
  ${e.loading?u`<div class="muted">Loading chat…</div>`:w}
3948
- ${uy(Yw(e),A=>A.key,A=>A.kind==="interim"?qv(A.text):A.kind==="reading-indicator"?Kv():A.kind==="stream"?Hv(A.text,A.startedAt,e.onOpenSidebar):A.kind==="group"?jv(A,{onOpenSidebar:e.onOpenSidebar,showReasoning:a,assistantName:e.assistantName}):w)}
3948
+ ${py(Zw(e),A=>A.key,A=>A.kind==="interim"?jv(A.text):A.kind==="reading-indicator"?Hv():A.kind==="stream"?Vv(A.text,A.startedAt,e.onOpenSidebar):A.kind==="group"?Gv(A,{onOpenSidebar:e.onOpenSidebar,showReasoning:a,assistantName:e.assistantName}):w)}
3949
3949
  </div>
3950
3950
  `;return u`
3951
3951
  <section
3952
3952
  class="card chat"
3953
- @drop=${A=>Kw(A,e)}
3954
- @dragover=${qw}
3955
- @dragleave=${Hw}
3953
+ @drop=${A=>Hw(A,e)}
3954
+ @dragover=${jw}
3955
+ @dragleave=${Vw}
3956
3956
  >
3957
3957
  ${e.disabledReason?u`<div class="callout">${e.disabledReason}</div>`:w}
3958
3958
 
3959
3959
  ${e.error?u`<div class="callout danger">${e.error}</div>`:w}
3960
3960
 
3961
- ${Fw(e.compactionStatus)}
3961
+ ${zw(e.compactionStatus)}
3962
3962
 
3963
3963
  ${e.focusMode?u`
3964
3964
  <button
@@ -3999,7 +3999,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
3999
3999
  @resize=${A=>{var T;return(T=e.onSplitRatioChange)==null?void 0:T.call(e,A.detail.splitRatio)}}
4000
4000
  ></resizable-divider>
4001
4001
  <div class="chat-sidebar">
4002
- ${sb({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
4002
+ ${ab({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
4003
4003
  ${e.sidebarContent}
4004
4004
  \`\`\``)}})}
4005
4005
  </div>
@@ -4021,13 +4021,13 @@ ${e.sidebarContent}
4021
4021
  `:w}
4022
4022
 
4023
4023
  <div class="chat-compose">
4024
- ${Qw(e)}
4025
- ${c?ib():u`
4024
+ ${Yw(e)}
4025
+ ${c?ob():u`
4026
4026
  <div class="chat-compose__row">
4027
4027
  <button
4028
4028
  class="chat-compose__emoji"
4029
4029
  type="button"
4030
- @click=${Vw}
4030
+ @click=${Qw}
4031
4031
  aria-label="Emoji"
4032
4032
  title="Emoji"
4033
4033
  >
@@ -4048,7 +4048,7 @@ ${e.sidebarContent}
4048
4048
  multiple
4049
4049
  accept="image/*,video/*,.pdf,.md,.txt,.csv,.json,.xml,.html,.css,.js,.ts,.py,.sh,.yaml,.yml,.toml,.ini,.cfg,.log,.sql"
4050
4050
  style="display:none"
4051
- @change=${A=>{const T=A.target,M=T.files;if(!(!M||M.length===0||!e.onAttachmentsChange)){for(let N=0;N<M.length;N++)zw(M[N],e);T.value=""}}}
4051
+ @change=${A=>{const T=A.target,M=T.files;if(!(!M||M.length===0||!e.onAttachmentsChange)){for(let N=0;N<M.length;N++)qw(M[N],e);T.value=""}}}
4052
4052
  />
4053
4053
  <label class="field chat-compose__field">
4054
4054
  <span>Message</span>
@@ -4056,8 +4056,8 @@ ${e.sidebarContent}
4056
4056
  .value=${e.draft}
4057
4057
  ?disabled=${!e.connected}
4058
4058
  @keydown=${A=>{A.key==="Enter"&&(A.isComposing||A.keyCode===229||A.shiftKey||e.connected&&(A.preventDefault(),t&&(e.onSend(),_l(A.target))))}}
4059
- @input=${A=>{const T=A.target;e.onDraftChange(T.value),Uw(T)}}
4060
- @paste=${A=>jw(A,e)}
4059
+ @input=${A=>{const T=A.target;e.onDraftChange(T.value),Fw(T)}}
4060
+ @paste=${A=>Gw(A,e)}
4061
4061
  placeholder=${l}
4062
4062
  ></textarea>
4063
4063
  </label>
@@ -4071,7 +4071,7 @@ ${e.sidebarContent}
4071
4071
  ${E.square}
4072
4072
  </button>
4073
4073
  `:w}
4074
- ${d?nb(e.connected):u`
4074
+ ${d?sb(e.connected):u`
4075
4075
  <button
4076
4076
  class="btn btn--icon chat-compose__send primary"
4077
4077
  ?disabled=${!e.connected}
@@ -4084,14 +4084,14 @@ ${e.sidebarContent}
4084
4084
  </div>`}
4085
4085
  <div class="emoji-picker-popup">
4086
4086
  <emoji-picker
4087
- @emoji-click=${A=>Gw(A,e)}
4087
+ @emoji-click=${A=>Jw(A,e)}
4088
4088
  ></emoji-picker>
4089
4089
  </div>
4090
4090
  </div>
4091
4091
  </section>
4092
- `}function Jw(e){return e.map(t=>{if(t.kind!=="message")return t;const n=mc(t.message),i=yc(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 Yw(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=mc(r);if(!s&&l.role.toLowerCase()==="toolresult"){const c=r,m=(Array.isArray(c.content)?c.content:[]).filter(v=>{const p=v.type;return p==="image"||p==="file"});m.length>0&&t.push({kind:"message",key:ko(r,a),message:{role:"assistant",content:m,timestamp:l.timestamp}});continue}t.push({kind:"message",key:ko(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:ko(i[a],a+n.length),message:i[a]});if(e.interimText&&t.push({kind:"interim",key:"interim:thinking",text:e.interimText}),e.stream!==null){const a=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:a,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:a})}for(const a of e.queue){const r=((o=a.attachments)==null?void 0:o.filter(c=>c.fileName).map(c=>c.fileName))??[],l=r.length>0?a.text?`${r.join(", ")}
4092
+ `}function Xw(e){return e.map(t=>{if(t.kind!=="message")return t;const n=vc(t.message),i=bc(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 Zw(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=vc(r);if(!s&&l.role.toLowerCase()==="toolresult"){const c=r,m=(Array.isArray(c.content)?c.content:[]).filter(v=>{const p=v.type;return p==="image"||p==="file"});m.length>0&&t.push({kind:"message",key:ko(r,a),message:{role:"assistant",content:m,timestamp:l.timestamp}});continue}t.push({kind:"message",key:ko(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:ko(i[a],a+n.length),message:i[a]});if(e.interimText&&t.push({kind:"interim",key:"interim:thinking",text:e.interimText}),e.stream!==null){const a=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:a,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:a})}for(const a of e.queue){const r=((o=a.attachments)==null?void 0:o.filter(c=>c.fileName).map(c=>c.fileName))??[],l=r.length>0?a.text?`${r.join(", ")}
4093
4093
 
4094
- ${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 Jw(t)}function ko(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 Xw(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 jd(e){return e.replace(/@s\.whatsapp\.net$/,"").replace(/@g\.us$/,"")}function Zw(e){const t=e.searchQuery.toLowerCase(),n=t?e.conversations.filter(i=>i.name.toLowerCase().includes(t)||i.jid.includes(t)):e.conversations;return u`
4094
+ ${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 Xw(t)}function ko(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 ek(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 Gd(e){return e.replace(/@s\.whatsapp\.net$/,"").replace(/@g\.us$/,"")}function tk(e){const t=e.searchQuery.toLowerCase(),n=t?e.conversations.filter(i=>i.name.toLowerCase().includes(t)||i.jid.includes(t)):e.conversations;return u`
4095
4095
  <div class="wa-list">
4096
4096
  <div class="wa-list__header">
4097
4097
  <input
@@ -4106,29 +4106,29 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4106
4106
  </button>
4107
4107
  </div>
4108
4108
  <div class="wa-list__items">
4109
- ${e.loading?u`<div class="wa-list__empty">Loading...</div>`:n.length===0?u`<div class="wa-list__empty">${e.conversations.length===0?"No conversations yet":"No matches"}</div>`:n.map(i=>ek(i,i.jid===e.selectedJid,()=>e.onSelectConversation(i.jid)))}
4109
+ ${e.loading?u`<div class="wa-list__empty">Loading...</div>`:n.length===0?u`<div class="wa-list__empty">${e.conversations.length===0?"No conversations yet":"No matches"}</div>`:n.map(i=>nk(i,i.jid===e.selectedJid,()=>e.onSelectConversation(i.jid)))}
4110
4110
  </div>
4111
4111
  </div>
4112
- `}function ek(e,t,n){const i=e.type==="group"&&e.activation?u`<span class="wa-badge wa-badge--${e.activation}">${e.activation}</span>`:w;return u`
4112
+ `}function nk(e,t,n){const i=e.type==="group"&&e.activation?u`<span class="wa-badge wa-badge--${e.activation}">${e.activation}</span>`:w;return u`
4113
4113
  <button class="wa-list__item ${t?"wa-list__item--selected":""}" @click=${n}>
4114
4114
  <span class="wa-list__icon ${e.type==="group"?"wa-list__icon--group":""}">${e.type==="group"?E.users:E.user}</span>
4115
4115
  <div class="wa-list__info">
4116
4116
  <span class="wa-list__name">${e.name}</span>
4117
- <span class="wa-list__jid">${jd(e.jid)}</span>
4117
+ <span class="wa-list__jid">${Gd(e.jid)}</span>
4118
4118
  </div>
4119
4119
  ${i}
4120
4120
  </button>
4121
- `}function tk(e){const t=e.conversations.find(n=>n.jid===e.selectedJid);return t?u`
4121
+ `}function ik(e){const t=e.conversations.find(n=>n.jid===e.selectedJid);return t?u`
4122
4122
  <div class="wa-header">
4123
4123
  <button class="wa-header__back" @click=${e.onBack} title="Back to conversations">
4124
4124
  <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>
4125
4125
  </button>
4126
4126
  <div class="wa-header__info">
4127
4127
  <span class="wa-header__name">${t.name}</span>
4128
- <span class="wa-header__jid">${jd(t.jid)}</span>
4128
+ <span class="wa-header__jid">${Gd(t.jid)}</span>
4129
4129
  </div>
4130
4130
  </div>
4131
- `:u``}function nk(e){var n;const t=e.groupInfo;return!t||!((n=e.selectedJid)!=null&&n.endsWith("@g.us"))?u``:u`
4131
+ `:u``}function sk(e){var n;const t=e.groupInfo;return!t||!((n=e.selectedJid)!=null&&n.endsWith("@g.us"))?u``:u`
4132
4132
  <div class="wa-group-settings">
4133
4133
  <div class="wa-group-settings__row">
4134
4134
  <label class="wa-group-settings__label">Activation</label>
@@ -4147,29 +4147,29 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4147
4147
  ${t.desc?u` · ${t.desc}`:w}
4148
4148
  </div>
4149
4149
  </div>
4150
- `}function ik(e){return e.length===0?u`<div class="wa-messages__empty">No messages available</div>`:u`
4150
+ `}function ok(e){return e.length===0?u`<div class="wa-messages__empty">No messages available</div>`:u`
4151
4151
  ${e.map(t=>u`
4152
4152
  <div class="wa-bubble ${t.fromMe?"wa-bubble--me":""}">
4153
4153
  ${!t.fromMe&&t.senderName?u`<div class="wa-bubble__sender">${t.senderName}</div>`:w}
4154
4154
  ${t.quoted?u`<div class="wa-bubble__quoted">${t.quoted.body}</div>`:w}
4155
4155
  <div class="wa-bubble__body">${t.body}</div>
4156
- <div class="wa-bubble__time">${Xw(t.timestamp)}</div>
4156
+ <div class="wa-bubble__time">${ek(t.timestamp)}</div>
4157
4157
  </div>
4158
4158
  `)}
4159
- `}function sk(e){return u`
4159
+ `}function ak(e){return u`
4160
4160
  <div class="wa-container ${e.selectedJid?"wa-container--detail":""}">
4161
- ${Zw(e)}
4161
+ ${tk(e)}
4162
4162
  <div class="wa-view">
4163
4163
  ${e.selectedJid?u`
4164
- ${tk(e)}
4165
- ${nk(e)}
4164
+ ${ik(e)}
4165
+ ${sk(e)}
4166
4166
  <div class="wa-messages">
4167
- ${e.messagesLoading?u`<div class="wa-messages__empty">Loading messages...</div>`:ik(e.messages)}
4167
+ ${e.messagesLoading?u`<div class="wa-messages__empty">Loading messages...</div>`:ok(e.messages)}
4168
4168
  </div>
4169
4169
  `:u`<div class="wa-view__empty">Select a conversation</div>`}
4170
4170
  </div>
4171
4171
  </div>
4172
- `}function ok(e){if(e.label)return e.label;const t=parseInt(e.key.split(":")[2]??"0",10);return!t||isNaN(t)?e.key:`Chat — ${new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`}function ak(e,t){const n=e.key===t.activeSessionKey,i=ok(e),s=e.updatedAt?un(e.updatedAt):"",o=t.confirmDeleteKey??null;return u`
4172
+ `}function rk(e){if(e.label)return e.label;const t=parseInt(e.key.split(":")[2]??"0",10);return!t||isNaN(t)?e.key:`Chat — ${new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`}function lk(e,t){const n=e.key===t.activeSessionKey,i=rk(e),s=e.updatedAt?un(e.updatedAt):"",o=t.confirmDeleteKey??null;return u`
4173
4173
  <div
4174
4174
  class="chat-sidebar__row ${n?"chat-sidebar__row--active":""}"
4175
4175
  @click=${()=>{n||t.onSelectSession(e.key)}}
@@ -4218,7 +4218,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4218
4218
  `}
4219
4219
  </div>
4220
4220
  </div>
4221
- `}function rk(e){var n;const t=((n=e.sessions)==null?void 0:n.sessions)??[];return t.length===0?w:u`
4221
+ `}function ck(e){var n;const t=((n=e.sessions)==null?void 0:n.sessions)??[];return t.length===0?w:u`
4222
4222
  <aside
4223
4223
  class="chat-sessions-sidebar ${e.open?"chat-sessions-sidebar--open":""}"
4224
4224
  aria-label="Chat sessions"
@@ -4243,11 +4243,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4243
4243
  </div>
4244
4244
  </div>
4245
4245
  <div class="chat-sidebar__list">
4246
- ${t.map(i=>ak(i,e))}
4246
+ ${t.map(i=>lk(i,e))}
4247
4247
  </div>
4248
4248
  </div>
4249
4249
  </aside>
4250
- `}const lk=u`<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 ck(e){var p;if(!e.connected)return u`
4250
+ `}const uk=u`<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 dk(e){var p;if(!e.connected)return u`
4251
4251
  <div class="setup-container">
4252
4252
  <div class="setup-card">
4253
4253
  <div class="setup-spinner"></div>
@@ -4270,7 +4270,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4270
4270
  target="_blank"
4271
4271
  rel="noopener"
4272
4272
  title="Open public chat in new tab"
4273
- >Public ${lk}</a>`:w,l=e.whatsappProps?u`
4273
+ >Public ${uk}</a>`:w,l=e.whatsappProps?u`
4274
4274
  <div class="chat-page-tabs">
4275
4275
  <button
4276
4276
  class="chat-page-tab ${t==="chat"?"active":""}"
@@ -4281,11 +4281,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4281
4281
  @click=${()=>{var b;return(b=e.onChatPageTabChange)==null?void 0:b.call(e,"whatsapp")}}
4282
4282
  >WhatsApp</button>
4283
4283
  </div>
4284
- `:w,c=i&&t==="chat"?rk({sessions:n,activeSessionKey:e.sessionKey,open:s,confirmDeleteKey:e.chatSidebarConfirmDeleteKey??null,onNewSession:e.onNewSession,onSelectSession:e.onSelectSession??(()=>{}),onRenameSession:e.onRenameSession??(()=>{}),onDeleteSession:e.onDeleteSession??(()=>{}),onArmDelete:e.onArmDelete??(()=>{}),onClose:e.onToggleSessions}):w,d=i&&s&&t==="chat"?u`<div
4284
+ `:w,c=i&&t==="chat"?ck({sessions:n,activeSessionKey:e.sessionKey,open:s,confirmDeleteKey:e.chatSidebarConfirmDeleteKey??null,onNewSession:e.onNewSession,onSelectSession:e.onSelectSession??(()=>{}),onRenameSession:e.onRenameSession??(()=>{}),onDeleteSession:e.onDeleteSession??(()=>{}),onArmDelete:e.onArmDelete??(()=>{}),onClose:e.onToggleSessions}):w,d=i&&s&&t==="chat"?u`<div
4285
4285
  class="chat-sessions-backdrop"
4286
4286
  @click=${()=>{var b;return(b=e.onToggleSessions)==null?void 0:b.call(e)}}
4287
4287
  style="position:fixed;inset:0;z-index:199;background:rgba(0,0,0,0.4);"
4288
- ></div>`:w,m=(p=e.sessionKey)!=null&&p.trim()?t==="whatsapp"&&e.whatsappProps?sk(e.whatsappProps):Hd(e):u`
4288
+ ></div>`:w,m=(p=e.sessionKey)!=null&&p.trim()?t==="whatsapp"&&e.whatsappProps?ak(e.whatsappProps):Vd(e):u`
4289
4289
  <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:16px;color:var(--tasker-muted-grey);padding:32px;text-align:center;">
4290
4290
  <p>No active session.</p>
4291
4291
  <button class="chat-public-link" style="cursor:pointer;" @click=${()=>e.onNewSession()}>
@@ -4317,13 +4317,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4317
4317
  </div>
4318
4318
  </div>
4319
4319
  </div>
4320
- `}async function Vd(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 uk(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 dk(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 pk(e){return e?`${pc(e)} (${un(e)})`:"n/a"}function xo(e){return e>=1e3?`${Math.round(e/1e3)}k`:String(e)}function hk(e){if(e.totalTokens==null)return"n/a";const t=e.totalTokens??0,n=e.contextTokens??0;return n?`${Math.round(t/n*100)}% (${xo(t)} / ${xo(n)})`:xo(t)}function Gd(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?un(t.lastRunAtMs):"never";return`${n} · last ${i}`}function Qd(e){const t=e.schedule;return t.kind==="at"?`One-time: ${pc(t.atMs)}`:t.kind==="every"?`Every ${ga(t.everyMs)}`:gk(t.expr,t.tz)}function gk(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," ")})`:"",c=(x,C)=>new Date(2e3,0,1,x,C).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=/^\d{1,2}$/.test(i)?parseInt(i,10):null,m=Ml(s);if(d===null||!m)return`${e}${t?` (${t})`:""}`;const v=m.map(x=>c(x,d)),p=v.length<=3?v.join(" & "):`${v.slice(0,-1).join(", ")} & ${v[v.length-1]}`,b=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&a==="*"){if(r==="*")return`Daily at ${p}${l}`;if(r==="1-5")return`Weekdays at ${p}${l}`;if(r==="0,6"||r==="6,0")return`Weekends at ${p}${l}`;const x=Ml(r);if(x)return`${x.map(A=>b[A%7]??String(A)).join(", ")} at ${p}${l}`}return`${e}${t?` (${t})`:""}`}function Ml(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 fk(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 Il(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 Ae=null;function mk(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 yk(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 vk(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function bk(e){return e||"Default"}const wk=u`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,kk=u`<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>`,xk=u`<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>`,Ts=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,$k=u`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,Jd=u`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,Sk=u`<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 Rl(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return u`
4321
- ${Ak(e)}
4322
- ${Ck(e)}
4323
- ${n?Tk(e):w}
4324
- ${t?Mk(t,e):w}
4325
- ${e.runModalJobId?Ik(e):w}
4326
- `}function Ak(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 u`
4320
+ `}async function Qd(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 pk(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 hk(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 gk(e){return e?`${gc(e)} (${un(e)})`:"n/a"}function xo(e){return e>=1e3?`${Math.round(e/1e3)}k`:String(e)}function fk(e){if(e.totalTokens==null)return"n/a";const t=e.totalTokens??0,n=e.contextTokens??0;return n?`${Math.round(t/n*100)}% (${xo(t)} / ${xo(n)})`:xo(t)}function Jd(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?un(t.lastRunAtMs):"never";return`${n} · last ${i}`}function Yd(e){const t=e.schedule;return t.kind==="at"?`One-time: ${gc(t.atMs)}`:t.kind==="every"?`Every ${ga(t.everyMs)}`:mk(t.expr,t.tz)}function mk(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," ")})`:"",c=(x,C)=>new Date(2e3,0,1,x,C).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=/^\d{1,2}$/.test(i)?parseInt(i,10):null,m=Ml(s);if(d===null||!m)return`${e}${t?` (${t})`:""}`;const v=m.map(x=>c(x,d)),p=v.length<=3?v.join(" & "):`${v.slice(0,-1).join(", ")} & ${v[v.length-1]}`,b=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&a==="*"){if(r==="*")return`Daily at ${p}${l}`;if(r==="1-5")return`Weekdays at ${p}${l}`;if(r==="0,6"||r==="6,0")return`Weekends at ${p}${l}`;const x=Ml(r);if(x)return`${x.map(A=>b[A%7]??String(A)).join(", ")} at ${p}${l}`}return`${e}${t?` (${t})`:""}`}function Ml(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 yk(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 Il(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 Ae=null;function vk(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 bk(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 wk(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function kk(e){return e||"Default"}const xk=u`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,$k=u`<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>`,Sk=u`<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>`,Ts=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,Ak=u`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,Xd=u`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,Ck=u`<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 Rl(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return u`
4321
+ ${Ek(e)}
4322
+ ${Tk(e)}
4323
+ ${n?_k(e):w}
4324
+ ${t?Rk(t,e):w}
4325
+ ${e.runModalJobId?Lk(e):w}
4326
+ `}function Ek(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 u`
4327
4327
  <div class="event-status-bar">
4328
4328
  <div class="event-status-bar__info">
4329
4329
  <span class="statusDot ${n?"ok":""}"></span>
@@ -4345,14 +4345,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4345
4345
  ${e.error?u`<span class="muted">${e.error}</span>`:w}
4346
4346
  </div>
4347
4347
  <button class="btn primary btn--sm" @click=${e.onNewEventModalOpen}>
4348
- ${Jd} New Event
4348
+ ${Xd} New Event
4349
4349
  </button>
4350
4350
  </div>
4351
- `}function Ck(e){return e.jobs.length===0?u`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:u`
4351
+ `}function Tk(e){return e.jobs.length===0?u`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:u`
4352
4352
  <div class="event-grid">
4353
- ${e.jobs.map(t=>Ek(t,e))}
4353
+ ${e.jobs.map(t=>Pk(t,e))}
4354
4354
  </div>
4355
- `}function Ek(e,t){return u`
4355
+ `}function Pk(e,t){return u`
4356
4356
  <div
4357
4357
  class="event-card ${e.enabled?"":"disabled"}"
4358
4358
  @click=${()=>t.onDetailOpen(e)}
@@ -4363,12 +4363,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4363
4363
  ${e.enabled?"On":"Off"}
4364
4364
  </span>
4365
4365
  </div>
4366
- <div class="event-card__schedule">${Qd(e)}</div>
4367
- ${e.agentId?u`<div class="event-card__agent">${bk(e.agentId)}</div>`:w}
4366
+ <div class="event-card__schedule">${Yd(e)}</div>
4367
+ ${e.agentId?u`<div class="event-card__agent">${kk(e.agentId)}</div>`:w}
4368
4368
  ${Il(e)?u`<div class="event-card__agent muted" style="font-size: 11px;">\u2192 ${Il(e)}</div>`:w}
4369
4369
  <div class="event-card__footer">
4370
4370
  <div class="event-card__status">
4371
- <span class="muted" style="font-size: 11px;">${Gd(e)}</span>
4371
+ <span class="muted" style="font-size: 11px;">${Jd(e)}</span>
4372
4372
  </div>
4373
4373
  <div class="event-card__actions" @click=${n=>n.stopPropagation()}>
4374
4374
  <button
@@ -4377,7 +4377,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4377
4377
  ?disabled=${t.busy}
4378
4378
  @click=${()=>t.onToggle(e,!e.enabled)}
4379
4379
  >
4380
- ${e.enabled?kk:wk}
4380
+ ${e.enabled?$k:xk}
4381
4381
  </button>
4382
4382
  <button
4383
4383
  class="btn-icon"
@@ -4385,7 +4385,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4385
4385
  ?disabled=${t.busy}
4386
4386
  @click=${()=>t.onRun(e)}
4387
4387
  >
4388
- ${$k}
4388
+ ${Ak}
4389
4389
  </button>
4390
4390
  ${t.pendingDeleteId===e.id?u`<button
4391
4391
  class="btn danger btn--sm"
@@ -4396,11 +4396,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4396
4396
  title="Delete"
4397
4397
  ?disabled=${t.busy}
4398
4398
  @click=${()=>{t.onArmDelete(e.id),Ae&&clearTimeout(Ae),Ae=setTimeout(()=>{t.onArmDelete(""),Ae=null},3e3)}}
4399
- >${xk}</button>`}
4399
+ >${Sk}</button>`}
4400
4400
  </div>
4401
4401
  </div>
4402
4402
  </div>
4403
- `}function Tk(e){const t=!!e.editJobId,n=mk(e),i=()=>{e.onNewEventModalClose()};return u`
4403
+ `}function _k(e){const t=!!e.editJobId,n=vk(e),i=()=>{e.onNewEventModalClose()};return u`
4404
4404
  <div class="event-modal-overlay" @click=${i}>
4405
4405
  <div class="event-modal" @click=${s=>s.stopPropagation()}>
4406
4406
  <div class="event-modal__header">
@@ -4458,7 +4458,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4458
4458
  </label>
4459
4459
  </div>
4460
4460
 
4461
- ${_k(e)}
4461
+ ${Ik(e)}
4462
4462
 
4463
4463
  <div class="form-grid" style="margin-top: 12px;">
4464
4464
  <label class="field">
@@ -4520,7 +4520,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4520
4520
  @change=${s=>e.onFormChange({channel:s.target.value})}
4521
4521
  >
4522
4522
  ${n.map(s=>u`<option value=${s}>
4523
- ${yk(e,s)}
4523
+ ${bk(e,s)}
4524
4524
  </option>`)}
4525
4525
  </select>
4526
4526
  </label>
@@ -4533,7 +4533,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4533
4533
  />
4534
4534
  </label>
4535
4535
  </div>
4536
- ${Pk(e)}
4536
+ ${Mk(e)}
4537
4537
  <div class="form-grid" style="margin-top: 12px;">
4538
4538
  <label class="field">
4539
4539
  <span>Timeout (seconds)</span>
@@ -4564,7 +4564,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4564
4564
  </div>
4565
4565
  </div>
4566
4566
  </div>
4567
- `}function Pk(e){const t=e.form.recipients;return u`
4567
+ `}function Mk(e){const t=e.form.recipients;return u`
4568
4568
  <div style="margin-top: 8px;">
4569
4569
  <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
4570
4570
  <span style="font-size: 13px; color: var(--muted);">Recipients</span>
@@ -4572,7 +4572,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4572
4572
  class="btn btn--sm"
4573
4573
  @click=${()=>{e.onFormChange({recipients:[...t,""]})}}
4574
4574
  >
4575
- ${Jd} Add
4575
+ ${Xd} Add
4576
4576
  </button>
4577
4577
  </div>
4578
4578
  ${t.length===0&&!e.form.toAdmins?u`<div class="muted" style="font-size: 12px; padding: 4px 0;">No recipients. Add a phone number or enable "All admins".</div>`:w}
@@ -4594,7 +4594,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4594
4594
  </div>
4595
4595
  `)}
4596
4596
  </div>
4597
- `}function _k(e){const t=e.form;return t.scheduleKind==="at"?u`
4597
+ `}function Ik(e){const t=e.form;return t.scheduleKind==="at"?u`
4598
4598
  <label class="field" style="margin-top: 12px;">
4599
4599
  <span>Run at</span>
4600
4600
  <input
@@ -4643,7 +4643,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4643
4643
  />
4644
4644
  </label>
4645
4645
  </div>
4646
- `}function Mk(e,t){var n;return u`
4646
+ `}function Rk(e,t){var n;return u`
4647
4647
  <div class="event-modal-overlay" @click=${t.onDetailClose}>
4648
4648
  <div class="event-modal" @click=${i=>i.stopPropagation()}>
4649
4649
  <div class="event-modal__header">
@@ -4661,7 +4661,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4661
4661
  ?disabled=${t.busy}
4662
4662
  @click=${()=>t.onEdit(e)}
4663
4663
  >
4664
- ${Sk} Edit
4664
+ ${Ck} Edit
4665
4665
  </button>
4666
4666
  <button
4667
4667
  class="btn"
@@ -4697,7 +4697,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4697
4697
  </div>
4698
4698
  <div class="event-detail-row">
4699
4699
  <span class="event-detail-label">Schedule</span>
4700
- <span class="event-detail-value">${Qd(e)}</span>
4700
+ <span class="event-detail-value">${Yd(e)}</span>
4701
4701
  </div>
4702
4702
  ${e.agentId?u`
4703
4703
  <div class="event-detail-row">
@@ -4719,12 +4719,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4719
4719
  </div>
4720
4720
  <div class="event-detail-row" style="flex-direction: column; align-items: stretch; gap: 4px;">
4721
4721
  <span class="event-detail-label">Action</span>
4722
- <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${fk(e,!1)}</span>
4722
+ <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${yk(e,!1)}</span>
4723
4723
  </div>
4724
4724
  ${e.payload.kind==="agentTurn"&&e.payload.to?u`
4725
4725
  <div class="event-detail-row">
4726
4726
  <span class="event-detail-label">Send to</span>
4727
- <span class="event-detail-value mono">${vk(e.payload.to)}</span>
4727
+ <span class="event-detail-value mono">${wk(e.payload.to)}</span>
4728
4728
  </div>
4729
4729
  `:w}
4730
4730
  ${e.payload.kind==="agentTurn"&&(e.payload.channel??e.payload.provider)?u`
@@ -4744,12 +4744,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4744
4744
  <div class="event-detail-section">
4745
4745
  <div class="event-detail-row">
4746
4746
  <span class="event-detail-label">Last run</span>
4747
- <span class="event-detail-value">${Gd(e)}</span>
4747
+ <span class="event-detail-value">${Jd(e)}</span>
4748
4748
  </div>
4749
4749
  ${(n=e.state)!=null&&n.nextRunAtMs?u`
4750
4750
  <div class="event-detail-row">
4751
4751
  <span class="event-detail-label">Next run</span>
4752
- <span class="event-detail-value">${pk(e.state.nextRunAtMs)}</span>
4752
+ <span class="event-detail-value">${gk(e.state.nextRunAtMs)}</span>
4753
4753
  </div>
4754
4754
  `:w}
4755
4755
  </div>
@@ -4760,14 +4760,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4760
4760
  </div>
4761
4761
  ${t.runs.length===0?u`<div class="muted" style="font-size: 13px;">No runs recorded yet.</div>`:u`
4762
4762
  <div class="list">
4763
- ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>Lk(i))}
4763
+ ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>Dk(i))}
4764
4764
  </div>
4765
4765
  `}
4766
4766
  </div>
4767
4767
 
4768
4768
  </div>
4769
4769
  </div>
4770
- `}function Ik(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 u`
4770
+ `}function Lk(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 u`
4771
4771
  <div class="event-modal-overlay" @click=${e.onRunModalClose}>
4772
4772
  <div class="event-modal" style="max-width: 480px;" @click=${s=>s.stopPropagation()}>
4773
4773
  <div class="event-modal__header">
@@ -4812,10 +4812,10 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4812
4812
  `}
4813
4813
  </div>
4814
4814
  </div>
4815
- `}function Rk(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 Lk(e){return u`
4815
+ `}function Bk(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 Dk(e){return u`
4816
4816
  <div class="list-item" style="grid-template-columns: 1fr; gap: 6px;">
4817
4817
  <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
4818
- <span class=${Rk(e.status)} style="font-size: 11px; padding: 2px 8px;">
4818
+ <span class=${Bk(e.status)} style="font-size: 11px; padding: 2px 8px;">
4819
4819
  ${e.status}
4820
4820
  </span>
4821
4821
  <span class="muted" style="font-size: 12px;">${un(e.ts)}</span>
@@ -4829,7 +4829,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4829
4829
  </details>
4830
4830
  `:w}
4831
4831
  </div>
4832
- `}function Yd(e,t=16){return u`<i data-lucide="${e}" style="width:${t}px;height:${t}px;display:inline-block;vertical-align:middle"></i>`}function Bk(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(c=>{var d;return i==="preloaded"&&!c.preloaded||i==="user"&&(c.preloaded||c.marketplace)||i==="licensed"&&!c.marketplace||s!=="all"&&!((d=c.agents)!=null&&d.includes(s))?!1:n?[c.name,c.description].join(" ").toLowerCase().includes(n):!0}),a=(c,d)=>u`
4832
+ `}function Zd(e,t=16){return u`<i data-lucide="${e}" style="width:${t}px;height:${t}px;display:inline-block;vertical-align:middle"></i>`}function Nk(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(c=>{var d;return i==="preloaded"&&!c.preloaded||i==="user"&&(c.preloaded||c.marketplace)||i==="licensed"&&!c.marketplace||s!=="all"&&!((d=c.agents)!=null&&d.includes(s))?!1:n?[c.name,c.description].join(" ").toLowerCase().includes(n):!0}),a=(c,d)=>u`
4833
4833
  <button
4834
4834
  class="chip ${i===d?"chip-ok":""}"
4835
4835
  style="cursor: pointer; border: none; background: ${i===d?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${i===d?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
@@ -4884,20 +4884,20 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4884
4884
 
4885
4885
  ${o.length===0?u`<div class="muted" style="margin-top: 16px;">No skills found.</div>`:u`
4886
4886
  <div class="list" style="margin-top: 16px;">
4887
- ${o.map(c=>Dk(c,e))}
4887
+ ${o.map(c=>Uk(c,e))}
4888
4888
  </div>
4889
4889
  `}
4890
4890
  </section>
4891
4891
 
4892
- ${e.detail?Ok(e):w}
4893
- ${e.addModal?Fk(e):w}
4894
- `}function Dk(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"),u`
4892
+ ${e.detail?Wk(e):w}
4893
+ ${e.addModal?zk(e):w}
4894
+ `}function Uk(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"),u`
4895
4895
  <div class="list-item" style="cursor: pointer;" @click=${()=>t.onViewDetail(e.skillKey)}>
4896
4896
  <div class="list-main">
4897
4897
  <div class="list-title">
4898
- ${e.icon?Yd(e.icon,16):u`<span>&#x1F9E9;</span>`} ${e.name}
4898
+ ${e.icon?Zd(e.icon,16):u`<span>&#x1F9E9;</span>`} ${e.name}
4899
4899
  </div>
4900
- <div class="list-sub">${vh(e.description,140)}</div>
4900
+ <div class="list-sub">${wh(e.description,140)}</div>
4901
4901
  <div class="chip-row" style="margin-top: 6px;">
4902
4902
  <span class="chip ${e.preloaded?"chip-ok":""}">
4903
4903
  ${e.marketplace?"Licensed":e.preloaded?"Preloaded":"User"}
@@ -4910,7 +4910,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4910
4910
  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."}
4911
4911
  @click=${l=>{l.stopPropagation(),t.onAlwaysActiveToggle(e.skillKey,!e.alwaysActive)}}
4912
4912
  >${e.alwaysActive?"Always active":"On demand"}</span>`}
4913
- ${Nk(e,t)}
4913
+ ${Ok(e,t)}
4914
4914
  </div>
4915
4915
  ${a.length>0?u`
4916
4916
  <div class="muted" style="margin-top: 6px;">
@@ -4980,7 +4980,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4980
4980
  `:w}
4981
4981
  </div>
4982
4982
  </div>
4983
- `}function Nk(e,t){if(e.agentsLocked)return w;const n=e.agents??["admin","public"],i=n.includes("subagent")?"subagent":n.includes("admin")&&n.includes("public")?"both":n.includes("admin")?"admin":"public",s=a=>t.onAgentsChange(e.skillKey,a),o=(a,r,l)=>u`
4983
+ `}function Ok(e,t){if(e.agentsLocked)return w;const n=e.agents??["admin","public"],i=n.includes("subagent")?"subagent":n.includes("admin")&&n.includes("public")?"both":n.includes("admin")?"admin":"public",s=a=>t.onAgentsChange(e.skillKey,a),o=(a,r,l)=>u`
4984
4984
  <button
4985
4985
  style="cursor: pointer; border: none; background: ${i===r?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${i===r?"#fff":"var(--text)"}; padding: 3px 8px; border-radius: 4px; font-size: 11px;"
4986
4986
  @click=${c=>{c.stopPropagation(),s(l)}}
@@ -4996,8 +4996,8 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4996
4996
  ${o("Public","public",["public"])}
4997
4997
  ${o("Sub-agent","subagent",["subagent"])}
4998
4998
  </span>
4999
- ${i==="subagent"?Uk(e,t):w}
5000
- `}function Uk(e,t){const n=t.selectableTools??[],i=new Set(e.tools??[]),s=o=>{var r;const a=i.has(o)?[...i].filter(l=>l!==o):[...i,o];(r=t.onToolsChange)==null||r.call(t,e.skillKey,a)};return u`
4999
+ ${i==="subagent"?Fk(e,t):w}
5000
+ `}function Fk(e,t){const n=t.selectableTools??[],i=new Set(e.tools??[]),s=o=>{var r;const a=i.has(o)?[...i].filter(l=>l!==o):[...i,o];(r=t.onToolsChange)==null||r.call(t,e.skillKey,a)};return u`
5001
5001
  <div
5002
5002
  class="tools-selector"
5003
5003
  style="margin-top: 8px; padding: 8px 10px; background: var(--bg-hover, rgba(255,255,255,0.04)); border-radius: 6px; font-size: 12px;"
@@ -5017,7 +5017,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5017
5017
  `)}
5018
5018
  ${i.size===0?u`<p class="tools-note" style="margin: 6px 0 0; color: var(--text-muted, #888); font-style: italic;">No tools declared — sub-agent will use the default worker profile.</p>`:w}
5019
5019
  </div>
5020
- `}function Xd(e,t){const n=["Zap","Globe","BookOpen","Calendar","Camera","Clock","Cloud","Code","Database","FileText","Headphones","Heart","Home","Image","Mail","Map","MessageSquare","Music","Phone","Puzzle","Search","Settings","ShoppingCart","Star","Tag","Truck","User","Wallet","Wrench","Cpu"],i=e.icon??"Puzzle";return u`
5020
+ `}function ep(e,t){const n=["Zap","Globe","BookOpen","Calendar","Camera","Clock","Cloud","Code","Database","FileText","Headphones","Heart","Home","Image","Mail","Map","MessageSquare","Music","Phone","Puzzle","Search","Settings","ShoppingCart","Star","Tag","Truck","User","Wallet","Wrench","Cpu"],i=e.icon??"Puzzle";return u`
5021
5021
  <div class="icon-picker" style="margin-top: 12px; margin-bottom: 16px;" @click=${s=>s.stopPropagation()}>
5022
5022
  <label style="font-weight: 600; margin-bottom: 6px; display: block; color: var(--text-muted, #888); font-size: 12px;">Icon</label>
5023
5023
  <div class="icon-grid" style="display: flex; flex-wrap: wrap; gap: 4px;">
@@ -5028,12 +5028,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5028
5028
  style="cursor: pointer; border: ${s===i?"2px solid var(--accent, #3b82f6)":"1px solid var(--border, rgba(255,255,255,0.1))"}; background: ${s===i?"var(--accent-subtle, rgba(59,130,246,0.15))":"var(--bg-hover, rgba(255,255,255,0.06))"}; border-radius: 6px; padding: 6px; display: flex; align-items: center; justify-content: center; width: 36px; height: 36px;"
5029
5029
  @click=${()=>{var o;return(o=t.onIconChange)==null?void 0:o.call(t,e.skillKey,s)}}
5030
5030
  >
5031
- ${Yd(s,20)}
5031
+ ${Zd(s,20)}
5032
5032
  </button>
5033
5033
  `)}
5034
5034
  </div>
5035
5035
  </div>
5036
- `}function Ok(e){var l,c,d;const t=e.detail,n=["SKILL.md",...t.references.map(m=>m.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((l=t.references.find(m=>m.name===i))==null?void 0:l.content)??"",o=m=>{m.target.classList.contains("event-modal-overlay")&&e.onDetailClose()},a=(d=(c=e.report)==null?void 0:c.skills)==null?void 0:d.find(m=>m.name===t.name),r=a?!a.preloaded:!1;return u`
5036
+ `}function Wk(e){var l,c,d;const t=e.detail,n=["SKILL.md",...t.references.map(m=>m.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((l=t.references.find(m=>m.name===i))==null?void 0:l.content)??"",o=m=>{m.target.classList.contains("event-modal-overlay")&&e.onDetailClose()},a=(d=(c=e.report)==null?void 0:c.skills)==null?void 0:d.find(m=>m.name===t.name),r=a?!a.preloaded:!1;return u`
5037
5037
  <div class="event-modal-overlay" @click=${o}>
5038
5038
  <div class="event-modal" style="width: min(720px, 100%);" @click=${m=>m.stopPropagation()}>
5039
5039
  <div class="event-modal__header">
@@ -5043,7 +5043,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5043
5043
  <button class="event-modal__close" @click=${e.onDetailClose}>&times;</button>
5044
5044
  </div>
5045
5045
  </div>
5046
- ${r&&a?Xd(a,e):w}
5046
+ ${r&&a?ep(a,e):w}
5047
5047
  ${n.length>1?u`
5048
5048
  <div class="chip-row" style="margin-bottom: 12px; flex-wrap: wrap;">
5049
5049
  ${n.map(m=>u`
@@ -5060,7 +5060,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5060
5060
  <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>
5061
5061
  </div>
5062
5062
  </div>
5063
- `}function Fk(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 u`
5063
+ `}function zk(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 u`
5064
5064
  <div class="event-modal-overlay" @click=${o}>
5065
5065
  <div class="event-modal" style="width: min(620px, 100%);" @click=${r=>r.stopPropagation()}>
5066
5066
  <div class="event-modal__header">
@@ -5068,14 +5068,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5068
5068
  <button class="event-modal__close" @click=${e.onAddClose}>&times;</button>
5069
5069
  </div>
5070
5070
 
5071
- ${i?Wk(e,n):t?zk(e,n):u`
5071
+ ${i?Kk(e,n):t?qk(e,n):u`
5072
5072
  <div class="muted" style="text-align: center; padding: 32px 16px;">
5073
5073
  No drafts available. Ask your assistant to create a skill and it will appear here.
5074
5074
  </div>
5075
5075
  `}
5076
5076
  </div>
5077
5077
  </div>
5078
- `}function Wk(e,t){const n=e.addForm,i=e.formSource==="installed",s=i?"Save Skill":"Save Draft",o=n.references.length>0,a=e.editTab||"SKILL.md",r=n.references.find(d=>d.name===a),l=i&&e.report?e.report.skills.find(d=>d.name===n.name):void 0,c=d=>u`
5078
+ `}function Kk(e,t){const n=e.addForm,i=e.formSource==="installed",s=i?"Save Skill":"Save Draft",o=n.references.length>0,a=e.editTab||"SKILL.md",r=n.references.find(d=>d.name===a),l=i&&e.report?e.report.skills.find(d=>d.name===n.name):void 0,c=d=>u`
5079
5079
  <button
5080
5080
  class="chip ${d===a?"chip-ok":""}"
5081
5081
  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;"
@@ -5090,7 +5090,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5090
5090
  placeholder="my-skill"
5091
5091
  />
5092
5092
  </label>
5093
- ${i&&l?Xd(l,e):w}
5093
+ ${i&&l?ep(l,e):w}
5094
5094
  ${o?u`
5095
5095
  <div class="chip-row" style="margin-bottom: 12px; flex-wrap: wrap; gap: 4px;">
5096
5096
  ${c("SKILL.md")}
@@ -5127,7 +5127,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5127
5127
  ${t?"Saving…":s}
5128
5128
  </button>
5129
5129
  </div>
5130
- `}function zk(e,t){return u`
5130
+ `}function qk(e,t){return u`
5131
5131
  <div class="card-sub" style="margin-bottom: 16px;">
5132
5132
  Skills prepared by your assistant. Review, install, or delete.
5133
5133
  </div>
@@ -5168,7 +5168,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5168
5168
  </div>
5169
5169
  `})}
5170
5170
  </div>
5171
- `}const Kk=["user","assistant","tool_call","tool_result","thinking","error"],Ll={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function Zd(e,t){return e==="tool"?"tool_call":e==="tool_result"&&typeof t=="string"&&t.startsWith("[error]")?"error":e}function qk(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 Hk(e){return e.split(":").slice(2).join(":")||e}function jk(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Vk(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const Bl=300;function Gk(e,t){const n=Zd(e.type,e.content);return t[n]??!0}function Qk(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!Gk(i,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:jk(i,t));return u`
5171
+ `}const Hk=["user","assistant","tool_call","tool_result","thinking","error"],Ll={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function tp(e,t){return e==="tool"?"tool_call":e==="tool_result"&&typeof t=="string"&&t.startsWith("[error]")?"error":e}function jk(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 Vk(e){return e.split(":").slice(2).join(":")||e}function Gk(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Qk(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const Bl=300;function Jk(e,t){const n=tp(e.type,e.content);return t[n]??!0}function Yk(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!Jk(i,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:Gk(i,t));return u`
5172
5172
  <div>
5173
5173
  <button class="chips-toggle" style="margin-top: 10px;" @click=${e.onToggleChips}>
5174
5174
  <span class="chips-toggle-icon ${e.chipsExpanded?"expanded":""}">${E.chevronDown}</span>
@@ -5176,7 +5176,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5176
5176
  </button>
5177
5177
  ${e.chipsExpanded?u`
5178
5178
  <div class="chip-row" style="margin-top: 6px;">
5179
- ${Kk.map(i=>u`
5179
+ ${Hk.map(i=>u`
5180
5180
  <label class="chip session-log-chip ${i}">
5181
5181
  <input
5182
5182
  type="checkbox"
@@ -5210,13 +5210,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5210
5210
  ${e.error?u`<div class="callout danger" style="margin-top: 10px;">${e.error}</div>`:w}
5211
5211
 
5212
5212
  <div class="log-stream" style="margin-top: 10px;" @scroll=${e.onScroll}>
5213
- ${n.length===0?u`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{var d,m;const o=Zd(i.type,i.content),a=Vk(i,s),r=e.expandedIds.has(a),l=i.content.length>Bl,c=r||!l?i.content:i.content.slice(0,Bl)+"…";return u`
5213
+ ${n.length===0?u`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{var d,m;const o=tp(i.type,i.content),a=Qk(i,s),r=e.expandedIds.has(a),l=i.content.length>Bl,c=r||!l?i.content:i.content.slice(0,Bl)+"…";return u`
5214
5214
  <div class="log-row session-entry ${o}">
5215
5215
  <div class="log-row-header">
5216
- <span class="log-time mono">${qk(i.timestamp)}</span>
5216
+ <span class="log-time mono">${jk(i.timestamp)}</span>
5217
5217
  <span class="session-log-type ${o}">${o==="thinking"&&typeof((d=i.meta)==null?void 0:d.thinkingLevel)=="string"?`Thinking (${i.meta.thinkingLevel})`:Ll[o]}</span>
5218
5218
  <span class="log-subsystem mono">${i.agentId}</span>
5219
- <span class="session-label mono">${Hk(i.sessionKey)}</span>
5219
+ <span class="session-label mono">${Vk(i.sessionKey)}</span>
5220
5220
  ${i.toolName?u`<span class="session-tool mono">${i.toolName}</span>`:w}
5221
5221
  ${i.toolCallId?u`<span class="session-call-id mono">${i.toolCallId.slice(0,12)}</span>`:w}
5222
5222
  ${i.model?u`<span class="session-model mono">${i.model}</span>`:w}
@@ -5231,7 +5231,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5231
5231
  `})}
5232
5232
  </div>
5233
5233
  </div>
5234
- `}const ia=["trace","debug","info","warn","error","fatal"];function Jk(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function ep(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Yk(e){const t=!e.isAdmin||e.logsSubTab==="session";return u`
5234
+ `}const ia=["trace","debug","info","warn","error","fatal"];function Xk(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function np(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Zk(e){const t=!e.isAdmin||e.logsSubTab==="session";return u`
5235
5235
  <section class="card">
5236
5236
  <div class="logs-toolbar">
5237
5237
  <div class="sp-tabs" style="margin: 0;">
@@ -5282,7 +5282,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5282
5282
  <button
5283
5283
  class="btn btn-sm"
5284
5284
  ?disabled=${e.entries.length===0}
5285
- @click=${()=>{const n=e.filterText.trim().toLowerCase(),i=ia.some(a=>!e.levelFilters[a]),s=e.entries.filter(a=>a.level&&!e.levelFilters[a.level]?!1:ep(a,n)),o=n||i?"filtered":"visible";e.onExport(s.map(a=>a.raw),o)}}
5285
+ @click=${()=>{const n=e.filterText.trim().toLowerCase(),i=ia.some(a=>!e.levelFilters[a]),s=e.entries.filter(a=>a.level&&!e.levelFilters[a.level]?!1:np(a,n)),o=n||i?"filtered":"visible";e.onExport(s.map(a=>a.raw),o)}}
5286
5286
  >
5287
5287
  Export
5288
5288
  </button>
@@ -5296,9 +5296,9 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5296
5296
  </div>
5297
5297
  </div>
5298
5298
 
5299
- ${t?Qk(e.sessionLogsProps):Xk(e)}
5299
+ ${t?Yk(e.sessionLogsProps):ex(e)}
5300
5300
  </section>
5301
- `}function Xk(e){const t=e.filterText.trim().toLowerCase();ia.some(l=>!e.levelFilters[l]);const n=e.entries.filter(l=>l.level&&!e.levelFilters[l.level]?!1:ep(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 u`
5301
+ `}function ex(e){const t=e.filterText.trim().toLowerCase();ia.some(l=>!e.levelFilters[l]);const n=e.entries.filter(l=>l.level&&!e.levelFilters[l.level]?!1:np(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 u`
5302
5302
  ${i.length>1?u`
5303
5303
  <div class="logs-date-nav">
5304
5304
  <button class="btn btn-sm" ?disabled=${!r}
@@ -5351,7 +5351,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5351
5351
  ${n.length===0?u`<div class="muted" style="padding: 12px;">No log entries.</div>`:[...n].reverse().map(l=>u`
5352
5352
  <div class="log-row">
5353
5353
  <div class="log-row-header">
5354
- <span class="log-time mono">${Jk(l.time)}</span>
5354
+ <span class="log-time mono">${Xk(l.time)}</span>
5355
5355
  <span class="log-level ${l.level??""}">${l.level??""}</span>
5356
5356
  <span class="log-subsystem mono">${l.subsystem??""}</span>
5357
5357
  </div>
@@ -5359,77 +5359,72 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5359
5359
  </div>
5360
5360
  `)}
5361
5361
  </div>
5362
- `}const Zk=[{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"}],ex=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,tx=u`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`;function nx(e){return u`
5363
- ${ix(e)}
5364
- ${sx(e)}
5362
+ `}const tx=[{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"}],nx=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,ix=u`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,Dl="padding:5px 14px; border:none; border-radius:4px; cursor:pointer; font-size:13px; font-weight:600; background:rgba(255,255,255,0.14); color:inherit;",Nl="padding:5px 14px; border:none; border-radius:4px; cursor:pointer; font-size:13px; font-weight:400; background:transparent; color:rgba(128,128,128,0.8);";function sx(e){return u`
5365
5363
  ${ox(e)}
5366
- ${rx(e)}
5367
- ${lx(e)}
5368
- `}function ix(e){return u`
5364
+ <div style="${e.form.enabled?"":"opacity: 0.35; pointer-events: none;"}">
5365
+ ${ax(e)}
5366
+ </div>
5367
+ ${dx(e)}
5368
+ `}function ox(e){return u`
5369
5369
  <label class="field checkbox" style="margin: 16px 0;">
5370
5370
  <input
5371
5371
  type="checkbox"
5372
5372
  .checked=${e.form.enabled}
5373
5373
  @change=${t=>e.onFormChange({enabled:t.target.checked})}
5374
5374
  />
5375
- <span style="margin-left: 8px;">
5376
- Enable opening hours
5377
- <span class="muted" style="font-size: 12px; display: block; margin-top: 2px;">
5378
- When enabled, the public assistant does not respond outside the scheduled hours below.
5379
- </span>
5380
- </span>
5375
+ <span style="margin-left: 8px;">Enable opening hours</span>
5381
5376
  </label>
5382
- `}function sx(e){const t=e.form.enabled;return u`
5383
- <label
5384
- class="field checkbox"
5385
- style="margin: 0 0 16px; ${t?"":"opacity: 0.4; pointer-events: none;"}"
5386
- >
5387
- <input
5388
- type="checkbox"
5389
- .checked=${e.form.publicAgentEnabled}
5390
- ?disabled=${!t}
5391
- @change=${n=>e.onFormChange({publicAgentEnabled:n.target.checked})}
5392
- />
5393
- <span style="margin-left: 8px;">
5394
- Public agent responds during opening hours
5395
- <span class="muted" style="font-size: 12px; display: block; margin-top: 2px;">
5396
- ${t?"When disabled, the assistant is silenced during opening hours — useful as a temporary override without changing the schedule.":"Enable opening hours first."}
5397
- </span>
5398
- </span>
5399
- </label>
5400
- `}function ox(e){return u`
5377
+ `}function ax(e){return u`
5378
+ ${rx(e)}
5379
+ ${lx(e)}
5380
+ ${ux(e)}
5381
+ `}function rx(e){const t=e.form.invertedMode;return u`
5382
+ <div style="display:flex; align-items:center; gap:8px; margin-bottom:20px;">
5383
+ <span style="font-size:13px; opacity:0.6; white-space:nowrap;">Agent responds</span>
5384
+ <div style="display:flex; gap:4px; background:rgba(255,255,255,0.06); border-radius:6px; padding:3px;">
5385
+ <button
5386
+ style="${t?Nl:Dl}"
5387
+ @click=${()=>e.onFormChange({invertedMode:!1})}
5388
+ >During hours</button>
5389
+ <button
5390
+ style="${t?Dl:Nl}"
5391
+ @click=${()=>e.onFormChange({invertedMode:!0})}
5392
+ >Outside hours</button>
5393
+ </div>
5394
+ </div>
5395
+ `}function lx(e){const t=e.form.invertedMode?"Silent hours":"Active hours";return u`
5401
5396
  <div style="margin-bottom: 20px;">
5402
- <div style="font-size: 14px; font-weight: 500; margin-bottom: 12px;">Weekly Schedule</div>
5397
+ <div style="font-size: 14px; font-weight: 500; margin-bottom: 12px;">${t}</div>
5403
5398
  <div class="oh-schedule">
5404
- ${Zk.map(t=>ax(t,e))}
5399
+ ${tx.map(n=>cx(n,e))}
5405
5400
  </div>
5406
5401
  </div>
5407
- `}function ax(e,t){const n=t.form.days[e.key];if(!n)return w;const i=n.closed;return u`
5402
+ `}function cx(e,t){const n=t.form.days[e.key];if(!n)return w;const i=n.closed,s=t.form.invertedMode?"All day":"Closed";return u`
5408
5403
  <div class="oh-day-row">
5409
5404
  <div class="oh-day-label">${e.label}</div>
5410
5405
  <div class="oh-day-times" style="${i?"opacity: 0.35; pointer-events: none;":""}">
5411
5406
  <input
5412
5407
  type="time"
5413
5408
  .value=${n.start}
5414
- @input=${s=>t.onDayChange(e.key,"start",s.target.value)}
5409
+ @input=${o=>t.onDayChange(e.key,"start",o.target.value)}
5415
5410
  />
5416
5411
  <span class="oh-time-sep">&ndash;</span>
5417
5412
  <input
5418
5413
  type="time"
5419
5414
  .value=${n.end}
5420
- @input=${s=>t.onDayChange(e.key,"end",s.target.value)}
5415
+ @input=${o=>t.onDayChange(e.key,"end",o.target.value)}
5421
5416
  />
5422
5417
  </div>
5423
5418
  <label class="oh-closed-toggle">
5424
5419
  <input
5425
5420
  type="checkbox"
5426
5421
  .checked=${i}
5427
- @change=${s=>t.onDayChange(e.key,"closed",s.target.checked)}
5422
+ @change=${o=>t.onDayChange(e.key,"closed",o.target.checked)}
5428
5423
  />
5429
- <span>Closed</span>
5424
+ <span>${s}</span>
5430
5425
  </label>
5431
5426
  </div>
5432
- `}let _i="";function rx(e){const t=e.form.closedDates;return u`
5427
+ `}let _i="";function ux(e){const t=e.form.closedDates;return u`
5433
5428
  <div style="margin-bottom: 20px;">
5434
5429
  <div style="font-size: 14px; font-weight: 500; margin-bottom: 10px;">Closed Dates</div>
5435
5430
  <div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">
@@ -5441,7 +5436,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5441
5436
  style="width: 16px; height: 16px; padding: 0;"
5442
5437
  @click=${()=>e.onRemoveClosedDate(n)}
5443
5438
  >
5444
- ${ex}
5439
+ ${nx}
5445
5440
  </button>
5446
5441
  </span>
5447
5442
  `)}
@@ -5457,28 +5452,28 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5457
5452
  class="btn btn--sm"
5458
5453
  @click=${()=>{if(_i){e.onAddClosedDate(_i);const n=document.getElementById("oh-new-closed-date");n&&(n.value=""),_i=""}}}
5459
5454
  >
5460
- ${tx} Add
5455
+ ${ix} Add
5461
5456
  </button>
5462
5457
  </div>
5463
5458
  </div>
5464
- `}function lx(e){return u`
5465
- <div style="display: flex; justify-content: flex-end; padding-top: 8px;">
5459
+ `}function dx(e){const t=e.busy?"Saving…":e.saved?"Saved":"Save";return u`
5460
+ <div style="padding-top: 8px;">
5466
5461
  <button
5467
5462
  class="btn primary"
5468
5463
  ?disabled=${e.busy}
5469
5464
  @click=${e.onSave}
5470
5465
  >
5471
- ${e.busy?"Saving…":"Save"}
5466
+ ${t}
5472
5467
  </button>
5473
5468
  </div>
5474
- `}function Ja(e){var n;if(e.channel)return e.channel;if((n=e.origin)!=null&&n.provider)return e.origin.provider;if(e.lastChannel)return e.lastChannel;const t=e.key;return t.startsWith("webchat:")?"webchat":t.startsWith("whatsapp:")?"whatsapp":t.startsWith("telegram:")?"telegram":t.startsWith("discord:")?"discord":t.startsWith("imessage:")?"imessage":t.includes(":cron:")?"system":"unknown"}function tp(e){switch(e){case"whatsapp":return"WhatsApp";case"telegram":return"Telegram";case"webchat":return"Web Chat";case"discord":return"Discord";case"googlechat":return"Google Chat";case"slack":return"Slack";case"signal":return"Signal";case"imessage":return"iMessage";case"system":return"System";default:return e}}function cx(e){switch(e){case"whatsapp":return E.smartphone;case"telegram":return E.send;case"webchat":return E.globe;case"system":return E.monitor;default:return E.messageSquare}}const ux=[{id:"all",label:"All types"},{id:"direct",label:"Direct"},{id:"group",label:"Group"}];function dx(e){const t=new Set;for(const i of e){const s=Ja(i);s!=="unknown"&&t.add(s)}const n=[...t].sort();return[{id:"all",label:"All channels"},...n.map(i=>({id:i,label:tp(i)}))]}function Ya(e){const t=ha(e);return(t==null?void 0:t.agentId)??null}function px(e){const t=new Set;for(const i of e){const s=Ya(i.key);s&&t.add(s)}const n=[...t].sort();return[{id:"all",label:"All agents"},...n.map(i=>({id:i,label:i}))]}function Dl(e,t,n,i,s){return u`
5469
+ `}function Ja(e){var n;if(e.channel)return e.channel;if((n=e.origin)!=null&&n.provider)return e.origin.provider;if(e.lastChannel)return e.lastChannel;const t=e.key;return t.startsWith("webchat:")?"webchat":t.startsWith("whatsapp:")?"whatsapp":t.startsWith("telegram:")?"telegram":t.startsWith("discord:")?"discord":t.startsWith("imessage:")?"imessage":t.includes(":cron:")?"system":"unknown"}function ip(e){switch(e){case"whatsapp":return"WhatsApp";case"telegram":return"Telegram";case"webchat":return"Web Chat";case"discord":return"Discord";case"googlechat":return"Google Chat";case"slack":return"Slack";case"signal":return"Signal";case"imessage":return"iMessage";case"system":return"System";default:return e}}function px(e){switch(e){case"whatsapp":return E.smartphone;case"telegram":return E.send;case"webchat":return E.globe;case"system":return E.monitor;default:return E.messageSquare}}const hx=[{id:"all",label:"All types"},{id:"direct",label:"Direct"},{id:"group",label:"Group"}];function gx(e){const t=new Set;for(const i of e){const s=Ja(i);s!=="unknown"&&t.add(s)}const n=[...t].sort();return[{id:"all",label:"All channels"},...n.map(i=>({id:i,label:ip(i)}))]}function Ya(e){const t=ha(e);return(t==null?void 0:t.agentId)??null}function fx(e){const t=new Set;for(const i of e){const s=Ya(i.key);s&&t.add(s)}const n=[...t].sort();return[{id:"all",label:"All agents"},...n.map(i=>({id:i,label:i}))]}function Ul(e,t,n,i,s){return u`
5475
5470
  <div class="sp-sessions-toolbar">
5476
5471
  <select
5477
5472
  class="sp-filter-select"
5478
5473
  .value=${e.kindFilter}
5479
5474
  @change=${o=>e.onKindFilterChange(o.target.value)}
5480
5475
  >
5481
- ${ux.map(o=>u`<option value=${o.id} ?selected=${e.kindFilter===o.id}>${o.label}</option>`)}
5476
+ ${hx.map(o=>u`<option value=${o.id} ?selected=${e.kindFilter===o.id}>${o.label}</option>`)}
5482
5477
  </select>
5483
5478
  ${t.length>2?u`
5484
5479
  <select
@@ -5508,7 +5503,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5508
5503
  ${E.refreshCw}
5509
5504
  </button>
5510
5505
  </div>
5511
- `}const Nl=[{id:"",label:"Default"},{id:"claude-opus-4-6",label:"Opus"},{id:"claude-sonnet-4-5-20250929",label:"Sonnet"},{id:"claude-haiku-4-5-20251001",label:"Haiku"}],hx=[{id:"",label:"Default"},{id:"off",label:"Off"},{id:"minimal",label:"Minimal"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}];function gx(e,t){const n=e.model??"",i=e.thinkingLevel??"",s=n||i;return u`
5506
+ `}const Ol=[{id:"",label:"Default"},{id:"claude-opus-4-6",label:"Opus"},{id:"claude-sonnet-4-5-20250929",label:"Sonnet"},{id:"claude-haiku-4-5-20251001",label:"Haiku"}],mx=[{id:"",label:"Default"},{id:"off",label:"Off"},{id:"minimal",label:"Minimal"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}];function yx(e,t){const n=e.model??"",i=e.thinkingLevel??"",s=n||i;return u`
5512
5507
  <div class="sp-session-settings">
5513
5508
  <div class="sp-session-settings__field">
5514
5509
  <label>Model</label>
@@ -5516,8 +5511,8 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5516
5511
  class="sp-filter-select"
5517
5512
  @change=${o=>{const a=o.target.value;t.onPatch(e.key,{model:a||null})}}
5518
5513
  >
5519
- ${Nl.map(o=>{const a=o.id===n||!o.id&&!n;return u`<option value=${o.id} ?selected=${a}>${o.label}</option>`})}
5520
- ${n&&!Nl.some(o=>o.id===n)?u`<option value=${n} selected>${n}</option>`:w}
5514
+ ${Ol.map(o=>{const a=o.id===n||!o.id&&!n;return u`<option value=${o.id} ?selected=${a}>${o.label}</option>`})}
5515
+ ${n&&!Ol.some(o=>o.id===n)?u`<option value=${n} selected>${n}</option>`:w}
5521
5516
  </select>
5522
5517
  </div>
5523
5518
  <div class="sp-session-settings__field">
@@ -5526,7 +5521,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5526
5521
  class="sp-filter-select"
5527
5522
  @change=${o=>{const a=o.target.value;t.onPatch(e.key,{thinkingLevel:a||null})}}
5528
5523
  >
5529
- ${hx.map(o=>{const a=o.id===i||!o.id&&!i;return u`<option value=${o.id} ?selected=${a}>${o.label}</option>`})}
5524
+ ${mx.map(o=>{const a=o.id===i||!o.id&&!i;return u`<option value=${o.id} ?selected=${a}>${o.label}</option>`})}
5530
5525
  </select>
5531
5526
  </div>
5532
5527
  ${s?u`<button
@@ -5537,7 +5532,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5537
5532
  title="Clear all per-session overrides and use agent defaults"
5538
5533
  >Reset to defaults</button>`:w}
5539
5534
  </div>
5540
- `}function fx(e){const t=new Map;for(const n of e)n.id&&n.name&&t.set(n.id,n.name);return t}function mx(e,t){const n=e.key.split(":"),i=n[n.length-1];return i!=null&&i.startsWith("+")&&t.has(i)?t.get(i):e.displayName&&t.has(e.displayName)?t.get(e.displayName):null}function yx(e,t,n,i){var C,A;const s=e.displayName||e.label||e.key,o=mx(e,n),a=o?`${s} (${o})`:s,r=e.model??"default",l=hk(e),c=e.updatedAt?un(e.updatedAt):"never",d=e.kind!=="unknown"?e.kind:"",m=Ja(e),v=tp(m),p=cx(m),b=t.expandedKey===e.key,x=i?Ya(e.key):null;return u`
5535
+ `}function vx(e){const t=new Map;for(const n of e)n.id&&n.name&&t.set(n.id,n.name);return t}function bx(e,t){const n=e.key.split(":"),i=n[n.length-1];return i!=null&&i.startsWith("+")&&t.has(i)?t.get(i):e.displayName&&t.has(e.displayName)?t.get(e.displayName):null}function wx(e,t,n,i){var C,A;const s=e.displayName||e.label||e.key,o=bx(e,n),a=o?`${s} (${o})`:s,r=e.model??"default",l=fk(e),c=e.updatedAt?un(e.updatedAt):"never",d=e.kind!=="unknown"?e.kind:"",m=Ja(e),v=ip(m),p=px(m),b=t.expandedKey===e.key,x=i?Ya(e.key):null;return u`
5541
5536
  <div class="sp-session-row ${b?"sp-session-row--expanded":""}">
5542
5537
  <div class="sp-session-row__main">
5543
5538
  <div class="sp-list-item-title" style="font-family: inherit; font-size: 14px; word-break: break-all;">
@@ -5609,25 +5604,25 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5609
5604
  </button>`}
5610
5605
  </div>
5611
5606
  </div>
5612
- ${b?gx(e,t):w}
5613
- `}function vx(e){var r;if(e.loading&&!e.result)return u`
5607
+ ${b?yx(e,t):w}
5608
+ `}function kx(e){var r;if(e.loading&&!e.result)return u`
5614
5609
  <div style="text-align: center; padding: 32px;">
5615
5610
  <div class="setup-spinner"></div>
5616
5611
  <p style="margin-top: 12px; color: var(--tasker-muted-grey);">Loading sessions...</p>
5617
5612
  </div>
5618
5613
  `;if(e.error)return u`
5619
- ${Dl(e,[],[],0,0)}
5614
+ ${Ul(e,[],[],0,0)}
5620
5615
  <div class="callout error" style="margin-bottom: 12px;">${e.error}</div>
5621
- `;const t=((r=e.result)==null?void 0:r.sessions)??[],n=dx(t),i=px(t),s=i.length>2,o=t.filter(l=>!(e.kindFilter!=="all"&&l.kind!==e.kindFilter||e.channelFilter!=="all"&&Ja(l)!==e.channelFilter||e.agentFilter!=="all"&&Ya(l.key)!==e.agentFilter)),a=fx(e.contacts);return u`
5622
- ${Dl(e,n,i,o.length,t.length)}
5623
- ${o.length===0?u`<p style="text-align: center; color: var(--tasker-muted-grey); padding: 24px 0;">No sessions found.</p>`:o.map(l=>yx(l,e,a,s))}
5624
- `}const Ul=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"sessions",label:"Sessions"},{id:"opening-hours",label:"Opening Hours"},{id:"logs",label:"Logs"}];function bx(e){switch(e.activeTab){case"cron":return Rl(e.cronProps);case"skills":return Bk(e.skillsProps);case"sessions":return vx(e.sessionsProps);case"opening-hours":return nx(e.openingHoursProps);case"logs":return Yk(e.logsProps);default:return Rl(e.cronProps)}}function wx(e){return e.connected?u`
5616
+ `;const t=((r=e.result)==null?void 0:r.sessions)??[],n=gx(t),i=fx(t),s=i.length>2,o=t.filter(l=>!(e.kindFilter!=="all"&&l.kind!==e.kindFilter||e.channelFilter!=="all"&&Ja(l)!==e.channelFilter||e.agentFilter!=="all"&&Ya(l.key)!==e.agentFilter)),a=vx(e.contacts);return u`
5617
+ ${Ul(e,n,i,o.length,t.length)}
5618
+ ${o.length===0?u`<p style="text-align: center; color: var(--tasker-muted-grey); padding: 24px 0;">No sessions found.</p>`:o.map(l=>wx(l,e,a,s))}
5619
+ `}const Fl=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"sessions",label:"Sessions"},{id:"opening-hours",label:"Opening Hours"},{id:"logs",label:"Logs"}];function xx(e){switch(e.activeTab){case"cron":return Rl(e.cronProps);case"skills":return Nk(e.skillsProps);case"sessions":return kx(e.sessionsProps);case"opening-hours":return sx(e.openingHoursProps);case"logs":return Zk(e.logsProps);default:return Rl(e.cronProps)}}function $x(e){return e.connected?u`
5625
5620
  <div class="setup-container" style="overflow: hidden; height: 100vh;">
5626
5621
  ${Nt("Advanced",e.wsProps)}
5627
5622
  <div class="setup-card sp-card-advanced" style="text-align: left; display: flex; flex-direction: column; min-height: 0; flex: 1; max-height: calc(100vh - 80px);">
5628
5623
  <!-- Desktop tabs -->
5629
5624
  <div class="sp-tabs sp-tabs--desktop" style="flex-shrink: 0;">
5630
- ${Ul.map(t=>u`
5625
+ ${Fl.map(t=>u`
5631
5626
  <button
5632
5627
  class="sp-tab ${e.activeTab===t.id?"active":""}"
5633
5628
  @click=${()=>e.onTabChange(t.id)}
@@ -5643,11 +5638,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5643
5638
  style="font-size: 14px; padding: 8px 32px 8px 12px;"
5644
5639
  @change=${t=>e.onTabChange(t.target.value)}
5645
5640
  >
5646
- ${Ul.map(t=>u`<option value=${t.id} ?selected=${e.activeTab===t.id}>${t.label}</option>`)}
5641
+ ${Fl.map(t=>u`<option value=${t.id} ?selected=${e.activeTab===t.id}>${t.label}</option>`)}
5647
5642
  </select>
5648
5643
  </div>
5649
5644
  <div style="flex: 1; overflow-y: auto; min-height: 0;">
5650
- ${bx(e)}
5645
+ ${xx(e)}
5651
5646
  </div>
5652
5647
  </div>
5653
5648
  </div>
@@ -5658,7 +5653,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5658
5653
  <p>Connecting to gateway...</p>
5659
5654
  </div>
5660
5655
  </div>
5661
- `}function kx(){return location.protocol==="https:"&&!location.hostname.endsWith(".local")&&location.hostname!=="localhost"}function Ol(e){if(!e.show)return w;const t=nt(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const a=C=>C==="__master__"||C.startsWith("admin:"),r=C=>{var T;o=C.target.value;const A=(T=C.target.closest(".login-card"))==null?void 0:T.querySelector(".login-change-pin");A&&(A.style.display=a(o)?"":"none")},l=C=>{const A=C.target;A.value=A.value.replace(/\D/g,"").slice(0,6)},c=C=>{const A=C.currentTarget,T=A.closest(".login-pin-wrapper"),M=T==null?void 0:T.querySelector("input");if(!M)return;const N=M.type==="text";M.type=N?"password":"text",A.classList.toggle("active",!N)},d=e.accounts.filter(C=>C.id==="__master__"||C.id.startsWith("admin:")),m=e.accounts.filter(C=>C.id!=="__master__"&&!C.id.startsWith("admin:")),v=d.length>0&&m.length>0,p=(C,A)=>u`
5656
+ `}function Sx(){return location.protocol==="https:"&&!location.hostname.endsWith(".local")&&location.hostname!=="localhost"}function Wl(e){if(!e.show)return w;const t=nt(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const a=C=>C==="__master__"||C.startsWith("admin:"),r=C=>{var T;o=C.target.value;const A=(T=C.target.closest(".login-card"))==null?void 0:T.querySelector(".login-change-pin");A&&(A.style.display=a(o)?"":"none")},l=C=>{const A=C.target;A.value=A.value.replace(/\D/g,"").slice(0,6)},c=C=>{const A=C.currentTarget,T=A.closest(".login-pin-wrapper"),M=T==null?void 0:T.querySelector("input");if(!M)return;const N=M.type==="text";M.type=N?"password":"text",A.classList.toggle("active",!N)},d=e.accounts.filter(C=>C.id==="__master__"||C.id.startsWith("admin:")),m=e.accounts.filter(C=>C.id!=="__master__"&&!C.id.startsWith("admin:")),v=d.length>0&&m.length>0,p=(C,A)=>u`
5662
5657
  <option value=${C.id} ?selected=${A===0&&!v}>
5663
5658
  ${C.displayName}
5664
5659
  </option>
@@ -5817,14 +5812,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5817
5812
  @click=${C=>{var A;C.preventDefault(),(A=e.onToggleChangePinMode)==null||A.call(e)}}
5818
5813
  >Change PIN</a>
5819
5814
  </p>`:w}
5820
- ${kx()?u`<p class="login-hint" style="margin-top: 16px;">
5815
+ ${Sx()?u`<p class="login-hint" style="margin-top: 16px;">
5821
5816
  Remote session via ${location.hostname}
5822
5817
  &middot;
5823
5818
  <a class="login-link" href="/__remote-auth/logout">Sign out</a>
5824
5819
  </p>`:w}
5825
5820
  </div>
5826
5821
  </div>
5827
- `}function xx(e){if(!e.connected)return u`
5822
+ `}function Ax(e){if(!e.connected)return u`
5828
5823
  <div class="setup-container">
5829
5824
  <div class="setup-card">
5830
5825
  <div class="setup-spinner"></div>
@@ -5837,10 +5832,10 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5837
5832
  <span class="public-chat-header__name">${n}</span>
5838
5833
  </div>
5839
5834
  <div class="chat-viewport">
5840
- ${Hd(t)}
5835
+ ${Vd(t)}
5841
5836
  </div>
5842
5837
  </div>
5843
- `}async function $x(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 ii(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 Sx(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 ii(e),(s=t.onCreated)==null||s.call(t,l)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function Ax(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 ii(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function Cx(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 ii(e)}catch(i){e.workspacesError=String(i)}}}const Mi=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:Sx,loadWorkspaces:ii,removeWorkspace:Ax,renameWorkspace:Cx},Symbol.toStringTag,{value:"Module"})),np={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"},Fl=np,sa={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(np));new Set(Object.values(sa));function Ex(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 Tx=4008;class Px{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 m;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 zg();const v=(m=Hg({deviceId:o.deviceId,role:t}))==null?void 0:m.token;r=v??this.opts.token,a=!!(v&&this.opts.token)}const l=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let c;if(s&&o){const v=Date.now(),p=this.connectNonce??void 0,b=Ex({deviceId:o.deviceId,clientId:this.opts.clientName??Fl.CONTROL_UI,clientMode:this.opts.mode??sa.WEBCHAT,role:t,scopes:n,signedAtMs:v,token:r??null,nonce:p}),x=await Kg(o.privateKey,b);c={id:o.deviceId,publicKey:o.publicKey,signature:x,signedAt:v,nonce:p}}const d={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Fl.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??sa.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",d).then(v=>{var p,b,x;(p=v==null?void 0:v.auth)!=null&&p.deviceToken&&o&&jg({deviceId:o.deviceId,role:v.auth.role??t,token:v.auth.deviceToken,scopes:v.auth.scopes??[]}),this.backoffMs=800,(x=(b=this.opts).onHello)==null||x.call(b,v)}).catch(()=>{var v;a&&o&&Vg({deviceId:o.deviceId,role:t}),(v=this.ws)==null||v.close(Tx,"connect failed")})}handleMessage(t){var s,o,a,r,l,c;let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const d=n;if(d.event==="connect.challenge"){const v=d.payload,p=v&&typeof v.nonce=="string"?v.nonce:null;p&&(this.connectNonce=p,this.sendConnect());return}const m=typeof d.seq=="number"?d.seq:null;m!==null&&(this.lastSeq!==null&&m>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:m})),this.lastSeq=m);try{(r=(a=this.opts).onEvent)==null||r.call(a,d)}catch(v){console.error("[gateway] event handler error:",v)}return}if(i.type==="res"){const d=n,m=this.pending.get(d.id);if(!m)return;if(this.pending.delete(d.id),d.ok)m.resolve(d.payload);else{const v=new Error(((l=d.error)==null?void 0:l.message)??"request failed");v.payload=d.payload,v.details=(c=d.error)==null?void 0:c.details,m.reject(v)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=vs(),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 oa(e){return typeof e=="object"&&e!==null}function _x(e){if(!oa(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!oa(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 Mx(e){if(!oa(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 ip(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Ix(e,t){const n=ip(e).filter(i=>i.id!==t.id);return n.push(t),n}function Wl(e,t){return ip(e).filter(n=>n.id!==t)}class Rx{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 $o=null;function qn(){return $o||($o=new Rx),$o}function Xa(e){return e instanceof Error?e.message:String(e)}async function Lx(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=Xa(t)}finally{e.browserLoading=!1}}async function Bx(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=Xa(t)}finally{e.browserLoading=!1}}}async function So(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 Ao(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 Dx(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=Xa(t)}}function Nx(e){e.browserInputMode=!e.browserInputMode}function Ux(e){e.browserFullscreen=!e.browserFullscreen,qn().detach()}function Ox(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,qn().updateFrame(t.data,t.metadata)}function Fx(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Wx(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function aa(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=Mo(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function Wi(e){return(await e.request("apikeys.list")).providers??[]}async function zl(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function zx(e,t){await e.request("apikeys.remove",{provider:t})}async function Kx(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const gs="taskmaster_update_pending";async function sp(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 qx(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(gs,String(Date.now())),localStorage.removeItem(Za)}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")Hn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw Hn(),new Error(o.result.reason||"Update failed")}catch(o){Hn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function Hx(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 c=e.updateProgressSteps.find(d=>d.index===r);c?(c.status="running",c.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,c=t.ok,d=t.durationMs,m=e.updateProgressSteps.find(p=>p.index===r);m?(m.status=c?"done":"failed",m.durationMs=d):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:l,status:c?"done":"failed",durationMs:d}];const v=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${a} done (${r+1}/${l})`:`Update step failed: ${a}${v}`,(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,Hn()}(o=e.requestUpdate)==null||o.call(e)}}async function jx(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=Gx();Hn();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||Qx(a.result.ts))return;e.updateLastResult=a.result;const c=(n=a.result.after)==null?void 0:n.version;if(a.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,a.result.status==="ok"){const d=(i=a.result.before)==null?void 0:i.version,m=c??a.result.currentVersion;e.updateMessage=d?`Updated: v${d} → v${m}`:`Updated to v${m}`}else{const d=a.result.reason??((s=a.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${d}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const Za="taskmaster_update_dismissed";function Vx(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Za,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function Gx(){try{const e=localStorage.getItem(gs);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(gs),!1):!0:!1}catch{return!1}}function Hn(){try{localStorage.removeItem(gs)}catch{}}function Qx(e){try{const t=localStorage.getItem(Za);return t?Number(t)>=e:!1}catch{return!1}}const Kl="notification-banner",ql={rate_limit:"rate limit",auth:"auth error",billing:"billing",timeout:"timeout",format:"format error"};function Jx(e){const t=document.getElementById(Kl);if(!e){t==null||t.remove();return}t&&t.remove();const n=document.createElement("div");n.id=Kl,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=e.reason&&ql[e.reason]?` (${ql[e.reason]})`:"",s=document.createElement("span");s.textContent=e.message+i,n.appendChild(s);const o=document.createElement("button");o.setAttribute("aria-label","Dismiss"),o.textContent="×",Object.assign(o.style,{background:"none",border:"none",outline:"none",color:"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"18px",padding:"0 4px"}),o.addEventListener("click",()=>n.remove()),n.appendChild(o),(document.querySelector("main")??document.body).prepend(n),e.autoDismiss&&setTimeout(()=>n.remove(),8e3)}function Co(e,t){var r,l,c;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=(c=t.defaultAgentId)==null?void 0:c.trim();return n==="main"||n===s||o&&(n===`agent:${o}:main`||n===`agent:${o}:${s}`)?i:n}function Yx(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=Co(e.sessionKey,t),i=Co(e.settings.sessionKey,t),s=Co(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&&ut(e,a)}function ze(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 Px({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,c;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){Hl(e,a),aa(e),(((c=e.publicChatConfig)==null?void 0:c.auth)??"anonymous")==="anonymous"&&a0(e);return}ns()&&(Ra(),e.uninstallDone=!1),Hl(e,a),e.handleAccessCheck(),jx(e).then(()=>{sp(e)}),aa(e),$x(e),(e.chatPage||e.setup)&&e0(e),Aa(e,{quiet:!0}),Sa(e,{quiet:!0}),ii(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&He(e),e.setup&&(t0(e),n0(e),i0(e),s0(e),o0(e)),es(e)},onClose:({code:a,reason:r})=>{e.connected=!1,a!==1012&&(e.lastError=`disconnected (${a}): ${r||"no reason"}`)},onEvent:a=>Xx(e,a),onGap:({expected:a,received:r})=>{console.warn(`[gateway] event gap: expected seq ${a}, got ${r}`),es(e)}}),e.client.start()}function Xx(e,t){try{Zx(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function Zx(e,t){var n,i;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;zh(e,t.payload);return}if(t.event==="chat"){const s=t.payload;s!=null&&s.sessionKey&&Bu(e,s.sessionKey);const o=kc(e,s);if((o==="final"||o==="error"||o==="aborted")&&(fa(e),Uf(e)),o==="final"){const a=e,r=Math.max((((n=a.chatMessages)==null?void 0:n.length)??0)+10,dn);nn(a,{limit:r}),(i=a.loadChatSessions)==null||i.call(a)}return}if(t.event==="suggestions"){const s=t.payload;(s==null?void 0:s.sessionKey)===e.sessionKey&&Array.isArray(s.suggestions)&&s.suggestions.length>0&&(e.chatSuggestions=s.suggestions);return}if(t.event==="presence"){const s=t.payload;s!=null&&s.presence&&Array.isArray(s.presence)&&(e.presenceEntries=s.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"){const s=t.payload;s&&ig(e,s),e.tab==="cron"&&e.loadCron()}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&Sa(e,{quiet:!0}),t.event==="exec.approval.requested"){const s=_x(t.payload);if(s){e.execApprovalQueue=Ix(e.execApprovalQueue,s),e.execApprovalError=null;const o=Math.max(0,s.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Wl(e.execApprovalQueue,s.id)},o)}return}if(t.event==="browser.screencast.frame"){Ox(e,t.payload);return}if(t.event==="browser.handoff"){Fx(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Wx(e);return}if(t.event==="exec.approval.resolved"){const s=Mx(t.payload);s&&(e.execApprovalQueue=Wl(e.execApprovalQueue,s.id));return}if(t.event==="update.progress"){Hx(e,t.payload);return}if(t.event==="notification"){const s=t.payload;(s==null?void 0:s.category)==="model-fallback"&&Jx(s);return}}function Hl(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&&Yx(e,n.sessionDefaults)}async function e0(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 t0(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await Wi(e.client)}catch{}}async function n0(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function i0(e){if(!(!e.client||!e.connected))try{e.tunnelStatus=await e.client.request("tunnel.status"),e.tunnelQrDataUrl=null}catch{}}async function s0(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 o0(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 jl="taskmaster_public_id";function op(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${jl}=`));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=`${jl}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function a0(e){var n,i,s;if(!e.client||!e.connected)return;const t=op((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=Yn(r,a.sessionKey),nn(e)}}catch(o){console.error("[public-chat] failed to resolve anonymous session:",o),e.lastError="Failed to start chat session"}}let ve=!1,le=null,rn="",ln="",cn="",Ps="",yn="phone",jn="";function ap(e){return e.replace(/[\s\-()]/g,"")}function rt(){ve=!1,le=null,rn="",ln="",cn="",Ps="",yn="phone",jn=""}async function r0(e){if(!e.client||!e.connected)return;const t=op(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){le=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function Vl(e){if(!e.client||ve)return;const t=ap(rn);if(!t){le="Please enter your phone number",e.requestUpdate();return}ve=!0,le=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:cn.trim()||void 0,accountId:e.accountId,channel:jn||void 0});n!=null&&n.ok?(Ps=n.channel??"",yn="phone",e.onAuthStepChange("otp")):le=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){le=n instanceof Error?n.message:"Failed to send verification code"}finally{ve=!1,e.requestUpdate()}}async function Gl(e){if(!e.client||ve)return;const t=ln.trim().toLowerCase();if(!t||!t.includes("@")){le="Please enter a valid email address",e.requestUpdate();return}ve=!0,le=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{identifier:t,accountId:e.accountId});n!=null&&n.ok?(Ps=n.channel??"email",yn="email",e.onAuthStepChange("otp")):le=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){le=n instanceof Error?n.message:"Failed to send verification code"}finally{ve=!1,e.requestUpdate()}}async function Ql(e,t){if(!(!e.client||ve)){if(!t.trim()){le="Please enter the verification code",e.requestUpdate();return}ve=!0,le=null,e.requestUpdate();try{const n=yn==="email"?ln.trim().toLowerCase():ap(rn),i=await e.client.request("public.otp.verify",{identifier:n,code:t.trim(),accountId:e.accountId});i!=null&&i.ok&&i.sessionKey?(rt(),e.onAuthenticated(i.sessionKey)):le=(i==null?void 0:i.error)??"Invalid verification code"}catch(n){le=n instanceof Error?n.message:"Verification failed"}finally{ve=!1,e.requestUpdate()}}}function Xe(e){return w}function Ii(e){return u`
5838
+ `}async function Cx(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 ii(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 Ex(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 ii(e),(s=t.onCreated)==null||s.call(t,l)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function Tx(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 ii(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function Px(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 ii(e)}catch(i){e.workspacesError=String(i)}}}const Mi=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:Ex,loadWorkspaces:ii,removeWorkspace:Tx,renameWorkspace:Px},Symbol.toStringTag,{value:"Module"})),sp={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"},zl=sp,sa={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(sp));new Set(Object.values(sa));function _x(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 Mx=4008;class Ix{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 m;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 qg();const v=(m=Vg({deviceId:o.deviceId,role:t}))==null?void 0:m.token;r=v??this.opts.token,a=!!(v&&this.opts.token)}const l=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let c;if(s&&o){const v=Date.now(),p=this.connectNonce??void 0,b=_x({deviceId:o.deviceId,clientId:this.opts.clientName??zl.CONTROL_UI,clientMode:this.opts.mode??sa.WEBCHAT,role:t,scopes:n,signedAtMs:v,token:r??null,nonce:p}),x=await Hg(o.privateKey,b);c={id:o.deviceId,publicKey:o.publicKey,signature:x,signedAt:v,nonce:p}}const d={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??zl.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??sa.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",d).then(v=>{var p,b,x;(p=v==null?void 0:v.auth)!=null&&p.deviceToken&&o&&Gg({deviceId:o.deviceId,role:v.auth.role??t,token:v.auth.deviceToken,scopes:v.auth.scopes??[]}),this.backoffMs=800,(x=(b=this.opts).onHello)==null||x.call(b,v)}).catch(()=>{var v;a&&o&&Qg({deviceId:o.deviceId,role:t}),(v=this.ws)==null||v.close(Mx,"connect failed")})}handleMessage(t){var s,o,a,r,l,c;let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const d=n;if(d.event==="connect.challenge"){const v=d.payload,p=v&&typeof v.nonce=="string"?v.nonce:null;p&&(this.connectNonce=p,this.sendConnect());return}const m=typeof d.seq=="number"?d.seq:null;m!==null&&(this.lastSeq!==null&&m>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:m})),this.lastSeq=m);try{(r=(a=this.opts).onEvent)==null||r.call(a,d)}catch(v){console.error("[gateway] event handler error:",v)}return}if(i.type==="res"){const d=n,m=this.pending.get(d.id);if(!m)return;if(this.pending.delete(d.id),d.ok)m.resolve(d.payload);else{const v=new Error(((l=d.error)==null?void 0:l.message)??"request failed");v.payload=d.payload,v.details=(c=d.error)==null?void 0:c.details,m.reject(v)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=vs(),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 oa(e){return typeof e=="object"&&e!==null}function Rx(e){if(!oa(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!oa(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 Lx(e){if(!oa(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 op(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Bx(e,t){const n=op(e).filter(i=>i.id!==t.id);return n.push(t),n}function Kl(e,t){return op(e).filter(n=>n.id!==t)}class Dx{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 $o=null;function qn(){return $o||($o=new Dx),$o}function Xa(e){return e instanceof Error?e.message:String(e)}async function Nx(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=Xa(t)}finally{e.browserLoading=!1}}async function Ux(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=Xa(t)}finally{e.browserLoading=!1}}}async function So(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 Ao(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 Ox(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=Xa(t)}}function Fx(e){e.browserInputMode=!e.browserInputMode}function Wx(e){e.browserFullscreen=!e.browserFullscreen,qn().detach()}function zx(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,qn().updateFrame(t.data,t.metadata)}function Kx(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function qx(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function aa(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=Mo(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function Wi(e){return(await e.request("apikeys.list")).providers??[]}async function ql(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Hx(e,t){await e.request("apikeys.remove",{provider:t})}async function jx(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const gs="taskmaster_update_pending";async function ap(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 Vx(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(gs,String(Date.now())),localStorage.removeItem(Za)}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")Hn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw Hn(),new Error(o.result.reason||"Update failed")}catch(o){Hn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function Gx(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 c=e.updateProgressSteps.find(d=>d.index===r);c?(c.status="running",c.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,c=t.ok,d=t.durationMs,m=e.updateProgressSteps.find(p=>p.index===r);m?(m.status=c?"done":"failed",m.durationMs=d):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:l,status:c?"done":"failed",durationMs:d}];const v=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${a} done (${r+1}/${l})`:`Update step failed: ${a}${v}`,(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,Hn()}(o=e.requestUpdate)==null||o.call(e)}}async function Qx(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=Yx();Hn();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||Xx(a.result.ts))return;e.updateLastResult=a.result;const c=(n=a.result.after)==null?void 0:n.version;if(a.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,a.result.status==="ok"){const d=(i=a.result.before)==null?void 0:i.version,m=c??a.result.currentVersion;e.updateMessage=d?`Updated: v${d} → v${m}`:`Updated to v${m}`}else{const d=a.result.reason??((s=a.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${d}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const Za="taskmaster_update_dismissed";function Jx(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Za,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function Yx(){try{const e=localStorage.getItem(gs);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(gs),!1):!0:!1}catch{return!1}}function Hn(){try{localStorage.removeItem(gs)}catch{}}function Xx(e){try{const t=localStorage.getItem(Za);return t?Number(t)>=e:!1}catch{return!1}}const Hl="notification-banner",jl={rate_limit:"rate limit",auth:"auth error",billing:"billing",timeout:"timeout",format:"format error"};function Zx(e){const t=document.getElementById(Hl);if(!e){t==null||t.remove();return}t&&t.remove();const n=document.createElement("div");n.id=Hl,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=e.reason&&jl[e.reason]?` (${jl[e.reason]})`:"",s=document.createElement("span");s.textContent=e.message+i,n.appendChild(s);const o=document.createElement("button");o.setAttribute("aria-label","Dismiss"),o.textContent="×",Object.assign(o.style,{background:"none",border:"none",outline:"none",color:"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"18px",padding:"0 4px"}),o.addEventListener("click",()=>n.remove()),n.appendChild(o),(document.querySelector("main")??document.body).prepend(n),e.autoDismiss&&setTimeout(()=>n.remove(),8e3)}function Co(e,t){var r,l,c;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=(c=t.defaultAgentId)==null?void 0:c.trim();return n==="main"||n===s||o&&(n===`agent:${o}:main`||n===`agent:${o}:${s}`)?i:n}function e0(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=Co(e.sessionKey,t),i=Co(e.settings.sessionKey,t),s=Co(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&&ut(e,a)}function ze(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 Ix({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,c;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){Vl(e,a),aa(e),(((c=e.publicChatConfig)==null?void 0:c.auth)??"anonymous")==="anonymous"&&c0(e);return}ns()&&(Ra(),e.uninstallDone=!1),Vl(e,a),e.handleAccessCheck(),Qx(e).then(()=>{ap(e)}),aa(e),Cx(e),(e.chatPage||e.setup)&&i0(e),Aa(e,{quiet:!0}),Sa(e,{quiet:!0}),ii(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&He(e),e.setup&&(s0(e),o0(e),a0(e),r0(e),l0(e)),es(e)},onClose:({code:a,reason:r})=>{e.connected=!1,a!==1012&&(e.lastError=`disconnected (${a}): ${r||"no reason"}`)},onEvent:a=>t0(e,a),onGap:({expected:a,received:r})=>{console.warn(`[gateway] event gap: expected seq ${a}, got ${r}`),es(e)}}),e.client.start()}function t0(e,t){try{n0(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function n0(e,t){var n,i;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;qh(e,t.payload);return}if(t.event==="chat"){const s=t.payload;s!=null&&s.sessionKey&&Nu(e,s.sessionKey);const o=$c(e,s);if((o==="final"||o==="error"||o==="aborted")&&(fa(e),Ff(e)),o==="final"){const a=e,r=Math.max((((n=a.chatMessages)==null?void 0:n.length)??0)+10,dn);nn(a,{limit:r}),(i=a.loadChatSessions)==null||i.call(a)}return}if(t.event==="suggestions"){const s=t.payload;(s==null?void 0:s.sessionKey)===e.sessionKey&&Array.isArray(s.suggestions)&&s.suggestions.length>0&&(e.chatSuggestions=s.suggestions);return}if(t.event==="presence"){const s=t.payload;s!=null&&s.presence&&Array.isArray(s.presence)&&(e.presenceEntries=s.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"){const s=t.payload;s&&og(e,s),e.tab==="cron"&&e.loadCron()}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&Sa(e,{quiet:!0}),t.event==="exec.approval.requested"){const s=Rx(t.payload);if(s){e.execApprovalQueue=Bx(e.execApprovalQueue,s),e.execApprovalError=null;const o=Math.max(0,s.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Kl(e.execApprovalQueue,s.id)},o)}return}if(t.event==="browser.screencast.frame"){zx(e,t.payload);return}if(t.event==="browser.handoff"){Kx(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){qx(e);return}if(t.event==="exec.approval.resolved"){const s=Lx(t.payload);s&&(e.execApprovalQueue=Kl(e.execApprovalQueue,s.id));return}if(t.event==="update.progress"){Gx(e,t.payload);return}if(t.event==="notification"){const s=t.payload;(s==null?void 0:s.category)==="model-fallback"&&Zx(s);return}}function Vl(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&&e0(e,n.sessionDefaults)}async function i0(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 s0(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await Wi(e.client)}catch{}}async function o0(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function a0(e){if(!(!e.client||!e.connected))try{e.tunnelStatus=await e.client.request("tunnel.status"),e.tunnelQrDataUrl=null}catch{}}async function r0(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 l0(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 Gl="taskmaster_public_id";function rp(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${Gl}=`));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=`${Gl}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function c0(e){var n,i,s;if(!e.client||!e.connected)return;const t=rp((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=Yn(r,a.sessionKey),nn(e)}}catch(o){console.error("[public-chat] failed to resolve anonymous session:",o),e.lastError="Failed to start chat session"}}let ve=!1,le=null,rn="",ln="",cn="",Ps="",yn="phone",jn="";function lp(e){return e.replace(/[\s\-()]/g,"")}function rt(){ve=!1,le=null,rn="",ln="",cn="",Ps="",yn="phone",jn=""}async function u0(e){if(!e.client||!e.connected)return;const t=rp(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){le=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function Ql(e){if(!e.client||ve)return;const t=lp(rn);if(!t){le="Please enter your phone number",e.requestUpdate();return}ve=!0,le=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:cn.trim()||void 0,accountId:e.accountId,channel:jn||void 0});n!=null&&n.ok?(Ps=n.channel??"",yn="phone",e.onAuthStepChange("otp")):le=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){le=n instanceof Error?n.message:"Failed to send verification code"}finally{ve=!1,e.requestUpdate()}}async function Jl(e){if(!e.client||ve)return;const t=ln.trim().toLowerCase();if(!t||!t.includes("@")){le="Please enter a valid email address",e.requestUpdate();return}ve=!0,le=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{identifier:t,accountId:e.accountId});n!=null&&n.ok?(Ps=n.channel??"email",yn="email",e.onAuthStepChange("otp")):le=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){le=n instanceof Error?n.message:"Failed to send verification code"}finally{ve=!1,e.requestUpdate()}}async function Yl(e,t){if(!(!e.client||ve)){if(!t.trim()){le="Please enter the verification code",e.requestUpdate();return}ve=!0,le=null,e.requestUpdate();try{const n=yn==="email"?ln.trim().toLowerCase():lp(rn),i=await e.client.request("public.otp.verify",{identifier:n,code:t.trim(),accountId:e.accountId});i!=null&&i.ok&&i.sessionKey?(rt(),e.onAuthenticated(i.sessionKey)):le=(i==null?void 0:i.error)??"Invalid verification code"}catch(n){le=n instanceof Error?n.message:"Verification failed"}finally{ve=!1,e.requestUpdate()}}}function Xe(e){return w}function Ii(e){return u`
5844
5839
  <div class="public-auth__form">
5845
5840
  <label class="field public-auth__field">
5846
5841
  <span>Your name (optional)</span>
@@ -5857,7 +5852,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5857
5852
  type="tel"
5858
5853
  .value=${rn}
5859
5854
  @input=${t=>{rn=t.target.value}}
5860
- @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Vl(e))}}
5855
+ @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Ql(e))}}
5861
5856
  placeholder="+44 7123 456789"
5862
5857
  required
5863
5858
  />
@@ -5866,7 +5861,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5866
5861
  <button
5867
5862
  class="btn primary public-auth__btn"
5868
5863
  ?disabled=${ve}
5869
- @click=${()=>{Vl(e)}}
5864
+ @click=${()=>{Ql(e)}}
5870
5865
  >
5871
5866
  ${ve?"Sending...":"Send verification code"}
5872
5867
  </button>
@@ -5888,7 +5883,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5888
5883
  type="email"
5889
5884
  .value=${ln}
5890
5885
  @input=${t=>{ln=t.target.value}}
5891
- @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Gl(e))}}
5886
+ @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Jl(e))}}
5892
5887
  placeholder="you@example.com"
5893
5888
  required
5894
5889
  />
@@ -5897,12 +5892,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5897
5892
  <button
5898
5893
  class="btn primary public-auth__btn"
5899
5894
  ?disabled=${ve}
5900
- @click=${()=>{Gl(e)}}
5895
+ @click=${()=>{Jl(e)}}
5901
5896
  >
5902
5897
  ${ve?"Sending...":"Send verification code"}
5903
5898
  </button>
5904
5899
  </div>
5905
- `}function Jl(e){let t="";const n=yn==="email",i=n?"email":Ps==="sms"?"SMS":"WhatsApp",s=n?ln:rn,o=n?"email":"phone";return u`
5900
+ `}function Xl(e){let t="";const n=yn==="email",i=n?"email":Ps==="sms"?"SMS":"WhatsApp",s=n?ln:rn,o=n?"email":"phone";return u`
5906
5901
  <div class="public-auth__form">
5907
5902
  <p class="public-auth__hint">
5908
5903
  We sent a verification code to <strong>${s}</strong> via ${i}.
@@ -5914,7 +5909,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5914
5909
  inputmode="numeric"
5915
5910
  maxlength="6"
5916
5911
  @input=${a=>{t=a.target.value}}
5917
- @keydown=${a=>{a.key==="Enter"&&(a.preventDefault(),Ql(e,t))}}
5912
+ @keydown=${a=>{a.key==="Enter"&&(a.preventDefault(),Yl(e,t))}}
5918
5913
  placeholder="123456"
5919
5914
  required
5920
5915
  />
@@ -5923,7 +5918,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5923
5918
  <button
5924
5919
  class="btn primary public-auth__btn"
5925
5920
  ?disabled=${ve}
5926
- @click=${()=>{Ql(e,t)}}
5921
+ @click=${()=>{Yl(e,t)}}
5927
5922
  >
5928
5923
  ${ve?"Verifying...":"Verify"}
5929
5924
  </button>
@@ -5934,7 +5929,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5934
5929
  ${n?"Use a different email":"Use a different number"}
5935
5930
  </button>
5936
5931
  </div>
5937
- `}function l0(e){const{authMode:t,authStep:n}=e,i=!e.otpChannels||e.otpChannels.length>0;if(t==="anonymous")return u`
5932
+ `}function d0(e){const{authMode:t,authStep:n}=e,i=!e.otpChannels||e.otpChannels.length>0;if(t==="anonymous")return u`
5938
5933
  <div class="setup-container">
5939
5934
  <div class="setup-card">
5940
5935
  <div class="setup-spinner"></div>
@@ -5954,7 +5949,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
5954
5949
  <div class="public-auth">
5955
5950
  ${Xe()}
5956
5951
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
5957
- ${Jl(e)}
5952
+ ${Xl(e)}
5958
5953
  </div>
5959
5954
  </div>
5960
5955
  `:n==="email"?u`
@@ -6024,7 +6019,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
6024
6019
  ${Xe()}
6025
6020
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
6026
6021
  <p class="public-auth__subtitle">${v}</p>
6027
- ${n==="otp"?Jl(e):n==="email"?Eo(e):Ii(e)}
6022
+ ${n==="otp"?Xl(e):n==="email"?Eo(e):Ii(e)}
6028
6023
  ${n!=="otp"?u`
6029
6024
  <button class="btn public-auth__btn public-auth__btn--link"
6030
6025
  @click=${()=>{rt(),e.onAuthStepChange("idle")}}>
@@ -6042,7 +6037,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
6042
6037
  <div class="public-auth__choices">
6043
6038
  <button
6044
6039
  class="btn primary public-auth__btn"
6045
- @click=${()=>{r0(e)}}
6040
+ @click=${()=>{u0(e)}}
6046
6041
  >
6047
6042
  Chat now
6048
6043
  </button>
@@ -6078,7 +6073,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
6078
6073
  `:w}
6079
6074
  </div>
6080
6075
  </div>
6081
- `}function er(){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 rp=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];async function tr(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 rp){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=er();n.publicAgentEnabled=t.publicAgentEnabled,e.openingHoursForm=n}}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursLoading=!1}}}async function lp(e){if(!(!e.client||!e.connected||e.openingHoursBusy)){e.openingHoursBusy=!0,e.openingHoursError=null;try{const t=e.openingHoursForm,n={};for(const a of rp){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 tr(e)}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursBusy=!1}}}const c0=Object.freeze(Object.defineProperty({__proto__:null,defaultOpeningHoursForm:er,loadOpeningHours:tr,saveOpeningHours:lp},Symbol.toStringTag,{value:"Module"}));function u0(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 c=l.id??"";c&&i.push({phone:c,paired:((s=o.meta)==null?void 0:s.paired)===!0})}return i.sort((o,a)=>o.paired&&!a.paired?-1:!o.paired&&a.paired?1:0),i}function cp(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,a=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const d=c.match;if(!d||typeof d!="object"||(d.channel??"").toLowerCase()!=="whatsapp")continue;const v=d.peer;if(!v||typeof v!="object"||v.kind!=="dm")continue;const p=v.id??"";p&&(c.meta&&o.set(p,c.meta),d.accountId&&a.set(p,d.accountId))}const r=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const d=c.match;if(!d||typeof d!="object"||(d.channel??"").toLowerCase()!=="whatsapp")return!0;const v=d.peer;return!v||typeof v!="object"?!0:v.kind!=="dm"}),l=t.map(c=>{const d=i??a.get(c.phone),m={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};d&&(m.accountId=d);const v={agentId:n,match:m},p=o.get(c.phone);return p?v.meta=p:c.paired&&(v.meta={paired:!0}),v});return[...r,...l]}function d0(e,t="admin"){if(!e)return[];const n=e.bindings;if(!Array.isArray(n))return[];const i=[];for(const s of n){if(!s||typeof s!="object"||s.agentId!==t&&s.agentId!=="management")continue;const o=s.match;if(!o||typeof o!="object"||(o.channel??"").toLowerCase()!=="telegram")continue;const r=o.peer;if(!r||typeof r!="object"||r.kind!=="dm")continue;const l=r.id??"";l&&i.push({username:l})}return i}function up(e,t,n="admin",i){const s=r=>r===n||r==="management",o=e.filter(r=>{if(!r||typeof r!="object"||!s(r.agentId))return!0;const l=r.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="telegram")return!0;const d=l.peer;return!d||typeof d!="object"?!0:d.kind!=="dm"}),a=t.map(r=>{const l={channel:"telegram",peer:{kind:"dm",id:r.username}};return i&&(l.accountId=i),{agentId:n,match:l}});return[...o,...a]}async function vn(e,t){if(!e.client||!e.connected)return;if(!t){e.adminPhones=[],e.telegramAdmins=[];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=he(s??{}),e.adminPhones=u0(s,n),e.telegramAdmins=d0(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function dp(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=he(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],d=[...e.adminPhones,{phone:o}],m=cp(c,d,s,i);bs(l,["bindings"],m);const v=(r=e.configSnapshot)==null?void 0:r.hash;if(!v){e.adminsError="Config hash missing; reload and retry.";return}const p=fe(l);await e.client.request("config.set",{raw:p,baseHash:v}),await vn(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function pp(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=he(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],d=e.adminPhones.filter(b=>b.phone!==t),m=cp(c,d,s,i);bs(l,["bindings"],m);const v=(r=e.configSnapshot)==null?void 0:r.hash;if(!v){e.adminsError="Config hash missing; reload and retry.";return}const p=fe(l);await e.client.request("config.set",{raw:p,baseHash:v}),await vn(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function hp(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=t.trim();if(!/^\d{4,15}$/.test(o)){e.adminsError="Enter a numeric Telegram user ID (e.g. 123456789). Find yours via @userinfobot in Telegram.";return}if(e.telegramAdmins.some(l=>l.username===o)){e.adminsError="This user ID is already an admin.";return}e.adminsSaving=!0,e.adminsError=null;try{const l=he(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],d=[...e.telegramAdmins,{username:o}],m=up(c,d,s,i);bs(l,["bindings"],m);const v=(r=e.configSnapshot)==null?void 0:r.hash;if(!v){e.adminsError="Config hash missing; reload and retry.";return}const p=fe(l);await e.client.request("config.set",{raw:p,baseHash:v}),await vn(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function gp(e,t,n,i){var o,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n;e.adminsSaving=!0,e.adminsError=null;try{const r=he(e.configForm??((o=e.configSnapshot)==null?void 0:o.config)??{}),l=r.bindings??[],c=e.telegramAdmins.filter(p=>p.username!==t),d=up(l,c,s,i);bs(r,["bindings"],d);const m=(a=e.configSnapshot)==null?void 0:a.hash;if(!m){e.adminsError="Config hash missing; reload and retry.";return}const v=fe(r);await e.client.request("config.set",{raw:v,baseHash:m}),await vn(e,n)}catch(r){e.adminsError=String(r)}finally{e.adminsSaving=!1}}const p0=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:dp,addTelegramAdmin:hp,loadAdmins:vn,removeAdmin:pp,removeTelegramAdmin:gp},Symbol.toStringTag,{value:"Module"}));async function dt(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 fp(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 dt(e,i)}catch(a){e.contactsError=String(a)}finally{e.contactsSaving=!1}}async function mp(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 dt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function ra(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 dt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function yp(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 dt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const h0=Object.freeze(Object.defineProperty({__proto__:null,addContact:fp,deleteContact:mp,deleteContactField:yp,loadContacts:dt,setContactField:ra},Symbol.toStringTag,{value:"Module"}));let Ct=null,zi=null,Ki=null;const To=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function Vt(){Ct&&(clearInterval(Ct),Ct=null),zi&&(clearInterval(zi),zi=null),Ki&&(clearTimeout(Ki),Ki=null)}function Rn(e){if(e.workspaces.length===0)return;const{hasPins:t,authenticated:n,adminUsername:i,master:s}=e.accessState,o=t&&n?i??(s?"Admin":null):null;return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:a=>e.handleWorkspaceSelect(a),hasPins:t,isMaster:s,onLogout:()=>e.handleLogout(),loggedInAs:o,auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function g0(e){if(e.workspaces.length===0)return;const{hasPins:t,authenticated:n,adminUsername:i,master:s}=e.accessState,o=t&&n?i??(s?"Admin":null):null;return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:a=>e.handleWorkspaceSelect(a),onAddAccount:()=>{e.addingWorkspace=!0},hasPins:t,isMaster:s,onLogout:()=>e.handleLogout(),loggedInAs:o,auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function f0(e){const t=Me(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 Vn(e){const t=Me(e);return(t==null?void 0:t.accountId)??void 0}function m0(e){var i;const t=Me(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 y0(e){return e.selectedWorkspace??void 0}function Me(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}function Ri(e){const t=Me(e);return t?(t.displayName??t.name).trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9_-]/g,""):null}const v0=/^data:/i,b0=/^https?:\/\//i;function Yl(e){var r,l;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=ha(e.sessionKey),i=(n==null?void 0:n.agentId)??((l=e.agentsList)==null?void 0:l.defaultId)??"main",s=t.find(c=>c.id===i),o=s==null?void 0:s.identity,a=(o==null?void 0:o.avatarUrl)??(o==null?void 0:o.avatar);if(a)return v0.test(a)||b0.test(a)?a:o==null?void 0:o.avatarUrl}function w0(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 k0(e){var s,o;if(!e)return{configured:!1,running:!1,botUsername:null,mode:null,lastError:null};const t=(s=e.channelAccounts)==null?void 0:s.telegram;if(!Array.isArray(t)||t.length===0)return{configured:!1,running:!1,botUsername:null,mode:null,lastError:null};const n=t[0],i=n.probe;return{configured:n.configured??!1,running:n.running??!1,botUsername:i!=null&&i.ok?((o=i.bot)==null?void 0:o.username)??null:null,mode:n.mode??null,lastError:n.lastError??null}}async function Li(e,t){e.telegramPairingLoading=!0;try{const n=await e.client.request("channels.telegram.pairing.list",{accountId:t});e.telegramPairingRequests=n??[]}catch{e.telegramPairingRequests=[]}finally{e.telegramPairingLoading=!1}}function x0(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 $0(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,c;return((l=r.match)==null?void 0:l.channel)==="imessage"&&((c=r.meta)==null?void 0:c.imessageOwner)});if(!i)return null;const s=i.agentId;for(const r of e.workspaces)if(r.agents.some(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 qi(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:()=>Vn(e),set:()=>{}}}),t}function S0(){requestAnimationFrame(()=>{const e=document.querySelector(".wa-messages");e&&(e.scrollTop=e.scrollHeight)})}function A0(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:Vn(e),onSelectConversation:t=>{const n=qi(e);uk(n,t).then(()=>{e.requestUpdate(),S0()})},onBack:()=>{e.waSelectedJid=null,e.waMessages=[],e.waGroupInfo=null,e.requestUpdate()},onSearchChange:t=>{e.waSearchQuery=t,e.requestUpdate()},onActivationChange:(t,n)=>{const i=qi(e);dk(i,t,n).then(()=>e.requestUpdate())},onRefresh:()=>{const t=qi(e);Vd(t).then(()=>e.requestUpdate())},requestUpdate:()=>e.requestUpdate()}}function C0(e){var t,n,i,s,o,a,r,l,c,d,m,v;if(e.embeddingDownloading&&!e.publicChat)return u`
6076
+ `}function er(){return{enabled:!1,publicAgentEnabled:!0,invertedMode:!1,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 cp=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];async function tr(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 cp){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,invertedMode:n.invertedMode??!1,days:i,closedDates:[...n.closedDates??[]].sort()}}else{const n=er();n.publicAgentEnabled=t.publicAgentEnabled,e.openingHoursForm=n}}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursLoading=!1}}}async function up(e){if(!(!e.client||!e.connected||e.openingHoursBusy)){e.openingHoursBusy=!0,e.openingHoursError=null;try{const t=e.openingHoursForm,n={};for(const a of cp){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,invertedMode:t.invertedMode||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",skipRestart:!0}),await tr(e),e.openingHoursSaved=!0,setTimeout(()=>{e.openingHoursSaved=!1},2e3)}catch(t){e.openingHoursError=String(t)}finally{e.openingHoursBusy=!1}}}const p0=Object.freeze(Object.defineProperty({__proto__:null,defaultOpeningHoursForm:er,loadOpeningHours:tr,saveOpeningHours:up},Symbol.toStringTag,{value:"Module"}));function h0(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 c=l.id??"";c&&i.push({phone:c,paired:((s=o.meta)==null?void 0:s.paired)===!0})}return i.sort((o,a)=>o.paired&&!a.paired?-1:!o.paired&&a.paired?1:0),i}function dp(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,a=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const d=c.match;if(!d||typeof d!="object"||(d.channel??"").toLowerCase()!=="whatsapp")continue;const v=d.peer;if(!v||typeof v!="object"||v.kind!=="dm")continue;const p=v.id??"";p&&(c.meta&&o.set(p,c.meta),d.accountId&&a.set(p,d.accountId))}const r=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const d=c.match;if(!d||typeof d!="object"||(d.channel??"").toLowerCase()!=="whatsapp")return!0;const v=d.peer;return!v||typeof v!="object"?!0:v.kind!=="dm"}),l=t.map(c=>{const d=i??a.get(c.phone),m={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};d&&(m.accountId=d);const v={agentId:n,match:m},p=o.get(c.phone);return p?v.meta=p:c.paired&&(v.meta={paired:!0}),v});return[...r,...l]}function g0(e,t="admin"){if(!e)return[];const n=e.bindings;if(!Array.isArray(n))return[];const i=[];for(const s of n){if(!s||typeof s!="object"||s.agentId!==t&&s.agentId!=="management")continue;const o=s.match;if(!o||typeof o!="object"||(o.channel??"").toLowerCase()!=="telegram")continue;const r=o.peer;if(!r||typeof r!="object"||r.kind!=="dm")continue;const l=r.id??"";l&&i.push({username:l})}return i}function pp(e,t,n="admin",i){const s=r=>r===n||r==="management",o=e.filter(r=>{if(!r||typeof r!="object"||!s(r.agentId))return!0;const l=r.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="telegram")return!0;const d=l.peer;return!d||typeof d!="object"?!0:d.kind!=="dm"}),a=t.map(r=>{const l={channel:"telegram",peer:{kind:"dm",id:r.username}};return i&&(l.accountId=i),{agentId:n,match:l}});return[...o,...a]}async function vn(e,t){if(!e.client||!e.connected)return;if(!t){e.adminPhones=[],e.telegramAdmins=[];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=he(s??{}),e.adminPhones=h0(s,n),e.telegramAdmins=g0(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function hp(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=he(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],d=[...e.adminPhones,{phone:o}],m=dp(c,d,s,i);bs(l,["bindings"],m);const v=(r=e.configSnapshot)==null?void 0:r.hash;if(!v){e.adminsError="Config hash missing; reload and retry.";return}const p=fe(l);await e.client.request("config.set",{raw:p,baseHash:v}),await vn(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function gp(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=he(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],d=e.adminPhones.filter(b=>b.phone!==t),m=dp(c,d,s,i);bs(l,["bindings"],m);const v=(r=e.configSnapshot)==null?void 0:r.hash;if(!v){e.adminsError="Config hash missing; reload and retry.";return}const p=fe(l);await e.client.request("config.set",{raw:p,baseHash:v}),await vn(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function fp(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=t.trim();if(!/^\d{4,15}$/.test(o)){e.adminsError="Enter a numeric Telegram user ID (e.g. 123456789). Find yours via @userinfobot in Telegram.";return}if(e.telegramAdmins.some(l=>l.username===o)){e.adminsError="This user ID is already an admin.";return}e.adminsSaving=!0,e.adminsError=null;try{const l=he(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],d=[...e.telegramAdmins,{username:o}],m=pp(c,d,s,i);bs(l,["bindings"],m);const v=(r=e.configSnapshot)==null?void 0:r.hash;if(!v){e.adminsError="Config hash missing; reload and retry.";return}const p=fe(l);await e.client.request("config.set",{raw:p,baseHash:v}),await vn(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function mp(e,t,n,i){var o,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n;e.adminsSaving=!0,e.adminsError=null;try{const r=he(e.configForm??((o=e.configSnapshot)==null?void 0:o.config)??{}),l=r.bindings??[],c=e.telegramAdmins.filter(p=>p.username!==t),d=pp(l,c,s,i);bs(r,["bindings"],d);const m=(a=e.configSnapshot)==null?void 0:a.hash;if(!m){e.adminsError="Config hash missing; reload and retry.";return}const v=fe(r);await e.client.request("config.set",{raw:v,baseHash:m}),await vn(e,n)}catch(r){e.adminsError=String(r)}finally{e.adminsSaving=!1}}const f0=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:hp,addTelegramAdmin:fp,loadAdmins:vn,removeAdmin:gp,removeTelegramAdmin:mp},Symbol.toStringTag,{value:"Module"}));async function dt(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 yp(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 dt(e,i)}catch(a){e.contactsError=String(a)}finally{e.contactsSaving=!1}}async function vp(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 dt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function ra(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 dt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function bp(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 dt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const m0=Object.freeze(Object.defineProperty({__proto__:null,addContact:yp,deleteContact:vp,deleteContactField:bp,loadContacts:dt,setContactField:ra},Symbol.toStringTag,{value:"Module"}));let Ct=null,zi=null,Ki=null;const To=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function Vt(){Ct&&(clearInterval(Ct),Ct=null),zi&&(clearInterval(zi),zi=null),Ki&&(clearTimeout(Ki),Ki=null)}function Rn(e){if(e.workspaces.length===0)return;const{hasPins:t,authenticated:n,adminUsername:i,master:s}=e.accessState,o=t&&n?i??(s?"Admin":null):null;return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:a=>e.handleWorkspaceSelect(a),hasPins:t,isMaster:s,onLogout:()=>e.handleLogout(),loggedInAs:o,auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function y0(e){if(e.workspaces.length===0)return;const{hasPins:t,authenticated:n,adminUsername:i,master:s}=e.accessState,o=t&&n?i??(s?"Admin":null):null;return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:a=>e.handleWorkspaceSelect(a),onAddAccount:()=>{e.addingWorkspace=!0},hasPins:t,isMaster:s,onLogout:()=>e.handleLogout(),loggedInAs:o,auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function v0(e){const t=Me(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 Vn(e){const t=Me(e);return(t==null?void 0:t.accountId)??void 0}function b0(e){var i;const t=Me(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 w0(e){return e.selectedWorkspace??void 0}function Me(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}function Ri(e){const t=Me(e);return t?(t.displayName??t.name).trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9_-]/g,""):null}const k0=/^data:/i,x0=/^https?:\/\//i;function Zl(e){var r,l;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=ha(e.sessionKey),i=(n==null?void 0:n.agentId)??((l=e.agentsList)==null?void 0:l.defaultId)??"main",s=t.find(c=>c.id===i),o=s==null?void 0:s.identity,a=(o==null?void 0:o.avatarUrl)??(o==null?void 0:o.avatar);if(a)return k0.test(a)||x0.test(a)?a:o==null?void 0:o.avatarUrl}function $0(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 S0(e){var s,o;if(!e)return{configured:!1,running:!1,botUsername:null,mode:null,lastError:null};const t=(s=e.channelAccounts)==null?void 0:s.telegram;if(!Array.isArray(t)||t.length===0)return{configured:!1,running:!1,botUsername:null,mode:null,lastError:null};const n=t[0],i=n.probe;return{configured:n.configured??!1,running:n.running??!1,botUsername:i!=null&&i.ok?((o=i.bot)==null?void 0:o.username)??null:null,mode:n.mode??null,lastError:n.lastError??null}}async function Li(e,t){e.telegramPairingLoading=!0;try{const n=await e.client.request("channels.telegram.pairing.list",{accountId:t});e.telegramPairingRequests=n??[]}catch{e.telegramPairingRequests=[]}finally{e.telegramPairingLoading=!1}}function A0(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 C0(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,c;return((l=r.match)==null?void 0:l.channel)==="imessage"&&((c=r.meta)==null?void 0:c.imessageOwner)});if(!i)return null;const s=i.agentId;for(const r of e.workspaces)if(r.agents.some(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 qi(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:()=>Vn(e),set:()=>{}}}),t}function E0(){requestAnimationFrame(()=>{const e=document.querySelector(".wa-messages");e&&(e.scrollTop=e.scrollHeight)})}function T0(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:Vn(e),onSelectConversation:t=>{const n=qi(e);pk(n,t).then(()=>{e.requestUpdate(),E0()})},onBack:()=>{e.waSelectedJid=null,e.waMessages=[],e.waGroupInfo=null,e.requestUpdate()},onSearchChange:t=>{e.waSearchQuery=t,e.requestUpdate()},onActivationChange:(t,n)=>{const i=qi(e);hk(i,t,n).then(()=>e.requestUpdate())},onRefresh:()=>{const t=qi(e);Qd(t).then(()=>e.requestUpdate())},requestUpdate:()=>e.requestUpdate()}}function P0(e){var t,n,i,s,o,a,r,l,c,d,m,v;if(e.embeddingDownloading&&!e.publicChat)return u`
6082
6077
  <div class="setup-container">
6083
6078
  <div class="setup-card" style="text-align:center; max-width:420px;">
6084
6079
  <div class="setup-spinner"></div>
@@ -6099,7 +6094,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
6099
6094
  <p>Connecting...</p>
6100
6095
  </div>
6101
6096
  </div>
6102
- `;if(!e.publicChatAuthenticated)return l0({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:C=>{var T;e.publicChatSessionKey=C,e.sessionKey=C,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const A=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";e.chatMessage=Yn(A,C),se(async()=>{const{loadChatHistory:M}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:M}},void 0,import.meta.url).then(({loadChatHistory:M})=>{M(e)})},onAuthStepChange:C=>{e.publicChatAuthStep=C},requestUpdate:()=>{e.requestUpdate()}});const p=(t=e.publicChatConfig)==null?void 0:t.greeting,b=e.chatMessages,x=!e.chatLoading&&p?[{role:"assistant",content:[{type:"text",text:p}],timestamp:0},...Array.isArray(b)?b:[]]:b;return xx({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:x,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Yl(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:C=>{e.chatMessage=C,e.chatSuggestions=[],e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),se(async()=>{const{loadChatHistory:C}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:C}},void 0,import.meta.url).then(({loadChatHistory:C})=>{C(e)})),onDraftChange:C=>{var T;e.chatMessage=C;const A=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";Rr(A,e.sessionKey,C)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:C=>e.chatAttachments=C,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:C=>e.removeQueuedMessage(C),onChatScroll:C=>e.handleChatScroll(C),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}})}if(e.connected&&e.accessState.checked){const{accessState:p}=e;if(p.hasPins&&!p.authenticated)return Ol({show:!0,isFirstTime:!1,accounts:p.accounts,error:p.error,busy:p.busy,onSubmit:(b,x)=>{x!=null&&e.handlePinSubmit(b,x)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(b,x,C)=>e.handleChangePin(b,x,C)});if(!p.hasMasterPin&&!p.authenticated&&e.setup)return Ol({show:!0,isFirstTime:!0,accounts:[],error:p.error,busy:p.busy,onSubmit:b=>e.handleSetMasterPin(b)});if(!p.hasMasterPin&&!p.authenticated&&!e.setup)return window.location.href="/setup",w}if(e.setup){const p=w0(e.channelsSnapshot),b=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],x=x0(e.channelsSnapshot),C=k0(e.channelsSnapshot),A=((o=(s=e.channelsSnapshot)==null?void 0:s.channelAccounts)==null?void 0:o.telegram)??[],T=$0(e),M=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},N=()=>{const y=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=To[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,Vt(),Ct=setInterval(()=>{const k=(Date.now()-y)/1e3,S=Math.min(95,95*(1-Math.exp(-k/30)));e.tailscaleConnectProgress=Math.round(S);let P=To[0][1];for(const[I,B]of To)k>=I&&(P=B);e.tailscaleConnectMessage=P},500)};return Qm({connected:e.connected,serverPlatform:((r=(a=e.hello)==null?void 0:a.server)==null?void 0:r.platform)??null,assistantName:e.assistantName,currentStep:e.setupStep,licenseKey:e.licenseKey,licenseBusy:e.licenseBusy,licenseValid:e.licenseValid,licenseMessage:e.licenseMessage,licenseTier:e.licenseTier,licenseDeviceId:e.licenseDeviceId,licenseStoredKey:e.licenseStoredKey,onLicenseKeyChange:y=>e.handleLicenseKeyChange(y),onLicenseActivate:()=>e.handleLicenseActivate(),onLicenseRemove:async()=>{await e.handleLicenseRemove(),e.licenseRemoveConfirm=!1},licenseRemoveConfirm:e.licenseRemoveConfirm,onLicenseRemoveConfirm:()=>{e.licenseRemoveConfirm=!0},onLicenseRemoveCancel:()=>{e.licenseRemoveConfirm=!1},authConnected:e.authConnected,authBusy:e.authBusy,authMessage:e.authMessage,authUrl:e.authUrl,authCodeInput:e.authCodeInput,authExpiresIn:e.authExpiresIn,authRefreshToken:e.authRefreshToken,claudeAuthModalOpen:e.claudeAuthModalOpen,authRefreshTokenInput:e.authRefreshTokenInput,authRefreshTokenBusy:e.authRefreshTokenBusy,authRefreshTokenError:e.authRefreshTokenError,onClaudeAuthModalOpen:()=>e.handleClaudeAuthModalOpen(),onClaudeAuthModalClose:()=>e.handleClaudeAuthModalClose(),onRefreshTokenInputChange:y=>{e.authRefreshTokenInput=y},onImportRefreshToken:()=>e.handleImportRefreshToken(),whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:p,whatsappAccounts:b,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:y=>{e.addingWhatsAppAccount=y,e.whatsappAccountError=null},onSetNewWhatsAppAccountName:y=>{e.newWhatsAppAccountName=y},onSetNewWhatsAppAccountProvider:y=>{e.newWhatsAppAccountProvider=y,e.whatsappAccountError=null},onSetNewCloudPhoneNumberId:y=>{e.newCloudPhoneNumberId=y},onSetNewCloudBusinessAccountId:y=>{e.newCloudBusinessAccountId=y},onSetNewCloudAccessToken:y=>{e.newCloudAccessToken=y},onSetNewCloudWebhookVerifyToken:y=>{e.newCloudWebhookVerifyToken=y},onAddWhatsAppBaileysAccount:async y=>{await e.handleAddWhatsAppAccount(y)},onAddCloudApiAccount:async(y,k)=>{await e.handleAddCloudApiAccount(y,k)},gatewayHealthy:e.gatewayHealthy,gatewayHealthLoading:e.gatewayHealthLoading,gatewayHealthMessage:e.gatewayHealthMessage,gatewayRestartBusy:e.gatewayRestartBusy,updateAvailable:e.updateAvailable,currentVersion:e.currentVersion,latestVersion:e.latestVersion,updateChecking:e.updateChecking,updateRunning:e.updateRunning,updateMessage:e.updateMessage,updateProgressSteps:e.updateProgressSteps,updateLastResult:e.updateLastResult,onUpdateCheck:()=>e.handleUpdateCheck(),onUpdateRun:()=>e.handleUpdateRun(),onUpdateDismissResult:()=>e.handleUpdateDismissResult(),uninstallConfirm:e.uninstallConfirm,uninstallBusy:e.uninstallBusy,uninstallDone:e.uninstallDone,uninstallError:e.uninstallError,uninstallConfirmText:e.uninstallConfirmText,onUninstallConfirm:()=>e.handleUninstallConfirm(),onUninstallCancel:()=>e.handleUninstallCancel(),onUninstallConfirmTextChange:y=>e.handleUninstallConfirmTextChange(y),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onDisconnect:()=>{e.handleDisconnect()},onSubmitAuthCode:y=>e.handleAuthSubmitCode(y),onAuthCodeChange:y=>e.handleAuthCodeChange(y),onWhatsAppRelink:async y=>{await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await Q(e,!0),e.requestUpdate())},onWhatsAppUnlink:async y=>{await e.handleWhatsAppLogout(y)},onWhatsAppReset:async y=>{await e.handleWhatsAppLogout(y),await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await Q(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await Q(e,!0),await e.handleGatewayHealthCheck()},onRefreshGatewayStatus:()=>e.handleGatewayHealthCheck(),onRefreshWhatsAppStatus:()=>Q(e,!0),onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),Q(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:y=>e.handleRemoveWhatsAppAccount(y),workspaces:e.workspaces,workspacesLoading:e.workspacesLoading,workspacesError:e.workspacesError,addingWorkspace:e.addingWorkspace,newWorkspaceName:e.newWorkspaceName,newWorkspacePath:e.newWorkspacePath,workspaceSaving:e.workspaceSaving,workspaceRemoveConfirm:e.workspaceRemoveConfirm,newWorkspacePin:e.newWorkspacePin,onSetNewWorkspacePin:y=>{e.newWorkspacePin=y},onWorkspaceCreate:async(y,k)=>{const S=e.newWorkspacePin;await e.handleWorkspaceCreate(y,k),S.match(/^\d{4,6}$/)&&(await dg(e,y,S),e.newWorkspacePin="")},onWorkspaceRemove:y=>e.handleWorkspaceRemove(y),onSetAddingWorkspace:y=>{e.addingWorkspace=y},onSetNewWorkspaceName:y=>{e.newWorkspaceName=y},onSetNewWorkspacePath:y=>{e.newWorkspacePath=y},onSetWorkspaceRemoveConfirm:y=>{e.workspaceRemoveConfirm=y},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(y,k)=>e.handleWorkspaceRename(y,k),whatsappAgentEnabled:(()=>{const y=Me(e),k=y==null?void 0:y.accountId,S=k?b.find(P=>P.accountId===k):b[0];return(S==null?void 0:S.dmPolicy)!=="disabled"})(),onWhatsAppAgentEnabledToggle:async()=>{var B;const y=Me(e),k=y==null?void 0:y.accountId,S=k?b.find(L=>L.accountId===k):b[0];if(!S)return;const P=S.dmPolicy!=="disabled",I=P?{dmPolicy:"disabled",groupPolicy:"disabled"}:{dmPolicy:"open",allowFrom:["*"],groupPolicy:"open"};try{const L=await e.client.request("config.get"),F=L.config,q=(B=F==null?void 0:F.channels)==null?void 0:B.whatsapp,ue=((q==null?void 0:q.accounts)??{})[S.accountId]?{channels:{whatsapp:{accounts:{[S.accountId]:I}}}}:{channels:{whatsapp:I}};await e.client.request("config.patch",{raw:JSON.stringify(ue),baseHash:L.hash,note:`WhatsApp agent → ${P?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),await Q(e,!1)}catch(L){console.error("Agent enabled toggle failed:",L)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:x.configured,imessageRunning:x.running,imessageConnected:x.connected,imessageLastError:x.lastError,imessageSelfChatMode:x.selfChatMode,imessageCliPath:x.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:T,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),k=y.config,S=(k==null?void 0:k.bindings)??[],P=Me(e),I=P==null?void 0:P.agents.find(Y=>Y.id.endsWith("-admin")||Y.id==="admin"),B=(I==null?void 0:I.id)??"admin",L=S.filter(Y=>{var ue;return((ue=Y.match)==null?void 0:ue.channel)!=="imessage"}),F=[{agentId:B,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],q=[...L,...F];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:q}),baseHash:y.hash,note:"Enable iMessage (self-chat) for "+((P==null?void 0:P.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Q(e,!0),He(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await Q(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),k=y.config,P=((k==null?void 0:k.bindings)??[]).filter(I=>{var B;return((B=I.match)==null?void 0:B.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:P}),baseHash:y.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Q(e,!0),He(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),k=y.config,S=(k==null?void 0:k.bindings)??[],P=Me(e),I=P==null?void 0:P.agents.find(q=>q.id.endsWith("-admin")||q.id==="admin"),B=(I==null?void 0:I.id)??"admin",L=S.filter(q=>{var Y;return((Y=q.match)==null?void 0:Y.channel)!=="imessage"}),F=[{agentId:B,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:[...L,...F]}),baseHash:y.hash,note:"Reassign iMessage to "+((P==null?void 0:P.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Q(e,!0),He(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},telegramConfigured:C.configured,telegramRunning:C.running,telegramBotUsername:C.botUsername,telegramMode:C.mode,telegramLastError:C.lastError,telegramBusy:e.telegramBusy,telegramSettingsOpen:e.telegramSettingsOpen,telegramConnectOpen:e.telegramConnectOpen,telegramConnectToken:e.telegramConnectToken,telegramProbeResult:e.telegramProbeResult,telegramProbing:e.telegramProbing,telegramError:e.telegramError,onTelegramConnect:()=>{e.telegramConnectOpen=!0,e.telegramAddingBot=!0,e.telegramConnectToken="",e.telegramNewBotName="",e.telegramNewBotDmPolicy="open",e.telegramNewBotAdminRouting=!0,e.telegramProbeResult=null,e.telegramError=null,e.telegramBotError=null},onTelegramConnectClose:()=>{e.telegramConnectOpen=!1,e.telegramAddingBot=!1,e.telegramConnectToken="",e.telegramNewBotName="",e.telegramNewBotDmPolicy="open",e.telegramNewBotAdminRouting=!0,e.telegramProbeResult=null,e.telegramError=null,e.telegramBotError=null},onTelegramTokenChange:y=>{e.telegramConnectToken=y},onTelegramProbe:()=>{Ic(e)},onTelegramSave:()=>{Rc(e)},onTelegramSettingsOpen:()=>{e.telegramSettingsOpen=!0;const y=Vn(e)??"default";Li(e,y)},onTelegramSettingsClose:()=>{e.telegramSettingsOpen=!1},onTelegramDisconnect:()=>{Lc(e)},onRefreshTelegramStatus:()=>{Q(e,!0)},onTelegramAddBot:()=>{var k;const y=((k=e.telegramProbeResult)==null?void 0:k.username)??e.telegramNewBotName;Bc(e,y,e.telegramConnectToken,e.telegramNewBotDmPolicy,e.telegramNewBotAdminRouting)},onTelegramRemoveBot:y=>{Dc(e,y)},onTelegramDmPolicyChange:(y,k)=>{Nc(e,y,k)},onTelegramAdminRoutingChange:(y,k)=>{Uc(e,y,k)},onTelegramWhitelistAdd:(y,k)=>{Oc(e,y,k)},onTelegramWhitelistRemove:(y,k)=>{Fc(e,y,k)},onTelegramNewBotNameChange:y=>{e.telegramNewBotName=y},onTelegramNewWhitelistUsernameChange:y=>{e.telegramNewWhitelistUsername=y},telegramAddingBot:e.telegramAddingBot,telegramNewBotName:e.telegramNewBotName,telegramNewBotDmPolicy:e.telegramNewBotDmPolicy,telegramNewBotAdminRouting:e.telegramNewBotAdminRouting,onTelegramNewBotDmPolicyChange:y=>{e.telegramNewBotDmPolicy=y},onTelegramNewBotAdminRoutingChange:y=>{e.telegramNewBotAdminRouting=y},telegramBotSaving:e.telegramBotSaving,telegramBotError:e.telegramBotError,telegramDmPolicySaving:e.telegramDmPolicySaving,telegramWhitelistSaving:e.telegramWhitelistSaving,telegramWhitelistError:e.telegramWhitelistError,telegramNewWhitelistUsername:e.telegramNewWhitelistUsername,telegramExpandedBotId:e.telegramExpandedBotId,onTelegramExpandBot:y=>{e.telegramExpandedBotId=y},telegramAccounts:A,telegramPairingRequests:e.telegramPairingRequests,telegramPairingLoading:e.telegramPairingLoading,telegramPairingAccountId:Vn(e)??"default",telegramPairingActioning:e.telegramPairingActioning,onTelegramPairingLoad:y=>{Li(e,y)},onTelegramPairingApprove:async(y,k)=>{e.telegramPairingActioning=new Set([...e.telegramPairingActioning,k]);try{await e.client.request("channels.telegram.pairing.approve",{accountId:y,code:k}),e.telegramPairingRequests=e.telegramPairingRequests.filter(S=>S.code!==k)}catch{await Li(e,y)}finally{e.telegramPairingActioning=new Set([...e.telegramPairingActioning].filter(S=>S!==k))}},onTelegramPairingReject:async(y,k)=>{e.telegramPairingActioning=new Set([...e.telegramPairingActioning,k]);try{await e.client.request("channels.telegram.pairing.reject",{accountId:y,code:k}),e.telegramPairingRequests=e.telegramPairingRequests.filter(S=>S.code!==k)}catch{await Li(e,y)}finally{e.telegramPairingActioning=new Set([...e.telegramPairingActioning].filter(S=>S!==k))}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:y=>{var k,S,P,I,B,L;if(e.infoModalOpen=y,y==="remote-access"){const F=((k=e.tailscaleStatus)==null?void 0:k.tailnetUrl)??((S=e.tailscaleStatus)!=null&&S.hostname?`https://${e.tailscaleStatus.hostname}`:null);F&&!e.remoteAccessQrDataUrl&&e.client.request("qr.generate",{url:F}).then(q=>{e.remoteAccessQrDataUrl=(q==null?void 0:q.dataUrl)??null}).catch(()=>{})}else if(y==="cloudflare"){const F=((P=e.tunnelStatus)==null?void 0:P.publicUrl)??null;F&&!e.tunnelQrDataUrl&&e.client.request("qr.generate",{url:F}).then(q=>{e.tunnelQrDataUrl=(q==null?void 0:q.dataUrl)??null}).catch(()=>{})}else if(y==="public-chat"){const F=((I=e.tunnelStatus)==null?void 0:I.publicChatBaseUrl)??null,q=((B=e.tailscaleStatus)==null?void 0:B.publicUrl)??((L=e.tailscaleStatus)==null?void 0:L.tailnetUrl)??null,Y=Ri(e),ue=F&&Y?`${F}/chat/${encodeURIComponent(Y)}`:q&&Y?`${q}/public/chat/${encodeURIComponent(Y)}`:null;ue&&!e.publicChatQrDataUrl&&e.client.request("qr.generate",{url:ue}).then(Ve=>{e.publicChatQrDataUrl=(Ve==null?void 0:Ve.dataUrl)??null}).catch(()=>{})}},onInfoModalClose:()=>{e.infoModalOpen=null},remoteAccessQrDataUrl:e.remoteAccessQrDataUrl??null,publicChatQrDataUrl:e.publicChatQrDataUrl??null,publicChatFullUrl:(()=>{var P,I,B;const y=((P=e.tunnelStatus)==null?void 0:P.publicChatBaseUrl)??null,k=((I=e.tailscaleStatus)==null?void 0:I.publicUrl)??((B=e.tailscaleStatus)==null?void 0:B.tailnetUrl)??null,S=Ri(e);return S?y?`${y}/chat/${encodeURIComponent(S)}`:k?`${k}/public/chat/${encodeURIComponent(S)}`:null:null})(),isMaster:e.accessState.master,apiKeyProviders:e.apiKeyProviders,apiKeyModalOpen:e.apiKeyModalOpen,apiKeyBusy:e.apiKeyBusy,apiKeyError:e.apiKeyError,apiKeySuccess:e.apiKeySuccess,apiKeySavingProvider:e.apiKeySavingProvider,onApiKeyModalOpen:()=>{e.apiKeyModalOpen=!0,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeyModalClose:()=>{e.apiKeyModalOpen=!1,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeySave:async(y,k)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await zl(e.client,y,k);const S=`${y} key saved`;e.apiKeySuccess=S,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Wi(e.client)}catch{}y==="anthropic"&&await e.handleAuthStatusCheck(),setTimeout(()=>{e.apiKeySuccess===S&&(e.apiKeySuccess=null)},2500)}catch(S){e.apiKeyError=S instanceof Error?S.message:"Failed to save key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyRemove:async y=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await zx(e.client,y);const k=`${y} key removed`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Wi(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyDisable:async(y,k)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Kx(e.client,y,k);const S=`${y} ${k?"disabled":"enabled"}`;e.apiKeySuccess=S,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Wi(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===S&&(e.apiKeySuccess=null)},2500)}catch(S){e.apiKeyError=S instanceof Error?S.message:`Failed to ${k?"disable":"enable"} key`,e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},authApiKeyMode:e.authApiKeyMode,authApiKeyInput:e.authApiKeyInput,authApiKeyBusy:e.authApiKeyBusy,authApiKeyError:e.authApiKeyError,onAuthApiKeyToggle:()=>{e.authApiKeyMode=!e.authApiKeyMode,e.authApiKeyError=null},onAuthApiKeyChange:y=>{e.authApiKeyInput=y},onAuthApiKeySubmit:async()=>{const y=e.authApiKeyInput.trim();if(y){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await zl(e.client,"anthropic",y),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(k){e.authApiKeyError=k instanceof Error?k.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var k;const y=e.selectedWorkspace??((k=e.workspaces[0])==null?void 0:k.name);return y?e.accessState.accounts.some(S=>S.id===y):!1})(),accountPinModalOpen:e.accountPinModalOpen,accountPinBusy:e.accountPinBusy,accountPinError:e.accountPinError,accountPinSuccess:e.accountPinSuccess,onAccountPinModalOpen:()=>{e.accountPinModalOpen=!0,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinModalClose:()=>{e.accountPinModalOpen=!1,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinSave:(y,k)=>{var P;const S=e.selectedWorkspace??((P=e.workspaces[0])==null?void 0:P.name);S&&e.handleAccountPinSave(S,y,k)},publicChatAccountId:Ri(e),publicChatSettingsOpen:e.publicChatSettingsOpen,onPublicChatSettingsOpen:()=>{e.publicChatSettingsOpen=!0},onPublicChatSettingsClose:()=>{e.publicChatSettingsOpen=!1},publicChatWidgetModalOpen:e.publicChatWidgetModalOpen,onPublicChatWidgetModalOpen:()=>{e.publicChatWidgetModalOpen=!0},onPublicChatWidgetModalClose:()=>{e.publicChatWidgetModalOpen=!1},publicChatEnabled:(()=>{var S;const y=(S=e.configSnapshot)==null?void 0:S.config,k=y==null?void 0:y.publicChat;return(k==null?void 0:k.enabled)===!0})(),publicChatAuthMode:(()=>{var B,L;const y=(B=e.configSnapshot)==null?void 0:B.config,k=y==null?void 0:y.publicChat,S=e.selectedWorkspace??"",P=k==null?void 0:k.accountSettings,I=((L=P==null?void 0:P[S])==null?void 0:L.auth)??(k==null?void 0:k.auth);return I==="verified"||I==="choice"?I:"anonymous"})(),publicChatGreeting:(()=>{var I;const y=(I=e.configSnapshot)==null?void 0:I.config,k=y==null?void 0:y.publicChat,S=k==null?void 0:k.greetings,P=e.selectedWorkspace??"";return(P&&(S==null?void 0:S[P]))??""})(),publicChatGreetingBusy:e.publicChatGreetingBusy,onPublicChatGreetingToggle:async()=>{var k;if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const S=await e.client.request("config.get"),P=S.config,I=(k=P==null?void 0:P.publicChat)==null?void 0:k.greetings;if(I==null?void 0:I[y]){const L={publicChat:{greetings:{[y]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(L),baseHash:S.hash,note:`Public chat greeting → disabled (${y})`,skipRestart:!0})}else{const L=await e.client.request("public.greeting.generate",{accountId:y});if(L!=null&&L.ok&&L.greeting){const F=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:L.greeting}}}),baseHash:F.hash,note:`Public chat greeting → enabled (${y})`,skipRestart:!0})}}e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Public chat greeting toggle failed:",S)}finally{e.publicChatGreetingBusy=!1}}},onPublicChatGreetingSave:async y=>{const k=e.selectedWorkspace??"";if(k)try{const S=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[k]:y}}}),baseHash:S.hash,note:`Public chat greeting text updated (${k})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Public chat greeting save failed:",S)}},onPublicChatGreetingRegenerate:async()=>{if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const k=await e.client.request("public.greeting.generate",{accountId:y});if(k!=null&&k.ok&&k.greeting){const S=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:k.greeting}}}),baseHash:S.hash,note:`Public chat greeting regenerated (${y})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}}catch(k){console.error("Public chat greeting regeneration failed:",k)}finally{e.publicChatGreetingBusy=!1}}},publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var y;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const k=await e.client.request("config.get"),S=k.config,P=((y=S==null?void 0:S.publicChat)==null?void 0:y.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!P}}),baseHash:k.hash,note:`Public chat → ${P?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),e.publicChatQrDataUrl=null}catch(k){console.error("Public chat toggle failed:",k)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async y=>{if(e.publicChatToggleBusy)return;const k=e.selectedWorkspace??"";if(k){e.publicChatToggleBusy=!0;try{const S=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{accountSettings:{[k]:{auth:y}}}}),baseHash:S.hash,note:`Public chat auth → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Public chat auth mode change failed:",S)}finally{e.publicChatToggleBusy=!1}}},publicChatEmailFrom:(()=>{var S,P;const y=(S=e.configSnapshot)==null?void 0:S.config,k=(P=y==null?void 0:y.publicChat)==null?void 0:P.email;return(k==null?void 0:k.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var B,L;const y=(B=e.configSnapshot)==null?void 0:B.config,k=y==null?void 0:y.publicChat,S=e.selectedWorkspace??"",P=k==null?void 0:k.accountSettings,I=((L=P==null?void 0:P[S])==null?void 0:L.verifyMethods)??(k==null?void 0:k.verifyMethods);return Array.isArray(I)?I:["whatsapp","sms"]})(),onPublicChatEmailSave:async(y,k)=>{if(e.publicChatEmailBusy)return;const S=e.selectedWorkspace??"";if(S){e.publicChatEmailBusy=!0;try{const P=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{email:{from:y||void 0},accountSettings:{[S]:{verifyMethods:k}}}}),baseHash:P.hash,note:"Update email verification settings for public chat",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(P){console.error("Email verification save failed:",P)}finally{e.publicChatEmailBusy=!1}}},brandAccentColor:(()=>{var S;const y=e.selectedWorkspace;return y?((S=Ke()[y])==null?void 0:S.accentColor)??"":""})(),brandBackgroundColor:(()=>{var S;const y=e.selectedWorkspace;return y?((S=Ke()[y])==null?void 0:S.backgroundColor)??"":""})(),brandHasLogo:(()=>{var S;const y=e.selectedWorkspace;return y?!!((S=Ke()[y])!=null&&S.logoUrl):!1})(),agentSettingsOpen:e.agentSettingsOpen,agentSettingsAgents:(()=>{var P,I;const y=Me(e);if(!y)return[];const k=(P=e.configSnapshot)==null?void 0:P.config,S=(I=k==null?void 0:k.agents)==null?void 0:I.list;return y.agents.map(B=>{var ue;const L=Array.isArray(S)?S.find(Ve=>Ve.id===B.id):void 0,F=L==null?void 0:L.model,q=typeof F=="string"?F:(F==null?void 0:F.primary)??null,Y=B.id.endsWith("-admin")||B.id==="admin";return{id:B.id,label:Y?"Admin":"Public",model:(q==null?void 0:q.trim())||null,thinkingLevel:((ue=L==null?void 0:L.thinkingLevel)==null?void 0:ue.trim())||null}})})(),agentSettingsModelCatalog:e.chatModelCatalog??[],memoryProvider:(()=>{var S,P,I;const y=(S=e.configSnapshot)==null?void 0:S.config,k=(I=(P=y==null?void 0:y.agents)==null?void 0:P.defaults)==null?void 0:I.memorySearch;return typeof(k==null?void 0:k.provider)=="string"&&k.provider?k.provider:"local"})(),memoryFallback:(()=>{var S,P,I;const y=(S=e.configSnapshot)==null?void 0:S.config,k=(I=(P=y==null?void 0:y.agents)==null?void 0:P.defaults)==null?void 0:I.memorySearch;return typeof(k==null?void 0:k.fallback)=="string"&&k.fallback?k.fallback:"none"})(),onAgentSettingsToggle:()=>{e.agentSettingsOpen=!e.agentSettingsOpen},onAgentModelChange:async(y,k)=>{try{const S=await e.client.request("config.get"),P=S.config,I=(P==null?void 0:P.agents)??{},B=Array.isArray(I.list)?[...I.list]:[],L=B.findIndex(q=>q.id===y);if(k)L>=0?B[L]={...B[L],model:k}:B.push({id:y,model:k});else if(L>=0){const{model:q,...Y}=B[L];Object.keys(Y).length<=1?B.splice(L,1):B[L]=Y}const F=B.length>0?{agents:{list:B}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(F),baseHash:S.hash,note:`Agent ${y} model → ${k||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Agent model change failed:",S)}},onAgentThinkingChange:async(y,k)=>{try{const S=await e.client.request("config.get"),P=S.config,I=(P==null?void 0:P.agents)??{},B=Array.isArray(I.list)?[...I.list]:[],L=B.findIndex(Y=>Y.id===y),F=k==="off"?void 0:k;if(F)L>=0?B[L]={...B[L],thinkingLevel:F}:B.push({id:y,thinkingLevel:F});else if(L>=0){const{thinkingLevel:Y,...ue}=B[L];Object.keys(ue).length<=1?B.splice(L,1):B[L]=ue}const q=B.length>0?{agents:{list:B}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(q),baseHash:S.hash,note:`Agent ${y} thinking → ${F||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Agent thinking change failed:",S)}},onMemoryProviderChange:async y=>{try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{provider:y}}}}),baseHash:k.hash,note:`Memory search provider → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Memory provider change failed:",k)}},onMemoryFallbackChange:async y=>{try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{fallback:y}}}}),baseHash:k.hash,note:`Memory search fallback → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Memory fallback change failed:",k)}},brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async y=>{var S;const k=e.selectedWorkspace;if(!(!k||e.brandingBusy)){e.brandingBusy=!0;try{const P=await e.client.request("config.get"),I=P.config,B=((S=I==null?void 0:I.workspaces)==null?void 0:S[k])??{},L=B.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[k]:{...B,brand:{...L,accentColor:y}}}}),baseHash:P.hash,note:`Brand accent → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const F=Ke();F[k]||(F[k]={}),F[k].accentColor=y,Nn(k)}catch(P){console.error("Brand accent change failed:",P)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async y=>{var S;const k=e.selectedWorkspace;if(!(!k||e.brandingBusy)){e.brandingBusy=!0;try{const P=await e.client.request("config.get"),I=P.config,B=((S=I==null?void 0:I.workspaces)==null?void 0:S[k])??{},L=B.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[k]:{...B,brand:{...L,backgroundColor:y}}}}),baseHash:P.hash,note:`Brand background → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const F=Ke();F[k]||(F[k]={}),F[k].backgroundColor=y,Nn(k)}catch(P){console.error("Brand background change failed:",P)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async y=>{const k=e.selectedWorkspace;if(console.log(`[brand-upload] file=${y.name} type=${y.type} size=${y.size} ws=${k} busy=${e.brandingBusy}`),!k||e.brandingBusy){console.warn(`[brand-upload] skipped: ws=${k} busy=${e.brandingBusy}`);return}e.brandingBusy=!0;try{const S=await y.arrayBuffer(),P=new Uint8Array(S);let I="";for(let q=0;q<P.length;q++)I+=String.fromCharCode(P[q]);const B=btoa(I);console.log(`[brand-upload] sending RPC: workspace=${k} base64Len=${B.length} mimeType=${y.type}`);const L=await e.client.request("brand.uploadLogo",{workspace:k,data:B,mimeType:y.type});console.log("[brand-upload] RPC result:",L);const F=Ke();F[k]||(F[k]={}),F[k].logoUrl=`/brand-logo/${encodeURIComponent(k)}`}catch(S){console.error("Brand logo upload failed:",S),alert(`Brand logo upload failed: ${S.message||S}`)}finally{e.brandingBusy=!1}},onBrandLogoRemove:async()=>{const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:y});const k=Ke();k[y]&&delete k[y].logoUrl}catch(k){console.error("Brand logo remove failed:",k)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var k;const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{const S=await e.client.request("config.get"),P=S.config,I=((k=P==null?void 0:P.workspaces)==null?void 0:k[y])??{},{brand:B,...L}=I;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[y]:{...L,brand:null}}}),baseHash:S.hash,note:"Brand reset to defaults",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");try{await e.client.request("brand.removeLogo",{workspace:y})}catch{}const F=Ke();delete F[y],Nn(y)}catch(S){console.error("Brand reset failed:",S)}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,N();try{const y=await e.client.request("tailscale.enable");y.authUrl?(Ct&&(clearInterval(Ct),Ct=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=y.authUrl,zi=setInterval(async()=>{try{const k=await e.client.request("tailscale.status");e.tailscaleStatus=k,e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,k.loggedIn&&(Vt(),e.tailscaleAuthUrl=null,e.tailscaleConnectSuccess=!0,e.tailscaleConnectMessage="Connected!",setTimeout(()=>{e.tailscaleConnectSuccess=!1,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1},1500))}catch{}},3e3),Ki=setTimeout(()=>{Vt(),e.tailscaleBusy&&(e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)},3e5)):y.alreadyLoggedIn?(Vt(),e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1):(Vt(),e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)}catch(y){console.error("Tailscale enable failed:",y),Vt(),e.tailscaleError=y.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleServeEnableUrl=null,e.tailscaleDisableConfirm=!1;try{await e.client.request("tailscale.serve.enable"),await M(),await new Promise(k=>setTimeout(k,350)),e.tailscaleDisableConfirm=!1}catch(k){console.error("Tailscale serve enable failed:",k);const S=k;(y=S.payload)!=null&&y.enableUrl&&(e.tailscaleServeEnableUrl=S.payload.enableUrl),e.tailscaleError=S.message||"Failed to enable Remote Access"}finally{e.tailscaleBusy=!1}}},onTailscaleServeDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleDisableConfirm=!1;try{await e.client.request("tailscale.serve.disable"),await M()}catch(y){console.error("Tailscale serve disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable"),await M()}catch(k){console.error("Tailscale funnel enable failed:",k);const S=k;(y=S.payload)!=null&&y.enableUrl&&(e.tailscaleFunnelEnableUrl=S.payload.enableUrl),e.tailscaleError=S.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 M()}catch(y){console.error("Tailscale funnel disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleDisableConfirmToggle:()=>{e.tailscaleBusy||(e.tailscaleDisableConfirm=!e.tailscaleDisableConfirm)},tunnelStatus:e.tunnelStatus,tunnelBusy:e.tunnelBusy,tunnelError:e.tunnelError,tunnelAuthUrl:e.tunnelAuthUrl,tunnelSetupStep:e.tunnelSetupStep,tunnelQrDataUrl:e.tunnelQrDataUrl,tunnelHostnameInput:e.tunnelHostnameInput,tunnelUsernameInput:e.tunnelUsernameInput,tunnelPasswordInput:e.tunnelPasswordInput,tunnelPasswordConfirmInput:e.tunnelPasswordConfirmInput,onTunnelInstall:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null;try{const y=await e.client.request("tunnel.install");y.ok||(e.tunnelError=y.error??"Install failed"),e.tunnelStatus=await e.client.request("tunnel.status")}catch(y){e.tunnelError=y.message||"Install failed"}finally{e.tunnelBusy=!1}}},onTunnelLogin:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null,e.tunnelAuthUrl=null;try{const y=await e.client.request("tunnel.login");if(y.authUrl){e.tunnelAuthUrl=y.authUrl,e.client.request("qr.generate",{url:y.authUrl}).then(B=>{e.tunnelQrDataUrl=(B==null?void 0:B.dataUrl)??null}).catch(()=>{});const k=async()=>{var B;try{if((await e.client.request("tunnel.loginStatus")).authenticated)return P(),e.tunnelAuthUrl=null,e.tunnelQrDataUrl=null,e.tunnelBusy=!1,e.tunnelStatus=await e.client.request("tunnel.status"),(B=e.tunnelStatus)!=null&&B.tunnelId||(e.tunnelSetupStep=3),!0}catch{}return!1};let S=null;const P=()=>{S!==null&&(clearInterval(S),S=null),document.removeEventListener("visibilitychange",I)},I=()=>{document.visibilityState==="visible"&&k()};document.addEventListener("visibilitychange",I),S=setInterval(()=>{k()},3e3),setTimeout(()=>{P(),e.tunnelAuthUrl&&(e.tunnelAuthUrl=null,e.tunnelBusy=!1,e.tunnelError="Authentication timed out. Make sure you have a domain registered with Cloudflare, then try again.")},3e5)}else e.tunnelStatus=await e.client.request("tunnel.status"),e.tunnelBusy=!1}catch(y){e.tunnelError=y.message||"Login failed",e.tunnelBusy=!1}}},onTunnelCreate:async()=>{var k,S;if(e.tunnelBusy)return;const y=(S=(k=e.tunnelStatus)==null?void 0:k.authorizedDomain)==null?void 0:S.trim();if(!y){e.tunnelError="No authorized domain found — complete Cloudflare login first";return}e.tunnelBusy=!0,e.tunnelError=null;try{const P=await e.client.request("tunnel.create",{domain:y});P.ok?(e.tunnelSetupStep=4,e.tunnelError=null):e.tunnelError=P.error??"Failed to create tunnel",e.tunnelStatus=await e.client.request("tunnel.status")}catch(P){e.tunnelError=P.message||"Failed to create tunnel"}finally{e.tunnelBusy=!1}},onTunnelSetRemotePassword:async()=>{var S,P,I;if(e.tunnelBusy)return;const y=(S=e.tunnelPasswordInput)==null?void 0:S.trim(),k=(P=e.tunnelPasswordConfirmInput)==null?void 0:P.trim();if(!y||y.length<8){e.tunnelError="Password must be at least 8 characters";return}if(y!==k){e.tunnelError="Passwords do not match";return}e.tunnelBusy=!0,e.tunnelError=null;try{const B=((I=e.tunnelUsernameInput)==null?void 0:I.trim())||"admin",L=await e.client.request("remoteAuth.setCredentials",{username:B,password:y});L.ok?(e.tunnelSetupStep=5,e.tunnelError=null):e.tunnelError=L.message??"Failed to set password",e.tunnelStatus=await e.client.request("tunnel.status")}catch(B){e.tunnelError=B.message||"Failed to set password"}finally{e.tunnelBusy=!1}},onTunnelEnable:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null;try{const y=await e.client.request("tunnel.enable");y.ok?(e.tunnelSetupStep=0,e.tunnelError=null):e.tunnelError=y.error??"Failed to enable tunnel",e.tunnelStatus=await e.client.request("tunnel.status"),e.publicChatQrDataUrl=null}catch(y){e.tunnelError=y.message||"Failed to enable tunnel"}finally{e.tunnelBusy=!1}}},onTunnelDisable:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null;try{const y=await e.client.request("tunnel.disable");y.ok||(e.tunnelError=y.error??"Failed to disable tunnel"),e.tunnelStatus=await e.client.request("tunnel.status")}catch(y){e.tunnelError=y.message||"Failed to disable tunnel"}finally{e.tunnelBusy=!1}}},onTunnelSetupStepChange:y=>{e.tunnelSetupStep=y,e.tunnelError=null},onTunnelHostnameChange:y=>{e.tunnelHostnameInput=y},onTunnelUsernameChange:y=>{e.tunnelUsernameInput=y},onTunnelPasswordChange:y=>{e.tunnelPasswordInput=y},onTunnelPasswordConfirmChange:y=>{e.tunnelPasswordConfirmInput=y},onTunnelLoginCancel:()=>{e.tunnelAuthUrl=null,e.tunnelQrDataUrl=null,e.tunnelBusy=!1},onTunnelErrorDismiss:()=>{e.tunnelError=null},wifiModalOpen:e.wifiModalOpen,onWifiModalToggle:()=>{e.wifiModalOpen=!e.wifiModalOpen,e.wifiModalOpen||(e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null)},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{var y;if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[k,S]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiNetworks=k.networks,S.connected&&S.signal==null&&((y=k.networks)!=null&&y.length)){const P=k.networks.find(I=>I.active)||k.networks.find(I=>I.ssid===S.ssid);P&&(S.signal=P.signal)}e.wifiStatus=S}catch(k){console.error("WiFi scan failed:",k),e.wifiError=k.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{var k;if(e.wifiBusy||!e.wifiSelectedSsid)return;const y=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const S=await e.client.request("wifi.connect",{ssid:y,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:S.connected,ssid:S.ssid,signal:null,ip:S.ip,savedSsid:S.ssid,autoconnect:!0},e.wifiBusy=!1;try{const[P,I]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(I.connected&&I.signal==null&&((k=P.networks)!=null&&k.length)){const B=P.networks.find(L=>L.active)||P.networks.find(L=>L.ssid===I.ssid);B&&(I.signal=B.signal)}e.wifiStatus=I}catch{}}catch(S){console.error("WiFi connect failed:",S),e.wifiError=S.message||"Failed to connect",e.wifiBusy=!1}},onWifiDisconnect:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.disconnect"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi disconnect failed:",y),e.wifiError=y.message||"Failed to disconnect"}finally{e.wifiBusy=!1}}},onWifiForget:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.forget"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi forget failed:",y),e.wifiError=y.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:y=>{e.wifiSelectedSsid=y,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:y=>{e.wifiPassword=y},networkPort:e.networkPort,networkHostname:e.networkHostname,networkPortInput:e.networkPortInput,networkHostnameInput:e.networkHostnameInput,networkModalOpen:e.networkModalOpen,networkBusy:e.networkBusy,networkError:e.networkError,networkSuccess:e.networkSuccess,onNetworkModalToggle:()=>{e.networkModalOpen=!e.networkModalOpen,e.networkModalOpen&&(e.networkPortInput=String(e.networkPort??""),e.networkHostnameInput=e.networkHostname,e.networkError=null,e.networkSuccess=null)},onNetworkPortChange:y=>{e.networkPortInput=y,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:y=>{e.networkHostnameInput=y,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const y=e.networkPortInput.trim(),k=Number.parseInt(y,10),S=e.networkHostnameInput.trim();if(!y||!Number.isFinite(k)||k<1024||k>65535){e.networkError="Port must be a number between 1024 and 65535",e.networkBusy=!1;return}const P=k!==e.networkPort,I=S!==e.networkHostname;if(!P&&!I){e.networkBusy=!1;return}try{I&&await e.client.request("network.setHostname",{hostname:S});const B={};P&&(B.gateway={port:k}),I&&(B.discovery={bonjourHostname:S});const L=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify(B),baseHash:L.hash,note:[P?`Port → ${k}`:null,I?`Hostname → ${S}`:null].filter(Boolean).join(", "),restartDelayMs:2e3}),e.networkSuccess="Saved — redirecting...";const F=window.location.protocol,q=I?`${S}.local`:window.location.hostname,Y=P?k:e.networkPort,ue=`${F}//${q}:${Y}/setup`;setTimeout(()=>{window.location.href=ue},1500)}catch(B){console.error("Network save failed:",B),e.networkError=B.message||"Failed to save network settings",e.networkBusy=!1}},wsProps:g0(e)})}if(e.filesPage){const p=m0(e);return Zf({connected:e.connected,wsProps:Rn(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:()=>{fn(e,p),xs(e,p)},onReindex:()=>hf(e,p),onSelectFile:b=>{e.filesPendingDeletePath=null,Iu(e,b,p)},onToggleSelectFile:b=>af(e,b,p),onToggleDir:b=>gf(e,b),onUpload:(b,x)=>cf(e,b,x,p),onNewFolder:(b,x)=>uf(e,b,x,p),onDownload:b=>Lu(e,b,p),onBulkDownload:()=>rf(e,p),onDelete:b=>{e.filesPendingDeletePath=null,df(e,b,p)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:b=>{e.filesPendingDeletePath=b||null},onMoveToDir:(b,x)=>lf(e,b,x,p),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:b=>{const x=e.filesSearchAgentId??p;ff(e,b,x)},onSearchAgentChange:b=>{e.filesSearchAgentId=b},onSearchClear:()=>{mf(e)},onSearchQueryChange:b=>{e.filesSearchQuery=b}})}if(e.browserPage)return Vf({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:()=>Lx(e),onStop:()=>Bx(e),onToggleInput:()=>Nx(e),onToggleFullscreen:()=>Ux(e),onCompleteHandoff:()=>Dx(e),onCanvasMouseDown:p=>{const x=p.target.getBoundingClientRect(),A=qn().translateCoordinates(p.clientX-x.left,p.clientY-x.top);So(e,"mousePressed",A.x,A.y,p.button===2?"right":p.button===1?"middle":"left")},onCanvasMouseUp:p=>{const x=p.target.getBoundingClientRect(),A=qn().translateCoordinates(p.clientX-x.left,p.clientY-x.top);So(e,"mouseReleased",A.x,A.y)},onCanvasMouseMove:p=>{const b=qn();if(b.shouldThrottleMouseMove())return;const C=p.target.getBoundingClientRect(),A=b.translateCoordinates(p.clientX-C.left,p.clientY-C.top);So(e,"mouseMoved",A.x,A.y)},onCanvasKeyDown:p=>{let b=0;p.altKey&&(b|=1),p.ctrlKey&&(b|=2),p.metaKey&&(b|=4),p.shiftKey&&(b|=8),Ao(e,"keyDown",p.key,{code:p.code,modifiers:b||void 0}),p.key.length===1&&Ao(e,"char",p.key,{text:p.key})},onCanvasKeyUp:p=>{Ao(e,"keyUp",p.key,{code:p.code})}});if(e.adminsPage){const p=f0(e),b=Vn(e);return Zm({connected:e.connected,wsProps:Rn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>vn(e,p),onAdd:x=>{dp(e,x,p,b).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:x=>pp(e,x,p,b),onNewPhoneChange:x=>e.handleAdminsNewPhoneChange(x),telegramAdmins:e.telegramAdmins,newTelegramUsername:e.adminsNewTelegramUsername,adminsPageTab:e.adminsPageTab??"external",onPageTabChange:x=>{e.adminsPageTab=x},activeAdminTab:e.adminsActiveTab??"whatsapp",onTabChange:x=>{e.adminsActiveTab=x},onTelegramAdd:x=>{hp(e,x,p,b).then(()=>{e.adminsError||(e.adminsNewTelegramUsername="")})},onTelegramRemove:x=>gp(e,x,p,b),onNewTelegramUsernameChange:x=>{e.adminsNewTelegramUsername=x,e.adminsError&&(e.adminsError=null)},isMaster:e.accessState.master,namedAdmins:e.accessState.accounts.filter(x=>x.id.startsWith("admin:")).map(x=>x.displayName),adminUsersAddBusy:e.adminUsersAddBusy,adminUsersAddError:e.adminUsersAddError,adminUsersRemoveConfirm:e.adminUsersRemoveConfirm,adminUsersRemoveBusy:e.adminUsersRemoveBusy,adminUsersChangePinUsername:e.adminUsersChangePinUsername,adminUsersChangePinBusy:e.adminUsersChangePinBusy,adminUsersChangePinError:e.adminUsersChangePinError,onAdminUsersAdd:(x,C)=>{e.handleAdminUsersAdd(x,C)},onAdminUsersRemoveConfirm:x=>{e.adminUsersRemoveConfirm=x},onAdminUsersRemove:x=>{e.handleAdminUsersRemove(x)},onAdminUsersChangePinOpen:x=>{e.adminUsersChangePinUsername=x,e.adminUsersChangePinError=null},onAdminUsersUpdatePin:(x,C)=>{e.handleAdminUsersUpdatePin(x,C)}})}if(e.contactsPage){const p=y0(e);return oy({connected:e.connected,wsProps:Rn(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:b=>e.contactsSearchQuery=b,onSearchSubmit:()=>dt(e,p),onAdd:(b,x)=>fp(e,b,x,p),onDelete:b=>mp(e,b,p),onSetField:(b,x,C)=>ra(e,b,x,C,p),onDeleteField:(b,x)=>yp(e,b,x,p),onToggleExpand:b=>{e.contactsEditingId=e.contactsEditingId===b?null:b},onShowAddForm:()=>e.contactsShowAddForm=!0,onCancelAddForm:()=>{e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName=""},onNewRecordPhoneChange:b=>e.handleContactsNewPhoneChange(b),onNewRecordNameChange:b=>e.handleContactsNewNameChange(b),onRefresh:()=>dt(e,p),onDeleteConfirmOpen:b=>e.contactsDeleteConfirmId=b,onDeleteConfirmClose:()=>e.contactsDeleteConfirmId=null,onAddFieldOpen:b=>{e.contactsAddFieldForId=b,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldClose:()=>{e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldKeyChange:b=>e.contactsAddFieldKey=b,onAddFieldValueChange:b=>e.contactsAddFieldValue=b,onAddFieldSubmit:()=>{const b=e.contactsAddFieldForId,x=e.contactsAddFieldKey.trim();!b||!x||(ra(e,b,x,e.contactsAddFieldValue,p),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const p=e.connected?null:"Disconnected from gateway.",b=Yl(e),x=e.chatAvatarUrl??b??null,C=(()=>{var M;const A=(M=e.configSnapshot)==null?void 0:M.config,T=A==null?void 0:A.publicChat;return(T==null?void 0:T.enabled)===!0})();return ck({connected:e.connected,wsProps:Rn(e),publicChatEnabled:C,publicChatAccountId:Ri(e)??void 0,chatPageTab:e.chatPageTab??"chat",onChatPageTabChange:A=>{if(e.chatPageTab=A,A==="whatsapp"&&!e.waLoading&&e.waConversations.length===0){const T=qi(e);Vd(T).then(()=>e.requestUpdate())}},whatsappProps:A0(e),sessionKey:e.sessionKey,onSessionKeyChange:A=>{const T=e.selectedWorkspace??"";Io(),Jn(T,e.sessionKey,e.chatMessage),e.sessionKey=A,e.chatMessage=Yn(T,A),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:A,lastActiveSessionKey:A}),e.loadAssistantIdentity(),nn(e),zo(e)},showThinking:e.settings.chatShowThinking??!1,verboseLevel:e.chatVerboseLevel,suggestions:e.chatSuggestions,onSuggestionClick:A=>{e.chatMessage=A,e.chatSuggestions=[],e.handleSendChat()},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:x,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:p,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const A=Math.max(e.chatMessages.length+10,dn);return Promise.all([nn(e,{limit:A}),zo(e)])},onToggleFocusMode:()=>{},onChatScroll:A=>e.handleChatScroll(A),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:A=>{e.chatMessage=A,Rr(e.selectedWorkspace??"",e.sessionKey,A)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:A=>e.chatAttachments=A,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:A=>e.removeQueuedMessage(A),onNewSession:()=>e.newSession(),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:A=>e.handleOpenSidebar(A),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:A=>e.handleSplitRatioChange(A),chatSessions:e.chatSessions,chatSessionsOpen:e.chatSessionsOpen,chatSidebarConfirmDeleteKey:e.chatSidebarConfirmDeleteKey,onSelectSession:A=>e.selectSession(A),onRenameSession:(A,T)=>{e.renameSession(A,T)},onDeleteSession:A=>{e.deleteChatSession(A)},onArmDelete:A=>{e.chatSidebarConfirmDeleteKey=A},onToggleSessions:()=>{const A=e;A.chatSessionsOpen=!A.chatSessionsOpen},assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?wx({connected:e.connected,wsProps:Rn(e),activeTab:e.advancedTab,onTabChange:p=>{var b,x;if(e.advancedTab=p,p==="cron"&&e.loadCron(),p==="skills"&&(Ce(e,{clearMessages:!0}),e.selectableTools.length||Su(e).then(C=>{e.selectableTools=C})),p==="sessions"){ht(e);const C=(b=Me(e))==null?void 0:b.name;C&&!((x=e.contactsRecords)!=null&&x.length)&&dt(e,C)}p==="opening-hours"&&tr(e),p==="logs"&&(e.logsSubTab==="session"?On(e,{reset:!0}):St(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(c=(l=e.channelsSnapshot)==null?void 0:l.channelMeta)!=null&&c.length?e.channelsSnapshot.channelMeta.map(p=>p.id):((d=e.channelsSnapshot)==null?void 0:d.channelOrder)??[],channelLabels:((m=e.channelsSnapshot)==null?void 0:m.channelLabels)??{},channelMeta:((v=e.channelsSnapshot)==null?void 0:v.channelMeta)??[],agentIds:(()=>{var b;const p=Me(e);return((b=p==null?void 0:p.agents)==null?void 0:b.map(x=>x.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:p=>{e.cronDetailJobId=p.id,Bo(e,p.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:p=>{e.cronForm=og(p),e.cronEditJobId=p.id,e.cronDetailJobId=null},onEditSave:()=>{const p=e.cronEditJobId;p&&ag(e,p).then(()=>{e.cronEditJobId=null})},onFormChange:p=>e.cronForm={...e.cronForm,...p},onRefresh:()=>e.loadCron(),onAdd:()=>{eg(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(p,b)=>tg(e,p,b),onRun:p=>ng(e,p),onRemove:p=>{e.cronPendingDeleteId=null,sg(e,p)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:p=>{e.cronPendingDeleteId=p||null},onLoadRuns:p=>Bo(e,p),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:p=>e.skillsFilter=p,onTypeFilterChange:p=>e.skillsTypeFilter=p,onRefresh:()=>Ce(e,{clearMessages:!0}),onToggle:(p,b)=>cu(e,p,b),onEdit:(p,b)=>lu(e,p,b),onSaveKey:p=>uu(e,p),onInstall:(p,b,x)=>du(e,p,b,x),onViewDetail:p=>pu(e,p),onDetailClose:()=>hu(e),onDetailTab:p=>gu(e,p),onAddOpen:()=>fu(e),onAddClose:()=>mu(e),onImportDraft:p=>yu(e,p),onInstallDraft:p=>vu(e,p),onDeleteDraft:p=>bu(e,p),onAddSave:()=>Ca(e),onAddFormUpdate:(p,b)=>{e.skillAddForm={...e.skillAddForm,[p]:b}},onAlwaysActiveToggle:(p,b)=>$u(e,p,b),onDelete:p=>Cu(e,p),onEditSkill:p=>Fo(e,p),onEditDetail:p=>wu(e,p),onRefUpdate:(p,b)=>ku(e,p,b),onEditTab:p=>xu(e,p),agentFilter:e.skillsAgentFilter,onAgentFilterChange:p=>e.skillsAgentFilter=p,onAgentsChange:(p,b)=>Au(e,p,b),selectableTools:e.selectableTools,onToolsChange:(p,b)=>{Wo(e,p,{tools:b}).then(()=>Ce(e))},onIconChange:(p,b)=>{Wo(e,p,{icon:b}).then(()=>(Fo(e,p),Ce(e))).catch(x=>console.error("[icon-picker] patchSkillMetadata failed:",x))}},logsProps:{logsSubTab:e.logsSubTab,isAdmin:e.accessState.master||!e.accessState.hasPins,onSubTabChange:p=>{e.logsSubTab=p,p==="session"?On(e,{reset:!0}):St(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:p=>e.sessionLogsFilterText=p,onTypeToggle:(p,b)=>{const x=e;x.sessionLogsTypeFilters={...x.sessionLogsTypeFilters,[p]:b}},onAgentToggle:(p,b)=>{const x=e;x.sessionLogsAgentFilters={...x.sessionLogsAgentFilters,[p]:b}},onToggleAutoFollow:p=>e.sessionLogsAutoFollow=p,onToggleChips:()=>{const p=e;p.sessionLogsChipsExpanded=!p.sessionLogsChipsExpanded},onToggleExpand:p=>{const b=e,x=new Set(b.sessionLogsExpandedIds);x.has(p)?x.delete(p):x.add(p),b.sessionLogsExpandedIds=x,b.requestUpdate()},onRefresh:()=>{On(e,{reset:!0})},onExport:(p,b)=>e.exportSessionLogs(p,b),onScroll:p=>e.handleSessionLogsScroll(p)},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:p=>{e.logsDate=p,St(e,{reset:!0})},onFilterTextChange:p=>e.logsFilterText=p,onLevelToggle:(p,b)=>{e.logsLevelFilters={...e.logsLevelFilters,[p]:b}},onToggleAutoFollow:p=>e.logsAutoFollow=p,onToggleChips:()=>{const p=e;p.logsChipsExpanded=!p.logsChipsExpanded},onRefresh:()=>St(e,{reset:!0}),onExport:(p,b)=>e.exportSessionLogs(p,b),onDownloadFull:p=>{const b=new URLSearchParams;p&&b.set("date",p);const x=Tt();x&&b.set("token",x);const C=b.toString();window.open(`/logs/download${C?`?${C}`:""}`,"_blank")},onScroll:p=>e.handleLogsScroll(p)},openingHoursProps:{loading:e.openingHoursLoading,error:e.openingHoursError,busy:e.openingHoursBusy,form:e.openingHoursForm,onFormChange:p=>{const b=e;b.openingHoursForm={...b.openingHoursForm,...p}},onDayChange:(p,b,x)=>{const C=e,A={...C.openingHoursForm.days};A[p]={...A[p],[b]:x},C.openingHoursForm={...C.openingHoursForm,days:A}},onAddClosedDate:p=>{const b=e;b.openingHoursForm.closedDates.includes(p)||(b.openingHoursForm={...b.openingHoursForm,closedDates:[...b.openingHoursForm.closedDates,p].sort()})},onRemoveClosedDate:p=>{const b=e;b.openingHoursForm={...b.openingHoursForm,closedDates:b.openingHoursForm.closedDates.filter(x=>x!==p)}},onSave:()=>{lp(e)}},sessionsProps:{loading:e.sessionsLoading,error:e.sessionsError,result:e.sessionsResult,kindFilter:e.sessionsKindFilter??"all",channelFilter:e.sessionsChannelFilter??"all",agentFilter:e.sessionsAgentFilter??"all",pendingAction:e.sessionsPendingAction??null,expandedKey:e.sessionsExpandedKey??null,contacts:e.contactsRecords??[],onKindFilterChange:p=>{e.sessionsKindFilter=p},onChannelFilterChange:p=>{e.sessionsChannelFilter=p},onAgentFilterChange:p=>{e.sessionsAgentFilter=p},onArmAction:(p,b)=>{e.sessionsPendingAction={key:p,action:b},e._sessionsPendingTimer&&clearTimeout(e._sessionsPendingTimer),e._sessionsPendingTimer=window.setTimeout(()=>{e.sessionsPendingAction=null,e._sessionsPendingTimer=null},3e3)},onReset:p=>{e.sessionsPendingAction=null,$c(e,p)},onDelete:p=>{e.sessionsPendingAction=null,Sc(e,p)},onRefresh:()=>{ht(e)},onToggleExpand:p=>{e.sessionsExpandedKey=e.sessionsExpandedKey===p?null:p},onPatch:(p,b)=>{xc(e,p,b)}}}):(window.location.replace("/chat"),u``)}function E0(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 Xl(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function T0(e,t,n){return u`
6097
+ `;if(!e.publicChatAuthenticated)return d0({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:C=>{var T;e.publicChatSessionKey=C,e.sessionKey=C,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const A=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";e.chatMessage=Yn(A,C),se(async()=>{const{loadChatHistory:M}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:M}},void 0,import.meta.url).then(({loadChatHistory:M})=>{M(e)})},onAuthStepChange:C=>{e.publicChatAuthStep=C},requestUpdate:()=>{e.requestUpdate()}});const p=(t=e.publicChatConfig)==null?void 0:t.greeting,b=e.chatMessages,x=!e.chatLoading&&p?[{role:"assistant",content:[{type:"text",text:p}],timestamp:0},...Array.isArray(b)?b:[]]:b;return Ax({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:x,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Zl(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:C=>{e.chatMessage=C,e.chatSuggestions=[],e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),se(async()=>{const{loadChatHistory:C}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:C}},void 0,import.meta.url).then(({loadChatHistory:C})=>{C(e)})),onDraftChange:C=>{var T;e.chatMessage=C;const A=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";Rr(A,e.sessionKey,C)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:C=>e.chatAttachments=C,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:C=>e.removeQueuedMessage(C),onChatScroll:C=>e.handleChatScroll(C),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}})}if(e.connected&&e.accessState.checked){const{accessState:p}=e;if(p.hasPins&&!p.authenticated)return Wl({show:!0,isFirstTime:!1,accounts:p.accounts,error:p.error,busy:p.busy,onSubmit:(b,x)=>{x!=null&&e.handlePinSubmit(b,x)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(b,x,C)=>e.handleChangePin(b,x,C)});if(!p.hasMasterPin&&!p.authenticated&&e.setup)return Wl({show:!0,isFirstTime:!0,accounts:[],error:p.error,busy:p.busy,onSubmit:b=>e.handleSetMasterPin(b)});if(!p.hasMasterPin&&!p.authenticated&&!e.setup)return window.location.href="/setup",w}if(e.setup){const p=$0(e.channelsSnapshot),b=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],x=A0(e.channelsSnapshot),C=S0(e.channelsSnapshot),A=((o=(s=e.channelsSnapshot)==null?void 0:s.channelAccounts)==null?void 0:o.telegram)??[],T=C0(e),M=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},N=()=>{const y=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=To[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,Vt(),Ct=setInterval(()=>{const k=(Date.now()-y)/1e3,S=Math.min(95,95*(1-Math.exp(-k/30)));e.tailscaleConnectProgress=Math.round(S);let P=To[0][1];for(const[I,B]of To)k>=I&&(P=B);e.tailscaleConnectMessage=P},500)};return Ym({connected:e.connected,serverPlatform:((r=(a=e.hello)==null?void 0:a.server)==null?void 0:r.platform)??null,assistantName:e.assistantName,currentStep:e.setupStep,licenseKey:e.licenseKey,licenseBusy:e.licenseBusy,licenseValid:e.licenseValid,licenseMessage:e.licenseMessage,licenseTier:e.licenseTier,licenseDeviceId:e.licenseDeviceId,licenseStoredKey:e.licenseStoredKey,onLicenseKeyChange:y=>e.handleLicenseKeyChange(y),onLicenseActivate:()=>e.handleLicenseActivate(),onLicenseRemove:async()=>{await e.handleLicenseRemove(),e.licenseRemoveConfirm=!1},licenseRemoveConfirm:e.licenseRemoveConfirm,onLicenseRemoveConfirm:()=>{e.licenseRemoveConfirm=!0},onLicenseRemoveCancel:()=>{e.licenseRemoveConfirm=!1},authConnected:e.authConnected,authBusy:e.authBusy,authMessage:e.authMessage,authUrl:e.authUrl,authCodeInput:e.authCodeInput,authExpiresIn:e.authExpiresIn,authRefreshToken:e.authRefreshToken,claudeAuthModalOpen:e.claudeAuthModalOpen,authRefreshTokenInput:e.authRefreshTokenInput,authRefreshTokenBusy:e.authRefreshTokenBusy,authRefreshTokenError:e.authRefreshTokenError,onClaudeAuthModalOpen:()=>e.handleClaudeAuthModalOpen(),onClaudeAuthModalClose:()=>e.handleClaudeAuthModalClose(),onRefreshTokenInputChange:y=>{e.authRefreshTokenInput=y},onImportRefreshToken:()=>e.handleImportRefreshToken(),whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:p,whatsappAccounts:b,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:y=>{e.addingWhatsAppAccount=y,e.whatsappAccountError=null},onSetNewWhatsAppAccountName:y=>{e.newWhatsAppAccountName=y},onSetNewWhatsAppAccountProvider:y=>{e.newWhatsAppAccountProvider=y,e.whatsappAccountError=null},onSetNewCloudPhoneNumberId:y=>{e.newCloudPhoneNumberId=y},onSetNewCloudBusinessAccountId:y=>{e.newCloudBusinessAccountId=y},onSetNewCloudAccessToken:y=>{e.newCloudAccessToken=y},onSetNewCloudWebhookVerifyToken:y=>{e.newCloudWebhookVerifyToken=y},onAddWhatsAppBaileysAccount:async y=>{await e.handleAddWhatsAppAccount(y)},onAddCloudApiAccount:async(y,k)=>{await e.handleAddCloudApiAccount(y,k)},gatewayHealthy:e.gatewayHealthy,gatewayHealthLoading:e.gatewayHealthLoading,gatewayHealthMessage:e.gatewayHealthMessage,gatewayRestartBusy:e.gatewayRestartBusy,updateAvailable:e.updateAvailable,currentVersion:e.currentVersion,latestVersion:e.latestVersion,updateChecking:e.updateChecking,updateRunning:e.updateRunning,updateMessage:e.updateMessage,updateProgressSteps:e.updateProgressSteps,updateLastResult:e.updateLastResult,onUpdateCheck:()=>e.handleUpdateCheck(),onUpdateRun:()=>e.handleUpdateRun(),onUpdateDismissResult:()=>e.handleUpdateDismissResult(),uninstallConfirm:e.uninstallConfirm,uninstallBusy:e.uninstallBusy,uninstallDone:e.uninstallDone,uninstallError:e.uninstallError,uninstallConfirmText:e.uninstallConfirmText,onUninstallConfirm:()=>e.handleUninstallConfirm(),onUninstallCancel:()=>e.handleUninstallCancel(),onUninstallConfirmTextChange:y=>e.handleUninstallConfirmTextChange(y),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onDisconnect:()=>{e.handleDisconnect()},onSubmitAuthCode:y=>e.handleAuthSubmitCode(y),onAuthCodeChange:y=>e.handleAuthCodeChange(y),onWhatsAppRelink:async y=>{await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await Q(e,!0),e.requestUpdate())},onWhatsAppUnlink:async y=>{await e.handleWhatsAppLogout(y)},onWhatsAppReset:async y=>{await e.handleWhatsAppLogout(y),await e.handleWhatsAppStart(!0,y),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(y),await Q(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await Q(e,!0),await e.handleGatewayHealthCheck()},onRefreshGatewayStatus:()=>e.handleGatewayHealthCheck(),onRefreshWhatsAppStatus:()=>Q(e,!0),onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),Q(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:y=>e.handleRemoveWhatsAppAccount(y),workspaces:e.workspaces,workspacesLoading:e.workspacesLoading,workspacesError:e.workspacesError,addingWorkspace:e.addingWorkspace,newWorkspaceName:e.newWorkspaceName,newWorkspacePath:e.newWorkspacePath,workspaceSaving:e.workspaceSaving,workspaceRemoveConfirm:e.workspaceRemoveConfirm,newWorkspacePin:e.newWorkspacePin,onSetNewWorkspacePin:y=>{e.newWorkspacePin=y},onWorkspaceCreate:async(y,k)=>{const S=e.newWorkspacePin;await e.handleWorkspaceCreate(y,k),S.match(/^\d{4,6}$/)&&(await hg(e,y,S),e.newWorkspacePin="")},onWorkspaceRemove:y=>e.handleWorkspaceRemove(y),onSetAddingWorkspace:y=>{e.addingWorkspace=y},onSetNewWorkspaceName:y=>{e.newWorkspaceName=y},onSetNewWorkspacePath:y=>{e.newWorkspacePath=y},onSetWorkspaceRemoveConfirm:y=>{e.workspaceRemoveConfirm=y},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(y,k)=>e.handleWorkspaceRename(y,k),whatsappAgentEnabled:(()=>{const y=Me(e),k=y==null?void 0:y.accountId,S=k?b.find(P=>P.accountId===k):b[0];return(S==null?void 0:S.dmPolicy)!=="disabled"})(),onWhatsAppAgentEnabledToggle:async()=>{var B;const y=Me(e),k=y==null?void 0:y.accountId,S=k?b.find(L=>L.accountId===k):b[0];if(!S)return;const P=S.dmPolicy!=="disabled",I=P?{dmPolicy:"disabled",groupPolicy:"disabled"}:{dmPolicy:"open",allowFrom:["*"],groupPolicy:"open"};try{const L=await e.client.request("config.get"),F=L.config,q=(B=F==null?void 0:F.channels)==null?void 0:B.whatsapp,ue=((q==null?void 0:q.accounts)??{})[S.accountId]?{channels:{whatsapp:{accounts:{[S.accountId]:I}}}}:{channels:{whatsapp:I}};await e.client.request("config.patch",{raw:JSON.stringify(ue),baseHash:L.hash,note:`WhatsApp agent → ${P?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),await Q(e,!1)}catch(L){console.error("Agent enabled toggle failed:",L)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:x.configured,imessageRunning:x.running,imessageConnected:x.connected,imessageLastError:x.lastError,imessageSelfChatMode:x.selfChatMode,imessageCliPath:x.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:T,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),k=y.config,S=(k==null?void 0:k.bindings)??[],P=Me(e),I=P==null?void 0:P.agents.find(Y=>Y.id.endsWith("-admin")||Y.id==="admin"),B=(I==null?void 0:I.id)??"admin",L=S.filter(Y=>{var ue;return((ue=Y.match)==null?void 0:ue.channel)!=="imessage"}),F=[{agentId:B,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],q=[...L,...F];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:q}),baseHash:y.hash,note:"Enable iMessage (self-chat) for "+((P==null?void 0:P.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Q(e,!0),He(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await Q(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),k=y.config,P=((k==null?void 0:k.bindings)??[]).filter(I=>{var B;return((B=I.match)==null?void 0:B.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:P}),baseHash:y.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Q(e,!0),He(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const y=await e.client.request("config.get"),k=y.config,S=(k==null?void 0:k.bindings)??[],P=Me(e),I=P==null?void 0:P.agents.find(q=>q.id.endsWith("-admin")||q.id==="admin"),B=(I==null?void 0:I.id)??"admin",L=S.filter(q=>{var Y;return((Y=q.match)==null?void 0:Y.channel)!=="imessage"}),F=[{agentId:B,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:[...L,...F]}),baseHash:y.hash,note:"Reassign iMessage to "+((P==null?void 0:P.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([Q(e,!0),He(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},telegramConfigured:C.configured,telegramRunning:C.running,telegramBotUsername:C.botUsername,telegramMode:C.mode,telegramLastError:C.lastError,telegramBusy:e.telegramBusy,telegramSettingsOpen:e.telegramSettingsOpen,telegramConnectOpen:e.telegramConnectOpen,telegramConnectToken:e.telegramConnectToken,telegramProbeResult:e.telegramProbeResult,telegramProbing:e.telegramProbing,telegramError:e.telegramError,onTelegramConnect:()=>{e.telegramConnectOpen=!0,e.telegramAddingBot=!0,e.telegramConnectToken="",e.telegramNewBotName="",e.telegramNewBotDmPolicy="open",e.telegramNewBotAdminRouting=!0,e.telegramProbeResult=null,e.telegramError=null,e.telegramBotError=null},onTelegramConnectClose:()=>{e.telegramConnectOpen=!1,e.telegramAddingBot=!1,e.telegramConnectToken="",e.telegramNewBotName="",e.telegramNewBotDmPolicy="open",e.telegramNewBotAdminRouting=!0,e.telegramProbeResult=null,e.telegramError=null,e.telegramBotError=null},onTelegramTokenChange:y=>{e.telegramConnectToken=y},onTelegramProbe:()=>{Lc(e)},onTelegramSave:()=>{Bc(e)},onTelegramSettingsOpen:()=>{e.telegramSettingsOpen=!0;const y=Vn(e)??"default";Li(e,y)},onTelegramSettingsClose:()=>{e.telegramSettingsOpen=!1},onTelegramDisconnect:()=>{Dc(e)},onRefreshTelegramStatus:()=>{Q(e,!0)},onTelegramAddBot:()=>{var k;const y=((k=e.telegramProbeResult)==null?void 0:k.username)??e.telegramNewBotName;Nc(e,y,e.telegramConnectToken,e.telegramNewBotDmPolicy,e.telegramNewBotAdminRouting)},onTelegramRemoveBot:y=>{Uc(e,y)},onTelegramDmPolicyChange:(y,k)=>{Oc(e,y,k)},onTelegramAdminRoutingChange:(y,k)=>{Fc(e,y,k)},onTelegramWhitelistAdd:(y,k)=>{Wc(e,y,k)},onTelegramWhitelistRemove:(y,k)=>{zc(e,y,k)},onTelegramNewBotNameChange:y=>{e.telegramNewBotName=y},onTelegramNewWhitelistUsernameChange:y=>{e.telegramNewWhitelistUsername=y},telegramAddingBot:e.telegramAddingBot,telegramNewBotName:e.telegramNewBotName,telegramNewBotDmPolicy:e.telegramNewBotDmPolicy,telegramNewBotAdminRouting:e.telegramNewBotAdminRouting,onTelegramNewBotDmPolicyChange:y=>{e.telegramNewBotDmPolicy=y},onTelegramNewBotAdminRoutingChange:y=>{e.telegramNewBotAdminRouting=y},telegramBotSaving:e.telegramBotSaving,telegramBotError:e.telegramBotError,telegramDmPolicySaving:e.telegramDmPolicySaving,telegramWhitelistSaving:e.telegramWhitelistSaving,telegramWhitelistError:e.telegramWhitelistError,telegramNewWhitelistUsername:e.telegramNewWhitelistUsername,telegramExpandedBotId:e.telegramExpandedBotId,onTelegramExpandBot:y=>{e.telegramExpandedBotId=y},telegramAccounts:A,telegramPairingRequests:e.telegramPairingRequests,telegramPairingLoading:e.telegramPairingLoading,telegramPairingAccountId:Vn(e)??"default",telegramPairingActioning:e.telegramPairingActioning,onTelegramPairingLoad:y=>{Li(e,y)},onTelegramPairingApprove:async(y,k)=>{e.telegramPairingActioning=new Set([...e.telegramPairingActioning,k]);try{await e.client.request("channels.telegram.pairing.approve",{accountId:y,code:k}),e.telegramPairingRequests=e.telegramPairingRequests.filter(S=>S.code!==k)}catch{await Li(e,y)}finally{e.telegramPairingActioning=new Set([...e.telegramPairingActioning].filter(S=>S!==k))}},onTelegramPairingReject:async(y,k)=>{e.telegramPairingActioning=new Set([...e.telegramPairingActioning,k]);try{await e.client.request("channels.telegram.pairing.reject",{accountId:y,code:k}),e.telegramPairingRequests=e.telegramPairingRequests.filter(S=>S.code!==k)}catch{await Li(e,y)}finally{e.telegramPairingActioning=new Set([...e.telegramPairingActioning].filter(S=>S!==k))}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:y=>{var k,S,P,I,B,L;if(e.infoModalOpen=y,y==="remote-access"){const F=((k=e.tailscaleStatus)==null?void 0:k.tailnetUrl)??((S=e.tailscaleStatus)!=null&&S.hostname?`https://${e.tailscaleStatus.hostname}`:null);F&&!e.remoteAccessQrDataUrl&&e.client.request("qr.generate",{url:F}).then(q=>{e.remoteAccessQrDataUrl=(q==null?void 0:q.dataUrl)??null}).catch(()=>{})}else if(y==="cloudflare"){const F=((P=e.tunnelStatus)==null?void 0:P.publicUrl)??null;F&&!e.tunnelQrDataUrl&&e.client.request("qr.generate",{url:F}).then(q=>{e.tunnelQrDataUrl=(q==null?void 0:q.dataUrl)??null}).catch(()=>{})}else if(y==="public-chat"){const F=((I=e.tunnelStatus)==null?void 0:I.publicChatBaseUrl)??null,q=((B=e.tailscaleStatus)==null?void 0:B.publicUrl)??((L=e.tailscaleStatus)==null?void 0:L.tailnetUrl)??null,Y=Ri(e),ue=F&&Y?`${F}/chat/${encodeURIComponent(Y)}`:q&&Y?`${q}/public/chat/${encodeURIComponent(Y)}`:null;ue&&!e.publicChatQrDataUrl&&e.client.request("qr.generate",{url:ue}).then(Ve=>{e.publicChatQrDataUrl=(Ve==null?void 0:Ve.dataUrl)??null}).catch(()=>{})}},onInfoModalClose:()=>{e.infoModalOpen=null},remoteAccessQrDataUrl:e.remoteAccessQrDataUrl??null,publicChatQrDataUrl:e.publicChatQrDataUrl??null,publicChatFullUrl:(()=>{var P,I,B;const y=((P=e.tunnelStatus)==null?void 0:P.publicChatBaseUrl)??null,k=((I=e.tailscaleStatus)==null?void 0:I.publicUrl)??((B=e.tailscaleStatus)==null?void 0:B.tailnetUrl)??null,S=Ri(e);return S?y?`${y}/chat/${encodeURIComponent(S)}`:k?`${k}/public/chat/${encodeURIComponent(S)}`:null:null})(),isMaster:e.accessState.master,apiKeyProviders:e.apiKeyProviders,apiKeyModalOpen:e.apiKeyModalOpen,apiKeyBusy:e.apiKeyBusy,apiKeyError:e.apiKeyError,apiKeySuccess:e.apiKeySuccess,apiKeySavingProvider:e.apiKeySavingProvider,onApiKeyModalOpen:()=>{e.apiKeyModalOpen=!0,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeyModalClose:()=>{e.apiKeyModalOpen=!1,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeySave:async(y,k)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await ql(e.client,y,k);const S=`${y} key saved`;e.apiKeySuccess=S,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Wi(e.client)}catch{}y==="anthropic"&&await e.handleAuthStatusCheck(),setTimeout(()=>{e.apiKeySuccess===S&&(e.apiKeySuccess=null)},2500)}catch(S){e.apiKeyError=S instanceof Error?S.message:"Failed to save key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyRemove:async y=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Hx(e.client,y);const k=`${y} key removed`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Wi(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyDisable:async(y,k)=>{e.apiKeySavingProvider=y,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await jx(e.client,y,k);const S=`${y} ${k?"disabled":"enabled"}`;e.apiKeySuccess=S,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Wi(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===S&&(e.apiKeySuccess=null)},2500)}catch(S){e.apiKeyError=S instanceof Error?S.message:`Failed to ${k?"disable":"enable"} key`,e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},authApiKeyMode:e.authApiKeyMode,authApiKeyInput:e.authApiKeyInput,authApiKeyBusy:e.authApiKeyBusy,authApiKeyError:e.authApiKeyError,onAuthApiKeyToggle:()=>{e.authApiKeyMode=!e.authApiKeyMode,e.authApiKeyError=null},onAuthApiKeyChange:y=>{e.authApiKeyInput=y},onAuthApiKeySubmit:async()=>{const y=e.authApiKeyInput.trim();if(y){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await ql(e.client,"anthropic",y),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(k){e.authApiKeyError=k instanceof Error?k.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var k;const y=e.selectedWorkspace??((k=e.workspaces[0])==null?void 0:k.name);return y?e.accessState.accounts.some(S=>S.id===y):!1})(),accountPinModalOpen:e.accountPinModalOpen,accountPinBusy:e.accountPinBusy,accountPinError:e.accountPinError,accountPinSuccess:e.accountPinSuccess,onAccountPinModalOpen:()=>{e.accountPinModalOpen=!0,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinModalClose:()=>{e.accountPinModalOpen=!1,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinSave:(y,k)=>{var P;const S=e.selectedWorkspace??((P=e.workspaces[0])==null?void 0:P.name);S&&e.handleAccountPinSave(S,y,k)},publicChatAccountId:Ri(e),publicChatSettingsOpen:e.publicChatSettingsOpen,onPublicChatSettingsOpen:()=>{e.publicChatSettingsOpen=!0},onPublicChatSettingsClose:()=>{e.publicChatSettingsOpen=!1},publicChatWidgetModalOpen:e.publicChatWidgetModalOpen,onPublicChatWidgetModalOpen:()=>{e.publicChatWidgetModalOpen=!0},onPublicChatWidgetModalClose:()=>{e.publicChatWidgetModalOpen=!1},publicChatEnabled:(()=>{var S;const y=(S=e.configSnapshot)==null?void 0:S.config,k=y==null?void 0:y.publicChat;return(k==null?void 0:k.enabled)===!0})(),publicChatAuthMode:(()=>{var B,L;const y=(B=e.configSnapshot)==null?void 0:B.config,k=y==null?void 0:y.publicChat,S=e.selectedWorkspace??"",P=k==null?void 0:k.accountSettings,I=((L=P==null?void 0:P[S])==null?void 0:L.auth)??(k==null?void 0:k.auth);return I==="verified"||I==="choice"?I:"anonymous"})(),publicChatGreeting:(()=>{var I;const y=(I=e.configSnapshot)==null?void 0:I.config,k=y==null?void 0:y.publicChat,S=k==null?void 0:k.greetings,P=e.selectedWorkspace??"";return(P&&(S==null?void 0:S[P]))??""})(),publicChatGreetingBusy:e.publicChatGreetingBusy,onPublicChatGreetingToggle:async()=>{var k;if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const S=await e.client.request("config.get"),P=S.config,I=(k=P==null?void 0:P.publicChat)==null?void 0:k.greetings;if(I==null?void 0:I[y]){const L={publicChat:{greetings:{[y]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(L),baseHash:S.hash,note:`Public chat greeting → disabled (${y})`,skipRestart:!0})}else{const L=await e.client.request("public.greeting.generate",{accountId:y});if(L!=null&&L.ok&&L.greeting){const F=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:L.greeting}}}),baseHash:F.hash,note:`Public chat greeting → enabled (${y})`,skipRestart:!0})}}e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Public chat greeting toggle failed:",S)}finally{e.publicChatGreetingBusy=!1}}},onPublicChatGreetingSave:async y=>{const k=e.selectedWorkspace??"";if(k)try{const S=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[k]:y}}}),baseHash:S.hash,note:`Public chat greeting text updated (${k})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Public chat greeting save failed:",S)}},onPublicChatGreetingRegenerate:async()=>{if(e.publicChatGreetingBusy)return;const y=e.selectedWorkspace??"";if(y){e.publicChatGreetingBusy=!0;try{const k=await e.client.request("public.greeting.generate",{accountId:y});if(k!=null&&k.ok&&k.greeting){const S=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[y]:k.greeting}}}),baseHash:S.hash,note:`Public chat greeting regenerated (${y})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}}catch(k){console.error("Public chat greeting regeneration failed:",k)}finally{e.publicChatGreetingBusy=!1}}},publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var y;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const k=await e.client.request("config.get"),S=k.config,P=((y=S==null?void 0:S.publicChat)==null?void 0:y.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!P}}),baseHash:k.hash,note:`Public chat → ${P?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),e.publicChatQrDataUrl=null}catch(k){console.error("Public chat toggle failed:",k)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async y=>{if(e.publicChatToggleBusy)return;const k=e.selectedWorkspace??"";if(k){e.publicChatToggleBusy=!0;try{const S=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{accountSettings:{[k]:{auth:y}}}}),baseHash:S.hash,note:`Public chat auth → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Public chat auth mode change failed:",S)}finally{e.publicChatToggleBusy=!1}}},publicChatEmailFrom:(()=>{var S,P;const y=(S=e.configSnapshot)==null?void 0:S.config,k=(P=y==null?void 0:y.publicChat)==null?void 0:P.email;return(k==null?void 0:k.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var B,L;const y=(B=e.configSnapshot)==null?void 0:B.config,k=y==null?void 0:y.publicChat,S=e.selectedWorkspace??"",P=k==null?void 0:k.accountSettings,I=((L=P==null?void 0:P[S])==null?void 0:L.verifyMethods)??(k==null?void 0:k.verifyMethods);return Array.isArray(I)?I:["whatsapp","sms"]})(),onPublicChatEmailSave:async(y,k)=>{if(e.publicChatEmailBusy)return;const S=e.selectedWorkspace??"";if(S){e.publicChatEmailBusy=!0;try{const P=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{email:{from:y||void 0},accountSettings:{[S]:{verifyMethods:k}}}}),baseHash:P.hash,note:"Update email verification settings for public chat",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(P){console.error("Email verification save failed:",P)}finally{e.publicChatEmailBusy=!1}}},brandAccentColor:(()=>{var S;const y=e.selectedWorkspace;return y?((S=Ke()[y])==null?void 0:S.accentColor)??"":""})(),brandBackgroundColor:(()=>{var S;const y=e.selectedWorkspace;return y?((S=Ke()[y])==null?void 0:S.backgroundColor)??"":""})(),brandHasLogo:(()=>{var S;const y=e.selectedWorkspace;return y?!!((S=Ke()[y])!=null&&S.logoUrl):!1})(),agentSettingsOpen:e.agentSettingsOpen,agentSettingsAgents:(()=>{var P,I;const y=Me(e);if(!y)return[];const k=(P=e.configSnapshot)==null?void 0:P.config,S=(I=k==null?void 0:k.agents)==null?void 0:I.list;return y.agents.map(B=>{var ue;const L=Array.isArray(S)?S.find(Ve=>Ve.id===B.id):void 0,F=L==null?void 0:L.model,q=typeof F=="string"?F:(F==null?void 0:F.primary)??null,Y=B.id.endsWith("-admin")||B.id==="admin";return{id:B.id,label:Y?"Admin":"Public",model:(q==null?void 0:q.trim())||null,thinkingLevel:((ue=L==null?void 0:L.thinkingLevel)==null?void 0:ue.trim())||null}})})(),agentSettingsModelCatalog:e.chatModelCatalog??[],memoryProvider:(()=>{var S,P,I;const y=(S=e.configSnapshot)==null?void 0:S.config,k=(I=(P=y==null?void 0:y.agents)==null?void 0:P.defaults)==null?void 0:I.memorySearch;return typeof(k==null?void 0:k.provider)=="string"&&k.provider?k.provider:"local"})(),memoryFallback:(()=>{var S,P,I;const y=(S=e.configSnapshot)==null?void 0:S.config,k=(I=(P=y==null?void 0:y.agents)==null?void 0:P.defaults)==null?void 0:I.memorySearch;return typeof(k==null?void 0:k.fallback)=="string"&&k.fallback?k.fallback:"none"})(),onAgentSettingsToggle:()=>{e.agentSettingsOpen=!e.agentSettingsOpen},onAgentModelChange:async(y,k)=>{try{const S=await e.client.request("config.get"),P=S.config,I=(P==null?void 0:P.agents)??{},B=Array.isArray(I.list)?[...I.list]:[],L=B.findIndex(q=>q.id===y);if(k)L>=0?B[L]={...B[L],model:k}:B.push({id:y,model:k});else if(L>=0){const{model:q,...Y}=B[L];Object.keys(Y).length<=1?B.splice(L,1):B[L]=Y}const F=B.length>0?{agents:{list:B}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(F),baseHash:S.hash,note:`Agent ${y} model → ${k||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Agent model change failed:",S)}},onAgentThinkingChange:async(y,k)=>{try{const S=await e.client.request("config.get"),P=S.config,I=(P==null?void 0:P.agents)??{},B=Array.isArray(I.list)?[...I.list]:[],L=B.findIndex(Y=>Y.id===y),F=k==="off"?void 0:k;if(F)L>=0?B[L]={...B[L],thinkingLevel:F}:B.push({id:y,thinkingLevel:F});else if(L>=0){const{thinkingLevel:Y,...ue}=B[L];Object.keys(ue).length<=1?B.splice(L,1):B[L]=ue}const q=B.length>0?{agents:{list:B}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(q),baseHash:S.hash,note:`Agent ${y} thinking → ${F||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(S){console.error("Agent thinking change failed:",S)}},onMemoryProviderChange:async y=>{try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{provider:y}}}}),baseHash:k.hash,note:`Memory search provider → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Memory provider change failed:",k)}},onMemoryFallbackChange:async y=>{try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({agents:{defaults:{memorySearch:{fallback:y}}}}),baseHash:k.hash,note:`Memory search fallback → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Memory fallback change failed:",k)}},brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async y=>{var S;const k=e.selectedWorkspace;if(!(!k||e.brandingBusy)){e.brandingBusy=!0;try{const P=await e.client.request("config.get"),I=P.config,B=((S=I==null?void 0:I.workspaces)==null?void 0:S[k])??{},L=B.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[k]:{...B,brand:{...L,accentColor:y}}}}),baseHash:P.hash,note:`Brand accent → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const F=Ke();F[k]||(F[k]={}),F[k].accentColor=y,Nn(k)}catch(P){console.error("Brand accent change failed:",P)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async y=>{var S;const k=e.selectedWorkspace;if(!(!k||e.brandingBusy)){e.brandingBusy=!0;try{const P=await e.client.request("config.get"),I=P.config,B=((S=I==null?void 0:I.workspaces)==null?void 0:S[k])??{},L=B.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[k]:{...B,brand:{...L,backgroundColor:y}}}}),baseHash:P.hash,note:`Brand background → ${y}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const F=Ke();F[k]||(F[k]={}),F[k].backgroundColor=y,Nn(k)}catch(P){console.error("Brand background change failed:",P)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async y=>{const k=e.selectedWorkspace;if(console.log(`[brand-upload] file=${y.name} type=${y.type} size=${y.size} ws=${k} busy=${e.brandingBusy}`),!k||e.brandingBusy){console.warn(`[brand-upload] skipped: ws=${k} busy=${e.brandingBusy}`);return}e.brandingBusy=!0;try{const S=await y.arrayBuffer(),P=new Uint8Array(S);let I="";for(let q=0;q<P.length;q++)I+=String.fromCharCode(P[q]);const B=btoa(I);console.log(`[brand-upload] sending RPC: workspace=${k} base64Len=${B.length} mimeType=${y.type}`);const L=await e.client.request("brand.uploadLogo",{workspace:k,data:B,mimeType:y.type});console.log("[brand-upload] RPC result:",L);const F=Ke();F[k]||(F[k]={}),F[k].logoUrl=`/brand-logo/${encodeURIComponent(k)}`}catch(S){console.error("Brand logo upload failed:",S),alert(`Brand logo upload failed: ${S.message||S}`)}finally{e.brandingBusy=!1}},onBrandLogoRemove:async()=>{const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:y});const k=Ke();k[y]&&delete k[y].logoUrl}catch(k){console.error("Brand logo remove failed:",k)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var k;const y=e.selectedWorkspace;if(!(!y||e.brandingBusy)){e.brandingBusy=!0;try{const S=await e.client.request("config.get"),P=S.config,I=((k=P==null?void 0:P.workspaces)==null?void 0:k[y])??{},{brand:B,...L}=I;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[y]:{...L,brand:null}}}),baseHash:S.hash,note:"Brand reset to defaults",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");try{await e.client.request("brand.removeLogo",{workspace:y})}catch{}const F=Ke();delete F[y],Nn(y)}catch(S){console.error("Brand reset failed:",S)}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,N();try{const y=await e.client.request("tailscale.enable");y.authUrl?(Ct&&(clearInterval(Ct),Ct=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=y.authUrl,zi=setInterval(async()=>{try{const k=await e.client.request("tailscale.status");e.tailscaleStatus=k,e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,k.loggedIn&&(Vt(),e.tailscaleAuthUrl=null,e.tailscaleConnectSuccess=!0,e.tailscaleConnectMessage="Connected!",setTimeout(()=>{e.tailscaleConnectSuccess=!1,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1},1500))}catch{}},3e3),Ki=setTimeout(()=>{Vt(),e.tailscaleBusy&&(e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)},3e5)):y.alreadyLoggedIn?(Vt(),e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1):(Vt(),e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)}catch(y){console.error("Tailscale enable failed:",y),Vt(),e.tailscaleError=y.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleServeEnableUrl=null,e.tailscaleDisableConfirm=!1;try{await e.client.request("tailscale.serve.enable"),await M(),await new Promise(k=>setTimeout(k,350)),e.tailscaleDisableConfirm=!1}catch(k){console.error("Tailscale serve enable failed:",k);const S=k;(y=S.payload)!=null&&y.enableUrl&&(e.tailscaleServeEnableUrl=S.payload.enableUrl),e.tailscaleError=S.message||"Failed to enable Remote Access"}finally{e.tailscaleBusy=!1}}},onTailscaleServeDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleDisableConfirm=!1;try{await e.client.request("tailscale.serve.disable"),await M()}catch(y){console.error("Tailscale serve disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var y;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable"),await M()}catch(k){console.error("Tailscale funnel enable failed:",k);const S=k;(y=S.payload)!=null&&y.enableUrl&&(e.tailscaleFunnelEnableUrl=S.payload.enableUrl),e.tailscaleError=S.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 M()}catch(y){console.error("Tailscale funnel disable failed:",y)}finally{e.tailscaleBusy=!1}}},onTailscaleDisableConfirmToggle:()=>{e.tailscaleBusy||(e.tailscaleDisableConfirm=!e.tailscaleDisableConfirm)},tunnelStatus:e.tunnelStatus,tunnelBusy:e.tunnelBusy,tunnelError:e.tunnelError,tunnelAuthUrl:e.tunnelAuthUrl,tunnelSetupStep:e.tunnelSetupStep,tunnelQrDataUrl:e.tunnelQrDataUrl,tunnelHostnameInput:e.tunnelHostnameInput,tunnelUsernameInput:e.tunnelUsernameInput,tunnelPasswordInput:e.tunnelPasswordInput,tunnelPasswordConfirmInput:e.tunnelPasswordConfirmInput,onTunnelInstall:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null;try{const y=await e.client.request("tunnel.install");y.ok||(e.tunnelError=y.error??"Install failed"),e.tunnelStatus=await e.client.request("tunnel.status")}catch(y){e.tunnelError=y.message||"Install failed"}finally{e.tunnelBusy=!1}}},onTunnelLogin:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null,e.tunnelAuthUrl=null;try{const y=await e.client.request("tunnel.login");if(y.authUrl){e.tunnelAuthUrl=y.authUrl,e.client.request("qr.generate",{url:y.authUrl}).then(B=>{e.tunnelQrDataUrl=(B==null?void 0:B.dataUrl)??null}).catch(()=>{});const k=async()=>{var B;try{if((await e.client.request("tunnel.loginStatus")).authenticated)return P(),e.tunnelAuthUrl=null,e.tunnelQrDataUrl=null,e.tunnelBusy=!1,e.tunnelStatus=await e.client.request("tunnel.status"),(B=e.tunnelStatus)!=null&&B.tunnelId||(e.tunnelSetupStep=3),!0}catch{}return!1};let S=null;const P=()=>{S!==null&&(clearInterval(S),S=null),document.removeEventListener("visibilitychange",I)},I=()=>{document.visibilityState==="visible"&&k()};document.addEventListener("visibilitychange",I),S=setInterval(()=>{k()},3e3),setTimeout(()=>{P(),e.tunnelAuthUrl&&(e.tunnelAuthUrl=null,e.tunnelBusy=!1,e.tunnelError="Authentication timed out. Make sure you have a domain registered with Cloudflare, then try again.")},3e5)}else e.tunnelStatus=await e.client.request("tunnel.status"),e.tunnelBusy=!1}catch(y){e.tunnelError=y.message||"Login failed",e.tunnelBusy=!1}}},onTunnelCreate:async()=>{var k,S;if(e.tunnelBusy)return;const y=(S=(k=e.tunnelStatus)==null?void 0:k.authorizedDomain)==null?void 0:S.trim();if(!y){e.tunnelError="No authorized domain found — complete Cloudflare login first";return}e.tunnelBusy=!0,e.tunnelError=null;try{const P=await e.client.request("tunnel.create",{domain:y});P.ok?(e.tunnelSetupStep=4,e.tunnelError=null):e.tunnelError=P.error??"Failed to create tunnel",e.tunnelStatus=await e.client.request("tunnel.status")}catch(P){e.tunnelError=P.message||"Failed to create tunnel"}finally{e.tunnelBusy=!1}},onTunnelSetRemotePassword:async()=>{var S,P,I;if(e.tunnelBusy)return;const y=(S=e.tunnelPasswordInput)==null?void 0:S.trim(),k=(P=e.tunnelPasswordConfirmInput)==null?void 0:P.trim();if(!y||y.length<8){e.tunnelError="Password must be at least 8 characters";return}if(y!==k){e.tunnelError="Passwords do not match";return}e.tunnelBusy=!0,e.tunnelError=null;try{const B=((I=e.tunnelUsernameInput)==null?void 0:I.trim())||"admin",L=await e.client.request("remoteAuth.setCredentials",{username:B,password:y});L.ok?(e.tunnelSetupStep=5,e.tunnelError=null):e.tunnelError=L.message??"Failed to set password",e.tunnelStatus=await e.client.request("tunnel.status")}catch(B){e.tunnelError=B.message||"Failed to set password"}finally{e.tunnelBusy=!1}},onTunnelEnable:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null;try{const y=await e.client.request("tunnel.enable");y.ok?(e.tunnelSetupStep=0,e.tunnelError=null):e.tunnelError=y.error??"Failed to enable tunnel",e.tunnelStatus=await e.client.request("tunnel.status"),e.publicChatQrDataUrl=null}catch(y){e.tunnelError=y.message||"Failed to enable tunnel"}finally{e.tunnelBusy=!1}}},onTunnelDisable:async()=>{if(!e.tunnelBusy){e.tunnelBusy=!0,e.tunnelError=null;try{const y=await e.client.request("tunnel.disable");y.ok||(e.tunnelError=y.error??"Failed to disable tunnel"),e.tunnelStatus=await e.client.request("tunnel.status")}catch(y){e.tunnelError=y.message||"Failed to disable tunnel"}finally{e.tunnelBusy=!1}}},onTunnelSetupStepChange:y=>{e.tunnelSetupStep=y,e.tunnelError=null},onTunnelHostnameChange:y=>{e.tunnelHostnameInput=y},onTunnelUsernameChange:y=>{e.tunnelUsernameInput=y},onTunnelPasswordChange:y=>{e.tunnelPasswordInput=y},onTunnelPasswordConfirmChange:y=>{e.tunnelPasswordConfirmInput=y},onTunnelLoginCancel:()=>{e.tunnelAuthUrl=null,e.tunnelQrDataUrl=null,e.tunnelBusy=!1},onTunnelErrorDismiss:()=>{e.tunnelError=null},wifiModalOpen:e.wifiModalOpen,onWifiModalToggle:()=>{e.wifiModalOpen=!e.wifiModalOpen,e.wifiModalOpen||(e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null)},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{var y;if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[k,S]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiNetworks=k.networks,S.connected&&S.signal==null&&((y=k.networks)!=null&&y.length)){const P=k.networks.find(I=>I.active)||k.networks.find(I=>I.ssid===S.ssid);P&&(S.signal=P.signal)}e.wifiStatus=S}catch(k){console.error("WiFi scan failed:",k),e.wifiError=k.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{var k;if(e.wifiBusy||!e.wifiSelectedSsid)return;const y=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const S=await e.client.request("wifi.connect",{ssid:y,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:S.connected,ssid:S.ssid,signal:null,ip:S.ip,savedSsid:S.ssid,autoconnect:!0},e.wifiBusy=!1;try{const[P,I]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(I.connected&&I.signal==null&&((k=P.networks)!=null&&k.length)){const B=P.networks.find(L=>L.active)||P.networks.find(L=>L.ssid===I.ssid);B&&(I.signal=B.signal)}e.wifiStatus=I}catch{}}catch(S){console.error("WiFi connect failed:",S),e.wifiError=S.message||"Failed to connect",e.wifiBusy=!1}},onWifiDisconnect:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.disconnect"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi disconnect failed:",y),e.wifiError=y.message||"Failed to disconnect"}finally{e.wifiBusy=!1}}},onWifiForget:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.forget"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const y=await e.client.request("wifi.status");e.wifiStatus=y}catch(y){console.error("WiFi forget failed:",y),e.wifiError=y.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:y=>{e.wifiSelectedSsid=y,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:y=>{e.wifiPassword=y},networkPort:e.networkPort,networkHostname:e.networkHostname,networkPortInput:e.networkPortInput,networkHostnameInput:e.networkHostnameInput,networkModalOpen:e.networkModalOpen,networkBusy:e.networkBusy,networkError:e.networkError,networkSuccess:e.networkSuccess,onNetworkModalToggle:()=>{e.networkModalOpen=!e.networkModalOpen,e.networkModalOpen&&(e.networkPortInput=String(e.networkPort??""),e.networkHostnameInput=e.networkHostname,e.networkError=null,e.networkSuccess=null)},onNetworkPortChange:y=>{e.networkPortInput=y,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:y=>{e.networkHostnameInput=y,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const y=e.networkPortInput.trim(),k=Number.parseInt(y,10),S=e.networkHostnameInput.trim();if(!y||!Number.isFinite(k)||k<1024||k>65535){e.networkError="Port must be a number between 1024 and 65535",e.networkBusy=!1;return}const P=k!==e.networkPort,I=S!==e.networkHostname;if(!P&&!I){e.networkBusy=!1;return}try{I&&await e.client.request("network.setHostname",{hostname:S});const B={};P&&(B.gateway={port:k}),I&&(B.discovery={bonjourHostname:S});const L=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify(B),baseHash:L.hash,note:[P?`Port → ${k}`:null,I?`Hostname → ${S}`:null].filter(Boolean).join(", "),restartDelayMs:2e3}),e.networkSuccess="Saved — redirecting...";const F=window.location.protocol,q=I?`${S}.local`:window.location.hostname,Y=P?k:e.networkPort,ue=`${F}//${q}:${Y}/setup`;setTimeout(()=>{window.location.href=ue},1500)}catch(B){console.error("Network save failed:",B),e.networkError=B.message||"Failed to save network settings",e.networkBusy=!1}},wsProps:y0(e)})}if(e.filesPage){const p=b0(e);return tm({connected:e.connected,wsProps:Rn(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:()=>{fn(e,p),xs(e,p)},onReindex:()=>ff(e,p),onSelectFile:b=>{e.filesPendingDeletePath=null,Lu(e,b,p)},onToggleSelectFile:b=>lf(e,b,p),onToggleDir:b=>mf(e,b),onUpload:(b,x)=>df(e,b,x,p),onNewFolder:(b,x)=>pf(e,b,x,p),onDownload:b=>Du(e,b,p),onBulkDownload:()=>cf(e,p),onDelete:b=>{e.filesPendingDeletePath=null,hf(e,b,p)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:b=>{e.filesPendingDeletePath=b||null},onMoveToDir:(b,x)=>uf(e,b,x,p),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:b=>{const x=e.filesSearchAgentId??p;yf(e,b,x)},onSearchAgentChange:b=>{e.filesSearchAgentId=b},onSearchClear:()=>{vf(e)},onSearchQueryChange:b=>{e.filesSearchQuery=b}})}if(e.browserPage)return Qf({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:()=>Nx(e),onStop:()=>Ux(e),onToggleInput:()=>Fx(e),onToggleFullscreen:()=>Wx(e),onCompleteHandoff:()=>Ox(e),onCanvasMouseDown:p=>{const x=p.target.getBoundingClientRect(),A=qn().translateCoordinates(p.clientX-x.left,p.clientY-x.top);So(e,"mousePressed",A.x,A.y,p.button===2?"right":p.button===1?"middle":"left")},onCanvasMouseUp:p=>{const x=p.target.getBoundingClientRect(),A=qn().translateCoordinates(p.clientX-x.left,p.clientY-x.top);So(e,"mouseReleased",A.x,A.y)},onCanvasMouseMove:p=>{const b=qn();if(b.shouldThrottleMouseMove())return;const C=p.target.getBoundingClientRect(),A=b.translateCoordinates(p.clientX-C.left,p.clientY-C.top);So(e,"mouseMoved",A.x,A.y)},onCanvasKeyDown:p=>{let b=0;p.altKey&&(b|=1),p.ctrlKey&&(b|=2),p.metaKey&&(b|=4),p.shiftKey&&(b|=8),Ao(e,"keyDown",p.key,{code:p.code,modifiers:b||void 0}),p.key.length===1&&Ao(e,"char",p.key,{text:p.key})},onCanvasKeyUp:p=>{Ao(e,"keyUp",p.key,{code:p.code})}});if(e.adminsPage){const p=v0(e),b=Vn(e);return ty({connected:e.connected,wsProps:Rn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>vn(e,p),onAdd:x=>{hp(e,x,p,b).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:x=>gp(e,x,p,b),onNewPhoneChange:x=>e.handleAdminsNewPhoneChange(x),telegramAdmins:e.telegramAdmins,newTelegramUsername:e.adminsNewTelegramUsername,adminsPageTab:e.adminsPageTab??"external",onPageTabChange:x=>{e.adminsPageTab=x},activeAdminTab:e.adminsActiveTab??"whatsapp",onTabChange:x=>{e.adminsActiveTab=x},onTelegramAdd:x=>{fp(e,x,p,b).then(()=>{e.adminsError||(e.adminsNewTelegramUsername="")})},onTelegramRemove:x=>mp(e,x,p,b),onNewTelegramUsernameChange:x=>{e.adminsNewTelegramUsername=x,e.adminsError&&(e.adminsError=null)},isMaster:e.accessState.master,namedAdmins:e.accessState.accounts.filter(x=>x.id.startsWith("admin:")).map(x=>x.displayName),adminUsersAddBusy:e.adminUsersAddBusy,adminUsersAddError:e.adminUsersAddError,adminUsersRemoveConfirm:e.adminUsersRemoveConfirm,adminUsersRemoveBusy:e.adminUsersRemoveBusy,adminUsersChangePinUsername:e.adminUsersChangePinUsername,adminUsersChangePinBusy:e.adminUsersChangePinBusy,adminUsersChangePinError:e.adminUsersChangePinError,onAdminUsersAdd:(x,C)=>{e.handleAdminUsersAdd(x,C)},onAdminUsersRemoveConfirm:x=>{e.adminUsersRemoveConfirm=x},onAdminUsersRemove:x=>{e.handleAdminUsersRemove(x)},onAdminUsersChangePinOpen:x=>{e.adminUsersChangePinUsername=x,e.adminUsersChangePinError=null},onAdminUsersUpdatePin:(x,C)=>{e.handleAdminUsersUpdatePin(x,C)}})}if(e.contactsPage){const p=w0(e);return ry({connected:e.connected,wsProps:Rn(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:b=>e.contactsSearchQuery=b,onSearchSubmit:()=>dt(e,p),onAdd:(b,x)=>yp(e,b,x,p),onDelete:b=>vp(e,b,p),onSetField:(b,x,C)=>ra(e,b,x,C,p),onDeleteField:(b,x)=>bp(e,b,x,p),onToggleExpand:b=>{e.contactsEditingId=e.contactsEditingId===b?null:b},onShowAddForm:()=>e.contactsShowAddForm=!0,onCancelAddForm:()=>{e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName=""},onNewRecordPhoneChange:b=>e.handleContactsNewPhoneChange(b),onNewRecordNameChange:b=>e.handleContactsNewNameChange(b),onRefresh:()=>dt(e,p),onDeleteConfirmOpen:b=>e.contactsDeleteConfirmId=b,onDeleteConfirmClose:()=>e.contactsDeleteConfirmId=null,onAddFieldOpen:b=>{e.contactsAddFieldForId=b,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldClose:()=>{e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldKeyChange:b=>e.contactsAddFieldKey=b,onAddFieldValueChange:b=>e.contactsAddFieldValue=b,onAddFieldSubmit:()=>{const b=e.contactsAddFieldForId,x=e.contactsAddFieldKey.trim();!b||!x||(ra(e,b,x,e.contactsAddFieldValue,p),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const p=e.connected?null:"Disconnected from gateway.",b=Zl(e),x=e.chatAvatarUrl??b??null,C=(()=>{var M;const A=(M=e.configSnapshot)==null?void 0:M.config,T=A==null?void 0:A.publicChat;return(T==null?void 0:T.enabled)===!0})();return dk({connected:e.connected,wsProps:Rn(e),publicChatEnabled:C,publicChatAccountId:Ri(e)??void 0,chatPageTab:e.chatPageTab??"chat",onChatPageTabChange:A=>{if(e.chatPageTab=A,A==="whatsapp"&&!e.waLoading&&e.waConversations.length===0){const T=qi(e);Qd(T).then(()=>e.requestUpdate())}},whatsappProps:T0(e),sessionKey:e.sessionKey,onSessionKeyChange:A=>{const T=e.selectedWorkspace??"";Io(),Jn(T,e.sessionKey,e.chatMessage),e.sessionKey=A,e.chatMessage=Yn(T,A),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:A,lastActiveSessionKey:A}),e.loadAssistantIdentity(),nn(e),zo(e)},showThinking:e.settings.chatShowThinking??!1,verboseLevel:e.chatVerboseLevel,suggestions:e.chatSuggestions,onSuggestionClick:A=>{e.chatMessage=A,e.chatSuggestions=[],e.handleSendChat()},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:x,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:p,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const A=Math.max(e.chatMessages.length+10,dn);return Promise.all([nn(e,{limit:A}),zo(e)])},onToggleFocusMode:()=>{},onChatScroll:A=>e.handleChatScroll(A),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:A=>{e.chatMessage=A,Rr(e.selectedWorkspace??"",e.sessionKey,A)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:A=>e.chatAttachments=A,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:A=>e.removeQueuedMessage(A),onNewSession:()=>e.newSession(),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:A=>e.handleOpenSidebar(A),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:A=>e.handleSplitRatioChange(A),chatSessions:e.chatSessions,chatSessionsOpen:e.chatSessionsOpen,chatSidebarConfirmDeleteKey:e.chatSidebarConfirmDeleteKey,onSelectSession:A=>e.selectSession(A),onRenameSession:(A,T)=>{e.renameSession(A,T)},onDeleteSession:A=>{e.deleteChatSession(A)},onArmDelete:A=>{e.chatSidebarConfirmDeleteKey=A},onToggleSessions:()=>{const A=e;A.chatSessionsOpen=!A.chatSessionsOpen},assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?$x({connected:e.connected,wsProps:Rn(e),activeTab:e.advancedTab,onTabChange:p=>{var b,x;if(e.advancedTab=p,p==="cron"&&e.loadCron(),p==="skills"&&(Ce(e,{clearMessages:!0}),e.selectableTools.length||Cu(e).then(C=>{e.selectableTools=C})),p==="sessions"){ht(e);const C=(b=Me(e))==null?void 0:b.name;C&&!((x=e.contactsRecords)!=null&&x.length)&&dt(e,C)}p==="opening-hours"&&tr(e),p==="logs"&&(e.logsSubTab==="session"?On(e,{reset:!0}):St(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(c=(l=e.channelsSnapshot)==null?void 0:l.channelMeta)!=null&&c.length?e.channelsSnapshot.channelMeta.map(p=>p.id):((d=e.channelsSnapshot)==null?void 0:d.channelOrder)??[],channelLabels:((m=e.channelsSnapshot)==null?void 0:m.channelLabels)??{},channelMeta:((v=e.channelsSnapshot)==null?void 0:v.channelMeta)??[],agentIds:(()=>{var b;const p=Me(e);return((b=p==null?void 0:p.agents)==null?void 0:b.map(x=>x.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:p=>{e.cronDetailJobId=p.id,Bo(e,p.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:p=>{e.cronForm=rg(p),e.cronEditJobId=p.id,e.cronDetailJobId=null},onEditSave:()=>{const p=e.cronEditJobId;p&&lg(e,p).then(()=>{e.cronEditJobId=null})},onFormChange:p=>e.cronForm={...e.cronForm,...p},onRefresh:()=>e.loadCron(),onAdd:()=>{ng(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(p,b)=>ig(e,p,b),onRun:p=>sg(e,p),onRemove:p=>{e.cronPendingDeleteId=null,ag(e,p)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:p=>{e.cronPendingDeleteId=p||null},onLoadRuns:p=>Bo(e,p),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:p=>e.skillsFilter=p,onTypeFilterChange:p=>e.skillsTypeFilter=p,onRefresh:()=>Ce(e,{clearMessages:!0}),onToggle:(p,b)=>du(e,p,b),onEdit:(p,b)=>uu(e,p,b),onSaveKey:p=>pu(e,p),onInstall:(p,b,x)=>hu(e,p,b,x),onViewDetail:p=>gu(e,p),onDetailClose:()=>fu(e),onDetailTab:p=>mu(e,p),onAddOpen:()=>yu(e),onAddClose:()=>vu(e),onImportDraft:p=>bu(e,p),onInstallDraft:p=>wu(e,p),onDeleteDraft:p=>ku(e,p),onAddSave:()=>Ca(e),onAddFormUpdate:(p,b)=>{e.skillAddForm={...e.skillAddForm,[p]:b}},onAlwaysActiveToggle:(p,b)=>Au(e,p,b),onDelete:p=>Tu(e,p),onEditSkill:p=>Fo(e,p),onEditDetail:p=>xu(e,p),onRefUpdate:(p,b)=>$u(e,p,b),onEditTab:p=>Su(e,p),agentFilter:e.skillsAgentFilter,onAgentFilterChange:p=>e.skillsAgentFilter=p,onAgentsChange:(p,b)=>Eu(e,p,b),selectableTools:e.selectableTools,onToolsChange:(p,b)=>{Wo(e,p,{tools:b}).then(()=>Ce(e))},onIconChange:(p,b)=>{Wo(e,p,{icon:b}).then(()=>(Fo(e,p),Ce(e))).catch(x=>console.error("[icon-picker] patchSkillMetadata failed:",x))}},logsProps:{logsSubTab:e.logsSubTab,isAdmin:e.accessState.master||!e.accessState.hasPins,onSubTabChange:p=>{e.logsSubTab=p,p==="session"?On(e,{reset:!0}):St(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:p=>e.sessionLogsFilterText=p,onTypeToggle:(p,b)=>{const x=e;x.sessionLogsTypeFilters={...x.sessionLogsTypeFilters,[p]:b}},onAgentToggle:(p,b)=>{const x=e;x.sessionLogsAgentFilters={...x.sessionLogsAgentFilters,[p]:b}},onToggleAutoFollow:p=>e.sessionLogsAutoFollow=p,onToggleChips:()=>{const p=e;p.sessionLogsChipsExpanded=!p.sessionLogsChipsExpanded},onToggleExpand:p=>{const b=e,x=new Set(b.sessionLogsExpandedIds);x.has(p)?x.delete(p):x.add(p),b.sessionLogsExpandedIds=x,b.requestUpdate()},onRefresh:()=>{On(e,{reset:!0})},onExport:(p,b)=>e.exportSessionLogs(p,b),onScroll:p=>e.handleSessionLogsScroll(p)},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:p=>{e.logsDate=p,St(e,{reset:!0})},onFilterTextChange:p=>e.logsFilterText=p,onLevelToggle:(p,b)=>{e.logsLevelFilters={...e.logsLevelFilters,[p]:b}},onToggleAutoFollow:p=>e.logsAutoFollow=p,onToggleChips:()=>{const p=e;p.logsChipsExpanded=!p.logsChipsExpanded},onRefresh:()=>St(e,{reset:!0}),onExport:(p,b)=>e.exportSessionLogs(p,b),onDownloadFull:p=>{const b=new URLSearchParams;p&&b.set("date",p);const x=Tt();x&&b.set("token",x);const C=b.toString();window.open(`/logs/download${C?`?${C}`:""}`,"_blank")},onScroll:p=>e.handleLogsScroll(p)},openingHoursProps:{loading:e.openingHoursLoading,error:e.openingHoursError,busy:e.openingHoursBusy,saved:e.openingHoursSaved,form:e.openingHoursForm,onFormChange:p=>{const b=e;b.openingHoursForm={...b.openingHoursForm,...p}},onDayChange:(p,b,x)=>{const C=e,A={...C.openingHoursForm.days};A[p]={...A[p],[b]:x},C.openingHoursForm={...C.openingHoursForm,days:A}},onAddClosedDate:p=>{const b=e;b.openingHoursForm.closedDates.includes(p)||(b.openingHoursForm={...b.openingHoursForm,closedDates:[...b.openingHoursForm.closedDates,p].sort()})},onRemoveClosedDate:p=>{const b=e;b.openingHoursForm={...b.openingHoursForm,closedDates:b.openingHoursForm.closedDates.filter(x=>x!==p)}},onSave:()=>{up(e)}},sessionsProps:{loading:e.sessionsLoading,error:e.sessionsError,result:e.sessionsResult,kindFilter:e.sessionsKindFilter??"all",channelFilter:e.sessionsChannelFilter??"all",agentFilter:e.sessionsAgentFilter??"all",pendingAction:e.sessionsPendingAction??null,expandedKey:e.sessionsExpandedKey??null,contacts:e.contactsRecords??[],onKindFilterChange:p=>{e.sessionsKindFilter=p},onChannelFilterChange:p=>{e.sessionsChannelFilter=p},onAgentFilterChange:p=>{e.sessionsAgentFilter=p},onArmAction:(p,b)=>{e.sessionsPendingAction={key:p,action:b},e._sessionsPendingTimer&&clearTimeout(e._sessionsPendingTimer),e._sessionsPendingTimer=window.setTimeout(()=>{e.sessionsPendingAction=null,e._sessionsPendingTimer=null},3e3)},onReset:p=>{e.sessionsPendingAction=null,Ac(e,p)},onDelete:p=>{e.sessionsPendingAction=null,Cc(e,p)},onRefresh:()=>{ht(e)},onToggleExpand:p=>{e.sessionsExpandedKey=e.sessionsExpandedKey===p?null:p},onPatch:(p,b)=>{Sc(e,p,b)}}}):(window.location.replace("/chat"),u``)}function _0(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 ec(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function M0(e,t,n){return u`
6103
6098
  <div class="audit-modal-overlay" @click=${s=>{s.target.classList.contains("audit-modal-overlay")&&n()}}>
6104
6099
  <div class="audit-modal-card">
6105
6100
  <div class="audit-modal-header">
@@ -6115,11 +6110,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
6115
6110
  ${e.map(s=>u`
6116
6111
  <div class="audit-modal-entry">
6117
6112
  <div class="audit-modal-entry-path">
6118
- <span class="audit-modal-folder audit-modal-folder--${Xl(s.path)}">${Xl(s.path)}</span>
6113
+ <span class="audit-modal-folder audit-modal-folder--${ec(s.path)}">${ec(s.path)}</span>
6119
6114
  <a href="/files" class="audit-modal-path-link">${s.path}</a>
6120
6115
  </div>
6121
6116
  <div class="audit-modal-entry-meta">
6122
- ${E0(s.timestamp)}
6117
+ ${_0(s.timestamp)}
6123
6118
  <span class="audit-modal-agent">${s.agentId}</span>
6124
6119
  </div>
6125
6120
  </div>
@@ -6131,7 +6126,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
6131
6126
  `}
6132
6127
  </div>
6133
6128
  </div>
6134
- `}const P0={trace:!1,debug:!1,info:!0,warn:!0,error:!0,fatal:!0},_0={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 M0(e){e.basePath=Cf();const t=nt();cc(t.accentColor),uc(t.backgroundColor);const n=document.querySelector('link[rel="icon"]');if(n&&!e.publicChat&&(n.href=t.iconUrl),window.scrollTo(0,0),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}`,ze(e);return}if(bf(e),e.setup){document.title=`${t.name} Setup`,ze(e);return}if(e.filesPage){document.title=`${t.name} Files`,kf(e),ze(e);return}if(e.browserPage){document.title=`${t.name} Browser`,ze(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,ze(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,ze(e);return}if(e.chatPage){document.title=`${t.name} Chat`,ze(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,ze(e),Zi(e),Xi(e);return}_f(e,!0),Ef(e),Tf(e),window.addEventListener("popstate",e.popStateHandler),$f(e),ze(e),yf(e),e.tab==="logs"&&(e.logsSubTab==="session"?Zi(e):Xi(e)),e.tab==="debug"&&_a(e)}function I0(e){Jh(e)}function R0(e){var t;window.removeEventListener("popstate",e.popStateHandler),vf(e),Ta(e),Pa(e),Ma(e),wf(e),xf(e),Pf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function L0(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;pn(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&Lo(e,t.has("tab")||t.has("logsAutoFollow")),(t.has("sessionLogsEntries")||t.has("sessionLogsAutoFollow"))&&e.sessionLogsAutoFollow&&e.logsAtBottom&&Lo(e,t.has("sessionLogsAutoFollow"))}}function B0(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 D0(e,t,n){await ma(e,t,n),await Q(e,!0)}async function N0(e,t){await Tc(e,t),await Q(e,!0)}async function U0(e,t){await Pc(e,t),await Q(e,!0)}async function O0(e,t){await _c(e,t)}async function F0(e,t,n){await Mc(e,t,n)}async function W0(e,t){await Wc(e,t)}async function z0(e){await Zh(e),await He(e),await Q(e,!0)}async function K0(e){await He(e),await Q(e,!0)}function q0(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 vp(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 bp(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function H0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=B0(n??void 0)}function j0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function V0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function G0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function Q0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=vp(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(bp(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:q0(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 Q(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function J0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=vp(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(bp(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 Q(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function Y0(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 X0(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 Z0(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 e$(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}}}async function t$(e){if(e.client){e.authBusy=!0;try{await e.client.request("auth.disconnect",{}),e.authConnected=!1,e.authExpiresIn=null,e.authMessage=null,e.authRefreshToken=null}catch(t){e.authMessage=t instanceof Error?t.message:"Failed to disconnect"}finally{e.authBusy=!1}}}function n$(e,t){e.authCodeInput=t}async function i$(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 s$(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 o$(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 a$(e,t){e.licenseKey=t}async function r$(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 l$(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 c$=Object.defineProperty,u$=Object.getOwnPropertyDescriptor,g=(e,t,n,i)=>{for(var s=i>1?void 0:i?u$(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&&c$(t,n,s),s};const Po=sh();function d$(){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 p$(){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 h$(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function g$(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function f$(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function m$(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function y$(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function v$(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let h=class extends Zt{constructor(){super(...arguments),this.settings=qs(),this.password="",this.tab="chat",this.onboarding=d$(),this.setup=p$(),this.filesPage=h$(),this.browserPage=g$(),this.adminsPage=f$(),this.contactsPage=m$(),this.chatPage=y$(),this.advancedPage=v$(),this.advancedTab="cron",this.sessionsKindFilter="all",this.sessionsChannelFilter="all",this.sessionsAgentFilter="all",this.sessionsPendingAction=null,this.sessionsExpandedKey=null,this._sessionsPendingTimer=null,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=zc,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=Po.name,this.assistantAvatar=Po.avatar,this.assistantAgentId=Po.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.chatSessions=null,this.chatSessionsOpen=!1,this.chatSidebarConfirmDeleteKey=null,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=`{
6129
+ `}const I0={trace:!1,debug:!1,info:!0,warn:!0,error:!0,fatal:!0},R0={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 L0(e){e.basePath=Tf();const t=nt();dc(t.accentColor),pc(t.backgroundColor);const n=document.querySelector('link[rel="icon"]');if(n&&!e.publicChat&&(n.href=t.iconUrl),window.scrollTo(0,0),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}`,ze(e);return}if(kf(e),e.setup){document.title=`${t.name} Setup`,ze(e);return}if(e.filesPage){document.title=`${t.name} Files`,$f(e),ze(e);return}if(e.browserPage){document.title=`${t.name} Browser`,ze(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,ze(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,ze(e);return}if(e.chatPage){document.title=`${t.name} Chat`,ze(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,ze(e),Zi(e),Xi(e);return}If(e,!0),Pf(e),_f(e),window.addEventListener("popstate",e.popStateHandler),Af(e),ze(e),bf(e),e.tab==="logs"&&(e.logsSubTab==="session"?Zi(e):Xi(e)),e.tab==="debug"&&_a(e)}function B0(e){Xh(e)}function D0(e){var t;window.removeEventListener("popstate",e.popStateHandler),wf(e),Ta(e),Pa(e),Ma(e),xf(e),Sf(e),Mf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function N0(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;pn(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&Lo(e,t.has("tab")||t.has("logsAutoFollow")),(t.has("sessionLogsEntries")||t.has("sessionLogsAutoFollow"))&&e.sessionLogsAutoFollow&&e.logsAtBottom&&Lo(e,t.has("sessionLogsAutoFollow"))}}function U0(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 O0(e,t,n){await ma(e,t,n),await Q(e,!0)}async function F0(e,t){await _c(e,t),await Q(e,!0)}async function W0(e,t){await Mc(e,t),await Q(e,!0)}async function z0(e,t){await Ic(e,t)}async function K0(e,t,n){await Rc(e,t,n)}async function q0(e,t){await Kc(e,t)}async function H0(e){await tg(e),await He(e),await Q(e,!0)}async function j0(e){await He(e),await Q(e,!0)}function V0(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 wp(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 kp(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function G0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=U0(n??void 0)}function Q0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function J0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function Y0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function X0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=wp(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(kp(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:V0(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 Q(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function Z0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=wp(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(kp(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 Q(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function e$(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 t$(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 n$(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 i$(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}}}async function s$(e){if(e.client){e.authBusy=!0;try{await e.client.request("auth.disconnect",{}),e.authConnected=!1,e.authExpiresIn=null,e.authMessage=null,e.authRefreshToken=null}catch(t){e.authMessage=t instanceof Error?t.message:"Failed to disconnect"}finally{e.authBusy=!1}}}function o$(e,t){e.authCodeInput=t}async function a$(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 r$(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 l$(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 c$(e,t){e.licenseKey=t}async function u$(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 d$(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 p$=Object.defineProperty,h$=Object.getOwnPropertyDescriptor,g=(e,t,n,i)=>{for(var s=i>1?void 0:i?h$(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&&p$(t,n,s),s};const Po=ah();function g$(){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 f$(){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 m$(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function y$(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function v$(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function b$(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function w$(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function k$(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let h=class extends Zt{constructor(){super(...arguments),this.settings=qs(),this.password="",this.tab="chat",this.onboarding=g$(),this.setup=f$(),this.filesPage=m$(),this.browserPage=y$(),this.adminsPage=v$(),this.contactsPage=b$(),this.chatPage=w$(),this.advancedPage=k$(),this.advancedTab="cron",this.sessionsKindFilter="all",this.sessionsChannelFilter="all",this.sessionsAgentFilter="all",this.sessionsPendingAction=null,this.sessionsExpandedKey=null,this._sessionsPendingTimer=null,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=qc,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=Po.name,this.assistantAvatar=Po.avatar,this.assistantAgentId=Po.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.chatSessions=null,this.chatSessionsOpen=!1,this.chatSidebarConfirmDeleteKey=null,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=`{
6135
6130
  }
6136
- `,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.tunnelStatus=null,this.tunnelBusy=!1,this.tunnelError=null,this.tunnelAuthUrl=null,this.tunnelSetupStep=0,this.tunnelQrDataUrl=null,this.tunnelHostnameInput="",this.tunnelUsernameInput="admin",this.tunnelPasswordInput="",this.tunnelPasswordConfirmInput="",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={..._0},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=er(),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.selectableTools=[],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.telegramAdmins=[],this.adminsNewTelegramUsername="",this.adminsActiveTab="whatsapp",this.adminsPageTab="external",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.telegramBusy=!1,this.telegramSettingsOpen=!1,this.telegramConnectOpen=!1,this.telegramConnectToken="",this.telegramProbeResult=null,this.telegramProbing=!1,this.telegramError=null,this.telegramAddingBot=!1,this.telegramNewBotName="",this.telegramNewBotDmPolicy="open",this.telegramNewBotAdminRouting=!0,this.telegramBotSaving=!1,this.telegramBotError=null,this.telegramDmPolicySaving=!1,this.telegramWhitelistSaving=!1,this.telegramWhitelistError=null,this.telegramNewWhitelistUsername="",this.telegramExpandedBotId=null,this.telegramPairingRequests=[],this.telegramPairingLoading=!1,this.telegramPairingActioning=new Set,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.adminUsersModalOpen=!1,this.adminUsersAddBusy=!1,this.adminUsersAddError=null,this.adminUsersRemoveConfirm=null,this.adminUsersRemoveBusy=!1,this.adminUsersChangePinUsername=null,this.adminUsersChangePinBusy=!1,this.adminUsersChangePinError=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={...P0},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=()=>Mf(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._beforeUnloadHandler=()=>{var t;Io();const e=this.selectedWorkspace??((t=this.publicChatConfig)==null?void 0:t.accountId)??"";e&&Jn(e,this.sessionKey,this.chatMessage)}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),M0(this),window.addEventListener("beforeunload",this._beforeUnloadHandler)}firstUpdated(){I0(this)}disconnectedCallback(){window.removeEventListener("beforeunload",this._beforeUnloadHandler),this.stopEmbeddingPoll(),R0(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){L0(this,e),typeof window.lucide<"u"&&window.lucide.createIcons()}connect(){ze(this)}handleChatScroll(e){Kh(this,e)}handleLogsScroll(e){Hh(this,e)}handleSessionLogsScroll(e){jh(this,e)}exportLogs(e,t){Gh(e,t)}exportSessionLogs(e,t){Qh(e,t)}resetToolStream(){fa(this)}resetChatScroll(){Vh(this)}async loadAssistantIdentity(){await aa(this)}applySettings(e){ut(this,e)}setTab(e){Sf(this,e)}setTheme(e,t){Af(this,e,t)}async loadOverview(){await Uu(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 Ou(this)}async handleAbortChat(){await Wu(this)}removeQueuedMessage(e){Bf(this,e)}async handleSendChat(e,t){await Df(this,e,t)}async handleWhatsAppStart(e,t){await D0(this,e,t)}async handleWhatsAppWait(e){await N0(this,e)}async handleWhatsAppLogout(e){await U0(this,e)}async handleAddWhatsAppAccount(e){await O0(this,e)}async handleAddCloudApiAccount(e,t){await F0(this,e,t)}async handleRemoveWhatsAppAccount(e){await W0(this,e)}async handleAccessCheck(){await bi(this)}async handlePinSubmit(e,t){await cg(this,e,t),this.accessState.authenticated&&(this.accessState.workspace?this.handleWorkspaceSelect(this.accessState.workspace):this.reloadCurrentPageData())}async handleSetMasterPin(e){await ug(this,e)}async handleLogout(){await pg(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{if(e.startsWith("admin:")){const i=e.slice(6),s=await this.client.request("access.changeAdminPin",{username:i,currentPin:t,newPin:n});if(!s.ok){this.changePinError=s.message??"Incorrect current PIN",this.changePinBusy=!1;return}}else{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 bi(this),setTimeout(()=>{this.accountPinModalOpen=!1,this.accountPinSuccess=null,this.accountPinError=null},1500)}catch{this.accountPinError="Failed to save PIN",this.accountPinBusy=!1}}}async handleAdminUsersAdd(e,t){if(this.client){this.adminUsersAddBusy=!0,this.adminUsersAddError=null;try{const n=Tt(),i=await this.client.request("access.addAdmin",{username:e,pin:t,accessToken:n});if(i.ok===!1){this.adminUsersAddError=i.message??"Failed to add admin",this.adminUsersAddBusy=!1;return}this.adminUsersAddBusy=!1,await bi(this)}catch(n){this.adminUsersAddError=String(n)||"Failed to add admin",this.adminUsersAddBusy=!1}}}async handleAdminUsersRemove(e){if(this.client){this.adminUsersRemoveBusy=!0;try{const t=Tt();await this.client.request("access.removeAdmin",{username:e,accessToken:t}),this.adminUsersRemoveConfirm=null,this.adminUsersRemoveBusy=!1,await bi(this)}catch{this.adminUsersRemoveBusy=!1}}}async handleAdminUsersUpdatePin(e,t){if(this.client){this.adminUsersChangePinBusy=!0,this.adminUsersChangePinError=null;try{const n=Tt(),i=await this.client.request("access.updateAdminPin",{username:e,pin:t,accessToken:n});if(i.ok===!1){this.adminUsersChangePinError=i.message??"Failed to update PIN",this.adminUsersChangePinBusy=!1;return}this.adminUsersChangePinUsername=null,this.adminUsersChangePinBusy=!1,this.adminUsersChangePinError=null}catch{this.adminUsersChangePinError="Failed to update PIN",this.adminUsersChangePinBusy=!1}}}async handleLicenseStatusCheck(){await i$(this)}async handleLicenseActivate(){await s$(this)}async handleLicenseRemove(){await o$(this)}handleLicenseKeyChange(e){a$(this,e)}async handleAuthStatusCheck(){await X0(this)}async handleAuthStart(){await Z0(this)}async handleAuthSubmitCode(e){await e$(this,e)}handleAuthCodeChange(e){n$(this,e)}handleClaudeAuthModalOpen(){this.claudeAuthModalOpen=!0}handleClaudeAuthModalClose(){this.claudeAuthModalOpen=!1,this.authUrl=null,this.authMessage=null,this.authRefreshTokenInput="",this.authRefreshTokenError=null}async handleDisconnect(){await t$(this),this.handleClaudeAuthModalClose()}async handleImportRefreshToken(){await Y0(this)}async handleGatewayHealthCheck(){await r$(this)}async handleGatewayRestart(){await l$(this)}async handleUpdateCheck(){await sp(this)}async handleUpdateRun(){await qx(this)}handleUpdateDismissResult(){Vx(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 se(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>jr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){se(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>jr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await Mu(this)}async clearAudit(){await of(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,fn(this,t),xs(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();se(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>p0);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}async loadChatSessions(){if(!(!this.client||!this.connected))try{const e=await this.client.request("sessions.list",{accountId:this.selectedWorkspace}),n=`webchat:${this.resolveAdminAgentId()??"main"}:`,i=[];for(const o of e.sessions){const a=o.key.indexOf(n);if(a<0)continue;const r=o.key.substring(a);i.push({...o,key:r})}const s=this.sessionKey;s.startsWith("webchat:")&&s.startsWith(n)&&!i.some(o=>o.key===s)&&i.unshift({key:s,kind:"direct",updatedAt:Date.now()}),this.chatSessions={...e,sessions:i,count:i.length}}catch{}}newSession(){const t=`webchat:${this.resolveAdminAgentId()??"main"}:${Date.now()}`;this.sessionKey=t,this.chatMessage="",this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t});const n={key:t,kind:"direct",updatedAt:Date.now()},i=this.chatSessions;this.chatSessions={ts:Date.now(),path:(i==null?void 0:i.path)??"",count:((i==null?void 0:i.sessions.length)??0)+1,defaults:(i==null?void 0:i.defaults)??{model:null,contextTokens:null},sessions:[n,...(i==null?void 0:i.sessions)??[]]},this.chatSessionsOpen=!1,this.resetChatScroll()}selectSession(e){this.sessionKey=e,this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.applySettings({...this.settings,sessionKey:e,lastActiveSessionKey:e}),this.chatSessionsOpen=!1,se(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this)})}async renameSession(e,t){this.chatSessions&&(this.chatSessions={...this.chatSessions,sessions:this.chatSessions.sessions.map(n=>n.key===e?{...n,label:t??void 0}:n)});try{const{patchSession:n}=await se(async()=>{const{patchSession:i}=await Promise.resolve().then(()=>Qs);return{patchSession:i}},void 0,import.meta.url);await n(this,e,{label:t})}catch{await this.loadChatSessions()}}async deleteChatSession(e){var n,i;this.chatSidebarConfirmDeleteKey=null;const t=((n=this.chatSessions)==null?void 0:n.sessions.filter(s=>s.key!==e))??[];if(this.chatSessions&&(this.chatSessions={...this.chatSessions,sessions:t,count:t.length}),this.sessionKey===e){const s=((i=t[0])==null?void 0:i.key)??"";this.sessionKey=s,this.chatMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.applySettings({...this.settings,sessionKey:s||"cleared",lastActiveSessionKey:s||"cleared"}),s&&se(async()=>{const{loadChatHistory:o}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:o}},void 0,import.meta.url).then(({loadChatHistory:o})=>{o(this)})}se(async()=>{const{deleteSession:s}=await Promise.resolve().then(()=>Qs);return{deleteSession:s}},void 0,import.meta.url).then(({deleteSession:s})=>s(this,e))}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&&!this.sessionKey.startsWith("webchat:")&&this.sessionKey!==""&&this.sessionKey!=="cleared"){const t=`webchat:${e}:${Date.now()}`;this.sessionKey=t,this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.resetChatScroll(),this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity()}this.loadChatSessions(),se(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this).then(()=>{pn(this,!0)})})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=qh(this),{loadOlderChatHistory:t}=await se(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>Yt);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"&&se(async()=>{const{loadOpeningHours:n}=await Promise.resolve().then(()=>c0);return{loadOpeningHours:n}},void 0,import.meta.url).then(({loadOpeningHours:n})=>{n(this)}),this.advancedTab==="logs"&&(this.logsSubTab==="session"?se(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>_u);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):se(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>yg);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&se(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>Yg);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})}),this.advancedTab==="sessions"&&se(async()=>{const{loadSessions:n}=await Promise.resolve().then(()=>Qs);return{loadSessions:n}},void 0,import.meta.url).then(({loadSessions:n})=>{n(this)})}async handleChannelConfigSave(){await z0(this)}async handleChannelConfigReload(){await K0(this)}handleNostrProfileEdit(e,t){H0(this,e,t)}handleNostrProfileCancel(){j0(this)}handleNostrProfileFieldChange(e,t){V0(this,e,t)}async handleNostrProfileSave(){await Q0(this)}async handleNostrProfileImport(){await J0(this)}handleNostrProfileToggleAdvanced(){G0(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;se(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>h0);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 se(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>Mi);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await se(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>Mi);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await se(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>rg);return{loadChannels:s}},void 0,import.meta.url);await n(this,{name:e,workspacePath:t,onCreated:s=>{if(!s.accountId)return;const o=s.accountId;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 se(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>Mi);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 se(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>Mi);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){Io(),this.selectedWorkspace&&Jn(this.selectedWorkspace,this.sessionKey,this.chatMessage),this.selectedWorkspace=e,this.publicChatQrDataUrl=null,localStorage.setItem("taskmaster-selected-workspace",e),Nn(e),Ir(e),this.settings=qs(),this.chatMessage=Yn(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.chatSessions=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.publicChat||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.accountId,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)}Nn(this.selectedWorkspace),Ir(this.selectedWorkspace),this.settings=qs(),this.sessionKey=this.settings.sessionKey,this.chatMessage=Yn(this.selectedWorkspace,this.settings.sessionKey),this.reloadCurrentPageData()}render(){return u`${C0(this)}${this.auditModalOpen?T0(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):w}`}};g([f()],h.prototype,"settings",2);g([f()],h.prototype,"password",2);g([f()],h.prototype,"tab",2);g([f()],h.prototype,"onboarding",2);g([f()],h.prototype,"setup",2);g([f()],h.prototype,"filesPage",2);g([f()],h.prototype,"browserPage",2);g([f()],h.prototype,"adminsPage",2);g([f()],h.prototype,"contactsPage",2);g([f()],h.prototype,"chatPage",2);g([f()],h.prototype,"advancedPage",2);g([f()],h.prototype,"advancedTab",2);g([f()],h.prototype,"sessionsKindFilter",2);g([f()],h.prototype,"sessionsChannelFilter",2);g([f()],h.prototype,"sessionsAgentFilter",2);g([f()],h.prototype,"sessionsPendingAction",2);g([f()],h.prototype,"sessionsExpandedKey",2);g([f()],h.prototype,"publicChat",2);g([f()],h.prototype,"publicChatConfig",2);g([f()],h.prototype,"publicChatSessionKey",2);g([f()],h.prototype,"publicChatAuthenticated",2);g([f()],h.prototype,"publicChatAuthStep",2);g([f()],h.prototype,"connected",2);g([f()],h.prototype,"accessState",2);g([f()],h.prototype,"theme",2);g([f()],h.prototype,"themeResolved",2);g([f()],h.prototype,"hello",2);g([f()],h.prototype,"lastError",2);g([f()],h.prototype,"eventLog",2);g([f()],h.prototype,"assistantName",2);g([f()],h.prototype,"assistantAvatar",2);g([f()],h.prototype,"assistantAgentId",2);g([f()],h.prototype,"sessionKey",2);g([f()],h.prototype,"chatLoading",2);g([f()],h.prototype,"chatSending",2);g([f()],h.prototype,"chatMessage",2);g([f()],h.prototype,"chatMessages",2);g([f()],h.prototype,"chatHistoryTotal",2);g([f()],h.prototype,"chatHistoryHasMore",2);g([f()],h.prototype,"chatLoadingOlder",2);g([f()],h.prototype,"chatToolMessages",2);g([f()],h.prototype,"chatStream",2);g([f()],h.prototype,"chatInterimText",2);g([f()],h.prototype,"chatSuggestions",2);g([f()],h.prototype,"chatStreamStartedAt",2);g([f()],h.prototype,"chatRunId",2);g([f()],h.prototype,"compactionStatus",2);g([f()],h.prototype,"chatAvatarUrl",2);g([f()],h.prototype,"chatModelCatalog",2);g([f()],h.prototype,"chatVerboseLevel",2);g([f()],h.prototype,"chatQueue",2);g([f()],h.prototype,"chatAttachments",2);g([f()],h.prototype,"sidebarOpen",2);g([f()],h.prototype,"sidebarContent",2);g([f()],h.prototype,"sidebarError",2);g([f()],h.prototype,"splitRatio",2);g([f()],h.prototype,"chatSessions",2);g([f()],h.prototype,"chatSessionsOpen",2);g([f()],h.prototype,"chatSidebarConfirmDeleteKey",2);g([f()],h.prototype,"nodesLoading",2);g([f()],h.prototype,"nodes",2);g([f()],h.prototype,"devicesLoading",2);g([f()],h.prototype,"devicesError",2);g([f()],h.prototype,"devicesList",2);g([f()],h.prototype,"execApprovalsLoading",2);g([f()],h.prototype,"execApprovalsSaving",2);g([f()],h.prototype,"execApprovalsDirty",2);g([f()],h.prototype,"execApprovalsSnapshot",2);g([f()],h.prototype,"execApprovalsForm",2);g([f()],h.prototype,"execApprovalsSelectedAgent",2);g([f()],h.prototype,"execApprovalsTarget",2);g([f()],h.prototype,"execApprovalsTargetNodeId",2);g([f()],h.prototype,"execApprovalQueue",2);g([f()],h.prototype,"execApprovalBusy",2);g([f()],h.prototype,"execApprovalError",2);g([f()],h.prototype,"configLoading",2);g([f()],h.prototype,"configRaw",2);g([f()],h.prototype,"configRawOriginal",2);g([f()],h.prototype,"configValid",2);g([f()],h.prototype,"configIssues",2);g([f()],h.prototype,"configSaving",2);g([f()],h.prototype,"configApplying",2);g([f()],h.prototype,"updateRunning",2);g([f()],h.prototype,"applySessionKey",2);g([f()],h.prototype,"configSnapshot",2);g([f()],h.prototype,"configSchema",2);g([f()],h.prototype,"configSchemaVersion",2);g([f()],h.prototype,"configSchemaLoading",2);g([f()],h.prototype,"configUiHints",2);g([f()],h.prototype,"configForm",2);g([f()],h.prototype,"configFormOriginal",2);g([f()],h.prototype,"configFormDirty",2);g([f()],h.prototype,"configFormMode",2);g([f()],h.prototype,"configSearchQuery",2);g([f()],h.prototype,"configActiveSection",2);g([f()],h.prototype,"configActiveSubsection",2);g([f()],h.prototype,"channelsLoading",2);g([f()],h.prototype,"channelsSnapshot",2);g([f()],h.prototype,"channelsError",2);g([f()],h.prototype,"channelsLastSuccess",2);g([f()],h.prototype,"whatsappLoginMessage",2);g([f()],h.prototype,"whatsappLoginQrDataUrl",2);g([f()],h.prototype,"whatsappLoginConnected",2);g([f()],h.prototype,"whatsappBusy",2);g([f()],h.prototype,"whatsappActiveQrAccountId",2);g([f()],h.prototype,"whatsappPairedPhone",2);g([f()],h.prototype,"addingWhatsAppAccount",2);g([f()],h.prototype,"newWhatsAppAccountName",2);g([f()],h.prototype,"newWhatsAppAccountProvider",2);g([f()],h.prototype,"newCloudPhoneNumberId",2);g([f()],h.prototype,"newCloudBusinessAccountId",2);g([f()],h.prototype,"newCloudAccessToken",2);g([f()],h.prototype,"newCloudWebhookVerifyToken",2);g([f()],h.prototype,"whatsappAccountError",2);g([f()],h.prototype,"whatsappAccountSaving",2);g([f()],h.prototype,"whatsappSettingsOpen",2);g([f()],h.prototype,"publicChatToggleBusy",2);g([f()],h.prototype,"publicChatGreetingBusy",2);g([f()],h.prototype,"publicChatEmailBusy",2);g([f()],h.prototype,"publicChatSettingsOpen",2);g([f()],h.prototype,"publicChatWidgetModalOpen",2);g([f()],h.prototype,"brandingBusy",2);g([f()],h.prototype,"agentSettingsOpen",2);g([f()],h.prototype,"brandingExpanded",2);g([f()],h.prototype,"tailscaleStatus",2);g([f()],h.prototype,"tailscaleBusy",2);g([f()],h.prototype,"tailscaleAuthUrl",2);g([f()],h.prototype,"tailscaleError",2);g([f()],h.prototype,"tailscaleServeEnableUrl",2);g([f()],h.prototype,"tailscaleFunnelEnableUrl",2);g([f()],h.prototype,"tailscaleDisableConfirm",2);g([f()],h.prototype,"tailscaleConnectProgress",2);g([f()],h.prototype,"tailscaleConnectMessage",2);g([f()],h.prototype,"tailscaleConnectSuccess",2);g([f()],h.prototype,"tunnelStatus",2);g([f()],h.prototype,"tunnelBusy",2);g([f()],h.prototype,"tunnelError",2);g([f()],h.prototype,"tunnelAuthUrl",2);g([f()],h.prototype,"tunnelSetupStep",2);g([f()],h.prototype,"tunnelQrDataUrl",2);g([f()],h.prototype,"tunnelHostnameInput",2);g([f()],h.prototype,"tunnelUsernameInput",2);g([f()],h.prototype,"tunnelPasswordInput",2);g([f()],h.prototype,"tunnelPasswordConfirmInput",2);g([f()],h.prototype,"wifiStatus",2);g([f()],h.prototype,"wifiNetworks",2);g([f()],h.prototype,"wifiBusy",2);g([f()],h.prototype,"wifiError",2);g([f()],h.prototype,"wifiPassword",2);g([f()],h.prototype,"wifiSelectedSsid",2);g([f()],h.prototype,"networkPort",2);g([f()],h.prototype,"networkHostname",2);g([f()],h.prototype,"networkPortInput",2);g([f()],h.prototype,"networkHostnameInput",2);g([f()],h.prototype,"networkModalOpen",2);g([f()],h.prototype,"networkBusy",2);g([f()],h.prototype,"networkError",2);g([f()],h.prototype,"networkSuccess",2);g([f()],h.prototype,"wifiModalOpen",2);g([f()],h.prototype,"licenseKey",2);g([f()],h.prototype,"licenseBusy",2);g([f()],h.prototype,"licenseValid",2);g([f()],h.prototype,"licenseMessage",2);g([f()],h.prototype,"licenseTier",2);g([f()],h.prototype,"licenseDeviceId",2);g([f()],h.prototype,"licenseStoredKey",2);g([f()],h.prototype,"licenseRemoveConfirm",2);g([f()],h.prototype,"authConnected",2);g([f()],h.prototype,"authBusy",2);g([f()],h.prototype,"authMessage",2);g([f()],h.prototype,"authUrl",2);g([f()],h.prototype,"authCodeInput",2);g([f()],h.prototype,"authExpiresIn",2);g([f()],h.prototype,"authRefreshToken",2);g([f()],h.prototype,"claudeAuthModalOpen",2);g([f()],h.prototype,"authRefreshTokenInput",2);g([f()],h.prototype,"authRefreshTokenBusy",2);g([f()],h.prototype,"authRefreshTokenError",2);g([f()],h.prototype,"setupStep",2);g([f()],h.prototype,"gatewayHealthy",2);g([f()],h.prototype,"gatewayHealthLoading",2);g([f()],h.prototype,"gatewayHealthMessage",2);g([f()],h.prototype,"gatewayRestartBusy",2);g([f()],h.prototype,"updateAvailable",2);g([f()],h.prototype,"currentVersion",2);g([f()],h.prototype,"latestVersion",2);g([f()],h.prototype,"updateChecking",2);g([f()],h.prototype,"updateMessage",2);g([f()],h.prototype,"updateProgressSteps",2);g([f()],h.prototype,"updateLastResult",2);g([f()],h.prototype,"uninstallConfirm",2);g([f()],h.prototype,"uninstallBusy",2);g([f()],h.prototype,"uninstallDone",2);g([f()],h.prototype,"uninstallError",2);g([f()],h.prototype,"uninstallConfirmText",2);g([f()],h.prototype,"nostrProfileFormState",2);g([f()],h.prototype,"nostrProfileAccountId",2);g([f()],h.prototype,"presenceLoading",2);g([f()],h.prototype,"presenceEntries",2);g([f()],h.prototype,"presenceError",2);g([f()],h.prototype,"presenceStatus",2);g([f()],h.prototype,"agentsLoading",2);g([f()],h.prototype,"agentsList",2);g([f()],h.prototype,"agentsError",2);g([f()],h.prototype,"sessionsLoading",2);g([f()],h.prototype,"sessionsResult",2);g([f()],h.prototype,"sessionsError",2);g([f()],h.prototype,"cronLoading",2);g([f()],h.prototype,"cronJobs",2);g([f()],h.prototype,"cronStatus",2);g([f()],h.prototype,"cronError",2);g([f()],h.prototype,"cronForm",2);g([f()],h.prototype,"cronRunsJobId",2);g([f()],h.prototype,"cronRuns",2);g([f()],h.prototype,"cronBusy",2);g([f()],h.prototype,"cronNewEventModal",2);g([f()],h.prototype,"cronDetailJobId",2);g([f()],h.prototype,"cronEditJobId",2);g([f()],h.prototype,"cronPendingDeleteId",2);g([f()],h.prototype,"cronRunModalJobId",2);g([f()],h.prototype,"cronRunModalJobName",2);g([f()],h.prototype,"cronRunResult",2);g([f()],h.prototype,"openingHoursLoading",2);g([f()],h.prototype,"openingHoursError",2);g([f()],h.prototype,"openingHoursBusy",2);g([f()],h.prototype,"openingHoursForm",2);g([f()],h.prototype,"browserScreencastActive",2);g([f()],h.prototype,"browserScreencastFrame",2);g([f()],h.prototype,"browserScreencastMetadata",2);g([f()],h.prototype,"browserHandoffPending",2);g([f()],h.prototype,"browserHandoffReason",2);g([f()],h.prototype,"browserHandoffId",2);g([f()],h.prototype,"browserInputMode",2);g([f()],h.prototype,"browserFullscreen",2);g([f()],h.prototype,"browserLoading",2);g([f()],h.prototype,"browserError",2);g([f()],h.prototype,"filesLoading",2);g([f()],h.prototype,"filesTree",2);g([f()],h.prototype,"filesRoot",2);g([f()],h.prototype,"filesError",2);g([f()],h.prototype,"filesSelectedPath",2);g([f()],h.prototype,"filesSelectedPaths",2);g([f()],h.prototype,"filesPreviewContent",2);g([f()],h.prototype,"filesPreviewLoading",2);g([f()],h.prototype,"filesPreviewBinary",2);g([f()],h.prototype,"filesPreviewSize",2);g([f()],h.prototype,"filesExpandedDirs",2);g([f()],h.prototype,"filesCurrentDir",2);g([f()],h.prototype,"filesPendingDeletePath",2);g([f()],h.prototype,"filesMessage",2);g([f()],h.prototype,"filesUploadBusy",2);g([f()],h.prototype,"filesReindexBusy",2);g([f()],h.prototype,"filesMemoryStatus",2);g([f()],h.prototype,"embeddingDownloading",2);g([f()],h.prototype,"filesSearchQuery",2);g([f()],h.prototype,"filesSearchResults",2);g([f()],h.prototype,"filesSearchLoading",2);g([f()],h.prototype,"filesSearchAgentId",2);g([f()],h.prototype,"auditEntries",2);g([f()],h.prototype,"auditLoading",2);g([f()],h.prototype,"auditModalOpen",2);g([f()],h.prototype,"skillsLoading",2);g([f()],h.prototype,"skillsReport",2);g([f()],h.prototype,"skillsError",2);g([f()],h.prototype,"skillsFilter",2);g([f()],h.prototype,"skillsTypeFilter",2);g([f()],h.prototype,"skillsAgentFilter",2);g([f()],h.prototype,"selectableTools",2);g([f()],h.prototype,"skillEdits",2);g([f()],h.prototype,"skillsBusyKey",2);g([f()],h.prototype,"skillMessages",2);g([f()],h.prototype,"skillDetail",2);g([f()],h.prototype,"skillDetailTab",2);g([f()],h.prototype,"skillAddModal",2);g([f()],h.prototype,"skillAddForm",2);g([f()],h.prototype,"skillAddFormSource",2);g([f()],h.prototype,"skillEditTab",2);g([f()],h.prototype,"skillDrafts",2);g([f()],h.prototype,"adminsLoading",2);g([f()],h.prototype,"adminPhones",2);g([f()],h.prototype,"telegramAdmins",2);g([f()],h.prototype,"adminsNewTelegramUsername",2);g([f()],h.prototype,"adminsActiveTab",2);g([f()],h.prototype,"adminsPageTab",2);g([f()],h.prototype,"adminsError",2);g([f()],h.prototype,"adminsSaving",2);g([f()],h.prototype,"adminsNewPhone",2);g([f()],h.prototype,"contactsLoading",2);g([f()],h.prototype,"contactsSaving",2);g([f()],h.prototype,"contactsRecords",2);g([f()],h.prototype,"contactsError",2);g([f()],h.prototype,"contactsSearchQuery",2);g([f()],h.prototype,"contactsEditingId",2);g([f()],h.prototype,"contactsShowAddForm",2);g([f()],h.prototype,"contactsNewPhone",2);g([f()],h.prototype,"contactsNewName",2);g([f()],h.prototype,"contactsDeleteConfirmId",2);g([f()],h.prototype,"contactsAddFieldForId",2);g([f()],h.prototype,"contactsAddFieldKey",2);g([f()],h.prototype,"contactsAddFieldValue",2);g([f()],h.prototype,"imessageEnableConfirm",2);g([f()],h.prototype,"imessageEnabling",2);g([f()],h.prototype,"telegramBusy",2);g([f()],h.prototype,"telegramSettingsOpen",2);g([f()],h.prototype,"telegramConnectOpen",2);g([f()],h.prototype,"telegramConnectToken",2);g([f()],h.prototype,"telegramProbeResult",2);g([f()],h.prototype,"telegramProbing",2);g([f()],h.prototype,"telegramError",2);g([f()],h.prototype,"telegramAddingBot",2);g([f()],h.prototype,"telegramNewBotName",2);g([f()],h.prototype,"telegramNewBotDmPolicy",2);g([f()],h.prototype,"telegramNewBotAdminRouting",2);g([f()],h.prototype,"telegramBotSaving",2);g([f()],h.prototype,"telegramBotError",2);g([f()],h.prototype,"telegramDmPolicySaving",2);g([f()],h.prototype,"telegramWhitelistSaving",2);g([f()],h.prototype,"telegramWhitelistError",2);g([f()],h.prototype,"telegramNewWhitelistUsername",2);g([f()],h.prototype,"telegramExpandedBotId",2);g([f()],h.prototype,"telegramPairingRequests",2);g([f()],h.prototype,"telegramPairingLoading",2);g([f()],h.prototype,"telegramPairingActioning",2);g([f()],h.prototype,"chatPageTab",2);g([f()],h.prototype,"waConversations",2);g([f()],h.prototype,"waSelectedJid",2);g([f()],h.prototype,"waMessages",2);g([f()],h.prototype,"waGroupInfo",2);g([f()],h.prototype,"waLoading",2);g([f()],h.prototype,"waMessagesLoading",2);g([f()],h.prototype,"waSearchQuery",2);g([f()],h.prototype,"waComposeDraft",2);g([f()],h.prototype,"waSending",2);g([f()],h.prototype,"waLastError",2);g([f()],h.prototype,"infoModalOpen",2);g([f()],h.prototype,"remoteAccessQrDataUrl",2);g([f()],h.prototype,"publicChatQrDataUrl",2);g([f()],h.prototype,"workspaces",2);g([f()],h.prototype,"workspacesLoading",2);g([f()],h.prototype,"workspacesError",2);g([f()],h.prototype,"selectedWorkspace",2);g([f()],h.prototype,"addingWorkspace",2);g([f()],h.prototype,"newWorkspaceName",2);g([f()],h.prototype,"newWorkspacePath",2);g([f()],h.prototype,"newWorkspacePin",2);g([f()],h.prototype,"accountPinModalOpen",2);g([f()],h.prototype,"accountPinBusy",2);g([f()],h.prototype,"accountPinError",2);g([f()],h.prototype,"accountPinSuccess",2);g([f()],h.prototype,"adminUsersModalOpen",2);g([f()],h.prototype,"adminUsersAddBusy",2);g([f()],h.prototype,"adminUsersAddError",2);g([f()],h.prototype,"adminUsersRemoveConfirm",2);g([f()],h.prototype,"adminUsersRemoveBusy",2);g([f()],h.prototype,"adminUsersChangePinUsername",2);g([f()],h.prototype,"adminUsersChangePinBusy",2);g([f()],h.prototype,"adminUsersChangePinError",2);g([f()],h.prototype,"apiKeyProviders",2);g([f()],h.prototype,"apiKeyModalOpen",2);g([f()],h.prototype,"apiKeyBusy",2);g([f()],h.prototype,"apiKeyError",2);g([f()],h.prototype,"apiKeySuccess",2);g([f()],h.prototype,"apiKeySavingProvider",2);g([f()],h.prototype,"authApiKeyMode",2);g([f()],h.prototype,"authApiKeyInput",2);g([f()],h.prototype,"authApiKeyBusy",2);g([f()],h.prototype,"authApiKeyError",2);g([f()],h.prototype,"pinChanging",2);g([f()],h.prototype,"pinChangeBusy",2);g([f()],h.prototype,"pinChangeError",2);g([f()],h.prototype,"loginChangePinMode",2);g([f()],h.prototype,"changePinBusy",2);g([f()],h.prototype,"changePinError",2);g([f()],h.prototype,"changePinSuccess",2);g([f()],h.prototype,"workspaceSaving",2);g([f()],h.prototype,"workspaceRemoveConfirm",2);g([f()],h.prototype,"renamingWorkspace",2);g([f()],h.prototype,"renameWorkspaceName",2);g([f()],h.prototype,"debugLoading",2);g([f()],h.prototype,"debugStatus",2);g([f()],h.prototype,"debugHealth",2);g([f()],h.prototype,"debugModels",2);g([f()],h.prototype,"debugHeartbeat",2);g([f()],h.prototype,"debugCallMethod",2);g([f()],h.prototype,"debugCallParams",2);g([f()],h.prototype,"debugCallResult",2);g([f()],h.prototype,"debugCallError",2);g([f()],h.prototype,"logsLoading",2);g([f()],h.prototype,"logsError",2);g([f()],h.prototype,"logsFile",2);g([f()],h.prototype,"logsEntries",2);g([f()],h.prototype,"logsFilterText",2);g([f()],h.prototype,"logsLevelFilters",2);g([f()],h.prototype,"logsAutoFollow",2);g([f()],h.prototype,"logsTruncated",2);g([f()],h.prototype,"logsCursor",2);g([f()],h.prototype,"logsLastFetchAt",2);g([f()],h.prototype,"logsLimit",2);g([f()],h.prototype,"logsMaxBytes",2);g([f()],h.prototype,"logsAtBottom",2);g([f()],h.prototype,"logsDate",2);g([f()],h.prototype,"logsAvailableDates",2);g([f()],h.prototype,"logsSubTab",2);g([f()],h.prototype,"logsChipsExpanded",2);g([f()],h.prototype,"sessionLogsLoading",2);g([f()],h.prototype,"sessionLogsError",2);g([f()],h.prototype,"sessionLogsEntries",2);g([f()],h.prototype,"sessionLogsFilterText",2);g([f()],h.prototype,"sessionLogsTypeFilters",2);g([f()],h.prototype,"sessionLogsAgentFilters",2);g([f()],h.prototype,"sessionLogsAgents",2);g([f()],h.prototype,"sessionLogsAutoFollow",2);g([f()],h.prototype,"sessionLogsChipsExpanded",2);g([f()],h.prototype,"sessionLogsCursors",2);g([f()],h.prototype,"sessionLogsLastFetchAt",2);g([f()],h.prototype,"sessionLogsAtBottom",2);g([f()],h.prototype,"chatUserNearBottom",2);h=g([rc("taskmaster-app")],h);
6137
- //# sourceMappingURL=index-c6Rca5oP.js.map
6131
+ `,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.tunnelStatus=null,this.tunnelBusy=!1,this.tunnelError=null,this.tunnelAuthUrl=null,this.tunnelSetupStep=0,this.tunnelQrDataUrl=null,this.tunnelHostnameInput="",this.tunnelUsernameInput="admin",this.tunnelPasswordInput="",this.tunnelPasswordConfirmInput="",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={...R0},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.openingHoursSaved=!1,this.openingHoursForm=er(),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.selectableTools=[],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.telegramAdmins=[],this.adminsNewTelegramUsername="",this.adminsActiveTab="whatsapp",this.adminsPageTab="external",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.telegramBusy=!1,this.telegramSettingsOpen=!1,this.telegramConnectOpen=!1,this.telegramConnectToken="",this.telegramProbeResult=null,this.telegramProbing=!1,this.telegramError=null,this.telegramAddingBot=!1,this.telegramNewBotName="",this.telegramNewBotDmPolicy="open",this.telegramNewBotAdminRouting=!0,this.telegramBotSaving=!1,this.telegramBotError=null,this.telegramDmPolicySaving=!1,this.telegramWhitelistSaving=!1,this.telegramWhitelistError=null,this.telegramNewWhitelistUsername="",this.telegramExpandedBotId=null,this.telegramPairingRequests=[],this.telegramPairingLoading=!1,this.telegramPairingActioning=new Set,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.adminUsersModalOpen=!1,this.adminUsersAddBusy=!1,this.adminUsersAddError=null,this.adminUsersRemoveConfirm=null,this.adminUsersRemoveBusy=!1,this.adminUsersChangePinUsername=null,this.adminUsersChangePinBusy=!1,this.adminUsersChangePinError=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={...I0},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=()=>Rf(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._beforeUnloadHandler=()=>{var t;Io();const e=this.selectedWorkspace??((t=this.publicChatConfig)==null?void 0:t.accountId)??"";e&&Jn(e,this.sessionKey,this.chatMessage)}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),L0(this),window.addEventListener("beforeunload",this._beforeUnloadHandler)}firstUpdated(){B0(this)}disconnectedCallback(){window.removeEventListener("beforeunload",this._beforeUnloadHandler),this.stopEmbeddingPoll(),D0(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){N0(this,e),typeof window.lucide<"u"&&window.lucide.createIcons()}connect(){ze(this)}handleChatScroll(e){Hh(this,e)}handleLogsScroll(e){Vh(this,e)}handleSessionLogsScroll(e){Gh(this,e)}exportLogs(e,t){Jh(e,t)}exportSessionLogs(e,t){Yh(e,t)}resetToolStream(){fa(this)}resetChatScroll(){Qh(this)}async loadAssistantIdentity(){await aa(this)}applySettings(e){ut(this,e)}setTab(e){Cf(this,e)}setTheme(e,t){Ef(this,e,t)}async loadOverview(){await Fu(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 Wu(this)}async handleAbortChat(){await Ku(this)}removeQueuedMessage(e){Nf(this,e)}async handleSendChat(e,t){await Uf(this,e,t)}async handleWhatsAppStart(e,t){await O0(this,e,t)}async handleWhatsAppWait(e){await F0(this,e)}async handleWhatsAppLogout(e){await W0(this,e)}async handleAddWhatsAppAccount(e){await z0(this,e)}async handleAddCloudApiAccount(e,t){await K0(this,e,t)}async handleRemoveWhatsAppAccount(e){await q0(this,e)}async handleAccessCheck(){await bi(this)}async handlePinSubmit(e,t){await dg(this,e,t),this.accessState.authenticated&&(this.accessState.workspace?this.handleWorkspaceSelect(this.accessState.workspace):this.reloadCurrentPageData())}async handleSetMasterPin(e){await pg(this,e)}async handleLogout(){await gg(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{if(e.startsWith("admin:")){const i=e.slice(6),s=await this.client.request("access.changeAdminPin",{username:i,currentPin:t,newPin:n});if(!s.ok){this.changePinError=s.message??"Incorrect current PIN",this.changePinBusy=!1;return}}else{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 bi(this),setTimeout(()=>{this.accountPinModalOpen=!1,this.accountPinSuccess=null,this.accountPinError=null},1500)}catch{this.accountPinError="Failed to save PIN",this.accountPinBusy=!1}}}async handleAdminUsersAdd(e,t){if(this.client){this.adminUsersAddBusy=!0,this.adminUsersAddError=null;try{const n=Tt(),i=await this.client.request("access.addAdmin",{username:e,pin:t,accessToken:n});if(i.ok===!1){this.adminUsersAddError=i.message??"Failed to add admin",this.adminUsersAddBusy=!1;return}this.adminUsersAddBusy=!1,await bi(this)}catch(n){this.adminUsersAddError=String(n)||"Failed to add admin",this.adminUsersAddBusy=!1}}}async handleAdminUsersRemove(e){if(this.client){this.adminUsersRemoveBusy=!0;try{const t=Tt();await this.client.request("access.removeAdmin",{username:e,accessToken:t}),this.adminUsersRemoveConfirm=null,this.adminUsersRemoveBusy=!1,await bi(this)}catch{this.adminUsersRemoveBusy=!1}}}async handleAdminUsersUpdatePin(e,t){if(this.client){this.adminUsersChangePinBusy=!0,this.adminUsersChangePinError=null;try{const n=Tt(),i=await this.client.request("access.updateAdminPin",{username:e,pin:t,accessToken:n});if(i.ok===!1){this.adminUsersChangePinError=i.message??"Failed to update PIN",this.adminUsersChangePinBusy=!1;return}this.adminUsersChangePinUsername=null,this.adminUsersChangePinBusy=!1,this.adminUsersChangePinError=null}catch{this.adminUsersChangePinError="Failed to update PIN",this.adminUsersChangePinBusy=!1}}}async handleLicenseStatusCheck(){await a$(this)}async handleLicenseActivate(){await r$(this)}async handleLicenseRemove(){await l$(this)}handleLicenseKeyChange(e){c$(this,e)}async handleAuthStatusCheck(){await t$(this)}async handleAuthStart(){await n$(this)}async handleAuthSubmitCode(e){await i$(this,e)}handleAuthCodeChange(e){o$(this,e)}handleClaudeAuthModalOpen(){this.claudeAuthModalOpen=!0}handleClaudeAuthModalClose(){this.claudeAuthModalOpen=!1,this.authUrl=null,this.authMessage=null,this.authRefreshTokenInput="",this.authRefreshTokenError=null}async handleDisconnect(){await s$(this),this.handleClaudeAuthModalClose()}async handleImportRefreshToken(){await e$(this)}async handleGatewayHealthCheck(){await u$(this)}async handleGatewayRestart(){await d$(this)}async handleUpdateCheck(){await ap(this)}async handleUpdateRun(){await Vx(this)}handleUpdateDismissResult(){Jx(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 se(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>jr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){se(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>jr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await Ru(this)}async clearAudit(){await rf(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,fn(this,t),xs(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();se(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>f0);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}async loadChatSessions(){if(!(!this.client||!this.connected))try{const e=await this.client.request("sessions.list",{accountId:this.selectedWorkspace}),n=`webchat:${this.resolveAdminAgentId()??"main"}:`,i=[];for(const o of e.sessions){const a=o.key.indexOf(n);if(a<0)continue;const r=o.key.substring(a);i.push({...o,key:r})}const s=this.sessionKey;s.startsWith("webchat:")&&s.startsWith(n)&&!i.some(o=>o.key===s)&&i.unshift({key:s,kind:"direct",updatedAt:Date.now()}),this.chatSessions={...e,sessions:i,count:i.length}}catch{}}newSession(){const t=`webchat:${this.resolveAdminAgentId()??"main"}:${Date.now()}`;this.sessionKey=t,this.chatMessage="",this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t});const n={key:t,kind:"direct",updatedAt:Date.now()},i=this.chatSessions;this.chatSessions={ts:Date.now(),path:(i==null?void 0:i.path)??"",count:((i==null?void 0:i.sessions.length)??0)+1,defaults:(i==null?void 0:i.defaults)??{model:null,contextTokens:null},sessions:[n,...(i==null?void 0:i.sessions)??[]]},this.chatSessionsOpen=!1,this.resetChatScroll()}selectSession(e){this.sessionKey=e,this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.applySettings({...this.settings,sessionKey:e,lastActiveSessionKey:e}),this.chatSessionsOpen=!1,se(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this)})}async renameSession(e,t){this.chatSessions&&(this.chatSessions={...this.chatSessions,sessions:this.chatSessions.sessions.map(n=>n.key===e?{...n,label:t??void 0}:n)});try{const{patchSession:n}=await se(async()=>{const{patchSession:i}=await Promise.resolve().then(()=>Qs);return{patchSession:i}},void 0,import.meta.url);await n(this,e,{label:t})}catch{await this.loadChatSessions()}}async deleteChatSession(e){var n,i;this.chatSidebarConfirmDeleteKey=null;const t=((n=this.chatSessions)==null?void 0:n.sessions.filter(s=>s.key!==e))??[];if(this.chatSessions&&(this.chatSessions={...this.chatSessions,sessions:t,count:t.length}),this.sessionKey===e){const s=((i=t[0])==null?void 0:i.key)??"";this.sessionKey=s,this.chatMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.applySettings({...this.settings,sessionKey:s||"cleared",lastActiveSessionKey:s||"cleared"}),s&&se(async()=>{const{loadChatHistory:o}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:o}},void 0,import.meta.url).then(({loadChatHistory:o})=>{o(this)})}se(async()=>{const{deleteSession:s}=await Promise.resolve().then(()=>Qs);return{deleteSession:s}},void 0,import.meta.url).then(({deleteSession:s})=>s(this,e))}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&&!this.sessionKey.startsWith("webchat:")&&this.sessionKey!==""&&this.sessionKey!=="cleared"){const t=`webchat:${e}:${Date.now()}`;this.sessionKey=t,this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.resetChatScroll(),this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity()}this.loadChatSessions(),se(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>Yt);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this).then(()=>{pn(this,!0)})})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=jh(this),{loadOlderChatHistory:t}=await se(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>Yt);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"&&se(async()=>{const{loadOpeningHours:n}=await Promise.resolve().then(()=>p0);return{loadOpeningHours:n}},void 0,import.meta.url).then(({loadOpeningHours:n})=>{n(this)}),this.advancedTab==="logs"&&(this.logsSubTab==="session"?se(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>Iu);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):se(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>bg);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&se(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>Zg);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})}),this.advancedTab==="sessions"&&se(async()=>{const{loadSessions:n}=await Promise.resolve().then(()=>Qs);return{loadSessions:n}},void 0,import.meta.url).then(({loadSessions:n})=>{n(this)})}async handleChannelConfigSave(){await H0(this)}async handleChannelConfigReload(){await j0(this)}handleNostrProfileEdit(e,t){G0(this,e,t)}handleNostrProfileCancel(){Q0(this)}handleNostrProfileFieldChange(e,t){J0(this,e,t)}async handleNostrProfileSave(){await X0(this)}async handleNostrProfileImport(){await Z0(this)}handleNostrProfileToggleAdvanced(){Y0(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;se(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>m0);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 se(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>Mi);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await se(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>Mi);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await se(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>cg);return{loadChannels:s}},void 0,import.meta.url);await n(this,{name:e,workspacePath:t,onCreated:s=>{if(!s.accountId)return;const o=s.accountId;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 se(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>Mi);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 se(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>Mi);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){Io(),this.selectedWorkspace&&Jn(this.selectedWorkspace,this.sessionKey,this.chatMessage),this.selectedWorkspace=e,this.publicChatQrDataUrl=null,localStorage.setItem("taskmaster-selected-workspace",e),Nn(e),Ir(e),this.settings=qs(),this.chatMessage=Yn(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.chatSessions=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.publicChat||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.accountId,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)}Nn(this.selectedWorkspace),Ir(this.selectedWorkspace),this.settings=qs(),this.sessionKey=this.settings.sessionKey,this.chatMessage=Yn(this.selectedWorkspace,this.settings.sessionKey),this.reloadCurrentPageData()}render(){return u`${P0(this)}${this.auditModalOpen?M0(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):w}`}};g([f()],h.prototype,"settings",2);g([f()],h.prototype,"password",2);g([f()],h.prototype,"tab",2);g([f()],h.prototype,"onboarding",2);g([f()],h.prototype,"setup",2);g([f()],h.prototype,"filesPage",2);g([f()],h.prototype,"browserPage",2);g([f()],h.prototype,"adminsPage",2);g([f()],h.prototype,"contactsPage",2);g([f()],h.prototype,"chatPage",2);g([f()],h.prototype,"advancedPage",2);g([f()],h.prototype,"advancedTab",2);g([f()],h.prototype,"sessionsKindFilter",2);g([f()],h.prototype,"sessionsChannelFilter",2);g([f()],h.prototype,"sessionsAgentFilter",2);g([f()],h.prototype,"sessionsPendingAction",2);g([f()],h.prototype,"sessionsExpandedKey",2);g([f()],h.prototype,"publicChat",2);g([f()],h.prototype,"publicChatConfig",2);g([f()],h.prototype,"publicChatSessionKey",2);g([f()],h.prototype,"publicChatAuthenticated",2);g([f()],h.prototype,"publicChatAuthStep",2);g([f()],h.prototype,"connected",2);g([f()],h.prototype,"accessState",2);g([f()],h.prototype,"theme",2);g([f()],h.prototype,"themeResolved",2);g([f()],h.prototype,"hello",2);g([f()],h.prototype,"lastError",2);g([f()],h.prototype,"eventLog",2);g([f()],h.prototype,"assistantName",2);g([f()],h.prototype,"assistantAvatar",2);g([f()],h.prototype,"assistantAgentId",2);g([f()],h.prototype,"sessionKey",2);g([f()],h.prototype,"chatLoading",2);g([f()],h.prototype,"chatSending",2);g([f()],h.prototype,"chatMessage",2);g([f()],h.prototype,"chatMessages",2);g([f()],h.prototype,"chatHistoryTotal",2);g([f()],h.prototype,"chatHistoryHasMore",2);g([f()],h.prototype,"chatLoadingOlder",2);g([f()],h.prototype,"chatToolMessages",2);g([f()],h.prototype,"chatStream",2);g([f()],h.prototype,"chatInterimText",2);g([f()],h.prototype,"chatSuggestions",2);g([f()],h.prototype,"chatStreamStartedAt",2);g([f()],h.prototype,"chatRunId",2);g([f()],h.prototype,"compactionStatus",2);g([f()],h.prototype,"chatAvatarUrl",2);g([f()],h.prototype,"chatModelCatalog",2);g([f()],h.prototype,"chatVerboseLevel",2);g([f()],h.prototype,"chatQueue",2);g([f()],h.prototype,"chatAttachments",2);g([f()],h.prototype,"sidebarOpen",2);g([f()],h.prototype,"sidebarContent",2);g([f()],h.prototype,"sidebarError",2);g([f()],h.prototype,"splitRatio",2);g([f()],h.prototype,"chatSessions",2);g([f()],h.prototype,"chatSessionsOpen",2);g([f()],h.prototype,"chatSidebarConfirmDeleteKey",2);g([f()],h.prototype,"nodesLoading",2);g([f()],h.prototype,"nodes",2);g([f()],h.prototype,"devicesLoading",2);g([f()],h.prototype,"devicesError",2);g([f()],h.prototype,"devicesList",2);g([f()],h.prototype,"execApprovalsLoading",2);g([f()],h.prototype,"execApprovalsSaving",2);g([f()],h.prototype,"execApprovalsDirty",2);g([f()],h.prototype,"execApprovalsSnapshot",2);g([f()],h.prototype,"execApprovalsForm",2);g([f()],h.prototype,"execApprovalsSelectedAgent",2);g([f()],h.prototype,"execApprovalsTarget",2);g([f()],h.prototype,"execApprovalsTargetNodeId",2);g([f()],h.prototype,"execApprovalQueue",2);g([f()],h.prototype,"execApprovalBusy",2);g([f()],h.prototype,"execApprovalError",2);g([f()],h.prototype,"configLoading",2);g([f()],h.prototype,"configRaw",2);g([f()],h.prototype,"configRawOriginal",2);g([f()],h.prototype,"configValid",2);g([f()],h.prototype,"configIssues",2);g([f()],h.prototype,"configSaving",2);g([f()],h.prototype,"configApplying",2);g([f()],h.prototype,"updateRunning",2);g([f()],h.prototype,"applySessionKey",2);g([f()],h.prototype,"configSnapshot",2);g([f()],h.prototype,"configSchema",2);g([f()],h.prototype,"configSchemaVersion",2);g([f()],h.prototype,"configSchemaLoading",2);g([f()],h.prototype,"configUiHints",2);g([f()],h.prototype,"configForm",2);g([f()],h.prototype,"configFormOriginal",2);g([f()],h.prototype,"configFormDirty",2);g([f()],h.prototype,"configFormMode",2);g([f()],h.prototype,"configSearchQuery",2);g([f()],h.prototype,"configActiveSection",2);g([f()],h.prototype,"configActiveSubsection",2);g([f()],h.prototype,"channelsLoading",2);g([f()],h.prototype,"channelsSnapshot",2);g([f()],h.prototype,"channelsError",2);g([f()],h.prototype,"channelsLastSuccess",2);g([f()],h.prototype,"whatsappLoginMessage",2);g([f()],h.prototype,"whatsappLoginQrDataUrl",2);g([f()],h.prototype,"whatsappLoginConnected",2);g([f()],h.prototype,"whatsappBusy",2);g([f()],h.prototype,"whatsappActiveQrAccountId",2);g([f()],h.prototype,"whatsappPairedPhone",2);g([f()],h.prototype,"addingWhatsAppAccount",2);g([f()],h.prototype,"newWhatsAppAccountName",2);g([f()],h.prototype,"newWhatsAppAccountProvider",2);g([f()],h.prototype,"newCloudPhoneNumberId",2);g([f()],h.prototype,"newCloudBusinessAccountId",2);g([f()],h.prototype,"newCloudAccessToken",2);g([f()],h.prototype,"newCloudWebhookVerifyToken",2);g([f()],h.prototype,"whatsappAccountError",2);g([f()],h.prototype,"whatsappAccountSaving",2);g([f()],h.prototype,"whatsappSettingsOpen",2);g([f()],h.prototype,"publicChatToggleBusy",2);g([f()],h.prototype,"publicChatGreetingBusy",2);g([f()],h.prototype,"publicChatEmailBusy",2);g([f()],h.prototype,"publicChatSettingsOpen",2);g([f()],h.prototype,"publicChatWidgetModalOpen",2);g([f()],h.prototype,"brandingBusy",2);g([f()],h.prototype,"agentSettingsOpen",2);g([f()],h.prototype,"brandingExpanded",2);g([f()],h.prototype,"tailscaleStatus",2);g([f()],h.prototype,"tailscaleBusy",2);g([f()],h.prototype,"tailscaleAuthUrl",2);g([f()],h.prototype,"tailscaleError",2);g([f()],h.prototype,"tailscaleServeEnableUrl",2);g([f()],h.prototype,"tailscaleFunnelEnableUrl",2);g([f()],h.prototype,"tailscaleDisableConfirm",2);g([f()],h.prototype,"tailscaleConnectProgress",2);g([f()],h.prototype,"tailscaleConnectMessage",2);g([f()],h.prototype,"tailscaleConnectSuccess",2);g([f()],h.prototype,"tunnelStatus",2);g([f()],h.prototype,"tunnelBusy",2);g([f()],h.prototype,"tunnelError",2);g([f()],h.prototype,"tunnelAuthUrl",2);g([f()],h.prototype,"tunnelSetupStep",2);g([f()],h.prototype,"tunnelQrDataUrl",2);g([f()],h.prototype,"tunnelHostnameInput",2);g([f()],h.prototype,"tunnelUsernameInput",2);g([f()],h.prototype,"tunnelPasswordInput",2);g([f()],h.prototype,"tunnelPasswordConfirmInput",2);g([f()],h.prototype,"wifiStatus",2);g([f()],h.prototype,"wifiNetworks",2);g([f()],h.prototype,"wifiBusy",2);g([f()],h.prototype,"wifiError",2);g([f()],h.prototype,"wifiPassword",2);g([f()],h.prototype,"wifiSelectedSsid",2);g([f()],h.prototype,"networkPort",2);g([f()],h.prototype,"networkHostname",2);g([f()],h.prototype,"networkPortInput",2);g([f()],h.prototype,"networkHostnameInput",2);g([f()],h.prototype,"networkModalOpen",2);g([f()],h.prototype,"networkBusy",2);g([f()],h.prototype,"networkError",2);g([f()],h.prototype,"networkSuccess",2);g([f()],h.prototype,"wifiModalOpen",2);g([f()],h.prototype,"licenseKey",2);g([f()],h.prototype,"licenseBusy",2);g([f()],h.prototype,"licenseValid",2);g([f()],h.prototype,"licenseMessage",2);g([f()],h.prototype,"licenseTier",2);g([f()],h.prototype,"licenseDeviceId",2);g([f()],h.prototype,"licenseStoredKey",2);g([f()],h.prototype,"licenseRemoveConfirm",2);g([f()],h.prototype,"authConnected",2);g([f()],h.prototype,"authBusy",2);g([f()],h.prototype,"authMessage",2);g([f()],h.prototype,"authUrl",2);g([f()],h.prototype,"authCodeInput",2);g([f()],h.prototype,"authExpiresIn",2);g([f()],h.prototype,"authRefreshToken",2);g([f()],h.prototype,"claudeAuthModalOpen",2);g([f()],h.prototype,"authRefreshTokenInput",2);g([f()],h.prototype,"authRefreshTokenBusy",2);g([f()],h.prototype,"authRefreshTokenError",2);g([f()],h.prototype,"setupStep",2);g([f()],h.prototype,"gatewayHealthy",2);g([f()],h.prototype,"gatewayHealthLoading",2);g([f()],h.prototype,"gatewayHealthMessage",2);g([f()],h.prototype,"gatewayRestartBusy",2);g([f()],h.prototype,"updateAvailable",2);g([f()],h.prototype,"currentVersion",2);g([f()],h.prototype,"latestVersion",2);g([f()],h.prototype,"updateChecking",2);g([f()],h.prototype,"updateMessage",2);g([f()],h.prototype,"updateProgressSteps",2);g([f()],h.prototype,"updateLastResult",2);g([f()],h.prototype,"uninstallConfirm",2);g([f()],h.prototype,"uninstallBusy",2);g([f()],h.prototype,"uninstallDone",2);g([f()],h.prototype,"uninstallError",2);g([f()],h.prototype,"uninstallConfirmText",2);g([f()],h.prototype,"nostrProfileFormState",2);g([f()],h.prototype,"nostrProfileAccountId",2);g([f()],h.prototype,"presenceLoading",2);g([f()],h.prototype,"presenceEntries",2);g([f()],h.prototype,"presenceError",2);g([f()],h.prototype,"presenceStatus",2);g([f()],h.prototype,"agentsLoading",2);g([f()],h.prototype,"agentsList",2);g([f()],h.prototype,"agentsError",2);g([f()],h.prototype,"sessionsLoading",2);g([f()],h.prototype,"sessionsResult",2);g([f()],h.prototype,"sessionsError",2);g([f()],h.prototype,"cronLoading",2);g([f()],h.prototype,"cronJobs",2);g([f()],h.prototype,"cronStatus",2);g([f()],h.prototype,"cronError",2);g([f()],h.prototype,"cronForm",2);g([f()],h.prototype,"cronRunsJobId",2);g([f()],h.prototype,"cronRuns",2);g([f()],h.prototype,"cronBusy",2);g([f()],h.prototype,"cronNewEventModal",2);g([f()],h.prototype,"cronDetailJobId",2);g([f()],h.prototype,"cronEditJobId",2);g([f()],h.prototype,"cronPendingDeleteId",2);g([f()],h.prototype,"cronRunModalJobId",2);g([f()],h.prototype,"cronRunModalJobName",2);g([f()],h.prototype,"cronRunResult",2);g([f()],h.prototype,"openingHoursLoading",2);g([f()],h.prototype,"openingHoursError",2);g([f()],h.prototype,"openingHoursBusy",2);g([f()],h.prototype,"openingHoursSaved",2);g([f()],h.prototype,"openingHoursForm",2);g([f()],h.prototype,"browserScreencastActive",2);g([f()],h.prototype,"browserScreencastFrame",2);g([f()],h.prototype,"browserScreencastMetadata",2);g([f()],h.prototype,"browserHandoffPending",2);g([f()],h.prototype,"browserHandoffReason",2);g([f()],h.prototype,"browserHandoffId",2);g([f()],h.prototype,"browserInputMode",2);g([f()],h.prototype,"browserFullscreen",2);g([f()],h.prototype,"browserLoading",2);g([f()],h.prototype,"browserError",2);g([f()],h.prototype,"filesLoading",2);g([f()],h.prototype,"filesTree",2);g([f()],h.prototype,"filesRoot",2);g([f()],h.prototype,"filesError",2);g([f()],h.prototype,"filesSelectedPath",2);g([f()],h.prototype,"filesSelectedPaths",2);g([f()],h.prototype,"filesPreviewContent",2);g([f()],h.prototype,"filesPreviewLoading",2);g([f()],h.prototype,"filesPreviewBinary",2);g([f()],h.prototype,"filesPreviewSize",2);g([f()],h.prototype,"filesExpandedDirs",2);g([f()],h.prototype,"filesCurrentDir",2);g([f()],h.prototype,"filesPendingDeletePath",2);g([f()],h.prototype,"filesMessage",2);g([f()],h.prototype,"filesUploadBusy",2);g([f()],h.prototype,"filesReindexBusy",2);g([f()],h.prototype,"filesMemoryStatus",2);g([f()],h.prototype,"embeddingDownloading",2);g([f()],h.prototype,"filesSearchQuery",2);g([f()],h.prototype,"filesSearchResults",2);g([f()],h.prototype,"filesSearchLoading",2);g([f()],h.prototype,"filesSearchAgentId",2);g([f()],h.prototype,"auditEntries",2);g([f()],h.prototype,"auditLoading",2);g([f()],h.prototype,"auditModalOpen",2);g([f()],h.prototype,"skillsLoading",2);g([f()],h.prototype,"skillsReport",2);g([f()],h.prototype,"skillsError",2);g([f()],h.prototype,"skillsFilter",2);g([f()],h.prototype,"skillsTypeFilter",2);g([f()],h.prototype,"skillsAgentFilter",2);g([f()],h.prototype,"selectableTools",2);g([f()],h.prototype,"skillEdits",2);g([f()],h.prototype,"skillsBusyKey",2);g([f()],h.prototype,"skillMessages",2);g([f()],h.prototype,"skillDetail",2);g([f()],h.prototype,"skillDetailTab",2);g([f()],h.prototype,"skillAddModal",2);g([f()],h.prototype,"skillAddForm",2);g([f()],h.prototype,"skillAddFormSource",2);g([f()],h.prototype,"skillEditTab",2);g([f()],h.prototype,"skillDrafts",2);g([f()],h.prototype,"adminsLoading",2);g([f()],h.prototype,"adminPhones",2);g([f()],h.prototype,"telegramAdmins",2);g([f()],h.prototype,"adminsNewTelegramUsername",2);g([f()],h.prototype,"adminsActiveTab",2);g([f()],h.prototype,"adminsPageTab",2);g([f()],h.prototype,"adminsError",2);g([f()],h.prototype,"adminsSaving",2);g([f()],h.prototype,"adminsNewPhone",2);g([f()],h.prototype,"contactsLoading",2);g([f()],h.prototype,"contactsSaving",2);g([f()],h.prototype,"contactsRecords",2);g([f()],h.prototype,"contactsError",2);g([f()],h.prototype,"contactsSearchQuery",2);g([f()],h.prototype,"contactsEditingId",2);g([f()],h.prototype,"contactsShowAddForm",2);g([f()],h.prototype,"contactsNewPhone",2);g([f()],h.prototype,"contactsNewName",2);g([f()],h.prototype,"contactsDeleteConfirmId",2);g([f()],h.prototype,"contactsAddFieldForId",2);g([f()],h.prototype,"contactsAddFieldKey",2);g([f()],h.prototype,"contactsAddFieldValue",2);g([f()],h.prototype,"imessageEnableConfirm",2);g([f()],h.prototype,"imessageEnabling",2);g([f()],h.prototype,"telegramBusy",2);g([f()],h.prototype,"telegramSettingsOpen",2);g([f()],h.prototype,"telegramConnectOpen",2);g([f()],h.prototype,"telegramConnectToken",2);g([f()],h.prototype,"telegramProbeResult",2);g([f()],h.prototype,"telegramProbing",2);g([f()],h.prototype,"telegramError",2);g([f()],h.prototype,"telegramAddingBot",2);g([f()],h.prototype,"telegramNewBotName",2);g([f()],h.prototype,"telegramNewBotDmPolicy",2);g([f()],h.prototype,"telegramNewBotAdminRouting",2);g([f()],h.prototype,"telegramBotSaving",2);g([f()],h.prototype,"telegramBotError",2);g([f()],h.prototype,"telegramDmPolicySaving",2);g([f()],h.prototype,"telegramWhitelistSaving",2);g([f()],h.prototype,"telegramWhitelistError",2);g([f()],h.prototype,"telegramNewWhitelistUsername",2);g([f()],h.prototype,"telegramExpandedBotId",2);g([f()],h.prototype,"telegramPairingRequests",2);g([f()],h.prototype,"telegramPairingLoading",2);g([f()],h.prototype,"telegramPairingActioning",2);g([f()],h.prototype,"chatPageTab",2);g([f()],h.prototype,"waConversations",2);g([f()],h.prototype,"waSelectedJid",2);g([f()],h.prototype,"waMessages",2);g([f()],h.prototype,"waGroupInfo",2);g([f()],h.prototype,"waLoading",2);g([f()],h.prototype,"waMessagesLoading",2);g([f()],h.prototype,"waSearchQuery",2);g([f()],h.prototype,"waComposeDraft",2);g([f()],h.prototype,"waSending",2);g([f()],h.prototype,"waLastError",2);g([f()],h.prototype,"infoModalOpen",2);g([f()],h.prototype,"remoteAccessQrDataUrl",2);g([f()],h.prototype,"publicChatQrDataUrl",2);g([f()],h.prototype,"workspaces",2);g([f()],h.prototype,"workspacesLoading",2);g([f()],h.prototype,"workspacesError",2);g([f()],h.prototype,"selectedWorkspace",2);g([f()],h.prototype,"addingWorkspace",2);g([f()],h.prototype,"newWorkspaceName",2);g([f()],h.prototype,"newWorkspacePath",2);g([f()],h.prototype,"newWorkspacePin",2);g([f()],h.prototype,"accountPinModalOpen",2);g([f()],h.prototype,"accountPinBusy",2);g([f()],h.prototype,"accountPinError",2);g([f()],h.prototype,"accountPinSuccess",2);g([f()],h.prototype,"adminUsersModalOpen",2);g([f()],h.prototype,"adminUsersAddBusy",2);g([f()],h.prototype,"adminUsersAddError",2);g([f()],h.prototype,"adminUsersRemoveConfirm",2);g([f()],h.prototype,"adminUsersRemoveBusy",2);g([f()],h.prototype,"adminUsersChangePinUsername",2);g([f()],h.prototype,"adminUsersChangePinBusy",2);g([f()],h.prototype,"adminUsersChangePinError",2);g([f()],h.prototype,"apiKeyProviders",2);g([f()],h.prototype,"apiKeyModalOpen",2);g([f()],h.prototype,"apiKeyBusy",2);g([f()],h.prototype,"apiKeyError",2);g([f()],h.prototype,"apiKeySuccess",2);g([f()],h.prototype,"apiKeySavingProvider",2);g([f()],h.prototype,"authApiKeyMode",2);g([f()],h.prototype,"authApiKeyInput",2);g([f()],h.prototype,"authApiKeyBusy",2);g([f()],h.prototype,"authApiKeyError",2);g([f()],h.prototype,"pinChanging",2);g([f()],h.prototype,"pinChangeBusy",2);g([f()],h.prototype,"pinChangeError",2);g([f()],h.prototype,"loginChangePinMode",2);g([f()],h.prototype,"changePinBusy",2);g([f()],h.prototype,"changePinError",2);g([f()],h.prototype,"changePinSuccess",2);g([f()],h.prototype,"workspaceSaving",2);g([f()],h.prototype,"workspaceRemoveConfirm",2);g([f()],h.prototype,"renamingWorkspace",2);g([f()],h.prototype,"renameWorkspaceName",2);g([f()],h.prototype,"debugLoading",2);g([f()],h.prototype,"debugStatus",2);g([f()],h.prototype,"debugHealth",2);g([f()],h.prototype,"debugModels",2);g([f()],h.prototype,"debugHeartbeat",2);g([f()],h.prototype,"debugCallMethod",2);g([f()],h.prototype,"debugCallParams",2);g([f()],h.prototype,"debugCallResult",2);g([f()],h.prototype,"debugCallError",2);g([f()],h.prototype,"logsLoading",2);g([f()],h.prototype,"logsError",2);g([f()],h.prototype,"logsFile",2);g([f()],h.prototype,"logsEntries",2);g([f()],h.prototype,"logsFilterText",2);g([f()],h.prototype,"logsLevelFilters",2);g([f()],h.prototype,"logsAutoFollow",2);g([f()],h.prototype,"logsTruncated",2);g([f()],h.prototype,"logsCursor",2);g([f()],h.prototype,"logsLastFetchAt",2);g([f()],h.prototype,"logsLimit",2);g([f()],h.prototype,"logsMaxBytes",2);g([f()],h.prototype,"logsAtBottom",2);g([f()],h.prototype,"logsDate",2);g([f()],h.prototype,"logsAvailableDates",2);g([f()],h.prototype,"logsSubTab",2);g([f()],h.prototype,"logsChipsExpanded",2);g([f()],h.prototype,"sessionLogsLoading",2);g([f()],h.prototype,"sessionLogsError",2);g([f()],h.prototype,"sessionLogsEntries",2);g([f()],h.prototype,"sessionLogsFilterText",2);g([f()],h.prototype,"sessionLogsTypeFilters",2);g([f()],h.prototype,"sessionLogsAgentFilters",2);g([f()],h.prototype,"sessionLogsAgents",2);g([f()],h.prototype,"sessionLogsAutoFollow",2);g([f()],h.prototype,"sessionLogsChipsExpanded",2);g([f()],h.prototype,"sessionLogsCursors",2);g([f()],h.prototype,"sessionLogsLastFetchAt",2);g([f()],h.prototype,"sessionLogsAtBottom",2);g([f()],h.prototype,"chatUserNearBottom",2);h=g([cc("taskmaster-app")],h);
6132
+ //# sourceMappingURL=index-QAV6uia0.js.map