@rubytech/taskmaster 1.11.2 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,23 @@
1
- var Du=Object.defineProperty;var Bu=(e,t,n)=>t in e?Du(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var q=(e,t,n)=>Bu(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 Nu="modulepreload",Ou=function(e,t){return new URL(e,t).href},nr={},le=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};const a=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),l=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));s=c(n.map(h=>{if(h=Ou(h,i),h in nr)return;nr[h]=!0;const d=h.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(i)for(let S=a.length-1;S>=0;S--){const x=a[S];if(x.href===h&&(!d||x.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${p}`))return;const v=document.createElement("link");if(v.rel=d?"stylesheet":Nu,d||(v.as="script"),v.crossOrigin="",v.href=h,l&&v.setAttribute("nonce",l),document.head.appendChild(v),d)return new Promise((S,x)=>{v.addEventListener("load",S),v.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${h}`)))})}))}function o(a){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=a,window.dispatchEvent(r),!r.defaultPrevented)throw a}return s.then(a=>{for(const r of a||[])r.status==="rejected"&&o(r.reason);return t().catch(o)})};const xi=globalThis,qo=xi.ShadowRoot&&(xi.ShadyCSS===void 0||xi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ho=Symbol(),ir=new WeakMap;let Ll=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==Ho)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(qo&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=ir.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&ir.set(n,t))}return t}toString(){return this.cssText}};const Fu=e=>new Ll(typeof e=="string"?e:e+"",void 0,Ho),Uu=(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 Ll(n,e,Ho)},Wu=(e,t)=>{if(qo)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=xi.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},sr=qo?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Fu(n)})(e):e;const{is:Ku,defineProperty:zu,getOwnPropertyDescriptor:qu,getOwnPropertyNames:Hu,getOwnPropertySymbols:ju,getPrototypeOf:Gu}=Object,ot=globalThis,or=ot.trustedTypes,Vu=or?or.emptyScript:"",Es=ot.reactiveElementPolyfillSupport,Cn=(e,t)=>e,Pi={toAttribute(e,t){switch(t){case Boolean:e=e?Vu: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}},jo=(e,t)=>!Ku(e,t),ar={attribute:!0,type:String,converter:Pi,reflect:!1,useDefault:!1,hasChanged:jo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ot.litPropertyMetadata??(ot.litPropertyMetadata=new WeakMap);let zt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=ar){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,n);s!==void 0&&zu(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=qu(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)??ar}static _$Ei(){if(this.hasOwnProperty(Cn("elementProperties")))return;const t=Gu(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Cn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Cn("properties"))){const n=this.properties,i=[...Hu(n),...ju(n)];for(const s of i)this.createProperty(s,n[s])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[i,s]of n)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[n,i]of this.elementProperties){const s=this._$Eu(n,i);s!==void 0&&this._$Eh.set(s,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const n=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)n.unshift(sr(s))}else t!==void 0&&n.push(sr(t));return n}static _$Eu(t,n){const i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$ES=new Promise(n=>this.enableUpdating=n),this._$AL=new Map,this._$E_(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(n=>n(this))}addController(t){var n;(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&((n=t.hostConnected)==null||n.call(t))}removeController(t){var n;(n=this._$EO)==null||n.delete(t)}_$E_(){const t=new Map,n=this.constructor.elementProperties;for(const i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Wu(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:Pi).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:Pi;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??jo)(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){}};zt.elementStyles=[],zt.shadowRootOptions={mode:"open"},zt[Cn("elementProperties")]=new Map,zt[Cn("finalized")]=new Map,Es==null||Es({ReactiveElement:zt}),(ot.reactiveElementVersions??(ot.reactiveElementVersions=[])).push("2.1.2");const En=globalThis,rr=e=>e,Ii=En.trustedTypes,lr=Ii?Ii.createPolicy("lit-html",{createHTML:e=>e}):void 0,Rl="$lit$",st=`lit$${Math.random().toFixed(9).slice(2)}$`,Dl="?"+st,Qu=`<${Dl}>`,At=document,On=()=>At.createComment(""),Fn=e=>e===null||typeof e!="object"&&typeof e!="function",Go=Array.isArray,Ju=e=>Go(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ts=`[
2
- \f\r]`,hn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,cr=/-->/g,dr=/>/g,ht=RegExp(`>|${Ts}(?:([^\\s"'>=/]+)(${Ts}*=${Ts}*(?:[^
3
- \f\r"'\`<>=]|("|')|))|$)`,"g"),ur=/'/g,pr=/"/g,Bl=/^(?:script|style|textarea|title)$/i,Yu=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),u=Yu(1),rt=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),hr=new WeakMap,vt=At.createTreeWalker(At,129);function Nl(e,t){if(!Go(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return lr!==void 0?lr.createHTML(t):t}const Xu=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",a=hn;for(let r=0;r<n;r++){const l=e[r];let c,h,d=-1,p=0;for(;p<l.length&&(a.lastIndex=p,h=a.exec(l),h!==null);)p=a.lastIndex,a===hn?h[1]==="!--"?a=cr:h[1]!==void 0?a=dr:h[2]!==void 0?(Bl.test(h[2])&&(s=RegExp("</"+h[2],"g")),a=ht):h[3]!==void 0&&(a=ht):a===ht?h[0]===">"?(a=s??hn,d=-1):h[1]===void 0?d=-2:(d=a.lastIndex-h[2].length,c=h[1],a=h[3]===void 0?ht:h[3]==='"'?pr:ur):a===pr||a===ur?a=ht:a===cr||a===dr?a=hn:(a=ht,s=void 0);const v=a===ht&&e[r+1].startsWith("/>")?" ":"";o+=a===hn?l+Qu:d>=0?(i.push(c),l.slice(0,d)+Rl+l.slice(d)+st+v):l+st+(d===-2?r:v)}return[Nl(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let go=class Ol{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,l=this.parts,[c,h]=Xu(t,n);if(this.el=Ol.createElement(c,i),vt.currentNode=this.el.content,n===2||n===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=vt.nextNode())!==null&&l.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const d of s.getAttributeNames())if(d.endsWith(Rl)){const p=h[a++],v=s.getAttribute(d).split(st),S=/([.?@])?(.*)/.exec(p);l.push({type:1,index:o,name:S[2],strings:v,ctor:S[1]==="."?ep:S[1]==="?"?tp:S[1]==="@"?np:ts}),s.removeAttribute(d)}else d.startsWith(st)&&(l.push({type:6,index:o}),s.removeAttribute(d));if(Bl.test(s.tagName)){const d=s.textContent.split(st),p=d.length-1;if(p>0){s.textContent=Ii?Ii.emptyScript:"";for(let v=0;v<p;v++)s.append(d[v],On()),vt.nextNode(),l.push({type:2,index:++o});s.append(d[p],On())}}}else if(s.nodeType===8)if(s.data===Dl)l.push({type:2,index:o});else{let d=-1;for(;(d=s.data.indexOf(st,d+1))!==-1;)l.push({type:7,index:o}),d+=st.length-1}o++}}static createElement(t,n){const i=At.createElement("template");return i.innerHTML=t,i}};function Jt(e,t,n=e,i){var a,r;if(t===rt)return t;let s=i!==void 0?(a=n._$Co)==null?void 0:a[i]:n._$Cl;const o=Fn(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=Jt(e,s._$AS(e,t.values),s,i)),t}class Zu{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:n},parts:i}=this._$AD,s=((t==null?void 0:t.creationScope)??At).importNode(n,!0);vt.currentNode=s;let o=vt.nextNode(),a=0,r=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new es(o,o.nextSibling,this,t):l.type===1?c=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(c=new ip(o,this,t)),this._$AV.push(c),l=i[++r]}a!==(l==null?void 0:l.index)&&(o=vt.nextNode(),a++)}return vt.currentNode=At,s}p(t){let n=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}}let es=class Fl{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=Jt(this,t,n),Fn(t)?t===w||t==null||t===""?(this._$AH!==w&&this._$AR(),this._$AH=w):t!==this._$AH&&t!==rt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ju(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&&Fn(this._$AH)?this._$AA.nextSibling.data=t:this.T(At.createTextNode(t)),this._$AH=t}$(t){var o;const{values:n,_$litType$:i}=t,s=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=go.createElement(Nl(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 Zu(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=hr.get(t.strings);return n===void 0&&hr.set(t.strings,n=new go(t)),n}k(t){Go(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 Fl(this.O(On()),this.O(On()),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=rr(t).nextSibling;rr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class ts{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=Jt(this,t,n,0),a=!Fn(t)||t!==this._$AH&&t!==rt,a&&(this._$AH=t);else{const r=t;let l,c;for(t=o[0],l=0;l<o.length-1;l++)c=Jt(this,r[i+l],n,l),c===rt&&(c=this._$AH[l]),a||(a=!Fn(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 ep=class extends ts{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},tp=class extends ts{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},np=class extends ts{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=Jt(this,t,n,0)??w)===rt)return;const i=this._$AH,s=t===w&&i!==w||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==w&&(i===w||s);s&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var n;typeof this._$AH=="function"?this._$AH.call(((n=this.options)==null?void 0:n.host)??this.element,t):this._$AH.handleEvent(t)}},ip=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){Jt(this,t)}};const sp={I:es},_s=En.litHtmlPolyfillSupport;_s==null||_s(go,es),(En.litHtmlVersions??(En.litHtmlVersions=[])).push("3.3.2");const op=(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 es(t.insertBefore(On(),o),o,void 0,n??{})}return s._$AI(e),s};const $t=globalThis;let Gt=class extends zt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var n;const t=super.createRenderRoot();return(n=this.renderOptions).renderBefore??(n.renderBefore=t.firstChild),t}update(t){const n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=op(n,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)==null||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)==null||t.setConnected(!1)}render(){return rt}};var Il;Gt._$litElement$=!0,Gt.finalized=!0,(Il=$t.litElementHydrateSupport)==null||Il.call($t,{LitElement:Gt});const Ms=$t.litElementPolyfillSupport;Ms==null||Ms({LitElement:Gt});($t.litElementVersions??($t.litElementVersions=[])).push("4.2.2");const Ul=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const ap={attribute:!0,type:String,converter:Pi,reflect:!1,hasChanged:jo},rp=(e=ap,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 ns(e){return(t,n)=>typeof n=="object"?rp(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 y(e){return ns({...e,state:!0,attribute:!1})}const lp=50,cp=200,dp="Assistant";function fr(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=fr(e==null?void 0:e.name,lp)??dp,n=fr((e==null?void 0:e.avatar)??void 0,cp)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function up(){return mo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const pp="Taskmaster",hp="/taskmaster-icon.png",fp="#00d4ff",gp="";let oi=null;function Ye(){return oi||(oi={name:window.__TASKMASTER_BRAND_NAME__||pp,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||hp,accentColor:window.__TASKMASTER_ACCENT_COLOR__||fp,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||gp},oi)}function Be(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function Wl(e){const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return t?`${parseInt(t[1],16)}, ${parseInt(t[2],16)}, ${parseInt(t[3],16)}`:null}function mp(e){const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);if(!t)return 0;const[n,i,s]=[t[1],t[2],t[3]].map(o=>{const a=parseInt(o,16)/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)});return .2126*n+.7152*i+.0722*s}function Kl(e){const t=Wl(e);if(!t)return;const n=document.documentElement;n.style.setProperty("--accent",e),n.style.setProperty("--accent-hover",e),n.style.setProperty("--accent-muted",e),n.style.setProperty("--primary",e),n.style.setProperty("--ring",e),n.style.setProperty("--accent-subtle",`rgba(${t}, 0.15)`),n.style.setProperty("--accent-glow",`rgba(${t}, 0.25)`),n.style.setProperty("--tasker-orange",e),n.style.setProperty("--tasker-orange-hover",e),n.style.setProperty("--tasker-orange-glow",`rgba(${t}, 0.25)`);const i=mp(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function ai(e,t,n){const i=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!i||!s)return e;const o=(c,h)=>Math.round(parseInt(i[c],16)*(1-n)+parseInt(s[h],16)*n),a=o(1,1),r=o(2,2),l=o(3,3);return`#${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}const fn={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function zl(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries(fn))t.style.setProperty(i,s);t.style.removeProperty("--brand-bg"),t.style.removeProperty("--brand-bg-subtle"),t.style.removeProperty("--brand-bg-card");return}const n=Wl(e);n&&(t.style.setProperty("--bg",ai(fn["--bg"],e,.08)),t.style.setProperty("--bg-muted",ai(fn["--bg-muted"],e,.1)),t.style.setProperty("--card",ai(fn["--card"],e,.12)),t.style.setProperty("--secondary",ai(fn["--secondary"],e,.1)),t.style.setProperty("--brand-bg",e),t.style.setProperty("--brand-bg-subtle",`rgba(${n}, 0.08)`),t.style.setProperty("--brand-bg-card",`rgba(${n}, 0.12)`))}function Tn(e){const t=Ye(),n=Be(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;Kl(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;zl(o)}const Li="taskmaster.control.settings.v1",ql="taskmaster.account.settings.";function _n(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const Wt={gatewayUrl:_n(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},it={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function yp(){try{const e=localStorage.getItem(Li);if(!e)return{...Wt,gatewayUrl:_n()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():_n(),token:typeof t.token=="string"?t.token:Wt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:Wt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:Wt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:Wt.navGroupsCollapsed}}catch{return{...Wt,gatewayUrl:_n()}}}function vp(e){if(!e)return{...it};try{const t=localStorage.getItem(ql+e);if(!t)return{...it};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():it.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||it.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:it.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:it.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:it.splitRatio}}catch{return{...it}}}let Ri=null;function gr(e){Ri=e}function Ps(){return{...yp(),...vp(Ri)}}function bp(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(Li,JSON.stringify(t)),Ri){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem(ql+Ri,JSON.stringify(n))}}const wp="taskmaster.draft.";function Vo(e,t){return wp+e+"."+t}function Un(e,t,n){try{const i=Vo(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function Wn(e,t){try{return localStorage.getItem(Vo(e,t))??""}catch{return""}}function kp(e,t){try{localStorage.removeItem(Vo(e,t))}catch{}}let bt=null,Se=null;function mr(e,t,n){Se={workspace:e,sessionKey:t,text:n},bt!=null&&clearTimeout(bt),bt=setTimeout(()=>{Se&&Un(Se.workspace,Se.sessionKey,Se.text),Se=null,bt=null},300)}function yo(){bt!=null&&clearTimeout(bt),bt=null,Se&&(Un(Se.workspace,Se.sessionKey,Se.text),Se=null)}(function(){try{const t=localStorage.getItem(Li);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:_n(),token:typeof n.token=="string"?n.token:"",theme:n.theme==="light"||n.theme==="dark"||n.theme==="system"?n.theme:"system",navCollapsed:typeof n.navCollapsed=="boolean"?n.navCollapsed:!1,navGroupsCollapsed:typeof n.navGroupsCollapsed=="object"&&n.navGroupsCollapsed!==null?n.navGroupsCollapsed:{}};localStorage.setItem(Li,JSON.stringify(i))}catch{}})();function Hl(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 $p=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,ri=/<\s*\/?\s*final\b[^>]*>/gi,yr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function xp(e,t){return e.trimStart()}function Sp(e,t){if(!e||!$p.test(e))return e;let n=e;ri.test(n)?(ri.lastIndex=0,n=n.replace(ri,"")):ri.lastIndex=0,yr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(yr)){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),xp(i)}function jl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function is(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 Qo(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 Ap(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Gl(e,t){return e.length<=t?{text:e,truncated:!1,total:e.length}:{text:e.slice(0,Math.max(0,t)),truncated:!0,total:e.length}}function Di(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Is(e){return Sp(e)}const Cp=/^\[([^\]]+)\]\s*/,Ep=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Ls=new WeakMap,Rs=new WeakMap;function Tp(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:Ep.some(t=>e.startsWith(`${t} `))}function Ds(e){const t=e.match(Cp);if(!t)return e;const n=t[1]??"";return Tp(n)?e.slice(t[0].length):e}function Mn(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?Is(i):Ds(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"?Is(o):Ds(o)}}return typeof t.text=="string"?n==="assistant"?Is(t.text):Ds(t.text):null}function Vl(e){if(!e||typeof e!="object")return Mn(e);const t=e;if(Ls.has(t))return Ls.get(t)??null;const n=Mn(e);return Ls.set(t,n),n}function vr(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=Mp(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 _p(e){if(!e||typeof e!="object")return vr(e);const t=e;if(Rs.has(t))return Rs.get(t)??null;const n=vr(e);return Rs.set(t,n),n}function Mp(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 Pp(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 Ip=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,Lp=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,Rp=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Dp=/^A new session was started via \/new or \/reset\./;function Bp(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"&&Ip.test(s)||n==="assistant"&&Lp.test(s)||n==="user"&&Dp.test(s)||n==="assistant"&&Rp.test(s)):!1}function Ql(e){return e.filter(t=>!Bp(t))}function Jl(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(d=>{const v=String(d.type??"").toLowerCase();return v==="toolresult"||v==="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(d=>({type:d.type||"text",text:d.text,name:d.name,args:d.args||d.arguments})):typeof t.text=="string"&&(l=[{type:"text",text:t.text}]);const c=typeof t.timestamp=="number"?t.timestamp:Date.now(),h=typeof t.id=="string"?t.id:void 0;return{role:n,content:l,timestamp:c,id:h}}function Yl(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 Xl(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function br(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Np(){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 ss(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(e&&typeof e.getRandomValues=="function"){const t=new Uint8Array(16);return e.getRandomValues(t),br(t)}return br(Np())}const Fe=50;async function Oe(e,t){if(!e.client||!e.connected)return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??Fe;try{const i=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:n}),s=Array.isArray(i.messages)?i.messages:[],o=typeof i.totalMessages=="number"?i.totalMessages:s.length,a=Ql(s);e.chatMessages=a,e.chatHistoryTotal=o,e.chatHistoryHasMore=o>s.length,e.chatThinkingLevel=i.thinkingLevel??null,e.chatModelProvider=typeof i.modelProvider=="string"?i.modelProvider:null,e.chatModel=typeof i.model=="string"?i.model:null,e.chatVerboseLevel=typeof i.verboseLevel=="string"?i.verboseLevel:null,e.chatFillerEnabled=typeof i.fillerEnabled=="boolean"?i.fillerEnabled:null}catch(i){e.lastError=String(i)}finally{e.chatLoading=!1}}async function Op(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:Fe,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=Ql(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 Fp(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function Zl(e,t,n){if(e.chatSuggestions=[],!e.client||!e.connected)return!1;const i=t.trim(),s=n&&n.length>0;if(!i&&!s)return!1;const o=Date.now(),a=(n??[]).filter(v=>!v.fileName),r=(n??[]).filter(v=>v.fileName),l=[],c=r.map(v=>v.fileName).filter(Boolean);if(c.length>0){const v=i?`${c.join(", ")}
1
+ var Bu=Object.defineProperty;var Nu=(e,t,n)=>t in e?Bu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var q=(e,t,n)=>Nu(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 Ou="modulepreload",Fu=function(e,t){return new URL(e,t).href},ir={},le=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};const a=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),l=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));s=c(n.map(h=>{if(h=Fu(h,i),h in ir)return;ir[h]=!0;const d=h.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(i)for(let x=a.length-1;x>=0;x--){const S=a[x];if(S.href===h&&(!d||S.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${p}`))return;const g=document.createElement("link");if(g.rel=d?"stylesheet":Ou,d||(g.as="script"),g.crossOrigin="",g.href=h,l&&g.setAttribute("nonce",l),document.head.appendChild(g),d)return new Promise((x,S)=>{g.addEventListener("load",x),g.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${h}`)))})}))}function o(a){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=a,window.dispatchEvent(r),!r.defaultPrevented)throw a}return s.then(a=>{for(const r of a||[])r.status==="rejected"&&o(r.reason);return t().catch(o)})};const Si=globalThis,Ho=Si.ShadowRoot&&(Si.ShadyCSS===void 0||Si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,jo=Symbol(),sr=new WeakMap;let Rl=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==jo)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(Ho&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=sr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&sr.set(n,t))}return t}toString(){return this.cssText}};const Uu=e=>new Rl(typeof e=="string"?e:e+"",void 0,jo),Wu=(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 Rl(n,e,jo)},Ku=(e,t)=>{if(Ho)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=Si.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},or=Ho?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Uu(n)})(e):e;const{is:zu,defineProperty:qu,getOwnPropertyDescriptor:Hu,getOwnPropertyNames:ju,getOwnPropertySymbols:Gu,getPrototypeOf:Vu}=Object,at=globalThis,ar=at.trustedTypes,Qu=ar?ar.emptyScript:"",Ts=at.reactiveElementPolyfillSupport,Cn=(e,t)=>e,Ii={toAttribute(e,t){switch(t){case Boolean:e=e?Qu: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}},Go=(e,t)=>!zu(e,t),rr={attribute:!0,type:String,converter:Ii,reflect:!1,useDefault:!1,hasChanged:Go};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),at.litPropertyMetadata??(at.litPropertyMetadata=new WeakMap);let qt=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=rr){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&&qu(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:o}=Hu(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)??rr}static _$Ei(){if(this.hasOwnProperty(Cn("elementProperties")))return;const t=Vu(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Cn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Cn("properties"))){const n=this.properties,i=[...ju(n),...Gu(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(or(s))}else t!==void 0&&n.push(or(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 Ku(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:Ii).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:Ii;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??Go)(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){}};qt.elementStyles=[],qt.shadowRootOptions={mode:"open"},qt[Cn("elementProperties")]=new Map,qt[Cn("finalized")]=new Map,Ts==null||Ts({ReactiveElement:qt}),(at.reactiveElementVersions??(at.reactiveElementVersions=[])).push("2.1.2");const En=globalThis,lr=e=>e,Li=En.trustedTypes,cr=Li?Li.createPolicy("lit-html",{createHTML:e=>e}):void 0,Dl="$lit$",ot=`lit$${Math.random().toFixed(9).slice(2)}$`,Bl="?"+ot,Ju=`<${Bl}>`,Ct=document,Fn=()=>Ct.createComment(""),Un=e=>e===null||typeof e!="object"&&typeof e!="function",Vo=Array.isArray,Yu=e=>Vo(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",_s=`[
2
+ \f\r]`,hn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,dr=/-->/g,ur=/>/g,ft=RegExp(`>|${_s}(?:([^\\s"'>=/]+)(${_s}*=${_s}*(?:[^
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),pr=/'/g,hr=/"/g,Nl=/^(?:script|style|textarea|title)$/i,Xu=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),u=Xu(1),lt=Symbol.for("lit-noChange"),w=Symbol.for("lit-nothing"),fr=new WeakMap,bt=Ct.createTreeWalker(Ct,129);function Ol(e,t){if(!Vo(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return cr!==void 0?cr.createHTML(t):t}const Zu=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",a=hn;for(let r=0;r<n;r++){const l=e[r];let c,h,d=-1,p=0;for(;p<l.length&&(a.lastIndex=p,h=a.exec(l),h!==null);)p=a.lastIndex,a===hn?h[1]==="!--"?a=dr:h[1]!==void 0?a=ur:h[2]!==void 0?(Nl.test(h[2])&&(s=RegExp("</"+h[2],"g")),a=ft):h[3]!==void 0&&(a=ft):a===ft?h[0]===">"?(a=s??hn,d=-1):h[1]===void 0?d=-2:(d=a.lastIndex-h[2].length,c=h[1],a=h[3]===void 0?ft:h[3]==='"'?hr:pr):a===hr||a===pr?a=ft:a===dr||a===ur?a=hn:(a=ft,s=void 0);const g=a===ft&&e[r+1].startsWith("/>")?" ":"";o+=a===hn?l+Ju:d>=0?(i.push(c),l.slice(0,d)+Dl+l.slice(d)+ot+g):l+ot+(d===-2?r:g)}return[Ol(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let mo=class Fl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,a=0;const r=t.length-1,l=this.parts,[c,h]=Zu(t,n);if(this.el=Fl.createElement(c,i),bt.currentNode=this.el.content,n===2||n===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=bt.nextNode())!==null&&l.length<r;){if(s.nodeType===1){if(s.hasAttributes())for(const d of s.getAttributeNames())if(d.endsWith(Dl)){const p=h[a++],g=s.getAttribute(d).split(ot),x=/([.?@])?(.*)/.exec(p);l.push({type:1,index:o,name:x[2],strings:g,ctor:x[1]==="."?tp:x[1]==="?"?np:x[1]==="@"?ip:ns}),s.removeAttribute(d)}else d.startsWith(ot)&&(l.push({type:6,index:o}),s.removeAttribute(d));if(Nl.test(s.tagName)){const d=s.textContent.split(ot),p=d.length-1;if(p>0){s.textContent=Li?Li.emptyScript:"";for(let g=0;g<p;g++)s.append(d[g],Fn()),bt.nextNode(),l.push({type:2,index:++o});s.append(d[p],Fn())}}}else if(s.nodeType===8)if(s.data===Bl)l.push({type:2,index:o});else{let d=-1;for(;(d=s.data.indexOf(ot,d+1))!==-1;)l.push({type:7,index:o}),d+=ot.length-1}o++}}static createElement(t,n){const i=Ct.createElement("template");return i.innerHTML=t,i}};function Jt(e,t,n=e,i){var a,r;if(t===lt)return t;let s=i!==void 0?(a=n._$Co)==null?void 0:a[i]:n._$Cl;const o=Un(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==o&&((r=s==null?void 0:s._$AO)==null||r.call(s,!1),o===void 0?s=void 0:(s=new o(e),s._$AT(e,n,i)),i!==void 0?(n._$Co??(n._$Co=[]))[i]=s:n._$Cl=s),s!==void 0&&(t=Jt(e,s._$AS(e,t.values),s,i)),t}class ep{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)??Ct).importNode(n,!0);bt.currentNode=s;let o=bt.nextNode(),a=0,r=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new ts(o,o.nextSibling,this,t):l.type===1?c=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(c=new sp(o,this,t)),this._$AV.push(c),l=i[++r]}a!==(l==null?void 0:l.index)&&(o=bt.nextNode(),a++)}return bt.currentNode=Ct,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 ts=class Ul{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=Jt(this,t,n),Un(t)?t===w||t==null||t===""?(this._$AH!==w&&this._$AR(),this._$AH=w):t!==this._$AH&&t!==lt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Yu(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==w&&Un(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ct.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=mo.createElement(Ol(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 ep(s,this),r=a.u(this.options);a.p(n),this.T(r),this._$AH=a}}_$AC(t){let n=fr.get(t.strings);return n===void 0&&fr.set(t.strings,n=new mo(t)),n}k(t){Vo(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 Ul(this.O(Fn()),this.O(Fn()),this,this.options)):i=n[s],i._$AI(o),s++;s<n.length&&(this._$AR(i&&i._$AB.nextSibling,s),n.length=s)}_$AR(t=this._$AA.nextSibling,n){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,n);t!==this._$AB;){const s=lr(t).nextSibling;lr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class ns{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=Jt(this,t,n,0),a=!Un(t)||t!==this._$AH&&t!==lt,a&&(this._$AH=t);else{const r=t;let l,c;for(t=o[0],l=0;l<o.length-1;l++)c=Jt(this,r[i+l],n,l),c===lt&&(c=this._$AH[l]),a||(a=!Un(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 tp=class extends ns{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===w?void 0:t}},np=class extends ns{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==w)}},ip=class extends ns{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=Jt(this,t,n,0)??w)===lt)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)}},sp=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){Jt(this,t)}};const op={I:ts},Ms=En.litHtmlPolyfillSupport;Ms==null||Ms(mo,ts),(En.litHtmlVersions??(En.litHtmlVersions=[])).push("3.3.2");const ap=(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 ts(t.insertBefore(Fn(),o),o,void 0,n??{})}return s._$AI(e),s};const xt=globalThis;let Gt=class extends qt{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=ap(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 lt}};var Ll;Gt._$litElement$=!0,Gt.finalized=!0,(Ll=xt.litElementHydrateSupport)==null||Ll.call(xt,{LitElement:Gt});const Ps=xt.litElementPolyfillSupport;Ps==null||Ps({LitElement:Gt});(xt.litElementVersions??(xt.litElementVersions=[])).push("4.2.2");const Wl=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const rp={attribute:!0,type:String,converter:Ii,reflect:!1,hasChanged:Go},lp=(e=rp,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 is(e){return(t,n)=>typeof n=="object"?lp(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 v(e){return is({...e,state:!0,attribute:!1})}const cp=50,dp=200,up="Assistant";function gr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function yo(e){const t=gr(e==null?void 0:e.name,cp)??up,n=gr((e==null?void 0:e.avatar)??void 0,dp)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function pp(){return yo(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const hp="Taskmaster",fp="/taskmaster-icon.png",gp="#00d4ff",mp="";let ai=null;function Ye(){return ai||(ai={name:window.__TASKMASTER_BRAND_NAME__||hp,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||fp,accentColor:window.__TASKMASTER_ACCENT_COLOR__||gp,backgroundColor:window.__TASKMASTER_BACKGROUND_COLOR__||mp},ai)}function Be(){return window.__TASKMASTER_WORKSPACE_BRANDS__??{}}function Kl(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 yp(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 zl(e){const t=Kl(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=yp(e)>.4?"#111111":"#ffffff";n.style.setProperty("--accent-foreground",i),n.style.setProperty("--primary-foreground",i)}function ri(e,t,n){const i=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(t);if(!i||!s)return e;const o=(c,h)=>Math.round(parseInt(i[c],16)*(1-n)+parseInt(s[h],16)*n),a=o(1,1),r=o(2,2),l=o(3,3);return`#${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}const fn={"--bg":"#12141a","--bg-muted":"#262a35","--card":"#181b22","--secondary":"#1e2028"};function ql(e){const t=document.documentElement;if(!e){for(const[i,s]of Object.entries(fn))t.style.setProperty(i,s);t.style.removeProperty("--brand-bg"),t.style.removeProperty("--brand-bg-subtle"),t.style.removeProperty("--brand-bg-card");return}const n=Kl(e);n&&(t.style.setProperty("--bg",ri(fn["--bg"],e,.08)),t.style.setProperty("--bg-muted",ri(fn["--bg-muted"],e,.1)),t.style.setProperty("--card",ri(fn["--card"],e,.12)),t.style.setProperty("--secondary",ri(fn["--secondary"],e,.1)),t.style.setProperty("--brand-bg",e),t.style.setProperty("--brand-bg-subtle",`rgba(${n}, 0.08)`),t.style.setProperty("--brand-bg-card",`rgba(${n}, 0.12)`))}function Tn(e){const t=Ye(),n=Be(),i=e?n[e]:void 0,s=(i==null?void 0:i.accentColor)??t.accentColor;zl(s);const o=(i==null?void 0:i.backgroundColor)??t.backgroundColor;ql(o)}const Ri="taskmaster.control.settings.v1",Hl="taskmaster.account.settings.";function _n(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const Kt={gatewayUrl:_n(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},it={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function vp(){try{const e=localStorage.getItem(Ri);if(!e)return{...Kt,gatewayUrl:_n()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():_n(),token:typeof t.token=="string"?t.token:Kt.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:Kt.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:Kt.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:Kt.navGroupsCollapsed}}catch{return{...Kt,gatewayUrl:_n()}}}function bp(e){if(!e)return{...it};try{const t=localStorage.getItem(Hl+e);if(!t)return{...it};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():it.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||it.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:it.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:it.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:it.splitRatio}}catch{return{...it}}}let Di=null;function mr(e){Di=e}function Is(){return{...vp(),...bp(Di)}}function wp(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(Ri,JSON.stringify(t)),Di){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem(Hl+Di,JSON.stringify(n))}}const kp="taskmaster.draft.";function Qo(e,t){return kp+e+"."+t}function Wn(e,t,n){try{const i=Qo(e,t);n?localStorage.setItem(i,n):localStorage.removeItem(i)}catch{}}function Kn(e,t){try{return localStorage.getItem(Qo(e,t))??""}catch{return""}}function $p(e,t){try{localStorage.removeItem(Qo(e,t))}catch{}}let wt=null,Se=null;function yr(e,t,n){Se={workspace:e,sessionKey:t,text:n},wt!=null&&clearTimeout(wt),wt=setTimeout(()=>{Se&&Wn(Se.workspace,Se.sessionKey,Se.text),Se=null,wt=null},300)}function vo(){wt!=null&&clearTimeout(wt),wt=null,Se&&(Wn(Se.workspace,Se.sessionKey,Se.text),Se=null)}(function(){try{const t=localStorage.getItem(Ri);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:_n(),token:typeof n.token=="string"?n.token:"",theme:n.theme==="light"||n.theme==="dark"||n.theme==="system"?n.theme:"system",navCollapsed:typeof n.navCollapsed=="boolean"?n.navCollapsed:!1,navGroupsCollapsed:typeof n.navGroupsCollapsed=="object"&&n.navGroupsCollapsed!==null?n.navGroupsCollapsed:{}};localStorage.setItem(Ri,JSON.stringify(i))}catch{}})();function jl(e){var o;const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const i=(o=n[1])==null?void 0:o.trim(),s=n.slice(2).join(":");return!i||!s?null:{agentId:i,rest:s}}const xp=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,li=/<\s*\/?\s*final\b[^>]*>/gi,vr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function Sp(e,t){return e.trimStart()}function Ap(e,t){if(!e||!xp.test(e))return e;let n=e;li.test(n)?(li.lastIndex=0,n=n.replace(li,"")):li.lastIndex=0,vr.lastIndex=0;let i="",s=0,o=!1;for(const a of n.matchAll(vr)){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),Sp(i)}function Gl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function ss(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 Jo(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 Cp(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Vl(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 Bi(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Ls(e){return Ap(e)}const Ep=/^\[([^\]]+)\]\s*/,Tp=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Rs=new WeakMap,Ds=new WeakMap;function _p(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:Tp.some(t=>e.startsWith(`${t} `))}function Bs(e){const t=e.match(Ep);if(!t)return e;const n=t[1]??"";return _p(n)?e.slice(t[0].length):e}function Mn(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?Ls(i):Bs(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"?Ls(o):Bs(o)}}return typeof t.text=="string"?n==="assistant"?Ls(t.text):Bs(t.text):null}function Ql(e){if(!e||typeof e!="object")return Mn(e);const t=e;if(Rs.has(t))return Rs.get(t)??null;const n=Mn(e);return Rs.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=Pp(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 Mp(e){if(!e||typeof e!="object")return br(e);const t=e;if(Ds.has(t))return Ds.get(t)??null;const n=br(e);return Ds.set(t,n),n}function Pp(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 Ip(e){const t=e.trim();if(!t)return"";const n=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).map(i=>`_${i}_`);return n.length?["_Reasoning:_",...n].join(`
8
+ `):""}const Lp=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,Rp=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,Dp=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Bp=/^A new session was started via \/new or \/reset\./;function Np(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"&&Lp.test(s)||n==="assistant"&&Rp.test(s)||n==="user"&&Bp.test(s)||n==="assistant"&&Dp.test(s)):!1}function Jl(e){return e.filter(t=>!Np(t))}function Yl(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(d=>{const g=String(d.type??"").toLowerCase();return g==="toolresult"||g==="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(d=>({type:d.type||"text",text:d.text,name:d.name,args:d.args||d.arguments})):typeof t.text=="string"&&(l=[{type:"text",text:t.text}]);const c=typeof t.timestamp=="number"?t.timestamp:Date.now(),h=typeof t.id=="string"?t.id:void 0;return{role:n,content:l,timestamp:c,id:h}}function Xl(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 Zl(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function wr(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 Op(){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 os(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),wr(t)}return wr(Op())}const Fe=50;async function Oe(e,t){if(!e.client||!e.connected)return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??Fe;try{const i=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:n}),s=Array.isArray(i.messages)?i.messages:[],o=typeof i.totalMessages=="number"?i.totalMessages:s.length,a=Jl(s);e.chatMessages=a,e.chatHistoryTotal=o,e.chatHistoryHasMore=o>s.length,e.chatThinkingLevel=i.thinkingLevel??null,e.chatModelProvider=typeof i.modelProvider=="string"?i.modelProvider:null,e.chatModel=typeof i.model=="string"?i.model:null,e.chatVerboseLevel=typeof i.verboseLevel=="string"?i.verboseLevel:null,e.chatFillerEnabled=typeof i.fillerEnabled=="boolean"?i.fillerEnabled:null}catch(i){e.lastError=String(i)}finally{e.chatLoading=!1}}async function Fp(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:Fe,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=Jl(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 Up(e){const t=/^data:(.+?);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function ec(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(g=>!g.fileName),r=(n??[]).filter(g=>g.fileName),l=[],c=r.map(g=>g.fileName).filter(Boolean);if(c.length>0){const g=i?`${c.join(", ")}
9
9
 
10
- ${i}`:c.join(", ");l.push({type:"text",text:v})}else i&&l.push({type:"text",text:i});for(const v of a)l.push({type:"image",source:{type:"base64",media_type:v.mimeType,data:v.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:l,timestamp:o}],e.chatSending=!0,e.lastError=null;const h=ss();e.chatRunId=h,e.chatStream="",e.chatStreamStartedAt=o;const d=[...a,...r],p=d.length>0?d.map(v=>{if(v.textContent)return{type:"document",mimeType:v.mimeType||"text/plain",fileName:v.fileName,content:btoa(unescape(encodeURIComponent(v.textContent)))};const S=Fp(v.dataUrl);return S?{type:v.fileName?"document":"image",mimeType:S.mimeType,fileName:v.fileName,content:S.content}:null}).filter(v=>v!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:h,attachments:p}),!0}catch(v){const S=String(v);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=S,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+S}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function ec(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 tc(e,t){var n,i;if(!t||t.sessionKey!==e.sessionKey)return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return t.state==="final"?"final":null;if(t.state==="working"){const o=(t.message?(n=Mn(t.message))==null?void 0:n.trim():void 0)||((i=e.chatStream)==null?void 0:i.trim());if(o)if(!e.chatInterimText)e.chatInterimText=o;else{const a=o.trim(),r=e.chatInterimText.trim();a===r||r.endsWith(a)||(a.startsWith(r)?e.chatInterimText=o:e.chatInterimText=`${e.chatInterimText}
10
+ ${i}`:c.join(", ");l.push({type:"text",text:g})}else i&&l.push({type:"text",text:i});for(const g of a)l.push({type:"image",source:{type:"base64",media_type:g.mimeType,data:g.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:l,timestamp:o}],e.chatSending=!0,e.lastError=null;const h=os();e.chatRunId=h,e.chatStream="",e.chatStreamStartedAt=o;const d=[...a,...r],p=d.length>0?d.map(g=>{if(g.textContent)return{type:"document",mimeType:g.mimeType||"text/plain",fileName:g.fileName,content:btoa(unescape(encodeURIComponent(g.textContent)))};const x=Up(g.dataUrl);return x?{type:g.fileName?"document":"image",mimeType:x.mimeType,fileName:g.fileName,content:x.content}:null}).filter(g=>g!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:h,attachments:p}),!0}catch(g){const x=String(g);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=x,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+x}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function tc(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 nc(e,t){var n,i;if(!t||t.sessionKey!==e.sessionKey)return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return t.state==="final"?"final":null;if(t.state==="working"){const o=(t.message?(n=Mn(t.message))==null?void 0:n.trim():void 0)||((i=e.chatStream)==null?void 0:i.trim());if(o)if(!e.chatInterimText)e.chatInterimText=o;else{const a=o.trim(),r=e.chatInterimText.trim();a===r||r.endsWith(a)||(a.startsWith(r)?e.chatInterimText=o:e.chatInterimText=`${e.chatInterimText}
11
11
 
12
- ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.message);return typeof s=="string"&&s.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:s.trim()}],timestamp:Date.now(),filler:!0}]),"block"}else if(t.state==="delta"){e.chatSuggestions=[];const s=Mn(t.message);if(typeof s=="string"){if(s.trim()==="NO_REPLY")return null;const o=e.chatStream??"";(!o||s.length>=o.length)&&(e.chatStream=s)}}else t.state==="final"||t.state==="aborted"?(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null):t.state==="error"&&(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null,e.lastError=t.errorMessage??"chat error");return t.state}const Bi=Object.freeze(Object.defineProperty({__proto__:null,CHAT_PAGE_SIZE:Fe,abortChatRun:ec,handleChatEvent:tc,loadChatHistory:Oe,loadOlderChatHistory:Op,sendChatMessage:Zl},Symbol.toStringTag,{value:"Module"}));async function Jo(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:e.sessionsIncludeGlobal??!0,includeUnknown:e.sessionsIncludeUnknown??!1},n=Di(e.sessionsFilterActive??"",0),i=Di(e.sessionsFilterLimit??"",0);n>0&&(t.activeMinutes=n),i>0&&(t.limit=i);const s=await e.client.request("sessions.list",t);s&&(e.sessionsResult=s)}catch(t){e.sessionsError=String(t)}finally{e.sessionsLoading=!1}}}async function li(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 Jo(e)}catch(s){e.sessionsError=String(s)}}const wr=50,Up=80,Wp=12e4;function Kp(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 kr(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=Kp(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=Gl(n,Wp);return i.truncated?`${i.text}
12
+ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.message);return typeof s=="string"&&s.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:s.trim()}],timestamp:Date.now(),filler:!0}]),"block"}else if(t.state==="delta"){e.chatSuggestions=[];const s=Mn(t.message);if(typeof s=="string"){if(s.trim()==="NO_REPLY")return null;const o=e.chatStream??"";(!o||s.length>=o.length)&&(e.chatStream=s)}}else t.state==="final"||t.state==="aborted"?(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null):t.state==="error"&&(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.chatInterimText=null,e.lastError=t.errorMessage??"chat error");return t.state}const Ni=Object.freeze(Object.defineProperty({__proto__:null,CHAT_PAGE_SIZE:Fe,abortChatRun:tc,handleChatEvent:nc,loadChatHistory:Oe,loadOlderChatHistory:Fp,sendChatMessage:ec},Symbol.toStringTag,{value:"Module"}));async function Yo(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:e.sessionsIncludeGlobal??!0,includeUnknown:e.sessionsIncludeUnknown??!1},n=Bi(e.sessionsFilterActive??"",0),i=Bi(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 ci(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 Yo(e)}catch(s){e.sessionsError=String(s)}}const kr=50,Wp=80,Kp=12e4;function zp(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 $r(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=zp(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=Vl(n,Kp);return i.truncated?`${i.text}
14
14
 
15
- … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function zp(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 qp(e){if(e.toolStreamOrder.length<=wr)return;const t=e.toolStreamOrder.length-wr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function Hp(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function vo(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Hp(e)}function jp(e,t=!1){if(t){vo(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>vo(e),Up))}function Yo(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],vo(e)}const Gp=5e3;function Vp(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},Gp))}function Qp(e,t){if(!t)return;if(t.stream==="compaction"){Vp(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"?kr(i.partialResult):a==="result"?kr(i.result):void 0,c=Date.now();let h=e.toolStreamById.get(s);h?(h.name=o,r!==void 0&&(h.args=r),l!==void 0&&(h.output=l),h.updatedAt=c):(h={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,h),e.toolStreamOrder.push(s)),h.message=zp(h),qp(e),jp(e,a==="result")}let ci=0;function nn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++ci,i=()=>{const s=e.querySelector(".chat-thread");if(s){const o=getComputedStyle(s).overflowY;if(o==="auto"||o==="scroll"||s.scrollHeight-s.clientHeight>1)return s}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{n===ci&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==ci)return;const s=i();if(!s)return;const o=s.scrollHeight-s.scrollTop-s.clientHeight;if(!(t||e.chatUserNearBottom||o<200))return;t&&(e.chatHasAutoScrolled=!0),s.scrollTop=s.scrollHeight,e.chatUserNearBottom=!0;const r=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{if(e.chatScrollTimeout=null,n!==ci)return;const l=i();if(!l)return;const c=l.scrollHeight-l.scrollTop-l.clientHeight;(t||e.chatUserNearBottom||c<200)&&(l.scrollTop=l.scrollHeight,e.chatUserNearBottom=!0)},r)}))})}function nc(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 Jp(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 Yp(e){const t=e.querySelector(".chat-thread");if(!t)return null;const n=t.scrollHeight,i=t.scrollTop;return()=>{const s=t.scrollHeight-n;t.scrollTop=i+s}}function Xp(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Zp(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function eh(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function th(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 qp(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 Hp(e){if(e.toolStreamOrder.length<=kr)return;const t=e.toolStreamOrder.length-kr,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function jp(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function bo(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),jp(e)}function Gp(e,t=!1){if(t){bo(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>bo(e),Wp))}function Xo(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],bo(e)}const Vp=5e3;function Qp(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},Vp))}function Jp(e,t){if(!t)return;if(t.stream==="compaction"){Qp(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"?$r(i.partialResult):a==="result"?$r(i.result):void 0,c=Date.now();let h=e.toolStreamById.get(s);h?(h.name=o,r!==void 0&&(h.args=r),l!==void 0&&(h.output=l),h.updatedAt=c):(h={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,h),e.toolStreamOrder.push(s)),h.message=qp(h),Hp(e),Gp(e,a==="result")}let di=0;function nn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=++di,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===di&&(e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,n!==di)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!==di)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 ic(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 Yp(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 Xp(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 Zp(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function eh(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function th(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function nh(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 nh(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 ih(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 ih(e){if(typeof ResizeObserver>"u")return;const t=e.querySelector(".topbar");if(!t)return;const n=()=>{const{height:i}=t.getBoundingClientRect();e.style.setProperty("--topbar-height",`${i}px`)};n(),e.topbarObserver=new ResizeObserver(()=>n()),e.topbarObserver.observe(t)}function lt(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function Ct(e){return`${JSON.stringify(e,null,2).trimEnd()}
20
- `}function ic(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 Ue(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});oh(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function sc(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});sh(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function sh(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function oh(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?Ct(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=Ct(e.configForm):e.configRaw=n,e.configValid=typeof t.valid=="boolean"?t.valid:null,e.configIssues=Array.isArray(t.issues)?t.issues:[],e.configFormDirty||(e.configForm=lt(t.config??{}),e.configFormOriginal=lt(t.config??{}),e.configRawOriginal=n)}async function ah(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?Ct(e.configForm):e.configRaw,i=(t=e.configSnapshot)==null?void 0:t.hash;if(!i){e.lastError="Config hash missing; reload and retry.";return}await e.client.request("config.set",{raw:n,baseHash:i}),e.configFormDirty=!1,await Ue(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function sn(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 Hn(e){if(!(!e.client||!e.connected)&&!e.cronLoading){e.cronLoading=!0,e.cronError=null;try{const t={includeDisabled:!0};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(t.agentIds=e.workspaceAgentIds);const n=await e.client.request("cron.list",t);e.cronJobs=Array.isArray(n.jobs)?n.jobs:[]}catch(t){e.cronError=String(t)}finally{e.cronLoading=!1}}}function oc(e){if(e.scheduleKind==="at"){const n=Date.parse(e.scheduleAt);if(!Number.isFinite(n))throw new Error("Invalid run time.");return{kind:"at",atMs:n}}if(e.scheduleKind==="every"){const n=Di(e.everyAmount,0);if(n<=0)throw new Error("Invalid interval amount.");const i=e.everyUnit;return{kind:"every",everyMs:n*(i==="minutes"?6e4:i==="hours"?36e5:864e5)}}const t=e.cronExpr.trim();if(!t)throw new Error("Cron expression required.");return{kind:"cron",expr:t,tz:e.cronTz.trim()||void 0}}function ac(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=Di(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function rh(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=oc(e.cronForm),i=ac(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 Hn(e),await sn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function lh(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 Hn(e),await sn(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function ch(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 dh(e,t){e.cronRunModalJobId&&t.jobId===e.cronRunModalJobId&&t.action==="finished"&&(e.cronRunResult={status:t.status??"unknown",durationMs:t.durationMs,summary:t.summary,error:t.error})}async function uh(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 Hn(e),await sn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function ph(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 hh(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=oc(e.cronForm),i=ac(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 Hn(e),await sn(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 ee(e,t){if(!(!e.client||!e.connected)&&!e.channelsLoading){e.channelsLoading=!0,e.channelsError=null;try{const n=await e.client.request("channels.status",{probe:t,timeoutMs:8e3});e.channelsSnapshot=n,e.channelsLastSuccess=Date.now()}catch(n){e.channelsError=String(n)}finally{e.channelsLoading=!1}}}async function Xo(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 rc(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 lc(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 cc(e,t){if(!e.client||!e.connected||e.whatsappAccountSaving)return;const n=t.trim();if(!n){e.whatsappAccountError="Account name is required.";return}const i=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");if(!i){e.whatsappAccountError="Invalid account name.";return}e.whatsappAccountSaving=!0,e.whatsappAccountError=null;try{const s=await e.client.request("config.get",{});e.configSnapshot=s;const o=lt(s.config??{});(!o.channels||typeof o.channels!="object")&&(o.channels={});const a=o.channels;(!a.whatsapp||typeof a.whatsapp!="object")&&(a.whatsapp={});const r=a.whatsapp;(!r.accounts||typeof r.accounts!="object")&&(r.accounts={});const l=r.accounts;if(l[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}l[i]={name:n,provider:"baileys"};const c=s.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const h=Ct(o);await e.client.request("config.set",{raw:h,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await ee(e,!0),await Xo(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function dc(e,t){if(!(!e.client||!e.connected)&&!e.whatsappAccountSaving){e.whatsappAccountSaving=!0,e.whatsappAccountError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=lt(n.config??{}),s=i.channels,o=s==null?void 0:s.whatsapp,a=o==null?void 0:o.accounts;if(!a){e.whatsappAccountError="No accounts found in config.";return}if(Object.keys(a).length<=1){e.whatsappAccountError="Cannot remove the last account.";return}if(!a[t]){e.whatsappAccountError=`Account "${t}" not found.`;return}try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t})}catch{}delete a[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(h=>{const d=h.match;return!d||d.channel!=="whatsapp"?!0:d.accountId!==t}));const l=n.hash;if(!l){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=Ct(i);await e.client.request("config.set",{raw:c,baseHash:l}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await ee(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const fh=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:cc,loadChannels:ee,logoutWhatsApp:lc,removeWhatsAppAccount:dc,startWhatsAppLogin:Xo,waitWhatsAppLogin:rc},Symbol.toStringTag,{value:"Module"}));async function Zo(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 gh=2e3,mh=new Set(["trace","debug","info","warn","error","fatal"]);function yh(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 vh(e){if(typeof e!="string")return null;const t=e.toLowerCase();return mh.has(t)?t:null}function uc(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=vh((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=yh(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 Vt(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.logsLoading=!0),e.logsError=null;try{const i=await e.client.request("logs.tail",{cursor:t!=null&&t.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),o=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(uc),a=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=a?o:[...e.logsEntries,...o].slice(-gh),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t!=null&&t.quiet||(e.logsLoading=!1)}}}const bh=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:Vt,parseLogLine:uc},Symbol.toStringTag,{value:"Module"}));const pc={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:pe,n:Si,Gx:$r,Gy:xr,a:Bs,d:Ns,h:wh}=pc,Et=32,ea=64,kh=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ae=(e="")=>{const t=new Error(e);throw kh(t,ae),t},$h=e=>typeof e=="bigint",xh=e=>typeof e=="string",Sh=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",dt=(e,t,n="")=>{const i=Sh(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}`;ae(a+"expected Uint8Array"+r+", got "+l)}return e},os=e=>new Uint8Array(e),hc=e=>Uint8Array.from(e),fc=(e,t)=>e.toString(16).padStart(t,"0"),gc=e=>Array.from(dt(e)).map(t=>fc(t,2)).join(""),je={_0:48,_9:57,A:65,F:70,a:97,f:102},Sr=e=>{if(e>=je._0&&e<=je._9)return e-je._0;if(e>=je.A&&e<=je.F)return e-(je.A-10);if(e>=je.a&&e<=je.f)return e-(je.a-10)},mc=e=>{const t="hex invalid";if(!xh(e))return ae(t);const n=e.length,i=n/2;if(n%2)return ae(t);const s=os(i);for(let o=0,a=0;o<i;o++,a+=2){const r=Sr(e.charCodeAt(a)),l=Sr(e.charCodeAt(a+1));if(r===void 0||l===void 0)return ae(t);s[o]=r*16+l}return s},yc=()=>globalThis==null?void 0:globalThis.crypto,Ah=()=>{var e;return((e=yc())==null?void 0:e.subtle)??ae("crypto.subtle must be defined, consider polyfill")},Kn=(...e)=>{const t=os(e.reduce((i,s)=>i+dt(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Ch=(e=Et)=>yc().getRandomValues(os(e)),Ni=BigInt,mt=(e,t,n,i="bad number: out of range")=>$h(e)&&t<=e&&e<n?e:ae(i),D=(e,t=pe)=>{const n=e%t;return n>=0n?n:t+n},vc=e=>D(e,Si),Eh=(e,t)=>{(e===0n||t<=0n)&&ae("no inverse n="+e+" mod="+t);let n=D(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?D(s,t):ae("no inverse")},Th=e=>{const t=$c[e];return typeof t!="function"&&ae("hashes."+e+" not set"),t},Os=e=>e instanceof Tt?e:ae("Point expected"),wo=2n**256n,Ne=class Ne{constructor(t,n,i,s){q(this,"X");q(this,"Y");q(this,"Z");q(this,"T");const o=wo;this.X=mt(t,0n,o),this.Y=mt(n,0n,o),this.Z=mt(i,1n,o),this.T=mt(s,0n,o),Object.freeze(this)}static CURVE(){return pc}static fromAffine(t){return new Ne(t.x,t.y,1n,D(t.x*t.y))}static fromBytes(t,n=!1){const i=Ns,s=hc(dt(t,Et)),o=t[31];s[31]=o&-129;const a=wc(s);mt(a,0n,n?wo:pe);const l=D(a*a),c=D(l-1n),h=D(i*l+1n);let{isValid:d,value:p}=Mh(c,h);d||ae("bad point: y not sqrt");const v=(p&1n)===1n,S=(o&128)!==0;return!n&&p===0n&&S&&ae("bad point: x==0, isLastByteOdd"),S!==v&&(p=D(-p)),new Ne(p,a,1n,D(p*a))}static fromHex(t,n){return Ne.fromBytes(mc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Bs,n=Ns,i=this;if(i.is0())return ae("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,l=D(s*s),c=D(o*o),h=D(a*a),d=D(h*h),p=D(l*t),v=D(h*D(p+c)),S=D(d+D(n*D(l*c)));if(v!==S)return ae("bad point: equation left != right (1)");const x=D(s*o),T=D(a*r);return x!==T?ae("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:a,Z:r}=Os(t),l=D(n*r),c=D(o*s),h=D(i*r),d=D(a*s);return l===c&&h===d}is0(){return this.equals(jt)}negate(){return new Ne(D(-this.X),this.Y,this.Z,D(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=Bs,o=D(t*t),a=D(n*n),r=D(2n*D(i*i)),l=D(s*o),c=t+n,h=D(D(c*c)-o-a),d=l+a,p=d-r,v=l-a,S=D(h*p),x=D(d*v),T=D(h*v),f=D(p*d);return new Ne(S,x,f,T)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:l,T:c}=Os(t),h=Bs,d=Ns,p=D(n*a),v=D(i*r),S=D(o*d*c),x=D(s*l),T=D((n+i)*(a+r)-p-v),f=D(x-S),b=D(x+S),k=D(v-h*p),A=D(T*f),E=D(b*k),M=D(T*k),P=D(f*b);return new Ne(A,E,P,M)}subtract(t){return this.add(Os(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return jt;if(mt(t,1n,Si),t===1n)return this;if(this.equals(_t))return Wh(t).p;let i=jt,s=_t;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?i=i.add(o):n&&(s=s.add(o));return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:i}=this;if(this.equals(jt))return{x:0n,y:1n};const s=Eh(i,pe);D(i*s)!==1n&&ae("invalid inverse");const o=D(t*s),a=D(n*s);return{x:o,y:a}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=bc(n);return i[31]|=t&1n?128:0,i}toHex(){return gc(this.toBytes())}clearCofactor(){return this.multiply(Ni(wh),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Si/2n,!1).double();return Si%2n&&(t=t.add(this)),t.is0()}};q(Ne,"BASE"),q(Ne,"ZERO");let Tt=Ne;const _t=new Tt($r,xr,1n,D($r*xr)),jt=new Tt(0n,1n,1n,0n);Tt.BASE=_t;Tt.ZERO=jt;const bc=e=>mc(fc(mt(e,0n,wo),ea)).reverse(),wc=e=>Ni("0x"+gc(hc(dt(e)).reverse())),Ie=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=pe;return n},_h=e=>{const n=e*e%pe*e%pe,i=Ie(n,2n)*n%pe,s=Ie(i,1n)*e%pe,o=Ie(s,5n)*s%pe,a=Ie(o,10n)*o%pe,r=Ie(a,20n)*a%pe,l=Ie(r,40n)*r%pe,c=Ie(l,80n)*l%pe,h=Ie(c,80n)*l%pe,d=Ie(h,10n)*o%pe;return{pow_p_5_8:Ie(d,2n)*e%pe,b2:n}},Ar=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Mh=(e,t)=>{const n=D(t*t*t),i=D(n*n*t),s=_h(e*i).pow_p_5_8;let o=D(e*n*s);const a=D(t*o*o),r=o,l=D(o*Ar),c=a===e,h=a===D(-e),d=a===D(-e*Ar);return c&&(o=r),(h||d)&&(o=l),(D(o)&1n)===1n&&(o=D(-o)),{isValid:c||h,value:o}},ko=e=>vc(wc(e)),ta=(...e)=>$c.sha512Async(Kn(...e)),Ph=(...e)=>Th("sha512")(Kn(...e)),kc=e=>{const t=e.slice(0,Et);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Et,ea),i=ko(t),s=_t.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},na=e=>ta(dt(e,Et)).then(kc),Ih=e=>kc(Ph(dt(e,Et))),Lh=e=>na(e).then(t=>t.pointBytes),Rh=e=>ta(e.hashable).then(e.finish),Dh=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=ko(t),a=_t.multiply(o).toBytes();return{hashable:Kn(a,i,n),finish:c=>{const h=vc(o+ko(c)*s);return dt(Kn(a,bc(h)),ea)}}},Bh=async(e,t)=>{const n=dt(e),i=await na(t),s=await ta(i.prefix,n);return Rh(Dh(i,s,n))},$c={sha512Async:async e=>{const t=Ah(),n=Kn(e);return os(await t.digest("SHA-512",n.buffer))},sha512:void 0},Nh=(e=Ch(Et))=>e,Oh={getExtendedPublicKeyAsync:na,getExtendedPublicKey:Ih,randomSecretKey:Nh},Oi=8,Fh=256,xc=Math.ceil(Fh/Oi)+1,$o=2**(Oi-1),Uh=()=>{const e=[];let t=_t,n=t;for(let i=0;i<xc;i++){n=t,e.push(n);for(let s=1;s<$o;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Cr;const Er=(e,t)=>{const n=t.negate();return e?n:t},Wh=e=>{const t=Cr||(Cr=Uh());let n=jt,i=_t;const s=2**Oi,o=s,a=Ni(s-1),r=Ni(Oi);for(let l=0;l<xc;l++){let c=Number(e&a);e>>=r,c>$o&&(c-=o,e+=1n);const h=l*$o,d=h,p=h+Math.abs(c)-1,v=l%2!==0,S=c<0;c===0?i=i.add(Er(v,t[d])):n=n.add(Er(S,t[p]))}return e!==0n&&ae("invalid wnaf"),{p:n,f:i}},Fs="taskmaster-device-identity-v1";function xo(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Sc(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4),i=atob(n),s=new Uint8Array(i.length);for(let o=0;o<i.length;o+=1)s[o]=i.charCodeAt(o);return s}function Kh(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Ac(e){const t=await crypto.subtle.digest("SHA-256",e);return Kh(new Uint8Array(t))}async function zh(){const e=Oh.randomSecretKey(),t=await Lh(e);return{deviceId:await Ac(t),publicKey:xo(t),privateKey:xo(e)}}async function qh(){try{const n=localStorage.getItem(Fs);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 Ac(Sc(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(Fs,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 zh(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Fs,JSON.stringify(t)),e}async function Hh(e,t){const n=Sc(e),i=new TextEncoder().encode(t),s=await Bh(i,n);return xo(s)}const Cc="taskmaster.device.auth.v1";function ia(e){return e.trim()}function jh(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 sa(){try{const e=window.localStorage.getItem(Cc);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 Ec(e){try{window.localStorage.setItem(Cc,JSON.stringify(e))}catch{}}function Gh(e){const t=sa();if(!t||t.deviceId!==e.deviceId)return null;const n=ia(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function Vh(e){const t=ia(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=sa();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:jh(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Ec(n),s}function Qh(e){const t=sa();if(!t||t.deviceId!==e.deviceId)return;const n=ia(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Ec(i)}async function oa(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 Jh(e){return{method:"exec.approvals.get",params:{}}}async function Yh(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=Jh(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);Xh(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function Xh(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=lt(t.file??{}))}async function Tc(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 ct(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function Ze(e){return e instanceof Error?e.message:String(e)}function zn(){return{name:"",skillContent:"",references:[]}}async function Xe(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=Ze(n)}finally{e.skillsLoading=!1}}}function _c(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Mc(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 Xe(e),ct(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=Ze(i);e.skillsError=s,ct(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Pc(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 Xe(e),ct(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=Ze(n);e.skillsError=i,ct(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Ic(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 Xe(e),ct(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=Ze(s);e.skillsError=o,ct(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function Lc(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=Ze(n)}}function Rc(e){e.skillDetail=null,e.skillDetailTab=""}function Dc(e,t){e.skillDetailTab=t}async function Bc(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 Nc(e){e.skillAddModal=!1,e.skillAddForm=zn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[]}function Oc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n}))},e.skillAddFormSource="draft"}async function Fc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n}))},e.skillAddFormSource="installed",await ra(e)}async function ra(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}),e.skillAddModal=!1,e.skillAddForm=zn(),e.skillAddFormSource="draft",e.skillDrafts=[],await Xe(e),ct(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=[],ct(e,i,{kind:"success",message:"Draft saved"}))}catch(n){e.skillsError=Ze(n)}finally{e.skillsBusyKey=null}}}async function Uc(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=Ze(n)}}async function Wc(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("skills.read",{name:t});if(!n)return;e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i}))},e.skillAddFormSource="installed",e.skillAddModal=!0,e.skillDrafts=[]}catch(n){e.skillsError=Ze(n)}}function Kc(e,t){const n=e.skillDetail;n&&(e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i}))},e.skillAddFormSource="installed",e.skillEditTab=t&&t!=="SKILL.md"?t:"SKILL.md",e.skillDetail=null,e.skillDetailTab="",e.skillAddModal=!0,e.skillDrafts=[])}function zc(e,t,n){e.skillAddForm={...e.skillAddForm,references:e.skillAddForm.references.map(i=>i.name===t?{...i,content:n}:i)}}function qc(e,t){e.skillEditTab=t}async function Hc(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await Xe(e)}catch(n){e.skillsError=Ze(n)}finally{e.skillsBusyKey=null}}}const Zh=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:Nc,closeSkillDetail:Rc,deleteDraft:Uc,deleteSkill:Hc,editDetailSkill:Kc,editSkill:Wc,emptyAddForm:zn,importDraft:Oc,installDraft:Fc,installSkill:Ic,loadSkills:Xe,openAddSkillModal:Bc,saveNewSkill:ra,saveSkillApiKey:Pc,setEditTab:qc,setSkillDetailTab:Dc,updateFormReference:zc,updateSkillEdit:_c,updateSkillEnabled:Mc,viewSkillDetail:Lc},Symbol.toStringTag,{value:"Module"})),jc={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},Gc=new Map(Object.entries(jc).map(([e,t])=>[t,e]));function as(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function qn(e){if(!e)return"/";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function ef(e,t=""){const n=as(t),i=jc[e];return n?`${n}${i}`:i}function Vc(e,t=""){const n=as(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=qn(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":Gc.get(s)??null}function tf(e){let t=qn(e);if(t.endsWith("/index.html")&&(t=qn(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let i=0;i<n.length;i++){const s=`/${n.slice(i).join("/")}`.toLowerCase();if(Gc.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 la(e){return e==="system"?nf():e}const di=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,ui=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 h=.5,d=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")h=di(n.pointerClientX/window.innerWidth),d=di(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const p=n.element.getBoundingClientRect();p.width>0&&p.height>0&&typeof window<"u"&&(h=di((p.left+p.width/2)/window.innerWidth),d=di((p.top+p.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${h*100}%`),o.style.setProperty("--theme-switch-y",`${d*100}%`),o.classList.add("theme-transition");try{const p=(c=a.startViewTransition)==null?void 0:c.call(a,()=>{t()});p!=null&&p.finished?p.finished.finally(()=>ui(o)):ui(o)}catch{ui(o),t()}return}t(),ui(o)},af=2e3;async function Pn(e,t){if(!(!e.client||!e.connected)&&!(e.sessionLogsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.sessionLogsLoading=!0),e.sessionLogsError=null;try{const n={cursors:t!=null&&t.reset?void 0:e.sessionLogsCursors,limit:500};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(n.agents=e.workspaceAgentIds);const s=await e.client.request("sessions.transcript",n),o=Array.isArray(s.entries)?s.entries:[],a=!!(t!=null&&t.reset||Object.keys(e.sessionLogsCursors).length===0);e.sessionLogsEntries=a?o:[...e.sessionLogsEntries,...o].slice(-af),s.cursors&&(e.sessionLogsCursors=s.cursors),Array.isArray(s.agents)&&(e.sessionLogsAgents=s.agents),e.sessionLogsLastFetchAt=Date.now()}catch(n){e.sessionLogsError=String(n)}finally{t!=null&&t.quiet||(e.sessionLogsLoading=!1)}}}const Qc=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:Pn},Symbol.toStringTag,{value:"Module"}));async function Jc(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 We(e){return e instanceof Error?e.message:String(e)}let pi=null;function on(e,t){pi&&clearTimeout(pi),e.filesMessage={kind:"success",text:t},pi=setTimeout(()=>{e.filesMessage=null,pi=null},3e3)}async function an(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=We(n)}finally{e.filesLoading=!1}}}}async function lf(e,t,n){e.filesSelectedPaths=new Set([t]),await Yc(e,t,n)}async function cf(e,t,n){const i=new Set(e.filesSelectedPaths);if(i.has(t)?i.delete(t):i.add(t),e.filesSelectedPaths=i,i.size===1){const s=[...i][0];await Yc(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function df(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 Xc(e,o,t),i++}catch(a){s=We(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:on(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 Yc(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=We(i)}finally{e.filesPreviewLoading=!1}}}async function Xc(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:We(i)}}}async function pf(e,t,n,i){if(!e.client||!e.connected)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="";for(const a of n)try{const r=await a.arrayBuffer(),l=btoa(new Uint8Array(r).reduce((h,d)=>h+String.fromCharCode(d),"")),c={path:t,name:a.name,data:l};i&&(c.agentId=i),await e.client.request("files.upload",c),s++}catch(r){o=We(r)}e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:on(e,`${s} file${s!==1?"s":""} uploaded`),await an(e,i)}async function hf(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),on(e,`Created ${s}`),await an(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:We(o)}}}async function ff(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),on(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await an(e,n)}catch(i){e.filesMessage={kind:"error",text:We(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),on(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await an(e,i)}catch(s){e.filesMessage={kind:"error",text:We(s)}}}}async function rs(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 mf(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;on(e,`Re-indexed: ${s} files, ${o} chunks`),await rs(e,t)}catch(n){e.filesMessage={kind:"error",text:We(n)}}finally{e.filesReindexBusy=!1}}}function yf(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 vf(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:We(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function bf(e){e.filesSearchQuery="",e.filesSearchResults=null}function wf(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{aa(e,{quiet:!0})},5e3))}function kf(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function ca(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Vt(e,{quiet:!0})},2e3))}function da(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function ua(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||Pn(e,{quiet:!0})},2e3))}function pa(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function ha(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&Zo(e)},3e3))}function fa(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function $f(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{Jc(e)},3e4))}function xf(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function Sf(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{const t=e;t.filesPage&&rs(t,t.filesResolvedAgentId)},3e3))}function Af(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function at(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,bp(n),t.theme!==e.theme&&(e.theme=t.theme,ls(e,la(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Zc(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&at(e,{...e.settings,lastActiveSessionKey:n})}function Cf(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),i=t.get("password"),s=t.get("session"),o=t.get("gatewayUrl");let a=!1;if(n!=null){const l=n.trim();l&&l!==e.settings.token&&at(e,{...e.settings,token:l}),t.delete("token"),a=!0}if(i!=null){const l=i.trim();l&&(e.password=l),t.delete("password"),a=!0}if(s!=null){const l=s.trim();l&&(e.sessionKey=l,at(e,{...e.settings,sessionKey:l,lastActiveSessionKey:l}))}if(o!=null){const l=o.trim();l&&l!==e.settings.gatewayUrl&&at(e,{...e.settings,gatewayUrl:l}),t.delete("gatewayUrl"),a=!0}if(!a)return;const r=new URL(window.location.href);r.search=t.toString(),window.history.replaceState({},"",r.toString())}function Ef(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?ua(e):ca(e):(da(e),pa(e)),t==="debug"?ha(e):fa(e),Fi(e),td(e,t,!1)}function Tf(e,t,n){of({nextTheme:t,applyTheme:()=>{e.theme=t,at(e,{...e.settings,theme:t}),ls(e,la(t))},context:n,currentTheme:e.theme})}async function Fi(e){if(e.tab==="overview"&&await nd(e),e.tab==="channels"&&await Df(e),e.tab==="instances"&&await Tc(e),e.tab==="cron"&&await ga(e),e.tab==="skills"&&await Xe(e),e.tab==="nodes"&&(await aa(e),await oa(e),await Ue(e),await Yh(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await Uf(e),nn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await sc(e),await Ue(e)),e.tab==="debug"&&(await Zo(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await le(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>Qc);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await Vt(e,{reset:!0});nc(e,!0)}}function _f(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?as(e):tf(window.location.pathname)}function Mf(e){e.theme=e.settings.theme??"system",ls(e,la(e.theme))}function ls(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function Pf(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"&&ls(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function If(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 Lf(e,t){if(typeof window>"u")return;const n=Vc(window.location.pathname,e.basePath)??"chat";ed(e,n),td(e,n,t)}function Rf(e){var s;if(typeof window>"u")return;const t=Vc(window.location.pathname,e.basePath);if(!t)return;const i=(s=new URL(window.location.href).searchParams.get("session"))==null?void 0:s.trim();i&&(e.sessionKey=i,at(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),ed(e,t)}function ed(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?ua(e):ca(e):(da(e),pa(e)),t==="debug"?ha(e):fa(e),e.connected&&Fi(e)}function td(e,t,n){if(typeof window>"u")return;const i=qn(ef(t,e.basePath)),s=qn(window.location.pathname),o=new URL(window.location.href);t==="chat"&&e.sessionKey?o.searchParams.set("session",e.sessionKey):o.searchParams.delete("session"),s!==i&&(o.pathname=i),n?window.history.replaceState({},"",o.toString()):window.history.pushState({},"",o.toString())}async function nd(e){await Promise.all([ee(e,!1),Tc(e),Jo(e),sn(e),Zo(e)])}async function Df(e){await Promise.all([ee(e,!0),sc(e),Ue(e)])}async function ga(e){await Promise.all([ee(e,!1),sn(e),Hn(e)])}function id(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 sd(e){e.connected&&(e.chatMessage="",await ec(e))}function Nf(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:ss(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],nn(e))}async function od(e,t,n){var s,o;Yo(e);const i=await Zl(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&&Zc(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),nn(e),i&&!e.chatRunId&&ad(e),i}async function ad(e){if(!e.connected||id(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await od(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function Of(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function Ff(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),o=e.chatAttachments??[],a=t==null?o:[],r=a.length>0;if(!(!s&&!r)){if(Bf(s)){await sd(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],kp(e.selectedWorkspace??"",e.sessionKey)),id(e)){Nf(e,s,a);return}await od(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 Uf(e){var i;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,Fe);await Promise.all([Oe(t,{limit:n}),Jo(t),So(e)]),nn(e,!0)}const Wf=ad;function Kf(e){var s,o,a;const t=Hl(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(s=e.hello)==null?void 0:s.snapshot;return((a=(o=n==null?void 0:n.sessionDefaults)==null?void 0:o.defaultAgentId)==null?void 0:a.trim())||"main"}function zf(e,t){const n=as(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function So(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=Kf(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 L={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>`,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>`,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>`,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>`},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"><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>`,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 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>`,jf=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 Tr=!1;function Gf(){Tr||(Tr=!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 Lt(e,t){var d;const n=(p,v)=>p===e?u`<span class="sp-page-nav-current">${p}</span>`:u`<a href=${v}>${p}</a>`,i=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 sh(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 ct(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function Et(e){return`${JSON.stringify(e,null,2).trimEnd()}
20
+ `}function sc(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 Ue(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});ah(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function oc(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});oh(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function oh(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function ah(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?Et(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=Et(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=ct(t.config??{}),e.configFormOriginal=ct(t.config??{}),e.configRawOriginal=n)}async function rh(e){var t;if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const n=e.configFormMode==="form"&&e.configForm?Et(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 Ue(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function sn(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("cron.status",{});e.cronStatus=t}catch(t){e.cronError=String(t)}}async function jn(e){if(!(!e.client||!e.connected)&&!e.cronLoading){e.cronLoading=!0,e.cronError=null;try{const t={includeDisabled:!0};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(t.agentIds=e.workspaceAgentIds);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 ac(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=Bi(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 rc(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=Bi(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function lh(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=ac(e.cronForm),i=rc(e.cronForm),s=e.cronForm.agentId.trim(),o=(t=e.cronForm.accountId)==null?void 0:t.trim(),a={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,accountId:o||void 0,enabled:e.cronForm.enabled,schedule:n,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:i,isolation:e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?{postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:void 0};if(!a.name)throw new Error("Name required.");await e.client.request("cron.add",a),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await jn(e),await sn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function ch(e,t,n){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.update",{id:t.id,patch:{enabled:n}}),await jn(e),await sn(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function dh(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 wo(e,t.id)}catch(n){e.cronError=String(n),e.cronRunResult={status:"error",error:String(n)}}finally{e.cronBusy=!1}}}function uh(e,t){e.cronRunModalJobId&&t.jobId===e.cronRunModalJobId&&t.action==="finished"&&(e.cronRunResult={status:t.status??"unknown",durationMs:t.durationMs,summary:t.summary,error:t.error})}async function ph(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.remove",{id:t.id}),e.cronRunsJobId===t.id&&(e.cronRunsJobId=null,e.cronRuns=[]),await jn(e),await sn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}function hh(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 fh(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=ac(e.cronForm),i=rc(e.cronForm),s={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:e.cronForm.agentId.trim()||void 0,enabled:e.cronForm.enabled,schedule:n,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:i};if(e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?s.isolation={postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:s.isolation=void 0,!s.name)throw new Error("Name required.");await e.client.request("cron.update",{id:t,patch:s}),await jn(e),await sn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function wo(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("cron.runs",{id:t,limit:50});e.cronRunsJobId=t,e.cronRuns=Array.isArray(n.entries)?n.entries:[]}catch(n){e.cronError=String(n)}}async function ee(e,t){if(!(!e.client||!e.connected)&&!e.channelsLoading){e.channelsLoading=!0,e.channelsError=null;try{const n=await e.client.request("channels.status",{probe:t,timeoutMs:8e3});e.channelsSnapshot=n,e.channelsLastSuccess=Date.now()}catch(n){e.channelsError=String(n)}finally{e.channelsLoading=!1}}}async function Zo(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 lc(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 cc(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 dc(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=ct(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 h=Et(o);await e.client.request("config.set",{raw:h,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await ee(e,!0),await Zo(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function uc(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=ct(n.config??{}),s=i.channels,o=s==null?void 0:s.whatsapp,a=o==null?void 0:o.accounts;if(!a){e.whatsappAccountError="No accounts found in config.";return}if(Object.keys(a).length<=1){e.whatsappAccountError="Cannot remove the last account.";return}if(!a[t]){e.whatsappAccountError=`Account "${t}" not found.`;return}try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t})}catch{}delete a[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(h=>{const d=h.match;return!d||d.channel!=="whatsapp"?!0:d.accountId!==t}));const l=n.hash;if(!l){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=Et(i);await e.client.request("config.set",{raw:c,baseHash:l}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await ee(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const gh=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:dc,loadChannels:ee,logoutWhatsApp:cc,removeWhatsAppAccount:uc,startWhatsAppLogin:Zo,waitWhatsAppLogin:lc},Symbol.toStringTag,{value:"Module"}));async function ea(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 mh=2e3,yh=new Set(["trace","debug","info","warn","error","fatal"]);function vh(e){if(typeof e!="string")return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return!n||typeof n!="object"?null:n}catch{return null}}function bh(e){if(typeof e!="string")return null;const t=e.toLowerCase();return yh.has(t)?t:null}function pc(e){if(!e.trim())return{raw:e,message:e};try{const t=JSON.parse(e),n=t&&typeof t._meta=="object"&&t._meta!==null?t._meta:null,i=typeof t.time=="string"?t.time:typeof(n==null?void 0:n.date)=="string"?n==null?void 0:n.date:null,s=bh((n==null?void 0:n.logLevelName)??(n==null?void 0:n.level)),o=typeof t[0]=="string"?t[0]:typeof(n==null?void 0:n.name)=="string"?n==null?void 0:n.name:null,a=vh(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 Vt(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.logsLoading=!0),e.logsError=null;try{const i=await e.client.request("logs.tail",{cursor:t!=null&&t.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),o=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(pc),a=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=a?o:[...e.logsEntries,...o].slice(-mh),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t!=null&&t.quiet||(e.logsLoading=!1)}}}const wh=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:Vt,parseLogLine:pc},Symbol.toStringTag,{value:"Module"}));const hc={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:pe,n:Ai,Gx:xr,Gy:Sr,a:Ns,d:Os,h:kh}=hc,Tt=32,ta=64,$h=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ae=(e="")=>{const t=new Error(e);throw $h(t,ae),t},xh=e=>typeof e=="bigint",Sh=e=>typeof e=="string",Ah=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",ut=(e,t,n="")=>{const i=Ah(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}`;ae(a+"expected Uint8Array"+r+", got "+l)}return e},as=e=>new Uint8Array(e),fc=e=>Uint8Array.from(e),gc=(e,t)=>e.toString(16).padStart(t,"0"),mc=e=>Array.from(ut(e)).map(t=>gc(t,2)).join(""),je={_0:48,_9:57,A:65,F:70,a:97,f:102},Ar=e=>{if(e>=je._0&&e<=je._9)return e-je._0;if(e>=je.A&&e<=je.F)return e-(je.A-10);if(e>=je.a&&e<=je.f)return e-(je.a-10)},yc=e=>{const t="hex invalid";if(!Sh(e))return ae(t);const n=e.length,i=n/2;if(n%2)return ae(t);const s=as(i);for(let o=0,a=0;o<i;o++,a+=2){const r=Ar(e.charCodeAt(a)),l=Ar(e.charCodeAt(a+1));if(r===void 0||l===void 0)return ae(t);s[o]=r*16+l}return s},vc=()=>globalThis==null?void 0:globalThis.crypto,Ch=()=>{var e;return((e=vc())==null?void 0:e.subtle)??ae("crypto.subtle must be defined, consider polyfill")},zn=(...e)=>{const t=as(e.reduce((i,s)=>i+ut(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Eh=(e=Tt)=>vc().getRandomValues(as(e)),Oi=BigInt,yt=(e,t,n,i="bad number: out of range")=>xh(e)&&t<=e&&e<n?e:ae(i),D=(e,t=pe)=>{const n=e%t;return n>=0n?n:t+n},bc=e=>D(e,Ai),Th=(e,t)=>{(e===0n||t<=0n)&&ae("no inverse n="+e+" mod="+t);let n=D(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?D(s,t):ae("no inverse")},_h=e=>{const t=xc[e];return typeof t!="function"&&ae("hashes."+e+" not set"),t},Fs=e=>e instanceof _t?e:ae("Point expected"),ko=2n**256n,Ne=class Ne{constructor(t,n,i,s){q(this,"X");q(this,"Y");q(this,"Z");q(this,"T");const o=ko;this.X=yt(t,0n,o),this.Y=yt(n,0n,o),this.Z=yt(i,1n,o),this.T=yt(s,0n,o),Object.freeze(this)}static CURVE(){return hc}static fromAffine(t){return new Ne(t.x,t.y,1n,D(t.x*t.y))}static fromBytes(t,n=!1){const i=Os,s=fc(ut(t,Tt)),o=t[31];s[31]=o&-129;const a=kc(s);yt(a,0n,n?ko:pe);const l=D(a*a),c=D(l-1n),h=D(i*l+1n);let{isValid:d,value:p}=Ph(c,h);d||ae("bad point: y not sqrt");const g=(p&1n)===1n,x=(o&128)!==0;return!n&&p===0n&&x&&ae("bad point: x==0, isLastByteOdd"),x!==g&&(p=D(-p)),new Ne(p,a,1n,D(p*a))}static fromHex(t,n){return Ne.fromBytes(yc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Ns,n=Os,i=this;if(i.is0())return ae("bad point: ZERO");const{X:s,Y:o,Z:a,T:r}=i,l=D(s*s),c=D(o*o),h=D(a*a),d=D(h*h),p=D(l*t),g=D(h*D(p+c)),x=D(d+D(n*D(l*c)));if(g!==x)return ae("bad point: equation left != right (1)");const S=D(s*o),T=D(a*r);return S!==T?ae("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:a,Z:r}=Fs(t),l=D(n*r),c=D(o*s),h=D(i*r),d=D(a*s);return l===c&&h===d}is0(){return this.equals(jt)}negate(){return new Ne(D(-this.X),this.Y,this.Z,D(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=Ns,o=D(t*t),a=D(n*n),r=D(2n*D(i*i)),l=D(s*o),c=t+n,h=D(D(c*c)-o-a),d=l+a,p=d-r,g=l-a,x=D(h*p),S=D(d*g),T=D(h*g),f=D(p*d);return new Ne(x,S,f,T)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:a,Y:r,Z:l,T:c}=Fs(t),h=Ns,d=Os,p=D(n*a),g=D(i*r),x=D(o*d*c),S=D(s*l),T=D((n+i)*(a+r)-p-g),f=D(S-x),b=D(S+x),k=D(g-h*p),A=D(T*f),E=D(b*k),M=D(T*k),P=D(f*b);return new Ne(A,E,P,M)}subtract(t){return this.add(Fs(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return jt;if(yt(t,1n,Ai),t===1n)return this;if(this.equals(Mt))return Kh(t).p;let i=jt,s=Mt;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?i=i.add(o):n&&(s=s.add(o));return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:i}=this;if(this.equals(jt))return{x:0n,y:1n};const s=Th(i,pe);D(i*s)!==1n&&ae("invalid inverse");const o=D(t*s),a=D(n*s);return{x:o,y:a}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=wc(n);return i[31]|=t&1n?128:0,i}toHex(){return mc(this.toBytes())}clearCofactor(){return this.multiply(Oi(kh),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ai/2n,!1).double();return Ai%2n&&(t=t.add(this)),t.is0()}};q(Ne,"BASE"),q(Ne,"ZERO");let _t=Ne;const Mt=new _t(xr,Sr,1n,D(xr*Sr)),jt=new _t(0n,1n,1n,0n);_t.BASE=Mt;_t.ZERO=jt;const wc=e=>yc(gc(yt(e,0n,ko),ta)).reverse(),kc=e=>Oi("0x"+mc(fc(ut(e)).reverse())),Ie=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=pe;return n},Mh=e=>{const n=e*e%pe*e%pe,i=Ie(n,2n)*n%pe,s=Ie(i,1n)*e%pe,o=Ie(s,5n)*s%pe,a=Ie(o,10n)*o%pe,r=Ie(a,20n)*a%pe,l=Ie(r,40n)*r%pe,c=Ie(l,80n)*l%pe,h=Ie(c,80n)*l%pe,d=Ie(h,10n)*o%pe;return{pow_p_5_8:Ie(d,2n)*e%pe,b2:n}},Cr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Ph=(e,t)=>{const n=D(t*t*t),i=D(n*n*t),s=Mh(e*i).pow_p_5_8;let o=D(e*n*s);const a=D(t*o*o),r=o,l=D(o*Cr),c=a===e,h=a===D(-e),d=a===D(-e*Cr);return c&&(o=r),(h||d)&&(o=l),(D(o)&1n)===1n&&(o=D(-o)),{isValid:c||h,value:o}},$o=e=>bc(kc(e)),na=(...e)=>xc.sha512Async(zn(...e)),Ih=(...e)=>_h("sha512")(zn(...e)),$c=e=>{const t=e.slice(0,Tt);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Tt,ta),i=$o(t),s=Mt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},ia=e=>na(ut(e,Tt)).then($c),Lh=e=>$c(Ih(ut(e,Tt))),Rh=e=>ia(e).then(t=>t.pointBytes),Dh=e=>na(e.hashable).then(e.finish),Bh=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=$o(t),a=Mt.multiply(o).toBytes();return{hashable:zn(a,i,n),finish:c=>{const h=bc(o+$o(c)*s);return ut(zn(a,wc(h)),ta)}}},Nh=async(e,t)=>{const n=ut(e),i=await ia(t),s=await na(i.prefix,n);return Dh(Bh(i,s,n))},xc={sha512Async:async e=>{const t=Ch(),n=zn(e);return as(await t.digest("SHA-512",n.buffer))},sha512:void 0},Oh=(e=Eh(Tt))=>e,Fh={getExtendedPublicKeyAsync:ia,getExtendedPublicKey:Lh,randomSecretKey:Oh},Fi=8,Uh=256,Sc=Math.ceil(Uh/Fi)+1,xo=2**(Fi-1),Wh=()=>{const e=[];let t=Mt,n=t;for(let i=0;i<Sc;i++){n=t,e.push(n);for(let s=1;s<xo;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Er;const Tr=(e,t)=>{const n=t.negate();return e?n:t},Kh=e=>{const t=Er||(Er=Wh());let n=jt,i=Mt;const s=2**Fi,o=s,a=Oi(s-1),r=Oi(Fi);for(let l=0;l<Sc;l++){let c=Number(e&a);e>>=r,c>xo&&(c-=o,e+=1n);const h=l*xo,d=h,p=h+Math.abs(c)-1,g=l%2!==0,x=c<0;c===0?i=i.add(Tr(g,t[d])):n=n.add(Tr(x,t[p]))}return e!==0n&&ae("invalid wnaf"),{p:n,f:i}},Us="taskmaster-device-identity-v1";function So(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Ac(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 zh(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Cc(e){const t=await crypto.subtle.digest("SHA-256",e);return zh(new Uint8Array(t))}async function qh(){const e=Fh.randomSecretKey(),t=await Rh(e);return{deviceId:await Cc(t),publicKey:So(t),privateKey:So(e)}}async function Hh(){try{const n=localStorage.getItem(Us);if(n){const i=JSON.parse(n);if((i==null?void 0:i.version)===1&&typeof i.deviceId=="string"&&typeof i.publicKey=="string"&&typeof i.privateKey=="string"){const s=await Cc(Ac(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(Us,JSON.stringify(o)),{deviceId:s,publicKey:i.publicKey,privateKey:i.privateKey}}return{deviceId:i.deviceId,publicKey:i.publicKey,privateKey:i.privateKey}}}}catch{}const e=await qh(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Us,JSON.stringify(t)),e}async function jh(e,t){const n=Ac(e),i=new TextEncoder().encode(t),s=await Nh(i,n);return So(s)}const Ec="taskmaster.device.auth.v1";function sa(e){return e.trim()}function Gh(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 oa(){try{const e=window.localStorage.getItem(Ec);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 Tc(e){try{window.localStorage.setItem(Ec,JSON.stringify(e))}catch{}}function Vh(e){const t=oa();if(!t||t.deviceId!==e.deviceId)return null;const n=sa(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function Qh(e){const t=sa(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=oa();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:Gh(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Tc(n),s}function Jh(e){const t=oa();if(!t||t.deviceId!==e.deviceId)return;const n=sa(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Tc(i)}async function aa(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 ra(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 Yh(e){return{method:"exec.approvals.get",params:{}}}async function Xh(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=Yh(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);Zh(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function Zh(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=ct(t.file??{}))}async function _c(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 dt(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function Ze(e){return e instanceof Error?e.message:String(e)}function qn(){return{name:"",skillContent:"",references:[]}}async function Xe(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=Ze(n)}finally{e.skillsLoading=!1}}}function Mc(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Pc(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 Xe(e),dt(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=Ze(i);e.skillsError=s,dt(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Ic(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 Xe(e),dt(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=Ze(n);e.skillsError=i,dt(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Lc(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 Xe(e),dt(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=Ze(s);e.skillsError=o,dt(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}async function Rc(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=Ze(n)}}function Dc(e){e.skillDetail=null,e.skillDetailTab=""}function Bc(e,t){e.skillDetailTab=t}async function Nc(e){if(e.skillAddModal=!0,e.skillAddForm=qn(),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 Oc(e){e.skillAddModal=!1,e.skillAddForm=qn(),e.skillAddFormSource="draft",e.skillEditTab="SKILL.md",e.skillDrafts=[]}function Fc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n}))},e.skillAddFormSource="draft"}async function Uc(e,t){e.skillAddForm={name:t.name,skillContent:t.skillContent,references:t.references.map(n=>({...n}))},e.skillAddFormSource="installed",await la(e)}async function la(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}),e.skillAddModal=!1,e.skillAddForm=qn(),e.skillAddFormSource="draft",e.skillDrafts=[],await Xe(e),dt(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=qn(),e.skillAddFormSource="draft",e.skillDrafts=[],dt(e,i,{kind:"success",message:"Draft saved"}))}catch(n){e.skillsError=Ze(n)}finally{e.skillsBusyKey=null}}}async function Wc(e,t){if(!(!e.client||!e.connected))try{await e.client.request("skills.deleteDraft",{name:t}),e.skillDrafts=e.skillDrafts.filter(n=>n.name!==t)}catch(n){e.skillsError=Ze(n)}}async function Kc(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("skills.read",{name:t});if(!n)return;e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i}))},e.skillAddFormSource="installed",e.skillAddModal=!0,e.skillDrafts=[]}catch(n){e.skillsError=Ze(n)}}function zc(e,t){const n=e.skillDetail;n&&(e.skillAddForm={name:n.name,skillContent:n.content,references:n.references.map(i=>({...i}))},e.skillAddFormSource="installed",e.skillEditTab=t&&t!=="SKILL.md"?t:"SKILL.md",e.skillDetail=null,e.skillDetailTab="",e.skillAddModal=!0,e.skillDrafts=[])}function qc(e,t,n){e.skillAddForm={...e.skillAddForm,references:e.skillAddForm.references.map(i=>i.name===t?{...i,content:n}:i)}}function Hc(e,t){e.skillEditTab=t}async function jc(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.delete",{name:t}),await Xe(e)}catch(n){e.skillsError=Ze(n)}finally{e.skillsBusyKey=null}}}const ef=Object.freeze(Object.defineProperty({__proto__:null,closeAddSkillModal:Oc,closeSkillDetail:Dc,deleteDraft:Wc,deleteSkill:jc,editDetailSkill:zc,editSkill:Kc,emptyAddForm:qn,importDraft:Fc,installDraft:Uc,installSkill:Lc,loadSkills:Xe,openAddSkillModal:Nc,saveNewSkill:la,saveSkillApiKey:Ic,setEditTab:Hc,setSkillDetailTab:Bc,updateFormReference:qc,updateSkillEdit:Mc,updateSkillEnabled:Pc,viewSkillDetail:Rc},Symbol.toStringTag,{value:"Module"})),Gc={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},Vc=new Map(Object.entries(Gc).map(([e,t])=>[t,e]));function rs(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function Hn(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 tf(e,t=""){const n=rs(t),i=Gc[e];return n?`${n}${i}`:i}function Qc(e,t=""){const n=rs(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=Hn(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":Vc.get(s)??null}function nf(e){let t=Hn(e);if(t.endsWith("/index.html")&&(t=Hn(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(Vc.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function sf(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ca(e){return e==="system"?sf():e}const ui=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,of=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,pi=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},af=({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=of();if(!!a.startViewTransition&&!r){let h=.5,d=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")h=ui(n.pointerClientX/window.innerWidth),d=ui(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const p=n.element.getBoundingClientRect();p.width>0&&p.height>0&&typeof window<"u"&&(h=ui((p.left+p.width/2)/window.innerWidth),d=ui((p.top+p.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${h*100}%`),o.style.setProperty("--theme-switch-y",`${d*100}%`),o.classList.add("theme-transition");try{const p=(c=a.startViewTransition)==null?void 0:c.call(a,()=>{t()});p!=null&&p.finished?p.finished.finally(()=>pi(o)):pi(o)}catch{pi(o),t()}return}t(),pi(o)},rf=2e3;async function Pn(e,t){if(!(!e.client||!e.connected)&&!(e.sessionLogsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.sessionLogsLoading=!0),e.sessionLogsError=null;try{const n={cursors:t!=null&&t.reset?void 0:e.sessionLogsCursors,limit:500};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(n.agents=e.workspaceAgentIds);const s=await e.client.request("sessions.transcript",n),o=Array.isArray(s.entries)?s.entries:[],a=!!(t!=null&&t.reset||Object.keys(e.sessionLogsCursors).length===0);e.sessionLogsEntries=a?o:[...e.sessionLogsEntries,...o].slice(-rf),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 Jc=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:Pn},Symbol.toStringTag,{value:"Module"}));async function Yc(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 lf(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function We(e){return e instanceof Error?e.message:String(e)}let hi=null;function on(e,t){hi&&clearTimeout(hi),e.filesMessage={kind:"success",text:t},hi=setTimeout(()=>{e.filesMessage=null,hi=null},3e3)}async function an(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=We(n)}finally{e.filesLoading=!1}}}}async function cf(e,t,n){e.filesSelectedPaths=new Set([t]),await Xc(e,t,n)}async function df(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 Xc(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function uf(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 Zc(e,o,t),i++}catch(a){s=We(a)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:on(e,`${i} file${i!==1?"s":""} downloaded`)}async function pf(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await mf(e,t,o,i)}async function Xc(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=We(i)}finally{e.filesPreviewLoading=!1}}}async function Zc(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:We(i)}}}async function hf(e,t,n,i){if(!e.client||!e.connected)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="";for(const a of n)try{const r=await a.arrayBuffer(),l=btoa(new Uint8Array(r).reduce((h,d)=>h+String.fromCharCode(d),"")),c={path:t,name:a.name,data:l};i&&(c.agentId=i),await e.client.request("files.upload",c),s++}catch(r){o=We(r)}e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:on(e,`${s} file${s!==1?"s":""} uploaded`),await an(e,i)}async function ff(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),on(e,`Created ${s}`),await an(e,i),e.filesExpandedDirs=new Set([...e.filesExpandedDirs,s]),e.filesCurrentDir=s}catch(o){e.filesMessage={kind:"error",text:We(o)}}}async function gf(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),on(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await an(e,n)}catch(i){e.filesMessage={kind:"error",text:We(i)}}}}async function mf(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),on(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await an(e,i)}catch(s){e.filesMessage={kind:"error",text:We(s)}}}}async function ls(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 yf(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;on(e,`Re-indexed: ${s} files, ${o} chunks`),await ls(e,t)}catch(n){e.filesMessage={kind:"error",text:We(n)}}finally{e.filesReindexBusy=!1}}}function vf(e,t){const n=new Set(e.filesExpandedDirs);n.has(t)?n.delete(t):n.add(t),e.filesExpandedDirs=n,e.filesCurrentDir=t}async function bf(e,t,n){if(!(!e.client||!e.connected)){if(!t.trim()){e.filesSearchResults=null;return}e.filesSearchLoading=!0,e.filesSearchResults=null;try{const i={query:t.trim(),maxResults:20};n&&(i.agentId=n);const s=await e.client.request("memory.search",i);e.filesSearchResults=(s==null?void 0:s.results)??[]}catch(i){e.filesMessage={kind:"error",text:We(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function wf(e){e.filesSearchQuery="",e.filesSearchResults=null}function kf(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{ra(e,{quiet:!0})},5e3))}function $f(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function da(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Vt(e,{quiet:!0})},2e3))}function ua(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function pa(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||Pn(e,{quiet:!0})},2e3))}function ha(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function fa(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&ea(e)},3e3))}function ga(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function xf(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{Yc(e)},3e4))}function Sf(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function Af(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{const t=e;t.filesPage&&ls(t,t.filesResolvedAgentId)},3e3))}function Cf(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function rt(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,wp(n),t.theme!==e.theme&&(e.theme=t.theme,cs(e,ca(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function ed(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&rt(e,{...e.settings,lastActiveSessionKey:n})}function Ef(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&&rt(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,rt(e,{...e.settings,sessionKey:l,lastActiveSessionKey:l}))}if(o!=null){const l=o.trim();l&&l!==e.settings.gatewayUrl&&rt(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 Tf(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?pa(e):da(e):(ua(e),ha(e)),t==="debug"?fa(e):ga(e),Ui(e),nd(e,t,!1)}function _f(e,t,n){af({nextTheme:t,applyTheme:()=>{e.theme=t,rt(e,{...e.settings,theme:t}),cs(e,ca(t))},context:n,currentTheme:e.theme})}async function Ui(e){if(e.tab==="overview"&&await id(e),e.tab==="channels"&&await Bf(e),e.tab==="instances"&&await _c(e),e.tab==="cron"&&await ma(e),e.tab==="skills"&&await Xe(e),e.tab==="nodes"&&(await ra(e),await aa(e),await Ue(e),await Xh(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await Wf(e),nn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await oc(e),await Ue(e)),e.tab==="debug"&&(await ea(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await le(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>Jc);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await Vt(e,{reset:!0});ic(e,!0)}}function Mf(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?rs(e):nf(window.location.pathname)}function Pf(e){e.theme=e.settings.theme??"system",cs(e,ca(e.theme))}function cs(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function If(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"&&cs(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Lf(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 Rf(e,t){if(typeof window>"u")return;const n=Qc(window.location.pathname,e.basePath)??"chat";td(e,n),nd(e,n,t)}function Df(e){var s;if(typeof window>"u")return;const t=Qc(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,rt(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),td(e,t)}function td(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?pa(e):da(e):(ua(e),ha(e)),t==="debug"?fa(e):ga(e),e.connected&&Ui(e)}function nd(e,t,n){if(typeof window>"u")return;const i=Hn(tf(t,e.basePath)),s=Hn(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 id(e){await Promise.all([ee(e,!1),_c(e),Yo(e),sn(e),ea(e)])}async function Bf(e){await Promise.all([ee(e,!0),oc(e),Ue(e)])}async function ma(e){await Promise.all([ee(e,!1),sn(e),jn(e)])}function sd(e){return e.chatSending||!!e.chatRunId}function Nf(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 od(e){e.connected&&(e.chatMessage="",await tc(e))}function Of(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:os(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],nn(e))}async function ad(e,t,n){var s,o;Xo(e);const i=await ec(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&&ed(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),nn(e),i&&!e.chatRunId&&rd(e),i}async function rd(e){if(!e.connected||sd(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await ad(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function Ff(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function Uf(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),o=e.chatAttachments??[],a=t==null?o:[],r=a.length>0;if(!(!s&&!r)){if(Nf(s)){await od(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[],$p(e.selectedWorkspace??"",e.sessionKey)),sd(e)){Of(e,s,a);return}await ad(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 Wf(e){var i;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,Fe);await Promise.all([Oe(t,{limit:n}),Yo(t),Ao(e)]),nn(e,!0)}const Kf=rd;function zf(e){var s,o,a;const t=jl(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(s=e.hello)==null?void 0:s.snapshot;return((a=(o=n==null?void 0:n.sessionDefaults)==null?void 0:o.defaultAgentId)==null?void 0:a.trim())||"main"}function qf(e,t){const n=rs(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Ao(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=zf(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=qf(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 L={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>`,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>`,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>`,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>`},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"><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>`,jf=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>`,Gf=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 _r=!1;function Vf(){_r||(_r=!0,document.addEventListener("click",e=>{const t=document.getElementById("nav-burger-toggle");if(!(t!=null&&t.checked))return;const n=t.closest(".setup-header");n!=null&&n.contains(e.target)||(t.checked=!1)}))}function Rt(e,t){var d;const n=(p,g)=>p===e?u`<span class="sp-page-nav-current">${p}</span>`:u`<a href=${g}>${p}</a>`,i=u`
21
21
  ${n("Setup","/setup")}
22
22
  ${n("Chat","/chat")}
23
23
  ${n("Admins","/admins")}
@@ -25,10 +25,10 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
25
25
  ${n("Files","/files")}
26
26
  ${n("Browser","/browser")}
27
27
  ${n("Advanced","/advanced")}
28
- `,o=t&&(t.isMaster!==!1||!t.hasPins)?Qf(t):w,a=t!=null&&t.hasPins&&t.onLogout?u`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${qf}</button>`:w,r=t!=null&&t.onRestartGateway?Vf(t.onRestartGateway):w,l=(t==null?void 0:t.auditCount)??0,c=l>0&&(t!=null&&t.onAuditClick)?u`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
- ${Hf}
28
+ `,o=t&&(t.isMaster!==!1||!t.hasPins)?Jf(t):w,a=t!=null&&t.hasPins&&t.onLogout?u`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${Hf}</button>`:w,r=t!=null&&t.onRestartGateway?Qf(t.onRestartGateway):w,l=(t==null?void 0:t.auditCount)??0,c=l>0&&(t!=null&&t.onAuditClick)?u`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
+ ${jf}
30
30
  <span class="nav-audit-badge">${l>99?"99+":l}</span>
31
- </button>`:w,h=()=>{const p=document.getElementById("nav-burger-toggle");p&&(p.checked=!1)};return Gf(),u`
31
+ </button>`:w,h=()=>{const p=document.getElementById("nav-burger-toggle");p&&(p.checked=!1)};return Vf(),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">
@@ -51,10 +51,10 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
51
51
  ${i}
52
52
  </nav>
53
53
  </div>
54
- `}function Vf(e){let t=!1;return u`
54
+ `}function Qf(e){let t=!1;return u`
55
55
  <span class="nav-restart-container" style="position: relative;">
56
56
  <button class="nav-restart-btn" @click=${o=>{const r=o.currentTarget.closest(".nav-restart-container");if(!r)return;const l=r.querySelector(".nav-restart-confirm");l&&(t=!t,l.style.display=t?"flex":"none")}} title="Restart gateway">
57
- ${jf}
57
+ ${Gf}
58
58
  </button>
59
59
  <div class="nav-restart-confirm" style="display: none;">
60
60
  <p>Restart the gateway?</p>
@@ -64,7 +64,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
64
64
  </div>
65
65
  </div>
66
66
  </span>
67
- `}function Qf(e){const{workspaces:t,selectedWorkspace:n,onWorkspaceSelect:i}=e;return u`
67
+ `}function Jf(e){const{workspaces:t,selectedWorkspace:n,onWorkspaceSelect:i}=e;return u`
68
68
  <select
69
69
  class="sp-workspace-selector"
70
70
  .value=${n??""}
@@ -78,7 +78,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
78
78
  <option disabled>───</option>
79
79
  <option value="__add__">+ Add Account</option>
80
80
  </select>
81
- `}function Jf(e){return e.connected?e.fullscreen&&e.active?u`
81
+ `}function Yf(e){return e.connected?e.fullscreen&&e.active?u`
82
82
  <div class="sp-fullscreen-overlay">
83
83
  <div class="sp-fullscreen-toolbar">
84
84
  <button
@@ -120,7 +120,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
120
120
  </div>
121
121
  `:u`
122
122
  <div class="setup-container">
123
- ${Lt("Browser")}
123
+ ${Rt("Browser")}
124
124
  <div class="setup-card sp-card-wide">
125
125
  <h1>Remote Browser</h1>
126
126
  <p style="margin-bottom: 16px;">Live view of the headless Chrome instance.</p>
@@ -210,14 +210,14 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
210
210
  <p>Connecting to gateway...</p>
211
211
  </div>
212
212
  </div>
213
- `}const Ui="application/x-taskmaster-file-path";let ft=null;function rd(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function ld(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function Yf(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(Ui);if(i){ld(i)!==t&&n.onMoveToDir(i,t);return}const s=(a=e.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&n.onUpload(t,r)}}function cd(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`
213
+ `}const Wi="application/x-taskmaster-file-path";let gt=null;function ld(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function cd(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function Xf(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(Wi);if(i){cd(i)!==t&&n.onMoveToDir(i,t);return}const s=(a=e.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&n.onUpload(t,r)}}function dd(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`
214
214
  <div
215
215
  class="sp-tree-item sp-tree-dir ${s?"expanded":""} ${a?"current":""}"
216
216
  style="padding-left: ${r}px;"
217
217
  @click=${()=>t.onToggleDir(e.path)}
218
218
  @dragover=${c=>{c.preventDefault(),c.stopPropagation(),c.dataTransfer&&(c.dataTransfer.dropEffect="move"),c.currentTarget.classList.add("sp-drop-target")}}
219
219
  @dragleave=${c=>{c.currentTarget.classList.remove("sp-drop-target")}}
220
- @drop=${c=>Yf(c,e.path,t)}
220
+ @drop=${c=>Xf(c,e.path,t)}
221
221
  >
222
222
  <span class="sp-tree-chevron">${s?"−":"+"}</span>
223
223
  <span class="sp-tree-icon">${L.folder}</span>
@@ -228,20 +228,20 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
228
228
  @click=${c=>{c.stopPropagation(),t.onDelete(e.path)}}
229
229
  >×</span>`:w}
230
230
  </div>
231
- ${s&&e.children?e.children.map(c=>cd(c,t,n+1)):w}
231
+ ${s&&e.children?e.children.map(c=>dd(c,t,n+1)):w}
232
232
  `:u`
233
233
  <div
234
234
  class="sp-tree-item sp-tree-file ${o?"selected":""}"
235
235
  style="padding-left: ${r}px;"
236
236
  draggable="true"
237
237
  @click=${c=>{c.metaKey||c.ctrlKey?t.onToggleSelectFile(e.path):t.onSelectFile(e.path)}}
238
- @dragstart=${c=>{c.dataTransfer&&(c.dataTransfer.effectAllowed="move",c.dataTransfer.setData(Ui,e.path),c.dataTransfer.setData("text/plain",e.name))}}
238
+ @dragstart=${c=>{c.dataTransfer&&(c.dataTransfer.effectAllowed="move",c.dataTransfer.setData(Wi,e.path),c.dataTransfer.setData("text/plain",e.name))}}
239
239
  >
240
240
  <span class="sp-tree-icon">${L.fileText}</span>
241
241
  <span class="sp-tree-name">${e.name}</span>
242
- <span class="sp-tree-size">${rd(e.size)}</span>
242
+ <span class="sp-tree-size">${ld(e.size)}</span>
243
243
  </div>
244
- `}function Xf(e){const t=e.selectedPaths.size;return t<2?w:u`
244
+ `}function Zf(e){const t=e.selectedPaths.size;return t<2?w:u`
245
245
  <div class="sp-bulk-actions">
246
246
  <span style="color: var(--tasker-muted-grey); font-size: 13px;">${t} files selected</span>
247
247
  <button
@@ -252,7 +252,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
252
252
  Download ${t} files
253
253
  </button>
254
254
  </div>
255
- `}function Zf(e){if(e.selectedPaths.size!==1||!e.selectedPath)return w;if(e.previewLoading)return u`
255
+ `}function eg(e){if(e.selectedPaths.size!==1||!e.selectedPath)return w;if(e.previewLoading)return u`
256
256
  <div class="sp-file-preview">
257
257
  <div class="setup-spinner" style="width: 32px; height: 32px; margin: 24px auto;"></div>
258
258
  </div>
@@ -262,21 +262,21 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
262
262
  <div>
263
263
  <strong>${t}</strong>
264
264
  <div class="sp-file-preview-meta">
265
- ${e.selectedPath}${e.previewSize!=null?` — ${rd(e.previewSize)}`:""}
265
+ ${e.selectedPath}${e.previewSize!=null?` — ${ld(e.previewSize)}`:""}
266
266
  </div>
267
267
  </div>
268
268
  <div class="sp-file-actions">
269
269
  <button class="setup-button secondary" style="padding: 8px 16px; font-size: 13px;" @click=${()=>e.onDownload(e.selectedPath)}>
270
270
  Download
271
271
  </button>
272
- <button class="setup-button danger" style="padding: 8px 16px; font-size: 13px;" @click=${()=>{e.pendingDeletePath===e.selectedPath?(ft&&clearTimeout(ft),ft=null,e.onDelete(e.selectedPath)):(e.onArmDelete(e.selectedPath),ft&&clearTimeout(ft),ft=setTimeout(()=>{e.onArmDelete(""),ft=null},3e3))}}>
272
+ <button class="setup-button danger" style="padding: 8px 16px; font-size: 13px;" @click=${()=>{e.pendingDeletePath===e.selectedPath?(gt&&clearTimeout(gt),gt=null,e.onDelete(e.selectedPath)):(e.onArmDelete(e.selectedPath),gt&&clearTimeout(gt),gt=setTimeout(()=>{e.onArmDelete(""),gt=null},3e3))}}>
273
273
  ${e.pendingDeletePath===e.selectedPath?"Confirm delete?":"Delete"}
274
274
  </button>
275
275
  </div>
276
276
  </div>
277
277
  ${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>`}
278
278
  </div>
279
- `}function eg(e){return u`
279
+ `}function tg(e){return u`
280
280
  <div class="sp-search-bar">
281
281
  <input
282
282
  type="text"
@@ -308,7 +308,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
308
308
  Clear
309
309
  </button>`:w}
310
310
  </div>
311
- `}function tg(e){return e.searchResults?e.searchResults.length===0?u`<div class="sp-search-results">
311
+ `}function ng(e){return e.searchResults?e.searchResults.length===0?u`<div class="sp-search-results">
312
312
  <div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No results found.</div>
313
313
  </div>`:u`
314
314
  <div class="sp-search-results">
@@ -328,9 +328,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
328
328
  </div>
329
329
  `)}
330
330
  </div>
331
- `:w}function ng(e){const t=e.currentDir;return e.connected?u`
331
+ `:w}function ig(e){const t=e.currentDir;return e.connected?u`
332
332
  <div class="setup-container">
333
- ${Lt("Files",e.wsProps)}
333
+ ${Rt("Files",e.wsProps)}
334
334
  <div class="setup-card sp-card-wide">
335
335
  <h1>Workspace Files</h1>
336
336
  <p style="margin-bottom: 16px;">Browse, upload, and manage files in your workspace. Drag files between folders to move them.</p>
@@ -392,18 +392,18 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
392
392
 
393
393
  ${e.uploadBusy?u`<div style="margin-top: 12px; color: var(--tasker-orange); font-weight: 600; font-size: 14px;">Uploading...</div>`:w}
394
394
 
395
- ${eg(e)}
395
+ ${tg(e)}
396
396
 
397
- ${e.searchResults!==null?tg(e):u`<div
397
+ ${e.searchResults!==null?ng(e):u`<div
398
398
  class="sp-file-tree"
399
- @dragover=${n=>{n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(Ui)?"move":"copy")}}
400
- @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(Ui);if(i){ld(i)!=="."&&e.onMoveToDir(i,".");return}const s=(a=n.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&e.onUpload(t,r)}}}
399
+ @dragover=${n=>{n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(Wi)?"move":"copy")}}
400
+ @drop=${n=>{var o,a;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(Wi);if(i){cd(i)!=="."&&e.onMoveToDir(i,".");return}const s=(a=n.dataTransfer)==null?void 0:a.files;if(s&&s.length>0){const r=Array.from(s).filter(l=>l.name.toLowerCase().endsWith(".md"));r.length>0&&e.onUpload(t,r)}}}
401
401
  >
402
- ${e.tree.length===0&&!e.loading?u`<div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No files found. Drop .md files here to upload.</div>`:e.tree.map(n=>cd(n,e,0))}
402
+ ${e.tree.length===0&&!e.loading?u`<div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No files found. Drop .md files here to upload.</div>`:e.tree.map(n=>dd(n,e,0))}
403
403
  </div>`}
404
404
 
405
- ${Xf(e)}
406
405
  ${Zf(e)}
406
+ ${eg(e)}
407
407
  </div>
408
408
  </div>
409
409
  `:u`
@@ -413,7 +413,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
413
413
  <p>Connecting to gateway...</p>
414
414
  </div>
415
415
  </div>
416
- `}const ma="taskmaster_uninstall_done";async function ig(e){var t,n;if(!(!e.client||!e.connected)&&!e.uninstallBusy){e.uninstallBusy=!0,e.uninstallError=null,(t=e.requestUpdate)==null||t.call(e),sg();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 Wi(){try{return localStorage.getItem(ma)==="1"}catch{return!1}}function ya(){try{localStorage.removeItem(ma)}catch{}}function sg(){try{localStorage.setItem(ma,"1")}catch{}}const _r=Object.freeze(Object.defineProperty({__proto__:null,checkUninstallDone:Wi,clearUninstallDone:ya,runUninstall:ig},Symbol.toStringTag,{value:"Module"}));function Q(e){return u`
416
+ `}const ya="taskmaster_uninstall_done";async function sg(e){var t,n;if(!(!e.client||!e.connected)&&!e.uninstallBusy){e.uninstallBusy=!0,e.uninstallError=null,(t=e.requestUpdate)==null||t.call(e),og();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 Ki(){try{return localStorage.getItem(ya)==="1"}catch{return!1}}function va(){try{localStorage.removeItem(ya)}catch{}}function og(){try{localStorage.setItem(ya,"1")}catch{}}const Mr=Object.freeze(Object.defineProperty({__proto__:null,checkUninstallDone:Ki,clearUninstallDone:va,runUninstall:sg},Symbol.toStringTag,{value:"Module"}));function Q(e){return u`
417
417
  <span
418
418
  class="setup-status-light"
419
419
  style="background: ${{good:"#22c55e",bad:"#ef4444",partial:"#eab308",unknown:"#6b7280"}[e]}"
@@ -426,7 +426,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
426
426
  >
427
427
  ${L.info}
428
428
  </button>
429
- `}function og(e){var s;if(!e.infoModalOpen)return w;let t="",n=[],i=w;switch(e.infoModalOpen){case"gateway":{const o=typeof window<"u"?window.location.host:"unknown";t="Gateway",n=[{label:"Status",value:e.gatewayHealthy===!1?"Stopped":"Running"},{label:"What",value:"The core service that powers Taskmaster — handles AI conversations, message routing, and all connected channels"},{label:"Address",value:o},{label:"Health",value:e.gatewayHealthMessage||"OK"}];break}case"claude":{const o=e.authExpiresIn;let a="N/A";if(o!=null&&o>0)if(o>60){const r=Math.floor(o/60),l=o%60;a=l>0?`${r}h ${l}m`:`${r}h`}else a=`${o}m`;t="Claude",n=[{label:"Status",value:e.authConnected?"Connected":"Disconnected"},{label:"What",value:"Connection to Claude, the AI that powers natural conversation and tool use"},{label:"How",value:"Authenticated via OAuth — tokens refresh automatically when they expire"},{label:"Token Expiry",value:a},...e.authMessage?[{label:"Message",value:e.authMessage}]:[]];break}case"license":{const o=e.licenseStoredKey?`…${e.licenseStoredKey.slice(-12)}`:"N/A";t="License",n=[{label:"Status",value:e.licenseValid?"Active":"Inactive"},{label:"What",value:"Your Taskmaster license key, tied to this specific device"},{label:"Key",value:o},{label:"Tier",value:e.licenseTier||"Standard"},{label:"Device ID",value:e.licenseDeviceId||"N/A"}];break}case"whatsapp":{const o=rn(e),a=o?va(o,e):null;t="WhatsApp",n=[{label:"Status",value:a!=null&&a.connected?"Connected":"Disconnected"},{label:"What",value:"WhatsApp integration — receive and respond to customer messages through WhatsApp"},{label:"How",value:"Links to your WhatsApp account by scanning a QR code, then routes messages to your AI assistant"},{label:"Account",value:(a==null?void 0:a.name)||(a==null?void 0:a.accountId)||"Default"},{label:"Phone",value:((s=a==null?void 0:a.self)==null?void 0:s.e164)||"Not paired"},{label:"Linked",value:a!=null&&a.linked?"Yes":"No"},...a!=null&&a.lastError?[{label:"Last Error",value:ba(a.lastError)}]:[]];break}case"imessage":{const{thisWsOwns:o}=wa(e);t="iMessage",n=[{label:"Status",value:o&&e.imessageConnected?"Connected":"Disconnected"},{label:"What",value:"iMessage integration — communicate with your AI assistant through Apple Messages"},{label:"How",value:"Uses the Mac's built-in Messages app; only one account can own the iMessage channel at a time"},{label:"Assigned To",value:e.imessageOwnerWorkspace??"Not assigned"},{label:"Mode",value:"Self-chat only"},...e.imessageLastError?[{label:"Last Error",value:e.imessageLastError}]:[]];break}case"update":{t="Software Update",n=[{label:"Status",value:e.updateAvailable===null?"Not checked":e.updateAvailable?"Update available":"Up to date"},{label:"What",value:"Checks for new versions of Taskmaster and lets you update from the control panel"},{label:"Current",value:e.currentVersion?`v${e.currentVersion}`:"Unknown"},{label:"Latest",value:e.latestVersion?`v${e.latestVersion}`:"Unknown"},...e.updateMessage?[{label:"Message",value:e.updateMessage}]:[]];break}case"remote-access":{const o=e.tailscaleStatus,a=o?o.installed?o.loggedIn?o.serveEnabled&&o.serveActive?"Active":o.serveEnabled&&!o.serveActive?"Enabled but not active":"Off":"Not connected":"Not installed":"Checking...";if(t="Remote Access",n=[{label:"Status",value:a},{label:"What",value:"Access this control panel from anywhere — your phone, another computer, or while away from home"},{label:"How",value:"Uses Tailscale to create a private, encrypted connection with a trusted HTTPS certificate (no browser warnings)"},{label:"Requires",value:"Tailscale installed on this device and on any device you want to access the control panel from, all logged into the same Tailscale account"},{label:"Internet Access",value:"Enable internet access (globe icon) to make Public Chat reachable from the web"},{label:"Cost",value:"Tailscale is free for personal use (up to 100 devices)"}],o!=null&&o.tailnetUrl){const r=o.tailnetUrl;i=u`
429
+ `}function ag(e){var s;if(!e.infoModalOpen)return w;let t="",n=[],i=w;switch(e.infoModalOpen){case"gateway":{const o=typeof window<"u"?window.location.host:"unknown";t="Gateway",n=[{label:"Status",value:e.gatewayHealthy===!1?"Stopped":"Running"},{label:"What",value:"The core service that powers Taskmaster — handles AI conversations, message routing, and all connected channels"},{label:"Address",value:o},{label:"Health",value:e.gatewayHealthMessage||"OK"}];break}case"claude":{const o=e.authExpiresIn;let a="N/A";if(o!=null&&o>0)if(o>60){const r=Math.floor(o/60),l=o%60;a=l>0?`${r}h ${l}m`:`${r}h`}else a=`${o}m`;t="Claude",n=[{label:"Status",value:e.authConnected?"Connected":"Disconnected"},{label:"What",value:"Connection to Claude, the AI that powers natural conversation and tool use"},{label:"How",value:"Authenticated via OAuth — tokens refresh automatically when they expire"},{label:"Token Expiry",value:a},...e.authMessage?[{label:"Message",value:e.authMessage}]:[]];break}case"license":{const o=e.licenseStoredKey?`…${e.licenseStoredKey.slice(-12)}`:"N/A";t="License",n=[{label:"Status",value:e.licenseValid?"Active":"Inactive"},{label:"What",value:"Your Taskmaster license key, tied to this specific device"},{label:"Key",value:o},{label:"Tier",value:e.licenseTier||"Standard"},{label:"Device ID",value:e.licenseDeviceId||"N/A"}];break}case"whatsapp":{const o=rn(e),a=o?ba(o,e):null;t="WhatsApp",n=[{label:"Status",value:a!=null&&a.connected?"Connected":"Disconnected"},{label:"What",value:"WhatsApp integration — receive and respond to customer messages through WhatsApp"},{label:"How",value:"Links to your WhatsApp account by scanning a QR code, then routes messages to your AI assistant"},{label:"Account",value:(a==null?void 0:a.name)||(a==null?void 0:a.accountId)||"Default"},{label:"Phone",value:((s=a==null?void 0:a.self)==null?void 0:s.e164)||"Not paired"},{label:"Linked",value:a!=null&&a.linked?"Yes":"No"},...a!=null&&a.lastError?[{label:"Last Error",value:wa(a.lastError)}]:[]];break}case"imessage":{const{thisWsOwns:o}=ka(e);t="iMessage",n=[{label:"Status",value:o&&e.imessageConnected?"Connected":"Disconnected"},{label:"What",value:"iMessage integration — communicate with your AI assistant through Apple Messages"},{label:"How",value:"Uses the Mac's built-in Messages app; only one account can own the iMessage channel at a time"},{label:"Assigned To",value:e.imessageOwnerWorkspace??"Not assigned"},{label:"Mode",value:"Self-chat only"},...e.imessageLastError?[{label:"Last Error",value:e.imessageLastError}]:[]];break}case"update":{t="Software Update",n=[{label:"Status",value:e.updateAvailable===null?"Not checked":e.updateAvailable?"Update available":"Up to date"},{label:"What",value:"Checks for new versions of Taskmaster and lets you update from the control panel"},{label:"Current",value:e.currentVersion?`v${e.currentVersion}`:"Unknown"},{label:"Latest",value:e.latestVersion?`v${e.latestVersion}`:"Unknown"},...e.updateMessage?[{label:"Message",value:e.updateMessage}]:[]];break}case"remote-access":{const o=e.tailscaleStatus,a=o?o.installed?o.loggedIn?o.serveEnabled&&o.serveActive?"Active":o.serveEnabled&&!o.serveActive?"Enabled but not active":"Off":"Not connected":"Not installed":"Checking...";if(t="Remote Access",n=[{label:"Status",value:a},{label:"What",value:"Access this control panel from anywhere — your phone, another computer, or while away from home"},{label:"How",value:"Uses Tailscale to create a private, encrypted connection with a trusted HTTPS certificate (no browser warnings)"},{label:"Requires",value:"Tailscale installed on this device and on any device you want to access the control panel from, all logged into the same Tailscale account"},{label:"Internet Access",value:"Enable internet access (globe icon) to make Public Chat reachable from the web"},{label:"Cost",value:"Tailscale is free for personal use (up to 100 devices)"}],o!=null&&o.tailnetUrl){const r=o.tailnetUrl;i=u`
430
430
  ${e.remoteAccessQrDataUrl?u`<div style="text-align: center; padding: 12px 0;">
431
431
  <img src=${e.remoteAccessQrDataUrl} alt="QR code for remote access URL" style="width: 180px; height: 180px; image-rendering: pixelated; border-radius: 8px;" />
432
432
  </div>`:w}
@@ -436,7 +436,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
436
436
  >${r}</a>
437
437
  <button class="setup-info-btn" title="Copy URL" @click=${async l=>{const c=l.currentTarget;try{await navigator.clipboard.writeText(r)}catch{const h=document.createElement("textarea");h.value=r,h.style.position="fixed",h.style.opacity="0",document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h)}c.classList.add("copied"),setTimeout(()=>c.classList.remove("copied"),1500)}}>${L.copy}</button>
438
438
  </div>
439
- `}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:kg[e.publicChatAuthMode]??"Open access"},{label:"Open access",value:"Anyone can chat without identifying themselves"},{label:"Phone OTP",value:"Visitors verify their phone number before chatting"},{label:"Visitor chooses",value:"Visitors can chat anonymously or verify their phone number"},{label:"SMS fallback",value:"If WhatsApp is not connected, verification codes are sent via SMS (uses Brevo same API key as email, plus SMS credits)"}],e.publicChatEnabled&&e.publicChatFullUrl){const o=e.publicChatFullUrl;i=u`
439
+ `}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:$g[e.publicChatAuthMode]??"Open access"},{label:"WhatsApp",value:"Sends verification codes via WhatsApp. Requires a connected WhatsApp account."},{label:"SMS",value:"Sends verification codes via text message. Uses Brevo — same API key as email. Requires prepaid SMS credits in your Brevo account."},{label:"Email",value:"Sends verification codes via email. Uses Brevo (free, 300 emails/day). Sender address is auto-detected from your verified sender in Brevo."},{label:"Provider",value:"SMS and email both use Brevo one API key, configured in API Keys above. WhatsApp uses your connected account."}],e.publicChatEnabled&&e.publicChatFullUrl){const o=e.publicChatFullUrl;i=u`
440
440
  ${e.publicChatQrDataUrl?u`<div style="text-align: center; padding: 12px 0;">
441
441
  <img src=${e.publicChatQrDataUrl} alt="QR code for public chat URL" style="width: 180px; height: 180px; image-rendering: pixelated; border-radius: 8px;" />
442
442
  </div>`:w}
@@ -477,7 +477,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
477
477
  </div>
478
478
  `})}
479
479
  </div>
480
- `}function Mr(e){const{licenseKey:t,licenseBusy:n,licenseValid:i,licenseMessage:s,licenseDeviceId:o,onLicenseKeyChange:a,onLicenseActivate:r}=e;return i===!0?u`
480
+ `}function Pr(e){const{licenseKey:t,licenseBusy:n,licenseValid:i,licenseMessage:s,licenseDeviceId:o,onLicenseKeyChange:a,onLicenseActivate:r}=e;return i===!0?u`
481
481
  <div class="setup-container">
482
482
  <div class="setup-card setup-success">
483
483
  ${Ee("license")}
@@ -546,7 +546,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
546
546
  </p>
547
547
  </div>
548
548
  </div>
549
- `}function ag(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:l,onAuthCodeChange:c,onSkipToWhatsApp:h}=e;return t===!0?u`
549
+ `}function rg(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:a,onStartAuth:r,onSubmitAuthCode:l,onAuthCodeChange:c,onSkipToWhatsApp:h}=e;return t===!0?u`
550
550
  <div class="setup-container">
551
551
  <div class="setup-card setup-success">
552
552
  ${Ee("auth")}
@@ -678,7 +678,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
678
678
  </p>
679
679
  </div>
680
680
  </div>
681
- `}function va(e,t){const n=new Map(t.whatsappAccounts.map(i=>[i.accountId,i]));return e.whatsappAccountId?n.get(e.whatsappAccountId)??null:e.isDefault&&t.whatsappAccounts.length===1?t.whatsappAccounts[0]??null:null}function rn(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 rg(e){const t=rn(e),n=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??Ye().name,i=e.whatsappBusy||e.gatewayHealthLoading;if(e.renamingWorkspace&&t){const s=()=>{const o=e.renameWorkspaceName.trim();o&&e.onWorkspaceRename(t.name,o)};return u`
681
+ `}function ba(e,t){const n=new Map(t.whatsappAccounts.map(i=>[i.accountId,i]));return e.whatsappAccountId?n.get(e.whatsappAccountId)??null:e.isDefault&&t.whatsappAccounts.length===1?t.whatsappAccounts[0]??null:null}function rn(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 lg(e){const t=rn(e),n=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??Ye().name,i=e.whatsappBusy||e.gatewayHealthLoading;if(e.renamingWorkspace&&t){const s=()=>{const o=e.renameWorkspaceName.trim();o&&e.onWorkspaceRename(t.name,o)};return u`
682
682
  <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 4px;">
683
683
  <input
684
684
  type="text"
@@ -720,7 +720,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
720
720
  ${L.rotateCw}
721
721
  </button>
722
722
  </div>
723
- `}function lg(e){return u`
723
+ `}function cg(e){return u`
724
724
  <div class="setup-status-item">
725
725
  ${Q(e.gatewayHealthy===!1?"bad":"good")}
726
726
  <div class="setup-status-info">
@@ -737,7 +737,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
737
737
  ${L.rotateCw}
738
738
  </button>
739
739
  </div>
740
- `}function cg(e){const t=e.authConnected===!0;return u`
740
+ `}function dg(e){const t=e.authConnected===!0;return u`
741
741
  <div class="setup-status-item">
742
742
  ${Q(t?"good":"bad")}
743
743
  <div class="setup-status-info">
@@ -766,7 +766,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
766
766
  </button>
767
767
  `}
768
768
  </div>
769
- `}function dg(e){return u`
769
+ `}function ug(e){return u`
770
770
  <div class="setup-status-item" style="flex-wrap: wrap;">
771
771
  ${Q("good")}
772
772
  <div class="setup-status-info">
@@ -806,7 +806,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
806
806
  </div>
807
807
  `:w}
808
808
  </div>
809
- `}function ba(e){var t,n;try{const i=JSON.parse(e),s=(i==null?void 0:i.error)??i,o=((n=(t=s==null?void 0:s.output)==null?void 0:t.payload)==null?void 0:n.message)??(s==null?void 0:s.message)??(i==null?void 0:i.message);if(o&&typeof o=="string")return o}catch{}return e.length>80?e.slice(0,77)+"…":e}function ug(e){var d;const t=rn(e);if(!t)return w;const n=va(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?ba(n.lastError):"Not connected":"Not paired",l=!(n!=null&&n.provider)||(n==null?void 0:n.provider)==="baileys",c=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(d=e.whatsappAccounts[0])==null?void 0:d.accountId:void 0),h=c!=null&&e.whatsappActiveQrAccountId===c;return u`
809
+ `}function wa(e){var t,n;try{const i=JSON.parse(e),s=(i==null?void 0:i.error)??i,o=((n=(t=s==null?void 0:s.output)==null?void 0:t.payload)==null?void 0:n.message)??(s==null?void 0:s.message)??(i==null?void 0:i.message);if(o&&typeof o=="string")return o}catch{}return e.length>80?e.slice(0,77)+"…":e}function pg(e){var d;const t=rn(e);if(!t)return w;const n=ba(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?wa(n.lastError):"Not connected":"Not paired",l=!(n!=null&&n.provider)||(n==null?void 0:n.provider)==="baileys",c=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(d=e.whatsappAccounts[0])==null?void 0:d.accountId:void 0),h=c!=null&&e.whatsappActiveQrAccountId===c;return u`
810
810
  <div class="setup-status-item" style="flex-wrap: wrap;">
811
811
  ${Q(a)}
812
812
  <div class="setup-status-info">
@@ -837,16 +837,16 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
837
837
  </div>
838
838
  `:w}
839
839
  </div>
840
- `}const pg=[{id:"claude-opus-4-6",shortName:"Opus"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku"}],hg="anthropic/claude-sonnet-4-5-20250929",fg=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function gg(e){var x,T;if(!e.whatsappSettingsOpen)return w;const t=rn(e);if(!t)return w;const n=va(t,e);if(!n)return w;const i=n.running&&n.connected,s=!n.provider||n.provider==="baileys",o=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(x=e.whatsappAccounts[0])==null?void 0:x.accountId:void 0),a=()=>e.onWhatsAppSettingsClose(),r=e.whatsappModelCatalog??[],l=new Set(r.filter(f=>f.provider==="anthropic").map(f=>f.id)),c=pg.filter(f=>l.has(f.id)),h=e.whatsappModel??hg,d=e.whatsappThinkingLevel??"off",p="display: flex; justify-content: space-between; font-size: 13px;",v="color: var(--tasker-text-grey);",S="color: var(--tasker-white); text-align: right;";return u`
840
+ `}const hg=[{id:"claude-opus-4-6",shortName:"Opus"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku"}],fg="anthropic/claude-sonnet-4-5-20250929",gg=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function mg(e){var S,T;if(!e.whatsappSettingsOpen)return w;const t=rn(e);if(!t)return w;const n=ba(t,e);if(!n)return w;const i=n.running&&n.connected,s=!n.provider||n.provider==="baileys",o=t.whatsappAccountId??(t.isDefault&&e.whatsappAccounts.length===1?(S=e.whatsappAccounts[0])==null?void 0:S.accountId:void 0),a=()=>e.onWhatsAppSettingsClose(),r=e.whatsappModelCatalog??[],l=new Set(r.filter(f=>f.provider==="anthropic").map(f=>f.id)),c=hg.filter(f=>l.has(f.id)),h=e.whatsappModel??fg,d=e.whatsappThinkingLevel??"off",p="display: flex; justify-content: space-between; font-size: 13px;",g="color: var(--tasker-text-grey);",x="color: var(--tasker-white); text-align: right;";return u`
841
841
  <div class="setup-info-overlay" @click=${f=>{f.target.classList.contains("setup-info-overlay")&&a()}}>
842
842
  <div class="setup-info-card" style="max-width: 360px;">
843
843
  <h3>WhatsApp</h3>
844
844
  <div style="display: flex; flex-direction: column; gap: 8px; margin-top: 12px;">
845
- <div style="${p}"><span style="${v}">Account</span><span style="${S}">${n.name||n.accountId||"Default"}</span></div>
846
- <div style="${p}"><span style="${v}">Phone</span><span style="${S}">${((T=n.self)==null?void 0:T.e164)||"Not paired"}</span></div>
847
- <div style="${p}"><span style="${v}">Connected</span><span style="${S}">${i?"Yes":"No"}</span></div>
848
- <div style="${p}"><span style="${v}">Linked</span><span style="${S}">${n.linked?"Yes":"No"}</span></div>
849
- ${n.lastError?u`<div style="${p}"><span style="${v}">Error</span><span style="${S}; color: #ef4444;">${ba(n.lastError)}</span></div>`:w}
845
+ <div style="${p}"><span style="${g}">Account</span><span style="${x}">${n.name||n.accountId||"Default"}</span></div>
846
+ <div style="${p}"><span style="${g}">Phone</span><span style="${x}">${((T=n.self)==null?void 0:T.e164)||"Not paired"}</span></div>
847
+ <div style="${p}"><span style="${g}">Connected</span><span style="${x}">${i?"Yes":"No"}</span></div>
848
+ <div style="${p}"><span style="${g}">Linked</span><span style="${x}">${n.linked?"Yes":"No"}</span></div>
849
+ ${n.lastError?u`<div style="${p}"><span style="${g}">Error</span><span style="${x}; color: #ef4444;">${wa(n.lastError)}</span></div>`:w}
850
850
  </div>
851
851
  ${s&&o?u`
852
852
  <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 16px 0 12px;"></div>
@@ -946,7 +946,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
946
946
  .value=${d}
947
947
  @change=${f=>{e.onWhatsAppThinkingChange(f.target.value)}}
948
948
  >
949
- ${fg.map(f=>u`
949
+ ${gg.map(f=>u`
950
950
  <option value=${f.value} ?selected=${d===f.value}>
951
951
  ${f.label}
952
952
  </option>
@@ -964,7 +964,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
964
964
  </button>
965
965
  </div>
966
966
  </div>
967
- `}function wa(e){const t=rn(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 mg(e){const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=wa(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`
967
+ `}function ka(e){const t=rn(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 yg(e){const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=ka(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`
968
968
  <div class="setup-status-item" style="flex-wrap: wrap;">
969
969
  ${Q(s)}
970
970
  <div class="setup-status-info">
@@ -982,7 +982,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
982
982
  </button>
983
983
  ${w}
984
984
  </div>
985
- `}function yg(e){if(!e.imessageEnableConfirm)return w;const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=wa(e),s=()=>{e.onIMessageEnableCancel()};return n?u`
985
+ `}function vg(e){if(!e.imessageEnableConfirm)return w;const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=ka(e),s=()=>{e.onIMessageEnableCancel()};return n?u`
986
986
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&s()}}>
987
987
  <div class="setup-info-card" style="text-align: center;">
988
988
  <h3>iMessage</h3>
@@ -1058,7 +1058,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1058
1058
  </button>
1059
1059
  </div>
1060
1060
  </div>
1061
- `}function vg(e){if(!e.isMaster)return w;const n=e.apiKeyProviders.filter(i=>i.hasKey).length;return u`
1061
+ `}function bg(e){if(!e.isMaster)return w;const n=e.apiKeyProviders.filter(i=>i.hasKey).length;return u`
1062
1062
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1063
1063
  <div class="setup-status-item">
1064
1064
  ${Q(n>0?"good":"bad")}
@@ -1073,17 +1073,17 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1073
1073
  >Manage</button>
1074
1074
  </div>
1075
1075
  </div>
1076
- ${bg(e)}
1077
- `}function bg(e){if(!e.apiKeyModalOpen)return w;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,h)=>{const d=h==null?void 0:h.closest(".setup-apikey-input"),p=d==null?void 0:d.querySelector("input"),v=p==null?void 0:p.value.trim();!v||v===n[c]||e.onApiKeySave(c,v)},s=c=>{const h=c.currentTarget,d=h.closest(".setup-apikey-input"),p=d==null?void 0:d.querySelector("input");if(!p)return;const v=p.type==="text";p.type=v?"password":"text",h.classList.toggle("active",!v)},o=(c,h)=>{const d=h.target,p=d.closest(".setup-apikey-input"),v=d.value.trim(),S=v.length>0&&v!==n[c],x=p==null?void 0:p.querySelector(".setup-apikey-save");x&&(x.style.display=S?"":"none");const T=p==null?void 0:p.querySelector(".setup-apikey-eye");T&&(T.style.display=v.length>0?"":"none")},a=t.filter(c=>c.primary),r=t.filter(c=>!c.primary),l=c=>{const h=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,d=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,p=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`,v=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} disabled`,S=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} enabled`;return u`
1076
+ ${wg(e)}
1077
+ `}function wg(e){if(!e.apiKeyModalOpen)return w;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,h)=>{const d=h==null?void 0:h.closest(".setup-apikey-input"),p=d==null?void 0:d.querySelector("input"),g=p==null?void 0:p.value.trim();!g||g===n[c]||e.onApiKeySave(c,g)},s=c=>{const h=c.currentTarget,d=h.closest(".setup-apikey-input"),p=d==null?void 0:d.querySelector("input");if(!p)return;const g=p.type==="text";p.type=g?"password":"text",h.classList.toggle("active",!g)},o=(c,h)=>{const d=h.target,p=d.closest(".setup-apikey-input"),g=d.value.trim(),x=g.length>0&&g!==n[c],S=p==null?void 0:p.querySelector(".setup-apikey-save");S&&(S.style.display=x?"":"none");const T=p==null?void 0:p.querySelector(".setup-apikey-eye");T&&(T.style.display=g.length>0?"":"none")},a=t.filter(c=>c.primary),r=t.filter(c=>!c.primary),l=c=>{const h=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,d=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,p=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`,g=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} disabled`,x=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} enabled`;return u`
1078
1078
  <div class="setup-apikey-row ${c.disabled?"disabled":""}">
1079
1079
  <div class="setup-apikey-info">
1080
1080
  <strong>${c.name}</strong>
1081
1081
  <span class="setup-apikey-category">${c.category}</span>
1082
1082
  ${d?u`<span class="setup-apikey-badge saved">Saved</span>`:w}
1083
1083
  ${p?u`<span class="setup-apikey-badge removed">Removed</span>`:w}
1084
- ${v?u`<span class="setup-apikey-badge removed">Disabled</span>`:w}
1085
- ${S?u`<span class="setup-apikey-badge saved">Enabled</span>`:w}
1086
- ${c.disabled&&!S?u`<span class="setup-apikey-badge apikey-disabled">Off</span>`:w}
1084
+ ${g?u`<span class="setup-apikey-badge removed">Disabled</span>`:w}
1085
+ ${x?u`<span class="setup-apikey-badge saved">Enabled</span>`:w}
1086
+ ${c.disabled&&!x?u`<span class="setup-apikey-badge apikey-disabled">Off</span>`:w}
1087
1087
  </div>
1088
1088
  <div class="setup-apikey-input">
1089
1089
  <input
@@ -1091,8 +1091,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1091
1091
  .value=${c.key??""}
1092
1092
  placeholder="Enter key"
1093
1093
  ?disabled=${e.apiKeyBusy||c.disabled}
1094
- @input=${x=>o(c.id,x)}
1095
- @keydown=${x=>{x.key==="Enter"&&i(c.id,x.target)}}
1094
+ @input=${S=>o(c.id,S)}
1095
+ @keydown=${S=>{S.key==="Enter"&&i(c.id,S.target)}}
1096
1096
  />
1097
1097
  <button
1098
1098
  class="setup-apikey-icon-btn setup-apikey-eye"
@@ -1104,7 +1104,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1104
1104
  class="setup-apikey-save setup-button"
1105
1105
  style="display: none;"
1106
1106
  ?disabled=${e.apiKeyBusy}
1107
- @click=${x=>i(c.id,x.currentTarget)}
1107
+ @click=${S=>i(c.id,S.currentTarget)}
1108
1108
  >Save</button>`}
1109
1109
  ${c.hasKey&&!h?u`
1110
1110
  <button
@@ -1138,7 +1138,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1138
1138
  </div>
1139
1139
  </div>
1140
1140
  </div>
1141
- `}function wg(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`
1141
+ `}function kg(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`
1142
1142
  <div class="setup-status-item">
1143
1143
  ${Q(t)}
1144
1144
  <div class="setup-status-info">
@@ -1166,7 +1166,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1166
1166
  </button>
1167
1167
  `}
1168
1168
  </div>
1169
- `}const kg={anonymous:"Open access",verified:"Phone OTP",choice:"Visitor chooses"};function $g(e){const t=e.publicChatEnabled;return u`
1169
+ `}const $g={anonymous:"Open access",verified:"Phone OTP",choice:"Visitor chooses"};function xg(e){const t=e.publicChatEnabled;return u`
1170
1170
  <div class="setup-status-item">
1171
1171
  ${Q(t?"good":"unknown")}
1172
1172
  <div class="setup-status-info">
@@ -1186,8 +1186,8 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1186
1186
  @click=${e.onPublicChatToggle}
1187
1187
  >${t?L.powerOff:L.power}</button>
1188
1188
  </div>
1189
- `}function xg(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:["phone"],o=s.includes("phone"),a=s.includes("email");return u`
1190
- <div class="setup-info-overlay" @click=${r=>{r.target.classList.contains("setup-info-overlay")&&t()}}>
1189
+ `}function Sg(e){var c,h;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=!!((c=e.whatsappChannelStatus)!=null&&c.running&&((h=e.whatsappChannelStatus)!=null&&h.connected));return u`
1190
+ <div class="setup-info-overlay" @click=${d=>{d.target.classList.contains("setup-info-overlay")&&t()}}>
1191
1191
  <div class="setup-info-card" style="max-width: 380px; max-height: 80vh; overflow-y: auto;">
1192
1192
  <h3 style="margin: 0 0 12px; display: flex; align-items: center; justify-content: space-between;">
1193
1193
  Public Chat
@@ -1206,7 +1206,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1206
1206
  class="setup-select-sm"
1207
1207
  style="width: 100%;"
1208
1208
  ?disabled=${e.publicChatBusy}
1209
- @change=${r=>{const l=r.target.value;e.onPublicChatAuthModeChange(l)}}
1209
+ @change=${d=>{const p=d.target.value;e.onPublicChatAuthModeChange(p)}}
1210
1210
  >
1211
1211
  <option value="anonymous" ?selected=${e.publicChatAuthMode==="anonymous"}>Open access</option>
1212
1212
  <option value="verified" ?selected=${e.publicChatAuthMode==="verified"}>Identity verification</option>
@@ -1241,7 +1241,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1241
1241
  style="width: 100%; margin-top: 8px; font-size: 12px; padding: 8px; border-radius: 6px; border: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2); color: var(--tasker-white); resize: vertical; min-height: 60px; font-family: inherit; box-sizing: border-box;"
1242
1242
  ?disabled=${e.publicChatGreetingBusy}
1243
1243
  .value=${e.publicChatGreetingBusy?"Generating...":e.publicChatGreeting}
1244
- @blur=${r=>{const l=r.target.value.trim();l&&l!==e.publicChatGreeting&&e.onPublicChatGreetingSave(l)}}
1244
+ @blur=${d=>{const p=d.target.value.trim();p&&p!==e.publicChatGreeting&&e.onPublicChatGreetingSave(p)}}
1245
1245
  ></textarea>
1246
1246
  `:u`
1247
1247
  <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7; margin-top: 4px;">
@@ -1256,53 +1256,51 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1256
1256
  <!-- Verify methods -->
1257
1257
  <div>
1258
1258
  <div style="font-size: 13px; color: var(--tasker-white); margin-bottom: 6px;">Verification methods</div>
1259
- <div style="display: flex; gap: 12px;">
1260
- <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
1259
+ <div style="display: flex; flex-direction: column; gap: 8px; text-align: left;">
1260
+ <label style="display: flex; align-items: flex-start; gap: 6px; ${l?"cursor: pointer;":"cursor: not-allowed; opacity: 0.5;"}">
1261
1261
  <input
1262
1262
  type="checkbox"
1263
- .checked=${o}
1264
- ?disabled=${e.publicChatEmailBusy||!a&&o}
1265
- @change=${r=>{const c=r.target.checked?[...s.filter(h=>h!=="phone"),"phone"]:s.filter(h=>h!=="phone");c.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,c)}}
1266
- style="accent-color: #22c55e;"
1263
+ .checked=${o&&l}
1264
+ ?disabled=${!l||e.publicChatEmailBusy||!a&&!r&&o}
1265
+ @change=${d=>{const g=d.target.checked?[...s.filter(x=>x!=="whatsapp"),"whatsapp"]:s.filter(x=>x!=="whatsapp");g.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,g)}}
1266
+ style="accent-color: #22c55e; margin-top: 2px;"
1267
1267
  />
1268
- <span style="font-size: 12px; color: var(--tasker-white);">Phone</span>
1268
+ <div>
1269
+ <span style="font-size: 12px; color: var(--tasker-white);">WhatsApp</span>
1270
+ <div style="font-size: 11px; color: var(--tasker-text-grey); opacity: 0.7;">
1271
+ ${l?"Phone OTP via WhatsApp":"No WhatsApp account connected on this account"}
1272
+ </div>
1273
+ </div>
1269
1274
  </label>
1270
- <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
1275
+ <label style="display: flex; align-items: flex-start; gap: 6px; cursor: pointer;">
1271
1276
  <input
1272
1277
  type="checkbox"
1273
1278
  .checked=${a}
1274
- ?disabled=${e.publicChatEmailBusy||!o&&a}
1275
- @change=${r=>{const c=r.target.checked?[...s.filter(h=>h!=="email"),"email"]:s.filter(h=>h!=="email");c.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,c)}}
1276
- style="accent-color: #22c55e;"
1279
+ ?disabled=${e.publicChatEmailBusy||!o&&!r&&a}
1280
+ @change=${d=>{const g=d.target.checked?[...s.filter(x=>x!=="sms"),"sms"]:s.filter(x=>x!=="sms");g.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,g)}}
1281
+ style="accent-color: #22c55e; margin-top: 2px;"
1277
1282
  />
1278
- <span style="font-size: 12px; color: var(--tasker-white);">Email</span>
1283
+ <div>
1284
+ <span style="font-size: 12px; color: var(--tasker-white);">SMS</span>
1285
+ <div style="font-size: 11px; color: var(--tasker-text-grey); opacity: 0.7;">Brevo API key + SMS credits</div>
1286
+ </div>
1287
+ </label>
1288
+ <label style="display: flex; align-items: flex-start; gap: 6px; cursor: pointer;">
1289
+ <input
1290
+ type="checkbox"
1291
+ .checked=${r}
1292
+ ?disabled=${e.publicChatEmailBusy||!o&&!a&&r}
1293
+ @change=${d=>{const g=d.target.checked?[...s.filter(x=>x!=="email"),"email"]:s.filter(x=>x!=="email");g.length>0&&e.onPublicChatEmailSave(e.publicChatEmailFrom,g)}}
1294
+ style="accent-color: #22c55e; margin-top: 2px;"
1295
+ />
1296
+ <div>
1297
+ <span style="font-size: 12px; color: var(--tasker-white);">Email</span>
1298
+ <div style="font-size: 11px; color: var(--tasker-text-grey); opacity: 0.7;">Brevo API key</div>
1299
+ </div>
1279
1300
  </label>
1280
1301
  </div>
1281
1302
  </div>
1282
1303
 
1283
- ${o?u`
1284
- <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 4px 0;"></div>
1285
-
1286
- <!-- SMS fallback (Brevo) -->
1287
- <div>
1288
- <div style="font-size: 13px; color: var(--tasker-white); margin-bottom: 4px;">SMS fallback (Brevo)</div>
1289
- <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7;">
1290
- Sends verification codes via SMS when WhatsApp is unavailable. Uses your Brevo API key (same as email). Purchase SMS credits in Brevo to enable.
1291
- </div>
1292
- </div>
1293
- `:w}
1294
-
1295
- ${a?u`
1296
- <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 4px 0;"></div>
1297
-
1298
- <!-- Email verification (Brevo) -->
1299
- <div>
1300
- <div style="font-size: 13px; color: var(--tasker-white); margin-bottom: 4px;">Email verification (Brevo)</div>
1301
- <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7;">
1302
- Sends verification codes via email. Add your Brevo API key in API Keys above. The sender address is your verified sender in Brevo.
1303
- </div>
1304
- </div>
1305
- `:w}
1306
1304
  `:w}
1307
1305
 
1308
1306
  <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 4px 0;"></div>
@@ -1316,7 +1314,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1316
1314
  </div>
1317
1315
  </div>
1318
1316
  </div>
1319
- `}function Sg(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>
1317
+ `}function Ag(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>
1320
1318
  <script>
1321
1319
  Taskmaster.init({
1322
1320
  server: "${i}",
@@ -1346,7 +1344,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1346
1344
  </div>
1347
1345
  </div>
1348
1346
  </div>
1349
- `}function Ag(e){const t=!!(e.brandAccentColor||e.brandBackgroundColor||e.brandHasLogo),n=t?"good":"unknown",i=e.brandingBusy;return u`
1347
+ `}function Cg(e){const t=!!(e.brandAccentColor||e.brandBackgroundColor||e.brandHasLogo),n=t?"good":"unknown",i=e.brandingBusy;return u`
1350
1348
  <div class="setup-status-item">
1351
1349
  ${Q(n)}
1352
1350
  <div class="setup-status-info">
@@ -1360,7 +1358,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1360
1358
  @click=${e.onBrandingToggle}
1361
1359
  >${i?"...":"Edit"}</button>
1362
1360
  </div>
1363
- `}function Cg(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`
1361
+ `}function Eg(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`
1364
1362
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onBrandingToggle()}}>
1365
1363
  <div class="setup-info-card" style="max-width: 400px; position: relative;">
1366
1364
  <h3 style="margin-right: 24px;">Branding</h3>
@@ -1441,7 +1439,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1441
1439
 
1442
1440
  </div>
1443
1441
  </div>
1444
- `}function Eg(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`
1442
+ `}function Tg(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`
1445
1443
  <div class="setup-info-overlay" @click=${r=>{r.target.classList.contains("setup-info-overlay")&&e.onTailscaleErrorDismiss()}}>
1446
1444
  <div class="setup-info-card" style="max-width: 380px; text-align: center;">
1447
1445
  <h3>Remote Access</h3>
@@ -1508,7 +1506,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1508
1506
  <p style="font-size: 14px; color: var(--tasker-text-grey); margin: 12px 0 0;">${a}</p>
1509
1507
  </div>
1510
1508
  </div>
1511
- `}function Tg(e){if(!e.isMaster)return w;const t=e.tailscaleStatus,n=e.tailscaleBusy,i=e.tailscaleAuthUrl;if(!t)return u`
1509
+ `}function _g(e){if(!e.isMaster)return w;const t=e.tailscaleStatus,n=e.tailscaleBusy,i=e.tailscaleAuthUrl;if(!t)return u`
1512
1510
  <div class="setup-status-item">
1513
1511
  ${Q("unknown")}
1514
1512
  <div class="setup-status-info">
@@ -1619,7 +1617,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1619
1617
  >${L.powerOff}</button>
1620
1618
  ${o}
1621
1619
  </div>
1622
- `}function Ao(e){const t=e>=70?4:e>=50?3:e>=30?2:1;return u`
1620
+ `}function Co(e){const t=e>=70?4:e>=50?3:e>=30?2:1;return u`
1623
1621
  <span style="display: inline-flex; align-items: flex-end; gap: 2px; height: 14px; vertical-align: middle;">
1624
1622
  ${[4,7,10,14].map((i,s)=>u`<span style="
1625
1623
  width: 3px;
@@ -1628,7 +1626,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1628
1626
  background: ${s<t?"var(--tasker-accent, #00e5ff)":"rgba(255,255,255,0.15)"};
1629
1627
  "></span>`)}
1630
1628
  </span>
1631
- `}function _g(e){if(e.serverPlatform!=="linux")return w;const t=e.wifiStatus,n=e.wifiBusy;if(!t)return u`
1629
+ `}function Mg(e){if(e.serverPlatform!=="linux")return w;const t=e.wifiStatus,n=e.wifiBusy;if(!t)return u`
1632
1630
  <div class="setup-status-item">
1633
1631
  ${Q("unknown")}
1634
1632
  <div class="setup-status-info">
@@ -1644,7 +1642,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1644
1642
  <span>NetworkManager not available</span>
1645
1643
  </div>
1646
1644
  </div>
1647
- `;const i=!!t.savedSsid&&!t.connected,s=t.connected?"good":"partial",o=t.connected?u`${t.ssid} ${t.signal!=null?u`<span style="margin-left: 4px;">${Ao(t.signal)}</span>`:w}`:i?u`${t.savedSsid} <span style="opacity: 0.4;">\u2014 reconnecting\u2026</span>`:"Not connected";return u`
1645
+ `;const i=!!t.savedSsid&&!t.connected,s=t.connected?"good":"partial",o=t.connected?u`${t.ssid} ${t.signal!=null?u`<span style="margin-left: 4px;">${Co(t.signal)}</span>`:w}`:i?u`${t.savedSsid} <span style="opacity: 0.4;">\u2014 reconnecting\u2026</span>`:"Not connected";return u`
1648
1646
  <div class="setup-status-item">
1649
1647
  ${Q(s)}
1650
1648
  <div class="setup-status-info">
@@ -1658,7 +1656,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1658
1656
  @click=${e.onWifiModalToggle}
1659
1657
  >${n?"...":"Edit"}</button>
1660
1658
  </div>
1661
- `}function Mg(e){if(!e.wifiModalOpen)return w;const t=e.wifiStatus,n=e.wifiBusy,i=e.wifiNetworks,s=e.wifiSelectedSsid;return u`
1659
+ `}function Pg(e){if(!e.wifiModalOpen)return w;const t=e.wifiStatus,n=e.wifiBusy,i=e.wifiNetworks,s=e.wifiSelectedSsid;return u`
1662
1660
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onWifiModalToggle()}}>
1663
1661
  <div class="setup-info-card" style="max-width: 420px; position: relative;">
1664
1662
  <h3 style="margin-right: 24px;">WiFi</h3>
@@ -1668,7 +1666,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1668
1666
  ${t!=null&&t.connected?u`
1669
1667
  <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 12px;">
1670
1668
  <span style="color: #22c55e;">${L.wifi}</span>
1671
- <span style="font-size: 13px;">${t.ssid}${t.signal!=null?u` ${Ao(t.signal)}`:w}${t.ip?u` <span style="opacity: 0.5;">(${t.ip})</span>`:w}</span>
1669
+ <span style="font-size: 13px;">${t.ssid}${t.signal!=null?u` ${Co(t.signal)}`:w}${t.ip?u` <span style="opacity: 0.5;">(${t.ip})</span>`:w}</span>
1672
1670
  <button
1673
1671
  class="setup-link-btn"
1674
1672
  style="margin-left: auto; font-size: 12px;"
@@ -1726,7 +1724,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1726
1724
  </span>
1727
1725
  <span style="display: flex; align-items: center; gap: 8px;">
1728
1726
  ${o.security!=="Open"?u`<span style="opacity: 0.4; font-size: 11px;" title="${o.security}">\uD83D\uDD12</span>`:w}
1729
- <span title="Signal: ${o.signal}%">${Ao(o.signal)}</span>
1727
+ <span title="Signal: ${o.signal}%">${Co(o.signal)}</span>
1730
1728
  </span>
1731
1729
  </button>
1732
1730
  `})}
@@ -1770,7 +1768,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1770
1768
  `:w}
1771
1769
  </div>
1772
1770
  </div>
1773
- `}function Pg(e){return e.isMaster?e.networkPort==null?u`
1771
+ `}function Ig(e){return e.isMaster?e.networkPort==null?u`
1774
1772
  <div class="setup-status-item">
1775
1773
  ${Q("unknown")}
1776
1774
  <div class="setup-status-info">
@@ -1791,7 +1789,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1791
1789
  @click=${e.onNetworkModalToggle}
1792
1790
  >Edit</button>
1793
1791
  </div>
1794
- `:w}function Ig(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`
1792
+ `:w}function Lg(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`
1795
1793
  <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&e.onNetworkModalToggle()}}>
1796
1794
  <div class="setup-info-card" style="max-width: 400px; position: relative;">
1797
1795
  <h3 style="margin-right: 24px;">Network</h3>
@@ -1859,7 +1857,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1859
1857
  </div>
1860
1858
  </div>
1861
1859
  </div>
1862
- `}function Lg(e){var i,s,o;const t=e.updateRunning,n=e.updateLastResult;if(!t&&!n)return w;if(t)return u`
1860
+ `}function Rg(e){var i,s,o;const t=e.updateRunning,n=e.updateLastResult;if(!t&&!n)return w;if(t)return u`
1863
1861
  <div class="setup-info-overlay">
1864
1862
  <div class="setup-info-card" style="max-width: 400px;">
1865
1863
  <h3>Software Update</h3>
@@ -1871,7 +1869,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1871
1869
  ${a.status==="running"?u`<span class="setup-update-spinner"></span>`:a.status==="done"?u`<span class="setup-update-icon-ok">${L.check}</span>`:u`<span class="setup-update-icon-fail">${L.x}</span>`}
1872
1870
  </span>
1873
1871
  <span class="setup-update-step-name">${a.name}</span>
1874
- ${a.durationMs!=null?u`<span class="setup-update-step-time">${Pr(a.durationMs)}</span>`:w}
1872
+ ${a.durationMs!=null?u`<span class="setup-update-step-time">${Ir(a.durationMs)}</span>`:w}
1875
1873
  </div>
1876
1874
  `)}
1877
1875
  </div>
@@ -1879,7 +1877,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1879
1877
  ${e.updateMessage?u`<p style="text-align: center; color: var(--tasker-text-grey); font-size: 13px; margin: 12px 0 0;">${e.updateMessage}</p>`:w}
1880
1878
  </div>
1881
1879
  </div>
1882
- `;if(n){const a=n.status==="ok";let r;if(a){const c=(i=n.before)==null?void 0:i.version,h=((s=n.after)==null?void 0:s.version)??n.currentVersion;r=c?`v${c} → v${h}`:`Updated to v${h}`}else r=n.reason??((o=n.failedStep)==null?void 0:o.name)??"unknown error";const l=n.durationMs!=null?Pr(n.durationMs):null;return u`
1880
+ `;if(n){const a=n.status==="ok";let r;if(a){const c=(i=n.before)==null?void 0:i.version,h=((s=n.after)==null?void 0:s.version)??n.currentVersion;r=c?`v${c} → v${h}`:`Updated to v${h}`}else r=n.reason??((o=n.failedStep)==null?void 0:o.name)??"unknown error";const l=n.durationMs!=null?Ir(n.durationMs):null;return u`
1883
1881
  <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onUpdateDismissResult()}}>
1884
1882
  <div class="setup-info-card" style="max-width: 360px; text-align: center;">
1885
1883
  <div class="setup-update-result-icon ${a?"ok":"fail"}">${a?L.circleCheck:L.circleX}</div>
@@ -1899,7 +1897,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1899
1897
  </button>
1900
1898
  </div>
1901
1899
  </div>
1902
- `}return w}function Pr(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 Rg(e){const t=e.accountHasPin;return u`
1900
+ `}return w}function Ir(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 Dg(e){const t=e.accountHasPin;return u`
1903
1901
  <div class="setup-status-item">
1904
1902
  ${Q(t?"good":"bad")}
1905
1903
  <div class="setup-status-info">
@@ -1912,7 +1910,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1912
1910
  @click=${()=>e.onAccountPinModalOpen()}
1913
1911
  >${t?"Change":"Set PIN"}</button>
1914
1912
  </div>
1915
- `}function Dg(e){if(!e.accountPinModalOpen)return w;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const a=c=>h=>{const d=h.target;d.value=d.value.replace(/\D/g,"").slice(0,6),c(d.value)},r=(c,h)=>{var p;let d=c.querySelector(".pin-modal-validation");d||(d=document.createElement("p"),d.className="login-error pin-modal-validation",(p=c.querySelector("button[type=submit]"))==null||p.before(d)),d.textContent=h},l=c=>{c.preventDefault();const h=c.target;if(!n){if(t&&!i){r(h,"Enter your current PIN");return}if(!s){r(h,"Enter a new PIN");return}if(!o){r(h,"Confirm your new PIN");return}if(s!==o){r(h,"PINs do not match");return}if(s.length<4){r(h,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return u`
1913
+ `}function Bg(e){if(!e.accountPinModalOpen)return w;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const a=c=>h=>{const d=h.target;d.value=d.value.replace(/\D/g,"").slice(0,6),c(d.value)},r=(c,h)=>{var p;let d=c.querySelector(".pin-modal-validation");d||(d=document.createElement("p"),d.className="login-error pin-modal-validation",(p=c.querySelector("button[type=submit]"))==null||p.before(d)),d.textContent=h},l=c=>{c.preventDefault();const h=c.target;if(!n){if(t&&!i){r(h,"Enter your current PIN");return}if(!s){r(h,"Enter a new PIN");return}if(!o){r(h,"Confirm your new PIN");return}if(s!==o){r(h,"PINs do not match");return}if(s.length<4){r(h,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return u`
1916
1914
  <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onAccountPinModalClose()}}>
1917
1915
  <div class="setup-info-card" style="max-width: 340px;">
1918
1916
  <div class="setup-info-header">
@@ -1969,7 +1967,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
1969
1967
  </form>
1970
1968
  </div>
1971
1969
  </div>
1972
- `}function Bg(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`
1970
+ `}function Ng(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`
1973
1971
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1974
1972
  <div class="setup-add-account">
1975
1973
  <strong>New Account</strong>
@@ -2032,7 +2030,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2032
2030
  </div>
2033
2031
  </div>
2034
2032
  </div>
2035
- `}function Ng(e){const t=rn(e);return!t||t.isDefault?w:e.workspaceRemoveConfirm===t.name?u`
2033
+ `}function Og(e){const t=rn(e);return!t||t.isDefault?w:e.workspaceRemoveConfirm===t.name?u`
2036
2034
  <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 12px;">
2037
2035
  <div style="font-size: 13px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
2038
2036
  <span style="color: var(--tasker-danger, #ef4444);">Remove "${t.displayName??t.name}" and its WhatsApp account?</span>
@@ -2061,7 +2059,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2061
2059
  @click=${i=>{i.preventDefault(),e.onSetWorkspaceRemoveConfirm(t.name)}}
2062
2060
  >Remove Account</a>
2063
2061
  </p>
2064
- `}function Og(e){if(e.uninstallDone)return u`
2062
+ `}function Fg(e){if(e.uninstallDone)return u`
2065
2063
  <div style="margin-top: 24px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
2066
2064
  <p style="color: var(--tasker-danger, #ef4444); font-size: 13px; font-weight: 600; margin: 0 0 8px 0;">
2067
2065
  Taskmaster has been uninstalled.
@@ -2116,11 +2114,11 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2116
2114
  @click=${t=>{t.preventDefault(),e.onUninstallConfirm()}}
2117
2115
  >Uninstall Taskmaster</a>
2118
2116
  </p>
2119
- `}function Fg(){return u`
2117
+ `}function Ug(){return u`
2120
2118
  <p class="setup-hint" style="margin-top: 4px; font-size: 12px; opacity: 0.6;">
2121
2119
  Need help? <a href="https://wa.me/447591215452" target="_blank" rel="noopener" style="color: var(--tasker-orange);">Message Tuesday on WhatsApp</a>
2122
2120
  </p>
2123
- `}function Ug(e){const{whatsappBusy:t,whatsappLoginMessage:n,whatsappLoginQrDataUrl:i,whatsappLoginConnected:s,whatsappChannelStatus:o}=e;if(i)return u`
2121
+ `}function Wg(e){const{whatsappBusy:t,whatsappLoginMessage:n,whatsappLoginQrDataUrl:i,whatsappLoginConnected:s,whatsappChannelStatus:o}=e;if(i)return u`
2124
2122
  <div class="setup-container">
2125
2123
  <div class="setup-card">
2126
2124
  <h1>Scan with WhatsApp</h1>
@@ -2157,33 +2155,33 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2157
2155
  `;const a=(o==null?void 0:o.running)&&(o==null?void 0:o.connected);if(o){const h=(e.whatsappAccounts.length>1?e.whatsappAccounts.every(d=>d.running&&d.connected):a)&&e.authConnected;return u`
2158
2156
  <div class="setup-container">
2159
2157
  <div class="setup-card ${h?"setup-success":""} setup-dashboard-wide">
2160
- ${rg(e)}
2158
+ ${lg(e)}
2161
2159
  <div class="setup-status-dashboard">
2162
- ${lg(e)}
2163
2160
  ${cg(e)}
2164
2161
  ${dg(e)}
2165
2162
  ${ug(e)}
2166
- ${e.serverPlatform==="darwin"?mg(e):w}
2167
- ${Rg(e)}
2168
- ${wg(e)}
2169
- ${$g(e)}
2170
- ${Ag(e)}
2171
- ${Tg(e)}
2172
- ${Pg(e)}
2163
+ ${pg(e)}
2164
+ ${e.serverPlatform==="darwin"?yg(e):w}
2165
+ ${Dg(e)}
2166
+ ${kg(e)}
2167
+ ${xg(e)}
2168
+ ${Cg(e)}
2173
2169
  ${_g(e)}
2170
+ ${Ig(e)}
2171
+ ${Mg(e)}
2174
2172
  </div>
2175
2173
 
2176
- ${Dg(e)}
2177
- ${Cg(e)}
2178
- ${xg(e)}
2179
- ${Ig(e)}
2180
- ${Mg(e)}
2181
- ${Eg(e)}
2182
- ${vg(e)}
2183
2174
  ${Bg(e)}
2175
+ ${Eg(e)}
2176
+ ${Sg(e)}
2177
+ ${Lg(e)}
2178
+ ${Pg(e)}
2179
+ ${Tg(e)}
2180
+ ${bg(e)}
2184
2181
  ${Ng(e)}
2185
2182
  ${Og(e)}
2186
- ${Fg()}
2183
+ ${Fg(e)}
2184
+ ${Ug()}
2187
2185
  ${e.workspacesError?u`<p class="setup-error" style="margin-top: 8px;">${e.workspacesError}</p>`:w}
2188
2186
  </div>
2189
2187
  </div>
@@ -2228,7 +2226,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2228
2226
  </button>
2229
2227
  </div>
2230
2228
  </div>
2231
- `}function Wg(e){const{connected:t,currentStep:n}=e;if(t&&Wi()&&ya(),e.uninstallDone||!t&&Wi())return u`
2229
+ `}function Kg(e){const{connected:t,currentStep:n}=e;if(t&&Ki()&&va(),e.uninstallDone||!t&&Ki())return u`
2232
2230
  <div class="setup-container">
2233
2231
  <div class="setup-card">
2234
2232
  <p style="color: var(--tasker-danger, #ef4444); font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
@@ -2251,7 +2249,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2251
2249
  <p>${o?"Restarting gateway after update…":"Connecting to gateway..."}</p>
2252
2250
  </div>
2253
2251
  </div>
2254
- `}let i;switch(n){case"license":i=Mr(e);break;case"auth":i=ag(e);break;case"whatsapp":case"complete":i=Ug(e);break;default:i=Mr(e)}const s=Lt("Setup",e.wsProps);return u`${i}${og(e)}${yg(e)}${gg(e)}${Lg(e)}${Sg(e)}${s}`}function Kg(e,t){const n=e.paired?"Paired phone (used to link WhatsApp)":"Admin access via WhatsApp DM";return u`
2252
+ `}let i;switch(n){case"license":i=Pr(e);break;case"auth":i=rg(e);break;case"whatsapp":case"complete":i=Wg(e);break;default:i=Pr(e)}const s=Rt("Setup",e.wsProps);return u`${i}${ag(e)}${vg(e)}${mg(e)}${Rg(e)}${Ag(e)}${s}`}function zg(e,t){const n=e.paired?"Paired phone (used to link WhatsApp)":"Admin access via WhatsApp DM";return u`
2255
2253
  <div class="sp-list-item">
2256
2254
  <div class="sp-list-item-main">
2257
2255
  <div class="sp-list-item-title">${e.phone}</div>
@@ -2266,7 +2264,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2266
2264
  Remove
2267
2265
  </button>`}
2268
2266
  </div>
2269
- `}function zg(e){if(!e.connected)return u`
2267
+ `}function qg(e){if(!e.connected)return u`
2270
2268
  <div class="setup-container">
2271
2269
  <div class="setup-card">
2272
2270
  <div class="setup-spinner"></div>
@@ -2275,7 +2273,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2275
2273
  </div>
2276
2274
  `;const t=n=>{n.preventDefault(),e.newPhone.trim()&&e.onAdd(e.newPhone)};return u`
2277
2275
  <div class="setup-container">
2278
- ${Lt("Admins",e.wsProps)}
2276
+ ${Rt("Admins",e.wsProps)}
2279
2277
  <div class="setup-card" style="max-width: 520px;">
2280
2278
  <h1>Admin Phones</h1>
2281
2279
  <p style="margin-bottom: 16px;">
@@ -2315,7 +2313,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2315
2313
  </form>
2316
2314
 
2317
2315
  <div class="sp-list" style="margin-top: 20px;">
2318
- ${e.phones.length===0?u`<div class="sp-list-empty">No admin phones configured yet.</div>`:e.phones.map(n=>Kg(n,e))}
2316
+ ${e.phones.length===0?u`<div class="sp-list-empty">No admin phones configured yet.</div>`:e.phones.map(n=>zg(n,e))}
2319
2317
  </div>
2320
2318
 
2321
2319
  <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
@@ -2326,13 +2324,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2326
2324
 
2327
2325
  </div>
2328
2326
  </div>
2329
- `}const dd=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`;function qg(e){return Object.keys(e.fields).length}function Hg(e,t){return u`
2327
+ `}const ud=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`;function Hg(e){return Object.keys(e.fields).length}function jg(e,t){return u`
2330
2328
  <div class="event-modal-overlay" @click=${t.onDeleteConfirmClose}>
2331
2329
  <div class="event-modal" style="width: min(400px, 100%);" @click=${n=>n.stopPropagation()}>
2332
2330
  <div class="event-modal__header">
2333
2331
  <div class="event-modal__title">Delete Contact</div>
2334
2332
  <button class="event-modal__close" @click=${t.onDeleteConfirmClose}>
2335
- ${dd}
2333
+ ${ud}
2336
2334
  </button>
2337
2335
  </div>
2338
2336
  <p style="margin: 0 0 8px; color: rgba(255,255,255,0.7); font-size: 14px; line-height: 1.5;">
@@ -2358,13 +2356,13 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2358
2356
  </div>
2359
2357
  </div>
2360
2358
  </div>
2361
- `}function jg(e,t){const n=t.addFieldKey.trim().length>0,i=s=>{s.preventDefault(),n&&t.onAddFieldSubmit()};return u`
2359
+ `}function Gg(e,t){const n=t.addFieldKey.trim().length>0,i=s=>{s.preventDefault(),n&&t.onAddFieldSubmit()};return u`
2362
2360
  <div class="event-modal-overlay" @click=${t.onAddFieldClose}>
2363
2361
  <div class="event-modal" style="width: min(400px, 100%);" @click=${s=>s.stopPropagation()}>
2364
2362
  <div class="event-modal__header">
2365
2363
  <div class="event-modal__title">Add Field</div>
2366
2364
  <button class="event-modal__close" @click=${t.onAddFieldClose}>
2367
- ${dd}
2365
+ ${ud}
2368
2366
  </button>
2369
2367
  </div>
2370
2368
  <p style="margin: 0 0 16px; color: rgba(255,255,255,0.5); font-size: 13px;">
@@ -2409,7 +2407,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2409
2407
  </form>
2410
2408
  </div>
2411
2409
  </div>
2412
- `}function Gg(e,t){const n=Object.entries(e.fields);return u`
2410
+ `}function Vg(e,t){const n=Object.entries(e.fields);return u`
2413
2411
  <div class="contacts-record-fields">
2414
2412
  ${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`
2415
2413
  <div class="contacts-field-row">
@@ -2456,7 +2454,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2456
2454
  </button>
2457
2455
  </div>
2458
2456
  </div>
2459
- `}function Vg(e,t){const n=t.editingId===e.id,i=qg(e),s=i===0?"No fields":`${i} field${i>1?"s":""}`;return u`
2457
+ `}function Qg(e,t){const n=t.editingId===e.id,i=Hg(e),s=i===0?"No fields":`${i} field${i>1?"s":""}`;return u`
2460
2458
  <div class="contacts-record">
2461
2459
  <div
2462
2460
  class="contacts-record-header"
@@ -2468,9 +2466,9 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2468
2466
  </div>
2469
2467
  <span class="contacts-record-meta">${s}</span>
2470
2468
  </div>
2471
- ${n?Gg(e,t):w}
2469
+ ${n?Vg(e,t):w}
2472
2470
  </div>
2473
- `}function Qg(e){if(!e.connected)return u`
2471
+ `}function Jg(e){if(!e.connected)return u`
2474
2472
  <div class="setup-container">
2475
2473
  <div class="setup-card">
2476
2474
  <div class="setup-spinner"></div>
@@ -2479,7 +2477,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2479
2477
  </div>
2480
2478
  `;const t=o=>{o.preventDefault(),e.onSearchSubmit()},n=o=>{o.preventDefault(),e.newRecordPhone.trim()&&e.newRecordName.trim()&&e.onAdd(e.newRecordPhone,e.newRecordName)},i=e.deleteConfirmId?e.records.find(o=>o.id===e.deleteConfirmId):null,s=e.addFieldForId?e.records.find(o=>o.id===e.addFieldForId):null;return u`
2481
2479
  <div class="setup-container">
2482
- ${Lt("Contacts",e.wsProps)}
2480
+ ${Rt("Contacts",e.wsProps)}
2483
2481
  <div class="setup-card" style="max-width: 620px;">
2484
2482
  <h1>Contact Records</h1>
2485
2483
  <p style="margin-bottom: 16px;">
@@ -2566,7 +2564,7 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2566
2564
  <div style="margin-top: 16px;">
2567
2565
  ${e.records.length===0?u`<div class="contacts-empty">
2568
2566
  ${e.searchQuery.trim()?`No records matching "${e.searchQuery}".`:"No contact records yet. Add one to get started."}
2569
- </div>`:e.records.map(o=>Vg(o,e))}
2567
+ </div>`:e.records.map(o=>Qg(o,e))}
2570
2568
  </div>
2571
2569
 
2572
2570
  <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
@@ -2578,35 +2576,35 @@ ${o}`)}return e.chatStream="","working"}else if(t.state==="block"){const s=Mn(t.
2578
2576
  </div>
2579
2577
  </div>
2580
2578
 
2581
- ${i?Hg(i,e):w}
2582
- ${s?jg(s,e):w}
2583
- `}const ud={CHILD:2},pd=e=>(...t)=>({_$litDirective$:e,values:t});let hd=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:Jg}=sp,Ir=e=>e,Lr=()=>document.createComment(""),gn=(e,t,n)=>{var o;const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const a=i.insertBefore(Lr(),s),r=i.insertBefore(Lr(),s);n=new Jg(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 h=Ir(c).nextSibling;Ir(i).insertBefore(c,s),c=h}}}return n},gt=(e,t,n=e)=>(e._$AI(t,n),e),Yg={},Xg=(e,t=Yg)=>e._$AH=t,Zg=e=>e._$AH,Us=e=>{e._$AR(),e._$AA.remove()};const Rr=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},em=pd(class extends hd{constructor(e){if(super(e),e.type!==ud.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=Zg(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,h,d=0,p=s.length-1,v=0,S=o.length-1;for(;d<=p&&v<=S;)if(s[d]===null)d++;else if(s[p]===null)p--;else if(r[d]===a[v])l[v]=gt(s[d],o[v]),d++,v++;else if(r[p]===a[S])l[S]=gt(s[p],o[S]),p--,S--;else if(r[d]===a[S])l[S]=gt(s[d],o[S]),gn(e,l[S+1],s[d]),d++,S--;else if(r[p]===a[v])l[v]=gt(s[p],o[v]),gn(e,s[d],s[p]),p--,v++;else if(c===void 0&&(c=Rr(a,v,S),h=Rr(r,d,p)),c.has(r[d]))if(c.has(r[p])){const x=h.get(a[v]),T=x!==void 0?s[x]:null;if(T===null){const f=gn(e,s[d]);gt(f,o[v]),l[v]=f}else l[v]=gt(T,o[v]),gn(e,s[d],T),s[x]=null;v++}else Us(s[p]),p--;else Us(s[d]),d++;for(;v<=S;){const x=gn(e,l[S+1]);gt(x,o[v]),l[v++]=x}for(;d<=p;){const x=s[d++];x!==null&&Us(x)}return this.ut=a,Xg(e,l),rt}});class Co extends hd{constructor(t){if(super(t),this.it=w,t.type!==ud.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===w||t==null)return this._t=void 0,this.it=t;if(t===rt)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const n=[t];return n.raw=n,this._t={_$litType$:this.constructor.resultType,strings:n,values:[]}}}Co.directiveName="unsafeHTML",Co.resultType=1;const Ki=pd(Co);const{entries:fd,setPrototypeOf:Dr,isFrozen:tm,getPrototypeOf:nm,getOwnPropertyDescriptor:im}=Object;let{freeze:ye,seal:$e,create:Eo}=Object,{apply:To,construct:_o}=typeof Reflect<"u"&&Reflect;ye||(ye=function(t){return t});$e||($e=function(t){return t});To||(To=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)});_o||(_o=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return new t(...i)});const hi=ve(Array.prototype.forEach),sm=ve(Array.prototype.lastIndexOf),Br=ve(Array.prototype.pop),mn=ve(Array.prototype.push),om=ve(Array.prototype.splice),Ai=ve(String.prototype.toLowerCase),Ws=ve(String.prototype.toString),Ks=ve(String.prototype.match),yn=ve(String.prototype.replace),am=ve(String.prototype.indexOf),rm=ve(String.prototype.trim),xe=ve(Object.prototype.hasOwnProperty),ge=ve(RegExp.prototype.test),vn=lm(TypeError);function ve(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 To(e,t,i)}}function lm(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return _o(e,n)}}function K(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ai;Dr&&Dr(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(tm(t)||(t[i]=o),s=o)}e[s]=!0}return e}function cm(e){for(let t=0;t<e.length;t++)xe(e,t)||(e[t]=null);return e}function Re(e){const t=Eo(null);for(const[n,i]of fd(e))xe(e,n)&&(Array.isArray(i)?t[n]=cm(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Re(i):t[n]=i);return t}function bn(e,t){for(;e!==null;){const i=im(e,t);if(i){if(i.get)return ve(i.get);if(typeof i.value=="function")return ve(i.value)}e=nm(e)}function n(){return null}return n}const Nr=ye(["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"]),zs=ye(["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"]),qs=ye(["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"]),dm=ye(["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"]),Hs=ye(["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"]),um=ye(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Or=ye(["#text"]),Fr=ye(["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"]),js=ye(["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"]),Ur=ye(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),fi=ye(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),pm=$e(/\{\{[\w\W]*|[\w\W]*\}\}/gm),hm=$e(/<%[\w\W]*|[\w\W]*%>/gm),fm=$e(/\$\{[\w\W]*/gm),gm=$e(/^data-[\-\w.\u00B7-\uFFFF]+$/),mm=$e(/^aria-[\-\w]+$/),gd=$e(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ym=$e(/^(?:\w+script|data):/i),vm=$e(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),md=$e(/^html$/i),bm=$e(/^[a-z][.\w]*(-[.\w]+)+$/i);var Wr=Object.freeze({__proto__:null,ARIA_ATTR:mm,ATTR_WHITESPACE:vm,CUSTOM_ELEMENT:bm,DATA_ATTR:gm,DOCTYPE_NAME:md,ERB_EXPR:hm,IS_ALLOWED_URI:gd,IS_SCRIPT_OR_DATA:ym,MUSTACHE_EXPR:pm,TMPLIT_EXPR:fm});const wn={element:1,text:3,progressingInstruction:7,comment:8,document:9},wm=function(){return typeof window>"u"?null:window},km=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}},Kr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function yd(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:wm();const t=N=>yd(N);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==wn.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,s=i.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:r,Element:l,NodeFilter:c,NamedNodeMap:h=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:p,trustedTypes:v}=e,S=l.prototype,x=bn(S,"cloneNode"),T=bn(S,"remove"),f=bn(S,"nextSibling"),b=bn(S,"childNodes"),k=bn(S,"parentNode");if(typeof a=="function"){const N=n.createElement("template");N.content&&N.content.ownerDocument&&(n=N.content.ownerDocument)}let A,E="";const{implementation:M,createNodeIterator:P,createDocumentFragment:R,getElementsByTagName:F}=n,{importNode:H}=i;let z=Kr();t.isSupported=typeof fd=="function"&&typeof k=="function"&&M&&M.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ke,ERB_EXPR:_e,TMPLIT_EXPR:Ke,DATA_ATTR:gs,ARIA_ATTR:ms,IS_SCRIPT_OR_DATA:ys,ATTR_WHITESPACE:Vn,CUSTOM_ELEMENT:vs}=Wr;let{IS_ALLOWED_URI:Qn}=Wr,te=null;const Jn=K({},[...Nr,...zs,...qs,...Hs,...Or]);let ne=null;const Yn=K({},[...Fr,...js,...Ur,...fi]);let X=Object.seal(Eo(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}})),ut=null,dn=null;const tt=Object.seal(Eo(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Xn=!0,C=!0,I=!1,U=!0,W=!1,Z=!0,J=!1,fe=!1,nt=!1,Bt=!1,Zn=!1,ei=!1,Fa=!0,Ua=!1;const Eu="user-content-";let bs=!0,un=!1,Nt={},Me=null;const ws=K({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Wa=null;const Ka=K({},["audio","video","img","source","image","track"]);let ks=null;const za=K({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ti="http://www.w3.org/1998/Math/MathML",ni="http://www.w3.org/2000/svg",ze="http://www.w3.org/1999/xhtml";let Ot=ze,$s=!1,xs=null;const Tu=K({},[ti,ni,ze],Ws);let ii=K({},["mi","mo","mn","ms","mtext"]),si=K({},["annotation-xml"]);const _u=K({},["title","style","font","a","script"]);let pn=null;const Mu=["application/xhtml+xml","text/html"],Pu="text/html";let oe=null,Ft=null;const Iu=n.createElement("form"),qa=function($){return $ instanceof RegExp||$ instanceof Function},Ss=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ft&&Ft===$)){if((!$||typeof $!="object")&&($={}),$=Re($),pn=Mu.indexOf($.PARSER_MEDIA_TYPE)===-1?Pu:$.PARSER_MEDIA_TYPE,oe=pn==="application/xhtml+xml"?Ws:Ai,te=xe($,"ALLOWED_TAGS")?K({},$.ALLOWED_TAGS,oe):Jn,ne=xe($,"ALLOWED_ATTR")?K({},$.ALLOWED_ATTR,oe):Yn,xs=xe($,"ALLOWED_NAMESPACES")?K({},$.ALLOWED_NAMESPACES,Ws):Tu,ks=xe($,"ADD_URI_SAFE_ATTR")?K(Re(za),$.ADD_URI_SAFE_ATTR,oe):za,Wa=xe($,"ADD_DATA_URI_TAGS")?K(Re(Ka),$.ADD_DATA_URI_TAGS,oe):Ka,Me=xe($,"FORBID_CONTENTS")?K({},$.FORBID_CONTENTS,oe):ws,ut=xe($,"FORBID_TAGS")?K({},$.FORBID_TAGS,oe):Re({}),dn=xe($,"FORBID_ATTR")?K({},$.FORBID_ATTR,oe):Re({}),Nt=xe($,"USE_PROFILES")?$.USE_PROFILES:!1,Xn=$.ALLOW_ARIA_ATTR!==!1,C=$.ALLOW_DATA_ATTR!==!1,I=$.ALLOW_UNKNOWN_PROTOCOLS||!1,U=$.ALLOW_SELF_CLOSE_IN_ATTR!==!1,W=$.SAFE_FOR_TEMPLATES||!1,Z=$.SAFE_FOR_XML!==!1,J=$.WHOLE_DOCUMENT||!1,Bt=$.RETURN_DOM||!1,Zn=$.RETURN_DOM_FRAGMENT||!1,ei=$.RETURN_TRUSTED_TYPE||!1,nt=$.FORCE_BODY||!1,Fa=$.SANITIZE_DOM!==!1,Ua=$.SANITIZE_NAMED_PROPS||!1,bs=$.KEEP_CONTENT!==!1,un=$.IN_PLACE||!1,Qn=$.ALLOWED_URI_REGEXP||gd,Ot=$.NAMESPACE||ze,ii=$.MATHML_TEXT_INTEGRATION_POINTS||ii,si=$.HTML_INTEGRATION_POINTS||si,X=$.CUSTOM_ELEMENT_HANDLING||{},$.CUSTOM_ELEMENT_HANDLING&&qa($.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(X.tagNameCheck=$.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$.CUSTOM_ELEMENT_HANDLING&&qa($.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(X.attributeNameCheck=$.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$.CUSTOM_ELEMENT_HANDLING&&typeof $.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(X.allowCustomizedBuiltInElements=$.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),W&&(C=!1),Zn&&(Bt=!0),Nt&&(te=K({},Or),ne=[],Nt.html===!0&&(K(te,Nr),K(ne,Fr)),Nt.svg===!0&&(K(te,zs),K(ne,js),K(ne,fi)),Nt.svgFilters===!0&&(K(te,qs),K(ne,js),K(ne,fi)),Nt.mathMl===!0&&(K(te,Hs),K(ne,Ur),K(ne,fi))),$.ADD_TAGS&&(typeof $.ADD_TAGS=="function"?tt.tagCheck=$.ADD_TAGS:(te===Jn&&(te=Re(te)),K(te,$.ADD_TAGS,oe))),$.ADD_ATTR&&(typeof $.ADD_ATTR=="function"?tt.attributeCheck=$.ADD_ATTR:(ne===Yn&&(ne=Re(ne)),K(ne,$.ADD_ATTR,oe))),$.ADD_URI_SAFE_ATTR&&K(ks,$.ADD_URI_SAFE_ATTR,oe),$.FORBID_CONTENTS&&(Me===ws&&(Me=Re(Me)),K(Me,$.FORBID_CONTENTS,oe)),$.ADD_FORBID_CONTENTS&&(Me===ws&&(Me=Re(Me)),K(Me,$.ADD_FORBID_CONTENTS,oe)),bs&&(te["#text"]=!0),J&&K(te,["html","head","body"]),te.table&&(K(te,["tbody"]),delete ut.tbody),$.TRUSTED_TYPES_POLICY){if(typeof $.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=$.TRUSTED_TYPES_POLICY,E=A.createHTML("")}else A===void 0&&(A=km(v,s)),A!==null&&typeof E=="string"&&(E=A.createHTML(""));ye&&ye($),Ft=$}},Ha=K({},[...zs,...qs,...dm]),ja=K({},[...Hs,...um]),Lu=function($){let _=k($);(!_||!_.tagName)&&(_={namespaceURI:Ot,tagName:"template"});const B=Ai($.tagName),Y=Ai(_.tagName);return xs[$.namespaceURI]?$.namespaceURI===ni?_.namespaceURI===ze?B==="svg":_.namespaceURI===ti?B==="svg"&&(Y==="annotation-xml"||ii[Y]):!!Ha[B]:$.namespaceURI===ti?_.namespaceURI===ze?B==="math":_.namespaceURI===ni?B==="math"&&si[Y]:!!ja[B]:$.namespaceURI===ze?_.namespaceURI===ni&&!si[Y]||_.namespaceURI===ti&&!ii[Y]?!1:!ja[B]&&(_u[B]||!Ha[B]):!!(pn==="application/xhtml+xml"&&xs[$.namespaceURI]):!1},Pe=function($){mn(t.removed,{element:$});try{k($).removeChild($)}catch{T($)}},pt=function($,_){try{mn(t.removed,{attribute:_.getAttributeNode($),from:_})}catch{mn(t.removed,{attribute:null,from:_})}if(_.removeAttribute($),$==="is")if(Bt||Zn)try{Pe(_)}catch{}else try{_.setAttribute($,"")}catch{}},Ga=function($){let _=null,B=null;if(nt)$="<remove></remove>"+$;else{const se=Ks($,/^[\r\n\t ]+/);B=se&&se[0]}pn==="application/xhtml+xml"&&Ot===ze&&($='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$+"</body></html>");const Y=A?A.createHTML($):$;if(Ot===ze)try{_=new p().parseFromString(Y,pn)}catch{}if(!_||!_.documentElement){_=M.createDocument(Ot,"template",null);try{_.documentElement.innerHTML=$s?E:Y}catch{}}const de=_.body||_.documentElement;return $&&B&&de.insertBefore(n.createTextNode(B),de.childNodes[0]||null),Ot===ze?F.call(_,J?"html":"body")[0]:J?_.documentElement:de},Va=function($){return P.call($.ownerDocument||$,$,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},As=function($){return $ instanceof d&&(typeof $.nodeName!="string"||typeof $.textContent!="string"||typeof $.removeChild!="function"||!($.attributes instanceof h)||typeof $.removeAttribute!="function"||typeof $.setAttribute!="function"||typeof $.namespaceURI!="string"||typeof $.insertBefore!="function"||typeof $.hasChildNodes!="function")},Qa=function($){return typeof r=="function"&&$ instanceof r};function qe(N,$,_){hi(N,B=>{B.call(t,$,_,Ft)})}const Ja=function($){let _=null;if(qe(z.beforeSanitizeElements,$,null),As($))return Pe($),!0;const B=oe($.nodeName);if(qe(z.uponSanitizeElement,$,{tagName:B,allowedTags:te}),Z&&$.hasChildNodes()&&!Qa($.firstElementChild)&&ge(/<[/\w!]/g,$.innerHTML)&&ge(/<[/\w!]/g,$.textContent)||$.nodeType===wn.progressingInstruction||Z&&$.nodeType===wn.comment&&ge(/<[/\w]/g,$.data))return Pe($),!0;if(!(tt.tagCheck instanceof Function&&tt.tagCheck(B))&&(!te[B]||ut[B])){if(!ut[B]&&Xa(B)&&(X.tagNameCheck instanceof RegExp&&ge(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B)))return!1;if(bs&&!Me[B]){const Y=k($)||$.parentNode,de=b($)||$.childNodes;if(de&&Y){const se=de.length;for(let be=se-1;be>=0;--be){const He=x(de[be],!0);He.__removalCount=($.__removalCount||0)+1,Y.insertBefore(He,f($))}}}return Pe($),!0}return $ instanceof l&&!Lu($)||(B==="noscript"||B==="noembed"||B==="noframes")&&ge(/<\/no(script|embed|frames)/i,$.innerHTML)?(Pe($),!0):(W&&$.nodeType===wn.text&&(_=$.textContent,hi([ke,_e,Ke],Y=>{_=yn(_,Y," ")}),$.textContent!==_&&(mn(t.removed,{element:$.cloneNode()}),$.textContent=_)),qe(z.afterSanitizeElements,$,null),!1)},Ya=function($,_,B){if(Fa&&(_==="id"||_==="name")&&(B in n||B in Iu))return!1;if(!(C&&!dn[_]&&ge(gs,_))){if(!(Xn&&ge(ms,_))){if(!(tt.attributeCheck instanceof Function&&tt.attributeCheck(_,$))){if(!ne[_]||dn[_]){if(!(Xa($)&&(X.tagNameCheck instanceof RegExp&&ge(X.tagNameCheck,$)||X.tagNameCheck instanceof Function&&X.tagNameCheck($))&&(X.attributeNameCheck instanceof RegExp&&ge(X.attributeNameCheck,_)||X.attributeNameCheck instanceof Function&&X.attributeNameCheck(_,$))||_==="is"&&X.allowCustomizedBuiltInElements&&(X.tagNameCheck instanceof RegExp&&ge(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B))))return!1}else if(!ks[_]){if(!ge(Qn,yn(B,Vn,""))){if(!((_==="src"||_==="xlink:href"||_==="href")&&$!=="script"&&am(B,"data:")===0&&Wa[$])){if(!(I&&!ge(ys,yn(B,Vn,"")))){if(B)return!1}}}}}}}return!0},Xa=function($){return $!=="annotation-xml"&&Ks($,vs)},Za=function($){qe(z.beforeSanitizeAttributes,$,null);const{attributes:_}=$;if(!_||As($))return;const B={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let Y=_.length;for(;Y--;){const de=_[Y],{name:se,namespaceURI:be,value:He}=de,Ut=oe(se),Cs=He;let re=se==="value"?Cs:rm(Cs);if(B.attrName=Ut,B.attrValue=re,B.keepAttr=!0,B.forceKeepAttr=void 0,qe(z.uponSanitizeAttribute,$,B),re=B.attrValue,Ua&&(Ut==="id"||Ut==="name")&&(pt(se,$),re=Eu+re),Z&&ge(/((--!?|])>)|<\/(style|title|textarea)/i,re)){pt(se,$);continue}if(Ut==="attributename"&&Ks(re,"href")){pt(se,$);continue}if(B.forceKeepAttr)continue;if(!B.keepAttr){pt(se,$);continue}if(!U&&ge(/\/>/i,re)){pt(se,$);continue}W&&hi([ke,_e,Ke],tr=>{re=yn(re,tr," ")});const er=oe($.nodeName);if(!Ya(er,Ut,re)){pt(se,$);continue}if(A&&typeof v=="object"&&typeof v.getAttributeType=="function"&&!be)switch(v.getAttributeType(er,Ut)){case"TrustedHTML":{re=A.createHTML(re);break}case"TrustedScriptURL":{re=A.createScriptURL(re);break}}if(re!==Cs)try{be?$.setAttributeNS(be,se,re):$.setAttribute(se,re),As($)?Pe($):Br(t.removed)}catch{pt(se,$)}}qe(z.afterSanitizeAttributes,$,null)},Ru=function N($){let _=null;const B=Va($);for(qe(z.beforeSanitizeShadowDOM,$,null);_=B.nextNode();)qe(z.uponSanitizeShadowNode,_,null),Ja(_),Za(_),_.content instanceof o&&N(_.content);qe(z.afterSanitizeShadowDOM,$,null)};return t.sanitize=function(N){let $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},_=null,B=null,Y=null,de=null;if($s=!N,$s&&(N="<!-->"),typeof N!="string"&&!Qa(N))if(typeof N.toString=="function"){if(N=N.toString(),typeof N!="string")throw vn("dirty is not a string, aborting")}else throw vn("toString is not a function");if(!t.isSupported)return N;if(fe||Ss($),t.removed=[],typeof N=="string"&&(un=!1),un){if(N.nodeName){const He=oe(N.nodeName);if(!te[He]||ut[He])throw vn("root node is forbidden and cannot be sanitized in-place")}}else if(N instanceof r)_=Ga("<!---->"),B=_.ownerDocument.importNode(N,!0),B.nodeType===wn.element&&B.nodeName==="BODY"||B.nodeName==="HTML"?_=B:_.appendChild(B);else{if(!Bt&&!W&&!J&&N.indexOf("<")===-1)return A&&ei?A.createHTML(N):N;if(_=Ga(N),!_)return Bt?null:ei?E:""}_&&nt&&Pe(_.firstChild);const se=Va(un?N:_);for(;Y=se.nextNode();)Ja(Y),Za(Y),Y.content instanceof o&&Ru(Y.content);if(un)return N;if(Bt){if(Zn)for(de=R.call(_.ownerDocument);_.firstChild;)de.appendChild(_.firstChild);else de=_;return(ne.shadowroot||ne.shadowrootmode)&&(de=H.call(i,de,!0)),de}let be=J?_.outerHTML:_.innerHTML;return J&&te["!doctype"]&&_.ownerDocument&&_.ownerDocument.doctype&&_.ownerDocument.doctype.name&&ge(md,_.ownerDocument.doctype.name)&&(be="<!DOCTYPE "+_.ownerDocument.doctype.name+`>
2584
- `+be),W&&hi([ke,_e,Ke],He=>{be=yn(be,He," ")}),A&&ei?A.createHTML(be):be},t.setConfig=function(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ss(N),fe=!0},t.clearConfig=function(){Ft=null,fe=!1},t.isValidAttribute=function(N,$,_){Ft||Ss({});const B=oe(N),Y=oe($);return Ya(B,Y,_)},t.addHook=function(N,$){typeof $=="function"&&mn(z[N],$)},t.removeHook=function(N,$){if($!==void 0){const _=sm(z[N],$);return _===-1?void 0:om(z[N],_,1)[0]}return Br(z[N])},t.removeHooks=function(N){z[N]=[]},t.removeAllHooks=function(){z=Kr()},t}var Mo=yd();function ka(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Rt=ka();function vd(e){Rt=e}var In={exec:()=>null};function j(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(s,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(me.caret,"$1"),n=n.replace(s,a),i},getRegex:()=>new RegExp(n,t)};return i}var $m=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),me={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")},xm=/^(?:[ \t]*(?:\n|$))+/,Sm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Am=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,jn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Cm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,$a=/(?:[*+-]|\d{1,9}[.)])/,bd=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,wd=j(bd).replace(/bull/g,$a).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(),Em=j(bd).replace(/bull/g,$a).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(),xa=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Tm=/^[^\n]+/,Sa=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,_m=j(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Sa).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Mm=j(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,$a).getRegex(),cs="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",Aa=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Pm=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",Aa).replace("tag",cs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),kd=j(xa).replace("hr",jn).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",cs).getRegex(),Im=j(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",kd).getRegex(),Ca={blockquote:Im,code:Sm,def:_m,fences:Am,heading:Cm,hr:jn,html:Pm,lheading:wd,list:Mm,newline:xm,paragraph:kd,table:In,text:Tm},zr=j("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",jn).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",cs).getRegex(),Lm={...Ca,lheading:Em,table:zr,paragraph:j(xa).replace("hr",jn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",zr).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",cs).getRegex()},Rm={...Ca,html:j(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Aa).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:In,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:j(xa).replace("hr",jn).replace("heading",` *#{1,6} *[^
2585
- ]`).replace("lheading",wd).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Dm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Bm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,$d=/^( {2,}|\\)\n(?!\s*$)/,Nm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ds=/[\p{P}\p{S}]/u,Ea=/[\s\p{P}\p{S}]/u,xd=/[^\s\p{P}\p{S}]/u,Om=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ea).getRegex(),Sd=/(?!~)[\p{P}\p{S}]/u,Fm=/(?!~)[\s\p{P}\p{S}]/u,Um=/(?:[^\s\p{P}\p{S}]|~)/u,Wm=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",$m?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ad=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Km=j(Ad,"u").replace(/punct/g,ds).getRegex(),zm=j(Ad,"u").replace(/punct/g,Sd).getRegex(),Cd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",qm=j(Cd,"gu").replace(/notPunctSpace/g,xd).replace(/punctSpace/g,Ea).replace(/punct/g,ds).getRegex(),Hm=j(Cd,"gu").replace(/notPunctSpace/g,Um).replace(/punctSpace/g,Fm).replace(/punct/g,Sd).getRegex(),jm=j("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,xd).replace(/punctSpace/g,Ea).replace(/punct/g,ds).getRegex(),Gm=j(/\\(punct)/,"gu").replace(/punct/g,ds).getRegex(),Vm=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(),Qm=j(Aa).replace("(?:-->|$)","-->").getRegex(),Jm=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",Qm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),zi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Ym=j(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",zi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ed=j(/^!?\[(label)\]\[(ref)\]/).replace("label",zi).replace("ref",Sa).getRegex(),Td=j(/^!?\[(ref)\](?:\[\])?/).replace("ref",Sa).getRegex(),Xm=j("reflink|nolink(?!\\()","g").replace("reflink",Ed).replace("nolink",Td).getRegex(),qr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ta={_backpedal:In,anyPunctuation:Gm,autolink:Vm,blockSkip:Wm,br:$d,code:Bm,del:In,emStrongLDelim:Km,emStrongRDelimAst:qm,emStrongRDelimUnd:jm,escape:Dm,link:Ym,nolink:Td,punctuation:Om,reflink:Ed,reflinkSearch:Xm,tag:Jm,text:Nm,url:In},Zm={...Ta,link:j(/^!?\[(label)\]\((.*?)\)/).replace("label",zi).getRegex(),reflink:j(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",zi).getRegex()},Po={...Ta,emStrongRDelimAst:Hm,emStrongLDelim:zm,url:j(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",qr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:j(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",qr).getRegex()},ey={...Po,br:j($d).replace("{2,}","*").getRegex(),text:j(Po.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},gi={normal:Ca,gfm:Lm,pedantic:Rm},kn={normal:Ta,gfm:Po,breaks:ey,pedantic:Zm},ty={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Hr=e=>ty[e];function Ve(e,t){if(t){if(me.escapeTest.test(e))return e.replace(me.escapeReplace,Hr)}else if(me.escapeTestNoEncode.test(e))return e.replace(me.escapeReplaceNoEncode,Hr);return e}function jr(e){try{e=encodeURI(e).replace(me.percentDecode,"%")}catch{return null}return e}function Gr(e,t){var o;let n=e.replace(me.findPipe,(a,r,l)=>{let c=!1,h=r;for(;--h>=0&&l[h]==="\\";)c=!c;return c?"|":" |"}),i=n.split(me.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(me.slashPipe,"|");return i}function $n(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 ny(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 Vr(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 iy(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2579
+ ${i?jg(i,e):w}
2580
+ ${s?Gg(s,e):w}
2581
+ `}const pd={CHILD:2},hd=e=>(...t)=>({_$litDirective$:e,values:t});let fd=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:Yg}=op,Lr=e=>e,Rr=()=>document.createComment(""),gn=(e,t,n)=>{var o;const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const a=i.insertBefore(Rr(),s),r=i.insertBefore(Rr(),s);n=new Yg(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 h=Lr(c).nextSibling;Lr(i).insertBefore(c,s),c=h}}}return n},mt=(e,t,n=e)=>(e._$AI(t,n),e),Xg={},Zg=(e,t=Xg)=>e._$AH=t,em=e=>e._$AH,Ws=e=>{e._$AR(),e._$AA.remove()};const Dr=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},tm=hd(class extends fd{constructor(e){if(super(e),e.type!==pd.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=em(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,h,d=0,p=s.length-1,g=0,x=o.length-1;for(;d<=p&&g<=x;)if(s[d]===null)d++;else if(s[p]===null)p--;else if(r[d]===a[g])l[g]=mt(s[d],o[g]),d++,g++;else if(r[p]===a[x])l[x]=mt(s[p],o[x]),p--,x--;else if(r[d]===a[x])l[x]=mt(s[d],o[x]),gn(e,l[x+1],s[d]),d++,x--;else if(r[p]===a[g])l[g]=mt(s[p],o[g]),gn(e,s[d],s[p]),p--,g++;else if(c===void 0&&(c=Dr(a,g,x),h=Dr(r,d,p)),c.has(r[d]))if(c.has(r[p])){const S=h.get(a[g]),T=S!==void 0?s[S]:null;if(T===null){const f=gn(e,s[d]);mt(f,o[g]),l[g]=f}else l[g]=mt(T,o[g]),gn(e,s[d],T),s[S]=null;g++}else Ws(s[p]),p--;else Ws(s[d]),d++;for(;g<=x;){const S=gn(e,l[x+1]);mt(S,o[g]),l[g++]=S}for(;d<=p;){const S=s[d++];S!==null&&Ws(S)}return this.ut=a,Zg(e,l),lt}});class Eo extends fd{constructor(t){if(super(t),this.it=w,t.type!==pd.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===lt)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:[]}}}Eo.directiveName="unsafeHTML",Eo.resultType=1;const zi=hd(Eo);const{entries:gd,setPrototypeOf:Br,isFrozen:nm,getPrototypeOf:im,getOwnPropertyDescriptor:sm}=Object;let{freeze:ye,seal:$e,create:To}=Object,{apply:_o,construct:Mo}=typeof Reflect<"u"&&Reflect;ye||(ye=function(t){return t});$e||($e=function(t){return t});_o||(_o=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)});Mo||(Mo=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 fi=ve(Array.prototype.forEach),om=ve(Array.prototype.lastIndexOf),Nr=ve(Array.prototype.pop),mn=ve(Array.prototype.push),am=ve(Array.prototype.splice),Ci=ve(String.prototype.toLowerCase),Ks=ve(String.prototype.toString),zs=ve(String.prototype.match),yn=ve(String.prototype.replace),rm=ve(String.prototype.indexOf),lm=ve(String.prototype.trim),xe=ve(Object.prototype.hasOwnProperty),ge=ve(RegExp.prototype.test),vn=cm(TypeError);function ve(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 _o(e,t,i)}}function cm(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Mo(e,n)}}function K(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ci;Br&&Br(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&(nm(t)||(t[i]=o),s=o)}e[s]=!0}return e}function dm(e){for(let t=0;t<e.length;t++)xe(e,t)||(e[t]=null);return e}function Re(e){const t=To(null);for(const[n,i]of gd(e))xe(e,n)&&(Array.isArray(i)?t[n]=dm(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Re(i):t[n]=i);return t}function bn(e,t){for(;e!==null;){const i=sm(e,t);if(i){if(i.get)return ve(i.get);if(typeof i.value=="function")return ve(i.value)}e=im(e)}function n(){return null}return n}const Or=ye(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),qs=ye(["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"]),Hs=ye(["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"]),um=ye(["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"]),js=ye(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),pm=ye(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Fr=ye(["#text"]),Ur=ye(["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"]),Gs=ye(["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"]),Wr=ye(["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"]),gi=ye(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),hm=$e(/\{\{[\w\W]*|[\w\W]*\}\}/gm),fm=$e(/<%[\w\W]*|[\w\W]*%>/gm),gm=$e(/\$\{[\w\W]*/gm),mm=$e(/^data-[\-\w.\u00B7-\uFFFF]+$/),ym=$e(/^aria-[\-\w]+$/),md=$e(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),vm=$e(/^(?:\w+script|data):/i),bm=$e(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),yd=$e(/^html$/i),wm=$e(/^[a-z][.\w]*(-[.\w]+)+$/i);var Kr=Object.freeze({__proto__:null,ARIA_ATTR:ym,ATTR_WHITESPACE:bm,CUSTOM_ELEMENT:wm,DATA_ATTR:mm,DOCTYPE_NAME:yd,ERB_EXPR:fm,IS_ALLOWED_URI:md,IS_SCRIPT_OR_DATA:vm,MUSTACHE_EXPR:hm,TMPLIT_EXPR:gm});const wn={element:1,text:3,progressingInstruction:7,comment:8,document:9},km=function(){return typeof window>"u"?null:window},$m=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}},zr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function vd(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:km();const t=N=>vd(N);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==wn.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,s=i.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:r,Element:l,NodeFilter:c,NamedNodeMap:h=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:p,trustedTypes:g}=e,x=l.prototype,S=bn(x,"cloneNode"),T=bn(x,"remove"),f=bn(x,"nextSibling"),b=bn(x,"childNodes"),k=bn(x,"parentNode");if(typeof a=="function"){const N=n.createElement("template");N.content&&N.content.ownerDocument&&(n=N.content.ownerDocument)}let A,E="";const{implementation:M,createNodeIterator:P,createDocumentFragment:R,getElementsByTagName:F}=n,{importNode:H}=i;let z=zr();t.isSupported=typeof gd=="function"&&typeof k=="function"&&M&&M.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ke,ERB_EXPR:_e,TMPLIT_EXPR:Ke,DATA_ATTR:ms,ARIA_ATTR:ys,IS_SCRIPT_OR_DATA:vs,ATTR_WHITESPACE:Qn,CUSTOM_ELEMENT:bs}=Kr;let{IS_ALLOWED_URI:Jn}=Kr,te=null;const Yn=K({},[...Or,...qs,...Hs,...js,...Fr]);let ne=null;const Xn=K({},[...Ur,...Gs,...Wr,...gi]);let X=Object.seal(To(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}})),pt=null,dn=null;const tt=Object.seal(To(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Zn=!0,C=!0,I=!1,U=!0,W=!1,Z=!0,J=!1,fe=!1,nt=!1,Nt=!1,ei=!1,ti=!1,Ua=!0,Wa=!1;const Tu="user-content-";let ws=!0,un=!1,Ot={},Me=null;const ks=K({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ka=null;const za=K({},["audio","video","img","source","image","track"]);let $s=null;const qa=K({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ni="http://www.w3.org/1998/Math/MathML",ii="http://www.w3.org/2000/svg",ze="http://www.w3.org/1999/xhtml";let Ft=ze,xs=!1,Ss=null;const _u=K({},[ni,ii,ze],Ks);let si=K({},["mi","mo","mn","ms","mtext"]),oi=K({},["annotation-xml"]);const Mu=K({},["title","style","font","a","script"]);let pn=null;const Pu=["application/xhtml+xml","text/html"],Iu="text/html";let oe=null,Ut=null;const Lu=n.createElement("form"),Ha=function($){return $ instanceof RegExp||$ instanceof Function},As=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ut&&Ut===$)){if((!$||typeof $!="object")&&($={}),$=Re($),pn=Pu.indexOf($.PARSER_MEDIA_TYPE)===-1?Iu:$.PARSER_MEDIA_TYPE,oe=pn==="application/xhtml+xml"?Ks:Ci,te=xe($,"ALLOWED_TAGS")?K({},$.ALLOWED_TAGS,oe):Yn,ne=xe($,"ALLOWED_ATTR")?K({},$.ALLOWED_ATTR,oe):Xn,Ss=xe($,"ALLOWED_NAMESPACES")?K({},$.ALLOWED_NAMESPACES,Ks):_u,$s=xe($,"ADD_URI_SAFE_ATTR")?K(Re(qa),$.ADD_URI_SAFE_ATTR,oe):qa,Ka=xe($,"ADD_DATA_URI_TAGS")?K(Re(za),$.ADD_DATA_URI_TAGS,oe):za,Me=xe($,"FORBID_CONTENTS")?K({},$.FORBID_CONTENTS,oe):ks,pt=xe($,"FORBID_TAGS")?K({},$.FORBID_TAGS,oe):Re({}),dn=xe($,"FORBID_ATTR")?K({},$.FORBID_ATTR,oe):Re({}),Ot=xe($,"USE_PROFILES")?$.USE_PROFILES:!1,Zn=$.ALLOW_ARIA_ATTR!==!1,C=$.ALLOW_DATA_ATTR!==!1,I=$.ALLOW_UNKNOWN_PROTOCOLS||!1,U=$.ALLOW_SELF_CLOSE_IN_ATTR!==!1,W=$.SAFE_FOR_TEMPLATES||!1,Z=$.SAFE_FOR_XML!==!1,J=$.WHOLE_DOCUMENT||!1,Nt=$.RETURN_DOM||!1,ei=$.RETURN_DOM_FRAGMENT||!1,ti=$.RETURN_TRUSTED_TYPE||!1,nt=$.FORCE_BODY||!1,Ua=$.SANITIZE_DOM!==!1,Wa=$.SANITIZE_NAMED_PROPS||!1,ws=$.KEEP_CONTENT!==!1,un=$.IN_PLACE||!1,Jn=$.ALLOWED_URI_REGEXP||md,Ft=$.NAMESPACE||ze,si=$.MATHML_TEXT_INTEGRATION_POINTS||si,oi=$.HTML_INTEGRATION_POINTS||oi,X=$.CUSTOM_ELEMENT_HANDLING||{},$.CUSTOM_ELEMENT_HANDLING&&Ha($.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(X.tagNameCheck=$.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$.CUSTOM_ELEMENT_HANDLING&&Ha($.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(X.attributeNameCheck=$.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$.CUSTOM_ELEMENT_HANDLING&&typeof $.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(X.allowCustomizedBuiltInElements=$.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),W&&(C=!1),ei&&(Nt=!0),Ot&&(te=K({},Fr),ne=[],Ot.html===!0&&(K(te,Or),K(ne,Ur)),Ot.svg===!0&&(K(te,qs),K(ne,Gs),K(ne,gi)),Ot.svgFilters===!0&&(K(te,Hs),K(ne,Gs),K(ne,gi)),Ot.mathMl===!0&&(K(te,js),K(ne,Wr),K(ne,gi))),$.ADD_TAGS&&(typeof $.ADD_TAGS=="function"?tt.tagCheck=$.ADD_TAGS:(te===Yn&&(te=Re(te)),K(te,$.ADD_TAGS,oe))),$.ADD_ATTR&&(typeof $.ADD_ATTR=="function"?tt.attributeCheck=$.ADD_ATTR:(ne===Xn&&(ne=Re(ne)),K(ne,$.ADD_ATTR,oe))),$.ADD_URI_SAFE_ATTR&&K($s,$.ADD_URI_SAFE_ATTR,oe),$.FORBID_CONTENTS&&(Me===ks&&(Me=Re(Me)),K(Me,$.FORBID_CONTENTS,oe)),$.ADD_FORBID_CONTENTS&&(Me===ks&&(Me=Re(Me)),K(Me,$.ADD_FORBID_CONTENTS,oe)),ws&&(te["#text"]=!0),J&&K(te,["html","head","body"]),te.table&&(K(te,["tbody"]),delete pt.tbody),$.TRUSTED_TYPES_POLICY){if(typeof $.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=$.TRUSTED_TYPES_POLICY,E=A.createHTML("")}else A===void 0&&(A=$m(g,s)),A!==null&&typeof E=="string"&&(E=A.createHTML(""));ye&&ye($),Ut=$}},ja=K({},[...qs,...Hs,...um]),Ga=K({},[...js,...pm]),Ru=function($){let _=k($);(!_||!_.tagName)&&(_={namespaceURI:Ft,tagName:"template"});const B=Ci($.tagName),Y=Ci(_.tagName);return Ss[$.namespaceURI]?$.namespaceURI===ii?_.namespaceURI===ze?B==="svg":_.namespaceURI===ni?B==="svg"&&(Y==="annotation-xml"||si[Y]):!!ja[B]:$.namespaceURI===ni?_.namespaceURI===ze?B==="math":_.namespaceURI===ii?B==="math"&&oi[Y]:!!Ga[B]:$.namespaceURI===ze?_.namespaceURI===ii&&!oi[Y]||_.namespaceURI===ni&&!si[Y]?!1:!Ga[B]&&(Mu[B]||!ja[B]):!!(pn==="application/xhtml+xml"&&Ss[$.namespaceURI]):!1},Pe=function($){mn(t.removed,{element:$});try{k($).removeChild($)}catch{T($)}},ht=function($,_){try{mn(t.removed,{attribute:_.getAttributeNode($),from:_})}catch{mn(t.removed,{attribute:null,from:_})}if(_.removeAttribute($),$==="is")if(Nt||ei)try{Pe(_)}catch{}else try{_.setAttribute($,"")}catch{}},Va=function($){let _=null,B=null;if(nt)$="<remove></remove>"+$;else{const se=zs($,/^[\r\n\t ]+/);B=se&&se[0]}pn==="application/xhtml+xml"&&Ft===ze&&($='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$+"</body></html>");const Y=A?A.createHTML($):$;if(Ft===ze)try{_=new p().parseFromString(Y,pn)}catch{}if(!_||!_.documentElement){_=M.createDocument(Ft,"template",null);try{_.documentElement.innerHTML=xs?E:Y}catch{}}const de=_.body||_.documentElement;return $&&B&&de.insertBefore(n.createTextNode(B),de.childNodes[0]||null),Ft===ze?F.call(_,J?"html":"body")[0]:J?_.documentElement:de},Qa=function($){return P.call($.ownerDocument||$,$,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Cs=function($){return $ instanceof d&&(typeof $.nodeName!="string"||typeof $.textContent!="string"||typeof $.removeChild!="function"||!($.attributes instanceof h)||typeof $.removeAttribute!="function"||typeof $.setAttribute!="function"||typeof $.namespaceURI!="string"||typeof $.insertBefore!="function"||typeof $.hasChildNodes!="function")},Ja=function($){return typeof r=="function"&&$ instanceof r};function qe(N,$,_){fi(N,B=>{B.call(t,$,_,Ut)})}const Ya=function($){let _=null;if(qe(z.beforeSanitizeElements,$,null),Cs($))return Pe($),!0;const B=oe($.nodeName);if(qe(z.uponSanitizeElement,$,{tagName:B,allowedTags:te}),Z&&$.hasChildNodes()&&!Ja($.firstElementChild)&&ge(/<[/\w!]/g,$.innerHTML)&&ge(/<[/\w!]/g,$.textContent)||$.nodeType===wn.progressingInstruction||Z&&$.nodeType===wn.comment&&ge(/<[/\w]/g,$.data))return Pe($),!0;if(!(tt.tagCheck instanceof Function&&tt.tagCheck(B))&&(!te[B]||pt[B])){if(!pt[B]&&Za(B)&&(X.tagNameCheck instanceof RegExp&&ge(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B)))return!1;if(ws&&!Me[B]){const Y=k($)||$.parentNode,de=b($)||$.childNodes;if(de&&Y){const se=de.length;for(let be=se-1;be>=0;--be){const He=S(de[be],!0);He.__removalCount=($.__removalCount||0)+1,Y.insertBefore(He,f($))}}}return Pe($),!0}return $ instanceof l&&!Ru($)||(B==="noscript"||B==="noembed"||B==="noframes")&&ge(/<\/no(script|embed|frames)/i,$.innerHTML)?(Pe($),!0):(W&&$.nodeType===wn.text&&(_=$.textContent,fi([ke,_e,Ke],Y=>{_=yn(_,Y," ")}),$.textContent!==_&&(mn(t.removed,{element:$.cloneNode()}),$.textContent=_)),qe(z.afterSanitizeElements,$,null),!1)},Xa=function($,_,B){if(Ua&&(_==="id"||_==="name")&&(B in n||B in Lu))return!1;if(!(C&&!dn[_]&&ge(ms,_))){if(!(Zn&&ge(ys,_))){if(!(tt.attributeCheck instanceof Function&&tt.attributeCheck(_,$))){if(!ne[_]||dn[_]){if(!(Za($)&&(X.tagNameCheck instanceof RegExp&&ge(X.tagNameCheck,$)||X.tagNameCheck instanceof Function&&X.tagNameCheck($))&&(X.attributeNameCheck instanceof RegExp&&ge(X.attributeNameCheck,_)||X.attributeNameCheck instanceof Function&&X.attributeNameCheck(_,$))||_==="is"&&X.allowCustomizedBuiltInElements&&(X.tagNameCheck instanceof RegExp&&ge(X.tagNameCheck,B)||X.tagNameCheck instanceof Function&&X.tagNameCheck(B))))return!1}else if(!$s[_]){if(!ge(Jn,yn(B,Qn,""))){if(!((_==="src"||_==="xlink:href"||_==="href")&&$!=="script"&&rm(B,"data:")===0&&Ka[$])){if(!(I&&!ge(vs,yn(B,Qn,"")))){if(B)return!1}}}}}}}return!0},Za=function($){return $!=="annotation-xml"&&zs($,bs)},er=function($){qe(z.beforeSanitizeAttributes,$,null);const{attributes:_}=$;if(!_||Cs($))return;const B={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let Y=_.length;for(;Y--;){const de=_[Y],{name:se,namespaceURI:be,value:He}=de,Wt=oe(se),Es=He;let re=se==="value"?Es:lm(Es);if(B.attrName=Wt,B.attrValue=re,B.keepAttr=!0,B.forceKeepAttr=void 0,qe(z.uponSanitizeAttribute,$,B),re=B.attrValue,Wa&&(Wt==="id"||Wt==="name")&&(ht(se,$),re=Tu+re),Z&&ge(/((--!?|])>)|<\/(style|title|textarea)/i,re)){ht(se,$);continue}if(Wt==="attributename"&&zs(re,"href")){ht(se,$);continue}if(B.forceKeepAttr)continue;if(!B.keepAttr){ht(se,$);continue}if(!U&&ge(/\/>/i,re)){ht(se,$);continue}W&&fi([ke,_e,Ke],nr=>{re=yn(re,nr," ")});const tr=oe($.nodeName);if(!Xa(tr,Wt,re)){ht(se,$);continue}if(A&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!be)switch(g.getAttributeType(tr,Wt)){case"TrustedHTML":{re=A.createHTML(re);break}case"TrustedScriptURL":{re=A.createScriptURL(re);break}}if(re!==Es)try{be?$.setAttributeNS(be,se,re):$.setAttribute(se,re),Cs($)?Pe($):Nr(t.removed)}catch{ht(se,$)}}qe(z.afterSanitizeAttributes,$,null)},Du=function N($){let _=null;const B=Qa($);for(qe(z.beforeSanitizeShadowDOM,$,null);_=B.nextNode();)qe(z.uponSanitizeShadowNode,_,null),Ya(_),er(_),_.content instanceof o&&N(_.content);qe(z.afterSanitizeShadowDOM,$,null)};return t.sanitize=function(N){let $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},_=null,B=null,Y=null,de=null;if(xs=!N,xs&&(N="<!-->"),typeof N!="string"&&!Ja(N))if(typeof N.toString=="function"){if(N=N.toString(),typeof N!="string")throw vn("dirty is not a string, aborting")}else throw vn("toString is not a function");if(!t.isSupported)return N;if(fe||As($),t.removed=[],typeof N=="string"&&(un=!1),un){if(N.nodeName){const He=oe(N.nodeName);if(!te[He]||pt[He])throw vn("root node is forbidden and cannot be sanitized in-place")}}else if(N instanceof r)_=Va("<!---->"),B=_.ownerDocument.importNode(N,!0),B.nodeType===wn.element&&B.nodeName==="BODY"||B.nodeName==="HTML"?_=B:_.appendChild(B);else{if(!Nt&&!W&&!J&&N.indexOf("<")===-1)return A&&ti?A.createHTML(N):N;if(_=Va(N),!_)return Nt?null:ti?E:""}_&&nt&&Pe(_.firstChild);const se=Qa(un?N:_);for(;Y=se.nextNode();)Ya(Y),er(Y),Y.content instanceof o&&Du(Y.content);if(un)return N;if(Nt){if(ei)for(de=R.call(_.ownerDocument);_.firstChild;)de.appendChild(_.firstChild);else de=_;return(ne.shadowroot||ne.shadowrootmode)&&(de=H.call(i,de,!0)),de}let be=J?_.outerHTML:_.innerHTML;return J&&te["!doctype"]&&_.ownerDocument&&_.ownerDocument.doctype&&_.ownerDocument.doctype.name&&ge(yd,_.ownerDocument.doctype.name)&&(be="<!DOCTYPE "+_.ownerDocument.doctype.name+`>
2582
+ `+be),W&&fi([ke,_e,Ke],He=>{be=yn(be,He," ")}),A&&ti?A.createHTML(be):be},t.setConfig=function(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};As(N),fe=!0},t.clearConfig=function(){Ut=null,fe=!1},t.isValidAttribute=function(N,$,_){Ut||As({});const B=oe(N),Y=oe($);return Xa(B,Y,_)},t.addHook=function(N,$){typeof $=="function"&&mn(z[N],$)},t.removeHook=function(N,$){if($!==void 0){const _=om(z[N],$);return _===-1?void 0:am(z[N],_,1)[0]}return Nr(z[N])},t.removeHooks=function(N){z[N]=[]},t.removeAllHooks=function(){z=zr()},t}var Po=vd();function $a(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Dt=$a();function bd(e){Dt=e}var In={exec:()=>null};function j(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(s,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(me.caret,"$1"),n=n.replace(s,a),i},getRegex:()=>new RegExp(n,t)};return i}var xm=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),me={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")},Sm=/^(?:[ \t]*(?:\n|$))+/,Am=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Cm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Gn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Em=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,xa=/(?:[*+-]|\d{1,9}[.)])/,wd=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,kd=j(wd).replace(/bull/g,xa).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(),Tm=j(wd).replace(/bull/g,xa).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(),Sa=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,_m=/^[^\n]+/,Aa=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Mm=j(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Aa).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pm=j(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,xa).getRegex(),ds="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",Ca=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Im=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",Ca).replace("tag",ds).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),$d=j(Sa).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ds).getRegex(),Lm=j(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",$d).getRegex(),Ea={blockquote:Lm,code:Am,def:Mm,fences:Cm,heading:Em,hr:Gn,html:Im,lheading:kd,list:Pm,newline:Sm,paragraph:$d,table:In,text:_m},qr=j("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ds).getRegex(),Rm={...Ea,lheading:Tm,table:qr,paragraph:j(Sa).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",qr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ds).getRegex()},Dm={...Ea,html:j(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ca).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:In,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:j(Sa).replace("hr",Gn).replace("heading",` *#{1,6} *[^
2583
+ ]`).replace("lheading",kd).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Bm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Nm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,xd=/^( {2,}|\\)\n(?!\s*$)/,Om=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,us=/[\p{P}\p{S}]/u,Ta=/[\s\p{P}\p{S}]/u,Sd=/[^\s\p{P}\p{S}]/u,Fm=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ta).getRegex(),Ad=/(?!~)[\p{P}\p{S}]/u,Um=/(?!~)[\s\p{P}\p{S}]/u,Wm=/(?:[^\s\p{P}\p{S}]|~)/u,Km=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",xm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Cd=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,zm=j(Cd,"u").replace(/punct/g,us).getRegex(),qm=j(Cd,"u").replace(/punct/g,Ad).getRegex(),Ed="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Hm=j(Ed,"gu").replace(/notPunctSpace/g,Sd).replace(/punctSpace/g,Ta).replace(/punct/g,us).getRegex(),jm=j(Ed,"gu").replace(/notPunctSpace/g,Wm).replace(/punctSpace/g,Um).replace(/punct/g,Ad).getRegex(),Gm=j("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Sd).replace(/punctSpace/g,Ta).replace(/punct/g,us).getRegex(),Vm=j(/\\(punct)/,"gu").replace(/punct/g,us).getRegex(),Qm=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(),Jm=j(Ca).replace("(?:-->|$)","-->").getRegex(),Ym=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",Jm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),qi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Xm=j(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",qi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Td=j(/^!?\[(label)\]\[(ref)\]/).replace("label",qi).replace("ref",Aa).getRegex(),_d=j(/^!?\[(ref)\](?:\[\])?/).replace("ref",Aa).getRegex(),Zm=j("reflink|nolink(?!\\()","g").replace("reflink",Td).replace("nolink",_d).getRegex(),Hr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,_a={_backpedal:In,anyPunctuation:Vm,autolink:Qm,blockSkip:Km,br:xd,code:Nm,del:In,emStrongLDelim:zm,emStrongRDelimAst:Hm,emStrongRDelimUnd:Gm,escape:Bm,link:Xm,nolink:_d,punctuation:Fm,reflink:Td,reflinkSearch:Zm,tag:Ym,text:Om,url:In},ey={..._a,link:j(/^!?\[(label)\]\((.*?)\)/).replace("label",qi).getRegex(),reflink:j(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",qi).getRegex()},Io={..._a,emStrongRDelimAst:jm,emStrongLDelim:qm,url:j(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Hr).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",Hr).getRegex()},ty={...Io,br:j(xd).replace("{2,}","*").getRegex(),text:j(Io.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},mi={normal:Ea,gfm:Rm,pedantic:Dm},kn={normal:_a,gfm:Io,breaks:ty,pedantic:ey},ny={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},jr=e=>ny[e];function Ve(e,t){if(t){if(me.escapeTest.test(e))return e.replace(me.escapeReplace,jr)}else if(me.escapeTestNoEncode.test(e))return e.replace(me.escapeReplaceNoEncode,jr);return e}function Gr(e){try{e=encodeURI(e).replace(me.percentDecode,"%")}catch{return null}return e}function Vr(e,t){var o;let n=e.replace(me.findPipe,(a,r,l)=>{let c=!1,h=r;for(;--h>=0&&l[h]==="\\";)c=!c;return c?"|":" |"}),i=n.split(me.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(me.slashPipe,"|");return i}function $n(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 iy(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 Qr(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 sy(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2586
2584
  `).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(`
2587
- `)}var qi=class{constructor(e){q(this,"options");q(this,"rules");q(this,"lexer");this.options=e||Rt}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:$n(n,`
2588
- `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=iy(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=$n(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:$n(t[0],`
2585
+ `)}var Hi=class{constructor(e){q(this,"options");q(this,"rules");q(this,"lexer");this.options=e||Dt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:$n(n,`
2586
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=sy(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=$n(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:$n(t[0],`
2589
2587
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=$n(t[0],`
2590
2588
  `).split(`
2591
2589
  `),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(`
2592
2590
  `),h=c.replace(this.rules.other.blockquoteSetextReplace,`
2593
2591
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
2594
2592
  ${c}`:c,s=s?`${s}
2595
- ${h}`:h;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,o,!0),this.lexer.state.top=d,n.length===0)break;let p=o.at(-1);if((p==null?void 0:p.type)==="code")break;if((p==null?void 0:p.type)==="blockquote"){let v=p,S=v.raw+`
2593
+ ${h}`:h;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,o,!0),this.lexer.state.top=d,n.length===0)break;let p=o.at(-1);if((p==null?void 0:p.type)==="code")break;if((p==null?void 0:p.type)==="blockquote"){let g=p,x=g.raw+`
2596
2594
  `+n.join(`
2597
- `),x=this.blockquote(S);o[o.length-1]=x,i=i.substring(0,i.length-v.raw.length)+x.raw,s=s.substring(0,s.length-v.text.length)+x.text;break}else if((p==null?void 0:p.type)==="list"){let v=p,S=v.raw+`
2595
+ `),S=this.blockquote(x);o[o.length-1]=S,i=i.substring(0,i.length-g.raw.length)+S.raw,s=s.substring(0,s.length-g.text.length)+S.text;break}else if((p==null?void 0:p.type)==="list"){let g=p,x=g.raw+`
2598
2596
  `+n.join(`
2599
- `),x=this.list(S);o[o.length-1]=x,i=i.substring(0,i.length-p.raw.length)+x.raw,s=s.substring(0,s.length-v.raw.length)+x.raw,n=S.substring(o.at(-1).raw.length).split(`
2600
- `);continue}}return{type:"blockquote",raw:i,tokens:o,text:s}}}list(e){var n,i;let t=this.rules.block.list.exec(e);if(t){let s=t[1].trim(),o=s.length>1,a={type:"list",raw:"",ordered:o,start:o?+s.slice(0,-1):"",loose:!1,items:[]};s=o?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=o?s:"[*+-]");let r=this.rules.other.listItemRegex(s),l=!1;for(;e;){let h=!1,d="",p="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let v=t[2].split(`
2601
- `,1)[0].replace(this.rules.other.listReplaceTabs,f=>" ".repeat(3*f.length)),S=e.split(`
2602
- `,1)[0],x=!v.trim(),T=0;if(this.options.pedantic?(T=2,p=v.trimStart()):x?T=t[1].length+1:(T=t[2].search(this.rules.other.nonSpaceChar),T=T>4?1:T,p=v.slice(T),T+=t[1].length),x&&this.rules.other.blankLine.test(S)&&(d+=S+`
2603
- `,e=e.substring(S.length+1),h=!0),!h){let f=this.rules.other.nextBulletRegex(T),b=this.rules.other.hrRegex(T),k=this.rules.other.fencesBeginRegex(T),A=this.rules.other.headingBeginRegex(T),E=this.rules.other.htmlBeginRegex(T);for(;e;){let M=e.split(`
2604
- `,1)[0],P;if(S=M,this.options.pedantic?(S=S.replace(this.rules.other.listReplaceNesting," "),P=S):P=S.replace(this.rules.other.tabCharGlobal," "),k.test(S)||A.test(S)||E.test(S)||f.test(S)||b.test(S))break;if(P.search(this.rules.other.nonSpaceChar)>=T||!S.trim())p+=`
2605
- `+P.slice(T);else{if(x||v.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||k.test(v)||A.test(v)||b.test(v))break;p+=`
2606
- `+S}!x&&!S.trim()&&(x=!0),d+=M+`
2607
- `,e=e.substring(M.length+1),v=P.slice(T)}}a.loose||(l?a.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(l=!0)),a.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),a.raw+=d}let c=a.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;a.raw=a.raw.trimEnd();for(let h of a.items){if(this.lexer.state.top=!1,h.tokens=this.lexer.blockTokens(h.text,[]),h.task){if(h.text=h.text.replace(this.rules.other.listReplaceTask,""),((n=h.tokens[0])==null?void 0:n.type)==="text"||((i=h.tokens[0])==null?void 0:i.type)==="paragraph"){h.tokens[0].raw=h.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),h.tokens[0].text=h.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}}let d=this.rules.other.listTaskCheckbox.exec(h.raw);if(d){let p={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};h.checked=p.checked,a.loose?h.tokens[0]&&["paragraph","text"].includes(h.tokens[0].type)&&"tokens"in h.tokens[0]&&h.tokens[0].tokens?(h.tokens[0].raw=p.raw+h.tokens[0].raw,h.tokens[0].text=p.raw+h.tokens[0].text,h.tokens[0].tokens.unshift(p)):h.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):h.tokens.unshift(p)}}if(!a.loose){let d=h.tokens.filter(v=>v.type==="space"),p=d.length>0&&d.some(v=>this.rules.other.anyLine.test(v.raw));a.loose=p}}if(a.loose)for(let h of a.items){h.loose=!0;for(let d of h.tokens)d.type==="text"&&(d.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=Gr(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(`
2608
- `):[],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(Gr(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)===`
2609
- `?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=$n(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=ny(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)),Vr(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 Vr(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 h=[...i[0]][0].length,d=e.slice(0,s+i.index+h+a);if(Math.min(s,a)%2){let v=d.slice(1,-1);return{type:"em",raw:d,text:v,tokens:this.lexer.inlineTokens(v)}}let p=d.slice(2,-2);return{type:"strong",raw:d,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,i;return t[2]==="@"?(n=t[1],i="mailto:"+n):(n=t[1],i=n),{type:"link",raw:t[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n;let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=((n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Ae=class Io{constructor(t){q(this,"tokens");q(this,"options");q(this,"state");q(this,"inlineQueue");q(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Rt,this.options.tokenizer=this.options.tokenizer||new qi,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:me,block:gi.normal,inline:kn.normal};this.options.pedantic?(n.block=gi.pedantic,n.inline=kn.pedantic):this.options.gfm&&(n.block=gi.gfm,this.options.breaks?n.inline=kn.breaks:n.inline=kn.gfm),this.tokenizer.rules=n}static get rules(){return{block:gi,inline:kn}}static lex(t,n){return new Io(n).lex(t)}static lexInline(t,n){return new Io(n).inlineTokens(t)}lex(t){t=t.replace(me.carriageReturn,`
2597
+ `),S=this.list(x);o[o.length-1]=S,i=i.substring(0,i.length-p.raw.length)+S.raw,s=s.substring(0,s.length-g.raw.length)+S.raw,n=x.substring(o.at(-1).raw.length).split(`
2598
+ `);continue}}return{type:"blockquote",raw:i,tokens:o,text:s}}}list(e){var n,i;let t=this.rules.block.list.exec(e);if(t){let s=t[1].trim(),o=s.length>1,a={type:"list",raw:"",ordered:o,start:o?+s.slice(0,-1):"",loose:!1,items:[]};s=o?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=o?s:"[*+-]");let r=this.rules.other.listItemRegex(s),l=!1;for(;e;){let h=!1,d="",p="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let g=t[2].split(`
2599
+ `,1)[0].replace(this.rules.other.listReplaceTabs,f=>" ".repeat(3*f.length)),x=e.split(`
2600
+ `,1)[0],S=!g.trim(),T=0;if(this.options.pedantic?(T=2,p=g.trimStart()):S?T=t[1].length+1:(T=t[2].search(this.rules.other.nonSpaceChar),T=T>4?1:T,p=g.slice(T),T+=t[1].length),S&&this.rules.other.blankLine.test(x)&&(d+=x+`
2601
+ `,e=e.substring(x.length+1),h=!0),!h){let f=this.rules.other.nextBulletRegex(T),b=this.rules.other.hrRegex(T),k=this.rules.other.fencesBeginRegex(T),A=this.rules.other.headingBeginRegex(T),E=this.rules.other.htmlBeginRegex(T);for(;e;){let M=e.split(`
2602
+ `,1)[0],P;if(x=M,this.options.pedantic?(x=x.replace(this.rules.other.listReplaceNesting," "),P=x):P=x.replace(this.rules.other.tabCharGlobal," "),k.test(x)||A.test(x)||E.test(x)||f.test(x)||b.test(x))break;if(P.search(this.rules.other.nonSpaceChar)>=T||!x.trim())p+=`
2603
+ `+P.slice(T);else{if(S||g.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||k.test(g)||A.test(g)||b.test(g))break;p+=`
2604
+ `+x}!S&&!x.trim()&&(S=!0),d+=M+`
2605
+ `,e=e.substring(M.length+1),g=P.slice(T)}}a.loose||(l?a.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(l=!0)),a.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),a.raw+=d}let c=a.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;a.raw=a.raw.trimEnd();for(let h of a.items){if(this.lexer.state.top=!1,h.tokens=this.lexer.blockTokens(h.text,[]),h.task){if(h.text=h.text.replace(this.rules.other.listReplaceTask,""),((n=h.tokens[0])==null?void 0:n.type)==="text"||((i=h.tokens[0])==null?void 0:i.type)==="paragraph"){h.tokens[0].raw=h.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),h.tokens[0].text=h.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}}let d=this.rules.other.listTaskCheckbox.exec(h.raw);if(d){let p={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};h.checked=p.checked,a.loose?h.tokens[0]&&["paragraph","text"].includes(h.tokens[0].type)&&"tokens"in h.tokens[0]&&h.tokens[0].tokens?(h.tokens[0].raw=p.raw+h.tokens[0].raw,h.tokens[0].text=p.raw+h.tokens[0].text,h.tokens[0].tokens.unshift(p)):h.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):h.tokens.unshift(p)}}if(!a.loose){let d=h.tokens.filter(g=>g.type==="space"),p=d.length>0&&d.some(g=>this.rules.other.anyLine.test(g.raw));a.loose=p}}if(a.loose)for(let h of a.items){h.loose=!0;for(let d of h.tokens)d.type==="text"&&(d.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=Vr(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(`
2606
+ `):[],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(Vr(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)===`
2607
+ `?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=$n(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=iy(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)),Qr(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 Qr(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 h=[...i[0]][0].length,d=e.slice(0,s+i.index+h+a);if(Math.min(s,a)%2){let g=d.slice(1,-1);return{type:"em",raw:d,text:g,tokens:this.lexer.inlineTokens(g)}}let p=d.slice(2,-2);return{type:"strong",raw:d,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,i;return t[2]==="@"?(n=t[1],i="mailto:"+n):(n=t[1],i=n),{type:"link",raw:t[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n;let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=((n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Ae=class Lo{constructor(t){q(this,"tokens");q(this,"options");q(this,"state");q(this,"inlineQueue");q(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Dt,this.options.tokenizer=this.options.tokenizer||new Hi,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:me,block:mi.normal,inline:kn.normal};this.options.pedantic?(n.block=mi.pedantic,n.inline=kn.pedantic):this.options.gfm&&(n.block=mi.gfm,this.options.breaks?n.inline=kn.breaks:n.inline=kn.gfm),this.tokenizer.rules=n}static get rules(){return{block:mi,inline:kn}}static lex(t,n){return new Lo(n).lex(t)}static lexInline(t,n){return new Lo(n).inlineTokens(t)}lex(t){t=t.replace(me.carriageReturn,`
2610
2608
  `),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(me.tabCharGlobal," ").replace(me.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+=`
2611
2609
  `: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(`
2612
2610
  `)?"":`
@@ -2620,7 +2618,7 @@ ${h}`:h;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
2620
2618
  `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(r),i=l.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2621
2619
  `)?"":`
2622
2620
  `)+r.raw,c.text+=`
2623
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(r);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var l,c,h,d,p;let i=t,s=null;if(this.tokens.links){let v=Object.keys(this.tokens.links);if(v.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)v.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(i))!=null;)i=i.slice(0,s.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)o=s[2]?s[2].length:0,i=i.slice(0,s.index+o)+"["+"a".repeat(s[0].length-o-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);i=((c=(l=this.options.hooks)==null?void 0:l.emStrongMask)==null?void 0:c.call({lexer:this},i))??i;let a=!1,r="";for(;t;){a||(r=""),a=!1;let v;if((d=(h=this.options.extensions)==null?void 0:h.inline)!=null&&d.some(x=>(v=x.call({lexer:this},t,n))?(t=t.substring(v.raw.length),n.push(v),!0):!1))continue;if(v=this.tokenizer.escape(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.tag(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.link(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(v.raw.length);let x=n.at(-1);v.type==="text"&&(x==null?void 0:x.type)==="text"?(x.raw+=v.raw,x.text+=v.text):n.push(v);continue}if(v=this.tokenizer.emStrong(t,i,r)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.codespan(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.br(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.del(t)){t=t.substring(v.raw.length),n.push(v);continue}if(v=this.tokenizer.autolink(t)){t=t.substring(v.raw.length),n.push(v);continue}if(!this.state.inLink&&(v=this.tokenizer.url(t))){t=t.substring(v.raw.length),n.push(v);continue}let S=t;if((p=this.options.extensions)!=null&&p.startInline){let x=1/0,T=t.slice(1),f;this.options.extensions.startInline.forEach(b=>{f=b.call({lexer:this},T),typeof f=="number"&&f>=0&&(x=Math.min(x,f))}),x<1/0&&x>=0&&(S=t.substring(0,x+1))}if(v=this.tokenizer.inlineText(S)){t=t.substring(v.raw.length),v.raw.slice(-1)!=="_"&&(r=v.raw.slice(-1)),a=!0;let x=n.at(-1);(x==null?void 0:x.type)==="text"?(x.raw+=v.raw,x.text+=v.text):n.push(v);continue}if(t){let x="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(x);break}else throw new Error(x)}}return n}},Hi=class{constructor(e){q(this,"options");q(this,"parser");this.options=e||Rt}space(e){return""}code({text:e,lang:t,escaped:n}){var o;let i=(o=(t||"").match(me.notSpaceStart))==null?void 0:o[0],s=e.replace(me.endingNewline,"")+`
2621
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(r);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var l,c,h,d,p;let i=t,s=null;if(this.tokens.links){let g=Object.keys(this.tokens.links);if(g.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)g.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(i))!=null;)i=i.slice(0,s.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)o=s[2]?s[2].length:0,i=i.slice(0,s.index+o)+"["+"a".repeat(s[0].length-o-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);i=((c=(l=this.options.hooks)==null?void 0:l.emStrongMask)==null?void 0:c.call({lexer:this},i))??i;let a=!1,r="";for(;t;){a||(r=""),a=!1;let g;if((d=(h=this.options.extensions)==null?void 0:h.inline)!=null&&d.some(S=>(g=S.call({lexer:this},t,n))?(t=t.substring(g.raw.length),n.push(g),!0):!1))continue;if(g=this.tokenizer.escape(t)){t=t.substring(g.raw.length),n.push(g);continue}if(g=this.tokenizer.tag(t)){t=t.substring(g.raw.length),n.push(g);continue}if(g=this.tokenizer.link(t)){t=t.substring(g.raw.length),n.push(g);continue}if(g=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(g.raw.length);let S=n.at(-1);g.type==="text"&&(S==null?void 0:S.type)==="text"?(S.raw+=g.raw,S.text+=g.text):n.push(g);continue}if(g=this.tokenizer.emStrong(t,i,r)){t=t.substring(g.raw.length),n.push(g);continue}if(g=this.tokenizer.codespan(t)){t=t.substring(g.raw.length),n.push(g);continue}if(g=this.tokenizer.br(t)){t=t.substring(g.raw.length),n.push(g);continue}if(g=this.tokenizer.del(t)){t=t.substring(g.raw.length),n.push(g);continue}if(g=this.tokenizer.autolink(t)){t=t.substring(g.raw.length),n.push(g);continue}if(!this.state.inLink&&(g=this.tokenizer.url(t))){t=t.substring(g.raw.length),n.push(g);continue}let x=t;if((p=this.options.extensions)!=null&&p.startInline){let S=1/0,T=t.slice(1),f;this.options.extensions.startInline.forEach(b=>{f=b.call({lexer:this},T),typeof f=="number"&&f>=0&&(S=Math.min(S,f))}),S<1/0&&S>=0&&(x=t.substring(0,S+1))}if(g=this.tokenizer.inlineText(x)){t=t.substring(g.raw.length),g.raw.slice(-1)!=="_"&&(r=g.raw.slice(-1)),a=!0;let S=n.at(-1);(S==null?void 0:S.type)==="text"?(S.raw+=g.raw,S.text+=g.text):n.push(g);continue}if(t){let S="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(S);break}else throw new Error(S)}}return n}},ji=class{constructor(e){q(this,"options");q(this,"parser");this.options=e||Dt}space(e){return""}code({text:e,lang:t,escaped:n}){var o;let i=(o=(t||"").match(me.notSpaceStart))==null?void 0:o[0],s=e.replace(me.endingNewline,"")+`
2624
2622
  `;return i?'<pre><code class="language-'+Ve(i)+'">'+(n?s:Ve(s,!0))+`</code></pre>
2625
2623
  `:"<pre><code>"+(n?s:Ve(s,!0))+`</code></pre>
2626
2624
  `}blockquote({tokens:e}){return`<blockquote>
@@ -2638,26 +2636,26 @@ ${this.parser.parse(e)}</blockquote>
2638
2636
  `}tablerow({text:e}){return`<tr>
2639
2637
  ${e}</tr>
2640
2638
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
2641
- `}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>${Ve(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=jr(e);if(s===null)return i;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+Ve(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=jr(e);if(s===null)return Ve(n);e=s;let o=`<img src="${e}" alt="${n}"`;return t&&(o+=` title="${Ve(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ve(e.text)}},_a=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ce=class Lo{constructor(t){q(this,"options");q(this,"renderer");q(this,"textRenderer");this.options=t||Rt,this.options.renderer=this.options.renderer||new Hi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new _a}static parse(t,n){return new Lo(n).parse(t)}static parseInline(t,n){return new Lo(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}},$i,An=($i=class{constructor(e){q(this,"options");q(this,"block");this.options=e||Rt}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Ae.lex:Ae.lexInline}provideParser(){return this.block?Ce.parse:Ce.parseInline}},q($i,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),q($i,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),$i),sy=class{constructor(...e){q(this,"defaults",ka());q(this,"options",this.setOptions);q(this,"parse",this.parseMarkdown(!0));q(this,"parseInline",this.parseMarkdown(!1));q(this,"Parser",Ce);q(this,"Renderer",Hi);q(this,"TextRenderer",_a);q(this,"Lexer",Ae);q(this,"Tokenizer",qi);q(this,"Hooks",An);this.use(...e)}walkTokens(e,t){var i,s;let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let a=o;for(let r of a.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of a.rows)for(let l of r)n=n.concat(this.walkTokens(l.tokens,t));break}case"list":{let a=o;n=n.concat(this.walkTokens(a.items,t));break}default:{let a=o;(s=(i=this.defaults.extensions)==null?void 0:i.childTokens)!=null&&s[a.type]?this.defaults.extensions.childTokens[a.type].forEach(r=>{let l=a[r].flat(1/0);n=n.concat(this.walkTokens(l,t))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let o=t.renderers[s.name];o?t.renderers[s.name]=function(...a){let r=s.renderer.apply(this,a);return r===!1&&(r=o.apply(this,a)),r}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[s.level];o?o.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),i.extensions=t),n.renderer){let s=this.defaults.renderer||new Hi(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 h=r.apply(s,c);return h===!1&&(h=l.apply(s,c)),h||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new qi(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 h=r.apply(s,c);return h===!1&&(h=l.apply(s,c)),h}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new An;for(let o in n.hooks){if(!(o in s))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,r=n.hooks[a],l=s[a];An.passThroughHooks.has(o)?s[a]=c=>{if(this.defaults.async&&An.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await r.call(s,c);return l.call(s,d)})();let h=r.call(s,c);return l.call(s,h)}:s[a]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await r.apply(s,c);return d===!1&&(d=await l.apply(s,c)),d})();let h=r.apply(s,c);return h===!1&&(h=l.apply(s,c)),h}}i.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(a){let r=[];return r.push(o.call(this,a)),s&&(r=r.concat(s.call(this,a))),r}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ae.lex(e,t??this.defaults)}parser(e,t){return Ce.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let i={...n},s={...this.defaults,...i},o=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let a=s.hooks?await s.hooks.preprocess(t):t,r=await(s.hooks?await s.hooks.provideLexer():e?Ae.lex:Ae.lexInline)(a,s),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?Ce.parse:Ce.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?Ae.lex:Ae.lexInline)(t,s);s.hooks&&(a=s.hooks.processAllTokens(a)),s.walkTokens&&this.walkTokens(a,s.walkTokens);let r=(s.hooks?s.hooks.provideParser():e?Ce.parse:Ce.parseInline)(a,s);return s.hooks&&(r=s.hooks.postprocess(r)),r}catch(a){return o(a)}}}onError(e,t){return n=>{if(n.message+=`
2642
- Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Ve(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},Mt=new sy;function V(e,t){return Mt.parse(e,t)}V.options=V.setOptions=function(e){return Mt.setOptions(e),V.defaults=Mt.defaults,vd(V.defaults),V};V.getDefaults=ka;V.defaults=Rt;V.use=function(...e){return Mt.use(...e),V.defaults=Mt.defaults,vd(V.defaults),V};V.walkTokens=function(e,t){return Mt.walkTokens(e,t)};V.parseInline=Mt.parseInline;V.Parser=Ce;V.parser=Ce.parse;V.Renderer=Hi;V.TextRenderer=_a;V.Lexer=Ae;V.lexer=Ae.lex;V.Tokenizer=qi;V.Hooks=An;V.parse=V;V.options;V.setOptions;V.use;V.walkTokens;V.parseInline;Ce.parse;Ae.lex;V.setOptions({gfm:!0,breaks:!0,mangle:!1});const Qr=["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"],Jr=["class","href","rel","target","title","start"];let Yr=!1;const oy=14e4,ay=4e4,ry=200,Gs=5e4,wt=new Map;function ly(e){const t=wt.get(e);return t===void 0?null:(wt.delete(e),wt.set(e,t),t)}function Xr(e,t){if(wt.set(e,t),wt.size<=ry)return;const n=wt.keys().next().value;n&&wt.delete(n)}function cy(){Yr||(Yr=!0,Mo.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function ji(e){const t=e.trim();if(!t)return"";if(cy(),t.length<=Gs){const a=ly(t);if(a!==null)return a}const n=Gl(t,oy),i=n.truncated?`
2639
+ `}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>${Ve(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=Gr(e);if(s===null)return i;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+Ve(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=Gr(e);if(s===null)return Ve(n);e=s;let o=`<img src="${e}" alt="${n}"`;return t&&(o+=` title="${Ve(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ve(e.text)}},Ma=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ce=class Ro{constructor(t){q(this,"options");q(this,"renderer");q(this,"textRenderer");this.options=t||Dt,this.options.renderer=this.options.renderer||new ji,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ma}static parse(t,n){return new Ro(n).parse(t)}static parseInline(t,n){return new Ro(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}},xi,An=(xi=class{constructor(e){q(this,"options");q(this,"block");this.options=e||Dt}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Ae.lex:Ae.lexInline}provideParser(){return this.block?Ce.parse:Ce.parseInline}},q(xi,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),q(xi,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),xi),oy=class{constructor(...e){q(this,"defaults",$a());q(this,"options",this.setOptions);q(this,"parse",this.parseMarkdown(!0));q(this,"parseInline",this.parseMarkdown(!1));q(this,"Parser",Ce);q(this,"Renderer",ji);q(this,"TextRenderer",Ma);q(this,"Lexer",Ae);q(this,"Tokenizer",Hi);q(this,"Hooks",An);this.use(...e)}walkTokens(e,t){var i,s;let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let a=o;for(let r of a.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of a.rows)for(let l of r)n=n.concat(this.walkTokens(l.tokens,t));break}case"list":{let a=o;n=n.concat(this.walkTokens(a.items,t));break}default:{let a=o;(s=(i=this.defaults.extensions)==null?void 0:i.childTokens)!=null&&s[a.type]?this.defaults.extensions.childTokens[a.type].forEach(r=>{let l=a[r].flat(1/0);n=n.concat(this.walkTokens(l,t))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let o=t.renderers[s.name];o?t.renderers[s.name]=function(...a){let r=s.renderer.apply(this,a);return r===!1&&(r=o.apply(this,a)),r}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[s.level];o?o.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),i.extensions=t),n.renderer){let s=this.defaults.renderer||new ji(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 h=r.apply(s,c);return h===!1&&(h=l.apply(s,c)),h||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Hi(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 h=r.apply(s,c);return h===!1&&(h=l.apply(s,c)),h}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new An;for(let o in n.hooks){if(!(o in s))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,r=n.hooks[a],l=s[a];An.passThroughHooks.has(o)?s[a]=c=>{if(this.defaults.async&&An.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await r.call(s,c);return l.call(s,d)})();let h=r.call(s,c);return l.call(s,h)}:s[a]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await r.apply(s,c);return d===!1&&(d=await l.apply(s,c)),d})();let h=r.apply(s,c);return h===!1&&(h=l.apply(s,c)),h}}i.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(a){let r=[];return r.push(o.call(this,a)),s&&(r=r.concat(s.call(this,a))),r}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ae.lex(e,t??this.defaults)}parser(e,t){return Ce.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let i={...n},s={...this.defaults,...i},o=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let a=s.hooks?await s.hooks.preprocess(t):t,r=await(s.hooks?await s.hooks.provideLexer():e?Ae.lex:Ae.lexInline)(a,s),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?Ce.parse:Ce.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?Ae.lex:Ae.lexInline)(t,s);s.hooks&&(a=s.hooks.processAllTokens(a)),s.walkTokens&&this.walkTokens(a,s.walkTokens);let r=(s.hooks?s.hooks.provideParser():e?Ce.parse:Ce.parseInline)(a,s);return s.hooks&&(r=s.hooks.postprocess(r)),r}catch(a){return o(a)}}}onError(e,t){return n=>{if(n.message+=`
2640
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Ve(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},Pt=new oy;function V(e,t){return Pt.parse(e,t)}V.options=V.setOptions=function(e){return Pt.setOptions(e),V.defaults=Pt.defaults,bd(V.defaults),V};V.getDefaults=$a;V.defaults=Dt;V.use=function(...e){return Pt.use(...e),V.defaults=Pt.defaults,bd(V.defaults),V};V.walkTokens=function(e,t){return Pt.walkTokens(e,t)};V.parseInline=Pt.parseInline;V.Parser=Ce;V.parser=Ce.parse;V.Renderer=ji;V.TextRenderer=Ma;V.Lexer=Ae;V.lexer=Ae.lex;V.Tokenizer=Hi;V.Hooks=An;V.parse=V;V.options;V.setOptions;V.use;V.walkTokens;V.parseInline;Ce.parse;Ae.lex;V.setOptions({gfm:!0,breaks:!0,mangle:!1});const Jr=["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"],Yr=["class","href","rel","target","title","start"];let Xr=!1;const ay=14e4,ry=4e4,ly=200,Vs=5e4,kt=new Map;function cy(e){const t=kt.get(e);return t===void 0?null:(kt.delete(e),kt.set(e,t),t)}function Zr(e,t){if(kt.set(e,t),kt.size<=ly)return;const n=kt.keys().next().value;n&&kt.delete(n)}function dy(){Xr||(Xr=!0,Po.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function Gi(e){const t=e.trim();if(!t)return"";if(dy(),t.length<=Vs){const a=cy(t);if(a!==null)return a}const n=Vl(t,ay),i=n.truncated?`
2643
2641
 
2644
- … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>ay){const r=`<pre class="code-block">${dy(`${n.text}${i}`)}</pre>`,l=Mo.sanitize(r,{ALLOWED_TAGS:Qr,ALLOWED_ATTR:Jr});return t.length<=Gs&&Xr(t,l),l}const s=V.parse(`${n.text}${i}`),o=Mo.sanitize(s,{ALLOWED_TAGS:Qr,ALLOWED_ATTR:Jr});return t.length<=Gs&&Xr(t,o),o}function dy(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const uy=1500,py=2e3,_d="Copy as markdown",hy="Copied",fy="Copy failed";async function gy(e){if(!e)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return!1}}}function mi(e,t){e.title=t,e.setAttribute("aria-label",t)}function my(e){const t=e.label??_d;return u`
2642
+ … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>ry){const r=`<pre class="code-block">${uy(`${n.text}${i}`)}</pre>`,l=Po.sanitize(r,{ALLOWED_TAGS:Jr,ALLOWED_ATTR:Yr});return t.length<=Vs&&Zr(t,l),l}const s=V.parse(`${n.text}${i}`),o=Po.sanitize(s,{ALLOWED_TAGS:Jr,ALLOWED_ATTR:Yr});return t.length<=Vs&&Zr(t,o),o}function uy(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const py=1500,hy=2e3,Md="Copy as markdown",fy="Copied",gy="Copy failed";async function my(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 yi(e,t){e.title=t,e.setAttribute("aria-label",t)}function yy(e){const t=e.label??Md;return u`
2645
2643
  <button
2646
2644
  class="chat-copy-btn"
2647
2645
  type="button"
2648
2646
  title=${t}
2649
2647
  aria-label=${t}
2650
- @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 gy(e.text());if(i.isConnected){if(delete i.dataset.copying,i.removeAttribute("aria-busy"),i.disabled=!1,!s){i.dataset.error="1",mi(i,fy),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.error,mi(i,t))},py);return}i.dataset.copied="1",mi(i,hy),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.copied,mi(i,t))},uy)}}}
2648
+ @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 my(e.text());if(i.isConnected){if(delete i.dataset.copying,i.removeAttribute("aria-busy"),i.disabled=!1,!s){i.dataset.error="1",yi(i,gy),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.error,yi(i,t))},hy);return}i.dataset.copied="1",yi(i,fy),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.copied,yi(i,t))},py)}}}
2651
2649
  >
2652
2650
  <span class="chat-copy-btn__icon" aria-hidden="true">
2653
2651
  <span class="chat-copy-btn__icon-copy">${L.copy}</span>
2654
2652
  <span class="chat-copy-btn__icon-check">${L.check}</span>
2655
2653
  </span>
2656
2654
  </button>
2657
- `}function yy(e){return my({text:()=>e,label:_d})}function vy(e){const t=e,n=by(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:wy(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=ky(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(Xl(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=Vl(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function by(e){return Array.isArray(e)?e.filter(Boolean):[]}function wy(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 ky(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const Vs=40,Qs=new Map;async function $y(e){const t=Qs.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/Vs),l=[];for(let d=0;d<Vs;d++){let p=0;const v=d*r,S=Math.min(v+r,a.length);for(let x=v;x<S;x++){const T=Math.abs(a[x]);T>p&&(p=T)}l.push(p)}const c=Math.max(...l,.01),h=l.map(d=>Math.max(d/c,.08));return Qs.set(e,h),n.close(),h}catch{const n=Array.from(e).reduce((s,o)=>(s<<5)-s+o.charCodeAt(0)|0,0),i=[];for(let s=0;s<Vs;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return Qs.set(e,i),i}}const Js=[1,1.5,2],Gi=new Map;function xy(e){let t=Gi.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:[]},Gi.set(e,t),$y(e).then(i=>{t.waveform=i,Md(e)}),t}const Ln="http://www.w3.org/2000/svg";function Sy(){const e=document.createElementNS(Ln,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Ln,"polygon");return t.setAttribute("points","6,3 20,12 6,21"),e.appendChild(t),e}function Ay(){const e=document.createElementNS(Ln,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Ln,"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(Ln,"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=Gi.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)}Rn(t,n)}}function Rn(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?Vi(t.currentTime):Vi(t.duration))}function Ys(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?Ay():Sy();i?n.replaceChild(s,i):n.appendChild(s)}function Vi(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 Zr=new Set;function Cy(e){if(Zr.has(e))return;Zr.add(e);const t=Gi.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=qt(e);i&&Rn(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=qt(e);i&&Rn(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=qt(e);i&&(Rn(i,t),Ys(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=qt(e);i&&Ys(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=qt(e);i&&Ys(i,!0)})}function Ey(e,t){const n=xy(e);Cy(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const l=Js.indexOf(n.speed),c=Js[(l+1)%Js.length];n.speed=c,n.audio.playbackRate=c;const h=r.target.closest(".vnp__speed");h&&(h.textContent=`${c}×`)},o=r=>{r.stopPropagation();const l=r.target.closest(".vnp__waveform");if(!l)return;const c=l.getBoundingClientRect(),h=Math.max(0,Math.min(1,(r.clientX-c.left)/c.width));if(n.duration>0){n.audio.currentTime=h*n.duration,n.currentTime=n.audio.currentTime;const d=l.closest(".vnp");d&&Rn(d,n)}},a=n.playing||n.currentTime>0?Vi(n.currentTime):Vi(n.duration);return queueMicrotask(()=>Md(e)),u`
2655
+ `}function vy(e){return yy({text:()=>e,label:Md})}function by(e){const t=e,n=wy(t.content),i=[];for(const s of n){const o=String(s.type??"").toLowerCase();(["toolcall","tool_call","tooluse","tool_use"].includes(o)||typeof s.name=="string"&&s.arguments!=null)&&i.push({kind:"call",name:s.name??"tool",args:ky(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const a=$y(s),r=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:r,text:a})}if(Zl(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=Ql(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function wy(e){return Array.isArray(e)?e.filter(Boolean):[]}function ky(e){if(typeof e!="string")return e;const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function $y(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}const Qs=40,Js=new Map;async function xy(e){const t=Js.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/Qs),l=[];for(let d=0;d<Qs;d++){let p=0;const g=d*r,x=Math.min(g+r,a.length);for(let S=g;S<x;S++){const T=Math.abs(a[S]);T>p&&(p=T)}l.push(p)}const c=Math.max(...l,.01),h=l.map(d=>Math.max(d/c,.08));return Js.set(e,h),n.close(),h}catch{const n=Array.from(e).reduce((s,o)=>(s<<5)-s+o.charCodeAt(0)|0,0),i=[];for(let s=0;s<Qs;s++){const o=Math.abs((n*(s+1)*9301+49297)%233280/233280);i.push(.15+o*.85)}return Js.set(e,i),i}}const Ys=[1,1.5,2],Vi=new Map;function Sy(e){let t=Vi.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:[]},Vi.set(e,t),xy(e).then(i=>{t.waveform=i,Pd(e)}),t}const Ln="http://www.w3.org/2000/svg";function Ay(){const e=document.createElementNS(Ln,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Ln,"polygon");return t.setAttribute("points","6,3 20,12 6,21"),e.appendChild(t),e}function Cy(){const e=document.createElementNS(Ln,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","currentColor");const t=document.createElementNS(Ln,"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(Ln,"rect");return n.setAttribute("x","15"),n.setAttribute("y","3"),n.setAttribute("width","4"),n.setAttribute("height","18"),n.setAttribute("rx","1"),e.append(t,n),e}function Ht(e){return document.querySelector(`.vnp[data-url="${CSS.escape(e)}"]`)}function Pd(e){const t=Ht(e);if(!t)return;const n=Vi.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)}Rn(t,n)}}function Rn(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?Qi(t.currentTime):Qi(t.duration))}function Xs(e,t){const n=e.querySelector(".vnp__play");if(!n)return;const i=n.querySelector("svg"),s=t?Cy():Ay();i?n.replaceChild(s,i):n.appendChild(s)}function Qi(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 el=new Set;function Ey(e){if(el.has(e))return;el.add(e);const t=Vi.get(e);if(!t)return;const{audio:n}=t;n.addEventListener("loadedmetadata",()=>{t.duration=n.duration;const i=Ht(e);i&&Rn(i,t)}),n.addEventListener("timeupdate",()=>{t.currentTime=n.currentTime;const i=Ht(e);i&&Rn(i,t)}),n.addEventListener("ended",()=>{t.playing=!1,n.currentTime=0,t.currentTime=0;const i=Ht(e);i&&(Rn(i,t),Xs(i,!1))}),n.addEventListener("pause",()=>{t.playing=!1;const i=Ht(e);i&&Xs(i,!1)}),n.addEventListener("play",()=>{t.playing=!0;const i=Ht(e);i&&Xs(i,!0)})}function Ty(e,t){const n=Sy(e);Ey(e);const i=r=>{r.stopPropagation(),n.playing?n.audio.pause():n.audio.play()},s=r=>{r.stopPropagation();const l=Ys.indexOf(n.speed),c=Ys[(l+1)%Ys.length];n.speed=c,n.audio.playbackRate=c;const h=r.target.closest(".vnp__speed");h&&(h.textContent=`${c}×`)},o=r=>{r.stopPropagation();const l=r.target.closest(".vnp__waveform");if(!l)return;const c=l.getBoundingClientRect(),h=Math.max(0,Math.min(1,(r.clientX-c.left)/c.width));if(n.duration>0){n.audio.currentTime=h*n.duration,n.currentTime=n.audio.currentTime;const d=l.closest(".vnp");d&&Rn(d,n)}},a=n.playing||n.currentTime>0?Qi(n.currentTime):Qi(n.duration);return queueMicrotask(()=>Pd(e)),u`
2658
2656
  <div class="vnp" data-url=${e} @click=${r=>r.stopPropagation()}>
2659
2657
  <button class="vnp__play" @click=${i} aria-label=${n.playing?"Pause":"Play"}>
2660
- ${n.playing?_y():Ty()}
2658
+ ${n.playing?My():_y()}
2661
2659
  </button>
2662
2660
 
2663
2661
  <div class="vnp__body">
@@ -2670,7 +2668,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2670
2668
  </div>
2671
2669
  </div>
2672
2670
  </div>
2673
- `}function Ty(){return u`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function _y(){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 My(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",h=l.startsWith("data:")?l:`data:${c};base64,${l}`;i.push({url:h})}else if(typeof a.data=="string"&&a.data){const r=a.data,l=a.mimeType||a.media_type||"image/png",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 Py(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 Iy(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Ly(e){return u`
2671
+ `}function _y(){return u`<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21" /></svg>`}function My(){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 Py(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",h=l.startsWith("data:")?l:`data:${c};base64,${l}`;i.push({url:h})}else if(typeof a.data=="string"&&a.data){const r=a.data,l=a.mimeType||a.media_type||"image/png",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 Iy(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 Ly(e){return e==="application/pdf"?"📄":e.startsWith("audio/")?"🎵":"📎"}function Ry(e){return u`
2674
2672
  <div class="chat-group assistant">
2675
2673
  <div class="chat-group-messages">
2676
2674
  <div class="chat-bubble chat-reading-indicator" aria-hidden="true">
@@ -2680,30 +2678,30 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2680
2678
  </div>
2681
2679
  </div>
2682
2680
  </div>
2683
- `}function Ry(e){return u`
2681
+ `}function Dy(e){return u`
2684
2682
  <div class="chat-group assistant">
2685
2683
  <div class="chat-group-messages">
2686
2684
  <div class="chat-interim fade-in">
2687
- ${Ki(ji(e))}
2685
+ ${zi(Gi(e))}
2688
2686
  </div>
2689
2687
  </div>
2690
2688
  </div>
2691
- `}function Dy(e,t,n,i){return u`
2689
+ `}function By(e,t,n,i){return u`
2692
2690
  <div class="chat-group assistant">
2693
2691
  <div class="chat-group-messages">
2694
- ${Pd({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
2692
+ ${Id({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
2695
2693
  </div>
2696
2694
  </div>
2697
- `}function By(e,t){const n=Yl(e.role),i=n==="user"?"user":n==="assistant"?"assistant":"other",s=new Date(e.timestamp).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"});return u`
2695
+ `}function Ny(e,t){const n=Xl(e.role),i=n==="user"?"user":n==="assistant"?"assistant":"other",s=new Date(e.timestamp).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"});return u`
2698
2696
  <div class="chat-group ${i}">
2699
2697
  <div class="chat-group-messages">
2700
- ${e.messages.map((o,a)=>Pd(o.message,{isStreaming:e.isStreaming&&a===e.messages.length-1,showReasoning:t.showReasoning}))}
2698
+ ${e.messages.map((o,a)=>Id(o.message,{isStreaming:e.isStreaming&&a===e.messages.length-1,showReasoning:t.showReasoning}))}
2701
2699
  <div class="chat-group-footer">
2702
2700
  <span class="chat-group-timestamp">${s}</span>
2703
2701
  </div>
2704
2702
  </div>
2705
2703
  </div>
2706
- `}function Ny(e){return e.length===0?w:u`
2704
+ `}function Oy(e){return e.length===0?w:u`
2707
2705
  <div class="chat-message-images">
2708
2706
  ${e.map(t=>u`
2709
2707
  <img
@@ -2714,12 +2712,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2714
2712
  />
2715
2713
  `)}
2716
2714
  </div>
2717
- `}function Oy(e){return e.length===0?w:u`
2715
+ `}function Fy(e){return e.length===0?w:u`
2718
2716
  <div class="chat-message-files">
2719
- ${e.map(t=>t.mimeType==="application/pdf"?Uy(t):t.mimeType.startsWith("audio/")?Ey(t.url,t.name):Wy(t))}
2717
+ ${e.map(t=>t.mimeType==="application/pdf"?Wy(t):t.mimeType.startsWith("audio/")?Ty(t.url,t.name):Ky(t))}
2720
2718
  </div>
2721
- `}function Fy(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 h=document.createElementNS("http://www.w3.org/2000/svg","line");h.setAttribute("x1","6"),h.setAttribute("y1","6"),h.setAttribute("x2","18"),h.setAttribute("y2","18"),l.append(c,h),r.appendChild(l),s.append(o,a,r);const d=document.createElement("iframe");d.className="chat-pdf-modal__frame",d.src=e,d.title=t,i.append(s,d),n.appendChild(i),n.addEventListener("click",p=>{p.target===n&&n.remove()}),r.addEventListener("click",()=>n.remove()),document.body.appendChild(n)}function Uy(e){return u`
2722
- <div class="chat-pdf-preview" @click=${()=>Fy(e.url,e.name)}>
2719
+ `}function Uy(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 h=document.createElementNS("http://www.w3.org/2000/svg","line");h.setAttribute("x1","6"),h.setAttribute("y1","6"),h.setAttribute("x2","18"),h.setAttribute("y2","18"),l.append(c,h),r.appendChild(l),s.append(o,a,r);const d=document.createElement("iframe");d.className="chat-pdf-modal__frame",d.src=e,d.title=t,i.append(s,d),n.appendChild(i),n.addEventListener("click",p=>{p.target===n&&n.remove()}),r.addEventListener("click",()=>n.remove()),document.body.appendChild(n)}function Wy(e){return u`
2720
+ <div class="chat-pdf-preview" @click=${()=>Uy(e.url,e.name)}>
2723
2721
  <iframe
2724
2722
  src=${e.url}
2725
2723
  class="chat-pdf-preview__frame"
@@ -2733,39 +2731,39 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2733
2731
  @click=${t=>t.stopPropagation()}
2734
2732
  >${e.name}</a>
2735
2733
  </div>
2736
- `}function Wy(e){return u`
2734
+ `}function Ky(e){return u`
2737
2735
  <a
2738
2736
  class="chat-file-card"
2739
2737
  href=${e.url}
2740
2738
  target="_blank"
2741
2739
  rel="noreferrer noopener"
2742
2740
  >
2743
- <span class="chat-file-card__icon">${Iy(e.mimeType)}</span>
2741
+ <span class="chat-file-card__icon">${Ly(e.mimeType)}</span>
2744
2742
  <span class="chat-file-card__name">${e.name}</span>
2745
2743
  </a>
2746
- `}function Pd(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=Xl(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=vy(e).length>0,l=My(e),c=l.length>0,h=Py(e),d=h.length>0,p=Vl(e),v=t.showReasoning&&s==="assistant"?_p(e):null,S=p!=null&&p.trim()?p:null,x=v?Pp(v):null,T=S,f=(s==="assistant"||s==="user")&&!!(T!=null&&T.trim()),b=["chat-bubble",f?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!T&&(r||o)||!T&&!c&&!d?w:u`
2744
+ `}function Id(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=Zl(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",r=by(e).length>0,l=Py(e),c=l.length>0,h=Iy(e),d=h.length>0,p=Ql(e),g=t.showReasoning&&s==="assistant"?Mp(e):null,x=p!=null&&p.trim()?p:null,S=g?Ip(g):null,T=x,f=(s==="assistant"||s==="user")&&!!(T!=null&&T.trim()),b=["chat-bubble",f?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!T&&(r||o)||!T&&!c&&!d?w:u`
2747
2745
  <div class="${b}">
2748
- ${f?yy(T):w}
2749
- ${Ny(l)}
2750
- ${Oy(h)}
2751
- ${x?u`<div class="chat-thinking">${Ki(ji(x))}</div>`:w}
2752
- ${T?u`<div class="chat-text">${Ki(ji(T))}</div>`:w}
2746
+ ${f?vy(T):w}
2747
+ ${Oy(l)}
2748
+ ${Fy(h)}
2749
+ ${S?u`<div class="chat-thinking">${zi(Gi(S))}</div>`:w}
2750
+ ${T?u`<div class="chat-text">${zi(Gi(T))}</div>`:w}
2753
2751
  </div>
2754
- `}const O={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let G=null,xt=null,St=!1;function el(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}function yt(){if(O.timerId&&(clearInterval(O.timerId),O.timerId=null),O.stream){for(const e of O.stream.getTracks())e.stop();O.stream=null}xt&&(clearTimeout(xt),xt=null),Qi(),O.mediaRecorder=null,O.audioChunks=[],O.active=!1,O.cancelled=!1,St=!1}async function Id(e){var t;try{if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))return console.warn("[voice] getUserMedia unavailable (requires secure context)"),yt(),!1;const n=await navigator.mediaDevices.getUserMedia({audio:!0});O.stream=n;const i=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"",s=i?new MediaRecorder(n,{mimeType:i}):new MediaRecorder(n);return O.mediaRecorder=s,O.audioChunks=[],O.mode=e,O.startTime=Date.now(),O.elapsed=0,O.active=!0,O.cancelled=!1,s.ondataavailable=o=>{o.data.size>0&&O.audioChunks.push(o.data)},s.onstop=()=>{if(O.cancelled){yt(),G==null||G.onRequestRender();return}const o=new Blob(O.audioChunks,{type:s.mimeType});if(o.size===0){yt(),G==null||G.onRequestRender();return}const a=new FileReader;a.onload=()=>{const r=a.result,l=s.mimeType.includes("mp4")?"m4a":"webm",c={id:ss(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${l}`};yt(),G==null||G.onSend(c),G==null||G.onRequestRender()},a.onerror=()=>{yt(),G==null||G.onRequestRender()},a.readAsDataURL(o)},s.start(250),O.timerId=setInterval(()=>{O.elapsed=Math.floor((Date.now()-O.startTime)/1e3),G==null||G.onRequestRender()},1e3),G==null||G.onRequestRender(),!0}catch(n){return console.warn("[voice] startRecording failed:",n),yt(),!1}}function Ld(){!O.active||!O.mediaRecorder||(O.cancelled=!1,O.mediaRecorder.state==="recording"&&O.mediaRecorder.stop())}function Rd(){!O.active||!O.mediaRecorder||(O.cancelled=!0,O.mediaRecorder.state==="recording"?O.mediaRecorder.stop():(yt(),G==null||G.onRequestRender()))}function Ky(){document.addEventListener("pointerup",Dd)}function Qi(){document.removeEventListener("pointerup",Dd)}function Dd(e){if(!St&&!O.active){Qi();return}if(St=!1,Qi(),xt&&(clearTimeout(xt),xt=null,!O.active)){Id("tap");return}O.active&&O.mode==="hold"&&(O.cancelled?Rd():Ld()),e.preventDefault()}function zy(e){O.active||(St=!0,O.startX=e.clientX,Ky(),xt=setTimeout(async()=>{if(!St)return;await Id("hold")||(St=!1,Qi())},300))}function tl(e){if(!O.active||O.mode!=="hold"||!St)return;const t=O.startX-e.clientX;t>80?(O.cancelled=!0,G==null||G.onRequestRender()):O.cancelled&&t<=60&&(O.cancelled=!1,G==null||G.onRequestRender())}function qy(){return O.active}function Hy(e){G=e}function jy(e){return u`
2752
+ `}const O={active:!1,mode:"tap",startTime:0,elapsed:0,mediaRecorder:null,audioChunks:[],stream:null,timerId:null,startX:0,cancelled:!1};let G=null,St=null,At=!1;function tl(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}function vt(){if(O.timerId&&(clearInterval(O.timerId),O.timerId=null),O.stream){for(const e of O.stream.getTracks())e.stop();O.stream=null}St&&(clearTimeout(St),St=null),Ji(),O.mediaRecorder=null,O.audioChunks=[],O.active=!1,O.cancelled=!1,At=!1}async function Ld(e){var t;try{if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))return console.warn("[voice] getUserMedia unavailable (requires secure context)"),vt(),!1;const n=await navigator.mediaDevices.getUserMedia({audio:!0});O.stream=n;const i=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"",s=i?new MediaRecorder(n,{mimeType:i}):new MediaRecorder(n);return O.mediaRecorder=s,O.audioChunks=[],O.mode=e,O.startTime=Date.now(),O.elapsed=0,O.active=!0,O.cancelled=!1,s.ondataavailable=o=>{o.data.size>0&&O.audioChunks.push(o.data)},s.onstop=()=>{if(O.cancelled){vt(),G==null||G.onRequestRender();return}const o=new Blob(O.audioChunks,{type:s.mimeType});if(o.size===0){vt(),G==null||G.onRequestRender();return}const a=new FileReader;a.onload=()=>{const r=a.result,l=s.mimeType.includes("mp4")?"m4a":"webm",c={id:os(),dataUrl:r,mimeType:s.mimeType||"audio/webm",fileName:`voice-note-${Date.now()}.${l}`};vt(),G==null||G.onSend(c),G==null||G.onRequestRender()},a.onerror=()=>{vt(),G==null||G.onRequestRender()},a.readAsDataURL(o)},s.start(250),O.timerId=setInterval(()=>{O.elapsed=Math.floor((Date.now()-O.startTime)/1e3),G==null||G.onRequestRender()},1e3),G==null||G.onRequestRender(),!0}catch(n){return console.warn("[voice] startRecording failed:",n),vt(),!1}}function Rd(){!O.active||!O.mediaRecorder||(O.cancelled=!1,O.mediaRecorder.state==="recording"&&O.mediaRecorder.stop())}function Dd(){!O.active||!O.mediaRecorder||(O.cancelled=!0,O.mediaRecorder.state==="recording"?O.mediaRecorder.stop():(vt(),G==null||G.onRequestRender()))}function zy(){document.addEventListener("pointerup",Bd)}function Ji(){document.removeEventListener("pointerup",Bd)}function Bd(e){if(!At&&!O.active){Ji();return}if(At=!1,Ji(),St&&(clearTimeout(St),St=null,!O.active)){Ld("tap");return}O.active&&O.mode==="hold"&&(O.cancelled?Dd():Rd()),e.preventDefault()}function qy(e){O.active||(At=!0,O.startX=e.clientX,zy(),St=setTimeout(async()=>{if(!At)return;await Ld("hold")||(At=!1,Ji())},300))}function nl(e){if(!O.active||O.mode!=="hold"||!At)return;const t=O.startX-e.clientX;t>80?(O.cancelled=!0,G==null||G.onRequestRender()):O.cancelled&&t<=60&&(O.cancelled=!1,G==null||G.onRequestRender())}function Hy(){return O.active}function jy(e){G=e}function Gy(e){return u`
2755
2753
  <button
2756
2754
  class="btn btn--icon chat-compose__mic"
2757
2755
  ?disabled=${!e}
2758
- @pointerdown=${zy}
2756
+ @pointerdown=${qy}
2759
2757
  aria-label="Record voice note"
2760
2758
  title="Tap to record, hold to send on release"
2761
2759
  >
2762
2760
  ${L.mic}
2763
2761
  </button>
2764
- `}function Gy(){return O.active?O.mode==="tap"?u`
2765
- <div class="chat-voice-recording" @pointermove=${tl}>
2762
+ `}function Vy(){return O.active?O.mode==="tap"?u`
2763
+ <div class="chat-voice-recording" @pointermove=${nl}>
2766
2764
  <button
2767
2765
  class="btn btn--icon chat-voice-recording__trash"
2768
- @click=${Rd}
2766
+ @click=${Dd}
2769
2767
  aria-label="Cancel recording"
2770
2768
  title="Discard"
2771
2769
  >
@@ -2773,11 +2771,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2773
2771
  </button>
2774
2772
  <div class="chat-voice-recording__indicator">
2775
2773
  <span class="chat-voice-recording__dot"></span>
2776
- <span class="chat-voice-recording__timer">${el(O.elapsed)}</span>
2774
+ <span class="chat-voice-recording__timer">${tl(O.elapsed)}</span>
2777
2775
  </div>
2778
2776
  <button
2779
2777
  class="btn btn--icon chat-voice-recording__send primary"
2780
- @click=${Ld}
2778
+ @click=${Rd}
2781
2779
  aria-label="Send voice note"
2782
2780
  title="Send"
2783
2781
  >
@@ -2785,16 +2783,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2785
2783
  </button>
2786
2784
  </div>
2787
2785
  `:u`
2788
- <div class="chat-voice-recording hold" @pointermove=${tl}>
2786
+ <div class="chat-voice-recording hold" @pointermove=${nl}>
2789
2787
  <div class="chat-voice-recording__indicator">
2790
2788
  <span class="chat-voice-recording__dot"></span>
2791
- <span class="chat-voice-recording__timer">${el(O.elapsed)}</span>
2789
+ <span class="chat-voice-recording__timer">${tl(O.elapsed)}</span>
2792
2790
  <span class="chat-voice-recording__slide ${O.cancelled?"cancelled":""}">
2793
2791
  ${O.cancelled?"Release to cancel":"← Slide to cancel"}
2794
2792
  </span>
2795
2793
  </div>
2796
2794
  </div>
2797
- `:w}function Vy(e){return u`
2795
+ `:w}function Qy(e){return u`
2798
2796
  <div class="sidebar-panel">
2799
2797
  <div class="sidebar-header">
2800
2798
  <div class="sidebar-title">Tool Output</div>
@@ -2808,10 +2806,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2808
2806
  <button @click=${e.onViewRawText} class="btn" style="margin-top: 12px;">
2809
2807
  View Raw Text
2810
2808
  </button>
2811
- `:e.content?u`<div class="sidebar-markdown">${Ki(ji(e.content))}</div>`:u`<div class="muted">No content available</div>`}
2809
+ `:e.content?u`<div class="sidebar-markdown">${zi(Gi(e.content))}</div>`:u`<div class="muted">No content available</div>`}
2812
2810
  </div>
2813
2811
  </div>
2814
- `}var Qy=Object.defineProperty,Jy=Object.getOwnPropertyDescriptor,us=(e,t,n,i)=>{for(var s=i>1?void 0:i?Jy(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&&Qy(t,n,s),s};let Yt=class extends Gt{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,s=(e.clientX-this.startX)/n;let o=this.startRatio+s;o=Math.max(this.minRatio,Math.min(this.maxRatio,o)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:o},bubbles:!0,composed:!0}))},this.handleMouseUp=()=>{this.isDragging=!1,this.classList.remove("dragging"),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}render(){return 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)}};Yt.styles=Uu`
2812
+ `}var Jy=Object.defineProperty,Yy=Object.getOwnPropertyDescriptor,ps=(e,t,n,i)=>{for(var s=i>1?void 0:i?Yy(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&&Jy(t,n,s),s};let Yt=class extends Gt{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,s=(e.clientX-this.startX)/n;let o=this.startRatio+s;o=Math.max(this.minRatio,Math.min(this.maxRatio,o)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:o},bubbles:!0,composed:!0}))},this.handleMouseUp=()=>{this.isDragging=!1,this.classList.remove("dragging"),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}render(){return 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)}};Yt.styles=Wu`
2815
2813
  :host {
2816
2814
  width: 4px;
2817
2815
  cursor: col-resize;
@@ -2837,21 +2835,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2837
2835
  :host(.dragging) {
2838
2836
  background: var(--accent, #007bff);
2839
2837
  }
2840
- `;us([ns({type:Number})],Yt.prototype,"splitRatio",2);us([ns({type:Number})],Yt.prototype,"minRatio",2);us([ns({type:Number})],Yt.prototype,"maxRatio",2);Yt=us([Ul("resizable-divider")],Yt);function yi(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function Xs(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const Yy=1,Xy=1,Dt="emoji",Xt="keyvalue",Ma="favorites",Zy="tokens",Bd="tokens",ev="unicode",Nd="count",tv="group",nv="order",Od="group-order",Ro="eTag",Ji="url",nl="skinTone",ln="readonly",Pa="readwrite",Fd="skinUnicodes",iv="skinUnicodes",sv="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",ov="en";function av(e,t){const n=new Set,i=[];for(const s of e){const o=t(s);n.has(o)||(n.add(o),i.push(s))}return i}function il(e){return av(e,t=>t.unicode)}function rv(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[a,[r,l]]of Object.entries(s))o.createIndex(a,r,{multiEntry:l});return o}t(Xt),t(Dt,ev,{[Bd]:[Zy,!0],[Od]:[[tv,nv]],[Fd]:[iv,!0]}),t(Ma,void 0,{[Nd]:[""]})}const Do={},Ci={},Yi={};function Ud(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function lv(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,Yy);Do[e]=s,s.onupgradeneeded=o=>{o.oldVersion<Xy&&rv(s.result)},Ud(n,i,s)});return t.onclose=()=>Ia(e),t}function cv(e){return Ci[e]||(Ci[e]=lv(e)),Ci[e]}function et(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 Ia(e){const t=Do[e],n=t&&t.result;if(n){n.close();const i=Yi[e];if(i)for(const s of i)s()}delete Do[e],delete Ci[e],delete Yi[e]}function dv(e){return new Promise((t,n)=>{Ia(e);const i=indexedDB.deleteDatabase(e);Ud(t,n,i)})}function uv(e,t){let n=Yi[e];n||(n=Yi[e]=[]),n.push(t)}const pv=new Set([":D","XD",":'D","O:)",":X",":P",";P","XP",":L",":Z",":j","8D","XO","8)",":B",":O",":S",":'o","Dx","X(","D:",":C",">0)",":3","</3","<3","\\M/",":E","8#"]);function Qt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||pv.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const hv=2;function Wd(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=hv)}function fv(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:l,emoji:c,version:h})=>{const d=[...new Set(Wd([...(a||[]).map(Qt).flat(),...(l||[]).map(Qt).flat(),...Qt(n),i]))].sort(),p={annotation:n,group:s,order:o,tags:l,tokens:d,unicode:c,version:h};if(i&&(p.emoticon=i),a&&(p.shortcodes=a),r){p.skinTones=[],p.skinUnicodes=[],p.skinVersions=[];for(const{tone:v,emoji:S,version:x}of r)p.skinTones.push(v),p.skinUnicodes.push(S),p.skinVersions.push(x)}return p})}function Kd(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function Pt(e,t,n){Kd(e,"get",t,n)}function zd(e,t,n){Kd(e,"getAll",t,n)}function La(e){e.commit&&e.commit()}function gv(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 qd(e,t){const n=gv(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 mv(e){return!await Ra(e,Xt,Ji)}async function yv(e,t,n){const[i,s]=await Promise.all([Ro,Ji].map(o=>Ra(e,Xt,o)));return i===n&&s===t}async function vv(e,t){return et(e,Dt,ln,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=l=>{const c=l.target.result;for(const h of c)if(a=h.unicode,t(h))return o(h);if(c.length<50)return o();r()}};r()})}async function Hd(e,t,n,i){{const s=fv(t);await et(e,[Dt,Xt],Pa,([o,a],r)=>{let l,c,h=0;function d(){++h===2&&p()}function p(){if(!(l===i&&c===n)){o.clear();for(const v of s)o.put(v);a.put(i,Ro),a.put(n,Ji),La(r)}}Pt(a,Ro,v=>{l=v,d()}),Pt(a,Ji,v=>{c=v,d()})})}}async function bv(e,t){return et(e,Dt,ln,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);zd(n.index(Od),o,s)})}async function jd(e,t){const n=Wd(Qt(t));return n.length?et(e,Dt,ln,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&l()},l=()=>{const c=qd(a,h=>h.unicode);o(c.sort((h,d)=>h.order<d.order?-1:1))};for(let c=0;c<n.length;c++){const h=n[c],d=c===n.length-1?IDBKeyRange.bound(h,h+"￿",!1,!0):IDBKeyRange.only(h);zd(i.index(Bd),d,p=>{a.push(p),r()})}}):[]}async function wv(e,t){const n=await jd(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await vv(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function kv(e,t){return et(e,Dt,ln,(n,i,s)=>Pt(n,t,o=>{if(o)return s(o);Pt(n.index(Fd),t,a=>s(a||null))}))}function Ra(e,t,n){return et(e,t,ln,(i,s,o)=>Pt(i,n,o))}function $v(e,t,n,i){return et(e,t,Pa,(s,o)=>{s.put(i,n),La(o)})}function xv(e,t){return et(e,Ma,Pa,(n,i)=>Pt(n,t,s=>{n.put((s||0)+1,t),La(i)}))}function Sv(e,t,n){return n===0?[]:et(e,[Ma,Dt],ln,([i,s],o,a)=>{const r=[];i.index(Nd).openCursor(void 0,"prev").onsuccess=l=>{const c=l.target.result;if(!c)return a(r);function h(v){if(r.push(v),r.length===n)return a(r);c.continue()}const d=c.primaryKey,p=t.byName(d);if(p)return h(p);Pt(s,d,v=>{if(v)return h(v);c.continue()})}})}const vi="";function Av(e,t){const n=new Map;for(const s of e){const o=t(s);for(const a of o){let r=n;for(let c=0;c<a.length;c++){const h=a.charAt(c);let d=r.get(h);d||(d=new Map,r.set(h,d)),r=d}let l=r.get(vi);l||(l=[],r.set(vi,l)),l.push(s)}}return(s,o)=>{let a=n;for(let c=0;c<s.length;c++){const h=s.charAt(c),d=a.get(h);if(d)a=d;else return[]}if(o)return a.get(vi)||[];const r=[],l=[a];for(;l.length;){const h=[...l.shift().entries()].sort((d,p)=>d[0]<p[0]?-1:1);for(const[d,p]of h)d===vi?r.push(...p):l.push(p)}return r}}const Cv=["name","url"];function Ev(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||Cv.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function sl(e){Ev(e);const t=(p,v)=>p.name.toLowerCase()<v.name.toLowerCase()?-1:1,n=e.sort(t),s=Av(e,p=>{const v=new Set;if(p.shortcodes)for(const S of p.shortcodes)for(const x of Qt(S))v.add(x);return v}),o=p=>s(p,!0),a=p=>s(p,!1),r=p=>{const v=Qt(p),S=v.map((x,T)=>(T<v.length-1?o:a)(x));return qd(S,x=>x.name).sort(t)},l=new Map,c=new Map;for(const p of e){c.set(p.name.toLowerCase(),p);for(const v of p.shortcodes||[])l.set(v.toLowerCase(),p)}return{all:n,search:r,byShortcode:p=>l.get(p.toLowerCase()),byName:p=>c.get(p.toLowerCase())}}const Tv=typeof wrappedJSObject<"u";function xn(e){if(!e)return e;if(Tv&&(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 Gd(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const _v=["annotation","emoji","group","order","version"];function Mv(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||_v.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function Vd(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Pv(e){const t=await fetch(e,{method:"HEAD"});Vd(t,e);const n=t.headers.get("etag");return Gd(n),n}async function Bo(e){const t=await fetch(e);Vd(t,e);const n=t.headers.get("etag");Gd(n);const i=await t.json();return Mv(i),[n,i]}function Iv(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Lv(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 Qd(e){const t=JSON.stringify(e);let n=Lv(t);const i=await crypto.subtle.digest("SHA-1",n),s=Iv(i);return btoa(s)}async function Rv(e,t){let n,i=await Pv(t);if(!i){const s=await Bo(t);i=s[0],n=s[1],i||(i=await Qd(n))}await yv(e,t,i)||(n||(n=(await Bo(t))[1]),await Hd(e,n,t,i))}async function Dv(e,t){let[n,i]=await Bo(t);n||(n=await Qd(i)),await Hd(e,i,t,n)}async function Bv(e,t){try{await Rv(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class Nv{constructor({dataSource:t=sv,locale:n=ov,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=sl(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await cv(this._dbName);uv(this._dbName,this._clear);const n=this.dataSource;await mv(t)?await Dv(t,n):this._lazyUpdate=Bv(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 Xs(t),await this.ready(),il(await bv(this._db,t)).map(xn)}async getEmojiBySearchQuery(t){yi(t),await this.ready();const n=this._custom.search(t),i=il(await jd(this._db,t)).map(xn);return[...n,...i]}async getEmojiByShortcode(t){yi(t),await this.ready();const n=this._custom.byShortcode(t);return n||xn(await wv(this._db,t))}async getEmojiByUnicodeOrName(t){yi(t),await this.ready();const n=this._custom.byName(t);return n||xn(await kv(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Ra(this._db,Xt,nl)||0}async setPreferredSkinTone(t){return Xs(t),await this.ready(),$v(this._db,Xt,nl,t)}async incrementFavoriteEmojiCount(t){return yi(t),await this.ready(),xv(this._db,t)}async getTopFavoriteEmoji(t){return Xs(t),await this.ready(),(await Sv(this._db,this._custom,t)).map(xn)}set customEmoji(t){this._custom=sl(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 Ia(this._dbName)}async delete(){await this._shutdown(),await dv(this._dbName)}}const No=[[-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})),Zs=No.slice(1),Ov=2,ol=6,Jd=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function al(e){return e.unicode.includes("‍")}const Fv={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},Uv=1e3,Wv="🖐️",Kv=8,zv=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],Yd='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',qv=(e,t)=>e<t?-1:e>t?1:0,rl=(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 ${Yd}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},Hv=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function jv(e){const t=rl(e,"#000"),n=rl(e,"#fff");return t&&n&&Hv(t,n)}function Gv(){const e=Object.entries(Fv);try{for(const[t,n]of e)if(jv(t))return n}catch{}return e[0][1]}let eo;const to=()=>(eo||(eo=new Promise(e=>Jd(()=>e(Gv())))),eo),Oo=new Map,Vv="️",Qv="\uD83C",Jv="‍",Yv=127995,Xv=57339;function Zv(e,t){if(t===0)return e;const n=e.indexOf(Jv);return n!==-1?e.substring(0,n)+String.fromCodePoint(Yv+t-1)+e.substring(n):(e.endsWith(Vv)&&(e=e.substring(0,e.length-1)),e+Qv+String.fromCodePoint(Xv+t-1))}function Le(e){e.preventDefault(),e.stopPropagation()}function no(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function Xd(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 eb(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 Ei=requestAnimationFrame;let tb=typeof ResizeObserver=="function";function nb(e,t,n){let i;tb?(i=new ResizeObserver(n),i.observe(e)):Ei(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function ll(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let io;function ib(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=ll(a);r===0&&(s=!0),typeof io>"u"&&(io=ll(t));const l=r/1.8<io;Oo.set(o.unicode,l),l||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
2838
+ `;ps([is({type:Number})],Yt.prototype,"splitRatio",2);ps([is({type:Number})],Yt.prototype,"minRatio",2);ps([is({type:Number})],Yt.prototype,"maxRatio",2);Yt=ps([Wl("resizable-divider")],Yt);function vi(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function Zs(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const Xy=1,Zy=1,Bt="emoji",Xt="keyvalue",Pa="favorites",ev="tokens",Nd="tokens",tv="unicode",Od="count",nv="group",iv="order",Fd="group-order",Do="eTag",Yi="url",il="skinTone",ln="readonly",Ia="readwrite",Ud="skinUnicodes",sv="skinUnicodes",ov="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",av="en";function rv(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 sl(e){return rv(e,t=>t.unicode)}function lv(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[a,[r,l]]of Object.entries(s))o.createIndex(a,r,{multiEntry:l});return o}t(Xt),t(Bt,tv,{[Nd]:[ev,!0],[Fd]:[[nv,iv]],[Ud]:[sv,!0]}),t(Pa,void 0,{[Od]:[""]})}const Bo={},Ei={},Xi={};function Wd(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function cv(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,Xy);Bo[e]=s,s.onupgradeneeded=o=>{o.oldVersion<Zy&&lv(s.result)},Wd(n,i,s)});return t.onclose=()=>La(e),t}function dv(e){return Ei[e]||(Ei[e]=cv(e)),Ei[e]}function et(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 La(e){const t=Bo[e],n=t&&t.result;if(n){n.close();const i=Xi[e];if(i)for(const s of i)s()}delete Bo[e],delete Ei[e],delete Xi[e]}function uv(e){return new Promise((t,n)=>{La(e);const i=indexedDB.deleteDatabase(e);Wd(t,n,i)})}function pv(e,t){let n=Xi[e];n||(n=Xi[e]=[]),n.push(t)}const hv=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 Qt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||hv.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const fv=2;function Kd(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=fv)}function gv(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:a,skins:r,tags:l,emoji:c,version:h})=>{const d=[...new Set(Kd([...(a||[]).map(Qt).flat(),...(l||[]).map(Qt).flat(),...Qt(n),i]))].sort(),p={annotation:n,group:s,order:o,tags:l,tokens:d,unicode:c,version:h};if(i&&(p.emoticon=i),a&&(p.shortcodes=a),r){p.skinTones=[],p.skinUnicodes=[],p.skinVersions=[];for(const{tone:g,emoji:x,version:S}of r)p.skinTones.push(g),p.skinUnicodes.push(x),p.skinVersions.push(S)}return p})}function zd(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function It(e,t,n){zd(e,"get",t,n)}function qd(e,t,n){zd(e,"getAll",t,n)}function Ra(e){e.commit&&e.commit()}function mv(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 Hd(e,t){const n=mv(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 yv(e){return!await Da(e,Xt,Yi)}async function vv(e,t,n){const[i,s]=await Promise.all([Do,Yi].map(o=>Da(e,Xt,o)));return i===n&&s===t}async function bv(e,t){return et(e,Bt,ln,(i,s,o)=>{let a;const r=()=>{i.getAll(a&&IDBKeyRange.lowerBound(a,!0),50).onsuccess=l=>{const c=l.target.result;for(const h of c)if(a=h.unicode,t(h))return o(h);if(c.length<50)return o();r()}};r()})}async function jd(e,t,n,i){{const s=gv(t);await et(e,[Bt,Xt],Ia,([o,a],r)=>{let l,c,h=0;function d(){++h===2&&p()}function p(){if(!(l===i&&c===n)){o.clear();for(const g of s)o.put(g);a.put(i,Do),a.put(n,Yi),Ra(r)}}It(a,Do,g=>{l=g,d()}),It(a,Yi,g=>{c=g,d()})})}}async function wv(e,t){return et(e,Bt,ln,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);qd(n.index(Fd),o,s)})}async function Gd(e,t){const n=Kd(Qt(t));return n.length?et(e,Bt,ln,(i,s,o)=>{const a=[],r=()=>{a.length===n.length&&l()},l=()=>{const c=Hd(a,h=>h.unicode);o(c.sort((h,d)=>h.order<d.order?-1:1))};for(let c=0;c<n.length;c++){const h=n[c],d=c===n.length-1?IDBKeyRange.bound(h,h+"￿",!1,!0):IDBKeyRange.only(h);qd(i.index(Nd),d,p=>{a.push(p),r()})}}):[]}async function kv(e,t){const n=await Gd(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await bv(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function $v(e,t){return et(e,Bt,ln,(n,i,s)=>It(n,t,o=>{if(o)return s(o);It(n.index(Ud),t,a=>s(a||null))}))}function Da(e,t,n){return et(e,t,ln,(i,s,o)=>It(i,n,o))}function xv(e,t,n,i){return et(e,t,Ia,(s,o)=>{s.put(i,n),Ra(o)})}function Sv(e,t){return et(e,Pa,Ia,(n,i)=>It(n,t,s=>{n.put((s||0)+1,t),Ra(i)}))}function Av(e,t,n){return n===0?[]:et(e,[Pa,Bt],ln,([i,s],o,a)=>{const r=[];i.index(Od).openCursor(void 0,"prev").onsuccess=l=>{const c=l.target.result;if(!c)return a(r);function h(g){if(r.push(g),r.length===n)return a(r);c.continue()}const d=c.primaryKey,p=t.byName(d);if(p)return h(p);It(s,d,g=>{if(g)return h(g);c.continue()})}})}const bi="";function Cv(e,t){const n=new Map;for(const s of e){const o=t(s);for(const a of o){let r=n;for(let c=0;c<a.length;c++){const h=a.charAt(c);let d=r.get(h);d||(d=new Map,r.set(h,d)),r=d}let l=r.get(bi);l||(l=[],r.set(bi,l)),l.push(s)}}return(s,o)=>{let a=n;for(let c=0;c<s.length;c++){const h=s.charAt(c),d=a.get(h);if(d)a=d;else return[]}if(o)return a.get(bi)||[];const r=[],l=[a];for(;l.length;){const h=[...l.shift().entries()].sort((d,p)=>d[0]<p[0]?-1:1);for(const[d,p]of h)d===bi?r.push(...p):l.push(p)}return r}}const Ev=["name","url"];function Tv(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||Ev.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function ol(e){Tv(e);const t=(p,g)=>p.name.toLowerCase()<g.name.toLowerCase()?-1:1,n=e.sort(t),s=Cv(e,p=>{const g=new Set;if(p.shortcodes)for(const x of p.shortcodes)for(const S of Qt(x))g.add(S);return g}),o=p=>s(p,!0),a=p=>s(p,!1),r=p=>{const g=Qt(p),x=g.map((S,T)=>(T<g.length-1?o:a)(S));return Hd(x,S=>S.name).sort(t)},l=new Map,c=new Map;for(const p of e){c.set(p.name.toLowerCase(),p);for(const g of p.shortcodes||[])l.set(g.toLowerCase(),p)}return{all:n,search:r,byShortcode:p=>l.get(p.toLowerCase()),byName:p=>c.get(p.toLowerCase())}}const _v=typeof wrappedJSObject<"u";function xn(e){if(!e)return e;if(_v&&(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 Vd(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Mv=["annotation","emoji","group","order","version"];function Pv(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Mv.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function Qd(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Iv(e){const t=await fetch(e,{method:"HEAD"});Qd(t,e);const n=t.headers.get("etag");return Vd(n),n}async function No(e){const t=await fetch(e);Qd(t,e);const n=t.headers.get("etag");Vd(n);const i=await t.json();return Pv(i),[n,i]}function Lv(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Rv(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 Jd(e){const t=JSON.stringify(e);let n=Rv(t);const i=await crypto.subtle.digest("SHA-1",n),s=Lv(i);return btoa(s)}async function Dv(e,t){let n,i=await Iv(t);if(!i){const s=await No(t);i=s[0],n=s[1],i||(i=await Jd(n))}await vv(e,t,i)||(n||(n=(await No(t))[1]),await jd(e,n,t,i))}async function Bv(e,t){let[n,i]=await No(t);n||(n=await Jd(i)),await jd(e,i,t,n)}async function Nv(e,t){try{await Dv(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class Ov{constructor({dataSource:t=ov,locale:n=av,customEmoji:i=[]}={}){this.dataSource=t,this.locale=n,this._dbName=`emoji-picker-element-${this.locale}`,this._db=void 0,this._lazyUpdate=void 0,this._custom=ol(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await dv(this._dbName);pv(this._dbName,this._clear);const n=this.dataSource;await yv(t)?await Bv(t,n):this._lazyUpdate=Nv(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 Zs(t),await this.ready(),sl(await wv(this._db,t)).map(xn)}async getEmojiBySearchQuery(t){vi(t),await this.ready();const n=this._custom.search(t),i=sl(await Gd(this._db,t)).map(xn);return[...n,...i]}async getEmojiByShortcode(t){vi(t),await this.ready();const n=this._custom.byShortcode(t);return n||xn(await kv(this._db,t))}async getEmojiByUnicodeOrName(t){vi(t),await this.ready();const n=this._custom.byName(t);return n||xn(await $v(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Da(this._db,Xt,il)||0}async setPreferredSkinTone(t){return Zs(t),await this.ready(),xv(this._db,Xt,il,t)}async incrementFavoriteEmojiCount(t){return vi(t),await this.ready(),Sv(this._db,t)}async getTopFavoriteEmoji(t){return Zs(t),await this.ready(),(await Av(this._db,this._custom,t)).map(xn)}set customEmoji(t){this._custom=ol(t)}get customEmoji(){return this._custom.all}async _shutdown(){await this.ready();try{await this._lazyUpdate}catch{}}_clear(){this._db=this._ready=this._lazyUpdate=void 0}async close(){await this._shutdown(),await La(this._dbName)}async delete(){await this._shutdown(),await uv(this._dbName)}}const Oo=[[-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})),eo=Oo.slice(1),Fv=2,al=6,Yd=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function rl(e){return e.unicode.includes("‍")}const Uv={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},Wv=1e3,Kv="🖐️",zv=8,qv=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],Xd='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',Hv=(e,t)=>e<t?-1:e>t?1:0,ll=(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 ${Xd}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},jv=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function Gv(e){const t=ll(e,"#000"),n=ll(e,"#fff");return t&&n&&jv(t,n)}function Vv(){const e=Object.entries(Uv);try{for(const[t,n]of e)if(Gv(t))return n}catch{}return e[0][1]}let to;const no=()=>(to||(to=new Promise(e=>Yd(()=>e(Vv())))),to),Fo=new Map,Qv="️",Jv="\uD83C",Yv="‍",Xv=127995,Zv=57339;function eb(e,t){if(t===0)return e;const n=e.indexOf(Yv);return n!==-1?e.substring(0,n)+String.fromCodePoint(Xv+t-1)+e.substring(n):(e.endsWith(Qv)&&(e=e.substring(0,e.length-1)),e+Jv+String.fromCodePoint(Zv+t-1))}function Le(e){e.preventDefault(),e.stopPropagation()}function io(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function Zd(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 tb(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 Ti=requestAnimationFrame;let nb=typeof ResizeObserver=="function";function ib(e,t,n){let i;nb?(i=new ResizeObserver(n),i.observe(e)):Ti(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function cl(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let so;function sb(e,t,n){let i=!0,s=!1;for(const o of e){const a=n(o);if(!a)continue;const r=cl(a);r===0&&(s=!0),typeof so>"u"&&(so=cl(t));const l=r/1.8<so;Fo.set(o.unicode,l),l||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
2841
2839
  This is likely due to using \`display:none\` which is unsupported.
2842
2840
  If this is a Jest/Vitest environment, you can ignore this warning.
2843
- For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function sb(e){return Xd(e,t=>t)}function ob(e){e&&(e.scrollTop=0)}function Dn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function cl(e){return""+e}function ab(e){const t=document.createElement("template");return t.innerHTML=e,t}const rb=new WeakMap,lb=new WeakMap,cb=Symbol("un-keyed"),db="replaceChildren"in Element.prototype;function ub(e,t){db?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function pb(e,t){let n=e.firstChild,i=0;for(;n;){if(t[i]!==n)return!0;n=n.nextSibling,i++}return i!==t.length}function hb(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=pb(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&ub(i,e)}function fb(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 h=r+cl(c)+l;i.setAttribute(a,h)}else{let h;Array.isArray(c)?hb(c,n):c instanceof Element?(h=c,i.replaceWith(h)):i.nodeValue=cl(c),h&&(n.targetNode=h)}}}function gb(e){let t="",n=!1,i=!1,s=-1;const o=new Map,a=[];let r=0;for(let c=0,h=e.length;c<h;c++){const d=e[c];if(t+=d.slice(r),c===h-1)break;for(let b=0;b<d.length;b++)switch(d.charAt(b)){case"<":{d.charAt(b+1)==="/"?a.pop():(n=!0,a.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const p=a[a.length-1],v=Dn(o,p,()=>[]);let S,x,T;if(i){const b=/(\S+)="?([^"=]*)$/.exec(d);S=b[1],x=b[2];const k=/^([^">]*)("?)/.exec(e[c+1]);T=k[1],t=t.slice(0,-1*b[0].length),r=k[0].length}else r=0;const f={attributeName:S,attributeValuePre:x,attributeValuePost:T,expressionIndex:c};v.push(f),!n&&!i&&(t+=" ")}return{template:ab(t),elementsToBindings:o}}function dl(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 mb(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))dl(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&dl(r,o,n)}while(o=s.nextNode())}return n}function yb(e){const{template:t,elementsToBindings:n}=Dn(rb,e,()=>gb(e)),i=t.cloneNode(!0).content.firstElementChild,s=mb(i,n);return function(a){return fb(a,s),i}}function vb(e){const t=Dn(lb,e,()=>new Map);let n=cb;function i(o,...a){const r=Dn(t,o,()=>new Map);return Dn(r,n,()=>yb(o))(a)}function s(o,a,r){return o.map((l,c)=>{const h=n;n=r(l);try{return a(l,c)}finally{n=h}})}return{map:s,html:i}}function bb(e,t,n,i,s,o,a,r,l){const{labelWithSkin:c,titleForEmoji:h,unicodeWithSkin:d}=n,{html:p,map:v}=vb(t);function S(b,k,A){return v(b,(E,M)=>p`<button role="${k?"option":"menuitem"}" aria-selected="${k?M===t.activeSearchItem:null}" aria-label="${c(E,t.currentSkinTone)}" title="${h(E)}" class="${"emoji"+(k&&M===t.activeSearchItem?" active":"")+(E.unicode?"":" custom-emoji")}" id="${`${A}-${E.id}`}" style="${E.unicode?null:`--custom-emoji-background: url(${JSON.stringify(E.url)})`}">${E.unicode?d(E,t.currentSkinTone):""}</button>`,E=>`${A}-${E.id}`)}const T=p`<section data-ref="rootElement" class="picker" aria-label="${t.i18n.regionLabel}" style="${t.pickerStyle||""}"><div class="pad-top"></div><div class="search-row"><div class="search-wrapper"><input id="search" class="search" type="search" role="combobox" enterkeyhint="search" placeholder="${t.i18n.searchLabel}" autocapitalize="none" autocomplete="off" spellcheck="true" aria-expanded="${!!(t.searchMode&&t.currentEmojis.length)}" aria-controls="search-results" aria-describedby="search-description" aria-autocomplete="list" aria-activedescendant="${t.activeSearchItemId?`emo-${t.activeSearchItemId}`:null}" data-ref="searchElement" data-on-input="onSearchInput" data-on-keydown="onSearchKeydown"><label class="sr-only" for="search">${t.i18n.searchLabel}</label> <span id="search-description" class="sr-only">${t.i18n.searchDescription}</span></div><div class="skintone-button-wrapper ${t.skinTonePickerExpandedAfterAnimation?"expanded":""}"><button id="skintone-button" class="emoji ${t.skinTonePickerExpanded?"hide-focus":""}" aria-label="${t.skinToneButtonLabel}" title="${t.skinToneButtonLabel}" aria-describedby="skintone-description" aria-haspopup="listbox" aria-expanded="${t.skinTonePickerExpanded}" aria-controls="skintone-list" data-on-click="onClickSkinToneButton">${t.skinToneButtonText||""}</button></div><span id="skintone-description" class="sr-only">${t.i18n.skinToneDescription}</span><div data-ref="skinToneDropdown" id="skintone-list" class="skintone-list hide-focus ${t.skinTonePickerExpanded?"":"hidden no-animate"}" style="transform:translateY(${t.skinTonePickerExpanded?0:"calc(-1 * var(--num-skintones) * var(--total-emoji-size))"})" role="listbox" aria-label="${t.i18n.skinTonesLabel}" aria-activedescendant="skintone-${t.activeSkinTone}" aria-hidden="${!t.skinTonePickerExpanded}" tabIndex="-1" data-on-focusout="onSkinToneOptionsFocusOut" data-on-click="onSkinToneOptionsClick" data-on-keydown="onSkinToneOptionsKeydown" data-on-keyup="onSkinToneOptionsKeyup">${v(t.skinTones,(b,k)=>p`<div id="skintone-${k}" class="emoji ${k===t.activeSkinTone?"active":""}" aria-selected="${k===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[k]}" aria-label="${t.i18n.skinTones[k]}">${b}</div>`,b=>b)}</div></div><div class="nav" role="tablist" style="grid-template-columns:repeat(${t.groups.length},1fr)" aria-label="${t.i18n.categoriesLabel}" data-on-keydown="onNavKeydown" data-on-click="onNavClick">${v(t.groups,b=>p`<button role="tab" class="nav-button" aria-controls="tab-${b.id}" aria-label="${t.i18n.categories[b.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===b.id}" title="${t.i18n.categories[b.name]}" data-group-id="${b.id}"><div class="nav-emoji emoji">${b.emoji}</div></button>`,b=>b.id)}</div><div class="indicator-wrapper"><div class="indicator" style="transform:translateX(${(t.isRtl?-1:1)*t.currentGroupIndex*100}%)"></div></div><div class="message ${t.message?"":"gone"}" role="alert" aria-live="polite">${t.message||""}</div><div data-ref="tabpanelElement" class="tabpanel ${!t.databaseLoaded||t.message?"gone":""}" role="${t.searchMode?"region":"tabpanel"}" aria-label="${t.searchMode?t.i18n.searchResultsLabel:t.i18n.categories[t.currentGroup.name]}" id="${t.searchMode?null:`tab-${t.currentGroup.id}`}" tabIndex="0" data-on-click="onEmojiClick"><div data-action="calculateEmojiGridStyle">${v(t.currentEmojisWithCategories,(b,k)=>p`<div><div id="menu-label-${k}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:b.category?b.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${k!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(b.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${k}" id="${t.searchMode?"search-results":null}">${S(b.emojis,t.searchMode,"emo")}</div></div>`,b=>b.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${S(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,f=(b,k)=>{for(const A of e.querySelectorAll(`[${b}]`))k(A,A.getAttribute(b))};if(l){e.appendChild(T);for(const b of["click","focusout","input","keydown","keyup"])f(`data-on-${b}`,(k,A)=>{k.addEventListener(b,i[A])});f("data-ref",(b,k)=>{o[k]=b}),a.addEventListener("abort",()=>{e.removeChild(T)})}f("data-action",(b,k)=>{let A=r.get(k);A||r.set(k,A=new WeakSet),A.has(b)||(A.add(b),s[k](b))})}const Xi=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function wb(e){let t=!1,n;const i=new Map,s=new Set;let o;const a=()=>{if(t)return;const c=[...s];s.clear();try{for(const h of c)h()}finally{o=!1,s.size&&(o=!0,Xi(a))}},r=new Proxy({},{get(c,h){if(n){let d=i.get(h);d||(d=new Set,i.set(h,d)),d.add(n)}return c[h]},set(c,h,d){if(c[h]!==d){c[h]=d;const p=i.get(h);if(p){for(const v of p)s.add(v);o||(o=!0,Xi(a))}}return!0}}),l=c=>{const h=()=>{const d=n;n=h;try{return c()}finally{n=d}};return h()};return e.addEventListener("abort",()=>{t=!0}),{state:r,createEffect:l}}function so(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 ul=new WeakMap;function kb(e,t,n){{const i=e.closest(".tabpanel");let s=ul.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),ul.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const oo=[],{assign:bi}=Object;function $b(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=wb(s),r=new Map;bi(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),bi(o,t),bi(o,{initialLoad:!0,currentEmojis:[],currentEmojisWithCategories:[],rawSearchText:"",searchText:"",searchMode:!1,activeSearchItem:-1,message:void 0,skinTonePickerExpanded:!1,skinTonePickerExpandedAfterAnimation:!1,currentSkinTone:0,activeSkinTone:0,skinToneButtonText:void 0,pickerStyle:void 0,skinToneButtonLabel:"",skinTones:[],currentFavorites:[],defaultFavoriteEmojis:void 0,numColumns:Kv,isRtl:!1,currentGroupIndex:0,groups:Zs,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const l=C=>{e.getElementById(C).focus()},c=C=>e.getElementById(`emo-${C.id}`),h=(C,I)=>{n.rootElement.dispatchEvent(new CustomEvent(C,{detail:I,bubbles:!0,composed:!0}))},d=(C,I)=>C.id===I.id,p=(C,I)=>{const{category:U,emojis:W}=C,{category:Z,emojis:J}=I;return U!==Z?!1:so(W,J,d)},v=C=>{so(o.currentEmojis,C,d)||(o.currentEmojis=C)},S=C=>{o.searchMode!==C&&(o.searchMode=C)},x=C=>{so(o.currentEmojisWithCategories,C,p)||(o.currentEmojisWithCategories=C)},T=(C,I)=>I&&C.skins&&C.skins[I]||C.unicode,k={labelWithSkin:(C,I)=>sb([C.name||T(C,I),C.annotation,...C.shortcodes||oo].filter(Boolean)).join(", "),titleForEmoji:C=>C.annotation||(C.shortcodes||oo).join(", "),unicodeWithSkin:T},A={onClickSkinToneButton:X,onEmojiClick:Jn,onNavClick:Vn,onNavKeydown:vs,onSearchKeydown:ys,onSkinToneOptionsClick:Yn,onSkinToneOptionsFocusOut:tt,onSkinToneOptionsKeydown:ut,onSkinToneOptionsKeyup:dn,onSearchInput:Xn},E={calculateEmojiGridStyle:R,updateOnIntersection:F};let M=!0;a(()=>{bb(e,o,k,A,E,n,s,r,M),M=!1}),o.emojiVersion||to().then(C=>{C||(o.message=o.i18n.emojiUnsupportedMessage)}),a(()=>{async function C(){let I=!1;const U=setTimeout(()=>{I=!0,o.message=o.i18n.loadingMessage},Uv);try{await o.database.ready(),o.databaseLoaded=!0}catch(W){console.error(W),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(U),I&&(I=!1,o.message="")}}o.database&&C()}),a(()=>{o.pickerStyle=`
2841
+ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function ob(e){return Zd(e,t=>t)}function ab(e){e&&(e.scrollTop=0)}function Dn(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function dl(e){return""+e}function rb(e){const t=document.createElement("template");return t.innerHTML=e,t}const lb=new WeakMap,cb=new WeakMap,db=Symbol("un-keyed"),ub="replaceChildren"in Element.prototype;function pb(e,t){ub?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function hb(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 fb(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=hb(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&pb(i,e)}function gb(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 h=r+dl(c)+l;i.setAttribute(a,h)}else{let h;Array.isArray(c)?fb(c,n):c instanceof Element?(h=c,i.replaceWith(h)):i.nodeValue=dl(c),h&&(n.targetNode=h)}}}function mb(e){let t="",n=!1,i=!1,s=-1;const o=new Map,a=[];let r=0;for(let c=0,h=e.length;c<h;c++){const d=e[c];if(t+=d.slice(r),c===h-1)break;for(let b=0;b<d.length;b++)switch(d.charAt(b)){case"<":{d.charAt(b+1)==="/"?a.pop():(n=!0,a.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const p=a[a.length-1],g=Dn(o,p,()=>[]);let x,S,T;if(i){const b=/(\S+)="?([^"=]*)$/.exec(d);x=b[1],S=b[2];const k=/^([^">]*)("?)/.exec(e[c+1]);T=k[1],t=t.slice(0,-1*b[0].length),r=k[0].length}else r=0;const f={attributeName:x,attributeValuePre:S,attributeValuePost:T,expressionIndex:c};g.push(f),!n&&!i&&(t+=" ")}return{template:rb(t),elementsToBindings:o}}function ul(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 yb(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))ul(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,a=-1;do{const r=t.get(++a);r&&ul(r,o,n)}while(o=s.nextNode())}return n}function vb(e){const{template:t,elementsToBindings:n}=Dn(lb,e,()=>mb(e)),i=t.cloneNode(!0).content.firstElementChild,s=yb(i,n);return function(a){return gb(a,s),i}}function bb(e){const t=Dn(cb,e,()=>new Map);let n=db;function i(o,...a){const r=Dn(t,o,()=>new Map);return Dn(r,n,()=>vb(o))(a)}function s(o,a,r){return o.map((l,c)=>{const h=n;n=r(l);try{return a(l,c)}finally{n=h}})}return{map:s,html:i}}function wb(e,t,n,i,s,o,a,r,l){const{labelWithSkin:c,titleForEmoji:h,unicodeWithSkin:d}=n,{html:p,map:g}=bb(t);function x(b,k,A){return g(b,(E,M)=>p`<button role="${k?"option":"menuitem"}" aria-selected="${k?M===t.activeSearchItem:null}" aria-label="${c(E,t.currentSkinTone)}" title="${h(E)}" class="${"emoji"+(k&&M===t.activeSearchItem?" active":"")+(E.unicode?"":" custom-emoji")}" id="${`${A}-${E.id}`}" style="${E.unicode?null:`--custom-emoji-background: url(${JSON.stringify(E.url)})`}">${E.unicode?d(E,t.currentSkinTone):""}</button>`,E=>`${A}-${E.id}`)}const T=p`<section data-ref="rootElement" class="picker" aria-label="${t.i18n.regionLabel}" style="${t.pickerStyle||""}"><div class="pad-top"></div><div class="search-row"><div class="search-wrapper"><input id="search" class="search" type="search" role="combobox" enterkeyhint="search" placeholder="${t.i18n.searchLabel}" autocapitalize="none" autocomplete="off" spellcheck="true" aria-expanded="${!!(t.searchMode&&t.currentEmojis.length)}" aria-controls="search-results" aria-describedby="search-description" aria-autocomplete="list" aria-activedescendant="${t.activeSearchItemId?`emo-${t.activeSearchItemId}`:null}" data-ref="searchElement" data-on-input="onSearchInput" data-on-keydown="onSearchKeydown"><label class="sr-only" for="search">${t.i18n.searchLabel}</label> <span id="search-description" class="sr-only">${t.i18n.searchDescription}</span></div><div class="skintone-button-wrapper ${t.skinTonePickerExpandedAfterAnimation?"expanded":""}"><button id="skintone-button" class="emoji ${t.skinTonePickerExpanded?"hide-focus":""}" aria-label="${t.skinToneButtonLabel}" title="${t.skinToneButtonLabel}" aria-describedby="skintone-description" aria-haspopup="listbox" aria-expanded="${t.skinTonePickerExpanded}" aria-controls="skintone-list" data-on-click="onClickSkinToneButton">${t.skinToneButtonText||""}</button></div><span id="skintone-description" class="sr-only">${t.i18n.skinToneDescription}</span><div data-ref="skinToneDropdown" id="skintone-list" class="skintone-list hide-focus ${t.skinTonePickerExpanded?"":"hidden no-animate"}" style="transform:translateY(${t.skinTonePickerExpanded?0:"calc(-1 * var(--num-skintones) * var(--total-emoji-size))"})" role="listbox" aria-label="${t.i18n.skinTonesLabel}" aria-activedescendant="skintone-${t.activeSkinTone}" aria-hidden="${!t.skinTonePickerExpanded}" tabIndex="-1" data-on-focusout="onSkinToneOptionsFocusOut" data-on-click="onSkinToneOptionsClick" data-on-keydown="onSkinToneOptionsKeydown" data-on-keyup="onSkinToneOptionsKeyup">${g(t.skinTones,(b,k)=>p`<div id="skintone-${k}" class="emoji ${k===t.activeSkinTone?"active":""}" aria-selected="${k===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[k]}" aria-label="${t.i18n.skinTones[k]}">${b}</div>`,b=>b)}</div></div><div class="nav" role="tablist" style="grid-template-columns:repeat(${t.groups.length},1fr)" aria-label="${t.i18n.categoriesLabel}" data-on-keydown="onNavKeydown" data-on-click="onNavClick">${g(t.groups,b=>p`<button role="tab" class="nav-button" aria-controls="tab-${b.id}" aria-label="${t.i18n.categories[b.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===b.id}" title="${t.i18n.categories[b.name]}" data-group-id="${b.id}"><div class="nav-emoji emoji">${b.emoji}</div></button>`,b=>b.id)}</div><div class="indicator-wrapper"><div class="indicator" style="transform:translateX(${(t.isRtl?-1:1)*t.currentGroupIndex*100}%)"></div></div><div class="message ${t.message?"":"gone"}" role="alert" aria-live="polite">${t.message||""}</div><div data-ref="tabpanelElement" class="tabpanel ${!t.databaseLoaded||t.message?"gone":""}" role="${t.searchMode?"region":"tabpanel"}" aria-label="${t.searchMode?t.i18n.searchResultsLabel:t.i18n.categories[t.currentGroup.name]}" id="${t.searchMode?null:`tab-${t.currentGroup.id}`}" tabIndex="0" data-on-click="onEmojiClick"><div data-action="calculateEmojiGridStyle">${g(t.currentEmojisWithCategories,(b,k)=>p`<div><div id="menu-label-${k}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:b.category?b.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${k!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil(b.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${k}" id="${t.searchMode?"search-results":null}">${x(b.emojis,t.searchMode,"emo")}</div></div>`,b=>b.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${x(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,f=(b,k)=>{for(const A of e.querySelectorAll(`[${b}]`))k(A,A.getAttribute(b))};if(l){e.appendChild(T);for(const b of["click","focusout","input","keydown","keyup"])f(`data-on-${b}`,(k,A)=>{k.addEventListener(b,i[A])});f("data-ref",(b,k)=>{o[k]=b}),a.addEventListener("abort",()=>{e.removeChild(T)})}f("data-action",(b,k)=>{let A=r.get(k);A||r.set(k,A=new WeakSet),A.has(b)||(A.add(b),s[k](b))})}const Zi=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function kb(e){let t=!1,n;const i=new Map,s=new Set;let o;const a=()=>{if(t)return;const c=[...s];s.clear();try{for(const h of c)h()}finally{o=!1,s.size&&(o=!0,Zi(a))}},r=new Proxy({},{get(c,h){if(n){let d=i.get(h);d||(d=new Set,i.set(h,d)),d.add(n)}return c[h]},set(c,h,d){if(c[h]!==d){c[h]=d;const p=i.get(h);if(p){for(const g of p)s.add(g);o||(o=!0,Zi(a))}}return!0}}),l=c=>{const h=()=>{const d=n;n=h;try{return c()}finally{n=d}};return h()};return e.addEventListener("abort",()=>{t=!0}),{state:r,createEffect:l}}function oo(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 pl=new WeakMap;function $b(e,t,n){{const i=e.closest(".tabpanel");let s=pl.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),pl.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const ao=[],{assign:wi}=Object;function xb(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:a}=kb(s),r=new Map;wi(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),wi(o,t),wi(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:zv,isRtl:!1,currentGroupIndex:0,groups:eo,databaseLoaded:!1,activeSearchItemId:void 0}),a(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const l=C=>{e.getElementById(C).focus()},c=C=>e.getElementById(`emo-${C.id}`),h=(C,I)=>{n.rootElement.dispatchEvent(new CustomEvent(C,{detail:I,bubbles:!0,composed:!0}))},d=(C,I)=>C.id===I.id,p=(C,I)=>{const{category:U,emojis:W}=C,{category:Z,emojis:J}=I;return U!==Z?!1:oo(W,J,d)},g=C=>{oo(o.currentEmojis,C,d)||(o.currentEmojis=C)},x=C=>{o.searchMode!==C&&(o.searchMode=C)},S=C=>{oo(o.currentEmojisWithCategories,C,p)||(o.currentEmojisWithCategories=C)},T=(C,I)=>I&&C.skins&&C.skins[I]||C.unicode,k={labelWithSkin:(C,I)=>ob([C.name||T(C,I),C.annotation,...C.shortcodes||ao].filter(Boolean)).join(", "),titleForEmoji:C=>C.annotation||(C.shortcodes||ao).join(", "),unicodeWithSkin:T},A={onClickSkinToneButton:X,onEmojiClick:Yn,onNavClick:Qn,onNavKeydown:bs,onSearchKeydown:vs,onSkinToneOptionsClick:Xn,onSkinToneOptionsFocusOut:tt,onSkinToneOptionsKeydown:pt,onSkinToneOptionsKeyup:dn,onSearchInput:Zn},E={calculateEmojiGridStyle:R,updateOnIntersection:F};let M=!0;a(()=>{wb(e,o,k,A,E,n,s,r,M),M=!1}),o.emojiVersion||no().then(C=>{C||(o.message=o.i18n.emojiUnsupportedMessage)}),a(()=>{async function C(){let I=!1;const U=setTimeout(()=>{I=!0,o.message=o.i18n.loadingMessage},Wv);try{await o.database.ready(),o.databaseLoaded=!0}catch(W){console.error(W),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(U),I&&(I=!1,o.message="")}}o.database&&C()}),a(()=>{o.pickerStyle=`
2844
2842
  --num-groups: ${o.groups.length};
2845
2843
  --indicator-opacity: ${o.searchMode?0:1};
2846
- --num-skintones: ${ol};`}),a(()=>{o.customEmoji&&o.database&&P()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==No&&(o.groups=No):o.groups!==Zs&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=Zs)}),a(()=>{async function C(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}C()}),a(()=>{o.skinTones=Array(ol).fill().map((C,I)=>Zv(o.skinToneEmoji,I))}),a(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),a(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),a(()=>{async function C(){const{database:I}=o,U=(await Promise.all(zv.map(W=>I.getEmojiByUnicodeOrName(W)))).filter(Boolean);o.defaultFavoriteEmojis=U}o.databaseLoaded&&C()});function P(){const{customEmoji:C,database:I}=o,U=C||oo;I.customEmoji!==U&&(I.customEmoji=U)}a(()=>{async function C(){P();const{database:I,defaultFavoriteEmojis:U,numColumns:W}=o,Z=await I.getTopFavoriteEmoji(W),J=await Ke(Xd([...Z,...U],fe=>fe.unicode||fe.name).slice(0,W));o.currentFavorites=J}o.databaseLoaded&&o.defaultFavoriteEmojis&&C()});function R(C){nb(C,s,()=>{{const I=getComputedStyle(n.rootElement),U=parseInt(I.getPropertyValue("--num-columns"),10),W=I.getPropertyValue("direction")==="rtl";o.numColumns=U,o.isRtl=W}})}function F(C){kb(C,s,I=>{for(const{target:U,isIntersecting:W}of I)U.classList.toggle("onscreen",W)})}a(()=>{async function C(){const{searchText:I,currentGroup:U,databaseLoaded:W,customEmoji:Z}=o;if(!W)o.currentEmojis=[],o.searchMode=!1;else if(I.length>=Ov){const J=await ms(I);o.searchText===I&&(v(J),S(!0))}else{const{id:J}=U;if(J!==-1||Z&&Z.length){const fe=await gs(J);o.currentGroup.id===J&&(v(fe),S(!1))}}}C()});const H=()=>{Ei(()=>ob(n.tabpanelElement))};a(()=>{const{currentEmojis:C,emojiVersion:I}=o,U=C.filter(W=>W.unicode).filter(W=>al(W)&&!Oo.has(W.unicode));if(!I&&U.length)v(C),Ei(()=>z(U));else{const W=I?C:C.filter(ke);v(W),H()}});function z(C){ib(C,n.baselineEmoji,c)?H():o.currentEmojis=[...o.currentEmojis]}function ke(C){return!C.unicode||!al(C)||Oo.get(C.unicode)}async function _e(C){const I=o.emojiVersion||await to();return C.filter(({version:U})=>!U||U<=I)}async function Ke(C){return eb(C,o.emojiVersion||await to())}async function gs(C){const I=C===-1?o.customEmoji:await o.database.getEmojiByGroup(C);return Ke(await _e(I))}async function ms(C){return Ke(await _e(await o.database.getEmojiBySearchQuery(C)))}a(()=>{}),a(()=>{function C(){const{searchMode:U,currentEmojis:W}=o;if(U)return[{category:"",emojis:W}];const Z=new Map;for(const J of W){const fe=J.category||"";let nt=Z.get(fe);nt||(nt=[],Z.set(fe,nt)),nt.push(J)}return[...Z.entries()].map(([J,fe])=>({category:J,emojis:fe})).sort((J,fe)=>o.customCategorySorting(J.category,fe.category))}const I=C();x(I)}),a(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),a(()=>{const{rawSearchText:C}=o;Jd(()=>{o.searchText=(C||"").trim(),o.activeSearchItem=-1})});function ys(C){if(!o.searchMode||!o.currentEmojis.length)return;const I=U=>{Le(C),o.activeSearchItem=no(U,o.activeSearchItem,o.currentEmojis)};switch(C.key){case"ArrowDown":return I(!1);case"ArrowUp":return I(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Le(C),te(o.currentEmojis[o.activeSearchItem].id)}}function Vn(C){const{target:I}=C,U=I.closest(".nav-button");if(!U)return;const W=parseInt(U.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(Z=>Z.id===W)}function vs(C){const{target:I,key:U}=C,W=Z=>{Z&&(Le(C),Z.focus())};switch(U){case"ArrowLeft":return W(I.previousElementSibling);case"ArrowRight":return W(I.nextElementSibling);case"Home":return W(I.parentElement.firstElementChild);case"End":return W(I.parentElement.lastElementChild)}}async function Qn(C){const I=await o.database.getEmojiByUnicodeOrName(C),U=[...o.currentEmojis,...o.currentFavorites].find(Z=>Z.id===C),W=U.unicode&&T(U,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(C),{emoji:I,skinTone:o.currentSkinTone,...W&&{unicode:W},...U.name&&{name:U.name}}}async function te(C){const I=Qn(C);h("emoji-click-sync",I),h("emoji-click",await I)}function Jn(C){const{target:I}=C;if(!I.classList.contains("emoji"))return;Le(C);const U=I.id.substring(4);te(U)}function ne(C){o.currentSkinTone=C,o.skinTonePickerExpanded=!1,l("skintone-button"),h("skin-tone-change",{skinTone:C}),o.database.setPreferredSkinTone(C)}function Yn(C){const{target:{id:I}}=C,U=I&&I.match(/^skintone-(\d)/);if(!U)return;Le(C);const W=parseInt(U[1],10);ne(W)}function X(C){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Le(C),Ei(()=>l("skintone-list")))}a(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function ut(C){if(!o.skinTonePickerExpanded)return;const I=async U=>{Le(C),o.activeSkinTone=U};switch(C.key){case"ArrowUp":return I(no(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return I(no(!1,o.activeSkinTone,o.skinTones));case"Home":return I(0);case"End":return I(o.skinTones.length-1);case"Enter":return Le(C),ne(o.activeSkinTone);case"Escape":return Le(C),o.skinTonePickerExpanded=!1,l("skintone-button")}}function dn(C){if(o.skinTonePickerExpanded&&C.key===" ")return Le(C),ne(o.activeSkinTone)}async function tt(C){const{relatedTarget:I}=C;(!I||I.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function Xn(C){o.rawSearchText=C.target.value}return{$set(C){bi(o,C)},$destroy(){i.abort()}}}const xb="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Sb="en";var Ab={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"}},Cb=':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 Zd=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],Eb=`:host{--emoji-font-family:${Yd}}`;class Da extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=Cb+Eb,this.shadowRoot.appendChild(n),this._ctx={locale:Sb,dataSource:xb,skinToneEmoji:Wv,customCategorySorting:qv,customEmoji:null,i18n:Ab,emojiVersion:null,...t};for(const i of Zd)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=$b(this.shadowRoot,this._ctx))}disconnectedCallback(){pl(this),Xi(()=>{if(!this.isConnected&&this._cmp){this._cmp.$destroy(),this._cmp=void 0;const{database:t}=this._ctx;t.close().catch(n=>console.error(n))}})}static get observedAttributes(){return["locale","data-source","skin-tone-emoji","emoji-version"]}attributeChangedCallback(t,n,i){this._set(t.replace(/-([a-z])/g,(s,o)=>o.toUpperCase()),t==="emoji-version"?parseFloat(i):i)}_set(t,n){this._ctx[t]=n,this._cmp&&this._cmp.$set({[t]:n}),["locale","dataSource"].includes(t)&&this._dbFlush()}_dbCreate(){const{locale:t,dataSource:n,database:i}=this._ctx;(!i||i.locale!==t||i.dataSource!==n)&&this._set("database",new Nv({locale:t,dataSource:n}))}_dbFlush(){Xi(()=>this._dbCreate())}}const eu={};for(const e of Zd)eu[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(Da.prototype,eu);function pl(e){e instanceof Da||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Da);function Tb(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 hl(e){e.style.height="44px",e.style.overflowY="hidden"}const _b=5e3;function Mb(e){return e?e.active?u`
2844
+ --num-skintones: ${al};`}),a(()=>{o.customEmoji&&o.database&&P()}),a(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==Oo&&(o.groups=Oo):o.groups!==eo&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=eo)}),a(()=>{async function C(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}C()}),a(()=>{o.skinTones=Array(al).fill().map((C,I)=>eb(o.skinToneEmoji,I))}),a(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),a(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),a(()=>{async function C(){const{database:I}=o,U=(await Promise.all(qv.map(W=>I.getEmojiByUnicodeOrName(W)))).filter(Boolean);o.defaultFavoriteEmojis=U}o.databaseLoaded&&C()});function P(){const{customEmoji:C,database:I}=o,U=C||ao;I.customEmoji!==U&&(I.customEmoji=U)}a(()=>{async function C(){P();const{database:I,defaultFavoriteEmojis:U,numColumns:W}=o,Z=await I.getTopFavoriteEmoji(W),J=await Ke(Zd([...Z,...U],fe=>fe.unicode||fe.name).slice(0,W));o.currentFavorites=J}o.databaseLoaded&&o.defaultFavoriteEmojis&&C()});function R(C){ib(C,s,()=>{{const I=getComputedStyle(n.rootElement),U=parseInt(I.getPropertyValue("--num-columns"),10),W=I.getPropertyValue("direction")==="rtl";o.numColumns=U,o.isRtl=W}})}function F(C){$b(C,s,I=>{for(const{target:U,isIntersecting:W}of I)U.classList.toggle("onscreen",W)})}a(()=>{async function C(){const{searchText:I,currentGroup:U,databaseLoaded:W,customEmoji:Z}=o;if(!W)o.currentEmojis=[],o.searchMode=!1;else if(I.length>=Fv){const J=await ys(I);o.searchText===I&&(g(J),x(!0))}else{const{id:J}=U;if(J!==-1||Z&&Z.length){const fe=await ms(J);o.currentGroup.id===J&&(g(fe),x(!1))}}}C()});const H=()=>{Ti(()=>ab(n.tabpanelElement))};a(()=>{const{currentEmojis:C,emojiVersion:I}=o,U=C.filter(W=>W.unicode).filter(W=>rl(W)&&!Fo.has(W.unicode));if(!I&&U.length)g(C),Ti(()=>z(U));else{const W=I?C:C.filter(ke);g(W),H()}});function z(C){sb(C,n.baselineEmoji,c)?H():o.currentEmojis=[...o.currentEmojis]}function ke(C){return!C.unicode||!rl(C)||Fo.get(C.unicode)}async function _e(C){const I=o.emojiVersion||await no();return C.filter(({version:U})=>!U||U<=I)}async function Ke(C){return tb(C,o.emojiVersion||await no())}async function ms(C){const I=C===-1?o.customEmoji:await o.database.getEmojiByGroup(C);return Ke(await _e(I))}async function ys(C){return Ke(await _e(await o.database.getEmojiBySearchQuery(C)))}a(()=>{}),a(()=>{function C(){const{searchMode:U,currentEmojis:W}=o;if(U)return[{category:"",emojis:W}];const Z=new Map;for(const J of W){const fe=J.category||"";let nt=Z.get(fe);nt||(nt=[],Z.set(fe,nt)),nt.push(J)}return[...Z.entries()].map(([J,fe])=>({category:J,emojis:fe})).sort((J,fe)=>o.customCategorySorting(J.category,fe.category))}const I=C();S(I)}),a(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),a(()=>{const{rawSearchText:C}=o;Yd(()=>{o.searchText=(C||"").trim(),o.activeSearchItem=-1})});function vs(C){if(!o.searchMode||!o.currentEmojis.length)return;const I=U=>{Le(C),o.activeSearchItem=io(U,o.activeSearchItem,o.currentEmojis)};switch(C.key){case"ArrowDown":return I(!1);case"ArrowUp":return I(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Le(C),te(o.currentEmojis[o.activeSearchItem].id)}}function Qn(C){const{target:I}=C,U=I.closest(".nav-button");if(!U)return;const W=parseInt(U.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(Z=>Z.id===W)}function bs(C){const{target:I,key:U}=C,W=Z=>{Z&&(Le(C),Z.focus())};switch(U){case"ArrowLeft":return W(I.previousElementSibling);case"ArrowRight":return W(I.nextElementSibling);case"Home":return W(I.parentElement.firstElementChild);case"End":return W(I.parentElement.lastElementChild)}}async function Jn(C){const I=await o.database.getEmojiByUnicodeOrName(C),U=[...o.currentEmojis,...o.currentFavorites].find(Z=>Z.id===C),W=U.unicode&&T(U,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(C),{emoji:I,skinTone:o.currentSkinTone,...W&&{unicode:W},...U.name&&{name:U.name}}}async function te(C){const I=Jn(C);h("emoji-click-sync",I),h("emoji-click",await I)}function Yn(C){const{target:I}=C;if(!I.classList.contains("emoji"))return;Le(C);const U=I.id.substring(4);te(U)}function ne(C){o.currentSkinTone=C,o.skinTonePickerExpanded=!1,l("skintone-button"),h("skin-tone-change",{skinTone:C}),o.database.setPreferredSkinTone(C)}function Xn(C){const{target:{id:I}}=C,U=I&&I.match(/^skintone-(\d)/);if(!U)return;Le(C);const W=parseInt(U[1],10);ne(W)}function X(C){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Le(C),Ti(()=>l("skintone-list")))}a(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function pt(C){if(!o.skinTonePickerExpanded)return;const I=async U=>{Le(C),o.activeSkinTone=U};switch(C.key){case"ArrowUp":return I(io(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return I(io(!1,o.activeSkinTone,o.skinTones));case"Home":return I(0);case"End":return I(o.skinTones.length-1);case"Enter":return Le(C),ne(o.activeSkinTone);case"Escape":return Le(C),o.skinTonePickerExpanded=!1,l("skintone-button")}}function dn(C){if(o.skinTonePickerExpanded&&C.key===" ")return Le(C),ne(o.activeSkinTone)}async function tt(C){const{relatedTarget:I}=C;(!I||I.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function Zn(C){o.rawSearchText=C.target.value}return{$set(C){wi(o,C)},$destroy(){i.abort()}}}const Sb="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Ab="en";var Cb={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"}},Eb=':host{--emoji-size:1.375rem;--emoji-padding:0.5rem;--category-emoji-size:var(--emoji-size);--category-emoji-padding:var(--emoji-padding);--indicator-height:3px;--input-border-radius:0.5rem;--input-border-size:1px;--input-font-size:1rem;--input-line-height:1.5;--input-padding:0.25rem;--num-columns:8;--outline-size:2px;--border-size:1px;--border-radius:0;--skintone-border-radius:1rem;--category-font-size:1rem;display:flex;width:min-content;height:400px}:host,:host(.light){color-scheme:light;--background:#fff;--border-color:#e0e0e0;--indicator-color:#385ac1;--input-border-color:#999;--input-font-color:#111;--input-placeholder-color:#999;--outline-color:#999;--category-font-color:#111;--button-active-background:#e6e6e6;--button-hover-background:#d9d9d9}:host(.dark){color-scheme:dark;--background:#222;--border-color:#444;--indicator-color:#5373ec;--input-border-color:#ccc;--input-font-color:#efefef;--input-placeholder-color:#ccc;--outline-color:#fff;--category-font-color:#efefef;--button-active-background:#555555;--button-hover-background:#484848}@media (prefers-color-scheme:dark){:host{color-scheme:dark;--background:#222;--border-color:#444;--indicator-color:#5373ec;--input-border-color:#ccc;--input-font-color:#efefef;--input-placeholder-color:#ccc;--outline-color:#fff;--category-font-color:#efefef;--button-active-background:#555555;--button-hover-background:#484848}}:host([hidden]){display:none}button{margin:0;padding:0;border:0;background:0 0;box-shadow:none;-webkit-tap-highlight-color:transparent}button::-moz-focus-inner{border:0}input{padding:0;margin:0;line-height:1.15;font-family:inherit}input[type=search]{-webkit-appearance:none}:focus{outline:var(--outline-color) solid var(--outline-size);outline-offset:calc(-1*var(--outline-size))}:host([data-js-focus-visible]) :focus:not([data-focus-visible-added]){outline:0}:focus:not(:focus-visible){outline:0}.hide-focus{outline:0}*{box-sizing:border-box}.picker{contain:content;display:flex;flex-direction:column;background:var(--background);border:var(--border-size) solid var(--border-color);border-radius:var(--border-radius);width:100%;height:100%;overflow:hidden;--total-emoji-size:calc(var(--emoji-size) + (2 * var(--emoji-padding)));--total-category-emoji-size:calc(var(--category-emoji-size) + (2 * var(--category-emoji-padding)))}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.hidden{opacity:0;pointer-events:none}.abs-pos{position:absolute;left:0;top:0}.gone{display:none!important}.skintone-button-wrapper,.skintone-list{background:var(--background);z-index:3}.skintone-button-wrapper.expanded{z-index:1}.skintone-list{position:absolute;inset-inline-end:0;top:0;z-index:2;overflow:visible;border-bottom:var(--border-size) solid var(--border-color);border-radius:0 0 var(--skintone-border-radius) var(--skintone-border-radius);will-change:transform;transition:transform .2s ease-in-out;transform-origin:center 0}@media (prefers-reduced-motion:reduce){.skintone-list{transition-duration:.001s}}@supports not (inset-inline-end:0){.skintone-list{right:0}}.skintone-list.no-animate{transition:none}.tabpanel{overflow-y:auto;scrollbar-gutter:stable;-webkit-overflow-scrolling:touch;will-change:transform;min-height:0;flex:1;contain:content}.emoji-menu{display:grid;grid-template-columns:repeat(var(--num-columns),var(--total-emoji-size));justify-content:space-around;align-items:flex-start;width:100%}.emoji-menu.visibility-auto{content-visibility:auto;contain-intrinsic-size:calc(var(--num-columns)*var(--total-emoji-size)) calc(var(--num-rows)*var(--total-emoji-size))}.category{padding:var(--emoji-padding);font-size:var(--category-font-size);color:var(--category-font-color)}.emoji,button.emoji{font-size:var(--emoji-size);display:flex;align-items:center;justify-content:center;border-radius:100%;height:var(--total-emoji-size);width:var(--total-emoji-size);line-height:1;overflow:hidden;font-family:var(--emoji-font-family);cursor:pointer}@media (hover:hover) and (pointer:fine){.emoji:hover,button.emoji:hover{background:var(--button-hover-background)}}.emoji.active,.emoji:active,button.emoji.active,button.emoji:active{background:var(--button-active-background)}.onscreen .custom-emoji::after{content:"";width:var(--emoji-size);height:var(--emoji-size);background-repeat:no-repeat;background-position:center center;background-size:contain;background-image:var(--custom-emoji-background)}.nav,.nav-button{align-items:center}.nav{display:grid;justify-content:space-between;contain:content}.nav-button{display:flex;justify-content:center}.nav-emoji{font-size:var(--category-emoji-size);width:var(--total-category-emoji-size);height:var(--total-category-emoji-size)}.indicator-wrapper{display:flex;border-bottom:1px solid var(--border-color)}.indicator{width:calc(100%/var(--num-groups));height:var(--indicator-height);opacity:var(--indicator-opacity);background-color:var(--indicator-color);will-change:transform,opacity;transition:opacity .1s linear,transform .25s ease-in-out}@media (prefers-reduced-motion:reduce){.indicator{will-change:opacity;transition:opacity .1s linear}}.pad-top,input.search{background:var(--background);width:100%}.pad-top{height:var(--emoji-padding);z-index:3}.search-row{display:flex;align-items:center;position:relative;padding-inline-start:var(--emoji-padding);padding-bottom:var(--emoji-padding)}.search-wrapper{flex:1;min-width:0}input.search{padding:var(--input-padding);border-radius:var(--input-border-radius);border:var(--input-border-size) solid var(--input-border-color);color:var(--input-font-color);font-size:var(--input-font-size);line-height:var(--input-line-height)}input.search::placeholder{color:var(--input-placeholder-color)}.favorites{overflow-y:auto;scrollbar-gutter:stable;display:flex;flex-direction:row;border-top:var(--border-size) solid var(--border-color);contain:content}.message{padding:var(--emoji-padding)}';const eu=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],Tb=`:host{--emoji-font-family:${Xd}}`;class Ba extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=Eb+Tb,this.shadowRoot.appendChild(n),this._ctx={locale:Ab,dataSource:Sb,skinToneEmoji:Kv,customCategorySorting:Hv,customEmoji:null,i18n:Cb,emojiVersion:null,...t};for(const i of eu)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){hl(this),this._cmp||(this._cmp=xb(this.shadowRoot,this._ctx))}disconnectedCallback(){hl(this),Zi(()=>{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 Ov({locale:t,dataSource:n}))}_dbFlush(){Zi(()=>this._dbCreate())}}const tu={};for(const e of eu)tu[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(Ba.prototype,tu);function hl(e){e instanceof Ba||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Ba);function _b(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 fl(e){e.style.height="44px",e.style.overflowY="hidden"}const Mb=5e3;function Pb(e){return e?e.active?u`
2847
2845
  <div class="callout info compaction-indicator compaction-indicator--active">
2848
2846
  ${L.loader} Compacting context...
2849
2847
  </div>
2850
- `:e.completedAt&&Date.now()-e.completedAt<_b?u`
2848
+ `:e.completedAt&&Date.now()-e.completedAt<Mb?u`
2851
2849
  <div class="callout success compaction-indicator compaction-indicator--complete">
2852
2850
  ${L.check} Context compacted
2853
2851
  </div>
2854
- `:w:w}const Qe=5*1024*1024;function Je(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Te(e,t){var i,s,o;let n=(i=e.closest(".chat"))==null?void 0:i.querySelector(".chat-attachment-error");if(!n){n=document.createElement("div"),n.className="callout danger chat-attachment-error",n.style.cssText="margin: 8px 4px; animation: fade-in 200ms ease-out;";const a=(s=e.closest(".chat"))==null?void 0:s.querySelector(".chat-compose");(o=a==null?void 0:a.parentElement)==null||o.insertBefore(n,a)}n.textContent=t,setTimeout(()=>n==null?void 0:n.remove(),4e3)}const Pb=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function tu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function nu(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Pb.test(e.name)}function iu(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function su(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function Ib(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(tu(e)){if(e.size>Qe){n&&Te(n,`Image too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(nu(e)){if(e.size>Qe){n&&Te(n,`File too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),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(iu(e)){if(e.size>Qe){n&&Te(n,`PDF too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(su(e)){if(e.size>Qe){n&&Te(n,`Video too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),dataUrl:i.result,mimeType:e.type||"video/mp4",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else n&&Te(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Lb(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(tu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`Image too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:l,mimeType:a.type},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsDataURL(a)}else if(nu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`File too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:l},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsText(a)}else if(iu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`PDF too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:l,mimeType:"application/pdf",fileName:a.name},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsDataURL(a)}else if(su(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`Video too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:l,mimeType:a.type||"video/mp4",fileName:a.name},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsDataURL(a)}else Te(n,`Unsupported file type: ${a.name}. Use the Files page to upload to workspace.`)}}function Rb(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function Db(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function Bb(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>Qe){const d=((a=(o=e.target)==null?void 0:o.closest)==null?void 0:a.call(o,".chat"))??document.querySelector(".chat");d&&Te(d,`${c} too large (${(l.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const h=new FileReader;h.onload=()=>{var x;const d=h.result,p=l.type.startsWith("video/"),v={id:Je(),dataUrl:d,mimeType:l.type,fileName:p?l.name||"video.mp4":void 0},S=t.attachments??[];(x=t.onAttachmentsChange)==null||x.call(t,[...S,v])},h.readAsDataURL(l)}}}function Nb(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 Ob(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 h=s==null?void 0:s.querySelector(".emoji-picker-popup"),d=s==null?void 0:s.querySelector(".chat-compose__emoji");h==null||h.classList.remove("active"),d==null||d.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const p=a+i.length;o.setSelectionRange(p,p)})}function Fb(e){const t=e.attachments??[];return t.length===0?w:u`
2852
+ `:w:w}const Qe=5*1024*1024;function Je(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Te(e,t){var i,s,o;let n=(i=e.closest(".chat"))==null?void 0:i.querySelector(".chat-attachment-error");if(!n){n=document.createElement("div"),n.className="callout danger chat-attachment-error",n.style.cssText="margin: 8px 4px; animation: fade-in 200ms ease-out;";const a=(s=e.closest(".chat"))==null?void 0:s.querySelector(".chat-compose");(o=a==null?void 0:a.parentElement)==null||o.insertBefore(n,a)}n.textContent=t,setTimeout(()=>n==null?void 0:n.remove(),4e3)}const Ib=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function nu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function iu(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Ib.test(e.name)}function su(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function ou(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function Lb(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(nu(e)){if(e.size>Qe){n&&Te(n,`Image too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(iu(e)){if(e.size>Qe){n&&Te(n,`File too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),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(su(e)){if(e.size>Qe){n&&Te(n,`PDF too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(ou(e)){if(e.size>Qe){n&&Te(n,`Video too large (${(e.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);return}const i=new FileReader;i.onload=()=>{var o;const s={id:Je(),dataUrl:i.result,mimeType:e.type||"video/mp4",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else n&&Te(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Rb(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(nu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`Image too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:l,mimeType:a.type},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsDataURL(a)}else if(iu(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`File too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:"",mimeType:a.type||"text/plain",fileName:a.name,textContent:l},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsText(a)}else if(su(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`PDF too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:l,mimeType:"application/pdf",fileName:a.name},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsDataURL(a)}else if(ou(a)){if(!t.onAttachmentsChange)continue;if(a.size>Qe){Te(n,`Video too large (${(a.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const r=new FileReader;r.onload=()=>{var d;const l=r.result,c={id:Je(),dataUrl:l,mimeType:a.type||"video/mp4",fileName:a.name},h=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...h,c])},r.readAsDataURL(a)}else Te(n,`Unsupported file type: ${a.name}. Use the Files page to upload to workspace.`)}}function Db(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function Bb(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function Nb(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>Qe){const d=((a=(o=e.target)==null?void 0:o.closest)==null?void 0:a.call(o,".chat"))??document.querySelector(".chat");d&&Te(d,`${c} too large (${(l.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const h=new FileReader;h.onload=()=>{var S;const d=h.result,p=l.type.startsWith("video/"),g={id:Je(),dataUrl:d,mimeType:l.type,fileName:p?l.name||"video.mp4":void 0},x=t.attachments??[];(S=t.onAttachmentsChange)==null||S.call(t,[...x,g])},h.readAsDataURL(l)}}}function Ob(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 Fb(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 h=s==null?void 0:s.querySelector(".emoji-picker-popup"),d=s==null?void 0:s.querySelector(".chat-compose__emoji");h==null||h.classList.remove("active"),d==null||d.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const p=a+i.length;o.setSelectionRange(p,p)})}function Ub(e){const t=e.attachments??[];return t.length===0?w:u`
2855
2853
  <div class="chat-attachments">
2856
2854
  ${t.map(n=>{var i;return n.fileName?u`
2857
2855
  <div class="chat-attachment chat-attachment--file">
@@ -2884,7 +2882,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
2884
2882
  </div>
2885
2883
  `})}
2886
2884
  </div>
2887
- `}function ou(e){var S,x,T;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(x=(S=e.sessions)==null?void 0:S.sessions)==null?void 0:x.find(f=>f.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",a=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const r=(((T=e.attachments)==null?void 0:T.length)??0)>0,l=e.connected?r?"Add a message...":"Message...":"Connecting…";Hy({onSend:f=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],f]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var f;(f=e.requestUpdate)==null||f.call(e)}});const c=qy(),h=!c&&!e.draft.trim()&&!r&&!n,d=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),v=u`
2885
+ `}function au(e){var x,S,T;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(S=(x=e.sessions)==null?void 0:x.sessions)==null?void 0:S.find(f=>f.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",a=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const r=(((T=e.attachments)==null?void 0:T.length)??0)>0,l=e.connected?r?"Add a message...":"Message...":"Connecting…";jy({onSend:f=>{e.onAttachmentsChange&&e.onAttachmentsChange([...e.attachments??[],f]),requestAnimationFrame(()=>e.onSend())},onRequestRender:()=>{var f;(f=e.requestUpdate)==null||f.call(e)}});const c=Hy(),h=!c&&!e.draft.trim()&&!r&&!n,d=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),g=u`
2888
2886
  <div
2889
2887
  class="chat-thread"
2890
2888
  role="log"
@@ -2895,20 +2893,20 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
2895
2893
  ${e.loadingOlder?u`<span class="chat-load-more__spinner">${L.loader}</span> Loading older messages…`:u`<button class="chat-load-more__btn" type="button" @click=${e.onLoadOlder}>Load older messages</button>`}
2896
2894
  </div>`:w}
2897
2895
  ${e.loading?u`<div class="muted">Loading chat…</div>`:w}
2898
- ${em(jb(e),f=>f.key,f=>f.kind==="interim"?Ry(f.text):f.kind==="reading-indicator"?Ly():f.kind==="stream"?Dy(f.text,f.startedAt,e.onOpenSidebar):f.kind==="group"?By(f,{onOpenSidebar:e.onOpenSidebar,showReasoning:a,assistantName:e.assistantName}):w)}
2896
+ ${tm(Gb(e),f=>f.key,f=>f.kind==="interim"?Dy(f.text):f.kind==="reading-indicator"?Ry():f.kind==="stream"?By(f.text,f.startedAt,e.onOpenSidebar):f.kind==="group"?Ny(f,{onOpenSidebar:e.onOpenSidebar,showReasoning:a,assistantName:e.assistantName}):w)}
2899
2897
  </div>
2900
2898
  `;return u`
2901
2899
  <section
2902
2900
  class="card chat"
2903
- @drop=${f=>Lb(f,e)}
2904
- @dragover=${Rb}
2905
- @dragleave=${Db}
2901
+ @drop=${f=>Rb(f,e)}
2902
+ @dragover=${Db}
2903
+ @dragleave=${Bb}
2906
2904
  >
2907
2905
  ${e.disabledReason?u`<div class="callout">${e.disabledReason}</div>`:w}
2908
2906
 
2909
2907
  ${e.error?u`<div class="callout danger">${e.error}</div>`:w}
2910
2908
 
2911
- ${Mb(e.compactionStatus)}
2909
+ ${Pb(e.compactionStatus)}
2912
2910
 
2913
2911
  ${e.focusMode?u`
2914
2912
  <button
@@ -2929,7 +2927,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
2929
2927
  class="chat-main"
2930
2928
  style="flex: ${p?`0 0 ${d*100}%`:"1 1 100%"}"
2931
2929
  >
2932
- ${v}
2930
+ ${g}
2933
2931
  ${e.nearBottom===!1?u`
2934
2932
  <button
2935
2933
  class="chat-scroll-bottom"
@@ -2949,7 +2947,7 @@ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`
2949
2947
  @resize=${f=>{var b;return(b=e.onSplitRatioChange)==null?void 0:b.call(e,f.detail.splitRatio)}}
2950
2948
  ></resizable-divider>
2951
2949
  <div class="chat-sidebar">
2952
- ${Vy({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
2950
+ ${Qy({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
2953
2951
  ${e.sidebarContent}
2954
2952
  \`\`\``)}})}
2955
2953
  </div>
@@ -2971,13 +2969,13 @@ ${e.sidebarContent}
2971
2969
  `:w}
2972
2970
 
2973
2971
  <div class="chat-compose">
2974
- ${Fb(e)}
2975
- ${c?Gy():u`
2972
+ ${Ub(e)}
2973
+ ${c?Vy():u`
2976
2974
  <div class="chat-compose__row">
2977
2975
  <button
2978
2976
  class="chat-compose__emoji"
2979
2977
  type="button"
2980
- @click=${Nb}
2978
+ @click=${Ob}
2981
2979
  aria-label="Emoji"
2982
2980
  title="Emoji"
2983
2981
  >
@@ -2998,16 +2996,16 @@ ${e.sidebarContent}
2998
2996
  multiple
2999
2997
  accept="image/*,video/*,.pdf,.md,.txt,.csv,.json,.xml,.html,.css,.js,.ts,.py,.sh,.yaml,.yml,.toml,.ini,.cfg,.log,.sql"
3000
2998
  style="display:none"
3001
- @change=${f=>{const b=f.target,k=b.files;if(!(!k||k.length===0||!e.onAttachmentsChange)){for(let A=0;A<k.length;A++)Ib(k[A],e);b.value=""}}}
2999
+ @change=${f=>{const b=f.target,k=b.files;if(!(!k||k.length===0||!e.onAttachmentsChange)){for(let A=0;A<k.length;A++)Lb(k[A],e);b.value=""}}}
3002
3000
  />
3003
3001
  <label class="field chat-compose__field">
3004
3002
  <span>Message</span>
3005
3003
  <textarea
3006
3004
  .value=${e.draft}
3007
3005
  ?disabled=${!e.connected}
3008
- @keydown=${f=>{f.key==="Enter"&&(f.isComposing||f.keyCode===229||f.shiftKey||e.connected&&(f.preventDefault(),t&&(e.onSend(),hl(f.target))))}}
3009
- @input=${f=>{const b=f.target;e.onDraftChange(b.value),Tb(b)}}
3010
- @paste=${f=>Bb(f,e)}
3006
+ @keydown=${f=>{f.key==="Enter"&&(f.isComposing||f.keyCode===229||f.shiftKey||e.connected&&(f.preventDefault(),t&&(e.onSend(),fl(f.target))))}}
3007
+ @input=${f=>{const b=f.target;e.onDraftChange(b.value),_b(b)}}
3008
+ @paste=${f=>Nb(f,e)}
3011
3009
  placeholder=${l}
3012
3010
  ></textarea>
3013
3011
  </label>
@@ -3021,11 +3019,11 @@ ${e.sidebarContent}
3021
3019
  ${L.square}
3022
3020
  </button>
3023
3021
  `:w}
3024
- ${h?jy(e.connected):u`
3022
+ ${h?Gy(e.connected):u`
3025
3023
  <button
3026
3024
  class="btn btn--icon chat-compose__send primary"
3027
3025
  ?disabled=${!e.connected}
3028
- @click=${f=>{var k;e.onSend();const b=(k=f.target.closest(".chat-compose"))==null?void 0:k.querySelector("textarea");b&&hl(b)}}
3026
+ @click=${f=>{var k;e.onSend();const b=(k=f.target.closest(".chat-compose"))==null?void 0:k.querySelector("textarea");b&&fl(b)}}
3029
3027
  aria-label="${n?"Queue":"Send"}"
3030
3028
  title="${n?"Queue message":"Send (Enter)"}"
3031
3029
  >
@@ -3034,13 +3032,13 @@ ${e.sidebarContent}
3034
3032
  </div>`}
3035
3033
  <div class="emoji-picker-popup">
3036
3034
  <emoji-picker
3037
- @emoji-click=${f=>Ob(f,e)}
3035
+ @emoji-click=${f=>Fb(f,e)}
3038
3036
  ></emoji-picker>
3039
3037
  </div>
3040
- ${e.publicMode?w:qb(e)}
3038
+ ${e.publicMode?w:Hb(e)}
3041
3039
  </div>
3042
3040
  </section>
3043
- `}const Ub=[{id:"claude-opus-4-6",shortName:"Opus",description:"Most capable"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet",description:"Fast & capable"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku",description:"Fastest"}];function Wb(e,t){const n=new Set(e.filter(s=>s.provider==="anthropic").map(s=>s.id)),i=Ub.filter(s=>n.has(s.id)).map(s=>({key:`anthropic/${s.id}`,...s}));if(t&&!i.some(s=>s.key===t)){const[s,...o]=t.split("/"),a=o.join("/"),r=e.find(l=>l.provider===s&&l.id===a);r&&i.unshift({key:t,id:r.id,shortName:r.name,description:s})}return i}const Kb=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function zb(e){var s;const t=e.currentTarget,n=(s=t.closest(".chat-model-bar"))==null?void 0:s.querySelector(".chat-settings-menu");if(!n)return;const i=n.classList.contains("active");if(document.querySelectorAll(".chat-settings-menu.active").forEach(o=>o.classList.remove("active")),!i){n.classList.add("active");const o=a=>{!n.contains(a.target)&&a.target!==t&&!t.contains(a.target)&&(n.classList.remove("active"),document.removeEventListener("click",o))};requestAnimationFrame(()=>document.addEventListener("click",o))}}function qb(e){if(!e.connected)return w;const t=e.modelCatalog??[],n=e.modelProvider&&e.model?`${e.modelProvider}/${e.model}`:null,i=Wb(t,n);if(i.length===0)return w;const s=e.thinkingLevel??"off",o=e.verboseLevel==="on"||e.verboseLevel==="full",a=e.fillerEnabled===!0;return u`
3041
+ `}const Wb=[{id:"claude-opus-4-6",shortName:"Opus",description:"Most capable"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet",description:"Fast & capable"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku",description:"Fastest"}];function Kb(e,t){const n=new Set(e.filter(s=>s.provider==="anthropic").map(s=>s.id)),i=Wb.filter(s=>n.has(s.id)).map(s=>({key:`anthropic/${s.id}`,...s}));if(t&&!i.some(s=>s.key===t)){const[s,...o]=t.split("/"),a=o.join("/"),r=e.find(l=>l.provider===s&&l.id===a);r&&i.unshift({key:t,id:r.id,shortName:r.name,description:s})}return i}const zb=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function qb(e){var s;const t=e.currentTarget,n=(s=t.closest(".chat-model-bar"))==null?void 0:s.querySelector(".chat-settings-menu");if(!n)return;const i=n.classList.contains("active");if(document.querySelectorAll(".chat-settings-menu.active").forEach(o=>o.classList.remove("active")),!i){n.classList.add("active");const o=a=>{!n.contains(a.target)&&a.target!==t&&!t.contains(a.target)&&(n.classList.remove("active"),document.removeEventListener("click",o))};requestAnimationFrame(()=>document.addEventListener("click",o))}}function Hb(e){if(!e.connected)return w;const t=e.modelCatalog??[],n=e.modelProvider&&e.model?`${e.modelProvider}/${e.model}`:null,i=Kb(t,n);if(i.length===0)return w;const s=e.thinkingLevel??"off",o=e.verboseLevel==="on"||e.verboseLevel==="full",a=e.fillerEnabled===!0;return u`
3044
3042
  <div class="chat-model-bar">
3045
3043
  <div class="chat-model-bar__select">
3046
3044
  <select
@@ -3061,7 +3059,7 @@ ${e.sidebarContent}
3061
3059
  .value=${s}
3062
3060
  @change=${r=>{const l=r.target.value;e.onThinkingLevelChange&&e.onThinkingLevelChange(l)}}
3063
3061
  >
3064
- ${Kb.map(r=>u`
3062
+ ${zb.map(r=>u`
3065
3063
  <option value=${r.value} ?selected=${r.value===s}>
3066
3064
  Thinking: ${r.label}
3067
3065
  </option>
@@ -3071,7 +3069,7 @@ ${e.sidebarContent}
3071
3069
  <button
3072
3070
  class="chat-model-bar__settings-btn"
3073
3071
  type="button"
3074
- @click=${zb}
3072
+ @click=${qb}
3075
3073
  aria-label="Message settings"
3076
3074
  title="Message settings"
3077
3075
  >
@@ -3098,9 +3096,9 @@ ${e.sidebarContent}
3098
3096
  </label>
3099
3097
  </div>
3100
3098
  </div>
3101
- `}function Hb(e){const t=[];let n=null;for(const i of e){if(i.kind!=="message"){n&&(t.push(n),n=null),t.push(i);continue}const s=Jl(i.message),o=Yl(s.role),a=s.timestamp||Date.now();!n||n.role!==o?(n&&t.push(n),n={kind:"group",key:`group:${o}:${i.key}`,role:o,messages:[{message:i.message,key:i.key}],timestamp:a,isStreaming:!1}):n.messages.push({message:i.message,key:i.key})}return n&&t.push(n),t}function jb(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=Jl(r);if(!s&&l.role.toLowerCase()==="toolresult"){const c=r,d=(Array.isArray(c.content)?c.content:[]).filter(p=>{const v=p.type;return v==="image"||v==="file"});d.length>0&&t.push({kind:"message",key:ao(r,a),message:{role:"assistant",content:d,timestamp:l.timestamp}});continue}t.push({kind:"message",key:ao(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:ao(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(", ")}
3099
+ `}function jb(e){const t=[];let n=null;for(const i of e){if(i.kind!=="message"){n&&(t.push(n),n=null),t.push(i);continue}const s=Yl(i.message),o=Xl(s.role),a=s.timestamp||Date.now();!n||n.role!==o?(n&&t.push(n),n={kind:"group",key:`group:${o}:${i.key}`,role:o,messages:[{message:i.message,key:i.key}],timestamp:a,isStreaming:!1}):n.messages.push({message:i.message,key:i.key})}return n&&t.push(n),t}function Gb(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=Yl(r);if(!s&&l.role.toLowerCase()==="toolresult"){const c=r,d=(Array.isArray(c.content)?c.content:[]).filter(p=>{const g=p.type;return g==="image"||g==="file"});d.length>0&&t.push({kind:"message",key:ro(r,a),message:{role:"assistant",content:d,timestamp:l.timestamp}});continue}t.push({kind:"message",key:ro(r,a),message:r})}if(s)for(let a=0;a<i.length;a++)t.push({kind:"message",key:ro(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(", ")}
3102
3100
 
3103
- ${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 Hb(t)}function ao(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}`}const Gb=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 Vb(e){if(!e.connected)return u`
3101
+ ${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 jb(t)}function ro(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}`}const Vb=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 Qb(e){if(!e.connected)return u`
3104
3102
  <div class="setup-container">
3105
3103
  <div class="setup-card">
3106
3104
  <div class="setup-spinner"></div>
@@ -3113,21 +3111,21 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3113
3111
  target="_blank"
3114
3112
  rel="noopener"
3115
3113
  title="Open public chat in new tab"
3116
- >Public ${Gb}</a>`:w;return u`
3114
+ >Public ${Vb}</a>`:w;return u`
3117
3115
  <div class="setup-container setup-container--full chat-page">
3118
- ${Lt("Chat",e.wsProps)}
3116
+ ${Rt("Chat",e.wsProps)}
3119
3117
  ${t}
3120
3118
  <div class="chat-viewport">
3121
- ${ou(e)}
3119
+ ${au(e)}
3122
3120
  </div>
3123
3121
  </div>
3124
- `}function Qb(e){return e?`${jl(e)} (${is(e)})`:"n/a"}function au(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?is(t.lastRunAtMs):"never";return`${n} · last ${i}`}function ru(e){const t=e.schedule;return t.kind==="at"?`One-time: ${jl(t.atMs)}`:t.kind==="every"?`Every ${Qo(t.everyMs)}`:Jb(t.expr,t.tz)}function Jb(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,T)=>new Date(2e3,0,1,x,T).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),h=/^\d{1,2}$/.test(i)?parseInt(i,10):null,d=fl(s);if(h===null||!d)return`${e}${t?` (${t})`:""}`;const p=d.map(x=>c(x,h)),v=p.length<=3?p.join(" & "):`${p.slice(0,-1).join(", ")} & ${p[p.length-1]}`,S=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&a==="*"){if(r==="*")return`Daily at ${v}${l}`;if(r==="1-5")return`Weekdays at ${v}${l}`;if(r==="0,6"||r==="6,0")return`Weekends at ${v}${l}`;const x=fl(r);if(x)return`${x.map(f=>S[f%7]??String(f)).join(", ")} at ${v}${l}`}return`${e}${t?` (${t})`:""}`}function fl(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 Yb(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 gl(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 we=null;function Xb(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 Zb(e,t){var i,s;if(t==="last")return"last";const n=(i=e.channelMeta)==null?void 0:i.find(o=>o.id===t);return n!=null&&n.label?n.label:((s=e.channelLabels)==null?void 0:s[t])??t}function ew(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function tw(e){return e||"Default"}const nw=u`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,iw=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>`,sw=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>`,ps=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,ow=u`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,lu=u`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,aw=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 ml(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return u`
3125
- ${rw(e)}
3122
+ `}function Jb(e){return e?`${Gl(e)} (${ss(e)})`:"n/a"}function ru(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?ss(t.lastRunAtMs):"never";return`${n} · last ${i}`}function lu(e){const t=e.schedule;return t.kind==="at"?`One-time: ${Gl(t.atMs)}`:t.kind==="every"?`Every ${Jo(t.everyMs)}`:Yb(t.expr,t.tz)}function Yb(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=(S,T)=>new Date(2e3,0,1,S,T).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),h=/^\d{1,2}$/.test(i)?parseInt(i,10):null,d=gl(s);if(h===null||!d)return`${e}${t?` (${t})`:""}`;const p=d.map(S=>c(S,h)),g=p.length<=3?p.join(" & "):`${p.slice(0,-1).join(", ")} & ${p[p.length-1]}`,x=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&a==="*"){if(r==="*")return`Daily at ${g}${l}`;if(r==="1-5")return`Weekdays at ${g}${l}`;if(r==="0,6"||r==="6,0")return`Weekends at ${g}${l}`;const S=gl(r);if(S)return`${S.map(f=>x[f%7]??String(f)).join(", ")} at ${g}${l}`}return`${e}${t?` (${t})`:""}`}function gl(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 Xb(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 ml(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 we=null;function Zb(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 ew(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 tw(e){return e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.toLowerCase()==="admins"?"All admins":n).join(", ")}function nw(e){return e||"Default"}const iw=u`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,sw=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>`,ow=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>`,hs=u`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,aw=u`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,cu=u`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`,rw=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 yl(e){const t=e.detailJobId?e.jobs.find(i=>i.id===e.detailJobId)??null:null,n=e.newEventModalOpen||!!e.editJobId;return u`
3126
3123
  ${lw(e)}
3127
- ${n?dw(e):w}
3128
- ${t?hw(t,e):w}
3129
- ${e.runModalJobId?fw(e):w}
3130
- `}function rw(e){const t=e.status,n=(t==null?void 0:t.enabled)??!1,i=(t==null?void 0:t.jobs)??0,s=t==null?void 0:t.nextWakeAtMs;return u`
3124
+ ${cw(e)}
3125
+ ${n?uw(e):w}
3126
+ ${t?fw(t,e):w}
3127
+ ${e.runModalJobId?gw(e):w}
3128
+ `}function lw(e){const t=e.status,n=(t==null?void 0:t.enabled)??!1,i=(t==null?void 0:t.jobs)??0,s=t==null?void 0:t.nextWakeAtMs;return u`
3131
3129
  <div class="event-status-bar">
3132
3130
  <div class="event-status-bar__info">
3133
3131
  <span class="statusDot ${n?"ok":""}"></span>
@@ -3136,7 +3134,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3136
3134
  <span>${i} event${i!==1?"s":""}</span>
3137
3135
  ${s?u`
3138
3136
  <span class="event-status-bar__sep">\u00b7</span>
3139
- <span>Next: ${is(s)}</span>
3137
+ <span>Next: ${ss(s)}</span>
3140
3138
  `:w}
3141
3139
  <button
3142
3140
  class="btn btn--sm"
@@ -3149,14 +3147,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3149
3147
  ${e.error?u`<span class="muted">${e.error}</span>`:w}
3150
3148
  </div>
3151
3149
  <button class="btn primary btn--sm" @click=${e.onNewEventModalOpen}>
3152
- ${lu} New Event
3150
+ ${cu} New Event
3153
3151
  </button>
3154
3152
  </div>
3155
- `}function lw(e){return e.jobs.length===0?u`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:u`
3153
+ `}function cw(e){return e.jobs.length===0?u`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:u`
3156
3154
  <div class="event-grid">
3157
- ${e.jobs.map(t=>cw(t,e))}
3155
+ ${e.jobs.map(t=>dw(t,e))}
3158
3156
  </div>
3159
- `}function cw(e,t){return u`
3157
+ `}function dw(e,t){return u`
3160
3158
  <div
3161
3159
  class="event-card ${e.enabled?"":"disabled"}"
3162
3160
  @click=${()=>t.onDetailOpen(e)}
@@ -3167,12 +3165,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3167
3165
  ${e.enabled?"On":"Off"}
3168
3166
  </span>
3169
3167
  </div>
3170
- <div class="event-card__schedule">${ru(e)}</div>
3171
- ${e.agentId?u`<div class="event-card__agent">${tw(e.agentId)}</div>`:w}
3172
- ${gl(e)?u`<div class="event-card__agent muted" style="font-size: 11px;">\u2192 ${gl(e)}</div>`:w}
3168
+ <div class="event-card__schedule">${lu(e)}</div>
3169
+ ${e.agentId?u`<div class="event-card__agent">${nw(e.agentId)}</div>`:w}
3170
+ ${ml(e)?u`<div class="event-card__agent muted" style="font-size: 11px;">\u2192 ${ml(e)}</div>`:w}
3173
3171
  <div class="event-card__footer">
3174
3172
  <div class="event-card__status">
3175
- <span class="muted" style="font-size: 11px;">${au(e)}</span>
3173
+ <span class="muted" style="font-size: 11px;">${ru(e)}</span>
3176
3174
  </div>
3177
3175
  <div class="event-card__actions" @click=${n=>n.stopPropagation()}>
3178
3176
  <button
@@ -3181,7 +3179,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3181
3179
  ?disabled=${t.busy}
3182
3180
  @click=${()=>t.onToggle(e,!e.enabled)}
3183
3181
  >
3184
- ${e.enabled?iw:nw}
3182
+ ${e.enabled?sw:iw}
3185
3183
  </button>
3186
3184
  <button
3187
3185
  class="btn-icon"
@@ -3189,7 +3187,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3189
3187
  ?disabled=${t.busy}
3190
3188
  @click=${()=>t.onRun(e)}
3191
3189
  >
3192
- ${ow}
3190
+ ${aw}
3193
3191
  </button>
3194
3192
  ${t.pendingDeleteId===e.id?u`<button
3195
3193
  class="btn danger btn--sm"
@@ -3200,17 +3198,17 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3200
3198
  title="Delete"
3201
3199
  ?disabled=${t.busy}
3202
3200
  @click=${()=>{t.onArmDelete(e.id),we&&clearTimeout(we),we=setTimeout(()=>{t.onArmDelete(""),we=null},3e3)}}
3203
- >${sw}</button>`}
3201
+ >${ow}</button>`}
3204
3202
  </div>
3205
3203
  </div>
3206
3204
  </div>
3207
- `}function dw(e){const t=!!e.editJobId,n=Xb(e),i=()=>{e.onNewEventModalClose()};return u`
3205
+ `}function uw(e){const t=!!e.editJobId,n=Zb(e),i=()=>{e.onNewEventModalClose()};return u`
3208
3206
  <div class="event-modal-overlay" @click=${i}>
3209
3207
  <div class="event-modal" @click=${s=>s.stopPropagation()}>
3210
3208
  <div class="event-modal__header">
3211
3209
  <div class="event-modal__title">${t?"Edit Event":"New Event"}</div>
3212
3210
  <button class="event-modal__close" @click=${i}>
3213
- ${ps}
3211
+ ${hs}
3214
3212
  </button>
3215
3213
  </div>
3216
3214
 
@@ -3262,7 +3260,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3262
3260
  </label>
3263
3261
  </div>
3264
3262
 
3265
- ${pw(e)}
3263
+ ${hw(e)}
3266
3264
 
3267
3265
  <div class="form-grid" style="margin-top: 12px;">
3268
3266
  <label class="field">
@@ -3324,7 +3322,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3324
3322
  @change=${s=>e.onFormChange({channel:s.target.value})}
3325
3323
  >
3326
3324
  ${n.map(s=>u`<option value=${s}>
3327
- ${Zb(e,s)}
3325
+ ${ew(e,s)}
3328
3326
  </option>`)}
3329
3327
  </select>
3330
3328
  </label>
@@ -3337,7 +3335,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3337
3335
  />
3338
3336
  </label>
3339
3337
  </div>
3340
- ${uw(e)}
3338
+ ${pw(e)}
3341
3339
  <div class="form-grid" style="margin-top: 12px;">
3342
3340
  <label class="field">
3343
3341
  <span>Timeout (seconds)</span>
@@ -3368,7 +3366,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3368
3366
  </div>
3369
3367
  </div>
3370
3368
  </div>
3371
- `}function uw(e){const t=e.form.recipients;return u`
3369
+ `}function pw(e){const t=e.form.recipients;return u`
3372
3370
  <div style="margin-top: 8px;">
3373
3371
  <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
3374
3372
  <span style="font-size: 13px; color: var(--muted);">Recipients</span>
@@ -3376,7 +3374,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3376
3374
  class="btn btn--sm"
3377
3375
  @click=${()=>{e.onFormChange({recipients:[...t,""]})}}
3378
3376
  >
3379
- ${lu} Add
3377
+ ${cu} Add
3380
3378
  </button>
3381
3379
  </div>
3382
3380
  ${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}
@@ -3393,12 +3391,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3393
3391
  title="Remove"
3394
3392
  @click=${()=>{const s=t.filter((o,a)=>a!==i);e.onFormChange({recipients:s})}}
3395
3393
  >
3396
- ${ps}
3394
+ ${hs}
3397
3395
  </button>
3398
3396
  </div>
3399
3397
  `)}
3400
3398
  </div>
3401
- `}function pw(e){const t=e.form;return t.scheduleKind==="at"?u`
3399
+ `}function hw(e){const t=e.form;return t.scheduleKind==="at"?u`
3402
3400
  <label class="field" style="margin-top: 12px;">
3403
3401
  <span>Run at</span>
3404
3402
  <input
@@ -3447,13 +3445,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3447
3445
  />
3448
3446
  </label>
3449
3447
  </div>
3450
- `}function hw(e,t){var n;return u`
3448
+ `}function fw(e,t){var n;return u`
3451
3449
  <div class="event-modal-overlay" @click=${t.onDetailClose}>
3452
3450
  <div class="event-modal" @click=${i=>i.stopPropagation()}>
3453
3451
  <div class="event-modal__header">
3454
3452
  <div class="event-modal__title">${e.name||"Untitled Event"}</div>
3455
3453
  <button class="event-modal__close" @click=${t.onDetailClose}>
3456
- ${ps}
3454
+ ${hs}
3457
3455
  </button>
3458
3456
  </div>
3459
3457
 
@@ -3465,7 +3463,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3465
3463
  ?disabled=${t.busy}
3466
3464
  @click=${()=>t.onEdit(e)}
3467
3465
  >
3468
- ${aw} Edit
3466
+ ${rw} Edit
3469
3467
  </button>
3470
3468
  <button
3471
3469
  class="btn"
@@ -3501,7 +3499,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3501
3499
  </div>
3502
3500
  <div class="event-detail-row">
3503
3501
  <span class="event-detail-label">Schedule</span>
3504
- <span class="event-detail-value">${ru(e)}</span>
3502
+ <span class="event-detail-value">${lu(e)}</span>
3505
3503
  </div>
3506
3504
  ${e.agentId?u`
3507
3505
  <div class="event-detail-row">
@@ -3523,12 +3521,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3523
3521
  </div>
3524
3522
  <div class="event-detail-row" style="flex-direction: column; align-items: stretch; gap: 4px;">
3525
3523
  <span class="event-detail-label">Action</span>
3526
- <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${Yb(e,!1)}</span>
3524
+ <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${Xb(e,!1)}</span>
3527
3525
  </div>
3528
3526
  ${e.payload.kind==="agentTurn"&&e.payload.to?u`
3529
3527
  <div class="event-detail-row">
3530
3528
  <span class="event-detail-label">Send to</span>
3531
- <span class="event-detail-value mono">${ew(e.payload.to)}</span>
3529
+ <span class="event-detail-value mono">${tw(e.payload.to)}</span>
3532
3530
  </div>
3533
3531
  `:w}
3534
3532
  ${e.payload.kind==="agentTurn"&&(e.payload.channel??e.payload.provider)?u`
@@ -3548,12 +3546,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3548
3546
  <div class="event-detail-section">
3549
3547
  <div class="event-detail-row">
3550
3548
  <span class="event-detail-label">Last run</span>
3551
- <span class="event-detail-value">${au(e)}</span>
3549
+ <span class="event-detail-value">${ru(e)}</span>
3552
3550
  </div>
3553
3551
  ${(n=e.state)!=null&&n.nextRunAtMs?u`
3554
3552
  <div class="event-detail-row">
3555
3553
  <span class="event-detail-label">Next run</span>
3556
- <span class="event-detail-value">${Qb(e.state.nextRunAtMs)}</span>
3554
+ <span class="event-detail-value">${Jb(e.state.nextRunAtMs)}</span>
3557
3555
  </div>
3558
3556
  `:w}
3559
3557
  </div>
@@ -3564,20 +3562,20 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3564
3562
  </div>
3565
3563
  ${t.runs.length===0?u`<div class="muted" style="font-size: 13px;">No runs recorded yet.</div>`:u`
3566
3564
  <div class="list">
3567
- ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>mw(i))}
3565
+ ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>yw(i))}
3568
3566
  </div>
3569
3567
  `}
3570
3568
  </div>
3571
3569
 
3572
3570
  </div>
3573
3571
  </div>
3574
- `}function fw(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)??"";return u`
3572
+ `}function gw(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)??"";return u`
3575
3573
  <div class="event-modal-overlay" @click=${e.onRunModalClose}>
3576
3574
  <div class="event-modal" style="max-width: 480px;" @click=${s=>s.stopPropagation()}>
3577
3575
  <div class="event-modal__header">
3578
3576
  <div class="event-modal__title">${e.runModalJobName}</div>
3579
3577
  <button class="event-modal__close" @click=${e.onRunModalClose}>
3580
- ${ps}
3578
+ ${hs}
3581
3579
  </button>
3582
3580
  </div>
3583
3581
 
@@ -3597,7 +3595,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3597
3595
  >
3598
3596
  ${i}
3599
3597
  </span>
3600
- ${t.durationMs!=null?u`<span class="muted" style="font-size: 13px;">${Qo(t.durationMs)}</span>`:w}
3598
+ ${t.durationMs!=null?u`<span class="muted" style="font-size: 13px;">${Jo(t.durationMs)}</span>`:w}
3601
3599
  </div>
3602
3600
  ${t.summary?u`
3603
3601
  <div style="white-space: pre-wrap; font-size: 13px; line-height: 1.6; max-height: 400px; overflow-y: auto; color: var(--fg);">
@@ -3618,14 +3616,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3618
3616
  `}
3619
3617
  </div>
3620
3618
  </div>
3621
- `}function gw(e){const t=e.toLowerCase();return t==="ok"||t==="success"?"chip chip-ok":t==="error"||t==="fail"||t==="failed"?"chip chip-warn":"chip"}function mw(e){return u`
3619
+ `}function mw(e){const t=e.toLowerCase();return t==="ok"||t==="success"?"chip chip-ok":t==="error"||t==="fail"||t==="failed"?"chip chip-warn":"chip"}function yw(e){return u`
3622
3620
  <div class="list-item" style="grid-template-columns: 1fr; gap: 6px;">
3623
3621
  <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
3624
- <span class=${gw(e.status)} style="font-size: 11px; padding: 2px 8px;">
3622
+ <span class=${mw(e.status)} style="font-size: 11px; padding: 2px 8px;">
3625
3623
  ${e.status}
3626
3624
  </span>
3627
- <span class="muted" style="font-size: 12px;">${is(e.ts)}</span>
3628
- <span class="muted" style="font-size: 12px;">${Qo(e.durationMs)}</span>
3625
+ <span class="muted" style="font-size: 12px;">${ss(e.ts)}</span>
3626
+ <span class="muted" style="font-size: 12px;">${Jo(e.durationMs)}</span>
3629
3627
  </div>
3630
3628
  ${e.summary?u`<div class="muted" style="font-size: 12px;">${e.summary}</div>`:w}
3631
3629
  ${e.error?u`
@@ -3635,7 +3633,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3635
3633
  </details>
3636
3634
  `:w}
3637
3635
  </div>
3638
- `}function yw(e){var a;const t=((a=e.report)==null?void 0:a.skills)??[],n=e.filter.trim().toLowerCase(),i=e.typeFilter,s=t.filter(r=>i==="preloaded"&&!r.preloaded||i==="user"&&r.preloaded?!1:n?[r.name,r.description].join(" ").toLowerCase().includes(n):!0),o=(r,l)=>u`
3636
+ `}function vw(e){var a;const t=((a=e.report)==null?void 0:a.skills)??[],n=e.filter.trim().toLowerCase(),i=e.typeFilter,s=t.filter(r=>i==="preloaded"&&!r.preloaded||i==="user"&&r.preloaded?!1:n?[r.name,r.description].join(" ").toLowerCase().includes(n):!0),o=(r,l)=>u`
3639
3637
  <button
3640
3638
  class="chip ${i===l?"chip-ok":""}"
3641
3639
  style="cursor: pointer; border: none; background: ${i===l?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${i===l?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
@@ -3677,20 +3675,20 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3677
3675
 
3678
3676
  ${s.length===0?u`<div class="muted" style="margin-top: 16px;">No skills found.</div>`:u`
3679
3677
  <div class="list" style="margin-top: 16px;">
3680
- ${s.map(r=>vw(r,e))}
3678
+ ${s.map(r=>bw(r,e))}
3681
3679
  </div>
3682
3680
  `}
3683
3681
  </section>
3684
3682
 
3685
- ${e.detail?bw(e):w}
3686
- ${e.addModal?ww(e):w}
3687
- `}function vw(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`
3683
+ ${e.detail?ww(e):w}
3684
+ ${e.addModal?kw(e):w}
3685
+ `}function bw(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`
3688
3686
  <div class="list-item" style="cursor: pointer;" @click=${()=>t.onViewDetail(e.name)}>
3689
3687
  <div class="list-main">
3690
3688
  <div class="list-title">
3691
3689
  ${e.emoji?`${e.emoji} `:""}${e.name}
3692
3690
  </div>
3693
- <div class="list-sub">${Ap(e.description,140)}</div>
3691
+ <div class="list-sub">${Cp(e.description,140)}</div>
3694
3692
  <div class="chip-row" style="margin-top: 6px;">
3695
3693
  <span class="chip ${e.preloaded?"chip-ok":""}">
3696
3694
  ${e.preloaded?"Preloaded":"User"}
@@ -3765,7 +3763,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3765
3763
  `:w}
3766
3764
  </div>
3767
3765
  </div>
3768
- `}function bw(e){var l,c,h;const t=e.detail,n=["SKILL.md",...t.references.map(d=>d.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((l=t.references.find(d=>d.name===i))==null?void 0:l.content)??"",o=d=>{d.target.classList.contains("event-modal-overlay")&&e.onDetailClose()},a=(h=(c=e.report)==null?void 0:c.skills)==null?void 0:h.find(d=>d.name===t.name),r=a?!a.preloaded:!1;return u`
3766
+ `}function ww(e){var l,c,h;const t=e.detail,n=["SKILL.md",...t.references.map(d=>d.name)],i=e.detailTab||"SKILL.md",s=i==="SKILL.md"?t.content:((l=t.references.find(d=>d.name===i))==null?void 0:l.content)??"",o=d=>{d.target.classList.contains("event-modal-overlay")&&e.onDetailClose()},a=(h=(c=e.report)==null?void 0:c.skills)==null?void 0:h.find(d=>d.name===t.name),r=a?!a.preloaded:!1;return u`
3769
3767
  <div class="event-modal-overlay" @click=${o}>
3770
3768
  <div class="event-modal" style="width: min(720px, 100%);" @click=${d=>d.stopPropagation()}>
3771
3769
  <div class="event-modal__header">
@@ -3791,7 +3789,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3791
3789
  <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>
3792
3790
  </div>
3793
3791
  </div>
3794
- `}function ww(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`
3792
+ `}function kw(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`
3795
3793
  <div class="event-modal-overlay" @click=${o}>
3796
3794
  <div class="event-modal" style="width: min(620px, 100%);" @click=${r=>r.stopPropagation()}>
3797
3795
  <div class="event-modal__header">
@@ -3799,14 +3797,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3799
3797
  <button class="event-modal__close" @click=${e.onAddClose}>&times;</button>
3800
3798
  </div>
3801
3799
 
3802
- ${i?kw(e,n):t?$w(e,n):u`
3800
+ ${i?$w(e,n):t?xw(e,n):u`
3803
3801
  <div class="muted" style="text-align: center; padding: 32px 16px;">
3804
3802
  No drafts available. Ask your assistant to create a skill and it will appear here.
3805
3803
  </div>
3806
3804
  `}
3807
3805
  </div>
3808
3806
  </div>
3809
- `}function kw(e,t){const n=e.addForm,s=e.formSource==="installed"?"Save Skill":"Save Draft",o=n.references.length>0,a=e.editTab||"SKILL.md",r=n.references.find(c=>c.name===a),l=c=>u`
3807
+ `}function $w(e,t){const n=e.addForm,s=e.formSource==="installed"?"Save Skill":"Save Draft",o=n.references.length>0,a=e.editTab||"SKILL.md",r=n.references.find(c=>c.name===a),l=c=>u`
3810
3808
  <button
3811
3809
  class="chip ${c===a?"chip-ok":""}"
3812
3810
  style="cursor: pointer; border: none; background: ${c===a?"var(--accent, #3b82f6)":"var(--bg-hover, rgba(255,255,255,0.06))"}; color: ${c===a?"#fff":"var(--text)"}; padding: 4px 10px; border-radius: 4px; font-size: 12px;"
@@ -3857,7 +3855,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3857
3855
  ${t?"Saving…":s}
3858
3856
  </button>
3859
3857
  </div>
3860
- `}function $w(e,t){return u`
3858
+ `}function xw(e,t){return u`
3861
3859
  <div class="card-sub" style="margin-bottom: 16px;">
3862
3860
  Skills prepared by your assistant. Review, install, or delete.
3863
3861
  </div>
@@ -3898,7 +3896,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3898
3896
  </div>
3899
3897
  `})}
3900
3898
  </div>
3901
- `}const xw=["user","assistant","tool_call","tool_result","thinking","error"],yl={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function cu(e){return e==="tool"?"tool_call":e}function Sw(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 Aw(e){return e.split(":").slice(2).join(":")||e}function Cw(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Ew(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const vl=300;function Tw(e,t){const n=cu(e);return t[n]??!0}function _w(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!Tw(i.type,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:Cw(i,t));return u`
3899
+ `}const Sw=["user","assistant","tool_call","tool_result","thinking","error"],vl={user:"User",assistant:"Assistant",tool:"Tool",tool_call:"Call",tool_result:"Result",thinking:"Thinking",error:"Error",system:"System"};function du(e){return e==="tool"?"tool_call":e}function Aw(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 Cw(e){return e.split(":").slice(2).join(":")||e}function Ew(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName,e.toolCallId].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Tw(e,t){return`${e.sessionId}:${e.timestamp}:${t}`}const bl=300;function _w(e,t){const n=du(e);return t[n]??!0}function Mw(e){const t=e.filterText.trim().toLowerCase(),n=e.entries.filter(i=>!_w(i.type,e.typeFilters)||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:Ew(i,t));return u`
3902
3900
  <div>
3903
3901
  <button class="chips-toggle" style="margin-top: 10px;" @click=${e.onToggleChips}>
3904
3902
  <span class="chips-toggle-icon ${e.chipsExpanded?"expanded":""}">${L.chevronDown}</span>
@@ -3906,14 +3904,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3906
3904
  </button>
3907
3905
  ${e.chipsExpanded?u`
3908
3906
  <div class="chip-row" style="margin-top: 6px;">
3909
- ${xw.map(i=>u`
3907
+ ${Sw.map(i=>u`
3910
3908
  <label class="chip session-log-chip ${i}">
3911
3909
  <input
3912
3910
  type="checkbox"
3913
3911
  .checked=${e.typeFilters[i]}
3914
3912
  @change=${s=>e.onTypeToggle(i,s.target.checked)}
3915
3913
  />
3916
- <span>${yl[i]}</span>
3914
+ <span>${vl[i]}</span>
3917
3915
  </label>
3918
3916
  `)}
3919
3917
  ${e.agents.map(i=>u`
@@ -3940,13 +3938,13 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3940
3938
  ${e.error?u`<div class="callout danger" style="margin-top: 10px;">${e.error}</div>`:w}
3941
3939
 
3942
3940
  <div class="log-stream" style="margin-top: 10px;" @scroll=${e.onScroll}>
3943
- ${n.length===0?u`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=cu(i.type),a=Ew(i,s),r=e.expandedIds.has(a),l=i.content.length>vl,c=r||!l?i.content:i.content.slice(0,vl)+"…";return u`
3941
+ ${n.length===0?u`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map((i,s)=>{const o=du(i.type),a=Tw(i,s),r=e.expandedIds.has(a),l=i.content.length>bl,c=r||!l?i.content:i.content.slice(0,bl)+"…";return u`
3944
3942
  <div class="log-row session-entry ${o}">
3945
3943
  <div class="log-row-header">
3946
- <span class="log-time mono">${Sw(i.timestamp)}</span>
3947
- <span class="session-log-type ${o}">${yl[o]}</span>
3944
+ <span class="log-time mono">${Aw(i.timestamp)}</span>
3945
+ <span class="session-log-type ${o}">${vl[o]}</span>
3948
3946
  <span class="log-subsystem mono">${i.agentId}</span>
3949
- <span class="session-label mono">${Aw(i.sessionKey)}</span>
3947
+ <span class="session-label mono">${Cw(i.sessionKey)}</span>
3950
3948
  ${i.toolName?u`<span class="session-tool mono">${i.toolName}</span>`:w}
3951
3949
  ${i.toolCallId?u`<span class="session-call-id mono">${i.toolCallId.slice(0,12)}</span>`:w}
3952
3950
  ${i.model?u`<span class="session-model mono">${i.model}</span>`:w}
@@ -3960,7 +3958,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
3960
3958
  `})}
3961
3959
  </div>
3962
3960
  </div>
3963
- `}const Fo=["trace","debug","info","warn","error","fatal"];function Mw(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function du(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Pw(e){const t=e.logsSubTab==="session";return u`
3961
+ `}const Uo=["trace","debug","info","warn","error","fatal"];function Pw(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function uu(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Iw(e){const t=e.logsSubTab==="session";return u`
3964
3962
  <section class="card">
3965
3963
  <div class="logs-toolbar">
3966
3964
  <div class="sp-tabs" style="margin: 0;">
@@ -4009,7 +4007,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4009
4007
  <button
4010
4008
  class="btn btn-sm"
4011
4009
  ?disabled=${e.entries.length===0}
4012
- @click=${()=>{const n=e.filterText.trim().toLowerCase(),i=Fo.some(a=>!e.levelFilters[a]),s=e.entries.filter(a=>a.level&&!e.levelFilters[a.level]?!1:du(a,n)),o=n||i?"filtered":"visible";e.onExport(s.map(a=>a.raw),o)}}
4010
+ @click=${()=>{const n=e.filterText.trim().toLowerCase(),i=Uo.some(a=>!e.levelFilters[a]),s=e.entries.filter(a=>a.level&&!e.levelFilters[a.level]?!1:uu(a,n)),o=n||i?"filtered":"visible";e.onExport(s.map(a=>a.raw),o)}}
4013
4011
  >
4014
4012
  Export
4015
4013
  </button>
@@ -4017,16 +4015,16 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4017
4015
  </div>
4018
4016
  </div>
4019
4017
 
4020
- ${t?_w(e.sessionLogsProps):Iw(e)}
4018
+ ${t?Mw(e.sessionLogsProps):Lw(e)}
4021
4019
  </section>
4022
- `}function Iw(e){const t=e.filterText.trim().toLowerCase();Fo.some(i=>!e.levelFilters[i]);const n=e.entries.filter(i=>i.level&&!e.levelFilters[i.level]?!1:du(i,t));return u`
4020
+ `}function Lw(e){const t=e.filterText.trim().toLowerCase();Uo.some(i=>!e.levelFilters[i]);const n=e.entries.filter(i=>i.level&&!e.levelFilters[i.level]?!1:uu(i,t));return u`
4023
4021
  <button class="chips-toggle" @click=${e.onToggleChips}>
4024
4022
  <span class="chips-toggle-icon ${e.chipsExpanded?"expanded":""}">${L.chevronDown}</span>
4025
4023
  Filters
4026
4024
  </button>
4027
4025
  ${e.chipsExpanded?u`
4028
4026
  <div class="chip-row" style="margin-top: 6px; align-items: center;">
4029
- ${Fo.map(i=>u`
4027
+ ${Uo.map(i=>u`
4030
4028
  <label class="chip log-chip ${i}">
4031
4029
  <input
4032
4030
  type="checkbox"
@@ -4057,7 +4055,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4057
4055
  ${n.length===0?u`<div class="muted" style="padding: 12px;">No log entries.</div>`:[...n].reverse().map(i=>u`
4058
4056
  <div class="log-row">
4059
4057
  <div class="log-row-header">
4060
- <span class="log-time mono">${Mw(i.time)}</span>
4058
+ <span class="log-time mono">${Pw(i.time)}</span>
4061
4059
  <span class="log-level ${i.level??""}">${i.level??""}</span>
4062
4060
  <span class="log-subsystem mono">${i.subsystem??""}</span>
4063
4061
  </div>
@@ -4065,12 +4063,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4065
4063
  </div>
4066
4064
  `)}
4067
4065
  </div>
4068
- `}const Lw=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"logs",label:"Logs"}];function Rw(e){switch(e.activeTab){case"cron":return ml(e.cronProps);case"skills":return yw(e.skillsProps);case"logs":return Pw(e.logsProps);default:return ml(e.cronProps)}}function Dw(e){return e.connected?u`
4066
+ `}const Rw=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"logs",label:"Logs"}];function Dw(e){switch(e.activeTab){case"cron":return yl(e.cronProps);case"skills":return vw(e.skillsProps);case"logs":return Iw(e.logsProps);default:return yl(e.cronProps)}}function Bw(e){return e.connected?u`
4069
4067
  <div class="setup-container">
4070
- ${Lt("Advanced",e.wsProps)}
4068
+ ${Rt("Advanced",e.wsProps)}
4071
4069
  <div class="setup-card sp-card-advanced" style="text-align: left;">
4072
4070
  <div class="sp-tabs">
4073
- ${Lw.map(t=>u`
4071
+ ${Rw.map(t=>u`
4074
4072
  <button
4075
4073
  class="sp-tab ${e.activeTab===t.id?"active":""}"
4076
4074
  @click=${()=>e.onTabChange(t.id)}
@@ -4079,7 +4077,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4079
4077
  </button>
4080
4078
  `)}
4081
4079
  </div>
4082
- ${Rw(e)}
4080
+ ${Dw(e)}
4083
4081
  </div>
4084
4082
  </div>
4085
4083
  `:u`
@@ -4089,19 +4087,19 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4089
4087
  <p>Connecting to gateway...</p>
4090
4088
  </div>
4091
4089
  </div>
4092
- `}function bl(e){if(!e.show)return w;const t=Ye(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const a=v=>{var x;o=v.target.value;const S=(x=v.target.closest(".login-card"))==null?void 0:x.querySelector(".login-change-pin");S&&(S.style.display=o==="__master__"?"":"none")},r=v=>S=>{const x=S.target;x.value=x.value.replace(/\D/g,"").slice(0,6),v(x.value)},l=v=>{const S=v.currentTarget,x=S.closest(".login-pin-wrapper"),T=x==null?void 0:x.querySelector("input");if(!T)return;const f=T.type==="text";T.type=f?"password":"text",S.classList.toggle("active",!f)},c=!n&&e.accounts.length>1?u`
4090
+ `}function wl(e){if(!e.show)return w;const t=Ye(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const a=g=>{var S;o=g.target.value;const x=(S=g.target.closest(".login-card"))==null?void 0:S.querySelector(".login-change-pin");x&&(x.style.display=o==="__master__"?"":"none")},r=g=>x=>{const S=x.target;S.value=S.value.replace(/\D/g,"").slice(0,6),g(S.value)},l=g=>{const x=g.currentTarget,S=x.closest(".login-pin-wrapper"),T=S==null?void 0:S.querySelector("input");if(!T)return;const f=T.type==="text";T.type=f?"password":"text",x.classList.toggle("active",!f)},c=!n&&e.accounts.length>1?u`
4093
4091
  <select
4094
4092
  class="login-account-select"
4095
4093
  @change=${a}
4096
4094
  ?disabled=${e.busy||s}
4097
4095
  >
4098
- ${e.accounts.map((v,S)=>u`
4099
- <option value=${v.id} ?selected=${S===0}>
4100
- ${v.displayName}
4096
+ ${e.accounts.map((g,x)=>u`
4097
+ <option value=${g.id} ?selected=${x===0}>
4098
+ ${g.displayName}
4101
4099
  </option>
4102
4100
  `)}
4103
4101
  </select>
4104
- `:w;if(i){let v="",S="",x="";const T=f=>{var b;f.preventDefault(),!s&&(!v||!S||!x||S===x&&o&&((b=e.onChangePin)==null||b.call(e,o,v,S)))};return u`
4102
+ `:w;if(i){let g="",x="",S="";const T=f=>{var b;f.preventDefault(),!s&&(!g||!x||!S||x===S&&o&&((b=e.onChangePin)==null||b.call(e,o,g,x)))};return u`
4105
4103
  <div class="login-overlay">
4106
4104
  <div class="login-card">
4107
4105
  <img class="login-logo" src="${t.iconUrl}" alt="${t.name}" />
@@ -4119,7 +4117,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4119
4117
  maxlength="6"
4120
4118
  placeholder="Current PIN"
4121
4119
  ?disabled=${s}
4122
- @input=${r(f=>{v=f})}
4120
+ @input=${r(f=>{g=f})}
4123
4121
  autofocus
4124
4122
  />
4125
4123
  <button class="login-pin-toggle" type="button" @click=${l}>
@@ -4137,7 +4135,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4137
4135
  maxlength="6"
4138
4136
  placeholder="New PIN (4-6 digits)"
4139
4137
  ?disabled=${s}
4140
- @input=${r(f=>{S=f})}
4138
+ @input=${r(f=>{x=f})}
4141
4139
  />
4142
4140
  <button class="login-pin-toggle" type="button" @click=${l}>
4143
4141
  <span class="pin-eye-show">${L.eye}</span>
@@ -4154,7 +4152,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4154
4152
  maxlength="6"
4155
4153
  placeholder="Confirm new PIN"
4156
4154
  ?disabled=${s}
4157
- @input=${r(f=>{x=f})}
4155
+ @input=${r(f=>{S=f})}
4158
4156
  />
4159
4157
  <button class="login-pin-toggle" type="button" @click=${l}>
4160
4158
  <span class="pin-eye-show">${L.eye}</span>
@@ -4178,7 +4176,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4178
4176
  </p>
4179
4177
  </div>
4180
4178
  </div>
4181
- `}let h="",d="";const p=v=>{if(v.preventDefault(),!e.busy)if(n){if(!h||!d||h!==d)return;e.onSubmit(h)}else{if(!h||!o)return;e.onSubmit(o,h)}};return u`
4179
+ `}let h="",d="";const p=g=>{if(g.preventDefault(),!e.busy)if(n){if(!h||!d||h!==d)return;e.onSubmit(h)}else{if(!h||!o)return;e.onSubmit(o,h)}};return u`
4182
4180
  <div class="login-overlay">
4183
4181
  <div class="login-card">
4184
4182
  <img class="login-logo" src="${t.iconUrl}" alt="${t.name}" />
@@ -4198,7 +4196,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4198
4196
  maxlength="6"
4199
4197
  placeholder="${n?"Choose a 4-6 digit PIN":"PIN"}"
4200
4198
  ?disabled=${e.busy}
4201
- @input=${r(v=>{h=v})}
4199
+ @input=${r(g=>{h=g})}
4202
4200
  autofocus
4203
4201
  />
4204
4202
  <button class="login-pin-toggle" type="button" @click=${l}>
@@ -4217,7 +4215,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4217
4215
  maxlength="6"
4218
4216
  placeholder="Confirm PIN"
4219
4217
  ?disabled=${e.busy}
4220
- @input=${r(v=>{d=v})}
4218
+ @input=${r(g=>{d=g})}
4221
4219
  />
4222
4220
  <button class="login-pin-toggle" type="button" @click=${l}>
4223
4221
  <span class="pin-eye-show">${L.eye}</span>
@@ -4234,16 +4232,16 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4234
4232
  ${e.busy?u`<span class="login-spinner"></span>`:n?"Set PIN":"Unlock"}
4235
4233
  </button>
4236
4234
  </form>
4237
- ${n?u`<p class="login-hint">This PIN protects all accounts on this device. You'll need it every time you open the dashboard.</p>`:e.accounts.some(v=>v.id==="__master__")?u`<p class="login-hint login-change-pin" style="margin-top: 16px;${o!=="__master__"?" display: none;":""}">
4235
+ ${n?u`<p class="login-hint">This PIN protects all accounts on this device. You'll need it every time you open the dashboard.</p>`:e.accounts.some(g=>g.id==="__master__")?u`<p class="login-hint login-change-pin" style="margin-top: 16px;${o!=="__master__"?" display: none;":""}">
4238
4236
  <a
4239
4237
  class="login-link"
4240
4238
  href="#"
4241
- @click=${v=>{var S;v.preventDefault(),(S=e.onToggleChangePinMode)==null||S.call(e)}}
4239
+ @click=${g=>{var x;g.preventDefault(),(x=e.onToggleChangePinMode)==null||x.call(e)}}
4242
4240
  >Change PIN</a>
4243
4241
  </p>`:w}
4244
4242
  </div>
4245
4243
  </div>
4246
- `}function Bw(e){if(!e.connected)return u`
4244
+ `}function Nw(e){if(!e.connected)return u`
4247
4245
  <div class="setup-container">
4248
4246
  <div class="setup-card">
4249
4247
  <div class="setup-spinner"></div>
@@ -4256,10 +4254,10 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4256
4254
  <span class="public-chat-header__name">${n}</span>
4257
4255
  </div>
4258
4256
  <div class="chat-viewport">
4259
- ${ou(t)}
4257
+ ${au(t)}
4260
4258
  </div>
4261
4259
  </div>
4262
- `}async function Nw(e){if(!(!e.client||!e.connected)&&!e.agentsLoading){e.agentsLoading=!0,e.agentsError=null;try{const t=await e.client.request("agents.list",{});t&&(e.agentsList=t)}catch(t){e.agentsError=String(t)}finally{e.agentsLoading=!1}}}async function Gn(e){if(!(!e.client||!e.connected)&&!e.workspacesLoading){e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});e.workspaces=t.workspaces}catch(t){e.workspacesError=String(t)}finally{e.workspacesLoading=!1}}}async function Ow(e,t){var i,s;if(!e.client||!e.connected||e.workspaceSaving)return;const n=t.name.trim();if(!n){e.workspacesError="Account name is required.";return}e.workspaceSaving=!0,e.workspacesError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const a=o.hash;if(!a){e.workspacesError="Config hash missing; reload and retry.";return}const r={name:n,baseHash:a,whatsappAccountName:n};(i=t.workspacePath)!=null&&i.trim()&&(r.workspaceDir=t.workspacePath.trim());const l=await e.client.request("workspaces.create",r);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Gn(e),(s=t.onCreated)==null||s.call(t,l)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function Fw(e,t){if(!(!e.client||!e.connected)&&!e.workspaceSaving){e.workspaceSaving=!0,e.workspacesError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=n.hash;if(!i){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.remove",{name:t,baseHash:i}),e.workspaceRemoveConfirm=null,await Gn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function Uw(e,t,n){if(!(!e.client||!e.connected)){e.workspacesError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.hash;if(!s){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.rename",{name:t,displayName:n,baseHash:s}),await Gn(e)}catch(i){e.workspacesError=String(i)}}}const wi=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:Ow,loadWorkspaces:Gn,removeWorkspace:Fw,renameWorkspace:Uw},Symbol.toStringTag,{value:"Module"})),uu={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"},wl=uu,Uo={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(uu));new Set(Object.values(Uo));function Ww(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 Kw=4008;class zw{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 d;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 qh();const p=(d=Gh({deviceId:o.deviceId,role:t}))==null?void 0:d.token;r=p??this.opts.token,a=!!(p&&this.opts.token)}const l=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let c;if(s&&o){const p=Date.now(),v=this.connectNonce??void 0,S=Ww({deviceId:o.deviceId,clientId:this.opts.clientName??wl.CONTROL_UI,clientMode:this.opts.mode??Uo.WEBCHAT,role:t,scopes:n,signedAtMs:p,token:r??null,nonce:v}),x=await Hh(o.privateKey,S);c={id:o.deviceId,publicKey:o.publicKey,signature:x,signedAt:p,nonce:v}}const h={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??wl.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Uo.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",h).then(p=>{var v,S,x;(v=p==null?void 0:p.auth)!=null&&v.deviceToken&&o&&Vh({deviceId:o.deviceId,role:p.auth.role??t,token:p.auth.deviceToken,scopes:p.auth.scopes??[]}),this.backoffMs=800,(x=(S=this.opts).onHello)==null||x.call(S,p)}).catch(()=>{var p;a&&o&&Qh({deviceId:o.deviceId,role:t}),(p=this.ws)==null||p.close(Kw,"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 h=n;if(h.event==="connect.challenge"){const p=h.payload,v=p&&typeof p.nonce=="string"?p.nonce:null;v&&(this.connectNonce=v,this.sendConnect());return}const d=typeof h.seq=="number"?h.seq:null;d!==null&&(this.lastSeq!==null&&d>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:d})),this.lastSeq=d);try{(r=(a=this.opts).onEvent)==null||r.call(a,h)}catch(p){console.error("[gateway] event handler error:",p)}return}if(i.type==="res"){const h=n,d=this.pending.get(h.id);if(!d)return;if(this.pending.delete(h.id),h.ok)d.resolve(h.payload);else{const p=new Error(((l=h.error)==null?void 0:l.message)??"request failed");p.payload=h.payload,p.details=(c=h.error)==null?void 0:c.details,d.reject(p)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=ss(),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 Wo(e){return typeof e=="object"&&e!==null}function qw(e){if(!Wo(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Wo(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 Hw(e){if(!Wo(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 pu(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function jw(e,t){const n=pu(e).filter(i=>i.id!==t.id);return n.push(t),n}function kl(e,t){return pu(e).filter(n=>n.id!==t)}class Gw{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 ro=null;function Bn(){return ro||(ro=new Gw),ro}function Ba(e){return e instanceof Error?e.message:String(e)}async function Vw(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=Ba(t)}finally{e.browserLoading=!1}}async function Qw(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=Ba(t)}finally{e.browserLoading=!1}}}async function lo(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 co(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 Jw(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=Ba(t)}}function Yw(e){e.browserInputMode=!e.browserInputMode}function Xw(e){e.browserFullscreen=!e.browserFullscreen,Bn().detach()}function Zw(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,Bn().updateFrame(t.data,t.metadata)}function ek(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function tk(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function Ko(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 Ti(e){return(await e.request("apikeys.list")).providers??[]}async function $l(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function nk(e,t){await e.request("apikeys.remove",{provider:t})}async function ik(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const Zi="taskmaster_update_pending";async function hu(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 sk(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(Zi,String(Date.now())),localStorage.removeItem(Na)}catch{}try{const o=await e.client.request("update.run",{restartDelayMs:2e3,note:"Update from setup page"});if(o.ok&&o.result.status==="ok")e.updateMessage="Updated — restarting gateway...",(n=e.requestUpdate)==null||n.call(e);else if(o.ok&&o.result.status==="skipped")Nn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw Nn(),new Error(o.result.reason||"Update failed")}catch(o){Nn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function ok(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const a=t.name,r=t.index,l=t.total;e.updateMessage=`Updating: ${a} (${r+1}/${l})`;const c=e.updateProgressSteps.find(h=>h.index===r);c?(c.status="running",c.name=a):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total: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,h=t.durationMs,d=e.updateProgressSteps.find(v=>v.index===r);d?(d.status=c?"done":"failed",d.durationMs=h):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:l,status:c?"done":"failed",durationMs:h}];const p=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${a} done (${r+1}/${l})`:`Update step failed: ${a}${p}`,(s=e.requestUpdate)==null||s.call(e)}else if(n==="complete"){if(t.status==="ok")e.updateMessage="Update complete — restarting gateway...";else{const r=t.reason;e.updateMessage=r?`Update failed: ${r}`:"Update failed",e.updateRunning=!1,Nn()}(o=e.requestUpdate)==null||o.call(e)}}async function ak(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=lk();Nn();try{const a=await e.client.request("update.lastResult",{});if(!a.ok||!a.result)return;const r=5*6e4,l=Date.now()-a.result.ts<r;if(!t&&!l||ck(a.result.ts))return;e.updateLastResult=a.result;const c=(n=a.result.after)==null?void 0:n.version;if(a.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,a.result.status==="ok"){const h=(i=a.result.before)==null?void 0:i.version,d=c??a.result.currentVersion;e.updateMessage=h?`Updated: v${h} → v${d}`:`Updated to v${d}`}else{const h=a.result.reason??((s=a.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${h}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const Na="taskmaster_update_dismissed";function rk(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Na,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function lk(){try{const e=localStorage.getItem(Zi);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(Zi),!1):!0:!1}catch{return!1}}function Nn(){try{localStorage.removeItem(Zi)}catch{}}function ck(e){try{const t=localStorage.getItem(Na);return t?Number(t)>=e:!1}catch{return!1}}function uo(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 dk(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=uo(e.sessionKey,t),i=uo(e.settings.sessionKey,t),s=uo(e.settings.lastActiveSessionKey,t),o=n||i||e.sessionKey,a={...e.settings,sessionKey:i||o,lastActiveSessionKey:s||o},r=a.sessionKey!==e.settings.sessionKey||a.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),r&&at(e,a)}function De(e){var s;e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;const t=!!e.publicChat,n=e.setup||e.filesPage||e.browserPage||e.chatPage||e.adminsPage||e.contactsPage||e.advancedPage,i=t?"public-chat":n?"setup-ui":"taskmaster-control-ui";(s=e.client)==null||s.stop(),e.client=new zw({url:e.settings.gatewayUrl,token:t?void 0:e.settings.token.trim()?e.settings.token:void 0,password:t?void 0:e.password.trim()?e.password:void 0,clientName:i,mode:"webchat",role:t?"public":void 0,scopes:t?[]:void 0,onHello:o=>{var a;if(e.connected=!0,e.lastError=null,e.hello=o,t){xl(e,o),Ko(e),(((a=e.publicChatConfig)==null?void 0:a.auth)??"anonymous")==="anonymous"&&vk(e);return}Wi()&&(ya(),e.uninstallDone=!1),xl(e,o),e.handleAccessCheck(),ak(e).then(()=>{hu(e)}),Ko(e),Nw(e),(e.chatPage||e.setup)&&hk(e),aa(e,{quiet:!0}),oa(e,{quiet:!0}),Gn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Ue(e),e.setup&&(fk(e),gk(e),mk(e),yk(e)),Fi(e)},onClose:({code:o,reason:a})=>{e.connected=!1,o!==1012&&(e.lastError=`disconnected (${o}): ${a||"no reason"}`)},onEvent:o=>uk(e,o),onGap:({expected:o,received:a})=>{console.warn(`[gateway] event gap: expected seq ${o}, got ${a}`),Fi(e)}}),e.client.start()}function uk(e,t){try{pk(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function pk(e,t){var n;if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),e.tab==="debug"&&(e.eventLog=e.eventLogBuffer),t.event==="agent"){if(e.onboarding)return;Qp(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&Zc(e,i.sessionKey);const s=tc(e,i);if((s==="final"||s==="error"||s==="aborted")&&(Yo(e),Wf(e)),s==="final"){const o=e,a=Math.max((((n=o.chatMessages)==null?void 0:n.length)??0)+10,Fe);Oe(o,{limit:a})}return}if(t.event==="suggestions"){const i=t.payload;(i==null?void 0:i.sessionKey)===e.sessionKey&&Array.isArray(i.suggestions)&&i.suggestions.length>0&&(e.chatSuggestions=i.suggestions);return}if(t.event==="presence"){const i=t.payload;i!=null&&i.presence&&Array.isArray(i.presence)&&(e.presenceEntries=i.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"){const i=t.payload;i&&dh(e,i),e.tab==="cron"&&ga(e)}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&oa(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=qw(t.payload);if(i){e.execApprovalQueue=jw(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=kl(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){Zw(e,t.payload);return}if(t.event==="browser.handoff"){ek(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){tk(e);return}if(t.event==="exec.approval.resolved"){const i=Hw(t.payload);i&&(e.execApprovalQueue=kl(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){ok(e,t.payload);return}}function xl(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&&dk(e,n.sessionDefaults)}async function hk(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 fk(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await Ti(e.client)}catch{}}async function gk(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function mk(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("wifi.status");if(e.wifiStatus=t,t!=null&&t.connected&&t.signal==null)try{const[n,i]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiStatus=i,i.signal==null&&n.networks){const s=n.networks.find(o=>o.active);s&&(e.wifiStatus={...i,signal:s.signal})}}catch{}}catch{}}async function yk(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("network.status");e.networkPort=t.port,e.networkHostname=t.hostname,e.networkPortInput=String(t.port),e.networkHostnameInput=t.hostname}catch{}}const Sl="taskmaster_public_id";function fu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${Sl}=`));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=`${Sl}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function vk(e){var n,i,s;if(!e.client||!e.connected)return;const t=fu((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=Wn(r,a.sessionKey),Oe(e)}}catch(o){console.error("[public-chat] failed to resolve anonymous session:",o),e.lastError="Failed to start chat session"}}let he=!1,ie=null,Zt="",en="",tn="",hs="",cn="phone";function gu(e){return e.replace(/[\s\-()]/g,"")}function Ht(){he=!1,ie=null,Zt="",en="",tn="",hs="",cn="phone"}async function bk(e){if(!e.client||!e.connected)return;const t=fu(e.cookieTtlDays);try{const n=await e.client.request("public.session",{cookieId:t,accountId:e.accountId});n!=null&&n.sessionKey&&e.onAuthenticated(n.sessionKey)}catch(n){ie=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function Al(e){if(!e.client||he)return;const t=gu(Zt);if(!t){ie="Please enter your phone number",e.requestUpdate();return}he=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:tn.trim()||void 0,accountId:e.accountId});n!=null&&n.ok?(hs=n.channel??"",cn="phone",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{he=!1,e.requestUpdate()}}async function Cl(e){if(!e.client||he)return;const t=en.trim().toLowerCase();if(!t||!t.includes("@")){ie="Please enter a valid email address",e.requestUpdate();return}he=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{identifier:t,accountId:e.accountId});n!=null&&n.ok?(hs=n.channel??"email",cn="email",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{he=!1,e.requestUpdate()}}async function El(e,t){if(!(!e.client||he)){if(!t.trim()){ie="Please enter the verification code",e.requestUpdate();return}he=!0,ie=null,e.requestUpdate();try{const n=cn==="email"?en.trim().toLowerCase():gu(Zt),i=await e.client.request("public.otp.verify",{identifier:n,code:t.trim(),accountId:e.accountId});i!=null&&i.ok&&i.sessionKey?(Ht(),e.onAuthenticated(i.sessionKey)):ie=(i==null?void 0:i.error)??"Invalid verification code"}catch(n){ie=n instanceof Error?n.message:"Verification failed"}finally{he=!1,e.requestUpdate()}}}function Ge(e){return w}function ki(e){return u`
4260
+ `}async function Ow(e){if(!(!e.client||!e.connected)&&!e.agentsLoading){e.agentsLoading=!0,e.agentsError=null;try{const t=await e.client.request("agents.list",{});t&&(e.agentsList=t)}catch(t){e.agentsError=String(t)}finally{e.agentsLoading=!1}}}async function Vn(e){if(!(!e.client||!e.connected)&&!e.workspacesLoading){e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});e.workspaces=t.workspaces}catch(t){e.workspacesError=String(t)}finally{e.workspacesLoading=!1}}}async function Fw(e,t){var i,s;if(!e.client||!e.connected||e.workspaceSaving)return;const n=t.name.trim();if(!n){e.workspacesError="Account name is required.";return}e.workspaceSaving=!0,e.workspacesError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const a=o.hash;if(!a){e.workspacesError="Config hash missing; reload and retry.";return}const r={name:n,baseHash:a,whatsappAccountName:n};(i=t.workspacePath)!=null&&i.trim()&&(r.workspaceDir=t.workspacePath.trim());const l=await e.client.request("workspaces.create",r);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await Vn(e),(s=t.onCreated)==null||s.call(t,l)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function Uw(e,t){if(!(!e.client||!e.connected)&&!e.workspaceSaving){e.workspaceSaving=!0,e.workspacesError=null;try{const n=await e.client.request("config.get",{});e.configSnapshot=n;const i=n.hash;if(!i){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.remove",{name:t,baseHash:i}),e.workspaceRemoveConfirm=null,await Vn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function Ww(e,t,n){if(!(!e.client||!e.connected)){e.workspacesError=null;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.hash;if(!s){e.workspacesError="Config hash missing; reload and retry.";return}await e.client.request("workspaces.rename",{name:t,displayName:n,baseHash:s}),await Vn(e)}catch(i){e.workspacesError=String(i)}}}const ki=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:Fw,loadWorkspaces:Vn,removeWorkspace:Uw,renameWorkspace:Ww},Symbol.toStringTag,{value:"Module"})),pu={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"},kl=pu,Wo={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(pu));new Set(Object.values(Wo));function Kw(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 zw=4008;class qw{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 d;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 Hh();const p=(d=Vh({deviceId:o.deviceId,role:t}))==null?void 0:d.token;r=p??this.opts.token,a=!!(p&&this.opts.token)}const l=r||this.opts.password?{token:r,password:this.opts.password}:void 0;let c;if(s&&o){const p=Date.now(),g=this.connectNonce??void 0,x=Kw({deviceId:o.deviceId,clientId:this.opts.clientName??kl.CONTROL_UI,clientMode:this.opts.mode??Wo.WEBCHAT,role:t,scopes:n,signedAtMs:p,token:r??null,nonce:g}),S=await jh(o.privateKey,x);c={id:o.deviceId,publicKey:o.publicKey,signature:S,signedAt:p,nonce:g}}const h={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??kl.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Wo.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",h).then(p=>{var g,x,S;(g=p==null?void 0:p.auth)!=null&&g.deviceToken&&o&&Qh({deviceId:o.deviceId,role:p.auth.role??t,token:p.auth.deviceToken,scopes:p.auth.scopes??[]}),this.backoffMs=800,(S=(x=this.opts).onHello)==null||S.call(x,p)}).catch(()=>{var p;a&&o&&Jh({deviceId:o.deviceId,role:t}),(p=this.ws)==null||p.close(zw,"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 h=n;if(h.event==="connect.challenge"){const p=h.payload,g=p&&typeof p.nonce=="string"?p.nonce:null;g&&(this.connectNonce=g,this.sendConnect());return}const d=typeof h.seq=="number"?h.seq:null;d!==null&&(this.lastSeq!==null&&d>this.lastSeq+1&&((o=(s=this.opts).onGap)==null||o.call(s,{expected:this.lastSeq+1,received:d})),this.lastSeq=d);try{(r=(a=this.opts).onEvent)==null||r.call(a,h)}catch(p){console.error("[gateway] event handler error:",p)}return}if(i.type==="res"){const h=n,d=this.pending.get(h.id);if(!d)return;if(this.pending.delete(h.id),h.ok)d.resolve(h.payload);else{const p=new Error(((l=h.error)==null?void 0:l.message)??"request failed");p.payload=h.payload,p.details=(c=h.error)==null?void 0:c.details,d.reject(p)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=os(),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 Ko(e){return typeof e=="object"&&e!==null}function Hw(e){if(!Ko(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Ko(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 jw(e){if(!Ko(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 hu(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Gw(e,t){const n=hu(e).filter(i=>i.id!==t.id);return n.push(t),n}function $l(e,t){return hu(e).filter(n=>n.id!==t)}class Vw{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 lo=null;function Bn(){return lo||(lo=new Vw),lo}function Na(e){return e instanceof Error?e.message:String(e)}async function Qw(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=Na(t)}finally{e.browserLoading=!1}}async function Jw(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=Na(t)}finally{e.browserLoading=!1}}}async function co(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 uo(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 Yw(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=Na(t)}}function Xw(e){e.browserInputMode=!e.browserInputMode}function Zw(e){e.browserFullscreen=!e.browserFullscreen,Bn().detach()}function ek(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,Bn().updateFrame(t.data,t.metadata)}function tk(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function nk(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function zo(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=yo(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function _i(e){return(await e.request("apikeys.list")).providers??[]}async function xl(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function ik(e,t){await e.request("apikeys.remove",{provider:t})}async function sk(e,t,n){await e.request("apikeys.disable",{provider:t,disabled:n})}const es="taskmaster_update_pending";async function fu(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 ok(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(es,String(Date.now())),localStorage.removeItem(Oa)}catch{}try{const o=await e.client.request("update.run",{restartDelayMs:2e3,note:"Update from setup page"});if(o.ok&&o.result.status==="ok")e.updateMessage="Updated — restarting gateway...",(n=e.requestUpdate)==null||n.call(e);else if(o.ok&&o.result.status==="skipped")Nn(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw Nn(),new Error(o.result.reason||"Update failed")}catch(o){Nn(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function ak(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(h=>h.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,h=t.durationMs,d=e.updateProgressSteps.find(g=>g.index===r);d?(d.status=c?"done":"failed",d.durationMs=h):e.updateProgressSteps=[...e.updateProgressSteps,{name:a,index:r,total:l,status:c?"done":"failed",durationMs:h}];const p=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${a} done (${r+1}/${l})`:`Update step failed: ${a}${p}`,(s=e.requestUpdate)==null||s.call(e)}else if(n==="complete"){if(t.status==="ok")e.updateMessage="Update complete — restarting gateway...";else{const r=t.reason;e.updateMessage=r?`Update failed: ${r}`:"Update failed",e.updateRunning=!1,Nn()}(o=e.requestUpdate)==null||o.call(e)}}async function rk(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=ck();Nn();try{const a=await e.client.request("update.lastResult",{});if(!a.ok||!a.result)return;const r=5*6e4,l=Date.now()-a.result.ts<r;if(!t&&!l||dk(a.result.ts))return;e.updateLastResult=a.result;const c=(n=a.result.after)==null?void 0:n.version;if(a.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,a.result.status==="ok"){const h=(i=a.result.before)==null?void 0:i.version,d=c??a.result.currentVersion;e.updateMessage=h?`Updated: v${h} → v${d}`:`Updated to v${d}`}else{const h=a.result.reason??((s=a.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${h}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const Oa="taskmaster_update_dismissed";function lk(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(Oa,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function ck(){try{const e=localStorage.getItem(es);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(es),!1):!0:!1}catch{return!1}}function Nn(){try{localStorage.removeItem(es)}catch{}}function dk(e){try{const t=localStorage.getItem(Oa);return t?Number(t)>=e:!1}catch{return!1}}function po(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 uk(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=po(e.sessionKey,t),i=po(e.settings.sessionKey,t),s=po(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&&rt(e,a)}function De(e){var s;e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;const t=!!e.publicChat,n=e.setup||e.filesPage||e.browserPage||e.chatPage||e.adminsPage||e.contactsPage||e.advancedPage,i=t?"public-chat":n?"setup-ui":"taskmaster-control-ui";(s=e.client)==null||s.stop(),e.client=new qw({url:e.settings.gatewayUrl,token:t?void 0:e.settings.token.trim()?e.settings.token:void 0,password:t?void 0:e.password.trim()?e.password:void 0,clientName:i,mode:"webchat",role:t?"public":void 0,scopes:t?[]:void 0,onHello:o=>{var a;if(e.connected=!0,e.lastError=null,e.hello=o,t){Sl(e,o),zo(e),(((a=e.publicChatConfig)==null?void 0:a.auth)??"anonymous")==="anonymous"&&bk(e);return}Ki()&&(va(),e.uninstallDone=!1),Sl(e,o),e.handleAccessCheck(),rk(e).then(()=>{fu(e)}),zo(e),Ow(e),(e.chatPage||e.setup)&&fk(e),ra(e,{quiet:!0}),aa(e,{quiet:!0}),Vn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Ue(e),e.setup&&(gk(e),mk(e),yk(e),vk(e)),Ui(e)},onClose:({code:o,reason:a})=>{e.connected=!1,o!==1012&&(e.lastError=`disconnected (${o}): ${a||"no reason"}`)},onEvent:o=>pk(e,o),onGap:({expected:o,received:a})=>{console.warn(`[gateway] event gap: expected seq ${o}, got ${a}`),Ui(e)}}),e.client.start()}function pk(e,t){try{hk(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function hk(e,t){var n;if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),e.tab==="debug"&&(e.eventLog=e.eventLogBuffer),t.event==="agent"){if(e.onboarding)return;Jp(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&ed(e,i.sessionKey);const s=nc(e,i);if((s==="final"||s==="error"||s==="aborted")&&(Xo(e),Kf(e)),s==="final"){const o=e,a=Math.max((((n=o.chatMessages)==null?void 0:n.length)??0)+10,Fe);Oe(o,{limit:a})}return}if(t.event==="suggestions"){const i=t.payload;(i==null?void 0:i.sessionKey)===e.sessionKey&&Array.isArray(i.suggestions)&&i.suggestions.length>0&&(e.chatSuggestions=i.suggestions);return}if(t.event==="presence"){const i=t.payload;i!=null&&i.presence&&Array.isArray(i.presence)&&(e.presenceEntries=i.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"){const i=t.payload;i&&uh(e,i),e.tab==="cron"&&ma(e)}if((t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&aa(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=Hw(t.payload);if(i){e.execApprovalQueue=Gw(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=$l(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){ek(e,t.payload);return}if(t.event==="browser.handoff"){tk(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){nk(e);return}if(t.event==="exec.approval.resolved"){const i=jw(t.payload);i&&(e.execApprovalQueue=$l(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){ak(e,t.payload);return}}function Sl(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&&uk(e,n.sessionDefaults)}async function fk(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 gk(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await _i(e.client)}catch{}}async function mk(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null}catch{}}async function yk(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 vk(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 Al="taskmaster_public_id";function gu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${Al}=`));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=`${Al}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function bk(e){var n,i,s;if(!e.client||!e.connected)return;const t=gu((n=e.publicChatConfig)==null?void 0:n.cookieTtlDays);try{const o=(i=e.publicChatConfig)==null?void 0:i.accountId,a=await e.client.request("public.session",{cookieId:t,accountId:o});if(a!=null&&a.sessionKey){e.publicChatSessionKey=a.sessionKey,e.sessionKey=a.sessionKey,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const r=((s=e.publicChatConfig)==null?void 0:s.accountId)??"";e.chatMessage=Kn(r,a.sessionKey),Oe(e)}}catch(o){console.error("[public-chat] failed to resolve anonymous session:",o),e.lastError="Failed to start chat session"}}let he=!1,ie=null,Zt="",en="",tn="",fs="",cn="phone",On="";function mu(e){return e.replace(/[\s\-()]/g,"")}function st(){he=!1,ie=null,Zt="",en="",tn="",fs="",cn="phone",On=""}async function wk(e){if(!e.client||!e.connected)return;const t=gu(e.cookieTtlDays);try{const n=await e.client.request("public.session",{cookieId:t,accountId:e.accountId});n!=null&&n.sessionKey&&e.onAuthenticated(n.sessionKey)}catch(n){ie=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function Cl(e){if(!e.client||he)return;const t=mu(Zt);if(!t){ie="Please enter your phone number",e.requestUpdate();return}he=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:tn.trim()||void 0,accountId:e.accountId,channel:On||void 0});n!=null&&n.ok?(fs=n.channel??"",cn="phone",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{he=!1,e.requestUpdate()}}async function El(e){if(!e.client||he)return;const t=en.trim().toLowerCase();if(!t||!t.includes("@")){ie="Please enter a valid email address",e.requestUpdate();return}he=!0,ie=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{identifier:t,accountId:e.accountId});n!=null&&n.ok?(fs=n.channel??"email",cn="email",e.onAuthStepChange("otp")):ie=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){ie=n instanceof Error?n.message:"Failed to send verification code"}finally{he=!1,e.requestUpdate()}}async function Tl(e,t){if(!(!e.client||he)){if(!t.trim()){ie="Please enter the verification code",e.requestUpdate();return}he=!0,ie=null,e.requestUpdate();try{const n=cn==="email"?en.trim().toLowerCase():mu(Zt),i=await e.client.request("public.otp.verify",{identifier:n,code:t.trim(),accountId:e.accountId});i!=null&&i.ok&&i.sessionKey?(st(),e.onAuthenticated(i.sessionKey)):ie=(i==null?void 0:i.error)??"Invalid verification code"}catch(n){ie=n instanceof Error?n.message:"Verification failed"}finally{he=!1,e.requestUpdate()}}}function Ge(e){return w}function $i(e){return u`
4263
4261
  <div class="public-auth__form">
4264
4262
  <label class="field public-auth__field">
4265
4263
  <span>Your name (optional)</span>
@@ -4276,7 +4274,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4276
4274
  type="tel"
4277
4275
  .value=${Zt}
4278
4276
  @input=${t=>{Zt=t.target.value}}
4279
- @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Al(e))}}
4277
+ @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Cl(e))}}
4280
4278
  placeholder="+44 7123 456789"
4281
4279
  required
4282
4280
  />
@@ -4285,12 +4283,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4285
4283
  <button
4286
4284
  class="btn primary public-auth__btn"
4287
4285
  ?disabled=${he}
4288
- @click=${()=>{Al(e)}}
4286
+ @click=${()=>{Cl(e)}}
4289
4287
  >
4290
4288
  ${he?"Sending...":"Send verification code"}
4291
4289
  </button>
4292
4290
  </div>
4293
- `}function po(e){return u`
4291
+ `}function ho(e){return u`
4294
4292
  <div class="public-auth__form">
4295
4293
  <label class="field public-auth__field">
4296
4294
  <span>Your name (optional)</span>
@@ -4307,7 +4305,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4307
4305
  type="email"
4308
4306
  .value=${en}
4309
4307
  @input=${t=>{en=t.target.value}}
4310
- @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Cl(e))}}
4308
+ @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),El(e))}}
4311
4309
  placeholder="you@example.com"
4312
4310
  required
4313
4311
  />
@@ -4316,12 +4314,12 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4316
4314
  <button
4317
4315
  class="btn primary public-auth__btn"
4318
4316
  ?disabled=${he}
4319
- @click=${()=>{Cl(e)}}
4317
+ @click=${()=>{El(e)}}
4320
4318
  >
4321
4319
  ${he?"Sending...":"Send verification code"}
4322
4320
  </button>
4323
4321
  </div>
4324
- `}function Tl(e){let t="";const n=cn==="email",i=n?"email":hs==="sms"?"SMS":"WhatsApp",s=n?en:Zt,o=n?"email":"phone";return u`
4322
+ `}function _l(e){let t="";const n=cn==="email",i=n?"email":fs==="sms"?"SMS":"WhatsApp",s=n?en:Zt,o=n?"email":"phone";return u`
4325
4323
  <div class="public-auth__form">
4326
4324
  <p class="public-auth__hint">
4327
4325
  We sent a verification code to <strong>${s}</strong> via ${i}.
@@ -4333,7 +4331,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4333
4331
  inputmode="numeric"
4334
4332
  maxlength="6"
4335
4333
  @input=${a=>{t=a.target.value}}
4336
- @keydown=${a=>{a.key==="Enter"&&(a.preventDefault(),El(e,t))}}
4334
+ @keydown=${a=>{a.key==="Enter"&&(a.preventDefault(),Tl(e,t))}}
4337
4335
  placeholder="123456"
4338
4336
  required
4339
4337
  />
@@ -4342,7 +4340,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4342
4340
  <button
4343
4341
  class="btn primary public-auth__btn"
4344
4342
  ?disabled=${he}
4345
- @click=${()=>{El(e,t)}}
4343
+ @click=${()=>{Tl(e,t)}}
4346
4344
  >
4347
4345
  ${he?"Verifying...":"Verify"}
4348
4346
  </button>
@@ -4353,14 +4351,14 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4353
4351
  ${n?"Use a different email":"Use a different number"}
4354
4352
  </button>
4355
4353
  </div>
4356
- `}function wk(e){const{authMode:t,authStep:n}=e,i=!e.otpChannels||e.otpChannels.length>0;if(t==="anonymous")return u`
4354
+ `}function kk(e){const{authMode:t,authStep:n}=e,i=!e.otpChannels||e.otpChannels.length>0;if(t==="anonymous")return u`
4357
4355
  <div class="setup-container">
4358
4356
  <div class="setup-card">
4359
4357
  <div class="setup-spinner"></div>
4360
4358
  <p>Starting chat...</p>
4361
4359
  </div>
4362
4360
  </div>
4363
- `;if(t==="verified"){const h=e.verifyMethods??["phone"],d=h.includes("phone"),p=h.includes("email");return!i&&!p?u`
4361
+ `;if(t==="verified"){const h=e.verifyMethods??["whatsapp","sms"],d=h.includes("whatsapp")||h.includes("sms")||h.includes("phone"),p=h.includes("email");return!i&&!p?u`
4364
4362
  <div class="setup-container">
4365
4363
  <div class="public-auth">
4366
4364
  ${Ge()}
@@ -4373,7 +4371,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4373
4371
  <div class="public-auth">
4374
4372
  ${Ge()}
4375
4373
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4376
- ${Tl(e)}
4374
+ ${_l(e)}
4377
4375
  </div>
4378
4376
  </div>
4379
4377
  `:n==="email"?u`
@@ -4382,10 +4380,10 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4382
4380
  ${Ge()}
4383
4381
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4384
4382
  <p class="public-auth__subtitle">Verify your email address to get started.</p>
4385
- ${po(e)}
4383
+ ${ho(e)}
4386
4384
  ${d?u`
4387
4385
  <button class="btn public-auth__btn public-auth__btn--link"
4388
- @click=${()=>{Ht(),e.onAuthStepChange("phone")}}>
4386
+ @click=${()=>{st(),e.onAuthStepChange("phone")}}>
4389
4387
  Use phone number instead
4390
4388
  </button>
4391
4389
  `:w}
@@ -4397,10 +4395,10 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4397
4395
  ${Ge()}
4398
4396
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4399
4397
  <p class="public-auth__subtitle">Verify your phone number to get started.</p>
4400
- ${ki(e)}
4398
+ ${$i(e)}
4401
4399
  ${p?u`
4402
4400
  <button class="btn public-auth__btn public-auth__btn--link"
4403
- @click=${()=>{Ht(),e.onAuthStepChange("email")}}>
4401
+ @click=${()=>{st(),e.onAuthStepChange("email")}}>
4404
4402
  Use email instead
4405
4403
  </button>
4406
4404
  `:w}
@@ -4412,9 +4410,9 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4412
4410
  ${Ge()}
4413
4411
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4414
4412
  <p class="public-auth__subtitle">Authenticate to get started.</p>
4415
- ${ki(e)}
4413
+ ${$i(e)}
4416
4414
  <button class="btn public-auth__btn public-auth__btn--link"
4417
- @click=${()=>{Ht(),e.onAuthStepChange("email")}}>
4415
+ @click=${()=>{st(),e.onAuthStepChange("email")}}>
4418
4416
  Use email instead
4419
4417
  </button>
4420
4418
  </div>
@@ -4425,7 +4423,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4425
4423
  ${Ge()}
4426
4424
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4427
4425
  <p class="public-auth__subtitle">Verify your email address to get started.</p>
4428
- ${po(e)}
4426
+ ${ho(e)}
4429
4427
  </div>
4430
4428
  </div>
4431
4429
  `:u`
@@ -4434,25 +4432,25 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4434
4432
  ${Ge()}
4435
4433
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4436
4434
  <p class="public-auth__subtitle">Verify your phone number to get started.</p>
4437
- ${ki(e)}
4435
+ ${$i(e)}
4438
4436
  </div>
4439
4437
  </div>
4440
- `}const s=e.verifyMethods??["phone"],o=s.includes("phone"),a=s.includes("email"),r=i&&o||a;if(n==="phone"||n==="email"||n==="otp"){const d=n==="email"||n==="otp"&&cn==="email"?"Verify your email address to continue your conversation across devices.":"Verify your phone number to continue your conversation across devices.";return u`
4438
+ `}const s=e.verifyMethods??["whatsapp","sms"],o=s.includes("whatsapp")&&(!e.otpChannels||e.otpChannels.includes("whatsapp")),a=s.includes("sms"),r=s.includes("email"),c=o||a||s.includes("phone")||r;if(n==="phone"||n==="email"||n==="otp"){const h=n==="email"||n==="otp"&&cn==="email",p=h?"Verify your email address to continue your conversation across devices.":`Verify your phone number to receive a code via ${h?"email":On==="sms"?"SMS":"WhatsApp"}.`;return u`
4441
4439
  <div class="setup-container">
4442
4440
  <div class="public-auth">
4443
4441
  ${Ge()}
4444
4442
  <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
4445
- <p class="public-auth__subtitle">${d}</p>
4446
- ${n==="otp"?Tl(e):n==="email"?po(e):ki(e)}
4447
- ${n!=="otp"&&o&&a?u`
4443
+ <p class="public-auth__subtitle">${p}</p>
4444
+ ${n==="otp"?_l(e):n==="email"?ho(e):$i(e)}
4445
+ ${n!=="otp"?u`
4448
4446
  <button class="btn public-auth__btn public-auth__btn--link"
4449
- @click=${()=>{Ht(),e.onAuthStepChange(n==="phone"?"email":"phone")}}>
4450
- ${n==="phone"?"Use email instead":"Use phone number instead"}
4447
+ @click=${()=>{st(),e.onAuthStepChange("idle")}}>
4448
+ Back
4451
4449
  </button>
4452
4450
  `:w}
4453
4451
  </div>
4454
4452
  </div>
4455
- `}const l=o?"phone":"email",c=o&&a?"Authenticate":a?"Authenticate with email":"Authenticate with phone";return u`
4453
+ `}return u`
4456
4454
  <div class="setup-container">
4457
4455
  <div class="public-auth">
4458
4456
  ${Ge()}
@@ -4461,27 +4459,43 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4461
4459
  <div class="public-auth__choices">
4462
4460
  <button
4463
4461
  class="btn primary public-auth__btn"
4464
- @click=${()=>{bk(e)}}
4462
+ @click=${()=>{wk(e)}}
4465
4463
  >
4466
4464
  Chat now
4467
4465
  </button>
4466
+ ${o?u`
4467
+ <button
4468
+ class="btn public-auth__btn"
4469
+ @click=${()=>{st(),On="whatsapp",e.onAuthStepChange("phone")}}
4470
+ >
4471
+ Authenticate with WhatsApp
4472
+ </button>
4473
+ `:w}
4474
+ ${a?u`
4475
+ <button
4476
+ class="btn public-auth__btn"
4477
+ @click=${()=>{st(),On="sms",e.onAuthStepChange("phone")}}
4478
+ >
4479
+ Authenticate with SMS
4480
+ </button>
4481
+ `:w}
4468
4482
  ${r?u`
4469
4483
  <button
4470
4484
  class="btn public-auth__btn"
4471
- @click=${()=>{Ht(),e.onAuthStepChange(l)}}
4485
+ @click=${()=>{st(),e.onAuthStepChange("email")}}
4472
4486
  >
4473
- ${c}
4487
+ Authenticate with email
4474
4488
  </button>
4475
4489
  `:w}
4476
4490
  </div>
4477
- ${r?u`
4491
+ ${c?u`
4478
4492
  <p class="public-auth__hint">
4479
4493
  Verifying your identity lets you continue your conversation across devices.
4480
4494
  </p>
4481
4495
  `:w}
4482
4496
  </div>
4483
4497
  </div>
4484
- `}const Oa="taskmaster-access-session",mu={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function yu(){try{return localStorage.getItem(Oa)}catch{return null}}function vu(e){try{localStorage.setItem(Oa,e)}catch{}}function kk(){try{localStorage.removeItem(Oa)}catch{}}async function _l(e){if(e.client)try{const t=yu(),n=await e.client.request("access.status",{token:t});e.accessState={...e.accessState,checked:!0,hasPins:n.hasPins,hasMasterPin:n.hasMasterPin,accounts:n.accounts??[],authenticated:n.authenticated,workspace:n.workspace,master:n.master,error:null}}catch{e.accessState={...e.accessState,checked:!0,hasPins:!1,hasMasterPin:!1,accounts:[],authenticated:!0,error:null}}}async function $k(e,t,n){if(e.client){e.accessState={...e.accessState,busy:!0,error:null};try{const i=await e.client.request("access.verify",{account:t,pin:n});i.ok&&i.token?(vu(i.token),e.accessState={...e.accessState,authenticated:!0,workspace:i.workspace??null,master:i.master??!1,busy:!1,error:null}):e.accessState={...e.accessState,busy:!1,error:i.message??"Incorrect PIN"}}catch{e.accessState={...e.accessState,busy:!1,error:"Failed to verify PIN"}}}}async function xk(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?(vu(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 Sk(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 Ak(e){const t=yu();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}kk(),e.accessState={...mu,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}function Ck(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 bu(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,a=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const h=c.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")continue;const p=h.peer;if(!p||typeof p!="object"||p.kind!=="dm")continue;const v=p.id??"";v&&(c.meta&&o.set(v,c.meta),h.accountId&&a.set(v,h.accountId))}const r=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const h=c.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")return!0;const p=h.peer;return!p||typeof p!="object"?!0:p.kind!=="dm"}),l=t.map(c=>{const h=i??a.get(c.phone),d={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};h&&(d.accountId=h);const p={agentId:n,match:d},v=o.get(c.phone);return v?p.meta=v:c.paired&&(p.meta={paired:!0}),p});return[...r,...l]}async function fs(e,t){if(!e.client||!e.connected)return;if(!t){e.adminPhones=[];return}if(e.adminsLoading)return;e.adminsLoading=!0,e.adminsError=null;const n=t;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.config;e.configForm=lt(s??{}),e.adminPhones=Ck(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function wu(e,t,n,i){var a,r;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n;let o=t.replace(/[\s\-\(\)]/g,"");if(!o){e.adminsError="Phone number is required";return}if(o.startsWith("+")||(o="+"+o),!/^\+[1-9]\d{6,14}$/.test(o)){e.adminsError="Invalid phone number. Use international format (e.g., +44 7504 472444)";return}if(e.adminPhones.some(l=>l.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const l=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],h=[...e.adminPhones,{phone:o}],d=bu(c,h,s,i);ic(l,["bindings"],d);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const v=Ct(l);await e.client.request("config.set",{raw:v,baseHash:p}),await fs(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function ku(e,t,n,i){var a,r;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n,o=e.adminPhones.find(l=>l.phone===t);if(o!=null&&o.paired){e.adminsError="Cannot remove the paired phone. Unlink WhatsApp first.";return}e.adminsSaving=!0,e.adminsError=null;try{const l=lt(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],h=e.adminPhones.filter(S=>S.phone!==t),d=bu(c,h,s,i);ic(l,["bindings"],d);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const v=Ct(l);await e.client.request("config.set",{raw:v,baseHash:p}),await fs(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}const Ek=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:wu,loadAdmins:fs,removeAdmin:ku},Symbol.toStringTag,{value:"Module"}));async function It(e,t){if(!(!e.client||!e.connected)){if(!t){e.contactsRecords=[];return}if(!e.contactsLoading){e.contactsLoading=!0,e.contactsError=null;try{const n=e.contactsSearchQuery.trim(),i=n?await e.client.request("records.search",{query:n,workspace:t}):await e.client.request("records.list",{workspace:t});e.contactsRecords=i.records??[]}catch(n){e.contactsError=String(n)}finally{e.contactsLoading=!1}}}}async function $u(e,t,n,i){if(!e.client||!e.connected||e.contactsSaving)return;let s=t.replace(/[\s\-\(\)]/g,"");const o=n.trim();if(!s){e.contactsError="Phone number is required";return}if(!o){e.contactsError="Name is required";return}if(s.startsWith("+")||(s="+"+s),!/^\+[1-9]\d{6,14}$/.test(s)){e.contactsError="Invalid phone number. Use international format (e.g., +44 7490 553305)";return}e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.set",{id:s,name:o,fields:{},workspace:i}),e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName="",await It(e,i)}catch(a){e.contactsError=String(a)}finally{e.contactsSaving=!1}}async function xu(e,t,n){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.delete",{id:t}),e.contactsEditingId===t&&(e.contactsEditingId=null),await It(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function zo(e,t,n,i,s){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.setField",{id:t,key:n,value:i}),await It(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Su(e,t,n,i){if(!(!e.client||!e.connected)&&!e.contactsSaving){e.contactsSaving=!0,e.contactsError=null;try{await e.client.request("records.deleteField",{id:t,key:n}),await It(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const Tk=Object.freeze(Object.defineProperty({__proto__:null,addContact:$u,deleteContact:xu,deleteContactField:Su,loadContacts:It,setContactField:zo},Symbol.toStringTag,{value:"Module"}));let kt=null,_i=null,Mi=null;const ho=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function Kt(){kt&&(clearInterval(kt),kt=null),_i&&(clearInterval(_i),_i=null),Mi&&(clearTimeout(Mi),Mi=null)}function Sn(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function _k(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),onAddAccount:()=>{e.addingWorkspace=!0},hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function Mk(e){const t=ue(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 Pk(e){const t=ue(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function Ik(e){var i;const t=ue(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 Lk(e){return e.selectedWorkspace??void 0}function ue(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const Rk=/^data:/i,Dk=/^https?:\/\//i;function Ml(e){var r,l;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=Hl(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 Rk.test(a)||Dk.test(a)?a:o==null?void 0:o.avatarUrl}function Bk(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 Nk(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 Ok(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 Fk(e){var t,n,i,s,o,a,r,l,c,h;if(e.embeddingDownloading&&!e.publicChat)return u`
4498
+ `}const Fa="taskmaster-access-session",yu={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function vu(){try{return localStorage.getItem(Fa)}catch{return null}}function bu(e){try{localStorage.setItem(Fa,e)}catch{}}function $k(){try{localStorage.removeItem(Fa)}catch{}}async function Ml(e){if(e.client)try{const t=vu(),n=await e.client.request("access.status",{token:t});e.accessState={...e.accessState,checked:!0,hasPins:n.hasPins,hasMasterPin:n.hasMasterPin,accounts:n.accounts??[],authenticated:n.authenticated,workspace:n.workspace,master:n.master,error:null}}catch{e.accessState={...e.accessState,checked:!0,hasPins:!1,hasMasterPin:!1,accounts:[],authenticated:!0,error:null}}}async function xk(e,t,n){if(e.client){e.accessState={...e.accessState,busy:!0,error:null};try{const i=await e.client.request("access.verify",{account:t,pin:n});i.ok&&i.token?(bu(i.token),e.accessState={...e.accessState,authenticated:!0,workspace:i.workspace??null,master:i.master??!1,busy:!1,error:null}):e.accessState={...e.accessState,busy:!1,error:i.message??"Incorrect PIN"}}catch{e.accessState={...e.accessState,busy:!1,error:"Failed to verify PIN"}}}}async function Sk(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?(bu(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 Ak(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 Ck(e){const t=vu();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}$k(),e.accessState={...yu,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}function Ek(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 wu(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,a=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const h=c.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")continue;const p=h.peer;if(!p||typeof p!="object"||p.kind!=="dm")continue;const g=p.id??"";g&&(c.meta&&o.set(g,c.meta),h.accountId&&a.set(g,h.accountId))}const r=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const h=c.match;if(!h||typeof h!="object"||(h.channel??"").toLowerCase()!=="whatsapp")return!0;const p=h.peer;return!p||typeof p!="object"?!0:p.kind!=="dm"}),l=t.map(c=>{const h=i??a.get(c.phone),d={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};h&&(d.accountId=h);const p={agentId:n,match:d},g=o.get(c.phone);return g?p.meta=g:c.paired&&(p.meta={paired:!0}),p});return[...r,...l]}async function gs(e,t){if(!e.client||!e.connected)return;if(!t){e.adminPhones=[];return}if(e.adminsLoading)return;e.adminsLoading=!0,e.adminsError=null;const n=t;try{const i=await e.client.request("config.get",{});e.configSnapshot=i;const s=i.config;e.configForm=ct(s??{}),e.adminPhones=Ek(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function ku(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=ct(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],h=[...e.adminPhones,{phone:o}],d=wu(c,h,s,i);sc(l,["bindings"],d);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const g=Et(l);await e.client.request("config.set",{raw:g,baseHash:p}),await gs(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}async function $u(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=ct(e.configForm??((a=e.configSnapshot)==null?void 0:a.config)??{}),c=l.bindings??[],h=e.adminPhones.filter(x=>x.phone!==t),d=wu(c,h,s,i);sc(l,["bindings"],d);const p=(r=e.configSnapshot)==null?void 0:r.hash;if(!p){e.adminsError="Config hash missing; reload and retry.";return}const g=Et(l);await e.client.request("config.set",{raw:g,baseHash:p}),await gs(e,n)}catch(l){e.adminsError=String(l)}finally{e.adminsSaving=!1}}const Tk=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:ku,loadAdmins:gs,removeAdmin:$u},Symbol.toStringTag,{value:"Module"}));async function Lt(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 xu(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 Lt(e,i)}catch(a){e.contactsError=String(a)}finally{e.contactsSaving=!1}}async function Su(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 Lt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function qo(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 Lt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Au(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 Lt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const _k=Object.freeze(Object.defineProperty({__proto__:null,addContact:xu,deleteContact:Su,deleteContactField:Au,loadContacts:Lt,setContactField:qo},Symbol.toStringTag,{value:"Module"}));let $t=null,Mi=null,Pi=null;const fo=[[0,"Checking Tailscale service..."],[5,"Starting login..."],[15,"Requesting authentication link..."],[40,"Setting up secure connection..."],[70,"Almost ready..."]];function zt(){$t&&(clearInterval($t),$t=null),Mi&&(clearInterval(Mi),Mi=null),Pi&&(clearTimeout(Pi),Pi=null)}function Sn(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function Mk(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),onAddAccount:()=>{e.addingWorkspace=!0},hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0},onRestartGateway:()=>e.handleGatewayRestart()}}function Pk(e){const t=ue(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 Ik(e){const t=ue(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function Lk(e){var i;const t=ue(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 Rk(e){return e.selectedWorkspace??void 0}function ue(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const Dk=/^data:/i,Bk=/^https?:\/\//i;function Pl(e){var r,l;const t=((r=e.agentsList)==null?void 0:r.agents)??[],n=jl(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 Dk.test(a)||Bk.test(a)?a:o==null?void 0:o.avatarUrl}function Nk(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 Ok(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 Fk(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 Uk(e){var t,n,i,s,o,a,r,l,c,h;if(e.embeddingDownloading&&!e.publicChat)return u`
4485
4499
  <div class="setup-container">
4486
4500
  <div class="setup-card" style="text-align:center; max-width:420px;">
4487
4501
  <div class="setup-spinner"></div>
@@ -4502,7 +4516,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4502
4516
  <p>Connecting...</p>
4503
4517
  </div>
4504
4518
  </div>
4505
- `;if(!e.publicChatAuthenticated)return wk({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:S=>{var T;e.publicChatSessionKey=S,e.sessionKey=S,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const x=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";e.chatMessage=Wn(x,S),le(async()=>{const{loadChatHistory:f}=await Promise.resolve().then(()=>Bi);return{loadChatHistory:f}},void 0,import.meta.url).then(({loadChatHistory:f})=>{f(e)})},onAuthStepChange:S=>{e.publicChatAuthStep=S},requestUpdate:()=>{e.requestUpdate()}});const d=(t=e.publicChatConfig)==null?void 0:t.greeting,p=e.chatMessages,v=!e.chatLoading&&d?[{role:"assistant",content:[{type:"text",text:d}],timestamp:0},...Array.isArray(p)?p:[]]:p;return Bw({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:v,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Ml(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:S=>{e.chatMessage=S,e.chatSuggestions=[],e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),le(async()=>{const{loadChatHistory:S}=await Promise.resolve().then(()=>Bi);return{loadChatHistory:S}},void 0,import.meta.url).then(({loadChatHistory:S})=>{S(e)})),onDraftChange:S=>{var T;e.chatMessage=S;const x=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";mr(x,e.sessionKey,S)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:S=>e.chatAttachments=S,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:S=>e.removeQueuedMessage(S),onChatScroll:S=>e.handleChatScroll(S),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}})}if(e.connected&&e.accessState.checked){const{accessState:d}=e;if(d.hasPins&&!d.authenticated)return bl({show:!0,isFirstTime:!1,accounts:d.accounts,error:d.error,busy:d.busy,onSubmit:(p,v)=>{v!=null&&e.handlePinSubmit(p,v)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,v,S)=>e.handleChangePin(p,v,S)});if(!d.hasMasterPin&&!d.authenticated&&e.setup)return bl({show:!0,isFirstTime:!0,accounts:[],error:d.error,busy:d.busy,onSubmit:p=>e.handleSetMasterPin(p)});if(!d.hasMasterPin&&!d.authenticated&&!e.setup)return window.location.href="/setup",w}if(e.setup){const d=Bk(e.channelsSnapshot),p=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],v=Nk(e.channelsSnapshot),S=Ok(e),x=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},T=()=>{const f=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=ho[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,Kt(),kt=setInterval(()=>{const b=(Date.now()-f)/1e3,k=Math.min(95,95*(1-Math.exp(-b/30)));e.tailscaleConnectProgress=Math.round(k);let A=ho[0][1];for(const[E,M]of ho)b>=E&&(A=M);e.tailscaleConnectMessage=A},500)};return Wg({connected:e.connected,serverPlatform:((o=(s=e.hello)==null?void 0:s.server)==null?void 0:o.platform)??null,assistantName:e.assistantName,currentStep:e.setupStep,licenseKey:e.licenseKey,licenseBusy:e.licenseBusy,licenseValid:e.licenseValid,licenseMessage:e.licenseMessage,licenseTier:e.licenseTier,licenseDeviceId:e.licenseDeviceId,licenseStoredKey:e.licenseStoredKey,onLicenseKeyChange:f=>e.handleLicenseKeyChange(f),onLicenseActivate:()=>e.handleLicenseActivate(),onLicenseRemove:async()=>{await e.handleLicenseRemove(),e.licenseRemoveConfirm=!1},licenseRemoveConfirm:e.licenseRemoveConfirm,onLicenseRemoveConfirm:()=>{e.licenseRemoveConfirm=!0},onLicenseRemoveCancel:()=>{e.licenseRemoveConfirm=!1},authConnected:e.authConnected,authBusy:e.authBusy,authMessage:e.authMessage,authUrl:e.authUrl,authCodeInput:e.authCodeInput,authExpiresIn:e.authExpiresIn,whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:d,whatsappAccounts:p,whatsappActiveQrAccountId:e.whatsappActiveQrAccountId,whatsappAccountSaving:e.whatsappAccountSaving,gatewayHealthy:e.gatewayHealthy,gatewayHealthLoading:e.gatewayHealthLoading,gatewayHealthMessage:e.gatewayHealthMessage,gatewayRestartBusy:e.gatewayRestartBusy,updateAvailable:e.updateAvailable,currentVersion:e.currentVersion,latestVersion:e.latestVersion,updateChecking:e.updateChecking,updateRunning:e.updateRunning,updateMessage:e.updateMessage,updateProgressSteps:e.updateProgressSteps,updateLastResult:e.updateLastResult,onUpdateCheck:()=>e.handleUpdateCheck(),onUpdateRun:()=>e.handleUpdateRun(),onUpdateDismissResult:()=>e.handleUpdateDismissResult(),uninstallConfirm:e.uninstallConfirm,uninstallBusy:e.uninstallBusy,uninstallDone:e.uninstallDone,uninstallError:e.uninstallError,uninstallConfirmText:e.uninstallConfirmText,onUninstallConfirm:()=>e.handleUninstallConfirm(),onUninstallCancel:()=>e.handleUninstallCancel(),onUninstallConfirmTextChange:f=>e.handleUninstallConfirmTextChange(f),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:f=>e.handleAuthSubmitCode(f),onAuthCodeChange:f=>e.handleAuthCodeChange(f),onSkipToWhatsApp:()=>e.handleSkipToWhatsApp(),onWhatsAppRelink:async f=>{await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await ee(e,!0),e.requestUpdate())},onWhatsAppUnlink:async f=>{await e.handleWhatsAppLogout(f)},onWhatsAppReset:async f=>{await e.handleWhatsAppLogout(f),await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await ee(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await ee(e,!0),await e.handleGatewayHealthCheck()},onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),ee(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:f=>e.handleRemoveWhatsAppAccount(f),workspaces:e.workspaces,workspacesLoading:e.workspacesLoading,workspacesError:e.workspacesError,addingWorkspace:e.addingWorkspace,newWorkspaceName:e.newWorkspaceName,newWorkspacePath:e.newWorkspacePath,workspaceSaving:e.workspaceSaving,workspaceRemoveConfirm:e.workspaceRemoveConfirm,newWorkspacePin:e.newWorkspacePin,onSetNewWorkspacePin:f=>{e.newWorkspacePin=f},onWorkspaceCreate:async(f,b)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(f,b),k.match(/^\d{4,6}$/)&&(await Sk(e,f,k),e.newWorkspacePin="")},onWorkspaceRemove:f=>e.handleWorkspaceRemove(f),onSetAddingWorkspace:f=>{e.addingWorkspace=f},onSetNewWorkspaceName:f=>{e.newWorkspaceName=f},onSetNewWorkspacePath:f=>{e.newWorkspacePath=f},onSetWorkspaceRemoveConfirm:f=>{e.workspaceRemoveConfirm=f},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(f,b)=>e.handleWorkspaceRename(f,b),whatsappDmPolicy:(()=>{const f=ue(e),b=f==null?void 0:f.whatsappAccountId,k=b?p.find(A=>A.accountId===b):p[0];return(k==null?void 0:k.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var P;const f=ue(e),b=f==null?void 0:f.whatsappAccountId,k=b?p.find(R=>R.accountId===b):p[0];if(!k)return;const E=k.dmPolicy!=null&&k.dmPolicy!=="disabled"?"disabled":"open",M=E==="open"?{dmPolicy:E,allowFrom:["*"]}:{dmPolicy:E};try{const R=await e.client.request("config.get"),F=R.config,H=(P=F==null?void 0:F.channels)==null?void 0:P.whatsapp,ke=((H==null?void 0:H.accounts)??{})[k.accountId]?{channels:{whatsapp:{accounts:{[k.accountId]:M}}}}:{channels:{whatsapp:M}};await e.client.request("config.patch",{raw:JSON.stringify(ke),baseHash:R.hash,note:`WhatsApp DM policy → ${E}`,skipRestart:!0}),await ee(e,!1)}catch(R){console.error("DM toggle failed:",R)}},whatsappModel:(()=>{var P,R;const f=ue(e);if(!f)return null;const b=f.agents.find(F=>F.id.endsWith("-public")||F.id==="public");if(!b)return null;const k=(P=e.configSnapshot)==null?void 0:P.config,A=(R=k==null?void 0:k.agents)==null?void 0:R.list;if(!Array.isArray(A))return null;const E=A.find(F=>F.id===b.id);if(!(E!=null&&E.model))return null;const M=typeof E.model=="string"?E.model:E.model.primary;return(M==null?void 0:M.trim())||null})(),whatsappModelCatalog:e.chatModelCatalog??[],onWhatsAppModelChange:async f=>{const b=ue(e);if(!b)return;const k=b.agents.find(A=>A.id.endsWith("-public")||A.id==="public");if(k)try{const A=await e.client.request("config.get"),E=A.config,M=(E==null?void 0:E.agents)??{},P=Array.isArray(M.list)?[...M.list]:[],R=P.findIndex(H=>H.id===k.id);if(f)R>=0?P[R]={...P[R],model:f}:P.push({id:k.id,model:f});else if(R>=0){const{model:H,...z}=P[R];Object.keys(z).length<=1?P.splice(R,1):P[R]=z}const F=P.length>0?{agents:{list:P}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(F),baseHash:A.hash,note:`Public agent model → ${f||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Model change failed:",A)}},whatsappThinkingLevel:(()=>{var M,P,R;const f=ue(e);if(!f)return null;const b=f.agents.find(F=>F.id.endsWith("-public")||F.id==="public");if(!b)return null;const k=(M=e.configSnapshot)==null?void 0:M.config,A=(P=k==null?void 0:k.agents)==null?void 0:P.list;if(!Array.isArray(A))return null;const E=A.find(F=>F.id===b.id);return((R=E==null?void 0:E.thinkingLevel)==null?void 0:R.trim())||null})(),onWhatsAppThinkingChange:async f=>{const b=ue(e);if(!b)return;const k=b.agents.find(A=>A.id.endsWith("-public")||A.id==="public");if(k)try{const A=await e.client.request("config.get"),E=A.config,M=(E==null?void 0:E.agents)??{},P=Array.isArray(M.list)?[...M.list]:[],R=P.findIndex(z=>z.id===k.id),F=f==="off"?void 0:f;if(F)R>=0?P[R]={...P[R],thinkingLevel:F}:P.push({id:k.id,thinkingLevel:F});else if(R>=0){const{thinkingLevel:z,...ke}=P[R];Object.keys(ke).length<=1?P.splice(R,1):P[R]=ke}const H=P.length>0?{agents:{list:P}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(H),baseHash:A.hash,note:`Public agent thinking → ${F||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Thinking change failed:",A)}},whatsappGroupPolicy:(()=>{var R,F;const f=(R=e.configSnapshot)==null?void 0:R.config,b=(F=f==null?void 0:f.channels)==null?void 0:F.whatsapp,k=ue(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},M=A?E[A]:void 0;return(M==null?void 0:M.groupPolicy)??(b==null?void 0:b.groupPolicy)??"allowlist"})(),whatsappGroupRequireMention:(()=>{var F,H;const f=(F=e.configSnapshot)==null?void 0:F.config,b=(H=f==null?void 0:f.channels)==null?void 0:H.whatsapp,k=ue(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},M=A?E[A]:void 0,R=((M==null?void 0:M.groups)??(b==null?void 0:b.groups)??{})["*"];return(R==null?void 0:R.requireMention)!==!1})(),onWhatsAppGroupToggle:async()=>{var k;const f=ue(e),b=f==null?void 0:f.whatsappAccountId;try{const A=await e.client.request("config.get"),E=A.config,M=((k=E==null?void 0:E.channels)==null?void 0:k.whatsapp)??{},P=M.accounts??{},R=b?P[b]:void 0,F=(R==null?void 0:R.groupPolicy)??M.groupPolicy??"allowlist",H=F==="disabled"||F==="allowlist",z=H?"open":"disabled",ke=H?{"*":{}}:void 0,_e={groupPolicy:z};ke&&(_e.groups=ke);const Ke=R?{channels:{whatsapp:{accounts:{[b]:_e}}}}:{channels:{whatsapp:_e}};await e.client.request("config.patch",{raw:JSON.stringify(Ke),baseHash:A.hash,note:`WhatsApp groups → ${z}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Group toggle failed:",A)}},onWhatsAppGroupMentionChange:async f=>{var A;const b=ue(e),k=b==null?void 0:b.whatsappAccountId;try{const E=await e.client.request("config.get"),M=E.config,R=(((A=M==null?void 0:M.channels)==null?void 0:A.whatsapp)??{}).accounts??{},F=k?R[k]:void 0,H={"*":{requireMention:f}},z=F?{channels:{whatsapp:{accounts:{[k]:{groups:H}}}}}:{channels:{whatsapp:{groups:H}}};await e.client.request("config.patch",{raw:JSON.stringify(z),baseHash:E.hash,note:`WhatsApp group mention → ${f?"when mentioned":"always"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(E){console.error("Group mention change failed:",E)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:v.configured,imessageRunning:v.running,imessageConnected:v.connected,imessageLastError:v.lastError,imessageSelfChatMode:v.selfChatMode,imessageCliPath:v.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:S,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,k=(b==null?void 0:b.bindings)??[],A=ue(e),E=A==null?void 0:A.agents.find(H=>H.id.endsWith("-admin")||H.id==="admin"),M=(E==null?void 0:E.id)??"admin",P=k.filter(H=>{var z;return((z=H.match)==null?void 0:z.channel)!=="imessage"}),R=[{agentId:M,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],F=[...P,...R];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:F}),baseHash:f.hash,note:"Enable iMessage (self-chat) for "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Ue(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await ee(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,A=((b==null?void 0:b.bindings)??[]).filter(E=>{var M;return((M=E.match)==null?void 0:M.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:A}),baseHash:f.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Ue(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,k=(b==null?void 0:b.bindings)??[],A=ue(e),E=A==null?void 0:A.agents.find(F=>F.id.endsWith("-admin")||F.id==="admin"),M=(E==null?void 0:E.id)??"admin",P=k.filter(F=>{var H;return((H=F.match)==null?void 0:H.channel)!=="imessage"}),R=[{agentId:M,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:[...P,...R]}),baseHash:f.hash,note:"Reassign iMessage to "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Ue(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:f=>{var b,k,A,E;if(e.infoModalOpen=f,f==="remote-access"){const M=((b=e.tailscaleStatus)==null?void 0:b.tailnetUrl)??((k=e.tailscaleStatus)!=null&&k.hostname?`https://${e.tailscaleStatus.hostname}`:null);M&&!e.remoteAccessQrDataUrl&&e.client.request("qr.generate",{url:M}).then(P=>{e.remoteAccessQrDataUrl=(P==null?void 0:P.dataUrl)??null}).catch(()=>{})}else if(f==="public-chat"){const M=((A=e.tailscaleStatus)==null?void 0:A.publicUrl)??((E=e.tailscaleStatus)==null?void 0:E.tailnetUrl)??null,P=e.selectedWorkspace??null;if(M&&P){const R=`${M}/public/chat/${encodeURIComponent(P)}`;e.publicChatQrDataUrl||e.client.request("qr.generate",{url:R}).then(F=>{e.publicChatQrDataUrl=(F==null?void 0:F.dataUrl)??null}).catch(()=>{})}}},onInfoModalClose:()=>{e.infoModalOpen=null},remoteAccessQrDataUrl:e.remoteAccessQrDataUrl??null,publicChatQrDataUrl:e.publicChatQrDataUrl??null,publicChatFullUrl:(()=>{var k,A;const f=((k=e.tailscaleStatus)==null?void 0:k.publicUrl)??((A=e.tailscaleStatus)==null?void 0:A.tailnetUrl)??null,b=e.selectedWorkspace??null;return!f||!b?null:`${f}/public/chat/${encodeURIComponent(b)}`})(),isMaster:e.accessState.master,apiKeyProviders:e.apiKeyProviders,apiKeyModalOpen:e.apiKeyModalOpen,apiKeyBusy:e.apiKeyBusy,apiKeyError:e.apiKeyError,apiKeySuccess:e.apiKeySuccess,apiKeySavingProvider:e.apiKeySavingProvider,onApiKeyModalOpen:()=>{e.apiKeyModalOpen=!0,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeyModalClose:()=>{e.apiKeyModalOpen=!1,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeySave:async(f,b)=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await $l(e.client,f,b);const k=`${f} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Ti(e.client)}catch{}f==="anthropic"&&await e.handleAuthStatusCheck(),setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:"Failed to save key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyRemove:async f=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await nk(e.client,f);const b=`${f} key removed`;e.apiKeySuccess=b,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Ti(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===b&&(e.apiKeySuccess=null)},2500)}catch(b){e.apiKeyError=b instanceof Error?b.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyDisable:async(f,b)=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await ik(e.client,f,b);const k=`${f} ${b?"disabled":"enabled"}`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Ti(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:`Failed to ${b?"disable":"enable"} key`,e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},authApiKeyMode:e.authApiKeyMode,authApiKeyInput:e.authApiKeyInput,authApiKeyBusy:e.authApiKeyBusy,authApiKeyError:e.authApiKeyError,onAuthApiKeyToggle:()=>{e.authApiKeyMode=!e.authApiKeyMode,e.authApiKeyError=null},onAuthApiKeyChange:f=>{e.authApiKeyInput=f},onAuthApiKeySubmit:async()=>{const f=e.authApiKeyInput.trim();if(f){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await $l(e.client,"anthropic",f),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(b){e.authApiKeyError=b instanceof Error?b.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var b;const f=e.selectedWorkspace??((b=e.workspaces[0])==null?void 0:b.name);return f?e.accessState.accounts.some(k=>k.id===f):!1})(),accountPinModalOpen:e.accountPinModalOpen,accountPinBusy:e.accountPinBusy,accountPinError:e.accountPinError,accountPinSuccess:e.accountPinSuccess,onAccountPinModalOpen:()=>{e.accountPinModalOpen=!0,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinModalClose:()=>{e.accountPinModalOpen=!1,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinSave:(f,b)=>{var A;const k=e.selectedWorkspace??((A=e.workspaces[0])==null?void 0:A.name);k&&e.handleAccountPinSave(k,f,b)},publicChatAccountId:e.selectedWorkspace??null,publicChatSettingsOpen:e.publicChatSettingsOpen,onPublicChatSettingsOpen:()=>{e.publicChatSettingsOpen=!0},onPublicChatSettingsClose:()=>{e.publicChatSettingsOpen=!1},publicChatWidgetModalOpen:e.publicChatWidgetModalOpen,onPublicChatWidgetModalOpen:()=>{e.publicChatWidgetModalOpen=!0},onPublicChatWidgetModalClose:()=>{e.publicChatWidgetModalOpen=!1},publicChatEnabled:(()=>{var k;const f=(k=e.configSnapshot)==null?void 0:k.config,b=f==null?void 0:f.publicChat;return(b==null?void 0:b.enabled)===!0})(),publicChatAuthMode:(()=>{var A;const f=(A=e.configSnapshot)==null?void 0:A.config,b=f==null?void 0:f.publicChat,k=b==null?void 0:b.auth;return k==="verified"||k==="choice"?k:"anonymous"})(),publicChatGreeting:(()=>{var E;const f=(E=e.configSnapshot)==null?void 0:E.config,b=f==null?void 0:f.publicChat,k=b==null?void 0:b.greetings,A=e.selectedWorkspace??"";return(A&&(k==null?void 0:k[A]))??""})(),publicChatGreetingBusy:e.publicChatGreetingBusy,onPublicChatGreetingToggle:async()=>{var b;if(e.publicChatGreetingBusy)return;const f=e.selectedWorkspace??"";if(f){e.publicChatGreetingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=(b=A==null?void 0:A.publicChat)==null?void 0:b.greetings;if(E==null?void 0:E[f]){const P={publicChat:{greetings:{[f]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(P),baseHash:k.hash,note:`Public chat greeting → disabled (${f})`,skipRestart:!0})}else{const P=await e.client.request("public.greeting.generate",{accountId:f});if(P!=null&&P.ok&&P.greeting){const R=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[f]:P.greeting}}}),baseHash:R.hash,note:`Public chat greeting → enabled (${f})`,skipRestart:!0})}}e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting toggle failed:",k)}finally{e.publicChatGreetingBusy=!1}}},onPublicChatGreetingSave:async f=>{const b=e.selectedWorkspace??"";if(b)try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[b]:f}}}),baseHash:k.hash,note:`Public chat greeting text updated (${b})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting save failed:",k)}},onPublicChatGreetingRegenerate:async()=>{if(e.publicChatGreetingBusy)return;const f=e.selectedWorkspace??"";if(f){e.publicChatGreetingBusy=!0;try{const b=await e.client.request("public.greeting.generate",{accountId:f});if(b!=null&&b.ok&&b.greeting){const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[f]:b.greeting}}}),baseHash:k.hash,note:`Public chat greeting regenerated (${f})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}}catch(b){console.error("Public chat greeting regeneration failed:",b)}finally{e.publicChatGreetingBusy=!1}}},publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var f;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get"),k=b.config,A=((f=k==null?void 0:k.publicChat)==null?void 0:f.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!A}}),baseHash:b.hash,note:`Public chat → ${A?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),e.publicChatQrDataUrl=null}catch(b){console.error("Public chat toggle failed:",b)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async f=>{if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{auth:f}}),baseHash:b.hash,note:`Public chat auth → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Public chat auth mode change failed:",b)}finally{e.publicChatToggleBusy=!1}}},publicChatEmailFrom:(()=>{var k,A;const f=(k=e.configSnapshot)==null?void 0:k.config,b=(A=f==null?void 0:f.publicChat)==null?void 0:A.email;return(b==null?void 0:b.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var A;const f=(A=e.configSnapshot)==null?void 0:A.config,b=f==null?void 0:f.publicChat,k=b==null?void 0:b.verifyMethods;return Array.isArray(k)?k:["phone"]})(),onPublicChatEmailSave:async(f,b)=>{if(!e.publicChatEmailBusy){e.publicChatEmailBusy=!0;try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{email:{from:f||void 0},verifyMethods:b}}),baseHash:k.hash,note:"Update email verification settings for public chat",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Email verification save failed:",k)}finally{e.publicChatEmailBusy=!1}}},brandAccentColor:(()=>{var k;const f=e.selectedWorkspace;return f?((k=Be()[f])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const f=e.selectedWorkspace;return f?((k=Be()[f])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const f=e.selectedWorkspace;return f?!!((k=Be()[f])!=null&&k.logoUrl):!1})(),brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async f=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,M=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=M.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...M,brand:{...P,accentColor:f}}}}),baseHash:A.hash,note:`Brand accent → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const R=Be();R[b]||(R[b]={}),R[b].accentColor=f,Tn(b)}catch(A){console.error("Brand accent change failed:",A)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async f=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,M=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=M.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...M,brand:{...P,backgroundColor:f}}}}),baseHash:A.hash,note:`Brand background → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const R=Be();R[b]||(R[b]={}),R[b].backgroundColor=f,Tn(b)}catch(A){console.error("Brand background change failed:",A)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async f=>{const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const k=await f.arrayBuffer(),A=new Uint8Array(k);let E="";for(let R=0;R<A.length;R++)E+=String.fromCharCode(A[R]);const M=btoa(E);await e.client.request("brand.uploadLogo",{workspace:b,data:M,mimeType:f.type});const P=Be();P[b]||(P[b]={}),P[b].logoUrl=`/brand-logo/${encodeURIComponent(b)}`}catch(k){console.error("Brand logo upload failed:",k)}finally{e.brandingBusy=!1}}},onBrandLogoRemove:async()=>{const f=e.selectedWorkspace;if(!(!f||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:f});const b=Be();b[f]&&delete b[f].logoUrl}catch(b){console.error("Brand logo remove failed:",b)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var b;const f=e.selectedWorkspace;if(!(!f||e.brandingBusy)){e.brandingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=((b=A==null?void 0:A.workspaces)==null?void 0:b[f])??{},{brand:M,...P}=E;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[f]:{...P,brand:null}}}),baseHash:k.hash,note:"Brand reset to defaults",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");try{await e.client.request("brand.removeLogo",{workspace:f})}catch{}const R=Be();delete R[f],Tn(f)}catch(k){console.error("Brand reset failed:",k)}finally{e.brandingBusy=!1}}},tailscaleStatus:e.tailscaleStatus,tailscaleBusy:e.tailscaleBusy,tailscaleAuthUrl:e.tailscaleAuthUrl,tailscaleError:e.tailscaleError,tailscaleFunnelEnableUrl:e.tailscaleFunnelEnableUrl,tailscaleDisableConfirm:e.tailscaleDisableConfirm,tailscaleConnectProgress:e.tailscaleConnectProgress,tailscaleConnectMessage:e.tailscaleConnectMessage,tailscaleConnectSuccess:e.tailscaleConnectSuccess,onTailscaleEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleAuthUrl=null,T();try{const f=await e.client.request("tailscale.enable");f.authUrl?(kt&&(clearInterval(kt),kt=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=f.authUrl,_i=setInterval(async()=>{try{const b=await e.client.request("tailscale.status");e.tailscaleStatus=b,e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,b.loggedIn&&(Kt(),e.tailscaleAuthUrl=null,e.tailscaleConnectSuccess=!0,e.tailscaleConnectMessage="Connected!",setTimeout(()=>{e.tailscaleConnectSuccess=!1,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1},1500))}catch{}},3e3),Mi=setTimeout(()=>{Kt(),e.tailscaleBusy&&(e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)},3e5)):f.alreadyLoggedIn?(Kt(),e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1):(Kt(),e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)}catch(f){console.error("Tailscale enable failed:",f),Kt(),e.tailscaleError=f.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null;try{await e.client.request("tailscale.serve.enable"),await x()}catch(f){console.error("Tailscale serve enable failed:",f),e.tailscaleError=f.message||"Failed to enable Remote Access"}finally{e.tailscaleBusy=!1}}},onTailscaleServeDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.serve.disable"),await x()}catch(f){console.error("Tailscale serve disable failed:",f)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var f;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable"),await x()}catch(b){console.error("Tailscale funnel enable failed:",b);const k=b;(f=k.payload)!=null&&f.enableUrl&&(e.tailscaleFunnelEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Funnel"}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.funnel.disable"),await x()}catch(f){console.error("Tailscale funnel disable failed:",f)}finally{e.tailscaleBusy=!1}}},onTailscaleDisableConfirmToggle:()=>{e.tailscaleDisableConfirm=!e.tailscaleDisableConfirm},wifiModalOpen:e.wifiModalOpen,onWifiModalToggle:()=>{e.wifiModalOpen=!e.wifiModalOpen,e.wifiModalOpen||(e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null)},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{var f;if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[b,k]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiNetworks=b.networks,k.connected&&k.signal==null&&((f=b.networks)!=null&&f.length)){const A=b.networks.find(E=>E.active)||b.networks.find(E=>E.ssid===k.ssid);A&&(k.signal=A.signal)}e.wifiStatus=k}catch(b){console.error("WiFi scan failed:",b),e.wifiError=b.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{var b;if(e.wifiBusy||!e.wifiSelectedSsid)return;const f=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const k=await e.client.request("wifi.connect",{ssid:f,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:k.connected,ssid:k.ssid,signal:null,ip:k.ip,savedSsid:k.ssid,autoconnect:!0},e.wifiBusy=!1;try{const[A,E]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(E.connected&&E.signal==null&&((b=A.networks)!=null&&b.length)){const M=A.networks.find(P=>P.active)||A.networks.find(P=>P.ssid===E.ssid);M&&(E.signal=M.signal)}e.wifiStatus=E}catch{}}catch(k){console.error("WiFi connect failed:",k),e.wifiError=k.message||"Failed to connect",e.wifiBusy=!1}},onWifiDisconnect:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.disconnect"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const f=await e.client.request("wifi.status");e.wifiStatus=f}catch(f){console.error("WiFi disconnect failed:",f),e.wifiError=f.message||"Failed to disconnect"}finally{e.wifiBusy=!1}}},onWifiForget:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.forget"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const f=await e.client.request("wifi.status");e.wifiStatus=f}catch(f){console.error("WiFi forget failed:",f),e.wifiError=f.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:f=>{e.wifiSelectedSsid=f,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:f=>{e.wifiPassword=f},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:f=>{e.networkPortInput=f,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:f=>{e.networkHostnameInput=f,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const f=e.networkPortInput.trim(),b=Number.parseInt(f,10),k=e.networkHostnameInput.trim();if(!f||!Number.isFinite(b)||b<1024||b>65535){e.networkError="Port must be a number between 1024 and 65535",e.networkBusy=!1;return}const A=b!==e.networkPort,E=k!==e.networkHostname;if(!A&&!E){e.networkBusy=!1;return}try{E&&await e.client.request("network.setHostname",{hostname:k});const M={};A&&(M.gateway={port:b}),E&&(M.discovery={bonjourHostname:k});const P=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify(M),baseHash:P.hash,note:[A?`Port → ${b}`:null,E?`Hostname → ${k}`:null].filter(Boolean).join(", "),restartDelayMs:2e3}),e.networkSuccess="Saved — redirecting...";const R=window.location.protocol,F=E?`${k}.local`:window.location.hostname,H=A?b:e.networkPort,z=`${R}//${F}:${H}/setup`;setTimeout(()=>{window.location.href=z},1500)}catch(M){console.error("Network save failed:",M),e.networkError=M.message||"Failed to save network settings",e.networkBusy=!1}},wsProps:_k(e)})}if(e.filesPage){const d=Ik(e);return ng({connected:e.connected,wsProps:Sn(e),loading:e.filesLoading,tree:e.filesTree,root:e.filesRoot,error:e.filesError,selectedPath:e.filesSelectedPath,selectedPaths:e.filesSelectedPaths,previewContent:e.filesPreviewContent,previewLoading:e.filesPreviewLoading,previewBinary:e.filesPreviewBinary,previewSize:e.filesPreviewSize,expandedDirs:e.filesExpandedDirs,currentDir:e.filesCurrentDir,message:e.filesMessage,uploadBusy:e.filesUploadBusy,reindexBusy:e.filesReindexBusy,memoryStatus:e.filesMemoryStatus,onRefresh:()=>{an(e,d),rs(e,d)},onReindex:()=>mf(e,d),onSelectFile:p=>{e.filesPendingDeletePath=null,lf(e,p,d)},onToggleSelectFile:p=>cf(e,p,d),onToggleDir:p=>yf(e,p),onUpload:(p,v)=>pf(e,p,v,d),onNewFolder:(p,v)=>hf(e,p,v,d),onDownload:p=>Xc(e,p,d),onBulkDownload:()=>df(e,d),onDelete:p=>{e.filesPendingDeletePath=null,ff(e,p,d)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,v)=>uf(e,p,v,d),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const v=e.filesSearchAgentId??d;vf(e,p,v)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{bf(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return Jf({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:()=>Vw(e),onStop:()=>Qw(e),onToggleInput:()=>Yw(e),onToggleFullscreen:()=>Xw(e),onCompleteHandoff:()=>Jw(e),onCanvasMouseDown:d=>{const v=d.target.getBoundingClientRect(),x=Bn().translateCoordinates(d.clientX-v.left,d.clientY-v.top);lo(e,"mousePressed",x.x,x.y,d.button===2?"right":d.button===1?"middle":"left")},onCanvasMouseUp:d=>{const v=d.target.getBoundingClientRect(),x=Bn().translateCoordinates(d.clientX-v.left,d.clientY-v.top);lo(e,"mouseReleased",x.x,x.y)},onCanvasMouseMove:d=>{const p=Bn();if(p.shouldThrottleMouseMove())return;const S=d.target.getBoundingClientRect(),x=p.translateCoordinates(d.clientX-S.left,d.clientY-S.top);lo(e,"mouseMoved",x.x,x.y)},onCanvasKeyDown:d=>{let p=0;d.altKey&&(p|=1),d.ctrlKey&&(p|=2),d.metaKey&&(p|=4),d.shiftKey&&(p|=8),co(e,"keyDown",d.key,{code:d.code,modifiers:p||void 0}),d.key.length===1&&co(e,"char",d.key,{text:d.key})},onCanvasKeyUp:d=>{co(e,"keyUp",d.key,{code:d.code})}});if(e.adminsPage){const d=Mk(e),p=Pk(e);return zg({connected:e.connected,wsProps:Sn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>fs(e,d),onAdd:v=>{wu(e,v,d,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:v=>ku(e,v,d,p),onNewPhoneChange:v=>e.handleAdminsNewPhoneChange(v)})}if(e.contactsPage){const d=Lk(e);return Qg({connected:e.connected,wsProps:Sn(e),loading:e.contactsLoading,saving:e.contactsSaving,records:e.contactsRecords,error:e.contactsError,searchQuery:e.contactsSearchQuery,editingId:e.contactsEditingId,showAddForm:e.contactsShowAddForm,newRecordPhone:e.contactsNewPhone,newRecordName:e.contactsNewName,deleteConfirmId:e.contactsDeleteConfirmId,addFieldForId:e.contactsAddFieldForId,addFieldKey:e.contactsAddFieldKey,addFieldValue:e.contactsAddFieldValue,onSearch:p=>e.contactsSearchQuery=p,onSearchSubmit:()=>It(e,d),onAdd:(p,v)=>$u(e,p,v,d),onDelete:p=>xu(e,p,d),onSetField:(p,v,S)=>zo(e,p,v,S,d),onDeleteField:(p,v)=>Su(e,p,v,d),onToggleExpand:p=>{e.contactsEditingId=e.contactsEditingId===p?null:p},onShowAddForm:()=>e.contactsShowAddForm=!0,onCancelAddForm:()=>{e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName=""},onNewRecordPhoneChange:p=>e.handleContactsNewPhoneChange(p),onNewRecordNameChange:p=>e.handleContactsNewNameChange(p),onRefresh:()=>It(e,d),onDeleteConfirmOpen:p=>e.contactsDeleteConfirmId=p,onDeleteConfirmClose:()=>e.contactsDeleteConfirmId=null,onAddFieldOpen:p=>{e.contactsAddFieldForId=p,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldClose:()=>{e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldKeyChange:p=>e.contactsAddFieldKey=p,onAddFieldValueChange:p=>e.contactsAddFieldValue=p,onAddFieldSubmit:()=>{const p=e.contactsAddFieldForId,v=e.contactsAddFieldKey.trim();!p||!v||(zo(e,p,v,e.contactsAddFieldValue,d),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const d=e.connected?null:"Disconnected from gateway.",p=Ml(e),v=e.chatAvatarUrl??p??null,S=(()=>{var f;const x=(f=e.configSnapshot)==null?void 0:f.config,T=x==null?void 0:x.publicChat;return(T==null?void 0:T.enabled)===!0})();return Vb({connected:e.connected,wsProps:Sn(e),publicChatEnabled:S,publicChatAccountId:e.selectedWorkspace??void 0,sessionKey:e.sessionKey,onSessionKeyChange:x=>{const T=e.selectedWorkspace??"";yo(),Un(T,e.sessionKey,e.chatMessage),e.sessionKey=x,e.chatMessage=Wn(T,x),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:x,lastActiveSessionKey:x}),e.loadAssistantIdentity(),Oe(e),So(e)},thinkingLevel:e.chatThinkingLevel,showThinking:e.settings.chatShowThinking??!1,modelProvider:e.chatModelProvider,model:e.chatModel,modelCatalog:e.chatModelCatalog,onModelChange:x=>{const T=Math.max(e.chatMessages.length+10,Fe);li(e,e.sessionKey,{model:x}).then(()=>{Oe(e,{limit:T})})},onThinkingLevelChange:x=>{const T=Math.max(e.chatMessages.length+10,Fe);li(e,e.sessionKey,{thinkingLevel:x==="off"?null:x}).then(()=>{Oe(e,{limit:T})})},verboseLevel:e.chatVerboseLevel,fillerEnabled:e.chatFillerEnabled,suggestions:e.chatSuggestions,onSuggestionClick:x=>{e.chatMessage=x,e.chatSuggestions=[],e.handleSendChat()},onVerboseChange:x=>{const T=Math.max(e.chatMessages.length+10,Fe);li(e,e.sessionKey,{verboseLevel:x==="off"?null:x}).then(()=>{Oe(e,{limit:T})})},onFillerChange:x=>{const T=Math.max(e.chatMessages.length+10,Fe);li(e,e.sessionKey,{fillerEnabled:x}).then(()=>{Oe(e,{limit:T})})},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:v,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,disabledReason:d,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const x=Math.max(e.chatMessages.length+10,Fe);return Promise.all([Oe(e,{limit:x}),So(e)])},onToggleFocusMode:()=>{},onChatScroll:x=>e.handleChatScroll(x),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:x=>{e.chatMessage=x,mr(e.selectedWorkspace??"",e.sessionKey,x)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:x=>e.chatAttachments=x,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:x=>e.removeQueuedMessage(x),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:x=>e.handleOpenSidebar(x),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:x=>e.handleSplitRatioChange(x),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?Dw({connected:e.connected,wsProps:Sn(e),activeTab:e.advancedTab,onTabChange:d=>{e.advancedTab=d,d==="cron"&&e.loadCron(),d==="skills"&&Xe(e,{clearMessages:!0}),d==="logs"&&(e.logsSubTab==="session"?Pn(e,{reset:!0}):Vt(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(r=(a=e.channelsSnapshot)==null?void 0:a.channelMeta)!=null&&r.length?e.channelsSnapshot.channelMeta.map(d=>d.id):((l=e.channelsSnapshot)==null?void 0:l.channelOrder)??[],channelLabels:((c=e.channelsSnapshot)==null?void 0:c.channelLabels)??{},channelMeta:((h=e.channelsSnapshot)==null?void 0:h.channelMeta)??[],agentIds:(()=>{var p;const d=ue(e);return((p=d==null?void 0:d.agents)==null?void 0:p.map(v=>v.id))??[]})(),runsJobId:e.cronRunsJobId,runs:e.cronRuns,newEventModalOpen:e.cronNewEventModal,onNewEventModalOpen:()=>{e.cronNewEventModal=!0},onNewEventModalClose:()=>{e.cronNewEventModal=!1,e.cronEditJobId=null},detailJobId:e.cronDetailJobId,editJobId:e.cronEditJobId,onDetailOpen:d=>{e.cronDetailJobId=d.id,bo(e,d.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:d=>{e.cronForm=ph(d),e.cronEditJobId=d.id,e.cronDetailJobId=null},onEditSave:()=>{const d=e.cronEditJobId;d&&hh(e,d).then(()=>{e.cronEditJobId=null})},onFormChange:d=>e.cronForm={...e.cronForm,...d},onRefresh:()=>e.loadCron(),onAdd:()=>{rh(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(d,p)=>lh(e,d,p),onRun:d=>ch(e,d),onRemove:d=>{e.cronPendingDeleteId=null,uh(e,d)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:d=>{e.cronPendingDeleteId=d||null},onLoadRuns:d=>bo(e,d),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:d=>e.skillsFilter=d,onTypeFilterChange:d=>e.skillsTypeFilter=d,onRefresh:()=>Xe(e,{clearMessages:!0}),onToggle:(d,p)=>Mc(e,d,p),onEdit:(d,p)=>_c(e,d,p),onSaveKey:d=>Pc(e,d),onInstall:(d,p,v)=>Ic(e,d,p,v),onViewDetail:d=>Lc(e,d),onDetailClose:()=>Rc(e),onDetailTab:d=>Dc(e,d),onAddOpen:()=>Bc(e),onAddClose:()=>Nc(e),onImportDraft:d=>Oc(e,d),onInstallDraft:d=>Fc(e,d),onDeleteDraft:d=>Uc(e,d),onAddSave:()=>ra(e),onAddFormUpdate:(d,p)=>{e.skillAddForm={...e.skillAddForm,[d]:p}},onDelete:d=>Hc(e,d),onEditSkill:d=>Wc(e,d),onEditDetail:d=>Kc(e,d),onRefUpdate:(d,p)=>zc(e,d,p),onEditTab:d=>qc(e,d)},logsProps:{logsSubTab:e.logsSubTab,onSubTabChange:d=>{e.logsSubTab=d,d==="session"?Pn(e,{reset:!0}):Vt(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:d=>e.sessionLogsFilterText=d,onTypeToggle:(d,p)=>{const v=e;v.sessionLogsTypeFilters={...v.sessionLogsTypeFilters,[d]:p}},onAgentToggle:(d,p)=>{const v=e;v.sessionLogsAgentFilters={...v.sessionLogsAgentFilters,[d]:p}},onToggleAutoFollow:d=>e.sessionLogsAutoFollow=d,onToggleChips:()=>{const d=e;d.sessionLogsChipsExpanded=!d.sessionLogsChipsExpanded},onToggleExpand:d=>{const p=e,v=new Set(p.sessionLogsExpandedIds);v.has(d)?v.delete(d):v.add(d),p.sessionLogsExpandedIds=v,p.requestUpdate()},onRefresh:()=>{Pn(e,{reset:!0})},onExport:(d,p)=>e.exportSessionLogs(d,p),onScroll:d=>e.handleSessionLogsScroll(d)},loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,chipsExpanded:e.logsChipsExpanded,truncated:e.logsTruncated,onFilterTextChange:d=>e.logsFilterText=d,onLevelToggle:(d,p)=>{e.logsLevelFilters={...e.logsLevelFilters,[d]:p}},onToggleAutoFollow:d=>e.logsAutoFollow=d,onToggleChips:()=>{const d=e;d.logsChipsExpanded=!d.logsChipsExpanded},onRefresh:()=>Vt(e,{reset:!0}),onExport:(d,p)=>e.exportSessionLogs(d,p),onScroll:d=>e.handleLogsScroll(d)}}):(window.location.replace("/chat"),u``)}function Uk(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 Pl(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function Wk(e,t,n){return u`
4519
+ `;if(!e.publicChatAuthenticated)return kk({authMode:e.publicChatConfig.auth??"anonymous",authStep:e.publicChatAuthStep,connected:e.connected,client:e.client,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,accountId:e.publicChatConfig.accountId,cookieTtlDays:e.publicChatConfig.cookieTtlDays,otpChannels:e.publicChatConfig.otpChannels,verifyMethods:e.publicChatConfig.verifyMethods,onAuthenticated:x=>{var T;e.publicChatSessionKey=x,e.sessionKey=x,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready";const S=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";e.chatMessage=Kn(S,x),le(async()=>{const{loadChatHistory:f}=await Promise.resolve().then(()=>Ni);return{loadChatHistory:f}},void 0,import.meta.url).then(({loadChatHistory:f})=>{f(e)})},onAuthStepChange:x=>{e.publicChatAuthStep=x},requestUpdate:()=>{e.requestUpdate()}});const d=(t=e.publicChatConfig)==null?void 0:t.greeting,p=e.chatMessages,g=!e.chatLoading&&d?[{role:"assistant",content:[{type:"text",text:d}],timestamp:0},...Array.isArray(p)?p:[]]:p;return Nw({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:g,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Pl(e)??null,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,canAbort:!!e.chatRunId,disabledReason:e.connected?null:"Disconnected.",error:e.lastError,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,suggestions:e.chatSuggestions,onSuggestionClick:x=>{e.chatMessage=x,e.chatSuggestions=[],e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),le(async()=>{const{loadChatHistory:x}=await Promise.resolve().then(()=>Ni);return{loadChatHistory:x}},void 0,import.meta.url).then(({loadChatHistory:x})=>{x(e)})),onDraftChange:x=>{var T;e.chatMessage=x;const S=((T=e.publicChatConfig)==null?void 0:T.accountId)??"";yr(S,e.sessionKey,x)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:x=>e.chatAttachments=x,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:x=>e.removeQueuedMessage(x),onChatScroll:x=>e.handleChatScroll(x),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}})}if(e.connected&&e.accessState.checked){const{accessState:d}=e;if(d.hasPins&&!d.authenticated)return wl({show:!0,isFirstTime:!1,accounts:d.accounts,error:d.error,busy:d.busy,onSubmit:(p,g)=>{g!=null&&e.handlePinSubmit(p,g)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(p,g,x)=>e.handleChangePin(p,g,x)});if(!d.hasMasterPin&&!d.authenticated&&e.setup)return wl({show:!0,isFirstTime:!0,accounts:[],error:d.error,busy:d.busy,onSubmit:p=>e.handleSetMasterPin(p)});if(!d.hasMasterPin&&!d.authenticated&&!e.setup)return window.location.href="/setup",w}if(e.setup){const d=Nk(e.channelsSnapshot),p=((i=(n=e.channelsSnapshot)==null?void 0:n.channelAccounts)==null?void 0:i.whatsapp)??[],g=Ok(e.channelsSnapshot),x=Fk(e),S=async()=>{e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null},T=()=>{const f=Date.now();e.tailscaleConnectProgress=0,e.tailscaleConnectMessage=fo[0][1],e.tailscaleConnectSuccess=!1,e.tailscaleError=null,zt(),$t=setInterval(()=>{const b=(Date.now()-f)/1e3,k=Math.min(95,95*(1-Math.exp(-b/30)));e.tailscaleConnectProgress=Math.round(k);let A=fo[0][1];for(const[E,M]of fo)b>=E&&(A=M);e.tailscaleConnectMessage=A},500)};return Kg({connected:e.connected,serverPlatform:((o=(s=e.hello)==null?void 0:s.server)==null?void 0:o.platform)??null,assistantName:e.assistantName,currentStep:e.setupStep,licenseKey:e.licenseKey,licenseBusy:e.licenseBusy,licenseValid:e.licenseValid,licenseMessage:e.licenseMessage,licenseTier:e.licenseTier,licenseDeviceId:e.licenseDeviceId,licenseStoredKey:e.licenseStoredKey,onLicenseKeyChange:f=>e.handleLicenseKeyChange(f),onLicenseActivate:()=>e.handleLicenseActivate(),onLicenseRemove:async()=>{await e.handleLicenseRemove(),e.licenseRemoveConfirm=!1},licenseRemoveConfirm:e.licenseRemoveConfirm,onLicenseRemoveConfirm:()=>{e.licenseRemoveConfirm=!0},onLicenseRemoveCancel:()=>{e.licenseRemoveConfirm=!1},authConnected:e.authConnected,authBusy:e.authBusy,authMessage:e.authMessage,authUrl:e.authUrl,authCodeInput:e.authCodeInput,authExpiresIn:e.authExpiresIn,whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:d,whatsappAccounts:p,whatsappActiveQrAccountId:e.whatsappActiveQrAccountId,whatsappAccountSaving:e.whatsappAccountSaving,gatewayHealthy:e.gatewayHealthy,gatewayHealthLoading:e.gatewayHealthLoading,gatewayHealthMessage:e.gatewayHealthMessage,gatewayRestartBusy:e.gatewayRestartBusy,updateAvailable:e.updateAvailable,currentVersion:e.currentVersion,latestVersion:e.latestVersion,updateChecking:e.updateChecking,updateRunning:e.updateRunning,updateMessage:e.updateMessage,updateProgressSteps:e.updateProgressSteps,updateLastResult:e.updateLastResult,onUpdateCheck:()=>e.handleUpdateCheck(),onUpdateRun:()=>e.handleUpdateRun(),onUpdateDismissResult:()=>e.handleUpdateDismissResult(),uninstallConfirm:e.uninstallConfirm,uninstallBusy:e.uninstallBusy,uninstallDone:e.uninstallDone,uninstallError:e.uninstallError,uninstallConfirmText:e.uninstallConfirmText,onUninstallConfirm:()=>e.handleUninstallConfirm(),onUninstallCancel:()=>e.handleUninstallCancel(),onUninstallConfirmTextChange:f=>e.handleUninstallConfirmTextChange(f),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:f=>e.handleAuthSubmitCode(f),onAuthCodeChange:f=>e.handleAuthCodeChange(f),onSkipToWhatsApp:()=>e.handleSkipToWhatsApp(),onWhatsAppRelink:async f=>{await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await ee(e,!0),e.requestUpdate())},onWhatsAppUnlink:async f=>{await e.handleWhatsAppLogout(f)},onWhatsAppReset:async f=>{await e.handleWhatsAppLogout(f),await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await ee(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await ee(e,!0),await e.handleGatewayHealthCheck()},onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),ee(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:f=>e.handleRemoveWhatsAppAccount(f),workspaces:e.workspaces,workspacesLoading:e.workspacesLoading,workspacesError:e.workspacesError,addingWorkspace:e.addingWorkspace,newWorkspaceName:e.newWorkspaceName,newWorkspacePath:e.newWorkspacePath,workspaceSaving:e.workspaceSaving,workspaceRemoveConfirm:e.workspaceRemoveConfirm,newWorkspacePin:e.newWorkspacePin,onSetNewWorkspacePin:f=>{e.newWorkspacePin=f},onWorkspaceCreate:async(f,b)=>{const k=e.newWorkspacePin;await e.handleWorkspaceCreate(f,b),k.match(/^\d{4,6}$/)&&(await Ak(e,f,k),e.newWorkspacePin="")},onWorkspaceRemove:f=>e.handleWorkspaceRemove(f),onSetAddingWorkspace:f=>{e.addingWorkspace=f},onSetNewWorkspaceName:f=>{e.newWorkspaceName=f},onSetNewWorkspacePath:f=>{e.newWorkspacePath=f},onSetWorkspaceRemoveConfirm:f=>{e.workspaceRemoveConfirm=f},renamingWorkspace:e.renamingWorkspace,renameWorkspaceName:e.renameWorkspaceName,onWorkspaceRenameStart:()=>e.handleWorkspaceRenameStart(),onWorkspaceRenameCancel:()=>e.handleWorkspaceRenameCancel(),onWorkspaceRename:(f,b)=>e.handleWorkspaceRename(f,b),whatsappDmPolicy:(()=>{const f=ue(e),b=f==null?void 0:f.whatsappAccountId,k=b?p.find(A=>A.accountId===b):p[0];return(k==null?void 0:k.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var P;const f=ue(e),b=f==null?void 0:f.whatsappAccountId,k=b?p.find(R=>R.accountId===b):p[0];if(!k)return;const E=k.dmPolicy!=null&&k.dmPolicy!=="disabled"?"disabled":"open",M=E==="open"?{dmPolicy:E,allowFrom:["*"]}:{dmPolicy:E};try{const R=await e.client.request("config.get"),F=R.config,H=(P=F==null?void 0:F.channels)==null?void 0:P.whatsapp,ke=((H==null?void 0:H.accounts)??{})[k.accountId]?{channels:{whatsapp:{accounts:{[k.accountId]:M}}}}:{channels:{whatsapp:M}};await e.client.request("config.patch",{raw:JSON.stringify(ke),baseHash:R.hash,note:`WhatsApp DM policy → ${E}`,skipRestart:!0}),await ee(e,!1)}catch(R){console.error("DM toggle failed:",R)}},whatsappModel:(()=>{var P,R;const f=ue(e);if(!f)return null;const b=f.agents.find(F=>F.id.endsWith("-public")||F.id==="public");if(!b)return null;const k=(P=e.configSnapshot)==null?void 0:P.config,A=(R=k==null?void 0:k.agents)==null?void 0:R.list;if(!Array.isArray(A))return null;const E=A.find(F=>F.id===b.id);if(!(E!=null&&E.model))return null;const M=typeof E.model=="string"?E.model:E.model.primary;return(M==null?void 0:M.trim())||null})(),whatsappModelCatalog:e.chatModelCatalog??[],onWhatsAppModelChange:async f=>{const b=ue(e);if(!b)return;const k=b.agents.find(A=>A.id.endsWith("-public")||A.id==="public");if(k)try{const A=await e.client.request("config.get"),E=A.config,M=(E==null?void 0:E.agents)??{},P=Array.isArray(M.list)?[...M.list]:[],R=P.findIndex(H=>H.id===k.id);if(f)R>=0?P[R]={...P[R],model:f}:P.push({id:k.id,model:f});else if(R>=0){const{model:H,...z}=P[R];Object.keys(z).length<=1?P.splice(R,1):P[R]=z}const F=P.length>0?{agents:{list:P}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(F),baseHash:A.hash,note:`Public agent model → ${f||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Model change failed:",A)}},whatsappThinkingLevel:(()=>{var M,P,R;const f=ue(e);if(!f)return null;const b=f.agents.find(F=>F.id.endsWith("-public")||F.id==="public");if(!b)return null;const k=(M=e.configSnapshot)==null?void 0:M.config,A=(P=k==null?void 0:k.agents)==null?void 0:P.list;if(!Array.isArray(A))return null;const E=A.find(F=>F.id===b.id);return((R=E==null?void 0:E.thinkingLevel)==null?void 0:R.trim())||null})(),onWhatsAppThinkingChange:async f=>{const b=ue(e);if(!b)return;const k=b.agents.find(A=>A.id.endsWith("-public")||A.id==="public");if(k)try{const A=await e.client.request("config.get"),E=A.config,M=(E==null?void 0:E.agents)??{},P=Array.isArray(M.list)?[...M.list]:[],R=P.findIndex(z=>z.id===k.id),F=f==="off"?void 0:f;if(F)R>=0?P[R]={...P[R],thinkingLevel:F}:P.push({id:k.id,thinkingLevel:F});else if(R>=0){const{thinkingLevel:z,...ke}=P[R];Object.keys(ke).length<=1?P.splice(R,1):P[R]=ke}const H=P.length>0?{agents:{list:P}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(H),baseHash:A.hash,note:`Public agent thinking → ${F||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Thinking change failed:",A)}},whatsappGroupPolicy:(()=>{var R,F;const f=(R=e.configSnapshot)==null?void 0:R.config,b=(F=f==null?void 0:f.channels)==null?void 0:F.whatsapp,k=ue(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},M=A?E[A]:void 0;return(M==null?void 0:M.groupPolicy)??(b==null?void 0:b.groupPolicy)??"allowlist"})(),whatsappGroupRequireMention:(()=>{var F,H;const f=(F=e.configSnapshot)==null?void 0:F.config,b=(H=f==null?void 0:f.channels)==null?void 0:H.whatsapp,k=ue(e),A=k==null?void 0:k.whatsappAccountId,E=(b==null?void 0:b.accounts)??{},M=A?E[A]:void 0,R=((M==null?void 0:M.groups)??(b==null?void 0:b.groups)??{})["*"];return(R==null?void 0:R.requireMention)!==!1})(),onWhatsAppGroupToggle:async()=>{var k;const f=ue(e),b=f==null?void 0:f.whatsappAccountId;try{const A=await e.client.request("config.get"),E=A.config,M=((k=E==null?void 0:E.channels)==null?void 0:k.whatsapp)??{},P=M.accounts??{},R=b?P[b]:void 0,F=(R==null?void 0:R.groupPolicy)??M.groupPolicy??"allowlist",H=F==="disabled"||F==="allowlist",z=H?"open":"disabled",ke=H?{"*":{}}:void 0,_e={groupPolicy:z};ke&&(_e.groups=ke);const Ke=R?{channels:{whatsapp:{accounts:{[b]:_e}}}}:{channels:{whatsapp:_e}};await e.client.request("config.patch",{raw:JSON.stringify(Ke),baseHash:A.hash,note:`WhatsApp groups → ${z}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Group toggle failed:",A)}},onWhatsAppGroupMentionChange:async f=>{var A;const b=ue(e),k=b==null?void 0:b.whatsappAccountId;try{const E=await e.client.request("config.get"),M=E.config,R=(((A=M==null?void 0:M.channels)==null?void 0:A.whatsapp)??{}).accounts??{},F=k?R[k]:void 0,H={"*":{requireMention:f}},z=F?{channels:{whatsapp:{accounts:{[k]:{groups:H}}}}}:{channels:{whatsapp:{groups:H}}};await e.client.request("config.patch",{raw:JSON.stringify(z),baseHash:E.hash,note:`WhatsApp group mention → ${f?"when mentioned":"always"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(E){console.error("Group mention change failed:",E)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:g.configured,imessageRunning:g.running,imessageConnected:g.connected,imessageLastError:g.lastError,imessageSelfChatMode:g.selfChatMode,imessageCliPath:g.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:x,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,k=(b==null?void 0:b.bindings)??[],A=ue(e),E=A==null?void 0:A.agents.find(H=>H.id.endsWith("-admin")||H.id==="admin"),M=(E==null?void 0:E.id)??"admin",P=k.filter(H=>{var z;return((z=H.match)==null?void 0:z.channel)!=="imessage"}),R=[{agentId:M,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],F=[...P,...R];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:F}),baseHash:f.hash,note:"Enable iMessage (self-chat) for "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Ue(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await ee(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,A=((b==null?void 0:b.bindings)??[]).filter(E=>{var M;return((M=E.match)==null?void 0:M.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:A}),baseHash:f.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Ue(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageReassign:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,k=(b==null?void 0:b.bindings)??[],A=ue(e),E=A==null?void 0:A.agents.find(F=>F.id.endsWith("-admin")||F.id==="admin"),M=(E==null?void 0:E.id)??"admin",P=k.filter(F=>{var H;return((H=F.match)==null?void 0:H.channel)!=="imessage"}),R=[{agentId:M,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:[...P,...R]}),baseHash:f.hash,note:"Reassign iMessage to "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([ee(e,!0),Ue(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:f=>{var b,k,A,E;if(e.infoModalOpen=f,f==="remote-access"){const M=((b=e.tailscaleStatus)==null?void 0:b.tailnetUrl)??((k=e.tailscaleStatus)!=null&&k.hostname?`https://${e.tailscaleStatus.hostname}`:null);M&&!e.remoteAccessQrDataUrl&&e.client.request("qr.generate",{url:M}).then(P=>{e.remoteAccessQrDataUrl=(P==null?void 0:P.dataUrl)??null}).catch(()=>{})}else if(f==="public-chat"){const M=((A=e.tailscaleStatus)==null?void 0:A.publicUrl)??((E=e.tailscaleStatus)==null?void 0:E.tailnetUrl)??null,P=e.selectedWorkspace??null;if(M&&P){const R=`${M}/public/chat/${encodeURIComponent(P)}`;e.publicChatQrDataUrl||e.client.request("qr.generate",{url:R}).then(F=>{e.publicChatQrDataUrl=(F==null?void 0:F.dataUrl)??null}).catch(()=>{})}}},onInfoModalClose:()=>{e.infoModalOpen=null},remoteAccessQrDataUrl:e.remoteAccessQrDataUrl??null,publicChatQrDataUrl:e.publicChatQrDataUrl??null,publicChatFullUrl:(()=>{var k,A;const f=((k=e.tailscaleStatus)==null?void 0:k.publicUrl)??((A=e.tailscaleStatus)==null?void 0:A.tailnetUrl)??null,b=e.selectedWorkspace??null;return!f||!b?null:`${f}/public/chat/${encodeURIComponent(b)}`})(),isMaster:e.accessState.master,apiKeyProviders:e.apiKeyProviders,apiKeyModalOpen:e.apiKeyModalOpen,apiKeyBusy:e.apiKeyBusy,apiKeyError:e.apiKeyError,apiKeySuccess:e.apiKeySuccess,apiKeySavingProvider:e.apiKeySavingProvider,onApiKeyModalOpen:()=>{e.apiKeyModalOpen=!0,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeyModalClose:()=>{e.apiKeyModalOpen=!1,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeySave:async(f,b)=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await xl(e.client,f,b);const k=`${f} key saved`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}f==="anthropic"&&await e.handleAuthStatusCheck(),setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:"Failed to save key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyRemove:async f=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await ik(e.client,f);const b=`${f} key removed`;e.apiKeySuccess=b,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===b&&(e.apiKeySuccess=null)},2500)}catch(b){e.apiKeyError=b instanceof Error?b.message:"Failed to remove key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyDisable:async(f,b)=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await sk(e.client,f,b);const k=`${f} ${b?"disabled":"enabled"}`;e.apiKeySuccess=k,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await _i(e.client)}catch{}setTimeout(()=>{e.apiKeySuccess===k&&(e.apiKeySuccess=null)},2500)}catch(k){e.apiKeyError=k instanceof Error?k.message:`Failed to ${b?"disable":"enable"} key`,e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},authApiKeyMode:e.authApiKeyMode,authApiKeyInput:e.authApiKeyInput,authApiKeyBusy:e.authApiKeyBusy,authApiKeyError:e.authApiKeyError,onAuthApiKeyToggle:()=>{e.authApiKeyMode=!e.authApiKeyMode,e.authApiKeyError=null},onAuthApiKeyChange:f=>{e.authApiKeyInput=f},onAuthApiKeySubmit:async()=>{const f=e.authApiKeyInput.trim();if(f){e.authApiKeyBusy=!0,e.authApiKeyError=null;try{await xl(e.client,"anthropic",f),await e.handleAuthStatusCheck(),e.authApiKeyMode=!1,e.authApiKeyInput=""}catch(b){e.authApiKeyError=b instanceof Error?b.message:"Failed to save API key"}finally{e.authApiKeyBusy=!1}}},accountHasPin:(()=>{var b;const f=e.selectedWorkspace??((b=e.workspaces[0])==null?void 0:b.name);return f?e.accessState.accounts.some(k=>k.id===f):!1})(),accountPinModalOpen:e.accountPinModalOpen,accountPinBusy:e.accountPinBusy,accountPinError:e.accountPinError,accountPinSuccess:e.accountPinSuccess,onAccountPinModalOpen:()=>{e.accountPinModalOpen=!0,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinModalClose:()=>{e.accountPinModalOpen=!1,e.accountPinError=null,e.accountPinSuccess=null},onAccountPinSave:(f,b)=>{var A;const k=e.selectedWorkspace??((A=e.workspaces[0])==null?void 0:A.name);k&&e.handleAccountPinSave(k,f,b)},publicChatAccountId:e.selectedWorkspace??null,publicChatSettingsOpen:e.publicChatSettingsOpen,onPublicChatSettingsOpen:()=>{e.publicChatSettingsOpen=!0},onPublicChatSettingsClose:()=>{e.publicChatSettingsOpen=!1},publicChatWidgetModalOpen:e.publicChatWidgetModalOpen,onPublicChatWidgetModalOpen:()=>{e.publicChatWidgetModalOpen=!0},onPublicChatWidgetModalClose:()=>{e.publicChatWidgetModalOpen=!1},publicChatEnabled:(()=>{var k;const f=(k=e.configSnapshot)==null?void 0:k.config,b=f==null?void 0:f.publicChat;return(b==null?void 0:b.enabled)===!0})(),publicChatAuthMode:(()=>{var M,P;const f=(M=e.configSnapshot)==null?void 0:M.config,b=f==null?void 0:f.publicChat,k=e.selectedWorkspace??"",A=b==null?void 0:b.accountSettings,E=((P=A==null?void 0:A[k])==null?void 0:P.auth)??(b==null?void 0:b.auth);return E==="verified"||E==="choice"?E:"anonymous"})(),publicChatGreeting:(()=>{var E;const f=(E=e.configSnapshot)==null?void 0:E.config,b=f==null?void 0:f.publicChat,k=b==null?void 0:b.greetings,A=e.selectedWorkspace??"";return(A&&(k==null?void 0:k[A]))??""})(),publicChatGreetingBusy:e.publicChatGreetingBusy,onPublicChatGreetingToggle:async()=>{var b;if(e.publicChatGreetingBusy)return;const f=e.selectedWorkspace??"";if(f){e.publicChatGreetingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=(b=A==null?void 0:A.publicChat)==null?void 0:b.greetings;if(E==null?void 0:E[f]){const P={publicChat:{greetings:{[f]:null}}};await e.client.request("config.patch",{raw:JSON.stringify(P),baseHash:k.hash,note:`Public chat greeting → disabled (${f})`,skipRestart:!0})}else{const P=await e.client.request("public.greeting.generate",{accountId:f});if(P!=null&&P.ok&&P.greeting){const R=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[f]:P.greeting}}}),baseHash:R.hash,note:`Public chat greeting → enabled (${f})`,skipRestart:!0})}}e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting toggle failed:",k)}finally{e.publicChatGreetingBusy=!1}}},onPublicChatGreetingSave:async f=>{const b=e.selectedWorkspace??"";if(b)try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[b]:f}}}),baseHash:k.hash,note:`Public chat greeting text updated (${b})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat greeting save failed:",k)}},onPublicChatGreetingRegenerate:async()=>{if(e.publicChatGreetingBusy)return;const f=e.selectedWorkspace??"";if(f){e.publicChatGreetingBusy=!0;try{const b=await e.client.request("public.greeting.generate",{accountId:f});if(b!=null&&b.ok&&b.greeting){const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{greetings:{[f]:b.greeting}}}),baseHash:k.hash,note:`Public chat greeting regenerated (${f})`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}}catch(b){console.error("Public chat greeting regeneration failed:",b)}finally{e.publicChatGreetingBusy=!1}}},publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var f;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get"),k=b.config,A=((f=k==null?void 0:k.publicChat)==null?void 0:f.enabled)===!0;await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{enabled:!A}}),baseHash:b.hash,note:`Public chat → ${A?"disabled":"enabled"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get"),e.publicChatQrDataUrl=null}catch(b){console.error("Public chat toggle failed:",b)}finally{e.publicChatToggleBusy=!1}}},onPublicChatAuthModeChange:async f=>{if(e.publicChatToggleBusy)return;const b=e.selectedWorkspace??"";if(b){e.publicChatToggleBusy=!0;try{const k=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{accountSettings:{[b]:{auth:f}}}}),baseHash:k.hash,note:`Public chat auth → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(k){console.error("Public chat auth mode change failed:",k)}finally{e.publicChatToggleBusy=!1}}},publicChatEmailFrom:(()=>{var k,A;const f=(k=e.configSnapshot)==null?void 0:k.config,b=(A=f==null?void 0:f.publicChat)==null?void 0:A.email;return(b==null?void 0:b.from)??""})(),publicChatEmailBusy:e.publicChatEmailBusy,publicChatVerifyMethods:(()=>{var M,P;const f=(M=e.configSnapshot)==null?void 0:M.config,b=f==null?void 0:f.publicChat,k=e.selectedWorkspace??"",A=b==null?void 0:b.accountSettings,E=((P=A==null?void 0:A[k])==null?void 0:P.verifyMethods)??(b==null?void 0:b.verifyMethods);return Array.isArray(E)?E:["whatsapp","sms"]})(),onPublicChatEmailSave:async(f,b)=>{if(e.publicChatEmailBusy)return;const k=e.selectedWorkspace??"";if(k){e.publicChatEmailBusy=!0;try{const A=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify({publicChat:{email:{from:f||void 0},accountSettings:{[k]:{verifyMethods:b}}}}),baseHash:A.hash,note:"Update email verification settings for public chat",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Email verification save failed:",A)}finally{e.publicChatEmailBusy=!1}}},brandAccentColor:(()=>{var k;const f=e.selectedWorkspace;return f?((k=Be()[f])==null?void 0:k.accentColor)??"":""})(),brandBackgroundColor:(()=>{var k;const f=e.selectedWorkspace;return f?((k=Be()[f])==null?void 0:k.backgroundColor)??"":""})(),brandHasLogo:(()=>{var k;const f=e.selectedWorkspace;return f?!!((k=Be()[f])!=null&&k.logoUrl):!1})(),brandingBusy:e.brandingBusy,brandingExpanded:e.brandingExpanded,onBrandingToggle:()=>{e.brandingExpanded=!e.brandingExpanded},onBrandAccentColorChange:async f=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,M=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=M.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...M,brand:{...P,accentColor:f}}}}),baseHash:A.hash,note:`Brand accent → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const R=Be();R[b]||(R[b]={}),R[b].accentColor=f,Tn(b)}catch(A){console.error("Brand accent change failed:",A)}finally{e.brandingBusy=!1}}},onBrandBackgroundColorChange:async f=>{var k;const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const A=await e.client.request("config.get"),E=A.config,M=((k=E==null?void 0:E.workspaces)==null?void 0:k[b])??{},P=M.brand??{};await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[b]:{...M,brand:{...P,backgroundColor:f}}}}),baseHash:A.hash,note:`Brand background → ${f}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");const R=Be();R[b]||(R[b]={}),R[b].backgroundColor=f,Tn(b)}catch(A){console.error("Brand background change failed:",A)}finally{e.brandingBusy=!1}}},onBrandLogoUpload:async f=>{const b=e.selectedWorkspace;if(!(!b||e.brandingBusy)){e.brandingBusy=!0;try{const k=await f.arrayBuffer(),A=new Uint8Array(k);let E="";for(let R=0;R<A.length;R++)E+=String.fromCharCode(A[R]);const M=btoa(E);await e.client.request("brand.uploadLogo",{workspace:b,data:M,mimeType:f.type});const P=Be();P[b]||(P[b]={}),P[b].logoUrl=`/brand-logo/${encodeURIComponent(b)}`}catch(k){console.error("Brand logo upload failed:",k)}finally{e.brandingBusy=!1}}},onBrandLogoRemove:async()=>{const f=e.selectedWorkspace;if(!(!f||e.brandingBusy)){e.brandingBusy=!0;try{await e.client.request("brand.removeLogo",{workspace:f});const b=Be();b[f]&&delete b[f].logoUrl}catch(b){console.error("Brand logo remove failed:",b)}finally{e.brandingBusy=!1}}},onBrandReset:async()=>{var b;const f=e.selectedWorkspace;if(!(!f||e.brandingBusy)){e.brandingBusy=!0;try{const k=await e.client.request("config.get"),A=k.config,E=((b=A==null?void 0:A.workspaces)==null?void 0:b[f])??{},{brand:M,...P}=E;await e.client.request("config.patch",{raw:JSON.stringify({workspaces:{[f]:{...P,brand:null}}}),baseHash:k.hash,note:"Brand reset to defaults",skipRestart:!0}),e.configSnapshot=await e.client.request("config.get");try{await e.client.request("brand.removeLogo",{workspace:f})}catch{}const R=Be();delete R[f],Tn(f)}catch(k){console.error("Brand reset failed:",k)}finally{e.brandingBusy=!1}}},tailscaleStatus:e.tailscaleStatus,tailscaleBusy:e.tailscaleBusy,tailscaleAuthUrl:e.tailscaleAuthUrl,tailscaleError:e.tailscaleError,tailscaleFunnelEnableUrl:e.tailscaleFunnelEnableUrl,tailscaleDisableConfirm:e.tailscaleDisableConfirm,tailscaleConnectProgress:e.tailscaleConnectProgress,tailscaleConnectMessage:e.tailscaleConnectMessage,tailscaleConnectSuccess:e.tailscaleConnectSuccess,onTailscaleEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleAuthUrl=null,T();try{const f=await e.client.request("tailscale.enable");f.authUrl?($t&&(clearInterval($t),$t=null),e.tailscaleConnectProgress=100,e.tailscaleConnectMessage="Waiting for authentication...",e.tailscaleAuthUrl=f.authUrl,Mi=setInterval(async()=>{try{const b=await e.client.request("tailscale.status");e.tailscaleStatus=b,e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,b.loggedIn&&(zt(),e.tailscaleAuthUrl=null,e.tailscaleConnectSuccess=!0,e.tailscaleConnectMessage="Connected!",setTimeout(()=>{e.tailscaleConnectSuccess=!1,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1},1500))}catch{}},3e3),Pi=setTimeout(()=>{zt(),e.tailscaleBusy&&(e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)},3e5)):f.alreadyLoggedIn?(zt(),e.tailscaleStatus=await e.client.request("tailscale.status"),e.remoteAccessQrDataUrl=null,e.publicChatQrDataUrl=null,e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1):(zt(),e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1)}catch(f){console.error("Tailscale enable failed:",f),zt(),e.tailscaleError=f.message||"Failed to enable Remote Access",e.tailscaleConnectProgress=0,e.tailscaleConnectMessage="",e.tailscaleBusy=!1}}},onTailscaleErrorDismiss:()=>{e.tailscaleError=null},onTailscaleServeEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null;try{await e.client.request("tailscale.serve.enable"),await S()}catch(f){console.error("Tailscale serve enable failed:",f),e.tailscaleError=f.message||"Failed to enable Remote Access"}finally{e.tailscaleBusy=!1}}},onTailscaleServeDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.serve.disable"),await S()}catch(f){console.error("Tailscale serve disable failed:",f)}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var f;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable"),await S()}catch(b){console.error("Tailscale funnel enable failed:",b);const k=b;(f=k.payload)!=null&&f.enableUrl&&(e.tailscaleFunnelEnableUrl=k.payload.enableUrl),e.tailscaleError=k.message||"Failed to enable Funnel"}finally{e.tailscaleBusy=!1}}},onTailscaleFunnelDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.funnel.disable"),await S()}catch(f){console.error("Tailscale funnel disable failed:",f)}finally{e.tailscaleBusy=!1}}},onTailscaleDisableConfirmToggle:()=>{e.tailscaleDisableConfirm=!e.tailscaleDisableConfirm},wifiModalOpen:e.wifiModalOpen,onWifiModalToggle:()=>{e.wifiModalOpen=!e.wifiModalOpen,e.wifiModalOpen||(e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null)},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{var f;if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const[b,k]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(e.wifiNetworks=b.networks,k.connected&&k.signal==null&&((f=b.networks)!=null&&f.length)){const A=b.networks.find(E=>E.active)||b.networks.find(E=>E.ssid===k.ssid);A&&(k.signal=A.signal)}e.wifiStatus=k}catch(b){console.error("WiFi scan failed:",b),e.wifiError=b.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{var b;if(e.wifiBusy||!e.wifiSelectedSsid)return;const f=e.wifiSelectedSsid;e.wifiBusy=!0,e.wifiError=null;try{const k=await e.client.request("wifi.connect",{ssid:f,password:e.wifiPassword});e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[],e.wifiStatus={available:!0,connected:k.connected,ssid:k.ssid,signal:null,ip:k.ip,savedSsid:k.ssid,autoconnect:!0},e.wifiBusy=!1;try{const[A,E]=await Promise.all([e.client.request("wifi.scan"),e.client.request("wifi.status")]);if(E.connected&&E.signal==null&&((b=A.networks)!=null&&b.length)){const M=A.networks.find(P=>P.active)||A.networks.find(P=>P.ssid===E.ssid);M&&(E.signal=M.signal)}e.wifiStatus=E}catch{}}catch(k){console.error("WiFi connect failed:",k),e.wifiError=k.message||"Failed to connect",e.wifiBusy=!1}},onWifiDisconnect:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.disconnect"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const f=await e.client.request("wifi.status");e.wifiStatus=f}catch(f){console.error("WiFi disconnect failed:",f),e.wifiError=f.message||"Failed to disconnect"}finally{e.wifiBusy=!1}}},onWifiForget:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.forget"),e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="";const f=await e.client.request("wifi.status");e.wifiStatus=f}catch(f){console.error("WiFi forget failed:",f),e.wifiError=f.message||"Failed to forget network"}finally{e.wifiBusy=!1}}},onWifiDismiss:()=>{e.wifiNetworks=[],e.wifiSelectedSsid=null,e.wifiPassword="",e.wifiError=null},onWifiSelectSsid:f=>{e.wifiSelectedSsid=f,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:f=>{e.wifiPassword=f},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:f=>{e.networkPortInput=f,e.networkError=null,e.networkSuccess=null},onNetworkHostnameChange:f=>{e.networkHostnameInput=f,e.networkError=null,e.networkSuccess=null},onNetworkSave:async()=>{if(e.networkBusy)return;e.networkBusy=!0,e.networkError=null,e.networkSuccess=null;const f=e.networkPortInput.trim(),b=Number.parseInt(f,10),k=e.networkHostnameInput.trim();if(!f||!Number.isFinite(b)||b<1024||b>65535){e.networkError="Port must be a number between 1024 and 65535",e.networkBusy=!1;return}const A=b!==e.networkPort,E=k!==e.networkHostname;if(!A&&!E){e.networkBusy=!1;return}try{E&&await e.client.request("network.setHostname",{hostname:k});const M={};A&&(M.gateway={port:b}),E&&(M.discovery={bonjourHostname:k});const P=await e.client.request("config.get");await e.client.request("config.patch",{raw:JSON.stringify(M),baseHash:P.hash,note:[A?`Port → ${b}`:null,E?`Hostname → ${k}`:null].filter(Boolean).join(", "),restartDelayMs:2e3}),e.networkSuccess="Saved — redirecting...";const R=window.location.protocol,F=E?`${k}.local`:window.location.hostname,H=A?b:e.networkPort,z=`${R}//${F}:${H}/setup`;setTimeout(()=>{window.location.href=z},1500)}catch(M){console.error("Network save failed:",M),e.networkError=M.message||"Failed to save network settings",e.networkBusy=!1}},wsProps:Mk(e)})}if(e.filesPage){const d=Lk(e);return ig({connected:e.connected,wsProps:Sn(e),loading:e.filesLoading,tree:e.filesTree,root:e.filesRoot,error:e.filesError,selectedPath:e.filesSelectedPath,selectedPaths:e.filesSelectedPaths,previewContent:e.filesPreviewContent,previewLoading:e.filesPreviewLoading,previewBinary:e.filesPreviewBinary,previewSize:e.filesPreviewSize,expandedDirs:e.filesExpandedDirs,currentDir:e.filesCurrentDir,message:e.filesMessage,uploadBusy:e.filesUploadBusy,reindexBusy:e.filesReindexBusy,memoryStatus:e.filesMemoryStatus,onRefresh:()=>{an(e,d),ls(e,d)},onReindex:()=>yf(e,d),onSelectFile:p=>{e.filesPendingDeletePath=null,cf(e,p,d)},onToggleSelectFile:p=>df(e,p,d),onToggleDir:p=>vf(e,p),onUpload:(p,g)=>hf(e,p,g,d),onNewFolder:(p,g)=>ff(e,p,g,d),onDownload:p=>Zc(e,p,d),onBulkDownload:()=>uf(e,d),onDelete:p=>{e.filesPendingDeletePath=null,gf(e,p,d)},pendingDeletePath:e.filesPendingDeletePath,onArmDelete:p=>{e.filesPendingDeletePath=p||null},onMoveToDir:(p,g)=>pf(e,p,g,d),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:p=>{const g=e.filesSearchAgentId??d;bf(e,p,g)},onSearchAgentChange:p=>{e.filesSearchAgentId=p},onSearchClear:()=>{wf(e)},onSearchQueryChange:p=>{e.filesSearchQuery=p}})}if(e.browserPage)return Yf({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:()=>Qw(e),onStop:()=>Jw(e),onToggleInput:()=>Xw(e),onToggleFullscreen:()=>Zw(e),onCompleteHandoff:()=>Yw(e),onCanvasMouseDown:d=>{const g=d.target.getBoundingClientRect(),S=Bn().translateCoordinates(d.clientX-g.left,d.clientY-g.top);co(e,"mousePressed",S.x,S.y,d.button===2?"right":d.button===1?"middle":"left")},onCanvasMouseUp:d=>{const g=d.target.getBoundingClientRect(),S=Bn().translateCoordinates(d.clientX-g.left,d.clientY-g.top);co(e,"mouseReleased",S.x,S.y)},onCanvasMouseMove:d=>{const p=Bn();if(p.shouldThrottleMouseMove())return;const x=d.target.getBoundingClientRect(),S=p.translateCoordinates(d.clientX-x.left,d.clientY-x.top);co(e,"mouseMoved",S.x,S.y)},onCanvasKeyDown:d=>{let p=0;d.altKey&&(p|=1),d.ctrlKey&&(p|=2),d.metaKey&&(p|=4),d.shiftKey&&(p|=8),uo(e,"keyDown",d.key,{code:d.code,modifiers:p||void 0}),d.key.length===1&&uo(e,"char",d.key,{text:d.key})},onCanvasKeyUp:d=>{uo(e,"keyUp",d.key,{code:d.code})}});if(e.adminsPage){const d=Pk(e),p=Ik(e);return qg({connected:e.connected,wsProps:Sn(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>gs(e,d),onAdd:g=>{ku(e,g,d,p).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:g=>$u(e,g,d,p),onNewPhoneChange:g=>e.handleAdminsNewPhoneChange(g)})}if(e.contactsPage){const d=Rk(e);return Jg({connected:e.connected,wsProps:Sn(e),loading:e.contactsLoading,saving:e.contactsSaving,records:e.contactsRecords,error:e.contactsError,searchQuery:e.contactsSearchQuery,editingId:e.contactsEditingId,showAddForm:e.contactsShowAddForm,newRecordPhone:e.contactsNewPhone,newRecordName:e.contactsNewName,deleteConfirmId:e.contactsDeleteConfirmId,addFieldForId:e.contactsAddFieldForId,addFieldKey:e.contactsAddFieldKey,addFieldValue:e.contactsAddFieldValue,onSearch:p=>e.contactsSearchQuery=p,onSearchSubmit:()=>Lt(e,d),onAdd:(p,g)=>xu(e,p,g,d),onDelete:p=>Su(e,p,d),onSetField:(p,g,x)=>qo(e,p,g,x,d),onDeleteField:(p,g)=>Au(e,p,g,d),onToggleExpand:p=>{e.contactsEditingId=e.contactsEditingId===p?null:p},onShowAddForm:()=>e.contactsShowAddForm=!0,onCancelAddForm:()=>{e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName=""},onNewRecordPhoneChange:p=>e.handleContactsNewPhoneChange(p),onNewRecordNameChange:p=>e.handleContactsNewNameChange(p),onRefresh:()=>Lt(e,d),onDeleteConfirmOpen:p=>e.contactsDeleteConfirmId=p,onDeleteConfirmClose:()=>e.contactsDeleteConfirmId=null,onAddFieldOpen:p=>{e.contactsAddFieldForId=p,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldClose:()=>{e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue=""},onAddFieldKeyChange:p=>e.contactsAddFieldKey=p,onAddFieldValueChange:p=>e.contactsAddFieldValue=p,onAddFieldSubmit:()=>{const p=e.contactsAddFieldForId,g=e.contactsAddFieldKey.trim();!p||!g||(qo(e,p,g,e.contactsAddFieldValue,d),e.contactsAddFieldForId=null,e.contactsAddFieldKey="",e.contactsAddFieldValue="")}})}if(e.chatPage){const d=e.connected?null:"Disconnected from gateway.",p=Pl(e),g=e.chatAvatarUrl??p??null,x=(()=>{var f;const S=(f=e.configSnapshot)==null?void 0:f.config,T=S==null?void 0:S.publicChat;return(T==null?void 0:T.enabled)===!0})();return Qb({connected:e.connected,wsProps:Sn(e),publicChatEnabled:x,publicChatAccountId:e.selectedWorkspace??void 0,sessionKey:e.sessionKey,onSessionKeyChange:S=>{const T=e.selectedWorkspace??"";vo(),Wn(T,e.sessionKey,e.chatMessage),e.sessionKey=S,e.chatMessage=Kn(T,S),e.chatAttachments=[],e.chatStream=null,e.chatInterimText=null,e.chatSuggestions=[],e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:S,lastActiveSessionKey:S}),e.loadAssistantIdentity(),Oe(e),Ao(e)},thinkingLevel:e.chatThinkingLevel,showThinking:e.settings.chatShowThinking??!1,modelProvider:e.chatModelProvider,model:e.chatModel,modelCatalog:e.chatModelCatalog,onModelChange:S=>{const T=Math.max(e.chatMessages.length+10,Fe);ci(e,e.sessionKey,{model:S}).then(()=>{Oe(e,{limit:T})})},onThinkingLevelChange:S=>{const T=Math.max(e.chatMessages.length+10,Fe);ci(e,e.sessionKey,{thinkingLevel:S==="off"?null:S}).then(()=>{Oe(e,{limit:T})})},verboseLevel:e.chatVerboseLevel,fillerEnabled:e.chatFillerEnabled,suggestions:e.chatSuggestions,onSuggestionClick:S=>{e.chatMessage=S,e.chatSuggestions=[],e.handleSendChat()},onVerboseChange:S=>{const T=Math.max(e.chatMessages.length+10,Fe);ci(e,e.sessionKey,{verboseLevel:S==="off"?null:S}).then(()=>{Oe(e,{limit:T})})},onFillerChange:S=>{const T=Math.max(e.chatMessages.length+10,Fe);ci(e,e.sessionKey,{fillerEnabled:S}).then(()=>{Oe(e,{limit:T})})},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:g,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:d,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const S=Math.max(e.chatMessages.length+10,Fe);return Promise.all([Oe(e,{limit:S}),Ao(e)])},onToggleFocusMode:()=>{},onChatScroll:S=>e.handleChatScroll(S),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:S=>{e.chatMessage=S,yr(e.selectedWorkspace??"",e.sessionKey,S)},requestUpdate:()=>e.requestUpdate(),attachments:e.chatAttachments,onAttachmentsChange:S=>e.chatAttachments=S,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:S=>e.removeQueuedMessage(S),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:S=>e.handleOpenSidebar(S),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:S=>e.handleSplitRatioChange(S),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?Bw({connected:e.connected,wsProps:Sn(e),activeTab:e.advancedTab,onTabChange:d=>{e.advancedTab=d,d==="cron"&&e.loadCron(),d==="skills"&&Xe(e,{clearMessages:!0}),d==="logs"&&(e.logsSubTab==="session"?Pn(e,{reset:!0}):Vt(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(r=(a=e.channelsSnapshot)==null?void 0:a.channelMeta)!=null&&r.length?e.channelsSnapshot.channelMeta.map(d=>d.id):((l=e.channelsSnapshot)==null?void 0:l.channelOrder)??[],channelLabels:((c=e.channelsSnapshot)==null?void 0:c.channelLabels)??{},channelMeta:((h=e.channelsSnapshot)==null?void 0:h.channelMeta)??[],agentIds:(()=>{var p;const d=ue(e);return((p=d==null?void 0:d.agents)==null?void 0:p.map(g=>g.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:d=>{e.cronDetailJobId=d.id,wo(e,d.id)},onDetailClose:()=>{e.cronDetailJobId=null},onEdit:d=>{e.cronForm=hh(d),e.cronEditJobId=d.id,e.cronDetailJobId=null},onEditSave:()=>{const d=e.cronEditJobId;d&&fh(e,d).then(()=>{e.cronEditJobId=null})},onFormChange:d=>e.cronForm={...e.cronForm,...d},onRefresh:()=>e.loadCron(),onAdd:()=>{lh(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(d,p)=>ch(e,d,p),onRun:d=>dh(e,d),onRemove:d=>{e.cronPendingDeleteId=null,ph(e,d)},pendingDeleteId:e.cronPendingDeleteId,onArmDelete:d=>{e.cronPendingDeleteId=d||null},onLoadRuns:d=>wo(e,d),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:d=>e.skillsFilter=d,onTypeFilterChange:d=>e.skillsTypeFilter=d,onRefresh:()=>Xe(e,{clearMessages:!0}),onToggle:(d,p)=>Pc(e,d,p),onEdit:(d,p)=>Mc(e,d,p),onSaveKey:d=>Ic(e,d),onInstall:(d,p,g)=>Lc(e,d,p,g),onViewDetail:d=>Rc(e,d),onDetailClose:()=>Dc(e),onDetailTab:d=>Bc(e,d),onAddOpen:()=>Nc(e),onAddClose:()=>Oc(e),onImportDraft:d=>Fc(e,d),onInstallDraft:d=>Uc(e,d),onDeleteDraft:d=>Wc(e,d),onAddSave:()=>la(e),onAddFormUpdate:(d,p)=>{e.skillAddForm={...e.skillAddForm,[d]:p}},onDelete:d=>jc(e,d),onEditSkill:d=>Kc(e,d),onEditDetail:d=>zc(e,d),onRefUpdate:(d,p)=>qc(e,d,p),onEditTab:d=>Hc(e,d)},logsProps:{logsSubTab:e.logsSubTab,onSubTabChange:d=>{e.logsSubTab=d,d==="session"?Pn(e,{reset:!0}):Vt(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:d=>e.sessionLogsFilterText=d,onTypeToggle:(d,p)=>{const g=e;g.sessionLogsTypeFilters={...g.sessionLogsTypeFilters,[d]:p}},onAgentToggle:(d,p)=>{const g=e;g.sessionLogsAgentFilters={...g.sessionLogsAgentFilters,[d]:p}},onToggleAutoFollow:d=>e.sessionLogsAutoFollow=d,onToggleChips:()=>{const d=e;d.sessionLogsChipsExpanded=!d.sessionLogsChipsExpanded},onToggleExpand:d=>{const p=e,g=new Set(p.sessionLogsExpandedIds);g.has(d)?g.delete(d):g.add(d),p.sessionLogsExpandedIds=g,p.requestUpdate()},onRefresh:()=>{Pn(e,{reset:!0})},onExport:(d,p)=>e.exportSessionLogs(d,p),onScroll:d=>e.handleSessionLogsScroll(d)},loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,chipsExpanded:e.logsChipsExpanded,truncated:e.logsTruncated,onFilterTextChange:d=>e.logsFilterText=d,onLevelToggle:(d,p)=>{e.logsLevelFilters={...e.logsLevelFilters,[d]:p}},onToggleAutoFollow:d=>e.logsAutoFollow=d,onToggleChips:()=>{const d=e;d.logsChipsExpanded=!d.logsChipsExpanded},onRefresh:()=>Vt(e,{reset:!0}),onExport:(d,p)=>e.exportSessionLogs(d,p),onScroll:d=>e.handleLogsScroll(d)}}):(window.location.replace("/chat"),u``)}function Wk(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 Il(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function Kk(e,t,n){return u`
4506
4520
  <div class="audit-modal-overlay" @click=${s=>{s.target.classList.contains("audit-modal-overlay")&&n()}}>
4507
4521
  <div class="audit-modal-card">
4508
4522
  <div class="audit-modal-header">
@@ -4518,11 +4532,11 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4518
4532
  ${e.map(s=>u`
4519
4533
  <div class="audit-modal-entry">
4520
4534
  <div class="audit-modal-entry-path">
4521
- <span class="audit-modal-folder audit-modal-folder--${Pl(s.path)}">${Pl(s.path)}</span>
4535
+ <span class="audit-modal-folder audit-modal-folder--${Il(s.path)}">${Il(s.path)}</span>
4522
4536
  <a href="/files" class="audit-modal-path-link">${s.path}</a>
4523
4537
  </div>
4524
4538
  <div class="audit-modal-entry-meta">
4525
- ${Uk(s.timestamp)}
4539
+ ${Wk(s.timestamp)}
4526
4540
  <span class="audit-modal-agent">${s.agentId}</span>
4527
4541
  </div>
4528
4542
  </div>
@@ -4534,7 +4548,7 @@ ${a.text}`:r.join(", "):a.text;t.push({kind:"message",key:`queue:${a.id}`,messag
4534
4548
  `}
4535
4549
  </div>
4536
4550
  </div>
4537
- `}const Kk={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},zk={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 qk(e){e.basePath=_f();const t=Ye();if(Kl(t.accentColor),zl(t.backgroundColor),window.scrollTo(0,0),$f(e),e.publicChat){const n=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__,i=(n==null?void 0:n.accountId)??"",s=i?i.charAt(0).toUpperCase()+i.slice(1):"Assistant";document.title=`Chat with ${s}`,De(e);return}if(e.setup){document.title=`${t.name} Setup`,De(e);return}if(e.filesPage){document.title=`${t.name} Files`,Sf(e),De(e);return}if(e.browserPage){document.title=`${t.name} Browser`,De(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,De(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,De(e);return}if(e.chatPage){document.title=`${t.name} Chat`,De(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,De(e);return}Lf(e,!0),Mf(e),Pf(e),window.addEventListener("popstate",e.popStateHandler),Cf(e),De(e),wf(e),e.tab==="logs"&&(e.logsSubTab==="session"?ua(e):ca(e)),e.tab==="debug"&&ha(e)}function Hk(e){ih(e)}function jk(e){var t;window.removeEventListener("popstate",e.popStateHandler),kf(e),da(e),pa(e),fa(e),xf(e),Af(e),If(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function Gk(e,t){if(!e.publicChat){if(e.filesPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleFilesLoad&&e.handleFilesLoad(),e.adminsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdminsLoad&&e.handleAdminsLoad(),e.contactsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleContactsLoad&&e.handleContactsLoad(),e.chatPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleChatLoad&&e.handleChatLoad(),e.advancedPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdvancedLoad&&e.handleAdvancedLoad(),e.setup&&e.connected){const n=t.has("connected")&&t.get("connected")===!1;n&&e.handleLicenseStatusCheck&&e.licenseValid===null&&!e.licenseBusy&&e.handleLicenseStatusCheck(),n&&e.handleUpdateCheck&&e.handleUpdateCheck();const i=t.has("setupStep")&&e.setupStep==="auth";(n||i)&&e.setupStep==="auth"&&e.handleAuthStatusCheck&&e.authConnected===null&&!e.authBusy&&e.handleAuthStatusCheck(),e.setupStep==="whatsapp"&&t.has("setupStep")&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(o=>{e.channelsSnapshot=o,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1})),t.has("whatsappLoginConnected")&&e.whatsappLoginConnected===!0&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(s=>{e.channelsSnapshot=s,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1}))}if(e.tab==="chat"&&!e.advancedPage&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),i=t.has("chatLoading")&&t.get("chatLoading")===!0&&e.chatLoading===!1;nn(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&nc(e,t.has("tab")||t.has("logsAutoFollow"))}}function Vk(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 Qk(e,t,n){await Xo(e,t,n),await ee(e,!0)}async function Jk(e,t){await rc(e,t),await ee(e,!0)}async function Yk(e,t){await lc(e,t),await ee(e,!0)}async function Xk(e,t){await cc(e,t)}async function Zk(e,t){await dc(e,t)}async function e0(e){await ah(e),await Ue(e),await ee(e,!0)}async function t0(e){await Ue(e),await ee(e,!0)}function n0(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 Au(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 Cu(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function i0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Vk(n??void 0)}function s0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function o0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function a0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function r0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Au(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(Cu(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:n0(s==null?void 0:s.details)};return}if(!s.persisted){e.nostrProfileFormState={...t,saving:!1,error:"Profile publish failed on all relays.",success:null};return}e.nostrProfileFormState={...t,saving:!1,error:null,success:"Profile published to relays.",fieldErrors:{},original:{...t.values}},await ee(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function l0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Au(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(Cu(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 ee(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function c0(e){if(e.client){e.authBusy=!0,e.authMessage=null;try{const t=await e.client.request("auth.status",{});e.authConnected=t.connected,e.authExpiresIn=t.expiresIn??null,e.authMessage=t.message??null,t.connected&&(e.setupStep="whatsapp")}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to check auth status"}finally{e.authBusy=!1}}}async function d0(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 u0(e,t){if(e.client){e.authBusy=!0,e.authMessage="Verifying code...";try{await e.client.request("auth.oauth.code",{code:t});const n=await e.client.request("auth.oauth.wait",{timeoutMs:3e4});n.connected?(e.authConnected=!0,e.authMessage=n.message??"Connected to Claude!",e.authUrl=null,e.authCodeInput=""):e.authMessage=n.message??"Still waiting for authorization..."}catch(n){e.authConnected=!1,e.authMessage=n instanceof Error?n.message:"Verification failed"}finally{e.authBusy=!1}}}function p0(e,t){e.authCodeInput=t}function h0(e){e.setupStep="whatsapp"}async function f0(e){if(e.client){e.licenseBusy=!0,e.licenseMessage=null;try{const t=await e.client.request("license.status",{});e.licenseDeviceId=t.deviceId??null,e.licenseStoredKey=t.key??null,t.licensed?(e.licenseValid=!0,e.licenseTier=t.tier??null,e.setupStep="auth"):(e.licenseValid=null,e.setupStep="license")}catch(t){const n=t instanceof Error?t.message:String(t);n.includes("unknown method")?(e.licenseValid=!0,e.setupStep="auth"):(e.licenseValid=null,e.licenseMessage=n,e.setupStep="license")}finally{e.licenseBusy=!1}}}async function g0(e){if(e.client&&e.licenseKey.trim()){e.licenseBusy=!0,e.licenseMessage=null,e.licenseValid=null;try{const t=await e.client.request("license.activate",{key:e.licenseKey.trim()});t.valid?(e.licenseValid=!0,e.licenseMessage=t.message??"License activated",e.licenseTier=t.tier??null,setTimeout(()=>{e.setupStep="auth"},1500)):(e.licenseValid=!1,e.licenseMessage=t.message??"Invalid license key")}catch(t){e.licenseValid=!1,e.licenseMessage=t instanceof Error?t.message:"Activation failed"}finally{e.licenseBusy=!1}}}async function m0(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 y0(e,t){e.licenseKey=t}async function v0(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 b0(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 w0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,m=(e,t,n,i)=>{for(var s=i>1?void 0:i?k0(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&&w0(t,n,s),s};const fo=up();function $0(){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 x0(){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 S0(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function A0(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function C0(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function E0(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function T0(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function _0(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let g=class extends Gt{constructor(){super(...arguments),this.settings=Ps(),this.password="",this.tab="chat",this.onboarding=$0(),this.setup=x0(),this.filesPage=S0(),this.browserPage=A0(),this.adminsPage=C0(),this.contactsPage=E0(),this.chatPage=T0(),this.advancedPage=_0(),this.advancedTab="cron",this.publicChat=!!window.__TASKMASTER_PUBLIC_CHAT__,this.publicChatConfig=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__??{},this.publicChatSessionKey=null,this.publicChatAuthenticated=!1,this.publicChatAuthStep="idle",this.connected=!1,this.accessState=mu,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=fo.name,this.assistantAvatar=fo.avatar,this.assistantAgentId=fo.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.chatThinkingLevel=null,this.chatModelProvider=null,this.chatModel=null,this.chatModelCatalog=[],this.chatVerboseLevel=null,this.chatFillerEnabled=null,this.chatQueue=[],this.chatAttachments=[],this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.splitRatio=this.settings.splitRatio,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.configLoading=!1,this.configRaw=`{
4551
+ `}const zk={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},qk={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 Hk(e){e.basePath=Mf();const t=Ye();zl(t.accentColor),ql(t.backgroundColor);const n=document.querySelector('link[rel="icon"]');if(n&&(n.href=t.iconUrl),window.scrollTo(0,0),xf(e),e.publicChat){const i=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__,s=(i==null?void 0:i.accountId)??"",o=s?s.charAt(0).toUpperCase()+s.slice(1):"Assistant";document.title=`Chat with ${o}`,De(e);return}if(e.setup){document.title=`${t.name} Setup`,De(e);return}if(e.filesPage){document.title=`${t.name} Files`,Af(e),De(e);return}if(e.browserPage){document.title=`${t.name} Browser`,De(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,De(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,De(e);return}if(e.chatPage){document.title=`${t.name} Chat`,De(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,De(e);return}Rf(e,!0),Pf(e),If(e),window.addEventListener("popstate",e.popStateHandler),Ef(e),De(e),kf(e),e.tab==="logs"&&(e.logsSubTab==="session"?pa(e):da(e)),e.tab==="debug"&&fa(e)}function jk(e){sh(e)}function Gk(e){var t;window.removeEventListener("popstate",e.popStateHandler),$f(e),ua(e),ha(e),ga(e),Sf(e),Cf(e),Lf(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function Vk(e,t){if(!e.publicChat){if(e.filesPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleFilesLoad&&e.handleFilesLoad(),e.adminsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdminsLoad&&e.handleAdminsLoad(),e.contactsPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleContactsLoad&&e.handleContactsLoad(),e.chatPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleChatLoad&&e.handleChatLoad(),e.advancedPage&&e.connected&&t.has("connected")&&t.get("connected")===!1&&e.handleAdvancedLoad&&e.handleAdvancedLoad(),e.setup&&e.connected){const n=t.has("connected")&&t.get("connected")===!1;n&&e.handleLicenseStatusCheck&&e.licenseValid===null&&!e.licenseBusy&&e.handleLicenseStatusCheck(),n&&e.handleUpdateCheck&&e.handleUpdateCheck();const i=t.has("setupStep")&&e.setupStep==="auth";(n||i)&&e.setupStep==="auth"&&e.handleAuthStatusCheck&&e.authConnected===null&&!e.authBusy&&e.handleAuthStatusCheck(),e.setupStep==="whatsapp"&&t.has("setupStep")&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(o=>{e.channelsSnapshot=o,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1})),t.has("whatsappLoginConnected")&&e.whatsappLoginConnected===!0&&e.client&&!e.channelsLoading&&(e.channelsLoading=!0,e.client.request("channels.status",{probe:!0,timeoutMs:8e3}).then(s=>{e.channelsSnapshot=s,e.channelsLoading=!1}).catch(()=>{e.channelsLoading=!1}))}if(e.tab==="chat"&&!e.advancedPage&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),i=t.has("chatLoading")&&t.get("chatLoading")===!0&&e.chatLoading===!1;nn(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&ic(e,t.has("tab")||t.has("logsAutoFollow"))}}function Qk(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 Jk(e,t,n){await Zo(e,t,n),await ee(e,!0)}async function Yk(e,t){await lc(e,t),await ee(e,!0)}async function Xk(e,t){await cc(e,t),await ee(e,!0)}async function Zk(e,t){await dc(e,t)}async function e0(e,t){await uc(e,t)}async function t0(e){await rh(e),await Ue(e),await ee(e,!0)}async function n0(e){await Ue(e),await ee(e,!0)}function i0(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 Cu(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 Eu(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function s0(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Qk(n??void 0)}function o0(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function a0(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function r0(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function l0(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Cu(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(Eu(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:i0(s==null?void 0:s.details)};return}if(!s.persisted){e.nostrProfileFormState={...t,saving:!1,error:"Profile publish failed on all relays.",success:null};return}e.nostrProfileFormState={...t,saving:!1,error:null,success:"Profile published to relays.",fieldErrors:{},original:{...t.values}},await ee(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function c0(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Cu(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(Eu(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 ee(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function d0(e){if(e.client){e.authBusy=!0,e.authMessage=null;try{const t=await e.client.request("auth.status",{});e.authConnected=t.connected,e.authExpiresIn=t.expiresIn??null,e.authMessage=t.message??null,t.connected&&(e.setupStep="whatsapp")}catch(t){e.authConnected=!1,e.authMessage=t instanceof Error?t.message:"Failed to check auth status"}finally{e.authBusy=!1}}}async function u0(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 p0(e,t){if(e.client){e.authBusy=!0,e.authMessage="Verifying code...";try{await e.client.request("auth.oauth.code",{code:t});const n=await e.client.request("auth.oauth.wait",{timeoutMs:3e4});n.connected?(e.authConnected=!0,e.authMessage=n.message??"Connected to Claude!",e.authUrl=null,e.authCodeInput=""):e.authMessage=n.message??"Still waiting for authorization..."}catch(n){e.authConnected=!1,e.authMessage=n instanceof Error?n.message:"Verification failed"}finally{e.authBusy=!1}}}function h0(e,t){e.authCodeInput=t}function f0(e){e.setupStep="whatsapp"}async function g0(e){if(e.client){e.licenseBusy=!0,e.licenseMessage=null;try{const t=await e.client.request("license.status",{});e.licenseDeviceId=t.deviceId??null,e.licenseStoredKey=t.key??null,t.licensed?(e.licenseValid=!0,e.licenseTier=t.tier??null,e.setupStep="auth"):(e.licenseValid=null,e.setupStep="license")}catch(t){const n=t instanceof Error?t.message:String(t);n.includes("unknown method")?(e.licenseValid=!0,e.setupStep="auth"):(e.licenseValid=null,e.licenseMessage=n,e.setupStep="license")}finally{e.licenseBusy=!1}}}async function m0(e){if(e.client&&e.licenseKey.trim()){e.licenseBusy=!0,e.licenseMessage=null,e.licenseValid=null;try{const t=await e.client.request("license.activate",{key:e.licenseKey.trim()});t.valid?(e.licenseValid=!0,e.licenseMessage=t.message??"License activated",e.licenseTier=t.tier??null,setTimeout(()=>{e.setupStep="auth"},1500)):(e.licenseValid=!1,e.licenseMessage=t.message??"Invalid license key")}catch(t){e.licenseValid=!1,e.licenseMessage=t instanceof Error?t.message:"Activation failed"}finally{e.licenseBusy=!1}}}async function y0(e){if(e.client){e.licenseBusy=!0;try{await e.client.request("license.remove",{}),e.licenseValid=null,e.licenseKey="",e.licenseTier=null,e.licenseMessage=null,e.setupStep="license"}catch(t){e.licenseMessage=t instanceof Error?t.message:"Failed to remove license"}finally{e.licenseBusy=!1}}}function v0(e,t){e.licenseKey=t}async function b0(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 w0(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 k0=Object.defineProperty,$0=Object.getOwnPropertyDescriptor,y=(e,t,n,i)=>{for(var s=i>1?void 0:i?$0(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&&k0(t,n,s),s};const go=pp();function x0(){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 S0(){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 A0(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function C0(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function E0(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function T0(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function _0(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function M0(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let m=class extends Gt{constructor(){super(...arguments),this.settings=Is(),this.password="",this.tab="chat",this.onboarding=x0(),this.setup=S0(),this.filesPage=A0(),this.browserPage=C0(),this.adminsPage=E0(),this.contactsPage=T0(),this.chatPage=_0(),this.advancedPage=M0(),this.advancedTab="cron",this.publicChat=!!window.__TASKMASTER_PUBLIC_CHAT__,this.publicChatConfig=window.__TASKMASTER_PUBLIC_CHAT_CONFIG__??{},this.publicChatSessionKey=null,this.publicChatAuthenticated=!1,this.publicChatAuthStep="idle",this.connected=!1,this.accessState=yu,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=go.name,this.assistantAvatar=go.avatar,this.assistantAgentId=go.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.chatThinkingLevel=null,this.chatModelProvider=null,this.chatModel=null,this.chatModelCatalog=[],this.chatVerboseLevel=null,this.chatFillerEnabled=null,this.chatQueue=[],this.chatAttachments=[],this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.splitRatio=this.settings.splitRatio,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.configLoading=!1,this.configRaw=`{
4538
4552
  }
4539
- `,this.configRawOriginal="",this.configValid=null,this.configIssues=[],this.configSaving=!1,this.configApplying=!1,this.updateRunning=!1,this.applySessionKey=this.settings.lastActiveSessionKey,this.configSnapshot=null,this.configSchema=null,this.configSchemaVersion=null,this.configSchemaLoading=!1,this.configUiHints={},this.configForm=null,this.configFormOriginal=null,this.configFormDirty=!1,this.configFormMode="form",this.configSearchQuery="",this.configActiveSection=null,this.configActiveSubsection=null,this.channelsLoading=!1,this.channelsSnapshot=null,this.channelsError=null,this.channelsLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.whatsappActiveQrAccountId=null,this.whatsappPairedPhone=null,this.addingWhatsAppAccount=!1,this.newWhatsAppAccountName="",this.whatsappAccountError=null,this.whatsappAccountSaving=!1,this.whatsappSettingsOpen=!1,this.publicChatToggleBusy=!1,this.publicChatGreetingBusy=!1,this.publicChatEmailBusy=!1,this.publicChatSettingsOpen=!1,this.publicChatWidgetModalOpen=!1,this.brandingBusy=!1,this.brandingExpanded=!1,this.tailscaleStatus=null,this.tailscaleBusy=!1,this.tailscaleAuthUrl=null,this.tailscaleError=null,this.tailscaleFunnelEnableUrl=null,this.tailscaleDisableConfirm=!1,this.tailscaleConnectProgress=0,this.tailscaleConnectMessage="",this.tailscaleConnectSuccess=!1,this.wifiStatus=null,this.wifiNetworks=[],this.wifiBusy=!1,this.wifiError=null,this.wifiPassword="",this.wifiSelectedSsid=null,this.networkPort=null,this.networkHostname="",this.networkPortInput="",this.networkHostnameInput="",this.networkModalOpen=!1,this.networkBusy=!1,this.networkError=null,this.networkSuccess=null,this.wifiModalOpen=!1,this.licenseKey="",this.licenseBusy=!1,this.licenseValid=null,this.licenseMessage=null,this.licenseTier=null,this.licenseDeviceId=null,this.licenseStoredKey=null,this.licenseRemoveConfirm=!1,this.authConnected=null,this.authBusy=!1,this.authMessage=null,this.authUrl=null,this.authCodeInput="",this.authExpiresIn=null,this.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={...zk},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.browserScreencastActive=!1,this.browserScreencastFrame=null,this.browserScreencastMetadata=null,this.browserHandoffPending=!1,this.browserHandoffReason=null,this.browserHandoffId=null,this.browserInputMode=!1,this.browserFullscreen=!1,this.browserLoading=!1,this.browserError=null,this.filesLoading=!1,this.filesTree=[],this.filesRoot="",this.filesError=null,this.filesSelectedPath=null,this.filesSelectedPaths=new Set,this.filesPreviewContent=null,this.filesPreviewLoading=!1,this.filesPreviewBinary=!1,this.filesPreviewSize=null,this.filesExpandedDirs=new Set,this.filesCurrentDir=".",this.filesPendingDeletePath=null,this.filesMessage=null,this.filesUploadBusy=!1,this.filesReindexBusy=!1,this.filesMemoryStatus=null,this.embeddingDownloading=!1,this.embeddingPollTimer=null,this.filesSearchQuery="",this.filesSearchResults=null,this.filesSearchLoading=!1,this.filesSearchAgentId=null,this.filesResolvedAgentId=void 0,this.auditEntries=[],this.auditLoading=!1,this.auditModalOpen=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillsTypeFilter="all",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillDetail=null,this.skillDetailTab="",this.skillAddModal=!1,this.skillAddForm={name:"",skillContent:"",references:[]},this.skillAddFormSource="draft",this.skillEditTab="SKILL.md",this.skillDrafts=[],this.adminsLoading=!1,this.adminPhones=[],this.adminsError=null,this.adminsSaving=!1,this.adminsNewPhone="",this.contactsLoading=!1,this.contactsSaving=!1,this.contactsRecords=[],this.contactsError=null,this.contactsSearchQuery="",this.contactsEditingId=null,this.contactsShowAddForm=!1,this.contactsNewPhone="",this.contactsNewName="",this.contactsDeleteConfirmId=null,this.contactsAddFieldForId=null,this.contactsAddFieldKey="",this.contactsAddFieldValue="",this.imessageEnableConfirm=!1,this.imessageEnabling=!1,this.infoModalOpen=null,this.remoteAccessQrDataUrl=null,this.publicChatQrDataUrl=null,this.workspaces=[],this.workspacesLoading=!1,this.workspacesError=null,this.selectedWorkspace=null,this.addingWorkspace=!1,this.newWorkspaceName="",this.newWorkspacePath="",this.newWorkspacePin="",this.accountPinModalOpen=!1,this.accountPinBusy=!1,this.accountPinError=null,this.accountPinSuccess=null,this.apiKeyProviders=[],this.apiKeyModalOpen=!1,this.apiKeyBusy=!1,this.apiKeyError=null,this.apiKeySuccess=null,this.apiKeySavingProvider=null,this.authApiKeyMode=!1,this.authApiKeyInput="",this.authApiKeyBusy=!1,this.authApiKeyError=null,this.pinChanging=null,this.pinChangeBusy=!1,this.pinChangeError=null,this.loginChangePinMode=!1,this.changePinBusy=!1,this.changePinError=null,this.changePinSuccess=null,this.workspaceSaving=!1,this.workspaceRemoveConfirm=null,this.renamingWorkspace=!1,this.renameWorkspaceName="",this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...Kk},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.logsSubTab="session",this.logsChipsExpanded=!1,this.sessionLogsLoading=!1,this.sessionLogsError=null,this.sessionLogsEntries=[],this.sessionLogsFilterText="",this.sessionLogsTypeFilters={user:!0,assistant:!0,tool:!0,tool_call:!0,tool_result:!0,thinking:!0,error:!0,system:!0},this.sessionLogsAgentFilters={},this.sessionLogsAgents=[],this.sessionLogsAutoFollow=!0,this.sessionLogsChipsExpanded=!1,this.sessionLogsExpandedIds=new Set,this.sessionLogsCursors={},this.sessionLogsLastFetchAt=null,this.sessionLogsAtBottom=!0,this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.chatUserNearBottom=!0,this.onLoadOlder=()=>this.handleLoadOlderChat(),this.nodesPollInterval=null,this.logsPollInterval=null,this.sessionLogsPollInterval=null,this.debugPollInterval=null,this.auditPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.basePath="",this.popStateHandler=()=>Rf(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._beforeUnloadHandler=()=>{var t;yo();const e=this.selectedWorkspace??((t=this.publicChatConfig)==null?void 0:t.accountId)??"";e&&Un(e,this.sessionKey,this.chatMessage)}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),qk(this),window.addEventListener("beforeunload",this._beforeUnloadHandler)}firstUpdated(){Hk(this)}disconnectedCallback(){window.removeEventListener("beforeunload",this._beforeUnloadHandler),this.stopEmbeddingPoll(),jk(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){Gk(this,e)}connect(){De(this)}handleChatScroll(e){Jp(this,e)}handleLogsScroll(e){Xp(this,e)}handleSessionLogsScroll(e){Zp(this,e)}exportLogs(e,t){th(e,t)}exportSessionLogs(e,t){nh(e,t)}resetToolStream(){Yo(this)}resetChatScroll(){eh(this)}async loadAssistantIdentity(){await Ko(this)}applySettings(e){at(this,e)}setTab(e){Ef(this,e)}setTheme(e,t){Tf(this,e,t)}async loadOverview(){await nd(this)}async loadCron(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.cronForm={...this.cronForm,accountId:(e==null?void 0:e.whatsappAccountId)??void 0},await ga(this)}async handleAbortChat(){await sd(this)}removeQueuedMessage(e){Of(this,e)}async handleSendChat(e,t){await Ff(this,e,t)}async handleWhatsAppStart(e,t){await Qk(this,e,t)}async handleWhatsAppWait(e){await Jk(this,e)}async handleWhatsAppLogout(e){await Yk(this,e)}async handleAddWhatsAppAccount(e){await Xk(this,e)}async handleRemoveWhatsAppAccount(e){await Zk(this,e)}async handleAccessCheck(){await _l(this)}async handlePinSubmit(e,t){await $k(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await xk(this,e)}async handleLogout(){await Ak(this)}toggleChangePinMode(){this.loginChangePinMode=!this.loginChangePinMode,this.changePinError=null,this.changePinSuccess=null}async handleChangePin(e,t,n){if(this.client){this.changePinBusy=!0,this.changePinError=null,this.changePinSuccess=null;try{const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.changePinError=i.message??"Incorrect current PIN",this.changePinBusy=!1;return}e==="__master__"?await this.client.request("access.setMasterPin",{pin:n}):await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.changePinSuccess="PIN changed successfully",this.changePinBusy=!1,setTimeout(()=>{this.loginChangePinMode=!1,this.changePinSuccess=null},2e3)}catch{this.changePinError="Failed to change PIN",this.changePinBusy=!1}}}async handleAccountPinSave(e,t,n){if(this.client){this.accountPinBusy=!0,this.accountPinError=null,this.accountPinSuccess=null;try{if(t!==null){const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.accountPinError=i.message??"Incorrect current PIN",this.accountPinBusy=!1;return}}await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.accountPinSuccess="PIN saved",this.accountPinBusy=!1,await _l(this),setTimeout(()=>{this.accountPinModalOpen=!1,this.accountPinSuccess=null,this.accountPinError=null},1500)}catch{this.accountPinError="Failed to save PIN",this.accountPinBusy=!1}}}async handleLicenseStatusCheck(){await f0(this)}async handleLicenseActivate(){await g0(this)}async handleLicenseRemove(){await m0(this)}handleLicenseKeyChange(e){y0(this,e)}async handleAuthStatusCheck(){await c0(this)}async handleAuthStart(){await d0(this)}async handleAuthSubmitCode(e){await u0(this,e)}handleAuthCodeChange(e){p0(this,e)}handleSkipToWhatsApp(){h0(this)}async handleGatewayHealthCheck(){await v0(this)}async handleGatewayRestart(){await b0(this)}async handleUpdateCheck(){await hu(this)}async handleUpdateRun(){await sk(this)}handleUpdateDismissResult(){rk(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 le(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>_r);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){le(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>_r);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await Jc(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,an(this,t),rs(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();le(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>Ek);return{loadAdmins:t}},void 0,import.meta.url).then(({loadAdmins:t})=>{t(this,e)})}resolveAdminAgentId(){const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(n=>n.id.endsWith("-admin")||n.id==="admin");return t==null?void 0:t.id}resolveFilesAgentId(){var n;const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return(t==null?void 0:t.id)??((n=e.agents[0])==null?void 0:n.id)}handleChatLoad(){const e=this.resolveAdminAgentId();if(e){const t=`agent:${e}:main`;t!==this.sessionKey&&(this.sessionKey=t,this.chatMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.resetChatScroll(),this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity())}le(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>Bi);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this).then(()=>{nn(this,!0)})})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=Yp(this),{loadOlderChatHistory:t}=await le(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>Bi);return{loadOlderChatHistory:i}},void 0,import.meta.url);await t(this)&&e&&(await this.updateComplete,e())}handleAdvancedLoad(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.sessionLogsEntries=[],this.sessionLogsCursors={},this.sessionLogsAgents=[],this.advancedTab==="cron"&&this.loadCron(),this.advancedTab==="logs"&&(this.logsSubTab==="session"?le(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>Qc);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):le(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>bh);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&le(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>Zh);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await e0(this)}async handleChannelConfigReload(){await t0(this)}handleNostrProfileEdit(e,t){i0(this,e,t)}handleNostrProfileCancel(){s0(this)}handleNostrProfileFieldChange(e,t){o0(this,e,t)}async handleNostrProfileSave(){await r0(this)}async handleNostrProfileImport(){await l0(this)}handleNostrProfileToggleAdvanced(){a0(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;le(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>Tk);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 le(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>wi);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await le(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>wi);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await le(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>fh);return{loadChannels:s}},void 0,import.meta.url);await n(this,{name:e,workspacePath:t,onCreated:s=>{if(!s.whatsappAccountId)return;const o=s.whatsappAccountId;this.handleWorkspaceSelect(e),setTimeout(async()=>{try{await i(this,!0),await this.handleWhatsAppStart(!0,o),this.whatsappLoginQrDataUrl&&(await this.handleWhatsAppWait(o),await i(this,!0),await this.handleWorkspacesLoad())}catch{}this.requestUpdate()},3e3)}})}async handleWorkspaceRemove(e){const{removeWorkspace:t}=await le(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>wi);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 le(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>wi);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){yo(),this.selectedWorkspace&&Un(this.selectedWorkspace,this.sessionKey,this.chatMessage),this.selectedWorkspace=e,this.publicChatQrDataUrl=null,localStorage.setItem("taskmaster-selected-workspace",e),Tn(e),gr(e),this.settings=Ps(),this.chatMessage=Wn(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.reloadCurrentPageData()}getSelectedWorkspaceInfo(){return this.selectedWorkspace?this.workspaces.find(e=>e.name===this.selectedWorkspace)??null:null}reloadCurrentPageData(){this.loadAuditEntries(),this.adminsPage?this.handleAdminsLoad():this.contactsPage?this.handleContactsLoad():this.filesPage?this.handleFilesLoad():this.chatPage?this.handleChatLoad():this.advancedPage&&this.handleAdvancedLoad()}initWorkspaceSelection(){if(this.workspaces.length===0){this.reloadCurrentPageData();return}const e=localStorage.getItem("taskmaster-selected-workspace"),t=e?this.workspaces.find(n=>n.name===e):null;if(t)this.selectedWorkspace=t.name;else{const n=this.workspaces.find(i=>i.isDefault)??this.workspaces[0];this.selectedWorkspace=n.name,localStorage.setItem("taskmaster-selected-workspace",n.name)}Tn(this.selectedWorkspace),gr(this.selectedWorkspace),this.settings=Ps(),this.chatMessage=Wn(this.selectedWorkspace,this.settings.sessionKey),this.reloadCurrentPageData()}render(){return u`${Fk(this)}${this.auditModalOpen?Wk(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):w}`}};m([y()],g.prototype,"settings",2);m([y()],g.prototype,"password",2);m([y()],g.prototype,"tab",2);m([y()],g.prototype,"onboarding",2);m([y()],g.prototype,"setup",2);m([y()],g.prototype,"filesPage",2);m([y()],g.prototype,"browserPage",2);m([y()],g.prototype,"adminsPage",2);m([y()],g.prototype,"contactsPage",2);m([y()],g.prototype,"chatPage",2);m([y()],g.prototype,"advancedPage",2);m([y()],g.prototype,"advancedTab",2);m([y()],g.prototype,"publicChat",2);m([y()],g.prototype,"publicChatConfig",2);m([y()],g.prototype,"publicChatSessionKey",2);m([y()],g.prototype,"publicChatAuthenticated",2);m([y()],g.prototype,"publicChatAuthStep",2);m([y()],g.prototype,"connected",2);m([y()],g.prototype,"accessState",2);m([y()],g.prototype,"theme",2);m([y()],g.prototype,"themeResolved",2);m([y()],g.prototype,"hello",2);m([y()],g.prototype,"lastError",2);m([y()],g.prototype,"eventLog",2);m([y()],g.prototype,"assistantName",2);m([y()],g.prototype,"assistantAvatar",2);m([y()],g.prototype,"assistantAgentId",2);m([y()],g.prototype,"sessionKey",2);m([y()],g.prototype,"chatLoading",2);m([y()],g.prototype,"chatSending",2);m([y()],g.prototype,"chatMessage",2);m([y()],g.prototype,"chatMessages",2);m([y()],g.prototype,"chatHistoryTotal",2);m([y()],g.prototype,"chatHistoryHasMore",2);m([y()],g.prototype,"chatLoadingOlder",2);m([y()],g.prototype,"chatToolMessages",2);m([y()],g.prototype,"chatStream",2);m([y()],g.prototype,"chatInterimText",2);m([y()],g.prototype,"chatSuggestions",2);m([y()],g.prototype,"chatStreamStartedAt",2);m([y()],g.prototype,"chatRunId",2);m([y()],g.prototype,"compactionStatus",2);m([y()],g.prototype,"chatAvatarUrl",2);m([y()],g.prototype,"chatThinkingLevel",2);m([y()],g.prototype,"chatModelProvider",2);m([y()],g.prototype,"chatModel",2);m([y()],g.prototype,"chatModelCatalog",2);m([y()],g.prototype,"chatVerboseLevel",2);m([y()],g.prototype,"chatFillerEnabled",2);m([y()],g.prototype,"chatQueue",2);m([y()],g.prototype,"chatAttachments",2);m([y()],g.prototype,"sidebarOpen",2);m([y()],g.prototype,"sidebarContent",2);m([y()],g.prototype,"sidebarError",2);m([y()],g.prototype,"splitRatio",2);m([y()],g.prototype,"nodesLoading",2);m([y()],g.prototype,"nodes",2);m([y()],g.prototype,"devicesLoading",2);m([y()],g.prototype,"devicesError",2);m([y()],g.prototype,"devicesList",2);m([y()],g.prototype,"execApprovalsLoading",2);m([y()],g.prototype,"execApprovalsSaving",2);m([y()],g.prototype,"execApprovalsDirty",2);m([y()],g.prototype,"execApprovalsSnapshot",2);m([y()],g.prototype,"execApprovalsForm",2);m([y()],g.prototype,"execApprovalsSelectedAgent",2);m([y()],g.prototype,"execApprovalsTarget",2);m([y()],g.prototype,"execApprovalsTargetNodeId",2);m([y()],g.prototype,"execApprovalQueue",2);m([y()],g.prototype,"execApprovalBusy",2);m([y()],g.prototype,"execApprovalError",2);m([y()],g.prototype,"configLoading",2);m([y()],g.prototype,"configRaw",2);m([y()],g.prototype,"configRawOriginal",2);m([y()],g.prototype,"configValid",2);m([y()],g.prototype,"configIssues",2);m([y()],g.prototype,"configSaving",2);m([y()],g.prototype,"configApplying",2);m([y()],g.prototype,"updateRunning",2);m([y()],g.prototype,"applySessionKey",2);m([y()],g.prototype,"configSnapshot",2);m([y()],g.prototype,"configSchema",2);m([y()],g.prototype,"configSchemaVersion",2);m([y()],g.prototype,"configSchemaLoading",2);m([y()],g.prototype,"configUiHints",2);m([y()],g.prototype,"configForm",2);m([y()],g.prototype,"configFormOriginal",2);m([y()],g.prototype,"configFormDirty",2);m([y()],g.prototype,"configFormMode",2);m([y()],g.prototype,"configSearchQuery",2);m([y()],g.prototype,"configActiveSection",2);m([y()],g.prototype,"configActiveSubsection",2);m([y()],g.prototype,"channelsLoading",2);m([y()],g.prototype,"channelsSnapshot",2);m([y()],g.prototype,"channelsError",2);m([y()],g.prototype,"channelsLastSuccess",2);m([y()],g.prototype,"whatsappLoginMessage",2);m([y()],g.prototype,"whatsappLoginQrDataUrl",2);m([y()],g.prototype,"whatsappLoginConnected",2);m([y()],g.prototype,"whatsappBusy",2);m([y()],g.prototype,"whatsappActiveQrAccountId",2);m([y()],g.prototype,"whatsappPairedPhone",2);m([y()],g.prototype,"addingWhatsAppAccount",2);m([y()],g.prototype,"newWhatsAppAccountName",2);m([y()],g.prototype,"whatsappAccountError",2);m([y()],g.prototype,"whatsappAccountSaving",2);m([y()],g.prototype,"whatsappSettingsOpen",2);m([y()],g.prototype,"publicChatToggleBusy",2);m([y()],g.prototype,"publicChatGreetingBusy",2);m([y()],g.prototype,"publicChatEmailBusy",2);m([y()],g.prototype,"publicChatSettingsOpen",2);m([y()],g.prototype,"publicChatWidgetModalOpen",2);m([y()],g.prototype,"brandingBusy",2);m([y()],g.prototype,"brandingExpanded",2);m([y()],g.prototype,"tailscaleStatus",2);m([y()],g.prototype,"tailscaleBusy",2);m([y()],g.prototype,"tailscaleAuthUrl",2);m([y()],g.prototype,"tailscaleError",2);m([y()],g.prototype,"tailscaleFunnelEnableUrl",2);m([y()],g.prototype,"tailscaleDisableConfirm",2);m([y()],g.prototype,"tailscaleConnectProgress",2);m([y()],g.prototype,"tailscaleConnectMessage",2);m([y()],g.prototype,"tailscaleConnectSuccess",2);m([y()],g.prototype,"wifiStatus",2);m([y()],g.prototype,"wifiNetworks",2);m([y()],g.prototype,"wifiBusy",2);m([y()],g.prototype,"wifiError",2);m([y()],g.prototype,"wifiPassword",2);m([y()],g.prototype,"wifiSelectedSsid",2);m([y()],g.prototype,"networkPort",2);m([y()],g.prototype,"networkHostname",2);m([y()],g.prototype,"networkPortInput",2);m([y()],g.prototype,"networkHostnameInput",2);m([y()],g.prototype,"networkModalOpen",2);m([y()],g.prototype,"networkBusy",2);m([y()],g.prototype,"networkError",2);m([y()],g.prototype,"networkSuccess",2);m([y()],g.prototype,"wifiModalOpen",2);m([y()],g.prototype,"licenseKey",2);m([y()],g.prototype,"licenseBusy",2);m([y()],g.prototype,"licenseValid",2);m([y()],g.prototype,"licenseMessage",2);m([y()],g.prototype,"licenseTier",2);m([y()],g.prototype,"licenseDeviceId",2);m([y()],g.prototype,"licenseStoredKey",2);m([y()],g.prototype,"licenseRemoveConfirm",2);m([y()],g.prototype,"authConnected",2);m([y()],g.prototype,"authBusy",2);m([y()],g.prototype,"authMessage",2);m([y()],g.prototype,"authUrl",2);m([y()],g.prototype,"authCodeInput",2);m([y()],g.prototype,"authExpiresIn",2);m([y()],g.prototype,"setupStep",2);m([y()],g.prototype,"gatewayHealthy",2);m([y()],g.prototype,"gatewayHealthLoading",2);m([y()],g.prototype,"gatewayHealthMessage",2);m([y()],g.prototype,"gatewayRestartBusy",2);m([y()],g.prototype,"updateAvailable",2);m([y()],g.prototype,"currentVersion",2);m([y()],g.prototype,"latestVersion",2);m([y()],g.prototype,"updateChecking",2);m([y()],g.prototype,"updateMessage",2);m([y()],g.prototype,"updateProgressSteps",2);m([y()],g.prototype,"updateLastResult",2);m([y()],g.prototype,"uninstallConfirm",2);m([y()],g.prototype,"uninstallBusy",2);m([y()],g.prototype,"uninstallDone",2);m([y()],g.prototype,"uninstallError",2);m([y()],g.prototype,"uninstallConfirmText",2);m([y()],g.prototype,"nostrProfileFormState",2);m([y()],g.prototype,"nostrProfileAccountId",2);m([y()],g.prototype,"presenceLoading",2);m([y()],g.prototype,"presenceEntries",2);m([y()],g.prototype,"presenceError",2);m([y()],g.prototype,"presenceStatus",2);m([y()],g.prototype,"agentsLoading",2);m([y()],g.prototype,"agentsList",2);m([y()],g.prototype,"agentsError",2);m([y()],g.prototype,"sessionsLoading",2);m([y()],g.prototype,"sessionsResult",2);m([y()],g.prototype,"sessionsError",2);m([y()],g.prototype,"cronLoading",2);m([y()],g.prototype,"cronJobs",2);m([y()],g.prototype,"cronStatus",2);m([y()],g.prototype,"cronError",2);m([y()],g.prototype,"cronForm",2);m([y()],g.prototype,"cronRunsJobId",2);m([y()],g.prototype,"cronRuns",2);m([y()],g.prototype,"cronBusy",2);m([y()],g.prototype,"cronNewEventModal",2);m([y()],g.prototype,"cronDetailJobId",2);m([y()],g.prototype,"cronEditJobId",2);m([y()],g.prototype,"cronPendingDeleteId",2);m([y()],g.prototype,"cronRunModalJobId",2);m([y()],g.prototype,"cronRunModalJobName",2);m([y()],g.prototype,"cronRunResult",2);m([y()],g.prototype,"browserScreencastActive",2);m([y()],g.prototype,"browserScreencastFrame",2);m([y()],g.prototype,"browserScreencastMetadata",2);m([y()],g.prototype,"browserHandoffPending",2);m([y()],g.prototype,"browserHandoffReason",2);m([y()],g.prototype,"browserHandoffId",2);m([y()],g.prototype,"browserInputMode",2);m([y()],g.prototype,"browserFullscreen",2);m([y()],g.prototype,"browserLoading",2);m([y()],g.prototype,"browserError",2);m([y()],g.prototype,"filesLoading",2);m([y()],g.prototype,"filesTree",2);m([y()],g.prototype,"filesRoot",2);m([y()],g.prototype,"filesError",2);m([y()],g.prototype,"filesSelectedPath",2);m([y()],g.prototype,"filesSelectedPaths",2);m([y()],g.prototype,"filesPreviewContent",2);m([y()],g.prototype,"filesPreviewLoading",2);m([y()],g.prototype,"filesPreviewBinary",2);m([y()],g.prototype,"filesPreviewSize",2);m([y()],g.prototype,"filesExpandedDirs",2);m([y()],g.prototype,"filesCurrentDir",2);m([y()],g.prototype,"filesPendingDeletePath",2);m([y()],g.prototype,"filesMessage",2);m([y()],g.prototype,"filesUploadBusy",2);m([y()],g.prototype,"filesReindexBusy",2);m([y()],g.prototype,"filesMemoryStatus",2);m([y()],g.prototype,"embeddingDownloading",2);m([y()],g.prototype,"filesSearchQuery",2);m([y()],g.prototype,"filesSearchResults",2);m([y()],g.prototype,"filesSearchLoading",2);m([y()],g.prototype,"filesSearchAgentId",2);m([y()],g.prototype,"auditEntries",2);m([y()],g.prototype,"auditLoading",2);m([y()],g.prototype,"auditModalOpen",2);m([y()],g.prototype,"skillsLoading",2);m([y()],g.prototype,"skillsReport",2);m([y()],g.prototype,"skillsError",2);m([y()],g.prototype,"skillsFilter",2);m([y()],g.prototype,"skillsTypeFilter",2);m([y()],g.prototype,"skillEdits",2);m([y()],g.prototype,"skillsBusyKey",2);m([y()],g.prototype,"skillMessages",2);m([y()],g.prototype,"skillDetail",2);m([y()],g.prototype,"skillDetailTab",2);m([y()],g.prototype,"skillAddModal",2);m([y()],g.prototype,"skillAddForm",2);m([y()],g.prototype,"skillAddFormSource",2);m([y()],g.prototype,"skillEditTab",2);m([y()],g.prototype,"skillDrafts",2);m([y()],g.prototype,"adminsLoading",2);m([y()],g.prototype,"adminPhones",2);m([y()],g.prototype,"adminsError",2);m([y()],g.prototype,"adminsSaving",2);m([y()],g.prototype,"adminsNewPhone",2);m([y()],g.prototype,"contactsLoading",2);m([y()],g.prototype,"contactsSaving",2);m([y()],g.prototype,"contactsRecords",2);m([y()],g.prototype,"contactsError",2);m([y()],g.prototype,"contactsSearchQuery",2);m([y()],g.prototype,"contactsEditingId",2);m([y()],g.prototype,"contactsShowAddForm",2);m([y()],g.prototype,"contactsNewPhone",2);m([y()],g.prototype,"contactsNewName",2);m([y()],g.prototype,"contactsDeleteConfirmId",2);m([y()],g.prototype,"contactsAddFieldForId",2);m([y()],g.prototype,"contactsAddFieldKey",2);m([y()],g.prototype,"contactsAddFieldValue",2);m([y()],g.prototype,"imessageEnableConfirm",2);m([y()],g.prototype,"imessageEnabling",2);m([y()],g.prototype,"infoModalOpen",2);m([y()],g.prototype,"remoteAccessQrDataUrl",2);m([y()],g.prototype,"publicChatQrDataUrl",2);m([y()],g.prototype,"workspaces",2);m([y()],g.prototype,"workspacesLoading",2);m([y()],g.prototype,"workspacesError",2);m([y()],g.prototype,"selectedWorkspace",2);m([y()],g.prototype,"addingWorkspace",2);m([y()],g.prototype,"newWorkspaceName",2);m([y()],g.prototype,"newWorkspacePath",2);m([y()],g.prototype,"newWorkspacePin",2);m([y()],g.prototype,"accountPinModalOpen",2);m([y()],g.prototype,"accountPinBusy",2);m([y()],g.prototype,"accountPinError",2);m([y()],g.prototype,"accountPinSuccess",2);m([y()],g.prototype,"apiKeyProviders",2);m([y()],g.prototype,"apiKeyModalOpen",2);m([y()],g.prototype,"apiKeyBusy",2);m([y()],g.prototype,"apiKeyError",2);m([y()],g.prototype,"apiKeySuccess",2);m([y()],g.prototype,"apiKeySavingProvider",2);m([y()],g.prototype,"authApiKeyMode",2);m([y()],g.prototype,"authApiKeyInput",2);m([y()],g.prototype,"authApiKeyBusy",2);m([y()],g.prototype,"authApiKeyError",2);m([y()],g.prototype,"pinChanging",2);m([y()],g.prototype,"pinChangeBusy",2);m([y()],g.prototype,"pinChangeError",2);m([y()],g.prototype,"loginChangePinMode",2);m([y()],g.prototype,"changePinBusy",2);m([y()],g.prototype,"changePinError",2);m([y()],g.prototype,"changePinSuccess",2);m([y()],g.prototype,"workspaceSaving",2);m([y()],g.prototype,"workspaceRemoveConfirm",2);m([y()],g.prototype,"renamingWorkspace",2);m([y()],g.prototype,"renameWorkspaceName",2);m([y()],g.prototype,"debugLoading",2);m([y()],g.prototype,"debugStatus",2);m([y()],g.prototype,"debugHealth",2);m([y()],g.prototype,"debugModels",2);m([y()],g.prototype,"debugHeartbeat",2);m([y()],g.prototype,"debugCallMethod",2);m([y()],g.prototype,"debugCallParams",2);m([y()],g.prototype,"debugCallResult",2);m([y()],g.prototype,"debugCallError",2);m([y()],g.prototype,"logsLoading",2);m([y()],g.prototype,"logsError",2);m([y()],g.prototype,"logsFile",2);m([y()],g.prototype,"logsEntries",2);m([y()],g.prototype,"logsFilterText",2);m([y()],g.prototype,"logsLevelFilters",2);m([y()],g.prototype,"logsAutoFollow",2);m([y()],g.prototype,"logsTruncated",2);m([y()],g.prototype,"logsCursor",2);m([y()],g.prototype,"logsLastFetchAt",2);m([y()],g.prototype,"logsLimit",2);m([y()],g.prototype,"logsMaxBytes",2);m([y()],g.prototype,"logsAtBottom",2);m([y()],g.prototype,"logsSubTab",2);m([y()],g.prototype,"logsChipsExpanded",2);m([y()],g.prototype,"sessionLogsLoading",2);m([y()],g.prototype,"sessionLogsError",2);m([y()],g.prototype,"sessionLogsEntries",2);m([y()],g.prototype,"sessionLogsFilterText",2);m([y()],g.prototype,"sessionLogsTypeFilters",2);m([y()],g.prototype,"sessionLogsAgentFilters",2);m([y()],g.prototype,"sessionLogsAgents",2);m([y()],g.prototype,"sessionLogsAutoFollow",2);m([y()],g.prototype,"sessionLogsChipsExpanded",2);m([y()],g.prototype,"sessionLogsCursors",2);m([y()],g.prototype,"sessionLogsLastFetchAt",2);m([y()],g.prototype,"sessionLogsAtBottom",2);m([y()],g.prototype,"chatUserNearBottom",2);g=m([Ul("taskmaster-app")],g);
4540
- //# sourceMappingURL=index-s8s_YKvR.js.map
4553
+ `,this.configRawOriginal="",this.configValid=null,this.configIssues=[],this.configSaving=!1,this.configApplying=!1,this.updateRunning=!1,this.applySessionKey=this.settings.lastActiveSessionKey,this.configSnapshot=null,this.configSchema=null,this.configSchemaVersion=null,this.configSchemaLoading=!1,this.configUiHints={},this.configForm=null,this.configFormOriginal=null,this.configFormDirty=!1,this.configFormMode="form",this.configSearchQuery="",this.configActiveSection=null,this.configActiveSubsection=null,this.channelsLoading=!1,this.channelsSnapshot=null,this.channelsError=null,this.channelsLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.whatsappActiveQrAccountId=null,this.whatsappPairedPhone=null,this.addingWhatsAppAccount=!1,this.newWhatsAppAccountName="",this.whatsappAccountError=null,this.whatsappAccountSaving=!1,this.whatsappSettingsOpen=!1,this.publicChatToggleBusy=!1,this.publicChatGreetingBusy=!1,this.publicChatEmailBusy=!1,this.publicChatSettingsOpen=!1,this.publicChatWidgetModalOpen=!1,this.brandingBusy=!1,this.brandingExpanded=!1,this.tailscaleStatus=null,this.tailscaleBusy=!1,this.tailscaleAuthUrl=null,this.tailscaleError=null,this.tailscaleFunnelEnableUrl=null,this.tailscaleDisableConfirm=!1,this.tailscaleConnectProgress=0,this.tailscaleConnectMessage="",this.tailscaleConnectSuccess=!1,this.wifiStatus=null,this.wifiNetworks=[],this.wifiBusy=!1,this.wifiError=null,this.wifiPassword="",this.wifiSelectedSsid=null,this.networkPort=null,this.networkHostname="",this.networkPortInput="",this.networkHostnameInput="",this.networkModalOpen=!1,this.networkBusy=!1,this.networkError=null,this.networkSuccess=null,this.wifiModalOpen=!1,this.licenseKey="",this.licenseBusy=!1,this.licenseValid=null,this.licenseMessage=null,this.licenseTier=null,this.licenseDeviceId=null,this.licenseStoredKey=null,this.licenseRemoveConfirm=!1,this.authConnected=null,this.authBusy=!1,this.authMessage=null,this.authUrl=null,this.authCodeInput="",this.authExpiresIn=null,this.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={...qk},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.browserScreencastActive=!1,this.browserScreencastFrame=null,this.browserScreencastMetadata=null,this.browserHandoffPending=!1,this.browserHandoffReason=null,this.browserHandoffId=null,this.browserInputMode=!1,this.browserFullscreen=!1,this.browserLoading=!1,this.browserError=null,this.filesLoading=!1,this.filesTree=[],this.filesRoot="",this.filesError=null,this.filesSelectedPath=null,this.filesSelectedPaths=new Set,this.filesPreviewContent=null,this.filesPreviewLoading=!1,this.filesPreviewBinary=!1,this.filesPreviewSize=null,this.filesExpandedDirs=new Set,this.filesCurrentDir=".",this.filesPendingDeletePath=null,this.filesMessage=null,this.filesUploadBusy=!1,this.filesReindexBusy=!1,this.filesMemoryStatus=null,this.embeddingDownloading=!1,this.embeddingPollTimer=null,this.filesSearchQuery="",this.filesSearchResults=null,this.filesSearchLoading=!1,this.filesSearchAgentId=null,this.filesResolvedAgentId=void 0,this.auditEntries=[],this.auditLoading=!1,this.auditModalOpen=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillsTypeFilter="all",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillDetail=null,this.skillDetailTab="",this.skillAddModal=!1,this.skillAddForm={name:"",skillContent:"",references:[]},this.skillAddFormSource="draft",this.skillEditTab="SKILL.md",this.skillDrafts=[],this.adminsLoading=!1,this.adminPhones=[],this.adminsError=null,this.adminsSaving=!1,this.adminsNewPhone="",this.contactsLoading=!1,this.contactsSaving=!1,this.contactsRecords=[],this.contactsError=null,this.contactsSearchQuery="",this.contactsEditingId=null,this.contactsShowAddForm=!1,this.contactsNewPhone="",this.contactsNewName="",this.contactsDeleteConfirmId=null,this.contactsAddFieldForId=null,this.contactsAddFieldKey="",this.contactsAddFieldValue="",this.imessageEnableConfirm=!1,this.imessageEnabling=!1,this.infoModalOpen=null,this.remoteAccessQrDataUrl=null,this.publicChatQrDataUrl=null,this.workspaces=[],this.workspacesLoading=!1,this.workspacesError=null,this.selectedWorkspace=null,this.addingWorkspace=!1,this.newWorkspaceName="",this.newWorkspacePath="",this.newWorkspacePin="",this.accountPinModalOpen=!1,this.accountPinBusy=!1,this.accountPinError=null,this.accountPinSuccess=null,this.apiKeyProviders=[],this.apiKeyModalOpen=!1,this.apiKeyBusy=!1,this.apiKeyError=null,this.apiKeySuccess=null,this.apiKeySavingProvider=null,this.authApiKeyMode=!1,this.authApiKeyInput="",this.authApiKeyBusy=!1,this.authApiKeyError=null,this.pinChanging=null,this.pinChangeBusy=!1,this.pinChangeError=null,this.loginChangePinMode=!1,this.changePinBusy=!1,this.changePinError=null,this.changePinSuccess=null,this.workspaceSaving=!1,this.workspaceRemoveConfirm=null,this.renamingWorkspace=!1,this.renameWorkspaceName="",this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...zk},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.logsSubTab="session",this.logsChipsExpanded=!1,this.sessionLogsLoading=!1,this.sessionLogsError=null,this.sessionLogsEntries=[],this.sessionLogsFilterText="",this.sessionLogsTypeFilters={user:!0,assistant:!0,tool:!0,tool_call:!0,tool_result:!0,thinking:!0,error:!0,system:!0},this.sessionLogsAgentFilters={},this.sessionLogsAgents=[],this.sessionLogsAutoFollow=!0,this.sessionLogsChipsExpanded=!1,this.sessionLogsExpandedIds=new Set,this.sessionLogsCursors={},this.sessionLogsLastFetchAt=null,this.sessionLogsAtBottom=!0,this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.chatUserNearBottom=!0,this.onLoadOlder=()=>this.handleLoadOlderChat(),this.nodesPollInterval=null,this.logsPollInterval=null,this.sessionLogsPollInterval=null,this.debugPollInterval=null,this.auditPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.basePath="",this.popStateHandler=()=>Df(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._beforeUnloadHandler=()=>{var t;vo();const e=this.selectedWorkspace??((t=this.publicChatConfig)==null?void 0:t.accountId)??"";e&&Wn(e,this.sessionKey,this.chatMessage)}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),Hk(this),window.addEventListener("beforeunload",this._beforeUnloadHandler)}firstUpdated(){jk(this)}disconnectedCallback(){window.removeEventListener("beforeunload",this._beforeUnloadHandler),this.stopEmbeddingPoll(),Gk(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){Vk(this,e)}connect(){De(this)}handleChatScroll(e){Yp(this,e)}handleLogsScroll(e){Zp(this,e)}handleSessionLogsScroll(e){eh(this,e)}exportLogs(e,t){nh(e,t)}exportSessionLogs(e,t){ih(e,t)}resetToolStream(){Xo(this)}resetChatScroll(){th(this)}async loadAssistantIdentity(){await zo(this)}applySettings(e){rt(this,e)}setTab(e){Tf(this,e)}setTheme(e,t){_f(this,e,t)}async loadOverview(){await id(this)}async loadCron(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.cronForm={...this.cronForm,accountId:(e==null?void 0:e.whatsappAccountId)??void 0},await ma(this)}async handleAbortChat(){await od(this)}removeQueuedMessage(e){Ff(this,e)}async handleSendChat(e,t){await Uf(this,e,t)}async handleWhatsAppStart(e,t){await Jk(this,e,t)}async handleWhatsAppWait(e){await Yk(this,e)}async handleWhatsAppLogout(e){await Xk(this,e)}async handleAddWhatsAppAccount(e){await Zk(this,e)}async handleRemoveWhatsAppAccount(e){await e0(this,e)}async handleAccessCheck(){await Ml(this)}async handlePinSubmit(e,t){await xk(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await Sk(this,e)}async handleLogout(){await Ck(this)}toggleChangePinMode(){this.loginChangePinMode=!this.loginChangePinMode,this.changePinError=null,this.changePinSuccess=null}async handleChangePin(e,t,n){if(this.client){this.changePinBusy=!0,this.changePinError=null,this.changePinSuccess=null;try{const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.changePinError=i.message??"Incorrect current PIN",this.changePinBusy=!1;return}e==="__master__"?await this.client.request("access.setMasterPin",{pin:n}):await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.changePinSuccess="PIN changed successfully",this.changePinBusy=!1,setTimeout(()=>{this.loginChangePinMode=!1,this.changePinSuccess=null},2e3)}catch{this.changePinError="Failed to change PIN",this.changePinBusy=!1}}}async handleAccountPinSave(e,t,n){if(this.client){this.accountPinBusy=!0,this.accountPinError=null,this.accountPinSuccess=null;try{if(t!==null){const i=await this.client.request("access.verify",{account:e,pin:t});if(!i.ok){this.accountPinError=i.message??"Incorrect current PIN",this.accountPinBusy=!1;return}}await this.client.request("access.setAccountPin",{workspace:e,pin:n}),this.accountPinSuccess="PIN saved",this.accountPinBusy=!1,await Ml(this),setTimeout(()=>{this.accountPinModalOpen=!1,this.accountPinSuccess=null,this.accountPinError=null},1500)}catch{this.accountPinError="Failed to save PIN",this.accountPinBusy=!1}}}async handleLicenseStatusCheck(){await g0(this)}async handleLicenseActivate(){await m0(this)}async handleLicenseRemove(){await y0(this)}handleLicenseKeyChange(e){v0(this,e)}async handleAuthStatusCheck(){await d0(this)}async handleAuthStart(){await u0(this)}async handleAuthSubmitCode(e){await p0(this,e)}handleAuthCodeChange(e){h0(this,e)}handleSkipToWhatsApp(){f0(this)}async handleGatewayHealthCheck(){await b0(this)}async handleGatewayRestart(){await w0(this)}async handleUpdateCheck(){await fu(this)}async handleUpdateRun(){await ok(this)}handleUpdateDismissResult(){lk(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 le(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>Mr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){le(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>Mr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await Yc(this)}async clearAudit(){await lf(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,an(this,t),ls(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();le(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>Tk);return{loadAdmins:t}},void 0,import.meta.url).then(({loadAdmins:t})=>{t(this,e)})}resolveAdminAgentId(){const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(n=>n.id.endsWith("-admin")||n.id==="admin");return t==null?void 0:t.id}resolveFilesAgentId(){var n;const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return(t==null?void 0:t.id)??((n=e.agents[0])==null?void 0:n.id)}handleChatLoad(){const e=this.resolveAdminAgentId();if(e){const t=`agent:${e}:main`;t!==this.sessionKey&&(this.sessionKey=t,this.chatMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestions=[],this.resetChatScroll(),this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity())}le(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>Ni);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this).then(()=>{nn(this,!0)})})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=Xp(this),{loadOlderChatHistory:t}=await le(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>Ni);return{loadOlderChatHistory:i}},void 0,import.meta.url);await t(this)&&e&&(await this.updateComplete,e())}handleAdvancedLoad(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.sessionLogsEntries=[],this.sessionLogsCursors={},this.sessionLogsAgents=[],this.advancedTab==="cron"&&this.loadCron(),this.advancedTab==="logs"&&(this.logsSubTab==="session"?le(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>Jc);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):le(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>wh);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&le(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>ef);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await t0(this)}async handleChannelConfigReload(){await n0(this)}handleNostrProfileEdit(e,t){s0(this,e,t)}handleNostrProfileCancel(){o0(this)}handleNostrProfileFieldChange(e,t){a0(this,e,t)}async handleNostrProfileSave(){await l0(this)}async handleNostrProfileImport(){await c0(this)}handleNostrProfileToggleAdvanced(){r0(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;le(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>_k);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 le(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>ki);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await le(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>ki);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await le(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>gh);return{loadChannels:s}},void 0,import.meta.url);await n(this,{name:e,workspacePath:t,onCreated:s=>{if(!s.whatsappAccountId)return;const o=s.whatsappAccountId;this.handleWorkspaceSelect(e),setTimeout(async()=>{try{await i(this,!0),await this.handleWhatsAppStart(!0,o),this.whatsappLoginQrDataUrl&&(await this.handleWhatsAppWait(o),await i(this,!0),await this.handleWorkspacesLoad())}catch{}this.requestUpdate()},3e3)}})}async handleWorkspaceRemove(e){const{removeWorkspace:t}=await le(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>ki);return{removeWorkspace:n}},void 0,import.meta.url);await t(this,e)}handleWorkspaceRenameStart(){const e=this.getSelectedWorkspaceInfo();this.renameWorkspaceName=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"",this.renamingWorkspace=!0}handleWorkspaceRenameCancel(){this.renamingWorkspace=!1,this.renameWorkspaceName=""}async handleWorkspaceRename(e,t){const{renameWorkspace:n}=await le(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>ki);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){vo(),this.selectedWorkspace&&Wn(this.selectedWorkspace,this.sessionKey,this.chatMessage),this.selectedWorkspace=e,this.publicChatQrDataUrl=null,localStorage.setItem("taskmaster-selected-workspace",e),Tn(e),mr(e),this.settings=Is(),this.chatMessage=Kn(e,this.settings.sessionKey),this.chatAttachments=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestions=[],this.chatStreamStartedAt=null,this.chatRunId=null,this.chatQueue=[],this.lastError=null,this.reloadCurrentPageData()}getSelectedWorkspaceInfo(){return this.selectedWorkspace?this.workspaces.find(e=>e.name===this.selectedWorkspace)??null:null}reloadCurrentPageData(){this.loadAuditEntries(),this.adminsPage?this.handleAdminsLoad():this.contactsPage?this.handleContactsLoad():this.filesPage?this.handleFilesLoad():this.chatPage?this.handleChatLoad():this.advancedPage&&this.handleAdvancedLoad()}initWorkspaceSelection(){if(this.workspaces.length===0){this.reloadCurrentPageData();return}const e=localStorage.getItem("taskmaster-selected-workspace"),t=e?this.workspaces.find(n=>n.name===e):null;if(t)this.selectedWorkspace=t.name;else{const n=this.workspaces.find(i=>i.isDefault)??this.workspaces[0];this.selectedWorkspace=n.name,localStorage.setItem("taskmaster-selected-workspace",n.name)}Tn(this.selectedWorkspace),mr(this.selectedWorkspace),this.settings=Is(),this.chatMessage=Kn(this.selectedWorkspace,this.settings.sessionKey),this.reloadCurrentPageData()}render(){return u`${Uk(this)}${this.auditModalOpen?Kk(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):w}`}};y([v()],m.prototype,"settings",2);y([v()],m.prototype,"password",2);y([v()],m.prototype,"tab",2);y([v()],m.prototype,"onboarding",2);y([v()],m.prototype,"setup",2);y([v()],m.prototype,"filesPage",2);y([v()],m.prototype,"browserPage",2);y([v()],m.prototype,"adminsPage",2);y([v()],m.prototype,"contactsPage",2);y([v()],m.prototype,"chatPage",2);y([v()],m.prototype,"advancedPage",2);y([v()],m.prototype,"advancedTab",2);y([v()],m.prototype,"publicChat",2);y([v()],m.prototype,"publicChatConfig",2);y([v()],m.prototype,"publicChatSessionKey",2);y([v()],m.prototype,"publicChatAuthenticated",2);y([v()],m.prototype,"publicChatAuthStep",2);y([v()],m.prototype,"connected",2);y([v()],m.prototype,"accessState",2);y([v()],m.prototype,"theme",2);y([v()],m.prototype,"themeResolved",2);y([v()],m.prototype,"hello",2);y([v()],m.prototype,"lastError",2);y([v()],m.prototype,"eventLog",2);y([v()],m.prototype,"assistantName",2);y([v()],m.prototype,"assistantAvatar",2);y([v()],m.prototype,"assistantAgentId",2);y([v()],m.prototype,"sessionKey",2);y([v()],m.prototype,"chatLoading",2);y([v()],m.prototype,"chatSending",2);y([v()],m.prototype,"chatMessage",2);y([v()],m.prototype,"chatMessages",2);y([v()],m.prototype,"chatHistoryTotal",2);y([v()],m.prototype,"chatHistoryHasMore",2);y([v()],m.prototype,"chatLoadingOlder",2);y([v()],m.prototype,"chatToolMessages",2);y([v()],m.prototype,"chatStream",2);y([v()],m.prototype,"chatInterimText",2);y([v()],m.prototype,"chatSuggestions",2);y([v()],m.prototype,"chatStreamStartedAt",2);y([v()],m.prototype,"chatRunId",2);y([v()],m.prototype,"compactionStatus",2);y([v()],m.prototype,"chatAvatarUrl",2);y([v()],m.prototype,"chatThinkingLevel",2);y([v()],m.prototype,"chatModelProvider",2);y([v()],m.prototype,"chatModel",2);y([v()],m.prototype,"chatModelCatalog",2);y([v()],m.prototype,"chatVerboseLevel",2);y([v()],m.prototype,"chatFillerEnabled",2);y([v()],m.prototype,"chatQueue",2);y([v()],m.prototype,"chatAttachments",2);y([v()],m.prototype,"sidebarOpen",2);y([v()],m.prototype,"sidebarContent",2);y([v()],m.prototype,"sidebarError",2);y([v()],m.prototype,"splitRatio",2);y([v()],m.prototype,"nodesLoading",2);y([v()],m.prototype,"nodes",2);y([v()],m.prototype,"devicesLoading",2);y([v()],m.prototype,"devicesError",2);y([v()],m.prototype,"devicesList",2);y([v()],m.prototype,"execApprovalsLoading",2);y([v()],m.prototype,"execApprovalsSaving",2);y([v()],m.prototype,"execApprovalsDirty",2);y([v()],m.prototype,"execApprovalsSnapshot",2);y([v()],m.prototype,"execApprovalsForm",2);y([v()],m.prototype,"execApprovalsSelectedAgent",2);y([v()],m.prototype,"execApprovalsTarget",2);y([v()],m.prototype,"execApprovalsTargetNodeId",2);y([v()],m.prototype,"execApprovalQueue",2);y([v()],m.prototype,"execApprovalBusy",2);y([v()],m.prototype,"execApprovalError",2);y([v()],m.prototype,"configLoading",2);y([v()],m.prototype,"configRaw",2);y([v()],m.prototype,"configRawOriginal",2);y([v()],m.prototype,"configValid",2);y([v()],m.prototype,"configIssues",2);y([v()],m.prototype,"configSaving",2);y([v()],m.prototype,"configApplying",2);y([v()],m.prototype,"updateRunning",2);y([v()],m.prototype,"applySessionKey",2);y([v()],m.prototype,"configSnapshot",2);y([v()],m.prototype,"configSchema",2);y([v()],m.prototype,"configSchemaVersion",2);y([v()],m.prototype,"configSchemaLoading",2);y([v()],m.prototype,"configUiHints",2);y([v()],m.prototype,"configForm",2);y([v()],m.prototype,"configFormOriginal",2);y([v()],m.prototype,"configFormDirty",2);y([v()],m.prototype,"configFormMode",2);y([v()],m.prototype,"configSearchQuery",2);y([v()],m.prototype,"configActiveSection",2);y([v()],m.prototype,"configActiveSubsection",2);y([v()],m.prototype,"channelsLoading",2);y([v()],m.prototype,"channelsSnapshot",2);y([v()],m.prototype,"channelsError",2);y([v()],m.prototype,"channelsLastSuccess",2);y([v()],m.prototype,"whatsappLoginMessage",2);y([v()],m.prototype,"whatsappLoginQrDataUrl",2);y([v()],m.prototype,"whatsappLoginConnected",2);y([v()],m.prototype,"whatsappBusy",2);y([v()],m.prototype,"whatsappActiveQrAccountId",2);y([v()],m.prototype,"whatsappPairedPhone",2);y([v()],m.prototype,"addingWhatsAppAccount",2);y([v()],m.prototype,"newWhatsAppAccountName",2);y([v()],m.prototype,"whatsappAccountError",2);y([v()],m.prototype,"whatsappAccountSaving",2);y([v()],m.prototype,"whatsappSettingsOpen",2);y([v()],m.prototype,"publicChatToggleBusy",2);y([v()],m.prototype,"publicChatGreetingBusy",2);y([v()],m.prototype,"publicChatEmailBusy",2);y([v()],m.prototype,"publicChatSettingsOpen",2);y([v()],m.prototype,"publicChatWidgetModalOpen",2);y([v()],m.prototype,"brandingBusy",2);y([v()],m.prototype,"brandingExpanded",2);y([v()],m.prototype,"tailscaleStatus",2);y([v()],m.prototype,"tailscaleBusy",2);y([v()],m.prototype,"tailscaleAuthUrl",2);y([v()],m.prototype,"tailscaleError",2);y([v()],m.prototype,"tailscaleFunnelEnableUrl",2);y([v()],m.prototype,"tailscaleDisableConfirm",2);y([v()],m.prototype,"tailscaleConnectProgress",2);y([v()],m.prototype,"tailscaleConnectMessage",2);y([v()],m.prototype,"tailscaleConnectSuccess",2);y([v()],m.prototype,"wifiStatus",2);y([v()],m.prototype,"wifiNetworks",2);y([v()],m.prototype,"wifiBusy",2);y([v()],m.prototype,"wifiError",2);y([v()],m.prototype,"wifiPassword",2);y([v()],m.prototype,"wifiSelectedSsid",2);y([v()],m.prototype,"networkPort",2);y([v()],m.prototype,"networkHostname",2);y([v()],m.prototype,"networkPortInput",2);y([v()],m.prototype,"networkHostnameInput",2);y([v()],m.prototype,"networkModalOpen",2);y([v()],m.prototype,"networkBusy",2);y([v()],m.prototype,"networkError",2);y([v()],m.prototype,"networkSuccess",2);y([v()],m.prototype,"wifiModalOpen",2);y([v()],m.prototype,"licenseKey",2);y([v()],m.prototype,"licenseBusy",2);y([v()],m.prototype,"licenseValid",2);y([v()],m.prototype,"licenseMessage",2);y([v()],m.prototype,"licenseTier",2);y([v()],m.prototype,"licenseDeviceId",2);y([v()],m.prototype,"licenseStoredKey",2);y([v()],m.prototype,"licenseRemoveConfirm",2);y([v()],m.prototype,"authConnected",2);y([v()],m.prototype,"authBusy",2);y([v()],m.prototype,"authMessage",2);y([v()],m.prototype,"authUrl",2);y([v()],m.prototype,"authCodeInput",2);y([v()],m.prototype,"authExpiresIn",2);y([v()],m.prototype,"setupStep",2);y([v()],m.prototype,"gatewayHealthy",2);y([v()],m.prototype,"gatewayHealthLoading",2);y([v()],m.prototype,"gatewayHealthMessage",2);y([v()],m.prototype,"gatewayRestartBusy",2);y([v()],m.prototype,"updateAvailable",2);y([v()],m.prototype,"currentVersion",2);y([v()],m.prototype,"latestVersion",2);y([v()],m.prototype,"updateChecking",2);y([v()],m.prototype,"updateMessage",2);y([v()],m.prototype,"updateProgressSteps",2);y([v()],m.prototype,"updateLastResult",2);y([v()],m.prototype,"uninstallConfirm",2);y([v()],m.prototype,"uninstallBusy",2);y([v()],m.prototype,"uninstallDone",2);y([v()],m.prototype,"uninstallError",2);y([v()],m.prototype,"uninstallConfirmText",2);y([v()],m.prototype,"nostrProfileFormState",2);y([v()],m.prototype,"nostrProfileAccountId",2);y([v()],m.prototype,"presenceLoading",2);y([v()],m.prototype,"presenceEntries",2);y([v()],m.prototype,"presenceError",2);y([v()],m.prototype,"presenceStatus",2);y([v()],m.prototype,"agentsLoading",2);y([v()],m.prototype,"agentsList",2);y([v()],m.prototype,"agentsError",2);y([v()],m.prototype,"sessionsLoading",2);y([v()],m.prototype,"sessionsResult",2);y([v()],m.prototype,"sessionsError",2);y([v()],m.prototype,"cronLoading",2);y([v()],m.prototype,"cronJobs",2);y([v()],m.prototype,"cronStatus",2);y([v()],m.prototype,"cronError",2);y([v()],m.prototype,"cronForm",2);y([v()],m.prototype,"cronRunsJobId",2);y([v()],m.prototype,"cronRuns",2);y([v()],m.prototype,"cronBusy",2);y([v()],m.prototype,"cronNewEventModal",2);y([v()],m.prototype,"cronDetailJobId",2);y([v()],m.prototype,"cronEditJobId",2);y([v()],m.prototype,"cronPendingDeleteId",2);y([v()],m.prototype,"cronRunModalJobId",2);y([v()],m.prototype,"cronRunModalJobName",2);y([v()],m.prototype,"cronRunResult",2);y([v()],m.prototype,"browserScreencastActive",2);y([v()],m.prototype,"browserScreencastFrame",2);y([v()],m.prototype,"browserScreencastMetadata",2);y([v()],m.prototype,"browserHandoffPending",2);y([v()],m.prototype,"browserHandoffReason",2);y([v()],m.prototype,"browserHandoffId",2);y([v()],m.prototype,"browserInputMode",2);y([v()],m.prototype,"browserFullscreen",2);y([v()],m.prototype,"browserLoading",2);y([v()],m.prototype,"browserError",2);y([v()],m.prototype,"filesLoading",2);y([v()],m.prototype,"filesTree",2);y([v()],m.prototype,"filesRoot",2);y([v()],m.prototype,"filesError",2);y([v()],m.prototype,"filesSelectedPath",2);y([v()],m.prototype,"filesSelectedPaths",2);y([v()],m.prototype,"filesPreviewContent",2);y([v()],m.prototype,"filesPreviewLoading",2);y([v()],m.prototype,"filesPreviewBinary",2);y([v()],m.prototype,"filesPreviewSize",2);y([v()],m.prototype,"filesExpandedDirs",2);y([v()],m.prototype,"filesCurrentDir",2);y([v()],m.prototype,"filesPendingDeletePath",2);y([v()],m.prototype,"filesMessage",2);y([v()],m.prototype,"filesUploadBusy",2);y([v()],m.prototype,"filesReindexBusy",2);y([v()],m.prototype,"filesMemoryStatus",2);y([v()],m.prototype,"embeddingDownloading",2);y([v()],m.prototype,"filesSearchQuery",2);y([v()],m.prototype,"filesSearchResults",2);y([v()],m.prototype,"filesSearchLoading",2);y([v()],m.prototype,"filesSearchAgentId",2);y([v()],m.prototype,"auditEntries",2);y([v()],m.prototype,"auditLoading",2);y([v()],m.prototype,"auditModalOpen",2);y([v()],m.prototype,"skillsLoading",2);y([v()],m.prototype,"skillsReport",2);y([v()],m.prototype,"skillsError",2);y([v()],m.prototype,"skillsFilter",2);y([v()],m.prototype,"skillsTypeFilter",2);y([v()],m.prototype,"skillEdits",2);y([v()],m.prototype,"skillsBusyKey",2);y([v()],m.prototype,"skillMessages",2);y([v()],m.prototype,"skillDetail",2);y([v()],m.prototype,"skillDetailTab",2);y([v()],m.prototype,"skillAddModal",2);y([v()],m.prototype,"skillAddForm",2);y([v()],m.prototype,"skillAddFormSource",2);y([v()],m.prototype,"skillEditTab",2);y([v()],m.prototype,"skillDrafts",2);y([v()],m.prototype,"adminsLoading",2);y([v()],m.prototype,"adminPhones",2);y([v()],m.prototype,"adminsError",2);y([v()],m.prototype,"adminsSaving",2);y([v()],m.prototype,"adminsNewPhone",2);y([v()],m.prototype,"contactsLoading",2);y([v()],m.prototype,"contactsSaving",2);y([v()],m.prototype,"contactsRecords",2);y([v()],m.prototype,"contactsError",2);y([v()],m.prototype,"contactsSearchQuery",2);y([v()],m.prototype,"contactsEditingId",2);y([v()],m.prototype,"contactsShowAddForm",2);y([v()],m.prototype,"contactsNewPhone",2);y([v()],m.prototype,"contactsNewName",2);y([v()],m.prototype,"contactsDeleteConfirmId",2);y([v()],m.prototype,"contactsAddFieldForId",2);y([v()],m.prototype,"contactsAddFieldKey",2);y([v()],m.prototype,"contactsAddFieldValue",2);y([v()],m.prototype,"imessageEnableConfirm",2);y([v()],m.prototype,"imessageEnabling",2);y([v()],m.prototype,"infoModalOpen",2);y([v()],m.prototype,"remoteAccessQrDataUrl",2);y([v()],m.prototype,"publicChatQrDataUrl",2);y([v()],m.prototype,"workspaces",2);y([v()],m.prototype,"workspacesLoading",2);y([v()],m.prototype,"workspacesError",2);y([v()],m.prototype,"selectedWorkspace",2);y([v()],m.prototype,"addingWorkspace",2);y([v()],m.prototype,"newWorkspaceName",2);y([v()],m.prototype,"newWorkspacePath",2);y([v()],m.prototype,"newWorkspacePin",2);y([v()],m.prototype,"accountPinModalOpen",2);y([v()],m.prototype,"accountPinBusy",2);y([v()],m.prototype,"accountPinError",2);y([v()],m.prototype,"accountPinSuccess",2);y([v()],m.prototype,"apiKeyProviders",2);y([v()],m.prototype,"apiKeyModalOpen",2);y([v()],m.prototype,"apiKeyBusy",2);y([v()],m.prototype,"apiKeyError",2);y([v()],m.prototype,"apiKeySuccess",2);y([v()],m.prototype,"apiKeySavingProvider",2);y([v()],m.prototype,"authApiKeyMode",2);y([v()],m.prototype,"authApiKeyInput",2);y([v()],m.prototype,"authApiKeyBusy",2);y([v()],m.prototype,"authApiKeyError",2);y([v()],m.prototype,"pinChanging",2);y([v()],m.prototype,"pinChangeBusy",2);y([v()],m.prototype,"pinChangeError",2);y([v()],m.prototype,"loginChangePinMode",2);y([v()],m.prototype,"changePinBusy",2);y([v()],m.prototype,"changePinError",2);y([v()],m.prototype,"changePinSuccess",2);y([v()],m.prototype,"workspaceSaving",2);y([v()],m.prototype,"workspaceRemoveConfirm",2);y([v()],m.prototype,"renamingWorkspace",2);y([v()],m.prototype,"renameWorkspaceName",2);y([v()],m.prototype,"debugLoading",2);y([v()],m.prototype,"debugStatus",2);y([v()],m.prototype,"debugHealth",2);y([v()],m.prototype,"debugModels",2);y([v()],m.prototype,"debugHeartbeat",2);y([v()],m.prototype,"debugCallMethod",2);y([v()],m.prototype,"debugCallParams",2);y([v()],m.prototype,"debugCallResult",2);y([v()],m.prototype,"debugCallError",2);y([v()],m.prototype,"logsLoading",2);y([v()],m.prototype,"logsError",2);y([v()],m.prototype,"logsFile",2);y([v()],m.prototype,"logsEntries",2);y([v()],m.prototype,"logsFilterText",2);y([v()],m.prototype,"logsLevelFilters",2);y([v()],m.prototype,"logsAutoFollow",2);y([v()],m.prototype,"logsTruncated",2);y([v()],m.prototype,"logsCursor",2);y([v()],m.prototype,"logsLastFetchAt",2);y([v()],m.prototype,"logsLimit",2);y([v()],m.prototype,"logsMaxBytes",2);y([v()],m.prototype,"logsAtBottom",2);y([v()],m.prototype,"logsSubTab",2);y([v()],m.prototype,"logsChipsExpanded",2);y([v()],m.prototype,"sessionLogsLoading",2);y([v()],m.prototype,"sessionLogsError",2);y([v()],m.prototype,"sessionLogsEntries",2);y([v()],m.prototype,"sessionLogsFilterText",2);y([v()],m.prototype,"sessionLogsTypeFilters",2);y([v()],m.prototype,"sessionLogsAgentFilters",2);y([v()],m.prototype,"sessionLogsAgents",2);y([v()],m.prototype,"sessionLogsAutoFollow",2);y([v()],m.prototype,"sessionLogsChipsExpanded",2);y([v()],m.prototype,"sessionLogsCursors",2);y([v()],m.prototype,"sessionLogsLastFetchAt",2);y([v()],m.prototype,"sessionLogsAtBottom",2);y([v()],m.prototype,"chatUserNearBottom",2);m=y([Wl("taskmaster-app")],m);
4554
+ //# sourceMappingURL=index-4h8fLLNN.js.map