@rubytech/taskmaster 1.0.94 → 1.0.96

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.
Files changed (45) hide show
  1. package/dist/agents/taskmaster-tools.js +4 -4
  2. package/dist/agents/tool-policy.js +2 -2
  3. package/dist/agents/tools/contact-lookup-tool.js +45 -0
  4. package/dist/agents/tools/contact-update-tool.js +68 -0
  5. package/dist/agents/tools/memory-tool.js +10 -3
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli/provision-seed.js +2 -2
  8. package/dist/control-ui/assets/index-6WdtDXJj.css +1 -0
  9. package/dist/control-ui/assets/index-lbNnMWBM.js +3508 -0
  10. package/dist/control-ui/assets/index-lbNnMWBM.js.map +1 -0
  11. package/dist/control-ui/index.html +2 -2
  12. package/dist/gateway/chat-sanitize.js +121 -5
  13. package/dist/gateway/media-http.js +120 -0
  14. package/dist/gateway/protocol/schema/logs-chat.js +4 -0
  15. package/dist/gateway/public-chat-api.js +5 -3
  16. package/dist/gateway/server-http.js +3 -0
  17. package/dist/gateway/server-methods/chat.js +12 -5
  18. package/dist/gateway/server-methods/wifi.js +202 -0
  19. package/dist/gateway/server-methods.js +2 -0
  20. package/dist/infra/heartbeat-infra-alert.js +143 -0
  21. package/dist/infra/heartbeat-runner.js +13 -0
  22. package/dist/memory/manager.js +15 -8
  23. package/extensions/diagnostics-otel/node_modules/.bin/acorn +0 -0
  24. package/extensions/googlechat/node_modules/.bin/taskmaster +0 -0
  25. package/extensions/line/node_modules/.bin/taskmaster +0 -0
  26. package/extensions/matrix/node_modules/.bin/markdown-it +0 -0
  27. package/extensions/matrix/node_modules/.bin/taskmaster +0 -0
  28. package/extensions/memory-lancedb/node_modules/.bin/arrow2csv +0 -0
  29. package/extensions/memory-lancedb/node_modules/.bin/openai +0 -0
  30. package/extensions/msteams/node_modules/.bin/taskmaster +0 -0
  31. package/extensions/nostr/node_modules/.bin/taskmaster +0 -0
  32. package/extensions/nostr/node_modules/.bin/tsc +0 -0
  33. package/extensions/nostr/node_modules/.bin/tsserver +0 -0
  34. package/extensions/zalo/node_modules/.bin/taskmaster +0 -0
  35. package/extensions/zalouser/node_modules/.bin/taskmaster +0 -0
  36. package/package.json +64 -54
  37. package/scripts/install.sh +0 -0
  38. package/taskmaster-docs/USER-GUIDE.md +1 -1
  39. package/dist/control-ui/assets/index-B7exVNNa.css +0 -1
  40. package/dist/control-ui/assets/index-DfQL37PU.js +0 -3379
  41. package/dist/control-ui/assets/index-DfQL37PU.js.map +0 -1
  42. package/templates/.DS_Store +0 -0
  43. package/templates/customer/.DS_Store +0 -0
  44. package/templates/customer/agents/.DS_Store +0 -0
  45. package/templates/taskmaster/.gitignore +0 -1
@@ -0,0 +1,3508 @@
1
+ var Bu=Object.defineProperty;var Fu=(e,t,n)=>t in e?Bu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var U=(e,t,n)=>Fu(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const r of o.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&i(r)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const Uu="modulepreload",Wu=function(e,t){return new URL(e,t).href},cr={},ie=function(t,n,i){let s=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const r=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),u=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));s=c(n.map(l=>{if(l=Wu(l,i),l in cr)return;cr[l]=!0;const d=l.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(i)for(let f=r.length-1;f>=0;f--){const b=r[f];if(b.href===l&&(!d||b.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${h}`))return;const v=document.createElement("link");if(v.rel=d?"stylesheet":Uu,d||(v.as="script"),v.crossOrigin="",v.href=l,u&&v.setAttribute("nonce",u),document.head.appendChild(v),d)return new Promise((f,b)=>{v.addEventListener("load",f),v.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return s.then(r=>{for(const a of r||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};const Vn=globalThis,Zs=Vn.ShadowRoot&&(Vn.ShadyCSS===void 0||Vn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Js=Symbol(),ur=new WeakMap;let tl=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==Js)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(Zs&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=ur.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&ur.set(n,t))}return t}toString(){return this.cssText}};const Ku=e=>new tl(typeof e=="string"?e:e+"",void 0,Js),zu=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((i,s,o)=>i+(r=>{if(r._$cssResult$===!0)return r.cssText;if(typeof r=="number")return r;throw Error("Value passed to 'css' function must be a 'css' function result: "+r+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[o+1],e[0]);return new tl(n,e,Js)},ju=(e,t)=>{if(Zs)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=Vn.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},dr=Zs?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return Ku(n)})(e):e;const{is:Hu,defineProperty:qu,getOwnPropertyDescriptor:Vu,getOwnPropertyNames:Gu,getOwnPropertySymbols:Qu,getPrototypeOf:Yu}=Object,Ve=globalThis,pr=Ve.trustedTypes,Xu=pr?pr.emptyScript:"",ji=Ve.reactiveElementPolyfillSupport,tn=(e,t)=>e,Zn={toAttribute(e,t){switch(t){case Boolean:e=e?Xu: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}},eo=(e,t)=>!Hu(e,t),hr={attribute:!0,type:String,converter:Zn,reflect:!1,useDefault:!1,hasChanged:eo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ve.litPropertyMetadata??(Ve.litPropertyMetadata=new WeakMap);let Tt=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=hr){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}=Vu(this.prototype,t)??{get(){return this[n]},set(r){this[n]=r}};return{get:s,set(r){const a=s==null?void 0:s.call(this);o==null||o.call(this,r),this.requestUpdate(t,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??hr}static _$Ei(){if(this.hasOwnProperty(tn("elementProperties")))return;const t=Yu(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(tn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(tn("properties"))){const n=this.properties,i=[...Gu(n),...Qu(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(dr(s))}else t!==void 0&&n.push(dr(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 ju(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$EO)==null||t.forEach(n=>{var i;return(i=n.hostConnected)==null?void 0:i.call(n)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$EO)==null||t.forEach(n=>{var i;return(i=n.hostDisconnected)==null?void 0:i.call(n)})}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){var o;const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const r=(((o=i.converter)==null?void 0:o.toAttribute)!==void 0?i.converter:Zn).toAttribute(n,i.type);this._$Em=t,r==null?this.removeAttribute(s):this.setAttribute(s,r),this._$Em=null}}_$AK(t,n){var o,r;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),u=typeof a.converter=="function"?{fromAttribute:a.converter}:((o=a.converter)==null?void 0:o.fromAttribute)!==void 0?a.converter:Zn;this._$Em=s;const c=u.fromAttribute(n,a.type);this[s]=c??((r=this._$Ej)==null?void 0:r.get(s))??c,this._$Em=null}}requestUpdate(t,n,i,s=!1,o){var r;if(t!==void 0){const a=this.constructor;if(s===!1&&(o=this[t]),i??(i=a.getPropertyOptions(t)),!((i.hasChanged??eo)(o,n)||i.useDefault&&i.reflect&&o===((r=this._$Ej)==null?void 0:r.get(t))&&!this.hasAttribute(a._$Eu(t,i))))return;this.C(t,n,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,n,{useDefault:i,reflect:s,wrapped:o},r){i&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,r??n??this[t]),o!==!0||r!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(n=void 0),this._$AL.set(t,n)),s===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(n){Promise.reject(n)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:a}=r,u=this[o];a!==!0||this._$AL.has(o)||u===void 0||this.C(o,void 0,r,u)}}let t=!1;const n=this._$AL;try{t=this.shouldUpdate(n),t?(this.willUpdate(n),(i=this._$EO)==null||i.forEach(s=>{var o;return(o=s.hostUpdate)==null?void 0:o.call(s)}),this.update(n)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(n)}willUpdate(t){}_$AE(t){var n;(n=this._$EO)==null||n.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach(n=>this._$ET(n,this[n]))),this._$EM()}updated(t){}firstUpdated(t){}};Tt.elementStyles=[],Tt.shadowRootOptions={mode:"open"},Tt[tn("elementProperties")]=new Map,Tt[tn("finalized")]=new Map,ji==null||ji({ReactiveElement:Tt}),(Ve.reactiveElementVersions??(Ve.reactiveElementVersions=[])).push("2.1.2");const nn=globalThis,fr=e=>e,Jn=nn.trustedTypes,gr=Jn?Jn.createPolicy("lit-html",{createHTML:e=>e}):void 0,nl="$lit$",qe=`lit$${Math.random().toFixed(9).slice(2)}$`,il="?"+qe,Zu=`<${il}>`,lt=document,dn=()=>lt.createComment(""),pn=e=>e===null||typeof e!="object"&&typeof e!="function",to=Array.isArray,Ju=e=>to(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Hi=`[
2
+ \f\r]`,zt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,mr=/-->/g,yr=/>/g,nt=RegExp(`>|${Hi}(?:([^\\s"'>=/]+)(${Hi}*=${Hi}*(?:[^
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),vr=/'/g,br=/"/g,sl=/^(?:script|style|textarea|title)$/i,ed=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),p=ed(1),Qe=Symbol.for("lit-noChange"),k=Symbol.for("lit-nothing"),wr=new WeakMap,ot=lt.createTreeWalker(lt,129);function ol(e,t){if(!to(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return gr!==void 0?gr.createHTML(t):t}const td=(e,t)=>{const n=e.length-1,i=[];let s,o=t===2?"<svg>":t===3?"<math>":"",r=zt;for(let a=0;a<n;a++){const u=e[a];let c,l,d=-1,h=0;for(;h<u.length&&(r.lastIndex=h,l=r.exec(u),l!==null);)h=r.lastIndex,r===zt?l[1]==="!--"?r=mr:l[1]!==void 0?r=yr:l[2]!==void 0?(sl.test(l[2])&&(s=RegExp("</"+l[2],"g")),r=nt):l[3]!==void 0&&(r=nt):r===nt?l[0]===">"?(r=s??zt,d=-1):l[1]===void 0?d=-2:(d=r.lastIndex-l[2].length,c=l[1],r=l[3]===void 0?nt:l[3]==='"'?br:vr):r===br||r===vr?r=nt:r===mr||r===yr?r=zt:(r=nt,s=void 0);const v=r===nt&&e[a+1].startsWith("/>")?" ":"";o+=r===zt?u+Zu:d>=0?(i.push(c),u.slice(0,d)+nl+u.slice(d)+qe+v):u+qe+(d===-2?a:v)}return[ol(e,o+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};let $s=class rl{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let o=0,r=0;const a=t.length-1,u=this.parts,[c,l]=td(t,n);if(this.el=rl.createElement(c,i),ot.currentNode=this.el.content,n===2||n===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=ot.nextNode())!==null&&u.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const d of s.getAttributeNames())if(d.endsWith(nl)){const h=l[r++],v=s.getAttribute(d).split(qe),f=/([.?@])?(.*)/.exec(h);u.push({type:1,index:o,name:f[2],strings:v,ctor:f[1]==="."?id:f[1]==="?"?sd:f[1]==="@"?od:wi}),s.removeAttribute(d)}else d.startsWith(qe)&&(u.push({type:6,index:o}),s.removeAttribute(d));if(sl.test(s.tagName)){const d=s.textContent.split(qe),h=d.length-1;if(h>0){s.textContent=Jn?Jn.emptyScript:"";for(let v=0;v<h;v++)s.append(d[v],dn()),ot.nextNode(),u.push({type:2,index:++o});s.append(d[h],dn())}}}else if(s.nodeType===8)if(s.data===il)u.push({type:2,index:o});else{let d=-1;for(;(d=s.data.indexOf(qe,d+1))!==-1;)u.push({type:7,index:o}),d+=qe.length-1}o++}}static createElement(t,n){const i=lt.createElement("template");return i.innerHTML=t,i}};function Lt(e,t,n=e,i){var r,a;if(t===Qe)return t;let s=i!==void 0?(r=n._$Co)==null?void 0:r[i]:n._$Cl;const o=pn(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==o&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),o===void 0?s=void 0:(s=new o(e),s._$AT(e,n,i)),i!==void 0?(n._$Co??(n._$Co=[]))[i]=s:n._$Cl=s),s!==void 0&&(t=Lt(e,s._$AS(e,t.values),s,i)),t}class nd{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)??lt).importNode(n,!0);ot.currentNode=s;let o=ot.nextNode(),r=0,a=0,u=i[0];for(;u!==void 0;){if(r===u.index){let c;u.type===2?c=new bi(o,o.nextSibling,this,t):u.type===1?c=new u.ctor(o,u.name,u.strings,this,t):u.type===6&&(c=new rd(o,this,t)),this._$AV.push(c),u=i[++a]}r!==(u==null?void 0:u.index)&&(o=ot.nextNode(),r++)}return ot.currentNode=lt,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 bi=class al{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=k,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=Lt(this,t,n),pn(t)?t===k||t==null||t===""?(this._$AH!==k&&this._$AR(),this._$AH=k):t!==this._$AH&&t!==Qe&&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!==k&&pn(this._$AH)?this._$AA.nextSibling.data=t:this.T(lt.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=$s.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 r=new nd(s,this),a=r.u(this.options);r.p(n),this.T(a),this._$AH=r}}_$AC(t){let n=wr.get(t.strings);return n===void 0&&wr.set(t.strings,n=new $s(t)),n}k(t){to(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 al(this.O(dn()),this.O(dn()),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=fr(t).nextSibling;fr(t).remove(),t=s}}setConnected(t){var n;this._$AM===void 0&&(this._$Cv=t,(n=this._$AP)==null||n.call(this,t))}};class wi{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,s,o){this.type=1,this._$AH=k,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=k}_$AI(t,n=this,i,s){const o=this.strings;let r=!1;if(o===void 0)t=Lt(this,t,n,0),r=!pn(t)||t!==this._$AH&&t!==Qe,r&&(this._$AH=t);else{const a=t;let u,c;for(t=o[0],u=0;u<o.length-1;u++)c=Lt(this,a[i+u],n,u),c===Qe&&(c=this._$AH[u]),r||(r=!pn(c)||c!==this._$AH[u]),c===k?t=k:t!==k&&(t+=(c??"")+o[u+1]),this._$AH[u]=c}r&&!s&&this.j(t)}j(t){t===k?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}let id=class extends wi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===k?void 0:t}},sd=class extends wi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==k)}},od=class extends wi{constructor(t,n,i,s,o){super(t,n,i,s,o),this.type=5}_$AI(t,n=this){if((t=Lt(this,t,n,0)??k)===Qe)return;const i=this._$AH,s=t===k&&i!==k||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==k&&(i===k||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)}},rd=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){Lt(this,t)}};const ad={I:bi},qi=nn.litHtmlPolyfillSupport;qi==null||qi($s,bi),(nn.litHtmlVersions??(nn.litHtmlVersions=[])).push("3.3.2");const ld=(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 bi(t.insertBefore(dn(),o),o,void 0,n??{})}return s._$AI(e),s};const at=globalThis;let _t=class extends Tt{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=ld(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 Qe}};var el;_t._$litElement$=!0,_t.finalized=!0,(el=at.litElementHydrateSupport)==null||el.call(at,{LitElement:_t});const Vi=at.litElementPolyfillSupport;Vi==null||Vi({LitElement:_t});(at.litElementVersions??(at.litElementVersions=[])).push("4.2.2");const ll=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const cd={attribute:!0,type:String,converter:Zn,reflect:!1,hasChanged:eo},ud=(e=cd,t,n)=>{const{kind:i,metadata:s}=n;let o=globalThis.litPropertyMetadata.get(s);if(o===void 0&&globalThis.litPropertyMetadata.set(s,o=new Map),i==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(n.name,e),i==="accessor"){const{name:r}=n;return{set(a){const u=t.get.call(this);t.set.call(this,a),this.requestUpdate(r,u,e,!0,a)},init(a){return a!==void 0&&this.C(r,void 0,e,a),a}}}if(i==="setter"){const{name:r}=n;return function(a){const u=this[r];t.call(this,a),this.requestUpdate(r,u,e,!0,a)}}throw Error("Unsupported decorator location: "+i)};function ki(e){return(t,n)=>typeof n=="object"?ud(e,t,n):((i,s,o)=>{const r=s.hasOwnProperty(o);return s.constructor.createProperty(o,i),r?Object.getOwnPropertyDescriptor(s,o):void 0})(e,t,n)}function y(e){return ki({...e,state:!0,attribute:!1})}const dd=50,pd=200,hd="Assistant";function kr(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function Es(e){const t=kr(e==null?void 0:e.name,dd)??hd,n=kr((e==null?void 0:e.avatar)??void 0,pd)??null;return{agentId:typeof(e==null?void 0:e.agentId)=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function fd(){return Es(typeof window>"u"?{}:{name:window.__TASKMASTER_ASSISTANT_NAME__,avatar:window.__TASKMASTER_ASSISTANT_AVATAR__})}const ei="taskmaster.control.settings.v1",cl="taskmaster.account.settings.";function sn(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}`}const Et={gatewayUrl:sn(),token:"",theme:"system",navCollapsed:!1,navGroupsCollapsed:{}},He={sessionKey:"main",lastActiveSessionKey:"main",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6};function gd(){try{const e=localStorage.getItem(ei);if(!e)return{...Et,gatewayUrl:sn()};const t=JSON.parse(e);return{gatewayUrl:typeof t.gatewayUrl=="string"&&t.gatewayUrl.trim()?t.gatewayUrl.trim():sn(),token:typeof t.token=="string"?t.token:Et.token,theme:t.theme==="light"||t.theme==="dark"||t.theme==="system"?t.theme:Et.theme,navCollapsed:typeof t.navCollapsed=="boolean"?t.navCollapsed:Et.navCollapsed,navGroupsCollapsed:typeof t.navGroupsCollapsed=="object"&&t.navGroupsCollapsed!==null?t.navGroupsCollapsed:Et.navGroupsCollapsed}}catch{return{...Et,gatewayUrl:sn()}}}function md(e){if(!e)return{...He};try{const t=localStorage.getItem(cl+e);if(!t)return{...He};const n=JSON.parse(t);return{sessionKey:typeof n.sessionKey=="string"&&n.sessionKey.trim()?n.sessionKey.trim():He.sessionKey,lastActiveSessionKey:typeof n.lastActiveSessionKey=="string"&&n.lastActiveSessionKey.trim()?n.lastActiveSessionKey.trim():typeof n.sessionKey=="string"&&n.sessionKey.trim()||He.lastActiveSessionKey,chatFocusMode:typeof n.chatFocusMode=="boolean"?n.chatFocusMode:He.chatFocusMode,chatShowThinking:typeof n.chatShowThinking=="boolean"?n.chatShowThinking:He.chatShowThinking,splitRatio:typeof n.splitRatio=="number"&&n.splitRatio>=.4&&n.splitRatio<=.7?n.splitRatio:He.splitRatio}}catch{return{...He}}}let ti=null;function Sr(e){ti=e}function Gi(){return{...gd(),...md(ti)}}function yd(e){const t={gatewayUrl:e.gatewayUrl,token:e.token,theme:e.theme,navCollapsed:e.navCollapsed,navGroupsCollapsed:e.navGroupsCollapsed};if(localStorage.setItem(ei,JSON.stringify(t)),ti){const n={sessionKey:e.sessionKey,lastActiveSessionKey:e.lastActiveSessionKey,chatFocusMode:e.chatFocusMode,chatShowThinking:e.chatShowThinking,splitRatio:e.splitRatio};localStorage.setItem(cl+ti,JSON.stringify(n))}}(function(){try{const t=localStorage.getItem(ei);if(!t)return;const n=JSON.parse(t);if(!("sessionKey"in n))return;const i={gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:sn(),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(ei,JSON.stringify(i))}catch{}})();function ul(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 vd=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,Ln=/<\s*\/?\s*final\b[^>]*>/gi,xr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function bd(e,t){return e.trimStart()}function wd(e,t){if(!e||!vd.test(e))return e;let n=e;Ln.test(n)?(Ln.lastIndex=0,n=n.replace(Ln,"")):Ln.lastIndex=0,xr.lastIndex=0;let i="",s=0,o=!1;for(const r of n.matchAll(xr)){const a=r.index??0,u=r[1]==="/";o?u&&(o=!1):(i+=n.slice(s,a),u||(o=!0)),s=a+r[0].length}return i+=n.slice(s),bd(i)}function dl(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function Si(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0){const r=-t,a=Math.round(r/1e3);if(a<60)return`in ${a}s`;const u=Math.round(a/60);if(u<60)return`in ${u}m`;const c=Math.round(u/60);return c<48?`in ${c}h`:`in ${Math.round(c/24)}d`}const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const i=Math.round(n/60);if(i<60)return`${i}m ago`;const s=Math.round(i/60);return s<48?`${s}h ago`:`${Math.round(s/24)}d ago`}function pl(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 kd(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function hl(e,t){return e.length<=t?{text:e,truncated:!1,total:e.length}:{text:e.slice(0,Math.max(0,t)),truncated:!0,total:e.length}}function ni(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Qi(e){return wd(e)}const Sd=/^\[([^\]]+)\]\s*/,xd=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Yi=new WeakMap,Xi=new WeakMap;function Ad(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:xd.some(t=>e.startsWith(`${t} `))}function Zi(e){const t=e.match(Sd);if(!t)return e;const n=t[1]??"";return Ad(n)?e.slice(t[0].length):e}function on(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?Qi(i):Zi(i);if(Array.isArray(i)){const s=i.map(o=>{const r=o;return r.type==="text"&&typeof r.text=="string"?r.text:null}).filter(o=>typeof o=="string");if(s.length>0){const o=s.join(`
4
+ `);return n==="assistant"?Qi(o):Zi(o)}}return typeof t.text=="string"?n==="assistant"?Qi(t.text):Zi(t.text):null}function fl(e){if(!e||typeof e!="object")return on(e);const t=e;if(Yi.has(t))return Yi.get(t)??null;const n=on(e);return Yi.set(t,n),n}function Ar(e){const n=e.content,i=[];if(Array.isArray(n))for(const a of n){const u=a;if(u.type==="thinking"&&typeof u.thinking=="string"){const c=u.thinking.trim();c&&i.push(c)}}if(i.length>0)return i.join(`
5
+ `);const s=Ed(e);if(!s)return null;const r=[...s.matchAll(/<\s*think(?:ing)?\s*>([\s\S]*?)<\s*\/\s*think(?:ing)?\s*>/gi)].map(a=>(a[1]??"").trim()).filter(Boolean);return r.length>0?r.join(`
6
+ `):null}function $d(e){if(!e||typeof e!="object")return Ar(e);const t=e;if(Xi.has(t))return Xi.get(t)??null;const n=Ar(e);return Xi.set(t,n),n}function Ed(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 Td(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 Cd=/Read HEARTBEAT\.md if it exists|reply HEARTBEAT_OK/i,_d=/^[\s*`_]*HEARTBEAT_OK[\s*`_]*$/i,Md=/^[\s*`_]*NO_REPLY[\s*`_]*$/i,Pd=/^A new session was started via \/new or \/reset\./;function Ld(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"&&Cd.test(s)||n==="assistant"&&_d.test(s)||n==="user"&&Pd.test(s)||n==="assistant"&&Md.test(s)):!1}function gl(e){return e.filter(t=>!Ld(t))}function ml(e){const t=e;let n=typeof t.role=="string"?t.role:"unknown";const i=typeof t.toolCallId=="string"||typeof t.tool_call_id=="string",s=t.content,o=Array.isArray(s)?s:null,r=Array.isArray(o)&&o.some(d=>{const v=String(d.type??"").toLowerCase();return v==="toolresult"||v==="tool_result"}),a=typeof t.toolName=="string"||typeof t.tool_name=="string";(i||r||a)&&(n="toolResult");let u=[];typeof t.content=="string"?u=[{type:"text",text:t.content}]:Array.isArray(t.content)?u=t.content.map(d=>({type:d.type||"text",text:d.text,name:d.name,args:d.args||d.arguments})):typeof t.text=="string"&&(u=[{type:"text",text:t.text}]);const c=typeof t.timestamp=="number"?t.timestamp:Date.now(),l=typeof t.id=="string"?t.id:void 0;return{role:n,content:u,timestamp:c,id:l}}function 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 vl(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function $r(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Id(){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 no(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(e&&typeof e.getRandomValues=="function"){const t=new Uint8Array(16);return e.getRandomValues(t),$r(t)}return $r(Id())}const Pe=50;async function Me(e,t){if(!e.client||!e.connected)return;e.chatLoading=!0,e.lastError=null;const n=(t==null?void 0:t.limit)??Pe;try{const i=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:n}),s=Array.isArray(i.messages)?i.messages:[],o=typeof i.totalMessages=="number"?i.totalMessages:s.length,r=gl(s);e.chatMessages=r,e.chatHistoryTotal=o,e.chatHistoryHasMore=o>s.length,e.chatThinkingLevel=i.thinkingLevel??null,e.chatModelProvider=typeof i.modelProvider=="string"?i.modelProvider:null,e.chatModel=typeof i.model=="string"?i.model:null,e.chatVerboseLevel=typeof i.verboseLevel=="string"?i.verboseLevel:null,e.chatFillerEnabled=typeof i.fillerEnabled=="boolean"?i.fillerEnabled:null}catch(i){e.lastError=String(i)}finally{e.chatLoading=!1}}async function Rd(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:Pe,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=gl(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 Nd(e){const t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function bl(e,t,n){if(e.chatSuggestion=null,!e.client||!e.connected)return!1;const i=t.trim(),s=n&&n.length>0;if(!i&&!s)return!1;const o=Date.now(),r=(n??[]).filter(v=>!v.fileName),a=(n??[]).filter(v=>v.fileName),u=[],c=a.map(v=>v.fileName).filter(Boolean);if(c.length>0){const v=i?`${c.join(", ")}
9
+
10
+ ${i}`:c.join(", ");u.push({type:"text",text:v})}else i&&u.push({type:"text",text:i});for(const v of r)u.push({type:"image",source:{type:"base64",media_type:v.mimeType,data:v.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:u,timestamp:o}],e.chatSending=!0,e.lastError=null;const l=no();e.chatRunId=l,e.chatStream="",e.chatStreamStartedAt=o;const d=[...r,...a],h=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 f=Nd(v.dataUrl);return f?{type:v.fileName?"document":"image",mimeType:f.mimeType,fileName:v.fileName,content:f.content}:null}).filter(v=>v!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:l,attachments:h}),!0}catch(v){const f=String(v);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=f,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+f}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function wl(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 kl(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=on(t.message))==null?void 0:n.trim():void 0)||((i=e.chatStream)==null?void 0:i.trim());return o&&(e.chatInterimText=e.chatInterimText?`${e.chatInterimText}
11
+
12
+ ${o}`:o),e.chatStream="","working"}else if(t.state==="block"){const s=on(t.message);return typeof s=="string"&&s.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:s.trim()}],timestamp:Date.now(),filler:!0}]),"block"}else if(t.state==="delta"){e.chatSuggestion=null;const s=on(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 ii=Object.freeze(Object.defineProperty({__proto__:null,CHAT_PAGE_SIZE:Pe,abortChatRun:wl,handleChatEvent:kl,loadChatHistory:Me,loadOlderChatHistory:Rd,sendChatMessage:bl},Symbol.toStringTag,{value:"Module"}));async function io(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:e.sessionsIncludeGlobal??!0,includeUnknown:e.sessionsIncludeUnknown??!1},n=ni(e.sessionsFilterActive??"",0),i=ni(e.sessionsFilterLimit??"",0);n>0&&(t.activeMinutes=n),i>0&&(t.limit=i);const s=await e.client.request("sessions.list",t);s&&(e.sessionsResult=s)}catch(t){e.sessionsError=String(t)}finally{e.sessionsLoading=!1}}}async function In(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 io(e)}catch(s){e.sessionsError=String(s)}}const Er=50,Dd=80,Od=12e4;function Bd(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 Tr(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=Bd(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=hl(n,Od);return i.truncated?`${i.text}
14
+
15
+ … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function Fd(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 Ud(e){if(e.toolStreamOrder.length<=Er)return;const t=e.toolStreamOrder.length-Er,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function Wd(e){e.chatToolMessages=e.toolStreamOrder.map(t=>{var n;return(n=e.toolStreamById.get(t))==null?void 0:n.message}).filter(t=>!!t)}function Ts(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Wd(e)}function Kd(e,t=!1){if(t){Ts(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>Ts(e),Dd))}function so(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],Ts(e)}const zd=5e3;function jd(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},zd))}function Hd(e,t){if(!t)return;if(t.stream==="compaction"){jd(e,t);return}if(t.stream!=="tool")return;const n=typeof t.sessionKey=="string"?t.sessionKey:void 0;if(n&&n!==e.sessionKey||!n&&e.chatRunId&&t.runId!==e.chatRunId||e.chatRunId&&t.runId!==e.chatRunId||!e.chatRunId)return;const i=t.data??{},s=typeof i.toolCallId=="string"?i.toolCallId:"";if(!s)return;const o=typeof i.name=="string"?i.name:"tool",r=typeof i.phase=="string"?i.phase:"",a=r==="start"?i.args:void 0,u=r==="update"?Tr(i.partialResult):r==="result"?Tr(i.result):void 0,c=Date.now();let l=e.toolStreamById.get(s);l?(l.name=o,a!==void 0&&(l.args=a),u!==void 0&&(l.output=u),l.updatedAt=c):(l={toolCallId:s,runId:t.runId,sessionKey:n,name:o,args:a,output:u,startedAt:typeof t.ts=="number"?t.ts:c,updatedAt:c,message:{}},e.toolStreamById.set(s,l),e.toolStreamOrder.push(s)),l.message=Fd(l),Ud(e),Kd(e,r==="result")}function gn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=()=>{const i=e.querySelector(".chat-thread");if(i){const s=getComputedStyle(i).overflowY;if(s==="auto"||s==="scroll"||i.scrollHeight-i.clientHeight>1)return i}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{e.chatScrollFrame=requestAnimationFrame(()=>{e.chatScrollFrame=null;const i=n();if(!i)return;const s=i.scrollHeight-i.scrollTop-i.clientHeight;if(!(t||e.chatUserNearBottom||s<200))return;t&&(e.chatHasAutoScrolled=!0),i.scrollTop=i.scrollHeight,e.chatUserNearBottom=!0;const r=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{e.chatScrollTimeout=null;const a=n();if(!a)return;const u=a.scrollHeight-a.scrollTop-a.clientHeight;(t||e.chatUserNearBottom||u<200)&&(a.scrollTop=a.scrollHeight,e.chatUserNearBottom=!0)},r)})})}function Sl(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 qd(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 Vd(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 Gd(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Qd(e,t){const n=t.currentTarget;n&&(e.logsAtBottom=n.scrollTop<80)}function Yd(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function Xd(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
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 Zd(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
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 Jd(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 Ye(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function ct(e){return`${JSON.stringify(e,null,2).trimEnd()}
20
+ `}function xl(e,t,n){if(t.length===0)return;let i=e;for(let o=0;o<t.length-1;o+=1){const r=t[o],a=t[o+1];if(typeof r=="number"){if(!Array.isArray(i))return;i[r]==null&&(i[r]=typeof a=="number"?[]:{}),i=i[r]}else{if(typeof i!="object"||i==null)return;const u=i;u[r]==null&&(u[r]=typeof a=="number"?[]:{}),i=u[r]}}const s=t[t.length-1];if(typeof s=="number"){Array.isArray(i)&&(i[s]=n);return}typeof i=="object"&&i!=null&&(i[s]=n)}async function Le(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});tp(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function Al(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});ep(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function ep(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function tp(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=Ye(t.config??{}),e.configFormOriginal=Ye(t.config??{}),e.configRawOriginal=n)}async function np(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 Le(e)}catch(n){e.lastError=String(n)}finally{e.configSaving=!1}}}async function mn(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 xi(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 ip(e){if(e.scheduleKind==="at"){const n=Date.parse(e.scheduleAt);if(!Number.isFinite(n))throw new Error("Invalid run time.");return{kind:"at",atMs:n}}if(e.scheduleKind==="every"){const n=ni(e.everyAmount,0);if(n<=0)throw new Error("Invalid interval amount.");const i=e.everyUnit;return{kind:"every",everyMs:n*(i==="minutes"?6e4:i==="hours"?36e5:864e5)}}const t=e.cronExpr.trim();if(!t)throw new Error("Cron expression required.");return{kind:"cron",expr:t,tz:e.cronTz.trim()||void 0}}function sp(e){if(e.payloadKind==="systemEvent"){const s=e.payloadText.trim();if(!s)throw new Error("System event text required.");return{kind:"systemEvent",text:s}}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),e.to.trim()&&(n.to=e.to.trim());const i=ni(e.timeoutSeconds,0);return i>0&&(n.timeoutSeconds=i),n}async function op(e){var t;if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const n=ip(e.cronForm),i=sp(e.cronForm),s=e.cronForm.agentId.trim(),o=(t=e.cronForm.accountId)==null?void 0:t.trim(),r={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,accountId:o||void 0,enabled:e.cronForm.enabled,schedule:n,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:i,isolation:e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?{postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:void 0};if(!r.name)throw new Error("Name required.");await e.client.request("cron.add",r),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await xi(e),await mn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function rp(e,t,n){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.update",{id:t.id,patch:{enabled:n}}),await xi(e),await mn(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function ap(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.run",{id:t.id,mode:"force"}),await Cs(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function lp(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 xi(e),await mn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Cs(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("cron.runs",{id:t,limit:50});e.cronRunsJobId=t,e.cronRuns=Array.isArray(n.entries)?n.entries:[]}catch(n){e.cronError=String(n)}}async function G(e,t){if(!(!e.client||!e.connected)&&!e.channelsLoading){e.channelsLoading=!0,e.channelsError=null;try{const n=await e.client.request("channels.status",{probe:t,timeoutMs:8e3});e.channelsSnapshot=n,e.channelsLastSuccess=Date.now()}catch(n){e.channelsError=String(n)}finally{e.channelsLoading=!1}}}async function oo(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 $l(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 El(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 Tl(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=Ye(s.config??{});(!o.channels||typeof o.channels!="object")&&(o.channels={});const r=o.channels;(!r.whatsapp||typeof r.whatsapp!="object")&&(r.whatsapp={});const a=r.whatsapp;(!a.accounts||typeof a.accounts!="object")&&(a.accounts={});const u=a.accounts;if(u[i]){e.whatsappAccountError=`Account "${i}" already exists.`;return}u[i]={name:n,provider:"baileys"};const c=s.hash;if(!c){e.whatsappAccountError="Config hash missing; reload and retry.";return}const l=ct(o);await e.client.request("config.set",{raw:l,baseHash:c}),e.addingWhatsAppAccount=!1,e.newWhatsAppAccountName="",await G(e,!0),await oo(e,!0,i)}catch(s){e.whatsappAccountError=String(s)}finally{e.whatsappAccountSaving=!1}}async function Cl(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=Ye(n.config??{}),s=i.channels,o=s==null?void 0:s.whatsapp,r=o==null?void 0:o.accounts;if(!r){e.whatsappAccountError="No accounts found in config.";return}if(Object.keys(r).length<=1){e.whatsappAccountError="Cannot remove the last account.";return}if(!r[t]){e.whatsappAccountError=`Account "${t}" not found.`;return}try{await e.client.request("channels.logout",{channel:"whatsapp",accountId:t})}catch{}delete r[t],Array.isArray(i.bindings)&&(i.bindings=i.bindings.filter(l=>{const d=l.match;return!d||d.channel!=="whatsapp"?!0:d.accountId!==t}));const u=n.hash;if(!u){e.whatsappAccountError="Config hash missing; reload and retry.";return}const c=ct(i);await e.client.request("config.set",{raw:c,baseHash:u}),e.whatsappActiveQrAccountId===t&&(e.whatsappActiveQrAccountId=null,e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null),await G(e,!0)}catch(n){e.whatsappAccountError=String(n)}finally{e.whatsappAccountSaving=!1}}}const cp=Object.freeze(Object.defineProperty({__proto__:null,addWhatsAppAccount:Tl,loadChannels:G,logoutWhatsApp:El,removeWhatsAppAccount:Cl,startWhatsAppLogin:oo,waitWhatsAppLogin:$l},Symbol.toStringTag,{value:"Module"}));async function ro(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,i,s]=await Promise.all([e.client.request("status",{}),e.client.request("health",{}),e.client.request("models.list",{}),e.client.request("last-heartbeat",{})]);e.debugStatus=t,e.debugHealth=n;const o=i;e.debugModels=Array.isArray(o==null?void 0:o.models)?o==null?void 0:o.models:[],e.debugHeartbeat=s}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}const up=2e3,dp=new Set(["trace","debug","info","warn","error","fatal"]);function pp(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 hp(e){if(typeof e!="string")return null;const t=e.toLowerCase();return dp.has(t)?t:null}function _l(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=hp((n==null?void 0:n.logLevelName)??(n==null?void 0:n.level)),o=typeof t[0]=="string"?t[0]:typeof(n==null?void 0:n.name)=="string"?n==null?void 0:n.name:null,r=pp(o);let a=null;r&&(typeof r.subsystem=="string"?a=r.subsystem:typeof r.module=="string"&&(a=r.module)),!a&&o&&o.length<120&&(a=o);let u=null;return typeof t[1]=="string"?u=t[1]:!r&&typeof t[0]=="string"?u=t[0]:typeof t.message=="string"&&(u=t.message),{raw:e,time:i,level:s,subsystem:a,message:u??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function Mt(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.logsLoading=!0),e.logsError=null;try{const i=await e.client.request("logs.tail",{cursor:t!=null&&t.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),o=(Array.isArray(i.lines)?i.lines.filter(a=>typeof a=="string"):[]).map(_l),r=!!(t!=null&&t.reset||i.reset||e.logsCursor==null);e.logsEntries=r?o:[...e.logsEntries,...o].slice(-up),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t!=null&&t.quiet||(e.logsLoading=!1)}}}const fp=Object.freeze(Object.defineProperty({__proto__:null,loadLogs:Mt,parseLogLine:_l},Symbol.toStringTag,{value:"Module"}));const Ml={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:re,n:Gn,Gx:Cr,Gy:_r,a:Ji,d:es,h:gp}=Ml,ut=32,ao=64,mp=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},te=(e="")=>{const t=new Error(e);throw mp(t,te),t},yp=e=>typeof e=="bigint",vp=e=>typeof e=="string",bp=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",Ze=(e,t,n="")=>{const i=bp(e),s=e==null?void 0:e.length,o=t!==void 0;if(!i||o&&s!==t){const r=n&&`"${n}" `,a=o?` of length ${t}`:"",u=i?`length=${s}`:`type=${typeof e}`;te(r+"expected Uint8Array"+a+", got "+u)}return e},Ai=e=>new Uint8Array(e),Pl=e=>Uint8Array.from(e),Ll=(e,t)=>e.toString(16).padStart(t,"0"),Il=e=>Array.from(Ze(e)).map(t=>Ll(t,2)).join(""),De={_0:48,_9:57,A:65,F:70,a:97,f:102},Mr=e=>{if(e>=De._0&&e<=De._9)return e-De._0;if(e>=De.A&&e<=De.F)return e-(De.A-10);if(e>=De.a&&e<=De.f)return e-(De.a-10)},Rl=e=>{const t="hex invalid";if(!vp(e))return te(t);const n=e.length,i=n/2;if(n%2)return te(t);const s=Ai(i);for(let o=0,r=0;o<i;o++,r+=2){const a=Mr(e.charCodeAt(r)),u=Mr(e.charCodeAt(r+1));if(a===void 0||u===void 0)return te(t);s[o]=a*16+u}return s},Nl=()=>globalThis==null?void 0:globalThis.crypto,wp=()=>{var e;return((e=Nl())==null?void 0:e.subtle)??te("crypto.subtle must be defined, consider polyfill")},hn=(...e)=>{const t=Ai(e.reduce((i,s)=>i+Ze(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},kp=(e=ut)=>Nl().getRandomValues(Ai(e)),si=BigInt,st=(e,t,n,i="bad number: out of range")=>yp(e)&&t<=e&&e<n?e:te(i),P=(e,t=re)=>{const n=e%t;return n>=0n?n:t+n},Dl=e=>P(e,Gn),Sp=(e,t)=>{(e===0n||t<=0n)&&te("no inverse n="+e+" mod="+t);let n=P(e,t),i=t,s=0n,o=1n;for(;n!==0n;){const r=i/n,a=i%n,u=s-o*r;i=n,n=a,s=o,o=u}return i===1n?P(s,t):te("no inverse")},xp=e=>{const t=Ul[e];return typeof t!="function"&&te("hashes."+e+" not set"),t},ts=e=>e instanceof dt?e:te("Point expected"),_s=2n**256n,_e=class _e{constructor(t,n,i,s){U(this,"X");U(this,"Y");U(this,"Z");U(this,"T");const o=_s;this.X=st(t,0n,o),this.Y=st(n,0n,o),this.Z=st(i,1n,o),this.T=st(s,0n,o),Object.freeze(this)}static CURVE(){return Ml}static fromAffine(t){return new _e(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){const i=es,s=Pl(Ze(t,ut)),o=t[31];s[31]=o&-129;const r=Bl(s);st(r,0n,n?_s:re);const u=P(r*r),c=P(u-1n),l=P(i*u+1n);let{isValid:d,value:h}=$p(c,l);d||te("bad point: y not sqrt");const v=(h&1n)===1n,f=(o&128)!==0;return!n&&h===0n&&f&&te("bad point: x==0, isLastByteOdd"),f!==v&&(h=P(-h)),new _e(h,r,1n,P(h*r))}static fromHex(t,n){return _e.fromBytes(Rl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Ji,n=es,i=this;if(i.is0())return te("bad point: ZERO");const{X:s,Y:o,Z:r,T:a}=i,u=P(s*s),c=P(o*o),l=P(r*r),d=P(l*l),h=P(u*t),v=P(l*P(h+c)),f=P(d+P(n*P(u*c)));if(v!==f)return te("bad point: equation left != right (1)");const b=P(s*o),S=P(r*a);return b!==S?te("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:o,Y:r,Z:a}=ts(t),u=P(n*a),c=P(o*s),l=P(i*a),d=P(r*s);return u===c&&l===d}is0(){return this.equals(Ct)}negate(){return new _e(P(-this.X),this.Y,this.Z,P(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=Ji,o=P(t*t),r=P(n*n),a=P(2n*P(i*i)),u=P(s*o),c=t+n,l=P(P(c*c)-o-r),d=u+r,h=d-a,v=u-r,f=P(l*h),b=P(d*v),S=P(l*v),A=P(h*d);return new _e(f,b,A,S)}add(t){const{X:n,Y:i,Z:s,T:o}=this,{X:r,Y:a,Z:u,T:c}=ts(t),l=Ji,d=es,h=P(n*r),v=P(i*a),f=P(o*d*c),b=P(s*u),S=P((n+i)*(r+a)-h-v),A=P(b-f),$=P(b+f),T=P(v-l*h),C=P(S*A),M=P($*T),R=P(S*T),B=P(A*$);return new _e(C,M,B,R)}subtract(t){return this.add(ts(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return Ct;if(st(t,1n,Gn),t===1n)return this;if(this.equals(pt))return Dp(t).p;let i=Ct,s=pt;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(Ct))return{x:0n,y:1n};const s=Sp(i,re);P(i*s)!==1n&&te("invalid inverse");const o=P(t*s),r=P(n*s);return{x:o,y:r}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=Ol(n);return i[31]|=t&1n?128:0,i}toHex(){return Il(this.toBytes())}clearCofactor(){return this.multiply(si(gp),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Gn/2n,!1).double();return Gn%2n&&(t=t.add(this)),t.is0()}};U(_e,"BASE"),U(_e,"ZERO");let dt=_e;const pt=new dt(Cr,_r,1n,P(Cr*_r)),Ct=new dt(0n,1n,1n,0n);dt.BASE=pt;dt.ZERO=Ct;const Ol=e=>Rl(Ll(st(e,0n,_s),ao)).reverse(),Bl=e=>si("0x"+Il(Pl(Ze(e)).reverse())),$e=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=re;return n},Ap=e=>{const n=e*e%re*e%re,i=$e(n,2n)*n%re,s=$e(i,1n)*e%re,o=$e(s,5n)*s%re,r=$e(o,10n)*o%re,a=$e(r,20n)*r%re,u=$e(a,40n)*a%re,c=$e(u,80n)*u%re,l=$e(c,80n)*u%re,d=$e(l,10n)*o%re;return{pow_p_5_8:$e(d,2n)*e%re,b2:n}},Pr=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,$p=(e,t)=>{const n=P(t*t*t),i=P(n*n*t),s=Ap(e*i).pow_p_5_8;let o=P(e*n*s);const r=P(t*o*o),a=o,u=P(o*Pr),c=r===e,l=r===P(-e),d=r===P(-e*Pr);return c&&(o=a),(l||d)&&(o=u),(P(o)&1n)===1n&&(o=P(-o)),{isValid:c||l,value:o}},Ms=e=>Dl(Bl(e)),lo=(...e)=>Ul.sha512Async(hn(...e)),Ep=(...e)=>xp("sha512")(hn(...e)),Fl=e=>{const t=e.slice(0,ut);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(ut,ao),i=Ms(t),s=pt.multiply(i),o=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:o}},co=e=>lo(Ze(e,ut)).then(Fl),Tp=e=>Fl(Ep(Ze(e,ut))),Cp=e=>co(e).then(t=>t.pointBytes),_p=e=>lo(e.hashable).then(e.finish),Mp=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,o=Ms(t),r=pt.multiply(o).toBytes();return{hashable:hn(r,i,n),finish:c=>{const l=Dl(o+Ms(c)*s);return Ze(hn(r,Ol(l)),ao)}}},Pp=async(e,t)=>{const n=Ze(e),i=await co(t),s=await lo(i.prefix,n);return _p(Mp(i,s,n))},Ul={sha512Async:async e=>{const t=wp(),n=hn(e);return Ai(await t.digest("SHA-512",n.buffer))},sha512:void 0},Lp=(e=kp(ut))=>e,Ip={getExtendedPublicKeyAsync:co,getExtendedPublicKey:Tp,randomSecretKey:Lp},oi=8,Rp=256,Wl=Math.ceil(Rp/oi)+1,Ps=2**(oi-1),Np=()=>{const e=[];let t=pt,n=t;for(let i=0;i<Wl;i++){n=t,e.push(n);for(let s=1;s<Ps;s++)n=n.add(t),e.push(n);t=n.double()}return e};let Lr;const Ir=(e,t)=>{const n=t.negate();return e?n:t},Dp=e=>{const t=Lr||(Lr=Np());let n=Ct,i=pt;const s=2**oi,o=s,r=si(s-1),a=si(oi);for(let u=0;u<Wl;u++){let c=Number(e&r);e>>=a,c>Ps&&(c-=o,e+=1n);const l=u*Ps,d=l,h=l+Math.abs(c)-1,v=u%2!==0,f=c<0;c===0?i=i.add(Ir(v,t[d])):n=n.add(Ir(f,t[h]))}return e!==0n&&te("invalid wnaf"),{p:n,f:i}},ns="taskmaster-device-identity-v1";function Ls(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Kl(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 Op(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function zl(e){const t=await crypto.subtle.digest("SHA-256",e);return Op(new Uint8Array(t))}async function Bp(){const e=Ip.randomSecretKey(),t=await Cp(e);return{deviceId:await zl(t),publicKey:Ls(t),privateKey:Ls(e)}}async function Fp(){try{const n=localStorage.getItem(ns);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 zl(Kl(i.publicKey));if(s!==i.deviceId){const o={...i,deviceId:s};return localStorage.setItem(ns,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 Bp(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(ns,JSON.stringify(t)),e}async function Up(e,t){const n=Kl(e),i=new TextEncoder().encode(t),s=await Pp(i,n);return Ls(s)}const jl="taskmaster.device.auth.v1";function uo(e){return e.trim()}function Wp(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 po(){try{const e=window.localStorage.getItem(jl);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 Hl(e){try{window.localStorage.setItem(jl,JSON.stringify(e))}catch{}}function Kp(e){const t=po();if(!t||t.deviceId!==e.deviceId)return null;const n=uo(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function zp(e){const t=uo(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=po();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:Wp(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Hl(n),s}function jp(e){const t=po();if(!t||t.deviceId!==e.deviceId)return;const n=uo(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Hl(i)}async function ho(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 fo(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 Hp(e){return{method:"exec.approvals.get",params:{}}}async function qp(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=Hp(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);Vp(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function Vp(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=Ye(t.file??{}))}async function ql(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 It(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function $i(e){return e instanceof Error?e.message:String(e)}async function ht(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=$i(n)}finally{e.skillsLoading=!1}}}function Vl(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Gl(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 ht(e),It(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=$i(i);e.skillsError=s,It(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Ql(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 ht(e),It(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=$i(n);e.skillsError=i,It(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Yl(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 ht(e),It(e,t,{kind:"success",message:(s==null?void 0:s.message)??"Installed"})}catch(s){const o=$i(s);e.skillsError=o,It(e,t,{kind:"error",message:o})}finally{e.skillsBusyKey=null}}}const Gp=Object.freeze(Object.defineProperty({__proto__:null,installSkill:Yl,loadSkills:ht,saveSkillApiKey:Ql,updateSkillEdit:Vl,updateSkillEnabled:Gl},Symbol.toStringTag,{value:"Module"})),Xl={overview:"/overview",channels:"/channels",instances:"/instances",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",admins:"/admins",config:"/config",debug:"/debug",logs:"/logs"},Zl=new Map(Object.entries(Xl).map(([e,t])=>[t,e]));function Ei(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function fn(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 Qp(e,t=""){const n=Ei(t),i=Xl[e];return n?`${n}${i}`:i}function Jl(e,t=""){const n=Ei(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=fn(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":Zl.get(s)??null}function Yp(e){let t=fn(e);if(t.endsWith("/index.html")&&(t=fn(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(Zl.has(s)){const o=n.slice(0,i);return o.length?`/${o.join("/")}`:""}}return`/${n.join("/")}`}function Xp(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function go(e){return e==="system"?Xp():e}const Rn=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,Zp=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,Nn=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},Jp=({nextTheme:e,applyTheme:t,context:n,currentTheme:i})=>{var c;if(i===e)return;const s=globalThis.document??null;if(!s){t();return}const o=s.documentElement,r=s,a=Zp();if(!!r.startViewTransition&&!a){let l=.5,d=.5;if((n==null?void 0:n.pointerClientX)!==void 0&&(n==null?void 0:n.pointerClientY)!==void 0&&typeof window<"u")l=Rn(n.pointerClientX/window.innerWidth),d=Rn(n.pointerClientY/window.innerHeight);else if(n!=null&&n.element){const h=n.element.getBoundingClientRect();h.width>0&&h.height>0&&typeof window<"u"&&(l=Rn((h.left+h.width/2)/window.innerWidth),d=Rn((h.top+h.height/2)/window.innerHeight))}o.style.setProperty("--theme-switch-x",`${l*100}%`),o.style.setProperty("--theme-switch-y",`${d*100}%`),o.classList.add("theme-transition");try{const h=(c=r.startViewTransition)==null?void 0:c.call(r,()=>{t()});h!=null&&h.finished?h.finished.finally(()=>Nn(o)):Nn(o)}catch{Nn(o),t()}return}t(),Nn(o)},eh=2e3;async function rn(e,t){if(!(!e.client||!e.connected)&&!(e.sessionLogsLoading&&!(t!=null&&t.quiet))){t!=null&&t.quiet||(e.sessionLogsLoading=!0),e.sessionLogsError=null;try{const n={cursors:t!=null&&t.reset?void 0:e.sessionLogsCursors,limit:500};Array.isArray(e.workspaceAgentIds)&&e.workspaceAgentIds.length>0&&(n.agents=e.workspaceAgentIds);const s=await e.client.request("sessions.transcript",n),o=Array.isArray(s.entries)?s.entries:[],r=!!(t!=null&&t.reset||Object.keys(e.sessionLogsCursors).length===0);e.sessionLogsEntries=r?o:[...e.sessionLogsEntries,...o].slice(-eh),s.cursors&&(e.sessionLogsCursors=s.cursors),Array.isArray(s.agents)&&(e.sessionLogsAgents=s.agents),e.sessionLogsLastFetchAt=Date.now()}catch(n){e.sessionLogsError=String(n)}finally{t!=null&&t.quiet||(e.sessionLogsLoading=!1)}}}const ec=Object.freeze(Object.defineProperty({__proto__:null,loadSessionLogs:rn},Symbol.toStringTag,{value:"Module"}));async function tc(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 th(e,t){if(!(!e.client||!e.connected))try{const n={};await e.client.request("memory.auditClear",n),e.auditEntries=[]}catch{}}function Ue(e){return e instanceof Error?e.message:String(e)}let Dn=null;function yn(e,t){Dn&&clearTimeout(Dn),e.filesMessage={kind:"success",text:t},Dn=setTimeout(()=>{e.filesMessage=null,Dn=null},3e3)}async function vn(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=Ue(n)}finally{e.filesLoading=!1}}}}async function nh(e,t,n){e.filesSelectedPaths=new Set([t]),await nc(e,t,n)}async function ih(e,t,n){const i=new Set(e.filesSelectedPaths);if(i.has(t)?i.delete(t):i.add(t),e.filesSelectedPaths=i,i.size===1){const s=[...i][0];await nc(e,s,n)}else e.filesSelectedPath=null,e.filesPreviewContent=null,e.filesPreviewSize=null,e.filesPreviewBinary=!1}async function sh(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 ic(e,o,t),i++}catch(r){s=Ue(r)}s?e.filesMessage={kind:"error",text:`${i} downloaded, error: ${s}`}:yn(e,`${i} file${i!==1?"s":""} downloaded`)}async function oh(e,t,n,i){const s=t.split("/").pop()??t,o=n==="."?s:`${n}/${s}`;o!==t&&await sc(e,t,o,i)}async function nc(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=Ue(i)}finally{e.filesPreviewLoading=!1}}}async function ic(e,t,n){if(!(!e.client||!e.connected))try{const i={path:t};n&&(i.agentId=n);const s=await e.client.request("files.download",i);if(!(s!=null&&s.base64)){e.filesMessage={kind:"error",text:"Download failed: no data"};return}const o=Uint8Array.from(atob(s.base64),c=>c.charCodeAt(0)),r=new Blob([o]),a=URL.createObjectURL(r),u=document.createElement("a");u.href=a,u.download=s.name??t.split("/").pop()??"download",document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(a)}catch(i){e.filesMessage={kind:"error",text:Ue(i)}}}async function rh(e,t,n,i){if(!e.client||!e.connected)return;e.filesUploadBusy=!0,e.filesMessage=null;let s=0,o="";for(const r of n)try{const a=await r.arrayBuffer(),u=btoa(new Uint8Array(a).reduce((l,d)=>l+String.fromCharCode(d),"")),c={path:t,name:r.name,data:u};i&&(c.agentId=i),await e.client.request("files.upload",c),s++}catch(a){o=Ue(a)}e.filesUploadBusy=!1,o?e.filesMessage={kind:"error",text:s>0?`${s} uploaded, error: ${o}`:o}:yn(e,`${s} file${s!==1?"s":""} uploaded`),await vn(e,i)}async function ah(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),yn(e,"File deleted"),e.filesSelectedPath===t&&(e.filesSelectedPath=null,e.filesPreviewContent=null),await vn(e,n)}catch(i){e.filesMessage={kind:"error",text:Ue(i)}}}}async function sc(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),yn(e,"File moved"),e.filesSelectedPath===t&&(e.filesSelectedPath=n),await vn(e,i)}catch(s){e.filesMessage={kind:"error",text:Ue(s)}}}}async function mo(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 lh(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;yn(e,`Re-indexed: ${s} files, ${o} chunks`),await mo(e,t)}catch(n){e.filesMessage={kind:"error",text:Ue(n)}}finally{e.filesReindexBusy=!1}}}function ch(e,t){const n=new Set(e.filesExpandedDirs);n.has(t)?n.delete(t):n.add(t),e.filesExpandedDirs=n}async function uh(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:Ue(i)},e.filesSearchResults=null}finally{e.filesSearchLoading=!1}}}function dh(e){e.filesSearchQuery="",e.filesSearchResults=null}function ph(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{fo(e,{quiet:!0})},5e3))}function hh(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function yo(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Mt(e,{quiet:!0})},2e3))}function vo(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function bo(e){e.sessionLogsPollInterval==null&&(e.sessionLogsPollInterval=window.setInterval(()=>{!(e.advancedPage?e.advancedTab==="logs":e.tab==="logs")||e.logsSubTab!=="session"||rn(e,{quiet:!0})},2e3))}function wo(e){e.sessionLogsPollInterval!=null&&(clearInterval(e.sessionLogsPollInterval),e.sessionLogsPollInterval=null)}function ko(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&ro(e)},3e3))}function So(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function fh(e){e.auditPollInterval==null&&(e.auditPollInterval=window.setInterval(()=>{tc(e)},3e4))}function gh(e){e.auditPollInterval!=null&&(clearInterval(e.auditPollInterval),e.auditPollInterval=null)}function mh(e){e.memoryStatusPollInterval==null&&(e.memoryStatusPollInterval=window.setInterval(()=>{if(e.tab!=="files")return;const t=e;mo(t,t.filesResolvedAgentId)},3e3))}function yh(e){e.memoryStatusPollInterval!=null&&(clearInterval(e.memoryStatusPollInterval),e.memoryStatusPollInterval=null)}function Ge(e,t){var i;const n={...t,lastActiveSessionKey:((i=t.lastActiveSessionKey)==null?void 0:i.trim())||t.sessionKey.trim()||"main"};e.settings=n,yd(n),t.theme!==e.theme&&(e.theme=t.theme,Ti(e,go(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function oc(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&Ge(e,{...e.settings,lastActiveSessionKey:n})}function vh(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),i=t.get("password"),s=t.get("session"),o=t.get("gatewayUrl");let r=!1;if(n!=null){const u=n.trim();u&&u!==e.settings.token&&Ge(e,{...e.settings,token:u}),t.delete("token"),r=!0}if(i!=null){const u=i.trim();u&&(e.password=u),t.delete("password"),r=!0}if(s!=null){const u=s.trim();u&&(e.sessionKey=u,Ge(e,{...e.settings,sessionKey:u,lastActiveSessionKey:u}))}if(o!=null){const u=o.trim();u&&u!==e.settings.gatewayUrl&&Ge(e,{...e.settings,gatewayUrl:u}),t.delete("gatewayUrl"),r=!0}if(!r)return;const a=new URL(window.location.href);a.search=t.toString(),window.history.replaceState({},"",a.toString())}function bh(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?bo(e):yo(e):(vo(e),wo(e)),t==="debug"?ko(e):So(e),ri(e),ac(e,t,!1)}function wh(e,t,n){Jp({nextTheme:t,applyTheme:()=>{e.theme=t,Ge(e,{...e.settings,theme:t}),Ti(e,go(t))},context:n,currentTheme:e.theme})}async function ri(e){if(e.tab==="overview"&&await lc(e),e.tab==="channels"&&await Th(e),e.tab==="instances"&&await ql(e),e.tab==="cron"&&await xo(e),e.tab==="skills"&&await ht(e),e.tab==="nodes"&&(await fo(e),await ho(e),await Le(e),await qp(e)),e.tab==="chat"&&!e.advancedPage&&!e.chatPage&&(await Lh(e),gn(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await Al(e),await Le(e)),e.tab==="debug"&&(await ro(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"){if(e.logsAtBottom=!0,e.logsSubTab==="session"){const{loadSessionLogs:n}=await ie(async()=>{const{loadSessionLogs:i}=await Promise.resolve().then(()=>ec);return{loadSessionLogs:i}},void 0,import.meta.url);await n(e,{reset:!0})}else await Mt(e,{reset:!0});Sl(e,!0)}}function kh(){if(typeof window>"u")return"";const e=window.__TASKMASTER_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?Ei(e):Yp(window.location.pathname)}function Sh(e){e.theme=e.settings.theme??"system",Ti(e,go(e.theme))}function Ti(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function xh(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"&&Ti(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Ah(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 $h(e,t){if(typeof window>"u")return;const n=Jl(window.location.pathname,e.basePath)??"chat";rc(e,n),ac(e,n,t)}function Eh(e){var s;if(typeof window>"u")return;const t=Jl(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,Ge(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),rc(e,t)}function rc(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?e.logsSubTab==="session"?bo(e):yo(e):(vo(e),wo(e)),t==="debug"?ko(e):So(e),e.connected&&ri(e)}function ac(e,t,n){if(typeof window>"u")return;const i=fn(Qp(t,e.basePath)),s=fn(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 lc(e){await Promise.all([G(e,!1),ql(e),io(e),mn(e),ro(e)])}async function Th(e){await Promise.all([G(e,!0),Al(e),Le(e)])}async function xo(e){await Promise.all([G(e,!1),mn(e),xi(e)])}function cc(e){return e.chatSending||!!e.chatRunId}function Ch(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 uc(e){e.connected&&(e.chatMessage="",await wl(e))}function _h(e,t,n){const i=t.trim(),s=!!(n&&n.length>0);!i&&!s||(e.chatQueue=[...e.chatQueue,{id:no(),text:i,createdAt:Date.now(),attachments:s?n==null?void 0:n.map(o=>({...o})):void 0}],gn(e))}async function dc(e,t,n){var s,o;so(e);const i=await bl(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&&oc(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),gn(e),i&&!e.chatRunId&&pc(e),i}async function pc(e){if(!e.connected||cc(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await dc(e,t.text,{attachments:t.attachments})||(e.chatQueue=[t,...e.chatQueue])}function Mh(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function Ph(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),o=e.chatAttachments??[],r=t==null?o:[],a=r.length>0;if(!(!s&&!a)){if(Ch(s)){await uc(e);return}if(t==null&&(e.chatMessage="",e.chatAttachments=[]),cc(e)){_h(e,s,r);return}await dc(e,s,{previousDraft:t==null?i:void 0,restoreDraft:!!(t&&(n!=null&&n.restoreDraft)),attachments:a?r:void 0,previousAttachments:t==null?o:void 0,restoreAttachments:!!(t&&(n!=null&&n.restoreDraft))})}}async function Lh(e){var i;const t=e,n=Math.max((((i=t.chatMessages)==null?void 0:i.length)??0)+10,Pe);await Promise.all([Me(t,{limit:n}),io(t),Is(e)]),gn(e,!0)}const Ih=pc;function Rh(e){var s,o,r;const t=ul(e.sessionKey);if(t!=null&&t.agentId)return t.agentId;const n=(s=e.hello)==null?void 0:s.snapshot;return((r=(o=n==null?void 0:n.sessionDefaults)==null?void 0:o.defaultAgentId)==null?void 0:r.trim())||"main"}function Nh(e,t){const n=Ei(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Is(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=Rh(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=Nh(e.basePath,t);try{const i=await fetch(n,{method:"GET"});if(!i.ok){e.chatAvatarUrl=null;return}const s=await i.json(),o=typeof s.avatarUrl=="string"?s.avatarUrl.trim():"";e.chatAvatarUrl=o||null}catch{e.chatAvatarUrl=null}}const D={messageSquare:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,monitor:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:p`<svg viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>`,copy:p`<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:p`<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`,brain:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<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:p`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>`,image:p`<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:p`<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:p`<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:p`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>`,circleCheck:p`<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>`,circleX:p`<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:p`<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:p`<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:p`<svg viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>`,smile:p`<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:p`<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:p`<svg viewBox="0 0 24 24"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>`,eye:p`<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:p`<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:p`<svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>`,chevronDown:p`<svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>`,film:p`<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>`},Dh="Taskmaster",Oh="/taskmaster-icon.png",hc="#00d4ff";let On=null;function Xe(){return On||(On={name:window.__TASKMASTER_BRAND_NAME__||Dh,iconUrl:window.__TASKMASTER_BRAND_ICON_URL__||Oh,accentColor:window.__TASKMASTER_ACCENT_COLOR__||hc},On)}function Bh(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 Fh(e){if(e===hc)return;const t=Bh(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 Uh=p`<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>`,Wh=p`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>`;let Rr=!1;function Kh(){Rr||(Rr=!0,document.addEventListener("click",e=>{const t=document.getElementById("nav-burger-toggle");if(!(t!=null&&t.checked))return;const n=t.closest(".setup-header");n!=null&&n.contains(e.target)||(t.checked=!1)}))}function yt(e,t){const n=(l,d)=>l===e?p`<span class="sp-page-nav-current">${l}</span>`:p`<a href=${d}>${l}</a>`,i=p`
21
+ ${n("Setup","/setup")}
22
+ ${n("Chat","/chat")}
23
+ ${n("Admins","/admins")}
24
+ ${n("Contacts","/contacts")}
25
+ ${n("Files","/files")}
26
+ ${n("Browser","/browser")}
27
+ ${n("Advanced","/advanced")}
28
+ `,o=t&&(t.isMaster!==!1||!t.hasPins)?zh(t):k,r=t!=null&&t.hasPins&&t.onLogout?p`<button class="nav-logout-btn" @click=${t.onLogout} title="Lock">${Uh}</button>`:k,a=(t==null?void 0:t.auditCount)??0,u=a>0&&(t!=null&&t.onAuditClick)?p`<button class="nav-audit-btn" @click=${t.onAuditClick} title="Memory writes to review">
29
+ ${Wh}
30
+ <span class="nav-audit-badge">${a>99?"99+":a}</span>
31
+ </button>`:k,c=()=>{const l=document.getElementById("nav-burger-toggle");l&&(l.checked=!1)};return Kh(),p`
32
+ <div class="setup-header">
33
+ <input type="checkbox" id="nav-burger-toggle" class="nav-burger-checkbox" />
34
+ <div class="setup-header-inner">
35
+ <img class="setup-header-logo" src="${Xe().iconUrl}" alt="${Xe().name}" />
36
+ <nav class="setup-header-nav">
37
+ ${i}
38
+ </nav>
39
+ <div class="setup-header-right">
40
+ ${o!==k?p`<span class="nav-selector-inline">${o}</span>`:k}
41
+ ${u}
42
+ ${r}
43
+ <label for="nav-burger-toggle" class="nav-burger-button" aria-label="Toggle menu">
44
+ <span class="nav-burger-icon"></span>
45
+ </label>
46
+ </div>
47
+ </div>
48
+ <nav class="setup-header-dropdown" @click=${c}>
49
+ ${o!==k?p`<div class="nav-selector-mobile">${o}</div>`:k}
50
+ ${i}
51
+ </nav>
52
+ </div>
53
+ `}function zh(e){const{workspaces:t,selectedWorkspace:n,onWorkspaceSelect:i}=e;return p`
54
+ <select
55
+ class="sp-workspace-selector"
56
+ .value=${n??""}
57
+ @change=${o=>{const r=o.target,a=r.value;if(a==="__add__"){r.value=n??"",e.onAddAccount?e.onAddAccount():window.location.href="/setup";return}i(a)}}
58
+ >
59
+ ${t.map(o=>p`
60
+ <option value=${o.name} ?selected=${o.name===n}>
61
+ ${o.displayName??o.name}
62
+ </option>
63
+ `)}
64
+ <option disabled>───</option>
65
+ <option value="__add__">+ Add Account</option>
66
+ </select>
67
+ `}function jh(e){return e.connected?e.fullscreen&&e.active?p`
68
+ <div class="sp-fullscreen-overlay">
69
+ <div class="sp-fullscreen-toolbar">
70
+ <button
71
+ class="setup-button ${e.inputMode?"primary":"secondary"}"
72
+ style="padding: 6px 14px; font-size: 13px;"
73
+ @click=${e.onToggleInput}
74
+ >
75
+ ${e.inputMode?"Input: ON":"Input: OFF"}
76
+ </button>
77
+ <button
78
+ class="setup-button secondary"
79
+ style="padding: 6px 14px; font-size: 13px;"
80
+ @click=${e.onToggleFullscreen}
81
+ >
82
+ Exit Fullscreen
83
+ </button>
84
+ <button
85
+ class="setup-button danger"
86
+ style="padding: 6px 14px; font-size: 13px;"
87
+ ?disabled=${e.loading}
88
+ @click=${e.onStop}
89
+ >
90
+ Stop
91
+ </button>
92
+ </div>
93
+ <div class="sp-fullscreen-canvas-wrap ${e.inputMode?"sp-input-active":""}">
94
+ <canvas
95
+ id="browser-screencast-canvas"
96
+ class="sp-canvas sp-canvas-fullscreen"
97
+ tabindex="0"
98
+ @mousedown=${t=>e.onCanvasMouseDown(t)}
99
+ @mouseup=${t=>e.onCanvasMouseUp(t)}
100
+ @mousemove=${t=>e.onCanvasMouseMove(t)}
101
+ @keydown=${t=>{t.preventDefault(),e.onCanvasKeyDown(t)}}
102
+ @keyup=${t=>{t.preventDefault(),e.onCanvasKeyUp(t)}}
103
+ @contextmenu=${t=>t.preventDefault()}
104
+ ></canvas>
105
+ </div>
106
+ </div>
107
+ `:p`
108
+ <div class="setup-container">
109
+ ${yt("Browser")}
110
+ <div class="setup-card sp-card-wide">
111
+ <h1>Remote Browser</h1>
112
+ <p style="margin-bottom: 16px;">Live view of the headless Chrome instance.</p>
113
+
114
+ <div class="sp-toolbar">
115
+ ${e.active?p`
116
+ <button
117
+ class="setup-button ${e.inputMode?"primary":"secondary"}"
118
+ style="padding: 10px 20px; font-size: 14px;"
119
+ @click=${e.onToggleInput}
120
+ >
121
+ ${e.inputMode?"Input: ON":"Input: OFF"}
122
+ </button>
123
+ <button
124
+ class="setup-button secondary"
125
+ style="padding: 10px 20px; font-size: 14px;"
126
+ @click=${e.onToggleFullscreen}
127
+ >
128
+ Fullscreen
129
+ </button>
130
+ <button
131
+ class="setup-button danger"
132
+ style="padding: 10px 20px; font-size: 14px;"
133
+ ?disabled=${e.loading}
134
+ @click=${e.onStop}
135
+ >
136
+ Stop
137
+ </button>
138
+ `:p`
139
+ <button
140
+ class="setup-button primary"
141
+ style="padding: 10px 20px; font-size: 14px;"
142
+ ?disabled=${e.loading}
143
+ @click=${e.onStart}
144
+ >
145
+ ${e.loading?"Starting...":"Start"}
146
+ </button>
147
+ `}
148
+ </div>
149
+
150
+ ${e.error?p`<div class="setup-error" style="margin-top: 16px;">${e.error}</div>`:k}
151
+
152
+ ${e.handoffPending?p`
153
+ <div class="setup-warning" style="margin-top: 16px; display: flex; align-items: center; justify-content: space-between; gap: 12px; text-align: left;">
154
+ <div>
155
+ <strong>Action required:</strong> ${e.handoffReason??"The agent needs you to complete an action in the browser."}
156
+ </div>
157
+ <button class="setup-button primary" style="flex-shrink: 0; padding: 10px 20px; font-size: 14px;" @click=${e.onCompleteHandoff}>
158
+ Done
159
+ </button>
160
+ </div>
161
+ `:k}
162
+
163
+ <div class="sp-canvas-area" style="margin-top: 16px;">
164
+ ${e.active?p`
165
+ <div class="sp-canvas-wrap ${e.inputMode?"sp-input-active":""}">
166
+ <canvas
167
+ id="browser-screencast-canvas"
168
+ class="sp-canvas"
169
+ tabindex="0"
170
+ @mousedown=${t=>e.onCanvasMouseDown(t)}
171
+ @mouseup=${t=>e.onCanvasMouseUp(t)}
172
+ @mousemove=${t=>e.onCanvasMouseMove(t)}
173
+ @keydown=${t=>{t.preventDefault(),e.onCanvasKeyDown(t)}}
174
+ @keyup=${t=>{t.preventDefault(),e.onCanvasKeyUp(t)}}
175
+ @contextmenu=${t=>t.preventDefault()}
176
+ ></canvas>
177
+ </div>
178
+ `:p`
179
+ <div class="sp-canvas-placeholder">
180
+ <div class="sp-canvas-placeholder-icon">${D.globe}</div>
181
+ <p>Click Start to begin streaming the Chrome viewport.</p>
182
+ </div>
183
+ `}
184
+ </div>
185
+
186
+ ${e.active&&e.inputMode?p`<p class="setup-hint" style="margin-top: 12px;">
187
+ Click the canvas to focus, then interact with the browser. Mouse and keyboard input are forwarded.
188
+ </p>`:k}
189
+
190
+ </div>
191
+ </div>
192
+ `:p`
193
+ <div class="setup-container">
194
+ <div class="setup-card">
195
+ <div class="setup-spinner"></div>
196
+ <p>Connecting to gateway...</p>
197
+ </div>
198
+ </div>
199
+ `}const ai="application/x-taskmaster-file-path";function fc(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function gc(e){const t=e.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function Hh(e,t,n){var o,r;e.preventDefault(),e.stopPropagation(),e.currentTarget.classList.remove("sp-drop-target");const i=(o=e.dataTransfer)==null?void 0:o.getData(ai);if(i){gc(i)!==t&&n.onMoveToDir(i,t);return}const s=(r=e.dataTransfer)==null?void 0:r.files;if(s&&s.length>0){const a=Array.from(s).filter(u=>u.name.toLowerCase().endsWith(".md"));a.length>0&&n.onUpload(t,a)}}function mc(e,t,n){const i=e.type==="directory"||e.type==="symlink"&&e.children!=null,s=t.expandedDirs.has(e.path),o=t.selectedPaths.has(e.path),r=n*20+12;return i?p`
200
+ <div
201
+ class="sp-tree-item sp-tree-dir ${s?"expanded":""}"
202
+ style="padding-left: ${r}px;"
203
+ @click=${()=>t.onToggleDir(e.path)}
204
+ @dragover=${a=>{a.preventDefault(),a.stopPropagation(),a.dataTransfer&&(a.dataTransfer.dropEffect="move"),a.currentTarget.classList.add("sp-drop-target")}}
205
+ @dragleave=${a=>{a.currentTarget.classList.remove("sp-drop-target")}}
206
+ @drop=${a=>Hh(a,e.path,t)}
207
+ >
208
+ <span class="sp-tree-chevron">${s?"−":"+"}</span>
209
+ <span class="sp-tree-icon">${D.folder}</span>
210
+ <span class="sp-tree-name">${e.name}</span>
211
+ </div>
212
+ ${s&&e.children?e.children.map(a=>mc(a,t,n+1)):k}
213
+ `:p`
214
+ <div
215
+ class="sp-tree-item sp-tree-file ${o?"selected":""}"
216
+ style="padding-left: ${r}px;"
217
+ draggable="true"
218
+ @click=${a=>{a.metaKey||a.ctrlKey?t.onToggleSelectFile(e.path):t.onSelectFile(e.path)}}
219
+ @dragstart=${a=>{a.dataTransfer&&(a.dataTransfer.effectAllowed="move",a.dataTransfer.setData(ai,e.path),a.dataTransfer.setData("text/plain",e.name))}}
220
+ >
221
+ <span class="sp-tree-icon">${D.fileText}</span>
222
+ <span class="sp-tree-name">${e.name}</span>
223
+ <span class="sp-tree-size">${fc(e.size)}</span>
224
+ </div>
225
+ `}function qh(e){const t=e.selectedPaths.size;return t<2?k:p`
226
+ <div class="sp-bulk-actions">
227
+ <span style="color: var(--tasker-muted-grey); font-size: 13px;">${t} files selected</span>
228
+ <button
229
+ class="setup-button secondary"
230
+ style="padding: 8px 16px; font-size: 13px;"
231
+ @click=${e.onBulkDownload}
232
+ >
233
+ Download ${t} files
234
+ </button>
235
+ </div>
236
+ `}function Vh(e){if(e.selectedPaths.size!==1||!e.selectedPath)return k;if(e.previewLoading)return p`
237
+ <div class="sp-file-preview">
238
+ <div class="setup-spinner" style="width: 32px; height: 32px; margin: 24px auto;"></div>
239
+ </div>
240
+ `;const t=e.selectedPath.split("/").pop()??e.selectedPath;return p`
241
+ <div class="sp-file-preview">
242
+ <div class="sp-file-preview-header">
243
+ <div>
244
+ <strong>${t}</strong>
245
+ <div class="sp-file-preview-meta">
246
+ ${e.selectedPath}${e.previewSize!=null?` — ${fc(e.previewSize)}`:""}
247
+ </div>
248
+ </div>
249
+ <div class="sp-file-actions">
250
+ <button class="setup-button secondary" style="padding: 8px 16px; font-size: 13px;" @click=${()=>e.onDownload(e.selectedPath)}>
251
+ Download
252
+ </button>
253
+ <button class="setup-button secondary" style="padding: 8px 16px; font-size: 13px;" @click=${()=>{const n=prompt("Move to (relative path):",e.selectedPath);n&&n!==e.selectedPath&&e.onMove(e.selectedPath,n)}}>
254
+ Move
255
+ </button>
256
+ <button class="setup-button danger" style="padding: 8px 16px; font-size: 13px;" @click=${()=>{confirm(`Delete ${t}?`)&&e.onDelete(e.selectedPath)}}>
257
+ Delete
258
+ </button>
259
+ </div>
260
+ </div>
261
+ ${e.previewBinary?p`<div class="sp-file-preview-body"><p style="color: var(--tasker-muted-grey);">Binary file — use Download to view.</p></div>`:e.previewContent!=null?p`<div class="sp-file-preview-body"><pre class="sp-file-code">${e.previewContent}</pre></div>`:p`<div class="sp-file-preview-body"><p style="color: var(--tasker-muted-grey);">File too large for preview — use Download.</p></div>`}
262
+ </div>
263
+ `}function Gh(e){if(!e.selectedPath)return".";if(e.expandedDirs.has(e.selectedPath))return e.selectedPath;const t=e.selectedPath.split("/");return t.length>1?t.slice(0,-1).join("/"):"."}function Qh(e){return p`
264
+ <div class="sp-search-bar">
265
+ <input
266
+ type="text"
267
+ class="sp-search-input"
268
+ placeholder="Search memory..."
269
+ .value=${e.searchQuery}
270
+ @input=${t=>e.onSearchQueryChange(t.target.value)}
271
+ @keydown=${t=>{t.key==="Enter"&&e.onSearch(e.searchQuery)}}
272
+ />
273
+ ${e.agentIds.length>1?p`<select
274
+ class="sp-search-agent-select"
275
+ @change=${t=>e.onSearchAgentChange(t.target.value)}
276
+ >
277
+ ${e.agentIds.map(t=>p`<option value=${t} ?selected=${t===e.searchAgentId}>${t}</option>`)}
278
+ </select>`:k}
279
+ <button
280
+ class="setup-button secondary"
281
+ style="padding: 8px 16px; font-size: 13px;"
282
+ ?disabled=${e.searchLoading||!e.searchQuery.trim()}
283
+ @click=${()=>e.onSearch(e.searchQuery)}
284
+ >
285
+ ${e.searchLoading?"Searching...":"Search"}
286
+ </button>
287
+ ${e.searchResults!==null?p`<button
288
+ class="setup-button secondary"
289
+ style="padding: 8px 16px; font-size: 13px;"
290
+ @click=${e.onSearchClear}
291
+ >
292
+ Clear
293
+ </button>`:k}
294
+ </div>
295
+ `}function Yh(e){return e.searchResults?e.searchResults.length===0?p`<div class="sp-search-results">
296
+ <div style="padding: 24px; color: var(--tasker-muted-grey); text-align: center;">No results found.</div>
297
+ </div>`:p`
298
+ <div class="sp-search-results">
299
+ ${e.searchResults.map(t=>p`
300
+ <div
301
+ class="sp-search-result ${e.selectedPath===t.path?"selected":""}"
302
+ @click=${()=>e.onSelectFile(t.path)}
303
+ >
304
+ <div class="sp-search-result-header">
305
+ <span class="sp-search-result-path">${t.path}</span>
306
+ <span class="sp-search-result-score">${(t.score*100).toFixed(0)}%</span>
307
+ </div>
308
+ <div class="sp-search-result-meta">
309
+ Lines ${t.startLine}\u2013${t.endLine} \u00b7 ${t.source}
310
+ </div>
311
+ <pre class="sp-search-result-snippet">${t.snippet}</pre>
312
+ </div>
313
+ `)}
314
+ </div>
315
+ `:k}function Xh(e){const t=Gh(e);return e.connected?p`
316
+ <div class="setup-container">
317
+ ${yt("Files",e.wsProps)}
318
+ <div class="setup-card sp-card-wide">
319
+ <h1>Workspace Files</h1>
320
+ <p style="margin-bottom: 16px;">Browse, upload, and manage files in your workspace. Drag files between folders to move them.</p>
321
+
322
+ <div class="sp-toolbar">
323
+ <label class="setup-button secondary" style="padding: 10px 20px; font-size: 14px; cursor: pointer;">
324
+ Upload
325
+ <input
326
+ type="file"
327
+ multiple
328
+ accept=".md"
329
+ style="display: none;"
330
+ @change=${n=>{const i=n.target;i.files&&i.files.length>0&&(e.onUpload(t,Array.from(i.files)),i.value="")}}
331
+ />
332
+ </label>
333
+ <button
334
+ class="setup-button secondary"
335
+ style="padding: 10px 20px; font-size: 14px;"
336
+ ?disabled=${e.loading}
337
+ @click=${e.onRefresh}
338
+ >
339
+ ${e.loading?"Loading...":"Refresh"}
340
+ </button>
341
+ <button
342
+ class="setup-button secondary"
343
+ style="padding: 10px 20px; font-size: 14px;"
344
+ ?disabled=${e.reindexBusy}
345
+ @click=${e.onReindex}
346
+ >
347
+ ${e.reindexBusy?"Re-indexing...":"Re-index"}
348
+ </button>
349
+ ${e.memoryStatus?e.memoryStatus.embeddingState==="downloading"?p`<span style="display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--tasker-orange, #f59e0b);">
350
+ <span
351
+ class="setup-status-light"
352
+ style="width: 10px; height: 10px; background: #f59e0b"
353
+ ></span>
354
+ Downloading embedding model\u2026
355
+ </span>`:p`<span style="display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--tasker-text-grey);">
356
+ <span
357
+ class="setup-status-light"
358
+ style="width: 10px; height: 10px; background: ${e.memoryStatus.syncing?"#f59e0b":e.memoryStatus.dirty?"#ef4444":"#22c55e"}"
359
+ ></span>
360
+ ${(()=>{var u;if(e.memoryStatus.syncing&&e.memoryStatus.syncProgress){const{completed:c,total:l,label:d}=e.memoryStatus.syncProgress;return d||(l>0?`Indexing ${c}/${l} files…`:"Indexing…")}const n=e.memoryStatus.files,i=e.memoryStatus.chunks,s=`${n} file${n!==1?"s":""}, ${i} chunks`,o=(u=e.memoryStatus)==null?void 0:u.model;if(!o)return s;const a=(o.includes("/")?o.split("/").pop():o).replace(/[-_]Q\d.*$/i,"").replace(/\.gguf$/i,"");return`${s} · ${a}`})()}
361
+ </span>`:k}
362
+ </div>
363
+
364
+ ${e.error?p`<div class="setup-error" style="margin-top: 16px;">${e.error}</div>`:k}
365
+
366
+ ${e.message?p`<div class="${e.message.kind==="error"?"setup-error":"setup-success-message"}" style="margin-top: 12px;">
367
+ ${e.message.text}
368
+ </div>`:k}
369
+
370
+ ${e.uploadBusy?p`<div style="margin-top: 12px; color: var(--tasker-orange); font-weight: 600; font-size: 14px;">Uploading...</div>`:k}
371
+
372
+ ${Qh(e)}
373
+
374
+ ${e.searchResults!==null?Yh(e):p`<div
375
+ class="sp-file-tree"
376
+ @dragover=${n=>{n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(ai)?"move":"copy")}}
377
+ @drop=${n=>{var o,r;n.preventDefault();const i=(o=n.dataTransfer)==null?void 0:o.getData(ai);if(i){gc(i)!=="."&&e.onMoveToDir(i,".");return}const s=(r=n.dataTransfer)==null?void 0:r.files;if(s&&s.length>0){const a=Array.from(s).filter(u=>u.name.toLowerCase().endsWith(".md"));a.length>0&&e.onUpload(t,a)}}}
378
+ >
379
+ ${e.tree.length===0&&!e.loading?p`<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=>mc(n,e,0))}
380
+ </div>`}
381
+
382
+ ${qh(e)}
383
+ ${Vh(e)}
384
+ </div>
385
+ </div>
386
+ `:p`
387
+ <div class="setup-container">
388
+ <div class="setup-card">
389
+ <div class="setup-spinner"></div>
390
+ <p>Connecting to gateway...</p>
391
+ </div>
392
+ </div>
393
+ `}const Ao="taskmaster_uninstall_done";async function Zh(e){var t,n;if(!(!e.client||!e.connected)&&!e.uninstallBusy){e.uninstallBusy=!0,e.uninstallError=null,(t=e.requestUpdate)==null||t.call(e),Jh();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 li(){try{return localStorage.getItem(Ao)==="1"}catch{return!1}}function $o(){try{localStorage.removeItem(Ao)}catch{}}function Jh(){try{localStorage.setItem(Ao,"1")}catch{}}const Nr=Object.freeze(Object.defineProperty({__proto__:null,checkUninstallDone:li,clearUninstallDone:$o,runUninstall:Zh},Symbol.toStringTag,{value:"Module"}));function q(e){return p`
394
+ <span
395
+ class="setup-status-light"
396
+ style="background: ${{good:"#22c55e",bad:"#ef4444",partial:"#eab308",unknown:"#6b7280"}[e]}"
397
+ ></span>
398
+ `}function ce(e,t){return p`
399
+ <button
400
+ class="setup-info-btn"
401
+ @click=${()=>t.onInfoModalOpen(e)}
402
+ title="Details"
403
+ >
404
+ ${D.info}
405
+ </button>
406
+ `}function ef(e){var i;if(!e.infoModalOpen)return k;let t="",n=[];switch(e.infoModalOpen){case"gateway":{const s=typeof window<"u"?window.location.host:"unknown";t="Gateway",n=[{label:"Status",value:e.gatewayHealthy===!1?"Stopped":"Running"},{label:"Address",value:s},{label:"Health",value:e.gatewayHealthMessage||"OK"}];break}case"claude":{const s=e.authExpiresIn;let o="N/A";if(s!=null&&s>0)if(s>60){const r=Math.floor(s/60),a=s%60;o=a>0?`${r}h ${a}m`:`${r}h`}else o=`${s}m`;t="Claude",n=[{label:"Connected",value:e.authConnected?"Yes":"No"},{label:"Token Expiry",value:o},{label:"Renewal",value:"Automatic (tokens refresh on expiry)"},...e.authMessage?[{label:"Message",value:e.authMessage}]:[]];break}case"license":{const s=e.licenseStoredKey?`…${e.licenseStoredKey.slice(-12)}`:"N/A";t="License",n=[{label:"Status",value:e.licenseValid?"Active":"Inactive"},{label:"Key",value:s},{label:"Tier",value:e.licenseTier||"Standard"},{label:"Device ID",value:e.licenseDeviceId||"N/A"}];break}case"whatsapp":{const s=Ot(e),o=s?Eo(s,e):null;t="WhatsApp",n=[{label:"Account",value:(o==null?void 0:o.name)||(o==null?void 0:o.accountId)||"Default"},{label:"Phone",value:((i=o==null?void 0:o.self)==null?void 0:i.e164)||"Not paired"},{label:"Connected",value:o!=null&&o.connected?"Yes":"No"},{label:"Linked",value:o!=null&&o.linked?"Yes":"No"},...o!=null&&o.lastError?[{label:"Last Error",value:yc(o.lastError)}]:[]];break}case"imessage":{const{thisWsOwns:s}=To(e);t="iMessage",n=[{label:"Connected",value:s&&e.imessageConnected?"Yes":"No"},{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:"Current",value:e.currentVersion?`v${e.currentVersion}`:"Unknown"},{label:"Latest",value:e.latestVersion?`v${e.latestVersion}`:"Unknown"},{label:"Status",value:e.updateAvailable===null?"Not checked":e.updateAvailable?"Update available":"Up to date"},...e.updateMessage?[{label:"Message",value:e.updateMessage}]:[]];break}case"internet":{const s=e.tailscaleStatus,o=s?s.installed?s.loggedIn?s.funnelEnabled&&s.funnelActive?"Active":s.funnelEnabled&&!s.funnelActive?"Enabled but not active":"Connected (not public)":"Not connected":"Not installed":"Checking...";t="Internet Access",n=[{label:"Status",value:o},{label:"What",value:"Makes your public chat and API reachable from the internet, not just your local network"},{label:"How",value:"Uses Tailscale Funnel — a free, secure tunnel that gives your device a public HTTPS address"},{label:"Security",value:"Only the /public/* paths are exposed. The control panel stays LAN-only."},...s!=null&&s.publicUrl?[{label:"Public URL",value:s.publicUrl}]:[],...s!=null&&s.hostname?[{label:"Hostname",value:s.hostname}]:[]];break}case"public-chat":{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:"Access mode",value:cf[e.publicChatAuthMode]??"Open access"},{label:"Open access",value:"Anyone can chat without identifying themselves"},{label:"WhatsApp OTP",value:"Visitors verify their phone number before chatting"},{label:"Visitor chooses",value:"Visitors can chat anonymously or verify via WhatsApp"}];break}case"account-pin":{t="Account PIN",n=[{label:"Status",value:e.accountHasPin?"Set":"Not set"},{label:"What",value:"A numeric PIN that protects this account on the control panel"},{label:"When needed",value:"Required when switching to this account or after the session expires"},{label:"Format",value:"4 to 6 digits"}];break}default:return k}return p`
407
+ <div class="setup-info-overlay" @click=${s=>{s.target.classList.contains("setup-info-overlay")&&e.onInfoModalClose()}}>
408
+ <div class="setup-info-card">
409
+ <h3>${t}</h3>
410
+ ${n.map(s=>p`
411
+ <div class="setup-info-row">
412
+ <span class="setup-info-label">${s.label}</span>
413
+ <span class="setup-info-value">${s.value}</span>
414
+ </div>
415
+ `)}
416
+ <button
417
+ class="setup-button secondary"
418
+ style="margin-top: 16px; width: 100%; padding: 10px;"
419
+ @click=${e.onInfoModalClose}
420
+ >
421
+ Close
422
+ </button>
423
+ </div>
424
+ </div>
425
+ `}function we(e){const t=[{id:"license",label:"1. Activate License"},{id:"auth",label:"2. Connect Claude"},{id:"whatsapp",label:"3. Link WhatsApp"}],n=["license","auth","whatsapp","complete"],i=n.indexOf(e);return p`
426
+ <div class="setup-steps">
427
+ ${t.map(s=>{const o=n.indexOf(s.id),r=e===s.id,a=i>o;return p`
428
+ <div
429
+ class="setup-step ${r?"active":""} ${a?"completed":""}"
430
+ >
431
+ <span class="setup-step-dot"></span>
432
+ <span class="setup-step-label">${s.label}</span>
433
+ </div>
434
+ `})}
435
+ </div>
436
+ `}function Dr(e){const{licenseKey:t,licenseBusy:n,licenseValid:i,licenseMessage:s,licenseDeviceId:o,onLicenseKeyChange:r,onLicenseActivate:a}=e;return i===!0?p`
437
+ <div class="setup-container">
438
+ <div class="setup-card setup-success">
439
+ ${we("license")}
440
+ <div class="setup-status-row">
441
+ ${q("good")}
442
+ <span>License Activated</span>
443
+ </div>
444
+ <p>${s??"Your license is active."}</p>
445
+ </div>
446
+ </div>
447
+ `:n&&!t?p`
448
+ <div class="setup-container">
449
+ <div class="setup-card">
450
+ ${we("license")}
451
+ <div class="setup-spinner"></div>
452
+ <p>Checking license...</p>
453
+ </div>
454
+ </div>
455
+ `:p`
456
+ <div class="setup-container">
457
+ <div class="setup-card">
458
+ ${we("license")}
459
+ <h1>Activate License</h1>
460
+ <p>Enter your license key to get started.</p>
461
+ ${o?p`
462
+ <div class="setup-device-id">
463
+ <span class="setup-device-id-label">Your Device ID</span>
464
+ <code class="setup-device-id-value">${o}</code>
465
+ <button
466
+ class="setup-device-id-copy"
467
+ title="Copy Device ID"
468
+ @click=${async u=>{const c=u.currentTarget;try{await navigator.clipboard.writeText(o),c.textContent="Copied!",setTimeout(()=>{c.textContent="Copy"},1500)}catch{const l=document.createElement("textarea");l.value=o,l.style.position="fixed",l.style.opacity="0",document.body.appendChild(l),l.select(),document.execCommand("copy"),document.body.removeChild(l),c.textContent="Copied!",setTimeout(()=>{c.textContent="Copy"},1500)}}}
469
+ >Copy</button>
470
+ <p class="setup-hint" style="margin-top: 4px;">
471
+ Send this ID along with your order number to our WhatsApp to receive your license key.
472
+ </p>
473
+ </div>
474
+ `:k}
475
+ <div class="setup-code-input">
476
+ <input
477
+ type="text"
478
+ placeholder="Paste your license key here"
479
+ .value=${t}
480
+ @input=${u=>r(u.target.value)}
481
+ @keydown=${u=>{u.key==="Enter"&&t.trim()&&a()}}
482
+ />
483
+ <button
484
+ class="setup-button"
485
+ ?disabled=${!t.trim()||n}
486
+ @click=${a}
487
+ >
488
+ ${n?"Activating...":"Activate"}
489
+ </button>
490
+ </div>
491
+ ${i===!1&&s?p`
492
+ <div class="setup-status-row" style="margin-top: 12px;">
493
+ ${q("bad")}
494
+ <span class="setup-error">${s}</span>
495
+ </div>
496
+ `:k}
497
+ <p class="setup-hint">
498
+ Need a license?
499
+ <a href="https://taskmaster.bot" target="_blank" rel="noopener">
500
+ Purchase at taskmaster.bot
501
+ </a>
502
+ </p>
503
+ </div>
504
+ </div>
505
+ `}function tf(e){const{authConnected:t,authBusy:n,authMessage:i,authUrl:s,authCodeInput:o,authExpiresIn:r,onStartAuth:a,onSubmitAuthCode:u,onAuthCodeChange:c,onSkipToWhatsApp:l}=e;return t===!0?p`
506
+ <div class="setup-container">
507
+ <div class="setup-card setup-success">
508
+ ${we("auth")}
509
+ <div class="setup-status-row">
510
+ ${q("good")}
511
+ <span>Claude Connected</span>
512
+ </div>
513
+ <p>
514
+ Your Claude Pro subscription is linked.
515
+ ${r?p`<br /><span class="setup-hint"
516
+ >Expires in ${r} minutes</span
517
+ >`:k}
518
+ </p>
519
+ <p style="color: var(--tasker-text-grey); font-size: 14px;">
520
+ Head to Chat to introduce yourself and finish setting up your assistant.
521
+ </p>
522
+ <a href="/chat" class="setup-button primary">
523
+ Continue to Chat →
524
+ </a>
525
+ </div>
526
+ </div>
527
+ `:n&&!s?p`
528
+ <div class="setup-container">
529
+ <div class="setup-card">
530
+ ${we("auth")}
531
+ <div class="setup-spinner"></div>
532
+ <p>Starting Claude connection...</p>
533
+ </div>
534
+ </div>
535
+ `:s?p`
536
+ <div class="setup-container">
537
+ <div class="setup-card">
538
+ ${we("auth")}
539
+ <h1>Connect to Claude</h1>
540
+ <p>Click the button below to sign in with your Claude Pro account.</p>
541
+ <a
542
+ href=${s}
543
+ target="_blank"
544
+ rel="noopener"
545
+ class="setup-button primary"
546
+ >
547
+ Sign in with Claude →
548
+ </a>
549
+ <div class="setup-divider">
550
+ <span>Then enter the code shown</span>
551
+ </div>
552
+ <div class="setup-code-input">
553
+ <input
554
+ type="text"
555
+ placeholder="Enter authorization code"
556
+ .value=${o}
557
+ @input=${d=>c(d.target.value)}
558
+ @keydown=${d=>{d.key==="Enter"&&o.trim()&&u(o.trim())}}
559
+ />
560
+ <button
561
+ class="setup-button"
562
+ ?disabled=${!o.trim()||n}
563
+ @click=${()=>u(o.trim())}
564
+ >
565
+ ${n?"Verifying...":"Submit"}
566
+ </button>
567
+ </div>
568
+ ${i?p`<p class="setup-hint">${i}</p>`:k}
569
+ <p class="setup-hint" style="margin-top: 16px;">
570
+ <a href="#" class="setup-link" @click=${d=>{d.preventDefault(),e.onAuthApiKeyToggle()}}>
571
+ Or use an API key instead
572
+ </a>
573
+ </p>
574
+ </div>
575
+ </div>
576
+ `:e.authApiKeyMode?p`
577
+ <div class="setup-container">
578
+ <div class="setup-card">
579
+ ${we("auth")}
580
+ <h1>Enter API Key</h1>
581
+ <p>Paste your Anthropic API key below.</p>
582
+ <div class="setup-code-input">
583
+ <input
584
+ type="password"
585
+ placeholder="sk-ant-..."
586
+ .value=${e.authApiKeyInput}
587
+ @input=${d=>e.onAuthApiKeyChange(d.target.value)}
588
+ @keydown=${d=>{d.key==="Enter"&&e.authApiKeyInput.trim()&&e.onAuthApiKeySubmit()}}
589
+ ?disabled=${e.authApiKeyBusy}
590
+ autofocus
591
+ />
592
+ <button
593
+ class="setup-button"
594
+ ?disabled=${!e.authApiKeyInput.trim()||e.authApiKeyBusy}
595
+ @click=${()=>e.onAuthApiKeySubmit()}
596
+ >${e.authApiKeyBusy?"Saving...":"Save"}</button>
597
+ </div>
598
+ ${e.authApiKeyError?p`<p class="setup-error">${e.authApiKeyError}</p>`:k}
599
+ <p class="setup-hint" style="margin-top: 16px;">
600
+ <a href="#" class="setup-link" @click=${d=>{d.preventDefault(),e.onAuthApiKeyToggle()}}>
601
+ Use OAuth instead
602
+ </a>
603
+ </p>
604
+ <p class="setup-hint">
605
+ Get an API key from
606
+ <a href="https://console.anthropic.com/settings/keys" target="_blank" rel="noopener">
607
+ console.anthropic.com
608
+ </a>
609
+ </p>
610
+ </div>
611
+ </div>
612
+ `:p`
613
+ <div class="setup-container">
614
+ <div class="setup-card">
615
+ ${we("auth")}
616
+ <h1>Connect to Claude</h1>
617
+ ${t===!1&&i?p`<p class="setup-error">${i}</p>`:p`<p>
618
+ First, let's connect your Claude Pro subscription.<br />
619
+ This powers your AI assistant.
620
+ </p>`}
621
+ <button class="setup-button primary" @click=${a}>
622
+ Connect to Claude →
623
+ </button>
624
+ <p class="setup-hint" style="margin-top: 8px;">
625
+ <a href="#" class="setup-link" @click=${d=>{d.preventDefault(),e.onAuthApiKeyToggle()}}>
626
+ Or enter your API key
627
+ </a>
628
+ </p>
629
+ <p class="setup-hint">
630
+ Need a Claude subscription?
631
+ <a href="https://claude.ai/upgrade" target="_blank" rel="noopener">
632
+ Get Claude Pro
633
+ </a>
634
+ </p>
635
+ </div>
636
+ </div>
637
+ `}function Eo(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 Ot(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 Or(e){const t=Ot(e),n=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??Xe().name,i=e.whatsappBusy||e.gatewayHealthLoading;if(e.renamingWorkspace&&t){const s=()=>{const o=e.renameWorkspaceName.trim();o&&e.onWorkspaceRename(t.name,o)};return p`
638
+ <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 4px;">
639
+ <input
640
+ type="text"
641
+ .value=${e.renameWorkspaceName}
642
+ @input=${o=>{e.renameWorkspaceName=o.target.value}}
643
+ @keydown=${o=>{o.key==="Enter"&&s(),o.key==="Escape"&&e.onWorkspaceRenameCancel()}}
644
+ style="flex: 1; font-size: 18px; font-weight: 600; background: var(--tasker-bg-input, rgba(255,255,255,0.08)); border: 1px solid var(--tasker-border, rgba(255,255,255,0.15)); border-radius: 6px; color: var(--tasker-white); padding: 4px 8px; outline: none;"
645
+ autofocus
646
+ />
647
+ <button
648
+ class="setup-status-action"
649
+ @click=${s}
650
+ title="Save"
651
+ style="color: #22c55e;"
652
+ >${D.check}</button>
653
+ <button
654
+ class="setup-status-action"
655
+ @click=${e.onWorkspaceRenameCancel}
656
+ title="Cancel"
657
+ >${D.x}</button>
658
+ </div>
659
+ `}return p`
660
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
661
+ <div style="display: flex; align-items: center; gap: 6px;">
662
+ <h2 style="margin: 0; font-size: 20px; font-weight: 600; color: var(--tasker-white);">${n}</h2>
663
+ <button
664
+ class="setup-status-action"
665
+ @click=${e.onWorkspaceRenameStart}
666
+ title="Rename"
667
+ style="opacity: 0.5; transform: scale(0.8);"
668
+ >${D.edit}</button>
669
+ </div>
670
+ <button
671
+ class="setup-status-action ${i?"spinning":""}"
672
+ ?disabled=${i}
673
+ @click=${e.onRefreshStatus}
674
+ title="Refresh Status"
675
+ >
676
+ ${D.rotateCw}
677
+ </button>
678
+ </div>
679
+ `}function Br(e){return p`
680
+ <div class="setup-status-item">
681
+ ${q(e.gatewayHealthy===!1?"bad":"good")}
682
+ <div class="setup-status-info">
683
+ <strong>Gateway</strong>
684
+ <span>${e.gatewayHealthMessage||"Running"}</span>
685
+ </div>
686
+ ${ce("gateway",e)}
687
+ <button
688
+ class="setup-status-action ${e.gatewayRestartBusy?"spinning":""}"
689
+ ?disabled=${e.gatewayRestartBusy}
690
+ @click=${e.onRestartGateway}
691
+ title="Restart Gateway"
692
+ >
693
+ ${D.rotateCw}
694
+ </button>
695
+ </div>
696
+ `}function Fr(e){const t=e.authConnected===!0;return p`
697
+ <div class="setup-status-item">
698
+ ${q(t?"good":"bad")}
699
+ <div class="setup-status-info">
700
+ <strong>Claude</strong>
701
+ <span>
702
+ ${t?"Connected":"Not connected"}${t&&e.authExpiresIn?p` <span style="color: var(--tasker-text-grey); font-size: 12px;">(${e.authExpiresIn>60?`${Math.floor(e.authExpiresIn/60)}h ${e.authExpiresIn%60}m`:`${e.authExpiresIn}m`})</span>`:k}
703
+ </span>
704
+ </div>
705
+ ${ce("claude",e)}
706
+ ${t?p`
707
+ <button
708
+ class="setup-status-action ${e.authBusy?"spinning":""}"
709
+ ?disabled=${e.authBusy}
710
+ @click=${e.onStartAuth}
711
+ title="Refresh Token"
712
+ >
713
+ ${D.rotateCw}
714
+ </button>
715
+ `:p`
716
+ <button
717
+ class="setup-status-action"
718
+ @click=${e.onStartAuth}
719
+ title="Connect Claude"
720
+ >
721
+ ${D.rotateCw}
722
+ </button>
723
+ `}
724
+ </div>
725
+ `}function Ur(e){return p`
726
+ <div class="setup-status-item" style="flex-wrap: wrap;">
727
+ ${q("good")}
728
+ <div class="setup-status-info">
729
+ <strong>License</strong>
730
+ <span>Active</span>
731
+ </div>
732
+ ${ce("license",e)}
733
+ <button
734
+ class="setup-status-action"
735
+ @click=${()=>{e.licenseRemoveConfirm?e.onLicenseRemoveCancel():e.onLicenseRemoveConfirm()}}
736
+ title="Manage License"
737
+ >
738
+ ${D.rotateCw}
739
+ </button>
740
+ ${e.licenseRemoveConfirm?p`
741
+ <div style="width: 100%; margin-top: 8px; margin-left: 30px;">
742
+ <p style="color: var(--tasker-text-grey); font-size: 13px; margin: 0 0 8px;">
743
+ Removing your license will disable ${Xe().name} until you enter a new key.
744
+ </p>
745
+ <div style="display: flex; gap: 8px;">
746
+ <button
747
+ class="setup-button danger"
748
+ style="font-size: 12px; padding: 4px 12px;"
749
+ ?disabled=${e.licenseBusy}
750
+ @click=${e.onLicenseRemove}
751
+ >
752
+ ${e.licenseBusy?"Removing…":"Remove License"}
753
+ </button>
754
+ <button
755
+ class="setup-button secondary"
756
+ style="font-size: 12px; padding: 4px 12px;"
757
+ @click=${e.onLicenseRemoveCancel}
758
+ >
759
+ Cancel
760
+ </button>
761
+ </div>
762
+ </div>
763
+ `:k}
764
+ </div>
765
+ `}function yc(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 Wr(e){var d;const t=Ot(e);if(!t)return k;const n=Eo(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,r=i?"good":s?"partial":o?"bad":"unknown",a=i?"Connected":s?"Linked, not connected":o?n!=null&&n.lastError?yc(n.lastError):"Not connected":"Not paired",u=!(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),l=c!=null&&e.whatsappActiveQrAccountId===c;return p`
766
+ <div class="setup-status-item" style="flex-wrap: wrap;">
767
+ ${q(r)}
768
+ <div class="setup-status-info">
769
+ <div style="display: flex; align-items: center; gap: 4px;">
770
+ <strong>WhatsApp</strong>
771
+ ${o&&i?p`
772
+ <button
773
+ class="setup-status-action"
774
+ @click=${e.onWhatsAppSettingsOpen}
775
+ title="WhatsApp Settings"
776
+ style="opacity: 0.5; transform: scale(0.75);"
777
+ >
778
+ ${D.settings}
779
+ </button>
780
+ `:k}
781
+ </div>
782
+ <span>${a}</span>
783
+ </div>
784
+ ${ce("whatsapp",e)}
785
+ ${u&&c?p`
786
+ <button
787
+ class="setup-status-action"
788
+ @click=${e.onRefreshStatus}
789
+ title="Refresh Status"
790
+ >
791
+ ${D.rotateCw}
792
+ </button>
793
+ ${n!=null&&n.linked?p`
794
+ <button
795
+ class="setup-status-action"
796
+ ?disabled=${e.whatsappBusy}
797
+ @click=${()=>e.onWhatsAppUnlink(c)}
798
+ title="Unlink WhatsApp"
799
+ >
800
+ ${D.unlink}
801
+ </button>
802
+ `:p`
803
+ <button
804
+ class="setup-status-action ${e.whatsappBusy&&l?"spinning":""}"
805
+ ?disabled=${e.whatsappBusy}
806
+ @click=${()=>e.onWhatsAppRelink(c)}
807
+ title="Link WhatsApp"
808
+ >
809
+ ${D.link}
810
+ </button>
811
+ `}
812
+ `:k}
813
+ ${l&&e.whatsappLoginQrDataUrl?p`
814
+ <div style="width: 100%; margin-top: 8px; margin-left: 30px;">
815
+ <div class="setup-qr" style="display: inline-flex;">
816
+ <img
817
+ src=${e.whatsappLoginQrDataUrl}
818
+ alt="WhatsApp QR"
819
+ style="width: 140px; height: 140px;"
820
+ />
821
+ </div>
822
+ ${e.whatsappLoginMessage?p`<p class="setup-hint" style="margin-top: 4px;">${e.whatsappLoginMessage}</p>`:k}
823
+ </div>
824
+ `:k}
825
+ </div>
826
+ `}const nf=[{id:"claude-opus-4-6",shortName:"Opus"},{id:"claude-sonnet-4-5-20250929",shortName:"Sonnet"},{id:"claude-haiku-4-5-20251001",shortName:"Haiku"}],sf="anthropic/claude-sonnet-4-5-20250929",of=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function rf(e){if(!e.whatsappSettingsOpen)return k;const t=Ot(e);if(!t)return k;const n=Eo(t,e),i=(n==null?void 0:n.running)&&(n==null?void 0:n.connected);if(!n||!i)return k;const s=()=>e.onWhatsAppSettingsClose(),o=e.whatsappModelCatalog??[],r=new Set(o.filter(l=>l.provider==="anthropic").map(l=>l.id)),a=nf.filter(l=>r.has(l.id)),u=e.whatsappModel??sf,c=e.whatsappThinkingLevel??"off";return p`
827
+ <div class="setup-info-overlay" @click=${l=>{l.target.classList.contains("setup-info-overlay")&&s()}}>
828
+ <div class="setup-info-card" style="max-width: 360px;">
829
+ <h3>Public Agent Settings</h3>
830
+ <div style="display: flex; flex-direction: column; gap: 16px; margin-top: 12px;">
831
+ <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
832
+ <input
833
+ type="checkbox"
834
+ .checked=${e.whatsappDmPolicy!=="disabled"&&e.whatsappDmPolicy!==null}
835
+ @change=${e.onWhatsAppDmToggle}
836
+ style="accent-color: #22c55e; margin-top: 2px;"
837
+ />
838
+ <div>
839
+ <div style="font-size: 13px; color: var(--tasker-white);">Enabled</div>
840
+ <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7;">Agent replies to 3rd party messages</div>
841
+ </div>
842
+ </label>
843
+ <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 4px 0;"></div>
844
+ <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
845
+ <input
846
+ type="checkbox"
847
+ .checked=${e.whatsappGroupPolicy==="open"}
848
+ @change=${e.onWhatsAppGroupToggle}
849
+ style="accent-color: #22c55e; margin-top: 2px;"
850
+ />
851
+ <div>
852
+ <div style="font-size: 13px; color: var(--tasker-white);">Group chats</div>
853
+ <div style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.7;">Agent responds in WhatsApp groups</div>
854
+ </div>
855
+ </label>
856
+ ${e.whatsappGroupPolicy==="open"?p`
857
+ <div style="display: flex; flex-direction: column; gap: 6px; padding-left: 24px;">
858
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
859
+ <input
860
+ type="radio"
861
+ name="wa-group-mention"
862
+ .checked=${e.whatsappGroupRequireMention}
863
+ @change=${()=>e.onWhatsAppGroupMentionChange(!0)}
864
+ style="accent-color: #22c55e;"
865
+ />
866
+ <div>
867
+ <div style="font-size: 13px; color: var(--tasker-white);">When mentioned</div>
868
+ <div style="font-size: 11px; color: var(--tasker-text-grey); opacity: 0.7;">Only responds when @mentioned</div>
869
+ </div>
870
+ </label>
871
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
872
+ <input
873
+ type="radio"
874
+ name="wa-group-mention"
875
+ .checked=${!e.whatsappGroupRequireMention}
876
+ @change=${()=>e.onWhatsAppGroupMentionChange(!1)}
877
+ style="accent-color: #22c55e;"
878
+ />
879
+ <div>
880
+ <div style="font-size: 13px; color: var(--tasker-white);">Always respond</div>
881
+ <div style="font-size: 11px; color: var(--tasker-text-grey); opacity: 0.7;">Responds to every message in groups</div>
882
+ </div>
883
+ </label>
884
+ </div>
885
+ `:k}
886
+ <div style="border-top: 1px solid rgba(255,255,255,0.08); margin: 4px 0;"></div>
887
+ ${a.length>0?p`
888
+ <div style="display: flex; align-items: center; gap: 8px;">
889
+ <div style="font-size: 13px; color: var(--tasker-text-grey); min-width: 60px;">Model</div>
890
+ <select
891
+ class="setup-model-select"
892
+ style="flex: 1;"
893
+ .value=${u}
894
+ @change=${l=>{e.onWhatsAppModelChange(l.target.value)}}
895
+ >
896
+ ${a.map(l=>p`
897
+ <option value=${"anthropic/"+l.id} ?selected=${u==="anthropic/"+l.id}>
898
+ ${l.shortName}
899
+ </option>
900
+ `)}
901
+ </select>
902
+ </div>
903
+ `:k}
904
+ <div style="display: flex; align-items: center; gap: 8px;">
905
+ <div style="font-size: 13px; color: var(--tasker-text-grey); min-width: 60px;">Thinking</div>
906
+ <select
907
+ class="setup-model-select"
908
+ style="flex: 1;"
909
+ .value=${c}
910
+ @change=${l=>{e.onWhatsAppThinkingChange(l.target.value)}}
911
+ >
912
+ ${of.map(l=>p`
913
+ <option value=${l.value} ?selected=${c===l.value}>
914
+ ${l.label}
915
+ </option>
916
+ `)}
917
+ </select>
918
+ </div>
919
+ </div>
920
+ <button
921
+ class="setup-button secondary"
922
+ style="margin-top: 20px; width: 100%; padding: 10px;"
923
+ @click=${s}
924
+ >
925
+ Close
926
+ </button>
927
+ </div>
928
+ </div>
929
+ `}function To(e){const t=Ot(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 Kr(e){const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=To(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"),p`
930
+ <div class="setup-status-item" style="flex-wrap: wrap;">
931
+ ${q(s)}
932
+ <div class="setup-status-info">
933
+ <strong>iMessage</strong>
934
+ <span>${o}</span>
935
+ </div>
936
+ ${ce("imessage",e)}
937
+ <button
938
+ class="setup-status-action ${e.imessageEnabling?"spinning":""}"
939
+ ?disabled=${e.imessageEnabling}
940
+ @click=${e.onIMessageEnable}
941
+ title="${n?"Manage iMessage":"Connect iMessage"}"
942
+ >
943
+ ${D.rotateCw}
944
+ </button>
945
+ ${k}
946
+ </div>
947
+ `}function af(e){if(!e.imessageEnableConfirm)return k;const{ownerWs:t,thisWsOwns:n,anotherWsOwns:i}=To(e),s=()=>{e.onIMessageEnableCancel()};return n?p`
948
+ <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&s()}}>
949
+ <div class="setup-info-card" style="text-align: center;">
950
+ <h3>iMessage</h3>
951
+ <p style="color: var(--tasker-text-grey); font-size: 13px; margin: 8px 0 16px;">
952
+ iMessage is connected to this business.
953
+ </p>
954
+ <p style="font-size: 12px; color: var(--tasker-text-grey); opacity: 0.6; margin-bottom: 16px;">
955
+ Self-chat only. Third-party iMessage DMs are not processed.
956
+ </p>
957
+ <button
958
+ class="setup-button secondary"
959
+ style="width: 100%; padding: 10px; color: #ef4444; border-color: #ef4444;"
960
+ ?disabled=${e.imessageEnabling}
961
+ @click=${()=>{e.onIMessageDisconnect()}}
962
+ >
963
+ ${e.imessageEnabling?"Disconnecting…":"Disconnect iMessage"}
964
+ </button>
965
+ <button
966
+ class="setup-button secondary"
967
+ style="width: 100%; padding: 10px; margin-top: 8px;"
968
+ @click=${s}
969
+ >
970
+ Close
971
+ </button>
972
+ </div>
973
+ </div>
974
+ `:i?p`
975
+ <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&s()}}>
976
+ <div class="setup-info-card" style="text-align: center;">
977
+ <h3>Connect iMessage</h3>
978
+ <p style="color: var(--tasker-text-grey); font-size: 13px; margin: 8px 0 16px;">
979
+ iMessage is currently connected to <strong style="text-transform: capitalize;">${t}</strong>.
980
+ Move it to this business?
981
+ </p>
982
+ <button
983
+ class="setup-button primary"
984
+ style="width: 100%; padding: 10px;"
985
+ ?disabled=${e.imessageEnabling}
986
+ @click=${()=>{e.onIMessageReassign()}}
987
+ >
988
+ ${e.imessageEnabling?"Connecting…":"Connect to This Business"}
989
+ </button>
990
+ <button
991
+ class="setup-button secondary"
992
+ style="width: 100%; padding: 10px; margin-top: 8px;"
993
+ @click=${s}
994
+ >
995
+ Cancel
996
+ </button>
997
+ </div>
998
+ </div>
999
+ `:p`
1000
+ <div class="setup-info-overlay" @click=${o=>{o.target.classList.contains("setup-info-overlay")&&s()}}>
1001
+ <div class="setup-info-card" style="text-align: center;">
1002
+ <h3>Enable iMessage</h3>
1003
+ <p style="color: var(--tasker-text-grey); font-size: 13px; margin: 8px 0 16px;">
1004
+ ${Xe().name} will respond to messages in Messages.app for this business.
1005
+ </p>
1006
+ <button
1007
+ class="setup-button primary"
1008
+ style="width: 100%; padding: 10px;"
1009
+ ?disabled=${e.imessageEnabling}
1010
+ @click=${()=>{e.onIMessageEnableConfirm()}}
1011
+ >
1012
+ ${e.imessageEnabling?"Connecting…":"Connect"}
1013
+ </button>
1014
+ <button
1015
+ class="setup-button secondary"
1016
+ style="width: 100%; padding: 10px; margin-top: 8px;"
1017
+ @click=${s}
1018
+ >
1019
+ Cancel
1020
+ </button>
1021
+ </div>
1022
+ </div>
1023
+ `}function zr(e){if(!e.isMaster)return k;const n=e.apiKeyProviders.filter(i=>i.hasKey).length;return p`
1024
+ <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1025
+ <div class="setup-status-item">
1026
+ ${q(n>0?"good":"bad")}
1027
+ <div class="setup-status-info">
1028
+ <strong>API Keys</strong>
1029
+ <span>${n} configured</span>
1030
+ </div>
1031
+ <button
1032
+ class="setup-link-btn"
1033
+ @click=${()=>e.onApiKeyModalOpen()}
1034
+ >Manage</button>
1035
+ </div>
1036
+ </div>
1037
+ ${lf(e)}
1038
+ `}function lf(e){if(!e.apiKeyModalOpen)return k;const t=e.apiKeyProviders,n={};for(const c of t)c.key&&(n[c.id]=c.key);const i=(c,l)=>{const d=l==null?void 0:l.closest(".setup-apikey-input"),h=d==null?void 0:d.querySelector("input"),v=h==null?void 0:h.value.trim();!v||v===n[c]||e.onApiKeySave(c,v)},s=c=>{const l=c.currentTarget,d=l.closest(".setup-apikey-input"),h=d==null?void 0:d.querySelector("input");if(!h)return;const v=h.type==="text";h.type=v?"password":"text",l.classList.toggle("active",!v)},o=(c,l)=>{const d=l.target,h=d.closest(".setup-apikey-input"),v=d.value.trim(),f=v.length>0&&v!==n[c],b=h==null?void 0:h.querySelector(".setup-apikey-save");b&&(b.style.display=f?"":"none");const S=h==null?void 0:h.querySelector(".setup-apikey-eye");S&&(S.style.display=v.length>0?"":"none")},r=t.filter(c=>c.primary),a=t.filter(c=>!c.primary),u=c=>{const l=e.apiKeySavingProvider===c.id&&e.apiKeyBusy,d=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key saved`,h=!e.apiKeyBusy&&e.apiKeySuccess===`${c.id} key removed`;return p`
1039
+ <div class="setup-apikey-row">
1040
+ <div class="setup-apikey-info">
1041
+ <strong>${c.name}</strong>
1042
+ <span class="setup-apikey-category">${c.category}</span>
1043
+ ${d?p`<span class="setup-apikey-badge saved">Saved</span>`:k}
1044
+ ${h?p`<span class="setup-apikey-badge removed">Removed</span>`:k}
1045
+ </div>
1046
+ <div class="setup-apikey-input">
1047
+ <input
1048
+ type="password"
1049
+ .value=${c.key??""}
1050
+ placeholder="Enter key"
1051
+ ?disabled=${e.apiKeyBusy}
1052
+ @input=${v=>o(c.id,v)}
1053
+ @keydown=${v=>{v.key==="Enter"&&i(c.id,v.target)}}
1054
+ />
1055
+ <button
1056
+ class="setup-apikey-icon-btn setup-apikey-eye"
1057
+ style=${c.hasKey?"":"display: none;"}
1058
+ title="Toggle visibility"
1059
+ @click=${s}
1060
+ >${D.eye}</button>
1061
+ ${l?p`<span class="setup-apikey-badge saving">Saving\u2026</span>`:p`<button
1062
+ class="setup-apikey-save setup-button"
1063
+ style="display: none;"
1064
+ ?disabled=${e.apiKeyBusy}
1065
+ @click=${v=>i(c.id,v.currentTarget)}
1066
+ >Save</button>`}
1067
+ ${c.hasKey&&!l?p`
1068
+ <button
1069
+ class="setup-apikey-icon-btn danger"
1070
+ title="Remove key"
1071
+ ?disabled=${e.apiKeyBusy}
1072
+ @click=${()=>e.onApiKeyRemove(c.id)}
1073
+ >${D.trash}</button>
1074
+ `:k}
1075
+ </div>
1076
+ </div>
1077
+ `};return p`
1078
+ <div class="setup-info-overlay" style="align-items: flex-start; padding-top: 72px;" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onApiKeyModalClose()}}>
1079
+ <div class="setup-info-card" style="max-width: 480px;">
1080
+ <h3 style="margin: 0 0 4px; text-align: center;">API Keys</h3>
1081
+ <div class="setup-apikey-list">
1082
+ ${e.apiKeyError?p`<p class="setup-error" style="margin: 0;">${e.apiKeyError}</p>`:k}
1083
+ ${r.map(u)}
1084
+ ${a.length>0?p`
1085
+ <details class="setup-apikey-advanced">
1086
+ <summary>Additional keys</summary>
1087
+ ${a.map(u)}
1088
+ </details>
1089
+ `:k}
1090
+ </div>
1091
+ </div>
1092
+ </div>
1093
+ `}function jr(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 p`
1094
+ <div class="setup-status-item">
1095
+ ${q(t)}
1096
+ <div class="setup-status-info">
1097
+ <strong>Software</strong>
1098
+ <span>${n}</span>
1099
+ </div>
1100
+ ${ce("update",e)}
1101
+ ${e.updateAvailable?p`
1102
+ <button
1103
+ class="setup-status-action ${i?"spinning":""}"
1104
+ ?disabled=${i}
1105
+ @click=${e.onUpdateRun}
1106
+ title="Update Now"
1107
+ >
1108
+ ${D.download}
1109
+ </button>
1110
+ `:p`
1111
+ <button
1112
+ class="setup-status-action ${i?"spinning":""}"
1113
+ ?disabled=${i}
1114
+ @click=${e.onUpdateCheck}
1115
+ title="Check for Updates"
1116
+ >
1117
+ ${D.rotateCw}
1118
+ </button>
1119
+ `}
1120
+ </div>
1121
+ `}const cf={anonymous:"Open access",verified:"WhatsApp OTP",choice:"Visitor chooses"};function Hr(e){const t=e.publicChatEnabled;return p`
1122
+ <div class="setup-status-item">
1123
+ ${q(t?"good":"unknown")}
1124
+ <div class="setup-status-info">
1125
+ <strong>Public Chat</strong>
1126
+ ${t?p`
1127
+ <select
1128
+ class="setup-select-sm"
1129
+ ?disabled=${e.publicChatBusy}
1130
+ @change=${i=>{const s=i.target.value;e.onPublicChatAuthModeChange(s)}}
1131
+ >
1132
+ <option value="anonymous" ?selected=${e.publicChatAuthMode==="anonymous"}>Open access</option>
1133
+ <option value="verified" ?selected=${e.publicChatAuthMode==="verified"}>WhatsApp OTP</option>
1134
+ <option value="choice" ?selected=${e.publicChatAuthMode==="choice"}>Visitor chooses</option>
1135
+ </select>
1136
+ `:p`<span>Disabled</span>`}
1137
+ </div>
1138
+ ${ce("public-chat",e)}
1139
+ <button
1140
+ class="setup-link-btn"
1141
+ ?disabled=${e.publicChatBusy}
1142
+ @click=${e.onPublicChatToggle}
1143
+ >${e.publicChatBusy?"...":t?"Disable":"Enable"}</button>
1144
+ </div>
1145
+ `}function uf(e){if(!e.isMaster)return k;const t=e.tailscaleStatus,n=e.tailscaleBusy,i=e.tailscaleAuthUrl;if(!t)return p`
1146
+ <div class="setup-status-item">
1147
+ ${q("unknown")}
1148
+ <div class="setup-status-info">
1149
+ <strong>Internet Access</strong>
1150
+ <span>Checking...</span>
1151
+ </div>
1152
+ ${ce("internet",e)}
1153
+ </div>
1154
+ `;if(!t.installed)return p`
1155
+ <div class="setup-status-item">
1156
+ ${q("unknown")}
1157
+ <div class="setup-status-info">
1158
+ <strong>Internet Access</strong>
1159
+ <span>Tailscale not installed</span>
1160
+ </div>
1161
+ ${ce("internet",e)}
1162
+ </div>
1163
+ `;if(i)return p`
1164
+ <div>
1165
+ <div class="setup-status-item">
1166
+ ${q("partial")}
1167
+ <div class="setup-status-info">
1168
+ <strong>Internet Access</strong>
1169
+ <span>Waiting for authentication...</span>
1170
+ </div>
1171
+ ${ce("internet",e)}
1172
+ </div>
1173
+ <div style="padding: 12px 0 4px 28px;">
1174
+ <p style="margin: 0 0 8px; font-size: 13px; opacity: 0.8;">
1175
+ Scan the QR code or open the link to log in with your Google or Microsoft account:
1176
+ </p>
1177
+ <div style="text-align: center; margin: 12px 0;">
1178
+ <img
1179
+ src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${encodeURIComponent(i)}"
1180
+ alt="Tailscale auth QR code"
1181
+ style="width: 180px; height: 180px; border-radius: 8px; background: #fff; padding: 8px;"
1182
+ />
1183
+ </div>
1184
+ <div style="text-align: center; margin-bottom: 8px;">
1185
+ <a
1186
+ href="${i}"
1187
+ target="_blank"
1188
+ rel="noopener"
1189
+ style="color: var(--tasker-link, #60a5fa); font-size: 13px; word-break: break-all;"
1190
+ >${i}</a>
1191
+ </div>
1192
+ </div>
1193
+ </div>
1194
+ `;if(!t.loggedIn)return p`
1195
+ <div class="setup-status-item">
1196
+ ${q("partial")}
1197
+ <div class="setup-status-info">
1198
+ <strong>Internet Access</strong>
1199
+ <span>Not connected</span>
1200
+ </div>
1201
+ ${ce("internet",e)}
1202
+ <button
1203
+ class="setup-link-btn"
1204
+ ?disabled=${n}
1205
+ @click=${e.onTailscaleEnable}
1206
+ >${n?"...":"Connect"}</button>
1207
+ </div>
1208
+ `;if(!t.funnelEnabled){const o=e.tailscaleFunnelEnableUrl;return p`
1209
+ <div>
1210
+ <div class="setup-status-item">
1211
+ ${q("partial")}
1212
+ <div class="setup-status-info">
1213
+ <strong>Internet Access</strong>
1214
+ <span>Connected (LAN only)</span>
1215
+ </div>
1216
+ ${ce("internet",e)}
1217
+ <button
1218
+ class="setup-link-btn"
1219
+ ?disabled=${n}
1220
+ @click=${e.onTailscaleFunnelEnable}
1221
+ >${n?"...":"Enable"}</button>
1222
+ </div>
1223
+ ${o?p`<div style="padding: 8px 0 4px 28px;">
1224
+ <p style="margin: 0 0 6px; font-size: 13px; color: #f59e0b;">
1225
+ Funnel must be enabled on your Tailscale account first.
1226
+ </p>
1227
+ <a
1228
+ href="${o}"
1229
+ target="_blank"
1230
+ rel="noopener"
1231
+ style="color: var(--tasker-link, #60a5fa); font-size: 13px; word-break: break-all;"
1232
+ >Open Tailscale admin to enable Funnel &rarr;</a>
1233
+ <p style="margin: 6px 0 0; font-size: 12px; opacity: 0.6;">
1234
+ After enabling, come back here and click Enable again.
1235
+ </p>
1236
+ </div>`:e.tailscaleError&&!o?p`<div style="padding: 8px 0 4px 28px;">
1237
+ <p style="margin: 0; font-size: 13px; color: #ef4444;">${e.tailscaleError}</p>
1238
+ </div>`:k}
1239
+ </div>
1240
+ `}if(!t.funnelActive)return p`
1241
+ <div>
1242
+ <div class="setup-status-item">
1243
+ ${q("error")}
1244
+ <div class="setup-status-info">
1245
+ <strong>Internet Access</strong>
1246
+ <span>Enabled but not active</span>
1247
+ </div>
1248
+ ${ce("internet",e)}
1249
+ <button
1250
+ class="setup-link-btn"
1251
+ ?disabled=${n}
1252
+ @click=${e.onTailscaleFunnelDisable}
1253
+ >${n?"...":"Disable"}</button>
1254
+ </div>
1255
+ <div style="padding: 8px 0 4px 28px;">
1256
+ <p style="margin: 0; font-size: 13px; color: #f59e0b;">
1257
+ Funnel is configured but not running. You may need to
1258
+ <a
1259
+ href="https://login.tailscale.com/admin/machines"
1260
+ target="_blank"
1261
+ rel="noopener"
1262
+ style="color: var(--tasker-link, #60a5fa);"
1263
+ >enable Funnel in Tailscale admin</a>,
1264
+ then disable and re-enable here.
1265
+ </p>
1266
+ </div>
1267
+ </div>
1268
+ `;const s=t.publicUrl??`https://${t.hostname}`;return p`
1269
+ <div class="setup-status-item">
1270
+ ${q("good")}
1271
+ <div class="setup-status-info">
1272
+ <strong>Internet Access</strong>
1273
+ <a
1274
+ href="${s}"
1275
+ target="_blank"
1276
+ rel="noopener"
1277
+ style="color: var(--tasker-link, #60a5fa); font-size: 12px; overflow-wrap: break-word; word-break: normal;"
1278
+ >${s}</a>
1279
+ </div>
1280
+ ${ce("internet",e)}
1281
+ <button
1282
+ class="setup-info-btn"
1283
+ title="Copy URL"
1284
+ @click=${o=>{const r=o.currentTarget;navigator.clipboard.writeText(s).then(()=>{r.classList.add("copied"),setTimeout(()=>r.classList.remove("copied"),1500)})}}
1285
+ >${D.copy}</button>
1286
+ <button
1287
+ class="setup-link-btn"
1288
+ ?disabled=${n}
1289
+ @click=${e.onTailscaleFunnelDisable}
1290
+ >${n?"...":"Disable"}</button>
1291
+ </div>
1292
+ `}function qr(e){return e>=70?"▇▇▇▇":e>=50?"▇▇▇▁":e>=30?"▇▇▁▁":"▇▁▁▁"}function Vr(e){var u;if(e.serverPlatform!=="linux")return k;const t=e.wifiStatus,n=e.wifiBusy;if(!t)return p`
1293
+ <div class="setup-status-item">
1294
+ ${q("unknown")}
1295
+ <div class="setup-status-info">
1296
+ <strong>WiFi</strong>
1297
+ <span>Checking...</span>
1298
+ </div>
1299
+ </div>
1300
+ `;if(!t.available)return p`
1301
+ <div class="setup-status-item">
1302
+ ${q("unknown")}
1303
+ <div class="setup-status-info">
1304
+ <strong>WiFi</strong>
1305
+ <span>NetworkManager not available</span>
1306
+ </div>
1307
+ </div>
1308
+ `;const i=e.wifiNetworks,s=e.wifiSelectedSsid,o=i.length>0,r=t.connected?"good":"partial",a=t.connected?p`${t.ssid} ${t.signal!=null?p`<span style="opacity: 0.5; font-size: 11px;">${qr(t.signal)}</span>`:k}`:"Not connected";return p`
1309
+ <div>
1310
+ <div class="setup-status-item">
1311
+ ${q(r)}
1312
+ <div class="setup-status-info">
1313
+ <strong>WiFi</strong>
1314
+ <span>${a}</span>
1315
+ ${t.connected&&t.ip?p`<span style="font-size: 11px; opacity: 0.5;">${t.ip}</span>`:k}
1316
+ </div>
1317
+ <button
1318
+ class="setup-link-btn"
1319
+ ?disabled=${n}
1320
+ @click=${e.onWifiScan}
1321
+ >${n?"...":o?"Rescan":"Scan"}</button>
1322
+ </div>
1323
+
1324
+ ${e.wifiError?p`<div style="padding: 4px 0 4px 28px;">
1325
+ <p style="margin: 0; font-size: 13px; color: #ef4444;">${e.wifiError}</p>
1326
+ </div>`:k}
1327
+
1328
+ ${o?p`
1329
+ <div style="padding: 8px 0 4px 28px;">
1330
+ <div style="
1331
+ max-height: 200px;
1332
+ overflow-y: auto;
1333
+ border: 1px solid rgba(255,255,255,0.1);
1334
+ border-radius: 6px;
1335
+ margin-bottom: 8px;
1336
+ ">
1337
+ ${i.map(c=>p`
1338
+ <button
1339
+ style="
1340
+ display: flex;
1341
+ align-items: center;
1342
+ justify-content: space-between;
1343
+ width: 100%;
1344
+ padding: 8px 12px;
1345
+ background: ${s===c.ssid?"rgba(255,255,255,0.1)":"transparent"};
1346
+ border: none;
1347
+ border-bottom: 1px solid rgba(255,255,255,0.06);
1348
+ color: inherit;
1349
+ font-size: 13px;
1350
+ cursor: pointer;
1351
+ text-align: left;
1352
+ "
1353
+ @click=${()=>e.onWifiSelectSsid(s===c.ssid?null:c.ssid)}
1354
+ >
1355
+ <span style="display: flex; align-items: center; gap: 8px;">
1356
+ ${c.active?p`<span style="color: #22c55e;" title="Connected">\u2713</span>`:k}
1357
+ <span>${c.ssid}</span>
1358
+ </span>
1359
+ <span style="display: flex; align-items: center; gap: 8px; opacity: 0.5; font-size: 11px;">
1360
+ ${c.security!=="Open"?p`<span title="${c.security}">\uD83D\uDD12</span>`:k}
1361
+ <span title="Signal: ${c.signal}%">${qr(c.signal)}</span>
1362
+ </span>
1363
+ </button>
1364
+ `)}
1365
+ </div>
1366
+
1367
+ ${s&&!i.find(c=>c.ssid===s&&c.active)?p`
1368
+ <div style="display: flex; gap: 8px; align-items: center;">
1369
+ ${((u=i.find(c=>c.ssid===s))==null?void 0:u.security)!=="Open"?p`
1370
+ <input
1371
+ type="password"
1372
+ placeholder="Password"
1373
+ .value=${e.wifiPassword}
1374
+ @input=${c=>e.onWifiPasswordChange(c.target.value)}
1375
+ @keydown=${c=>{c.key==="Enter"&&e.onWifiConnect()}}
1376
+ ?disabled=${n}
1377
+ style="
1378
+ flex: 1;
1379
+ padding: 6px 10px;
1380
+ background: rgba(255,255,255,0.06);
1381
+ border: 1px solid rgba(255,255,255,0.15);
1382
+ border-radius: 4px;
1383
+ color: inherit;
1384
+ font-size: 13px;
1385
+ outline: none;
1386
+ "
1387
+ />`:k}
1388
+ <button
1389
+ class="setup-button primary"
1390
+ style="padding: 6px 16px; font-size: 13px;"
1391
+ ?disabled=${n}
1392
+ @click=${e.onWifiConnect}
1393
+ >${n?"Connecting...":"Connect"}</button>
1394
+ </div>
1395
+ `:k}
1396
+ </div>
1397
+ `:k}
1398
+ </div>
1399
+ `}function df(e){var i,s,o;const t=e.updateRunning,n=e.updateLastResult;if(!t&&!n)return k;if(t)return p`
1400
+ <div class="setup-info-overlay">
1401
+ <div class="setup-info-card" style="max-width: 400px;">
1402
+ <h3>Software Update</h3>
1403
+ ${e.updateProgressSteps.length>0?p`
1404
+ <div class="setup-update-progress">
1405
+ ${e.updateProgressSteps.map(r=>p`
1406
+ <div class="setup-update-step ${r.status}">
1407
+ <span class="setup-update-step-icon">
1408
+ ${r.status==="running"?p`<span class="setup-update-spinner"></span>`:r.status==="done"?p`<span class="setup-update-icon-ok">${D.check}</span>`:p`<span class="setup-update-icon-fail">${D.x}</span>`}
1409
+ </span>
1410
+ <span class="setup-update-step-name">${r.name}</span>
1411
+ ${r.durationMs!=null?p`<span class="setup-update-step-time">${Gr(r.durationMs)}</span>`:k}
1412
+ </div>
1413
+ `)}
1414
+ </div>
1415
+ `:p`<div class="setup-spinner" style="margin: 16px auto;"></div>`}
1416
+ ${e.updateMessage?p`<p style="text-align: center; color: var(--tasker-text-grey); font-size: 13px; margin: 12px 0 0;">${e.updateMessage}</p>`:k}
1417
+ </div>
1418
+ </div>
1419
+ `;if(n){const r=n.status==="ok";let a;if(r){const c=(i=n.before)==null?void 0:i.version,l=((s=n.after)==null?void 0:s.version)??n.currentVersion;a=c?`v${c} → v${l}`:`Updated to v${l}`}else a=n.reason??((o=n.failedStep)==null?void 0:o.name)??"unknown error";const u=n.durationMs!=null?Gr(n.durationMs):null;return p`
1420
+ <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onUpdateDismissResult()}}>
1421
+ <div class="setup-info-card" style="max-width: 360px; text-align: center;">
1422
+ <div class="setup-update-result-icon ${r?"ok":"fail"}">${r?D.circleCheck:D.circleX}</div>
1423
+ <h3 style="color: ${r?"#22c55e":"#ef4444"};">
1424
+ ${r?"Update Complete":"Update Failed"}
1425
+ </h3>
1426
+ <p style="color: var(--tasker-text-grey); font-size: 14px; margin: 8px 0;">
1427
+ ${a}
1428
+ </p>
1429
+ ${u?p`<p style="color: rgba(255,255,255,0.3); font-size: 12px; margin: 4px 0 0;">${u}</p>`:k}
1430
+ <button
1431
+ class="setup-button secondary"
1432
+ style="margin-top: 20px; width: 100%; padding: 10px;"
1433
+ @click=${e.onUpdateDismissResult}
1434
+ >
1435
+ Close
1436
+ </button>
1437
+ </div>
1438
+ </div>
1439
+ `}return k}function Gr(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Qr(e){const t=e.accountHasPin;return p`
1440
+ <div class="setup-status-item">
1441
+ ${q(t?"good":"bad")}
1442
+ <div class="setup-status-info">
1443
+ <strong>Account PIN</strong>
1444
+ <span>${t?"Set":"Not set"}</span>
1445
+ </div>
1446
+ ${ce("account-pin",e)}
1447
+ <button
1448
+ class="setup-link-btn"
1449
+ @click=${()=>e.onAccountPinModalOpen()}
1450
+ >${t?"Change":"Set PIN"}</button>
1451
+ </div>
1452
+ `}function Yr(e){if(!e.accountPinModalOpen)return k;const t=e.accountHasPin,n=e.accountPinBusy;let i="",s="",o="";const r=c=>l=>{const d=l.target;d.value=d.value.replace(/\D/g,"").slice(0,6),c(d.value)},a=(c,l)=>{var h;let d=c.querySelector(".pin-modal-validation");d||(d=document.createElement("p"),d.className="login-error pin-modal-validation",(h=c.querySelector("button[type=submit]"))==null||h.before(d)),d.textContent=l},u=c=>{c.preventDefault();const l=c.target;if(!n){if(t&&!i){a(l,"Enter your current PIN");return}if(!s){a(l,"Enter a new PIN");return}if(!o){a(l,"Confirm your new PIN");return}if(s!==o){a(l,"PINs do not match");return}if(s.length<4){a(l,"PIN must be 4–6 digits");return}e.onAccountPinSave(t?i:null,s)}};return p`
1453
+ <div class="setup-info-overlay" @click=${c=>{c.target.classList.contains("setup-info-overlay")&&e.onAccountPinModalClose()}}>
1454
+ <div class="setup-info-card" style="max-width: 340px;">
1455
+ <div class="setup-info-header">
1456
+ <h3>${t?"Change Account PIN":"Set Account PIN"}</h3>
1457
+ <button class="setup-info-close" @click=${()=>e.onAccountPinModalClose()}>
1458
+ ${D.close}
1459
+ </button>
1460
+ </div>
1461
+ <form @submit=${u} style="display: flex; flex-direction: column; gap: 12px; padding: 16px 0 8px;">
1462
+ ${t?p`
1463
+ <input
1464
+ class="login-pin-input"
1465
+ type="password"
1466
+ inputmode="numeric"
1467
+ pattern="[0-9]*"
1468
+ minlength="4"
1469
+ maxlength="6"
1470
+ placeholder="Current PIN"
1471
+ ?disabled=${n}
1472
+ @input=${r(c=>{i=c})}
1473
+ autofocus
1474
+ />
1475
+ `:k}
1476
+ <input
1477
+ class="login-pin-input"
1478
+ type="password"
1479
+ inputmode="numeric"
1480
+ pattern="[0-9]*"
1481
+ minlength="4"
1482
+ maxlength="6"
1483
+ placeholder="New PIN (4–6 digits)"
1484
+ ?disabled=${n}
1485
+ @input=${r(c=>{s=c})}
1486
+ ${t?k:p`autofocus`}
1487
+ />
1488
+ <input
1489
+ class="login-pin-input"
1490
+ type="password"
1491
+ inputmode="numeric"
1492
+ pattern="[0-9]*"
1493
+ minlength="4"
1494
+ maxlength="6"
1495
+ placeholder="Confirm PIN"
1496
+ ?disabled=${n}
1497
+ @input=${r(c=>{o=c})}
1498
+ />
1499
+ ${e.accountPinError?p`<p class="login-error">${e.accountPinError}</p>`:k}
1500
+ ${e.accountPinSuccess?p`<p class="login-success">${e.accountPinSuccess}</p>`:k}
1501
+ <button
1502
+ class="login-submit"
1503
+ type="submit"
1504
+ ?disabled=${n}
1505
+ >${n?p`<span class="login-spinner"></span>`:t?"Change PIN":"Set PIN"}</button>
1506
+ </form>
1507
+ </div>
1508
+ </div>
1509
+ `}function Xr(e){if(!e.addingWorkspace)return k;const{workspaceSaving:t}=e;return p`
1510
+ <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1511
+ <div class="setup-add-account">
1512
+ <strong>New Account</strong>
1513
+ <input
1514
+ type="text"
1515
+ class="setup-add-account-input"
1516
+ placeholder=""
1517
+ .value=${e.newWorkspaceName}
1518
+ @input=${n=>e.onSetNewWorkspaceName(n.target.value)}
1519
+ @keydown=${n=>{n.key==="Enter"&&e.newWorkspaceName.trim()&&e.newWorkspacePin.match(/^\d{4,6}$/)&&e.onWorkspaceCreate(e.newWorkspaceName,e.newWorkspacePath||void 0)}}
1520
+ />
1521
+ <input
1522
+ type="password"
1523
+ inputmode="numeric"
1524
+ pattern="[0-9]*"
1525
+ minlength="4"
1526
+ maxlength="6"
1527
+ class="setup-add-account-input"
1528
+ placeholder="PIN for this account (4-6 digits)"
1529
+ .value=${e.newWorkspacePin}
1530
+ @input=${n=>{const i=n.target;i.value=i.value.replace(/\D/g,"").slice(0,6),e.onSetNewWorkspacePin(i.value)}}
1531
+ />
1532
+ <details style="margin-top: 8px;">
1533
+ <summary style="cursor: pointer; font-size: 12px; color: var(--tasker-text-grey);">
1534
+ Use existing workspace (advanced)
1535
+ </summary>
1536
+ <input
1537
+ type="text"
1538
+ class="setup-add-account-input"
1539
+ placeholder="/path/to/workspace"
1540
+ style="margin-top: 8px;"
1541
+ .value=${e.newWorkspacePath}
1542
+ @input=${n=>e.onSetNewWorkspacePath(n.target.value)}
1543
+ />
1544
+ </details>
1545
+ <div class="setup-add-account-actions" style="margin-top: 8px;">
1546
+ <button
1547
+ class="setup-button primary"
1548
+ ?disabled=${t||!e.newWorkspaceName.trim()||!e.newWorkspacePin.match(/^\d{4,6}$/)}
1549
+ @click=${()=>e.onWorkspaceCreate(e.newWorkspaceName,e.newWorkspacePath||void 0)}
1550
+ >
1551
+ ${t?"Creating…":"Create"}
1552
+ </button>
1553
+ <button
1554
+ class="setup-button secondary"
1555
+ @click=${()=>{e.onSetAddingWorkspace(!1),e.onSetNewWorkspaceName(""),e.onSetNewWorkspacePath(""),e.onSetNewWorkspacePin("")}}
1556
+ >
1557
+ Cancel
1558
+ </button>
1559
+ </div>
1560
+ </div>
1561
+ </div>
1562
+ `}function Zr(e){const t=Ot(e);return!t||t.isDefault?k:e.workspaceRemoveConfirm===t.name?p`
1563
+ <div style="margin-top: 16px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 12px;">
1564
+ <div style="font-size: 13px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
1565
+ <span style="color: var(--tasker-danger, #ef4444);">Remove "${t.displayName??t.name}" and its WhatsApp account?</span>
1566
+ <button
1567
+ class="setup-button danger"
1568
+ style="font-size: 12px; padding: 4px 12px;"
1569
+ ?disabled=${e.workspaceSaving}
1570
+ @click=${()=>e.onWorkspaceRemove(t.name)}
1571
+ >
1572
+ ${e.workspaceSaving?"Removing…":"Remove"}
1573
+ </button>
1574
+ <button
1575
+ class="setup-button secondary"
1576
+ style="font-size: 12px; padding: 4px 12px;"
1577
+ @click=${()=>e.onSetWorkspaceRemoveConfirm(null)}
1578
+ >
1579
+ Cancel
1580
+ </button>
1581
+ </div>
1582
+ </div>
1583
+ `:p`
1584
+ <p class="setup-hint" style="margin-top: 12px;">
1585
+ <a
1586
+ href="#"
1587
+ class="setup-link-danger"
1588
+ @click=${i=>{i.preventDefault(),e.onSetWorkspaceRemoveConfirm(t.name)}}
1589
+ >Remove Account</a>
1590
+ </p>
1591
+ `}function Jr(e){if(e.uninstallDone)return p`
1592
+ <div style="margin-top: 24px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1593
+ <p style="color: var(--tasker-danger, #ef4444); font-size: 13px; font-weight: 600; margin: 0 0 8px 0;">
1594
+ Taskmaster has been uninstalled.
1595
+ </p>
1596
+ <p style="font-size: 12px; color: var(--tasker-text-grey); margin: 0;">
1597
+ If the npm package was not removed automatically, run:<br/>
1598
+ <code style="font-size: 11px; background: rgba(255,255,255,0.06); padding: 2px 6px; border-radius: 3px;">sudo npm uninstall -g @rubytech/taskmaster</code>
1599
+ </p>
1600
+ </div>
1601
+ `;if(e.uninstallConfirm){const t=e.uninstallConfirmText==="UNINSTALL";return p`
1602
+ <div style="margin-top: 24px; border-top: 1px solid var(--tasker-border, rgba(255,255,255,0.1)); padding-top: 16px;">
1603
+ <p style="color: var(--tasker-danger, #ef4444); font-size: 13px; font-weight: 600; margin: 0 0 8px 0;">
1604
+ Uninstall Taskmaster
1605
+ </p>
1606
+ <p style="font-size: 12px; color: var(--tasker-text-grey); margin: 0 0 12px 0;">
1607
+ This will stop the gateway, remove all configuration, workspace files, and the npm package.
1608
+ This cannot be undone.
1609
+ </p>
1610
+ <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
1611
+ <input
1612
+ type="text"
1613
+ placeholder="Type UNINSTALL to confirm"
1614
+ .value=${e.uninstallConfirmText}
1615
+ ?disabled=${e.uninstallBusy}
1616
+ @input=${n=>e.onUninstallConfirmTextChange(n.target.value)}
1617
+ style="font-size: 12px; padding: 4px 8px; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.15); border-radius: 4px; color: inherit; width: 180px;"
1618
+ />
1619
+ <button
1620
+ class="setup-button danger"
1621
+ style="font-size: 12px; padding: 4px 12px;"
1622
+ ?disabled=${!t||e.uninstallBusy}
1623
+ @click=${e.onUninstallRun}
1624
+ >
1625
+ ${e.uninstallBusy?"Uninstalling…":"Uninstall"}
1626
+ </button>
1627
+ <button
1628
+ class="setup-button secondary"
1629
+ style="font-size: 12px; padding: 4px 12px;"
1630
+ ?disabled=${e.uninstallBusy}
1631
+ @click=${e.onUninstallCancel}
1632
+ >
1633
+ Cancel
1634
+ </button>
1635
+ </div>
1636
+ ${e.uninstallError?p`<p class="setup-error" style="margin-top: 8px; font-size: 12px;">${e.uninstallError}</p>`:k}
1637
+ </div>
1638
+ `}return p`
1639
+ <p class="setup-hint" style="margin-top: 8px;">
1640
+ <a
1641
+ href="#"
1642
+ class="setup-link-danger"
1643
+ @click=${t=>{t.preventDefault(),e.onUninstallConfirm()}}
1644
+ >Uninstall Taskmaster</a>
1645
+ </p>
1646
+ `}function ea(){return p`
1647
+ <p class="setup-hint" style="margin-top: 4px; font-size: 12px; opacity: 0.6;">
1648
+ Need help? <a href="https://wa.me/447591215452" target="_blank" rel="noopener" style="color: var(--tasker-orange);">Message Dave on WhatsApp</a>
1649
+ </p>
1650
+ `}function pf(e){const{whatsappBusy:t,whatsappLoginMessage:n,whatsappLoginQrDataUrl:i,whatsappLoginConnected:s,whatsappChannelStatus:o}=e;if(i)return p`
1651
+ <div class="setup-container">
1652
+ <div class="setup-card">
1653
+ <h1>Scan with WhatsApp</h1>
1654
+ <p>
1655
+ On your phone: WhatsApp → Settings → Linked Devices → Link a Device
1656
+ </p>
1657
+ <div class="setup-qr">
1658
+ <img src=${i} alt="WhatsApp QR Code" />
1659
+ </div>
1660
+ ${t?p`<p class="setup-waiting">Waiting for scan...</p>`:p`<p class="setup-hint">
1661
+ Scan the code above with your phone
1662
+ </p>`}
1663
+ <p class="setup-hint" style="margin-top: 16px;">
1664
+ <strong>Important:</strong> If you see "${Xe().name}" in your Linked
1665
+ Devices, remove it first before scanning.
1666
+ </p>
1667
+ <div class="setup-actions" style="margin-top: 24px;">
1668
+ <button
1669
+ class="setup-button secondary"
1670
+ @click=${e.onWhatsAppBack}
1671
+ >
1672
+ ← Back
1673
+ </button>
1674
+ </div>
1675
+ </div>
1676
+ </div>
1677
+ `;if(t)return p`
1678
+ <div class="setup-container">
1679
+ <div class="setup-card">
1680
+ <div class="setup-spinner"></div>
1681
+ <p>${n||"Connecting to WhatsApp..."}</p>
1682
+ </div>
1683
+ </div>
1684
+ `;const r=(o==null?void 0:o.running)&&(o==null?void 0:o.connected);return o?(e.whatsappAccounts.length>1?e.whatsappAccounts.every(l=>l.running&&l.connected):r)&&e.authConnected?p`
1685
+ <div class="setup-container">
1686
+ <div class="setup-card setup-success setup-dashboard-wide">
1687
+ ${Or(e)}
1688
+ <div class="setup-status-dashboard">
1689
+ ${Br(e)}
1690
+ ${Fr(e)}
1691
+ ${Ur(e)}
1692
+ ${Wr(e)}
1693
+ ${e.serverPlatform==="darwin"?Kr(e):k}
1694
+ ${Qr(e)}
1695
+ ${jr(e)}
1696
+ ${Hr(e)}
1697
+ ${uf(e)}
1698
+ ${Vr(e)}
1699
+ </div>
1700
+
1701
+ ${Yr(e)}
1702
+ ${zr(e)}
1703
+ ${Xr(e)}
1704
+ ${Zr(e)}
1705
+ ${Jr(e)}
1706
+ ${ea()}
1707
+ ${e.workspacesError?p`<p class="setup-error" style="margin-top: 8px;">${e.workspacesError}</p>`:k}
1708
+ </div>
1709
+ </div>
1710
+ `:p`
1711
+ <div class="setup-container">
1712
+ <div class="setup-card setup-dashboard-wide">
1713
+ ${Or(e)}
1714
+ <div class="setup-status-dashboard">
1715
+ ${Br(e)}
1716
+ ${Fr(e)}
1717
+ ${Ur(e)}
1718
+ ${Wr(e)}
1719
+ ${e.serverPlatform==="darwin"?Kr(e):k}
1720
+ ${Qr(e)}
1721
+ ${jr(e)}
1722
+ ${Hr(e)}
1723
+ ${Vr(e)}
1724
+ </div>
1725
+
1726
+ ${Yr(e)}
1727
+ ${zr(e)}
1728
+ ${Xr(e)}
1729
+ ${Zr(e)}
1730
+ ${Jr(e)}
1731
+ ${ea()}
1732
+ ${e.workspacesError?p`<p class="setup-error" style="margin-top: 8px;">${e.workspacesError}</p>`:k}
1733
+ </div>
1734
+ </div>
1735
+ `:o?s===!1&&n&&!t?p`
1736
+ <div class="setup-container">
1737
+ <div class="setup-card">
1738
+ ${we("whatsapp")}
1739
+ <div class="setup-status-row">
1740
+ ${q("bad")}
1741
+ <span>Connection Failed</span>
1742
+ </div>
1743
+ <p class="setup-error">${n}</p>
1744
+ <button
1745
+ class="setup-button primary"
1746
+ ?disabled=${t}
1747
+ @click=${e.onWhatsAppRelink}
1748
+ >
1749
+ Try Again
1750
+ </button>
1751
+ </div>
1752
+ </div>
1753
+ `:p`
1754
+ <div class="setup-container">
1755
+ <div class="setup-card">
1756
+ ${we("whatsapp")}
1757
+ ${n?p`<p class="setup-error">${n}</p>`:p`<div class="setup-spinner"></div>
1758
+ <p>Preparing...</p>`}
1759
+ </div>
1760
+ </div>
1761
+ `:p`
1762
+ <div class="setup-container">
1763
+ <div class="setup-card">
1764
+ ${we("whatsapp")}
1765
+ <div class="setup-spinner"></div>
1766
+ <p>Checking connection status...</p>
1767
+ <button
1768
+ class="setup-button secondary"
1769
+ style="margin-top: 16px;"
1770
+ @click=${e.onRefreshStatus}
1771
+ >
1772
+ Refresh Status
1773
+ </button>
1774
+ </div>
1775
+ </div>
1776
+ `}function hf(e){const{connected:t,currentStep:n}=e;if(t&&li()&&$o(),e.uninstallDone||!t&&li())return p`
1777
+ <div class="setup-container">
1778
+ <div class="setup-card">
1779
+ <p style="color: var(--tasker-danger, #ef4444); font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
1780
+ Taskmaster has been uninstalled.
1781
+ </p>
1782
+ <p style="font-size: 13px; color: var(--tasker-text-grey); margin: 0 0 16px 0;">
1783
+ The gateway service, configuration, and workspace files have been removed.
1784
+ </p>
1785
+ <p style="font-size: 13px; color: var(--tasker-text-grey); margin: 0 0 16px 0;">
1786
+ If the npm package was not removed automatically, run:
1787
+ </p>
1788
+ <code style="display: block; font-size: 12px; background: rgba(255,255,255,0.06); padding: 8px 12px; border-radius: 4px; margin: 0 0 16px 0;">sudo npm uninstall -g @rubytech/taskmaster</code>
1789
+ <p style="font-size: 12px; color: var(--tasker-text-grey); margin: 0;">You can close this tab.</p>
1790
+ </div>
1791
+ </div>
1792
+ `;if(!t){const o=e.updateRunning;return p`
1793
+ <div class="setup-container">
1794
+ <div class="setup-card">
1795
+ <div class="setup-spinner"></div>
1796
+ <p>${o?"Restarting gateway after update…":"Connecting to gateway..."}</p>
1797
+ </div>
1798
+ </div>
1799
+ `}let i;switch(n){case"license":i=Dr(e);break;case"auth":i=tf(e);break;case"whatsapp":case"complete":i=pf(e);break;default:i=Dr(e)}const s=yt("Setup",e.wsProps);return p`${i}${ef(e)}${af(e)}${rf(e)}${df(e)}${s}`}function ff(e,t){const n=e.paired?"Paired phone (used to link WhatsApp)":"Admin access via WhatsApp DM";return p`
1800
+ <div class="sp-list-item">
1801
+ <div class="sp-list-item-main">
1802
+ <div class="sp-list-item-title">${e.phone}</div>
1803
+ <div class="sp-list-item-sub">${n}</div>
1804
+ </div>
1805
+ ${e.paired?p`<span style="color: var(--tasker-orange); font-size: 13px; padding: 8px 16px;">Primary</span>`:p`<button
1806
+ class="setup-button danger"
1807
+ style="padding: 8px 16px; font-size: 13px;"
1808
+ ?disabled=${t.saving}
1809
+ @click=${()=>t.onRemove(e.phone)}
1810
+ >
1811
+ Remove
1812
+ </button>`}
1813
+ </div>
1814
+ `}function gf(e){if(!e.connected)return p`
1815
+ <div class="setup-container">
1816
+ <div class="setup-card">
1817
+ <div class="setup-spinner"></div>
1818
+ <p>Connecting to gateway...</p>
1819
+ </div>
1820
+ </div>
1821
+ `;const t=n=>{n.preventDefault(),e.newPhone.trim()&&e.onAdd(e.newPhone)};return p`
1822
+ <div class="setup-container">
1823
+ ${yt("Admins",e.wsProps)}
1824
+ <div class="setup-card" style="max-width: 520px;">
1825
+ <h1>Admin Phones</h1>
1826
+ <p style="margin-bottom: 16px;">
1827
+ Phone numbers that route to the admin agent instead of the public agent.
1828
+ </p>
1829
+
1830
+ <div class="sp-toolbar">
1831
+ <button
1832
+ class="setup-button secondary"
1833
+ style="padding: 10px 20px; font-size: 14px;"
1834
+ ?disabled=${e.loading}
1835
+ @click=${e.onRefresh}
1836
+ >
1837
+ ${e.loading?"Loading...":"Refresh"}
1838
+ </button>
1839
+ </div>
1840
+
1841
+ ${e.error?p`<div class="setup-error" style="margin-top: 16px;">${e.error}</div>`:k}
1842
+
1843
+ <form style="display: flex; flex-direction: row; gap: 12px; margin-top: 20px; align-items: stretch;" @submit=${t}>
1844
+ <input
1845
+ type="tel"
1846
+ style="flex: 1; padding: 10px 14px; font-size: 14px; border-radius: 8px; border: 1px solid rgba(255, 255, 255, 0.15); background: rgba(0, 0, 0, 0.3); color: var(--tasker-white); font-family: inherit;"
1847
+ placeholder="+44..."
1848
+ .value=${e.newPhone}
1849
+ @input=${n=>e.onNewPhoneChange(n.target.value)}
1850
+ ?disabled=${e.saving}
1851
+ />
1852
+ <button
1853
+ type="submit"
1854
+ class="setup-button primary"
1855
+ style="padding: 10px 20px; font-size: 14px; flex-shrink: 0;"
1856
+ ?disabled=${e.saving||!e.newPhone.trim()}
1857
+ >
1858
+ ${e.saving?"Saving...":"Add"}
1859
+ </button>
1860
+ </form>
1861
+
1862
+ <div class="sp-list" style="margin-top: 20px;">
1863
+ ${e.phones.length===0?p`<div class="sp-list-empty">No admin phones configured yet.</div>`:e.phones.map(n=>ff(n,e))}
1864
+ </div>
1865
+
1866
+ <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
1867
+ <strong style="color: var(--tasker-white);">How it works:</strong><br/>
1868
+ Messages from admin phones route to the <code style="background: rgba(255,255,255,0.1); padding: 2px 6px; border-radius: 4px; color: var(--tasker-orange);">admin</code> agent with full tool access.
1869
+ All other numbers go to <code style="background: rgba(255,255,255,0.1); padding: 2px 6px; border-radius: 4px; color: var(--tasker-orange);">public</code> with restricted access.
1870
+ </div>
1871
+
1872
+ </div>
1873
+ </div>
1874
+ `}function mf(e){return Object.keys(e.fields).length}function yf(e,t){const n=Object.entries(e.fields);return p`
1875
+ <div class="contacts-record-fields">
1876
+ ${n.length===0?p`<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])=>p`
1877
+ <div class="contacts-field-row">
1878
+ <input
1879
+ class="field-key"
1880
+ type="text"
1881
+ .value=${i}
1882
+ disabled
1883
+ title="Field name"
1884
+ />
1885
+ <input
1886
+ class="field-value"
1887
+ type="text"
1888
+ .value=${s}
1889
+ @change=${o=>t.onSetField(e.id,i,o.target.value)}
1890
+ ?disabled=${t.saving}
1891
+ title="Field value"
1892
+ />
1893
+ <button
1894
+ class="setup-button danger field-delete"
1895
+ ?disabled=${t.saving}
1896
+ @click=${()=>t.onDeleteField(e.id,i)}
1897
+ >
1898
+ ×
1899
+ </button>
1900
+ </div>
1901
+ `)}
1902
+ <div class="contacts-record-actions">
1903
+ <button
1904
+ class="setup-button secondary"
1905
+ style="font-size: 13px; padding: 8px 14px;"
1906
+ ?disabled=${t.saving}
1907
+ @click=${()=>{const i=prompt("Field name (e.g. status, plan, notes):");if(!(i!=null&&i.trim()))return;const s=prompt(`Value for "${i.trim()}":`);s!==null&&t.onSetField(e.id,i.trim(),s)}}
1908
+ >
1909
+ + Add Field
1910
+ </button>
1911
+ <button
1912
+ class="setup-button danger"
1913
+ style="font-size: 13px; padding: 8px 14px;"
1914
+ ?disabled=${t.saving}
1915
+ @click=${()=>{confirm(`Delete contact "${e.name}" (${e.id})?`)&&t.onDelete(e.id)}}
1916
+ >
1917
+ Delete Contact
1918
+ </button>
1919
+ </div>
1920
+ </div>
1921
+ `}function vf(e,t){const n=t.editingId===e.id,i=mf(e),s=i===0?"No fields":`${i} field${i>1?"s":""}`;return p`
1922
+ <div class="contacts-record">
1923
+ <div
1924
+ class="contacts-record-header"
1925
+ @click=${()=>t.onToggleExpand(e.id)}
1926
+ >
1927
+ <div class="contacts-record-info">
1928
+ <span class="contacts-record-name">${e.name}</span>
1929
+ <span class="contacts-record-phone">${e.id}</span>
1930
+ </div>
1931
+ <span class="contacts-record-meta">${s}</span>
1932
+ </div>
1933
+ ${n?yf(e,t):k}
1934
+ </div>
1935
+ `}function bf(e){if(!e.connected)return p`
1936
+ <div class="setup-container">
1937
+ <div class="setup-card">
1938
+ <div class="setup-spinner"></div>
1939
+ <p>Connecting to gateway...</p>
1940
+ </div>
1941
+ </div>
1942
+ `;const t=i=>{i.preventDefault(),e.onSearchSubmit()},n=i=>{i.preventDefault(),e.newRecordPhone.trim()&&e.newRecordName.trim()&&e.onAdd(e.newRecordPhone,e.newRecordName)};return p`
1943
+ <div class="setup-container">
1944
+ ${yt("Contacts",e.wsProps)}
1945
+ <div class="setup-card" style="max-width: 620px;">
1946
+ <h1>Contact Records</h1>
1947
+ <p style="margin-bottom: 16px;">
1948
+ Verified contact data managed by the business owner. Agents can read these records but cannot modify them.
1949
+ </p>
1950
+
1951
+ <div class="sp-toolbar" style="display: flex; gap: 8px;">
1952
+ <button
1953
+ class="setup-button secondary"
1954
+ style="padding: 10px 20px; font-size: 14px;"
1955
+ ?disabled=${e.loading}
1956
+ @click=${e.onRefresh}
1957
+ >
1958
+ ${e.loading?"Loading...":"Refresh"}
1959
+ </button>
1960
+ <button
1961
+ class="setup-button primary"
1962
+ style="padding: 10px 20px; font-size: 14px;"
1963
+ @click=${e.onShowAddForm}
1964
+ >
1965
+ + Add Contact
1966
+ </button>
1967
+ </div>
1968
+
1969
+ ${e.error?p`<div class="setup-error" style="margin-top: 16px;">${e.error}</div>`:k}
1970
+
1971
+ ${e.showAddForm?p`
1972
+ <form class="contacts-add-form" @submit=${n}>
1973
+ <input
1974
+ type="tel"
1975
+ placeholder="+447490553305"
1976
+ .value=${e.newRecordPhone}
1977
+ @input=${i=>e.onNewRecordPhoneChange(i.target.value)}
1978
+ ?disabled=${e.saving}
1979
+ />
1980
+ <input
1981
+ type="text"
1982
+ placeholder="Contact name"
1983
+ .value=${e.newRecordName}
1984
+ @input=${i=>e.onNewRecordNameChange(i.target.value)}
1985
+ ?disabled=${e.saving}
1986
+ />
1987
+ <div class="contacts-add-form-buttons">
1988
+ <button
1989
+ type="submit"
1990
+ class="setup-button primary"
1991
+ style="padding: 10px 20px; font-size: 14px;"
1992
+ ?disabled=${e.saving||!e.newRecordPhone.trim()||!e.newRecordName.trim()}
1993
+ >
1994
+ ${e.saving?"Saving...":"Add"}
1995
+ </button>
1996
+ <button
1997
+ type="button"
1998
+ class="setup-button secondary"
1999
+ style="padding: 10px 20px; font-size: 14px;"
2000
+ @click=${e.onCancelAddForm}
2001
+ >
2002
+ Cancel
2003
+ </button>
2004
+ </div>
2005
+ </form>
2006
+ `:k}
2007
+
2008
+ <form
2009
+ class="contacts-search"
2010
+ style="margin-top: 16px;"
2011
+ @submit=${t}
2012
+ >
2013
+ <input
2014
+ type="text"
2015
+ placeholder="Search by name or phone..."
2016
+ .value=${e.searchQuery}
2017
+ @input=${i=>e.onSearch(i.target.value)}
2018
+ />
2019
+ <button
2020
+ type="submit"
2021
+ class="setup-button secondary"
2022
+ style="padding: 10px 20px; font-size: 14px; flex-shrink: 0;"
2023
+ >
2024
+ Search
2025
+ </button>
2026
+ </form>
2027
+
2028
+ <div style="margin-top: 16px;">
2029
+ ${e.records.length===0?p`<div class="contacts-empty">
2030
+ ${e.searchQuery.trim()?`No records matching "${e.searchQuery}".`:"No contact records yet. Add one to get started."}
2031
+ </div>`:e.records.map(i=>vf(i,e))}
2032
+ </div>
2033
+
2034
+ <div class="setup-hint" style="margin-top: 20px; padding: 14px; background: rgba(0, 0, 0, 0.2); border-radius: 8px; text-align: left;">
2035
+ <strong style="color: var(--tasker-white);">How it works:</strong><br/>
2036
+ Records stored here are <strong>read-only for agents</strong> — they use the
2037
+ <code style="background: rgba(255,255,255,0.1); padding: 2px 6px; border-radius: 4px; color: var(--tasker-orange);">contact_lookup</code>
2038
+ tool to check payment status and account details, but cannot modify them. This prevents prompt injection from altering sensitive data.
2039
+ </div>
2040
+ </div>
2041
+ </div>
2042
+ `}const vc={CHILD:2},bc=e=>(...t)=>({_$litDirective$:e,values:t});let wc=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:wf}=ad,ta=e=>e,na=()=>document.createComment(""),jt=(e,t,n)=>{var o;const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const r=i.insertBefore(na(),s),a=i.insertBefore(na(),s);n=new wf(r,a,e,e.options)}else{const r=n._$AB.nextSibling,a=n._$AM,u=a!==e;if(u){let c;(o=n._$AQ)==null||o.call(n,e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==a._$AU&&n._$AP(c)}if(r!==s||u){let c=n._$AA;for(;c!==r;){const l=ta(c).nextSibling;ta(i).insertBefore(c,s),c=l}}}return n},it=(e,t,n=e)=>(e._$AI(t,n),e),kf={},Sf=(e,t=kf)=>e._$AH=t,xf=e=>e._$AH,is=e=>{e._$AR(),e._$AA.remove()};const ia=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},Af=bc(class extends wc{constructor(e){if(super(e),e.type!==vc.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,n){let i;n===void 0?n=t:t!==void 0&&(i=t);const s=[],o=[];let r=0;for(const a of e)s[r]=i?i(a,r):r,o[r]=n(a,r),r++;return{values:o,keys:s}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,i]){const s=xf(e),{values:o,keys:r}=this.dt(t,n,i);if(!Array.isArray(s))return this.ut=r,o;const a=this.ut??(this.ut=[]),u=[];let c,l,d=0,h=s.length-1,v=0,f=o.length-1;for(;d<=h&&v<=f;)if(s[d]===null)d++;else if(s[h]===null)h--;else if(a[d]===r[v])u[v]=it(s[d],o[v]),d++,v++;else if(a[h]===r[f])u[f]=it(s[h],o[f]),h--,f--;else if(a[d]===r[f])u[f]=it(s[d],o[f]),jt(e,u[f+1],s[d]),d++,f--;else if(a[h]===r[v])u[v]=it(s[h],o[v]),jt(e,s[d],s[h]),h--,v++;else if(c===void 0&&(c=ia(r,v,f),l=ia(a,d,h)),c.has(a[d]))if(c.has(a[h])){const b=l.get(r[v]),S=b!==void 0?s[b]:null;if(S===null){const A=jt(e,s[d]);it(A,o[v]),u[v]=A}else u[v]=it(S,o[v]),jt(e,s[d],S),s[b]=null;v++}else is(s[h]),h--;else is(s[d]),d++;for(;v<=f;){const b=jt(e,u[f+1]);it(b,o[v]),u[v++]=b}for(;d<=h;){const b=s[d++];b!==null&&is(b)}return this.ut=r,Sf(e,u),Qe}});class Rs extends wc{constructor(t){if(super(t),this.it=k,t.type!==vc.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===k||t==null)return this._t=void 0,this.it=t;if(t===Qe)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:[]}}}Rs.directiveName="unsafeHTML",Rs.resultType=1;const ci=bc(Rs);const{entries:kc,setPrototypeOf:sa,isFrozen:$f,getPrototypeOf:Ef,getOwnPropertyDescriptor:Tf}=Object;let{freeze:pe,seal:ge,create:Ns}=Object,{apply:Ds,construct:Os}=typeof Reflect<"u"&&Reflect;pe||(pe=function(t){return t});ge||(ge=function(t){return t});Ds||(Ds=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)});Os||(Os=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 Bn=he(Array.prototype.forEach),Cf=he(Array.prototype.lastIndexOf),oa=he(Array.prototype.pop),Ht=he(Array.prototype.push),_f=he(Array.prototype.splice),Qn=he(String.prototype.toLowerCase),ss=he(String.prototype.toString),os=he(String.prototype.match),qt=he(String.prototype.replace),Mf=he(String.prototype.indexOf),Pf=he(String.prototype.trim),ye=he(Object.prototype.hasOwnProperty),le=he(RegExp.prototype.test),Vt=Lf(TypeError);function he(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return Ds(e,t,i)}}function Lf(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Os(e,n)}}function F(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Qn;sa&&sa(e,null);let i=t.length;for(;i--;){let s=t[i];if(typeof s=="string"){const o=n(s);o!==s&&($f(t)||(t[i]=o),s=o)}e[s]=!0}return e}function If(e){for(let t=0;t<e.length;t++)ye(e,t)||(e[t]=null);return e}function Te(e){const t=Ns(null);for(const[n,i]of kc(e))ye(e,n)&&(Array.isArray(i)?t[n]=If(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Te(i):t[n]=i);return t}function Gt(e,t){for(;e!==null;){const i=Tf(e,t);if(i){if(i.get)return he(i.get);if(typeof i.value=="function")return he(i.value)}e=Ef(e)}function n(){return null}return n}const ra=pe(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),rs=pe(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),as=pe(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Rf=pe(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ls=pe(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Nf=pe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),aa=pe(["#text"]),la=pe(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),cs=pe(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),ca=pe(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Fn=pe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Df=ge(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Of=ge(/<%[\w\W]*|[\w\W]*%>/gm),Bf=ge(/\$\{[\w\W]*/gm),Ff=ge(/^data-[\-\w.\u00B7-\uFFFF]+$/),Uf=ge(/^aria-[\-\w]+$/),Sc=ge(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Wf=ge(/^(?:\w+script|data):/i),Kf=ge(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xc=ge(/^html$/i),zf=ge(/^[a-z][.\w]*(-[.\w]+)+$/i);var ua=Object.freeze({__proto__:null,ARIA_ATTR:Uf,ATTR_WHITESPACE:Kf,CUSTOM_ELEMENT:zf,DATA_ATTR:Ff,DOCTYPE_NAME:xc,ERB_EXPR:Of,IS_ALLOWED_URI:Sc,IS_SCRIPT_OR_DATA:Wf,MUSTACHE_EXPR:Df,TMPLIT_EXPR:Bf});const Qt={element:1,text:3,progressingInstruction:7,comment:8,document:9},jf=function(){return typeof window>"u"?null:window},Hf=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let i=null;const s="data-tt-policy-suffix";n&&n.hasAttribute(s)&&(i=n.getAttribute(s));const o="dompurify"+(i?"#"+i:"");try{return t.createPolicy(o,{createHTML(r){return r},createScriptURL(r){return r}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},da=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ac(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jf();const t=I=>Ac(I);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==Qt.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,s=i.currentScript,{DocumentFragment:o,HTMLTemplateElement:r,Node:a,Element:u,NodeFilter:c,NamedNodeMap:l=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:v}=e,f=u.prototype,b=Gt(f,"cloneNode"),S=Gt(f,"remove"),A=Gt(f,"nextSibling"),$=Gt(f,"childNodes"),T=Gt(f,"parentNode");if(typeof r=="function"){const I=n.createElement("template");I.content&&I.content.ownerDocument&&(n=I.content.ownerDocument)}let C,M="";const{implementation:R,createNodeIterator:B,createDocumentFragment:ee,getElementsByTagName:me}=n,{importNode:Ke}=i;let Z=da();t.isSupported=typeof kc=="function"&&typeof T=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Ft,ERB_EXPR:wt,TMPLIT_EXPR:Je,DATA_ATTR:Li,ARIA_ATTR:Ii,IS_SCRIPT_OR_DATA:Ri,ATTR_WHITESPACE:kn,CUSTOM_ELEMENT:Ni}=ua;let{IS_ALLOWED_URI:Sn}=ua,Q=null;const xn=F({},[...ra,...rs,...as,...ls,...aa]);let Y=null;const An=F({},[...la,...cs,...ca,...Fn]);let H=Object.seal(Ns(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}})),et=null,Ut=null;const ze=Object.seal(Ns(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let $n=!0,x=!0,_=!1,N=!0,O=!1,V=!0,z=!1,ae=!1,je=!1,kt=!1,En=!1,Tn=!1,qo=!0,Vo=!1;const Mu="user-content-";let Di=!0,Wt=!1,St={},xe=null;const Oi=F({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Go=null;const Qo=F({},["audio","video","img","source","image","track"]);let Bi=null;const Yo=F({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cn="http://www.w3.org/1998/Math/MathML",_n="http://www.w3.org/2000/svg",Ie="http://www.w3.org/1999/xhtml";let xt=Ie,Fi=!1,Ui=null;const Pu=F({},[Cn,_n,Ie],ss);let Mn=F({},["mi","mo","mn","ms","mtext"]),Pn=F({},["annotation-xml"]);const Lu=F({},["title","style","font","a","script"]);let Kt=null;const Iu=["application/xhtml+xml","text/html"],Ru="text/html";let J=null,At=null;const Nu=n.createElement("form"),Xo=function(w){return w instanceof RegExp||w instanceof Function},Wi=function(){let w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(At&&At===w)){if((!w||typeof w!="object")&&(w={}),w=Te(w),Kt=Iu.indexOf(w.PARSER_MEDIA_TYPE)===-1?Ru:w.PARSER_MEDIA_TYPE,J=Kt==="application/xhtml+xml"?ss:Qn,Q=ye(w,"ALLOWED_TAGS")?F({},w.ALLOWED_TAGS,J):xn,Y=ye(w,"ALLOWED_ATTR")?F({},w.ALLOWED_ATTR,J):An,Ui=ye(w,"ALLOWED_NAMESPACES")?F({},w.ALLOWED_NAMESPACES,ss):Pu,Bi=ye(w,"ADD_URI_SAFE_ATTR")?F(Te(Yo),w.ADD_URI_SAFE_ATTR,J):Yo,Go=ye(w,"ADD_DATA_URI_TAGS")?F(Te(Qo),w.ADD_DATA_URI_TAGS,J):Qo,xe=ye(w,"FORBID_CONTENTS")?F({},w.FORBID_CONTENTS,J):Oi,et=ye(w,"FORBID_TAGS")?F({},w.FORBID_TAGS,J):Te({}),Ut=ye(w,"FORBID_ATTR")?F({},w.FORBID_ATTR,J):Te({}),St=ye(w,"USE_PROFILES")?w.USE_PROFILES:!1,$n=w.ALLOW_ARIA_ATTR!==!1,x=w.ALLOW_DATA_ATTR!==!1,_=w.ALLOW_UNKNOWN_PROTOCOLS||!1,N=w.ALLOW_SELF_CLOSE_IN_ATTR!==!1,O=w.SAFE_FOR_TEMPLATES||!1,V=w.SAFE_FOR_XML!==!1,z=w.WHOLE_DOCUMENT||!1,kt=w.RETURN_DOM||!1,En=w.RETURN_DOM_FRAGMENT||!1,Tn=w.RETURN_TRUSTED_TYPE||!1,je=w.FORCE_BODY||!1,qo=w.SANITIZE_DOM!==!1,Vo=w.SANITIZE_NAMED_PROPS||!1,Di=w.KEEP_CONTENT!==!1,Wt=w.IN_PLACE||!1,Sn=w.ALLOWED_URI_REGEXP||Sc,xt=w.NAMESPACE||Ie,Mn=w.MATHML_TEXT_INTEGRATION_POINTS||Mn,Pn=w.HTML_INTEGRATION_POINTS||Pn,H=w.CUSTOM_ELEMENT_HANDLING||{},w.CUSTOM_ELEMENT_HANDLING&&Xo(w.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(H.tagNameCheck=w.CUSTOM_ELEMENT_HANDLING.tagNameCheck),w.CUSTOM_ELEMENT_HANDLING&&Xo(w.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(H.attributeNameCheck=w.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),w.CUSTOM_ELEMENT_HANDLING&&typeof w.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(H.allowCustomizedBuiltInElements=w.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),O&&(x=!1),En&&(kt=!0),St&&(Q=F({},aa),Y=[],St.html===!0&&(F(Q,ra),F(Y,la)),St.svg===!0&&(F(Q,rs),F(Y,cs),F(Y,Fn)),St.svgFilters===!0&&(F(Q,as),F(Y,cs),F(Y,Fn)),St.mathMl===!0&&(F(Q,ls),F(Y,ca),F(Y,Fn))),w.ADD_TAGS&&(typeof w.ADD_TAGS=="function"?ze.tagCheck=w.ADD_TAGS:(Q===xn&&(Q=Te(Q)),F(Q,w.ADD_TAGS,J))),w.ADD_ATTR&&(typeof w.ADD_ATTR=="function"?ze.attributeCheck=w.ADD_ATTR:(Y===An&&(Y=Te(Y)),F(Y,w.ADD_ATTR,J))),w.ADD_URI_SAFE_ATTR&&F(Bi,w.ADD_URI_SAFE_ATTR,J),w.FORBID_CONTENTS&&(xe===Oi&&(xe=Te(xe)),F(xe,w.FORBID_CONTENTS,J)),w.ADD_FORBID_CONTENTS&&(xe===Oi&&(xe=Te(xe)),F(xe,w.ADD_FORBID_CONTENTS,J)),Di&&(Q["#text"]=!0),z&&F(Q,["html","head","body"]),Q.table&&(F(Q,["tbody"]),delete et.tbody),w.TRUSTED_TYPES_POLICY){if(typeof w.TRUSTED_TYPES_POLICY.createHTML!="function")throw Vt('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof w.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Vt('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=w.TRUSTED_TYPES_POLICY,M=C.createHTML("")}else C===void 0&&(C=Hf(v,s)),C!==null&&typeof M=="string"&&(M=C.createHTML(""));pe&&pe(w),At=w}},Zo=F({},[...rs,...as,...Rf]),Jo=F({},[...ls,...Nf]),Du=function(w){let E=T(w);(!E||!E.tagName)&&(E={namespaceURI:xt,tagName:"template"});const L=Qn(w.tagName),j=Qn(E.tagName);return Ui[w.namespaceURI]?w.namespaceURI===_n?E.namespaceURI===Ie?L==="svg":E.namespaceURI===Cn?L==="svg"&&(j==="annotation-xml"||Mn[j]):!!Zo[L]:w.namespaceURI===Cn?E.namespaceURI===Ie?L==="math":E.namespaceURI===_n?L==="math"&&Pn[j]:!!Jo[L]:w.namespaceURI===Ie?E.namespaceURI===_n&&!Pn[j]||E.namespaceURI===Cn&&!Mn[j]?!1:!Jo[L]&&(Lu[L]||!Zo[L]):!!(Kt==="application/xhtml+xml"&&Ui[w.namespaceURI]):!1},Ae=function(w){Ht(t.removed,{element:w});try{T(w).removeChild(w)}catch{S(w)}},tt=function(w,E){try{Ht(t.removed,{attribute:E.getAttributeNode(w),from:E})}catch{Ht(t.removed,{attribute:null,from:E})}if(E.removeAttribute(w),w==="is")if(kt||En)try{Ae(E)}catch{}else try{E.setAttribute(w,"")}catch{}},er=function(w){let E=null,L=null;if(je)w="<remove></remove>"+w;else{const X=os(w,/^[\r\n\t ]+/);L=X&&X[0]}Kt==="application/xhtml+xml"&&xt===Ie&&(w='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+w+"</body></html>");const j=C?C.createHTML(w):w;if(xt===Ie)try{E=new h().parseFromString(j,Kt)}catch{}if(!E||!E.documentElement){E=R.createDocument(xt,"template",null);try{E.documentElement.innerHTML=Fi?M:j}catch{}}const se=E.body||E.documentElement;return w&&L&&se.insertBefore(n.createTextNode(L),se.childNodes[0]||null),xt===Ie?me.call(E,z?"html":"body")[0]:z?E.documentElement:se},tr=function(w){return B.call(w.ownerDocument||w,w,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Ki=function(w){return w instanceof d&&(typeof w.nodeName!="string"||typeof w.textContent!="string"||typeof w.removeChild!="function"||!(w.attributes instanceof l)||typeof w.removeAttribute!="function"||typeof w.setAttribute!="function"||typeof w.namespaceURI!="string"||typeof w.insertBefore!="function"||typeof w.hasChildNodes!="function")},nr=function(w){return typeof a=="function"&&w instanceof a};function Re(I,w,E){Bn(I,L=>{L.call(t,w,E,At)})}const ir=function(w){let E=null;if(Re(Z.beforeSanitizeElements,w,null),Ki(w))return Ae(w),!0;const L=J(w.nodeName);if(Re(Z.uponSanitizeElement,w,{tagName:L,allowedTags:Q}),V&&w.hasChildNodes()&&!nr(w.firstElementChild)&&le(/<[/\w!]/g,w.innerHTML)&&le(/<[/\w!]/g,w.textContent)||w.nodeType===Qt.progressingInstruction||V&&w.nodeType===Qt.comment&&le(/<[/\w]/g,w.data))return Ae(w),!0;if(!(ze.tagCheck instanceof Function&&ze.tagCheck(L))&&(!Q[L]||et[L])){if(!et[L]&&or(L)&&(H.tagNameCheck instanceof RegExp&&le(H.tagNameCheck,L)||H.tagNameCheck instanceof Function&&H.tagNameCheck(L)))return!1;if(Di&&!xe[L]){const j=T(w)||w.parentNode,se=$(w)||w.childNodes;if(se&&j){const X=se.length;for(let fe=X-1;fe>=0;--fe){const Ne=b(se[fe],!0);Ne.__removalCount=(w.__removalCount||0)+1,j.insertBefore(Ne,A(w))}}}return Ae(w),!0}return w instanceof u&&!Du(w)||(L==="noscript"||L==="noembed"||L==="noframes")&&le(/<\/no(script|embed|frames)/i,w.innerHTML)?(Ae(w),!0):(O&&w.nodeType===Qt.text&&(E=w.textContent,Bn([Ft,wt,Je],j=>{E=qt(E,j," ")}),w.textContent!==E&&(Ht(t.removed,{element:w.cloneNode()}),w.textContent=E)),Re(Z.afterSanitizeElements,w,null),!1)},sr=function(w,E,L){if(qo&&(E==="id"||E==="name")&&(L in n||L in Nu))return!1;if(!(x&&!Ut[E]&&le(Li,E))){if(!($n&&le(Ii,E))){if(!(ze.attributeCheck instanceof Function&&ze.attributeCheck(E,w))){if(!Y[E]||Ut[E]){if(!(or(w)&&(H.tagNameCheck instanceof RegExp&&le(H.tagNameCheck,w)||H.tagNameCheck instanceof Function&&H.tagNameCheck(w))&&(H.attributeNameCheck instanceof RegExp&&le(H.attributeNameCheck,E)||H.attributeNameCheck instanceof Function&&H.attributeNameCheck(E,w))||E==="is"&&H.allowCustomizedBuiltInElements&&(H.tagNameCheck instanceof RegExp&&le(H.tagNameCheck,L)||H.tagNameCheck instanceof Function&&H.tagNameCheck(L))))return!1}else if(!Bi[E]){if(!le(Sn,qt(L,kn,""))){if(!((E==="src"||E==="xlink:href"||E==="href")&&w!=="script"&&Mf(L,"data:")===0&&Go[w])){if(!(_&&!le(Ri,qt(L,kn,"")))){if(L)return!1}}}}}}}return!0},or=function(w){return w!=="annotation-xml"&&os(w,Ni)},rr=function(w){Re(Z.beforeSanitizeAttributes,w,null);const{attributes:E}=w;if(!E||Ki(w))return;const L={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Y,forceKeepAttr:void 0};let j=E.length;for(;j--;){const se=E[j],{name:X,namespaceURI:fe,value:Ne}=se,$t=J(X),zi=Ne;let ne=X==="value"?zi:Pf(zi);if(L.attrName=$t,L.attrValue=ne,L.keepAttr=!0,L.forceKeepAttr=void 0,Re(Z.uponSanitizeAttribute,w,L),ne=L.attrValue,Vo&&($t==="id"||$t==="name")&&(tt(X,w),ne=Mu+ne),V&&le(/((--!?|])>)|<\/(style|title|textarea)/i,ne)){tt(X,w);continue}if($t==="attributename"&&os(ne,"href")){tt(X,w);continue}if(L.forceKeepAttr)continue;if(!L.keepAttr){tt(X,w);continue}if(!N&&le(/\/>/i,ne)){tt(X,w);continue}O&&Bn([Ft,wt,Je],lr=>{ne=qt(ne,lr," ")});const ar=J(w.nodeName);if(!sr(ar,$t,ne)){tt(X,w);continue}if(C&&typeof v=="object"&&typeof v.getAttributeType=="function"&&!fe)switch(v.getAttributeType(ar,$t)){case"TrustedHTML":{ne=C.createHTML(ne);break}case"TrustedScriptURL":{ne=C.createScriptURL(ne);break}}if(ne!==zi)try{fe?w.setAttributeNS(fe,X,ne):w.setAttribute(X,ne),Ki(w)?Ae(w):oa(t.removed)}catch{tt(X,w)}}Re(Z.afterSanitizeAttributes,w,null)},Ou=function I(w){let E=null;const L=tr(w);for(Re(Z.beforeSanitizeShadowDOM,w,null);E=L.nextNode();)Re(Z.uponSanitizeShadowNode,E,null),ir(E),rr(E),E.content instanceof o&&I(E.content);Re(Z.afterSanitizeShadowDOM,w,null)};return t.sanitize=function(I){let w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E=null,L=null,j=null,se=null;if(Fi=!I,Fi&&(I="<!-->"),typeof I!="string"&&!nr(I))if(typeof I.toString=="function"){if(I=I.toString(),typeof I!="string")throw Vt("dirty is not a string, aborting")}else throw Vt("toString is not a function");if(!t.isSupported)return I;if(ae||Wi(w),t.removed=[],typeof I=="string"&&(Wt=!1),Wt){if(I.nodeName){const Ne=J(I.nodeName);if(!Q[Ne]||et[Ne])throw Vt("root node is forbidden and cannot be sanitized in-place")}}else if(I instanceof a)E=er("<!---->"),L=E.ownerDocument.importNode(I,!0),L.nodeType===Qt.element&&L.nodeName==="BODY"||L.nodeName==="HTML"?E=L:E.appendChild(L);else{if(!kt&&!O&&!z&&I.indexOf("<")===-1)return C&&Tn?C.createHTML(I):I;if(E=er(I),!E)return kt?null:Tn?M:""}E&&je&&Ae(E.firstChild);const X=tr(Wt?I:E);for(;j=X.nextNode();)ir(j),rr(j),j.content instanceof o&&Ou(j.content);if(Wt)return I;if(kt){if(En)for(se=ee.call(E.ownerDocument);E.firstChild;)se.appendChild(E.firstChild);else se=E;return(Y.shadowroot||Y.shadowrootmode)&&(se=Ke.call(i,se,!0)),se}let fe=z?E.outerHTML:E.innerHTML;return z&&Q["!doctype"]&&E.ownerDocument&&E.ownerDocument.doctype&&E.ownerDocument.doctype.name&&le(xc,E.ownerDocument.doctype.name)&&(fe="<!DOCTYPE "+E.ownerDocument.doctype.name+`>
2043
+ `+fe),O&&Bn([Ft,wt,Je],Ne=>{fe=qt(fe,Ne," ")}),C&&Tn?C.createHTML(fe):fe},t.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Wi(I),ae=!0},t.clearConfig=function(){At=null,ae=!1},t.isValidAttribute=function(I,w,E){At||Wi({});const L=J(I),j=J(w);return sr(L,j,E)},t.addHook=function(I,w){typeof w=="function"&&Ht(Z[I],w)},t.removeHook=function(I,w){if(w!==void 0){const E=Cf(Z[I],w);return E===-1?void 0:_f(Z[I],E,1)[0]}return oa(Z[I])},t.removeHooks=function(I){Z[I]=[]},t.removeAllHooks=function(){Z=da()},t}var Bs=Ac();function Co(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var vt=Co();function $c(e){vt=e}var an={exec:()=>null};function W(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(s,o)=>{let r=typeof o=="string"?o:o.source;return r=r.replace(ue.caret,"$1"),n=n.replace(s,r),i},getRegex:()=>new RegExp(n,t)};return i}var qf=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),ue={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},Vf=/^(?:[ \t]*(?:\n|$))+/,Gf=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Qf=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,bn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Yf=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,_o=/(?:[*+-]|\d{1,9}[.)])/,Ec=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Tc=W(Ec).replace(/bull/g,_o).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(),Xf=W(Ec).replace(/bull/g,_o).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(),Mo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Zf=/^[^\n]+/,Po=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Jf=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Po).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),eg=W(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,_o).getRegex(),Ci="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",Lo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,tg=W("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Lo).replace("tag",Ci).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Cc=W(Mo).replace("hr",bn).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",Ci).getRegex(),ng=W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Cc).getRegex(),Io={blockquote:ng,code:Gf,def:Jf,fences:Qf,heading:Yf,hr:bn,html:tg,lheading:Tc,list:eg,newline:Vf,paragraph:Cc,table:an,text:Zf},pa=W("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",bn).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",Ci).getRegex(),ig={...Io,lheading:Xf,table:pa,paragraph:W(Mo).replace("hr",bn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",pa).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",Ci).getRegex()},sg={...Io,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Lo).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:an,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(Mo).replace("hr",bn).replace("heading",` *#{1,6} *[^
2044
+ ]`).replace("lheading",Tc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},og=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,rg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,_c=/^( {2,}|\\)\n(?!\s*$)/,ag=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_i=/[\p{P}\p{S}]/u,Ro=/[\s\p{P}\p{S}]/u,Mc=/[^\s\p{P}\p{S}]/u,lg=W(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ro).getRegex(),Pc=/(?!~)[\p{P}\p{S}]/u,cg=/(?!~)[\s\p{P}\p{S}]/u,ug=/(?:[^\s\p{P}\p{S}]|~)/u,dg=W(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",qf?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Lc=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,pg=W(Lc,"u").replace(/punct/g,_i).getRegex(),hg=W(Lc,"u").replace(/punct/g,Pc).getRegex(),Ic="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",fg=W(Ic,"gu").replace(/notPunctSpace/g,Mc).replace(/punctSpace/g,Ro).replace(/punct/g,_i).getRegex(),gg=W(Ic,"gu").replace(/notPunctSpace/g,ug).replace(/punctSpace/g,cg).replace(/punct/g,Pc).getRegex(),mg=W("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Mc).replace(/punctSpace/g,Ro).replace(/punct/g,_i).getRegex(),yg=W(/\\(punct)/,"gu").replace(/punct/g,_i).getRegex(),vg=W(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),bg=W(Lo).replace("(?:-->|$)","-->").getRegex(),wg=W("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",bg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ui=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,kg=W(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",ui).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rc=W(/^!?\[(label)\]\[(ref)\]/).replace("label",ui).replace("ref",Po).getRegex(),Nc=W(/^!?\[(ref)\](?:\[\])?/).replace("ref",Po).getRegex(),Sg=W("reflink|nolink(?!\\()","g").replace("reflink",Rc).replace("nolink",Nc).getRegex(),ha=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,No={_backpedal:an,anyPunctuation:yg,autolink:vg,blockSkip:dg,br:_c,code:rg,del:an,emStrongLDelim:pg,emStrongRDelimAst:fg,emStrongRDelimUnd:mg,escape:og,link:kg,nolink:Nc,punctuation:lg,reflink:Rc,reflinkSearch:Sg,tag:wg,text:ag,url:an},xg={...No,link:W(/^!?\[(label)\]\((.*?)\)/).replace("label",ui).getRegex(),reflink:W(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ui).getRegex()},Fs={...No,emStrongRDelimAst:gg,emStrongLDelim:hg,url:W(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ha).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:W(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ha).getRegex()},Ag={...Fs,br:W(_c).replace("{2,}","*").getRegex(),text:W(Fs.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Un={normal:Io,gfm:ig,pedantic:sg},Yt={normal:No,gfm:Fs,breaks:Ag,pedantic:xg},$g={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},fa=e=>$g[e];function Oe(e,t){if(t){if(ue.escapeTest.test(e))return e.replace(ue.escapeReplace,fa)}else if(ue.escapeTestNoEncode.test(e))return e.replace(ue.escapeReplaceNoEncode,fa);return e}function ga(e){try{e=encodeURI(e).replace(ue.percentDecode,"%")}catch{return null}return e}function ma(e,t){var o;let n=e.replace(ue.findPipe,(r,a,u)=>{let c=!1,l=a;for(;--l>=0&&u[l]==="\\";)c=!c;return c?"|":" |"}),i=n.split(ue.splitPipe),s=0;if(i[0].trim()||i.shift(),i.length>0&&!((o=i.at(-1))!=null&&o.trim())&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;s<i.length;s++)i[s]=i[s].trim().replace(ue.slashPipe,"|");return i}function Xt(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 Eg(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 ya(e,t,n,i,s){let o=t.href,r=t.title||null,a=e[1].replace(s.other.outputLinkReplace,"$1");i.state.inLink=!0;let u={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:r,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,u}function Tg(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
2045
+ `).map(o=>{let r=o.match(n.other.beginningSpace);if(r===null)return o;let[a]=r;return a.length>=s.length?o.slice(s.length):o}).join(`
2046
+ `)}var di=class{constructor(e){U(this,"options");U(this,"rules");U(this,"lexer");this.options=e||vt}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:Xt(n,`
2047
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=Tg(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=Xt(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:Xt(t[0],`
2048
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Xt(t[0],`
2049
+ `).split(`
2050
+ `),i="",s="",o=[];for(;n.length>0;){let r=!1,a=[],u;for(u=0;u<n.length;u++)if(this.rules.other.blockquoteStart.test(n[u]))a.push(n[u]),r=!0;else if(!r)a.push(n[u]);else break;n=n.slice(u);let c=a.join(`
2051
+ `),l=c.replace(this.rules.other.blockquoteSetextReplace,`
2052
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
2053
+ ${c}`:c,s=s?`${s}
2054
+ ${l}`:l;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(l,o,!0),this.lexer.state.top=d,n.length===0)break;let h=o.at(-1);if((h==null?void 0:h.type)==="code")break;if((h==null?void 0:h.type)==="blockquote"){let v=h,f=v.raw+`
2055
+ `+n.join(`
2056
+ `),b=this.blockquote(f);o[o.length-1]=b,i=i.substring(0,i.length-v.raw.length)+b.raw,s=s.substring(0,s.length-v.text.length)+b.text;break}else if((h==null?void 0:h.type)==="list"){let v=h,f=v.raw+`
2057
+ `+n.join(`
2058
+ `),b=this.list(f);o[o.length-1]=b,i=i.substring(0,i.length-h.raw.length)+b.raw,s=s.substring(0,s.length-v.raw.length)+b.raw,n=f.substring(o.at(-1).raw.length).split(`
2059
+ `);continue}}return{type:"blockquote",raw:i,tokens:o,text:s}}}list(e){var n,i;let t=this.rules.block.list.exec(e);if(t){let s=t[1].trim(),o=s.length>1,r={type:"list",raw:"",ordered:o,start:o?+s.slice(0,-1):"",loose:!1,items:[]};s=o?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=o?s:"[*+-]");let a=this.rules.other.listItemRegex(s),u=!1;for(;e;){let l=!1,d="",h="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let v=t[2].split(`
2060
+ `,1)[0].replace(this.rules.other.listReplaceTabs,A=>" ".repeat(3*A.length)),f=e.split(`
2061
+ `,1)[0],b=!v.trim(),S=0;if(this.options.pedantic?(S=2,h=v.trimStart()):b?S=t[1].length+1:(S=t[2].search(this.rules.other.nonSpaceChar),S=S>4?1:S,h=v.slice(S),S+=t[1].length),b&&this.rules.other.blankLine.test(f)&&(d+=f+`
2062
+ `,e=e.substring(f.length+1),l=!0),!l){let A=this.rules.other.nextBulletRegex(S),$=this.rules.other.hrRegex(S),T=this.rules.other.fencesBeginRegex(S),C=this.rules.other.headingBeginRegex(S),M=this.rules.other.htmlBeginRegex(S);for(;e;){let R=e.split(`
2063
+ `,1)[0],B;if(f=R,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),B=f):B=f.replace(this.rules.other.tabCharGlobal," "),T.test(f)||C.test(f)||M.test(f)||A.test(f)||$.test(f))break;if(B.search(this.rules.other.nonSpaceChar)>=S||!f.trim())h+=`
2064
+ `+B.slice(S);else{if(b||v.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||T.test(v)||C.test(v)||$.test(v))break;h+=`
2065
+ `+f}!b&&!f.trim()&&(b=!0),d+=R+`
2066
+ `,e=e.substring(R.length+1),v=B.slice(S)}}r.loose||(u?r.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(u=!0)),r.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),r.raw+=d}let c=r.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let l of r.items){if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),l.task){if(l.text=l.text.replace(this.rules.other.listReplaceTask,""),((n=l.tokens[0])==null?void 0:n.type)==="text"||((i=l.tokens[0])==null?void 0:i.type)==="paragraph"){l.tokens[0].raw=l.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),l.tokens[0].text=l.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}}let d=this.rules.other.listTaskCheckbox.exec(l.raw);if(d){let h={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};l.checked=h.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=h.raw+l.tokens[0].raw,l.tokens[0].text=h.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(h)):l.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):l.tokens.unshift(h)}}if(!r.loose){let d=l.tokens.filter(v=>v.type==="space"),h=d.length>0&&d.some(v=>this.rules.other.anyLine.test(v.raw));r.loose=h}}if(r.loose)for(let l of r.items){l.loose=!0;for(let d of l.tokens)d.type==="text"&&(d.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:i,title:s}}}table(e){var r;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ma(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=(r=t[3])!=null&&r.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
2067
+ `):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===i.length){for(let a of i)this.rules.other.tableAlignRight.test(a)?o.align.push("right"):this.rules.other.tableAlignCenter.test(a)?o.align.push("center"):this.rules.other.tableAlignLeft.test(a)?o.align.push("left"):o.align.push(null);for(let a=0;a<n.length;a++)o.header.push({text:n[a],tokens:this.lexer.inline(n[a]),header:!0,align:o.align[a]});for(let a of s)o.rows.push(ma(a,o.header.length).map((u,c)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
2068
+ `?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=Xt(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=Eg(t[2],"()");if(o===-2)return;if(o>-1){let r=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,r).trim(),t[3]=""}}let i=t[2],s="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(i);o&&(i=o[1],s=o[3])}else s=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?i=i.slice(1):i=i.slice(1,-1)),ya(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 ya(n,s,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||i[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[2])||!n||this.rules.inline.punctuation.exec(n))){let s=[...i[0]].length-1,o,r,a=s,u=0,c=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(i=c.exec(t))!=null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o)continue;if(r=[...o].length,i[3]||i[4]){a+=r;continue}else if((i[5]||i[6])&&s%3&&!((s+r)%3)){u+=r;continue}if(a-=r,a>0)continue;r=Math.min(r,r+a+u);let l=[...i[0]][0].length,d=e.slice(0,s+i.index+l+r);if(Math.min(s,r)%2){let v=d.slice(1,-1);return{type:"em",raw:d,text:v,tokens:this.lexer.inlineTokens(v)}}let h=d.slice(2,-2);return{type:"strong",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,i;return t[2]==="@"?(n=t[1],i="mailto:"+n):(n=t[1],i=n),{type:"link",raw:t[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n;let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=((n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},ve=class Us{constructor(t){U(this,"tokens");U(this,"options");U(this,"state");U(this,"inlineQueue");U(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||vt,this.options.tokenizer=this.options.tokenizer||new di,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:ue,block:Un.normal,inline:Yt.normal};this.options.pedantic?(n.block=Un.pedantic,n.inline=Yt.pedantic):this.options.gfm&&(n.block=Un.gfm,this.options.breaks?n.inline=Yt.breaks:n.inline=Yt.gfm),this.tokenizer.rules=n}static get rules(){return{block:Un,inline:Yt}}static lex(t,n){return new Us(n).lex(t)}static lexInline(t,n){return new Us(n).inlineTokens(t)}lex(t){t=t.replace(ue.carriageReturn,`
2069
+ `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let i=this.inlineQueue[n];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],i=!1){var s,o,r;for(this.options.pedantic&&(t=t.replace(ue.tabCharGlobal," ").replace(ue.spaceLine,""));t;){let a;if((o=(s=this.options.extensions)==null?void 0:s.block)!=null&&o.some(c=>(a=c.call({lexer:this},t,n))?(t=t.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let c=n.at(-1);a.raw.length===1&&c!==void 0?c.raw+=`
2070
+ `:n.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2071
+ `)?"":`
2072
+ `)+a.raw,c.text+=`
2073
+ `+a.text,this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2074
+ `)?"":`
2075
+ `)+a.raw,c.text+=`
2076
+ `+a.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},n.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),n.push(a);continue}let u=t;if((r=this.options.extensions)!=null&&r.startBlock){let c=1/0,l=t.slice(1),d;this.options.extensions.startBlock.forEach(h=>{d=h.call({lexer:this},l),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(u=t.substring(0,c+1))}if(this.state.top&&(a=this.tokenizer.paragraph(u))){let c=n.at(-1);i&&(c==null?void 0:c.type)==="paragraph"?(c.raw+=(c.raw.endsWith(`
2077
+ `)?"":`
2078
+ `)+a.raw,c.text+=`
2079
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a),i=u.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let c=n.at(-1);(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(`
2080
+ `)?"":`
2081
+ `)+a.raw,c.text+=`
2082
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var u,c,l,d,h;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=(u=this.options.hooks)==null?void 0:u.emStrongMask)==null?void 0:c.call({lexer:this},i))??i;let r=!1,a="";for(;t;){r||(a=""),r=!1;let v;if((d=(l=this.options.extensions)==null?void 0:l.inline)!=null&&d.some(b=>(v=b.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 b=n.at(-1);v.type==="text"&&(b==null?void 0:b.type)==="text"?(b.raw+=v.raw,b.text+=v.text):n.push(v);continue}if(v=this.tokenizer.emStrong(t,i,a)){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 f=t;if((h=this.options.extensions)!=null&&h.startInline){let b=1/0,S=t.slice(1),A;this.options.extensions.startInline.forEach($=>{A=$.call({lexer:this},S),typeof A=="number"&&A>=0&&(b=Math.min(b,A))}),b<1/0&&b>=0&&(f=t.substring(0,b+1))}if(v=this.tokenizer.inlineText(f)){t=t.substring(v.raw.length),v.raw.slice(-1)!=="_"&&(a=v.raw.slice(-1)),r=!0;let b=n.at(-1);(b==null?void 0:b.type)==="text"?(b.raw+=v.raw,b.text+=v.text):n.push(v);continue}if(t){let b="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(b);break}else throw new Error(b)}}return n}},pi=class{constructor(e){U(this,"options");U(this,"parser");this.options=e||vt}space(e){return""}code({text:e,lang:t,escaped:n}){var o;let i=(o=(t||"").match(ue.notSpaceStart))==null?void 0:o[0],s=e.replace(ue.endingNewline,"")+`
2083
+ `;return i?'<pre><code class="language-'+Oe(i)+'">'+(n?s:Oe(s,!0))+`</code></pre>
2084
+ `:"<pre><code>"+(n?s:Oe(s,!0))+`</code></pre>
2085
+ `}blockquote({tokens:e}){return`<blockquote>
2086
+ ${this.parser.parse(e)}</blockquote>
2087
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
2088
+ `}hr(e){return`<hr>
2089
+ `}list(e){let t=e.ordered,n=e.start,i="";for(let r=0;r<e.items.length;r++){let a=e.items[r];i+=this.listitem(a)}let s=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+s+o+`>
2090
+ `+i+"</"+s+`>
2091
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
2092
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
2093
+ `}table(e){let t="",n="";for(let s=0;s<e.header.length;s++)n+=this.tablecell(e.header[s]);t+=this.tablerow({text:n});let i="";for(let s=0;s<e.rows.length;s++){let o=e.rows[s];n="";for(let r=0;r<o.length;r++)n+=this.tablecell(o[r]);i+=this.tablerow({text:n})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
2094
+ <thead>
2095
+ `+t+`</thead>
2096
+ `+i+`</table>
2097
+ `}tablerow({text:e}){return`<tr>
2098
+ ${e}</tr>
2099
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
2100
+ `}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>${Oe(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=ga(e);if(s===null)return i;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+Oe(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=ga(e);if(s===null)return Oe(n);e=s;let o=`<img src="${e}" alt="${n}"`;return t&&(o+=` title="${Oe(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Oe(e.text)}},Do=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}},be=class Ws{constructor(t){U(this,"options");U(this,"renderer");U(this,"textRenderer");this.options=t||vt,this.options.renderer=this.options.renderer||new pi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Do}static parse(t,n){return new Ws(n).parse(t)}static parseInline(t,n){return new Ws(n).parseInline(t)}parse(t){var i,s;let n="";for(let o=0;o<t.length;o++){let r=t[o];if((s=(i=this.options.extensions)==null?void 0:i.renderers)!=null&&s[r.type]){let u=r,c=this.options.extensions.renderers[u.type].call({parser:this},u);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(u.type)){n+=c||"";continue}}let a=r;switch(a.type){case"space":{n+=this.renderer.space(a);break}case"hr":{n+=this.renderer.hr(a);break}case"heading":{n+=this.renderer.heading(a);break}case"code":{n+=this.renderer.code(a);break}case"table":{n+=this.renderer.table(a);break}case"blockquote":{n+=this.renderer.blockquote(a);break}case"list":{n+=this.renderer.list(a);break}case"checkbox":{n+=this.renderer.checkbox(a);break}case"html":{n+=this.renderer.html(a);break}case"def":{n+=this.renderer.def(a);break}case"paragraph":{n+=this.renderer.paragraph(a);break}case"text":{n+=this.renderer.text(a);break}default:{let u='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return n}parseInline(t,n=this.renderer){var s,o;let i="";for(let r=0;r<t.length;r++){let a=t[r];if((o=(s=this.options.extensions)==null?void 0:s.renderers)!=null&&o[a.type]){let c=this.options.extensions.renderers[a.type].call({parser:this},a);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){i+=c||"";continue}}let u=a;switch(u.type){case"escape":{i+=n.text(u);break}case"html":{i+=n.html(u);break}case"link":{i+=n.link(u);break}case"image":{i+=n.image(u);break}case"checkbox":{i+=n.checkbox(u);break}case"strong":{i+=n.strong(u);break}case"em":{i+=n.em(u);break}case"codespan":{i+=n.codespan(u);break}case"br":{i+=n.br(u);break}case"del":{i+=n.del(u);break}case"text":{i+=n.text(u);break}default:{let c='Token with "'+u.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return i}},qn,en=(qn=class{constructor(e){U(this,"options");U(this,"block");this.options=e||vt}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?ve.lex:ve.lexInline}provideParser(){return this.block?be.parse:be.parseInline}},U(qn,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),U(qn,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),qn),Cg=class{constructor(...e){U(this,"defaults",Co());U(this,"options",this.setOptions);U(this,"parse",this.parseMarkdown(!0));U(this,"parseInline",this.parseMarkdown(!1));U(this,"Parser",be);U(this,"Renderer",pi);U(this,"TextRenderer",Do);U(this,"Lexer",ve);U(this,"Tokenizer",di);U(this,"Hooks",en);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 r=o;for(let a of r.header)n=n.concat(this.walkTokens(a.tokens,t));for(let a of r.rows)for(let u of a)n=n.concat(this.walkTokens(u.tokens,t));break}case"list":{let r=o;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=o;(s=(i=this.defaults.extensions)==null?void 0:i.childTokens)!=null&&s[r.type]?this.defaults.extensions.childTokens[r.type].forEach(a=>{let u=r[a].flat(1/0);n=n.concat(this.walkTokens(u,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.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(...r){let a=s.renderer.apply(this,r);return a===!1&&(a=o.apply(this,r)),a}: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 pi(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 r=o,a=n.renderer[r],u=s[r];s[r]=(...c)=>{let l=a.apply(s,c);return l===!1&&(l=u.apply(s,c)),l||""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new di(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 r=o,a=n.tokenizer[r],u=s[r];s[r]=(...c)=>{let l=a.apply(s,c);return l===!1&&(l=u.apply(s,c)),l}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new en;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 r=o,a=n.hooks[r],u=s[r];en.passThroughHooks.has(o)?s[r]=c=>{if(this.defaults.async&&en.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await a.call(s,c);return u.call(s,d)})();let l=a.call(s,c);return u.call(s,l)}:s[r]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await a.apply(s,c);return d===!1&&(d=await u.apply(s,c)),d})();let l=a.apply(s,c);return l===!1&&(l=u.apply(s,c)),l}}i.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(r){let a=[];return a.push(o.call(this,r)),s&&(a=a.concat(s.call(this,r))),a}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ve.lex(e,t??this.defaults)}parser(e,t){return be.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 r=s.hooks?await s.hooks.preprocess(t):t,a=await(s.hooks?await s.hooks.provideLexer():e?ve.lex:ve.lexInline)(r,s),u=s.hooks?await s.hooks.processAllTokens(a):a;s.walkTokens&&await Promise.all(this.walkTokens(u,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser():e?be.parse:be.parseInline)(u,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(o);try{s.hooks&&(t=s.hooks.preprocess(t));let r=(s.hooks?s.hooks.provideLexer():e?ve.lex:ve.lexInline)(t,s);s.hooks&&(r=s.hooks.processAllTokens(r)),s.walkTokens&&this.walkTokens(r,s.walkTokens);let a=(s.hooks?s.hooks.provideParser():e?be.parse:be.parseInline)(r,s);return s.hooks&&(a=s.hooks.postprocess(a)),a}catch(r){return o(r)}}}onError(e,t){return n=>{if(n.message+=`
2101
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Oe(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},ft=new Cg;function K(e,t){return ft.parse(e,t)}K.options=K.setOptions=function(e){return ft.setOptions(e),K.defaults=ft.defaults,$c(K.defaults),K};K.getDefaults=Co;K.defaults=vt;K.use=function(...e){return ft.use(...e),K.defaults=ft.defaults,$c(K.defaults),K};K.walkTokens=function(e,t){return ft.walkTokens(e,t)};K.parseInline=ft.parseInline;K.Parser=be;K.parser=be.parse;K.Renderer=pi;K.TextRenderer=Do;K.Lexer=ve;K.lexer=ve.lex;K.Tokenizer=di;K.Hooks=en;K.parse=K;K.options;K.setOptions;K.use;K.walkTokens;K.parseInline;be.parse;ve.lex;K.setOptions({gfm:!0,breaks:!0,mangle:!1});const va=["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"],ba=["class","href","rel","target","title","start"];let wa=!1;const _g=14e4,Mg=4e4,Pg=200,us=5e4,rt=new Map;function Lg(e){const t=rt.get(e);return t===void 0?null:(rt.delete(e),rt.set(e,t),t)}function ka(e,t){if(rt.set(e,t),rt.size<=Pg)return;const n=rt.keys().next().value;n&&rt.delete(n)}function Ig(){wa||(wa=!0,Bs.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function hi(e){const t=e.trim();if(!t)return"";if(Ig(),t.length<=us){const r=Lg(t);if(r!==null)return r}const n=hl(t,_g),i=n.truncated?`
2102
+
2103
+ … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>Mg){const a=`<pre class="code-block">${Rg(`${n.text}${i}`)}</pre>`,u=Bs.sanitize(a,{ALLOWED_TAGS:va,ALLOWED_ATTR:ba});return t.length<=us&&ka(t,u),u}const s=K.parse(`${n.text}${i}`),o=Bs.sanitize(s,{ALLOWED_TAGS:va,ALLOWED_ATTR:ba});return t.length<=us&&ka(t,o),o}function Rg(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const Ng=1500,Dg=2e3,Dc="Copy as markdown",Og="Copied",Bg="Copy failed";async function Fg(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 Wn(e,t){e.title=t,e.setAttribute("aria-label",t)}function Ug(e){const t=e.label??Dc;return p`
2104
+ <button
2105
+ class="chat-copy-btn"
2106
+ type="button"
2107
+ title=${t}
2108
+ aria-label=${t}
2109
+ @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 Fg(e.text());if(i.isConnected){if(delete i.dataset.copying,i.removeAttribute("aria-busy"),i.disabled=!1,!s){i.dataset.error="1",Wn(i,Bg),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.error,Wn(i,t))},Dg);return}i.dataset.copied="1",Wn(i,Og),window.setTimeout(()=>{i.isConnected&&(delete i.dataset.copied,Wn(i,t))},Ng)}}}
2110
+ >
2111
+ <span class="chat-copy-btn__icon" aria-hidden="true">
2112
+ <span class="chat-copy-btn__icon-copy">${D.copy}</span>
2113
+ <span class="chat-copy-btn__icon-check">${D.check}</span>
2114
+ </span>
2115
+ </button>
2116
+ `}function Wg(e){return Ug({text:()=>e,label:Dc})}function Kg(e){const t=e,n=zg(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:jg(s.arguments??s.args)})}for(const s of n){const o=String(s.type??"").toLowerCase();if(o!=="toolresult"&&o!=="tool_result")continue;const r=Hg(s),a=typeof s.name=="string"?s.name:"tool";i.push({kind:"result",name:a,text:r})}if(vl(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=fl(e)??void 0;i.push({kind:"result",name:s,text:o})}return i}function zg(e){return Array.isArray(e)?e.filter(Boolean):[]}function jg(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 Hg(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}function qg(e){var s;const n=e.content,i=[];if(Array.isArray(n))for(const o of n){if(typeof o!="object"||o===null)continue;const r=o;if(r.type==="image")if(((s=r.source)==null?void 0:s.type)==="base64"){const a=r.source,u=a.data,c=a.media_type||"image/png",l=u.startsWith("data:")?u:`data:${c};base64,${u}`;i.push({url:l})}else if(typeof r.data=="string"&&r.data){const a=r.data,u=r.mimeType||r.media_type||"image/png",c=a.startsWith("data:")?a:`data:${u};base64,${a}`;i.push({url:c})}else typeof r.url=="string"&&i.push({url:r.url});else if(r.type==="image_url"){const a=r.image_url;typeof(a==null?void 0:a.url)=="string"&&i.push({url:a.url})}}return i}function Vg(e){return p`
2117
+ <div class="chat-group assistant">
2118
+ <div class="chat-group-messages">
2119
+ <div class="chat-bubble chat-reading-indicator" aria-hidden="true">
2120
+ <span class="chat-reading-indicator__dots">
2121
+ <span></span><span></span><span></span>
2122
+ </span>
2123
+ </div>
2124
+ </div>
2125
+ </div>
2126
+ `}function Gg(e){return p`
2127
+ <div class="chat-group assistant">
2128
+ <div class="chat-group-messages">
2129
+ <div class="chat-interim fade-in">
2130
+ ${ci(hi(e))}
2131
+ </div>
2132
+ </div>
2133
+ </div>
2134
+ `}function Qg(e,t,n,i){return p`
2135
+ <div class="chat-group assistant">
2136
+ <div class="chat-group-messages">
2137
+ ${Oc({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!1,showReasoning:!1})}
2138
+ </div>
2139
+ </div>
2140
+ `}function Yg(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 p`
2141
+ <div class="chat-group ${i}">
2142
+ <div class="chat-group-messages">
2143
+ ${e.messages.map((o,r)=>Oc(o.message,{isStreaming:e.isStreaming&&r===e.messages.length-1,showReasoning:t.showReasoning}))}
2144
+ <div class="chat-group-footer">
2145
+ <span class="chat-group-timestamp">${s}</span>
2146
+ </div>
2147
+ </div>
2148
+ </div>
2149
+ `}function Xg(e){return e.length===0?k:p`
2150
+ <div class="chat-message-images">
2151
+ ${e.map(t=>p`
2152
+ <img
2153
+ src=${t.url}
2154
+ alt=${t.alt??"Attached image"}
2155
+ class="chat-message-image"
2156
+ @click=${()=>window.open(t.url,"_blank")}
2157
+ />
2158
+ `)}
2159
+ </div>
2160
+ `}function Oc(e,t,n){const i=e,s=typeof i.role=="string"?i.role:"unknown",o=vl(e)||s.toLowerCase()==="toolresult"||s.toLowerCase()==="tool_result"||typeof i.toolCallId=="string"||typeof i.tool_call_id=="string",a=Kg(e).length>0,u=qg(e),c=u.length>0,l=fl(e),d=t.showReasoning&&s==="assistant"?$d(e):null,h=l!=null&&l.trim()?l:null,v=d?Td(d):null,f=h,b=(s==="assistant"||s==="user")&&!!(f!=null&&f.trim()),S=["chat-bubble",b?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!f&&(a||o)||!f&&!c?k:p`
2161
+ <div class="${S}">
2162
+ ${b?Wg(f):k}
2163
+ ${Xg(u)}
2164
+ ${v?p`<div class="chat-thinking">${ci(hi(v))}</div>`:k}
2165
+ ${f?p`<div class="chat-text">${ci(hi(f))}</div>`:k}
2166
+ </div>
2167
+ `}function Zg(e){return p`
2168
+ <div class="sidebar-panel">
2169
+ <div class="sidebar-header">
2170
+ <div class="sidebar-title">Tool Output</div>
2171
+ <button @click=${e.onClose} class="btn" title="Close sidebar">
2172
+ ${D.x}
2173
+ </button>
2174
+ </div>
2175
+ <div class="sidebar-content">
2176
+ ${e.error?p`
2177
+ <div class="callout danger">${e.error}</div>
2178
+ <button @click=${e.onViewRawText} class="btn" style="margin-top: 12px;">
2179
+ View Raw Text
2180
+ </button>
2181
+ `:e.content?p`<div class="sidebar-markdown">${ci(hi(e.content))}</div>`:p`<div class="muted">No content available</div>`}
2182
+ </div>
2183
+ </div>
2184
+ `}var Jg=Object.defineProperty,em=Object.getOwnPropertyDescriptor,Mi=(e,t,n,i)=>{for(var s=i>1?void 0:i?em(t,n):t,o=e.length-1,r;o>=0;o--)(r=e[o])&&(s=(i?r(t,n,s):r(s))||s);return i&&s&&Jg(t,n,s),s};let Rt=class extends _t{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 p``}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)}};Rt.styles=zu`
2185
+ :host {
2186
+ width: 4px;
2187
+ cursor: col-resize;
2188
+ background: var(--border, #333);
2189
+ transition: background 150ms ease-out;
2190
+ flex-shrink: 0;
2191
+ position: relative;
2192
+ }
2193
+
2194
+ :host::before {
2195
+ content: "";
2196
+ position: absolute;
2197
+ top: 0;
2198
+ left: -4px;
2199
+ right: -4px;
2200
+ bottom: 0;
2201
+ }
2202
+
2203
+ :host(:hover) {
2204
+ background: var(--accent, #007bff);
2205
+ }
2206
+
2207
+ :host(.dragging) {
2208
+ background: var(--accent, #007bff);
2209
+ }
2210
+ `;Mi([ki({type:Number})],Rt.prototype,"splitRatio",2);Mi([ki({type:Number})],Rt.prototype,"minRatio",2);Mi([ki({type:Number})],Rt.prototype,"maxRatio",2);Rt=Mi([ll("resizable-divider")],Rt);function Kn(e){if(typeof e!="string"||!e)throw new Error("expected a non-empty string, got: "+e)}function ds(e){if(typeof e!="number")throw new Error("expected a number, got: "+e)}const tm=1,nm=1,bt="emoji",Nt="keyvalue",Oo="favorites",im="tokens",Bc="tokens",sm="unicode",Fc="count",om="group",rm="order",Uc="group-order",Ks="eTag",fi="url",Sa="skinTone",Bt="readonly",Bo="readwrite",Wc="skinUnicodes",am="skinUnicodes",lm="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",cm="en";function um(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 xa(e){return um(e,t=>t.unicode)}function dm(e){function t(n,i,s){const o=i?e.createObjectStore(n,{keyPath:i}):e.createObjectStore(n);if(s)for(const[r,[a,u]]of Object.entries(s))o.createIndex(r,a,{multiEntry:u});return o}t(Nt),t(bt,sm,{[Bc]:[im,!0],[Uc]:[[om,rm]],[Wc]:[am,!0]}),t(Oo,void 0,{[Fc]:[""]})}const zs={},Yn={},gi={};function Kc(e,t,n){n.onerror=()=>t(n.error),n.onblocked=()=>t(new Error("IDB blocked")),n.onsuccess=()=>e(n.result)}async function pm(e){const t=await new Promise((n,i)=>{const s=indexedDB.open(e,tm);zs[e]=s,s.onupgradeneeded=o=>{o.oldVersion<nm&&dm(s.result)},Kc(n,i,s)});return t.onclose=()=>Fo(e),t}function hm(e){return Yn[e]||(Yn[e]=pm(e)),Yn[e]}function We(e,t,n,i){return new Promise((s,o)=>{const r=e.transaction(t,n,{durability:"relaxed"}),a=typeof t=="string"?r.objectStore(t):t.map(c=>r.objectStore(c));let u;i(a,r,c=>{u=c}),r.oncomplete=()=>s(u),r.onerror=()=>o(r.error)})}function Fo(e){const t=zs[e],n=t&&t.result;if(n){n.close();const i=gi[e];if(i)for(const s of i)s()}delete zs[e],delete Yn[e],delete gi[e]}function fm(e){return new Promise((t,n)=>{Fo(e);const i=indexedDB.deleteDatabase(e);Kc(t,n,i)})}function gm(e,t){let n=gi[e];n||(n=gi[e]=[]),n.push(t)}const mm=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 Pt(e){return e.split(/[\s_]+/).map(t=>!t.match(/\w/)||mm.has(t)?t.toLowerCase():t.replace(/[)(:,]/g,"").replace(/’/g,"'").toLowerCase()).filter(Boolean)}const ym=2;function zc(e){return e.filter(Boolean).map(t=>t.toLowerCase()).filter(t=>t.length>=ym)}function vm(e){return e.map(({annotation:n,emoticon:i,group:s,order:o,shortcodes:r,skins:a,tags:u,emoji:c,version:l})=>{const d=[...new Set(zc([...(r||[]).map(Pt).flat(),...(u||[]).map(Pt).flat(),...Pt(n),i]))].sort(),h={annotation:n,group:s,order:o,tags:u,tokens:d,unicode:c,version:l};if(i&&(h.emoticon=i),r&&(h.shortcodes=r),a){h.skinTones=[],h.skinUnicodes=[],h.skinVersions=[];for(const{tone:v,emoji:f,version:b}of a)h.skinTones.push(v),h.skinUnicodes.push(f),h.skinVersions.push(b)}return h})}function jc(e,t,n,i){e[t](n).onsuccess=s=>i&&i(s.target.result)}function gt(e,t,n){jc(e,"get",t,n)}function Hc(e,t,n){jc(e,"getAll",t,n)}function Uo(e){e.commit&&e.commit()}function bm(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 qc(e,t){const n=bm(e,s=>s.length),i=[];for(const s of n)e.some(o=>o.findIndex(r=>t(r)===t(s))===-1)||i.push(s);return i}async function wm(e){return!await Wo(e,Nt,fi)}async function km(e,t,n){const[i,s]=await Promise.all([Ks,fi].map(o=>Wo(e,Nt,o)));return i===n&&s===t}async function Sm(e,t){return We(e,bt,Bt,(i,s,o)=>{let r;const a=()=>{i.getAll(r&&IDBKeyRange.lowerBound(r,!0),50).onsuccess=u=>{const c=u.target.result;for(const l of c)if(r=l.unicode,t(l))return o(l);if(c.length<50)return o();a()}};a()})}async function Vc(e,t,n,i){{const s=vm(t);await We(e,[bt,Nt],Bo,([o,r],a)=>{let u,c,l=0;function d(){++l===2&&h()}function h(){if(!(u===i&&c===n)){o.clear();for(const v of s)o.put(v);r.put(i,Ks),r.put(n,fi),Uo(a)}}gt(r,Ks,v=>{u=v,d()}),gt(r,fi,v=>{c=v,d()})})}}async function xm(e,t){return We(e,bt,Bt,(n,i,s)=>{const o=IDBKeyRange.bound([t,0],[t+1,0],!1,!0);Hc(n.index(Uc),o,s)})}async function Gc(e,t){const n=zc(Pt(t));return n.length?We(e,bt,Bt,(i,s,o)=>{const r=[],a=()=>{r.length===n.length&&u()},u=()=>{const c=qc(r,l=>l.unicode);o(c.sort((l,d)=>l.order<d.order?-1:1))};for(let c=0;c<n.length;c++){const l=n[c],d=c===n.length-1?IDBKeyRange.bound(l,l+"￿",!1,!0):IDBKeyRange.only(l);Hc(i.index(Bc),d,h=>{r.push(h),a()})}}):[]}async function Am(e,t){const n=await Gc(e,t);return n.length?n.filter(i=>(i.shortcodes||[]).map(o=>o.toLowerCase()).includes(t.toLowerCase()))[0]||null:await Sm(e,s=>(s.shortcodes||[]).includes(t.toLowerCase()))||null}async function $m(e,t){return We(e,bt,Bt,(n,i,s)=>gt(n,t,o=>{if(o)return s(o);gt(n.index(Wc),t,r=>s(r||null))}))}function Wo(e,t,n){return We(e,t,Bt,(i,s,o)=>gt(i,n,o))}function Em(e,t,n,i){return We(e,t,Bo,(s,o)=>{s.put(i,n),Uo(o)})}function Tm(e,t){return We(e,Oo,Bo,(n,i)=>gt(n,t,s=>{n.put((s||0)+1,t),Uo(i)}))}function Cm(e,t,n){return n===0?[]:We(e,[Oo,bt],Bt,([i,s],o,r)=>{const a=[];i.index(Fc).openCursor(void 0,"prev").onsuccess=u=>{const c=u.target.result;if(!c)return r(a);function l(v){if(a.push(v),a.length===n)return r(a);c.continue()}const d=c.primaryKey,h=t.byName(d);if(h)return l(h);gt(s,d,v=>{if(v)return l(v);c.continue()})}})}const zn="";function _m(e,t){const n=new Map;for(const s of e){const o=t(s);for(const r of o){let a=n;for(let c=0;c<r.length;c++){const l=r.charAt(c);let d=a.get(l);d||(d=new Map,a.set(l,d)),a=d}let u=a.get(zn);u||(u=[],a.set(zn,u)),u.push(s)}}return(s,o)=>{let r=n;for(let c=0;c<s.length;c++){const l=s.charAt(c),d=r.get(l);if(d)r=d;else return[]}if(o)return r.get(zn)||[];const a=[],u=[r];for(;u.length;){const l=[...u.shift().entries()].sort((d,h)=>d[0]<h[0]?-1:1);for(const[d,h]of l)d===zn?a.push(...h):u.push(h)}return a}}const Mm=["name","url"];function Pm(e){const t=e&&Array.isArray(e),n=t&&e.length&&(!e[0]||Mm.some(i=>!(i in e[0])));if(!t||n)throw new Error("Custom emojis are in the wrong format")}function Aa(e){Pm(e);const t=(h,v)=>h.name.toLowerCase()<v.name.toLowerCase()?-1:1,n=e.sort(t),s=_m(e,h=>{const v=new Set;if(h.shortcodes)for(const f of h.shortcodes)for(const b of Pt(f))v.add(b);return v}),o=h=>s(h,!0),r=h=>s(h,!1),a=h=>{const v=Pt(h),f=v.map((b,S)=>(S<v.length-1?o:r)(b));return qc(f,b=>b.name).sort(t)},u=new Map,c=new Map;for(const h of e){c.set(h.name.toLowerCase(),h);for(const v of h.shortcodes||[])u.set(v.toLowerCase(),h)}return{all:n,search:a,byShortcode:h=>u.get(h.toLowerCase()),byName:h=>c.get(h.toLowerCase())}}const Lm=typeof wrappedJSObject<"u";function Zt(e){if(!e)return e;if(Lm&&(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 Qc(e){e||console.warn("emoji-picker-element is more efficient if the dataSource server exposes an ETag header.")}const Im=["annotation","emoji","group","order","version"];function Rm(e){if(!e||!Array.isArray(e)||!e[0]||typeof e[0]!="object"||Im.some(t=>!(t in e[0])))throw new Error("Emoji data is in the wrong format")}function Yc(e,t){if(Math.floor(e.status/100)!==2)throw new Error("Failed to fetch: "+t+": "+e.status)}async function Nm(e){const t=await fetch(e,{method:"HEAD"});Yc(t,e);const n=t.headers.get("etag");return Qc(n),n}async function js(e){const t=await fetch(e);Yc(t,e);const n=t.headers.get("etag");Qc(n);const i=await t.json();return Rm(i),[n,i]}function Dm(e){for(var t="",n=new Uint8Array(e),i=n.byteLength,s=-1;++s<i;)t+=String.fromCharCode(n[s]);return t}function Om(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 Xc(e){const t=JSON.stringify(e);let n=Om(t);const i=await crypto.subtle.digest("SHA-1",n),s=Dm(i);return btoa(s)}async function Bm(e,t){let n,i=await Nm(t);if(!i){const s=await js(t);i=s[0],n=s[1],i||(i=await Xc(n))}await km(e,t,i)||(n||(n=(await js(t))[1]),await Vc(e,n,t,i))}async function Fm(e,t){let[n,i]=await js(t);n||(n=await Xc(i)),await Vc(e,i,t,n)}async function Um(e,t){try{await Bm(e,t)}catch(n){if(n.name!=="InvalidStateError")throw n}}class Wm{constructor({dataSource:t=lm,locale:n=cm,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=Aa(i),this._clear=this._clear.bind(this),this._ready=this._init()}async _init(){const t=this._db=await hm(this._dbName);gm(this._dbName,this._clear);const n=this.dataSource;await wm(t)?await Fm(t,n):this._lazyUpdate=Um(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 ds(t),await this.ready(),xa(await xm(this._db,t)).map(Zt)}async getEmojiBySearchQuery(t){Kn(t),await this.ready();const n=this._custom.search(t),i=xa(await Gc(this._db,t)).map(Zt);return[...n,...i]}async getEmojiByShortcode(t){Kn(t),await this.ready();const n=this._custom.byShortcode(t);return n||Zt(await Am(this._db,t))}async getEmojiByUnicodeOrName(t){Kn(t),await this.ready();const n=this._custom.byName(t);return n||Zt(await $m(this._db,t))}async getPreferredSkinTone(){return await this.ready(),await Wo(this._db,Nt,Sa)||0}async setPreferredSkinTone(t){return ds(t),await this.ready(),Em(this._db,Nt,Sa,t)}async incrementFavoriteEmojiCount(t){return Kn(t),await this.ready(),Tm(this._db,t)}async getTopFavoriteEmoji(t){return ds(t),await this.ready(),(await Cm(this._db,this._custom,t)).map(Zt)}set customEmoji(t){this._custom=Aa(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 Fo(this._dbName)}async delete(){await this._shutdown(),await fm(this._dbName)}}const Hs=[[-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})),ps=Hs.slice(1),Km=2,$a=6,Zc=typeof requestIdleCallback=="function"?requestIdleCallback:setTimeout;function Ea(e){return e.unicode.includes("‍")}const zm={"🫪":17,"🫩":16,"🫨":15.1,"🫠":14,"🥲":13.1,"🥻":12.1,"🥰":11,"🤩":5,"👱‍♀️":4,"🤣":3,"👁️‍🗨️":2,"😀":1,"😐️":.7,"😃":.6},jm=1e3,Hm="🖐️",qm=8,Vm=["😊","😒","❤️","👍️","😍","😂","😭","☺️","😔","😩","😏","💕","🙌","😘"],Jc='"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif',Gm=(e,t)=>e<t?-1:e>t?1:0,Ta=(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 ${Jc}`,i.fillStyle=t,i.scale(.01,.01),i.fillText(e,0,0),i.getImageData(0,0,1,1).data},Qm=(e,t)=>{const n=[...e].join(","),i=[...t].join(",");return n===i&&!n.startsWith("0,0,0,")};function Ym(e){const t=Ta(e,"#000"),n=Ta(e,"#fff");return t&&n&&Qm(t,n)}function Xm(){const e=Object.entries(zm);try{for(const[t,n]of e)if(Ym(t))return n}catch{}return e[0][1]}let hs;const fs=()=>(hs||(hs=new Promise(e=>Zc(()=>e(Xm())))),hs),qs=new Map,Zm="️",Jm="\uD83C",ey="‍",ty=127995,ny=57339;function iy(e,t){if(t===0)return e;const n=e.indexOf(ey);return n!==-1?e.substring(0,n)+String.fromCodePoint(ty+t-1)+e.substring(n):(e.endsWith(Zm)&&(e=e.substring(0,e.length-1)),e+Jm+String.fromCodePoint(ny+t-1))}function Ee(e){e.preventDefault(),e.stopPropagation()}function gs(e,t,n){return t+=e?-1:1,t<0?t=n.length-1:t>=n.length&&(t=0),t}function eu(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 sy(e,t){const n=i=>{const s={};for(const o of i)typeof o.tone=="number"&&o.version<=t&&(s[o.tone]=o.unicode);return s};return e.map(({unicode:i,skins:s,shortcodes:o,url:r,name:a,category:u,annotation:c})=>({unicode:i,name:a,shortcodes:o,url:r,category:u,annotation:c,id:i||a,skins:s&&n(s)}))}const Xn=requestAnimationFrame;let oy=typeof ResizeObserver=="function";function ry(e,t,n){let i;oy?(i=new ResizeObserver(n),i.observe(e)):Xn(n),t.addEventListener("abort",()=>{i&&i.disconnect()})}function Ca(e){{const t=document.createRange();return t.selectNode(e.firstChild),t.getBoundingClientRect().width}}let ms;function ay(e,t,n){let i=!0,s=!1;for(const o of e){const r=n(o);if(!r)continue;const a=Ca(r);a===0&&(s=!0),typeof ms>"u"&&(ms=Ca(t));const u=a/1.8<ms;qs.set(o.unicode,u),u||(i=!1)}return s&&console.warn(`Emoji support detection failed - emoji character is 0 width.
2211
+ This is likely due to using \`display:none\` which is unsupported.
2212
+ If this is a Jest/Vitest environment, you can ignore this warning.
2213
+ For details see: https://github.com/nolanlawson/emoji-picker-element/issues/514`),i}function ly(e){return eu(e,t=>t)}function cy(e){e&&(e.scrollTop=0)}function ln(e,t,n){let i=e.get(t);return i||(i=n(),e.set(t,i)),i}function _a(e){return""+e}function uy(e){const t=document.createElement("template");return t.innerHTML=e,t}const dy=new WeakMap,py=new WeakMap,hy=Symbol("un-keyed"),fy="replaceChildren"in Element.prototype;function gy(e,t){fy?e.replaceChildren(...t):(e.innerHTML="",e.append(...t))}function my(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 yy(e,t){const{targetNode:n}=t;let{targetParentNode:i}=t,s=!1;i?s=my(i,e):(s=!0,t.targetNode=void 0,t.targetParentNode=i=n.parentNode),s&&gy(i,e)}function vy(e,t){for(const n of t){const{targetNode:i,currentExpression:s,binding:{expressionIndex:o,attributeName:r,attributeValuePre:a,attributeValuePost:u}}=n,c=e[o];if(s!==c)if(n.currentExpression=c,r)if(c===null)i.removeAttribute(r);else{const l=a+_a(c)+u;i.setAttribute(r,l)}else{let l;Array.isArray(c)?yy(c,n):c instanceof Element?(l=c,i.replaceWith(l)):i.nodeValue=_a(c),l&&(n.targetNode=l)}}}function by(e){let t="",n=!1,i=!1,s=-1;const o=new Map,r=[];let a=0;for(let c=0,l=e.length;c<l;c++){const d=e[c];if(t+=d.slice(a),c===l-1)break;for(let $=0;$<d.length;$++)switch(d.charAt($)){case"<":{d.charAt($+1)==="/"?r.pop():(n=!0,r.push(++s));break}case">":{n=!1,i=!1;break}case"=":{i=!0;break}}const h=r[r.length-1],v=ln(o,h,()=>[]);let f,b,S;if(i){const $=/(\S+)="?([^"=]*)$/.exec(d);f=$[1],b=$[2];const T=/^([^">]*)("?)/.exec(e[c+1]);S=T[1],t=t.slice(0,-1*$[0].length),a=T[0].length}else a=0;const A={attributeName:f,attributeValuePre:b,attributeValuePost:S,expressionIndex:c};v.push(A),!n&&!i&&(t+=" ")}return{template:uy(t),elementsToBindings:o}}function Ma(e,t,n){for(let i=0;i<e.length;i++){const s=e[i],o=s.attributeName?t:t.firstChild,r={binding:s,targetNode:o,targetParentNode:void 0,currentExpression:void 0};n.push(r)}}function wy(e,t){const n=[];let i;if(t.size===1&&(i=t.get(0)))Ma(i,e,n);else{const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT);let o=e,r=-1;do{const a=t.get(++r);a&&Ma(a,o,n)}while(o=s.nextNode())}return n}function ky(e){const{template:t,elementsToBindings:n}=ln(dy,e,()=>by(e)),i=t.cloneNode(!0).content.firstElementChild,s=wy(i,n);return function(r){return vy(r,s),i}}function Sy(e){const t=ln(py,e,()=>new Map);let n=hy;function i(o,...r){const a=ln(t,o,()=>new Map);return ln(a,n,()=>ky(o))(r)}function s(o,r,a){return o.map((u,c)=>{const l=n;n=a(u);try{return r(u,c)}finally{n=l}})}return{map:s,html:i}}function xy(e,t,n,i,s,o,r,a,u){const{labelWithSkin:c,titleForEmoji:l,unicodeWithSkin:d}=n,{html:h,map:v}=Sy(t);function f($,T,C){return v($,(M,R)=>h`<button role="${T?"option":"menuitem"}" aria-selected="${T?R===t.activeSearchItem:null}" aria-label="${c(M,t.currentSkinTone)}" title="${l(M)}" class="${"emoji"+(T&&R===t.activeSearchItem?" active":"")+(M.unicode?"":" custom-emoji")}" id="${`${C}-${M.id}`}" style="${M.unicode?null:`--custom-emoji-background: url(${JSON.stringify(M.url)})`}">${M.unicode?d(M,t.currentSkinTone):""}</button>`,M=>`${C}-${M.id}`)}const S=h`<section data-ref="rootElement" class="picker" aria-label="${t.i18n.regionLabel}" style="${t.pickerStyle||""}"><div class="pad-top"></div><div class="search-row"><div class="search-wrapper"><input id="search" class="search" type="search" role="combobox" enterkeyhint="search" placeholder="${t.i18n.searchLabel}" autocapitalize="none" autocomplete="off" spellcheck="true" aria-expanded="${!!(t.searchMode&&t.currentEmojis.length)}" aria-controls="search-results" aria-describedby="search-description" aria-autocomplete="list" aria-activedescendant="${t.activeSearchItemId?`emo-${t.activeSearchItemId}`:null}" data-ref="searchElement" data-on-input="onSearchInput" data-on-keydown="onSearchKeydown"><label class="sr-only" for="search">${t.i18n.searchLabel}</label> <span id="search-description" class="sr-only">${t.i18n.searchDescription}</span></div><div class="skintone-button-wrapper ${t.skinTonePickerExpandedAfterAnimation?"expanded":""}"><button id="skintone-button" class="emoji ${t.skinTonePickerExpanded?"hide-focus":""}" aria-label="${t.skinToneButtonLabel}" title="${t.skinToneButtonLabel}" aria-describedby="skintone-description" aria-haspopup="listbox" aria-expanded="${t.skinTonePickerExpanded}" aria-controls="skintone-list" data-on-click="onClickSkinToneButton">${t.skinToneButtonText||""}</button></div><span id="skintone-description" class="sr-only">${t.i18n.skinToneDescription}</span><div data-ref="skinToneDropdown" id="skintone-list" class="skintone-list hide-focus ${t.skinTonePickerExpanded?"":"hidden no-animate"}" style="transform:translateY(${t.skinTonePickerExpanded?0:"calc(-1 * var(--num-skintones) * var(--total-emoji-size))"})" role="listbox" aria-label="${t.i18n.skinTonesLabel}" aria-activedescendant="skintone-${t.activeSkinTone}" aria-hidden="${!t.skinTonePickerExpanded}" tabIndex="-1" data-on-focusout="onSkinToneOptionsFocusOut" data-on-click="onSkinToneOptionsClick" data-on-keydown="onSkinToneOptionsKeydown" data-on-keyup="onSkinToneOptionsKeyup">${v(t.skinTones,($,T)=>h`<div id="skintone-${T}" class="emoji ${T===t.activeSkinTone?"active":""}" aria-selected="${T===t.activeSkinTone}" role="option" title="${t.i18n.skinTones[T]}" aria-label="${t.i18n.skinTones[T]}">${$}</div>`,$=>$)}</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,$=>h`<button role="tab" class="nav-button" aria-controls="tab-${$.id}" aria-label="${t.i18n.categories[$.name]}" aria-selected="${!t.searchMode&&t.currentGroup.id===$.id}" title="${t.i18n.categories[$.name]}" data-group-id="${$.id}"><div class="nav-emoji emoji">${$.emoji}</div></button>`,$=>$.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,($,T)=>h`<div><div id="menu-label-${T}" class="category ${t.currentEmojisWithCategories.length===1&&t.currentEmojisWithCategories[0].category===""?"gone":""}" aria-hidden="true">${t.searchMode?t.i18n.searchResultsLabel:$.category?$.category:t.currentEmojisWithCategories.length>1?t.i18n.categories.custom:t.i18n.categories[t.currentGroup.name]}</div><div class="emoji-menu ${T!==0&&!t.searchMode&&t.currentGroup.id===-1?"visibility-auto":""}" style="${`--num-rows: ${Math.ceil($.emojis.length/t.numColumns)}`}" data-action="updateOnIntersection" role="${t.searchMode?"listbox":"menu"}" aria-labelledby="menu-label-${T}" id="${t.searchMode?"search-results":null}">${f($.emojis,t.searchMode,"emo")}</div></div>`,$=>$.category)}</div></div><div class="favorites onscreen emoji-menu ${t.message?"gone":""}" role="menu" aria-label="${t.i18n.favoritesLabel}" data-on-click="onEmojiClick">${f(t.currentFavorites,!1,"fav")}</div><button data-ref="baselineEmoji" aria-hidden="true" tabindex="-1" class="abs-pos hidden emoji baseline-emoji">😀</button></section>`,A=($,T)=>{for(const C of e.querySelectorAll(`[${$}]`))T(C,C.getAttribute($))};if(u){e.appendChild(S);for(const $ of["click","focusout","input","keydown","keyup"])A(`data-on-${$}`,(T,C)=>{T.addEventListener($,i[C])});A("data-ref",($,T)=>{o[T]=$}),r.addEventListener("abort",()=>{e.removeChild(S)})}A("data-action",($,T)=>{let C=a.get(T);C||a.set(T,C=new WeakSet),C.has($)||(C.add($),s[T]($))})}const mi=typeof queueMicrotask=="function"?queueMicrotask:e=>Promise.resolve().then(e);function Ay(e){let t=!1,n;const i=new Map,s=new Set;let o;const r=()=>{if(t)return;const c=[...s];s.clear();try{for(const l of c)l()}finally{o=!1,s.size&&(o=!0,mi(r))}},a=new Proxy({},{get(c,l){if(n){let d=i.get(l);d||(d=new Set,i.set(l,d)),d.add(n)}return c[l]},set(c,l,d){if(c[l]!==d){c[l]=d;const h=i.get(l);if(h){for(const v of h)s.add(v);o||(o=!0,mi(r))}}return!0}}),u=c=>{const l=()=>{const d=n;n=l;try{return c()}finally{n=d}};return l()};return e.addEventListener("abort",()=>{t=!0}),{state:a,createEffect:u}}function ys(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 Pa=new WeakMap;function $y(e,t,n){{const i=e.closest(".tabpanel");let s=Pa.get(i);s||(s=new IntersectionObserver(n,{root:i,rootMargin:"50% 0px 50% 0px",threshold:0}),Pa.set(i,s),t.addEventListener("abort",()=>{s.disconnect()})),s.observe(e)}}const vs=[],{assign:jn}=Object;function Ey(e,t){const n={},i=new AbortController,s=i.signal,{state:o,createEffect:r}=Ay(s),a=new Map;jn(o,{skinToneEmoji:void 0,i18n:void 0,database:void 0,customEmoji:void 0,customCategorySorting:void 0,emojiVersion:void 0}),jn(o,t),jn(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:qm,isRtl:!1,currentGroupIndex:0,groups:ps,databaseLoaded:!1,activeSearchItemId:void 0}),r(()=>{o.currentGroup!==o.groups[o.currentGroupIndex]&&(o.currentGroup=o.groups[o.currentGroupIndex])});const u=x=>{e.getElementById(x).focus()},c=x=>e.getElementById(`emo-${x.id}`),l=(x,_)=>{n.rootElement.dispatchEvent(new CustomEvent(x,{detail:_,bubbles:!0,composed:!0}))},d=(x,_)=>x.id===_.id,h=(x,_)=>{const{category:N,emojis:O}=x,{category:V,emojis:z}=_;return N!==V?!1:ys(O,z,d)},v=x=>{ys(o.currentEmojis,x,d)||(o.currentEmojis=x)},f=x=>{o.searchMode!==x&&(o.searchMode=x)},b=x=>{ys(o.currentEmojisWithCategories,x,h)||(o.currentEmojisWithCategories=x)},S=(x,_)=>_&&x.skins&&x.skins[_]||x.unicode,T={labelWithSkin:(x,_)=>ly([x.name||S(x,_),x.annotation,...x.shortcodes||vs].filter(Boolean)).join(", "),titleForEmoji:x=>x.annotation||(x.shortcodes||vs).join(", "),unicodeWithSkin:S},C={onClickSkinToneButton:H,onEmojiClick:xn,onNavClick:kn,onNavKeydown:Ni,onSearchKeydown:Ri,onSkinToneOptionsClick:An,onSkinToneOptionsFocusOut:ze,onSkinToneOptionsKeydown:et,onSkinToneOptionsKeyup:Ut,onSearchInput:$n},M={calculateEmojiGridStyle:ee,updateOnIntersection:me};let R=!0;r(()=>{xy(e,o,T,C,M,n,s,a,R),R=!1}),o.emojiVersion||fs().then(x=>{x||(o.message=o.i18n.emojiUnsupportedMessage)}),r(()=>{async function x(){let _=!1;const N=setTimeout(()=>{_=!0,o.message=o.i18n.loadingMessage},jm);try{await o.database.ready(),o.databaseLoaded=!0}catch(O){console.error(O),o.message=o.i18n.networkErrorMessage}finally{clearTimeout(N),_&&(_=!1,o.message="")}}o.database&&x()}),r(()=>{o.pickerStyle=`
2214
+ --num-groups: ${o.groups.length};
2215
+ --indicator-opacity: ${o.searchMode?0:1};
2216
+ --num-skintones: ${$a};`}),r(()=>{o.customEmoji&&o.database&&B()}),r(()=>{o.customEmoji&&o.customEmoji.length?o.groups!==Hs&&(o.groups=Hs):o.groups!==ps&&(o.currentGroupIndex&&o.currentGroupIndex--,o.groups=ps)}),r(()=>{async function x(){o.databaseLoaded&&(o.currentSkinTone=await o.database.getPreferredSkinTone())}x()}),r(()=>{o.skinTones=Array($a).fill().map((x,_)=>iy(o.skinToneEmoji,_))}),r(()=>{o.skinToneButtonText=o.skinTones[o.currentSkinTone]}),r(()=>{o.skinToneButtonLabel=o.i18n.skinToneLabel.replace("{skinTone}",o.i18n.skinTones[o.currentSkinTone])}),r(()=>{async function x(){const{database:_}=o,N=(await Promise.all(Vm.map(O=>_.getEmojiByUnicodeOrName(O)))).filter(Boolean);o.defaultFavoriteEmojis=N}o.databaseLoaded&&x()});function B(){const{customEmoji:x,database:_}=o,N=x||vs;_.customEmoji!==N&&(_.customEmoji=N)}r(()=>{async function x(){B();const{database:_,defaultFavoriteEmojis:N,numColumns:O}=o,V=await _.getTopFavoriteEmoji(O),z=await Je(eu([...V,...N],ae=>ae.unicode||ae.name).slice(0,O));o.currentFavorites=z}o.databaseLoaded&&o.defaultFavoriteEmojis&&x()});function ee(x){ry(x,s,()=>{{const _=getComputedStyle(n.rootElement),N=parseInt(_.getPropertyValue("--num-columns"),10),O=_.getPropertyValue("direction")==="rtl";o.numColumns=N,o.isRtl=O}})}function me(x){$y(x,s,_=>{for(const{target:N,isIntersecting:O}of _)N.classList.toggle("onscreen",O)})}r(()=>{async function x(){const{searchText:_,currentGroup:N,databaseLoaded:O,customEmoji:V}=o;if(!O)o.currentEmojis=[],o.searchMode=!1;else if(_.length>=Km){const z=await Ii(_);o.searchText===_&&(v(z),f(!0))}else{const{id:z}=N;if(z!==-1||V&&V.length){const ae=await Li(z);o.currentGroup.id===z&&(v(ae),f(!1))}}}x()});const Ke=()=>{Xn(()=>cy(n.tabpanelElement))};r(()=>{const{currentEmojis:x,emojiVersion:_}=o,N=x.filter(O=>O.unicode).filter(O=>Ea(O)&&!qs.has(O.unicode));if(!_&&N.length)v(x),Xn(()=>Z(N));else{const O=_?x:x.filter(Ft);v(O),Ke()}});function Z(x){ay(x,n.baselineEmoji,c)?Ke():o.currentEmojis=[...o.currentEmojis]}function Ft(x){return!x.unicode||!Ea(x)||qs.get(x.unicode)}async function wt(x){const _=o.emojiVersion||await fs();return x.filter(({version:N})=>!N||N<=_)}async function Je(x){return sy(x,o.emojiVersion||await fs())}async function Li(x){const _=x===-1?o.customEmoji:await o.database.getEmojiByGroup(x);return Je(await wt(_))}async function Ii(x){return Je(await wt(await o.database.getEmojiBySearchQuery(x)))}r(()=>{}),r(()=>{function x(){const{searchMode:N,currentEmojis:O}=o;if(N)return[{category:"",emojis:O}];const V=new Map;for(const z of O){const ae=z.category||"";let je=V.get(ae);je||(je=[],V.set(ae,je)),je.push(z)}return[...V.entries()].map(([z,ae])=>({category:z,emojis:ae})).sort((z,ae)=>o.customCategorySorting(z.category,ae.category))}const _=x();b(_)}),r(()=>{o.activeSearchItemId=o.activeSearchItem!==-1&&o.currentEmojis[o.activeSearchItem].id}),r(()=>{const{rawSearchText:x}=o;Zc(()=>{o.searchText=(x||"").trim(),o.activeSearchItem=-1})});function Ri(x){if(!o.searchMode||!o.currentEmojis.length)return;const _=N=>{Ee(x),o.activeSearchItem=gs(N,o.activeSearchItem,o.currentEmojis)};switch(x.key){case"ArrowDown":return _(!1);case"ArrowUp":return _(!0);case"Enter":if(o.activeSearchItem===-1)o.activeSearchItem=0;else return Ee(x),Q(o.currentEmojis[o.activeSearchItem].id)}}function kn(x){const{target:_}=x,N=_.closest(".nav-button");if(!N)return;const O=parseInt(N.dataset.groupId,10);n.searchElement.value="",o.rawSearchText="",o.searchText="",o.activeSearchItem=-1,o.currentGroupIndex=o.groups.findIndex(V=>V.id===O)}function Ni(x){const{target:_,key:N}=x,O=V=>{V&&(Ee(x),V.focus())};switch(N){case"ArrowLeft":return O(_.previousElementSibling);case"ArrowRight":return O(_.nextElementSibling);case"Home":return O(_.parentElement.firstElementChild);case"End":return O(_.parentElement.lastElementChild)}}async function Sn(x){const _=await o.database.getEmojiByUnicodeOrName(x),N=[...o.currentEmojis,...o.currentFavorites].find(V=>V.id===x),O=N.unicode&&S(N,o.currentSkinTone);return await o.database.incrementFavoriteEmojiCount(x),{emoji:_,skinTone:o.currentSkinTone,...O&&{unicode:O},...N.name&&{name:N.name}}}async function Q(x){const _=Sn(x);l("emoji-click-sync",_),l("emoji-click",await _)}function xn(x){const{target:_}=x;if(!_.classList.contains("emoji"))return;Ee(x);const N=_.id.substring(4);Q(N)}function Y(x){o.currentSkinTone=x,o.skinTonePickerExpanded=!1,u("skintone-button"),l("skin-tone-change",{skinTone:x}),o.database.setPreferredSkinTone(x)}function An(x){const{target:{id:_}}=x,N=_&&_.match(/^skintone-(\d)/);if(!N)return;Ee(x);const O=parseInt(N[1],10);Y(O)}function H(x){o.skinTonePickerExpanded=!o.skinTonePickerExpanded,o.activeSkinTone=o.currentSkinTone,o.skinTonePickerExpanded&&(Ee(x),Xn(()=>u("skintone-list")))}r(()=>{o.skinTonePickerExpanded?n.skinToneDropdown.addEventListener("transitionend",()=>{o.skinTonePickerExpandedAfterAnimation=!0},{once:!0}):o.skinTonePickerExpandedAfterAnimation=!1});function et(x){if(!o.skinTonePickerExpanded)return;const _=async N=>{Ee(x),o.activeSkinTone=N};switch(x.key){case"ArrowUp":return _(gs(!0,o.activeSkinTone,o.skinTones));case"ArrowDown":return _(gs(!1,o.activeSkinTone,o.skinTones));case"Home":return _(0);case"End":return _(o.skinTones.length-1);case"Enter":return Ee(x),Y(o.activeSkinTone);case"Escape":return Ee(x),o.skinTonePickerExpanded=!1,u("skintone-button")}}function Ut(x){if(o.skinTonePickerExpanded&&x.key===" ")return Ee(x),Y(o.activeSkinTone)}async function ze(x){const{relatedTarget:_}=x;(!_||_.id!=="skintone-list")&&(o.skinTonePickerExpanded=!1)}function $n(x){o.rawSearchText=x.target.value}return{$set(x){jn(o,x)},$destroy(){i.abort()}}}const Ty="https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json",Cy="en";var _y={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"}},My=':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 tu=["customEmoji","customCategorySorting","database","dataSource","i18n","locale","skinToneEmoji","emojiVersion"],Py=`:host{--emoji-font-family:${Jc}}`;class Ko extends HTMLElement{constructor(t){super(),this.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=My+Py,this.shadowRoot.appendChild(n),this._ctx={locale:Cy,dataSource:Ty,skinToneEmoji:Hm,customCategorySorting:Gm,customEmoji:null,i18n:_y,emojiVersion:null,...t};for(const i of tu)i!=="database"&&Object.prototype.hasOwnProperty.call(this,i)&&(this._ctx[i]=this[i],delete this[i]);this._dbFlush()}connectedCallback(){La(this),this._cmp||(this._cmp=Ey(this.shadowRoot,this._ctx))}disconnectedCallback(){La(this),mi(()=>{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 Wm({locale:t,dataSource:n}))}_dbFlush(){mi(()=>this._dbCreate())}}const nu={};for(const e of tu)nu[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(Ko.prototype,nu);function La(e){e instanceof Ko||Object.setPrototypeOf(e,customElements.get(e.tagName.toLowerCase()).prototype)}customElements.get("emoji-picker")||customElements.define("emoji-picker",Ko);function Ly(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 Ia(e){e.style.height="44px",e.style.overflowY="hidden"}const Iy=5e3;function Ry(e){return e?e.active?p`
2217
+ <div class="callout info compaction-indicator compaction-indicator--active">
2218
+ ${D.loader} Compacting context...
2219
+ </div>
2220
+ `:e.completedAt&&Date.now()-e.completedAt<Iy?p`
2221
+ <div class="callout success compaction-indicator compaction-indicator--complete">
2222
+ ${D.check} Context compacted
2223
+ </div>
2224
+ `:k:k}const Be=5*1024*1024;function Fe(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function ke(e,t){var i,s,o;let n=(i=e.closest(".chat"))==null?void 0:i.querySelector(".chat-attachment-error");if(!n){n=document.createElement("div"),n.className="callout danger chat-attachment-error",n.style.cssText="margin: 8px 4px; animation: fade-in 200ms ease-out;";const r=(s=e.closest(".chat"))==null?void 0:s.querySelector(".chat-compose");(o=r==null?void 0:r.parentElement)==null||o.insertBefore(n,r)}n.textContent=t,setTimeout(()=>n==null?void 0:n.remove(),4e3)}const Ny=/\.(md|txt|csv|json|xml|html|css|js|ts|py|sh|yaml|yml|toml|ini|cfg|log|sql)$/i;function iu(e){return e.type.startsWith("image/")||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.name)}function su(e){return e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||Ny.test(e.name)}function ou(e){return e.type==="application/pdf"||/\.pdf$/i.test(e.name)}function ru(e){return e.type.startsWith("video/")||/\.(mp4|webm|mov|avi|mkv|m4v)$/i.test(e.name)}function Dy(e,t){if(!t.onAttachmentsChange)return;const n=document.querySelector(".chat");if(iu(e)){if(e.size>Be){n&&ke(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:Fe(),dataUrl:i.result,mimeType:e.type};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(su(e)){if(e.size>Be){n&&ke(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:Fe(),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(ou(e)){if(e.size>Be){n&&ke(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:Fe(),dataUrl:i.result,mimeType:"application/pdf",fileName:e.name};(o=t.onAttachmentsChange)==null||o.call(t,[...t.attachments??[],s])},i.readAsDataURL(e)}else if(ru(e)){if(e.size>Be){n&&ke(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:Fe(),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&&ke(n,`Unsupported file type: ${e.name}. Use the Files page to upload to workspace.`)}function Oy(e,t){var s;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;n.classList.remove("chat--dragover");const i=(s=e.dataTransfer)==null?void 0:s.files;if(!(!i||i.length===0))for(let o=0;o<i.length;o++){const r=i[o];if(iu(r)){if(!t.onAttachmentsChange)continue;if(r.size>Be){ke(n,`Image too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var d;const u=a.result,c={id:Fe(),dataUrl:u,mimeType:r.type},l=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...l,c])},a.readAsDataURL(r)}else if(su(r)){if(!t.onAttachmentsChange)continue;if(r.size>Be){ke(n,`File too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var d;const u=a.result,c={id:Fe(),dataUrl:"",mimeType:r.type||"text/plain",fileName:r.name,textContent:u},l=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...l,c])},a.readAsText(r)}else if(ou(r)){if(!t.onAttachmentsChange)continue;if(r.size>Be){ke(n,`PDF too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var d;const u=a.result,c={id:Fe(),dataUrl:u,mimeType:"application/pdf",fileName:r.name},l=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...l,c])},a.readAsDataURL(r)}else if(ru(r)){if(!t.onAttachmentsChange)continue;if(r.size>Be){ke(n,`Video too large (${(r.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const a=new FileReader;a.onload=()=>{var d;const u=a.result,c={id:Fe(),dataUrl:u,mimeType:r.type||"video/mp4",fileName:r.name},l=t.attachments??[];(d=t.onAttachmentsChange)==null||d.call(t,[...l,c])},a.readAsDataURL(r)}else ke(n,`Unsupported file type: ${r.name}. Use the Files page to upload to workspace.`)}}function By(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),e.currentTarget.classList.add("chat--dragover")}function Fy(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget,n=e.relatedTarget;(!n||!t.contains(n))&&t.classList.remove("chat--dragover")}function Uy(e,t){var s,o,r;const n=(s=e.clipboardData)==null?void 0:s.items;if(!n||!t.onAttachmentsChange)return;const i=[];for(let a=0;a<n.length;a++){const u=n[a];(u.type.startsWith("image/")||u.type.startsWith("video/"))&&i.push(u)}if(i.length!==0){e.preventDefault();for(const a of i){const u=a.getAsFile();if(!u)continue;const c=u.type.startsWith("video/")?"Video":"Image";if(u.size>Be){const d=((r=(o=e.target)==null?void 0:o.closest)==null?void 0:r.call(o,".chat"))??document.querySelector(".chat");d&&ke(d,`${c} too large (${(u.size/1024/1024).toFixed(1)} MB). Maximum is 5 MB.`);continue}const l=new FileReader;l.onload=()=>{var b;const d=l.result,h=u.type.startsWith("video/"),v={id:Fe(),dataUrl:d,mimeType:u.type,fileName:h?u.name||"video.mp4":void 0},f=t.attachments??[];(b=t.onAttachmentsChange)==null||b.call(t,[...f,v])},l.readAsDataURL(u)}}}function Wy(e){const t=e.currentTarget,n=t.closest(".chat-compose"),i=n==null?void 0:n.querySelector(".emoji-picker-popup");if(!i)return;const s=i.classList.toggle("active");if(t.classList.toggle("active",s),s){const o=r=>{i.contains(r.target)||t.contains(r.target)||(i.classList.remove("active"),t.classList.remove("active"),document.removeEventListener("click",o,!0))};requestAnimationFrame(()=>document.addEventListener("click",o,!0))}}function Ky(e,t){const n=e.detail,i=n==null?void 0:n.unicode;if(!i)return;const s=e.currentTarget.closest(".chat-compose"),o=s==null?void 0:s.querySelector("textarea");if(!o)return;const r=o.selectionStart??t.draft.length,a=o.selectionEnd??r,u=t.draft.slice(0,r),c=t.draft.slice(a);t.onDraftChange(u+i+c);const l=s==null?void 0:s.querySelector(".emoji-picker-popup"),d=s==null?void 0:s.querySelector(".chat-compose__emoji");l==null||l.classList.remove("active"),d==null||d.classList.remove("active"),requestAnimationFrame(()=>{o.focus();const h=r+i.length;o.setSelectionRange(h,h)})}function zy(e){const t=e.attachments??[];return t.length===0?k:p`
2225
+ <div class="chat-attachments">
2226
+ ${t.map(n=>{var i;return n.fileName?p`
2227
+ <div class="chat-attachment chat-attachment--file">
2228
+ <span class="chat-attachment__icon">${(i=n.mimeType)!=null&&i.startsWith("video/")?D.film:D.fileText}</span>
2229
+ <span class="chat-attachment__name" title=${n.fileName}>${n.fileName}</span>
2230
+ <button
2231
+ class="chat-attachment__remove chat-attachment__remove--file"
2232
+ type="button"
2233
+ aria-label="Remove attachment"
2234
+ @click=${()=>{var o;const s=(e.attachments??[]).filter(r=>r.id!==n.id);(o=e.onAttachmentsChange)==null||o.call(e,s)}}
2235
+ >
2236
+ ${D.x}
2237
+ </button>
2238
+ </div>
2239
+ `:p`
2240
+ <div class="chat-attachment">
2241
+ <img
2242
+ src=${n.dataUrl}
2243
+ alt="Attachment preview"
2244
+ class="chat-attachment__img"
2245
+ />
2246
+ <button
2247
+ class="chat-attachment__remove"
2248
+ type="button"
2249
+ aria-label="Remove attachment"
2250
+ @click=${()=>{var o;const s=(e.attachments??[]).filter(r=>r.id!==n.id);(o=e.onAttachmentsChange)==null||o.call(e,s)}}
2251
+ >
2252
+ ${D.x}
2253
+ </button>
2254
+ </div>
2255
+ `})}
2256
+ </div>
2257
+ `}function au(e){var h,v,f;const t=e.connected,n=e.sending||e.stream!==null,i=!!(e.canAbort&&e.onAbort),s=(v=(h=e.sessions)==null?void 0:h.sessions)==null?void 0:v.find(b=>b.key===e.sessionKey),o=(s==null?void 0:s.reasoningLevel)??"off",r=e.showThinking&&o!=="off";e.assistantName,e.assistantAvatar??e.assistantAvatarUrl;const a=(((f=e.attachments)==null?void 0:f.length)??0)>0,u=e.connected?a?"Add a message...":"Message...":"Connecting…",c=e.splitRatio??.6,l=!!(e.sidebarOpen&&e.onCloseSidebar),d=p`
2258
+ <div
2259
+ class="chat-thread"
2260
+ role="log"
2261
+ aria-live="polite"
2262
+ @scroll=${e.onChatScroll}
2263
+ >
2264
+ ${e.hasMore?p`<div class="chat-load-more">
2265
+ ${e.loadingOlder?p`<span class="chat-load-more__spinner">${D.loader}</span> Loading older messages…`:p`<button class="chat-load-more__btn" type="button" @click=${e.onLoadOlder}>Load older messages</button>`}
2266
+ </div>`:k}
2267
+ ${e.loading?p`<div class="muted">Loading chat…</div>`:k}
2268
+ ${Af(Yy(e),b=>b.key,b=>b.kind==="interim"?Gg(b.text):b.kind==="reading-indicator"?Vg():b.kind==="stream"?Qg(b.text,b.startedAt,e.onOpenSidebar):b.kind==="group"?Yg(b,{onOpenSidebar:e.onOpenSidebar,showReasoning:r,assistantName:e.assistantName}):k)}
2269
+ </div>
2270
+ `;return p`
2271
+ <section
2272
+ class="card chat"
2273
+ @drop=${b=>Oy(b,e)}
2274
+ @dragover=${By}
2275
+ @dragleave=${Fy}
2276
+ >
2277
+ ${e.disabledReason?p`<div class="callout">${e.disabledReason}</div>`:k}
2278
+
2279
+ ${e.error?p`<div class="callout danger">${e.error}</div>`:k}
2280
+
2281
+ ${Ry(e.compactionStatus)}
2282
+
2283
+ ${e.focusMode?p`
2284
+ <button
2285
+ class="chat-focus-exit"
2286
+ type="button"
2287
+ @click=${e.onToggleFocusMode}
2288
+ aria-label="Exit focus mode"
2289
+ title="Exit focus mode"
2290
+ >
2291
+ ${D.x}
2292
+ </button>
2293
+ `:k}
2294
+
2295
+ <div
2296
+ class="chat-split-container ${l?"chat-split-container--open":""}"
2297
+ >
2298
+ <div
2299
+ class="chat-main"
2300
+ style="flex: ${l?`0 0 ${c*100}%`:"1 1 100%"}"
2301
+ >
2302
+ ${d}
2303
+ ${e.nearBottom===!1?p`
2304
+ <button
2305
+ class="chat-scroll-bottom"
2306
+ type="button"
2307
+ @click=${b=>{const S=b.currentTarget.closest(".chat-main"),A=S==null?void 0:S.querySelector(".chat-thread");A&&A.scrollTo({top:A.scrollHeight,behavior:"smooth"})}}
2308
+ aria-label="Scroll to bottom"
2309
+ title="Scroll to bottom"
2310
+ >
2311
+ ${D.chevronDown}
2312
+ </button>
2313
+ `:k}
2314
+ </div>
2315
+
2316
+ ${l?p`
2317
+ <resizable-divider
2318
+ .splitRatio=${c}
2319
+ @resize=${b=>{var S;return(S=e.onSplitRatioChange)==null?void 0:S.call(e,b.detail.splitRatio)}}
2320
+ ></resizable-divider>
2321
+ <div class="chat-sidebar">
2322
+ ${Zg({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\`
2323
+ ${e.sidebarContent}
2324
+ \`\`\``)}})}
2325
+ </div>
2326
+ `:k}
2327
+ </div>
2328
+
2329
+ ${e.suggestion?p`
2330
+ <div class="chat-suggestions">
2331
+ <button
2332
+ class="chat-suggestion-chip"
2333
+ type="button"
2334
+ @click=${()=>{var b;return(b=e.onSuggestionClick)==null?void 0:b.call(e,e.suggestion)}}
2335
+ >
2336
+ ${e.suggestion}
2337
+ </button>
2338
+ </div>
2339
+ `:k}
2340
+
2341
+ <div class="chat-compose">
2342
+ ${zy(e)}
2343
+ <div class="chat-compose__row">
2344
+ <button
2345
+ class="chat-compose__emoji"
2346
+ type="button"
2347
+ @click=${Wy}
2348
+ aria-label="Emoji"
2349
+ title="Emoji"
2350
+ >
2351
+ ${D.smile}
2352
+ </button>
2353
+ <button
2354
+ class="chat-compose__attach"
2355
+ type="button"
2356
+ @click=${b=>{var A;const S=(A=b.currentTarget.closest(".chat-compose__row"))==null?void 0:A.querySelector(".chat-compose__file-input");S==null||S.click()}}
2357
+ aria-label="Attach file"
2358
+ title="Attach file"
2359
+ >
2360
+ ${D.paperclip}
2361
+ </button>
2362
+ <input
2363
+ class="chat-compose__file-input"
2364
+ type="file"
2365
+ multiple
2366
+ accept="image/*,video/*,.pdf,.md,.txt,.csv,.json,.xml,.html,.css,.js,.ts,.py,.sh,.yaml,.yml,.toml,.ini,.cfg,.log,.sql"
2367
+ style="display:none"
2368
+ @change=${b=>{const S=b.target,A=S.files;if(!(!A||A.length===0||!e.onAttachmentsChange)){for(let $=0;$<A.length;$++)Dy(A[$],e);S.value=""}}}
2369
+ />
2370
+ <label class="field chat-compose__field">
2371
+ <span>Message</span>
2372
+ <textarea
2373
+ .value=${e.draft}
2374
+ ?disabled=${!e.connected}
2375
+ @keydown=${b=>{b.key==="Enter"&&(b.isComposing||b.keyCode===229||b.shiftKey||e.connected&&(b.preventDefault(),t&&(e.onSend(),Ia(b.target))))}}
2376
+ @input=${b=>{const S=b.target;e.onDraftChange(S.value),Ly(S)}}
2377
+ @paste=${b=>Uy(b,e)}
2378
+ placeholder=${u}
2379
+ ></textarea>
2380
+ </label>
2381
+ ${i?p`
2382
+ <button
2383
+ class="btn btn--icon chat-compose__send"
2384
+ @click=${e.onAbort}
2385
+ aria-label="Stop"
2386
+ title="Stop generating"
2387
+ >
2388
+ ${D.square}
2389
+ </button>
2390
+ `:k}
2391
+ <button
2392
+ class="btn btn--icon chat-compose__send primary"
2393
+ ?disabled=${!e.connected}
2394
+ @click=${b=>{var A;e.onSend();const S=(A=b.target.closest(".chat-compose"))==null?void 0:A.querySelector("textarea");S&&Ia(S)}}
2395
+ aria-label="${n?"Queue":"Send"}"
2396
+ title="${n?"Queue message":"Send (Enter)"}"
2397
+ >
2398
+ ${D.send}
2399
+ </button>
2400
+ </div>
2401
+ <div class="emoji-picker-popup">
2402
+ <emoji-picker
2403
+ @emoji-click=${b=>Ky(b,e)}
2404
+ ></emoji-picker>
2405
+ </div>
2406
+ ${e.publicMode?k:Gy(e)}
2407
+ </div>
2408
+ </section>
2409
+ `}const jy=[{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 Hy(e){const t=new Set(e.filter(n=>n.provider==="anthropic").map(n=>n.id));return jy.filter(n=>t.has(n.id)).map(n=>({key:`anthropic/${n.id}`,...n}))}const qy=[{value:"off",label:"Off"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function Vy(e){var s;const t=e.currentTarget,n=(s=t.closest(".chat-model-bar"))==null?void 0:s.querySelector(".chat-settings-menu");if(!n)return;const i=n.classList.contains("active");if(document.querySelectorAll(".chat-settings-menu.active").forEach(o=>o.classList.remove("active")),!i){n.classList.add("active");const o=r=>{!n.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&(n.classList.remove("active"),document.removeEventListener("click",o))};requestAnimationFrame(()=>document.addEventListener("click",o))}}function Gy(e){if(!e.connected)return k;const t=e.modelCatalog??[],n=Hy(t);if(n.length===0)return k;const i=e.modelProvider&&e.model?`${e.modelProvider}/${e.model}`:null,s=e.thinkingLevel??"off",o=e.verboseLevel==="on"||e.verboseLevel==="full",r=e.fillerEnabled===!0;return p`
2410
+ <div class="chat-model-bar">
2411
+ <div class="chat-model-bar__select">
2412
+ <select
2413
+ class="chat-model-bar__dropdown"
2414
+ .value=${i??""}
2415
+ @change=${a=>{const u=a.target.value;u&&e.onModelChange&&e.onModelChange(u)}}
2416
+ >
2417
+ ${n.map(a=>p`
2418
+ <option value=${a.key} ?selected=${a.key===i}>
2419
+ ${a.shortName} — ${a.description}
2420
+ </option>
2421
+ `)}
2422
+ </select>
2423
+ </div>
2424
+ <div class="chat-model-bar__select">
2425
+ <select
2426
+ class="chat-model-bar__dropdown"
2427
+ .value=${s}
2428
+ @change=${a=>{const u=a.target.value;e.onThinkingLevelChange&&e.onThinkingLevelChange(u)}}
2429
+ >
2430
+ ${qy.map(a=>p`
2431
+ <option value=${a.value} ?selected=${a.value===s}>
2432
+ Thinking: ${a.label}
2433
+ </option>
2434
+ `)}
2435
+ </select>
2436
+ </div>
2437
+ <button
2438
+ class="chat-model-bar__settings-btn"
2439
+ type="button"
2440
+ @click=${Vy}
2441
+ aria-label="Message settings"
2442
+ title="Message settings"
2443
+ >
2444
+ ${D.slidersHorizontal}
2445
+ </button>
2446
+ <div class="chat-settings-menu">
2447
+ <label class="chat-settings-menu__item">
2448
+ <input
2449
+ type="checkbox"
2450
+ .checked=${o}
2451
+ @change=${a=>{const u=a.target.checked;e.onVerboseChange&&e.onVerboseChange(u?"on":"off")}}
2452
+ />
2453
+ <span>Verbose</span>
2454
+ <span class="chat-settings-menu__hint">Detailed responses</span>
2455
+ </label>
2456
+ <label class="chat-settings-menu__item">
2457
+ <input
2458
+ type="checkbox"
2459
+ .checked=${r}
2460
+ @change=${a=>{const u=a.target.checked;e.onFillerChange&&e.onFillerChange(u)}}
2461
+ />
2462
+ <span>Filler</span>
2463
+ <span class="chat-settings-menu__hint">Quick acks while thinking</span>
2464
+ </label>
2465
+ </div>
2466
+ </div>
2467
+ `}function Qy(e){const t=[];let n=null;for(const i of e){if(i.kind!=="message"){n&&(t.push(n),n=null),t.push(i);continue}const s=ml(i.message),o=yl(s.role),r=s.timestamp||Date.now();!n||n.role!==o?(n&&t.push(n),n={kind:"group",key:`group:${o}:${i.key}`,role:o,messages:[{message:i.message,key:i.key}],timestamp:r,isStreaming:!1}):n.messages.push({message:i.message,key:i.key})}return n&&t.push(n),t}function Yy(e){var o;const t=[],n=Array.isArray(e.messages)?e.messages:[],i=Array.isArray(e.toolMessages)?e.toolMessages:[],s=e.showThinking||e.verboseLevel==="on"||e.verboseLevel==="full";for(let r=0;r<n.length;r++){const a=n[r],u=ml(a);!s&&u.role.toLowerCase()==="toolresult"||t.push({kind:"message",key:Ra(a,r),message:a})}if(s)for(let r=0;r<i.length;r++)t.push({kind:"message",key:Ra(i[r],r+n.length),message:i[r]});if(e.interimText&&t.push({kind:"interim",key:"interim:thinking",text:e.interimText}),e.stream!==null){const r=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:r,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:r})}for(const r of e.queue){const a=((o=r.attachments)==null?void 0:o.filter(c=>c.fileName).map(c=>c.fileName))??[],u=a.length>0?r.text?`${a.join(", ")}
2468
+
2469
+ ${r.text}`:a.join(", "):r.text;t.push({kind:"message",key:`queue:${r.id}`,message:{role:"user",content:[{type:"text",text:u}],timestamp:r.createdAt}})}return Qy(t)}function Ra(e,t){const n=e,i=typeof n.toolCallId=="string"?n.toolCallId:"";if(i)return`tool:${i}`;const s=typeof n.id=="string"?n.id:"";if(s)return`msg:${s}`;const o=typeof n.messageId=="string"?n.messageId:"";if(o)return`msg:${o}`;const r=typeof n.timestamp=="number"?n.timestamp:null,a=typeof n.role=="string"?n.role:"unknown";return r!=null?`msg:${a}:${r}:${t}`:`msg:${a}:${t}`}const Xy=p`<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 Zy(e){if(!e.connected)return p`
2470
+ <div class="setup-container">
2471
+ <div class="setup-card">
2472
+ <div class="setup-spinner"></div>
2473
+ <p>Connecting to gateway...</p>
2474
+ </div>
2475
+ </div>
2476
+ `;const t=e.publicChatEnabled&&e.publicChatAccountId?p`<a
2477
+ class="chat-public-link"
2478
+ href="/public/chat/${e.publicChatAccountId}"
2479
+ target="_blank"
2480
+ rel="noopener"
2481
+ title="Open public chat in new tab"
2482
+ >Public ${Xy}</a>`:k;return p`
2483
+ <div class="setup-container setup-container--full chat-page">
2484
+ ${yt("Chat",e.wsProps)}
2485
+ ${t}
2486
+ <div class="chat-viewport">
2487
+ ${au(e)}
2488
+ </div>
2489
+ </div>
2490
+ `}function Jy(e){return e?`${dl(e)} (${Si(e)})`:"n/a"}function lu(e){const t=e.state??{},n=t.lastStatus??"n/a",i=t.lastRunAtMs?Si(t.lastRunAtMs):"never";return`${n} · last ${i}`}function cu(e){const t=e.schedule;return t.kind==="at"?`One-time: ${dl(t.atMs)}`:t.kind==="every"?`Every ${pl(t.everyMs)}`:ev(t.expr,t.tz)}function ev(e,t){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[i,s,o,r,a]=n,u=t?` (${t.replace(/^.*\//,"").replace(/_/g," ")})`:"",c=(b,S)=>new Date(2e3,0,1,b,S).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),l=/^\d{1,2}$/.test(i)?parseInt(i,10):null,d=Na(s);if(l===null||!d)return`${e}${t?` (${t})`:""}`;const h=d.map(b=>c(b,l)),v=h.length<=3?h.join(" & "):`${h.slice(0,-1).join(", ")} & ${h[h.length-1]}`,f=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(o==="*"&&r==="*"){if(a==="*")return`Daily at ${v}${u}`;if(a==="1-5")return`Weekdays at ${v}${u}`;if(a==="0,6"||a==="6,0")return`Weekends at ${v}${u}`;const b=Na(a);if(b)return`${b.map(A=>f[A%7]??String(A)).join(", ")} at ${v}${u}`}return`${e}${t?` (${t})`:""}`}function Na(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 tv(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 Da(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=[];return i&&s.push(i),n&&n!=="last"&&s.push(`via ${n}`),s.join(" ")||null}function nv(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 iv(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 sv(e){return e||"Default"}const Oa=p`<svg viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,ov=p`<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>`,rv=p`<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>`,uu=p`<svg viewBox="0 0 24 24"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,av=p`<svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`;function Ba(e){const t=e.detailJobId?e.jobs.find(n=>n.id===e.detailJobId)??null:null;return p`
2491
+ ${lv(e)}
2492
+ ${cv(e)}
2493
+ ${e.newEventModalOpen?dv(e):k}
2494
+ ${t?hv(t,e):k}
2495
+ `}function lv(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 p`
2496
+ <div class="event-status-bar">
2497
+ <div class="event-status-bar__info">
2498
+ <span class="statusDot ${n?"ok":""}"></span>
2499
+ <span>${n?"Active":"Inactive"}</span>
2500
+ <span class="event-status-bar__sep">\u00b7</span>
2501
+ <span>${i} event${i!==1?"s":""}</span>
2502
+ ${s?p`
2503
+ <span class="event-status-bar__sep">\u00b7</span>
2504
+ <span>Next: ${Si(s)}</span>
2505
+ `:k}
2506
+ <button
2507
+ class="btn btn--sm"
2508
+ ?disabled=${e.loading}
2509
+ @click=${e.onRefresh}
2510
+ style="margin-left: 4px;"
2511
+ >
2512
+ ${e.loading?"Refreshing…":"Refresh"}
2513
+ </button>
2514
+ ${e.error?p`<span class="muted">${e.error}</span>`:k}
2515
+ </div>
2516
+ <button class="btn primary btn--sm" @click=${e.onNewEventModalOpen}>
2517
+ ${av} New Event
2518
+ </button>
2519
+ </div>
2520
+ `}function cv(e){return e.jobs.length===0?p`<div class="muted" style="padding: 20px 0;">No events yet. Create one to get started.</div>`:p`
2521
+ <div class="event-grid">
2522
+ ${e.jobs.map(t=>uv(t,e))}
2523
+ </div>
2524
+ `}function uv(e,t){return p`
2525
+ <div
2526
+ class="event-card ${e.enabled?"":"disabled"}"
2527
+ @click=${()=>t.onDetailOpen(e)}
2528
+ >
2529
+ <div class="event-card__header">
2530
+ <div class="event-card__name">${e.name||"Untitled"}</div>
2531
+ <span class="chip ${e.enabled?"chip-ok":""}" style="font-size: 11px; padding: 2px 8px;">
2532
+ ${e.enabled?"On":"Off"}
2533
+ </span>
2534
+ </div>
2535
+ <div class="event-card__schedule">${cu(e)}</div>
2536
+ ${e.agentId?p`<div class="event-card__agent">${sv(e.agentId)}</div>`:k}
2537
+ ${Da(e)?p`<div class="event-card__agent muted" style="font-size: 11px;">\u2192 ${Da(e)}</div>`:k}
2538
+ <div class="event-card__footer">
2539
+ <div class="event-card__status">
2540
+ <span class="muted" style="font-size: 11px;">${lu(e)}</span>
2541
+ </div>
2542
+ <div class="event-card__actions" @click=${n=>n.stopPropagation()}>
2543
+ <button
2544
+ class="btn-icon"
2545
+ title="${e.enabled?"Pause":"Resume"}"
2546
+ ?disabled=${t.busy}
2547
+ @click=${()=>t.onToggle(e,!e.enabled)}
2548
+ >
2549
+ ${e.enabled?ov:Oa}
2550
+ </button>
2551
+ <button
2552
+ class="btn-icon"
2553
+ title="Run now"
2554
+ ?disabled=${t.busy}
2555
+ @click=${()=>t.onRun(e)}
2556
+ >
2557
+ ${Oa}
2558
+ </button>
2559
+ <button
2560
+ class="btn-icon danger"
2561
+ title="Delete"
2562
+ ?disabled=${t.busy}
2563
+ @click=${()=>t.onRemove(e)}
2564
+ >
2565
+ ${rv}
2566
+ </button>
2567
+ </div>
2568
+ </div>
2569
+ </div>
2570
+ `}function dv(e){const t=nv(e);return p`
2571
+ <div class="event-modal-overlay" @click=${e.onNewEventModalClose}>
2572
+ <div class="event-modal" @click=${n=>n.stopPropagation()}>
2573
+ <div class="event-modal__header">
2574
+ <div class="event-modal__title">New Event</div>
2575
+ <button class="event-modal__close" @click=${e.onNewEventModalClose}>
2576
+ ${uu}
2577
+ </button>
2578
+ </div>
2579
+
2580
+ <div class="form-grid">
2581
+ <label class="field">
2582
+ <span>Name</span>
2583
+ <input
2584
+ .value=${e.form.name}
2585
+ @input=${n=>e.onFormChange({name:n.target.value})}
2586
+ placeholder="e.g. Morning briefing"
2587
+ />
2588
+ </label>
2589
+ <label class="field">
2590
+ <span>Description</span>
2591
+ <input
2592
+ .value=${e.form.description}
2593
+ @input=${n=>e.onFormChange({description:n.target.value})}
2594
+ placeholder="What does this event do?"
2595
+ />
2596
+ </label>
2597
+ <label class="field">
2598
+ <span>Agent</span>
2599
+ <select
2600
+ .value=${e.form.agentId}
2601
+ @change=${n=>e.onFormChange({agentId:n.target.value})}
2602
+ >
2603
+ <option value="">Default</option>
2604
+ ${e.agentIds.map(n=>p`<option value=${n}>${n}</option>`)}
2605
+ </select>
2606
+ </label>
2607
+ <label class="field checkbox">
2608
+ <span>Enabled</span>
2609
+ <input
2610
+ type="checkbox"
2611
+ .checked=${e.form.enabled}
2612
+ @change=${n=>e.onFormChange({enabled:n.target.checked})}
2613
+ />
2614
+ </label>
2615
+ <label class="field">
2616
+ <span>Timing</span>
2617
+ <select
2618
+ .value=${e.form.scheduleKind}
2619
+ @change=${n=>e.onFormChange({scheduleKind:n.target.value})}
2620
+ >
2621
+ <option value="every">Repeating</option>
2622
+ <option value="at">One-time</option>
2623
+ <option value="cron">Custom schedule</option>
2624
+ </select>
2625
+ </label>
2626
+ </div>
2627
+
2628
+ ${pv(e)}
2629
+
2630
+ <div class="form-grid" style="margin-top: 12px;">
2631
+ <label class="field">
2632
+ <span>Session type</span>
2633
+ <select
2634
+ .value=${e.form.sessionTarget}
2635
+ @change=${n=>e.onFormChange({sessionTarget:n.target.value})}
2636
+ >
2637
+ <option value="main">Shared session</option>
2638
+ <option value="isolated">Separate session</option>
2639
+ </select>
2640
+ </label>
2641
+ <label class="field">
2642
+ <span>When to run</span>
2643
+ <select
2644
+ .value=${e.form.wakeMode}
2645
+ @change=${n=>e.onFormChange({wakeMode:n.target.value})}
2646
+ >
2647
+ <option value="next-heartbeat">Next available time</option>
2648
+ <option value="now">Right away</option>
2649
+ </select>
2650
+ </label>
2651
+ <label class="field">
2652
+ <span>Action type</span>
2653
+ <select
2654
+ .value=${e.form.payloadKind}
2655
+ @change=${n=>e.onFormChange({payloadKind:n.target.value})}
2656
+ >
2657
+ <option value="systemEvent">Background task</option>
2658
+ <option value="agentTurn">Send a message</option>
2659
+ </select>
2660
+ </label>
2661
+ </div>
2662
+
2663
+ <label class="field" style="margin-top: 12px;">
2664
+ <span>${e.form.payloadKind==="systemEvent"?"Task description":"Message to send"}</span>
2665
+ <textarea
2666
+ .value=${e.form.payloadText}
2667
+ @input=${n=>e.onFormChange({payloadText:n.target.value})}
2668
+ rows="4"
2669
+ placeholder="${e.form.payloadKind==="systemEvent"?"Describe what the assistant should do…":"Type the message to send…"}"
2670
+ ></textarea>
2671
+ </label>
2672
+
2673
+ ${e.form.payloadKind==="agentTurn"?p`
2674
+ <div class="form-grid" style="margin-top: 12px;">
2675
+ <label class="field checkbox">
2676
+ <span>Deliver response</span>
2677
+ <input
2678
+ type="checkbox"
2679
+ .checked=${e.form.deliver}
2680
+ @change=${n=>e.onFormChange({deliver:n.target.checked})}
2681
+ />
2682
+ </label>
2683
+ <label class="field">
2684
+ <span>Channel</span>
2685
+ <select
2686
+ .value=${e.form.channel||"last"}
2687
+ @change=${n=>e.onFormChange({channel:n.target.value})}
2688
+ >
2689
+ ${t.map(n=>p`<option value=${n}>
2690
+ ${iv(e,n)}
2691
+ </option>`)}
2692
+ </select>
2693
+ </label>
2694
+ <label class="field">
2695
+ <span>Send to</span>
2696
+ <input
2697
+ .value=${e.form.to}
2698
+ @input=${n=>e.onFormChange({to:n.target.value})}
2699
+ placeholder="+1555\u2026 or chat id"
2700
+ />
2701
+ </label>
2702
+ <label class="field">
2703
+ <span>Timeout (seconds)</span>
2704
+ <input
2705
+ .value=${e.form.timeoutSeconds}
2706
+ @input=${n=>e.onFormChange({timeoutSeconds:n.target.value})}
2707
+ />
2708
+ </label>
2709
+ ${e.form.sessionTarget==="isolated"?p`
2710
+ <label class="field">
2711
+ <span>Summary prefix</span>
2712
+ <input
2713
+ .value=${e.form.postToMainPrefix}
2714
+ @input=${n=>e.onFormChange({postToMainPrefix:n.target.value})}
2715
+ />
2716
+ </label>
2717
+ `:k}
2718
+ </div>
2719
+ `:k}
2720
+
2721
+ <div class="row" style="margin-top: 16px; justify-content: flex-end;">
2722
+ <button class="btn" @click=${e.onNewEventModalClose}>Cancel</button>
2723
+ <button class="btn primary" ?disabled=${e.busy} @click=${e.onAdd}>
2724
+ ${e.busy?"Creating…":"Create Event"}
2725
+ </button>
2726
+ </div>
2727
+ </div>
2728
+ </div>
2729
+ `}function pv(e){const t=e.form;return t.scheduleKind==="at"?p`
2730
+ <label class="field" style="margin-top: 12px;">
2731
+ <span>Run at</span>
2732
+ <input
2733
+ type="datetime-local"
2734
+ .value=${t.scheduleAt}
2735
+ @input=${n=>e.onFormChange({scheduleAt:n.target.value})}
2736
+ />
2737
+ </label>
2738
+ `:t.scheduleKind==="every"?p`
2739
+ <div class="form-grid" style="margin-top: 12px;">
2740
+ <label class="field">
2741
+ <span>Repeat every</span>
2742
+ <input
2743
+ .value=${t.everyAmount}
2744
+ @input=${n=>e.onFormChange({everyAmount:n.target.value})}
2745
+ />
2746
+ </label>
2747
+ <label class="field">
2748
+ <span>Unit</span>
2749
+ <select
2750
+ .value=${t.everyUnit}
2751
+ @change=${n=>e.onFormChange({everyUnit:n.target.value})}
2752
+ >
2753
+ <option value="minutes">Minutes</option>
2754
+ <option value="hours">Hours</option>
2755
+ <option value="days">Days</option>
2756
+ </select>
2757
+ </label>
2758
+ </div>
2759
+ `:p`
2760
+ <div class="form-grid" style="margin-top: 12px;">
2761
+ <label class="field">
2762
+ <span>Cron expression</span>
2763
+ <input
2764
+ .value=${t.cronExpr}
2765
+ @input=${n=>e.onFormChange({cronExpr:n.target.value})}
2766
+ placeholder="e.g. 0 7 * * *"
2767
+ />
2768
+ </label>
2769
+ <label class="field">
2770
+ <span>Timezone (optional)</span>
2771
+ <input
2772
+ .value=${t.cronTz}
2773
+ @input=${n=>e.onFormChange({cronTz:n.target.value})}
2774
+ placeholder="e.g. America/New_York"
2775
+ />
2776
+ </label>
2777
+ </div>
2778
+ `}function hv(e,t){var n;return p`
2779
+ <div class="event-modal-overlay" @click=${t.onDetailClose}>
2780
+ <div class="event-modal" @click=${i=>i.stopPropagation()}>
2781
+ <div class="event-modal__header">
2782
+ <div class="event-modal__title">${e.name||"Untitled Event"}</div>
2783
+ <button class="event-modal__close" @click=${t.onDetailClose}>
2784
+ ${uu}
2785
+ </button>
2786
+ </div>
2787
+
2788
+ ${e.description?p`<div style="color: var(--muted); font-size: 13px; margin-bottom: 16px;">${e.description}</div>`:k}
2789
+
2790
+ <div class="event-detail-section">
2791
+ <div class="event-detail-row">
2792
+ <span class="event-detail-label">Status</span>
2793
+ <span class="event-detail-value">
2794
+ <span class="chip ${e.enabled?"chip-ok":""}" style="font-size: 11px; padding: 2px 8px;">
2795
+ ${e.enabled?"Enabled":"Disabled"}
2796
+ </span>
2797
+ </span>
2798
+ </div>
2799
+ <div class="event-detail-row">
2800
+ <span class="event-detail-label">Schedule</span>
2801
+ <span class="event-detail-value">${cu(e)}</span>
2802
+ </div>
2803
+ ${e.agentId?p`
2804
+ <div class="event-detail-row">
2805
+ <span class="event-detail-label">Agent</span>
2806
+ <span class="event-detail-value mono">${e.agentId}</span>
2807
+ </div>
2808
+ `:k}
2809
+ <div class="event-detail-row">
2810
+ <span class="event-detail-label">Session</span>
2811
+ <span class="event-detail-value">
2812
+ ${e.sessionTarget==="main"?"Shared":"Separate"}
2813
+ </span>
2814
+ </div>
2815
+ <div class="event-detail-row">
2816
+ <span class="event-detail-label">Run mode</span>
2817
+ <span class="event-detail-value">
2818
+ ${e.wakeMode==="now"?"Right away":"Next available time"}
2819
+ </span>
2820
+ </div>
2821
+ <div class="event-detail-row" style="flex-direction: column; align-items: stretch; gap: 4px;">
2822
+ <span class="event-detail-label">Action</span>
2823
+ <span class="event-detail-value" style="text-align: left; white-space: pre-wrap; font-size: 12px; color: var(--muted); line-height: 1.5;">${tv(e,!1)}</span>
2824
+ </div>
2825
+ ${e.payload.kind==="agentTurn"&&e.payload.to?p`
2826
+ <div class="event-detail-row">
2827
+ <span class="event-detail-label">Send to</span>
2828
+ <span class="event-detail-value mono">${e.payload.to}</span>
2829
+ </div>
2830
+ `:k}
2831
+ ${e.payload.kind==="agentTurn"&&(e.payload.channel??e.payload.provider)?p`
2832
+ <div class="event-detail-row">
2833
+ <span class="event-detail-label">Channel</span>
2834
+ <span class="event-detail-value">${e.payload.channel??e.payload.provider}</span>
2835
+ </div>
2836
+ `:k}
2837
+ ${e.payload.kind==="agentTurn"?p`
2838
+ <div class="event-detail-row">
2839
+ <span class="event-detail-label">Auto-deliver</span>
2840
+ <span class="event-detail-value">${e.payload.deliver?"Yes":"No"}</span>
2841
+ </div>
2842
+ `:k}
2843
+ </div>
2844
+
2845
+ <div class="event-detail-section">
2846
+ <div class="event-detail-row">
2847
+ <span class="event-detail-label">Last run</span>
2848
+ <span class="event-detail-value">${lu(e)}</span>
2849
+ </div>
2850
+ ${(n=e.state)!=null&&n.nextRunAtMs?p`
2851
+ <div class="event-detail-row">
2852
+ <span class="event-detail-label">Next run</span>
2853
+ <span class="event-detail-value">${Jy(e.state.nextRunAtMs)}</span>
2854
+ </div>
2855
+ `:k}
2856
+ </div>
2857
+
2858
+ <div class="event-detail-section">
2859
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
2860
+ <span class="event-detail-label" style="font-size: 14px;">Recent Activity</span>
2861
+ </div>
2862
+ ${t.runs.length===0?p`<div class="muted" style="font-size: 13px;">No runs recorded yet.</div>`:p`
2863
+ <div class="list">
2864
+ ${[...t.runs].sort((i,s)=>s.ts-i.ts).map(i=>gv(i))}
2865
+ </div>
2866
+ `}
2867
+ </div>
2868
+
2869
+ <div class="row" style="margin-top: 16px; gap: 8px; justify-content: flex-end;">
2870
+ <button
2871
+ class="btn"
2872
+ ?disabled=${t.busy}
2873
+ @click=${()=>t.onToggle(e,!e.enabled)}
2874
+ >
2875
+ ${e.enabled?"Disable":"Enable"}
2876
+ </button>
2877
+ <button
2878
+ class="btn primary"
2879
+ ?disabled=${t.busy}
2880
+ @click=${()=>t.onRun(e)}
2881
+ >
2882
+ Run Now
2883
+ </button>
2884
+ <button
2885
+ class="btn danger"
2886
+ ?disabled=${t.busy}
2887
+ @click=${()=>{t.onRemove(e),t.onDetailClose()}}
2888
+ >
2889
+ Delete
2890
+ </button>
2891
+ </div>
2892
+ </div>
2893
+ </div>
2894
+ `}function fv(e){const t=e.toLowerCase();return t==="ok"||t==="success"?"chip chip-ok":t==="error"||t==="fail"||t==="failed"?"chip chip-warn":"chip"}function gv(e){return p`
2895
+ <div class="list-item" style="grid-template-columns: 1fr; gap: 6px;">
2896
+ <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
2897
+ <span class=${fv(e.status)} style="font-size: 11px; padding: 2px 8px;">
2898
+ ${e.status}
2899
+ </span>
2900
+ <span class="muted" style="font-size: 12px;">${Si(e.ts)}</span>
2901
+ <span class="muted" style="font-size: 12px;">${pl(e.durationMs)}</span>
2902
+ </div>
2903
+ ${e.summary?p`<div class="muted" style="font-size: 12px;">${e.summary}</div>`:k}
2904
+ ${e.error?p`
2905
+ <details style="margin-top: 2px;">
2906
+ <summary class="muted" style="cursor: pointer; font-size: 12px;">Error details</summary>
2907
+ <div class="muted" style="margin-top: 4px; white-space: pre-wrap; font-size: 12px;">${e.error}</div>
2908
+ </details>
2909
+ `:k}
2910
+ </div>
2911
+ `}function mv(e){var s;const t=((s=e.report)==null?void 0:s.skills)??[],n=e.filter.trim().toLowerCase(),i=n?t.filter(o=>[o.name,o.description,o.source].join(" ").toLowerCase().includes(n)):t;return p`
2912
+ <section class="card">
2913
+ <div class="row" style="justify-content: space-between;">
2914
+ <div>
2915
+ <div class="card-title">Skills</div>
2916
+ <div class="card-sub">Bundled, managed, and workspace skills.</div>
2917
+ </div>
2918
+ <button class="btn" ?disabled=${e.loading} @click=${e.onRefresh}>
2919
+ ${e.loading?"Loading…":"Refresh"}
2920
+ </button>
2921
+ </div>
2922
+
2923
+ <div class="filters" style="margin-top: 14px;">
2924
+ <label class="field" style="flex: 1;">
2925
+ <span>Filter</span>
2926
+ <input
2927
+ .value=${e.filter}
2928
+ @input=${o=>e.onFilterChange(o.target.value)}
2929
+ placeholder="Search skills"
2930
+ />
2931
+ </label>
2932
+ <div class="muted">${i.length} shown</div>
2933
+ </div>
2934
+
2935
+ ${e.error?p`<div class="callout danger" style="margin-top: 12px;">${e.error}</div>`:k}
2936
+
2937
+ ${i.length===0?p`<div class="muted" style="margin-top: 16px;">No skills found.</div>`:p`
2938
+ <div class="list" style="margin-top: 16px;">
2939
+ ${i.map(o=>yv(o,e))}
2940
+ </div>
2941
+ `}
2942
+ </section>
2943
+ `}function yv(e,t){const n=t.busyKey===e.skillKey,i=t.edits[e.skillKey]??"",s=t.messages[e.skillKey]??null,o=e.install.length>0&&e.missing.bins.length>0,r=[...e.missing.bins.map(u=>`bin:${u}`),...e.missing.env.map(u=>`env:${u}`),...e.missing.config.map(u=>`config:${u}`),...e.missing.os.map(u=>`os:${u}`)],a=[];return e.disabled&&a.push("disabled"),e.blockedByAllowlist&&a.push("blocked by allowlist"),p`
2944
+ <div class="list-item">
2945
+ <div class="list-main">
2946
+ <div class="list-title">
2947
+ ${e.emoji?`${e.emoji} `:""}${e.name}
2948
+ </div>
2949
+ <div class="list-sub">${kd(e.description,140)}</div>
2950
+ <div class="chip-row" style="margin-top: 6px;">
2951
+ <span class="chip">${e.source}</span>
2952
+ <span class="chip ${e.eligible?"chip-ok":"chip-warn"}">
2953
+ ${e.eligible?"eligible":"blocked"}
2954
+ </span>
2955
+ ${e.disabled?p`<span class="chip chip-warn">disabled</span>`:k}
2956
+ </div>
2957
+ ${r.length>0?p`
2958
+ <div class="muted" style="margin-top: 6px;">
2959
+ Missing: ${r.join(", ")}
2960
+ </div>
2961
+ `:k}
2962
+ ${a.length>0?p`
2963
+ <div class="muted" style="margin-top: 6px;">
2964
+ Reason: ${a.join(", ")}
2965
+ </div>
2966
+ `:k}
2967
+ </div>
2968
+ <div class="list-meta">
2969
+ <div class="row" style="justify-content: flex-end; flex-wrap: wrap;">
2970
+ <button
2971
+ class="btn"
2972
+ ?disabled=${n}
2973
+ @click=${()=>t.onToggle(e.skillKey,e.disabled)}
2974
+ >
2975
+ ${e.disabled?"Enable":"Disable"}
2976
+ </button>
2977
+ ${o?p`<button
2978
+ class="btn"
2979
+ ?disabled=${n}
2980
+ @click=${()=>t.onInstall(e.skillKey,e.name,e.install[0].id)}
2981
+ >
2982
+ ${n?"Installing…":e.install[0].label}
2983
+ </button>`:k}
2984
+ </div>
2985
+ ${s?p`<div
2986
+ class="muted"
2987
+ style="margin-top: 8px; color: ${s.kind==="error"?"var(--danger-color, #d14343)":"var(--success-color, #0a7f5a)"};"
2988
+ >
2989
+ ${s.message}
2990
+ </div>`:k}
2991
+ ${e.primaryEnv?p`
2992
+ <div class="field" style="margin-top: 10px;">
2993
+ <span>API key</span>
2994
+ <input
2995
+ type="password"
2996
+ .value=${i}
2997
+ @input=${u=>t.onEdit(e.skillKey,u.target.value)}
2998
+ />
2999
+ </div>
3000
+ <button
3001
+ class="btn primary"
3002
+ style="margin-top: 8px;"
3003
+ ?disabled=${n}
3004
+ @click=${()=>t.onSaveKey(e.skillKey)}
3005
+ >
3006
+ Save key
3007
+ </button>
3008
+ `:k}
3009
+ </div>
3010
+ </div>
3011
+ `}const Fa=["user","assistant","tool","thinking","error"],Ua={user:"User",assistant:"Assistant",tool:"Tool",thinking:"Thinking",error:"Error",system:"System"};function vv(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 bv(e){return e.split(":").slice(2).join(":")||e}function wv(e,t){return t?[e.content,e.agentId,e.sessionKey,e.sessionId,e.toolName].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function kv(e,t=500){return e.length<=t?e:e.slice(0,t)+"..."}function Sv(e){const t=e.filterText.trim().toLowerCase();Fa.some(i=>!e.typeFilters[i]),e.agents.some(i=>!e.agentFilters[i]);const n=e.entries.filter(i=>!e.typeFilters[i.type]||e.agents.length>0&&!(e.agentFilters[i.agentId]??!0)?!1:wv(i,t));return p`
3012
+ <div>
3013
+ <div class="filters" style="margin-top: 14px;">
3014
+ <label class="field" style="min-width: 220px;">
3015
+ <span>Filter</span>
3016
+ <input
3017
+ .value=${e.filterText}
3018
+ @input=${i=>e.onFilterTextChange(i.target.value)}
3019
+ placeholder="Search session logs"
3020
+ />
3021
+ </label>
3022
+ </div>
3023
+
3024
+ <div class="chip-row" style="margin-top: 12px;">
3025
+ ${Fa.map(i=>p`
3026
+ <label class="chip session-log-chip ${i}">
3027
+ <input
3028
+ type="checkbox"
3029
+ .checked=${e.typeFilters[i]}
3030
+ @change=${s=>e.onTypeToggle(i,s.target.checked)}
3031
+ />
3032
+ <span>${Ua[i]}</span>
3033
+ </label>
3034
+ `)}
3035
+ </div>
3036
+
3037
+ <div class="chip-row" style="margin-top: 8px; align-items: center;">
3038
+ ${e.agents.map(i=>p`
3039
+ <label class="chip agent-chip">
3040
+ <input
3041
+ type="checkbox"
3042
+ .checked=${e.agentFilters[i]??!0}
3043
+ @change=${s=>e.onAgentToggle(i,s.target.checked)}
3044
+ />
3045
+ <span>${i}</span>
3046
+ </label>
3047
+ `)}
3048
+ <label class="chip">
3049
+ <input
3050
+ type="checkbox"
3051
+ .checked=${e.autoFollow}
3052
+ @change=${i=>e.onToggleAutoFollow(i.target.checked)}
3053
+ />
3054
+ <span>Auto-follow</span>
3055
+ </label>
3056
+ </div>
3057
+
3058
+ ${e.error?p`<div class="callout danger" style="margin-top: 10px;">${e.error}</div>`:k}
3059
+
3060
+ <div class="log-stream" style="margin-top: 12px;" @scroll=${e.onScroll}>
3061
+ ${n.length===0?p`<div class="muted" style="padding: 12px;">No session log entries.</div>`:n.map(i=>p`
3062
+ <div class="log-row session-entry ${i.type}">
3063
+ <div class="log-row-header">
3064
+ <span class="log-time mono">${vv(i.timestamp)}</span>
3065
+ <span class="session-log-type ${i.type}">${Ua[i.type]}</span>
3066
+ <span class="log-subsystem mono">${i.agentId}</span>
3067
+ <span class="session-label mono">${bv(i.sessionKey)}</span>
3068
+ ${i.toolName?p`<span class="session-tool mono">${i.toolName}</span>`:k}
3069
+ ${i.model?p`<span class="session-model mono">${i.model}</span>`:k}
3070
+ </div>
3071
+ <div class="log-message mono">${kv(i.content)}</div>
3072
+ </div>
3073
+ `)}
3074
+ </div>
3075
+ </div>
3076
+ `}const Vs=["trace","debug","info","warn","error","fatal"];function xv(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 Av(e){return p`
3077
+ <section class="card">
3078
+ <div class="row" style="justify-content: space-between;">
3079
+ <div>
3080
+ <div class="card-title">Logs</div>
3081
+ <div class="card-sub">Session transcripts and system logs.</div>
3082
+ </div>
3083
+ <div class="row" style="gap: 8px;">
3084
+ ${e.logsSubTab==="system"?p`
3085
+ <button class="btn" ?disabled=${e.loading} @click=${e.onRefresh}>
3086
+ ${e.loading?"Loading…":"Refresh"}
3087
+ </button>
3088
+ <button
3089
+ class="btn"
3090
+ ?disabled=${e.entries.length===0}
3091
+ @click=${()=>{const t=e.filterText.trim().toLowerCase(),n=Vs.some(o=>!e.levelFilters[o]),i=e.entries.filter(o=>o.level&&!e.levelFilters[o.level]?!1:du(o,t)),s=t||n?"filtered":"visible";e.onExport(i.map(o=>o.raw),s)}}
3092
+ >
3093
+ Export
3094
+ </button>
3095
+ `:p`
3096
+ <button class="btn" ?disabled=${e.sessionLogsProps.loading} @click=${e.sessionLogsProps.onRefresh}>
3097
+ ${e.sessionLogsProps.loading?"Loading…":"Refresh"}
3098
+ </button>
3099
+ <button
3100
+ class="btn"
3101
+ ?disabled=${e.sessionLogsProps.entries.length===0}
3102
+ @click=${()=>{const t=e.sessionLogsProps,n=t.filterText.trim().toLowerCase(),s=t.entries.filter(o=>!t.typeFilters[o.type]||t.agents.length>0&&!(t.agentFilters[o.agentId]??!0)?!1:n?[o.content,o.agentId,o.sessionKey,o.sessionId,o.toolName].filter(Boolean).join(" ").toLowerCase().includes(n):!0).map(o=>`${o.timestamp} [${o.type}] ${o.agentId} ${o.sessionKey} ${o.toolName??""} ${o.content}`);t.onExport(s,n?"filtered":"visible")}}
3103
+ >
3104
+ Export
3105
+ </button>
3106
+ `}
3107
+ </div>
3108
+ </div>
3109
+
3110
+ <div class="sp-tabs" style="margin-top: 12px;">
3111
+ <button class="sp-tab ${e.logsSubTab==="session"?"active":""}"
3112
+ @click=${()=>e.onSubTabChange("session")}>
3113
+ Session Logs
3114
+ </button>
3115
+ <button class="sp-tab ${e.logsSubTab==="system"?"active":""}"
3116
+ @click=${()=>e.onSubTabChange("system")}>
3117
+ System Logs
3118
+ </button>
3119
+ </div>
3120
+
3121
+ ${e.logsSubTab==="session"?Sv(e.sessionLogsProps):$v(e)}
3122
+ </section>
3123
+ `}function $v(e){const t=e.filterText.trim().toLowerCase();Vs.some(i=>!e.levelFilters[i]);const n=e.entries.filter(i=>i.level&&!e.levelFilters[i.level]?!1:du(i,t));return p`
3124
+ <div class="filters" style="margin-top: 14px;">
3125
+ <label class="field" style="min-width: 220px;">
3126
+ <span>Filter</span>
3127
+ <input
3128
+ .value=${e.filterText}
3129
+ @input=${i=>e.onFilterTextChange(i.target.value)}
3130
+ placeholder="Search logs"
3131
+ />
3132
+ </label>
3133
+ <label class="field checkbox">
3134
+ <span>Auto-follow</span>
3135
+ <input
3136
+ type="checkbox"
3137
+ .checked=${e.autoFollow}
3138
+ @change=${i=>e.onToggleAutoFollow(i.target.checked)}
3139
+ />
3140
+ </label>
3141
+ </div>
3142
+
3143
+ <div class="chip-row" style="margin-top: 12px;">
3144
+ ${Vs.map(i=>p`
3145
+ <label class="chip log-chip ${i}">
3146
+ <input
3147
+ type="checkbox"
3148
+ .checked=${e.levelFilters[i]}
3149
+ @change=${s=>e.onLevelToggle(i,s.target.checked)}
3150
+ />
3151
+ <span>${i}</span>
3152
+ </label>
3153
+ `)}
3154
+ </div>
3155
+
3156
+ ${e.file?p`<div class="muted" style="margin-top: 10px;">File: ${e.file}</div>`:k}
3157
+ ${e.truncated?p`<div class="callout" style="margin-top: 10px;">
3158
+ Log output truncated; showing latest chunk.
3159
+ </div>`:k}
3160
+ ${e.error?p`<div class="callout danger" style="margin-top: 10px;">${e.error}</div>`:k}
3161
+
3162
+ <div class="log-stream" style="margin-top: 12px;" @scroll=${e.onScroll}>
3163
+ ${n.length===0?p`<div class="muted" style="padding: 12px;">No log entries.</div>`:[...n].reverse().map(i=>p`
3164
+ <div class="log-row">
3165
+ <div class="log-row-header">
3166
+ <span class="log-time mono">${xv(i.time)}</span>
3167
+ <span class="log-level ${i.level??""}">${i.level??""}</span>
3168
+ <span class="log-subsystem mono">${i.subsystem??""}</span>
3169
+ </div>
3170
+ <div class="log-message mono">${i.message??i.raw}</div>
3171
+ </div>
3172
+ `)}
3173
+ </div>
3174
+ `}const Ev=[{id:"cron",label:"Events"},{id:"skills",label:"Skills"},{id:"logs",label:"Logs"}];function Tv(e){switch(e.activeTab){case"cron":return Ba(e.cronProps);case"skills":return mv(e.skillsProps);case"logs":return Av(e.logsProps);default:return Ba(e.cronProps)}}function Cv(e){return e.connected?p`
3175
+ <div class="setup-container">
3176
+ ${yt("Advanced",e.wsProps)}
3177
+ <div class="setup-card sp-card-advanced" style="text-align: left;">
3178
+ <h1>Advanced</h1>
3179
+ <div class="sp-tabs">
3180
+ ${Ev.map(t=>p`
3181
+ <button
3182
+ class="sp-tab ${e.activeTab===t.id?"active":""}"
3183
+ @click=${()=>e.onTabChange(t.id)}
3184
+ >
3185
+ ${t.label}
3186
+ </button>
3187
+ `)}
3188
+ </div>
3189
+ ${Tv(e)}
3190
+ </div>
3191
+ </div>
3192
+ `:p`
3193
+ <div class="setup-container">
3194
+ <div class="setup-card">
3195
+ <div class="setup-spinner"></div>
3196
+ <p>Connecting to gateway...</p>
3197
+ </div>
3198
+ </div>
3199
+ `}function Wa(e){if(!e.show)return k;const t=Xe(),n=e.isFirstTime,i=e.changePinMode===!0&&!n,s=e.changePinBusy===!0;let o=e.accounts.length>0?e.accounts[0].id:"";const r=h=>{var f;o=h.target.value;const v=(f=h.target.closest(".login-card"))==null?void 0:f.querySelector(".login-change-pin");v&&(v.style.display=o==="__master__"?"":"none")},a=h=>v=>{const f=v.target;f.value=f.value.replace(/\D/g,"").slice(0,6),h(f.value)},u=!n&&e.accounts.length>1?p`
3200
+ <select
3201
+ class="login-account-select"
3202
+ @change=${r}
3203
+ ?disabled=${e.busy||s}
3204
+ >
3205
+ ${e.accounts.map((h,v)=>p`
3206
+ <option value=${h.id} ?selected=${v===0}>
3207
+ ${h.displayName}
3208
+ </option>
3209
+ `)}
3210
+ </select>
3211
+ `:k;if(i){let h="",v="",f="";const b=S=>{var A;S.preventDefault(),!s&&(!h||!v||!f||v===f&&o&&((A=e.onChangePin)==null||A.call(e,o,h,v)))};return p`
3212
+ <div class="login-overlay">
3213
+ <div class="login-card">
3214
+ <img class="login-logo" src="${t.iconUrl}" alt="${t.name}" />
3215
+ <h2 class="login-title">Change PIN</h2>
3216
+ <p class="login-subtitle">Enter your current PIN, then choose a new one</p>
3217
+ <form class="login-form" @submit=${b}>
3218
+ ${u}
3219
+ <input
3220
+ class="login-pin-input"
3221
+ type="password"
3222
+ inputmode="numeric"
3223
+ pattern="[0-9]*"
3224
+ minlength="4"
3225
+ maxlength="6"
3226
+ placeholder="Current PIN"
3227
+ ?disabled=${s}
3228
+ @input=${a(S=>{h=S})}
3229
+ autofocus
3230
+ />
3231
+ <input
3232
+ class="login-pin-input"
3233
+ type="password"
3234
+ inputmode="numeric"
3235
+ pattern="[0-9]*"
3236
+ minlength="4"
3237
+ maxlength="6"
3238
+ placeholder="New PIN (4-6 digits)"
3239
+ ?disabled=${s}
3240
+ @input=${a(S=>{v=S})}
3241
+ />
3242
+ <input
3243
+ class="login-pin-input"
3244
+ type="password"
3245
+ inputmode="numeric"
3246
+ pattern="[0-9]*"
3247
+ minlength="4"
3248
+ maxlength="6"
3249
+ placeholder="Confirm new PIN"
3250
+ ?disabled=${s}
3251
+ @input=${a(S=>{f=S})}
3252
+ />
3253
+ ${e.changePinError?p`<p class="login-error">${e.changePinError}</p>`:k}
3254
+ ${e.changePinSuccess?p`<p class="login-success">${e.changePinSuccess}</p>`:k}
3255
+ <button
3256
+ class="login-submit"
3257
+ type="submit"
3258
+ ?disabled=${s}
3259
+ >${s?p`<span class="login-spinner"></span>`:"Change PIN"}</button>
3260
+ </form>
3261
+ <p class="login-hint" style="margin-top: 16px;">
3262
+ <a
3263
+ class="login-link"
3264
+ href="#"
3265
+ @click=${S=>{var A;S.preventDefault(),(A=e.onToggleChangePinMode)==null||A.call(e)}}
3266
+ >Back to login</a>
3267
+ </p>
3268
+ </div>
3269
+ </div>
3270
+ `}let c="",l="";const d=h=>{if(h.preventDefault(),!e.busy)if(n){if(!c||!l||c!==l)return;e.onSubmit(c)}else{if(!c||!o)return;e.onSubmit(o,c)}};return p`
3271
+ <div class="login-overlay">
3272
+ <div class="login-card">
3273
+ <img class="login-logo" src="${t.iconUrl}" alt="${t.name}" />
3274
+ <h2 class="login-title">${t.name}</h2>
3275
+ <p class="login-subtitle">
3276
+ ${n?"Set a PIN to protect this device":"Enter your PIN to continue"}
3277
+ </p>
3278
+ <form class="login-form" @submit=${d}>
3279
+ ${u}
3280
+ <input
3281
+ class="login-pin-input"
3282
+ type="password"
3283
+ inputmode="numeric"
3284
+ pattern="[0-9]*"
3285
+ minlength="4"
3286
+ maxlength="6"
3287
+ placeholder="${n?"Choose a 4-6 digit PIN":"PIN"}"
3288
+ ?disabled=${e.busy}
3289
+ @input=${a(h=>{c=h})}
3290
+ autofocus
3291
+ />
3292
+ ${n?p`
3293
+ <input
3294
+ class="login-pin-input"
3295
+ type="password"
3296
+ inputmode="numeric"
3297
+ pattern="[0-9]*"
3298
+ minlength="4"
3299
+ maxlength="6"
3300
+ placeholder="Confirm PIN"
3301
+ ?disabled=${e.busy}
3302
+ @input=${a(h=>{l=h})}
3303
+ />
3304
+ `:k}
3305
+ ${e.error?p`<p class="login-error">${e.error}</p>`:k}
3306
+ <button
3307
+ class="login-submit"
3308
+ type="submit"
3309
+ ?disabled=${e.busy}
3310
+ >
3311
+ ${e.busy?p`<span class="login-spinner"></span>`:n?"Set PIN":"Unlock"}
3312
+ </button>
3313
+ </form>
3314
+ ${n?p`<p class="login-hint">This PIN protects all accounts on this device. You'll need it every time you open the dashboard.</p>`:e.accounts.some(h=>h.id==="__master__")?p`<p class="login-hint login-change-pin" style="margin-top: 16px;${o!=="__master__"?" display: none;":""}">
3315
+ <a
3316
+ class="login-link"
3317
+ href="#"
3318
+ @click=${h=>{var v;h.preventDefault(),(v=e.onToggleChangePinMode)==null||v.call(e)}}
3319
+ >Change PIN</a>
3320
+ </p>`:k}
3321
+ </div>
3322
+ </div>
3323
+ `}function _v(e){if(!e.connected)return p`
3324
+ <div class="setup-container">
3325
+ <div class="setup-card">
3326
+ <div class="setup-spinner"></div>
3327
+ <p>Connecting...</p>
3328
+ </div>
3329
+ </div>
3330
+ `;const t={...e,sessions:null,focusMode:!1,showThinking:!1,thinkingLevel:null,publicMode:!0,onToggleFocusMode:()=>{},onSessionKeyChange:()=>{},onNewSession:()=>{}},n=e.assistantName||"Assistant";return p`
3331
+ <div class="setup-container setup-container--full public-chat-page">
3332
+ <div class="public-chat-header">
3333
+ <span class="public-chat-header__name">${n}</span>
3334
+ </div>
3335
+ <div class="chat-viewport">
3336
+ ${au(t)}
3337
+ </div>
3338
+ </div>
3339
+ `}async function Mv(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 wn(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 Pv(e,t){var i,s;if(!e.client||!e.connected||e.workspaceSaving)return;const n=t.name.trim();if(!n){e.workspacesError="Account name is required.";return}e.workspaceSaving=!0,e.workspacesError=null;try{const o=await e.client.request("config.get",{});e.configSnapshot=o;const r=o.hash;if(!r){e.workspacesError="Config hash missing; reload and retry.";return}const a={name:n,baseHash:r,whatsappAccountName:n};(i=t.workspacePath)!=null&&i.trim()&&(a.workspaceDir=t.workspacePath.trim());const u=await e.client.request("workspaces.create",a);e.addingWorkspace=!1,e.newWorkspaceName="",e.newWorkspacePath="",await wn(e),(s=t.onCreated)==null||s.call(t,u)}catch(o){e.workspacesError=String(o)}finally{e.workspaceSaving=!1}}async function Lv(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 wn(e)}catch(n){e.workspacesError=String(n)}finally{e.workspaceSaving=!1}}}async function Iv(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 wn(e)}catch(i){e.workspacesError=String(i)}}}const Hn=Object.freeze(Object.defineProperty({__proto__:null,createWorkspace:Pv,loadWorkspaces:wn,removeWorkspace:Lv,renameWorkspace:Iv},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"},Ka=pu,Gs={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(pu));new Set(Object.values(Gs));function Rv(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 Nv=4008;class Dv{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,r=!1,a=this.opts.token;if(s){o=await Fp();const h=(d=Kp({deviceId:o.deviceId,role:t}))==null?void 0:d.token;a=h??this.opts.token,r=!!(h&&this.opts.token)}const u=a||this.opts.password?{token:a,password:this.opts.password}:void 0;let c;if(s&&o){const h=Date.now(),v=this.connectNonce??void 0,f=Rv({deviceId:o.deviceId,clientId:this.opts.clientName??Ka.CONTROL_UI,clientMode:this.opts.mode??Gs.WEBCHAT,role:t,scopes:n,signedAtMs:h,token:a??null,nonce:v}),b=await Up(o.privateKey,f);c={id:o.deviceId,publicKey:o.publicKey,signature:b,signedAt:h,nonce:v}}const l={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Ka.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Gs.WEBCHAT,instanceId:this.opts.instanceId},role:t,scopes:n,device:c,caps:[],auth:u,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",l).then(h=>{var v,f,b;(v=h==null?void 0:h.auth)!=null&&v.deviceToken&&o&&zp({deviceId:o.deviceId,role:h.auth.role??t,token:h.auth.deviceToken,scopes:h.auth.scopes??[]}),this.backoffMs=800,(b=(f=this.opts).onHello)==null||b.call(f,h)}).catch(()=>{var h;r&&o&&jp({deviceId:o.deviceId,role:t}),(h=this.ws)==null||h.close(Nv,"connect failed")})}handleMessage(t){var s,o,r,a,u,c;let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const l=n;if(l.event==="connect.challenge"){const h=l.payload,v=h&&typeof h.nonce=="string"?h.nonce:null;v&&(this.connectNonce=v,this.sendConnect());return}const d=typeof l.seq=="number"?l.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{(a=(r=this.opts).onEvent)==null||a.call(r,l)}catch(h){console.error("[gateway] event handler error:",h)}return}if(i.type==="res"){const l=n,d=this.pending.get(l.id);if(!d)return;if(this.pending.delete(l.id),l.ok)d.resolve(l.payload);else{const h=new Error(((u=l.error)==null?void 0:u.message)??"request failed");h.payload=l.payload,h.details=(c=l.error)==null?void 0:c.details,d.reject(h)}return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=no(),s={type:"req",id:i,method:t,params:n},o=new Promise((r,a)=>{this.pending.set(i,{resolve:u=>r(u),reject:a})});return this.ws.send(JSON.stringify(s)),o}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}function Qs(e){return typeof e=="object"&&e!==null}function Ov(e){if(!Qs(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Qs(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 Bv(e){if(!Qs(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 Fv(e,t){const n=hu(e).filter(i=>i.id!==t.id);return n.push(t),n}function za(e,t){return hu(e).filter(n=>n.id!==t)}class Uv{constructor(){this.canvas=null,this.ctx=null,this.img=new Image,this.pendingFrame=null,this.rafId=null,this.deviceWidth=1280,this.deviceHeight=720,this.lastMouseMoveAt=0,this.MOUSE_THROTTLE_MS=30}attach(t){this.canvas=t,this.ctx=t.getContext("2d")}detach(){this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.canvas=null,this.ctx=null,this.pendingFrame=null}updateFrame(t,n){if(n!=null&&n.deviceWidth&&(this.deviceWidth=n.deviceWidth),n!=null&&n.deviceHeight&&(this.deviceHeight=n.deviceHeight),this.pendingFrame=t,!this.canvas){const i=document.getElementById("browser-screencast-canvas");i&&this.attach(i)}this.rafId==null&&(this.rafId=requestAnimationFrame(()=>this.renderFrame()))}renderFrame(){this.rafId=null;const t=this.pendingFrame;!t||!this.canvas||!this.ctx||(this.pendingFrame=null,this.img.onload=()=>{!this.canvas||!this.ctx||((this.canvas.width!==this.img.width||this.canvas.height!==this.img.height)&&(this.canvas.width=this.img.width,this.canvas.height=this.img.height),this.ctx.drawImage(this.img,0,0))},this.img.src=`data:image/jpeg;base64,${t}`)}translateCoordinates(t,n){if(!this.canvas)return{x:t,y:n};const i=this.canvas.getBoundingClientRect(),s=this.canvas.width/i.width,o=this.canvas.height/i.height,r=this.deviceWidth/this.canvas.width,a=this.deviceHeight/this.canvas.height;return{x:Math.round(t*s*r),y:Math.round(n*o*a)}}shouldThrottleMouseMove(){const t=performance.now();return t-this.lastMouseMoveAt<this.MOUSE_THROTTLE_MS?!0:(this.lastMouseMoveAt=t,!1)}getDeviceDimensions(){return{width:this.deviceWidth,height:this.deviceHeight}}}let bs=null;function cn(){return bs||(bs=new Uv),bs}function zo(e){return e instanceof Error?e.message:String(e)}async function Wv(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=zo(t)}finally{e.browserLoading=!1}}async function Kv(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=zo(t)}finally{e.browserLoading=!1}}}async function ws(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 ks(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 zv(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=zo(t)}}function jv(e){e.browserInputMode=!e.browserInputMode}function Hv(e){e.browserFullscreen=!e.browserFullscreen,cn().detach()}function qv(e,t){if(!(t!=null&&t.data))return;e.browserScreencastFrame=t.data,e.browserScreencastMetadata=t.metadata??null,cn().updateFrame(t.data,t.metadata)}function Vv(e,t){t&&(e.browserHandoffPending=!0,e.browserHandoffReason=t.reason??"Action required",e.browserHandoffId=t.id??null)}function Gv(e){e.browserHandoffPending=!1,e.browserHandoffReason=null,e.browserHandoffId=null}async function Ys(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=Es(s);e.assistantName=o.name,e.assistantAvatar=o.avatar,e.assistantAgentId=o.agentId??null}catch{}}async function Xs(e){return(await e.request("apikeys.list")).providers??[]}async function ja(e,t,n){await e.request("apikeys.set",{provider:t,apiKey:n})}async function Qv(e,t){await e.request("apikeys.remove",{provider:t})}const yi="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 Yv(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(yi,String(Date.now())),localStorage.removeItem(jo)}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")un(),e.updateMessage=o.result.reason||"Update skipped",e.updateRunning=!1,(i=e.requestUpdate)==null||i.call(e);else throw un(),new Error(o.result.reason||"Update failed")}catch(o){un(),e.updateMessage=`Update failed: ${String(o)}`,e.updateRunning=!1,e.updateProgressSteps=[],(s=e.requestUpdate)==null||s.call(e)}}}function Xv(e,t){var i,s,o;const n=t.phase;if(n==="step-start"){const r=t.name,a=t.index,u=t.total;e.updateMessage=`Updating: ${r} (${a+1}/${u})`;const c=e.updateProgressSteps.find(l=>l.index===a);c?(c.status="running",c.name=r):e.updateProgressSteps=[...e.updateProgressSteps,{name:r,index:a,total:u,status:"running"}],(i=e.requestUpdate)==null||i.call(e)}else if(n==="step-done"){const r=t.name,a=t.index,u=t.total,c=t.ok,l=t.durationMs,d=e.updateProgressSteps.find(v=>v.index===a);d?(d.status=c?"done":"failed",d.durationMs=l):e.updateProgressSteps=[...e.updateProgressSteps,{name:r,index:a,total:u,status:c?"done":"failed",durationMs:l}];const h=!c&&t.error?`: ${t.error.slice(0,200)}`:"";e.updateMessage=c?`Updating: ${r} done (${a+1}/${u})`:`Update step failed: ${r}${h}`,(s=e.requestUpdate)==null||s.call(e)}else if(n==="complete"){if(t.status==="ok")e.updateMessage="Update complete — restarting gateway...";else{const a=t.reason;e.updateMessage=a?`Update failed: ${a}`:"Update failed",e.updateRunning=!1,un()}(o=e.requestUpdate)==null||o.call(e)}}async function Zv(e){var n,i,s,o;if(!e.client||!e.connected)return;const t=eb();un();try{const r=await e.client.request("update.lastResult",{});if(!r.ok||!r.result)return;const a=5*6e4,u=Date.now()-r.result.ts<a;if(!t&&!u||tb(r.result.ts))return;e.updateLastResult=r.result;const c=(n=r.result.after)==null?void 0:n.version;if(r.result.status==="ok"&&c&&(e.currentVersion=c),e.updateAvailable=!1,r.result.status==="ok"){const l=(i=r.result.before)==null?void 0:i.version,d=c??r.result.currentVersion;e.updateMessage=l?`Updated: v${l} → v${d}`:`Updated to v${d}`}else{const l=r.result.reason??((s=r.result.failedStep)==null?void 0:s.name)??"unknown error";e.updateMessage=`Update failed: ${l}`}}catch{}finally{e.updateRunning=!1,e.updateProgressSteps=[],(o=e.requestUpdate)==null||o.call(e)}}const jo="taskmaster_update_dismissed";function Jv(e){var t;e.updateLastResult=null,e.updateMessage=null;try{localStorage.setItem(jo,String(Date.now()))}catch{}(t=e.requestUpdate)==null||t.call(e)}function eb(){try{const e=localStorage.getItem(yi);return e?Date.now()-Number(e)>30*6e4?(localStorage.removeItem(yi),!1):!0:!1}catch{return!1}}function un(){try{localStorage.removeItem(yi)}catch{}}function tb(e){try{const t=localStorage.getItem(jo);return t?Number(t)>=e:!1}catch{return!1}}function Ss(e,t){var a,u,c;const n=(e??"").trim(),i=(a=t.mainSessionKey)==null?void 0:a.trim();if(!i)return n;if(!n)return i;const s=((u=t.mainKey)==null?void 0:u.trim())||"main",o=(c=t.defaultAgentId)==null?void 0:c.trim();return n==="main"||n===s||o&&(n===`agent:${o}:main`||n===`agent:${o}:${s}`)?i:n}function nb(e,t){if(!(t!=null&&t.mainSessionKey))return;const n=Ss(e.sessionKey,t),i=Ss(e.settings.sessionKey,t),s=Ss(e.settings.lastActiveSessionKey,t),o=n||i||e.sessionKey,r={...e.settings,sessionKey:i||o,lastActiveSessionKey:s||o},a=r.sessionKey!==e.settings.sessionKey||r.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),a&&Ge(e,r)}function Ce(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 Dv({url:e.settings.gatewayUrl,token:t?void 0:e.settings.token.trim()?e.settings.token:void 0,password:t?void 0:e.password.trim()?e.password:void 0,clientName:i,mode:"webchat",role:t?"public":void 0,scopes:t?[]:void 0,onHello:o=>{var r;if(e.connected=!0,e.lastError=null,e.hello=o,t){Ha(e,o),Ys(e),(((r=e.publicChatConfig)==null?void 0:r.auth)??"anonymous")==="anonymous"&&cb(e);return}li()&&($o(),e.uninstallDone=!1),Ha(e,o),e.handleAccessCheck(),Zv(e).then(()=>{fu(e)}),Ys(e),Mv(e),(e.chatPage||e.setup)&&ob(e),fo(e,{quiet:!0}),ho(e,{quiet:!0}),wn(e).then(()=>{e.initWorkspaceSelection()}),e.startEmbeddingPoll(),(e.setup||e.chatPage)&&Le(e),e.setup&&(rb(e),ab(e),lb(e)),ri(e)},onClose:({code:o,reason:r})=>{e.connected=!1,o!==1012&&(e.lastError=`disconnected (${o}): ${r||"no reason"}`)},onEvent:o=>ib(e,o),onGap:({expected:o,received:r})=>{console.warn(`[gateway] event gap: expected seq ${o}, got ${r}`),ri(e)}}),e.client.start()}function ib(e,t){try{sb(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function sb(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;Hd(e,t.payload);return}if(t.event==="chat"){const i=t.payload;i!=null&&i.sessionKey&&oc(e,i.sessionKey);const s=kl(e,i);if((s==="final"||s==="error"||s==="aborted")&&(so(e),Ih(e)),s==="final"){const o=e,r=Math.max((((n=o.chatMessages)==null?void 0:n.length)??0)+10,Pe);Me(o,{limit:r})}return}if(t.event==="suggestions"){const i=t.payload;(i==null?void 0:i.sessionKey)===e.sessionKey&&Array.isArray(i.suggestions)&&i.suggestions.length>0&&(e.chatSuggestion=i.suggestions[0]);return}if(t.event==="presence"){const i=t.payload;i!=null&&i.presence&&Array.isArray(i.presence)&&(e.presenceEntries=i.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"&&e.tab==="cron"&&xo(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&ho(e,{quiet:!0}),t.event==="exec.approval.requested"){const i=Ov(t.payload);if(i){e.execApprovalQueue=Fv(e.execApprovalQueue,i),e.execApprovalError=null;const s=Math.max(0,i.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=za(e.execApprovalQueue,i.id)},s)}return}if(t.event==="browser.screencast.frame"){qv(e,t.payload);return}if(t.event==="browser.handoff"){Vv(e,t.payload),e.browserPage||(window.location.href="/browser");return}if(t.event==="browser.handoff.resolved"){Gv(e);return}if(t.event==="exec.approval.resolved"){const i=Bv(t.payload);i&&(e.execApprovalQueue=za(e.execApprovalQueue,i.id));return}if(t.event==="update.progress"){Xv(e,t.payload);return}}function Ha(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&&nb(e,n.sessionDefaults)}async function ob(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 rb(e){if(!(!e.client||!e.connected))try{e.apiKeyProviders=await Xs(e.client)}catch{}}async function ab(e){if(!(!e.client||!e.connected))try{e.tailscaleStatus=await e.client.request("tailscale.status")}catch{}}async function lb(e){if(!(!e.client||!e.connected))try{e.wifiStatus=await e.client.request("wifi.status")}catch{}}const qa="taskmaster_public_id";function gu(e=30){var s;const t=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith(`${qa}=`));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=`${qa}=${n}; path=/; expires=${i}; SameSite=Lax`,n}async function cb(e){var n,i;if(!e.client||!e.connected)return;const t=gu((n=e.publicChatConfig)==null?void 0:n.cookieTtlDays);try{const s=(i=e.publicChatConfig)==null?void 0:i.accountId,o=await e.client.request("public.session",{cookieId:t,accountId:s});o!=null&&o.sessionKey&&(e.publicChatSessionKey=o.sessionKey,e.sessionKey=o.sessionKey,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready",Me(e))}catch(s){console.error("[public-chat] failed to resolve anonymous session:",s),e.lastError="Failed to start chat session"}}let Se=!1,de=null,Dt="",vi="";function mu(e){return e.replace(/[\s\-()]/g,"")}function yu(){Se=!1,de=null,Dt="",vi=""}async function ub(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){de=n instanceof Error?n.message:"Failed to start session",e.requestUpdate()}}async function Va(e){if(!e.client||Se)return;const t=mu(Dt);if(!t){de="Please enter your phone number",e.requestUpdate();return}Se=!0,de=null,e.requestUpdate();try{const n=await e.client.request("public.otp.request",{phone:t,name:vi.trim()||void 0});n!=null&&n.ok?e.onAuthStepChange("otp"):de=(n==null?void 0:n.error)??"Failed to send verification code"}catch(n){de=n instanceof Error?n.message:"Failed to send verification code"}finally{Se=!1,e.requestUpdate()}}async function Ga(e,t){if(!(!e.client||Se)){if(!t.trim()){de="Please enter the verification code",e.requestUpdate();return}Se=!0,de=null,e.requestUpdate();try{const n=await e.client.request("public.otp.verify",{phone:mu(Dt),code:t.trim(),accountId:e.accountId});n!=null&&n.ok&&n.sessionKey?(yu(),e.onAuthenticated(n.sessionKey)):de=(n==null?void 0:n.error)??"Invalid verification code"}catch(n){de=n instanceof Error?n.message:"Verification failed"}finally{Se=!1,e.requestUpdate()}}}function xs(e){return k}function Qa(e){return p`
3340
+ <div class="public-auth__form">
3341
+ <label class="field public-auth__field">
3342
+ <span>Your name (optional)</span>
3343
+ <input
3344
+ type="text"
3345
+ .value=${vi}
3346
+ @input=${t=>{vi=t.target.value}}
3347
+ placeholder="Name"
3348
+ />
3349
+ </label>
3350
+ <label class="field public-auth__field">
3351
+ <span>WhatsApp number</span>
3352
+ <input
3353
+ type="tel"
3354
+ .value=${Dt}
3355
+ @input=${t=>{Dt=t.target.value}}
3356
+ @keydown=${t=>{t.key==="Enter"&&(t.preventDefault(),Va(e))}}
3357
+ placeholder="+44 7123 456789"
3358
+ required
3359
+ />
3360
+ </label>
3361
+ ${de?p`<div class="public-auth__error">${de}</div>`:k}
3362
+ <button
3363
+ class="btn primary public-auth__btn"
3364
+ ?disabled=${Se}
3365
+ @click=${()=>{Va(e)}}
3366
+ >
3367
+ ${Se?"Sending...":"Send verification code"}
3368
+ </button>
3369
+ </div>
3370
+ `}function Ya(e){let t="";return p`
3371
+ <div class="public-auth__form">
3372
+ <p class="public-auth__hint">
3373
+ We sent a verification code to <strong>${Dt}</strong> via WhatsApp.
3374
+ </p>
3375
+ <label class="field public-auth__field">
3376
+ <span>Verification code</span>
3377
+ <input
3378
+ type="text"
3379
+ inputmode="numeric"
3380
+ maxlength="6"
3381
+ @input=${n=>{t=n.target.value}}
3382
+ @keydown=${n=>{n.key==="Enter"&&(n.preventDefault(),Ga(e,t))}}
3383
+ placeholder="123456"
3384
+ required
3385
+ />
3386
+ </label>
3387
+ ${de?p`<div class="public-auth__error">${de}</div>`:k}
3388
+ <button
3389
+ class="btn primary public-auth__btn"
3390
+ ?disabled=${Se}
3391
+ @click=${()=>{Ga(e,t)}}
3392
+ >
3393
+ ${Se?"Verifying...":"Verify"}
3394
+ </button>
3395
+ <button
3396
+ class="btn public-auth__btn public-auth__btn--link"
3397
+ @click=${()=>{de=null,e.onAuthStepChange("phone")}}
3398
+ >
3399
+ Use a different number
3400
+ </button>
3401
+ </div>
3402
+ `}function db(e){const{authMode:t,authStep:n}=e;return t==="anonymous"?p`
3403
+ <div class="setup-container">
3404
+ <div class="setup-card">
3405
+ <div class="setup-spinner"></div>
3406
+ <p>Starting chat...</p>
3407
+ </div>
3408
+ </div>
3409
+ `:t==="verified"?p`
3410
+ <div class="setup-container">
3411
+ <div class="public-auth">
3412
+ ${xs()}
3413
+ <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
3414
+ <p class="public-auth__subtitle">Verify your WhatsApp number to get started.</p>
3415
+ ${n==="otp"?Ya(e):Qa(e)}
3416
+ </div>
3417
+ </div>
3418
+ `:n==="phone"||n==="otp"?p`
3419
+ <div class="setup-container">
3420
+ <div class="public-auth">
3421
+ ${xs()}
3422
+ <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
3423
+ <p class="public-auth__subtitle">Verify your WhatsApp number to continue your conversation across devices.</p>
3424
+ ${n==="otp"?Ya(e):Qa(e)}
3425
+ </div>
3426
+ </div>
3427
+ `:p`
3428
+ <div class="setup-container">
3429
+ <div class="public-auth">
3430
+ ${xs()}
3431
+ <h2 class="public-auth__title">Chat with ${e.assistantName}</h2>
3432
+ <p class="public-auth__subtitle">How would you like to get started?</p>
3433
+ <div class="public-auth__choices">
3434
+ <button
3435
+ class="btn primary public-auth__btn"
3436
+ @click=${()=>{ub(e)}}
3437
+ >
3438
+ Chat now
3439
+ </button>
3440
+ <button
3441
+ class="btn public-auth__btn"
3442
+ @click=${()=>{yu(),e.onAuthStepChange("phone")}}
3443
+ >
3444
+ Verify with WhatsApp
3445
+ </button>
3446
+ </div>
3447
+ <p class="public-auth__hint">
3448
+ Verifying links your conversation with WhatsApp for seamless cross-device access.
3449
+ </p>
3450
+ </div>
3451
+ </div>
3452
+ `}const Ho="taskmaster-access-session",vu={checked:!1,hasPins:!1,hasMasterPin:!1,authenticated:!1,workspace:null,master:!1,accounts:[],error:null,busy:!1};function bu(){try{return localStorage.getItem(Ho)}catch{return null}}function wu(e){try{localStorage.setItem(Ho,e)}catch{}}function pb(){try{localStorage.removeItem(Ho)}catch{}}async function Xa(e){if(e.client)try{const t=bu(),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 hb(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?(wu(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 fb(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?(wu(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 gb(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 mb(e){const t=bu();if(e.client&&t)try{await e.client.request("access.logout",{token:t})}catch{}pb(),e.accessState={...vu,checked:!0,hasPins:!0,hasMasterPin:e.accessState.hasMasterPin,accounts:e.accessState.accounts}}function yb(e,t="admin"){var s;if(!e)return[];const n=e.bindings;if(!Array.isArray(n))return[];const i=[];for(const o of n){if(!o||typeof o!="object"||o.agentId!==t&&o.agentId!=="management")continue;const r=o.match;if(!r||typeof r!="object"||(r.channel??"").toLowerCase()!=="whatsapp")continue;const u=r.peer;if(!u||typeof u!="object"||u.kind!=="dm")continue;const c=u.id??"";c&&i.push({phone:c,paired:((s=o.meta)==null?void 0:s.paired)===!0})}return i.sort((o,r)=>o.paired&&!r.paired?-1:!o.paired&&r.paired?1:0),i}function ku(e,t,n="admin",i){const s=c=>c===n||c==="management",o=new Map,r=new Map;for(const c of e){if(!c||typeof c!="object"||!s(c.agentId))continue;const l=c.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="whatsapp")continue;const h=l.peer;if(!h||typeof h!="object"||h.kind!=="dm")continue;const v=h.id??"";v&&(c.meta&&o.set(v,c.meta),l.accountId&&r.set(v,l.accountId))}const a=e.filter(c=>{if(!c||typeof c!="object"||!s(c.agentId))return!0;const l=c.match;if(!l||typeof l!="object"||(l.channel??"").toLowerCase()!=="whatsapp")return!0;const h=l.peer;return!h||typeof h!="object"?!0:h.kind!=="dm"}),u=t.map(c=>{const l=i??r.get(c.phone),d={channel:"whatsapp",peer:{kind:"dm",id:c.phone}};l&&(d.accountId=l);const h={agentId:n,match:d},v=o.get(c.phone);return v?h.meta=v:c.paired&&(h.meta={paired:!0}),h});return[...a,...u]}async function Pi(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=Ye(s??{}),e.adminPhones=yb(s,n),e.configFormDirty=!1}catch(i){e.adminsError=String(i)}finally{e.adminsLoading=!1}}async function Su(e,t,n,i){var r,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n;let o=t.replace(/[\s\-\(\)]/g,"");if(!o){e.adminsError="Phone number is required";return}if(o.startsWith("+")||(o="+"+o),!/^\+[1-9]\d{6,14}$/.test(o)){e.adminsError="Invalid phone number. Use international format (e.g., +44 7504 472444)";return}if(e.adminPhones.some(u=>u.phone===o)){e.adminsError="Phone number already exists";return}e.adminsSaving=!0,e.adminsError=null;try{const u=Ye(e.configForm??((r=e.configSnapshot)==null?void 0:r.config)??{}),c=u.bindings??[],l=[...e.adminPhones,{phone:o}],d=ku(c,l,s,i);xl(u,["bindings"],d);const h=(a=e.configSnapshot)==null?void 0:a.hash;if(!h){e.adminsError="Config hash missing; reload and retry.";return}const v=ct(u);await e.client.request("config.set",{raw:v,baseHash:h}),await Pi(e,n)}catch(u){e.adminsError=String(u)}finally{e.adminsSaving=!1}}async function xu(e,t,n,i){var r,a;if(!e.client||!e.connected)return;if(!n){e.adminsError="No business selected.";return}if(e.adminsSaving)return;const s=n,o=e.adminPhones.find(u=>u.phone===t);if(o!=null&&o.paired){e.adminsError="Cannot remove the paired phone. Unlink WhatsApp first.";return}e.adminsSaving=!0,e.adminsError=null;try{const u=Ye(e.configForm??((r=e.configSnapshot)==null?void 0:r.config)??{}),c=u.bindings??[],l=e.adminPhones.filter(f=>f.phone!==t),d=ku(c,l,s,i);xl(u,["bindings"],d);const h=(a=e.configSnapshot)==null?void 0:a.hash;if(!h){e.adminsError="Config hash missing; reload and retry.";return}const v=ct(u);await e.client.request("config.set",{raw:v,baseHash:h}),await Pi(e,n)}catch(u){e.adminsError=String(u)}finally{e.adminsSaving=!1}}const vb=Object.freeze(Object.defineProperty({__proto__:null,addAdmin:Su,loadAdmins:Pi,removeAdmin:xu},Symbol.toStringTag,{value:"Module"}));async function mt(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 Au(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 mt(e,i)}catch(r){e.contactsError=String(r)}finally{e.contactsSaving=!1}}async function $u(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 mt(e,n)}catch(i){e.contactsError=String(i)}finally{e.contactsSaving=!1}}}async function Eu(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 mt(e,s)}catch(o){e.contactsError=String(o)}finally{e.contactsSaving=!1}}}async function Tu(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 mt(e,i)}catch(s){e.contactsError=String(s)}finally{e.contactsSaving=!1}}}const bb=Object.freeze(Object.defineProperty({__proto__:null,addContact:Au,deleteContact:$u,deleteContactField:Tu,loadContacts:mt,setContactField:Eu},Symbol.toStringTag,{value:"Module"}));function Jt(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0}}}function wb(e){if(e.workspaces.length!==0)return{workspaces:e.workspaces,selectedWorkspace:e.selectedWorkspace,onWorkspaceSelect:t=>e.handleWorkspaceSelect(t),onAddAccount:()=>{e.addingWorkspace=!0},hasPins:e.accessState.hasPins,isMaster:e.accessState.master,onLogout:()=>e.handleLogout(),auditCount:e.auditEntries.length,onAuditClick:()=>{e.auditModalOpen=!0}}}function kb(e){const t=oe(e);if(!t)return;const n=t.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return n==null?void 0:n.id}function Sb(e){const t=oe(e);return(t==null?void 0:t.whatsappAccountId)??void 0}function xb(e){var i;const t=oe(e);if(!t)return;const n=t.agents.find(s=>s.id.endsWith("-admin")||s.id==="admin");return(n==null?void 0:n.id)??((i=t.agents[0])==null?void 0:i.id)}function Ab(e){return e.selectedWorkspace??void 0}function oe(e){return e.selectedWorkspace?e.workspaces.find(t=>t.name===e.selectedWorkspace)??null:null}const $b=/^data:/i,Eb=/^https?:\/\//i;function Za(e){var a,u;const t=((a=e.agentsList)==null?void 0:a.agents)??[],n=ul(e.sessionKey),i=(n==null?void 0:n.agentId)??((u=e.agentsList)==null?void 0:u.defaultId)??"main",s=t.find(c=>c.id===i),o=s==null?void 0:s.identity,r=(o==null?void 0:o.avatarUrl)??(o==null?void 0:o.avatar);if(r)return $b.test(r)||Eb.test(r)?r:o==null?void 0:o.avatarUrl}function Tb(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 Cb(e){var r;if(!e)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const t=(r=e.channelAccounts)==null?void 0:r.imessage;if(!t||t.length===0)return{configured:!1,running:!1,connected:!1,lastError:null,selfChatMode:!1,dmPolicy:null,cliPath:null};const n=t[0],i=n.running??!1,s=n.probe,o=s!=null?s.ok===!0:i;return{configured:n.configured??!1,running:i,connected:o,lastError:n.lastError??null,selfChatMode:n.mode==="self-chat"||!!n.selfChatMode,dmPolicy:n.dmPolicy??null,cliPath:n.cliPath??null}}function _b(e){var r;const t=(r=e.configSnapshot)==null?void 0:r.config;if(!t)return null;const n=t.bindings;if(!Array.isArray(n))return null;const i=n.find(a=>{var u,c;return((u=a.match)==null?void 0:u.channel)==="imessage"&&((c=a.meta)==null?void 0:c.imessageOwner)});if(!i)return null;const s=i.agentId;for(const a of e.workspaces)if(a.agents.some(u=>u.id===s))return a.name;if(s==="admin"||s==="public"){const a=e.workspaces.find(u=>u.isDefault);return(a==null?void 0:a.name)??null}const o=s.replace(/-(admin|public)$/,"");if(o!==s){const a=e.workspaces.find(u=>u.name===o);return(a==null?void 0:a.name)??null}return null}function Mb(e){var t,n,i,s,o,r,a,u,c;if(e.embeddingDownloading&&!e.publicChat)return p`
3453
+ <div class="setup-container">
3454
+ <div class="setup-card" style="text-align:center; max-width:420px;">
3455
+ <div class="setup-spinner"></div>
3456
+ <h2 style="margin:16px 0 8px; font-size:1.1rem; font-weight:600; color:#fff;">Downloading embedding model</h2>
3457
+ <p style="margin:0; color:rgba(255,255,255,0.6); font-size:0.85rem; line-height:1.4;">
3458
+ This is a one-time download after install or upgrade.
3459
+ It may take a few minutes depending on your connection.
3460
+ </p>
3461
+ <p style="margin:12px 0 0; color:rgba(255,255,255,0.4); font-size:0.75rem;">
3462
+ Memory search will be available when the download completes.
3463
+ </p>
3464
+ </div>
3465
+ </div>
3466
+ `;if(e.publicChat)return e.connected?e.publicChatAuthenticated?_v({connected:e.connected,sessionKey:e.sessionKey,loading:e.chatLoading,sending:e.chatSending,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,assistantAvatarUrl:e.chatAvatarUrl??Za(e)??null,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,canAbort:!!e.chatRunId,disabledReason:e.connected?null:"Disconnected.",error:e.lastError,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,suggestion:e.chatSuggestion,onSuggestionClick:l=>{e.chatMessage=l,e.chatSuggestion=null,e.handleSendChat()},onRefresh:()=>(e.resetToolStream(),ie(async()=>{const{loadChatHistory:l}=await Promise.resolve().then(()=>ii);return{loadChatHistory:l}},void 0,import.meta.url).then(({loadChatHistory:l})=>{l(e)})),onDraftChange:l=>e.chatMessage=l,attachments:e.chatAttachments,onAttachmentsChange:l=>e.chatAttachments=l,onSend:()=>e.handleSendChat(),onAbort:()=>{e.handleAbortChat()},onQueueRemove:l=>e.removeQueuedMessage(l),onChatScroll:l=>e.handleChatScroll(l),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()}}):db({authMode:e.publicChatConfig.auth??"anonymous",authStep:e.publicChatAuthStep,connected:e.connected,client:e.client,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,accountId:e.publicChatConfig.accountId,cookieTtlDays:e.publicChatConfig.cookieTtlDays,onAuthenticated:l=>{e.publicChatSessionKey=l,e.sessionKey=l,e.publicChatAuthenticated=!0,e.publicChatAuthStep="ready",ie(async()=>{const{loadChatHistory:d}=await Promise.resolve().then(()=>ii);return{loadChatHistory:d}},void 0,import.meta.url).then(({loadChatHistory:d})=>{d(e)})},onAuthStepChange:l=>{e.publicChatAuthStep=l},requestUpdate:()=>{e.requestUpdate()}}):p`
3467
+ <div class="setup-container">
3468
+ <div class="setup-card">
3469
+ <div class="setup-spinner"></div>
3470
+ <p>Connecting...</p>
3471
+ </div>
3472
+ </div>
3473
+ `;if(e.connected&&e.accessState.checked){const{accessState:l}=e;if(l.hasPins&&!l.authenticated)return Wa({show:!0,isFirstTime:!1,accounts:l.accounts,error:l.error,busy:l.busy,onSubmit:(d,h)=>{h!=null&&e.handlePinSubmit(d,h)},changePinMode:e.loginChangePinMode,onToggleChangePinMode:()=>e.toggleChangePinMode(),changePinBusy:e.changePinBusy,changePinError:e.changePinError,changePinSuccess:e.changePinSuccess,onChangePin:(d,h,v)=>e.handleChangePin(d,h,v)});if(!l.hasMasterPin&&!l.authenticated&&e.setup)return Wa({show:!0,isFirstTime:!0,accounts:[],error:l.error,busy:l.busy,onSubmit:d=>e.handleSetMasterPin(d)});if(!l.hasMasterPin&&!l.authenticated&&!e.setup)return window.location.href="/setup",k}if(e.setup){const l=Tb(e.channelsSnapshot),d=((n=(t=e.channelsSnapshot)==null?void 0:t.channelAccounts)==null?void 0:n.whatsapp)??[],h=Cb(e.channelsSnapshot),v=_b(e);return hf({connected:e.connected,serverPlatform:((s=(i=e.hello)==null?void 0:i.server)==null?void 0:s.platform)??null,assistantName:e.assistantName,currentStep:e.setupStep,licenseKey:e.licenseKey,licenseBusy:e.licenseBusy,licenseValid:e.licenseValid,licenseMessage:e.licenseMessage,licenseTier:e.licenseTier,licenseDeviceId:e.licenseDeviceId,licenseStoredKey:e.licenseStoredKey,onLicenseKeyChange:f=>e.handleLicenseKeyChange(f),onLicenseActivate:()=>e.handleLicenseActivate(),onLicenseRemove:async()=>{await e.handleLicenseRemove(),e.licenseRemoveConfirm=!1},licenseRemoveConfirm:e.licenseRemoveConfirm,onLicenseRemoveConfirm:()=>{e.licenseRemoveConfirm=!0},onLicenseRemoveCancel:()=>{e.licenseRemoveConfirm=!1},authConnected:e.authConnected,authBusy:e.authBusy,authMessage:e.authMessage,authUrl:e.authUrl,authCodeInput:e.authCodeInput,authExpiresIn:e.authExpiresIn,whatsappBusy:e.whatsappBusy,whatsappLoginMessage:e.whatsappLoginMessage,whatsappLoginQrDataUrl:e.whatsappLoginQrDataUrl,whatsappLoginConnected:e.whatsappLoginConnected,whatsappChannelStatus:l,whatsappAccounts:d,whatsappActiveQrAccountId:e.whatsappActiveQrAccountId,whatsappAccountSaving:e.whatsappAccountSaving,gatewayHealthy:e.gatewayHealthy,gatewayHealthLoading:e.gatewayHealthLoading,gatewayHealthMessage:e.gatewayHealthMessage,gatewayRestartBusy:e.gatewayRestartBusy,updateAvailable:e.updateAvailable,currentVersion:e.currentVersion,latestVersion:e.latestVersion,updateChecking:e.updateChecking,updateRunning:e.updateRunning,updateMessage:e.updateMessage,updateProgressSteps:e.updateProgressSteps,updateLastResult:e.updateLastResult,onUpdateCheck:()=>e.handleUpdateCheck(),onUpdateRun:()=>e.handleUpdateRun(),onUpdateDismissResult:()=>e.handleUpdateDismissResult(),uninstallConfirm:e.uninstallConfirm,uninstallBusy:e.uninstallBusy,uninstallDone:e.uninstallDone,uninstallError:e.uninstallError,uninstallConfirmText:e.uninstallConfirmText,onUninstallConfirm:()=>e.handleUninstallConfirm(),onUninstallCancel:()=>e.handleUninstallCancel(),onUninstallConfirmTextChange:f=>e.handleUninstallConfirmTextChange(f),onUninstallRun:()=>e.handleUninstallRun(),onUninstallDismiss:()=>e.handleUninstallDismiss(),onStartAuth:()=>e.handleAuthStart(),onSubmitAuthCode:f=>e.handleAuthSubmitCode(f),onAuthCodeChange:f=>e.handleAuthCodeChange(f),onSkipToWhatsApp:()=>e.handleSkipToWhatsApp(),onWhatsAppRelink:async f=>{await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await G(e,!0),e.requestUpdate())},onWhatsAppUnlink:async f=>{await e.handleWhatsAppLogout(f)},onWhatsAppReset:async f=>{await e.handleWhatsAppLogout(f),await e.handleWhatsAppStart(!0,f),e.whatsappLoginQrDataUrl&&(await e.handleWhatsAppWait(f),await G(e,!0),e.requestUpdate())},onRefreshStatus:async()=>{await G(e,!0),await e.handleGatewayHealthCheck()},onWhatsAppBack:()=>{e.whatsappLoginQrDataUrl=null,e.whatsappLoginMessage=null,e.whatsappLoginConnected=null,e.whatsappActiveQrAccountId=null,e.requestUpdate(),G(e,!0)},onRestartGateway:()=>e.handleGatewayRestart(),onRemoveWhatsAppAccount:f=>e.handleRemoveWhatsAppAccount(f),workspaces:e.workspaces,workspacesLoading:e.workspacesLoading,workspacesError:e.workspacesError,addingWorkspace:e.addingWorkspace,newWorkspaceName:e.newWorkspaceName,newWorkspacePath:e.newWorkspacePath,workspaceSaving:e.workspaceSaving,workspaceRemoveConfirm:e.workspaceRemoveConfirm,newWorkspacePin:e.newWorkspacePin,onSetNewWorkspacePin:f=>{e.newWorkspacePin=f},onWorkspaceCreate:async(f,b)=>{const S=e.newWorkspacePin;await e.handleWorkspaceCreate(f,b),S.match(/^\d{4,6}$/)&&(await gb(e,f,S),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=oe(e),b=f==null?void 0:f.whatsappAccountId,S=b?d.find(A=>A.accountId===b):d[0];return(S==null?void 0:S.dmPolicy)??null})(),onWhatsAppDmToggle:async()=>{var C;const f=oe(e),b=f==null?void 0:f.whatsappAccountId,S=b?d.find(M=>M.accountId===b):d[0];if(!S)return;const $=S.dmPolicy!=null&&S.dmPolicy!=="disabled"?"disabled":"open",T=$==="open"?{dmPolicy:$,allowFrom:["*"]}:{dmPolicy:$};try{const M=await e.client.request("config.get"),R=M.config,B=(C=R==null?void 0:R.channels)==null?void 0:C.whatsapp,me=((B==null?void 0:B.accounts)??{})[S.accountId]?{channels:{whatsapp:{accounts:{[S.accountId]:T}}}}:{channels:{whatsapp:T}};await e.client.request("config.patch",{raw:JSON.stringify(me),baseHash:M.hash,note:`WhatsApp DM policy → ${$}`,skipRestart:!0}),await G(e,!1)}catch(M){console.error("DM toggle failed:",M)}},whatsappModel:(()=>{var C,M;const f=oe(e);if(!f)return null;const b=f.agents.find(R=>R.id.endsWith("-public")||R.id==="public");if(!b)return null;const S=(C=e.configSnapshot)==null?void 0:C.config,A=(M=S==null?void 0:S.agents)==null?void 0:M.list;if(!Array.isArray(A))return null;const $=A.find(R=>R.id===b.id);if(!($!=null&&$.model))return null;const T=typeof $.model=="string"?$.model:$.model.primary;return(T==null?void 0:T.trim())||null})(),whatsappModelCatalog:e.chatModelCatalog??[],onWhatsAppModelChange:async f=>{const b=oe(e);if(!b)return;const S=b.agents.find(A=>A.id.endsWith("-public")||A.id==="public");if(S)try{const A=await e.client.request("config.get"),$=A.config,T=($==null?void 0:$.agents)??{},C=Array.isArray(T.list)?[...T.list]:[],M=C.findIndex(B=>B.id===S.id);if(f)M>=0?C[M]={...C[M],model:f}:C.push({id:S.id,model:f});else if(M>=0){const{model:B,...ee}=C[M];Object.keys(ee).length<=1?C.splice(M,1):C[M]=ee}const R=C.length>0?{agents:{list:C}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(R),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 T,C,M;const f=oe(e);if(!f)return null;const b=f.agents.find(R=>R.id.endsWith("-public")||R.id==="public");if(!b)return null;const S=(T=e.configSnapshot)==null?void 0:T.config,A=(C=S==null?void 0:S.agents)==null?void 0:C.list;if(!Array.isArray(A))return null;const $=A.find(R=>R.id===b.id);return((M=$==null?void 0:$.thinkingLevel)==null?void 0:M.trim())||null})(),onWhatsAppThinkingChange:async f=>{const b=oe(e);if(!b)return;const S=b.agents.find(A=>A.id.endsWith("-public")||A.id==="public");if(S)try{const A=await e.client.request("config.get"),$=A.config,T=($==null?void 0:$.agents)??{},C=Array.isArray(T.list)?[...T.list]:[],M=C.findIndex(ee=>ee.id===S.id),R=f==="off"?void 0:f;if(R)M>=0?C[M]={...C[M],thinkingLevel:R}:C.push({id:S.id,thinkingLevel:R});else if(M>=0){const{thinkingLevel:ee,...me}=C[M];Object.keys(me).length<=1?C.splice(M,1):C[M]=me}const B=C.length>0?{agents:{list:C}}:{agents:{list:null}};await e.client.request("config.patch",{raw:JSON.stringify(B),baseHash:A.hash,note:`Public agent thinking → ${R||"default"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch(A){console.error("Thinking change failed:",A)}},whatsappGroupPolicy:(()=>{var M,R;const f=(M=e.configSnapshot)==null?void 0:M.config,b=(R=f==null?void 0:f.channels)==null?void 0:R.whatsapp,S=oe(e),A=S==null?void 0:S.whatsappAccountId,$=(b==null?void 0:b.accounts)??{},T=A?$[A]:void 0;return(T==null?void 0:T.groupPolicy)??(b==null?void 0:b.groupPolicy)??"allowlist"})(),whatsappGroupRequireMention:(()=>{var R,B;const f=(R=e.configSnapshot)==null?void 0:R.config,b=(B=f==null?void 0:f.channels)==null?void 0:B.whatsapp,S=oe(e),A=S==null?void 0:S.whatsappAccountId,$=(b==null?void 0:b.accounts)??{},T=A?$[A]:void 0,M=((T==null?void 0:T.groups)??(b==null?void 0:b.groups)??{})["*"];return(M==null?void 0:M.requireMention)!==!1})(),onWhatsAppGroupToggle:async()=>{var S;const f=oe(e),b=f==null?void 0:f.whatsappAccountId;try{const A=await e.client.request("config.get"),$=A.config,T=((S=$==null?void 0:$.channels)==null?void 0:S.whatsapp)??{},C=T.accounts??{},M=b?C[b]:void 0,R=(M==null?void 0:M.groupPolicy)??T.groupPolicy??"allowlist",B=R==="disabled"||R==="allowlist",ee=B?"open":"disabled",me=B?{"*":{}}:void 0,Ke={groupPolicy:ee};me&&(Ke.groups=me);const Z=M?{channels:{whatsapp:{accounts:{[b]:Ke}}}}:{channels:{whatsapp:Ke}};await e.client.request("config.patch",{raw:JSON.stringify(Z),baseHash:A.hash,note:`WhatsApp groups → ${ee}`,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=oe(e),S=b==null?void 0:b.whatsappAccountId;try{const $=await e.client.request("config.get"),T=$.config,M=(((A=T==null?void 0:T.channels)==null?void 0:A.whatsapp)??{}).accounts??{},R=S?M[S]:void 0,B={"*":{requireMention:f}},ee=R?{channels:{whatsapp:{accounts:{[S]:{groups:B}}}}}:{channels:{whatsapp:{groups:B}}};await e.client.request("config.patch",{raw:JSON.stringify(ee),baseHash:$.hash,note:`WhatsApp group mention → ${f?"when mentioned":"always"}`,skipRestart:!0}),e.configSnapshot=await e.client.request("config.get")}catch($){console.error("Group mention change failed:",$)}},whatsappSettingsOpen:e.whatsappSettingsOpen??!1,onWhatsAppSettingsOpen:()=>{e.whatsappSettingsOpen=!0},onWhatsAppSettingsClose:()=>{e.whatsappSettingsOpen=!1},imessageConfigured:h.configured,imessageRunning:h.running,imessageConnected:h.connected,imessageLastError:h.lastError,imessageSelfChatMode:h.selfChatMode,imessageCliPath:h.cliPath,imessageEnabling:e.imessageEnabling,imessageEnableConfirm:e.imessageEnableConfirm,imessageOwnerWorkspace:v,onIMessageEnable:()=>{e.imessageEnableConfirm=!0},onIMessageEnableConfirm:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,S=(b==null?void 0:b.bindings)??[],A=oe(e),$=A==null?void 0:A.agents.find(B=>B.id.endsWith("-admin")||B.id==="admin"),T=($==null?void 0:$.id)??"admin",C=S.filter(B=>{var ee;return((ee=B.match)==null?void 0:ee.channel)!=="imessage"}),M=[{agentId:T,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}],R=[...C,...M];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:R}),baseHash:f.hash,note:"Enable iMessage (self-chat) for "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Le(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},onIMessageEnableCancel:()=>{e.imessageEnableConfirm=!1},onIMessageProbe:async()=>{e.imessageEnabling=!0,e.requestUpdate();try{await G(e,!0)}finally{e.imessageEnabling=!1}},onIMessageDisconnect:async()=>{e.imessageEnabling=!0;try{const f=await e.client.request("config.get"),b=f.config,A=((b==null?void 0:b.bindings)??[]).filter($=>{var T;return((T=$.match)==null?void 0:T.channel)!=="imessage"});await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!1,dmPolicy:"disabled"}},bindings:A}),baseHash:f.hash,note:"Disconnect iMessage"}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Le(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,S=(b==null?void 0:b.bindings)??[],A=oe(e),$=A==null?void 0:A.agents.find(R=>R.id.endsWith("-admin")||R.id==="admin"),T=($==null?void 0:$.id)??"admin",C=S.filter(R=>{var B;return((B=R.match)==null?void 0:B.channel)!=="imessage"}),M=[{agentId:T,match:{channel:"imessage",peer:{kind:"dm",id:"__self__"}},meta:{imessageOwner:!0}}];await e.client.request("config.patch",{raw:JSON.stringify({channels:{imessage:{selfChatMode:!0,dmPolicy:"disabled",allowFrom:["*"]}},bindings:[...C,...M]}),baseHash:f.hash,note:"Reassign iMessage to "+((A==null?void 0:A.name)??"default")}),e.imessageEnableConfirm=!1,setTimeout(()=>{Promise.all([G(e,!0),Le(e)]).then(()=>{e.imessageEnabling=!1})},3e3)}catch{e.imessageEnabling=!1}},infoModalOpen:e.infoModalOpen,onInfoModalOpen:f=>{e.infoModalOpen=f},onInfoModalClose:()=>{e.infoModalOpen=null},isMaster:e.accessState.master,apiKeyProviders:e.apiKeyProviders,apiKeyModalOpen:e.apiKeyModalOpen,apiKeyBusy:e.apiKeyBusy,apiKeyError:e.apiKeyError,apiKeySuccess:e.apiKeySuccess,apiKeySavingProvider:e.apiKeySavingProvider,onApiKeyModalOpen:()=>{e.apiKeyModalOpen=!0,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeyModalClose:()=>{e.apiKeyModalOpen=!1,e.apiKeyError=null,e.apiKeySuccess=null,e.apiKeySavingProvider=null},onApiKeySave:async(f,b)=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await ja(e.client,f,b);const S=`${f} key saved`;e.apiKeySuccess=S,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Xs(e.client)}catch{}f==="anthropic"&&await e.handleAuthStatusCheck(),setTimeout(()=>{e.apiKeySuccess===S&&(e.apiKeySuccess=null)},2500)}catch(S){e.apiKeyError=S instanceof Error?S.message:"Failed to save key",e.apiKeySavingProvider=null}finally{e.apiKeyBusy=!1}},onApiKeyRemove:async f=>{e.apiKeySavingProvider=f,e.apiKeyBusy=!0,e.apiKeyError=null,e.apiKeySuccess=null;try{await Qv(e.client,f);const b=`${f} key removed`;e.apiKeySuccess=b,e.apiKeySavingProvider=null;try{e.apiKeyProviders=await Xs(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}},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 ja(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(S=>S.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 S=e.selectedWorkspace??((A=e.workspaces[0])==null?void 0:A.name);S&&e.handleAccountPinSave(S,f,b)},publicChatEnabled:(()=>{var S;const f=(S=e.configSnapshot)==null?void 0:S.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,S=b==null?void 0:b.auth;return S==="verified"||S==="choice"?S:"anonymous"})(),publicChatBusy:e.publicChatToggleBusy,onPublicChatToggle:async()=>{var f;if(!e.publicChatToggleBusy){e.publicChatToggleBusy=!0;try{const b=await e.client.request("config.get"),S=b.config,A=((f=S==null?void 0:S.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"}`}),e.configSnapshot=await e.client.request("config.get")}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}`}),e.configSnapshot=await e.client.request("config.get")}catch(b){console.error("Public chat auth mode change failed:",b)}finally{e.publicChatToggleBusy=!1}}},tailscaleStatus:e.tailscaleStatus,tailscaleBusy:e.tailscaleBusy,tailscaleAuthUrl:e.tailscaleAuthUrl,tailscaleError:e.tailscaleError,tailscaleFunnelEnableUrl:e.tailscaleFunnelEnableUrl,onTailscaleEnable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleAuthUrl=null;try{const f=await e.client.request("tailscale.enable");if(f.authUrl){e.tailscaleAuthUrl=f.authUrl;const b=setInterval(async()=>{try{const S=await e.client.request("tailscale.status");e.tailscaleStatus=S,S.loggedIn&&(clearInterval(b),e.tailscaleAuthUrl=null,e.tailscaleBusy=!1)}catch{}},3e3);setTimeout(()=>{clearInterval(b),e.tailscaleBusy&&(e.tailscaleBusy=!1)},3e5)}else f.alreadyLoggedIn&&(e.tailscaleStatus=await e.client.request("tailscale.status")),e.tailscaleBusy=!1}catch(f){console.error("Tailscale enable failed:",f),e.tailscaleBusy=!1}}},onTailscaleFunnelEnable:async()=>{var f;if(!e.tailscaleBusy){e.tailscaleBusy=!0,e.tailscaleError=null,e.tailscaleFunnelEnableUrl=null;try{await e.client.request("tailscale.funnel.enable")}catch(b){console.error("Tailscale funnel enable failed:",b);const S=b;(f=S.payload)!=null&&f.enableUrl&&(e.tailscaleFunnelEnableUrl=S.payload.enableUrl),e.tailscaleError=S.message||"Failed to enable Funnel",e.tailscaleBusy=!1}}},onTailscaleFunnelDisable:async()=>{if(!e.tailscaleBusy){e.tailscaleBusy=!0;try{await e.client.request("tailscale.funnel.disable")}catch(f){console.error("Tailscale funnel disable failed:",f),e.tailscaleBusy=!1}}},wifiStatus:e.wifiStatus,wifiNetworks:e.wifiNetworks,wifiBusy:e.wifiBusy,wifiError:e.wifiError,wifiPassword:e.wifiPassword,wifiSelectedSsid:e.wifiSelectedSsid,onWifiScan:async()=>{if(!e.wifiBusy){e.wifiBusy=!0,e.wifiError=null;try{const f=await e.client.request("wifi.scan");e.wifiNetworks=f.networks}catch(f){console.error("WiFi scan failed:",f),e.wifiError=f.message||"Failed to scan networks"}finally{e.wifiBusy=!1}}},onWifiConnect:async()=>{if(!(e.wifiBusy||!e.wifiSelectedSsid)){e.wifiBusy=!0,e.wifiError=null;try{await e.client.request("wifi.connect",{ssid:e.wifiSelectedSsid,password:e.wifiPassword}),e.wifiPassword="",e.wifiSelectedSsid=null,e.wifiNetworks=[];const f=await e.client.request("wifi.status");e.wifiStatus=f}catch(f){console.error("WiFi connect failed:",f),e.wifiError=f.message||"Failed to connect"}finally{e.wifiBusy=!1}}},onWifiSelectSsid:f=>{e.wifiSelectedSsid=f,e.wifiPassword="",e.wifiError=null},onWifiPasswordChange:f=>{e.wifiPassword=f},wsProps:wb(e)})}if(e.filesPage){const l=xb(e);return Xh({connected:e.connected,wsProps:Jt(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,message:e.filesMessage,uploadBusy:e.filesUploadBusy,reindexBusy:e.filesReindexBusy,memoryStatus:e.filesMemoryStatus,onRefresh:()=>vn(e,l),onReindex:()=>lh(e,l),onSelectFile:d=>nh(e,d,l),onToggleSelectFile:d=>ih(e,d,l),onToggleDir:d=>ch(e,d),onUpload:(d,h)=>rh(e,d,h,l),onDownload:d=>ic(e,d,l),onBulkDownload:()=>sh(e,l),onDelete:d=>ah(e,d,l),onMove:(d,h)=>sc(e,d,h,l),onMoveToDir:(d,h)=>oh(e,d,h,l),searchQuery:e.filesSearchQuery,searchResults:e.filesSearchResults,searchLoading:e.filesSearchLoading,searchAgentId:e.filesSearchAgentId,agentIds:e.workspaceAgentIds??[],onSearch:d=>{const h=e.filesSearchAgentId??l;uh(e,d,h)},onSearchAgentChange:d=>{e.filesSearchAgentId=d},onSearchClear:()=>{dh(e)},onSearchQueryChange:d=>{e.filesSearchQuery=d}})}if(e.browserPage)return jh({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:()=>Wv(e),onStop:()=>Kv(e),onToggleInput:()=>jv(e),onToggleFullscreen:()=>Hv(e),onCompleteHandoff:()=>zv(e),onCanvasMouseDown:l=>{const h=l.target.getBoundingClientRect(),f=cn().translateCoordinates(l.clientX-h.left,l.clientY-h.top);ws(e,"mousePressed",f.x,f.y,l.button===2?"right":l.button===1?"middle":"left")},onCanvasMouseUp:l=>{const h=l.target.getBoundingClientRect(),f=cn().translateCoordinates(l.clientX-h.left,l.clientY-h.top);ws(e,"mouseReleased",f.x,f.y)},onCanvasMouseMove:l=>{const d=cn();if(d.shouldThrottleMouseMove())return;const v=l.target.getBoundingClientRect(),f=d.translateCoordinates(l.clientX-v.left,l.clientY-v.top);ws(e,"mouseMoved",f.x,f.y)},onCanvasKeyDown:l=>{let d=0;l.altKey&&(d|=1),l.ctrlKey&&(d|=2),l.metaKey&&(d|=4),l.shiftKey&&(d|=8),ks(e,"keyDown",l.key,{code:l.code,modifiers:d||void 0}),l.key.length===1&&ks(e,"char",l.key,{text:l.key})},onCanvasKeyUp:l=>{ks(e,"keyUp",l.key,{code:l.code})}});if(e.adminsPage){const l=kb(e),d=Sb(e);return gf({connected:e.connected,wsProps:Jt(e),loading:e.adminsLoading,saving:e.adminsSaving,phones:e.adminPhones,error:e.adminsError,newPhone:e.adminsNewPhone,onRefresh:()=>Pi(e,l),onAdd:h=>{Su(e,h,l,d).then(()=>{e.adminsError||(e.adminsNewPhone="")})},onRemove:h=>xu(e,h,l,d),onNewPhoneChange:h=>e.handleAdminsNewPhoneChange(h)})}if(e.contactsPage){const l=Ab(e);return bf({connected:e.connected,wsProps:Jt(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,onSearch:d=>e.contactsSearchQuery=d,onSearchSubmit:()=>mt(e,l),onAdd:(d,h)=>Au(e,d,h,l),onDelete:d=>$u(e,d,l),onSetField:(d,h,v)=>Eu(e,d,h,v,l),onDeleteField:(d,h)=>Tu(e,d,h,l),onToggleExpand:d=>{e.contactsEditingId=e.contactsEditingId===d?null:d},onShowAddForm:()=>e.contactsShowAddForm=!0,onCancelAddForm:()=>{e.contactsShowAddForm=!1,e.contactsNewPhone="",e.contactsNewName=""},onNewRecordPhoneChange:d=>e.handleContactsNewPhoneChange(d),onNewRecordNameChange:d=>e.handleContactsNewNameChange(d),onRefresh:()=>mt(e,l)})}if(e.chatPage){const l=e.connected?null:"Disconnected from gateway.",d=Za(e),h=e.chatAvatarUrl??d??null,v=(()=>{var S;const f=(S=e.configSnapshot)==null?void 0:S.config,b=f==null?void 0:f.publicChat;return(b==null?void 0:b.enabled)===!0})();return Zy({connected:e.connected,wsProps:Jt(e),publicChatEnabled:v,publicChatAccountId:e.selectedWorkspace??void 0,sessionKey:e.sessionKey,onSessionKeyChange:f=>{e.sessionKey=f,e.chatMessage="",e.chatAttachments=[],e.chatStream=null,e.chatInterimText=null,e.chatSuggestion=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:f,lastActiveSessionKey:f}),e.loadAssistantIdentity(),Me(e),Is(e)},thinkingLevel:e.chatThinkingLevel,showThinking:e.settings.chatShowThinking??!1,modelProvider:e.chatModelProvider,model:e.chatModel,modelCatalog:e.chatModelCatalog,onModelChange:f=>{const b=Math.max(e.chatMessages.length+10,Pe);In(e,e.sessionKey,{model:f}).then(()=>{Me(e,{limit:b})})},onThinkingLevelChange:f=>{const b=Math.max(e.chatMessages.length+10,Pe);In(e,e.sessionKey,{thinkingLevel:f==="off"?null:f}).then(()=>{Me(e,{limit:b})})},verboseLevel:e.chatVerboseLevel,fillerEnabled:e.chatFillerEnabled,suggestion:e.chatSuggestion,onSuggestionClick:f=>{e.chatMessage=f,e.chatSuggestion=null,e.handleSendChat()},onVerboseChange:f=>{const b=Math.max(e.chatMessages.length+10,Pe);In(e,e.sessionKey,{verboseLevel:f==="off"?null:f}).then(()=>{Me(e,{limit:b})})},onFillerChange:f=>{const b=Math.max(e.chatMessages.length+10,Pe);In(e,e.sessionKey,{fillerEnabled:f}).then(()=>{Me(e,{limit:b})})},loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:h,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,interimText:e.chatInterimText,draft:e.chatMessage,queue:e.chatQueue,canSend:e.connected,disabledReason:l,error:e.lastError,sessions:e.sessionsResult,focusMode:!1,onRefresh:()=>{e.resetToolStream();const f=Math.max(e.chatMessages.length+10,Pe);return Promise.all([Me(e,{limit:f}),Is(e)])},onToggleFocusMode:()=>{},onChatScroll:f=>e.handleChatScroll(f),nearBottom:e.chatUserNearBottom,hasMore:e.chatHistoryHasMore,loadingOlder:e.chatLoadingOlder,onLoadOlder:()=>{e.handleLoadOlderChat()},onDraftChange:f=>e.chatMessage=f,attachments:e.chatAttachments,onAttachmentsChange:f=>e.chatAttachments=f,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:f=>e.removeQueuedMessage(f),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:f=>e.handleOpenSidebar(f),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:f=>e.handleSplitRatioChange(f),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar})}return e.advancedPage?Cv({connected:e.connected,wsProps:Jt(e),activeTab:e.advancedTab,onTabChange:l=>{e.advancedTab=l,l==="cron"&&e.loadCron(),l==="skills"&&ht(e,{clearMessages:!0}),l==="logs"&&(e.logsSubTab==="session"?rn(e,{reset:!0}):Mt(e,{reset:!0}))},cronProps:{loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:(r=(o=e.channelsSnapshot)==null?void 0:o.channelMeta)!=null&&r.length?e.channelsSnapshot.channelMeta.map(l=>l.id):((a=e.channelsSnapshot)==null?void 0:a.channelOrder)??[],channelLabels:((u=e.channelsSnapshot)==null?void 0:u.channelLabels)??{},channelMeta:((c=e.channelsSnapshot)==null?void 0:c.channelMeta)??[],agentIds:(()=>{var d;const l=oe(e);return((d=l==null?void 0:l.agents)==null?void 0:d.map(h=>h.id))??[]})(),runsJobId:e.cronRunsJobId,runs:e.cronRuns,newEventModalOpen:e.cronNewEventModal,onNewEventModalOpen:()=>{e.cronNewEventModal=!0},onNewEventModalClose:()=>{e.cronNewEventModal=!1},detailJobId:e.cronDetailJobId,onDetailOpen:l=>{e.cronDetailJobId=l.id,Cs(e,l.id)},onDetailClose:()=>{e.cronDetailJobId=null},onFormChange:l=>e.cronForm={...e.cronForm,...l},onRefresh:()=>e.loadCron(),onAdd:()=>{op(e).then(()=>{e.cronNewEventModal=!1})},onToggle:(l,d)=>rp(e,l,d),onRun:l=>ap(e,l),onRemove:l=>lp(e,l),onLoadRuns:l=>Cs(e,l)},skillsProps:{loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,onFilterChange:l=>e.skillsFilter=l,onRefresh:()=>ht(e,{clearMessages:!0}),onToggle:(l,d)=>Gl(e,l,d),onEdit:(l,d)=>Vl(e,l,d),onSaveKey:l=>Ql(e,l),onInstall:(l,d,h)=>Yl(e,l,d,h)},logsProps:{logsSubTab:e.logsSubTab,onSubTabChange:l=>{e.logsSubTab=l,l==="session"?rn(e,{reset:!0}):Mt(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,onFilterTextChange:l=>e.sessionLogsFilterText=l,onTypeToggle:(l,d)=>{const h=e;h.sessionLogsTypeFilters={...h.sessionLogsTypeFilters,[l]:d}},onAgentToggle:(l,d)=>{const h=e;h.sessionLogsAgentFilters={...h.sessionLogsAgentFilters,[l]:d}},onToggleAutoFollow:l=>e.sessionLogsAutoFollow=l,onRefresh:()=>{rn(e,{reset:!0})},onExport:(l,d)=>e.exportSessionLogs(l,d),onScroll:l=>e.handleSessionLogsScroll(l)},loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,truncated:e.logsTruncated,onFilterTextChange:l=>e.logsFilterText=l,onLevelToggle:(l,d)=>{e.logsLevelFilters={...e.logsLevelFilters,[l]:d}},onToggleAutoFollow:l=>e.logsAutoFollow=l,onRefresh:()=>Mt(e,{reset:!0}),onExport:(l,d)=>e.exportSessionLogs(l,d),onScroll:l=>e.handleLogsScroll(l)}}):(window.location.replace("/chat"),p``)}function Pb(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 Ja(e){return e.startsWith("memory/public/")?"public":e.startsWith("memory/shared/")?"shared":"other"}function Lb(e,t,n){return p`
3474
+ <div class="audit-modal-overlay" @click=${s=>{s.target.classList.contains("audit-modal-overlay")&&n()}}>
3475
+ <div class="audit-modal-card">
3476
+ <div class="audit-modal-header">
3477
+ <h3>Memory Writes to Review</h3>
3478
+ <button class="audit-modal-close" @click=${n}>&times;</button>
3479
+ </div>
3480
+ <p class="audit-modal-desc">
3481
+ These files were written to shared or public folders by the agent.
3482
+ Review to ensure no sensitive data was misplaced.
3483
+ </p>
3484
+ ${e.length===0?p`<p class="audit-modal-empty">No unreviewed writes.</p>`:p`
3485
+ <div class="audit-modal-list">
3486
+ ${e.map(s=>p`
3487
+ <div class="audit-modal-entry">
3488
+ <div class="audit-modal-entry-path">
3489
+ <span class="audit-modal-folder audit-modal-folder--${Ja(s.path)}">${Ja(s.path)}</span>
3490
+ <a href="/files" class="audit-modal-path-link">${s.path}</a>
3491
+ </div>
3492
+ <div class="audit-modal-entry-meta">
3493
+ ${Pb(s.timestamp)}
3494
+ <span class="audit-modal-agent">${s.agentId}</span>
3495
+ </div>
3496
+ </div>
3497
+ `)}
3498
+ </div>
3499
+ <button class="setup-button audit-modal-clear" @click=${t}>
3500
+ Mark All Reviewed
3501
+ </button>
3502
+ `}
3503
+ </div>
3504
+ </div>
3505
+ `}const Ib={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},Rb={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",to:"",timeoutSeconds:"",postToMainPrefix:""};function Nb(e){e.basePath=kh();const t=Xe();if(Fh(t.accentColor),window.scrollTo(0,0),fh(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}`,Ce(e);return}if(e.setup){document.title=`${t.name} Setup`,Ce(e);return}if(e.filesPage){document.title=`${t.name} Files`,mh(e),Ce(e);return}if(e.browserPage){document.title=`${t.name} Browser`,Ce(e);return}if(e.adminsPage){document.title=`${t.name} Admins`,Ce(e);return}if(e.contactsPage){document.title=`${t.name} Contacts`,Ce(e);return}if(e.chatPage){document.title=`${t.name} Chat`,Ce(e);return}if(e.advancedPage){document.title=`${t.name} Advanced`,Ce(e);return}$h(e,!0),Sh(e),xh(e),window.addEventListener("popstate",e.popStateHandler),vh(e),Ce(e),ph(e),e.tab==="logs"&&(e.logsSubTab==="session"?bo(e):yo(e)),e.tab==="debug"&&ko(e)}function Db(e){Jd(e)}function Ob(e){var t;window.removeEventListener("popstate",e.popStateHandler),hh(e),vo(e),wo(e),So(e),gh(e),yh(e),Ah(e),(t=e.topbarObserver)==null||t.disconnect(),e.topbarObserver=null}function Bb(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;gn(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&!e.advancedPage&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&Sl(e,t.has("tab")||t.has("logsAutoFollow"))}}function Fb(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 Ub(e,t,n){await oo(e,t,n),await G(e,!0)}async function Wb(e,t){await $l(e,t),await G(e,!0)}async function Kb(e,t){await El(e,t),await G(e,!0)}async function zb(e,t){await Tl(e,t)}async function jb(e,t){await Cl(e,t)}async function Hb(e){await np(e),await Le(e),await G(e,!0)}async function qb(e){await Le(e),await G(e,!0)}function Vb(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[i,...s]=n.split(":");if(!i||s.length===0)continue;const o=i.trim(),r=s.join(":").trim();o&&r&&(t[o]=r)}return t}function 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 _u(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function Gb(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Fb(n??void 0)}function Qb(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function Yb(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function Xb(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function Zb(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(_u(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:Vb(s==null?void 0:s.details)};return}if(!s.persisted){e.nostrProfileFormState={...t,saving:!1,error:"Profile publish failed on all relays.",success:null};return}e.nostrProfileFormState={...t,saving:!1,error:null,success:"Profile published to relays.",fieldErrors:{},original:{...t.values}},await G(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function Jb(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(_u(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),s=await i.json().catch(()=>null);if(!i.ok||(s==null?void 0:s.ok)===!1||!s){const u=(s==null?void 0:s.error)??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:u,success:null};return}const o=s.merged??s.imported??null,r=o?{...t.values,...o}:t.values,a=!!(r.banner||r.website||r.nip05||r.lud16);e.nostrProfileFormState={...t,importing:!1,values:r,error:null,success:s.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:a},s.saved&&await G(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}async function ew(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 tw(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 nw(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 iw(e,t){e.authCodeInput=t}function sw(e){e.setupStep="whatsapp"}async function ow(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 rw(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 aw(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 lw(e,t){e.licenseKey=t}async function cw(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 uw(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 dw=Object.defineProperty,pw=Object.getOwnPropertyDescriptor,m=(e,t,n,i)=>{for(var s=i>1?void 0:i?pw(t,n):t,o=e.length-1,r;o>=0;o--)(r=e[o])&&(s=(i?r(t,n,s):r(s))||s);return i&&s&&dw(t,n,s),s};const As=fd();function hw(){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 fw(){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 gw(){const e=window.location.pathname;return e==="/files"||e.endsWith("/files")}function mw(){const e=window.location.pathname;return e==="/browser"||e.endsWith("/browser")}function yw(){const e=window.location.pathname;return e==="/admins"||e.endsWith("/admins")}function vw(){const e=window.location.pathname;return e==="/contacts"||e.endsWith("/contacts")}function bw(){const e=window.location.pathname;return e==="/chat"||e.endsWith("/chat")}function ww(){const e=window.location.pathname;return e==="/advanced"||e.endsWith("/advanced")}let g=class extends _t{constructor(){super(...arguments),this.settings=Gi(),this.password="",this.tab="chat",this.onboarding=hw(),this.setup=fw(),this.filesPage=gw(),this.browserPage=mw(),this.adminsPage=yw(),this.contactsPage=vw(),this.chatPage=bw(),this.advancedPage=ww(),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=vu,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=As.name,this.assistantAvatar=As.avatar,this.assistantAgentId=As.agentId??null,this.sessionKey=this.settings.sessionKey,this.chatLoading=!1,this.chatSending=!1,this.chatMessage="",this.chatMessages=[],this.chatHistoryTotal=0,this.chatHistoryHasMore=!1,this.chatLoadingOlder=!1,this.chatToolMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestion=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatThinkingLevel=null,this.chatModelProvider=null,this.chatModel=null,this.chatModelCatalog=[],this.chatVerboseLevel=null,this.chatFillerEnabled=null,this.chatQueue=[],this.chatAttachments=[],this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.splitRatio=this.settings.splitRatio,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.configLoading=!1,this.configRaw=`{
3506
+ }
3507
+ `,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.tailscaleStatus=null,this.tailscaleBusy=!1,this.tailscaleAuthUrl=null,this.tailscaleError=null,this.tailscaleFunnelEnableUrl=null,this.wifiStatus=null,this.wifiNetworks=[],this.wifiBusy=!1,this.wifiError=null,this.wifiPassword="",this.wifiSelectedSsid=null,this.licenseKey="",this.licenseBusy=!1,this.licenseValid=null,this.licenseMessage=null,this.licenseTier=null,this.licenseDeviceId=null,this.licenseStoredKey=null,this.licenseRemoveConfirm=!1,this.authConnected=null,this.authBusy=!1,this.authMessage=null,this.authUrl=null,this.authCodeInput="",this.authExpiresIn=null,this.setupStep="license",this.gatewayHealthy=null,this.gatewayHealthLoading=!1,this.gatewayHealthMessage=null,this.gatewayRestartBusy=!1,this.updateAvailable=null,this.currentVersion=null,this.latestVersion=null,this.updateChecking=!1,this.updateMessage=null,this.updateProgressSteps=[],this.updateLastResult=null,this.uninstallConfirm=!1,this.uninstallBusy=!1,this.uninstallDone=!1,this.uninstallError=null,this.uninstallConfirmText="",this.nostrProfileFormState=null,this.nostrProfileAccountId=null,this.presenceLoading=!1,this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.sessionsLoading=!1,this.sessionsResult=null,this.sessionsError=null,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...Rb},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.cronNewEventModal=!1,this.cronDetailJobId=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.filesMessage=null,this.filesUploadBusy=!1,this.filesReindexBusy=!1,this.filesMemoryStatus=null,this.embeddingDownloading=!1,this.embeddingPollTimer=null,this.filesSearchQuery="",this.filesSearchResults=null,this.filesSearchLoading=!1,this.filesSearchAgentId=null,this.filesResolvedAgentId=void 0,this.auditEntries=[],this.auditLoading=!1,this.auditModalOpen=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.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.imessageEnableConfirm=!1,this.imessageEnabling=!1,this.infoModalOpen=null,this.workspaces=[],this.workspacesLoading=!1,this.workspacesError=null,this.selectedWorkspace=null,this.addingWorkspace=!1,this.newWorkspaceName="",this.newWorkspacePath="",this.newWorkspacePin="",this.accountPinModalOpen=!1,this.accountPinBusy=!1,this.accountPinError=null,this.accountPinSuccess=null,this.apiKeyProviders=[],this.apiKeyModalOpen=!1,this.apiKeyBusy=!1,this.apiKeyError=null,this.apiKeySuccess=null,this.apiKeySavingProvider=null,this.authApiKeyMode=!1,this.authApiKeyInput="",this.authApiKeyBusy=!1,this.authApiKeyError=null,this.pinChanging=null,this.pinChangeBusy=!1,this.pinChangeError=null,this.loginChangePinMode=!1,this.changePinBusy=!1,this.changePinError=null,this.changePinSuccess=null,this.workspaceSaving=!1,this.workspaceRemoveConfirm=null,this.renamingWorkspace=!1,this.renameWorkspaceName="",this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...Ib},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.logsSubTab="session",this.sessionLogsLoading=!1,this.sessionLogsError=null,this.sessionLogsEntries=[],this.sessionLogsFilterText="",this.sessionLogsTypeFilters={user:!0,assistant:!0,tool:!0,thinking:!0,error:!0,system:!0},this.sessionLogsAgentFilters={},this.sessionLogsAgents=[],this.sessionLogsAutoFollow=!0,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=()=>Eh(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),Nb(this)}firstUpdated(){Db(this)}disconnectedCallback(){this.stopEmbeddingPoll(),Ob(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){Bb(this,e)}connect(){Ce(this)}handleChatScroll(e){qd(this,e)}handleLogsScroll(e){Gd(this,e)}handleSessionLogsScroll(e){Qd(this,e)}exportLogs(e,t){Xd(e,t)}exportSessionLogs(e,t){Zd(e,t)}resetToolStream(){so(this)}resetChatScroll(){Yd(this)}async loadAssistantIdentity(){await Ys(this)}applySettings(e){Ge(this,e)}setTab(e){bh(this,e)}setTheme(e,t){wh(this,e,t)}async loadOverview(){await lc(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 xo(this)}async handleAbortChat(){await uc(this)}removeQueuedMessage(e){Mh(this,e)}async handleSendChat(e,t){await Ph(this,e,t)}async handleWhatsAppStart(e,t){await Ub(this,e,t)}async handleWhatsAppWait(e){await Wb(this,e)}async handleWhatsAppLogout(e){await Kb(this,e)}async handleAddWhatsAppAccount(e){await zb(this,e)}async handleRemoveWhatsAppAccount(e){await jb(this,e)}async handleAccessCheck(){await Xa(this)}async handlePinSubmit(e,t){await hb(this,e,t),this.accessState.authenticated&&this.accessState.workspace&&this.handleWorkspaceSelect(this.accessState.workspace)}async handleSetMasterPin(e){await fb(this,e)}async handleLogout(){await mb(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 Xa(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 ow(this)}async handleLicenseActivate(){await rw(this)}async handleLicenseRemove(){await aw(this)}handleLicenseKeyChange(e){lw(this,e)}async handleAuthStatusCheck(){await ew(this)}async handleAuthStart(){await tw(this)}async handleAuthSubmitCode(e){await nw(this,e)}handleAuthCodeChange(e){iw(this,e)}handleSkipToWhatsApp(){sw(this)}async handleGatewayHealthCheck(){await cw(this)}async handleGatewayRestart(){await uw(this)}async handleUpdateCheck(){await fu(this)}async handleUpdateRun(){await Yv(this)}handleUpdateDismissResult(){Jv(this)}handleUninstallConfirm(){this.uninstallConfirm=!0,this.uninstallConfirmText=""}handleUninstallCancel(){this.uninstallConfirm=!1,this.uninstallConfirmText="",this.uninstallError=null}handleUninstallConfirmTextChange(e){this.uninstallConfirmText=e}async handleUninstallRun(){const{runUninstall:e}=await ie(async()=>{const{runUninstall:t}=await Promise.resolve().then(()=>Nr);return{runUninstall:t}},void 0,import.meta.url);await e(this)}handleUninstallDismiss(){ie(async()=>{const{clearUninstallDone:e}=await Promise.resolve().then(()=>Nr);return{clearUninstallDone:e}},void 0,import.meta.url).then(({clearUninstallDone:e})=>{e()}),this.uninstallDone=!1,this.uninstallConfirm=!1,this.uninstallConfirmText=""}async loadAuditEntries(){await tc(this)}async clearAudit(){await th(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,vn(this,t),mo(this,t)}handleAdminsLoad(){const e=this.resolveAdminAgentId();ie(async()=>{const{loadAdmins:t}=await Promise.resolve().then(()=>vb);return{loadAdmins:t}},void 0,import.meta.url).then(({loadAdmins:t})=>{t(this,e)})}resolveAdminAgentId(){const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(n=>n.id.endsWith("-admin")||n.id==="admin");return t==null?void 0:t.id}resolveFilesAgentId(){var n;const e=this.getSelectedWorkspaceInfo();if(!e)return;const t=e.agents.find(i=>i.id.endsWith("-admin")||i.id==="admin");return(t==null?void 0:t.id)??((n=e.agents[0])==null?void 0:n.id)}handleChatLoad(){const e=this.resolveAdminAgentId();if(e){const t=`agent:${e}:main`;t!==this.sessionKey&&(this.sessionKey=t,this.chatMessages=[],this.chatStream=null,this.chatInterimText=null,this.chatRunId=null,this.chatSuggestion=null,this.applySettings({...this.settings,sessionKey:t,lastActiveSessionKey:t}),this.loadAssistantIdentity())}ie(async()=>{const{loadChatHistory:t}=await Promise.resolve().then(()=>ii);return{loadChatHistory:t}},void 0,import.meta.url).then(({loadChatHistory:t})=>{t(this)})}async handleLoadOlderChat(){if(this.chatLoadingOlder||!this.chatHistoryHasMore)return;const e=Vd(this),{loadOlderChatHistory:t}=await ie(async()=>{const{loadOlderChatHistory:i}=await Promise.resolve().then(()=>ii);return{loadOlderChatHistory:i}},void 0,import.meta.url);await t(this)&&e&&(await this.updateComplete,e())}handleAdvancedLoad(){var t;const e=this.getSelectedWorkspaceInfo();this.workspaceAgentIds=((t=e==null?void 0:e.agents)==null?void 0:t.map(n=>n.id))??void 0,this.sessionLogsEntries=[],this.sessionLogsCursors={},this.sessionLogsAgents=[],this.advancedTab==="cron"&&this.loadCron(),this.advancedTab==="logs"&&(this.logsSubTab==="session"?ie(async()=>{const{loadSessionLogs:n}=await Promise.resolve().then(()=>ec);return{loadSessionLogs:n}},void 0,import.meta.url).then(({loadSessionLogs:n})=>{n(this,{reset:!0})}):ie(async()=>{const{loadLogs:n}=await Promise.resolve().then(()=>fp);return{loadLogs:n}},void 0,import.meta.url).then(({loadLogs:n})=>{n(this,{reset:!0})})),this.advancedTab==="skills"&&ie(async()=>{const{loadSkills:n}=await Promise.resolve().then(()=>Gp);return{loadSkills:n}},void 0,import.meta.url).then(({loadSkills:n})=>{n(this,{clearMessages:!0})})}async handleChannelConfigSave(){await Hb(this)}async handleChannelConfigReload(){await qb(this)}handleNostrProfileEdit(e,t){Gb(this,e,t)}handleNostrProfileCancel(){Qb(this)}handleNostrProfileFieldChange(e,t){Yb(this,e,t)}async handleNostrProfileSave(){await Zb(this)}async handleNostrProfileImport(){await Jb(this)}handleNostrProfileToggleAdvanced(){Xb(this)}async handleExecApprovalDecision(e){const t=this.execApprovalQueue[0];if(!(!t||!this.client||this.execApprovalBusy)){this.execApprovalBusy=!0,this.execApprovalError=null;try{await this.client.request("exec.approval.resolve",{id:t.id,decision:e}),this.execApprovalQueue=this.execApprovalQueue.filter(n=>n.id!==t.id)}catch(n){this.execApprovalError=`Exec approval failed: ${String(n)}`}finally{this.execApprovalBusy=!1}}}handleOpenSidebar(e){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarCloseTimer=null)},200)}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}handleAdminsNewPhoneChange(e){this.adminsNewPhone=e,this.adminsError&&(this.adminsError=null)}handleContactsLoad(){const e=this.selectedWorkspace??void 0;ie(async()=>{const{loadContacts:t}=await Promise.resolve().then(()=>bb);return{loadContacts:t}},void 0,import.meta.url).then(({loadContacts:t})=>{t(this,e)})}handleContactsNewPhoneChange(e){this.contactsNewPhone=e,this.contactsError&&(this.contactsError=null)}handleContactsNewNameChange(e){this.contactsNewName=e,this.contactsError&&(this.contactsError=null)}async handleWorkspacesLoad(){const{loadWorkspaces:e}=await ie(async()=>{const{loadWorkspaces:t}=await Promise.resolve().then(()=>Hn);return{loadWorkspaces:t}},void 0,import.meta.url);await e(this)}async handleWorkspaceCreate(e,t){const{createWorkspace:n}=await ie(async()=>{const{createWorkspace:s}=await Promise.resolve().then(()=>Hn);return{createWorkspace:s}},void 0,import.meta.url),{loadChannels:i}=await ie(async()=>{const{loadChannels:s}=await Promise.resolve().then(()=>cp);return{loadChannels:s}},void 0,import.meta.url);await n(this,{name:e,workspacePath:t,onCreated:s=>{if(!s.whatsappAccountId)return;const o=s.whatsappAccountId;this.handleWorkspaceSelect(e),setTimeout(async()=>{try{await i(this,!0),await this.handleWhatsAppStart(!0,o),this.whatsappLoginQrDataUrl&&(await this.handleWhatsAppWait(o),await i(this,!0),await this.handleWorkspacesLoad())}catch{}this.requestUpdate()},3e3)}})}async handleWorkspaceRemove(e){const{removeWorkspace:t}=await ie(async()=>{const{removeWorkspace:n}=await Promise.resolve().then(()=>Hn);return{removeWorkspace:n}},void 0,import.meta.url);await t(this,e)}handleWorkspaceRenameStart(){const e=this.getSelectedWorkspaceInfo();this.renameWorkspaceName=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"",this.renamingWorkspace=!0}handleWorkspaceRenameCancel(){this.renamingWorkspace=!1,this.renameWorkspaceName=""}async handleWorkspaceRename(e,t){const{renameWorkspace:n}=await ie(async()=>{const{renameWorkspace:i}=await Promise.resolve().then(()=>Hn);return{renameWorkspace:i}},void 0,import.meta.url);await n(this,e,t),this.renamingWorkspace=!1,this.renameWorkspaceName=""}handleWorkspaceSelect(e){this.selectedWorkspace=e,localStorage.setItem("taskmaster-selected-workspace",e),Sr(e),this.settings=Gi(),this.chatMessage="",this.chatAttachments=[],this.chatStream=null,this.chatInterimText=null,this.chatSuggestion=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.chatQueue=[],this.lastError=null,this.reloadCurrentPageData()}getSelectedWorkspaceInfo(){return this.selectedWorkspace?this.workspaces.find(e=>e.name===this.selectedWorkspace)??null:null}reloadCurrentPageData(){this.loadAuditEntries(),this.adminsPage?this.handleAdminsLoad():this.contactsPage?this.handleContactsLoad():this.filesPage?this.handleFilesLoad():this.chatPage?this.handleChatLoad():this.advancedPage&&this.handleAdvancedLoad()}initWorkspaceSelection(){if(this.workspaces.length===0){this.reloadCurrentPageData();return}const e=localStorage.getItem("taskmaster-selected-workspace"),t=e?this.workspaces.find(n=>n.name===e):null;if(t)this.selectedWorkspace=t.name;else{const n=this.workspaces.find(i=>i.isDefault)??this.workspaces[0];this.selectedWorkspace=n.name,localStorage.setItem("taskmaster-selected-workspace",n.name)}Sr(this.selectedWorkspace),this.settings=Gi(),this.reloadCurrentPageData()}render(){return p`${Mb(this)}${this.auditModalOpen?Lb(this.auditEntries,()=>this.clearAudit(),()=>{this.auditModalOpen=!1}):k}`}};m([y()],g.prototype,"settings",2);m([y()],g.prototype,"password",2);m([y()],g.prototype,"tab",2);m([y()],g.prototype,"onboarding",2);m([y()],g.prototype,"setup",2);m([y()],g.prototype,"filesPage",2);m([y()],g.prototype,"browserPage",2);m([y()],g.prototype,"adminsPage",2);m([y()],g.prototype,"contactsPage",2);m([y()],g.prototype,"chatPage",2);m([y()],g.prototype,"advancedPage",2);m([y()],g.prototype,"advancedTab",2);m([y()],g.prototype,"publicChat",2);m([y()],g.prototype,"publicChatConfig",2);m([y()],g.prototype,"publicChatSessionKey",2);m([y()],g.prototype,"publicChatAuthenticated",2);m([y()],g.prototype,"publicChatAuthStep",2);m([y()],g.prototype,"connected",2);m([y()],g.prototype,"accessState",2);m([y()],g.prototype,"theme",2);m([y()],g.prototype,"themeResolved",2);m([y()],g.prototype,"hello",2);m([y()],g.prototype,"lastError",2);m([y()],g.prototype,"eventLog",2);m([y()],g.prototype,"assistantName",2);m([y()],g.prototype,"assistantAvatar",2);m([y()],g.prototype,"assistantAgentId",2);m([y()],g.prototype,"sessionKey",2);m([y()],g.prototype,"chatLoading",2);m([y()],g.prototype,"chatSending",2);m([y()],g.prototype,"chatMessage",2);m([y()],g.prototype,"chatMessages",2);m([y()],g.prototype,"chatHistoryTotal",2);m([y()],g.prototype,"chatHistoryHasMore",2);m([y()],g.prototype,"chatLoadingOlder",2);m([y()],g.prototype,"chatToolMessages",2);m([y()],g.prototype,"chatStream",2);m([y()],g.prototype,"chatInterimText",2);m([y()],g.prototype,"chatSuggestion",2);m([y()],g.prototype,"chatStreamStartedAt",2);m([y()],g.prototype,"chatRunId",2);m([y()],g.prototype,"compactionStatus",2);m([y()],g.prototype,"chatAvatarUrl",2);m([y()],g.prototype,"chatThinkingLevel",2);m([y()],g.prototype,"chatModelProvider",2);m([y()],g.prototype,"chatModel",2);m([y()],g.prototype,"chatModelCatalog",2);m([y()],g.prototype,"chatVerboseLevel",2);m([y()],g.prototype,"chatFillerEnabled",2);m([y()],g.prototype,"chatQueue",2);m([y()],g.prototype,"chatAttachments",2);m([y()],g.prototype,"sidebarOpen",2);m([y()],g.prototype,"sidebarContent",2);m([y()],g.prototype,"sidebarError",2);m([y()],g.prototype,"splitRatio",2);m([y()],g.prototype,"nodesLoading",2);m([y()],g.prototype,"nodes",2);m([y()],g.prototype,"devicesLoading",2);m([y()],g.prototype,"devicesError",2);m([y()],g.prototype,"devicesList",2);m([y()],g.prototype,"execApprovalsLoading",2);m([y()],g.prototype,"execApprovalsSaving",2);m([y()],g.prototype,"execApprovalsDirty",2);m([y()],g.prototype,"execApprovalsSnapshot",2);m([y()],g.prototype,"execApprovalsForm",2);m([y()],g.prototype,"execApprovalsSelectedAgent",2);m([y()],g.prototype,"execApprovalsTarget",2);m([y()],g.prototype,"execApprovalsTargetNodeId",2);m([y()],g.prototype,"execApprovalQueue",2);m([y()],g.prototype,"execApprovalBusy",2);m([y()],g.prototype,"execApprovalError",2);m([y()],g.prototype,"configLoading",2);m([y()],g.prototype,"configRaw",2);m([y()],g.prototype,"configRawOriginal",2);m([y()],g.prototype,"configValid",2);m([y()],g.prototype,"configIssues",2);m([y()],g.prototype,"configSaving",2);m([y()],g.prototype,"configApplying",2);m([y()],g.prototype,"updateRunning",2);m([y()],g.prototype,"applySessionKey",2);m([y()],g.prototype,"configSnapshot",2);m([y()],g.prototype,"configSchema",2);m([y()],g.prototype,"configSchemaVersion",2);m([y()],g.prototype,"configSchemaLoading",2);m([y()],g.prototype,"configUiHints",2);m([y()],g.prototype,"configForm",2);m([y()],g.prototype,"configFormOriginal",2);m([y()],g.prototype,"configFormDirty",2);m([y()],g.prototype,"configFormMode",2);m([y()],g.prototype,"configSearchQuery",2);m([y()],g.prototype,"configActiveSection",2);m([y()],g.prototype,"configActiveSubsection",2);m([y()],g.prototype,"channelsLoading",2);m([y()],g.prototype,"channelsSnapshot",2);m([y()],g.prototype,"channelsError",2);m([y()],g.prototype,"channelsLastSuccess",2);m([y()],g.prototype,"whatsappLoginMessage",2);m([y()],g.prototype,"whatsappLoginQrDataUrl",2);m([y()],g.prototype,"whatsappLoginConnected",2);m([y()],g.prototype,"whatsappBusy",2);m([y()],g.prototype,"whatsappActiveQrAccountId",2);m([y()],g.prototype,"whatsappPairedPhone",2);m([y()],g.prototype,"addingWhatsAppAccount",2);m([y()],g.prototype,"newWhatsAppAccountName",2);m([y()],g.prototype,"whatsappAccountError",2);m([y()],g.prototype,"whatsappAccountSaving",2);m([y()],g.prototype,"whatsappSettingsOpen",2);m([y()],g.prototype,"publicChatToggleBusy",2);m([y()],g.prototype,"tailscaleStatus",2);m([y()],g.prototype,"tailscaleBusy",2);m([y()],g.prototype,"tailscaleAuthUrl",2);m([y()],g.prototype,"tailscaleError",2);m([y()],g.prototype,"tailscaleFunnelEnableUrl",2);m([y()],g.prototype,"wifiStatus",2);m([y()],g.prototype,"wifiNetworks",2);m([y()],g.prototype,"wifiBusy",2);m([y()],g.prototype,"wifiError",2);m([y()],g.prototype,"wifiPassword",2);m([y()],g.prototype,"wifiSelectedSsid",2);m([y()],g.prototype,"licenseKey",2);m([y()],g.prototype,"licenseBusy",2);m([y()],g.prototype,"licenseValid",2);m([y()],g.prototype,"licenseMessage",2);m([y()],g.prototype,"licenseTier",2);m([y()],g.prototype,"licenseDeviceId",2);m([y()],g.prototype,"licenseStoredKey",2);m([y()],g.prototype,"licenseRemoveConfirm",2);m([y()],g.prototype,"authConnected",2);m([y()],g.prototype,"authBusy",2);m([y()],g.prototype,"authMessage",2);m([y()],g.prototype,"authUrl",2);m([y()],g.prototype,"authCodeInput",2);m([y()],g.prototype,"authExpiresIn",2);m([y()],g.prototype,"setupStep",2);m([y()],g.prototype,"gatewayHealthy",2);m([y()],g.prototype,"gatewayHealthLoading",2);m([y()],g.prototype,"gatewayHealthMessage",2);m([y()],g.prototype,"gatewayRestartBusy",2);m([y()],g.prototype,"updateAvailable",2);m([y()],g.prototype,"currentVersion",2);m([y()],g.prototype,"latestVersion",2);m([y()],g.prototype,"updateChecking",2);m([y()],g.prototype,"updateMessage",2);m([y()],g.prototype,"updateProgressSteps",2);m([y()],g.prototype,"updateLastResult",2);m([y()],g.prototype,"uninstallConfirm",2);m([y()],g.prototype,"uninstallBusy",2);m([y()],g.prototype,"uninstallDone",2);m([y()],g.prototype,"uninstallError",2);m([y()],g.prototype,"uninstallConfirmText",2);m([y()],g.prototype,"nostrProfileFormState",2);m([y()],g.prototype,"nostrProfileAccountId",2);m([y()],g.prototype,"presenceLoading",2);m([y()],g.prototype,"presenceEntries",2);m([y()],g.prototype,"presenceError",2);m([y()],g.prototype,"presenceStatus",2);m([y()],g.prototype,"agentsLoading",2);m([y()],g.prototype,"agentsList",2);m([y()],g.prototype,"agentsError",2);m([y()],g.prototype,"sessionsLoading",2);m([y()],g.prototype,"sessionsResult",2);m([y()],g.prototype,"sessionsError",2);m([y()],g.prototype,"cronLoading",2);m([y()],g.prototype,"cronJobs",2);m([y()],g.prototype,"cronStatus",2);m([y()],g.prototype,"cronError",2);m([y()],g.prototype,"cronForm",2);m([y()],g.prototype,"cronRunsJobId",2);m([y()],g.prototype,"cronRuns",2);m([y()],g.prototype,"cronBusy",2);m([y()],g.prototype,"cronNewEventModal",2);m([y()],g.prototype,"cronDetailJobId",2);m([y()],g.prototype,"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,"filesMessage",2);m([y()],g.prototype,"filesUploadBusy",2);m([y()],g.prototype,"filesReindexBusy",2);m([y()],g.prototype,"filesMemoryStatus",2);m([y()],g.prototype,"embeddingDownloading",2);m([y()],g.prototype,"filesSearchQuery",2);m([y()],g.prototype,"filesSearchResults",2);m([y()],g.prototype,"filesSearchLoading",2);m([y()],g.prototype,"filesSearchAgentId",2);m([y()],g.prototype,"auditEntries",2);m([y()],g.prototype,"auditLoading",2);m([y()],g.prototype,"auditModalOpen",2);m([y()],g.prototype,"skillsLoading",2);m([y()],g.prototype,"skillsReport",2);m([y()],g.prototype,"skillsError",2);m([y()],g.prototype,"skillsFilter",2);m([y()],g.prototype,"skillEdits",2);m([y()],g.prototype,"skillsBusyKey",2);m([y()],g.prototype,"skillMessages",2);m([y()],g.prototype,"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,"imessageEnableConfirm",2);m([y()],g.prototype,"imessageEnabling",2);m([y()],g.prototype,"infoModalOpen",2);m([y()],g.prototype,"workspaces",2);m([y()],g.prototype,"workspacesLoading",2);m([y()],g.prototype,"workspacesError",2);m([y()],g.prototype,"selectedWorkspace",2);m([y()],g.prototype,"addingWorkspace",2);m([y()],g.prototype,"newWorkspaceName",2);m([y()],g.prototype,"newWorkspacePath",2);m([y()],g.prototype,"newWorkspacePin",2);m([y()],g.prototype,"accountPinModalOpen",2);m([y()],g.prototype,"accountPinBusy",2);m([y()],g.prototype,"accountPinError",2);m([y()],g.prototype,"accountPinSuccess",2);m([y()],g.prototype,"apiKeyProviders",2);m([y()],g.prototype,"apiKeyModalOpen",2);m([y()],g.prototype,"apiKeyBusy",2);m([y()],g.prototype,"apiKeyError",2);m([y()],g.prototype,"apiKeySuccess",2);m([y()],g.prototype,"apiKeySavingProvider",2);m([y()],g.prototype,"authApiKeyMode",2);m([y()],g.prototype,"authApiKeyInput",2);m([y()],g.prototype,"authApiKeyBusy",2);m([y()],g.prototype,"authApiKeyError",2);m([y()],g.prototype,"pinChanging",2);m([y()],g.prototype,"pinChangeBusy",2);m([y()],g.prototype,"pinChangeError",2);m([y()],g.prototype,"loginChangePinMode",2);m([y()],g.prototype,"changePinBusy",2);m([y()],g.prototype,"changePinError",2);m([y()],g.prototype,"changePinSuccess",2);m([y()],g.prototype,"workspaceSaving",2);m([y()],g.prototype,"workspaceRemoveConfirm",2);m([y()],g.prototype,"renamingWorkspace",2);m([y()],g.prototype,"renameWorkspaceName",2);m([y()],g.prototype,"debugLoading",2);m([y()],g.prototype,"debugStatus",2);m([y()],g.prototype,"debugHealth",2);m([y()],g.prototype,"debugModels",2);m([y()],g.prototype,"debugHeartbeat",2);m([y()],g.prototype,"debugCallMethod",2);m([y()],g.prototype,"debugCallParams",2);m([y()],g.prototype,"debugCallResult",2);m([y()],g.prototype,"debugCallError",2);m([y()],g.prototype,"logsLoading",2);m([y()],g.prototype,"logsError",2);m([y()],g.prototype,"logsFile",2);m([y()],g.prototype,"logsEntries",2);m([y()],g.prototype,"logsFilterText",2);m([y()],g.prototype,"logsLevelFilters",2);m([y()],g.prototype,"logsAutoFollow",2);m([y()],g.prototype,"logsTruncated",2);m([y()],g.prototype,"logsCursor",2);m([y()],g.prototype,"logsLastFetchAt",2);m([y()],g.prototype,"logsLimit",2);m([y()],g.prototype,"logsMaxBytes",2);m([y()],g.prototype,"logsAtBottom",2);m([y()],g.prototype,"logsSubTab",2);m([y()],g.prototype,"sessionLogsLoading",2);m([y()],g.prototype,"sessionLogsError",2);m([y()],g.prototype,"sessionLogsEntries",2);m([y()],g.prototype,"sessionLogsFilterText",2);m([y()],g.prototype,"sessionLogsTypeFilters",2);m([y()],g.prototype,"sessionLogsAgentFilters",2);m([y()],g.prototype,"sessionLogsAgents",2);m([y()],g.prototype,"sessionLogsAutoFollow",2);m([y()],g.prototype,"sessionLogsCursors",2);m([y()],g.prototype,"sessionLogsLastFetchAt",2);m([y()],g.prototype,"sessionLogsAtBottom",2);m([y()],g.prototype,"chatUserNearBottom",2);g=m([ll("taskmaster-app")],g);
3508
+ //# sourceMappingURL=index-lbNnMWBM.js.map