@godmode-team/godmode 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();const bp="modulepreload",wp=function(e,t){return new URL(e,t).href},tr={},E=function(t,n,s){let a=Promise.resolve();if(n&&n.length>0){let u=function(p){return Promise.all(p.map(f=>Promise.resolve(f).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");a=u(n.map(p=>{if(p=wp(p,s),p in tr)return;tr[p]=!0;const f=p.endsWith(".css"),m=f?'[rel="stylesheet"]':"";if(s)for(let $=o.length-1;$>=0;$--){const d=o[$];if(d.href===p&&(!f||d.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${p}"]${m}`))return;const g=document.createElement("link");if(g.rel=f?"stylesheet":bp,f||(g.as="script"),g.crossOrigin="",g.href=p,c&&g.setAttribute("nonce",c),document.head.appendChild(g),f)return new Promise(($,d)=>{g.addEventListener("load",$),g.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};const $s=globalThis,Pi=$s.ShadowRoot&&($s.ShadyCSS===void 0||$s.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ii=Symbol(),nr=new WeakMap;let mc=class{constructor(t,n,s){if(this._$cssResult$=!0,s!==Ii)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(Pi&&t===void 0){const s=n!==void 0&&n.length===1;s&&(t=nr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&nr.set(n,t))}return t}toString(){return this.cssText}};const $p=e=>new mc(typeof e=="string"?e:e+"",void 0,Ii),kp=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((s,a,i)=>s+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(a)+e[i+1],e[0]);return new mc(n,e,Ii)},Sp=(e,t)=>{if(Pi)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const s=document.createElement("style"),a=$s.litNonce;a!==void 0&&s.setAttribute("nonce",a),s.textContent=n.cssText,e.appendChild(s)}},sr=Pi?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const s of t.cssRules)n+=s.cssText;return $p(n)})(e):e;const{is:Ap,defineProperty:_p,getOwnPropertyDescriptor:Tp,getOwnPropertyNames:xp,getOwnPropertySymbols:Cp,getPrototypeOf:Ep}=Object,Vs=globalThis,ar=Vs.trustedTypes,Lp=ar?ar.emptyScript:"",Rp=Vs.reactiveElementPolyfillSupport,On=(e,t)=>e,Ls={toAttribute(e,t){switch(t){case Boolean:e=e?Lp:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},Mi=(e,t)=>!Ap(e,t),ir={attribute:!0,type:String,converter:Ls,reflect:!1,useDefault:!1,hasChanged:Mi};Symbol.metadata??=Symbol("metadata"),Vs.litPropertyMetadata??=new WeakMap;let Jt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=ir){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 s=Symbol(),a=this.getPropertyDescriptor(t,s,n);a!==void 0&&_p(this.prototype,t,a)}}static getPropertyDescriptor(t,n,s){const{get:a,set:i}=Tp(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:a,set(o){const l=a?.call(this);i?.call(this,o),this.requestUpdate(t,l,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ir}static _$Ei(){if(this.hasOwnProperty(On("elementProperties")))return;const t=Ep(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(On("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(On("properties"))){const n=this.properties,s=[...xp(n),...Cp(n)];for(const a of s)this.createProperty(a,n[a])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[s,a]of n)this.elementProperties.set(s,a)}this._$Eh=new Map;for(const[n,s]of this.elementProperties){const a=this._$Eu(n,s);a!==void 0&&this._$Eh.set(a,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const n=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const a of s)n.unshift(sr(a))}else t!==void 0&&n.push(sr(t));return n}static _$Eu(t,n){const s=n.attribute;return s===!1?void 0:typeof s=="string"?s: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(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,n=this.constructor.elementProperties;for(const s of n.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Sp(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,s){this._$AK(t,s)}_$ET(t,n){const s=this.constructor.elementProperties.get(t),a=this.constructor._$Eu(t,s);if(a!==void 0&&s.reflect===!0){const i=(s.converter?.toAttribute!==void 0?s.converter:Ls).toAttribute(n,s.type);this._$Em=t,i==null?this.removeAttribute(a):this.setAttribute(a,i),this._$Em=null}}_$AK(t,n){const s=this.constructor,a=s._$Eh.get(t);if(a!==void 0&&this._$Em!==a){const i=s.getPropertyOptions(a),o=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:Ls;this._$Em=a;const l=o.fromAttribute(n,i.type);this[a]=l??this._$Ej?.get(a)??l,this._$Em=null}}requestUpdate(t,n,s,a=!1,i){if(t!==void 0){const o=this.constructor;if(a===!1&&(i=this[t]),s??=o.getPropertyOptions(t),!((s.hasChanged??Mi)(i,n)||s.useDefault&&s.reflect&&i===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,s))))return;this.C(t,n,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,n,{useDefault:s,reflect:a,wrapped:i},o){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??n??this[t]),i!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(n=void 0),this._$AL.set(t,n)),a===!0&&this._$Em!==t&&(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(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[a,i]of this._$Ep)this[a]=i;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[a,i]of s){const{wrapped:o}=i,l=this[a];o!==!0||this._$AL.has(a)||l===void 0||this.C(a,void 0,i,l)}}let t=!1;const n=this._$AL;try{t=this.shouldUpdate(n),t?(this.willUpdate(n),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(n)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(n)}willUpdate(t){}_$AE(t){this._$EO?.forEach(n=>n.hostUpdated?.()),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.forEach(n=>this._$ET(n,this[n])),this._$EM()}updated(t){}firstUpdated(t){}};Jt.elementStyles=[],Jt.shadowRootOptions={mode:"open"},Jt[On("elementProperties")]=new Map,Jt[On("finalized")]=new Map,Rp?.({ReactiveElement:Jt}),(Vs.reactiveElementVersions??=[]).push("2.1.2");const Di=globalThis,or=e=>e,Rs=Di.trustedTypes,rr=Rs?Rs.createPolicy("lit-html",{createHTML:e=>e}):void 0,vc="$lit$",ot=`lit$${Math.random().toFixed(9).slice(2)}$`,yc="?"+ot,Pp=`<${yc}>`,Et=document,zn=()=>Et.createComment(""),Kn=e=>e===null||typeof e!="object"&&typeof e!="function",Oi=Array.isArray,Ip=e=>Oi(e)||typeof e?.[Symbol.iterator]=="function",Aa=`[
1
+ (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();const yp="modulepreload",bp=function(e,t){return new URL(e,t).href},tr={},E=function(t,n,s){let a=Promise.resolve();if(n&&n.length>0){let u=function(p){return Promise.all(p.map(f=>Promise.resolve(f).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");a=u(n.map(p=>{if(p=bp(p,s),p in tr)return;tr[p]=!0;const f=p.endsWith(".css"),m=f?'[rel="stylesheet"]':"";if(s)for(let $=o.length-1;$>=0;$--){const d=o[$];if(d.href===p&&(!f||d.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${p}"]${m}`))return;const g=document.createElement("link");if(g.rel=f?"stylesheet":yp,f||(g.as="script"),g.crossOrigin="",g.href=p,c&&g.setAttribute("nonce",c),document.head.appendChild(g),f)return new Promise(($,d)=>{g.addEventListener("load",$),g.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};const $s=globalThis,Pi=$s.ShadowRoot&&($s.ShadyCSS===void 0||$s.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ii=Symbol(),nr=new WeakMap;let mc=class{constructor(t,n,s){if(this._$cssResult$=!0,s!==Ii)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(Pi&&t===void 0){const s=n!==void 0&&n.length===1;s&&(t=nr.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&nr.set(n,t))}return t}toString(){return this.cssText}};const wp=e=>new mc(typeof e=="string"?e:e+"",void 0,Ii),$p=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((s,a,i)=>s+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(a)+e[i+1],e[0]);return new mc(n,e,Ii)},kp=(e,t)=>{if(Pi)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const s=document.createElement("style"),a=$s.litNonce;a!==void 0&&s.setAttribute("nonce",a),s.textContent=n.cssText,e.appendChild(s)}},sr=Pi?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const s of t.cssRules)n+=s.cssText;return wp(n)})(e):e;const{is:Sp,defineProperty:Ap,getOwnPropertyDescriptor:_p,getOwnPropertyNames:Tp,getOwnPropertySymbols:xp,getPrototypeOf:Cp}=Object,Vs=globalThis,ar=Vs.trustedTypes,Ep=ar?ar.emptyScript:"",Lp=Vs.reactiveElementPolyfillSupport,On=(e,t)=>e,Ls={toAttribute(e,t){switch(t){case Boolean:e=e?Ep: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}},Mi=(e,t)=>!Sp(e,t),ir={attribute:!0,type:String,converter:Ls,reflect:!1,useDefault:!1,hasChanged:Mi};Symbol.metadata??=Symbol("metadata"),Vs.litPropertyMetadata??=new WeakMap;let Yt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=ir){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 s=Symbol(),a=this.getPropertyDescriptor(t,s,n);a!==void 0&&Ap(this.prototype,t,a)}}static getPropertyDescriptor(t,n,s){const{get:a,set:i}=_p(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:a,set(o){const l=a?.call(this);i?.call(this,o),this.requestUpdate(t,l,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ir}static _$Ei(){if(this.hasOwnProperty(On("elementProperties")))return;const t=Cp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(On("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(On("properties"))){const n=this.properties,s=[...Tp(n),...xp(n)];for(const a of s)this.createProperty(a,n[a])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[s,a]of n)this.elementProperties.set(s,a)}this._$Eh=new Map;for(const[n,s]of this.elementProperties){const a=this._$Eu(n,s);a!==void 0&&this._$Eh.set(a,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const n=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const a of s)n.unshift(sr(a))}else t!==void 0&&n.push(sr(t));return n}static _$Eu(t,n){const s=n.attribute;return s===!1?void 0:typeof s=="string"?s: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(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,n=this.constructor.elementProperties;for(const s of n.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return kp(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,s){this._$AK(t,s)}_$ET(t,n){const s=this.constructor.elementProperties.get(t),a=this.constructor._$Eu(t,s);if(a!==void 0&&s.reflect===!0){const i=(s.converter?.toAttribute!==void 0?s.converter:Ls).toAttribute(n,s.type);this._$Em=t,i==null?this.removeAttribute(a):this.setAttribute(a,i),this._$Em=null}}_$AK(t,n){const s=this.constructor,a=s._$Eh.get(t);if(a!==void 0&&this._$Em!==a){const i=s.getPropertyOptions(a),o=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:Ls;this._$Em=a;const l=o.fromAttribute(n,i.type);this[a]=l??this._$Ej?.get(a)??l,this._$Em=null}}requestUpdate(t,n,s,a=!1,i){if(t!==void 0){const o=this.constructor;if(a===!1&&(i=this[t]),s??=o.getPropertyOptions(t),!((s.hasChanged??Mi)(i,n)||s.useDefault&&s.reflect&&i===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,s))))return;this.C(t,n,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,n,{useDefault:s,reflect:a,wrapped:i},o){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??n??this[t]),i!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(n=void 0),this._$AL.set(t,n)),a===!0&&this._$Em!==t&&(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(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[a,i]of this._$Ep)this[a]=i;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[a,i]of s){const{wrapped:o}=i,l=this[a];o!==!0||this._$AL.has(a)||l===void 0||this.C(a,void 0,i,l)}}let t=!1;const n=this._$AL;try{t=this.shouldUpdate(n),t?(this.willUpdate(n),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(n)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(n)}willUpdate(t){}_$AE(t){this._$EO?.forEach(n=>n.hostUpdated?.()),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.forEach(n=>this._$ET(n,this[n])),this._$EM()}updated(t){}firstUpdated(t){}};Yt.elementStyles=[],Yt.shadowRootOptions={mode:"open"},Yt[On("elementProperties")]=new Map,Yt[On("finalized")]=new Map,Lp?.({ReactiveElement:Yt}),(Vs.reactiveElementVersions??=[]).push("2.1.2");const Di=globalThis,or=e=>e,Rs=Di.trustedTypes,rr=Rs?Rs.createPolicy("lit-html",{createHTML:e=>e}):void 0,vc="$lit$",ot=`lit$${Math.random().toFixed(9).slice(2)}$`,yc="?"+ot,Rp=`<${yc}>`,Ct=document,zn=()=>Ct.createComment(""),Kn=e=>e===null||typeof e!="object"&&typeof e!="function",Oi=Array.isArray,Pp=e=>Oi(e)||typeof e?.[Symbol.iterator]=="function",Aa=`[
2
2
  \f\r]`,wn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,lr=/-->/g,cr=/>/g,mt=RegExp(`>|${Aa}(?:([^\\s"'>=/]+)(${Aa}*=${Aa}*(?:[^
3
- \f\r"'\`<>=]|("|')|))|$)`,"g"),dr=/'/g,ur=/"/g,bc=/^(?:script|style|textarea|title)$/i,Mp=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),r=Mp(1),dt=Symbol.for("lit-noChange"),h=Symbol.for("lit-nothing"),pr=new WeakMap,Tt=Et.createTreeWalker(Et,129);function wc(e,t){if(!Oi(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return rr!==void 0?rr.createHTML(t):t}const Dp=(e,t)=>{const n=e.length-1,s=[];let a,i=t===2?"<svg>":t===3?"<math>":"",o=wn;for(let l=0;l<n;l++){const c=e[l];let u,p,f=-1,m=0;for(;m<c.length&&(o.lastIndex=m,p=o.exec(c),p!==null);)m=o.lastIndex,o===wn?p[1]==="!--"?o=lr:p[1]!==void 0?o=cr:p[2]!==void 0?(bc.test(p[2])&&(a=RegExp("</"+p[2],"g")),o=mt):p[3]!==void 0&&(o=mt):o===mt?p[0]===">"?(o=a??wn,f=-1):p[1]===void 0?f=-2:(f=o.lastIndex-p[2].length,u=p[1],o=p[3]===void 0?mt:p[3]==='"'?ur:dr):o===ur||o===dr?o=mt:o===lr||o===cr?o=wn:(o=mt,a=void 0);const g=o===mt&&e[l+1].startsWith("/>")?" ":"";i+=o===wn?c+Pp:f>=0?(s.push(u),c.slice(0,f)+vc+c.slice(f)+ot+g):c+ot+(f===-2?l:g)}return[wc(e,i+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Wn{constructor({strings:t,_$litType$:n},s){let a;this.parts=[];let i=0,o=0;const l=t.length-1,c=this.parts,[u,p]=Dp(t,n);if(this.el=Wn.createElement(u,s),Tt.currentNode=this.el.content,n===2||n===3){const f=this.el.content.firstChild;f.replaceWith(...f.childNodes)}for(;(a=Tt.nextNode())!==null&&c.length<l;){if(a.nodeType===1){if(a.hasAttributes())for(const f of a.getAttributeNames())if(f.endsWith(vc)){const m=p[o++],g=a.getAttribute(f).split(ot),$=/([.?@])?(.*)/.exec(m);c.push({type:1,index:i,name:$[2],strings:g,ctor:$[1]==="."?Np:$[1]==="?"?Fp:$[1]==="@"?Bp:Qs}),a.removeAttribute(f)}else f.startsWith(ot)&&(c.push({type:6,index:i}),a.removeAttribute(f));if(bc.test(a.tagName)){const f=a.textContent.split(ot),m=f.length-1;if(m>0){a.textContent=Rs?Rs.emptyScript:"";for(let g=0;g<m;g++)a.append(f[g],zn()),Tt.nextNode(),c.push({type:2,index:++i});a.append(f[m],zn())}}}else if(a.nodeType===8)if(a.data===yc)c.push({type:2,index:i});else{let f=-1;for(;(f=a.data.indexOf(ot,f+1))!==-1;)c.push({type:7,index:i}),f+=ot.length-1}i++}}static createElement(t,n){const s=Et.createElement("template");return s.innerHTML=t,s}}function an(e,t,n=e,s){if(t===dt)return t;let a=s!==void 0?n._$Co?.[s]:n._$Cl;const i=Kn(t)?void 0:t._$litDirective$;return a?.constructor!==i&&(a?._$AO?.(!1),i===void 0?a=void 0:(a=new i(e),a._$AT(e,n,s)),s!==void 0?(n._$Co??=[])[s]=a:n._$Cl=a),a!==void 0&&(t=an(e,a._$AS(e,t.values),a,s)),t}class Op{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:s}=this._$AD,a=(t?.creationScope??Et).importNode(n,!0);Tt.currentNode=a;let i=Tt.nextNode(),o=0,l=0,c=s[0];for(;c!==void 0;){if(o===c.index){let u;c.type===2?u=new Gs(i,i.nextSibling,this,t):c.type===1?u=new c.ctor(i,c.name,c.strings,this,t):c.type===6&&(u=new Up(i,this,t)),this._$AV.push(u),c=s[++l]}o!==c?.index&&(i=Tt.nextNode(),o++)}return Tt.currentNode=Et,a}p(t){let n=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,n),n+=s.strings.length-2):s._$AI(t[n])),n++}}let Gs=class $c{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,s,a){this.type=2,this._$AH=h,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=s,this.options=a,this._$Cv=a?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=an(this,t,n),Kn(t)?t===h||t==null||t===""?(this._$AH!==h&&this._$AR(),this._$AH=h):t!==this._$AH&&t!==dt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ip(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!==h&&Kn(this._$AH)?this._$AA.nextSibling.data=t:this.T(Et.createTextNode(t)),this._$AH=t}$(t){const{values:n,_$litType$:s}=t,a=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Wn.createElement(wc(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===a)this._$AH.p(n);else{const i=new Op(a,this),o=i.u(this.options);i.p(n),this.T(o),this._$AH=i}}_$AC(t){let n=pr.get(t.strings);return n===void 0&&pr.set(t.strings,n=new Wn(t)),n}k(t){Oi(this._$AH)||(this._$AH=[],this._$AR());const n=this._$AH;let s,a=0;for(const i of t)a===n.length?n.push(s=new $c(this.O(zn()),this.O(zn()),this,this.options)):s=n[a],s._$AI(i),a++;a<n.length&&(this._$AR(s&&s._$AB.nextSibling,a),n.length=a)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){const s=or(t).nextSibling;or(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Qs=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,s,a,i){this.type=1,this._$AH=h,this._$AN=void 0,this.element=t,this.name=n,this._$AM=a,this.options=i,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=h}_$AI(t,n=this,s,a){const i=this.strings;let o=!1;if(i===void 0)t=an(this,t,n,0),o=!Kn(t)||t!==this._$AH&&t!==dt,o&&(this._$AH=t);else{const l=t;let c,u;for(t=i[0],c=0;c<i.length-1;c++)u=an(this,l[s+c],n,c),u===dt&&(u=this._$AH[c]),o||=!Kn(u)||u!==this._$AH[c],u===h?t=h:t!==h&&(t+=(u??"")+i[c+1]),this._$AH[c]=u}o&&!a&&this.j(t)}j(t){t===h?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Np=class extends Qs{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===h?void 0:t}},Fp=class extends Qs{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==h)}},Bp=class extends Qs{constructor(t,n,s,a,i){super(t,n,s,a,i),this.type=5}_$AI(t,n=this){if((t=an(this,t,n,0)??h)===dt)return;const s=this._$AH,a=t===h&&s!==h||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,i=t!==h&&(s===h||a);a&&this.element.removeEventListener(this.name,this,s),i&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Up=class{constructor(t,n,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=n,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){an(this,t)}};const zp={I:Gs},Kp=Di.litHtmlPolyfillSupport;Kp?.(Wn,Gs),(Di.litHtmlVersions??=[]).push("3.3.2");const Wp=(e,t,n)=>{const s=n?.renderBefore??t;let a=s._$litPart$;if(a===void 0){const i=n?.renderBefore??null;s._$litPart$=a=new Gs(t.insertBefore(zn(),i),i,void 0,n??{})}return a._$AI(e),a};const Ni=globalThis;let nn=class extends Jt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Wp(n,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return dt}};nn._$litElement$=!0,nn.finalized=!0,Ni.litElementHydrateSupport?.({LitElement:nn});const qp=Ni.litElementPolyfillSupport;qp?.({LitElement:nn});(Ni.litElementVersions??=[]).push("4.2.2");const kc=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const jp={attribute:!0,type:String,converter:Ls,reflect:!1,hasChanged:Mi},Hp=(e=jp,t,n)=>{const{kind:s,metadata:a}=n;let i=globalThis.litPropertyMetadata.get(a);if(i===void 0&&globalThis.litPropertyMetadata.set(a,i=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),i.set(n.name,e),s==="accessor"){const{name:o}=n;return{set(l){const c=t.get.call(this);t.set.call(this,l),this.requestUpdate(o,c,e,!0,l)},init(l){return l!==void 0&&this.C(o,void 0,e,l),l}}}if(s==="setter"){const{name:o}=n;return function(l){const c=this[o];t.call(this,l),this.requestUpdate(o,c,e,!0,l)}}throw Error("Unsupported decorator location: "+s)};function Jn(e){return(t,n)=>typeof n=="object"?Hp(e,t,n):((s,a,i)=>{const o=a.hasOwnProperty(i);return a.constructor.createProperty(i,s),o?Object.getOwnPropertyDescriptor(a,i):void 0})(e,t,n)}function w(e){return Jn({...e,state:!0,attribute:!1})}async function Me(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 Vp(e,t){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const n=await e.client.request("web.login.start",{force:t,timeoutMs:3e4});e.whatsappLoginMessage=n.message??null,e.whatsappLoginQrDataUrl=n.qrDataUrl??null,e.whatsappLoginConnected=null}catch(n){e.whatsappLoginMessage=String(n),e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Gp(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const t=await e.client.request("web.login.wait",{timeoutMs:12e4});e.whatsappLoginMessage=t.message??null,e.whatsappLoginConnected=t.connected??null,t.connected&&(e.whatsappLoginQrDataUrl=null)}catch(t){e.whatsappLoginMessage=String(t),e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Qp(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{await e.client.request("channels.logout",{channel:"whatsapp"}),e.whatsappLoginMessage="Logged out.",e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}catch(t){e.whatsappLoginMessage=String(t)}finally{e.whatsappBusy=!1}}}function Lt(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function on(e){return`${JSON.stringify(e,null,2).trimEnd()}
4
- `}function Sc(e,t,n){if(t.length===0)return;let s=e;for(let i=0;i<t.length-1;i+=1){const o=t[i],l=t[i+1];if(typeof o=="number"){if(!Array.isArray(s))return;s[o]==null&&(s[o]=typeof l=="number"?[]:{}),s=s[o]}else{if(typeof s!="object"||s==null)return;const c=s;c[o]==null&&(c[o]=typeof l=="number"?[]:{}),s=c[o]}}const a=t[t.length-1];if(typeof a=="number"){Array.isArray(s)&&(s[a]=n);return}typeof s=="object"&&s!=null&&(s[a]=n)}function Ac(e,t){if(t.length===0)return;let n=e;for(let a=0;a<t.length-1;a+=1){const i=t[a];if(typeof i=="number"){if(!Array.isArray(n))return;n=n[i]}else{if(typeof n!="object"||n==null)return;n=n[i]}if(n==null)return}const s=t[t.length-1];if(typeof s=="number"){Array.isArray(n)&&n.splice(s,1);return}typeof n=="object"&&n!=null&&delete n[s]}async function Ye(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});Jp(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function _c(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});Yp(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function Yp(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function Jp(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?on(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=on(e.configForm):e.configRaw=n,e.configValid=typeof t.valid=="boolean"?t.valid:null,e.configIssues=Array.isArray(t.issues)?t.issues:[],e.configFormDirty||(e.configForm=Lt(t.config??{}),e.configFormOriginal=Lt(t.config??{}),e.configRawOriginal=n)}async function Ps(e){if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const t=e.configFormMode==="form"&&e.configForm?on(e.configForm):e.configRaw,n=e.configSnapshot?.hash;if(!n){e.lastError="Config hash missing; reload and retry.";return}await e.client.request("config.set",{raw:t,baseHash:n}),e.configFormDirty=!1,await Ye(e)}catch(t){e.lastError=String(t)}finally{e.configSaving=!1}}}async function Xp(e){if(!(!e.client||!e.connected)){e.configApplying=!0,e.lastError=null;try{const t=e.configFormMode==="form"&&e.configForm?on(e.configForm):e.configRaw,n=e.configSnapshot?.hash;if(!n){e.lastError="Config hash missing; reload and retry.";return}await e.client.request("config.apply",{raw:t,baseHash:n,sessionKey:e.applySessionKey}),e.configFormDirty=!1,await Ye(e)}catch(t){e.lastError=String(t)}finally{e.configApplying=!1}}}async function hr(e){if(!(!e.client||!e.connected)){e.updateRunning=!0,e.lastError=null;try{await e.client.request("godmode.update.run",{})}catch(t){e.lastError=String(t)}finally{e.updateRunning=!1}}}function Zt(e,t,n){const s=Lt(e.configForm??e.configSnapshot?.config??{});Sc(s,t,n),e.configForm=s,e.configFormDirty=!0,e.configFormMode==="form"&&(e.configRaw=on(s))}function fr(e,t){const n=Lt(e.configForm??e.configSnapshot?.config??{});Ac(n,t),e.configForm=n,e.configFormDirty=!0,e.configFormMode==="form"&&(e.configRaw=on(n))}async function Zp(e,t,n){Zt(e,["agents","defaults","model","primary"],t),Zt(e,["agents","defaults","model","fallbacks"],n),await Ps(e)}function eh(e){const{values:t,original:n}=e;return t.name!==n.name||t.displayName!==n.displayName||t.about!==n.about||t.picture!==n.picture||t.banner!==n.banner||t.website!==n.website||t.nip05!==n.nip05||t.lud16!==n.lud16}function th(e){const{state:t,callbacks:n,accountId:s}=e,a=eh(t),i=(l,c,u={})=>{const{type:p="text",placeholder:f,maxLength:m,help:g}=u,$=t.values[l]??"",d=t.fieldErrors[l],v=`nostr-profile-${l}`;return p==="textarea"?r`
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),dr=/'/g,ur=/"/g,bc=/^(?:script|style|textarea|title)$/i,Ip=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),r=Ip(1),dt=Symbol.for("lit-noChange"),h=Symbol.for("lit-nothing"),pr=new WeakMap,_t=Ct.createTreeWalker(Ct,129);function wc(e,t){if(!Oi(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return rr!==void 0?rr.createHTML(t):t}const Mp=(e,t)=>{const n=e.length-1,s=[];let a,i=t===2?"<svg>":t===3?"<math>":"",o=wn;for(let l=0;l<n;l++){const c=e[l];let u,p,f=-1,m=0;for(;m<c.length&&(o.lastIndex=m,p=o.exec(c),p!==null);)m=o.lastIndex,o===wn?p[1]==="!--"?o=lr:p[1]!==void 0?o=cr:p[2]!==void 0?(bc.test(p[2])&&(a=RegExp("</"+p[2],"g")),o=mt):p[3]!==void 0&&(o=mt):o===mt?p[0]===">"?(o=a??wn,f=-1):p[1]===void 0?f=-2:(f=o.lastIndex-p[2].length,u=p[1],o=p[3]===void 0?mt:p[3]==='"'?ur:dr):o===ur||o===dr?o=mt:o===lr||o===cr?o=wn:(o=mt,a=void 0);const g=o===mt&&e[l+1].startsWith("/>")?" ":"";i+=o===wn?c+Rp:f>=0?(s.push(u),c.slice(0,f)+vc+c.slice(f)+ot+g):c+ot+(f===-2?l:g)}return[wc(e,i+(e[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Wn{constructor({strings:t,_$litType$:n},s){let a;this.parts=[];let i=0,o=0;const l=t.length-1,c=this.parts,[u,p]=Mp(t,n);if(this.el=Wn.createElement(u,s),_t.currentNode=this.el.content,n===2||n===3){const f=this.el.content.firstChild;f.replaceWith(...f.childNodes)}for(;(a=_t.nextNode())!==null&&c.length<l;){if(a.nodeType===1){if(a.hasAttributes())for(const f of a.getAttributeNames())if(f.endsWith(vc)){const m=p[o++],g=a.getAttribute(f).split(ot),$=/([.?@])?(.*)/.exec(m);c.push({type:1,index:i,name:$[2],strings:g,ctor:$[1]==="."?Op:$[1]==="?"?Np:$[1]==="@"?Fp:Qs}),a.removeAttribute(f)}else f.startsWith(ot)&&(c.push({type:6,index:i}),a.removeAttribute(f));if(bc.test(a.tagName)){const f=a.textContent.split(ot),m=f.length-1;if(m>0){a.textContent=Rs?Rs.emptyScript:"";for(let g=0;g<m;g++)a.append(f[g],zn()),_t.nextNode(),c.push({type:2,index:++i});a.append(f[m],zn())}}}else if(a.nodeType===8)if(a.data===yc)c.push({type:2,index:i});else{let f=-1;for(;(f=a.data.indexOf(ot,f+1))!==-1;)c.push({type:7,index:i}),f+=ot.length-1}i++}}static createElement(t,n){const s=Ct.createElement("template");return s.innerHTML=t,s}}function an(e,t,n=e,s){if(t===dt)return t;let a=s!==void 0?n._$Co?.[s]:n._$Cl;const i=Kn(t)?void 0:t._$litDirective$;return a?.constructor!==i&&(a?._$AO?.(!1),i===void 0?a=void 0:(a=new i(e),a._$AT(e,n,s)),s!==void 0?(n._$Co??=[])[s]=a:n._$Cl=a),a!==void 0&&(t=an(e,a._$AS(e,t.values),a,s)),t}class Dp{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:s}=this._$AD,a=(t?.creationScope??Ct).importNode(n,!0);_t.currentNode=a;let i=_t.nextNode(),o=0,l=0,c=s[0];for(;c!==void 0;){if(o===c.index){let u;c.type===2?u=new Gs(i,i.nextSibling,this,t):c.type===1?u=new c.ctor(i,c.name,c.strings,this,t):c.type===6&&(u=new Bp(i,this,t)),this._$AV.push(u),c=s[++l]}o!==c?.index&&(i=_t.nextNode(),o++)}return _t.currentNode=Ct,a}p(t){let n=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,n),n+=s.strings.length-2):s._$AI(t[n])),n++}}let Gs=class $c{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,s,a){this.type=2,this._$AH=h,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=s,this.options=a,this._$Cv=a?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=an(this,t,n),Kn(t)?t===h||t==null||t===""?(this._$AH!==h&&this._$AR(),this._$AH=h):t!==this._$AH&&t!==dt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Pp(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!==h&&Kn(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ct.createTextNode(t)),this._$AH=t}$(t){const{values:n,_$litType$:s}=t,a=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Wn.createElement(wc(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===a)this._$AH.p(n);else{const i=new Dp(a,this),o=i.u(this.options);i.p(n),this.T(o),this._$AH=i}}_$AC(t){let n=pr.get(t.strings);return n===void 0&&pr.set(t.strings,n=new Wn(t)),n}k(t){Oi(this._$AH)||(this._$AH=[],this._$AR());const n=this._$AH;let s,a=0;for(const i of t)a===n.length?n.push(s=new $c(this.O(zn()),this.O(zn()),this,this.options)):s=n[a],s._$AI(i),a++;a<n.length&&(this._$AR(s&&s._$AB.nextSibling,a),n.length=a)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){const s=or(t).nextSibling;or(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Qs=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,s,a,i){this.type=1,this._$AH=h,this._$AN=void 0,this.element=t,this.name=n,this._$AM=a,this.options=i,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=h}_$AI(t,n=this,s,a){const i=this.strings;let o=!1;if(i===void 0)t=an(this,t,n,0),o=!Kn(t)||t!==this._$AH&&t!==dt,o&&(this._$AH=t);else{const l=t;let c,u;for(t=i[0],c=0;c<i.length-1;c++)u=an(this,l[s+c],n,c),u===dt&&(u=this._$AH[c]),o||=!Kn(u)||u!==this._$AH[c],u===h?t=h:t!==h&&(t+=(u??"")+i[c+1]),this._$AH[c]=u}o&&!a&&this.j(t)}j(t){t===h?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Op=class extends Qs{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===h?void 0:t}},Np=class extends Qs{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==h)}},Fp=class extends Qs{constructor(t,n,s,a,i){super(t,n,s,a,i),this.type=5}_$AI(t,n=this){if((t=an(this,t,n,0)??h)===dt)return;const s=this._$AH,a=t===h&&s!==h||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,i=t!==h&&(s===h||a);a&&this.element.removeEventListener(this.name,this,s),i&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Bp=class{constructor(t,n,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=n,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){an(this,t)}};const Up={I:Gs},zp=Di.litHtmlPolyfillSupport;zp?.(Wn,Gs),(Di.litHtmlVersions??=[]).push("3.3.2");const Kp=(e,t,n)=>{const s=n?.renderBefore??t;let a=s._$litPart$;if(a===void 0){const i=n?.renderBefore??null;s._$litPart$=a=new Gs(t.insertBefore(zn(),i),i,void 0,n??{})}return a._$AI(e),a};const Ni=globalThis;let nn=class extends Yt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Kp(n,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return dt}};nn._$litElement$=!0,nn.finalized=!0,Ni.litElementHydrateSupport?.({LitElement:nn});const Wp=Ni.litElementPolyfillSupport;Wp?.({LitElement:nn});(Ni.litElementVersions??=[]).push("4.2.2");const kc=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const qp={attribute:!0,type:String,converter:Ls,reflect:!1,hasChanged:Mi},jp=(e=qp,t,n)=>{const{kind:s,metadata:a}=n;let i=globalThis.litPropertyMetadata.get(a);if(i===void 0&&globalThis.litPropertyMetadata.set(a,i=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),i.set(n.name,e),s==="accessor"){const{name:o}=n;return{set(l){const c=t.get.call(this);t.set.call(this,l),this.requestUpdate(o,c,e,!0,l)},init(l){return l!==void 0&&this.C(o,void 0,e,l),l}}}if(s==="setter"){const{name:o}=n;return function(l){const c=this[o];t.call(this,l),this.requestUpdate(o,c,e,!0,l)}}throw Error("Unsupported decorator location: "+s)};function Jn(e){return(t,n)=>typeof n=="object"?jp(e,t,n):((s,a,i)=>{const o=a.hasOwnProperty(i);return a.constructor.createProperty(i,s),o?Object.getOwnPropertyDescriptor(a,i):void 0})(e,t,n)}function w(e){return Jn({...e,state:!0,attribute:!1})}async function Me(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 Hp(e,t){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const n=await e.client.request("web.login.start",{force:t,timeoutMs:3e4});e.whatsappLoginMessage=n.message??null,e.whatsappLoginQrDataUrl=n.qrDataUrl??null,e.whatsappLoginConnected=null}catch(n){e.whatsappLoginMessage=String(n),e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Vp(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const t=await e.client.request("web.login.wait",{timeoutMs:12e4});e.whatsappLoginMessage=t.message??null,e.whatsappLoginConnected=t.connected??null,t.connected&&(e.whatsappLoginQrDataUrl=null)}catch(t){e.whatsappLoginMessage=String(t),e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function Gp(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{await e.client.request("channels.logout",{channel:"whatsapp"}),e.whatsappLoginMessage="Logged out.",e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}catch(t){e.whatsappLoginMessage=String(t)}finally{e.whatsappBusy=!1}}}function Et(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function on(e){return`${JSON.stringify(e,null,2).trimEnd()}
4
+ `}function Sc(e,t,n){if(t.length===0)return;let s=e;for(let i=0;i<t.length-1;i+=1){const o=t[i],l=t[i+1];if(typeof o=="number"){if(!Array.isArray(s))return;s[o]==null&&(s[o]=typeof l=="number"?[]:{}),s=s[o]}else{if(typeof s!="object"||s==null)return;const c=s;c[o]==null&&(c[o]=typeof l=="number"?[]:{}),s=c[o]}}const a=t[t.length-1];if(typeof a=="number"){Array.isArray(s)&&(s[a]=n);return}typeof s=="object"&&s!=null&&(s[a]=n)}function Ac(e,t){if(t.length===0)return;let n=e;for(let a=0;a<t.length-1;a+=1){const i=t[a];if(typeof i=="number"){if(!Array.isArray(n))return;n=n[i]}else{if(typeof n!="object"||n==null)return;n=n[i]}if(n==null)return}const s=t[t.length-1];if(typeof s=="number"){Array.isArray(n)&&n.splice(s,1);return}typeof n=="object"&&n!=null&&delete n[s]}async function Ye(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});Yp(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function _c(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});Qp(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function Qp(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function Yp(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?on(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=on(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=Et(t.config??{}),e.configFormOriginal=Et(t.config??{}),e.configRawOriginal=n)}async function Ps(e){if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const t=e.configFormMode==="form"&&e.configForm?on(e.configForm):e.configRaw,n=e.configSnapshot?.hash;if(!n){e.lastError="Config hash missing; reload and retry.";return}await e.client.request("config.set",{raw:t,baseHash:n}),e.configFormDirty=!1,await Ye(e)}catch(t){e.lastError=String(t)}finally{e.configSaving=!1}}}async function Jp(e){if(!(!e.client||!e.connected)){e.configApplying=!0,e.lastError=null;try{const t=e.configFormMode==="form"&&e.configForm?on(e.configForm):e.configRaw,n=e.configSnapshot?.hash;if(!n){e.lastError="Config hash missing; reload and retry.";return}await e.client.request("config.apply",{raw:t,baseHash:n,sessionKey:e.applySessionKey}),e.configFormDirty=!1,await Ye(e)}catch(t){e.lastError=String(t)}finally{e.configApplying=!1}}}async function hr(e){if(!(!e.client||!e.connected)){e.updateRunning=!0,e.lastError=null;try{await e.client.request("godmode.update.run",{})}catch(t){e.lastError=String(t)}finally{e.updateRunning=!1}}}function Zt(e,t,n){const s=Et(e.configForm??e.configSnapshot?.config??{});Sc(s,t,n),e.configForm=s,e.configFormDirty=!0,e.configFormMode==="form"&&(e.configRaw=on(s))}function fr(e,t){const n=Et(e.configForm??e.configSnapshot?.config??{});Ac(n,t),e.configForm=n,e.configFormDirty=!0,e.configFormMode==="form"&&(e.configRaw=on(n))}async function Xp(e,t,n){Zt(e,["agents","defaults","model","primary"],t),Zt(e,["agents","defaults","model","fallbacks"],n),await Ps(e)}function Zp(e){const{values:t,original:n}=e;return t.name!==n.name||t.displayName!==n.displayName||t.about!==n.about||t.picture!==n.picture||t.banner!==n.banner||t.website!==n.website||t.nip05!==n.nip05||t.lud16!==n.lud16}function eh(e){const{state:t,callbacks:n,accountId:s}=e,a=Zp(t),i=(l,c,u={})=>{const{type:p="text",placeholder:f,maxLength:m,help:g}=u,$=t.values[l]??"",d=t.fieldErrors[l],v=`nostr-profile-${l}`;return p==="textarea"?r`
5
5
  <div class="form-field" style="margin-bottom: 12px;">
6
6
  <label for="${v}" style="display: block; margin-bottom: 4px; font-weight: 500;">
7
7
  ${c}
@@ -121,18 +121,18 @@
121
121
  </div>
122
122
  `:h}
123
123
  </div>
124
- `}function nh(e){const t={name:e?.name??"",displayName:e?.displayName??"",about:e?.about??"",picture:e?.picture??"",banner:e?.banner??"",website:e?.website??"",nip05:e?.nip05??"",lud16:e?.lud16??""};return{values:t,original:{...t},saving:!1,importing:!1,error:null,success:null,fieldErrors:{},showAdvanced:!!(e?.banner||e?.website||e?.nip05||e?.lud16)}}async function sh(e,t){await Vp(e,t),await Me(e,!0)}async function ah(e){await Gp(e),await Me(e,!0)}async function ih(e){await Qp(e),await Me(e,!0)}async function oh(e){await Ps(e),await Ye(e),await Me(e,!0)}async function rh(e){await Ye(e),await Me(e,!0)}function lh(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[s,...a]=n.split(":");if(!s||a.length===0)continue;const i=s.trim(),o=a.join(":").trim();i&&o&&(t[i]=o)}return t}function Tc(e){return(e.channelsSnapshot?.channelAccounts?.nostr??[])[0]?.accountId??e.nostrProfileAccountId??"default"}function xc(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function ch(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=nh(n??void 0)}function dh(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function uh(e,t,n){const s=e.nostrProfileFormState;s&&(e.nostrProfileFormState={...s,values:{...s.values,[t]:n},fieldErrors:{...s.fieldErrors,[t]:""}})}function ph(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function hh(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Tc(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const s=await fetch(xc(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),a=await s.json().catch(()=>null);if(!s.ok||a?.ok===!1||!a){const i=a?.error??`Profile update failed (${s.status})`;e.nostrProfileFormState={...t,saving:!1,error:i,success:null,fieldErrors:lh(a?.details)};return}if(!a.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 Me(e,!0)}catch(s){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(s)}`,success:null}}}async function fh(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Tc(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const s=await fetch(xc(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),a=await s.json().catch(()=>null);if(!s.ok||a?.ok===!1||!a){const c=a?.error??`Profile import failed (${s.status})`;e.nostrProfileFormState={...t,importing:!1,error:c,success:null};return}const i=a.merged??a.imported??null,o=i?{...t.values,...i}:t.values,l=!!(o.banner||o.website||o.nip05||o.lud16);e.nostrProfileFormState={...t,importing:!1,values:o,error:null,success:a.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:l},a.saved&&await Me(e,!0)}catch(s){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(s)}`,success:null}}}function Cc(e){const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const s=n[1]?.trim(),a=n.slice(2).join(":");return!s||!a?null:{agentId:s,rest:a}}const gh=80;function rn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=()=>{const s=e.querySelector(".chat-thread");if(s){const a=getComputedStyle(s).overflowY;if(a==="auto"||a==="scroll"||s.scrollHeight-s.clientHeight>1)return s}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{e.chatScrollFrame=requestAnimationFrame(()=>{e.chatScrollFrame=null;const s=n();if(!s)return;s.scrollHeight-s.scrollTop-s.clientHeight;const a=t&&!e.chatHasAutoScrolled;if(!(a||e.chatUserNearBottom)){e.chatNewMessagesBelow=!0;return}a&&(e.chatHasAutoScrolled=!0),e.chatIsAutoScrolling=!0,s.scrollTop=s.scrollHeight,e.chatNewMessagesBelow=!1,requestAnimationFrame(()=>{e.chatIsAutoScrolling=!1});const o=a?150:120;e.chatScrollTimeout=window.setTimeout(()=>{e.chatScrollTimeout=null;const l=n();!l||!(a||e.chatUserNearBottom)||(e.chatIsAutoScrolling=!0,l.scrollTop=l.scrollHeight,requestAnimationFrame(()=>{e.chatIsAutoScrolling=!1}))},o)})})}function Ec(e,t=!1){e.logsScrollFrame&&cancelAnimationFrame(e.logsScrollFrame),e.updateComplete.then(()=>{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;(t||s<80)&&(n.scrollTop=n.scrollHeight)})})}function mh(e,t){const n=t.currentTarget;if(!n||e.chatIsAutoScrolling)return;n.scrollHeight-n.scrollTop-n.clientHeight<gh?(e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1):e.chatUserNearBottom=!1}function vh(e,t){const n=t.currentTarget;if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;e.logsAtBottom=s<80}function Lc(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1}function yh(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
124
+ `}function th(e){const t={name:e?.name??"",displayName:e?.displayName??"",about:e?.about??"",picture:e?.picture??"",banner:e?.banner??"",website:e?.website??"",nip05:e?.nip05??"",lud16:e?.lud16??""};return{values:t,original:{...t},saving:!1,importing:!1,error:null,success:null,fieldErrors:{},showAdvanced:!!(e?.banner||e?.website||e?.nip05||e?.lud16)}}async function nh(e,t){await Hp(e,t),await Me(e,!0)}async function sh(e){await Vp(e),await Me(e,!0)}async function ah(e){await Gp(e),await Me(e,!0)}async function ih(e){await Ps(e),await Ye(e),await Me(e,!0)}async function oh(e){await Ye(e),await Me(e,!0)}function rh(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[s,...a]=n.split(":");if(!s||a.length===0)continue;const i=s.trim(),o=a.join(":").trim();i&&o&&(t[i]=o)}return t}function Tc(e){return(e.channelsSnapshot?.channelAccounts?.nostr??[])[0]?.accountId??e.nostrProfileAccountId??"default"}function xc(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function lh(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=th(n??void 0)}function ch(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function dh(e,t,n){const s=e.nostrProfileFormState;s&&(e.nostrProfileFormState={...s,values:{...s.values,[t]:n},fieldErrors:{...s.fieldErrors,[t]:""}})}function uh(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function ph(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Tc(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const s=await fetch(xc(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),a=await s.json().catch(()=>null);if(!s.ok||a?.ok===!1||!a){const i=a?.error??`Profile update failed (${s.status})`;e.nostrProfileFormState={...t,saving:!1,error:i,success:null,fieldErrors:rh(a?.details)};return}if(!a.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 Me(e,!0)}catch(s){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(s)}`,success:null}}}async function hh(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Tc(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const s=await fetch(xc(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),a=await s.json().catch(()=>null);if(!s.ok||a?.ok===!1||!a){const c=a?.error??`Profile import failed (${s.status})`;e.nostrProfileFormState={...t,importing:!1,error:c,success:null};return}const i=a.merged??a.imported??null,o=i?{...t.values,...i}:t.values,l=!!(o.banner||o.website||o.nip05||o.lud16);e.nostrProfileFormState={...t,importing:!1,values:o,error:null,success:a.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:l},a.saved&&await Me(e,!0)}catch(s){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(s)}`,success:null}}}function Cc(e){const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const s=n[1]?.trim(),a=n.slice(2).join(":");return!s||!a?null:{agentId:s,rest:a}}const fh=80;function rn(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=()=>{const s=e.querySelector(".chat-thread");if(s){const a=getComputedStyle(s).overflowY;if(a==="auto"||a==="scroll"||s.scrollHeight-s.clientHeight>1)return s}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{e.chatScrollFrame=requestAnimationFrame(()=>{e.chatScrollFrame=null;const s=n();if(!s)return;s.scrollHeight-s.scrollTop-s.clientHeight;const a=t&&!e.chatHasAutoScrolled;if(!(a||e.chatUserNearBottom)){e.chatNewMessagesBelow=!0;return}a&&(e.chatHasAutoScrolled=!0),e.chatIsAutoScrolling=!0,s.scrollTop=s.scrollHeight,e.chatNewMessagesBelow=!1,requestAnimationFrame(()=>{e.chatIsAutoScrolling=!1});const o=a?150:120;e.chatScrollTimeout=window.setTimeout(()=>{e.chatScrollTimeout=null;const l=n();!l||!(a||e.chatUserNearBottom)||(e.chatIsAutoScrolling=!0,l.scrollTop=l.scrollHeight,requestAnimationFrame(()=>{e.chatIsAutoScrolling=!1}))},o)})})}function Ec(e,t=!1){e.logsScrollFrame&&cancelAnimationFrame(e.logsScrollFrame),e.updateComplete.then(()=>{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;(t||s<80)&&(n.scrollTop=n.scrollHeight)})})}function gh(e,t){const n=t.currentTarget;if(!n||e.chatIsAutoScrolling)return;n.scrollHeight-n.scrollTop-n.clientHeight<fh?(e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1):e.chatUserNearBottom=!1}function mh(e,t){const n=t.currentTarget;if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;e.logsAtBottom=s<80}function Lc(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1}function vh(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
125
125
  `)}
126
- `],{type:"text/plain"}),s=URL.createObjectURL(n),a=document.createElement("a"),i=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");a.href=s,a.download=`godmode-logs-${t}-${i}.log`,a.click(),URL.revokeObjectURL(s)}function bh(e){if(typeof ResizeObserver>"u")return;const t=e.querySelector(".topbar");if(!t)return;const n=()=>{const{height:s}=t.getBoundingClientRect();e.style.setProperty("--topbar-height",`${s}px`)};n(),e.topbarObserver=new ResizeObserver(()=>n()),e.topbarObserver.observe(t)}const wh=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,hs=/<\s*\/?\s*final\b[^>]*>/gi,gr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function $h(e,t){return e.trimStart()}function kh(e,t){if(!e||!wh.test(e))return e;let n=e;hs.test(n)?(hs.lastIndex=0,n=n.replace(hs,"")):hs.lastIndex=0,gr.lastIndex=0;let s="",a=0,i=!1;for(const o of n.matchAll(gr)){const l=o.index??0,c=o[1]==="/";i?c&&(i=!1):(s+=n.slice(a,l),c||(i=!0)),a=l+o[0].length}return s+=n.slice(a),$h(s)}function qn(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString()}function z(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0)return"just now";const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const s=Math.round(n/60);if(s<60)return`${s}m ago`;const a=Math.round(s/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Sh(e){if(!e&&e!==0)return"";const t=Date.now()-e;if(t<0)return"now";const n=Math.round(t/1e3);if(n<60)return"now";const s=Math.round(n/60);if(s<60)return`${s}m`;const a=Math.round(s/60);return a<24?`${a}h`:`${Math.round(a/24)}d`}function Fi(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 s=Math.round(n/60);return s<48?`${s}h`:`${Math.round(s/24)}d`}function ai(e){return!e||e.length===0?"none":e.filter(t=>!!(t&&t.trim())).join(", ")}function ii(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Rc(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 Is(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function re(e){const t=e??new Date,n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${n}-${s}-${a}`}function _a(e){return kh(e)}const mr=50,Ah=80,_h=12e4;function oe(e,t){if(!e)return"";const n=e.trim().replace(/\n/g," ");return n.length<=t?n:n.slice(0,t-1)+"…"}function ie(e){return typeof e=="string"?e:e==null?"":JSON.stringify(e)}function vr(e,t){if(!t||typeof t!="object")return"";const n=t;switch(e.toLowerCase()){case"exec":return n.command?`\`${oe(ie(n.command),60)}\``:"";case"read":return n.path||n.file_path?`\`${oe(ie(n.path||n.file_path),50)}\``:"";case"write":return n.path||n.file_path?`→ \`${oe(ie(n.path||n.file_path),50)}\``:"";case"edit":return n.path||n.file_path?`\`${oe(ie(n.path||n.file_path),50)}\``:"";case"web_search":return n.query?`"${oe(ie(n.query),45)}"`:"";case"web_fetch":try{const u=new URL(ie(n.url));return u.hostname+(u.pathname!=="/"?u.pathname.slice(0,30):"")}catch{return oe(ie(n.url||""),50)}case"memory_search":return n.query?`"${oe(ie(n.query),45)}"`:"";case"browser":const s=ie(n.action),a=n.ref?` #${ie(n.ref)}`:"",i=n.targetUrl?` ${oe(ie(n.targetUrl),30)}`:"";return`${s}${a}${i}`;case"message":return n.action?`${ie(n.action)}${n.target?` → ${oe(ie(n.target),25)}`:""}`:"";case"sessions_spawn":return n.task?`"${oe(ie(n.task),40)}"`:"";case"cron":return n.action?ie(n.action):"";case"files_read":return n.fileId?`file:${oe(ie(n.fileId),20)}`:"";case"image":return n.image?oe(ie(n.image),40):"";default:const o=Object.keys(n).filter(u=>!["timeout","timeoutMs"].includes(u));if(o.length===0)return"";const l=o[0],c=n[l];return typeof c=="string"?`${l}: ${oe(c,35)}`:""}}function yr(e,t){if(!t)return"";const n=e.toLowerCase(),s=t.split(`
127
- `),a=s.length,i=t.length;if(["read","files_read"].includes(n))return`${i.toLocaleString()} chars${a>1?`, ${a} lines`:""}`;if(n==="exec")return a>1?`${a} lines`:oe(s[0],50);if(["web_search","memory_search"].includes(n))try{const o=JSON.parse(t),l=o.results?.length??o.count??0;return`${l} result${l!==1?"s":""}`}catch{return oe(t,40)}return n==="browser"?t.includes("snapshot")?"snapshot captured":t.includes("success")?"success":oe(t,40):i>100?`${i.toLocaleString()} chars`:oe(t,50)}function br(e){if(!e)return!0;const t=e.toLowerCase();return!(t.includes("error:")||t.includes("failed")||t.includes("exception")||t.includes("not found"))}function Th(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.text=="string")return t.text;const n=t.content;if(!Array.isArray(n))return null;const s=n.map(a=>{if(!a||typeof a!="object")return null;const i=a;return i.type==="text"&&typeof i.text=="string"?i.text:null}).filter(a=>!!a);return s.length===0?null:s.join(`
128
- `)}function wr(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=Th(e);let n;if(typeof e=="string")n=e;else if(t)n=t;else try{n=JSON.stringify(e,null,2)}catch{n=typeof e=="object"?"[object]":String(e)}const s=Rc(n,_h);return s.truncated?`${s.text}
126
+ `],{type:"text/plain"}),s=URL.createObjectURL(n),a=document.createElement("a"),i=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");a.href=s,a.download=`godmode-logs-${t}-${i}.log`,a.click(),URL.revokeObjectURL(s)}function yh(e){if(typeof ResizeObserver>"u")return;const t=e.querySelector(".topbar");if(!t)return;const n=()=>{const{height:s}=t.getBoundingClientRect();e.style.setProperty("--topbar-height",`${s}px`)};n(),e.topbarObserver=new ResizeObserver(()=>n()),e.topbarObserver.observe(t)}const bh=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,hs=/<\s*\/?\s*final\b[^>]*>/gi,gr=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function wh(e,t){return e.trimStart()}function $h(e,t){if(!e||!bh.test(e))return e;let n=e;hs.test(n)?(hs.lastIndex=0,n=n.replace(hs,"")):hs.lastIndex=0,gr.lastIndex=0;let s="",a=0,i=!1;for(const o of n.matchAll(gr)){const l=o.index??0,c=o[1]==="/";i?c&&(i=!1):(s+=n.slice(a,l),c||(i=!0)),a=l+o[0].length}return s+=n.slice(a),wh(s)}function qn(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString()}function z(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0)return"just now";const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const s=Math.round(n/60);if(s<60)return`${s}m ago`;const a=Math.round(s/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function kh(e){if(!e&&e!==0)return"";const t=Date.now()-e;if(t<0)return"now";const n=Math.round(t/1e3);if(n<60)return"now";const s=Math.round(n/60);if(s<60)return`${s}m`;const a=Math.round(s/60);return a<24?`${a}h`:`${Math.round(a/24)}d`}function Fi(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 s=Math.round(n/60);return s<48?`${s}h`:`${Math.round(s/24)}d`}function ai(e){return!e||e.length===0?"none":e.filter(t=>!!(t&&t.trim())).join(", ")}function ii(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Rc(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 Is(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function re(e){const t=e??new Date,n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${n}-${s}-${a}`}function _a(e){return $h(e)}const mr=50,Sh=80,Ah=12e4;function oe(e,t){if(!e)return"";const n=e.trim().replace(/\n/g," ");return n.length<=t?n:n.slice(0,t-1)+"…"}function ie(e){return typeof e=="string"?e:e==null?"":JSON.stringify(e)}function vr(e,t){if(!t||typeof t!="object")return"";const n=t;switch(e.toLowerCase()){case"exec":return n.command?`\`${oe(ie(n.command),60)}\``:"";case"read":return n.path||n.file_path?`\`${oe(ie(n.path||n.file_path),50)}\``:"";case"write":return n.path||n.file_path?`→ \`${oe(ie(n.path||n.file_path),50)}\``:"";case"edit":return n.path||n.file_path?`\`${oe(ie(n.path||n.file_path),50)}\``:"";case"web_search":return n.query?`"${oe(ie(n.query),45)}"`:"";case"web_fetch":try{const u=new URL(ie(n.url));return u.hostname+(u.pathname!=="/"?u.pathname.slice(0,30):"")}catch{return oe(ie(n.url||""),50)}case"memory_search":return n.query?`"${oe(ie(n.query),45)}"`:"";case"browser":const s=ie(n.action),a=n.ref?` #${ie(n.ref)}`:"",i=n.targetUrl?` ${oe(ie(n.targetUrl),30)}`:"";return`${s}${a}${i}`;case"message":return n.action?`${ie(n.action)}${n.target?` → ${oe(ie(n.target),25)}`:""}`:"";case"sessions_spawn":return n.task?`"${oe(ie(n.task),40)}"`:"";case"cron":return n.action?ie(n.action):"";case"files_read":return n.fileId?`file:${oe(ie(n.fileId),20)}`:"";case"image":return n.image?oe(ie(n.image),40):"";default:const o=Object.keys(n).filter(u=>!["timeout","timeoutMs"].includes(u));if(o.length===0)return"";const l=o[0],c=n[l];return typeof c=="string"?`${l}: ${oe(c,35)}`:""}}function yr(e,t){if(!t)return"";const n=e.toLowerCase(),s=t.split(`
127
+ `),a=s.length,i=t.length;if(["read","files_read"].includes(n))return`${i.toLocaleString()} chars${a>1?`, ${a} lines`:""}`;if(n==="exec")return a>1?`${a} lines`:oe(s[0],50);if(["web_search","memory_search"].includes(n))try{const o=JSON.parse(t),l=o.results?.length??o.count??0;return`${l} result${l!==1?"s":""}`}catch{return oe(t,40)}return n==="browser"?t.includes("snapshot")?"snapshot captured":t.includes("success")?"success":oe(t,40):i>100?`${i.toLocaleString()} chars`:oe(t,50)}function br(e){if(!e)return!0;const t=e.toLowerCase();return!(t.includes("error:")||t.includes("failed")||t.includes("exception")||t.includes("not found"))}function _h(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 s=n.map(a=>{if(!a||typeof a!="object")return null;const i=a;return i.type==="text"&&typeof i.text=="string"?i.text:null}).filter(a=>!!a);return s.length===0?null:s.join(`
128
+ `)}function wr(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=_h(e);let n;if(typeof e=="string")n=e;else if(t)n=t;else try{n=JSON.stringify(e,null,2)}catch{n=typeof e=="object"?"[object]":String(e)}const s=Rc(n,Ah);return s.truncated?`${s.text}
129
129
 
130
- … truncated (${s.total} chars, showing first ${s.text.length}).`:s.text}function xh(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 Ch(e){if(e.toolStreamOrder.length<=mr)return;const t=e.toolStreamOrder.length-mr,n=e.toolStreamOrder.splice(0,t);for(const s of n)e.toolStreamById.delete(s)}function Eh(e){e.chatToolMessages=e.toolStreamOrder.map(t=>e.toolStreamById.get(t)?.message).filter(t=>!!t)}function oi(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Eh(e)}function Lh(e,t=!1){if(t){oi(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>oi(e),Ah))}function Bi(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],e.currentToolName=null,e.currentToolInfo=null;const t=e;t.compactionStatus&&(t.compactionStatus=null),t.compactionClearTimer!=null&&(window.clearTimeout(t.compactionClearTimer),t.compactionClearTimer=null),oi(e)}const Rh=5e3;function Ph(e,t){const n=t.data??{},s=typeof n.phase=="string"?n.phase:"";e.compactionClearTimer!=null&&(window.clearTimeout(e.compactionClearTimer),e.compactionClearTimer=null),s==="start"?e.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null}:s==="end"&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus?.startedAt??null,completedAt:Date.now()},e.compactionClearTimer=window.setTimeout(()=>{e.compactionStatus=null,e.compactionClearTimer=null},Rh))}function Ih(e,t){if(!t)return;if(t.stream==="compaction"){Ph(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 s=t.data??{},a=typeof s.toolCallId=="string"?s.toolCallId:"";if(!a)return;const i=typeof s.name=="string"?s.name:"tool",o=typeof s.phase=="string"?s.phase:"",l=o==="start"?s.args:void 0,c=o==="update"?wr(s.partialResult):o==="result"?wr(s.result):void 0,u=Date.now();let p=e.toolStreamById.get(a);p?(p.name=i,l!==void 0&&(p.args=l,p.displayArgs=vr(i,l)),c!==void 0&&(p.output=c,p.resultSummary=yr(i,c),p.success=br(c)),p.updatedAt=u):(p={toolCallId:a,runId:t.runId,sessionKey:n,name:i,args:l,output:c,startedAt:typeof t.ts=="number"?t.ts:u,updatedAt:u,message:{},displayArgs:l?vr(i,l):void 0},e.toolStreamById.set(a,p),e.toolStreamOrder.push(a)),o==="start"?(e.currentToolName=i,e.currentToolInfo={name:i,details:p.displayArgs||void 0,startedAt:p.startedAt}):o==="result"&&(e.currentToolName=null,e.currentToolInfo=null,p.completedAt=u,p.resultSummary=yr(i,p.output),p.success=br(p.output)),p.message=xh(p),Ch(e),Lh(e,o==="result")}const Ui={CHILD:2},zi=e=>(...t)=>({_$litDirective$:e,values:t});let Ki=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,n,s){this._$Ct=t,this._$AM=n,this._$Ci=s}_$AS(t,n){return this.update(t,n)}update(t,n){return this.render(...n)}};class ri extends Ki{constructor(t){if(super(t),this.it=h,t.type!==Ui.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===h||t==null)return this._t=void 0,this.it=t;if(t===dt)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:[]}}}ri.directiveName="unsafeHTML",ri.resultType=1;const ke=zi(ri);const{entries:Pc,setPrototypeOf:$r,isFrozen:Mh,getPrototypeOf:Dh,getOwnPropertyDescriptor:Oh}=Object;let{freeze:fe,seal:Ce,create:li}=Object,{apply:ci,construct:di}=typeof Reflect<"u"&&Reflect;fe||(fe=function(t){return t});Ce||(Ce=function(t){return t});ci||(ci=function(t,n){for(var s=arguments.length,a=new Array(s>2?s-2:0),i=2;i<s;i++)a[i-2]=arguments[i];return t.apply(n,a)});di||(di=function(t){for(var n=arguments.length,s=new Array(n>1?n-1:0),a=1;a<n;a++)s[a-1]=arguments[a];return new t(...s)});const fs=ge(Array.prototype.forEach),Nh=ge(Array.prototype.lastIndexOf),kr=ge(Array.prototype.pop),$n=ge(Array.prototype.push),Fh=ge(Array.prototype.splice),ks=ge(String.prototype.toLowerCase),Ta=ge(String.prototype.toString),xa=ge(String.prototype.match),kn=ge(String.prototype.replace),Bh=ge(String.prototype.indexOf),Uh=ge(String.prototype.trim),Ee=ge(Object.prototype.hasOwnProperty),ue=ge(RegExp.prototype.test),Sn=zh(TypeError);function ge(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),a=1;a<n;a++)s[a-1]=arguments[a];return ci(e,t,s)}}function zh(e){return function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return di(e,n)}}function U(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ks;$r&&$r(e,null);let s=t.length;for(;s--;){let a=t[s];if(typeof a=="string"){const i=n(a);i!==a&&(Mh(t)||(t[s]=i),a=i)}e[a]=!0}return e}function Kh(e){for(let t=0;t<e.length;t++)Ee(e,t)||(e[t]=null);return e}function Be(e){const t=li(null);for(const[n,s]of Pc(e))Ee(e,n)&&(Array.isArray(s)?t[n]=Kh(s):s&&typeof s=="object"&&s.constructor===Object?t[n]=Be(s):t[n]=s);return t}function An(e,t){for(;e!==null;){const s=Oh(e,t);if(s){if(s.get)return ge(s.get);if(typeof s.value=="function")return ge(s.value)}e=Dh(e)}function n(){return null}return n}const Sr=fe(["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"]),Ca=fe(["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"]),Ea=fe(["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"]),Wh=fe(["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"]),La=fe(["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"]),qh=fe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ar=fe(["#text"]),_r=fe(["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"]),Ra=fe(["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"]),Tr=fe(["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"]),gs=fe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),jh=Ce(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Hh=Ce(/<%[\w\W]*|[\w\W]*%>/gm),Vh=Ce(/\$\{[\w\W]*/gm),Gh=Ce(/^data-[\-\w.\u00B7-\uFFFF]+$/),Qh=Ce(/^aria-[\-\w]+$/),Ic=Ce(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Yh=Ce(/^(?:\w+script|data):/i),Jh=Ce(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Mc=Ce(/^html$/i),Xh=Ce(/^[a-z][.\w]*(-[.\w]+)+$/i);var xr=Object.freeze({__proto__:null,ARIA_ATTR:Qh,ATTR_WHITESPACE:Jh,CUSTOM_ELEMENT:Xh,DATA_ATTR:Gh,DOCTYPE_NAME:Mc,ERB_EXPR:Hh,IS_ALLOWED_URI:Ic,IS_SCRIPT_OR_DATA:Yh,MUSTACHE_EXPR:jh,TMPLIT_EXPR:Vh});const _n={element:1,text:3,progressingInstruction:7,comment:8,document:9},Zh=function(){return typeof window>"u"?null:window},ef=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const a="data-tt-policy-suffix";n&&n.hasAttribute(a)&&(s=n.getAttribute(a));const i="dompurify"+(s?"#"+s:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Cr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Dc(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Zh();const t=O=>Dc(O);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==_n.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const s=n,a=s.currentScript,{DocumentFragment:i,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:u,NamedNodeMap:p=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:f,DOMParser:m,trustedTypes:g}=e,$=c.prototype,d=An($,"cloneNode"),v=An($,"remove"),S=An($,"nextSibling"),_=An($,"childNodes"),T=An($,"parentNode");if(typeof o=="function"){const O=n.createElement("template");O.content&&O.content.ownerDocument&&(n=O.content.ownerDocument)}let A,C="";const{implementation:L,createNodeIterator:P,createDocumentFragment:te,getElementsByTagName:Q}=n,{importNode:de}=s;let R=Cr();t.isSupported=typeof Pc=="function"&&typeof T=="function"&&L&&L.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:N,ERB_EXPR:B,TMPLIT_EXPR:W,DATA_ATTR:F,ARIA_ATTR:we,IS_SCRIPT_OR_DATA:Se,ATTR_WHITESPACE:D,CUSTOM_ELEMENT:De}=xr;let{IS_ALLOWED_URI:Ut}=xr,j=null;const gn=U({},[...Sr,...Ca,...Ea,...La,...Ar]);let Y=null;const mn=U({},[..._r,...Ra,...Tr,...gs]);let V=Object.seal(li(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}})),nt=null,ht=null;const st=Object.seal(li(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let vn=!0,zt=!0,ha=!1,No=!0,Kt=!1,os=!0,ft=!1,fa=!1,ga=!1,Wt=!1,rs=!1,ls=!1,Fo=!0,Bo=!1;const up="user-content-";let ma=!0,yn=!1,qt={},Oe=null;const va=U({},["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 Uo=null;const zo=U({},["audio","video","img","source","image","track"]);let ya=null;const Ko=U({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),cs="http://www.w3.org/1998/Math/MathML",ds="http://www.w3.org/2000/svg",qe="http://www.w3.org/1999/xhtml";let jt=qe,ba=!1,wa=null;const pp=U({},[cs,ds,qe],Ta);let us=U({},["mi","mo","mn","ms","mtext"]),ps=U({},["annotation-xml"]);const hp=U({},["title","style","font","a","script"]);let bn=null;const fp=["application/xhtml+xml","text/html"],gp="text/html";let Z=null,Ht=null;const mp=n.createElement("form"),Wo=function(k){return k instanceof RegExp||k instanceof Function},$a=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ht&&Ht===k)){if((!k||typeof k!="object")&&(k={}),k=Be(k),bn=fp.indexOf(k.PARSER_MEDIA_TYPE)===-1?gp:k.PARSER_MEDIA_TYPE,Z=bn==="application/xhtml+xml"?Ta:ks,j=Ee(k,"ALLOWED_TAGS")?U({},k.ALLOWED_TAGS,Z):gn,Y=Ee(k,"ALLOWED_ATTR")?U({},k.ALLOWED_ATTR,Z):mn,wa=Ee(k,"ALLOWED_NAMESPACES")?U({},k.ALLOWED_NAMESPACES,Ta):pp,ya=Ee(k,"ADD_URI_SAFE_ATTR")?U(Be(Ko),k.ADD_URI_SAFE_ATTR,Z):Ko,Uo=Ee(k,"ADD_DATA_URI_TAGS")?U(Be(zo),k.ADD_DATA_URI_TAGS,Z):zo,Oe=Ee(k,"FORBID_CONTENTS")?U({},k.FORBID_CONTENTS,Z):va,nt=Ee(k,"FORBID_TAGS")?U({},k.FORBID_TAGS,Z):Be({}),ht=Ee(k,"FORBID_ATTR")?U({},k.FORBID_ATTR,Z):Be({}),qt=Ee(k,"USE_PROFILES")?k.USE_PROFILES:!1,vn=k.ALLOW_ARIA_ATTR!==!1,zt=k.ALLOW_DATA_ATTR!==!1,ha=k.ALLOW_UNKNOWN_PROTOCOLS||!1,No=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Kt=k.SAFE_FOR_TEMPLATES||!1,os=k.SAFE_FOR_XML!==!1,ft=k.WHOLE_DOCUMENT||!1,Wt=k.RETURN_DOM||!1,rs=k.RETURN_DOM_FRAGMENT||!1,ls=k.RETURN_TRUSTED_TYPE||!1,ga=k.FORCE_BODY||!1,Fo=k.SANITIZE_DOM!==!1,Bo=k.SANITIZE_NAMED_PROPS||!1,ma=k.KEEP_CONTENT!==!1,yn=k.IN_PLACE||!1,Ut=k.ALLOWED_URI_REGEXP||Ic,jt=k.NAMESPACE||qe,us=k.MATHML_TEXT_INTEGRATION_POINTS||us,ps=k.HTML_INTEGRATION_POINTS||ps,V=k.CUSTOM_ELEMENT_HANDLING||{},k.CUSTOM_ELEMENT_HANDLING&&Wo(k.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(V.tagNameCheck=k.CUSTOM_ELEMENT_HANDLING.tagNameCheck),k.CUSTOM_ELEMENT_HANDLING&&Wo(k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(V.attributeNameCheck=k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),k.CUSTOM_ELEMENT_HANDLING&&typeof k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(V.allowCustomizedBuiltInElements=k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Kt&&(zt=!1),rs&&(Wt=!0),qt&&(j=U({},Ar),Y=[],qt.html===!0&&(U(j,Sr),U(Y,_r)),qt.svg===!0&&(U(j,Ca),U(Y,Ra),U(Y,gs)),qt.svgFilters===!0&&(U(j,Ea),U(Y,Ra),U(Y,gs)),qt.mathMl===!0&&(U(j,La),U(Y,Tr),U(Y,gs))),k.ADD_TAGS&&(typeof k.ADD_TAGS=="function"?st.tagCheck=k.ADD_TAGS:(j===gn&&(j=Be(j)),U(j,k.ADD_TAGS,Z))),k.ADD_ATTR&&(typeof k.ADD_ATTR=="function"?st.attributeCheck=k.ADD_ATTR:(Y===mn&&(Y=Be(Y)),U(Y,k.ADD_ATTR,Z))),k.ADD_URI_SAFE_ATTR&&U(ya,k.ADD_URI_SAFE_ATTR,Z),k.FORBID_CONTENTS&&(Oe===va&&(Oe=Be(Oe)),U(Oe,k.FORBID_CONTENTS,Z)),k.ADD_FORBID_CONTENTS&&(Oe===va&&(Oe=Be(Oe)),U(Oe,k.ADD_FORBID_CONTENTS,Z)),ma&&(j["#text"]=!0),ft&&U(j,["html","head","body"]),j.table&&(U(j,["tbody"]),delete nt.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw Sn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Sn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=k.TRUSTED_TYPES_POLICY,C=A.createHTML("")}else A===void 0&&(A=ef(g,a)),A!==null&&typeof C=="string"&&(C=A.createHTML(""));fe&&fe(k),Ht=k}},qo=U({},[...Ca,...Ea,...Wh]),jo=U({},[...La,...qh]),vp=function(k){let x=T(k);(!x||!x.tagName)&&(x={namespaceURI:jt,tagName:"template"});const M=ks(k.tagName),G=ks(x.tagName);return wa[k.namespaceURI]?k.namespaceURI===ds?x.namespaceURI===qe?M==="svg":x.namespaceURI===cs?M==="svg"&&(G==="annotation-xml"||us[G]):!!qo[M]:k.namespaceURI===cs?x.namespaceURI===qe?M==="math":x.namespaceURI===ds?M==="math"&&ps[G]:!!jo[M]:k.namespaceURI===qe?x.namespaceURI===ds&&!ps[G]||x.namespaceURI===cs&&!us[G]?!1:!jo[M]&&(hp[M]||!qo[M]):!!(bn==="application/xhtml+xml"&&wa[k.namespaceURI]):!1},Ne=function(k){$n(t.removed,{element:k});try{T(k).removeChild(k)}catch{v(k)}},gt=function(k,x){try{$n(t.removed,{attribute:x.getAttributeNode(k),from:x})}catch{$n(t.removed,{attribute:null,from:x})}if(x.removeAttribute(k),k==="is")if(Wt||rs)try{Ne(x)}catch{}else try{x.setAttribute(k,"")}catch{}},Ho=function(k){let x=null,M=null;if(ga)k="<remove></remove>"+k;else{const J=xa(k,/^[\r\n\t ]+/);M=J&&J[0]}bn==="application/xhtml+xml"&&jt===qe&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const G=A?A.createHTML(k):k;if(jt===qe)try{x=new m().parseFromString(G,bn)}catch{}if(!x||!x.documentElement){x=L.createDocument(jt,"template",null);try{x.documentElement.innerHTML=ba?C:G}catch{}}const le=x.body||x.documentElement;return k&&M&&le.insertBefore(n.createTextNode(M),le.childNodes[0]||null),jt===qe?Q.call(x,ft?"html":"body")[0]:ft?x.documentElement:le},Vo=function(k){return P.call(k.ownerDocument||k,k,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},ka=function(k){return k instanceof f&&(typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||!(k.attributes instanceof p)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function")},Go=function(k){return typeof l=="function"&&k instanceof l};function je(O,k,x){fs(O,M=>{M.call(t,k,x,Ht)})}const Qo=function(k){let x=null;if(je(R.beforeSanitizeElements,k,null),ka(k))return Ne(k),!0;const M=Z(k.nodeName);if(je(R.uponSanitizeElement,k,{tagName:M,allowedTags:j}),os&&k.hasChildNodes()&&!Go(k.firstElementChild)&&ue(/<[/\w!]/g,k.innerHTML)&&ue(/<[/\w!]/g,k.textContent)||k.nodeType===_n.progressingInstruction||os&&k.nodeType===_n.comment&&ue(/<[/\w]/g,k.data))return Ne(k),!0;if(!(st.tagCheck instanceof Function&&st.tagCheck(M))&&(!j[M]||nt[M])){if(!nt[M]&&Jo(M)&&(V.tagNameCheck instanceof RegExp&&ue(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M)))return!1;if(ma&&!Oe[M]){const G=T(k)||k.parentNode,le=_(k)||k.childNodes;if(le&&G){const J=le.length;for(let me=J-1;me>=0;--me){const He=d(le[me],!0);He.__removalCount=(k.__removalCount||0)+1,G.insertBefore(He,S(k))}}}return Ne(k),!0}return k instanceof c&&!vp(k)||(M==="noscript"||M==="noembed"||M==="noframes")&&ue(/<\/no(script|embed|frames)/i,k.innerHTML)?(Ne(k),!0):(Kt&&k.nodeType===_n.text&&(x=k.textContent,fs([N,B,W],G=>{x=kn(x,G," ")}),k.textContent!==x&&($n(t.removed,{element:k.cloneNode()}),k.textContent=x)),je(R.afterSanitizeElements,k,null),!1)},Yo=function(k,x,M){if(Fo&&(x==="id"||x==="name")&&(M in n||M in mp))return!1;if(!(zt&&!ht[x]&&ue(F,x))){if(!(vn&&ue(we,x))){if(!(st.attributeCheck instanceof Function&&st.attributeCheck(x,k))){if(!Y[x]||ht[x]){if(!(Jo(k)&&(V.tagNameCheck instanceof RegExp&&ue(V.tagNameCheck,k)||V.tagNameCheck instanceof Function&&V.tagNameCheck(k))&&(V.attributeNameCheck instanceof RegExp&&ue(V.attributeNameCheck,x)||V.attributeNameCheck instanceof Function&&V.attributeNameCheck(x,k))||x==="is"&&V.allowCustomizedBuiltInElements&&(V.tagNameCheck instanceof RegExp&&ue(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M))))return!1}else if(!ya[x]){if(!ue(Ut,kn(M,D,""))){if(!((x==="src"||x==="xlink:href"||x==="href")&&k!=="script"&&Bh(M,"data:")===0&&Uo[k])){if(!(ha&&!ue(Se,kn(M,D,"")))){if(M)return!1}}}}}}}return!0},Jo=function(k){return k!=="annotation-xml"&&xa(k,De)},Xo=function(k){je(R.beforeSanitizeAttributes,k,null);const{attributes:x}=k;if(!x||ka(k))return;const M={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Y,forceKeepAttr:void 0};let G=x.length;for(;G--;){const le=x[G],{name:J,namespaceURI:me,value:He}=le,Vt=Z(J),Sa=He;let ae=J==="value"?Sa:Uh(Sa);if(M.attrName=Vt,M.attrValue=ae,M.keepAttr=!0,M.forceKeepAttr=void 0,je(R.uponSanitizeAttribute,k,M),ae=M.attrValue,Bo&&(Vt==="id"||Vt==="name")&&(gt(J,k),ae=up+ae),os&&ue(/((--!?|])>)|<\/(style|title|textarea)/i,ae)){gt(J,k);continue}if(Vt==="attributename"&&xa(ae,"href")){gt(J,k);continue}if(M.forceKeepAttr)continue;if(!M.keepAttr){gt(J,k);continue}if(!No&&ue(/\/>/i,ae)){gt(J,k);continue}Kt&&fs([N,B,W],er=>{ae=kn(ae,er," ")});const Zo=Z(k.nodeName);if(!Yo(Zo,Vt,ae)){gt(J,k);continue}if(A&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!me)switch(g.getAttributeType(Zo,Vt)){case"TrustedHTML":{ae=A.createHTML(ae);break}case"TrustedScriptURL":{ae=A.createScriptURL(ae);break}}if(ae!==Sa)try{me?k.setAttributeNS(me,J,ae):k.setAttribute(J,ae),ka(k)?Ne(k):kr(t.removed)}catch{gt(J,k)}}je(R.afterSanitizeAttributes,k,null)},yp=function O(k){let x=null;const M=Vo(k);for(je(R.beforeSanitizeShadowDOM,k,null);x=M.nextNode();)je(R.uponSanitizeShadowNode,x,null),Qo(x),Xo(x),x.content instanceof i&&O(x.content);je(R.afterSanitizeShadowDOM,k,null)};return t.sanitize=function(O){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},x=null,M=null,G=null,le=null;if(ba=!O,ba&&(O="<!-->"),typeof O!="string"&&!Go(O))if(typeof O.toString=="function"){if(O=O.toString(),typeof O!="string")throw Sn("dirty is not a string, aborting")}else throw Sn("toString is not a function");if(!t.isSupported)return O;if(fa||$a(k),t.removed=[],typeof O=="string"&&(yn=!1),yn){if(O.nodeName){const He=Z(O.nodeName);if(!j[He]||nt[He])throw Sn("root node is forbidden and cannot be sanitized in-place")}}else if(O instanceof l)x=Ho("<!---->"),M=x.ownerDocument.importNode(O,!0),M.nodeType===_n.element&&M.nodeName==="BODY"||M.nodeName==="HTML"?x=M:x.appendChild(M);else{if(!Wt&&!Kt&&!ft&&O.indexOf("<")===-1)return A&&ls?A.createHTML(O):O;if(x=Ho(O),!x)return Wt?null:ls?C:""}x&&ga&&Ne(x.firstChild);const J=Vo(yn?O:x);for(;G=J.nextNode();)Qo(G),Xo(G),G.content instanceof i&&yp(G.content);if(yn)return O;if(Wt){if(rs)for(le=te.call(x.ownerDocument);x.firstChild;)le.appendChild(x.firstChild);else le=x;return(Y.shadowroot||Y.shadowrootmode)&&(le=de.call(s,le,!0)),le}let me=ft?x.outerHTML:x.innerHTML;return ft&&j["!doctype"]&&x.ownerDocument&&x.ownerDocument.doctype&&x.ownerDocument.doctype.name&&ue(Mc,x.ownerDocument.doctype.name)&&(me="<!DOCTYPE "+x.ownerDocument.doctype.name+`>
131
- `+me),Kt&&fs([N,B,W],He=>{me=kn(me,He," ")}),A&&ls?A.createHTML(me):me},t.setConfig=function(){let O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$a(O),fa=!0},t.clearConfig=function(){Ht=null,fa=!1},t.isValidAttribute=function(O,k,x){Ht||$a({});const M=Z(O),G=Z(k);return Yo(M,G,x)},t.addHook=function(O,k){typeof k=="function"&&$n(R[O],k)},t.removeHook=function(O,k){if(k!==void 0){const x=Nh(R[O],k);return x===-1?void 0:Fh(R[O],x,1)[0]}return kr(R[O])},t.removeHooks=function(O){R[O]=[]},t.removeAllHooks=function(){R=Cr()},t}var ln=Dc();function Wi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Nt=Wi();function Oc(e){Nt=e}var _t={exec:()=>null};function K(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(a,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(he.caret,"$1"),n=n.replace(a,o),s},getRegex:()=>new RegExp(n,t)};return s}var tf=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),he={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,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"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},nf=/^(?:[ \t]*(?:\n|$))+/,sf=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,af=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Xn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,of=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,qi=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Nc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Fc=K(Nc).replace(/bull/g,qi).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(),rf=K(Nc).replace(/bull/g,qi).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(),ji=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,lf=/^[^\n]+/,Hi=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,cf=K(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Hi).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),df=K(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,qi).getRegex(),Ys="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",Vi=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,uf=K("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Vi).replace("tag",Ys).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Bc=K(ji).replace("hr",Xn).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[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ys).getRegex(),pf=K(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Bc).getRegex(),Gi={blockquote:pf,code:sf,def:cf,fences:af,heading:of,hr:Xn,html:uf,lheading:Fc,list:df,newline:nf,paragraph:Bc,table:_t,text:lf},Er=K("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Xn).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[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ys).getRegex(),hf={...Gi,lheading:rf,table:Er,paragraph:K(ji).replace("hr",Xn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Er).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ys).getRegex()},ff={...Gi,html:K(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Vi).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:_t,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:K(ji).replace("hr",Xn).replace("heading",` *#{1,6} *[^
132
- ]`).replace("lheading",Fc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},gf=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,mf=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Uc=/^( {2,}|\\)\n(?!\s*$)/,vf=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Js=/[\p{P}\p{S}]/u,Qi=/[\s\p{P}\p{S}]/u,zc=/[^\s\p{P}\p{S}]/u,yf=K(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Qi).getRegex(),Kc=/(?!~)[\p{P}\p{S}]/u,bf=/(?!~)[\s\p{P}\p{S}]/u,wf=/(?:[^\s\p{P}\p{S}]|~)/u,Wc=/(?![*_])[\p{P}\p{S}]/u,$f=/(?![*_])[\s\p{P}\p{S}]/u,kf=/(?:[^\s\p{P}\p{S}]|[*_])/u,Sf=K(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",tf?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),qc=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Af=K(qc,"u").replace(/punct/g,Js).getRegex(),_f=K(qc,"u").replace(/punct/g,Kc).getRegex(),jc="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Tf=K(jc,"gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Qi).replace(/punct/g,Js).getRegex(),xf=K(jc,"gu").replace(/notPunctSpace/g,wf).replace(/punctSpace/g,bf).replace(/punct/g,Kc).getRegex(),Cf=K("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Qi).replace(/punct/g,Js).getRegex(),Ef=K(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Wc).getRegex(),Lf="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Rf=K(Lf,"gu").replace(/notPunctSpace/g,kf).replace(/punctSpace/g,$f).replace(/punct/g,Wc).getRegex(),Pf=K(/\\(punct)/,"gu").replace(/punct/g,Js).getRegex(),If=K(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Mf=K(Vi).replace("(?:-->|$)","-->").getRegex(),Df=K("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Mf).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ms=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Of=K(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Ms).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Hc=K(/^!?\[(label)\]\[(ref)\]/).replace("label",Ms).replace("ref",Hi).getRegex(),Vc=K(/^!?\[(ref)\](?:\[\])?/).replace("ref",Hi).getRegex(),Nf=K("reflink|nolink(?!\\()","g").replace("reflink",Hc).replace("nolink",Vc).getRegex(),Lr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Yi={_backpedal:_t,anyPunctuation:Pf,autolink:If,blockSkip:Sf,br:Uc,code:mf,del:_t,delLDelim:_t,delRDelim:_t,emStrongLDelim:Af,emStrongRDelimAst:Tf,emStrongRDelimUnd:Cf,escape:gf,link:Of,nolink:Vc,punctuation:yf,reflink:Hc,reflinkSearch:Nf,tag:Df,text:vf,url:_t},Ff={...Yi,link:K(/^!?\[(label)\]\((.*?)\)/).replace("label",Ms).getRegex(),reflink:K(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ms).getRegex()},ui={...Yi,emStrongRDelimAst:xf,emStrongLDelim:_f,delLDelim:Ef,delRDelim:Rf,url:K(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Lr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:K(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Lr).getRegex()},Bf={...ui,br:K(Uc).replace("{2,}","*").getRegex(),text:K(ui.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ms={normal:Gi,gfm:hf,pedantic:ff},Tn={normal:Yi,gfm:ui,breaks:Bf,pedantic:Ff},Uf={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Rr=e=>Uf[e];function Ue(e,t){if(t){if(he.escapeTest.test(e))return e.replace(he.escapeReplace,Rr)}else if(he.escapeTestNoEncode.test(e))return e.replace(he.escapeReplaceNoEncode,Rr);return e}function Pr(e){try{e=encodeURI(e).replace(he.percentDecode,"%")}catch{return null}return e}function Ir(e,t){let n=e.replace(he.findPipe,(i,o,l)=>{let c=!1,u=o;for(;--u>=0&&l[u]==="\\";)c=!c;return c?"|":" |"}),s=n.split(he.splitPipe),a=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;a<s.length;a++)s[a]=s[a].trim().replace(he.slashPipe,"|");return s}function xn(e,t,n){let s=e.length;if(s===0)return"";let a=0;for(;a<s&&e.charAt(s-a-1)===t;)a++;return e.slice(0,s-a)}function zf(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return n>0?-2:-1}function Kf(e,t=0){let n=t,s="";for(let a of e)if(a===" "){let i=4-n%4;s+=" ".repeat(i),n+=i}else s+=a,n++;return s}function Mr(e,t,n,s,a){let i=t.href,o=t.title||null,l=e[1].replace(a.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,c}function Wf(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(s===null)return t;let a=s[1];return t.split(`
130
+ … truncated (${s.total} chars, showing first ${s.text.length}).`:s.text}function Th(e){const t=[];return t.push({type:"toolcall",name:e.name,arguments:e.args??{}}),e.output&&t.push({type:"toolresult",name:e.name,text:e.output}),{role:"assistant",toolCallId:e.toolCallId,runId:e.runId,content:t,timestamp:e.startedAt}}function xh(e){if(e.toolStreamOrder.length<=mr)return;const t=e.toolStreamOrder.length-mr,n=e.toolStreamOrder.splice(0,t);for(const s of n)e.toolStreamById.delete(s)}function Ch(e){e.chatToolMessages=e.toolStreamOrder.map(t=>e.toolStreamById.get(t)?.message).filter(t=>!!t)}function oi(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Ch(e)}function Eh(e,t=!1){if(t){oi(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>oi(e),Sh))}function Bi(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],e.currentToolName=null,e.currentToolInfo=null;const t=e;t.compactionStatus&&(t.compactionStatus=null),t.compactionClearTimer!=null&&(window.clearTimeout(t.compactionClearTimer),t.compactionClearTimer=null),oi(e)}const Lh=5e3;function Rh(e,t){const n=t.data??{},s=typeof n.phase=="string"?n.phase:"";e.compactionClearTimer!=null&&(window.clearTimeout(e.compactionClearTimer),e.compactionClearTimer=null),s==="start"?e.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null}:s==="end"&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus?.startedAt??null,completedAt:Date.now()},e.compactionClearTimer=window.setTimeout(()=>{e.compactionStatus=null,e.compactionClearTimer=null},Lh))}function Ph(e,t){if(!t)return;if(t.stream==="compaction"){Rh(e,t);return}if(t.stream!=="tool")return;const n=typeof t.sessionKey=="string"?t.sessionKey:void 0;if(n&&n!==e.sessionKey||!n&&e.chatRunId&&t.runId!==e.chatRunId||e.chatRunId&&t.runId!==e.chatRunId||!e.chatRunId)return;const s=t.data??{},a=typeof s.toolCallId=="string"?s.toolCallId:"";if(!a)return;const i=typeof s.name=="string"?s.name:"tool",o=typeof s.phase=="string"?s.phase:"",l=o==="start"?s.args:void 0,c=o==="update"?wr(s.partialResult):o==="result"?wr(s.result):void 0,u=Date.now();let p=e.toolStreamById.get(a);p?(p.name=i,l!==void 0&&(p.args=l,p.displayArgs=vr(i,l)),c!==void 0&&(p.output=c,p.resultSummary=yr(i,c),p.success=br(c)),p.updatedAt=u):(p={toolCallId:a,runId:t.runId,sessionKey:n,name:i,args:l,output:c,startedAt:typeof t.ts=="number"?t.ts:u,updatedAt:u,message:{},displayArgs:l?vr(i,l):void 0},e.toolStreamById.set(a,p),e.toolStreamOrder.push(a)),o==="start"?(e.currentToolName=i,e.currentToolInfo={name:i,details:p.displayArgs||void 0,startedAt:p.startedAt}):o==="result"&&(e.currentToolName=null,e.currentToolInfo=null,p.completedAt=u,p.resultSummary=yr(i,p.output),p.success=br(p.output)),p.message=Th(p),xh(e),Eh(e,o==="result")}const Ui={CHILD:2},zi=e=>(...t)=>({_$litDirective$:e,values:t});let Ki=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,n,s){this._$Ct=t,this._$AM=n,this._$Ci=s}_$AS(t,n){return this.update(t,n)}update(t,n){return this.render(...n)}};class ri extends Ki{constructor(t){if(super(t),this.it=h,t.type!==Ui.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===h||t==null)return this._t=void 0,this.it=t;if(t===dt)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:[]}}}ri.directiveName="unsafeHTML",ri.resultType=1;const ke=zi(ri);const{entries:Pc,setPrototypeOf:$r,isFrozen:Ih,getPrototypeOf:Mh,getOwnPropertyDescriptor:Dh}=Object;let{freeze:fe,seal:Ce,create:li}=Object,{apply:ci,construct:di}=typeof Reflect<"u"&&Reflect;fe||(fe=function(t){return t});Ce||(Ce=function(t){return t});ci||(ci=function(t,n){for(var s=arguments.length,a=new Array(s>2?s-2:0),i=2;i<s;i++)a[i-2]=arguments[i];return t.apply(n,a)});di||(di=function(t){for(var n=arguments.length,s=new Array(n>1?n-1:0),a=1;a<n;a++)s[a-1]=arguments[a];return new t(...s)});const fs=ge(Array.prototype.forEach),Oh=ge(Array.prototype.lastIndexOf),kr=ge(Array.prototype.pop),$n=ge(Array.prototype.push),Nh=ge(Array.prototype.splice),ks=ge(String.prototype.toLowerCase),Ta=ge(String.prototype.toString),xa=ge(String.prototype.match),kn=ge(String.prototype.replace),Fh=ge(String.prototype.indexOf),Bh=ge(String.prototype.trim),Ee=ge(Object.prototype.hasOwnProperty),ue=ge(RegExp.prototype.test),Sn=Uh(TypeError);function ge(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),a=1;a<n;a++)s[a-1]=arguments[a];return ci(e,t,s)}}function Uh(e){return function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return di(e,n)}}function U(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ks;$r&&$r(e,null);let s=t.length;for(;s--;){let a=t[s];if(typeof a=="string"){const i=n(a);i!==a&&(Ih(t)||(t[s]=i),a=i)}e[a]=!0}return e}function zh(e){for(let t=0;t<e.length;t++)Ee(e,t)||(e[t]=null);return e}function Be(e){const t=li(null);for(const[n,s]of Pc(e))Ee(e,n)&&(Array.isArray(s)?t[n]=zh(s):s&&typeof s=="object"&&s.constructor===Object?t[n]=Be(s):t[n]=s);return t}function An(e,t){for(;e!==null;){const s=Dh(e,t);if(s){if(s.get)return ge(s.get);if(typeof s.value=="function")return ge(s.value)}e=Mh(e)}function n(){return null}return n}const Sr=fe(["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"]),Ca=fe(["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"]),Ea=fe(["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"]),Kh=fe(["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"]),La=fe(["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"]),Wh=fe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ar=fe(["#text"]),_r=fe(["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"]),Ra=fe(["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"]),Tr=fe(["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"]),gs=fe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),qh=Ce(/\{\{[\w\W]*|[\w\W]*\}\}/gm),jh=Ce(/<%[\w\W]*|[\w\W]*%>/gm),Hh=Ce(/\$\{[\w\W]*/gm),Vh=Ce(/^data-[\-\w.\u00B7-\uFFFF]+$/),Gh=Ce(/^aria-[\-\w]+$/),Ic=Ce(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Qh=Ce(/^(?:\w+script|data):/i),Yh=Ce(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Mc=Ce(/^html$/i),Jh=Ce(/^[a-z][.\w]*(-[.\w]+)+$/i);var xr=Object.freeze({__proto__:null,ARIA_ATTR:Gh,ATTR_WHITESPACE:Yh,CUSTOM_ELEMENT:Jh,DATA_ATTR:Vh,DOCTYPE_NAME:Mc,ERB_EXPR:jh,IS_ALLOWED_URI:Ic,IS_SCRIPT_OR_DATA:Qh,MUSTACHE_EXPR:qh,TMPLIT_EXPR:Hh});const _n={element:1,text:3,progressingInstruction:7,comment:8,document:9},Xh=function(){return typeof window>"u"?null:window},Zh=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const a="data-tt-policy-suffix";n&&n.hasAttribute(a)&&(s=n.getAttribute(a));const i="dompurify"+(s?"#"+s:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Cr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Dc(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Xh();const t=O=>Dc(O);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==_n.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const s=n,a=s.currentScript,{DocumentFragment:i,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:u,NamedNodeMap:p=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:f,DOMParser:m,trustedTypes:g}=e,$=c.prototype,d=An($,"cloneNode"),v=An($,"remove"),S=An($,"nextSibling"),_=An($,"childNodes"),T=An($,"parentNode");if(typeof o=="function"){const O=n.createElement("template");O.content&&O.content.ownerDocument&&(n=O.content.ownerDocument)}let A,C="";const{implementation:L,createNodeIterator:P,createDocumentFragment:te,getElementsByTagName:Q}=n,{importNode:de}=s;let R=Cr();t.isSupported=typeof Pc=="function"&&typeof T=="function"&&L&&L.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:N,ERB_EXPR:B,TMPLIT_EXPR:W,DATA_ATTR:F,ARIA_ATTR:we,IS_SCRIPT_OR_DATA:Se,ATTR_WHITESPACE:D,CUSTOM_ELEMENT:De}=xr;let{IS_ALLOWED_URI:Bt}=xr,j=null;const gn=U({},[...Sr,...Ca,...Ea,...La,...Ar]);let Y=null;const mn=U({},[..._r,...Ra,...Tr,...gs]);let V=Object.seal(li(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}})),nt=null,ht=null;const st=Object.seal(li(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let vn=!0,Ut=!0,ha=!1,No=!0,zt=!1,os=!0,ft=!1,fa=!1,ga=!1,Kt=!1,rs=!1,ls=!1,Fo=!0,Bo=!1;const dp="user-content-";let ma=!0,yn=!1,Wt={},Oe=null;const va=U({},["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 Uo=null;const zo=U({},["audio","video","img","source","image","track"]);let ya=null;const Ko=U({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),cs="http://www.w3.org/1998/Math/MathML",ds="http://www.w3.org/2000/svg",qe="http://www.w3.org/1999/xhtml";let qt=qe,ba=!1,wa=null;const up=U({},[cs,ds,qe],Ta);let us=U({},["mi","mo","mn","ms","mtext"]),ps=U({},["annotation-xml"]);const pp=U({},["title","style","font","a","script"]);let bn=null;const hp=["application/xhtml+xml","text/html"],fp="text/html";let Z=null,jt=null;const gp=n.createElement("form"),Wo=function(k){return k instanceof RegExp||k instanceof Function},$a=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(jt&&jt===k)){if((!k||typeof k!="object")&&(k={}),k=Be(k),bn=hp.indexOf(k.PARSER_MEDIA_TYPE)===-1?fp:k.PARSER_MEDIA_TYPE,Z=bn==="application/xhtml+xml"?Ta:ks,j=Ee(k,"ALLOWED_TAGS")?U({},k.ALLOWED_TAGS,Z):gn,Y=Ee(k,"ALLOWED_ATTR")?U({},k.ALLOWED_ATTR,Z):mn,wa=Ee(k,"ALLOWED_NAMESPACES")?U({},k.ALLOWED_NAMESPACES,Ta):up,ya=Ee(k,"ADD_URI_SAFE_ATTR")?U(Be(Ko),k.ADD_URI_SAFE_ATTR,Z):Ko,Uo=Ee(k,"ADD_DATA_URI_TAGS")?U(Be(zo),k.ADD_DATA_URI_TAGS,Z):zo,Oe=Ee(k,"FORBID_CONTENTS")?U({},k.FORBID_CONTENTS,Z):va,nt=Ee(k,"FORBID_TAGS")?U({},k.FORBID_TAGS,Z):Be({}),ht=Ee(k,"FORBID_ATTR")?U({},k.FORBID_ATTR,Z):Be({}),Wt=Ee(k,"USE_PROFILES")?k.USE_PROFILES:!1,vn=k.ALLOW_ARIA_ATTR!==!1,Ut=k.ALLOW_DATA_ATTR!==!1,ha=k.ALLOW_UNKNOWN_PROTOCOLS||!1,No=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,zt=k.SAFE_FOR_TEMPLATES||!1,os=k.SAFE_FOR_XML!==!1,ft=k.WHOLE_DOCUMENT||!1,Kt=k.RETURN_DOM||!1,rs=k.RETURN_DOM_FRAGMENT||!1,ls=k.RETURN_TRUSTED_TYPE||!1,ga=k.FORCE_BODY||!1,Fo=k.SANITIZE_DOM!==!1,Bo=k.SANITIZE_NAMED_PROPS||!1,ma=k.KEEP_CONTENT!==!1,yn=k.IN_PLACE||!1,Bt=k.ALLOWED_URI_REGEXP||Ic,qt=k.NAMESPACE||qe,us=k.MATHML_TEXT_INTEGRATION_POINTS||us,ps=k.HTML_INTEGRATION_POINTS||ps,V=k.CUSTOM_ELEMENT_HANDLING||{},k.CUSTOM_ELEMENT_HANDLING&&Wo(k.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(V.tagNameCheck=k.CUSTOM_ELEMENT_HANDLING.tagNameCheck),k.CUSTOM_ELEMENT_HANDLING&&Wo(k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(V.attributeNameCheck=k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),k.CUSTOM_ELEMENT_HANDLING&&typeof k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(V.allowCustomizedBuiltInElements=k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),zt&&(Ut=!1),rs&&(Kt=!0),Wt&&(j=U({},Ar),Y=[],Wt.html===!0&&(U(j,Sr),U(Y,_r)),Wt.svg===!0&&(U(j,Ca),U(Y,Ra),U(Y,gs)),Wt.svgFilters===!0&&(U(j,Ea),U(Y,Ra),U(Y,gs)),Wt.mathMl===!0&&(U(j,La),U(Y,Tr),U(Y,gs))),k.ADD_TAGS&&(typeof k.ADD_TAGS=="function"?st.tagCheck=k.ADD_TAGS:(j===gn&&(j=Be(j)),U(j,k.ADD_TAGS,Z))),k.ADD_ATTR&&(typeof k.ADD_ATTR=="function"?st.attributeCheck=k.ADD_ATTR:(Y===mn&&(Y=Be(Y)),U(Y,k.ADD_ATTR,Z))),k.ADD_URI_SAFE_ATTR&&U(ya,k.ADD_URI_SAFE_ATTR,Z),k.FORBID_CONTENTS&&(Oe===va&&(Oe=Be(Oe)),U(Oe,k.FORBID_CONTENTS,Z)),k.ADD_FORBID_CONTENTS&&(Oe===va&&(Oe=Be(Oe)),U(Oe,k.ADD_FORBID_CONTENTS,Z)),ma&&(j["#text"]=!0),ft&&U(j,["html","head","body"]),j.table&&(U(j,["tbody"]),delete nt.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw Sn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Sn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=k.TRUSTED_TYPES_POLICY,C=A.createHTML("")}else A===void 0&&(A=Zh(g,a)),A!==null&&typeof C=="string"&&(C=A.createHTML(""));fe&&fe(k),jt=k}},qo=U({},[...Ca,...Ea,...Kh]),jo=U({},[...La,...Wh]),mp=function(k){let x=T(k);(!x||!x.tagName)&&(x={namespaceURI:qt,tagName:"template"});const M=ks(k.tagName),G=ks(x.tagName);return wa[k.namespaceURI]?k.namespaceURI===ds?x.namespaceURI===qe?M==="svg":x.namespaceURI===cs?M==="svg"&&(G==="annotation-xml"||us[G]):!!qo[M]:k.namespaceURI===cs?x.namespaceURI===qe?M==="math":x.namespaceURI===ds?M==="math"&&ps[G]:!!jo[M]:k.namespaceURI===qe?x.namespaceURI===ds&&!ps[G]||x.namespaceURI===cs&&!us[G]?!1:!jo[M]&&(pp[M]||!qo[M]):!!(bn==="application/xhtml+xml"&&wa[k.namespaceURI]):!1},Ne=function(k){$n(t.removed,{element:k});try{T(k).removeChild(k)}catch{v(k)}},gt=function(k,x){try{$n(t.removed,{attribute:x.getAttributeNode(k),from:x})}catch{$n(t.removed,{attribute:null,from:x})}if(x.removeAttribute(k),k==="is")if(Kt||rs)try{Ne(x)}catch{}else try{x.setAttribute(k,"")}catch{}},Ho=function(k){let x=null,M=null;if(ga)k="<remove></remove>"+k;else{const J=xa(k,/^[\r\n\t ]+/);M=J&&J[0]}bn==="application/xhtml+xml"&&qt===qe&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const G=A?A.createHTML(k):k;if(qt===qe)try{x=new m().parseFromString(G,bn)}catch{}if(!x||!x.documentElement){x=L.createDocument(qt,"template",null);try{x.documentElement.innerHTML=ba?C:G}catch{}}const le=x.body||x.documentElement;return k&&M&&le.insertBefore(n.createTextNode(M),le.childNodes[0]||null),qt===qe?Q.call(x,ft?"html":"body")[0]:ft?x.documentElement:le},Vo=function(k){return P.call(k.ownerDocument||k,k,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},ka=function(k){return k instanceof f&&(typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||!(k.attributes instanceof p)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function")},Go=function(k){return typeof l=="function"&&k instanceof l};function je(O,k,x){fs(O,M=>{M.call(t,k,x,jt)})}const Qo=function(k){let x=null;if(je(R.beforeSanitizeElements,k,null),ka(k))return Ne(k),!0;const M=Z(k.nodeName);if(je(R.uponSanitizeElement,k,{tagName:M,allowedTags:j}),os&&k.hasChildNodes()&&!Go(k.firstElementChild)&&ue(/<[/\w!]/g,k.innerHTML)&&ue(/<[/\w!]/g,k.textContent)||k.nodeType===_n.progressingInstruction||os&&k.nodeType===_n.comment&&ue(/<[/\w]/g,k.data))return Ne(k),!0;if(!(st.tagCheck instanceof Function&&st.tagCheck(M))&&(!j[M]||nt[M])){if(!nt[M]&&Jo(M)&&(V.tagNameCheck instanceof RegExp&&ue(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M)))return!1;if(ma&&!Oe[M]){const G=T(k)||k.parentNode,le=_(k)||k.childNodes;if(le&&G){const J=le.length;for(let me=J-1;me>=0;--me){const He=d(le[me],!0);He.__removalCount=(k.__removalCount||0)+1,G.insertBefore(He,S(k))}}}return Ne(k),!0}return k instanceof c&&!mp(k)||(M==="noscript"||M==="noembed"||M==="noframes")&&ue(/<\/no(script|embed|frames)/i,k.innerHTML)?(Ne(k),!0):(zt&&k.nodeType===_n.text&&(x=k.textContent,fs([N,B,W],G=>{x=kn(x,G," ")}),k.textContent!==x&&($n(t.removed,{element:k.cloneNode()}),k.textContent=x)),je(R.afterSanitizeElements,k,null),!1)},Yo=function(k,x,M){if(Fo&&(x==="id"||x==="name")&&(M in n||M in gp))return!1;if(!(Ut&&!ht[x]&&ue(F,x))){if(!(vn&&ue(we,x))){if(!(st.attributeCheck instanceof Function&&st.attributeCheck(x,k))){if(!Y[x]||ht[x]){if(!(Jo(k)&&(V.tagNameCheck instanceof RegExp&&ue(V.tagNameCheck,k)||V.tagNameCheck instanceof Function&&V.tagNameCheck(k))&&(V.attributeNameCheck instanceof RegExp&&ue(V.attributeNameCheck,x)||V.attributeNameCheck instanceof Function&&V.attributeNameCheck(x,k))||x==="is"&&V.allowCustomizedBuiltInElements&&(V.tagNameCheck instanceof RegExp&&ue(V.tagNameCheck,M)||V.tagNameCheck instanceof Function&&V.tagNameCheck(M))))return!1}else if(!ya[x]){if(!ue(Bt,kn(M,D,""))){if(!((x==="src"||x==="xlink:href"||x==="href")&&k!=="script"&&Fh(M,"data:")===0&&Uo[k])){if(!(ha&&!ue(Se,kn(M,D,"")))){if(M)return!1}}}}}}}return!0},Jo=function(k){return k!=="annotation-xml"&&xa(k,De)},Xo=function(k){je(R.beforeSanitizeAttributes,k,null);const{attributes:x}=k;if(!x||ka(k))return;const M={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Y,forceKeepAttr:void 0};let G=x.length;for(;G--;){const le=x[G],{name:J,namespaceURI:me,value:He}=le,Ht=Z(J),Sa=He;let ae=J==="value"?Sa:Bh(Sa);if(M.attrName=Ht,M.attrValue=ae,M.keepAttr=!0,M.forceKeepAttr=void 0,je(R.uponSanitizeAttribute,k,M),ae=M.attrValue,Bo&&(Ht==="id"||Ht==="name")&&(gt(J,k),ae=dp+ae),os&&ue(/((--!?|])>)|<\/(style|title|textarea)/i,ae)){gt(J,k);continue}if(Ht==="attributename"&&xa(ae,"href")){gt(J,k);continue}if(M.forceKeepAttr)continue;if(!M.keepAttr){gt(J,k);continue}if(!No&&ue(/\/>/i,ae)){gt(J,k);continue}zt&&fs([N,B,W],er=>{ae=kn(ae,er," ")});const Zo=Z(k.nodeName);if(!Yo(Zo,Ht,ae)){gt(J,k);continue}if(A&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!me)switch(g.getAttributeType(Zo,Ht)){case"TrustedHTML":{ae=A.createHTML(ae);break}case"TrustedScriptURL":{ae=A.createScriptURL(ae);break}}if(ae!==Sa)try{me?k.setAttributeNS(me,J,ae):k.setAttribute(J,ae),ka(k)?Ne(k):kr(t.removed)}catch{gt(J,k)}}je(R.afterSanitizeAttributes,k,null)},vp=function O(k){let x=null;const M=Vo(k);for(je(R.beforeSanitizeShadowDOM,k,null);x=M.nextNode();)je(R.uponSanitizeShadowNode,x,null),Qo(x),Xo(x),x.content instanceof i&&O(x.content);je(R.afterSanitizeShadowDOM,k,null)};return t.sanitize=function(O){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},x=null,M=null,G=null,le=null;if(ba=!O,ba&&(O="<!-->"),typeof O!="string"&&!Go(O))if(typeof O.toString=="function"){if(O=O.toString(),typeof O!="string")throw Sn("dirty is not a string, aborting")}else throw Sn("toString is not a function");if(!t.isSupported)return O;if(fa||$a(k),t.removed=[],typeof O=="string"&&(yn=!1),yn){if(O.nodeName){const He=Z(O.nodeName);if(!j[He]||nt[He])throw Sn("root node is forbidden and cannot be sanitized in-place")}}else if(O instanceof l)x=Ho("<!---->"),M=x.ownerDocument.importNode(O,!0),M.nodeType===_n.element&&M.nodeName==="BODY"||M.nodeName==="HTML"?x=M:x.appendChild(M);else{if(!Kt&&!zt&&!ft&&O.indexOf("<")===-1)return A&&ls?A.createHTML(O):O;if(x=Ho(O),!x)return Kt?null:ls?C:""}x&&ga&&Ne(x.firstChild);const J=Vo(yn?O:x);for(;G=J.nextNode();)Qo(G),Xo(G),G.content instanceof i&&vp(G.content);if(yn)return O;if(Kt){if(rs)for(le=te.call(x.ownerDocument);x.firstChild;)le.appendChild(x.firstChild);else le=x;return(Y.shadowroot||Y.shadowrootmode)&&(le=de.call(s,le,!0)),le}let me=ft?x.outerHTML:x.innerHTML;return ft&&j["!doctype"]&&x.ownerDocument&&x.ownerDocument.doctype&&x.ownerDocument.doctype.name&&ue(Mc,x.ownerDocument.doctype.name)&&(me="<!DOCTYPE "+x.ownerDocument.doctype.name+`>
131
+ `+me),zt&&fs([N,B,W],He=>{me=kn(me,He," ")}),A&&ls?A.createHTML(me):me},t.setConfig=function(){let O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$a(O),fa=!0},t.clearConfig=function(){jt=null,fa=!1},t.isValidAttribute=function(O,k,x){jt||$a({});const M=Z(O),G=Z(k);return Yo(M,G,x)},t.addHook=function(O,k){typeof k=="function"&&$n(R[O],k)},t.removeHook=function(O,k){if(k!==void 0){const x=Oh(R[O],k);return x===-1?void 0:Nh(R[O],x,1)[0]}return kr(R[O])},t.removeHooks=function(O){R[O]=[]},t.removeAllHooks=function(){R=Cr()},t}var ln=Dc();function Wi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ot=Wi();function Oc(e){Ot=e}var At={exec:()=>null};function K(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(a,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(he.caret,"$1"),n=n.replace(a,o),s},getRegex:()=>new RegExp(n,t)};return s}var ef=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),he={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,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"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},tf=/^(?:[ \t]*(?:\n|$))+/,nf=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,sf=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Xn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,af=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,qi=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Nc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Fc=K(Nc).replace(/bull/g,qi).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(),of=K(Nc).replace(/bull/g,qi).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(),ji=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,rf=/^[^\n]+/,Hi=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,lf=K(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Hi).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),cf=K(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,qi).getRegex(),Ys="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",Vi=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,df=K("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Vi).replace("tag",Ys).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Bc=K(ji).replace("hr",Xn).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[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ys).getRegex(),uf=K(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Bc).getRegex(),Gi={blockquote:uf,code:nf,def:lf,fences:sf,heading:af,hr:Xn,html:df,lheading:Fc,list:cf,newline:tf,paragraph:Bc,table:At,text:rf},Er=K("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Xn).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[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ys).getRegex(),pf={...Gi,lheading:of,table:Er,paragraph:K(ji).replace("hr",Xn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Er).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ys).getRegex()},hf={...Gi,html:K(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Vi).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:At,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:K(ji).replace("hr",Xn).replace("heading",` *#{1,6} *[^
132
+ ]`).replace("lheading",Fc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ff=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,gf=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Uc=/^( {2,}|\\)\n(?!\s*$)/,mf=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Js=/[\p{P}\p{S}]/u,Qi=/[\s\p{P}\p{S}]/u,zc=/[^\s\p{P}\p{S}]/u,vf=K(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Qi).getRegex(),Kc=/(?!~)[\p{P}\p{S}]/u,yf=/(?!~)[\s\p{P}\p{S}]/u,bf=/(?:[^\s\p{P}\p{S}]|~)/u,Wc=/(?![*_])[\p{P}\p{S}]/u,wf=/(?![*_])[\s\p{P}\p{S}]/u,$f=/(?:[^\s\p{P}\p{S}]|[*_])/u,kf=K(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",ef?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),qc=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Sf=K(qc,"u").replace(/punct/g,Js).getRegex(),Af=K(qc,"u").replace(/punct/g,Kc).getRegex(),jc="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",_f=K(jc,"gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Qi).replace(/punct/g,Js).getRegex(),Tf=K(jc,"gu").replace(/notPunctSpace/g,bf).replace(/punctSpace/g,yf).replace(/punct/g,Kc).getRegex(),xf=K("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Qi).replace(/punct/g,Js).getRegex(),Cf=K(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Wc).getRegex(),Ef="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Lf=K(Ef,"gu").replace(/notPunctSpace/g,$f).replace(/punctSpace/g,wf).replace(/punct/g,Wc).getRegex(),Rf=K(/\\(punct)/,"gu").replace(/punct/g,Js).getRegex(),Pf=K(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),If=K(Vi).replace("(?:-->|$)","-->").getRegex(),Mf=K("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",If).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ms=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Df=K(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Ms).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Hc=K(/^!?\[(label)\]\[(ref)\]/).replace("label",Ms).replace("ref",Hi).getRegex(),Vc=K(/^!?\[(ref)\](?:\[\])?/).replace("ref",Hi).getRegex(),Of=K("reflink|nolink(?!\\()","g").replace("reflink",Hc).replace("nolink",Vc).getRegex(),Lr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Yi={_backpedal:At,anyPunctuation:Rf,autolink:Pf,blockSkip:kf,br:Uc,code:gf,del:At,delLDelim:At,delRDelim:At,emStrongLDelim:Sf,emStrongRDelimAst:_f,emStrongRDelimUnd:xf,escape:ff,link:Df,nolink:Vc,punctuation:vf,reflink:Hc,reflinkSearch:Of,tag:Mf,text:mf,url:At},Nf={...Yi,link:K(/^!?\[(label)\]\((.*?)\)/).replace("label",Ms).getRegex(),reflink:K(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ms).getRegex()},ui={...Yi,emStrongRDelimAst:Tf,emStrongLDelim:Af,delLDelim:Cf,delRDelim:Lf,url:K(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Lr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:K(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Lr).getRegex()},Ff={...ui,br:K(Uc).replace("{2,}","*").getRegex(),text:K(ui.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ms={normal:Gi,gfm:pf,pedantic:hf},Tn={normal:Yi,gfm:ui,breaks:Ff,pedantic:Nf},Bf={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Rr=e=>Bf[e];function Ue(e,t){if(t){if(he.escapeTest.test(e))return e.replace(he.escapeReplace,Rr)}else if(he.escapeTestNoEncode.test(e))return e.replace(he.escapeReplaceNoEncode,Rr);return e}function Pr(e){try{e=encodeURI(e).replace(he.percentDecode,"%")}catch{return null}return e}function Ir(e,t){let n=e.replace(he.findPipe,(i,o,l)=>{let c=!1,u=o;for(;--u>=0&&l[u]==="\\";)c=!c;return c?"|":" |"}),s=n.split(he.splitPipe),a=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;a<s.length;a++)s[a]=s[a].trim().replace(he.slashPipe,"|");return s}function xn(e,t,n){let s=e.length;if(s===0)return"";let a=0;for(;a<s&&e.charAt(s-a-1)===t;)a++;return e.slice(0,s-a)}function Uf(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return n>0?-2:-1}function zf(e,t=0){let n=t,s="";for(let a of e)if(a===" "){let i=4-n%4;s+=" ".repeat(i),n+=i}else s+=a,n++;return s}function Mr(e,t,n,s,a){let i=t.href,o=t.title||null,l=e[1].replace(a.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,c}function Kf(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(s===null)return t;let a=s[1];return t.split(`
133
133
  `).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[l]=o;return l.length>=a.length?i.slice(a.length):i}).join(`
134
- `)}var Ds=class{options;rules;lexer;constructor(e){this.options=e||Nt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:xn(n,`
135
- `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=Wf(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:s}}}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 s=xn(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:xn(t[0],`
134
+ `)}var Ds=class{options;rules;lexer;constructor(e){this.options=e||Ot}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:xn(n,`
135
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=Kf(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:s}}}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 s=xn(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:xn(t[0],`
136
136
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=xn(t[0],`
137
137
  `).split(`
138
138
  `),s="",a="",i=[];for(;n.length>0;){let o=!1,l=[],c;for(c=0;c<n.length;c++)if(this.rules.other.blockquoteStart.test(n[c]))l.push(n[c]),o=!0;else if(!o)l.push(n[c]);else break;n=n.slice(c);let u=l.join(`
@@ -144,7 +144,7 @@ ${p}`:p;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
144
144
  `),d=this.blockquote($);i[i.length-1]=d,s=s.substring(0,s.length-g.raw.length)+d.raw,a=a.substring(0,a.length-g.text.length)+d.text;break}else if(m?.type==="list"){let g=m,$=g.raw+`
145
145
  `+n.join(`
146
146
  `),d=this.list($);i[i.length-1]=d,s=s.substring(0,s.length-m.raw.length)+d.raw,a=a.substring(0,a.length-g.raw.length)+d.raw,n=$.substring(i.at(-1).raw.length).split(`
147
- `);continue}}return{type:"blockquote",raw:s,tokens:i,text:a}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,a={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let c=!1,u="",p="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let f=Kf(t[2].split(`
147
+ `);continue}}return{type:"blockquote",raw:s,tokens:i,text:a}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,a={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let c=!1,u="",p="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let f=zf(t[2].split(`
148
148
  `,1)[0],t[1].length),m=e.split(`
149
149
  `,1)[0],g=!f.trim(),$=0;if(this.options.pedantic?($=2,p=f.trimStart()):g?$=t[1].length+1:($=f.search(this.rules.other.nonSpaceChar),$=$>4?1:$,p=f.slice($),$+=t[1].length),g&&this.rules.other.blankLine.test(m)&&(u+=m+`
150
150
  `,e=e.substring(m.length+1),c=!0),!c){let d=this.rules.other.nextBulletRegex($),v=this.rules.other.hrRegex($),S=this.rules.other.fencesBeginRegex($),_=this.rules.other.headingBeginRegex($),T=this.rules.other.htmlBeginRegex($),A=this.rules.other.blockquoteBeginRegex($);for(;e;){let C=e.split(`
@@ -153,7 +153,7 @@ ${p}`:p;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
153
153
  `+m}g=!m.trim(),u+=C+`
154
154
  `,e=e.substring(C.length+1),f=L.slice($)}}a.loose||(o?a.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(o=!0)),a.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),a.raw+=u}let l=a.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;a.raw=a.raw.trimEnd();for(let c of a.items){if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),c.task){if(c.text=c.text.replace(this.rules.other.listReplaceTask,""),c.tokens[0]?.type==="text"||c.tokens[0]?.type==="paragraph"){c.tokens[0].raw=c.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),c.tokens[0].text=c.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=p.checked,a.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=p.raw+c.tokens[0].raw,c.tokens[0].text=p.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(p)):c.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):c.tokens.unshift(p)}}if(!a.loose){let u=c.tokens.filter(f=>f.type==="space"),p=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));a.loose=p}}if(a.loose)for(let c of a.items){c.loose=!0;for(let u of c.tokens)u.type==="text"&&(u.type="paragraph")}return a}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a=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:s,title:a}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Ir(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),a=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
155
155
  `):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o<n.length;o++)i.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:i.align[o]});for(let o of a)i.rows.push(Ir(o,i.header.length).map((l,c)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[c]})));return i}}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)===`
156
- `?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 i=xn(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=zf(t[2],"()");if(i===-2)return;if(i>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],a="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],a=i[3])}else a=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),Mr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.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 s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),a=t[s.toLowerCase()];if(!a){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Mr(n,a,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[2])||!n||this.rules.inline.punctuation.exec(n))){let a=[...s[0]].length-1,i,o,l=a,c=0,u=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,t=t.slice(-1*e.length+a);(s=u.exec(t))!=null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(o=[...i].length,s[3]||s[4]){l+=o;continue}else if((s[5]||s[6])&&a%3&&!((a+o)%3)){c+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+c);let p=[...s[0]][0].length,f=e.slice(0,a+s.index+p+o);if(Math.min(a,o)%2){let g=f.slice(1,-1);return{type:"em",raw:f,text:g,tokens:this.lexer.inlineTokens(g)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),a=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&a&&(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,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let a=[...s[0]].length-1,i,o,l=a,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+a);(s=c.exec(t))!=null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(o=[...i].length,o!==a))continue;if(s[3]||s[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let u=[...s[0]][0].length,p=e.slice(0,a+s.index+u+o),f=p.slice(a,-a);return{type:"del",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let a;do a=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(a!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Re=class pi{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Nt,this.options.tokenizer=this.options.tokenizer||new Ds,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:he,block:ms.normal,inline:Tn.normal};this.options.pedantic?(n.block=ms.pedantic,n.inline=Tn.pedantic):this.options.gfm&&(n.block=ms.gfm,this.options.breaks?n.inline=Tn.breaks:n.inline=Tn.gfm),this.tokenizer.rules=n}static get rules(){return{block:ms,inline:Tn}}static lex(t,n){return new pi(n).lex(t)}static lexInline(t,n){return new pi(n).inlineTokens(t)}lex(t){t=t.replace(he.carriageReturn,`
156
+ `?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 i=xn(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=Uf(t[2],"()");if(i===-2)return;if(i>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],a="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],a=i[3])}else a=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),Mr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.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 s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),a=t[s.toLowerCase()];if(!a){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Mr(n,a,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[2])||!n||this.rules.inline.punctuation.exec(n))){let a=[...s[0]].length-1,i,o,l=a,c=0,u=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,t=t.slice(-1*e.length+a);(s=u.exec(t))!=null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(o=[...i].length,s[3]||s[4]){l+=o;continue}else if((s[5]||s[6])&&a%3&&!((a+o)%3)){c+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+c);let p=[...s[0]][0].length,f=e.slice(0,a+s.index+p+o);if(Math.min(a,o)%2){let g=f.slice(1,-1);return{type:"em",raw:f,text:g,tokens:this.lexer.inlineTokens(g)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),a=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&a&&(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,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let a=[...s[0]].length-1,i,o,l=a,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+a);(s=c.exec(t))!=null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(o=[...i].length,o!==a))continue;if(s[3]||s[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let u=[...s[0]][0].length,p=e.slice(0,a+s.index+u+o),f=p.slice(a,-a);return{type:"del",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let a;do a=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(a!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Re=class pi{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ot,this.options.tokenizer=this.options.tokenizer||new Ds,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:he,block:ms.normal,inline:Tn.normal};this.options.pedantic?(n.block=ms.pedantic,n.inline=Tn.pedantic):this.options.gfm&&(n.block=ms.gfm,this.options.breaks?n.inline=Tn.breaks:n.inline=Tn.gfm),this.tokenizer.rules=n}static get rules(){return{block:ms,inline:Tn}}static lex(t,n){return new pi(n).lex(t)}static lexInline(t,n){return new pi(n).inlineTokens(t)}lex(t){t=t.replace(he.carriageReturn,`
157
157
  `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let s=this.inlineQueue[n];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],s=!1){for(this.options.pedantic&&(t=t.replace(he.tabCharGlobal," ").replace(he.spaceLine,""));t;){let a;if(this.options.extensions?.block?.some(o=>(a=o.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 o=n.at(-1);a.raw.length===1&&o!==void 0?o.raw+=`
158
158
  `:n.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
159
159
  `)?"":`
@@ -167,7 +167,7 @@ ${p}`:p;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
167
167
  `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(a),s=i.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(`
168
168
  `)?"":`
169
169
  `)+a.raw,o.text+=`
170
- `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(a);continue}if(t){let o="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let s=t,a=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)c.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,a.index)+"["+"a".repeat(a[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,a.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(a=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)i=a[2]?a[2].length:0,s=s.slice(0,a.index+i)+"["+"a".repeat(a[0].length-i-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let o=!1,l="";for(;t;){o||(l=""),o=!1;let c;if(this.options.extensions?.inline?.some(p=>(c=p.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let p=n.at(-1);c.type==="text"&&p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,s,l)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,s,l)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let u=t;if(this.options.extensions?.startInline){let p=1/0,f=t.slice(1),m;this.options.extensions.startInline.forEach(g=>{m=g.call({lexer:this},f),typeof m=="number"&&m>=0&&(p=Math.min(p,m))}),p<1/0&&p>=0&&(u=t.substring(0,p+1))}if(c=this.tokenizer.inlineText(u)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(l=c.raw.slice(-1)),o=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):n.push(c);continue}if(t){let p="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return n}},Os=class{options;parser;constructor(e){this.options=e||Nt}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(he.notSpaceStart)?.[0],a=e.replace(he.endingNewline,"")+`
170
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(a);continue}if(t){let o="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let s=t,a=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)c.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,a.index)+"["+"a".repeat(a[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,a.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(a=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)i=a[2]?a[2].length:0,s=s.slice(0,a.index+i)+"["+"a".repeat(a[0].length-i-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let o=!1,l="";for(;t;){o||(l=""),o=!1;let c;if(this.options.extensions?.inline?.some(p=>(c=p.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let p=n.at(-1);c.type==="text"&&p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,s,l)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,s,l)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let u=t;if(this.options.extensions?.startInline){let p=1/0,f=t.slice(1),m;this.options.extensions.startInline.forEach(g=>{m=g.call({lexer:this},f),typeof m=="number"&&m>=0&&(p=Math.min(p,m))}),p<1/0&&p>=0&&(u=t.substring(0,p+1))}if(c=this.tokenizer.inlineText(u)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(l=c.raw.slice(-1)),o=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):n.push(c);continue}if(t){let p="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return n}},Os=class{options;parser;constructor(e){this.options=e||Ot}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(he.notSpaceStart)?.[0],a=e.replace(he.endingNewline,"")+`
171
171
  `;return s?'<pre><code class="language-'+Ue(s)+'">'+(n?a:Ue(a,!0))+`</code></pre>
172
172
  `:"<pre><code>"+(n?a:Ue(a,!0))+`</code></pre>
173
173
  `}blockquote({tokens:e}){return`<blockquote>
@@ -185,11 +185,11 @@ ${this.parser.parse(e)}</blockquote>
185
185
  `}tablerow({text:e}){return`<tr>
186
186
  ${e}</tr>
187
187
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
188
- `}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>${Ue(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 s=this.parser.parseInline(n),a=Pr(e);if(a===null)return s;e=a;let i='<a href="'+e+'"';return t&&(i+=' title="'+Ue(t)+'"'),i+=">"+s+"</a>",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let a=Pr(e);if(a===null)return Ue(n);e=a;let i=`<img src="${e}" alt="${Ue(n)}"`;return t&&(i+=` title="${Ue(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ue(e.text)}},Ji=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}},Pe=class hi{options;renderer;textRenderer;constructor(t){this.options=t||Nt,this.options.renderer=this.options.renderer||new Os,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ji}static parse(t,n){return new hi(n).parse(t)}static parseInline(t,n){return new hi(n).parseInline(t)}parse(t){let n="";for(let s=0;s<t.length;s++){let a=t[s];if(this.options.extensions?.renderers?.[a.type]){let o=a,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let i=a;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(t,n=this.renderer){let s="";for(let a=0;a<t.length;a++){let i=t[a];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){s+=l||"";continue}}let o=i;switch(o.type){case"escape":{s+=n.text(o);break}case"html":{s+=n.html(o);break}case"link":{s+=n.link(o);break}case"image":{s+=n.image(o);break}case"checkbox":{s+=n.checkbox(o);break}case"strong":{s+=n.strong(o);break}case"em":{s+=n.em(o);break}case"codespan":{s+=n.codespan(o);break}case"br":{s+=n.br(o);break}case"del":{s+=n.del(o);break}case"text":{s+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}},Rn=class{options;block;constructor(t){this.options=t||Nt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?Re.lex:Re.lexInline}provideParser(){return this.block?Pe.parse:Pe.parseInline}},qf=class{defaults=Wi();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Pe;Renderer=Os;TextRenderer=Ji;Lexer=Re;Tokenizer=Ds;Hooks=Rn;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let a=s;for(let i of a.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of a.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let a=s;n=n.concat(this.walkTokens(a.items,t));break}default:{let a=s;this.defaults.extensions?.childTokens?.[a.type]?this.defaults.extensions.childTokens[a.type].forEach(i=>{let o=a[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let i=t.renderers[a.name];i?t.renderers[a.name]=function(...o){let l=a.renderer.apply(this,o);return l===!1&&(l=i.apply(this,o)),l}:t.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[a.level];i?i.unshift(a.tokenizer):t[a.level]=[a.tokenizer],a.start&&(a.level==="block"?t.startBlock?t.startBlock.push(a.start):t.startBlock=[a.start]:a.level==="inline"&&(t.startInline?t.startInline.push(a.start):t.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(t.childTokens[a.name]=a.childTokens)}),s.extensions=t),n.renderer){let a=this.defaults.renderer||new Os(this.defaults);for(let i in n.renderer){if(!(i in a))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,l=n.renderer[o],c=a[o];a[o]=(...u)=>{let p=l.apply(a,u);return p===!1&&(p=c.apply(a,u)),p||""}}s.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new Ds(this.defaults);for(let i in n.tokenizer){if(!(i in a))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,l=n.tokenizer[o],c=a[o];a[o]=(...u)=>{let p=l.apply(a,u);return p===!1&&(p=c.apply(a,u)),p}}s.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new Rn;for(let i in n.hooks){if(!(i in a))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,l=n.hooks[o],c=a[o];Rn.passThroughHooks.has(i)?a[o]=u=>{if(this.defaults.async&&Rn.passThroughHooksRespectAsync.has(i))return(async()=>{let f=await l.call(a,u);return c.call(a,f)})();let p=l.call(a,u);return c.call(a,p)}:a[o]=(...u)=>{if(this.defaults.async)return(async()=>{let f=await l.apply(a,u);return f===!1&&(f=await c.apply(a,u)),f})();let p=l.apply(a,u);return p===!1&&(p=c.apply(a,u)),p}}s.hooks=a}if(n.walkTokens){let a=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let l=[];return l.push(i.call(this,o)),a&&(l=l.concat(a.call(this,o))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Re.lex(e,t??this.defaults)}parser(e,t){return Pe.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},a={...this.defaults,...s},i=this.onError(!!a.silent,!!a.async);if(this.defaults.async===!0&&s.async===!1)return i(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 i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(a.hooks&&(a.hooks.options=a,a.hooks.block=e),a.async)return(async()=>{let o=a.hooks?await a.hooks.preprocess(t):t,l=await(a.hooks?await a.hooks.provideLexer():e?Re.lex:Re.lexInline)(o,a),c=a.hooks?await a.hooks.processAllTokens(l):l;a.walkTokens&&await Promise.all(this.walkTokens(c,a.walkTokens));let u=await(a.hooks?await a.hooks.provideParser():e?Pe.parse:Pe.parseInline)(c,a);return a.hooks?await a.hooks.postprocess(u):u})().catch(i);try{a.hooks&&(t=a.hooks.preprocess(t));let o=(a.hooks?a.hooks.provideLexer():e?Re.lex:Re.lexInline)(t,a);a.hooks&&(o=a.hooks.processAllTokens(o)),a.walkTokens&&this.walkTokens(o,a.walkTokens);let l=(a.hooks?a.hooks.provideParser():e?Pe.parse:Pe.parseInline)(o,a);return a.hooks&&(l=a.hooks.postprocess(l)),l}catch(o){return i(o)}}}onError(e,t){return n=>{if(n.message+=`
189
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ue(n.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},Rt=new qf;function q(e,t){return Rt.parse(e,t)}q.options=q.setOptions=function(e){return Rt.setOptions(e),q.defaults=Rt.defaults,Oc(q.defaults),q};q.getDefaults=Wi;q.defaults=Nt;q.use=function(...e){return Rt.use(...e),q.defaults=Rt.defaults,Oc(q.defaults),q};q.walkTokens=function(e,t){return Rt.walkTokens(e,t)};q.parseInline=Rt.parseInline;q.Parser=Pe;q.parser=Pe.parse;q.Renderer=Os;q.TextRenderer=Ji;q.Lexer=Re;q.lexer=Re.lex;q.Tokenizer=Ds;q.Hooks=Rn;q.parse=q;q.options;q.setOptions;q.use;q.walkTokens;q.parseInline;Pe.parse;Re.lex;q.setOptions({gfm:!0,breaks:!0,mangle:!1});const jf=/\.(html?|css|js|ts|tsx|jsx|json|md|txt|csv|py|sh|yaml|yml|xml|svg|png|jpe?g|gif|webp|pdf|log)$/i,Hf=new RegExp("(?<![(\\[`])(?:~\\/|\\/(?:Users|home|tmp|var|opt|etc|godmode)\\/)[\\w/.+@-]+\\.\\w+","g");function Vf(e){const t=e.split(/(```[\s\S]*?```|`[^`\n]+`)/g);for(let n=0;n<t.length;n++)n%2===0&&(t[n]=t[n].replace(Hf,s=>{if(!jf.test(s))return s;const a=s.startsWith("~/")?`file:///~/${s.slice(2)}`:`file://${s}`;return`[${s.split("/").pop()??s}](${a})`}));return t.join("")}const jn=["a","article","aside","b","blockquote","br","caption","col","colgroup","code","div","del","details","em","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","img","i","input","li","main","nav","ol","p","pre","section","span","strong","sub","sup","summary","table","tbody","td","th","thead","tr","ul"],Hn=["alt","checked","class","decoding","disabled","height","href","loading","open","rel","src","start","target","title","type","width","style"],Dr=/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|file):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;let Or=!1;const Gf=14e4,Qf=14e4,Yf=200,Pa=5e4,xt=new Map;function Jf(e){const t=xt.get(e);return t===void 0?null:(xt.delete(e),xt.set(e,t),t)}function Nr(e,t){if(xt.set(e,t),xt.size<=Yf)return;const n=xt.keys().next().value;n&&xt.delete(n)}function Xs(){Or||(Or=!0,ln.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function ye(e){const t=e.trim();if(!t)return"";if(Xs(),t.length<=Pa){const o=Jf(t);if(o!==null)return o}const n=Rc(t,Gf),s=n.truncated?`
188
+ `}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>${Ue(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 s=this.parser.parseInline(n),a=Pr(e);if(a===null)return s;e=a;let i='<a href="'+e+'"';return t&&(i+=' title="'+Ue(t)+'"'),i+=">"+s+"</a>",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let a=Pr(e);if(a===null)return Ue(n);e=a;let i=`<img src="${e}" alt="${Ue(n)}"`;return t&&(i+=` title="${Ue(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ue(e.text)}},Ji=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}},Pe=class hi{options;renderer;textRenderer;constructor(t){this.options=t||Ot,this.options.renderer=this.options.renderer||new Os,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ji}static parse(t,n){return new hi(n).parse(t)}static parseInline(t,n){return new hi(n).parseInline(t)}parse(t){let n="";for(let s=0;s<t.length;s++){let a=t[s];if(this.options.extensions?.renderers?.[a.type]){let o=a,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let i=a;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(t,n=this.renderer){let s="";for(let a=0;a<t.length;a++){let i=t[a];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){s+=l||"";continue}}let o=i;switch(o.type){case"escape":{s+=n.text(o);break}case"html":{s+=n.html(o);break}case"link":{s+=n.link(o);break}case"image":{s+=n.image(o);break}case"checkbox":{s+=n.checkbox(o);break}case"strong":{s+=n.strong(o);break}case"em":{s+=n.em(o);break}case"codespan":{s+=n.codespan(o);break}case"br":{s+=n.br(o);break}case"del":{s+=n.del(o);break}case"text":{s+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}},Rn=class{options;block;constructor(t){this.options=t||Ot}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?Re.lex:Re.lexInline}provideParser(){return this.block?Pe.parse:Pe.parseInline}},Wf=class{defaults=Wi();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Pe;Renderer=Os;TextRenderer=Ji;Lexer=Re;Tokenizer=Ds;Hooks=Rn;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let a=s;for(let i of a.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of a.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let a=s;n=n.concat(this.walkTokens(a.items,t));break}default:{let a=s;this.defaults.extensions?.childTokens?.[a.type]?this.defaults.extensions.childTokens[a.type].forEach(i=>{let o=a[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let i=t.renderers[a.name];i?t.renderers[a.name]=function(...o){let l=a.renderer.apply(this,o);return l===!1&&(l=i.apply(this,o)),l}:t.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[a.level];i?i.unshift(a.tokenizer):t[a.level]=[a.tokenizer],a.start&&(a.level==="block"?t.startBlock?t.startBlock.push(a.start):t.startBlock=[a.start]:a.level==="inline"&&(t.startInline?t.startInline.push(a.start):t.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(t.childTokens[a.name]=a.childTokens)}),s.extensions=t),n.renderer){let a=this.defaults.renderer||new Os(this.defaults);for(let i in n.renderer){if(!(i in a))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,l=n.renderer[o],c=a[o];a[o]=(...u)=>{let p=l.apply(a,u);return p===!1&&(p=c.apply(a,u)),p||""}}s.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new Ds(this.defaults);for(let i in n.tokenizer){if(!(i in a))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,l=n.tokenizer[o],c=a[o];a[o]=(...u)=>{let p=l.apply(a,u);return p===!1&&(p=c.apply(a,u)),p}}s.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new Rn;for(let i in n.hooks){if(!(i in a))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,l=n.hooks[o],c=a[o];Rn.passThroughHooks.has(i)?a[o]=u=>{if(this.defaults.async&&Rn.passThroughHooksRespectAsync.has(i))return(async()=>{let f=await l.call(a,u);return c.call(a,f)})();let p=l.call(a,u);return c.call(a,p)}:a[o]=(...u)=>{if(this.defaults.async)return(async()=>{let f=await l.apply(a,u);return f===!1&&(f=await c.apply(a,u)),f})();let p=l.apply(a,u);return p===!1&&(p=c.apply(a,u)),p}}s.hooks=a}if(n.walkTokens){let a=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let l=[];return l.push(i.call(this,o)),a&&(l=l.concat(a.call(this,o))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Re.lex(e,t??this.defaults)}parser(e,t){return Pe.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},a={...this.defaults,...s},i=this.onError(!!a.silent,!!a.async);if(this.defaults.async===!0&&s.async===!1)return i(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 i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(a.hooks&&(a.hooks.options=a,a.hooks.block=e),a.async)return(async()=>{let o=a.hooks?await a.hooks.preprocess(t):t,l=await(a.hooks?await a.hooks.provideLexer():e?Re.lex:Re.lexInline)(o,a),c=a.hooks?await a.hooks.processAllTokens(l):l;a.walkTokens&&await Promise.all(this.walkTokens(c,a.walkTokens));let u=await(a.hooks?await a.hooks.provideParser():e?Pe.parse:Pe.parseInline)(c,a);return a.hooks?await a.hooks.postprocess(u):u})().catch(i);try{a.hooks&&(t=a.hooks.preprocess(t));let o=(a.hooks?a.hooks.provideLexer():e?Re.lex:Re.lexInline)(t,a);a.hooks&&(o=a.hooks.processAllTokens(o)),a.walkTokens&&this.walkTokens(o,a.walkTokens);let l=(a.hooks?a.hooks.provideParser():e?Pe.parse:Pe.parseInline)(o,a);return a.hooks&&(l=a.hooks.postprocess(l)),l}catch(o){return i(o)}}}onError(e,t){return n=>{if(n.message+=`
189
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ue(n.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},Lt=new Wf;function q(e,t){return Lt.parse(e,t)}q.options=q.setOptions=function(e){return Lt.setOptions(e),q.defaults=Lt.defaults,Oc(q.defaults),q};q.getDefaults=Wi;q.defaults=Ot;q.use=function(...e){return Lt.use(...e),q.defaults=Lt.defaults,Oc(q.defaults),q};q.walkTokens=function(e,t){return Lt.walkTokens(e,t)};q.parseInline=Lt.parseInline;q.Parser=Pe;q.parser=Pe.parse;q.Renderer=Os;q.TextRenderer=Ji;q.Lexer=Re;q.lexer=Re.lex;q.Tokenizer=Ds;q.Hooks=Rn;q.parse=q;q.options;q.setOptions;q.use;q.walkTokens;q.parseInline;Pe.parse;Re.lex;q.setOptions({gfm:!0,breaks:!0,mangle:!1});const qf=/\.(html?|css|js|ts|tsx|jsx|json|md|txt|csv|py|sh|yaml|yml|xml|svg|png|jpe?g|gif|webp|pdf|log)$/i,jf=new RegExp("(?<![(\\[`])(?:~\\/|\\/(?:Users|home|tmp|var|opt|etc|godmode)\\/)[\\w/.+@-]+\\.\\w+","g");function Hf(e){const t=e.split(/(```[\s\S]*?```|`[^`\n]+`)/g);for(let n=0;n<t.length;n++)n%2===0&&(t[n]=t[n].replace(jf,s=>{if(!qf.test(s))return s;const a=s.startsWith("~/")?`file:///~/${s.slice(2)}`:`file://${s}`;return`[${s.split("/").pop()??s}](${a})`}));return t.join("")}const jn=["a","article","aside","b","blockquote","br","caption","col","colgroup","code","div","del","details","em","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","img","i","input","li","main","nav","ol","p","pre","section","span","strong","sub","sup","summary","table","tbody","td","th","thead","tr","ul"],Hn=["alt","checked","class","decoding","disabled","height","href","loading","open","rel","src","start","target","title","type","width","style"],Dr=/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|file):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;let Or=!1;const Vf=14e4,Gf=14e4,Qf=200,Pa=5e4,Tt=new Map;function Yf(e){const t=Tt.get(e);return t===void 0?null:(Tt.delete(e),Tt.set(e,t),t)}function Nr(e,t){if(Tt.set(e,t),Tt.size<=Qf)return;const n=Tt.keys().next().value;n&&Tt.delete(n)}function Xs(){Or||(Or=!0,ln.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function ye(e){const t=e.trim();if(!t)return"";if(Xs(),t.length<=Pa){const o=Yf(t);if(o!==null)return o}const n=Rc(t,Vf),s=n.truncated?`
190
190
 
191
- … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>Qf){const l=`<pre class="code-block">${ig(`${n.text}${s}`)}</pre>`,c=ln.sanitize(l,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn,ALLOWED_URI_REGEXP:Dr});return t.length<=Pa&&Nr(t,c),c}const a=q.parse(`${n.text}${s}`),i=ln.sanitize(a,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn,ALLOWED_URI_REGEXP:Dr});return t.length<=Pa&&Nr(t,i),i}function Xf(e){const t=e.trim();if(!t)return"";Xs();const n=q.parse(t);return ln.sanitize(n,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn}).replace(/<input([^>]*)\bdisabled\b([^>]*)>/g,"<input$1$2>")}function Gc(e){const t=e.trim();return t?(Xs(),ln.sanitize(t,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn,FORBID_TAGS:["base","iframe","link","meta","object","script"]})):""}const Zf=[...jn,"svg","path","circle","ellipse","rect","line","polyline","polygon","text","tspan","g","defs","linearGradient","radialGradient","stop","clipPath","mask","use","symbol","marker","pattern","animate","animateTransform"],eg=[...Hn,"viewBox","xmlns","preserveAspectRatio","d","cx","cy","r","rx","ry","x","x1","x2","y","y1","y2","dx","dy","fill","stroke","stroke-width","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","transform","opacity","points","text-anchor","dominant-baseline","font-size","font-weight","offset","stop-color","stop-opacity","gradientUnits","gradientTransform","marker-start","marker-mid","marker-end","clip-path","patternUnits","patternTransform","rotate","textLength","lengthAdjust","values","dur","repeatCount","attributeName","from","to","begin","calcMode","keySplines","keyTimes"];function tg(e){const t=e.trim();if(!t)return"";Xs();const{styles:n,html:s}=ng(t),a=ln.sanitize(s,{ALLOWED_TAGS:Zf,ALLOWED_ATTR:eg,FORBID_TAGS:["base","iframe","link","meta","object","script","style"]}),i=".dashboard-render";return n.map(l=>`<style>${ag(l,i)}</style>`).join(`
192
- `)+a}function ng(e){const t=[],n=e.replace(/<style[^>]*>([\s\S]*?)<\/style>/gi,(o,l)=>(t.push(l),"")),s=n.match(/<body[^>]*>([\s\S]*)<\/body>/i),i=(s?s[1]:n).replace(/<!DOCTYPE[^>]*>/gi,"").replace(/<\/?html[^>]*>/gi,"").replace(/<\/?head[^>]*>/gi,"").replace(/<\/?body[^>]*>/gi,"").replace(/<title[^>]*>[\s\S]*?<\/title>/gi,"").replace(/<meta[^>]*\/?>/gi,"").replace(/<link[^>]*\/?>/gi,"");return{styles:t,html:i}}function sg(e,t){let n=0;for(let s=t;s<e.length;s++)if(e[s]==="{")n++;else if(e[s]==="}"&&(n--,n===0))return s+1;return e.length}function ag(e,t){const n=e.replace(/@import\b[^;]*;/gi,""),s=[];let a=0;for(;a<n.length;){if(/\s/.test(n[a])){s.push(n[a]),a++;continue}if(n[a]==="/"&&n[a+1]==="*"){const p=n.indexOf("*/",a+2),f=p===-1?n.length:p+2;s.push(n.slice(a,f)),a=f;continue}if(n[a]==="}"){s.push("}"),a++;continue}if(/^@(-webkit-)?keyframes\s/.test(n.slice(a,a+30))){const p=sg(n,a);s.push(n.slice(a,p)),a=p;continue}if(/^@(media|supports|container|layer)\b/.test(n.slice(a,a+20))){const p=n.indexOf("{",a);if(p===-1){s.push(n.slice(a));break}s.push(n.slice(a,p+1)),a=p+1;continue}const i=n.indexOf("{",a);if(i===-1){s.push(n.slice(a));break}const o=n.slice(a,i).trim(),l=n.indexOf("}",i);if(l===-1){s.push(n.slice(a));break}const c=n.slice(i+1,l),u=o.split(",").map(p=>{const f=p.trim();if(!f)return p;if(f==="*")return`${t}, ${t} *`;if(/^(html|body|:root)$/i.test(f))return t;const m=f.replace(/^(html|body|:root)\s+/i,"");return`${t} ${m}`}).join(", ");s.push(`${u} {${c}}`),a=l+1}return s.join("")}function ig(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const og=500;let bt="",wt="";function Qc(e){const t=e.trim();if(!t)return"";if(t.length<og)return ye(t);const n=lg(t);if(n<0)return ye(t);const s=t.slice(0,n),a=t.slice(n);if(s===bt)return wt+ye(a);if(s.startsWith(bt)&&bt.length>0){const i=s.slice(bt.length);return wt=wt+ye(i),bt=s,wt+ye(a)}return wt=ye(s),bt=s,wt+ye(a)}function rg(){bt="",wt=""}function lg(e){let t=!1,n="";const s=[];let a=0;for(;a<e.length;){const i=e.indexOf(`
191
+ … truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>Gf){const l=`<pre class="code-block">${ag(`${n.text}${s}`)}</pre>`,c=ln.sanitize(l,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn,ALLOWED_URI_REGEXP:Dr});return t.length<=Pa&&Nr(t,c),c}const a=q.parse(`${n.text}${s}`),i=ln.sanitize(a,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn,ALLOWED_URI_REGEXP:Dr});return t.length<=Pa&&Nr(t,i),i}function Jf(e){const t=e.trim();if(!t)return"";Xs();const n=q.parse(t);return ln.sanitize(n,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn}).replace(/<input([^>]*)\bdisabled\b([^>]*)>/g,"<input$1$2>")}function Gc(e){const t=e.trim();return t?(Xs(),ln.sanitize(t,{ALLOWED_TAGS:jn,ALLOWED_ATTR:Hn,FORBID_TAGS:["base","iframe","link","meta","object","script"]})):""}const Xf=[...jn,"svg","path","circle","ellipse","rect","line","polyline","polygon","text","tspan","g","defs","linearGradient","radialGradient","stop","clipPath","mask","use","symbol","marker","pattern","animate","animateTransform"],Zf=[...Hn,"viewBox","xmlns","preserveAspectRatio","d","cx","cy","r","rx","ry","x","x1","x2","y","y1","y2","dx","dy","fill","stroke","stroke-width","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","transform","opacity","points","text-anchor","dominant-baseline","font-size","font-weight","offset","stop-color","stop-opacity","gradientUnits","gradientTransform","marker-start","marker-mid","marker-end","clip-path","patternUnits","patternTransform","rotate","textLength","lengthAdjust","values","dur","repeatCount","attributeName","from","to","begin","calcMode","keySplines","keyTimes"];function eg(e){const t=e.trim();if(!t)return"";Xs();const{styles:n,html:s}=tg(t),a=ln.sanitize(s,{ALLOWED_TAGS:Xf,ALLOWED_ATTR:Zf,FORBID_TAGS:["base","iframe","link","meta","object","script","style"]}),i=".dashboard-render";return n.map(l=>`<style>${sg(l,i)}</style>`).join(`
192
+ `)+a}function tg(e){const t=[],n=e.replace(/<style[^>]*>([\s\S]*?)<\/style>/gi,(o,l)=>(t.push(l),"")),s=n.match(/<body[^>]*>([\s\S]*)<\/body>/i),i=(s?s[1]:n).replace(/<!DOCTYPE[^>]*>/gi,"").replace(/<\/?html[^>]*>/gi,"").replace(/<\/?head[^>]*>/gi,"").replace(/<\/?body[^>]*>/gi,"").replace(/<title[^>]*>[\s\S]*?<\/title>/gi,"").replace(/<meta[^>]*\/?>/gi,"").replace(/<link[^>]*\/?>/gi,"");return{styles:t,html:i}}function ng(e,t){let n=0;for(let s=t;s<e.length;s++)if(e[s]==="{")n++;else if(e[s]==="}"&&(n--,n===0))return s+1;return e.length}function sg(e,t){const n=e.replace(/@import\b[^;]*;/gi,""),s=[];let a=0;for(;a<n.length;){if(/\s/.test(n[a])){s.push(n[a]),a++;continue}if(n[a]==="/"&&n[a+1]==="*"){const p=n.indexOf("*/",a+2),f=p===-1?n.length:p+2;s.push(n.slice(a,f)),a=f;continue}if(n[a]==="}"){s.push("}"),a++;continue}if(/^@(-webkit-)?keyframes\s/.test(n.slice(a,a+30))){const p=ng(n,a);s.push(n.slice(a,p)),a=p;continue}if(/^@(media|supports|container|layer)\b/.test(n.slice(a,a+20))){const p=n.indexOf("{",a);if(p===-1){s.push(n.slice(a));break}s.push(n.slice(a,p+1)),a=p+1;continue}const i=n.indexOf("{",a);if(i===-1){s.push(n.slice(a));break}const o=n.slice(a,i).trim(),l=n.indexOf("}",i);if(l===-1){s.push(n.slice(a));break}const c=n.slice(i+1,l),u=o.split(",").map(p=>{const f=p.trim();if(!f)return p;if(f==="*")return`${t}, ${t} *`;if(/^(html|body|:root)$/i.test(f))return t;const m=f.replace(/^(html|body|:root)\s+/i,"");return`${t} ${m}`}).join(", ");s.push(`${u} {${c}}`),a=l+1}return s.join("")}function ag(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const ig=500;let bt="",wt="";function Qc(e){const t=e.trim();if(!t)return"";if(t.length<ig)return ye(t);const n=rg(t);if(n<0)return ye(t);const s=t.slice(0,n),a=t.slice(n);if(s===bt)return wt+ye(a);if(s.startsWith(bt)&&bt.length>0){const i=s.slice(bt.length);return wt=wt+ye(i),bt=s,wt+ye(a)}return wt=ye(s),bt=s,wt+ye(a)}function og(){bt="",wt=""}function rg(e){let t=!1,n="";const s=[];let a=0;for(;a<e.length;){const i=e.indexOf(`
193
193
  `,a),o=i===-1?e.length:i,l=e.slice(a,o),c=l.trimStart(),u=c.match(/^(`{3,}|~{3,})/);if(u){const p=u[1];t?p.charAt(0)===n.charAt(0)&&p.length>=n.length&&c.slice(p.length).trim()===""&&(t=!1,n=""):(t=!0,n=p)}if(!t&&l.trim()===""){let p=o+1;for(;p<e.length&&e[p]===`
194
194
  `;)p++;p<e.length&&(s.length===0||s[s.length-1]!==p)&&s.push(p)}a=i===-1?e.length:i+1}return s.length<2?-1:s[s.length-2]}const H={messageSquare:r`
195
195
  <svg viewBox="0 0 24 24">
@@ -480,28 +480,28 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
480
480
  <path d="M8.5 2h7" />
481
481
  <path d="M7 16.5h10" />
482
482
  </svg>
483
- `},cg=1500,dg=2e3,Yc="Copy as markdown",ug="Copied",pg="Copy failed";async function hg(e){if(!e)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function vs(e,t){e.title=t,e.setAttribute("aria-label",t)}function fg(e){const t=e.label??Yc;return r`
483
+ `},lg=1500,cg=2e3,Yc="Copy as markdown",dg="Copied",ug="Copy failed";async function pg(e){if(!e)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function vs(e,t){e.title=t,e.setAttribute("aria-label",t)}function hg(e){const t=e.label??Yc;return r`
484
484
  <button
485
485
  class="chat-copy-btn"
486
486
  type="button"
487
487
  title=${t}
488
488
  aria-label=${t}
489
- @click=${async n=>{const s=n.currentTarget;if(s?.querySelector(".chat-copy-btn__icon"),!s||s.dataset.copying==="1")return;s.dataset.copying="1",s.setAttribute("aria-busy","true"),s.disabled=!0;const a=await hg(e.text());if(s.isConnected){if(delete s.dataset.copying,s.removeAttribute("aria-busy"),s.disabled=!1,!a){s.dataset.error="1",vs(s,pg),window.setTimeout(()=>{s.isConnected&&(delete s.dataset.error,vs(s,t))},dg);return}s.dataset.copied="1",vs(s,ug),window.setTimeout(()=>{s.isConnected&&(delete s.dataset.copied,vs(s,t))},cg)}}}
489
+ @click=${async n=>{const s=n.currentTarget;if(s?.querySelector(".chat-copy-btn__icon"),!s||s.dataset.copying==="1")return;s.dataset.copying="1",s.setAttribute("aria-busy","true"),s.disabled=!0;const a=await pg(e.text());if(s.isConnected){if(delete s.dataset.copying,s.removeAttribute("aria-busy"),s.disabled=!1,!a){s.dataset.error="1",vs(s,ug),window.setTimeout(()=>{s.isConnected&&(delete s.dataset.error,vs(s,t))},cg);return}s.dataset.copied="1",vs(s,dg),window.setTimeout(()=>{s.isConnected&&(delete s.dataset.copied,vs(s,t))},lg)}}}
490
490
  >
491
491
  <span class="chat-copy-btn__icon" aria-hidden="true">
492
492
  <span class="chat-copy-btn__icon-copy">${H.copy}</span>
493
493
  <span class="chat-copy-btn__icon-check">${H.check}</span>
494
494
  </span>
495
495
  </button>
496
- `}function gg(e){return fg({text:()=>e,label:Yc})}const Fr="NO_REPLY",mg=/<system-context\b[^>]*>[\s\S]*?<\/system-context>/gi,vg=["internal system context injected by godmode","treat it as invisible background instructions only","persistence protocol (non-negotiable)"];function Ia(e){let t=e.replace(mg,"").trim();const n=t.toLowerCase();for(const s of vg){const a=n.indexOf(s);if(a!==-1){const i=a+s.length,o=t.slice(i),l=o.search(/\n\n(?=[A-Z])/);l!==-1?t=o.slice(l).trim():t="";break}}return t}const yg=/^\s*\{[^{}]*"type"\s*:\s*"error"[^{}]*"error"\s*:\s*\{/;function Jc(e){if(!yg.test(e))return null;try{const t=JSON.parse(e);if(t?.type==="error"&&t?.error?.message)return`*API error: ${t.error.message}*`}catch{}return null}const bg=/^\[([^\]]+)\]\s*/,wg=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Ma=new WeakMap,Da=new WeakMap;function $g(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:wg.some(t=>e.startsWith(`${t} `))}function Ss(e){const t=e.match(bg);if(!t)return e;const n=t[1]??"";return $g(n)?e.slice(t[0].length):e}function Oa(e){const t=e.trim();return t===Fr||t.startsWith(`${Fr}
497
- `)}function Ct(e){const t=e,n=typeof t.role=="string"?t.role:"",s=t.content;if(typeof s=="string"){const a=Ia(s);if(!a)return null;const i=n==="assistant"?_a(a):Ss(a);return Oa(i)?null:i}if(Array.isArray(s)){const a=s.map(i=>{const o=i;return o.type==="text"&&typeof o.text=="string"?Ia(o.text):null}).filter(i=>typeof i=="string"&&i.length>0);if(a.length>0){const i=a.join(`
498
- `),o=n==="assistant"?_a(i):Ss(i);return Oa(o)?null:o}}if(typeof t.text=="string"){const a=Ia(t.text);if(!a)return null;const i=n==="assistant"?_a(a):Ss(a);return Oa(i)?null:i}return null}function Xi(e){if(!e||typeof e!="object")return Ct(e);const t=e;if(Ma.has(t))return Ma.get(t)??null;const n=Ct(e);return Ma.set(t,n),n}function fi(e){const n=e.content,s=[];if(Array.isArray(n))for(const l of n){const c=l;if(c.type==="thinking"&&typeof c.thinking=="string"){const u=c.thinking.trim();u&&s.push(u)}}if(s.length>0)return s.join(`
496
+ `}function fg(e){return hg({text:()=>e,label:Yc})}const Fr="NO_REPLY",gg=/<system-context\b[^>]*>[\s\S]*?<\/system-context>/gi,mg=["internal system context injected by godmode","treat it as invisible background instructions only","persistence protocol (non-negotiable)"];function Ia(e){let t=e.replace(gg,"").trim();const n=t.toLowerCase();for(const s of mg){const a=n.indexOf(s);if(a!==-1){const i=a+s.length,o=t.slice(i),l=o.search(/\n\n(?=[A-Z])/);l!==-1?t=o.slice(l).trim():t="";break}}return t}const vg=/^\s*\{[^{}]*"type"\s*:\s*"error"[^{}]*"error"\s*:\s*\{/;function Jc(e){if(!vg.test(e))return null;try{const t=JSON.parse(e);if(t?.type==="error"&&t?.error?.message)return`*API error: ${t.error.message}*`}catch{}return null}const yg=/^\[([^\]]+)\]\s*/,bg=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Ma=new WeakMap,Da=new WeakMap;function wg(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:bg.some(t=>e.startsWith(`${t} `))}function Ss(e){const t=e.match(yg);if(!t)return e;const n=t[1]??"";return wg(n)?e.slice(t[0].length):e}function Oa(e){const t=e.trim();return t===Fr||t.startsWith(`${Fr}
497
+ `)}function xt(e){const t=e,n=typeof t.role=="string"?t.role:"",s=t.content;if(typeof s=="string"){const a=Ia(s);if(!a)return null;const i=n==="assistant"?_a(a):Ss(a);return Oa(i)?null:i}if(Array.isArray(s)){const a=s.map(i=>{const o=i;return o.type==="text"&&typeof o.text=="string"?Ia(o.text):null}).filter(i=>typeof i=="string"&&i.length>0);if(a.length>0){const i=a.join(`
498
+ `),o=n==="assistant"?_a(i):Ss(i);return Oa(o)?null:o}}if(typeof t.text=="string"){const a=Ia(t.text);if(!a)return null;const i=n==="assistant"?_a(a):Ss(a);return Oa(i)?null:i}return null}function Xi(e){if(!e||typeof e!="object")return xt(e);const t=e;if(Ma.has(t))return Ma.get(t)??null;const n=xt(e);return Ma.set(t,n),n}function fi(e){const n=e.content,s=[];if(Array.isArray(n))for(const l of n){const c=l;if(c.type==="thinking"&&typeof c.thinking=="string"){const u=c.thinking.trim();u&&s.push(u)}}if(s.length>0)return s.join(`
499
499
  `);const a=Zc(e);if(!a)return null;const o=[...a.matchAll(/<\s*think(?:ing)?\s*>([\s\S]*?)<\s*\/\s*think(?:ing)?\s*>/gi)].map(l=>(l[1]??"").trim()).filter(Boolean);return o.length>0?o.join(`
500
500
  `):null}function Xc(e){if(!e||typeof e!="object")return fi(e);const t=e;if(Da.has(t))return Da.get(t)??null;const n=fi(e);return Da.set(t,n),n}function Zc(e){const t=e,n=t.content;if(typeof n=="string")return n;if(Array.isArray(n)){const s=n.map(a=>{const i=a;return i.type==="text"&&typeof i.text=="string"?i.text:null}).filter(a=>typeof a=="string");if(s.length>0)return s.join(`
501
501
  `)}return typeof t.text=="string"?t.text:null}function ed(e){const t=e.trim();if(!t)return"";const n=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>`_${s}_`);return n.length?["_Reasoning:_",...n].join(`
502
- `):""}const kg=Object.freeze(Object.defineProperty({__proto__:null,extractRawText:Zc,extractText:Ct,extractTextCached:Xi,extractThinking:fi,extractThinkingCached:Xc,formatApiError:Jc,formatReasoningMarkdown:ed,stripEnvelope:Ss},Symbol.toStringTag,{value:"Module"}));function td(e){const t=e;let n=typeof t.role=="string"?t.role:"unknown";const s=typeof t.toolCallId=="string"||typeof t.tool_call_id=="string",a=t.content,i=Array.isArray(a)?a:null,o=Array.isArray(i)&&i.some(f=>{const m=f,g=(typeof m.type=="string"?m.type:"").toLowerCase();return g==="toolresult"||g==="tool_result"}),l=typeof t.toolName=="string"||typeof t.tool_name=="string";(s||o||l)&&(n="toolResult");let c=[];typeof t.content=="string"?c=[{type:"text",text:t.content}]:Array.isArray(t.content)?c=t.content.map(f=>({type:f.type||"text",text:f.text,name:f.name,args:f.args||f.arguments})):typeof t.text=="string"&&(c=[{type:"text",text:t.text}]);const u=typeof t.timestamp=="number"?t.timestamp:Date.now(),p=typeof t.id=="string"?t.id:void 0;return{role:n,content:c,timestamp:u,id:p}}function Zi(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 nd(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}const Br={pdf:"📕",doc:"📘",docx:"📘",txt:"📄",rtf:"📄",xls:"📗",xlsx:"📗",csv:"📊",ppt:"📙",pptx:"📙",jpg:"🖼️",jpeg:"🖼️",png:"🖼️",gif:"🖼️",webp:"🖼️",svg:"🖼️",mp3:"🎵",wav:"🎵",m4a:"🎵",mp4:"🎬",mov:"🎬",avi:"🎬",zip:"📦",rar:"📦","7z":"📦",tar:"📦",gz:"📦",js:"📜",ts:"📜",py:"📜",json:"📜",html:"📜",css:"📜",md:"📜",default:"📎"};function sd(e){const t=e.split(".").pop()?.toLowerCase()||"";return Br[t]??Br.default}function ad(e,t){const n=t.split(".").pop()?.toLowerCase()||"";return{pdf:"PDF Document",doc:"Word Document",docx:"Word Document",xls:"Excel Spreadsheet",xlsx:"Excel Spreadsheet",csv:"CSV File",ppt:"PowerPoint",pptx:"PowerPoint",txt:"Text File",md:"Markdown",json:"JSON File",zip:"ZIP Archive",png:"PNG Image",jpg:"JPEG Image",jpeg:"JPEG Image",gif:"GIF Image",mp3:"Audio File",mp4:"Video File",html:"HTML Document",css:"Stylesheet",js:"JavaScript",ts:"TypeScript",py:"Python"}[n]||e.split("/")[1]?.toUpperCase()||"File"}const Sg={icon:"puzzle",detailKeys:["command","path","url","targetUrl","targetId","ref","element","node","nodeId","id","requestId","to","channelId","guildId","userId","name","query","pattern","messageId"]},Ag={bash:{icon:"wrench",title:"Bash",detailKeys:["command"]},process:{icon:"wrench",title:"Process",detailKeys:["sessionId"]},read:{icon:"fileText",title:"Read",detailKeys:["path"]},write:{icon:"edit",title:"Write",detailKeys:["path"]},edit:{icon:"penLine",title:"Edit",detailKeys:["path"]},attach:{icon:"paperclip",title:"Attach",detailKeys:["path","url","fileName"]},browser:{icon:"globe",title:"Browser",actions:{status:{label:"status"},start:{label:"start"},stop:{label:"stop"},tabs:{label:"tabs"},open:{label:"open",detailKeys:["targetUrl"]},focus:{label:"focus",detailKeys:["targetId"]},close:{label:"close",detailKeys:["targetId"]},snapshot:{label:"snapshot",detailKeys:["targetUrl","targetId","ref","element","format"]},screenshot:{label:"screenshot",detailKeys:["targetUrl","targetId","ref","element"]},navigate:{label:"navigate",detailKeys:["targetUrl","targetId"]},console:{label:"console",detailKeys:["level","targetId"]},pdf:{label:"pdf",detailKeys:["targetId"]},upload:{label:"upload",detailKeys:["paths","ref","inputRef","element","targetId"]},dialog:{label:"dialog",detailKeys:["accept","promptText","targetId"]},act:{label:"act",detailKeys:["request.kind","request.ref","request.selector","request.text","request.value"]}}},canvas:{icon:"image",title:"Canvas",actions:{present:{label:"present",detailKeys:["target","node","nodeId"]},hide:{label:"hide",detailKeys:["node","nodeId"]},navigate:{label:"navigate",detailKeys:["url","node","nodeId"]},eval:{label:"eval",detailKeys:["javaScript","node","nodeId"]},snapshot:{label:"snapshot",detailKeys:["format","node","nodeId"]},a2ui_push:{label:"A2UI push",detailKeys:["jsonlPath","node","nodeId"]},a2ui_reset:{label:"A2UI reset",detailKeys:["node","nodeId"]}}},nodes:{icon:"smartphone",title:"Nodes",actions:{status:{label:"status"},describe:{label:"describe",detailKeys:["node","nodeId"]},pending:{label:"pending"},approve:{label:"approve",detailKeys:["requestId"]},reject:{label:"reject",detailKeys:["requestId"]},notify:{label:"notify",detailKeys:["node","nodeId","title","body"]},camera_snap:{label:"camera snap",detailKeys:["node","nodeId","facing","deviceId"]},camera_list:{label:"camera list",detailKeys:["node","nodeId"]},camera_clip:{label:"camera clip",detailKeys:["node","nodeId","facing","duration","durationMs"]},screen_record:{label:"screen record",detailKeys:["node","nodeId","duration","durationMs","fps","screenIndex"]}}},cron:{icon:"loader",title:"Cron",actions:{status:{label:"status"},list:{label:"list"},add:{label:"add",detailKeys:["job.name","job.id","job.schedule","job.cron"]},update:{label:"update",detailKeys:["id"]},remove:{label:"remove",detailKeys:["id"]},run:{label:"run",detailKeys:["id"]},runs:{label:"runs",detailKeys:["id"]},wake:{label:"wake",detailKeys:["text","mode"]}}},gateway:{icon:"plug",title:"Gateway",actions:{restart:{label:"restart",detailKeys:["reason","delayMs"]},"config.get":{label:"config get"},"config.schema":{label:"config schema"},"config.apply":{label:"config apply",detailKeys:["restartDelayMs"]},"update.run":{label:"update run",detailKeys:["restartDelayMs"]}}},whatsapp_login:{icon:"circle",title:"WhatsApp Login",actions:{start:{label:"start"},wait:{label:"wait"}}},discord:{icon:"messageSquare",title:"Discord",actions:{react:{label:"react",detailKeys:["channelId","messageId","emoji"]},reactions:{label:"reactions",detailKeys:["channelId","messageId"]},sticker:{label:"sticker",detailKeys:["to","stickerIds"]},poll:{label:"poll",detailKeys:["question","to"]},permissions:{label:"permissions",detailKeys:["channelId"]},readMessages:{label:"read messages",detailKeys:["channelId","limit"]},sendMessage:{label:"send",detailKeys:["to","content"]},editMessage:{label:"edit",detailKeys:["channelId","messageId"]},deleteMessage:{label:"delete",detailKeys:["channelId","messageId"]},threadCreate:{label:"thread create",detailKeys:["channelId","name"]},threadList:{label:"thread list",detailKeys:["guildId","channelId"]},threadReply:{label:"thread reply",detailKeys:["channelId","content"]},pinMessage:{label:"pin",detailKeys:["channelId","messageId"]},unpinMessage:{label:"unpin",detailKeys:["channelId","messageId"]},listPins:{label:"list pins",detailKeys:["channelId"]},searchMessages:{label:"search",detailKeys:["guildId","content"]},memberInfo:{label:"member",detailKeys:["guildId","userId"]},roleInfo:{label:"roles",detailKeys:["guildId"]},emojiList:{label:"emoji list",detailKeys:["guildId"]},roleAdd:{label:"role add",detailKeys:["guildId","userId","roleId"]},roleRemove:{label:"role remove",detailKeys:["guildId","userId","roleId"]},channelInfo:{label:"channel",detailKeys:["channelId"]},channelList:{label:"channels",detailKeys:["guildId"]},voiceStatus:{label:"voice",detailKeys:["guildId","userId"]},eventList:{label:"events",detailKeys:["guildId"]},eventCreate:{label:"event create",detailKeys:["guildId","name"]},timeout:{label:"timeout",detailKeys:["guildId","userId"]},kick:{label:"kick",detailKeys:["guildId","userId"]},ban:{label:"ban",detailKeys:["guildId","userId"]}}},slack:{icon:"messageSquare",title:"Slack",actions:{react:{label:"react",detailKeys:["channelId","messageId","emoji"]},reactions:{label:"reactions",detailKeys:["channelId","messageId"]},sendMessage:{label:"send",detailKeys:["to","content"]},editMessage:{label:"edit",detailKeys:["channelId","messageId"]},deleteMessage:{label:"delete",detailKeys:["channelId","messageId"]},readMessages:{label:"read messages",detailKeys:["channelId","limit"]},pinMessage:{label:"pin",detailKeys:["channelId","messageId"]},unpinMessage:{label:"unpin",detailKeys:["channelId","messageId"]},listPins:{label:"list pins",detailKeys:["channelId"]},memberInfo:{label:"member",detailKeys:["userId"]},emojiList:{label:"emoji list"}}}},_g={fallback:Sg,tools:Ag},id=_g,Ur=id.fallback??{icon:"puzzle"},Tg=id.tools??{};function xg(e){return(e??"tool").trim()}function Cg(e){const t=e.replace(/_/g," ").trim();return t?t.split(/\s+/).map(n=>n.length<=2&&n.toUpperCase()===n?n:`${n.at(0)?.toUpperCase()??""}${n.slice(1)}`).join(" "):"Tool"}function Eg(e){const t=e?.trim();if(t)return t.replace(/_/g," ")}function od(e){if(e!=null){if(typeof e=="string"){const t=e.trim();if(!t)return;const n=t.split(/\r?\n/)[0]?.trim()??"";return n?n.length>160?`${n.slice(0,157)}…`:n:void 0}if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)){const t=e.map(s=>od(s)).filter(s=>!!s);if(t.length===0)return;const n=t.slice(0,3).join(", ");return t.length>3?`${n}…`:n}}}function Lg(e,t){if(!e||typeof e!="object")return;let n=e;for(const s of t.split(".")){if(!s||!n||typeof n!="object")return;n=n[s]}return n}function Rg(e,t){for(const n of t){const s=Lg(e,n),a=od(s);if(a)return a}}function Pg(e){if(!e||typeof e!="object")return;const t=e,n=typeof t.path=="string"?t.path:void 0;if(!n)return;const s=typeof t.offset=="number"?t.offset:void 0,a=typeof t.limit=="number"?t.limit:void 0;return s!==void 0&&a!==void 0?`${n}:${s}-${s+a}`:n}function Ig(e){if(!e||typeof e!="object")return;const t=e;return typeof t.path=="string"?t.path:void 0}function Mg(e,t){if(!(!e||!t))return e.actions?.[t]??void 0}function Dg(e){const t=xg(e.name),n=t.toLowerCase(),s=Tg[n],a=s?.icon??Ur.icon??"puzzle",i=s?.title??Cg(t),o=s?.label??t,l=e.args&&typeof e.args=="object"?e.args.action:void 0,c=typeof l=="string"?l.trim():void 0,u=Mg(s,c),p=Eg(u?.label??c);let f;n==="read"&&(f=Pg(e.args)),!f&&(n==="write"||n==="edit"||n==="attach")&&(f=Ig(e.args));const m=u?.detailKeys??s?.detailKeys??Ur.detailKeys??[];return!f&&m.length>0&&(f=Rg(e.args,m)),!f&&e.meta&&(f=e.meta),f&&(f=Ng(f)),{name:t,icon:a,title:i,label:o,verb:p,detail:f}}function Og(e){const t=[];if(e.verb&&t.push(e.verb),e.detail&&t.push(e.detail),t.length!==0)return t.join(" · ")}function Ng(e){return e&&e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~")}const Fg=80,Bg=2,zr=100,Ug=3;function Kr(e){const t=e.trim();if(t.startsWith("{")||t.startsWith("["))try{const n=JSON.parse(t);return"```json\n"+JSON.stringify(n,null,2)+"\n```"}catch{}return e}function zg(e){const t=e.split(`
503
- `),n=t.slice(0,Bg),s=n.join(`
504
- `);return s.length>zr?s.slice(0,zr)+"…":n.length<t.length?s+"…":s}function Kg(e){const t=e,n=Hg(t.content),s=[];for(const a of n){const i=(typeof a.type=="string"?a.type:"").toLowerCase();(["toolcall","tool_call","tooluse","tool_use"].includes(i)||typeof a.name=="string"&&a.arguments!=null)&&s.push({kind:"call",name:a.name??"tool",args:Vg(a.arguments??a.args)})}for(const a of n){const i=(typeof a.type=="string"?a.type:"").toLowerCase();if(i!=="toolresult"&&i!=="tool_result")continue;const o=Gg(a);if(qr(o))continue;const l=typeof a.name=="string"?a.name:"tool";s.push({kind:"result",name:l,text:o})}if(nd(e)&&!s.some(a=>a.kind==="result")){const a=typeof t.toolName=="string"&&t.toolName||typeof t.tool_name=="string"&&t.tool_name||"tool",i=Xi(e)??void 0;qr(i)||s.push({kind:"result",name:a,text:i})}return s}const Wg=new Set(["write","read","edit","attach"]);function qg(e){if(!e||typeof e!="object")return null;const t=e,n=t.path??t.file_path??t.filePath;return typeof n=="string"&&n.trim()?n.trim():null}function jg(e){if(!e)return null;const t=e.match(/(?:\/(?:Users|home|tmp|var)\/\S+|~\/\S+)/);return t?t[0].replace(/[.,;:!?)'"]+$/,""):null}function Wr(e,t,n,s){const a=Dg({name:e.name,args:e.args}),i=Og(a),o=!!e.text?.trim(),l=Wg.has(e.name.toLowerCase())?qg(e.args)??jg(e.text):null;if(l&&e.kind==="result"){const v=l.split("/").pop()||l,S=v.split(".").pop()?.toLowerCase()||"",_=sd(v),T=ad(S,v);return r`
502
+ `):""}const $g=Object.freeze(Object.defineProperty({__proto__:null,extractRawText:Zc,extractText:xt,extractTextCached:Xi,extractThinking:fi,extractThinkingCached:Xc,formatApiError:Jc,formatReasoningMarkdown:ed,stripEnvelope:Ss},Symbol.toStringTag,{value:"Module"}));function td(e){const t=e;let n=typeof t.role=="string"?t.role:"unknown";const s=typeof t.toolCallId=="string"||typeof t.tool_call_id=="string",a=t.content,i=Array.isArray(a)?a:null,o=Array.isArray(i)&&i.some(f=>{const m=f,g=(typeof m.type=="string"?m.type:"").toLowerCase();return g==="toolresult"||g==="tool_result"}),l=typeof t.toolName=="string"||typeof t.tool_name=="string";(s||o||l)&&(n="toolResult");let c=[];typeof t.content=="string"?c=[{type:"text",text:t.content}]:Array.isArray(t.content)?c=t.content.map(f=>({type:f.type||"text",text:f.text,name:f.name,args:f.args||f.arguments})):typeof t.text=="string"&&(c=[{type:"text",text:t.text}]);const u=typeof t.timestamp=="number"?t.timestamp:Date.now(),p=typeof t.id=="string"?t.id:void 0;return{role:n,content:c,timestamp:u,id:p}}function Zi(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 nd(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}const Br={pdf:"📕",doc:"📘",docx:"📘",txt:"📄",rtf:"📄",xls:"📗",xlsx:"📗",csv:"📊",ppt:"📙",pptx:"📙",jpg:"🖼️",jpeg:"🖼️",png:"🖼️",gif:"🖼️",webp:"🖼️",svg:"🖼️",mp3:"🎵",wav:"🎵",m4a:"🎵",mp4:"🎬",mov:"🎬",avi:"🎬",zip:"📦",rar:"📦","7z":"📦",tar:"📦",gz:"📦",js:"📜",ts:"📜",py:"📜",json:"📜",html:"📜",css:"📜",md:"📜",default:"📎"};function sd(e){const t=e.split(".").pop()?.toLowerCase()||"";return Br[t]??Br.default}function ad(e,t){const n=t.split(".").pop()?.toLowerCase()||"";return{pdf:"PDF Document",doc:"Word Document",docx:"Word Document",xls:"Excel Spreadsheet",xlsx:"Excel Spreadsheet",csv:"CSV File",ppt:"PowerPoint",pptx:"PowerPoint",txt:"Text File",md:"Markdown",json:"JSON File",zip:"ZIP Archive",png:"PNG Image",jpg:"JPEG Image",jpeg:"JPEG Image",gif:"GIF Image",mp3:"Audio File",mp4:"Video File",html:"HTML Document",css:"Stylesheet",js:"JavaScript",ts:"TypeScript",py:"Python"}[n]||e.split("/")[1]?.toUpperCase()||"File"}const kg={icon:"puzzle",detailKeys:["command","path","url","targetUrl","targetId","ref","element","node","nodeId","id","requestId","to","channelId","guildId","userId","name","query","pattern","messageId"]},Sg={bash:{icon:"wrench",title:"Bash",detailKeys:["command"]},process:{icon:"wrench",title:"Process",detailKeys:["sessionId"]},read:{icon:"fileText",title:"Read",detailKeys:["path"]},write:{icon:"edit",title:"Write",detailKeys:["path"]},edit:{icon:"penLine",title:"Edit",detailKeys:["path"]},attach:{icon:"paperclip",title:"Attach",detailKeys:["path","url","fileName"]},browser:{icon:"globe",title:"Browser",actions:{status:{label:"status"},start:{label:"start"},stop:{label:"stop"},tabs:{label:"tabs"},open:{label:"open",detailKeys:["targetUrl"]},focus:{label:"focus",detailKeys:["targetId"]},close:{label:"close",detailKeys:["targetId"]},snapshot:{label:"snapshot",detailKeys:["targetUrl","targetId","ref","element","format"]},screenshot:{label:"screenshot",detailKeys:["targetUrl","targetId","ref","element"]},navigate:{label:"navigate",detailKeys:["targetUrl","targetId"]},console:{label:"console",detailKeys:["level","targetId"]},pdf:{label:"pdf",detailKeys:["targetId"]},upload:{label:"upload",detailKeys:["paths","ref","inputRef","element","targetId"]},dialog:{label:"dialog",detailKeys:["accept","promptText","targetId"]},act:{label:"act",detailKeys:["request.kind","request.ref","request.selector","request.text","request.value"]}}},canvas:{icon:"image",title:"Canvas",actions:{present:{label:"present",detailKeys:["target","node","nodeId"]},hide:{label:"hide",detailKeys:["node","nodeId"]},navigate:{label:"navigate",detailKeys:["url","node","nodeId"]},eval:{label:"eval",detailKeys:["javaScript","node","nodeId"]},snapshot:{label:"snapshot",detailKeys:["format","node","nodeId"]},a2ui_push:{label:"A2UI push",detailKeys:["jsonlPath","node","nodeId"]},a2ui_reset:{label:"A2UI reset",detailKeys:["node","nodeId"]}}},nodes:{icon:"smartphone",title:"Nodes",actions:{status:{label:"status"},describe:{label:"describe",detailKeys:["node","nodeId"]},pending:{label:"pending"},approve:{label:"approve",detailKeys:["requestId"]},reject:{label:"reject",detailKeys:["requestId"]},notify:{label:"notify",detailKeys:["node","nodeId","title","body"]},camera_snap:{label:"camera snap",detailKeys:["node","nodeId","facing","deviceId"]},camera_list:{label:"camera list",detailKeys:["node","nodeId"]},camera_clip:{label:"camera clip",detailKeys:["node","nodeId","facing","duration","durationMs"]},screen_record:{label:"screen record",detailKeys:["node","nodeId","duration","durationMs","fps","screenIndex"]}}},cron:{icon:"loader",title:"Cron",actions:{status:{label:"status"},list:{label:"list"},add:{label:"add",detailKeys:["job.name","job.id","job.schedule","job.cron"]},update:{label:"update",detailKeys:["id"]},remove:{label:"remove",detailKeys:["id"]},run:{label:"run",detailKeys:["id"]},runs:{label:"runs",detailKeys:["id"]},wake:{label:"wake",detailKeys:["text","mode"]}}},gateway:{icon:"plug",title:"Gateway",actions:{restart:{label:"restart",detailKeys:["reason","delayMs"]},"config.get":{label:"config get"},"config.schema":{label:"config schema"},"config.apply":{label:"config apply",detailKeys:["restartDelayMs"]},"update.run":{label:"update run",detailKeys:["restartDelayMs"]}}},whatsapp_login:{icon:"circle",title:"WhatsApp Login",actions:{start:{label:"start"},wait:{label:"wait"}}},discord:{icon:"messageSquare",title:"Discord",actions:{react:{label:"react",detailKeys:["channelId","messageId","emoji"]},reactions:{label:"reactions",detailKeys:["channelId","messageId"]},sticker:{label:"sticker",detailKeys:["to","stickerIds"]},poll:{label:"poll",detailKeys:["question","to"]},permissions:{label:"permissions",detailKeys:["channelId"]},readMessages:{label:"read messages",detailKeys:["channelId","limit"]},sendMessage:{label:"send",detailKeys:["to","content"]},editMessage:{label:"edit",detailKeys:["channelId","messageId"]},deleteMessage:{label:"delete",detailKeys:["channelId","messageId"]},threadCreate:{label:"thread create",detailKeys:["channelId","name"]},threadList:{label:"thread list",detailKeys:["guildId","channelId"]},threadReply:{label:"thread reply",detailKeys:["channelId","content"]},pinMessage:{label:"pin",detailKeys:["channelId","messageId"]},unpinMessage:{label:"unpin",detailKeys:["channelId","messageId"]},listPins:{label:"list pins",detailKeys:["channelId"]},searchMessages:{label:"search",detailKeys:["guildId","content"]},memberInfo:{label:"member",detailKeys:["guildId","userId"]},roleInfo:{label:"roles",detailKeys:["guildId"]},emojiList:{label:"emoji list",detailKeys:["guildId"]},roleAdd:{label:"role add",detailKeys:["guildId","userId","roleId"]},roleRemove:{label:"role remove",detailKeys:["guildId","userId","roleId"]},channelInfo:{label:"channel",detailKeys:["channelId"]},channelList:{label:"channels",detailKeys:["guildId"]},voiceStatus:{label:"voice",detailKeys:["guildId","userId"]},eventList:{label:"events",detailKeys:["guildId"]},eventCreate:{label:"event create",detailKeys:["guildId","name"]},timeout:{label:"timeout",detailKeys:["guildId","userId"]},kick:{label:"kick",detailKeys:["guildId","userId"]},ban:{label:"ban",detailKeys:["guildId","userId"]}}},slack:{icon:"messageSquare",title:"Slack",actions:{react:{label:"react",detailKeys:["channelId","messageId","emoji"]},reactions:{label:"reactions",detailKeys:["channelId","messageId"]},sendMessage:{label:"send",detailKeys:["to","content"]},editMessage:{label:"edit",detailKeys:["channelId","messageId"]},deleteMessage:{label:"delete",detailKeys:["channelId","messageId"]},readMessages:{label:"read messages",detailKeys:["channelId","limit"]},pinMessage:{label:"pin",detailKeys:["channelId","messageId"]},unpinMessage:{label:"unpin",detailKeys:["channelId","messageId"]},listPins:{label:"list pins",detailKeys:["channelId"]},memberInfo:{label:"member",detailKeys:["userId"]},emojiList:{label:"emoji list"}}}},Ag={fallback:kg,tools:Sg},id=Ag,Ur=id.fallback??{icon:"puzzle"},_g=id.tools??{};function Tg(e){return(e??"tool").trim()}function xg(e){const t=e.replace(/_/g," ").trim();return t?t.split(/\s+/).map(n=>n.length<=2&&n.toUpperCase()===n?n:`${n.at(0)?.toUpperCase()??""}${n.slice(1)}`).join(" "):"Tool"}function Cg(e){const t=e?.trim();if(t)return t.replace(/_/g," ")}function od(e){if(e!=null){if(typeof e=="string"){const t=e.trim();if(!t)return;const n=t.split(/\r?\n/)[0]?.trim()??"";return n?n.length>160?`${n.slice(0,157)}…`:n:void 0}if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)){const t=e.map(s=>od(s)).filter(s=>!!s);if(t.length===0)return;const n=t.slice(0,3).join(", ");return t.length>3?`${n}…`:n}}}function Eg(e,t){if(!e||typeof e!="object")return;let n=e;for(const s of t.split(".")){if(!s||!n||typeof n!="object")return;n=n[s]}return n}function Lg(e,t){for(const n of t){const s=Eg(e,n),a=od(s);if(a)return a}}function Rg(e){if(!e||typeof e!="object")return;const t=e,n=typeof t.path=="string"?t.path:void 0;if(!n)return;const s=typeof t.offset=="number"?t.offset:void 0,a=typeof t.limit=="number"?t.limit:void 0;return s!==void 0&&a!==void 0?`${n}:${s}-${s+a}`:n}function Pg(e){if(!e||typeof e!="object")return;const t=e;return typeof t.path=="string"?t.path:void 0}function Ig(e,t){if(!(!e||!t))return e.actions?.[t]??void 0}function Mg(e){const t=Tg(e.name),n=t.toLowerCase(),s=_g[n],a=s?.icon??Ur.icon??"puzzle",i=s?.title??xg(t),o=s?.label??t,l=e.args&&typeof e.args=="object"?e.args.action:void 0,c=typeof l=="string"?l.trim():void 0,u=Ig(s,c),p=Cg(u?.label??c);let f;n==="read"&&(f=Rg(e.args)),!f&&(n==="write"||n==="edit"||n==="attach")&&(f=Pg(e.args));const m=u?.detailKeys??s?.detailKeys??Ur.detailKeys??[];return!f&&m.length>0&&(f=Lg(e.args,m)),!f&&e.meta&&(f=e.meta),f&&(f=Og(f)),{name:t,icon:a,title:i,label:o,verb:p,detail:f}}function Dg(e){const t=[];if(e.verb&&t.push(e.verb),e.detail&&t.push(e.detail),t.length!==0)return t.join(" · ")}function Og(e){return e&&e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~")}const Ng=80,Fg=2,zr=100,Bg=3;function Kr(e){const t=e.trim();if(t.startsWith("{")||t.startsWith("["))try{const n=JSON.parse(t);return"```json\n"+JSON.stringify(n,null,2)+"\n```"}catch{}return e}function Ug(e){const t=e.split(`
503
+ `),n=t.slice(0,Fg),s=n.join(`
504
+ `);return s.length>zr?s.slice(0,zr)+"…":n.length<t.length?s+"…":s}function zg(e){const t=e,n=jg(t.content),s=[];for(const a of n){const i=(typeof a.type=="string"?a.type:"").toLowerCase();(["toolcall","tool_call","tooluse","tool_use"].includes(i)||typeof a.name=="string"&&a.arguments!=null)&&s.push({kind:"call",name:a.name??"tool",args:Hg(a.arguments??a.args)})}for(const a of n){const i=(typeof a.type=="string"?a.type:"").toLowerCase();if(i!=="toolresult"&&i!=="tool_result")continue;const o=Vg(a);if(qr(o))continue;const l=typeof a.name=="string"?a.name:"tool";s.push({kind:"result",name:l,text:o})}if(nd(e)&&!s.some(a=>a.kind==="result")){const a=typeof t.toolName=="string"&&t.toolName||typeof t.tool_name=="string"&&t.tool_name||"tool",i=Xi(e)??void 0;qr(i)||s.push({kind:"result",name:a,text:i})}return s}const Kg=new Set(["write","read","edit","attach"]);function Wg(e){if(!e||typeof e!="object")return null;const t=e,n=t.path??t.file_path??t.filePath;return typeof n=="string"&&n.trim()?n.trim():null}function qg(e){if(!e)return null;const t=e.match(/(?:\/(?:Users|home|tmp|var)\/\S+|~\/\S+)/);return t?t[0].replace(/[.,;:!?)'"]+$/,""):null}function Wr(e,t,n,s){const a=Mg({name:e.name,args:e.args}),i=Dg(a),o=!!e.text?.trim(),l=Kg.has(e.name.toLowerCase())?Wg(e.args)??qg(e.text):null;if(l&&e.kind==="result"){const v=l.split("/").pop()||l,S=v.split(".").pop()?.toLowerCase()||"",_=sd(v),T=ad(S,v);return r`
505
505
  <div class="chat-artifact-card">
506
506
  <div class="chat-artifact-card__icon">${_}</div>
507
507
  <div class="chat-artifact-card__info">
@@ -518,7 +518,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
518
518
  ${i?`**Command:** \`${i}\`
519
519
 
520
520
  `:""}*No output — tool completed successfully.*`;t(S)}}:void 0,p=e.text?e.text.split(`
521
- `).length:0,f=o&&(e.text?.length??0)<=Fg,m=o&&!f&&p>Ug,g=o&&!m,$=!o,d=e.kind==="call"?"chat-tool-card--call":"chat-tool-card--result";return r`
521
+ `).length:0,f=o&&(e.text?.length??0)<=Ng,m=o&&!f&&p>Bg,g=o&&!m,$=!o,d=e.kind==="call"?"chat-tool-card--call":"chat-tool-card--result";return r`
522
522
  <div
523
523
  class="chat-tool-card ${d} ${c?"chat-tool-card--clickable":""}"
524
524
  @click=${u}
@@ -539,12 +539,12 @@ ${i?`**Command:** \`${i}\`
539
539
  <div class="chat-tool-card__status-text muted">Completed</div>
540
540
  `:h}
541
541
  ${m?r`<details class="chat-tool-card__expandable" @click=${v=>v.stopPropagation()}>
542
- <summary class="chat-tool-card__preview mono">${zg(e.text)}</summary>
542
+ <summary class="chat-tool-card__preview mono">${Ug(e.text)}</summary>
543
543
  <div class="chat-tool-card__full-output mono">${e.text}</div>
544
544
  </details>`:h}
545
545
  ${g?r`<div class="chat-tool-card__inline mono">${e.text}</div>`:h}
546
546
  </div>
547
- `}function Hg(e){return Array.isArray(e)?e.filter(Boolean):[]}function Vg(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 Gg(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}function qr(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("process exited")?!1:t.includes("(no new output)")&&t.includes("still running")}const jr={exec:["Executing","Running","Conjuring","Manifesting","Brewing"],read:["Reading","Perusing","Absorbing","Scanning","Devouring"],write:["Writing","Scribbling","Crafting","Inscribing","Authoring"],edit:["Editing","Refining","Polishing","Tweaking","Sculpting"],browser:["Browsing","Surfing","Exploring","Navigating","Spelunking"],web_search:["Searching","Hunting","Investigating","Sleuthing","Scouring"],web_fetch:["Fetching","Grabbing","Retrieving","Summoning","Acquiring"],memory_search:["Remembering","Recalling","Pondering","Reflecting"],image:["Analyzing","Examining","Scrutinizing","Inspecting","Beholding"],default:["Working on","Processing","Handling","Tinkering with","Wrangling"]};function rd(e){const t=e.toLowerCase().replace(/[^a-z_]/g,""),n=jr[t]??jr.default,s=Math.floor(Date.now()/2e3)%n.length;return n[s]}function Qg(e){const t=e.match(/\[Files uploaded:\s*([^\]]+)\]/);if(!t)return null;const n=t[1],s=[],a=/([^(,]+?)\s*\(fileId:\s*([^,]+),\s*size:\s*([^,]+),\s*type:\s*([^)]+)\)/g;let i;for(;(i=a.exec(n))!==null;)s.push({fileName:i[1].trim(),fileId:i[2].trim(),size:i[3].trim(),mimeType:i[4].trim()});return s.length>0?s:null}function Yg(e){return r`
547
+ `}function jg(e){return Array.isArray(e)?e.filter(Boolean):[]}function Hg(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 Vg(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}function qr(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("process exited")?!1:t.includes("(no new output)")&&t.includes("still running")}const jr={exec:["Executing","Running","Conjuring","Manifesting","Brewing"],read:["Reading","Perusing","Absorbing","Scanning","Devouring"],write:["Writing","Scribbling","Crafting","Inscribing","Authoring"],edit:["Editing","Refining","Polishing","Tweaking","Sculpting"],browser:["Browsing","Surfing","Exploring","Navigating","Spelunking"],web_search:["Searching","Hunting","Investigating","Sleuthing","Scouring"],web_fetch:["Fetching","Grabbing","Retrieving","Summoning","Acquiring"],memory_search:["Remembering","Recalling","Pondering","Reflecting"],image:["Analyzing","Examining","Scrutinizing","Inspecting","Beholding"],default:["Working on","Processing","Handling","Tinkering with","Wrangling"]};function rd(e){const t=e.toLowerCase().replace(/[^a-z_]/g,""),n=jr[t]??jr.default,s=Math.floor(Date.now()/2e3)%n.length;return n[s]}function Gg(e){const t=e.match(/\[Files uploaded:\s*([^\]]+)\]/);if(!t)return null;const n=t[1],s=[],a=/([^(,]+?)\s*\(fileId:\s*([^,]+),\s*size:\s*([^,]+),\s*type:\s*([^)]+)\)/g;let i;for(;(i=a.exec(n))!==null;)s.push({fileName:i[1].trim(),fileId:i[2].trim(),size:i[3].trim(),mimeType:i[4].trim()});return s.length>0?s:null}function Qg(e){return r`
548
548
  <div class="chat-file-uploads">
549
549
  ${e.map(t=>r`
550
550
  <div class="chat-file-upload-card">
@@ -556,12 +556,12 @@ ${i?`**Command:** \`${i}\`
556
556
  </div>
557
557
  `)}
558
558
  </div>
559
- `}function Jg(e){return e.replace(/\[Files uploaded:[^\]]+\]\s*/g,"").trim()}function Xg(e){if(!e)return e;if(e.startsWith("System:")||e.startsWith("GatewayRestart:")){const i=e.indexOf(`
559
+ `}function Yg(e){return e.replace(/\[Files uploaded:[^\]]+\]\s*/g,"").trim()}function Jg(e){if(!e)return e;if(e.startsWith("System:")||e.startsWith("GatewayRestart:")){const i=e.indexOf(`
560
560
 
561
561
  `);return i!==-1?e.slice(i+2).trim():""}let a=e.split(`
562
562
  `).filter(i=>{const o=i.trim();return!o.startsWith("System:")&&!o.startsWith("GatewayRestart:")}).join(`
563
563
  `);for(;a.startsWith(`
564
- `);)a=a.slice(1);return a.trim()}function Zg(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${Math.round(e)} B`}function gi(e){const t=e,n=t.content,s=[];if(Array.isArray(n))for(const i of n){if(typeof i!="object"||i===null)continue;const o=i;if(o.type==="image"){const l=o.source;if(l?.type==="base64"&&typeof l.data=="string"){const c=l.data,u=l.media_type||"image/png",p=c.startsWith("data:")?c:`data:${u};base64,${c}`;s.push({url:p})}else if(typeof o.data=="string"&&typeof o.mimeType=="string"){const c=o.data.startsWith("data:")?o.data:`data:${o.mimeType};base64,${o.data}`;s.push({url:c})}else typeof o.url=="string"?s.push({url:o.url}):o.omitted===!0&&s.push({omitted:!0,bytes:typeof o.bytes=="number"?o.bytes:void 0,mimeType:typeof o.mimeType=="string"?o.mimeType:void 0,alt:typeof o.fileName=="string"?o.fileName:void 0})}else if(o.type==="image_url"){const l=o.image_url;typeof l?.url=="string"&&s.push({url:l.url})}else o.type==="attachment"&&typeof o.content=="string"&&(o.mimeType||"").startsWith("image/")&&s.push({url:o.content,alt:o.fileName||void 0});if(o.type==="text"&&typeof o.text=="string"){const l=/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=o.text.match(l);if(c)for(const u of c)s.push({url:u})}if(Array.isArray(o.content))for(const l of o.content){if(typeof l!="object"||l===null)continue;const c=l;if(c.type==="image"){const u=c.source;if(u?.type==="base64"&&typeof u.data=="string"){const p=u.media_type||"image/png",f=u.data.startsWith("data:")?u.data:`data:${p};base64,${u.data}`;s.push({url:f})}else if(typeof c.data=="string"&&typeof c.mimeType=="string"){const p=c.data.startsWith("data:")?c.data:`data:${c.mimeType};base64,${c.data}`;s.push({url:p})}else c.omitted===!0&&s.push({omitted:!0,bytes:typeof c.bytes=="number"?c.bytes:void 0,mimeType:typeof c.mimeType=="string"?c.mimeType:void 0,alt:typeof c.fileName=="string"?c.fileName:void 0})}}}const a=t.attachments;if(Array.isArray(a))for(const i of a){if(typeof i!="object"||i===null)continue;const o=i;if(o.type==="image"&&typeof o.content=="string"){const l=o.mimeType||"image/png",c=o.content.startsWith("data:")?o.content:`data:${l};base64,${o.content}`;s.push({url:c,alt:o.fileName||void 0})}else o.type==="image"&&o.omitted===!0&&s.push({omitted:!0,bytes:typeof o.bytes=="number"?o.bytes:void 0,mimeType:typeof o.mimeType=="string"?o.mimeType:void 0,alt:typeof o.fileName=="string"?o.fileName:void 0})}return s}function em(e){const t=e,n=t.content,s=[];if(Array.isArray(n))for(const i of n){if(typeof i!="object"||i===null)continue;const o=i;if(o.type==="attachment"&&typeof o.content=="string"){const l=o.mimeType||"application/octet-stream";l.startsWith("image/")||s.push({fileName:o.fileName||"file",mimeType:l,content:o.content})}}const a=t.attachments;if(Array.isArray(a))for(const i of a){if(typeof i!="object"||i===null)continue;const o=i;o.type==="file"&&typeof o.content=="string"&&s.push({fileName:o.fileName||"file",mimeType:o.mimeType||"application/octet-stream",content:o.content})}return s}function tm(e,t){return r`
564
+ `);)a=a.slice(1);return a.trim()}function Xg(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${Math.round(e)} B`}function gi(e){const t=e,n=t.content,s=[];if(Array.isArray(n))for(const i of n){if(typeof i!="object"||i===null)continue;const o=i;if(o.type==="image"){const l=o.source;if(l?.type==="base64"&&typeof l.data=="string"){const c=l.data,u=l.media_type||"image/png",p=c.startsWith("data:")?c:`data:${u};base64,${c}`;s.push({url:p})}else if(typeof o.data=="string"&&typeof o.mimeType=="string"){const c=o.data.startsWith("data:")?o.data:`data:${o.mimeType};base64,${o.data}`;s.push({url:c})}else typeof o.url=="string"?s.push({url:o.url}):o.omitted===!0&&s.push({omitted:!0,bytes:typeof o.bytes=="number"?o.bytes:void 0,mimeType:typeof o.mimeType=="string"?o.mimeType:void 0,alt:typeof o.fileName=="string"?o.fileName:void 0})}else if(o.type==="image_url"){const l=o.image_url;typeof l?.url=="string"&&s.push({url:l.url})}else o.type==="attachment"&&typeof o.content=="string"&&(o.mimeType||"").startsWith("image/")&&s.push({url:o.content,alt:o.fileName||void 0});if(o.type==="text"&&typeof o.text=="string"){const l=/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=o.text.match(l);if(c)for(const u of c)s.push({url:u})}if(Array.isArray(o.content))for(const l of o.content){if(typeof l!="object"||l===null)continue;const c=l;if(c.type==="image"){const u=c.source;if(u?.type==="base64"&&typeof u.data=="string"){const p=u.media_type||"image/png",f=u.data.startsWith("data:")?u.data:`data:${p};base64,${u.data}`;s.push({url:f})}else if(typeof c.data=="string"&&typeof c.mimeType=="string"){const p=c.data.startsWith("data:")?c.data:`data:${c.mimeType};base64,${c.data}`;s.push({url:p})}else c.omitted===!0&&s.push({omitted:!0,bytes:typeof c.bytes=="number"?c.bytes:void 0,mimeType:typeof c.mimeType=="string"?c.mimeType:void 0,alt:typeof c.fileName=="string"?c.fileName:void 0})}}}const a=t.attachments;if(Array.isArray(a))for(const i of a){if(typeof i!="object"||i===null)continue;const o=i;if(o.type==="image"&&typeof o.content=="string"){const l=o.mimeType||"image/png",c=o.content.startsWith("data:")?o.content:`data:${l};base64,${o.content}`;s.push({url:c,alt:o.fileName||void 0})}else o.type==="image"&&o.omitted===!0&&s.push({omitted:!0,bytes:typeof o.bytes=="number"?o.bytes:void 0,mimeType:typeof o.mimeType=="string"?o.mimeType:void 0,alt:typeof o.fileName=="string"?o.fileName:void 0})}return s}function Zg(e){const t=e,n=t.content,s=[];if(Array.isArray(n))for(const i of n){if(typeof i!="object"||i===null)continue;const o=i;if(o.type==="attachment"&&typeof o.content=="string"){const l=o.mimeType||"application/octet-stream";l.startsWith("image/")||s.push({fileName:o.fileName||"file",mimeType:l,content:o.content})}}const a=t.attachments;if(Array.isArray(a))for(const i of a){if(typeof i!="object"||i===null)continue;const o=i;o.type==="file"&&typeof o.content=="string"&&s.push({fileName:o.fileName||"file",mimeType:o.mimeType||"application/octet-stream",content:o.content})}return s}function em(e,t){return r`
565
565
  <div class="chat-group assistant">
566
566
  ${eo("assistant",{assistantName:e?.name,assistantAvatar:e?.avatar})}
567
567
  <div class="chat-group-messages">
@@ -587,7 +587,7 @@ ${i?`**Command:** \`${i}\`
587
587
  </div>
588
588
  </div>
589
589
  </div>
590
- `}function nm(e,t,n,s,a){const i=new Date(t).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),o=s?.name??"Assistant";return r`
590
+ `}function tm(e,t,n,s,a){const i=new Date(t).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),o=s?.name??"Assistant";return r`
591
591
  <div class="chat-group assistant">
592
592
  ${eo("assistant",{assistantName:s?.name,assistantAvatar:s?.avatar})}
593
593
  <div class="chat-group-messages">
@@ -610,7 +610,7 @@ ${i?`**Command:** \`${i}\`
610
610
  </div>
611
611
  </div>
612
612
  </div>
613
- `}function sm(e,t){const n=Zi(e.role),s=t.assistantName??"Assistant",a=t.userName??"You",i=n==="user"?a:n==="assistant"?s:n,o=n==="user"?"user":n==="assistant"?"assistant":"other",l=new Date(e.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return r`
613
+ `}function nm(e,t){const n=Zi(e.role),s=t.assistantName??"Assistant",a=t.userName??"You",i=n==="user"?a:n==="assistant"?s:n,o=n==="user"?"user":n==="assistant"?"assistant":"other",l=new Date(e.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return r`
614
614
  <div class="chat-group ${o}">
615
615
  ${eo(e.role,{assistantName:s,assistantAvatar:t.assistantAvatar??null,userName:a,userAvatar:t.userAvatar??null})}
616
616
  <div class="chat-group-messages">
@@ -631,7 +631,7 @@ ${i?`**Command:** \`${i}\`
631
631
  alt="${s}"
632
632
  />`:a?r`<div class="chat-avatar ${l}" style="color: var(--accent);">${a}</div>`:r`<div class="chat-avatar ${l}" style="color: var(--accent);">⚛️</div>`:n==="tool"?r`<div class="chat-avatar ${l}">⚙</div>`:r`<div class="chat-avatar ${l}">?</div>`}function Hr(e){return/^https?:\/\//i.test(e)||/^data:image\//i.test(e)||e.startsWith("/")}function Vr(e,t,n){if(e.length===0)return h;const s=e.map((i,o)=>{if((i.omitted||!i.url)&&n){const l=n(o);if(l)return{...i,resolvedUrl:l}}return i}),a=s.filter(i=>(i.resolvedUrl||i.url)&&!i.omitted||i.resolvedUrl).map(i=>({url:i.resolvedUrl||i.url,alt:i.alt}));return r`
633
633
  <div class="chat-message-images">
634
- ${s.map(i=>{const o=i.resolvedUrl||i.url;if(!o){const c=Zg(i.bytes),p=[i.mimeType?i.mimeType.replace("image/","").toUpperCase():null,c,"preview omitted"].filter(Boolean).join(" - ");return r`
634
+ ${s.map(i=>{const o=i.resolvedUrl||i.url;if(!o){const c=Xg(i.bytes),p=[i.mimeType?i.mimeType.replace("image/","").toUpperCase():null,c,"preview omitted"].filter(Boolean).join(" - ");return r`
635
635
  <div
636
636
  class="chat-message-image chat-message-image--omitted"
637
637
  title=${i.alt??"Attached image"}
@@ -650,7 +650,7 @@ ${i?`**Command:** \`${i}\`
650
650
  />
651
651
  `})}
652
652
  </div>
653
- `}function am(e){return e.length===0?h:r`
653
+ `}function sm(e){return e.length===0?h:r`
654
654
  <div class="chat-message-files">
655
655
  ${e.map(t=>{const n=t.fileName.length>30?t.fileName.slice(0,27)+"...":t.fileName;return r`
656
656
  <a
@@ -663,11 +663,11 @@ ${i?`**Command:** \`${i}\`
663
663
  </a>
664
664
  `})}
665
665
  </div>
666
- `}function ld(e,t,n,s,a,i,o){try{return im(e,t,n,s,a,i,o)}catch(l){return console.error("[chat] message render error:",l),r`
666
+ `}function ld(e,t,n,s,a,i,o){try{return am(e,t,n,s,a,i,o)}catch(l){return console.error("[chat] message render error:",l),r`
667
667
  <div class="chat-bubble">
668
668
  <div class="chat-text"><em>Message failed to render</em></div>
669
669
  </div>
670
- `}}function im(e,t,n,s,a,i,o){const l=e,c=typeof l.role=="string"?l.role:"unknown",u=nd(e)||c.toLowerCase()==="toolresult"||c.toLowerCase()==="tool_result"||typeof l.toolCallId=="string"||typeof l.tool_call_id=="string",p=Kg(e),f=p.length>0,m=gi(e),g=m.length>0,$=typeof l._chatIdx=="number"?l._chatIdx:-1,d=i&&$>=0?N=>i($,N):void 0,v=em(e),S=v.length>0,_=Xi(e),T=t.showReasoning&&c==="assistant"?Xc(e):null,A=c==="user"&&_?Qg(_):null,C=A&&A.length>0;let L=_;if(c==="user"&&L&&(L=Xg(L)),L&&(L=L.replace(/<system-context\b[^>]*>[\s\S]*?<\/system-context>/gi,"").trim()||null),L){const N=Jc(L);N&&(L=N)}C&&L&&(L=Jg(L));const P=L?.trim()?L:null,te=T?ed(T):null,Q=P,de=c==="assistant"&&!!Q?.trim(),R=["chat-bubble",de?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");if(f&&u)return r`
670
+ `}}function am(e,t,n,s,a,i,o){const l=e,c=typeof l.role=="string"?l.role:"unknown",u=nd(e)||c.toLowerCase()==="toolresult"||c.toLowerCase()==="tool_result"||typeof l.toolCallId=="string"||typeof l.tool_call_id=="string",p=zg(e),f=p.length>0,m=gi(e),g=m.length>0,$=typeof l._chatIdx=="number"?l._chatIdx:-1,d=i&&$>=0?N=>i($,N):void 0,v=Zg(e),S=v.length>0,_=Xi(e),T=t.showReasoning&&c==="assistant"?Xc(e):null,A=c==="user"&&_?Gg(_):null,C=A&&A.length>0;let L=_;if(c==="user"&&L&&(L=Jg(L)),L&&(L=L.replace(/<system-context\b[^>]*>[\s\S]*?<\/system-context>/gi,"").trim()||null),L){const N=Jc(L);N&&(L=N)}C&&L&&(L=Yg(L));const P=L?.trim()?L:null,te=T?ed(T):null,Q=P,de=c==="assistant"&&!!Q?.trim(),R=["chat-bubble",de?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");if(f&&u)return r`
671
671
  ${g?Vr(m,a,d):h}
672
672
  ${p.map(N=>Wr(N,n,s,o))}
673
673
  `;if(!Q&&!f&&!g&&!S&&!C&&!te){const N=typeof l.errorMessage=="string"?l.errorMessage:null;if(l.stopReason==="error"&&N){let B=N;const W=N.match(/(\d+)\s*tokens?\s*>\s*(\d+)/);if(W){const F=parseInt(W[1]).toLocaleString(),we=parseInt(W[2]).toLocaleString();B=`Context overflow: ${F} tokens exceeded the ${we} token limit. The conversation needs to be compacted.`}else N.includes("prompt is too long")&&(B="Context overflow: The conversation is too long for the model.");return r`
@@ -676,10 +676,10 @@ ${i?`**Command:** \`${i}\`
676
676
  </div>
677
677
  `}return h}return r`
678
678
  <div class="${R}">
679
- ${de?gg(Q):h}
680
- ${C?Yg(A):h}
679
+ ${de?fg(Q):h}
680
+ ${C?Qg(A):h}
681
681
  ${Vr(m,a,d)}
682
- ${am(v)}
682
+ ${sm(v)}
683
683
  ${te?r`<details class="chat-thinking-details">
684
684
  <summary class="chat-thinking-summary">Thinking...</summary>
685
685
  <div class="chat-thinking">${ke(ye(te))}</div>
@@ -687,7 +687,7 @@ ${i?`**Command:** \`${i}\`
687
687
  ${Q?r`<div class="chat-text">${ke(t.isStreaming?Qc(Q):ye(Q))}</div>`:h}
688
688
  ${p.map(N=>Wr(N,n,s,o))}
689
689
  </div>
690
- `}function om(e){const t=e,n=typeof t.content=="string"?t.content:"",s=typeof t.keptMessages=="number"?t.keptMessages:null,a=typeof t.timestamp=="number"?new Date(t.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):"";return r`
690
+ `}function im(e){const t=e,n=typeof t.content=="string"?t.content:"",s=typeof t.keptMessages=="number"?t.keptMessages:null,a=typeof t.timestamp=="number"?new Date(t.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):"";return r`
691
691
  <div class="chat-compaction-summary">
692
692
  <div class="chat-compaction-summary__header">
693
693
  <span class="chat-compaction-summary__icon">📋</span>
@@ -699,7 +699,7 @@ ${i?`**Command:** \`${i}\`
699
699
  </div>
700
700
  ${a?r`<div class="chat-compaction-summary__timestamp">${a}</div>`:h}
701
701
  </div>
702
- `}function rm(e){return e.isCompactionSummary===!0}const lm=[{label:"",tabs:["chat","today","workspaces","second-brain","dashboards"]},{label:"Toolkit",tabs:["skills","trust","guardrails","options"]},{label:"Settings",tabs:["config","debug","logs"]},{label:"System",tabs:["mission-control","overview","channels","instances","sessions","cron","nodes"]}],cd={setup:"/setup",onboarding:"/onboarding",options:"/options",overview:"/overview",workspaces:"/workspaces",today:"/today",work:"/work","my-day":"/today",channels:"/channels",instances:"/instances",sessions:"/sessions",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",trust:"/trust",guardrails:"/guardrails",config:"/config",debug:"/debug",logs:"/logs","second-brain":"/second-brain","mission-control":"/mission-control",dashboards:"/dashboards"},cn=new Map(Object.entries(cd).map(([e,t])=>[t,e]));cn.set("/today","today");cn.set("/my-day","today");cn.set("/work","workspaces");function Zs(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function Vn(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 to(e,t=""){const n=Zs(t),s=cd[e];return n?`${n}${s}`:s}function dd(e,t=""){const n=Zs(t);let s=e||"/";n&&(s===n?s="/":s.startsWith(`${n}/`)&&(s=s.slice(n.length)));let a=Vn(s).toLowerCase();return a.endsWith("/index.html")&&(a="/"),a==="/"?"chat":cn.get(a)??null}function cm(e){let t=Vn(e);if(t.endsWith("/index.html")&&(t=Vn(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let s=0;s<n.length;s++){const a=`/${n.slice(s).join("/")}`.toLowerCase();if(cn.has(a)){const i=n.slice(0,s);return!i.length||i.some(l=>cn.has(`/${l.toLowerCase()}`))?"":`/${i.join("/")}`}}return`/${n.join("/")}`}function Gn(e){switch(e){case"setup":return"Setup";case"onboarding":return"Connect Your World";case"chat":return"Chat";case"today":case"my-day":return"Today";case"work":return"Work";case"overview":return"Overview";case"workspaces":return"Work";case"channels":return"Channels";case"instances":return"Instances";case"sessions":return"Sessions";case"cron":return"Cron Jobs";case"skills":return"Skills";case"nodes":return"Nodes";case"options":return"Lab";case"trust":return"Trust";case"guardrails":return"Guardrails";case"second-brain":return"Second Brain";case"mission-control":return"Mission Control";case"dashboards":return"Dashboards";case"config":return"Config";case"debug":return"Debug";case"logs":return"Logs";default:return"Control"}}function dm(e){switch(e){case"setup":return"🧭";case"onboarding":return"🧭";case"chat":return"💬";case"today":case"my-day":return"☀️";case"work":return"💼";case"overview":return"🎯";case"workspaces":return"📂";case"channels":return"🔗";case"instances":return"📡";case"sessions":return"📄";case"cron":return"⏰";case"skills":return"🧩";case"nodes":return"🖥️";case"options":return"🧪";case"trust":return"🛡️";case"guardrails":return"🚧";case"second-brain":return"🧠";case"mission-control":return"🛰️";case"dashboards":return"📊";case"config":return"⚙️";case"debug":return"🐛";case"logs":return"📜";default:return"📁"}}function um(e){switch(e){case"setup":return"Get GodMode configured and running.";case"onboarding":return"Set up the integrations that power your daily brief and agent features. Everything is optional.";case"chat":return"Your command center. Ask anything, customize any view.";case"today":case"my-day":return"Calendar, brief, tasks, and schedule for the day.";case"work":return"Your projects, files, tasks, and team — organized by workspace.";case"overview":return"Gateway status, entry points, and a fast health read.";case"workspaces":return"Projects, clients, and personal operating context.";case"channels":return"Manage channels and settings.";case"instances":return"Presence beacons from connected clients and nodes.";case"sessions":return"Inspect active sessions and adjust per-session defaults.";case"cron":return"Schedule wakeups and recurring agent runs.";case"skills":return"Manage your skills, discover new ones from ClawHub, and personalize them for your workflow.";case"nodes":return"Paired devices, capabilities, and command exposure.";case"options":return"Toggle experimental features and modules on and off.";case"trust":return"Scores build automatically as you use and rate skills.";case"guardrails":return"Safety gates that prevent runaway loops, bad searches, and lazy responses.";case"second-brain":return"Your Obsidian-powered second brain — identity, knowledge, and live AI context.";case"mission-control":return"Live command center — active agents, pipelines, and activity feed.";case"dashboards":return"Custom data views built by your AI ally — remix anything.";case"config":return"Edit ~/.openclaw/config.json safely.";case"debug":return"Gateway snapshots, events, and manual RPC calls.";case"logs":return"Live tail of the gateway file logs.";default:return""}}const ee="main";function pm(e){const t=[`viewing ${Gn(e.tab)} tab`];return e.tab==="dashboards"&&e.activeDashboard&&t.push(`dashboard: ${e.activeDashboard.title}`),e.tab==="workspaces"&&e.selectedWorkspace&&t.push(`workspace: ${e.selectedWorkspace.name}`),e.sidebarOpen&&e.sidebarFilePath&&t.push(`viewing file: ${e.sidebarFilePath}`),`[GodMode Context: ${t.join(", ")}]`}async function hm(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}}}const ud=50,pd=200,fm="Assistant";function Ns(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function mi(e){const t=Ns(e?.name,ud)??fm,n=Ns(e?.avatar??void 0,pd)??null;return{agentId:typeof e?.agentId=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function gm(){return mi(typeof window>"u"?{}:{name:window.__CLAWDBOT_ASSISTANT_NAME__,avatar:window.__CLAWDBOT_ASSISTANT_AVATAR__})}const mm="You";function Gr(e){const t=Ns(e?.name,ud)??mm,n=Ns(e?.avatar??void 0,pd)??null;return{name:t,avatar:n}}function vm(){return Gr(typeof window>"u"?{}:{name:window.__CLAWDBOT_USER_NAME__,avatar:window.__CLAWDBOT_USER_AVATAR__})}async function hd(e,t){if(!e.client||!e.connected)return;const n=e.sessionKey.trim(),s=n?{sessionKey:n}:{};try{const a=await e.client.request("agent.identity.get",s);if(!a)return;const i=mi(a);e.assistantName=i.name,e.assistantAvatar=i.avatar,e.assistantAgentId=i.agentId??null}catch{}}let Qr=!1;function Yr(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 ym(){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 bm(){Qr||(Qr=!0,console.warn("[uuid] crypto API missing; falling back to weak randomness"))}function ea(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),Yr(t)}return bm(),Yr(ym())}let $t=null,As=null;function fd(){return As}const Fs=new Map,Ke=new Map;function vi(e,t){const n=t.filter(s=>s?.role==="user").length;Fs.set(e,n)}async function no(e,t){try{const n=await e.request("chat.history",{sessionKey:t,limit:200}),s=Array.isArray(n.messages)?n.messages:[];return Ke.set(t,s),vi(t,s),s}catch{return Ke.get(t)??[]}}let Gt=0;async function ne(e){if(!e.client||!e.connected)return;const t=e.sessionKey,n=++Gt;e.chatLoading=!0,e.lastError=null;try{const s=await e.client.request("chat.history",{sessionKey:t,limit:200});if(n!==Gt||e.sessionKey!==t)return;e.chatMessages=Array.isArray(s.messages)?s.messages:[],e.chatThinkingLevel=s.thinkingLevel??null,vi(t,e.chatMessages),Ke.set(t,e.chatMessages)}catch{if(n!==Gt||e.sessionKey!==t)return;try{const s=await e.client.request("chat.history",{sessionKey:t,limit:200});if(n!==Gt||e.sessionKey!==t)return;e.chatMessages=Array.isArray(s.messages)?s.messages:[],e.chatThinkingLevel=s.thinkingLevel??null,vi(t,e.chatMessages),Ke.set(t,e.chatMessages)}catch(s){if(n!==Gt||e.sessionKey!==t)return;e.lastError=String(s)}}finally{n===Gt&&(e.chatLoading=!1)}}async function gd(e,t){const n=[...e.chatMessages],s=n.length;await ne(e),!t?.allowShrink&&s>0&&e.chatMessages.length<s&&(e.chatMessages=n,setTimeout(()=>{ne(e)},2e3))}function wm(e){const t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function so(e,t,n,s){if(!e.client||!e.connected)return!1;let a=t.trim();const i=n&&n.length>0;if(!a&&!i)return!1;!a&&i&&(a=n.some(p=>p.mimeType.startsWith("image/"))?"What's in this image?":"See attached file.");const o=Date.now();if(!s?.skipOptimisticUpdate){const u=[];if(a&&u.push({type:"text",text:a}),i)for(const p of n)p.mimeType.startsWith("image/")?u.push({type:"image",source:{type:"base64",media_type:p.mimeType,data:p.dataUrl}}):u.push({type:"attachment",mimeType:p.mimeType,fileName:p.fileName,content:p.dataUrl});e.chatMessages=[...e.chatMessages,{role:"user",content:u,timestamp:o}]}e.chatSending=!0,e.chatSendingSessionKey=e.sessionKey,e.lastError=null;const l=ea();e.chatRunId=l,e.chatStream="",e.chatStreamStartedAt=o,$t={message:a,attachments:i?n:void 0};let c;if(i){const u=[],p=[];for(const f of n){const m=wm(f.dataUrl);if(m)if(m.mimeType.startsWith("image/"))u.push({type:"image",mimeType:m.mimeType,content:m.content,fileName:f.fileName});else{const g=f.fileName||"file";p.push(`<document>
702
+ `}function om(e){return e.isCompactionSummary===!0}const rm=[{label:"",tabs:["chat","today","workspaces","second-brain","dashboards"]},{label:"Toolkit",tabs:["skills","trust","guardrails","options"]},{label:"Settings",tabs:["config","debug","logs"]},{label:"System",tabs:["mission-control","overview","channels","instances","sessions","cron","nodes"]}],cd={setup:"/setup",onboarding:"/onboarding",options:"/options",overview:"/overview",workspaces:"/workspaces",today:"/today",work:"/work","my-day":"/today",channels:"/channels",instances:"/instances",sessions:"/sessions",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",trust:"/trust",guardrails:"/guardrails",config:"/config",debug:"/debug",logs:"/logs","second-brain":"/second-brain","mission-control":"/mission-control",dashboards:"/dashboards"},cn=new Map(Object.entries(cd).map(([e,t])=>[t,e]));cn.set("/today","today");cn.set("/my-day","today");cn.set("/work","workspaces");function Zs(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function Vn(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 to(e,t=""){const n=Zs(t),s=cd[e];return n?`${n}${s}`:s}function dd(e,t=""){const n=Zs(t);let s=e||"/";n&&(s===n?s="/":s.startsWith(`${n}/`)&&(s=s.slice(n.length)));let a=Vn(s).toLowerCase();return a.endsWith("/index.html")&&(a="/"),a==="/"?"chat":cn.get(a)??null}function lm(e){let t=Vn(e);if(t.endsWith("/index.html")&&(t=Vn(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let s=0;s<n.length;s++){const a=`/${n.slice(s).join("/")}`.toLowerCase();if(cn.has(a)){const i=n.slice(0,s);return!i.length||i.some(l=>cn.has(`/${l.toLowerCase()}`))?"":`/${i.join("/")}`}}return`/${n.join("/")}`}function Gn(e){switch(e){case"setup":return"Setup";case"onboarding":return"Connect Your World";case"chat":return"Chat";case"today":case"my-day":return"Today";case"work":return"Work";case"overview":return"Overview";case"workspaces":return"Work";case"channels":return"Channels";case"instances":return"Instances";case"sessions":return"Sessions";case"cron":return"Cron Jobs";case"skills":return"Skills";case"nodes":return"Nodes";case"options":return"Lab";case"trust":return"Trust";case"guardrails":return"Guardrails";case"second-brain":return"Second Brain";case"mission-control":return"Mission Control";case"dashboards":return"Dashboards";case"config":return"Config";case"debug":return"Debug";case"logs":return"Logs";default:return"Control"}}function cm(e){switch(e){case"setup":return"🧭";case"onboarding":return"🧭";case"chat":return"💬";case"today":case"my-day":return"☀️";case"work":return"💼";case"overview":return"🎯";case"workspaces":return"📂";case"channels":return"🔗";case"instances":return"📡";case"sessions":return"📄";case"cron":return"⏰";case"skills":return"🧩";case"nodes":return"🖥️";case"options":return"🧪";case"trust":return"🛡️";case"guardrails":return"🚧";case"second-brain":return"🧠";case"mission-control":return"🛰️";case"dashboards":return"📊";case"config":return"⚙️";case"debug":return"🐛";case"logs":return"📜";default:return"📁"}}function dm(e){switch(e){case"setup":return"Get GodMode configured and running.";case"onboarding":return"Set up the integrations that power your daily brief and agent features. Everything is optional.";case"chat":return"Your command center. Ask anything, customize any view.";case"today":case"my-day":return"Calendar, brief, tasks, and schedule for the day.";case"work":return"Your projects, files, tasks, and team — organized by workspace.";case"overview":return"Gateway status, entry points, and a fast health read.";case"workspaces":return"Projects, clients, and personal operating context.";case"channels":return"Manage channels and settings.";case"instances":return"Presence beacons from connected clients and nodes.";case"sessions":return"Inspect active sessions and adjust per-session defaults.";case"cron":return"Schedule wakeups and recurring agent runs.";case"skills":return"Manage your skills, discover new ones from ClawHub, and personalize them for your workflow.";case"nodes":return"Paired devices, capabilities, and command exposure.";case"options":return"Toggle experimental features and modules on and off.";case"trust":return"Scores build automatically as you use and rate skills.";case"guardrails":return"Safety gates that prevent runaway loops, bad searches, and lazy responses.";case"second-brain":return"Your Obsidian-powered second brain — identity, knowledge, and live AI context.";case"mission-control":return"Live command center — active agents, pipelines, and activity feed.";case"dashboards":return"Custom data views built by your AI ally — remix anything.";case"config":return"Edit ~/.openclaw/config.json safely.";case"debug":return"Gateway snapshots, events, and manual RPC calls.";case"logs":return"Live tail of the gateway file logs.";default:return""}}const ee="main";function um(e){const t=[`viewing ${Gn(e.tab)} tab`];return e.tab==="dashboards"&&e.activeDashboard&&t.push(`dashboard: ${e.activeDashboard.title}`),e.tab==="workspaces"&&e.selectedWorkspace&&t.push(`workspace: ${e.selectedWorkspace.name}`),e.sidebarOpen&&e.sidebarFilePath&&t.push(`viewing file: ${e.sidebarFilePath}`),`[GodMode Context: ${t.join(", ")}]`}async function pm(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}}}const ud=50,pd=200,hm="Assistant";function Ns(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function mi(e){const t=Ns(e?.name,ud)??hm,n=Ns(e?.avatar??void 0,pd)??null;return{agentId:typeof e?.agentId=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function fm(){return mi(typeof window>"u"?{}:{name:window.__CLAWDBOT_ASSISTANT_NAME__,avatar:window.__CLAWDBOT_ASSISTANT_AVATAR__})}const gm="You";function Gr(e){const t=Ns(e?.name,ud)??gm,n=Ns(e?.avatar??void 0,pd)??null;return{name:t,avatar:n}}function mm(){return Gr(typeof window>"u"?{}:{name:window.__CLAWDBOT_USER_NAME__,avatar:window.__CLAWDBOT_USER_AVATAR__})}async function hd(e,t){if(!e.client||!e.connected)return;const n=e.sessionKey.trim(),s=n?{sessionKey:n}:{};try{const a=await e.client.request("agent.identity.get",s);if(!a)return;const i=mi(a);e.assistantName=i.name,e.assistantAvatar=i.avatar,e.assistantAgentId=i.agentId??null}catch{}}let Qr=!1;function Yr(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 vm(){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 ym(){Qr||(Qr=!0,console.warn("[uuid] crypto API missing; falling back to weak randomness"))}function ea(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),Yr(t)}return ym(),Yr(vm())}let $t=null,As=null;function fd(){return As}const Fs=new Map,Ke=new Map;function vi(e,t){const n=t.filter(s=>s?.role==="user").length;Fs.set(e,n)}async function no(e,t){try{const n=await e.request("chat.history",{sessionKey:t,limit:200}),s=Array.isArray(n.messages)?n.messages:[];return Ke.set(t,s),vi(t,s),s}catch{return Ke.get(t)??[]}}let Vt=0;async function ne(e){if(!e.client||!e.connected)return;const t=e.sessionKey,n=++Vt;e.chatLoading=!0,e.lastError=null;try{const s=await e.client.request("chat.history",{sessionKey:t,limit:200});if(n!==Vt||e.sessionKey!==t)return;e.chatMessages=Array.isArray(s.messages)?s.messages:[],e.chatThinkingLevel=s.thinkingLevel??null,vi(t,e.chatMessages),Ke.set(t,e.chatMessages)}catch{if(n!==Vt||e.sessionKey!==t)return;try{const s=await e.client.request("chat.history",{sessionKey:t,limit:200});if(n!==Vt||e.sessionKey!==t)return;e.chatMessages=Array.isArray(s.messages)?s.messages:[],e.chatThinkingLevel=s.thinkingLevel??null,vi(t,e.chatMessages),Ke.set(t,e.chatMessages)}catch(s){if(n!==Vt||e.sessionKey!==t)return;e.lastError=String(s)}}finally{n===Vt&&(e.chatLoading=!1)}}async function gd(e,t){const n=[...e.chatMessages],s=n.length;await ne(e),!t?.allowShrink&&s>0&&e.chatMessages.length<s&&(e.chatMessages=n,setTimeout(()=>{ne(e)},2e3))}function bm(e){const t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function so(e,t,n,s){if(!e.client||!e.connected)return!1;let a=t.trim();const i=n&&n.length>0;if(!a&&!i)return!1;!a&&i&&(a=n.some(p=>p.mimeType.startsWith("image/"))?"What's in this image?":"See attached file.");const o=Date.now();if(!s?.skipOptimisticUpdate){const u=[];if(a&&u.push({type:"text",text:a}),i)for(const p of n)p.mimeType.startsWith("image/")?u.push({type:"image",source:{type:"base64",media_type:p.mimeType,data:p.dataUrl}}):u.push({type:"attachment",mimeType:p.mimeType,fileName:p.fileName,content:p.dataUrl});e.chatMessages=[...e.chatMessages,{role:"user",content:u,timestamp:o}]}e.chatSending=!0,e.chatSendingSessionKey=e.sessionKey,e.lastError=null;const l=ea();e.chatRunId=l,e.chatStream="",e.chatStreamStartedAt=o,$t={message:a,attachments:i?n:void 0};let c;if(i){const u=[],p=[];for(const f of n){const m=bm(f.dataUrl);if(m)if(m.mimeType.startsWith("image/"))u.push({type:"image",mimeType:m.mimeType,content:m.content,fileName:f.fileName});else{const g=f.fileName||"file";p.push(`<document>
703
703
  <source>${g}</source>
704
704
  <mime_type>${m.mimeType}</mime_type>
705
705
  <content encoding="base64">
@@ -709,25 +709,25 @@ ${m.content}
709
709
 
710
710
  `)}
711
711
 
712
- ${a}`),u.length>0){const f=e.chatMessages.length-1,m=e.sessionKey,g=e.client.request("images.cache",{images:u.map($=>({data:$.content,mimeType:$.mimeType,fileName:$.fileName})),sessionKey:m}).then($=>{if($?.cached&&$.cached.length>0){const d=$.cached.map((v,S)=>({messageIndex:f,imageIndex:S,hash:v.hash,mimeType:v.mimeType,bytes:v.bytes,role:"user",timestamp:o}));return e.client.request("images.updateIndex",{sessionKey:m,images:d}).catch(()=>{})}}).catch(()=>{});As=g,g.finally(()=>{As===g&&(As=null)})}}try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:a,deliver:!1,idempotencyKey:l,attachments:c}),!0}catch(u){const p=String(u);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=p,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+p}],timestamp:Date.now()}],!1}finally{e.chatSending=!1,e.chatSendingSessionKey=null}}async function md(e){const t=e.pendingRetry;return t?(e.pendingRetry=null,so(e,t.message,t.attachments,{skipOptimisticUpdate:!0})):!1}function $m(e){e.pendingRetry=null}async function ao(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 vd(e,t){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!=="delta"&&rg(),t.state==="delta"){const n=Ct(t.message);if(typeof n=="string"){const s=e.chatStream??"";(!s||n.length>=s.length)&&(e.chatStream=n)}}else if(t.state==="final")e.chatStream&&e.chatStream.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:e.chatStream}],timestamp:Date.now()}]),e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,$t=null;else if(t.state==="aborted")e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,$t=null;else if(t.state==="error"){e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null;const n=t.errorMessage??"chat error";e.lastError=n;const s=n.includes("prompt is too long")||n.includes("tokens >");s&&$t&&(e.pendingRetry={message:$t.message,attachments:$t.attachments,timestamp:Date.now()}),$t=null;let a=n;if(s){const i=n.match(/(\d+)\s*tokens?\s*>\s*(\d+)/);if(i){const o=parseInt(i[1]).toLocaleString(),l=parseInt(i[2]).toLocaleString();a=`⚠️ Context overflow: ${o} tokens exceeds ${l} limit. Compact the conversation, then click "Retry" to resend your message.`}else a='⚠️ Context overflow: The conversation is too long. Compact and click "Retry" to resend.'}e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:a}],timestamp:Date.now(),isError:!0}]}return t.state}const Ge=Object.freeze(Object.defineProperty({__proto__:null,abortChatRun:ao,clearPendingRetry:$m,getPendingImageCache:fd,handleChatEvent:vd,laneMessageCache:Ke,loadChatHistory:ne,loadChatHistoryAfterFinal:gd,loadLaneHistory:no,retryPendingMessage:md,sendChatMessage:so,sessionTurnCounts:Fs},Symbol.toStringTag,{value:"Module"})),yd="godmode.device.auth.v1";function io(e){return e.trim()}function km(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const s=n.trim();s&&t.add(s)}return[...t].sort()}function oo(){try{const e=window.localStorage.getItem(yd);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 bd(e){try{window.localStorage.setItem(yd,JSON.stringify(e))}catch{}}function Sm(e){const t=oo();if(!t||t.deviceId!==e.deviceId)return null;const n=io(e.role),s=t.tokens[n];return!s||typeof s.token!="string"?null:s}function wd(e){const t=io(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},s=oo();s&&s.deviceId===e.deviceId&&(n.tokens={...s.tokens});const a={token:e.token,role:t,scopes:km(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=a,bd(n),a}function $d(e){const t=oo();if(!t||t.deviceId!==e.deviceId)return;const n=io(e.role);if(!t.tokens[n])return;const s={...t,tokens:{...t.tokens}};delete s.tokens[n],bd(s)}const kd={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:ce,n:_s,Gx:Jr,Gy:Xr,a:Na,d:Fa,h:Am}=kd,Pt=32,ro=64,_m=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},se=(e="")=>{const t=new Error(e);throw _m(t,se),t},Tm=e=>typeof e=="bigint",xm=e=>typeof e=="string",Cm=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",ut=(e,t,n="")=>{const s=Cm(e),a=e?.length,i=t!==void 0;if(!s||i&&a!==t){const o=n&&`"${n}" `,l=i?` of length ${t}`:"",c=s?`length=${a}`:`type=${typeof e}`;se(o+"expected Uint8Array"+l+", got "+c)}return e},ta=e=>new Uint8Array(e),Sd=e=>Uint8Array.from(e),Ad=(e,t)=>e.toString(16).padStart(t,"0"),_d=e=>Array.from(ut(e)).map(t=>Ad(t,2)).join(""),Ve={_0:48,_9:57,A:65,F:70,a:97,f:102},Zr=e=>{if(e>=Ve._0&&e<=Ve._9)return e-Ve._0;if(e>=Ve.A&&e<=Ve.F)return e-(Ve.A-10);if(e>=Ve.a&&e<=Ve.f)return e-(Ve.a-10)},Td=e=>{const t="hex invalid";if(!xm(e))return se(t);const n=e.length,s=n/2;if(n%2)return se(t);const a=ta(s);for(let i=0,o=0;i<s;i++,o+=2){const l=Zr(e.charCodeAt(o)),c=Zr(e.charCodeAt(o+1));if(l===void 0||c===void 0)return se(t);a[i]=l*16+c}return a},xd=()=>globalThis?.crypto,Em=()=>xd()?.subtle??se("crypto.subtle must be defined, consider polyfill"),Qn=(...e)=>{const t=ta(e.reduce((s,a)=>s+ut(a).length,0));let n=0;return e.forEach(s=>{t.set(s,n),n+=s.length}),t},Lm=(e=Pt)=>xd().getRandomValues(ta(e)),Bs=BigInt,kt=(e,t,n,s="bad number: out of range")=>Tm(e)&&t<=e&&e<n?e:se(s),I=(e,t=ce)=>{const n=e%t;return n>=0n?n:t+n},Cd=e=>I(e,_s),Rm=(e,t)=>{(e===0n||t<=0n)&&se("no inverse n="+e+" mod="+t);let n=I(e,t),s=t,a=0n,i=1n;for(;n!==0n;){const o=s/n,l=s%n,c=a-i*o;s=n,n=l,a=i,i=c}return s===1n?I(a,t):se("no inverse")},Pm=e=>{const t=Pd[e];return typeof t!="function"&&se("hashes."+e+" not set"),t},Ba=e=>e instanceof _e?e:se("Point expected"),yi=2n**256n;class _e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,s,a){const i=yi;this.X=kt(t,0n,i),this.Y=kt(n,0n,i),this.Z=kt(s,1n,i),this.T=kt(a,0n,i),Object.freeze(this)}static CURVE(){return kd}static fromAffine(t){return new _e(t.x,t.y,1n,I(t.x*t.y))}static fromBytes(t,n=!1){const s=Fa,a=Sd(ut(t,Pt)),i=t[31];a[31]=i&-129;const o=Ld(a);kt(o,0n,n?yi:ce);const c=I(o*o),u=I(c-1n),p=I(s*c+1n);let{isValid:f,value:m}=Mm(u,p);f||se("bad point: y not sqrt");const g=(m&1n)===1n,$=(i&128)!==0;return!n&&m===0n&&$&&se("bad point: x==0, isLastByteOdd"),$!==g&&(m=I(-m)),new _e(m,o,1n,I(m*o))}static fromHex(t,n){return _e.fromBytes(Td(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Na,n=Fa,s=this;if(s.is0())return se("bad point: ZERO");const{X:a,Y:i,Z:o,T:l}=s,c=I(a*a),u=I(i*i),p=I(o*o),f=I(p*p),m=I(c*t),g=I(p*I(m+u)),$=I(f+I(n*I(c*u)));if(g!==$)return se("bad point: equation left != right (1)");const d=I(a*i),v=I(o*l);return d!==v?se("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:s,Z:a}=this,{X:i,Y:o,Z:l}=Ba(t),c=I(n*l),u=I(i*a),p=I(s*l),f=I(o*a);return c===u&&p===f}is0(){return this.equals(en)}negate(){return new _e(I(-this.X),this.Y,this.Z,I(-this.T))}double(){const{X:t,Y:n,Z:s}=this,a=Na,i=I(t*t),o=I(n*n),l=I(2n*I(s*s)),c=I(a*i),u=t+n,p=I(I(u*u)-i-o),f=c+o,m=f-l,g=c-o,$=I(p*m),d=I(f*g),v=I(p*g),S=I(m*f);return new _e($,d,S,v)}add(t){const{X:n,Y:s,Z:a,T:i}=this,{X:o,Y:l,Z:c,T:u}=Ba(t),p=Na,f=Fa,m=I(n*o),g=I(s*l),$=I(i*f*u),d=I(a*c),v=I((n+s)*(o+l)-m-g),S=I(d-$),_=I(d+$),T=I(g-p*m),A=I(v*S),C=I(_*T),L=I(v*T),P=I(S*_);return new _e(A,C,P,L)}subtract(t){return this.add(Ba(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return en;if(kt(t,1n,_s),t===1n)return this;if(this.equals(It))return jm(t).p;let s=en,a=It;for(let i=this;t>0n;i=i.double(),t>>=1n)t&1n?s=s.add(i):n&&(a=a.add(i));return s}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:s}=this;if(this.equals(en))return{x:0n,y:1n};const a=Rm(s,ce);I(s*a)!==1n&&se("invalid inverse");const i=I(t*a),o=I(n*a);return{x:i,y:o}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),s=Ed(n);return s[31]|=t&1n?128:0,s}toHex(){return _d(this.toBytes())}clearCofactor(){return this.multiply(Bs(Am),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(_s/2n,!1).double();return _s%2n&&(t=t.add(this)),t.is0()}}const It=new _e(Jr,Xr,1n,I(Jr*Xr)),en=new _e(0n,1n,1n,0n);_e.BASE=It;_e.ZERO=en;const Ed=e=>Td(Ad(kt(e,0n,yi),ro)).reverse(),Ld=e=>Bs("0x"+_d(Sd(ut(e)).reverse())),Fe=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ce;return n},Im=e=>{const n=e*e%ce*e%ce,s=Fe(n,2n)*n%ce,a=Fe(s,1n)*e%ce,i=Fe(a,5n)*a%ce,o=Fe(i,10n)*i%ce,l=Fe(o,20n)*o%ce,c=Fe(l,40n)*l%ce,u=Fe(c,80n)*c%ce,p=Fe(u,80n)*c%ce,f=Fe(p,10n)*i%ce;return{pow_p_5_8:Fe(f,2n)*e%ce,b2:n}},el=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Mm=(e,t)=>{const n=I(t*t*t),s=I(n*n*t),a=Im(e*s).pow_p_5_8;let i=I(e*n*a);const o=I(t*i*i),l=i,c=I(i*el),u=o===e,p=o===I(-e),f=o===I(-e*el);return u&&(i=l),(p||f)&&(i=c),(I(i)&1n)===1n&&(i=I(-i)),{isValid:u||p,value:i}},bi=e=>Cd(Ld(e)),lo=(...e)=>Pd.sha512Async(Qn(...e)),Dm=(...e)=>Pm("sha512")(Qn(...e)),Rd=e=>{const t=e.slice(0,Pt);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Pt,ro),s=bi(t),a=It.multiply(s),i=a.toBytes();return{head:t,prefix:n,scalar:s,point:a,pointBytes:i}},co=e=>lo(ut(e,Pt)).then(Rd),Om=e=>Rd(Dm(ut(e,Pt))),Nm=e=>co(e).then(t=>t.pointBytes),Fm=e=>lo(e.hashable).then(e.finish),Bm=(e,t,n)=>{const{pointBytes:s,scalar:a}=e,i=bi(t),o=It.multiply(i).toBytes();return{hashable:Qn(o,s,n),finish:u=>{const p=Cd(i+bi(u)*a);return ut(Qn(o,Ed(p)),ro)}}},Um=async(e,t)=>{const n=ut(e),s=await co(t),a=await lo(s.prefix,n);return Fm(Bm(s,a,n))},Pd={sha512Async:async e=>{const t=Em(),n=Qn(e);return ta(await t.digest("SHA-512",n.buffer))},sha512:void 0},zm=(e=Lm(Pt))=>e,Km={getExtendedPublicKeyAsync:co,getExtendedPublicKey:Om,randomSecretKey:zm},Us=8,Wm=256,Id=Math.ceil(Wm/Us)+1,wi=2**(Us-1),qm=()=>{const e=[];let t=It,n=t;for(let s=0;s<Id;s++){n=t,e.push(n);for(let a=1;a<wi;a++)n=n.add(t),e.push(n);t=n.double()}return e};let tl;const nl=(e,t)=>{const n=t.negate();return e?n:t},jm=e=>{const t=tl||(tl=qm());let n=en,s=It;const a=2**Us,i=a,o=Bs(a-1),l=Bs(Us);for(let c=0;c<Id;c++){let u=Number(e&o);e>>=l,u>wi&&(u-=i,e+=1n);const p=c*wi,f=p,m=p+Math.abs(u)-1,g=c%2!==0,$=u<0;u===0?s=s.add(nl(g,t[f])):n=n.add(nl($,t[m]))}return e!==0n&&se("invalid wnaf"),{p:n,f:s}},Ua="godmode-device-identity-v1";function $i(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/g,"")}function Md(e){const t=e.replaceAll("-","+").replaceAll("_","/"),n=t+"=".repeat((4-t.length%4)%4),s=atob(n),a=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)a[i]=s.charCodeAt(i);return a}function Hm(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Dd(e){const t=await crypto.subtle.digest("SHA-256",e);return Hm(new Uint8Array(t))}async function Vm(){const e=Km.randomSecretKey(),t=await Nm(e);return{deviceId:await Dd(t),publicKey:$i(t),privateKey:$i(e)}}async function uo(){try{const n=localStorage.getItem(Ua);if(n){const s=JSON.parse(n);if(s?.version===1&&typeof s.deviceId=="string"&&typeof s.publicKey=="string"&&typeof s.privateKey=="string"){const a=await Dd(Md(s.publicKey));if(a!==s.deviceId){const i={...s,deviceId:a};return localStorage.setItem(Ua,JSON.stringify(i)),{deviceId:a,publicKey:s.publicKey,privateKey:s.privateKey}}return{deviceId:s.deviceId,publicKey:s.publicKey,privateKey:s.privateKey}}}}catch{}const e=await Vm(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Ua,JSON.stringify(t)),e}async function Gm(e,t){const n=Md(e),s=new TextEncoder().encode(t),a=await Um(s,n);return $i(a)}async function pt(e,t){if(!(!e.client||!e.connected)&&!e.devicesLoading){e.devicesLoading=!0,t?.quiet||(e.devicesError=null);try{const n=await e.client.request("device.pair.list",{});e.devicesList={pending:Array.isArray(n?.pending)?n.pending:[],paired:Array.isArray(n?.paired)?n.paired:[]}}catch(n){t?.quiet||(e.devicesError=String(n))}finally{e.devicesLoading=!1}}}async function Qm(e,t){if(!(!e.client||!e.connected))try{await e.client.request("device.pair.approve",{requestId:t}),await pt(e)}catch(n){e.devicesError=String(n)}}async function Ym(e,t){if(!(!e.client||!e.connected||!window.confirm("Reject this device pairing request?")))try{await e.client.request("device.pair.reject",{requestId:t}),await pt(e)}catch(s){e.devicesError=String(s)}}async function Jm(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("device.token.rotate",t);if(n?.token){const s=await uo(),a=n.role??t.role;(n.deviceId===s.deviceId||t.deviceId===s.deviceId)&&wd({deviceId:s.deviceId,role:a,token:n.token,scopes:n.scopes??t.scopes??[]}),window.prompt("New device token (copy and store securely):",n.token)}await pt(e)}catch(n){e.devicesError=String(n)}}async function Xm(e,t){if(!(!e.client||!e.connected||!window.confirm(`Revoke token for ${t.deviceId} (${t.role})?`)))try{await e.client.request("device.token.revoke",t);const s=await uo();t.deviceId===s.deviceId&&$d({deviceId:s.deviceId,role:t.role}),await pt(e)}catch(s){e.devicesError=String(s)}}function ki(e){return typeof e=="object"&&e!==null}function Zm(e){if(!ki(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!ki(n))return null;const s=typeof n.command=="string"?n.command.trim():"";if(!s)return null;const a=typeof e.createdAtMs=="number"?e.createdAtMs:0,i=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!a||!i?null:{id:t,request:{command:s,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:a,expiresAtMs:i}}function ev(e){if(!ki(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 Od(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function tv(e,t){const n=Od(e).filter(s=>s.id!==t.id);return n.push(t),n}function sl(e,t){return Od(e).filter(n=>n.id!==t)}async function na(e,t){if(!(!e.client||!e.connected)&&!e.nodesLoading){e.nodesLoading=!0,t?.quiet||(e.lastError=null);try{const n=await e.client.request("node.list",{}),s=Array.isArray(n.nodes)?n.nodes:[];JSON.stringify(s)!==JSON.stringify(e.nodes)&&(e.nodes=s)}catch(n){t?.quiet||(e.lastError=String(n))}finally{e.nodesLoading=!1}}}const Te=new Map;async function X(e,t){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const n=t?.includeGlobal??e.sessionsIncludeGlobal,s=t?.includeUnknown??e.sessionsIncludeUnknown,a=t?.activeMinutes??Is(e.sessionsFilterActive,0),i=t?.limit??Is(e.sessionsFilterLimit,50),o={includeGlobal:n,includeUnknown:s};a>0&&(o.activeMinutes=a),i>0&&(o.limit=i);const l=await e.client.request("sessions.list",o);if(l){if(l.sessions){const c=new Map;if(e.sessionsResult?.sessions)for(const u of e.sessionsResult.sessions)u.displayName&&c.set(u.key,u.displayName);l.sessions=l.sessions.map(u=>{if(u.displayName)return u;const p=Te.get(u.key);if(p)return{...u,displayName:p};const f=c.get(u.key);return f?{...u,displayName:f}:u})}e.sessionsResult=l}}catch(n){e.sessionsError=String(n)}finally{e.sessionsLoading=!1}}}async function Ts(e,t,n){if(!e.client||!e.connected)return{ok:!1};const s={key:t};"label"in n&&(s.label=n.label),"displayName"in n&&(s.displayName=n.displayName),"thinkingLevel"in n&&(s.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(s.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(s.reasoningLevel=n.reasoningLevel);try{const{safeRequest:a}=await E(async()=>{const{safeRequest:o}=await Promise.resolve().then(()=>fv);return{safeRequest:o}},void 0,import.meta.url),i=await a(e.client,"sessions.patch",s);return i.ok?{ok:!0,canonicalKey:i.data?.key??t}:(e.sessionsError=i.error,{ok:!1})}catch(a){return e.sessionsError=String(a),{ok:!1}}}async function Nd(e,t){if(!(!e.client||!e.connected||e.sessionsLoading||!window.confirm(`Delete session "${t}"?
712
+ ${a}`),u.length>0){const f=e.chatMessages.length-1,m=e.sessionKey,g=e.client.request("images.cache",{images:u.map($=>({data:$.content,mimeType:$.mimeType,fileName:$.fileName})),sessionKey:m}).then($=>{if($?.cached&&$.cached.length>0){const d=$.cached.map((v,S)=>({messageIndex:f,imageIndex:S,hash:v.hash,mimeType:v.mimeType,bytes:v.bytes,role:"user",timestamp:o}));return e.client.request("images.updateIndex",{sessionKey:m,images:d}).catch(()=>{})}}).catch(()=>{});As=g,g.finally(()=>{As===g&&(As=null)})}}try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:a,deliver:!1,idempotencyKey:l,attachments:c}),!0}catch(u){const p=String(u);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=p,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+p}],timestamp:Date.now()}],!1}finally{e.chatSending=!1,e.chatSendingSessionKey=null}}async function md(e){const t=e.pendingRetry;return t?(e.pendingRetry=null,so(e,t.message,t.attachments,{skipOptimisticUpdate:!0})):!1}function wm(e){e.pendingRetry=null}async function ao(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 vd(e,t){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!=="delta"&&og(),t.state==="delta"){const n=xt(t.message);if(typeof n=="string"){const s=e.chatStream??"";(!s||n.length>=s.length)&&(e.chatStream=n)}}else if(t.state==="final")e.chatStream&&e.chatStream.trim()&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:e.chatStream}],timestamp:Date.now()}]),e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,$t=null;else if(t.state==="aborted")e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,$t=null;else if(t.state==="error"){e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null;const n=t.errorMessage??"chat error";e.lastError=n;const s=n.includes("prompt is too long")||n.includes("tokens >");s&&$t&&(e.pendingRetry={message:$t.message,attachments:$t.attachments,timestamp:Date.now()}),$t=null;let a=n;if(s){const i=n.match(/(\d+)\s*tokens?\s*>\s*(\d+)/);if(i){const o=parseInt(i[1]).toLocaleString(),l=parseInt(i[2]).toLocaleString();a=`⚠️ Context overflow: ${o} tokens exceeds ${l} limit. Compact the conversation, then click "Retry" to resend your message.`}else a='⚠️ Context overflow: The conversation is too long. Compact and click "Retry" to resend.'}e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:a}],timestamp:Date.now(),isError:!0}]}return t.state}const Ge=Object.freeze(Object.defineProperty({__proto__:null,abortChatRun:ao,clearPendingRetry:wm,getPendingImageCache:fd,handleChatEvent:vd,laneMessageCache:Ke,loadChatHistory:ne,loadChatHistoryAfterFinal:gd,loadLaneHistory:no,retryPendingMessage:md,sendChatMessage:so,sessionTurnCounts:Fs},Symbol.toStringTag,{value:"Module"})),yd="godmode.device.auth.v1";function io(e){return e.trim()}function $m(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const s=n.trim();s&&t.add(s)}return[...t].sort()}function oo(){try{const e=window.localStorage.getItem(yd);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 bd(e){try{window.localStorage.setItem(yd,JSON.stringify(e))}catch{}}function km(e){const t=oo();if(!t||t.deviceId!==e.deviceId)return null;const n=io(e.role),s=t.tokens[n];return!s||typeof s.token!="string"?null:s}function wd(e){const t=io(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},s=oo();s&&s.deviceId===e.deviceId&&(n.tokens={...s.tokens});const a={token:e.token,role:t,scopes:$m(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=a,bd(n),a}function $d(e){const t=oo();if(!t||t.deviceId!==e.deviceId)return;const n=io(e.role);if(!t.tokens[n])return;const s={...t,tokens:{...t.tokens}};delete s.tokens[n],bd(s)}const kd={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:ce,n:_s,Gx:Jr,Gy:Xr,a:Na,d:Fa,h:Sm}=kd,Rt=32,ro=64,Am=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},se=(e="")=>{const t=new Error(e);throw Am(t,se),t},_m=e=>typeof e=="bigint",Tm=e=>typeof e=="string",xm=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",ut=(e,t,n="")=>{const s=xm(e),a=e?.length,i=t!==void 0;if(!s||i&&a!==t){const o=n&&`"${n}" `,l=i?` of length ${t}`:"",c=s?`length=${a}`:`type=${typeof e}`;se(o+"expected Uint8Array"+l+", got "+c)}return e},ta=e=>new Uint8Array(e),Sd=e=>Uint8Array.from(e),Ad=(e,t)=>e.toString(16).padStart(t,"0"),_d=e=>Array.from(ut(e)).map(t=>Ad(t,2)).join(""),Ve={_0:48,_9:57,A:65,F:70,a:97,f:102},Zr=e=>{if(e>=Ve._0&&e<=Ve._9)return e-Ve._0;if(e>=Ve.A&&e<=Ve.F)return e-(Ve.A-10);if(e>=Ve.a&&e<=Ve.f)return e-(Ve.a-10)},Td=e=>{const t="hex invalid";if(!Tm(e))return se(t);const n=e.length,s=n/2;if(n%2)return se(t);const a=ta(s);for(let i=0,o=0;i<s;i++,o+=2){const l=Zr(e.charCodeAt(o)),c=Zr(e.charCodeAt(o+1));if(l===void 0||c===void 0)return se(t);a[i]=l*16+c}return a},xd=()=>globalThis?.crypto,Cm=()=>xd()?.subtle??se("crypto.subtle must be defined, consider polyfill"),Qn=(...e)=>{const t=ta(e.reduce((s,a)=>s+ut(a).length,0));let n=0;return e.forEach(s=>{t.set(s,n),n+=s.length}),t},Em=(e=Rt)=>xd().getRandomValues(ta(e)),Bs=BigInt,kt=(e,t,n,s="bad number: out of range")=>_m(e)&&t<=e&&e<n?e:se(s),I=(e,t=ce)=>{const n=e%t;return n>=0n?n:t+n},Cd=e=>I(e,_s),Lm=(e,t)=>{(e===0n||t<=0n)&&se("no inverse n="+e+" mod="+t);let n=I(e,t),s=t,a=0n,i=1n;for(;n!==0n;){const o=s/n,l=s%n,c=a-i*o;s=n,n=l,a=i,i=c}return s===1n?I(a,t):se("no inverse")},Rm=e=>{const t=Pd[e];return typeof t!="function"&&se("hashes."+e+" not set"),t},Ba=e=>e instanceof _e?e:se("Point expected"),yi=2n**256n;class _e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,s,a){const i=yi;this.X=kt(t,0n,i),this.Y=kt(n,0n,i),this.Z=kt(s,1n,i),this.T=kt(a,0n,i),Object.freeze(this)}static CURVE(){return kd}static fromAffine(t){return new _e(t.x,t.y,1n,I(t.x*t.y))}static fromBytes(t,n=!1){const s=Fa,a=Sd(ut(t,Rt)),i=t[31];a[31]=i&-129;const o=Ld(a);kt(o,0n,n?yi:ce);const c=I(o*o),u=I(c-1n),p=I(s*c+1n);let{isValid:f,value:m}=Im(u,p);f||se("bad point: y not sqrt");const g=(m&1n)===1n,$=(i&128)!==0;return!n&&m===0n&&$&&se("bad point: x==0, isLastByteOdd"),$!==g&&(m=I(-m)),new _e(m,o,1n,I(m*o))}static fromHex(t,n){return _e.fromBytes(Td(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Na,n=Fa,s=this;if(s.is0())return se("bad point: ZERO");const{X:a,Y:i,Z:o,T:l}=s,c=I(a*a),u=I(i*i),p=I(o*o),f=I(p*p),m=I(c*t),g=I(p*I(m+u)),$=I(f+I(n*I(c*u)));if(g!==$)return se("bad point: equation left != right (1)");const d=I(a*i),v=I(o*l);return d!==v?se("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:s,Z:a}=this,{X:i,Y:o,Z:l}=Ba(t),c=I(n*l),u=I(i*a),p=I(s*l),f=I(o*a);return c===u&&p===f}is0(){return this.equals(en)}negate(){return new _e(I(-this.X),this.Y,this.Z,I(-this.T))}double(){const{X:t,Y:n,Z:s}=this,a=Na,i=I(t*t),o=I(n*n),l=I(2n*I(s*s)),c=I(a*i),u=t+n,p=I(I(u*u)-i-o),f=c+o,m=f-l,g=c-o,$=I(p*m),d=I(f*g),v=I(p*g),S=I(m*f);return new _e($,d,S,v)}add(t){const{X:n,Y:s,Z:a,T:i}=this,{X:o,Y:l,Z:c,T:u}=Ba(t),p=Na,f=Fa,m=I(n*o),g=I(s*l),$=I(i*f*u),d=I(a*c),v=I((n+s)*(o+l)-m-g),S=I(d-$),_=I(d+$),T=I(g-p*m),A=I(v*S),C=I(_*T),L=I(v*T),P=I(S*_);return new _e(A,C,P,L)}subtract(t){return this.add(Ba(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return en;if(kt(t,1n,_s),t===1n)return this;if(this.equals(Pt))return qm(t).p;let s=en,a=Pt;for(let i=this;t>0n;i=i.double(),t>>=1n)t&1n?s=s.add(i):n&&(a=a.add(i));return s}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:s}=this;if(this.equals(en))return{x:0n,y:1n};const a=Lm(s,ce);I(s*a)!==1n&&se("invalid inverse");const i=I(t*a),o=I(n*a);return{x:i,y:o}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),s=Ed(n);return s[31]|=t&1n?128:0,s}toHex(){return _d(this.toBytes())}clearCofactor(){return this.multiply(Bs(Sm),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(_s/2n,!1).double();return _s%2n&&(t=t.add(this)),t.is0()}}const Pt=new _e(Jr,Xr,1n,I(Jr*Xr)),en=new _e(0n,1n,1n,0n);_e.BASE=Pt;_e.ZERO=en;const Ed=e=>Td(Ad(kt(e,0n,yi),ro)).reverse(),Ld=e=>Bs("0x"+_d(Sd(ut(e)).reverse())),Fe=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=ce;return n},Pm=e=>{const n=e*e%ce*e%ce,s=Fe(n,2n)*n%ce,a=Fe(s,1n)*e%ce,i=Fe(a,5n)*a%ce,o=Fe(i,10n)*i%ce,l=Fe(o,20n)*o%ce,c=Fe(l,40n)*l%ce,u=Fe(c,80n)*c%ce,p=Fe(u,80n)*c%ce,f=Fe(p,10n)*i%ce;return{pow_p_5_8:Fe(f,2n)*e%ce,b2:n}},el=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Im=(e,t)=>{const n=I(t*t*t),s=I(n*n*t),a=Pm(e*s).pow_p_5_8;let i=I(e*n*a);const o=I(t*i*i),l=i,c=I(i*el),u=o===e,p=o===I(-e),f=o===I(-e*el);return u&&(i=l),(p||f)&&(i=c),(I(i)&1n)===1n&&(i=I(-i)),{isValid:u||p,value:i}},bi=e=>Cd(Ld(e)),lo=(...e)=>Pd.sha512Async(Qn(...e)),Mm=(...e)=>Rm("sha512")(Qn(...e)),Rd=e=>{const t=e.slice(0,Rt);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Rt,ro),s=bi(t),a=Pt.multiply(s),i=a.toBytes();return{head:t,prefix:n,scalar:s,point:a,pointBytes:i}},co=e=>lo(ut(e,Rt)).then(Rd),Dm=e=>Rd(Mm(ut(e,Rt))),Om=e=>co(e).then(t=>t.pointBytes),Nm=e=>lo(e.hashable).then(e.finish),Fm=(e,t,n)=>{const{pointBytes:s,scalar:a}=e,i=bi(t),o=Pt.multiply(i).toBytes();return{hashable:Qn(o,s,n),finish:u=>{const p=Cd(i+bi(u)*a);return ut(Qn(o,Ed(p)),ro)}}},Bm=async(e,t)=>{const n=ut(e),s=await co(t),a=await lo(s.prefix,n);return Nm(Fm(s,a,n))},Pd={sha512Async:async e=>{const t=Cm(),n=Qn(e);return ta(await t.digest("SHA-512",n.buffer))},sha512:void 0},Um=(e=Em(Rt))=>e,zm={getExtendedPublicKeyAsync:co,getExtendedPublicKey:Dm,randomSecretKey:Um},Us=8,Km=256,Id=Math.ceil(Km/Us)+1,wi=2**(Us-1),Wm=()=>{const e=[];let t=Pt,n=t;for(let s=0;s<Id;s++){n=t,e.push(n);for(let a=1;a<wi;a++)n=n.add(t),e.push(n);t=n.double()}return e};let tl;const nl=(e,t)=>{const n=t.negate();return e?n:t},qm=e=>{const t=tl||(tl=Wm());let n=en,s=Pt;const a=2**Us,i=a,o=Bs(a-1),l=Bs(Us);for(let c=0;c<Id;c++){let u=Number(e&o);e>>=l,u>wi&&(u-=i,e+=1n);const p=c*wi,f=p,m=p+Math.abs(u)-1,g=c%2!==0,$=u<0;u===0?s=s.add(nl(g,t[f])):n=n.add(nl($,t[m]))}return e!==0n&&se("invalid wnaf"),{p:n,f:s}},Ua="godmode-device-identity-v1";function $i(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/g,"")}function Md(e){const t=e.replaceAll("-","+").replaceAll("_","/"),n=t+"=".repeat((4-t.length%4)%4),s=atob(n),a=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)a[i]=s.charCodeAt(i);return a}function jm(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Dd(e){const t=await crypto.subtle.digest("SHA-256",e);return jm(new Uint8Array(t))}async function Hm(){const e=zm.randomSecretKey(),t=await Om(e);return{deviceId:await Dd(t),publicKey:$i(t),privateKey:$i(e)}}async function uo(){try{const n=localStorage.getItem(Ua);if(n){const s=JSON.parse(n);if(s?.version===1&&typeof s.deviceId=="string"&&typeof s.publicKey=="string"&&typeof s.privateKey=="string"){const a=await Dd(Md(s.publicKey));if(a!==s.deviceId){const i={...s,deviceId:a};return localStorage.setItem(Ua,JSON.stringify(i)),{deviceId:a,publicKey:s.publicKey,privateKey:s.privateKey}}return{deviceId:s.deviceId,publicKey:s.publicKey,privateKey:s.privateKey}}}}catch{}const e=await Hm(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(Ua,JSON.stringify(t)),e}async function Vm(e,t){const n=Md(e),s=new TextEncoder().encode(t),a=await Bm(s,n);return $i(a)}async function pt(e,t){if(!(!e.client||!e.connected)&&!e.devicesLoading){e.devicesLoading=!0,t?.quiet||(e.devicesError=null);try{const n=await e.client.request("device.pair.list",{});e.devicesList={pending:Array.isArray(n?.pending)?n.pending:[],paired:Array.isArray(n?.paired)?n.paired:[]}}catch(n){t?.quiet||(e.devicesError=String(n))}finally{e.devicesLoading=!1}}}async function Gm(e,t){if(!(!e.client||!e.connected))try{await e.client.request("device.pair.approve",{requestId:t}),await pt(e)}catch(n){e.devicesError=String(n)}}async function Qm(e,t){if(!(!e.client||!e.connected||!window.confirm("Reject this device pairing request?")))try{await e.client.request("device.pair.reject",{requestId:t}),await pt(e)}catch(s){e.devicesError=String(s)}}async function Ym(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("device.token.rotate",t);if(n?.token){const s=await uo(),a=n.role??t.role;(n.deviceId===s.deviceId||t.deviceId===s.deviceId)&&wd({deviceId:s.deviceId,role:a,token:n.token,scopes:n.scopes??t.scopes??[]}),window.prompt("New device token (copy and store securely):",n.token)}await pt(e)}catch(n){e.devicesError=String(n)}}async function Jm(e,t){if(!(!e.client||!e.connected||!window.confirm(`Revoke token for ${t.deviceId} (${t.role})?`)))try{await e.client.request("device.token.revoke",t);const s=await uo();t.deviceId===s.deviceId&&$d({deviceId:s.deviceId,role:t.role}),await pt(e)}catch(s){e.devicesError=String(s)}}function ki(e){return typeof e=="object"&&e!==null}function Xm(e){if(!ki(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!ki(n))return null;const s=typeof n.command=="string"?n.command.trim():"";if(!s)return null;const a=typeof e.createdAtMs=="number"?e.createdAtMs:0,i=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!a||!i?null:{id:t,request:{command:s,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:a,expiresAtMs:i}}function Zm(e){if(!ki(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 Od(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function ev(e,t){const n=Od(e).filter(s=>s.id!==t.id);return n.push(t),n}function sl(e,t){return Od(e).filter(n=>n.id!==t)}async function na(e,t){if(!(!e.client||!e.connected)&&!e.nodesLoading){e.nodesLoading=!0,t?.quiet||(e.lastError=null);try{const n=await e.client.request("node.list",{}),s=Array.isArray(n.nodes)?n.nodes:[];JSON.stringify(s)!==JSON.stringify(e.nodes)&&(e.nodes=s)}catch(n){t?.quiet||(e.lastError=String(n))}finally{e.nodesLoading=!1}}}const Te=new Map;async function X(e,t){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const n=t?.includeGlobal??e.sessionsIncludeGlobal,s=t?.includeUnknown??e.sessionsIncludeUnknown,a=t?.activeMinutes??Is(e.sessionsFilterActive,0),i=t?.limit??Is(e.sessionsFilterLimit,50),o={includeGlobal:n,includeUnknown:s};a>0&&(o.activeMinutes=a),i>0&&(o.limit=i);const l=await e.client.request("sessions.list",o);if(l){if(l.sessions){const c=new Map;if(e.sessionsResult?.sessions)for(const u of e.sessionsResult.sessions)u.displayName&&c.set(u.key,u.displayName);l.sessions=l.sessions.map(u=>{if(u.displayName)return u;const p=Te.get(u.key);if(p)return{...u,displayName:p};const f=c.get(u.key);return f?{...u,displayName:f}:u})}e.sessionsResult=l}}catch(n){e.sessionsError=String(n)}finally{e.sessionsLoading=!1}}}async function Ts(e,t,n){if(!e.client||!e.connected)return{ok:!1};const s={key:t};"label"in n&&(s.label=n.label),"displayName"in n&&(s.displayName=n.displayName),"thinkingLevel"in n&&(s.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(s.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(s.reasoningLevel=n.reasoningLevel);try{const{safeRequest:a}=await E(async()=>{const{safeRequest:o}=await Promise.resolve().then(()=>hv);return{safeRequest:o}},void 0,import.meta.url),i=await a(e.client,"sessions.patch",s);return i.ok?{ok:!0,canonicalKey:i.data?.key??t}:(e.sessionsError=i.error,{ok:!1})}catch(a){return e.sessionsError=String(a),{ok:!1}}}async function Nd(e,t){if(!(!e.client||!e.connected||e.sessionsLoading||!window.confirm(`Delete session "${t}"?
713
713
 
714
- Deletes the session entry and archives its transcript.`))){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.delete",{key:t,deleteTranscript:!0}),await X(e)}catch(s){e.sessionsError=String(s)}finally{e.sessionsLoading=!1}}}async function Mt(e){if(!(!e.client||!e.connected)){e.archivedSessionsLoading=!0;try{const t=await e.client.request("sessions.archived",{});t?.archived&&(e.archivedSessions=t.archived)}catch{}finally{e.archivedSessionsLoading=!1}}}async function Fd(e,t){if(!(!e.client||!e.connected))try{await e.client.request("sessions.archive",{sessionKey:t}),await Mt(e),await X(e)}catch(n){e.sessionsError=`Archive failed: ${String(n)}`}}async function Bd(e,t){if(!(!e.client||!e.connected))try{await e.client.request("sessions.unarchive",{sessionKey:t}),await Mt(e),await X(e)}catch(n){e.sessionsError=`Unarchive failed: ${String(n)}`}}async function Ud(e){if(!e.client||!e.connected)return 0;try{const n=(await e.client.request("sessions.autoArchive",{}))?.archivedCount??0;return await Mt(e),await X(e),n}catch(t){return e.sessionsError=`Auto-archive failed: ${String(t)}`,0}}const Cn=Object.freeze(Object.defineProperty({__proto__:null,archiveSession:Fd,autoTitleCache:Te,deleteSession:Nd,loadArchivedSessions:Mt,loadSessions:X,patchSession:Ts,triggerAutoArchive:Ud,unarchiveSession:Bd},Symbol.toStringTag,{value:"Module"})),nv=1800*1e3;function zd(e){return{openclawVersion:e.openclaw.version,openclawLatest:e.openclaw.latest,openclawUpdateAvailable:e.openclaw.updateAvailable,openclawInstallKind:e.openclaw.installKind,openclawChannel:e.openclaw.channel,pluginVersion:e.plugin.version,pluginLatest:e.plugin.latest,pluginUpdateAvailable:e.plugin.updateAvailable,fetchOk:e.fetchOk}}function Kd(e){const t=typeof e.behind=="number"?e.behind:null;return{openclawVersion:String(e.version??"unknown"),openclawLatest:null,openclawUpdateAvailable:(t??0)>0,openclawInstallKind:"unknown",openclawChannel:null,pluginVersion:"unknown",pluginLatest:null,pluginUpdateAvailable:!1,fetchOk:e.fetchOk}}async function sv(e){if(!(!e.client||!e.connected)){e.updateLoading=!0,e.updateError=null;try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=zd(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});t.error&&(e.updateError=String(t.error)),e.updateStatus=Kd(t),e.updateLastChecked=Date.now()}catch(t){e.updateError=String(t)}}finally{e.updateLoading=!1}}}async function al(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=zd(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});e.updateStatus=Kd(t),e.updateLastChecked=Date.now()}catch{}}}function av(e){e.updatePollInterval==null&&(al(e),e.updatePollInterval=window.setInterval(()=>{al(e)},nv))}function iv(e){const t=e;t.updatePollInterval!=null&&(clearInterval(t.updatePollInterval),t.updatePollInterval=null)}const Wd={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",GODMODE_WEBCHAT:"godmode-webchat",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",IOS_APP:"openclaw-ios",ANDROID_APP:"openclaw-android",MOLTBOT_MACOS:"moltbot-macos",MOLTBOT_IOS:"moltbot-ios",MOLTBOT_ANDROID:"moltbot-android",MOLTBOT_PROBE:"moltbot-probe",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},il=Wd,Si={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Wd));new Set(Object.values(Si));function ov(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),s=e.token??"",a=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),s];return t==="v2"&&a.push(e.nonce??""),a.join("|")}const rv=4008;class lv{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(){this.closed=!0,this.ws?.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){return this.ws?.readyState===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.addEventListener("open",()=>this.queueConnect()),this.ws.addEventListener("message",t=>this.handleMessage(String(t.data??""))),this.ws.addEventListener("close",t=>{const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),this.opts.onClose?.({code:t.code,reason:n}),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{}))}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(){if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=typeof crypto<"u"&&!!crypto.subtle,n=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"],s="operator";let a=null,i=!1,o=this.opts.token;if(t){a=await uo();const p=Sm({deviceId:a.deviceId,role:s})?.token;o=p??this.opts.token,i=!!(p&&this.opts.token)}const l=o||this.opts.password?{token:o,password:this.opts.password}:void 0;let c;if(t&&a){const p=Date.now(),f=this.connectNonce??void 0,m=ov({deviceId:a.deviceId,clientId:this.opts.clientName??il.CONTROL_UI,clientMode:this.opts.mode??Si.WEBCHAT,role:s,scopes:n,signedAtMs:p,token:o??null,nonce:f}),g=await Gm(a.privateKey,m);c={id:a.deviceId,publicKey:a.publicKey,signature:g,signedAt:p,nonce:f}}const u={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??il.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Si.WEBCHAT,instanceId:this.opts.instanceId},role:s,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",u).then(p=>{p?.auth?.deviceToken&&a&&wd({deviceId:a.deviceId,role:p.auth.role??s,token:p.auth.deviceToken,scopes:p.auth.scopes??[]}),this.backoffMs=800,this.opts.onHello?.(p)}).catch(()=>{i&&a&&$d({deviceId:a.deviceId,role:s}),this.ws?.close(rv,"connect failed")})}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;if(s.type==="event"){const a=n;if(a.event==="connect.challenge"){const o=a.payload,l=o&&typeof o.nonce=="string"?o.nonce:null;l&&(this.connectNonce=l,this.sendConnect());return}const i=typeof a.seq=="number"?a.seq:null;i!==null&&(this.lastSeq!==null&&i>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:i}),this.lastSeq=i);try{this.opts.onEvent?.(a)}catch(o){console.error("[gateway] event handler error:",o)}return}if(s.type==="res"){const a=n,i=this.pending.get(a.id);if(!i)return;this.pending.delete(a.id),a.ok?i.resolve(a.payload):i.reject(new Error(a.error?.message??"request failed"));return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const s=ea(),a={type:"req",id:s,method:t,params:n},i=new Promise((o,l)=>{this.pending.set(s,{resolve:c=>o(c),reject:l})});return this.ws.send(JSON.stringify(a)),i}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}const qd={displayName:"label",sessionKey:"conversationId"},jd={};for(const[e,t]of Object.entries(qd))jd[t]=e;const cv={"sessions.autoTitle":["sessions.patch"],"sessions.rename":["sessions.patch"]},Dt=new Map;function dv(){try{const e=sessionStorage.getItem("godmode:healing-cache");if(e){const t=JSON.parse(e);for(const[n,s]of Object.entries(t))Dt.set(n,s)}}catch{}}function ol(){try{const e={};for(const[t,n]of Dt)e[t]=n;sessionStorage.setItem("godmode:healing-cache",JSON.stringify(e))}catch{}}dv();function uv(e,t){const n=Dt.get(e);if(!n)return{method:e,params:t};const s=n.resolvedMethod;if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(n.fieldRenames).length>0){const a={...t};for(const[i,o]of Object.entries(n.fieldRenames))i in a&&!(o in a)&&(a[o]=a[i],delete a[i]);return{method:s,params:a}}return{method:s,params:t}}function pv(e,t,n){const s=n.toLowerCase(),a=n.match(/unexpected property[:\s]*['"]?(\w+)['"]?/i);if(a){const i=a[1],o=qd[i];if(o&&t&&typeof t=="object"){const l={...t};if(i in l)return l[o]=l[i],delete l[i],console.log(`[safe-request] Self-heal: ${e} — rewrote "${i}" → "${o}"`),{method:e,params:l,renames:{[i]:o}}}}if(s.includes("unknown method")||s.includes("method not found")){const i=cv[e];if(i&&i.length>0){const o=i[0];return console.log(`[safe-request] Self-heal: ${e} not found — falling back to ${o}`),{method:o,params:t,renames:{}}}}if((s.includes("unexpected property")||s.includes("unknown field"))&&t&&typeof t=="object"){const i={...t};let o=!1;const l={};for(const[c,u]of Object.entries(jd))c in i&&(i[u]=i[c],delete i[c],l[c]=u,o=!0,console.log(`[safe-request] Self-heal: ${e} — reverse alias "${c}" → "${u}"`));if(o)return{method:e,params:i,renames:l}}return null}async function zs(e,t,n,s){const a=s?.timeout??3e4;let{method:i,params:o}=s?.raw?{method:t,params:n}:uv(t,n);const l=async(c,u)=>Promise.race([e.request(c,u),new Promise((p,f)=>setTimeout(()=>f(new Error(`Request timeout (${a}ms): ${c}`)),a))]);try{return{ok:!0,data:await l(i,o),method:i,healed:i!==t}}catch(c){const u=String(c instanceof Error?c.message:c);if(s?.raw)return{ok:!1,error:u,method:t};const p=pv(i,o,u);if(p)try{const f=await l(p.method,p.params);return Dt.set(t,{resolvedMethod:p.method,fieldRenames:p.renames,ts:Date.now()}),ol(),{ok:!0,data:f,method:p.method,healed:!0}}catch(f){return{ok:!1,error:String(f instanceof Error?f.message:f),method:p.method,healed:!0}}if(s?.fallbacks)for(const f of s.fallbacks)try{const m=await l(f,o);return Dt.set(t,{resolvedMethod:f,fieldRenames:{},ts:Date.now()}),ol(),{ok:!0,data:m,method:f,healed:!0}}catch{continue}return{ok:!1,error:u,method:i}}}function Hd(){Dt.clear();try{sessionStorage.removeItem("godmode:healing-cache")}catch{}}function hv(){const e={};for(const[t,n]of Dt)e[t]=n;return e}const fv=Object.freeze(Object.defineProperty({__proto__:null,clearHealingCache:Hd,getHealingEntries:hv,safeRequest:zs},Symbol.toStringTag,{value:"Module"}));let be=null;function Vd(e,t){Hd();const n=String(e.version??e.serverVersion??e.gatewayVersion??"unknown"),s=typeof e.protocol=="number"?e.protocol:void 0;be={hostVersion:n,protocolVersion:s,methods:{},initializedAt:Date.now(),probing:!0};try{const a=sessionStorage.getItem("godmode:host-compat");if(a){const i=JSON.parse(a);if(i.hostVersion===n&&i.methods)return be.methods=i.methods,be.probing=!1,be}}catch{}return gv(t).catch(()=>{}),be}async function gv(e){if(!be)return;const t=[{method:"sessions.list",params:{limit:1}},{method:"sessions.patch",params:{key:"__compat_probe__"}},{method:"sessions.autoTitle",params:{sessionKey:"__compat_probe__"}},{method:"config.get",params:{}}];for(const n of t){const s={available:!1,testedAt:Date.now()};try{await e.request(n.method,n.params),s.available=!0}catch(a){const i=String(a instanceof Error?a.message:a),o=i.toLowerCase(),l=o.includes("unknown method")||o.includes("not found")&&o.includes("method");s.available=!l,l&&(s.error="method not available");const c=i.match(/(?:expected|valid|accepted) (?:fields?|properties?)[:\s]*\[([^\]]+)\]/i);c&&(s.fields=c[1].split(",").map(u=>u.trim().replace(/['"]/g,"")))}be.methods[n.method]=s}be.probing=!1;try{sessionStorage.setItem("godmode:host-compat",JSON.stringify(be))}catch{}}function Gd(e){if(!be)return;const t=be.methods[e];if(t)return t.available}function mv(){return be?.hostVersion??"unknown"}function vv(){return be}function yv(){return be?.probing??!1}async function Qd(e,t,n){const s=await zs(e,"sessions.patch",{key:t,label:n});return s.ok?{ok:!0}:(await zs(e,"sessions.patch",{key:t,displayName:n},{raw:!0})).ok?{ok:!0}:{ok:!1,error:s.error}}async function bv(e,t,n){if(Gd("sessions.autoTitle")!==!1){const l=await zs(e,"sessions.autoTitle",{sessionKey:t});if(l.ok)return{ok:!0,title:l.data?.title}}const a=n.find(l=>l.role==="user");if(!a)return{ok:!1,error:"No user message to derive title from"};const i=wv(a.content),o=await Qd(e,t,i);return o.ok?{ok:!0,title:i}:{ok:!1,error:o.error}}function wv(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/https?:\/\/\S+/g,"").replace(/[#*_~>]/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim();if(t=t.split(`
715
- `).filter(s=>s.trim().length>0)[0]??"New conversation",t.length>60){const s=t.slice(0,57),a=s.lastIndexOf(" ");t=(a>30?s.slice(0,a):s)+"..."}return t}function $v(e){return String(e.label??e.displayName??e.key??"Untitled")}const kv=Object.freeze(Object.defineProperty({__proto__:null,getHostCompat:vv,getHostVersion:mv,hasMethod:Gd,hostAutoTitle:bv,hostPatchSession:Qd,initHostCompat:Vd,isProbing:yv,readSessionName:$v},Symbol.toStringTag,{value:"Module"})),Ai=new Map;let rl=null,za=!1;function Sv(e,t,n){return Ai.get(`${e}:${t}:${n}`)??null}async function Yd(e){if(!e.client||!e.chatMessages?.length)return;const t=e.sessionKey,n=[];for(let s=0;s<e.chatMessages.length;s++){const a=e.chatMessages[s],i=gi(a);for(let o=0;o<i.length;o++)if(i[o].url&&!i[o].omitted){const l=/^data:([^;]+);base64,(.+)$/.exec(i[o].url);l&&n.push({data:l[2],mimeType:l[1],messageIndex:s,imageIndex:o,role:a.role||"unknown",timestamp:typeof a.timestamp=="number"?a.timestamp:void 0})}}if(n.length>0)try{const s=await e.client.request("images.cache",{images:n.map(a=>({data:a.data,mimeType:a.mimeType})),sessionKey:t});if(s?.cached){const a=n.map((i,o)=>({messageIndex:i.messageIndex,imageIndex:i.imageIndex,hash:s.cached[o]?.hash,mimeType:i.mimeType,bytes:s.cached[o]?.bytes??0,role:i.role,timestamp:i.timestamp})).filter(i=>!!i.hash);a.length>0&&await e.client.request("images.updateIndex",{sessionKey:t,images:a})}}catch{}if(!za){za=!0;try{const s=fd();s&&await s.catch(()=>{});const a=async()=>{const o=await e.client.request("images.resolve",{sessionKey:t});if(o?.images&&Object.keys(o.images).length>0){rl!==t&&Ai.clear();for(const[l,c]of Object.entries(o.images))Ai.set(`${t}:${l}`,c);return rl=t,e.chatMessages=[...e.chatMessages],!0}return!1};!await a()&&e.chatMessages?.some(o=>gi(o).some(c=>c.omitted||!c.url))&&(await new Promise(o=>setTimeout(o,500)),await a())}catch{}finally{za=!1}}}function Jd(e){Yd(e)}const Pn=[];function Av(){return[...Pn]}let rt=null;const _v=10,Tv=1e3,tn=new Map;function Ka(e,t){const n=(e??"").trim(),s=t.mainSessionKey?.trim();if(!s)return n;if(!n)return s;const a=t.mainKey?.trim()||"main",i=t.defaultAgentId?.trim();return n==="main"||n===a||i&&(n===`agent:${i}:main`||n===`agent:${i}:${a}`)?s:n}function xv(e,t){if(!t?.mainSessionKey)return;const n="main",s=p=>(p??"").trim()===n||(p??"").trim()==="",a=s(e.sessionKey)?e.sessionKey:Ka(e.sessionKey,t),i=s(e.settings.sessionKey)?e.settings.sessionKey:Ka(e.settings.sessionKey,t),o=s(e.settings.lastActiveSessionKey)?e.settings.lastActiveSessionKey:Ka(e.settings.lastActiveSessionKey,t),l=a||i||e.sessionKey,c={...e.settings,sessionKey:i||l,lastActiveSessionKey:o||l},u=c.sessionKey!==e.settings.sessionKey||c.lastActiveSessionKey!==e.settings.lastActiveSessionKey;l!==e.sessionKey&&(e.sessionKey=l),u&&Je(e,c)}function Cv(e){rt&&(clearTimeout(rt),rt=null);const t=(e.reconnectAttempt??0)+1;if(t>_v){e.lastError="Connection lost. Please refresh the page.",e.reconnecting=!1;return}e.reconnectAttempt=t,e.reconnecting=!0;const n=Math.min(Tv*Math.pow(2,t-1),3e4);rt=setTimeout(()=>{rt=null,e.connected||po(e)},n)}async function Ev(e){if(e.client)try{const t=await e.client.request("projects.list",{}),n=e;n.workspaceNeedsSetup=!t?.projects||t.projects.length===0}catch{}}async function Lv(e){if(!e.client)return;if(e.workspaceNeedsSetup===!1){try{const n=await e.client.request("onboarding.status",{});n&&!n.completedAt&&await e.client.request("onboarding.complete",{summary:null})}catch{}return}try{const n=await e.client.request("onboarding.status",{}),s=e;if(n&&!n.completedAt){s.onboardingActive=!0,s.onboardingPhase=n.phase??0,s.onboardingData=n;const a=e;a.showSetupTab=!0,n.identity?.name&&(a.setupQuickDone=!0)}else{s.onboardingActive=!1,s.onboardingData=n??null;const a=e;a.showSetupTab=!1}}catch{}}function Rv(e,t){if(!e.sessionsResult?.sessions)return;const n=e.sessionsResult.sessions.map(s=>s.key===t?{...s,updatedAt:Date.now()}:s);e.sessionsResult={...e.sessionsResult,sessions:n}}const ll=new Set;function Pv(e){const t=e.filter(n=>n.role==="user");if(t.length===0)return null;for(const n of t){let s="";typeof n.content=="string"?s=n.content:Array.isArray(n.content)&&(s=n.content.find(l=>l.type==="text")?.text??"");const a=Iv(s);if(!a.trim())continue;const i=Mv(a);if(i)return i}return null}const cl=["internal system context injected by godmode","treat it as invisible background instructions only","persistence protocol (non-negotiable)","[godmode — consciousness context]","[godmode — working context]","[enforcement: self-service gate]","[enforcement: output shield]","[godmode queue]","you are resourceful and thorough. your job is to get the job done","## persistence protocol","## core behaviors","## your role as prosper","your role as prosper (godmode ea)","elite executive assistant powering a personal ai operating system","be diligent first time.","exhaust reasonable options.","assume capability exists."];function Iv(e){let t=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"").replace(/<system>[\s\S]*?<\/system>/g,"").replace(/<context>[\s\S]*?<\/context>/g,"").replace(/<ide_selection>[\s\S]*?<\/ide_selection>/g,"").replace(/<ide_opened_file>[\s\S]*?<\/ide_opened_file>/g,"").replace(/<[a-z][a-z_-]*>[\s\S]*?<\/[a-z][a-z_-]*>/g,"");const n=t.toLowerCase();let s=0;for(const a of cl)n.includes(a.toLowerCase())&&s++;if(s>=2)t="";else if(s===1)for(const a of cl){const i=n.indexOf(a.toLowerCase());if(i!==-1){t=t.substring(0,i).trim();break}}return t.trim()}function Mv(e){const n=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/https?:\/\/\S+/g,"").replace(/!\[.*?\]\(.*?\)/g,"").split(new RegExp("(?<=[.!?])\\s+|\\n+")).map(u=>u.replace(/^#+\s*/,"").replace(/[*_`~[\]]/g,"").trim()).filter(u=>u.length>5);if(n.length===0)return null;const s=/^(hi|hey|hello|thanks|thank\s+you|thx|ok|okay|sure|alright|great)\b/i,a=/^(fix|add|create|update|change|build|implement|remove|delete|refactor|make|set\s+up|configure|enable|disable|show|hide|move|rename|convert|replace|write|edit|debug|test|deploy|install|run|check|review|optimize|improve|clean|reset|open|close|connect|disconnect|sync|upload|download|merge|split|sort|filter|search|format|generate|export|import|migrate|monitor|schedule|cancel|approve|reject|assign|unassign)\b/i,i=/\b(function|component|file|page|button|API|error|bug|feature|config|style|layout|route|test|database|server|client|UI|CSS|HTML|TypeScript|view|sidebar|modal|tab|form|input|output|session|message|chat|title|drive|upload|deploy|build)\b/i;function o(u){let p=0;return u.includes("?")&&(p+=3),a.test(u)&&(p+=5),i.test(u)&&(p+=2),/^(I |you |we |my |it'?s |this is |that |there )/i.test(u)&&(p-=1),s.test(u)&&(p-=5),u.length<15&&(p-=1),u.length>=15&&u.length<=60&&(p+=1),p}const l=n.map(u=>({text:u,score:o(u)}));l.sort((u,p)=>p.score-u.score);let c=l[0].text;return c=c.replace(/^(can you|could you|would you|will you|I need you to|I want you to|I'd like you to|help me to?|go ahead and)\s+/i,"").replace(/^(please|pls)\s+/i,"").trim(),c.length>0&&(c=c[0].toUpperCase()+c.slice(1)),c=c.replace(/[.!]+$/,"").trim(),c.length>50&&(c=c.slice(0,47).replace(/\s+\S*$/,"").trim()+"..."),c||null}async function Dv(e,t){const n=["telegram","slack","discord","whatsapp"],s=t.toLowerCase();if(n.some(i=>s.includes(i))||e.privateSessions?.has(t)||ll.has(t))return;const a=e.sessionsResult?.sessions?.find(i=>i.key===t);if(!(a?.label?.trim()||a?.displayName?.trim())){if(ll.add(t),!e.client||!e.connected){console.warn("[auto-title] skipped: not connected");return}try{const o=Pv(e.chatMessages??[]);if(!o){console.warn("[auto-title] no user message found to derive title");return}const{hostPatchSession:l}=await E(async()=>{const{hostPatchSession:u}=await Promise.resolve().then(()=>kv);return{hostPatchSession:u}},void 0,import.meta.url),c=await l(e.client,t,o);if(!c.ok){console.error("[auto-title] patch failed:",c.error);return}Te.set(t,o),e.sessionsResult?.sessions&&(e.sessionsResult={...e.sessionsResult,sessions:e.sessionsResult.sessions.map(u=>u.key===t?{...u,label:o,displayName:o}:u)}),e.requestUpdate?.()}catch(i){console.error("[auto-title] RPC call failed:",i)}}}function po(e){e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;const t=e;"sessionsLoading"in t&&(t.sessionsLoading=!1),"agentsLoading"in t&&(t.agentsLoading=!1),"nodesLoading"in t&&(t.nodesLoading=!1),"devicesLoading"in t&&(t.devicesLoading=!1),"channelsLoading"in t&&(t.channelsLoading=!1),"configLoading"in t&&(t.configLoading=!1),"presenceLoading"in t&&(t.presenceLoading=!1),"cronLoading"in t&&(t.cronLoading=!1),"skillsLoading"in t&&(t.skillsLoading=!1),"debugLoading"in t&&(t.debugLoading=!1),"logsLoading"in t&&(t.logsLoading=!1),rt&&(clearTimeout(rt),rt=null),e.client?.stop(),e.client=new lv({url:e.settings.gatewayUrl,token:e.settings.token.trim()?e.settings.token:void 0,password:e.password.trim()?e.password:void 0,clientName:"openclaw-control-ui",mode:"webchat",onHello:n=>{const s=e.reconnecting;if(e.connected=!0,e.lastError=null,e.hello=n,e.reconnecting=!1,e.reconnectAttempt=0,s){const a=e;typeof a.showToast=="function"&&a.showToast("Gateway reconnected","success",4e3),e.lastError="✓ Reconnected",setTimeout(()=>{e.lastError==="✓ Reconnected"&&(e.lastError=null)},3e3),e.chatRunId=null;const i=e;"chatStream"in i&&(i.chatStream=null),"chatStreamStartedAt"in i&&(i.chatStreamStartedAt=null);const o=e;if(o.todaySelectedDate){const l=new Date,c=`${l.getFullYear()}-${String(l.getMonth()+1).padStart(2,"0")}-${String(l.getDate()).padStart(2,"0")}`;o.todaySelectedDate!==c&&(o.todaySelectedDate=c)}e.workingSessions.clear(),e.requestUpdate?.();for(const l of tn.values())clearTimeout(l);tn.clear()}Vd(n,e.client),zv(e,n),hd(e),hm(e),na(e,{quiet:!0}),pt(e,{quiet:!0}),X(e),ts(e),Ev(e).then(()=>Lv(e)),Fv(e),Bv(e),av(e),Uv(e)},onClose:({code:n,reason:s})=>{e.connected=!1,iv(e);const a=e;"chatSending"in a&&(a.chatSending=!1),"chatSendingSessionKey"in a&&(a.chatSendingSessionKey=null),"chatRunId"in a&&(a.chatRunId=null),"chatStream"in a&&(a.chatStream=null),"chatStreamStartedAt"in a&&(a.chatStreamStartedAt=null);const i=e;"sessionsLoading"in i&&(i.sessionsLoading=!1),"agentsLoading"in i&&(i.agentsLoading=!1),"nodesLoading"in i&&(i.nodesLoading=!1),"devicesLoading"in i&&(i.devicesLoading=!1),"channelsLoading"in i&&(i.channelsLoading=!1),"presenceLoading"in i&&(i.presenceLoading=!1),n!==1012&&(e.lastError=`disconnected (${n}): ${s||"no reason"}`),Cv(e)},onEvent:n=>Ov(e,n),onGap:({expected:n,received:s})=>{e.lastError=`event gap detected (expected seq ${n}, got ${s}); refresh recommended`}}),e.client.start()}function Ov(e,t){try{Nv(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function Nv(e,t){if(Pn.unshift({ts:Date.now(),event:t.event,payload:t.payload}),Pn.length>250&&(Pn.length=250),e.tab==="debug"&&(e.eventLog=[...Pn]),t.event==="agent"){if(e.onboarding)return;const n=t.payload,s=n?.sessionKey;s&&n?.stream==="tool"&&n.data?.phase==="start"&&(e.workingSessions.has(s)||(e.workingSessions.add(s),e.requestUpdate?.())),Ih(e,n);return}if(t.event==="chat"){const n=t.payload;if(n?.sessionKey){if(Ao(e,n.sessionKey),n.state==="delta"){const a=tn.get(n.sessionKey);a&&(clearTimeout(a),tn.delete(n.sessionKey)),e.workingSessions.has(n.sessionKey)||(e.workingSessions.add(n.sessionKey),e.requestUpdate?.())}else if((n.state==="final"||n.state==="error"||n.state==="aborted")&&e.workingSessions.has(n.sessionKey)){const a=tn.get(n.sessionKey);a&&(clearTimeout(a),tn.delete(n.sessionKey)),e.workingSessions.delete(n.sessionKey),e.requestUpdate?.()}}n.state==="final"&&Rv(e,n.sessionKey);const s=vd(e,n);if(n&&n.sessionKey===ee){const a=e,i=e.tab==="chat"&&e.sessionKey===ee;if(n.state==="delta"){const o=Ct(n.message);if(!i){if(typeof o=="string"){const l=a.allyStream??"";(!l||o.length>=l.length)&&(a.allyStream=o)}a.allyWorking=!0,a.requestUpdate?.()}}else if(n.state==="final"){if(!i){const o=a.allyStream??Ct(n.message)??"";o&&(a.allyMessages=[...a.allyMessages??[],{role:"assistant",content:o,timestamp:Date.now()}]),a.allyStream=null,a.allyWorking=!1,!a.allyPanelOpen&&e.tab!=="chat"&&(a.allyUnread=(a.allyUnread??0)+1),a.requestUpdate?.(),a.allyPanelOpen&&e._scrollAllyToBottom()}}else if(n.state==="error"||n.state==="aborted"){if(!i){const o=Ct(n.message),l=n.state==="aborted"?"Response was stopped.":o||"Something went wrong — try again.";a.allyMessages=[...a.allyMessages??[],{role:"assistant",content:`*${l}*`,timestamp:Date.now()}]}a.allyStream=null,a.allyWorking=!1,a.requestUpdate?.()}}if(n.state==="final"&&(async()=>{try{await X(e,{activeMinutes:0})}catch(a){console.error("[auto-title] loadSessions failed, proceeding anyway:",a)}Dv(e,n.sessionKey)})(),(s==="final"||s==="error"||s==="aborted")&&(Bi(e),Tu(e),s==="final"&&e.compactionStatus?.active&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus.startedAt??null,completedAt:Date.now()}),(s==="error"||s==="aborted")&&e.compactionStatus?.active&&(e.compactionStatus=null),e.refreshSessionsAfterChat=!1),s==="final"){const a=!!e.compactionStatus?.completedAt;gd(e,{allowShrink:a}).then(()=>{Yd(e)});const i=e;i.tab==="dashboards"&&i.activeDashboardManifest?.sessionId&&i.activeDashboardManifest.sessionId===n.sessionKey&&E(async()=>{const{loadDashboard:o}=await import("./dashboards-BWn_hwxU.js");return{loadDashboard:o}},[],import.meta.url).then(({loadDashboard:o})=>{o(e,i.activeDashboardManifest.id)})}return}if(t.event==="presence"){const n=t.payload;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"&&e.tab==="cron"&&ca(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&pt(e,{quiet:!0}),t.event==="exec.approval.requested"){const n=Zm(t.payload);if(n){e.execApprovalQueue=tv(e.execApprovalQueue,n),e.execApprovalError=null;const s=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=sl(e.execApprovalQueue,n.id)},s)}return}if(t.event==="exec.process.completed"){const n=t.payload;if(n?.sessionId){const s=n.exitSignal?`signal ${n.exitSignal}`:`exit ${n.exitCode??0}`,a=n.status==="completed"?"✓":"✗",i=n.status==="completed"?"success":"warning",o=n.sessionId.slice(0,8),l=e;typeof l.showToast=="function"&&l.showToast(`${a} Process ${o} ${n.status} (${s})`,i,5e3)}return}if(t.event==="exec.approval.resolved"){const n=ev(t.payload);n&&(e.execApprovalQueue=sl(e.execApprovalQueue,n.id))}if(t.event==="daily-brief:update"){const n=t.payload;if(n){const s=e;s.dailyBrief=n}return}if(t.event==="ui.slot.update"){const n=t.payload;if(n?.tabId){const s=n.mode??"replace";if(n.html)s==="append"?e.dynamicSlots={...e.dynamicSlots,[n.tabId]:(e.dynamicSlots[n.tabId]??"")+n.html}:e.dynamicSlots={...e.dynamicSlots,[n.tabId]:n.html};else{const i={...e.dynamicSlots};delete i[n.tabId],e.dynamicSlots=i}e.requestUpdate?.()}return}if(t.event==="guardrails:update"){const n=e;typeof n.handleGuardrailsLoad=="function"&&n.handleGuardrailsLoad();return}if(t.event==="godmode.options:update"){const n=t.payload;if(n){const s=e;s.godmodeOptions=n,s.requestUpdate?.()}return}if(t.event==="proactiveIntel:insight"){const n=e;typeof n.handleIntelLoad=="function"&&n.handleIntelLoad();const s=t.payload;s?.newInsights&&typeof n.showToast=="function"&&n.showToast(`${s.newInsights} new intelligence insight${s.newInsights>1?"s":""} available`,"info",6e3);return}if(t.event==="proactiveIntel:update"){const n=e,s=n.secondBrainSubtab;typeof n.handleIntelLoad=="function"&&e.tab==="second-brain"&&s==="intel"&&n.handleIntelLoad();return}if(t.event==="onboarding:update"){const n=t.payload;if(n){const s=e;typeof n.phase=="number"&&(s.onboardingPhase=n.phase),s.onboardingData=n,n.completedAt&&(s.onboardingActive=!1),s.requestUpdate?.()}return}if(t.event==="ally:notification"){const n=t.payload;if(n){const s=e,a={role:"assistant",content:n.summary||"Notification received.",timestamp:Date.now(),isNotification:!0,actions:n.actions??[]};s.allyMessages=[...s.allyMessages??[],a],!s.allyPanelOpen&&e.tab!=="chat"&&(s.allyUnread=(s.allyUnread??0)+1),s.requestUpdate?.()}return}}async function Fv(e){const t=e;typeof t.loadFocusPulse=="function"&&await t.loadFocusPulse()}async function Bv(e){const t=e;typeof t.handleOptionsLoad=="function"&&await t.handleOptionsLoad()}async function Uv(e){if(typeof window>"u")return;const t=new URLSearchParams(window.location.search),n=t.get("openTask");if(!n||!e.client)return;t.delete("openTask");const s=t.toString()?`${window.location.pathname}?${t.toString()}`:window.location.pathname;window.history.replaceState({},"",s);try{const a=await e.client.request("tasks.openSession",{taskId:n});if(a?.sessionKey){e.sessionKey=a.sessionKey,e.tab="chat";const{loadChatHistory:i}=await E(async()=>{const{loadChatHistory:o}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:o}},void 0,import.meta.url);await i(e,a.sessionKey)}}catch(a){console.error("[GodMode] Failed to open task session:",a)}}function zv(e,t){const n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health),n?.sessionDefaults&&xv(e,n.sessionDefaults)}async function sa(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,s,a]=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 i=s;e.debugModels=Array.isArray(i?.models)?i?.models:[],e.debugHeartbeat=a}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}async function Kv(e){if(!(!e.client||!e.connected)){e.debugCallError=null,e.debugCallResult=null;try{const t=e.debugCallParams.trim()?JSON.parse(e.debugCallParams):{},n=await e.client.request(e.debugCallMethod.trim(),t);e.debugCallResult=JSON.stringify(n,null,2)}catch(t){e.debugCallError=String(t)}}}const Wv=2e3,qv=new Set(["trace","debug","info","warn","error","fatal"]);function jv(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 Hv(e){if(typeof e!="string")return null;const t=e.toLowerCase();return qv.has(t)?t:null}function Vv(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,s=typeof t.time=="string"?t.time:typeof n?.date=="string"?n?.date:null,a=Hv(n?.logLevelName??n?.level),i=typeof t[0]=="string"?t[0]:typeof n?.name=="string"?n?.name:null,o=jv(i);let l=null;o&&(typeof o.subsystem=="string"?l=o.subsystem:typeof o.module=="string"&&(l=o.module)),!l&&i&&i.length<120&&(l=i);let c=null;return typeof t[1]=="string"?c=t[1]:!o&&typeof t[0]=="string"?c=t[0]:typeof t.message=="string"&&(c=t.message),{raw:e,time:s,level:a,subsystem:l,message:c??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function ho(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!t?.quiet)){t?.quiet||(e.logsLoading=!0),e.logsError=null;try{const s=await e.client.request("logs.tail",{cursor:t?.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),i=(Array.isArray(s.lines)?s.lines.filter(l=>typeof l=="string"):[]).map(Vv),o=!!(t?.reset||s.reset||e.logsCursor==null);e.logsEntries=o?i:[...e.logsEntries,...i].slice(-Wv),typeof s.cursor=="number"&&(e.logsCursor=s.cursor),typeof s.file=="string"&&(e.logsFile=s.file),e.logsTruncated=!!s.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t?.quiet||(e.logsLoading=!1)}}}const Xd={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer",subagent:"Sub-Agent",swarm:"Swarm"};function Wa(e,t,n){return n?n.replace(/-/g," ").replace(/\b\w/g,s=>s.toUpperCase()):Xd[t??e]??e}function Zd(e,t){const n=(t??Date.now())-e;if(n<0)return"0s";const s=Math.floor(n/1e3);if(s<60)return`${s}s`;const a=Math.floor(s/60),i=s%60;if(a<60)return`${a}m ${i}s`;const o=Math.floor(a/60),l=a%60;return`${o}h ${l}m`}function Gv(){const e=new Date;return e.setHours(0,0,0,0),e.getTime()}function Qv(e){switch(e){case"running":case"validating":return"active";case"queued":return"queued";case"failed":return"failed";default:return"done"}}function Yv(e,t){const n=[],s=new Set;for(const a of t){a.childSessionKey&&s.add(a.childSessionKey);const i=a.swarm?.enabled===!0,o=a.status==="review";n.push({id:a.id,type:i?"swarm":"coding",task:a.description,status:Qv(a.status),model:a.model??null,startedAt:a.startedAt??a.createdAt,endedAt:a.completedAt??null,branch:a.branch,prUrl:a.prUrl,swarmStage:i?a.swarm.currentStage:void 0,swarmStages:i?a.swarm.stages:void 0,error:a.error,canCancel:a.status==="running"||a.status==="validating"||a.status==="queued",roleName:i?"Swarm":"Builder",childSessionKey:a.childSessionKey,isReview:o})}for(const a of e)s.has(a.childSessionKey)||n.push({id:a.runId,type:"subagent",task:a.task,status:a.endedAt?a.outcome?.status==="error"?"failed":"done":"active",model:a.model,startedAt:a.startedAt??a.createdAt,endedAt:a.endedAt,label:a.label,error:a.outcome?.error??void 0,roleName:a.label??"Sub-Agent",childSessionKey:a.childSessionKey});return n.sort((a,i)=>{const o={active:0,queued:1,failed:2,done:3},l=o[a.status]-o[i.status];return l!==0?l:(i.startedAt??0)-(a.startedAt??0)}),n}function Jv(e){const t=[];for(const n of e)n.status==="done"&&n.endedAt&&t.push({id:`${n.id}-done`,timestamp:n.endedAt,type:"completed",summary:n.task,prUrl:n.prUrl,agentRef:n}),n.status==="failed"&&n.endedAt&&t.push({id:`${n.id}-fail`,timestamp:n.endedAt,type:"failed",summary:`${n.task}${n.error?` — ${n.error}`:""}`,agentRef:n}),n.status==="active"&&n.startedAt&&t.push({id:`${n.id}-start`,timestamp:n.startedAt,type:"started",summary:n.task,agentRef:n}),n.status==="queued"&&n.startedAt&&t.push({id:`${n.id}-queue`,timestamp:n.startedAt,type:"queued",summary:n.task,agentRef:n});return t.sort((n,s)=>s.timestamp-n.timestamp),t.slice(0,50)}function Xv(e,t=0,n=0){const s=Gv();let a=0,i=0,o=0,l=0;for(const u of e)u.status==="active"&&a++,u.status==="done"&&u.endedAt&&u.endedAt>=s&&i++,u.status==="failed"&&u.endedAt&&u.endedAt>=s&&o++,u.type==="swarm"&&(u.status==="active"||u.status==="queued")&&l++;const c=e.filter(u=>u.isReview&&(u.type==="coding"||u.type==="swarm")).length;return{activeNow:a,completedToday:i,failed:o,swarmPipelines:l,queueDepth:t,queueReview:n+c}}async function hn(e,t){if(!e.client||!e.connected)return;const n=e;t?.quiet||(n.missionControlLoading=!0),n.missionControlError=null;try{let s=null;try{s=await e.client.request("queue.list",{limit:100})}catch{}const[a,i]=await Promise.all([e.client.request("subagents.list",{limit:200}),e.client.request("coding.list",{})]),o=Yv(a.runs??[],i.tasks??[]),l=s?.items??[],c=[];let u=0;for(const g of l)g.status==="processing"?o.push({id:g.id,type:"queue",task:g.title,status:"active",model:null,startedAt:g.startedAt??g.createdAt,endedAt:null,error:g.error,roleName:Wa(g.type,void 0,g.personaHint),queueItemType:g.type,outputPath:g.result?.outputPath,sourceTaskId:g.sourceTaskId,retryCount:g.retryCount,prUrl:g.result?.prUrl}):g.status==="review"?(u++,o.push({id:g.id,type:"queue",task:g.title,status:"done",model:null,startedAt:g.startedAt??g.createdAt,endedAt:g.completedAt??null,roleName:Wa(g.type,void 0,g.personaHint),queueItemType:g.type,outputPath:g.result?.outputPath,sourceTaskId:g.sourceTaskId,retryCount:g.retryCount,prUrl:g.result?.prUrl,isReview:!0})):g.status==="failed"?o.push({id:g.id,type:"queue",task:g.title,status:"failed",model:null,startedAt:g.startedAt??g.createdAt,endedAt:g.completedAt??null,error:g.error,roleName:Wa(g.type,void 0,g.personaHint),queueItemType:g.type,outputPath:g.result?.outputPath,sourceTaskId:g.sourceTaskId,retryCount:g.retryCount}):g.status==="pending"&&c.push(g);o.sort((g,$)=>{const d={active:0,queued:1,failed:2,done:3},v=d[g.status]-d[$.status];return v!==0?v:($.startedAt??0)-(g.startedAt??0)});const p=c.length,f=Xv(o,p,u),m=Jv(o);n.missionControlData={agents:o,stats:f,activityFeed:m,lastRefreshedAt:Date.now(),queueItems:c}}catch(s){console.error("[MissionControl] load error:",s),n.missionControlError=s instanceof Error?s.message:"Failed to load agent data"}finally{n.missionControlLoading=!1}}async function Zv(e,t){if(!(!e.client||!e.connected))try{await e.client.request("coding.cancel",{taskId:t}),e.showToast("Task cancelled","success",2e3),await hn(e)}catch(n){e.showToast("Failed to cancel task","error"),console.error("[MissionControl] cancel error:",n)}}async function ey(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("queue.approve",{id:t}),s=n?.item?.personaHint,a=n?.item?.title??"task";if(s){const i=s.replace(/-/g," ").replace(/\b\w/g,o=>o.toUpperCase());e.showToast(`Approved! How did ${i} do on "${a}"? Rate in Trust Tracker.`,"success",4e3)}else e.showToast("Item approved","success",2e3);await hn(e)}catch(n){e.showToast("Failed to approve item","error"),console.error("[MissionControl] approve error:",n)}}async function ty(e,t){if(!e.client||!e.connected)return!1;try{return(await e.client.request("coding.approve",{taskId:t}))?.approved?(e.showToast("Task approved","success",2e3),await hn(e),!0):!1}catch{return!1}}async function ny(e,t){if(!(!e.client||!e.connected))try{await e.client.request("queue.update",{id:t,status:"pending"}),await e.client.request("queue.process",{id:t}),e.showToast("Retrying...","success",2e3),await hn(e)}catch(n){e.showToast("Failed to retry","error"),console.error("[MissionControl] retry error:",n)}}async function sy(e,t){if(t.status==="failed")return{content:[`# Failed: ${t.task}`,"",`**Agent:** ${t.roleName}`,`**Retries:** ${t.retryCount??0}/2`,"","## Error","```",t.error??"Unknown error","```","","## What to do",t.retryCount&&t.retryCount>=2?"- This task failed after 2 automatic retries. Consider rephrasing the task or breaking it into smaller pieces.":"- Click **Retry** to attempt again with an improved prompt.","- Or remove this item and create a new one with more context."].join(`
714
+ Deletes the session entry and archives its transcript.`))){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.delete",{key:t,deleteTranscript:!0}),await X(e)}catch(s){e.sessionsError=String(s)}finally{e.sessionsLoading=!1}}}async function It(e){if(!(!e.client||!e.connected)){e.archivedSessionsLoading=!0;try{const t=await e.client.request("sessions.archived",{});t?.archived&&(e.archivedSessions=t.archived)}catch{}finally{e.archivedSessionsLoading=!1}}}async function Fd(e,t){if(!(!e.client||!e.connected))try{await e.client.request("sessions.archive",{sessionKey:t}),await It(e),await X(e)}catch(n){e.sessionsError=`Archive failed: ${String(n)}`}}async function Bd(e,t){if(!(!e.client||!e.connected))try{await e.client.request("sessions.unarchive",{sessionKey:t}),await It(e),await X(e)}catch(n){e.sessionsError=`Unarchive failed: ${String(n)}`}}async function Ud(e){if(!e.client||!e.connected)return 0;try{const n=(await e.client.request("sessions.autoArchive",{}))?.archivedCount??0;return await It(e),await X(e),n}catch(t){return e.sessionsError=`Auto-archive failed: ${String(t)}`,0}}const Cn=Object.freeze(Object.defineProperty({__proto__:null,archiveSession:Fd,autoTitleCache:Te,deleteSession:Nd,loadArchivedSessions:It,loadSessions:X,patchSession:Ts,triggerAutoArchive:Ud,unarchiveSession:Bd},Symbol.toStringTag,{value:"Module"})),tv=1800*1e3;function zd(e){return{openclawVersion:e.openclaw.version,openclawLatest:e.openclaw.latest,openclawUpdateAvailable:e.openclaw.updateAvailable,openclawInstallKind:e.openclaw.installKind,openclawChannel:e.openclaw.channel,pluginVersion:e.plugin.version,pluginLatest:e.plugin.latest,pluginUpdateAvailable:e.plugin.updateAvailable,fetchOk:e.fetchOk}}function Kd(e){const t=typeof e.behind=="number"?e.behind:null;return{openclawVersion:String(e.version??"unknown"),openclawLatest:null,openclawUpdateAvailable:(t??0)>0,openclawInstallKind:"unknown",openclawChannel:null,pluginVersion:"unknown",pluginLatest:null,pluginUpdateAvailable:!1,fetchOk:e.fetchOk}}async function nv(e){if(!(!e.client||!e.connected)){e.updateLoading=!0,e.updateError=null;try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=zd(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});t.error&&(e.updateError=String(t.error)),e.updateStatus=Kd(t),e.updateLastChecked=Date.now()}catch(t){e.updateError=String(t)}}finally{e.updateLoading=!1}}}async function al(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=zd(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});e.updateStatus=Kd(t),e.updateLastChecked=Date.now()}catch{}}}function sv(e){e.updatePollInterval==null&&(al(e),e.updatePollInterval=window.setInterval(()=>{al(e)},tv))}function av(e){const t=e;t.updatePollInterval!=null&&(clearInterval(t.updatePollInterval),t.updatePollInterval=null)}const Wd={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",GODMODE_WEBCHAT:"godmode-webchat",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",IOS_APP:"openclaw-ios",ANDROID_APP:"openclaw-android",MOLTBOT_MACOS:"moltbot-macos",MOLTBOT_IOS:"moltbot-ios",MOLTBOT_ANDROID:"moltbot-android",MOLTBOT_PROBE:"moltbot-probe",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},il=Wd,Si={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Wd));new Set(Object.values(Si));function iv(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),s=e.token??"",a=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),s];return t==="v2"&&a.push(e.nonce??""),a.join("|")}const ov=4008;class rv{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(){this.closed=!0,this.ws?.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){return this.ws?.readyState===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.addEventListener("open",()=>this.queueConnect()),this.ws.addEventListener("message",t=>this.handleMessage(String(t.data??""))),this.ws.addEventListener("close",t=>{const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),this.opts.onClose?.({code:t.code,reason:n}),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{}))}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(){if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=typeof crypto<"u"&&!!crypto.subtle,n=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"],s="operator";let a=null,i=!1,o=this.opts.token;if(t){a=await uo();const p=km({deviceId:a.deviceId,role:s})?.token;o=p??this.opts.token,i=!!(p&&this.opts.token)}const l=o||this.opts.password?{token:o,password:this.opts.password}:void 0;let c;if(t&&a){const p=Date.now(),f=this.connectNonce??void 0,m=iv({deviceId:a.deviceId,clientId:this.opts.clientName??il.CONTROL_UI,clientMode:this.opts.mode??Si.WEBCHAT,role:s,scopes:n,signedAtMs:p,token:o??null,nonce:f}),g=await Vm(a.privateKey,m);c={id:a.deviceId,publicKey:a.publicKey,signature:g,signedAt:p,nonce:f}}const u={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??il.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Si.WEBCHAT,instanceId:this.opts.instanceId},role:s,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",u).then(p=>{p?.auth?.deviceToken&&a&&wd({deviceId:a.deviceId,role:p.auth.role??s,token:p.auth.deviceToken,scopes:p.auth.scopes??[]}),this.backoffMs=800,this.opts.onHello?.(p)}).catch(()=>{i&&a&&$d({deviceId:a.deviceId,role:s}),this.ws?.close(ov,"connect failed")})}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;if(s.type==="event"){const a=n;if(a.event==="connect.challenge"){const o=a.payload,l=o&&typeof o.nonce=="string"?o.nonce:null;l&&(this.connectNonce=l,this.sendConnect());return}const i=typeof a.seq=="number"?a.seq:null;i!==null&&(this.lastSeq!==null&&i>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:i}),this.lastSeq=i);try{this.opts.onEvent?.(a)}catch(o){console.error("[gateway] event handler error:",o)}return}if(s.type==="res"){const a=n,i=this.pending.get(a.id);if(!i)return;this.pending.delete(a.id),a.ok?i.resolve(a.payload):i.reject(new Error(a.error?.message??"request failed"));return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const s=ea(),a={type:"req",id:s,method:t,params:n},i=new Promise((o,l)=>{this.pending.set(s,{resolve:c=>o(c),reject:l})});return this.ws.send(JSON.stringify(a)),i}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}const qd={displayName:"label",sessionKey:"conversationId"},jd={};for(const[e,t]of Object.entries(qd))jd[t]=e;const lv={"sessions.autoTitle":["sessions.patch"],"sessions.rename":["sessions.patch"]},Mt=new Map;function cv(){try{const e=sessionStorage.getItem("godmode:healing-cache");if(e){const t=JSON.parse(e);for(const[n,s]of Object.entries(t))Mt.set(n,s)}}catch{}}function ol(){try{const e={};for(const[t,n]of Mt)e[t]=n;sessionStorage.setItem("godmode:healing-cache",JSON.stringify(e))}catch{}}cv();function dv(e,t){const n=Mt.get(e);if(!n)return{method:e,params:t};const s=n.resolvedMethod;if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(n.fieldRenames).length>0){const a={...t};for(const[i,o]of Object.entries(n.fieldRenames))i in a&&!(o in a)&&(a[o]=a[i],delete a[i]);return{method:s,params:a}}return{method:s,params:t}}function uv(e,t,n){const s=n.toLowerCase(),a=n.match(/unexpected property[:\s]*['"]?(\w+)['"]?/i);if(a){const i=a[1],o=qd[i];if(o&&t&&typeof t=="object"){const l={...t};if(i in l)return l[o]=l[i],delete l[i],console.log(`[safe-request] Self-heal: ${e} — rewrote "${i}" → "${o}"`),{method:e,params:l,renames:{[i]:o}}}}if(s.includes("unknown method")||s.includes("method not found")){const i=lv[e];if(i&&i.length>0){const o=i[0];return console.log(`[safe-request] Self-heal: ${e} not found — falling back to ${o}`),{method:o,params:t,renames:{}}}}if((s.includes("unexpected property")||s.includes("unknown field"))&&t&&typeof t=="object"){const i={...t};let o=!1;const l={};for(const[c,u]of Object.entries(jd))c in i&&(i[u]=i[c],delete i[c],l[c]=u,o=!0,console.log(`[safe-request] Self-heal: ${e} — reverse alias "${c}" → "${u}"`));if(o)return{method:e,params:i,renames:l}}return null}async function zs(e,t,n,s){const a=s?.timeout??3e4;let{method:i,params:o}=s?.raw?{method:t,params:n}:dv(t,n);const l=async(c,u)=>Promise.race([e.request(c,u),new Promise((p,f)=>setTimeout(()=>f(new Error(`Request timeout (${a}ms): ${c}`)),a))]);try{return{ok:!0,data:await l(i,o),method:i,healed:i!==t}}catch(c){const u=String(c instanceof Error?c.message:c);if(s?.raw)return{ok:!1,error:u,method:t};const p=uv(i,o,u);if(p)try{const f=await l(p.method,p.params);return Mt.set(t,{resolvedMethod:p.method,fieldRenames:p.renames,ts:Date.now()}),ol(),{ok:!0,data:f,method:p.method,healed:!0}}catch(f){return{ok:!1,error:String(f instanceof Error?f.message:f),method:p.method,healed:!0}}if(s?.fallbacks)for(const f of s.fallbacks)try{const m=await l(f,o);return Mt.set(t,{resolvedMethod:f,fieldRenames:{},ts:Date.now()}),ol(),{ok:!0,data:m,method:f,healed:!0}}catch{continue}return{ok:!1,error:u,method:i}}}function Hd(){Mt.clear();try{sessionStorage.removeItem("godmode:healing-cache")}catch{}}function pv(){const e={};for(const[t,n]of Mt)e[t]=n;return e}const hv=Object.freeze(Object.defineProperty({__proto__:null,clearHealingCache:Hd,getHealingEntries:pv,safeRequest:zs},Symbol.toStringTag,{value:"Module"}));let be=null;function Vd(e,t){Hd();const n=String(e.version??e.serverVersion??e.gatewayVersion??"unknown"),s=typeof e.protocol=="number"?e.protocol:void 0;be={hostVersion:n,protocolVersion:s,methods:{},initializedAt:Date.now(),probing:!0};try{const a=sessionStorage.getItem("godmode:host-compat");if(a){const i=JSON.parse(a);if(i.hostVersion===n&&i.methods)return be.methods=i.methods,be.probing=!1,be}}catch{}return fv(t).catch(()=>{}),be}async function fv(e){if(!be)return;const t=[{method:"sessions.list",params:{limit:1}},{method:"sessions.patch",params:{key:"__compat_probe__"}},{method:"sessions.autoTitle",params:{sessionKey:"__compat_probe__"}},{method:"config.get",params:{}}];for(const n of t){const s={available:!1,testedAt:Date.now()};try{await e.request(n.method,n.params),s.available=!0}catch(a){const i=String(a instanceof Error?a.message:a),o=i.toLowerCase(),l=o.includes("unknown method")||o.includes("not found")&&o.includes("method");s.available=!l,l&&(s.error="method not available");const c=i.match(/(?:expected|valid|accepted) (?:fields?|properties?)[:\s]*\[([^\]]+)\]/i);c&&(s.fields=c[1].split(",").map(u=>u.trim().replace(/['"]/g,"")))}be.methods[n.method]=s}be.probing=!1;try{sessionStorage.setItem("godmode:host-compat",JSON.stringify(be))}catch{}}function Gd(e){if(!be)return;const t=be.methods[e];if(t)return t.available}function gv(){return be?.hostVersion??"unknown"}function mv(){return be}function vv(){return be?.probing??!1}async function Qd(e,t,n){const s=await zs(e,"sessions.patch",{key:t,label:n});return s.ok?{ok:!0}:(await zs(e,"sessions.patch",{key:t,displayName:n},{raw:!0})).ok?{ok:!0}:{ok:!1,error:s.error}}async function yv(e,t,n){if(Gd("sessions.autoTitle")!==!1){const l=await zs(e,"sessions.autoTitle",{sessionKey:t});if(l.ok)return{ok:!0,title:l.data?.title}}const a=n.find(l=>l.role==="user");if(!a)return{ok:!1,error:"No user message to derive title from"};const i=bv(a.content),o=await Qd(e,t,i);return o.ok?{ok:!0,title:i}:{ok:!1,error:o.error}}function bv(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/https?:\/\/\S+/g,"").replace(/[#*_~>]/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim();if(t=t.split(`
715
+ `).filter(s=>s.trim().length>0)[0]??"New conversation",t.length>60){const s=t.slice(0,57),a=s.lastIndexOf(" ");t=(a>30?s.slice(0,a):s)+"..."}return t}function wv(e){return String(e.label??e.displayName??e.key??"Untitled")}const $v=Object.freeze(Object.defineProperty({__proto__:null,getHostCompat:mv,getHostVersion:gv,hasMethod:Gd,hostAutoTitle:yv,hostPatchSession:Qd,initHostCompat:Vd,isProbing:vv,readSessionName:wv},Symbol.toStringTag,{value:"Module"})),Ai=new Map;let rl=null,za=!1;function kv(e,t,n){return Ai.get(`${e}:${t}:${n}`)??null}async function Yd(e){if(!e.client||!e.chatMessages?.length)return;const t=e.sessionKey,n=[];for(let s=0;s<e.chatMessages.length;s++){const a=e.chatMessages[s],i=gi(a);for(let o=0;o<i.length;o++)if(i[o].url&&!i[o].omitted){const l=/^data:([^;]+);base64,(.+)$/.exec(i[o].url);l&&n.push({data:l[2],mimeType:l[1],messageIndex:s,imageIndex:o,role:a.role||"unknown",timestamp:typeof a.timestamp=="number"?a.timestamp:void 0})}}if(n.length>0)try{const s=await e.client.request("images.cache",{images:n.map(a=>({data:a.data,mimeType:a.mimeType})),sessionKey:t});if(s?.cached){const a=n.map((i,o)=>({messageIndex:i.messageIndex,imageIndex:i.imageIndex,hash:s.cached[o]?.hash,mimeType:i.mimeType,bytes:s.cached[o]?.bytes??0,role:i.role,timestamp:i.timestamp})).filter(i=>!!i.hash);a.length>0&&await e.client.request("images.updateIndex",{sessionKey:t,images:a})}}catch{}if(!za){za=!0;try{const s=fd();s&&await s.catch(()=>{});const a=async()=>{const o=await e.client.request("images.resolve",{sessionKey:t});if(o?.images&&Object.keys(o.images).length>0){rl!==t&&Ai.clear();for(const[l,c]of Object.entries(o.images))Ai.set(`${t}:${l}`,c);return rl=t,e.chatMessages=[...e.chatMessages],!0}return!1};!await a()&&e.chatMessages?.some(o=>gi(o).some(c=>c.omitted||!c.url))&&(await new Promise(o=>setTimeout(o,500)),await a())}catch{}finally{za=!1}}}function Jd(e){Yd(e)}const Pn=[];function Sv(){return[...Pn]}let rt=null;const Av=10,_v=1e3,tn=new Map;function Ka(e,t){const n=(e??"").trim(),s=t.mainSessionKey?.trim();if(!s)return n;if(!n)return s;const a=t.mainKey?.trim()||"main",i=t.defaultAgentId?.trim();return n==="main"||n===a||i&&(n===`agent:${i}:main`||n===`agent:${i}:${a}`)?s:n}function Tv(e,t){if(!t?.mainSessionKey)return;const n="main",s=p=>(p??"").trim()===n||(p??"").trim()==="",a=s(e.sessionKey)?e.sessionKey:Ka(e.sessionKey,t),i=s(e.settings.sessionKey)?e.settings.sessionKey:Ka(e.settings.sessionKey,t),o=s(e.settings.lastActiveSessionKey)?e.settings.lastActiveSessionKey:Ka(e.settings.lastActiveSessionKey,t),l=a||i||e.sessionKey,c={...e.settings,sessionKey:i||l,lastActiveSessionKey:o||l},u=c.sessionKey!==e.settings.sessionKey||c.lastActiveSessionKey!==e.settings.lastActiveSessionKey;l!==e.sessionKey&&(e.sessionKey=l),u&&Je(e,c)}function xv(e){rt&&(clearTimeout(rt),rt=null);const t=(e.reconnectAttempt??0)+1;if(t>Av){e.lastError="Connection lost. Please refresh the page.",e.reconnecting=!1;return}e.reconnectAttempt=t,e.reconnecting=!0;const n=Math.min(_v*Math.pow(2,t-1),3e4);rt=setTimeout(()=>{rt=null,e.connected||po(e)},n)}async function Cv(e){if(e.client)try{const t=await e.client.request("projects.list",{}),n=e;n.workspaceNeedsSetup=!t?.projects||t.projects.length===0}catch{}}async function Ev(e){if(!e.client)return;if(e.workspaceNeedsSetup===!1){try{const n=await e.client.request("onboarding.status",{});n&&!n.completedAt&&await e.client.request("onboarding.complete",{summary:null})}catch{}return}try{const n=await e.client.request("onboarding.status",{}),s=e;if(n&&!n.completedAt){s.onboardingActive=!0,s.onboardingPhase=n.phase??0,s.onboardingData=n;const a=e;a.showSetupTab=!0,n.identity?.name&&(a.setupQuickDone=!0)}else{s.onboardingActive=!1,s.onboardingData=n??null;const a=e;a.showSetupTab=!1}}catch{}}function Lv(e,t){if(!e.sessionsResult?.sessions)return;const n=e.sessionsResult.sessions.map(s=>s.key===t?{...s,updatedAt:Date.now()}:s);e.sessionsResult={...e.sessionsResult,sessions:n}}const ll=new Set;function Rv(e){const t=e.filter(n=>n.role==="user");if(t.length===0)return null;for(const n of t){let s="";typeof n.content=="string"?s=n.content:Array.isArray(n.content)&&(s=n.content.find(l=>l.type==="text")?.text??"");const a=Pv(s);if(!a.trim())continue;const i=Iv(a);if(i)return i}return null}const cl=["internal system context injected by godmode","treat it as invisible background instructions only","persistence protocol (non-negotiable)","[godmode — consciousness context]","[godmode — working context]","[enforcement: self-service gate]","[enforcement: output shield]","[godmode queue]","you are resourceful and thorough. your job is to get the job done","## persistence protocol","## core behaviors","## your role as prosper","your role as prosper (godmode ea)","elite executive assistant powering a personal ai operating system","be diligent first time.","exhaust reasonable options.","assume capability exists."];function Pv(e){let t=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"").replace(/<system>[\s\S]*?<\/system>/g,"").replace(/<context>[\s\S]*?<\/context>/g,"").replace(/<ide_selection>[\s\S]*?<\/ide_selection>/g,"").replace(/<ide_opened_file>[\s\S]*?<\/ide_opened_file>/g,"").replace(/<[a-z][a-z_-]*>[\s\S]*?<\/[a-z][a-z_-]*>/g,"");const n=t.toLowerCase();let s=0;for(const a of cl)n.includes(a.toLowerCase())&&s++;if(s>=2)t="";else if(s===1)for(const a of cl){const i=n.indexOf(a.toLowerCase());if(i!==-1){t=t.substring(0,i).trim();break}}return t.trim()}function Iv(e){const n=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/https?:\/\/\S+/g,"").replace(/!\[.*?\]\(.*?\)/g,"").split(new RegExp("(?<=[.!?])\\s+|\\n+")).map(u=>u.replace(/^#+\s*/,"").replace(/[*_`~[\]]/g,"").trim()).filter(u=>u.length>5);if(n.length===0)return null;const s=/^(hi|hey|hello|thanks|thank\s+you|thx|ok|okay|sure|alright|great)\b/i,a=/^(fix|add|create|update|change|build|implement|remove|delete|refactor|make|set\s+up|configure|enable|disable|show|hide|move|rename|convert|replace|write|edit|debug|test|deploy|install|run|check|review|optimize|improve|clean|reset|open|close|connect|disconnect|sync|upload|download|merge|split|sort|filter|search|format|generate|export|import|migrate|monitor|schedule|cancel|approve|reject|assign|unassign)\b/i,i=/\b(function|component|file|page|button|API|error|bug|feature|config|style|layout|route|test|database|server|client|UI|CSS|HTML|TypeScript|view|sidebar|modal|tab|form|input|output|session|message|chat|title|drive|upload|deploy|build)\b/i;function o(u){let p=0;return u.includes("?")&&(p+=3),a.test(u)&&(p+=5),i.test(u)&&(p+=2),/^(I |you |we |my |it'?s |this is |that |there )/i.test(u)&&(p-=1),s.test(u)&&(p-=5),u.length<15&&(p-=1),u.length>=15&&u.length<=60&&(p+=1),p}const l=n.map(u=>({text:u,score:o(u)}));l.sort((u,p)=>p.score-u.score);let c=l[0].text;return c=c.replace(/^(can you|could you|would you|will you|I need you to|I want you to|I'd like you to|help me to?|go ahead and)\s+/i,"").replace(/^(please|pls)\s+/i,"").trim(),c.length>0&&(c=c[0].toUpperCase()+c.slice(1)),c=c.replace(/[.!]+$/,"").trim(),c.length>50&&(c=c.slice(0,47).replace(/\s+\S*$/,"").trim()+"..."),c||null}async function Mv(e,t){const n=["telegram","slack","discord","whatsapp"],s=t.toLowerCase();if(n.some(i=>s.includes(i))||e.privateSessions?.has(t)||ll.has(t))return;const a=e.sessionsResult?.sessions?.find(i=>i.key===t);if(!(a?.label?.trim()||a?.displayName?.trim())){if(ll.add(t),!e.client||!e.connected){console.warn("[auto-title] skipped: not connected");return}try{const o=Rv(e.chatMessages??[]);if(!o){console.warn("[auto-title] no user message found to derive title");return}const{hostPatchSession:l}=await E(async()=>{const{hostPatchSession:u}=await Promise.resolve().then(()=>$v);return{hostPatchSession:u}},void 0,import.meta.url),c=await l(e.client,t,o);if(!c.ok){console.error("[auto-title] patch failed:",c.error);return}Te.set(t,o),e.sessionsResult?.sessions&&(e.sessionsResult={...e.sessionsResult,sessions:e.sessionsResult.sessions.map(u=>u.key===t?{...u,label:o,displayName:o}:u)}),e.requestUpdate?.()}catch(i){console.error("[auto-title] RPC call failed:",i)}}}function po(e){e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;const t=e;"sessionsLoading"in t&&(t.sessionsLoading=!1),"agentsLoading"in t&&(t.agentsLoading=!1),"nodesLoading"in t&&(t.nodesLoading=!1),"devicesLoading"in t&&(t.devicesLoading=!1),"channelsLoading"in t&&(t.channelsLoading=!1),"configLoading"in t&&(t.configLoading=!1),"presenceLoading"in t&&(t.presenceLoading=!1),"cronLoading"in t&&(t.cronLoading=!1),"skillsLoading"in t&&(t.skillsLoading=!1),"debugLoading"in t&&(t.debugLoading=!1),"logsLoading"in t&&(t.logsLoading=!1),rt&&(clearTimeout(rt),rt=null),e.client?.stop(),e.client=new rv({url:e.settings.gatewayUrl,token:e.settings.token.trim()?e.settings.token:void 0,password:e.password.trim()?e.password:void 0,clientName:"openclaw-control-ui",mode:"webchat",onHello:n=>{const s=e.reconnecting;if(e.connected=!0,e.lastError=null,e.hello=n,e.reconnecting=!1,e.reconnectAttempt=0,s){const a=e;typeof a.showToast=="function"&&a.showToast("Gateway reconnected","success",4e3),e.lastError="✓ Reconnected",setTimeout(()=>{e.lastError==="✓ Reconnected"&&(e.lastError=null)},3e3),e.chatRunId=null;const i=e;"chatStream"in i&&(i.chatStream=null),"chatStreamStartedAt"in i&&(i.chatStreamStartedAt=null);const o=e;if(o.todaySelectedDate){const l=new Date,c=`${l.getFullYear()}-${String(l.getMonth()+1).padStart(2,"0")}-${String(l.getDate()).padStart(2,"0")}`;o.todaySelectedDate!==c&&(o.todaySelectedDate=c)}e.workingSessions.clear(),e.requestUpdate?.();for(const l of tn.values())clearTimeout(l);tn.clear()}Vd(n,e.client),Uv(e,n),hd(e),pm(e),na(e,{quiet:!0}),pt(e,{quiet:!0}),X(e),ts(e),Cv(e).then(()=>Ev(e)),Nv(e),Fv(e),sv(e),Bv(e)},onClose:({code:n,reason:s})=>{e.connected=!1,av(e);const a=e;"chatSending"in a&&(a.chatSending=!1),"chatSendingSessionKey"in a&&(a.chatSendingSessionKey=null),"chatRunId"in a&&(a.chatRunId=null),"chatStream"in a&&(a.chatStream=null),"chatStreamStartedAt"in a&&(a.chatStreamStartedAt=null);const i=e;"sessionsLoading"in i&&(i.sessionsLoading=!1),"agentsLoading"in i&&(i.agentsLoading=!1),"nodesLoading"in i&&(i.nodesLoading=!1),"devicesLoading"in i&&(i.devicesLoading=!1),"channelsLoading"in i&&(i.channelsLoading=!1),"presenceLoading"in i&&(i.presenceLoading=!1),n!==1012&&(e.lastError=`disconnected (${n}): ${s||"no reason"}`),xv(e)},onEvent:n=>Dv(e,n),onGap:({expected:n,received:s})=>{e.lastError=`event gap detected (expected seq ${n}, got ${s}); refresh recommended`}}),e.client.start()}function Dv(e,t){try{Ov(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function Ov(e,t){if(Pn.unshift({ts:Date.now(),event:t.event,payload:t.payload}),Pn.length>250&&(Pn.length=250),e.tab==="debug"&&(e.eventLog=[...Pn]),t.event==="agent"){if(e.onboarding)return;const n=t.payload,s=n?.sessionKey;s&&n?.stream==="tool"&&n.data?.phase==="start"&&(e.workingSessions.has(s)||(e.workingSessions.add(s),e.requestUpdate?.())),Ph(e,n);return}if(t.event==="chat"){const n=t.payload;if(n?.sessionKey){if(Ao(e,n.sessionKey),n.state==="delta"){const a=tn.get(n.sessionKey);a&&(clearTimeout(a),tn.delete(n.sessionKey)),e.workingSessions.has(n.sessionKey)||(e.workingSessions.add(n.sessionKey),e.requestUpdate?.())}else if((n.state==="final"||n.state==="error"||n.state==="aborted")&&e.workingSessions.has(n.sessionKey)){const a=tn.get(n.sessionKey);a&&(clearTimeout(a),tn.delete(n.sessionKey)),e.workingSessions.delete(n.sessionKey),e.requestUpdate?.()}}n.state==="final"&&Lv(e,n.sessionKey);const s=vd(e,n);if(n&&n.sessionKey===ee){const a=e,i=e.tab==="chat"&&e.sessionKey===ee;if(n.state==="delta"){const o=xt(n.message);if(!i){if(typeof o=="string"){const l=a.allyStream??"";(!l||o.length>=l.length)&&(a.allyStream=o)}a.allyWorking=!0,a.requestUpdate?.()}}else if(n.state==="final"){if(!i){const o=a.allyStream??xt(n.message)??"";o&&(a.allyMessages=[...a.allyMessages??[],{role:"assistant",content:o,timestamp:Date.now()}]),a.allyStream=null,a.allyWorking=!1,!a.allyPanelOpen&&e.tab!=="chat"&&(a.allyUnread=(a.allyUnread??0)+1),a.requestUpdate?.(),a.allyPanelOpen&&e._scrollAllyToBottom()}}else if(n.state==="error"||n.state==="aborted"){if(!i){const o=xt(n.message),l=n.state==="aborted"?"Response was stopped.":o||"Something went wrong — try again.";a.allyMessages=[...a.allyMessages??[],{role:"assistant",content:`*${l}*`,timestamp:Date.now()}]}a.allyStream=null,a.allyWorking=!1,a.requestUpdate?.()}}if(n.state==="final"&&(async()=>{try{await X(e,{activeMinutes:0})}catch(a){console.error("[auto-title] loadSessions failed, proceeding anyway:",a)}Mv(e,n.sessionKey)})(),(s==="final"||s==="error"||s==="aborted")&&(Bi(e),_u(e),s==="final"&&e.compactionStatus?.active&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus.startedAt??null,completedAt:Date.now()}),(s==="error"||s==="aborted")&&e.compactionStatus?.active&&(e.compactionStatus=null),e.refreshSessionsAfterChat=!1),s==="final"){const a=!!e.compactionStatus?.completedAt;gd(e,{allowShrink:a}).then(()=>{Yd(e)});const i=e;i.tab==="dashboards"&&i.activeDashboardManifest?.sessionId&&i.activeDashboardManifest.sessionId===n.sessionKey&&E(async()=>{const{loadDashboard:o}=await import("./dashboards-BWn_hwxU.js");return{loadDashboard:o}},[],import.meta.url).then(({loadDashboard:o})=>{o(e,i.activeDashboardManifest.id)})}return}if(t.event==="presence"){const n=t.payload;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"&&e.tab==="cron"&&ca(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&pt(e,{quiet:!0}),t.event==="exec.approval.requested"){const n=Xm(t.payload);if(n){e.execApprovalQueue=ev(e.execApprovalQueue,n),e.execApprovalError=null;const s=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=sl(e.execApprovalQueue,n.id)},s)}return}if(t.event==="exec.process.completed"){const n=t.payload;if(n?.sessionId){const s=n.exitSignal?`signal ${n.exitSignal}`:`exit ${n.exitCode??0}`,a=n.status==="completed"?"✓":"✗",i=n.status==="completed"?"success":"warning",o=n.sessionId.slice(0,8),l=e;typeof l.showToast=="function"&&l.showToast(`${a} Process ${o} ${n.status} (${s})`,i,5e3)}return}if(t.event==="exec.approval.resolved"){const n=Zm(t.payload);n&&(e.execApprovalQueue=sl(e.execApprovalQueue,n.id))}if(t.event==="daily-brief:update"){const n=t.payload;if(n){const s=e;s.dailyBrief=n}return}if(t.event==="ui.slot.update"){const n=t.payload;if(n?.tabId){const s=n.mode??"replace";if(n.html)s==="append"?e.dynamicSlots={...e.dynamicSlots,[n.tabId]:(e.dynamicSlots[n.tabId]??"")+n.html}:e.dynamicSlots={...e.dynamicSlots,[n.tabId]:n.html};else{const i={...e.dynamicSlots};delete i[n.tabId],e.dynamicSlots=i}e.requestUpdate?.()}return}if(t.event==="guardrails:update"){const n=e;typeof n.handleGuardrailsLoad=="function"&&n.handleGuardrailsLoad();return}if(t.event==="godmode.options:update"){const n=t.payload;if(n){const s=e;s.godmodeOptions=n,s.requestUpdate?.()}return}if(t.event==="proactiveIntel:insight"){const n=e;typeof n.handleIntelLoad=="function"&&n.handleIntelLoad();const s=t.payload;s?.newInsights&&typeof n.showToast=="function"&&n.showToast(`${s.newInsights} new intelligence insight${s.newInsights>1?"s":""} available`,"info",6e3);return}if(t.event==="proactiveIntel:update"){const n=e,s=n.secondBrainSubtab;typeof n.handleIntelLoad=="function"&&e.tab==="second-brain"&&s==="intel"&&n.handleIntelLoad();return}if(t.event==="onboarding:update"){const n=t.payload;if(n){const s=e;typeof n.phase=="number"&&(s.onboardingPhase=n.phase),s.onboardingData=n,n.completedAt&&(s.onboardingActive=!1),s.requestUpdate?.()}return}if(t.event==="ally:notification"){const n=t.payload;if(n){const s=e,a={role:"assistant",content:n.summary||"Notification received.",timestamp:Date.now(),isNotification:!0,actions:n.actions??[]};s.allyMessages=[...s.allyMessages??[],a],!s.allyPanelOpen&&e.tab!=="chat"&&(s.allyUnread=(s.allyUnread??0)+1),s.requestUpdate?.()}return}}async function Nv(e){const t=e;typeof t.loadFocusPulse=="function"&&await t.loadFocusPulse()}async function Fv(e){const t=e;typeof t.handleOptionsLoad=="function"&&await t.handleOptionsLoad()}async function Bv(e){if(typeof window>"u")return;const t=new URLSearchParams(window.location.search),n=t.get("openTask");if(!n||!e.client)return;t.delete("openTask");const s=t.toString()?`${window.location.pathname}?${t.toString()}`:window.location.pathname;window.history.replaceState({},"",s);try{const a=await e.client.request("tasks.openSession",{taskId:n});if(a?.sessionKey){e.sessionKey=a.sessionKey,e.tab="chat";const{loadChatHistory:i}=await E(async()=>{const{loadChatHistory:o}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:o}},void 0,import.meta.url);await i(e,a.sessionKey)}}catch(a){console.error("[GodMode] Failed to open task session:",a)}}function Uv(e,t){const n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health),n?.sessionDefaults&&Tv(e,n.sessionDefaults)}async function sa(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,s,a]=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 i=s;e.debugModels=Array.isArray(i?.models)?i?.models:[],e.debugHeartbeat=a}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}async function zv(e){if(!(!e.client||!e.connected)){e.debugCallError=null,e.debugCallResult=null;try{const t=e.debugCallParams.trim()?JSON.parse(e.debugCallParams):{},n=await e.client.request(e.debugCallMethod.trim(),t);e.debugCallResult=JSON.stringify(n,null,2)}catch(t){e.debugCallError=String(t)}}}const Kv=2e3,Wv=new Set(["trace","debug","info","warn","error","fatal"]);function qv(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 jv(e){if(typeof e!="string")return null;const t=e.toLowerCase();return Wv.has(t)?t:null}function Hv(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,s=typeof t.time=="string"?t.time:typeof n?.date=="string"?n?.date:null,a=jv(n?.logLevelName??n?.level),i=typeof t[0]=="string"?t[0]:typeof n?.name=="string"?n?.name:null,o=qv(i);let l=null;o&&(typeof o.subsystem=="string"?l=o.subsystem:typeof o.module=="string"&&(l=o.module)),!l&&i&&i.length<120&&(l=i);let c=null;return typeof t[1]=="string"?c=t[1]:!o&&typeof t[0]=="string"?c=t[0]:typeof t.message=="string"&&(c=t.message),{raw:e,time:s,level:a,subsystem:l,message:c??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function ho(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!t?.quiet)){t?.quiet||(e.logsLoading=!0),e.logsError=null;try{const s=await e.client.request("logs.tail",{cursor:t?.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),i=(Array.isArray(s.lines)?s.lines.filter(l=>typeof l=="string"):[]).map(Hv),o=!!(t?.reset||s.reset||e.logsCursor==null);e.logsEntries=o?i:[...e.logsEntries,...i].slice(-Kv),typeof s.cursor=="number"&&(e.logsCursor=s.cursor),typeof s.file=="string"&&(e.logsFile=s.file),e.logsTruncated=!!s.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t?.quiet||(e.logsLoading=!1)}}}const Xd={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer",subagent:"Sub-Agent",swarm:"Swarm"};function Wa(e,t,n){return n?n.replace(/-/g," ").replace(/\b\w/g,s=>s.toUpperCase()):Xd[t??e]??e}function Zd(e,t){const n=(t??Date.now())-e;if(n<0)return"0s";const s=Math.floor(n/1e3);if(s<60)return`${s}s`;const a=Math.floor(s/60),i=s%60;if(a<60)return`${a}m ${i}s`;const o=Math.floor(a/60),l=a%60;return`${o}h ${l}m`}function Vv(){const e=new Date;return e.setHours(0,0,0,0),e.getTime()}function Gv(e){switch(e){case"running":case"validating":return"active";case"queued":return"queued";case"failed":return"failed";default:return"done"}}function Qv(e,t){const n=[],s=new Set;for(const a of t){a.childSessionKey&&s.add(a.childSessionKey);const i=a.swarm?.enabled===!0,o=a.status==="review";n.push({id:a.id,type:i?"swarm":"coding",task:a.description,status:Gv(a.status),model:a.model??null,startedAt:a.startedAt??a.createdAt,endedAt:a.completedAt??null,branch:a.branch,prUrl:a.prUrl,swarmStage:i?a.swarm.currentStage:void 0,swarmStages:i?a.swarm.stages:void 0,error:a.error,canCancel:a.status==="running"||a.status==="validating"||a.status==="queued",roleName:i?"Swarm":"Builder",childSessionKey:a.childSessionKey,isReview:o})}for(const a of e)s.has(a.childSessionKey)||n.push({id:a.runId,type:"subagent",task:a.task,status:a.endedAt?a.outcome?.status==="error"?"failed":"done":"active",model:a.model,startedAt:a.startedAt??a.createdAt,endedAt:a.endedAt,label:a.label,error:a.outcome?.error??void 0,roleName:a.label??"Sub-Agent",childSessionKey:a.childSessionKey});return n.sort((a,i)=>{const o={active:0,queued:1,failed:2,done:3},l=o[a.status]-o[i.status];return l!==0?l:(i.startedAt??0)-(a.startedAt??0)}),n}function Yv(e){const t=[];for(const n of e)n.status==="done"&&n.endedAt&&t.push({id:`${n.id}-done`,timestamp:n.endedAt,type:"completed",summary:n.task,prUrl:n.prUrl,agentRef:n}),n.status==="failed"&&n.endedAt&&t.push({id:`${n.id}-fail`,timestamp:n.endedAt,type:"failed",summary:`${n.task}${n.error?` — ${n.error}`:""}`,agentRef:n}),n.status==="active"&&n.startedAt&&t.push({id:`${n.id}-start`,timestamp:n.startedAt,type:"started",summary:n.task,agentRef:n}),n.status==="queued"&&n.startedAt&&t.push({id:`${n.id}-queue`,timestamp:n.startedAt,type:"queued",summary:n.task,agentRef:n});return t.sort((n,s)=>s.timestamp-n.timestamp),t.slice(0,50)}function Jv(e,t=0,n=0){const s=Vv();let a=0,i=0,o=0,l=0;for(const u of e)u.status==="active"&&a++,u.status==="done"&&u.endedAt&&u.endedAt>=s&&i++,u.status==="failed"&&u.endedAt&&u.endedAt>=s&&o++,u.type==="swarm"&&(u.status==="active"||u.status==="queued")&&l++;const c=e.filter(u=>u.isReview&&(u.type==="coding"||u.type==="swarm")).length;return{activeNow:a,completedToday:i,failed:o,swarmPipelines:l,queueDepth:t,queueReview:n+c}}async function hn(e,t){if(!e.client||!e.connected)return;const n=e;t?.quiet||(n.missionControlLoading=!0),n.missionControlError=null;try{let s=null;try{s=await e.client.request("queue.list",{limit:100})}catch{}const[a,i]=await Promise.all([e.client.request("subagents.list",{limit:200}),e.client.request("coding.list",{})]),o=Qv(a.runs??[],i.tasks??[]),l=s?.items??[],c=[];let u=0;for(const g of l)g.status==="processing"?o.push({id:g.id,type:"queue",task:g.title,status:"active",model:null,startedAt:g.startedAt??g.createdAt,endedAt:null,error:g.error,roleName:Wa(g.type,void 0,g.personaHint),queueItemType:g.type,outputPath:g.result?.outputPath,sourceTaskId:g.sourceTaskId,retryCount:g.retryCount,prUrl:g.result?.prUrl}):g.status==="review"?(u++,o.push({id:g.id,type:"queue",task:g.title,status:"done",model:null,startedAt:g.startedAt??g.createdAt,endedAt:g.completedAt??null,roleName:Wa(g.type,void 0,g.personaHint),queueItemType:g.type,outputPath:g.result?.outputPath,sourceTaskId:g.sourceTaskId,retryCount:g.retryCount,prUrl:g.result?.prUrl,isReview:!0})):g.status==="failed"?o.push({id:g.id,type:"queue",task:g.title,status:"failed",model:null,startedAt:g.startedAt??g.createdAt,endedAt:g.completedAt??null,error:g.error,roleName:Wa(g.type,void 0,g.personaHint),queueItemType:g.type,outputPath:g.result?.outputPath,sourceTaskId:g.sourceTaskId,retryCount:g.retryCount}):g.status==="pending"&&c.push(g);o.sort((g,$)=>{const d={active:0,queued:1,failed:2,done:3},v=d[g.status]-d[$.status];return v!==0?v:($.startedAt??0)-(g.startedAt??0)});const p=c.length,f=Jv(o,p,u),m=Yv(o);n.missionControlData={agents:o,stats:f,activityFeed:m,lastRefreshedAt:Date.now(),queueItems:c}}catch(s){console.error("[MissionControl] load error:",s),n.missionControlError=s instanceof Error?s.message:"Failed to load agent data"}finally{n.missionControlLoading=!1}}async function Xv(e,t){if(!(!e.client||!e.connected))try{await e.client.request("coding.cancel",{taskId:t}),e.showToast("Task cancelled","success",2e3),await hn(e)}catch(n){e.showToast("Failed to cancel task","error"),console.error("[MissionControl] cancel error:",n)}}async function Zv(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("queue.approve",{id:t}),s=n?.item?.personaHint,a=n?.item?.title??"task";if(s){const i=s.replace(/-/g," ").replace(/\b\w/g,o=>o.toUpperCase());e.showToast(`Approved! How did ${i} do on "${a}"? Rate in Trust Tracker.`,"success",4e3)}else e.showToast("Item approved","success",2e3);await hn(e)}catch(n){e.showToast("Failed to approve item","error"),console.error("[MissionControl] approve error:",n)}}async function ey(e,t){if(!e.client||!e.connected)return!1;try{return(await e.client.request("coding.approve",{taskId:t}))?.approved?(e.showToast("Task approved","success",2e3),await hn(e),!0):!1}catch{return!1}}async function ty(e,t){if(!(!e.client||!e.connected))try{await e.client.request("queue.update",{id:t,status:"pending"}),await e.client.request("queue.process",{id:t}),e.showToast("Retrying...","success",2e3),await hn(e)}catch(n){e.showToast("Failed to retry","error"),console.error("[MissionControl] retry error:",n)}}async function ny(e,t){if(t.status==="failed")return{content:[`# Failed: ${t.task}`,"",`**Agent:** ${t.roleName}`,`**Retries:** ${t.retryCount??0}/2`,"","## Error","```",t.error??"Unknown error","```","","## What to do",t.retryCount&&t.retryCount>=2?"- This task failed after 2 automatic retries. Consider rephrasing the task or breaking it into smaller pieces.":"- Click **Retry** to attempt again with an improved prompt.","- Or remove this item and create a new one with more context."].join(`
716
716
  `),title:`Failed: ${t.task}`,mimeType:"text/markdown"};if(t.prUrl&&e.client)try{return{content:(await e.client.request("queue.prDiff",{prUrl:t.prUrl})).content,title:`PR: ${t.task}`,mimeType:"text/markdown"}}catch{return{content:`# ${t.task}
717
717
 
718
718
  [Open in GitHub](${t.prUrl})`,title:t.task,mimeType:"text/markdown"}}if(t.outputPath&&e.client)try{return{content:(await e.client.request("queue.readOutput",{path:t.outputPath})).content,title:t.task,mimeType:"text/markdown"}}catch{return{content:`Output file not found: ${t.outputPath}`,title:t.task,mimeType:"text/plain"}}return{content:`# ${t.task}
719
719
 
720
- No details available.`,title:t.task,mimeType:"text/markdown"}}const Qt=Object.freeze(Object.defineProperty({__proto__:null,AGENT_ROLE_NAMES:Xd,approveCodingTask:ty,approveQueueItem:ey,cancelCodingTask:Zv,formatDuration:Zd,loadAgentDetail:sy,loadMissionControl:hn,retryQueueItem:ny},Symbol.toStringTag,{value:"Module"}));function fo(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{na(e,{quiet:!0})},5e3))}function go(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function mo(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&ho(e,{quiet:!0})},2e3))}function vo(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function yo(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&sa(e)},3e3))}function bo(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function eu(e){e.missionControlPollInterval==null&&(e.missionControlPollInterval=window.setInterval(()=>{e.tab==="mission-control"&&hn(e,{quiet:!0})},5e3))}function tu(e){e.missionControlPollInterval!=null&&(clearInterval(e.missionControlPollInterval),e.missionControlPollInterval=null)}async function Zn(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 aa(e){if(!(!e.client||!e.connected)&&!e.cronLoading){e.cronLoading=!0,e.cronError=null;try{const t=await e.client.request("cron.list",{includeDisabled:!0});e.cronJobs=Array.isArray(t.jobs)?t.jobs:[]}catch(t){e.cronError=String(t)}finally{e.cronLoading=!1}}}function ay(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=Is(e.everyAmount,0);if(n<=0)throw new Error("Invalid interval amount.");const s=e.everyUnit;return{kind:"every",everyMs:n*(s==="minutes"?6e4:s==="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 iy(e){if(e.payloadKind==="systemEvent"){const a=e.payloadText.trim();if(!a)throw new Error("System event text required.");return{kind:"systemEvent",text:a}}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 s=Is(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function oy(e){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const t=ay(e.cronForm),n=iy(e.cronForm),s=e.cronForm.agentId.trim(),a={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,enabled:e.cronForm.enabled,schedule:t,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:n,isolation:e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?{postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:void 0};if(!a.name)throw new Error("Name required.");await e.client.request("cron.add",a),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await aa(e),await Zn(e)}catch(t){e.cronError=String(t)}finally{e.cronBusy=!1}}}async function ry(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 aa(e),await Zn(e)}catch(s){e.cronError=String(s)}finally{e.cronBusy=!1}}}async function ly(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 nu(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function cy(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 aa(e),await Zn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function nu(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 Ft(e){if(!(!e.client||!e.connected)){e.guardrailsLoading=!0;try{const[t,n]=await Promise.all([e.client.request("guardrails.list",{}),e.client.request("guardrails.history",{limit:50})]);e.guardrailsData={gates:t.gates,activity:n.activity,custom:t.custom??[]}}catch(t){console.error("[Guardrails] load error:",t),e.guardrailsData=null}finally{e.guardrailsLoading=!1}}}async function dy(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.set",{gateId:t,enabled:n});const a=e.guardrailsData?.gates.find(i=>i.id===t)?.name??t;e.showToast(`${a} ${n?"enabled":"disabled"}`,"success",2e3),await Ft(e)}catch(s){e.showToast("Failed to update guardrail","error"),console.error("[Guardrails] toggle error:",s)}}async function uy(e,t,n,s){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.set",{gateId:t,thresholds:{[n]:s}}),e.showToast("Threshold updated","success",2e3),await Ft(e)}catch(a){e.showToast("Failed to update threshold","error"),console.error("[Guardrails] threshold error:",a)}}async function py(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.setCustom",{id:t,enabled:n}),e.showToast(`Custom rule ${n?"enabled":"disabled"}`,"success",2e3),await Ft(e)}catch(s){e.showToast("Failed to update custom rule","error"),console.error("[Guardrails] toggleCustom error:",s)}}async function hy(e,t){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.removeCustom",{id:t}),e.showToast("Custom rule removed","success",2e3),await Ft(e)}catch(n){e.showToast("Failed to remove custom rule","error"),console.error("[Guardrails] deleteCustom error:",n)}}async function fy(e,t){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.addCustom",{guardrail:{name:t.name,description:"",enabled:!0,trigger:{tool:t.tool,patterns:t.patterns},action:t.action,message:t.message,...t.redirectTo?{redirectTo:t.redirectTo}:{}}}),e.showToast("Custom rule created","success",2e3),await Ft(e)}catch(n){e.showToast("Failed to create custom rule","error"),console.error("[Guardrails] addCustom error:",n)}}const Yt=Object.freeze(Object.defineProperty({__proto__:null,addCustomGuardrailFromUI:fy,deleteCustomGuardrail:hy,loadGuardrails:Ft,toggleCustomGuardrail:py,toggleGuardrail:dy,updateGuardrailThreshold:uy},Symbol.toStringTag,{value:"Module"}));function gy(e){if(!e||e.kind==="gateway")return{method:"exec.approvals.get",params:{}};const t=e.nodeId.trim();return t?{method:"exec.approvals.node.get",params:{nodeId:t}}:null}function my(e,t){if(!e||e.kind==="gateway")return{method:"exec.approvals.set",params:t};const n=e.nodeId.trim();return n?{method:"exec.approvals.node.set",params:{...t,nodeId:n}}:null}async function wo(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=gy(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const s=await e.client.request(n.method,n.params);vy(e,s)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function vy(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=Lt(t.file??{}))}async function yy(e,t){if(!(!e.client||!e.connected)){e.execApprovalsSaving=!0,e.lastError=null;try{const n=e.execApprovalsSnapshot?.hash;if(!n){e.lastError="Exec approvals hash missing; reload and retry.";return}const s=e.execApprovalsForm??e.execApprovalsSnapshot?.file??{},a=my(t,{file:s,baseHash:n});if(!a){e.lastError="Select a node before saving exec approvals.";return}await e.client.request(a.method,a.params),e.execApprovalsDirty=!1,await wo(e,t)}catch(n){e.lastError=String(n)}finally{e.execApprovalsSaving=!1}}}function by(e,t,n){const s=Lt(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});Sc(s,t,n),e.execApprovalsForm=s,e.execApprovalsDirty=!0}function wy(e,t){const n=Lt(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});Ac(n,t),e.execApprovalsForm=n,e.execApprovalsDirty=!0}const $y=["~/godmode/memory/AGENT-DAY.md","~/godmode/AGENT-DAY.md"];function ky(e){return[...[`~/godmode/memory/agent-day/${e}.md`,`~/godmode/memory/agent-log/${e}.md`,`~/godmode/memory/daily/${e}-agent-log.md`],...$y]}function Sy(e){return["Needs Review","Active Sub-Agents","Completed Today","Queue","Feedback Log","AGENT-DAY"].filter(s=>e.includes(s)).length>=2}async function su(e,t){try{const n=t?{date:t}:{},s=await e.request("dailyBrief.get",n);return!s||!s.content||!s.date?null:s}catch(n){return console.error("[MyDay] Failed to load daily brief:",n),null}}async function au(e,t,n){const s=t||re(),a="agentLog.get";try{const i=await e.request(a,{date:s});if(i?.content?.trim()&&i?.sourcePath)return{date:i.date||s,content:i.content,updatedAt:i.updatedAt||new Date().toISOString(),sourcePath:i.sourcePath}}catch(i){console.warn(`[MyDay] ${a} unavailable, falling back to files.read:`,i)}return Ay(e,s)}async function Ay(e,t){const n=ky(t),s=a=>a.includes("AGENT-DAY.md");for(const a of n)try{const i=await e.request("files.read",{path:a,maxSize:1e6});if(!i?.content?.trim()||!Sy(i.content)||s(a)&&typeof i.modifiedAt=="number"&&re(new Date(i.modifiedAt))!==t)continue;return{date:t,content:i.content,updatedAt:typeof i.modifiedAt=="number"?new Date(i.modifiedAt).toISOString():new Date().toISOString(),sourcePath:a}}catch{}return null}function ys(e,t,n){return new Promise((s,a)=>{const i=setTimeout(()=>a(new Error(`${n} timed out after ${t}ms`)),t);e.then(o=>{clearTimeout(i),s(o)},o=>{clearTimeout(i),a(o)})})}const _y={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer"};async function iu(e){if(!e.client||!e.connected)return[];e.todayTasksLoading=!0;try{const t=e.todaySelectedDate??re(),[n,s]=await Promise.all([e.client.request("tasks.today",{date:t,includeCompleted:!0}),e.client.request("queue.list",{limit:100}).catch(()=>({items:[]}))]),a=new Map;for(const o of s.items)o.sourceTaskId&&(o.status==="processing"||o.status==="review"||o.status==="failed")&&a.set(o.sourceTaskId,{status:o.status,type:o.type,roleName:_y[o.type]??o.type,queueItemId:o.id});const i=(n.tasks??[]).map(o=>({id:o.id,title:o.title,status:o.status,project:o.project,dueDate:o.dueDate,priority:o.priority,createdAt:o.createdAt,completedAt:o.completedAt,queueStatus:a.get(o.id)??null}));return e.todayTasks=i,i}catch(t){return console.error("[MyDay] Failed to load today tasks:",t),e.todayTasks??[]}finally{e.todayTasksLoading=!1}}async function Ty(e){if(!e.client||!e.connected)return[];try{const n=(await e.client.request("queue.list",{limit:50}))?.items??[],s=Date.now()-1440*60*1e3;return n.filter(a=>!(a.status!=="review"&&a.status!=="done"||a.status==="done"&&(a.completedAt??0)<s)).map(a=>({id:a.id,title:a.title,summary:a.result?.summary??a.description??"",status:a.status,completedAt:a.completedAt,outputPath:a.result?.outputPath,prUrl:a.result?.prUrl,sourceTaskId:a.sourceTaskId}))}catch(t){return console.error("[MyDay] Failed to load queue results for decision cards:",t),[]}}function xy(e,t){e.request("dailyBrief.syncTasks",t?{date:t}:{}).catch(n=>{console.warn("[MyDay] dailyBrief.syncTasks failed (non-blocking):",n)})}async function xs(e){if(!(!e.client||!e.connected)){e.dailyBriefLoading=!0,e.dailyBriefError=null;try{e.dailyBrief=await su(e.client,e.todaySelectedDate),e.loadBriefNotes&&await e.loadBriefNotes()}catch(t){e.dailyBriefError=t instanceof Error?t.message:"Failed to load daily brief",console.error("[MyDay] Brief load error:",t)}finally{e.dailyBriefLoading=!1}}}async function St(e,t){if(!(!e.client||!e.connected)){e.agentLogLoading=!0,e.agentLogError=null;try{e.agentLog=await au(e.client,e.todaySelectedDate,t)}catch(n){e.agentLogError=n instanceof Error?n.message:"Failed to load agent log",console.error("[MyDay] Agent log load error:",n)}finally{e.agentLogLoading=!1}}}function ou(e){const t=e||re(),n="VAULT",s=`01-Daily/${t}`,a=`obsidian://open?vault=${encodeURIComponent(n)}&file=${encodeURIComponent(s)}`;window.open(a,"_blank")}async function Ks(e){if(!e.client||!e.connected)return;e.myDayLoading=!0,e.myDayError=null,e.dailyBriefLoading=!0,e.agentLogLoading=!0,e.todayTasksLoading=!0;const t=e.todaySelectedDate,n=e.loadBriefNotes?ys(e.loadBriefNotes(),5e3,"Brief Notes"):Promise.resolve(),s=await Promise.allSettled([ys(su(e.client,t),1e4,"Daily Brief"),n,ys(au(e.client,t),1e4,"Agent Log"),ys(iu(e),8e3,"Today Tasks")]);e.dailyBrief=s[0].status==="fulfilled"?s[0].value:null,e.agentLog=s[2].status==="fulfilled"?s[2].value:null;const a=["Brief","Brief Notes","Agent Log","Today Tasks"],i=s.map((o,l)=>o.status==="rejected"?{section:a[l],reason:o.reason}:null).filter(Boolean);if(i.length>0){for(const o of i)console.warn(`[MyDay] ${o.section} failed:`,o.reason);i.length===s.length&&(e.myDayError="Failed to load daily brief")}e.myDayLoading=!1,e.dailyBriefLoading=!1,e.agentLogLoading=!1,e.todayTasksLoading=!1}function Cy(e,t){const n=s=>{t(s)};return e.on("daily-brief:update",n),()=>{e.off("daily-brief:update",n)}}function ru(e,t){const n=()=>{t()};return e.on("agent-log:update",n),()=>{e.off("agent-log:update",n)}}const In=Object.freeze(Object.defineProperty({__proto__:null,loadAgentLogOnly:St,loadBriefOnly:xs,loadMyDay:Ks,loadTodayQueueResults:Ty,loadTodayTasksWithQueueStatus:iu,openBriefInObsidian:ou,subscribeToAgentLogUpdates:ru,subscribeToBriefUpdates:Cy,syncTodayTasks:xy},Symbol.toStringTag,{value:"Module"}));async function $o(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 dn(e,t,n){if(!t.trim())return;const s={...e.skillMessages};n?s[t]=n:delete s[t],e.skillMessages=s}function ia(e){return e instanceof Error?e.message:String(e)}async function es(e,t){if(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=ia(n)}finally{e.skillsLoading=!1}}}function Ey(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Ly(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 es(e),dn(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(s){const a=ia(s);e.skillsError=a,dn(e,t,{kind:"error",message:a})}finally{e.skillsBusyKey=null}}}async function Ry(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 es(e),dn(e,t,{kind:"success",message:"API key saved"})}catch(n){const s=ia(n);e.skillsError=s,dn(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Py(e,t,n,s){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const a=await e.client.request("skills.install",{name:n,installId:s,timeoutMs:12e4});await es(e),dn(e,t,{kind:"success",message:a?.message??"Installed"})}catch(a){const i=ia(a);e.skillsError=i,dn(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function lu(e){if(!(!e.client||!e.connected)){e.workLoading=!0,e.workError=null;try{const t=await e.client.request("projects.list",{});e.workProjects=t.projects??[]}catch(t){console.error("[Work] Failed to load:",t),e.workError=t instanceof Error?t.message:"Failed to load"}finally{e.workLoading=!1}}}async function Iy(e,t){if(!e.client||!e.connected)return;const n=new Set(e.workDetailLoading??[]);n.add(t),e.workDetailLoading=n;try{const s=await e.client.request("projects.get",{id:t,includeFiles:!0,depth:2});if(s){const a=s.files??[];e.workProjectFiles={...e.workProjectFiles,[t]:a}}}catch(s){console.warn("[Work] Failed to load project details:",s)}finally{const s=new Set(e.workDetailLoading??[]);s.delete(t),e.workDetailLoading=s}}function oa(e,t=Date.now()){if(typeof e=="number"&&Number.isFinite(e))return new Date(e);if(typeof e=="string"){const n=Date.parse(e);if(Number.isFinite(n))return new Date(n)}return new Date(t)}function ko(e){return{id:e.id,name:e.name,emoji:e.emoji||"📁",type:e.type,path:e.path,artifactCount:e.artifactCount??0,sessionCount:e.sessionCount??0,lastUpdated:oa(e.lastUpdated,e.lastScanned)}}function qa(e){return{path:e.path,name:e.name,type:e.type,size:e.size,modified:oa(e.modified),isDirectory:e.isDirectory,searchText:e.searchText}}function dl(e){return{id:e.id,key:e.key,title:e.title,created:oa(e.created),status:e.status,workspaceSubfolder:e.workspaceSubfolder}}function Bt(e){return{id:e.id,title:e.title,status:e.status,project:e.project,dueDate:e.dueDate,priority:e.priority,createdAt:e.createdAt,completedAt:e.completedAt}}function cu(e){return e.map(t=>({name:t.name,path:t.path,type:t.type,fileType:t.fileType,size:t.size,modified:t.modified?oa(t.modified):void 0,children:t.children?cu(t.children):void 0}))}function My(e,t){return{...t,id:e.id,name:e.name,emoji:e.emoji,type:e.type,path:e.path,artifactCount:e.artifactCount,sessionCount:e.sessionCount,lastUpdated:e.lastUpdated}}async function ra(e){if(!e.client||!e.connected){e.workspaces=[],e.workspacesLoading=!1,e.workspacesError="Connect to gateway to see workspaces";return}e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});if(e.workspaces=(t.workspaces??[]).map(ko),e.selectedWorkspace){const n=e.workspaces.find(s=>s.id===e.selectedWorkspace?.id);n&&(e.selectedWorkspace=My(n,e.selectedWorkspace))}}catch(t){console.error("[Workspaces] load failed:",t),e.workspacesError=t instanceof Error?t.message:"Failed to load workspaces",e.workspaces=[]}finally{e.workspacesLoading=!1}}async function la(e,t){if(!e.client||!e.connected)return null;try{const n=await e.client.request("workspaces.get",{id:t});return n.workspace?{...ko(n.workspace),pinned:(n.pinned??[]).map(qa),pinnedSessions:(n.pinnedSessions??[]).map(dl),outputs:(n.outputs??[]).map(qa),folderTree:n.folderTree?cu(n.folderTree):void 0,sessions:(n.sessions??[]).map(dl),tasks:(n.tasks??[]).map(Bt),memory:(n.memory??[]).map(qa)}:null}catch(n){return console.error("[Workspaces] get failed:",n),null}}async function Dy(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("workspaces.readFile",n?{workspaceId:n,filePath:t}:{path:t});return s.content?{content:s.content,mime:s.contentType??s.mime??"text/plain"}:(s.error&&console.warn("[Workspaces] readFile failed:",s.error),null)}catch(s){return console.error("[Workspaces] readFile error:",s),null}}async function Oy(e){if(!(!e.client||!e.connected))try{e.workspacesLoading=!0,e.workspacesError=null,await e.client.request("workspaces.scan",{}),await ra(e)}catch(t){e.workspacesError=t instanceof Error?t.message:"Failed to scan workspaces"}finally{e.workspacesLoading=!1}}async function Ny(e,t){if(!t){e.selectedWorkspace=null;return}const n=await la(e,t.id);e.selectedWorkspace=n||{...t,pinned:[],pinnedSessions:[],outputs:[],sessions:[],tasks:[]}}async function Fy(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpin":"workspaces.pin",{workspaceId:t,filePath:n}),e.selectedWorkspace?.id===t){const a=await la(e,t);a&&(e.selectedWorkspace=a)}return!0}catch(a){return console.error("[Workspaces] pin toggle failed:",a),!1}}async function By(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpinSession":"workspaces.pinSession",{workspaceId:t,sessionKey:n}),e.selectedWorkspace?.id===t){const a=await la(e,t);a&&(e.selectedWorkspace=a)}return!0}catch(a){return console.error("[Workspaces] session pin toggle failed:",a),!1}}async function Uy(e,t){if(!e.client||!e.connected)return null;const n=String(t.name??"").trim();if(!n)return e.workspacesError="Workspace name is required",null;const s=t.type??"project",a=String(t.path??"").trim();try{const i=await e.client.request("workspaces.create",{name:n,type:s,...a?{path:a}:{}});if(!i.workspace)return e.workspacesError="Workspace creation returned no workspace",null;const o=ko(i.workspace),l=e.workspaces??[],c=new Map(l.map(u=>[u.id,u]));return c.set(o.id,o),e.workspaces=Array.from(c.values()).toSorted((u,p)=>p.lastUpdated.getTime()-u.lastUpdated.getTime()),e.workspacesError=null,o}catch(i){return console.error("[Workspaces] create failed:",i),e.workspacesError=i instanceof Error?i.message:"Failed to create workspace",null}}async function zy(e,t){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.delete",{id:t}),e.workspaces=(e.workspaces??[]).filter(n=>n.id!==t),e.selectedWorkspace?.id===t&&(e.selectedWorkspace=null),e.workspacesError=null,!0}catch(n){return console.error("[Workspaces] delete failed:",n),e.workspacesError=n instanceof Error?n.message:"Failed to delete workspace",!1}}function Ky(e,t){e.workspacesSearchQuery=t}function Wy(e){e.selectedWorkspace=null}async function qy(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("workspaces.teamSetupPrompt",{});t?.prompt&&(e.chatMessage=t.prompt,e.setTab?.("chat"))}catch{e.chatMessage="I want to set up a Team Workspace so my team can collaborate. Please walk me through it step by step, keeping it simple.",e.setTab?.("chat")}}function jy(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}async function Hy(e,t){if(!e.client||!e.connected)return[];try{return((await e.client.request("tasks.byProject",{project:t})).tasks??[]).map(Bt)}catch(n){return console.error("[Workspaces] loadWorkspaceTasks failed:",n),[]}}async function Vy(e){if(!e.client||!e.connected)return[];try{return((await e.client.request("tasks.list",{})).tasks??[]).map(Bt)}catch(t){return console.error("[Workspaces] loadAllTasks failed:",t),[]}}const Gy={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer"};async function Qy(e){if(!e.client||!e.connected)return[];try{const[t,n]=await Promise.all([e.client.request("tasks.list",{}),e.client.request("queue.list",{limit:100}).catch(()=>({items:[]}))]),s=new Map;for(const a of n.items)a.sourceTaskId&&(a.status==="processing"||a.status==="review"||a.status==="failed")&&s.set(a.sourceTaskId,{status:a.status,type:a.type,roleName:Gy[a.type]??a.type,queueItemId:a.id});return(t.tasks??[]).map(a=>({...Bt(a),queueStatus:s.get(a.id)??null}))}catch(t){return console.error("[Workspaces] loadAllTasksWithQueueStatus failed:",t),[]}}async function Yy(e,t,n){if(!e.client||!e.connected)return null;const s=n==="complete"?"pending":"complete";try{const a=await e.client.request("tasks.update",{id:t,status:s});return Bt(a)}catch(a){return console.error("[Workspaces] toggleTaskComplete failed:",a),null}}async function Jy(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.update",{id:t,...n});return Bt(s)}catch(s){return console.error("[Workspaces] updateTask failed:",s),null}}async function Xy(e,t){if(!e.client||!e.connected)return null;try{return await e.client.request("tasks.openSession",{taskId:t})}catch(n){return console.error("[Workspaces] startTask failed:",n),null}}async function Zy(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.create",{title:t,project:n,source:"chat"});return Bt(s)}catch(s){return console.error("[Workspaces] createTask failed:",s),null}}async function eb(e,t,n){if(!e.client||!e.connected)return null;try{return await e.client.request("workspaces.browseFolder",{workspaceId:t,folderPath:n})}catch(s){return console.error("[Workspaces] browseFolder failed:",s),null}}async function tb(e,t,n,s=50){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspaces.search",{workspaceId:t,query:n,limit:s})).results??[]}catch(a){return console.error("[Workspaces] search failed:",a),[]}}async function nb(e,t,n){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.createFolder",{workspaceId:t,folderPath:n}),!0}catch(s){return console.error("[Workspaces] createFolder failed:",s),!1}}async function sb(e,t,n,s){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.moveFile",{workspaceId:t,sourcePath:n,destPath:s}),!0}catch(a){return console.error("[Workspaces] moveFile failed:",a),!1}}async function ab(e,t,n,s){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.renameFile",{workspaceId:t,filePath:n,newName:s}),!0}catch(a){return console.error("[Workspaces] renameFile failed:",a),!1}}const pe=Object.freeze(Object.defineProperty({__proto__:null,browseWorkspaceFolder:eb,clearWorkspaceSelection:Wy,createTask:Zy,createWorkspace:Uy,createWorkspaceFolder:nb,deleteWorkspace:zy,getWorkspace:la,loadAllTasks:Vy,loadAllTasksWithQueueStatus:Qy,loadWorkspaceTasks:Hy,loadWorkspaces:ra,moveWorkspaceFile:sb,readWorkspaceFile:Dy,renameWorkspaceFile:ab,scanWorkspaces:Oy,searchWorkspaceFiles:tb,selectWorkspace:Ny,setWorkspacesSearchQuery:Ky,startTask:Xy,startTeamSetup:qy,toggleTaskComplete:Yy,toggleWorkspaceFolder:jy,toggleWorkspacePin:Fy,toggleWorkspaceSessionPin:By,updateTask:Jy},Symbol.toStringTag,{value:"Module"})),du="godmode.ui.settings.v1";function ib(){const e=new URLSearchParams(location.search),t=(()=>{const a=e.get("gatewayUrl");return a||(typeof window.__GODMODE_DEV__<"u"?"/ws":`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`)})(),n=e.get("token")||"",s={gatewayUrl:t,token:n,sessionKey:"main",lastActiveSessionKey:"main",theme:"system",chatFocusMode:!1,chatShowThinking:!0,splitRatio:.6,navCollapsed:!1,navGroupsCollapsed:{System:!0},openTabs:[],tabLastViewed:{},userName:"",userAvatar:"",chatParallelView:!1,parallelLanes:[null,null,null,null]};try{const a=localStorage.getItem(du);if(!a)return s;const i=JSON.parse(a);return{gatewayUrl:e.get("gatewayUrl")||(typeof window.__GODMODE_DEV__<"u"?"/ws":typeof i.gatewayUrl=="string"&&i.gatewayUrl.trim()?i.gatewayUrl.trim():s.gatewayUrl),token:n||(typeof i.token=="string"?i.token:""),sessionKey:typeof i.sessionKey=="string"&&i.sessionKey.trim()?i.sessionKey.trim():s.sessionKey,lastActiveSessionKey:typeof i.lastActiveSessionKey=="string"&&i.lastActiveSessionKey.trim()?i.lastActiveSessionKey.trim():typeof i.sessionKey=="string"&&i.sessionKey.trim()||s.lastActiveSessionKey,theme:i.theme==="light"||i.theme==="dark"||i.theme==="system"||i.theme==="lifetrack"?i.theme:s.theme,chatFocusMode:typeof i.chatFocusMode=="boolean"?i.chatFocusMode:s.chatFocusMode,chatShowThinking:typeof i.chatShowThinking=="boolean"?i.chatShowThinking:s.chatShowThinking,splitRatio:typeof i.splitRatio=="number"&&i.splitRatio>=.4&&i.splitRatio<=.7?i.splitRatio:s.splitRatio,navCollapsed:typeof i.navCollapsed=="boolean"?i.navCollapsed:s.navCollapsed,navGroupsCollapsed:typeof i.navGroupsCollapsed=="object"&&i.navGroupsCollapsed!==null?i.navGroupsCollapsed:s.navGroupsCollapsed,openTabs:Array.isArray(i.openTabs)&&i.openTabs.every(o=>typeof o=="string")?i.openTabs:s.openTabs,tabLastViewed:typeof i.tabLastViewed=="object"&&i.tabLastViewed!==null?i.tabLastViewed:s.tabLastViewed,userName:typeof i.userName=="string"?i.userName.trim().slice(0,50):s.userName,userAvatar:typeof i.userAvatar=="string"?i.userAvatar.trim():s.userAvatar,chatParallelView:typeof i.chatParallelView=="boolean"?i.chatParallelView:s.chatParallelView,parallelLanes:Array.isArray(i.parallelLanes)&&i.parallelLanes.length===4?i.parallelLanes.map(o=>typeof o=="string"?o:null):s.parallelLanes}}catch{return s}}function ob(e){localStorage.setItem(du,JSON.stringify(e))}const rb=56,lb="quantum-particles",cb="quantum-particle";let lt=null,Nn=null;function Ae(e,t){return Math.random()*(t-e)+e}function uu(){if(pu(),typeof document>"u")return;const e=document.querySelector(".shell");if(!e){Nn=requestAnimationFrame(()=>{Nn=null,uu()});return}lt=document.createElement("div"),lt.className=lb,Object.assign(lt.style,{position:"fixed",inset:"0",pointerEvents:"none",zIndex:"1",overflow:"hidden"});for(let t=0;t<rb;t++){const n=document.createElement("div");n.className=cb;const s=Ae(2,5),a=Ae(.3,.65),i=Ae(15,35),o=Ae(0,12),l=Ae(5,95),c=Ae(5,95),u=Ae(-150,150),p=Ae(-200,200),f=Ae(-250,250),m=Ae(-350,350),g=Ae(.8,1.5);Object.assign(n.style,{position:"absolute",left:`${l}%`,top:`${c}%`,width:`${s}px`,height:`${s}px`,borderRadius:"50%",background:`rgba(235, 158, 15, ${Ae(.7,1)})`,boxShadow:`0 0 ${s*3}px rgba(235, 158, 15, ${a*.7})`,opacity:"0",willChange:"transform, opacity",animation:`quantum-float ${i}s ${o}s ease-in-out infinite`}),n.style.setProperty("--particle-opacity",String(a)),n.style.setProperty("--drift-x",`${u}px`),n.style.setProperty("--drift-y",`${p}px`),n.style.setProperty("--drift-end-x",`${f}px`),n.style.setProperty("--drift-end-y",`${m}px`),n.style.setProperty("--particle-scale-mid",String(g)),lt.appendChild(n)}e.prepend(lt)}function pu(){Nn!==null&&(cancelAnimationFrame(Nn),Nn=null),lt&&(lt.remove(),lt=null)}function db(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"lifetrack"}function So(e){return e==="system"?db():e==="light"?"lifetrack":e}const bs=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,ub=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,En=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},pb=({nextTheme:e,applyTheme:t,context:n,currentTheme:s})=>{if(s===e)return;const a=globalThis.document??null;if(!a){t();return}const i=a.documentElement,o=a,l=ub();if(!!o.startViewTransition&&!l){let u=.5,p=.5;if(n?.pointerClientX!==void 0&&n?.pointerClientY!==void 0&&typeof window<"u")u=bs(n.pointerClientX/window.innerWidth),p=bs(n.pointerClientY/window.innerHeight);else if(n?.element){const m=n.element.getBoundingClientRect();m.width>0&&m.height>0&&typeof window<"u"&&(u=bs((m.left+m.width/2)/window.innerWidth),p=bs((m.top+m.height/2)/window.innerHeight))}i.style.setProperty("--theme-switch-x",`${u*100}%`),i.style.setProperty("--theme-switch-y",`${p*100}%`),i.classList.add("theme-transition");const f=setTimeout(()=>{En(i)},1e3);try{const m=o.startViewTransition?.(()=>{t()});m?.finished?m.finished.finally(()=>{clearTimeout(f),En(i)}):(clearTimeout(f),En(i))}catch{clearTimeout(f),En(i),t()}return}t(),En(i)};function hb(e,t){const n=Array.isArray(e)?[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))]:[];if(n.length===0&&t){const s=t.toLowerCase();s==="main"||s==="agent:main:main"||s.endsWith(":main")||n.push(t)}return n}function fb(e){const t={};if(!e||typeof e!="object")return t;for(const[n,s]of Object.entries(e)){const a=n.trim();!a||typeof s!="number"||!Number.isFinite(s)||(t[a]=Math.max(t[a]??0,s))}return t}function Je(e,t){const n=t.sessionKey.trim()||"main",s=hb(t.openTabs,n),a=fb(t.tabLastViewed),i={...t,sessionKey:n,openTabs:s,tabLastViewed:a,lastActiveSessionKey:t.lastActiveSessionKey?.trim()||n};e.settings=i,ob(i),i.theme!==e.theme&&(e.theme=i.theme,ns(e,So(i.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Ao(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&Je(e,{...e.settings,lastActiveSessionKey:n})}function hu(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),s=t.get("password"),a=t.get("session"),i=t.get("gatewayUrl");let o=!1;if(n!=null){const c=n.trim();c&&c!==e.settings.token&&Je(e,{...e.settings,token:c}),t.delete("token"),o=!0}if(s!=null){const c=s.trim();c&&(e.password=c),t.delete("password"),o=!0}if(a!=null){const c=a.trim();if(c){e.sessionKey=c;const u=c.toLowerCase(),f=u==="main"||u==="agent:main:main"||u.endsWith(":main")||e.settings.openTabs.includes(c)?e.settings.openTabs:[...e.settings.openTabs,c];Je(e,{...e.settings,sessionKey:c,lastActiveSessionKey:c,openTabs:f})}}if(i!=null){const c=i.trim();c&&c!==e.settings.gatewayUrl&&(e.pendingGatewayUrl=c),t.delete("gatewayUrl"),o=!0}if(!o)return;const l=new URL(window.location.href);l.search=t.toString(),window.history.replaceState({},"",l.toString())}function _o(e,t){const n=e.tab;if(n!==t&&(e.tab=t),n==="dashboards"&&t!=="dashboards"){const s=e;if(s.dashboardPreviousSessionKey&&s.activeDashboardId){const a=s.dashboardPreviousSessionKey;s.dashboardPreviousSessionKey=null,s.activeDashboardId=null,s.activeDashboardManifest=null,s.activeDashboardHtml=null,s.dashboardChatOpen=!1,e.sessionKey=a}}t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?fo(e):go(e),t==="logs"?mo(e):vo(e),t==="debug"?yo(e):bo(e),t==="mission-control"?eu(e):tu(e),ts(e),xo(e,t,!1)}function fu(e,t,n){pb({nextTheme:t,applyTheme:()=>{e.theme=t,Je(e,{...e.settings,theme:t}),ns(e,So(t))},context:n,currentTheme:e.theme})}async function ts(e){if(e.tab==="overview"&&await Co(e),(e.tab==="today"||e.tab==="my-day")&&(await Ks(e),E(()=>Promise.resolve().then(()=>In),void 0,import.meta.url).then(async({loadTodayQueueResults:t})=>{e.todayQueueResults=await t(e)}).catch(()=>{})),e.tab==="work"&&await lu(e),e.tab==="workspaces"&&(await ra(e),E(()=>Promise.resolve().then(()=>pe),void 0,import.meta.url).then(async({loadAllTasksWithQueueStatus:t})=>{e.allTasks=await t(e)})),e.tab==="data"&&e.handleDataRefresh(),e.tab==="channels"&&await $u(e),e.tab==="instances"&&await $o(e),e.tab==="sessions"&&(await X(e),await Mt(e)),e.tab==="cron"&&await ca(e),e.tab==="skills"&&await es(e),e.tab==="nodes"&&(await na(e),await pt(e),await Ye(e),await wo(e)),e.tab==="chat"&&(await Ro(e),rn(e,!e.chatHasAutoScrolled)),e.tab==="options"){const t=e;typeof t.handleOptionsLoad=="function"&&await t.handleOptionsLoad()}if(e.tab==="trust"){const t=e,n=[];typeof t.handleTrustLoad=="function"&&n.push(t.handleTrustLoad()),n.push(Ft(t)),n.push(X(t)),await Promise.all(n)}if(e.tab==="guardrails"){const t=e;typeof t.handleGuardrailsLoad=="function"&&await t.handleGuardrailsLoad()}if(e.tab==="mission-control"){const t=e;typeof t.handleMissionControlRefresh=="function"&&await t.handleMissionControlRefresh()}if(e.tab==="setup"){const t=e;typeof t.handleLoadSetupChecklist=="function"&&t.handleLoadSetupChecklist()}if(e.tab==="dashboards"){const t=e;typeof t.handleDashboardsRefresh=="function"&&await t.handleDashboardsRefresh()}if(e.tab==="second-brain"){const t=e,n=t.secondBrainSubtab;n==="intel"?typeof t.handleIntelLoad=="function"&&await t.handleIntelLoad():n==="files"?typeof t.handleSecondBrainFileTreeRefresh=="function"&&await t.handleSecondBrainFileTreeRefresh():typeof t.handleSecondBrainRefresh=="function"&&await t.handleSecondBrainRefresh()}e.tab==="config"&&(await _c(e),await Ye(e)),e.tab==="debug"&&(await sa(e),e.eventLog=Av()),e.tab==="logs"&&(e.logsAtBottom=!0,await ho(e,{reset:!0}),Ec(e,!0))}function gu(){if(typeof window>"u")return"";const e=window.__OPENCLAW_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?Zs(e):cm(window.location.pathname)}function mu(e){e.theme=e.settings.theme??"system",ns(e,So(e.theme))}function ns(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t==="dark"?"dark":"light",t==="lifetrack"?uu():pu()}function vu(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"&&ns(e,n.matches?"dark":"lifetrack")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function yu(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 bu(e,t){if(typeof window>"u")return;const n=dd(window.location.pathname,e.basePath)??"chat";To(e,n),xo(e,n,t)}function wu(e){if(typeof window>"u")return;const t=dd(window.location.pathname,e.basePath);if(!t)return;const s=new URL(window.location.href).searchParams.get("session")?.trim();if(s){e.sessionKey=s;const a=e.settings.openTabs.includes(s)?e.settings.openTabs:[...e.settings.openTabs,s];Je(e,{...e.settings,sessionKey:s,lastActiveSessionKey:s,openTabs:a})}To(e,t)}function To(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?fo(e):go(e),t==="logs"?mo(e):vo(e),t==="debug"?yo(e):bo(e),t==="mission-control"?eu(e):tu(e),e.connected&&ts(e)}function xo(e,t,n){if(typeof window>"u")return;const s=Vn(to(t,e.basePath)),a=Vn(window.location.pathname),i=new URL(window.location.href);t==="chat"&&e.sessionKey?i.searchParams.set("session",e.sessionKey):i.searchParams.delete("session"),a!==s&&(i.pathname=s),n?window.history.replaceState({},"",i.toString()):window.history.pushState({},"",i.toString())}function ve(e,t,n){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.set("session",t),n?window.history.replaceState({},"",s.toString()):window.history.pushState({},"",s.toString())}async function Co(e){await Promise.all([Me(e,!1),$o(e),X(e),Zn(e),sa(e)])}async function $u(e){await Promise.all([Me(e,!0),_c(e),Ye(e)])}async function ca(e){await Promise.all([Me(e,!1),Zn(e),aa(e)])}const gb=Object.freeze(Object.defineProperty({__proto__:null,applyResolvedTheme:ns,applySettings:Je,applySettingsFromUrl:hu,attachThemeListener:vu,detachThemeListener:yu,inferBasePath:gu,loadChannelsTab:$u,loadCron:ca,loadOverview:Co,onPopState:wu,refreshActiveTab:ts,setLastActiveSessionKey:Ao,setTab:_o,setTabFromRoute:To,setTheme:fu,syncTabWithLocation:bu,syncThemeWithSettings:mu,syncUrlWithSessionKey:ve,syncUrlWithTab:xo},Symbol.toStringTag,{value:"Module"}));function Ws(e){return e.chatSending||!!e.chatRunId}function $e(e,t){const n=t??e.sessionKey,s=e.chatMessage.trim();if(s)e.chatDrafts={...e.chatDrafts,[n]:s};else{const{[n]:a,...i}=e.chatDrafts;e.chatDrafts=i}}function Le(e,t){const n=t??e.sessionKey;e.chatMessage=e.chatDrafts[n]??""}function ku(e,t){const n=t??e.sessionKey,{[n]:s,...a}=e.chatDrafts;e.chatDrafts=a,n===e.sessionKey&&(e.chatMessage="")}function Su(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"}function mb(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/new"||n==="/reset"?!0:n.startsWith("/new ")||n.startsWith("/reset ")}async function Eo(e){e.connected&&(e.chatMessage="",await ao(e))}function vb(e,t,n){const s=t.trim(),a=!!(n&&n.length>0);if(!s&&!a)return;const i=Date.now();e.chatQueue=[...e.chatQueue,{id:ea(),text:s,createdAt:i,attachments:a?n?.map(l=>({...l})):void 0}];const o=[];if(s&&o.push({type:"text",text:s}),a&&n)for(const l of n)o.push({type:"image",source:{type:"base64",media_type:l.mimeType,data:l.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:o,timestamp:i}],rn(e,!0)}async function _i(e,t,n){Bi(e);const s=e;s.sessionKey&&s.workingSessions&&(s.workingSessions=new Set([...s.workingSessions,s.sessionKey])),n?.skipOptimisticUpdate||queueMicrotask(()=>{rn(e,!0)});const a=await so(e,t,n?.attachments,{skipOptimisticUpdate:n?.skipOptimisticUpdate});return!a&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!a&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),a&&(Ao(e,e.sessionKey),e.chatAttachments=[]),a&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),a&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),rn(e,!0),a&&!e.chatRunId&&Lo(e),a&&n?.refreshSessions&&(e.refreshSessionsAfterChat=!0),a}async function Lo(e){if(!e.connected||Ws(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await _i(e,t.text,{attachments:t.attachments,skipOptimisticUpdate:!0})||(e.chatQueue=[t,...e.chatQueue])}function Au(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function _u(e,t,n){if(!e.connected)return;const s=e.chatMessage,a=(t??e.chatMessage).trim(),i=e.chatAttachments??[],o=t==null?i:[],l=o.length>0;if(!a&&!l)return;if(Su(a)){await Eo(e);return}const c=mb(a);if(t==null&&(e.chatMessage="",ku(e)),n?.queue){vb(e,a,o),Ws(e)||await Lo(e);return}if(Ws(e)){await ao(e),await new Promise(u=>setTimeout(u,50)),await _i(e,a,{attachments:l?o:void 0,refreshSessions:c});return}await _i(e,a,{previousDraft:t==null?s:void 0,restoreDraft:!!(t&&n?.restoreDraft),attachments:l?o:void 0,previousAttachments:t==null?i:void 0,restoreAttachments:!!(t&&n?.restoreDraft),refreshSessions:c})}async function Ro(e){await Promise.all([ne(e),X(e,{activeMinutes:0}),qs(e)]),rn(e,!0)}const Tu=Lo;function yb(e){const t=Cc(e.sessionKey);return t?.agentId?t.agentId:e.hello?.snapshot?.sessionDefaults?.defaultAgentId?.trim()||"main"}function bb(e,t){const n=Zs(e),s=encodeURIComponent(t);return n?`${n}/avatar/${s}?meta=1`:`/avatar/${s}?meta=1`}async function qs(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=yb(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=bb(e.basePath,t);try{const s=await fetch(n,{method:"GET"});if(!s.ok){e.chatAvatarUrl=null;return}const a=await s.json(),i=typeof a.avatarUrl=="string"?a.avatarUrl.trim():"";e.chatAvatarUrl=i||null}catch{e.chatAvatarUrl=null}}const ja=Object.freeze(Object.defineProperty({__proto__:null,clearDraft:ku,flushChatQueueForEvent:Tu,handleAbortChat:Eo,handleSendChat:_u,isChatBusy:Ws,isChatStopCommand:Su,refreshChat:Ro,refreshChatAvatar:qs,removeQueuedMessage:Au,restoreDraft:Le,saveDraft:$e},Symbol.toStringTag,{value:"Module"})),wb={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},$b={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:""};const{I:kb}=zp,ul=e=>e,Sb=e=>e.strings===void 0,pl=()=>document.createComment(""),Ln=(e,t,n)=>{const s=e._$AA.parentNode,a=t===void 0?e._$AB:t._$AA;if(n===void 0){const i=s.insertBefore(pl(),a),o=s.insertBefore(pl(),a);n=new kb(i,o,e,e.options)}else{const i=n._$AB.nextSibling,o=n._$AM,l=o!==e;if(l){let c;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==o._$AU&&n._$AP(c)}if(i!==a||l){let c=n._$AA;for(;c!==i;){const u=ul(c).nextSibling;ul(s).insertBefore(c,a),c=u}}}return n},vt=(e,t,n=e)=>(e._$AI(t,n),e),Ab={},_b=(e,t=Ab)=>e._$AH=t,Tb=e=>e._$AH,Ha=e=>{e._$AR(),e._$AA.remove()};const hl=(e,t,n)=>{const s=new Map;for(let a=t;a<=n;a++)s.set(e[a],a);return s},da=zi(class extends Ki{constructor(e){if(super(e),e.type!==Ui.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,n){let s;n===void 0?n=t:t!==void 0&&(s=t);const a=[],i=[];let o=0;for(const l of e)a[o]=s?s(l,o):o,i[o]=n(l,o),o++;return{values:i,keys:a}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,s]){const a=Tb(e),{values:i,keys:o}=this.dt(t,n,s);if(!Array.isArray(a))return this.ut=o,i;const l=this.ut??=[],c=[];let u,p,f=0,m=a.length-1,g=0,$=i.length-1;for(;f<=m&&g<=$;)if(a[f]===null)f++;else if(a[m]===null)m--;else if(l[f]===o[g])c[g]=vt(a[f],i[g]),f++,g++;else if(l[m]===o[$])c[$]=vt(a[m],i[$]),m--,$--;else if(l[f]===o[$])c[$]=vt(a[f],i[$]),Ln(e,c[$+1],a[f]),f++,$--;else if(l[m]===o[g])c[g]=vt(a[m],i[g]),Ln(e,a[f],a[m]),m--,g++;else if(u===void 0&&(u=hl(o,g,$),p=hl(l,f,m)),u.has(l[f]))if(u.has(l[m])){const d=p.get(o[g]),v=d!==void 0?a[d]:null;if(v===null){const S=Ln(e,a[f]);vt(S,i[g]),c[g]=S}else c[g]=vt(v,i[g]),Ln(e,a[f],v),a[d]=null;g++}else Ha(a[m]),m--;else Ha(a[f]),f++;for(;g<=$;){const d=Ln(e,c[$+1]);vt(d,i[g]),c[g++]=d}for(;f<=m;){const d=a[f++];d!==null&&Ha(d)}return this.ut=o,_b(e,c),dt}});function ua(e){$e(e);const n=`agent:main:webchat-${ea().slice(0,8)}`;e.applySettings({...e.settings,openTabs:[...e.settings.openTabs,n],sessionKey:n,lastActiveSessionKey:n,tabLastViewed:{...e.settings.tabLastViewed,[n]:Date.now()}}),e.sessionKey=n,e.chatMessage="",e.chatMessages=[],e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.loadAssistantIdentity(),ve(e,n,!0),ne(e)}function xu(e,t){const n=to(t,e.basePath);return r`
720
+ No details available.`,title:t.task,mimeType:"text/markdown"}}const Gt=Object.freeze(Object.defineProperty({__proto__:null,AGENT_ROLE_NAMES:Xd,approveCodingTask:ey,approveQueueItem:Zv,cancelCodingTask:Xv,formatDuration:Zd,loadAgentDetail:ny,loadMissionControl:hn,retryQueueItem:ty},Symbol.toStringTag,{value:"Module"}));function fo(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{na(e,{quiet:!0})},5e3))}function go(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function mo(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&ho(e,{quiet:!0})},2e3))}function vo(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function yo(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&sa(e)},3e3))}function bo(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function eu(e){e.missionControlPollInterval==null&&(e.missionControlPollInterval=window.setInterval(()=>{e.tab==="mission-control"&&hn(e,{quiet:!0})},5e3))}function tu(e){e.missionControlPollInterval!=null&&(clearInterval(e.missionControlPollInterval),e.missionControlPollInterval=null)}async function Zn(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 aa(e){if(!(!e.client||!e.connected)&&!e.cronLoading){e.cronLoading=!0,e.cronError=null;try{const t=await e.client.request("cron.list",{includeDisabled:!0});e.cronJobs=Array.isArray(t.jobs)?t.jobs:[]}catch(t){e.cronError=String(t)}finally{e.cronLoading=!1}}}function sy(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=Is(e.everyAmount,0);if(n<=0)throw new Error("Invalid interval amount.");const s=e.everyUnit;return{kind:"every",everyMs:n*(s==="minutes"?6e4:s==="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 ay(e){if(e.payloadKind==="systemEvent"){const a=e.payloadText.trim();if(!a)throw new Error("System event text required.");return{kind:"systemEvent",text:a}}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 s=Is(e.timeoutSeconds,0);return s>0&&(n.timeoutSeconds=s),n}async function iy(e){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const t=sy(e.cronForm),n=ay(e.cronForm),s=e.cronForm.agentId.trim(),a={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,enabled:e.cronForm.enabled,schedule:t,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:n,isolation:e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?{postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:void 0};if(!a.name)throw new Error("Name required.");await e.client.request("cron.add",a),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await aa(e),await Zn(e)}catch(t){e.cronError=String(t)}finally{e.cronBusy=!1}}}async function oy(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 aa(e),await Zn(e)}catch(s){e.cronError=String(s)}finally{e.cronBusy=!1}}}async function ry(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 nu(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function ly(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 aa(e),await Zn(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function nu(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 Nt(e){if(!(!e.client||!e.connected)){e.guardrailsLoading=!0;try{const[t,n]=await Promise.all([e.client.request("guardrails.list",{}),e.client.request("guardrails.history",{limit:50})]);e.guardrailsData={gates:t.gates,activity:n.activity,custom:t.custom??[]}}catch(t){console.error("[Guardrails] load error:",t),e.guardrailsData=null}finally{e.guardrailsLoading=!1}}}async function cy(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.set",{gateId:t,enabled:n});const a=e.guardrailsData?.gates.find(i=>i.id===t)?.name??t;e.showToast(`${a} ${n?"enabled":"disabled"}`,"success",2e3),await Nt(e)}catch(s){e.showToast("Failed to update guardrail","error"),console.error("[Guardrails] toggle error:",s)}}async function dy(e,t,n,s){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.set",{gateId:t,thresholds:{[n]:s}}),e.showToast("Threshold updated","success",2e3),await Nt(e)}catch(a){e.showToast("Failed to update threshold","error"),console.error("[Guardrails] threshold error:",a)}}async function uy(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.setCustom",{id:t,enabled:n}),e.showToast(`Custom rule ${n?"enabled":"disabled"}`,"success",2e3),await Nt(e)}catch(s){e.showToast("Failed to update custom rule","error"),console.error("[Guardrails] toggleCustom error:",s)}}async function py(e,t){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.removeCustom",{id:t}),e.showToast("Custom rule removed","success",2e3),await Nt(e)}catch(n){e.showToast("Failed to remove custom rule","error"),console.error("[Guardrails] deleteCustom error:",n)}}async function hy(e,t){if(!(!e.client||!e.connected))try{await e.client.request("guardrails.addCustom",{guardrail:{name:t.name,description:"",enabled:!0,trigger:{tool:t.tool,patterns:t.patterns},action:t.action,message:t.message,...t.redirectTo?{redirectTo:t.redirectTo}:{}}}),e.showToast("Custom rule created","success",2e3),await Nt(e)}catch(n){e.showToast("Failed to create custom rule","error"),console.error("[Guardrails] addCustom error:",n)}}const Qt=Object.freeze(Object.defineProperty({__proto__:null,addCustomGuardrailFromUI:hy,deleteCustomGuardrail:py,loadGuardrails:Nt,toggleCustomGuardrail:uy,toggleGuardrail:cy,updateGuardrailThreshold:dy},Symbol.toStringTag,{value:"Module"}));function fy(e){if(!e||e.kind==="gateway")return{method:"exec.approvals.get",params:{}};const t=e.nodeId.trim();return t?{method:"exec.approvals.node.get",params:{nodeId:t}}:null}function gy(e,t){if(!e||e.kind==="gateway")return{method:"exec.approvals.set",params:t};const n=e.nodeId.trim();return n?{method:"exec.approvals.node.set",params:{...t,nodeId:n}}:null}async function wo(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=fy(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const s=await e.client.request(n.method,n.params);my(e,s)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function my(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=Et(t.file??{}))}async function vy(e,t){if(!(!e.client||!e.connected)){e.execApprovalsSaving=!0,e.lastError=null;try{const n=e.execApprovalsSnapshot?.hash;if(!n){e.lastError="Exec approvals hash missing; reload and retry.";return}const s=e.execApprovalsForm??e.execApprovalsSnapshot?.file??{},a=gy(t,{file:s,baseHash:n});if(!a){e.lastError="Select a node before saving exec approvals.";return}await e.client.request(a.method,a.params),e.execApprovalsDirty=!1,await wo(e,t)}catch(n){e.lastError=String(n)}finally{e.execApprovalsSaving=!1}}}function yy(e,t,n){const s=Et(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});Sc(s,t,n),e.execApprovalsForm=s,e.execApprovalsDirty=!0}function by(e,t){const n=Et(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});Ac(n,t),e.execApprovalsForm=n,e.execApprovalsDirty=!0}const wy=["~/godmode/memory/AGENT-DAY.md","~/godmode/AGENT-DAY.md"];function $y(e){return[...[`~/godmode/memory/agent-day/${e}.md`,`~/godmode/memory/agent-log/${e}.md`,`~/godmode/memory/daily/${e}-agent-log.md`],...wy]}function ky(e){return["Needs Review","Active Sub-Agents","Completed Today","Queue","Feedback Log","AGENT-DAY"].filter(s=>e.includes(s)).length>=2}async function su(e,t){try{const n=t?{date:t}:{},s=await e.request("dailyBrief.get",n);return!s||!s.content||!s.date?null:s}catch(n){return console.error("[MyDay] Failed to load daily brief:",n),null}}async function au(e,t,n){const s=t||re(),a="agentLog.get";try{const i=await e.request(a,{date:s});if(i?.content?.trim()&&i?.sourcePath)return{date:i.date||s,content:i.content,updatedAt:i.updatedAt||new Date().toISOString(),sourcePath:i.sourcePath}}catch(i){console.warn(`[MyDay] ${a} unavailable, falling back to files.read:`,i)}return Sy(e,s)}async function Sy(e,t){const n=$y(t),s=a=>a.includes("AGENT-DAY.md");for(const a of n)try{const i=await e.request("files.read",{path:a,maxSize:1e6});if(!i?.content?.trim()||!ky(i.content)||s(a)&&typeof i.modifiedAt=="number"&&re(new Date(i.modifiedAt))!==t)continue;return{date:t,content:i.content,updatedAt:typeof i.modifiedAt=="number"?new Date(i.modifiedAt).toISOString():new Date().toISOString(),sourcePath:a}}catch{}return null}function ys(e,t,n){return new Promise((s,a)=>{const i=setTimeout(()=>a(new Error(`${n} timed out after ${t}ms`)),t);e.then(o=>{clearTimeout(i),s(o)},o=>{clearTimeout(i),a(o)})})}const Ay={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer"};async function iu(e){if(!e.client||!e.connected)return[];e.todayTasksLoading=!0;try{const t=e.todaySelectedDate??re(),[n,s]=await Promise.all([e.client.request("tasks.today",{date:t,includeCompleted:!0}),e.client.request("queue.list",{limit:100}).catch(()=>({items:[]}))]),a=new Map;for(const o of s.items)o.sourceTaskId&&(o.status==="processing"||o.status==="review"||o.status==="failed")&&a.set(o.sourceTaskId,{status:o.status,type:o.type,roleName:Ay[o.type]??o.type,queueItemId:o.id});const i=(n.tasks??[]).map(o=>({id:o.id,title:o.title,status:o.status,project:o.project,dueDate:o.dueDate,priority:o.priority,createdAt:o.createdAt,completedAt:o.completedAt,queueStatus:a.get(o.id)??null}));return e.todayTasks=i,i}catch(t){return console.error("[MyDay] Failed to load today tasks:",t),e.todayTasks??[]}finally{e.todayTasksLoading=!1}}async function _y(e){if(!e.client||!e.connected)return[];try{const n=(await e.client.request("queue.list",{limit:50}))?.items??[],s=Date.now()-1440*60*1e3;return n.filter(a=>!(a.status!=="review"&&a.status!=="done"||a.status==="done"&&(a.completedAt??0)<s)).map(a=>({id:a.id,title:a.title,summary:a.result?.summary??a.description??"",status:a.status,completedAt:a.completedAt,outputPath:a.result?.outputPath,prUrl:a.result?.prUrl,sourceTaskId:a.sourceTaskId}))}catch(t){return console.error("[MyDay] Failed to load queue results for decision cards:",t),[]}}function Ty(e,t){e.request("dailyBrief.syncTasks",t?{date:t}:{}).catch(n=>{console.warn("[MyDay] dailyBrief.syncTasks failed (non-blocking):",n)})}async function xs(e){if(!(!e.client||!e.connected)){e.dailyBriefLoading=!0,e.dailyBriefError=null;try{e.dailyBrief=await su(e.client,e.todaySelectedDate),e.loadBriefNotes&&await e.loadBriefNotes()}catch(t){e.dailyBriefError=t instanceof Error?t.message:"Failed to load daily brief",console.error("[MyDay] Brief load error:",t)}finally{e.dailyBriefLoading=!1}}}async function Jt(e,t){if(!(!e.client||!e.connected)){e.agentLogLoading=!0,e.agentLogError=null;try{e.agentLog=await au(e.client,e.todaySelectedDate,t)}catch(n){e.agentLogError=n instanceof Error?n.message:"Failed to load agent log",console.error("[MyDay] Agent log load error:",n)}finally{e.agentLogLoading=!1}}}function ou(e){const t=e||re(),n="VAULT",s=`01-Daily/${t}`,a=`obsidian://open?vault=${encodeURIComponent(n)}&file=${encodeURIComponent(s)}`;window.open(a,"_blank")}async function Ks(e){if(!e.client||!e.connected)return;e.myDayLoading=!0,e.myDayError=null,e.dailyBriefLoading=!0,e.agentLogLoading=!0,e.todayTasksLoading=!0;const t=e.todaySelectedDate,n=e.loadBriefNotes?ys(e.loadBriefNotes(),5e3,"Brief Notes"):Promise.resolve(),s=await Promise.allSettled([ys(su(e.client,t),1e4,"Daily Brief"),n,ys(au(e.client,t),1e4,"Agent Log"),ys(iu(e),8e3,"Today Tasks")]);e.dailyBrief=s[0].status==="fulfilled"?s[0].value:null,e.agentLog=s[2].status==="fulfilled"?s[2].value:null;const a=["Brief","Brief Notes","Agent Log","Today Tasks"],i=s.map((o,l)=>o.status==="rejected"?{section:a[l],reason:o.reason}:null).filter(Boolean);if(i.length>0){for(const o of i)console.warn(`[MyDay] ${o.section} failed:`,o.reason);i.length===s.length&&(e.myDayError="Failed to load daily brief")}e.myDayLoading=!1,e.dailyBriefLoading=!1,e.agentLogLoading=!1,e.todayTasksLoading=!1}const In=Object.freeze(Object.defineProperty({__proto__:null,loadAgentLogOnly:Jt,loadBriefOnly:xs,loadMyDay:Ks,loadTodayQueueResults:_y,loadTodayTasksWithQueueStatus:iu,openBriefInObsidian:ou,syncTodayTasks:Ty},Symbol.toStringTag,{value:"Module"}));async function $o(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 dn(e,t,n){if(!t.trim())return;const s={...e.skillMessages};n?s[t]=n:delete s[t],e.skillMessages=s}function ia(e){return e instanceof Error?e.message:String(e)}async function es(e,t){if(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=ia(n)}finally{e.skillsLoading=!1}}}function xy(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Cy(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 es(e),dn(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(s){const a=ia(s);e.skillsError=a,dn(e,t,{kind:"error",message:a})}finally{e.skillsBusyKey=null}}}async function Ey(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 es(e),dn(e,t,{kind:"success",message:"API key saved"})}catch(n){const s=ia(n);e.skillsError=s,dn(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Ly(e,t,n,s){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const a=await e.client.request("skills.install",{name:n,installId:s,timeoutMs:12e4});await es(e),dn(e,t,{kind:"success",message:a?.message??"Installed"})}catch(a){const i=ia(a);e.skillsError=i,dn(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function ru(e){if(!(!e.client||!e.connected)){e.workLoading=!0,e.workError=null;try{const t=await e.client.request("projects.list",{});e.workProjects=t.projects??[]}catch(t){console.error("[Work] Failed to load:",t),e.workError=t instanceof Error?t.message:"Failed to load"}finally{e.workLoading=!1}}}async function Ry(e,t){if(!e.client||!e.connected)return;const n=new Set(e.workDetailLoading??[]);n.add(t),e.workDetailLoading=n;try{const s=await e.client.request("projects.get",{id:t,includeFiles:!0,depth:2});if(s){const a=s.files??[];e.workProjectFiles={...e.workProjectFiles,[t]:a}}}catch(s){console.warn("[Work] Failed to load project details:",s)}finally{const s=new Set(e.workDetailLoading??[]);s.delete(t),e.workDetailLoading=s}}function oa(e,t=Date.now()){if(typeof e=="number"&&Number.isFinite(e))return new Date(e);if(typeof e=="string"){const n=Date.parse(e);if(Number.isFinite(n))return new Date(n)}return new Date(t)}function ko(e){return{id:e.id,name:e.name,emoji:e.emoji||"📁",type:e.type,path:e.path,artifactCount:e.artifactCount??0,sessionCount:e.sessionCount??0,lastUpdated:oa(e.lastUpdated,e.lastScanned)}}function qa(e){return{path:e.path,name:e.name,type:e.type,size:e.size,modified:oa(e.modified),isDirectory:e.isDirectory,searchText:e.searchText}}function dl(e){return{id:e.id,key:e.key,title:e.title,created:oa(e.created),status:e.status,workspaceSubfolder:e.workspaceSubfolder}}function Ft(e){return{id:e.id,title:e.title,status:e.status,project:e.project,dueDate:e.dueDate,priority:e.priority,createdAt:e.createdAt,completedAt:e.completedAt}}function lu(e){return e.map(t=>({name:t.name,path:t.path,type:t.type,fileType:t.fileType,size:t.size,modified:t.modified?oa(t.modified):void 0,children:t.children?lu(t.children):void 0}))}function Py(e,t){return{...t,id:e.id,name:e.name,emoji:e.emoji,type:e.type,path:e.path,artifactCount:e.artifactCount,sessionCount:e.sessionCount,lastUpdated:e.lastUpdated}}async function ra(e){if(!e.client||!e.connected){e.workspaces=[],e.workspacesLoading=!1,e.workspacesError="Connect to gateway to see workspaces";return}e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});if(e.workspaces=(t.workspaces??[]).map(ko),e.selectedWorkspace){const n=e.workspaces.find(s=>s.id===e.selectedWorkspace?.id);n&&(e.selectedWorkspace=Py(n,e.selectedWorkspace))}}catch(t){console.error("[Workspaces] load failed:",t),e.workspacesError=t instanceof Error?t.message:"Failed to load workspaces",e.workspaces=[]}finally{e.workspacesLoading=!1}}async function la(e,t){if(!e.client||!e.connected)return null;try{const n=await e.client.request("workspaces.get",{id:t});return n.workspace?{...ko(n.workspace),pinned:(n.pinned??[]).map(qa),pinnedSessions:(n.pinnedSessions??[]).map(dl),outputs:(n.outputs??[]).map(qa),folderTree:n.folderTree?lu(n.folderTree):void 0,sessions:(n.sessions??[]).map(dl),tasks:(n.tasks??[]).map(Ft),memory:(n.memory??[]).map(qa)}:null}catch(n){return console.error("[Workspaces] get failed:",n),null}}async function Iy(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("workspaces.readFile",n?{workspaceId:n,filePath:t}:{path:t});return s.content?{content:s.content,mime:s.contentType??s.mime??"text/plain"}:(s.error&&console.warn("[Workspaces] readFile failed:",s.error),null)}catch(s){return console.error("[Workspaces] readFile error:",s),null}}async function My(e){if(!(!e.client||!e.connected))try{e.workspacesLoading=!0,e.workspacesError=null,await e.client.request("workspaces.scan",{}),await ra(e)}catch(t){e.workspacesError=t instanceof Error?t.message:"Failed to scan workspaces"}finally{e.workspacesLoading=!1}}async function Dy(e,t){if(!t){e.selectedWorkspace=null;return}const n=await la(e,t.id);e.selectedWorkspace=n||{...t,pinned:[],pinnedSessions:[],outputs:[],sessions:[],tasks:[]}}async function Oy(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpin":"workspaces.pin",{workspaceId:t,filePath:n}),e.selectedWorkspace?.id===t){const a=await la(e,t);a&&(e.selectedWorkspace=a)}return!0}catch(a){return console.error("[Workspaces] pin toggle failed:",a),!1}}async function Ny(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpinSession":"workspaces.pinSession",{workspaceId:t,sessionKey:n}),e.selectedWorkspace?.id===t){const a=await la(e,t);a&&(e.selectedWorkspace=a)}return!0}catch(a){return console.error("[Workspaces] session pin toggle failed:",a),!1}}async function Fy(e,t){if(!e.client||!e.connected)return null;const n=String(t.name??"").trim();if(!n)return e.workspacesError="Workspace name is required",null;const s=t.type??"project",a=String(t.path??"").trim();try{const i=await e.client.request("workspaces.create",{name:n,type:s,...a?{path:a}:{}});if(!i.workspace)return e.workspacesError="Workspace creation returned no workspace",null;const o=ko(i.workspace),l=e.workspaces??[],c=new Map(l.map(u=>[u.id,u]));return c.set(o.id,o),e.workspaces=Array.from(c.values()).toSorted((u,p)=>p.lastUpdated.getTime()-u.lastUpdated.getTime()),e.workspacesError=null,o}catch(i){return console.error("[Workspaces] create failed:",i),e.workspacesError=i instanceof Error?i.message:"Failed to create workspace",null}}async function By(e,t){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.delete",{id:t}),e.workspaces=(e.workspaces??[]).filter(n=>n.id!==t),e.selectedWorkspace?.id===t&&(e.selectedWorkspace=null),e.workspacesError=null,!0}catch(n){return console.error("[Workspaces] delete failed:",n),e.workspacesError=n instanceof Error?n.message:"Failed to delete workspace",!1}}function Uy(e,t){e.workspacesSearchQuery=t}function zy(e){e.selectedWorkspace=null}async function Ky(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("workspaces.teamSetupPrompt",{});t?.prompt&&(e.chatMessage=t.prompt,e.setTab?.("chat"))}catch{e.chatMessage="I want to set up a Team Workspace so my team can collaborate. Please walk me through it step by step, keeping it simple.",e.setTab?.("chat")}}function Wy(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}async function qy(e,t){if(!e.client||!e.connected)return[];try{return((await e.client.request("tasks.byProject",{project:t})).tasks??[]).map(Ft)}catch(n){return console.error("[Workspaces] loadWorkspaceTasks failed:",n),[]}}async function jy(e){if(!e.client||!e.connected)return[];try{return((await e.client.request("tasks.list",{})).tasks??[]).map(Ft)}catch(t){return console.error("[Workspaces] loadAllTasks failed:",t),[]}}const Hy={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer"};async function Vy(e){if(!e.client||!e.connected)return[];try{const[t,n]=await Promise.all([e.client.request("tasks.list",{}),e.client.request("queue.list",{limit:100}).catch(()=>({items:[]}))]),s=new Map;for(const a of n.items)a.sourceTaskId&&(a.status==="processing"||a.status==="review"||a.status==="failed")&&s.set(a.sourceTaskId,{status:a.status,type:a.type,roleName:Hy[a.type]??a.type,queueItemId:a.id});return(t.tasks??[]).map(a=>({...Ft(a),queueStatus:s.get(a.id)??null}))}catch(t){return console.error("[Workspaces] loadAllTasksWithQueueStatus failed:",t),[]}}async function Gy(e,t,n){if(!e.client||!e.connected)return null;const s=n==="complete"?"pending":"complete";try{const a=await e.client.request("tasks.update",{id:t,status:s});return Ft(a)}catch(a){return console.error("[Workspaces] toggleTaskComplete failed:",a),null}}async function Qy(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.update",{id:t,...n});return Ft(s)}catch(s){return console.error("[Workspaces] updateTask failed:",s),null}}async function Yy(e,t){if(!e.client||!e.connected)return null;try{return await e.client.request("tasks.openSession",{taskId:t})}catch(n){return console.error("[Workspaces] startTask failed:",n),null}}async function Jy(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.create",{title:t,project:n,source:"chat"});return Ft(s)}catch(s){return console.error("[Workspaces] createTask failed:",s),null}}async function Xy(e,t,n){if(!e.client||!e.connected)return null;try{return await e.client.request("workspaces.browseFolder",{workspaceId:t,folderPath:n})}catch(s){return console.error("[Workspaces] browseFolder failed:",s),null}}async function Zy(e,t,n,s=50){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspaces.search",{workspaceId:t,query:n,limit:s})).results??[]}catch(a){return console.error("[Workspaces] search failed:",a),[]}}async function eb(e,t,n){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.createFolder",{workspaceId:t,folderPath:n}),!0}catch(s){return console.error("[Workspaces] createFolder failed:",s),!1}}async function tb(e,t,n,s){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.moveFile",{workspaceId:t,sourcePath:n,destPath:s}),!0}catch(a){return console.error("[Workspaces] moveFile failed:",a),!1}}async function nb(e,t,n,s){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.renameFile",{workspaceId:t,filePath:n,newName:s}),!0}catch(a){return console.error("[Workspaces] renameFile failed:",a),!1}}const pe=Object.freeze(Object.defineProperty({__proto__:null,browseWorkspaceFolder:Xy,clearWorkspaceSelection:zy,createTask:Jy,createWorkspace:Fy,createWorkspaceFolder:eb,deleteWorkspace:By,getWorkspace:la,loadAllTasks:jy,loadAllTasksWithQueueStatus:Vy,loadWorkspaceTasks:qy,loadWorkspaces:ra,moveWorkspaceFile:tb,readWorkspaceFile:Iy,renameWorkspaceFile:nb,scanWorkspaces:My,searchWorkspaceFiles:Zy,selectWorkspace:Dy,setWorkspacesSearchQuery:Uy,startTask:Yy,startTeamSetup:Ky,toggleTaskComplete:Gy,toggleWorkspaceFolder:Wy,toggleWorkspacePin:Oy,toggleWorkspaceSessionPin:Ny,updateTask:Qy},Symbol.toStringTag,{value:"Module"})),cu="godmode.ui.settings.v1";function sb(){const e=new URLSearchParams(location.search),t=(()=>{const a=e.get("gatewayUrl");return a||(typeof window.__GODMODE_DEV__<"u"?"/ws":`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`)})(),n=e.get("token")||"",s={gatewayUrl:t,token:n,sessionKey:"main",lastActiveSessionKey:"main",theme:"system",chatFocusMode:!1,chatShowThinking:!0,splitRatio:.6,navCollapsed:!1,navGroupsCollapsed:{System:!0},openTabs:[],tabLastViewed:{},userName:"",userAvatar:"",chatParallelView:!1,parallelLanes:[null,null,null,null]};try{const a=localStorage.getItem(cu);if(!a)return s;const i=JSON.parse(a);return{gatewayUrl:e.get("gatewayUrl")||(typeof window.__GODMODE_DEV__<"u"?"/ws":typeof i.gatewayUrl=="string"&&i.gatewayUrl.trim()?i.gatewayUrl.trim():s.gatewayUrl),token:n||(typeof i.token=="string"?i.token:""),sessionKey:typeof i.sessionKey=="string"&&i.sessionKey.trim()?i.sessionKey.trim():s.sessionKey,lastActiveSessionKey:typeof i.lastActiveSessionKey=="string"&&i.lastActiveSessionKey.trim()?i.lastActiveSessionKey.trim():typeof i.sessionKey=="string"&&i.sessionKey.trim()||s.lastActiveSessionKey,theme:i.theme==="light"||i.theme==="dark"||i.theme==="system"||i.theme==="lifetrack"?i.theme:s.theme,chatFocusMode:typeof i.chatFocusMode=="boolean"?i.chatFocusMode:s.chatFocusMode,chatShowThinking:typeof i.chatShowThinking=="boolean"?i.chatShowThinking:s.chatShowThinking,splitRatio:typeof i.splitRatio=="number"&&i.splitRatio>=.4&&i.splitRatio<=.7?i.splitRatio:s.splitRatio,navCollapsed:typeof i.navCollapsed=="boolean"?i.navCollapsed:s.navCollapsed,navGroupsCollapsed:typeof i.navGroupsCollapsed=="object"&&i.navGroupsCollapsed!==null?i.navGroupsCollapsed:s.navGroupsCollapsed,openTabs:Array.isArray(i.openTabs)&&i.openTabs.every(o=>typeof o=="string")?i.openTabs:s.openTabs,tabLastViewed:typeof i.tabLastViewed=="object"&&i.tabLastViewed!==null?i.tabLastViewed:s.tabLastViewed,userName:typeof i.userName=="string"?i.userName.trim().slice(0,50):s.userName,userAvatar:typeof i.userAvatar=="string"?i.userAvatar.trim():s.userAvatar,chatParallelView:typeof i.chatParallelView=="boolean"?i.chatParallelView:s.chatParallelView,parallelLanes:Array.isArray(i.parallelLanes)&&i.parallelLanes.length===4?i.parallelLanes.map(o=>typeof o=="string"?o:null):s.parallelLanes}}catch{return s}}function ab(e){localStorage.setItem(cu,JSON.stringify(e))}const ib=56,ob="quantum-particles",rb="quantum-particle";let lt=null,Nn=null;function Ae(e,t){return Math.random()*(t-e)+e}function du(){if(uu(),typeof document>"u")return;const e=document.querySelector(".shell");if(!e){Nn=requestAnimationFrame(()=>{Nn=null,du()});return}lt=document.createElement("div"),lt.className=ob,Object.assign(lt.style,{position:"fixed",inset:"0",pointerEvents:"none",zIndex:"1",overflow:"hidden"});for(let t=0;t<ib;t++){const n=document.createElement("div");n.className=rb;const s=Ae(2,5),a=Ae(.3,.65),i=Ae(15,35),o=Ae(0,12),l=Ae(5,95),c=Ae(5,95),u=Ae(-150,150),p=Ae(-200,200),f=Ae(-250,250),m=Ae(-350,350),g=Ae(.8,1.5);Object.assign(n.style,{position:"absolute",left:`${l}%`,top:`${c}%`,width:`${s}px`,height:`${s}px`,borderRadius:"50%",background:`rgba(235, 158, 15, ${Ae(.7,1)})`,boxShadow:`0 0 ${s*3}px rgba(235, 158, 15, ${a*.7})`,opacity:"0",willChange:"transform, opacity",animation:`quantum-float ${i}s ${o}s ease-in-out infinite`}),n.style.setProperty("--particle-opacity",String(a)),n.style.setProperty("--drift-x",`${u}px`),n.style.setProperty("--drift-y",`${p}px`),n.style.setProperty("--drift-end-x",`${f}px`),n.style.setProperty("--drift-end-y",`${m}px`),n.style.setProperty("--particle-scale-mid",String(g)),lt.appendChild(n)}e.prepend(lt)}function uu(){Nn!==null&&(cancelAnimationFrame(Nn),Nn=null),lt&&(lt.remove(),lt=null)}function lb(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"lifetrack"}function So(e){return e==="system"?lb():e==="light"?"lifetrack":e}const bs=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,cb=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,En=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},db=({nextTheme:e,applyTheme:t,context:n,currentTheme:s})=>{if(s===e)return;const a=globalThis.document??null;if(!a){t();return}const i=a.documentElement,o=a,l=cb();if(!!o.startViewTransition&&!l){let u=.5,p=.5;if(n?.pointerClientX!==void 0&&n?.pointerClientY!==void 0&&typeof window<"u")u=bs(n.pointerClientX/window.innerWidth),p=bs(n.pointerClientY/window.innerHeight);else if(n?.element){const m=n.element.getBoundingClientRect();m.width>0&&m.height>0&&typeof window<"u"&&(u=bs((m.left+m.width/2)/window.innerWidth),p=bs((m.top+m.height/2)/window.innerHeight))}i.style.setProperty("--theme-switch-x",`${u*100}%`),i.style.setProperty("--theme-switch-y",`${p*100}%`),i.classList.add("theme-transition");const f=setTimeout(()=>{En(i)},1e3);try{const m=o.startViewTransition?.(()=>{t()});m?.finished?m.finished.finally(()=>{clearTimeout(f),En(i)}):(clearTimeout(f),En(i))}catch{clearTimeout(f),En(i),t()}return}t(),En(i)};function ub(e,t){const n=Array.isArray(e)?[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))]:[];if(n.length===0&&t){const s=t.toLowerCase();s==="main"||s==="agent:main:main"||s.endsWith(":main")||n.push(t)}return n}function pb(e){const t={};if(!e||typeof e!="object")return t;for(const[n,s]of Object.entries(e)){const a=n.trim();!a||typeof s!="number"||!Number.isFinite(s)||(t[a]=Math.max(t[a]??0,s))}return t}function Je(e,t){const n=t.sessionKey.trim()||"main",s=ub(t.openTabs,n),a=pb(t.tabLastViewed),i={...t,sessionKey:n,openTabs:s,tabLastViewed:a,lastActiveSessionKey:t.lastActiveSessionKey?.trim()||n};e.settings=i,ab(i),i.theme!==e.theme&&(e.theme=i.theme,ns(e,So(i.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Ao(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&Je(e,{...e.settings,lastActiveSessionKey:n})}function pu(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),s=t.get("password"),a=t.get("session"),i=t.get("gatewayUrl");let o=!1;if(n!=null){const c=n.trim();c&&c!==e.settings.token&&Je(e,{...e.settings,token:c}),t.delete("token"),o=!0}if(s!=null){const c=s.trim();c&&(e.password=c),t.delete("password"),o=!0}if(a!=null){const c=a.trim();if(c){e.sessionKey=c;const u=c.toLowerCase(),f=u==="main"||u==="agent:main:main"||u.endsWith(":main")||e.settings.openTabs.includes(c)?e.settings.openTabs:[...e.settings.openTabs,c];Je(e,{...e.settings,sessionKey:c,lastActiveSessionKey:c,openTabs:f})}}if(i!=null){const c=i.trim();c&&c!==e.settings.gatewayUrl&&(e.pendingGatewayUrl=c),t.delete("gatewayUrl"),o=!0}if(!o)return;const l=new URL(window.location.href);l.search=t.toString(),window.history.replaceState({},"",l.toString())}function _o(e,t){const n=e.tab;if(n!==t&&(e.tab=t),n==="dashboards"&&t!=="dashboards"){const s=e;if(s.dashboardPreviousSessionKey&&s.activeDashboardId){const a=s.dashboardPreviousSessionKey;s.dashboardPreviousSessionKey=null,s.activeDashboardId=null,s.activeDashboardManifest=null,s.activeDashboardHtml=null,s.dashboardChatOpen=!1,e.sessionKey=a}}t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?fo(e):go(e),t==="logs"?mo(e):vo(e),t==="debug"?yo(e):bo(e),t==="mission-control"?eu(e):tu(e),ts(e),xo(e,t,!1)}function hu(e,t,n){db({nextTheme:t,applyTheme:()=>{e.theme=t,Je(e,{...e.settings,theme:t}),ns(e,So(t))},context:n,currentTheme:e.theme})}async function ts(e){if(e.tab==="overview"&&await Co(e),(e.tab==="today"||e.tab==="my-day")&&(await Ks(e),E(()=>Promise.resolve().then(()=>In),void 0,import.meta.url).then(async({loadTodayQueueResults:t})=>{e.todayQueueResults=await t(e)}).catch(()=>{})),e.tab==="work"&&await ru(e),e.tab==="workspaces"&&(await ra(e),E(()=>Promise.resolve().then(()=>pe),void 0,import.meta.url).then(async({loadAllTasksWithQueueStatus:t})=>{e.allTasks=await t(e)})),e.tab==="data"&&e.handleDataRefresh(),e.tab==="channels"&&await wu(e),e.tab==="instances"&&await $o(e),e.tab==="sessions"&&(await X(e),await It(e)),e.tab==="cron"&&await ca(e),e.tab==="skills"&&await es(e),e.tab==="nodes"&&(await na(e),await pt(e),await Ye(e),await wo(e)),e.tab==="chat"&&(await Ro(e),rn(e,!e.chatHasAutoScrolled)),e.tab==="options"){const t=e;typeof t.handleOptionsLoad=="function"&&await t.handleOptionsLoad()}if(e.tab==="trust"){const t=e,n=[];typeof t.handleTrustLoad=="function"&&n.push(t.handleTrustLoad()),n.push(Nt(t)),n.push(X(t)),await Promise.all(n)}if(e.tab==="guardrails"){const t=e;typeof t.handleGuardrailsLoad=="function"&&await t.handleGuardrailsLoad()}if(e.tab==="mission-control"){const t=e;typeof t.handleMissionControlRefresh=="function"&&await t.handleMissionControlRefresh()}if(e.tab==="setup"){const t=e;typeof t.handleLoadSetupChecklist=="function"&&t.handleLoadSetupChecklist()}if(e.tab==="dashboards"){const t=e;typeof t.handleDashboardsRefresh=="function"&&await t.handleDashboardsRefresh()}if(e.tab==="second-brain"){const t=e,n=t.secondBrainSubtab;n==="intel"?typeof t.handleIntelLoad=="function"&&await t.handleIntelLoad():n==="files"?typeof t.handleSecondBrainFileTreeRefresh=="function"&&await t.handleSecondBrainFileTreeRefresh():typeof t.handleSecondBrainRefresh=="function"&&await t.handleSecondBrainRefresh()}e.tab==="config"&&(await _c(e),await Ye(e)),e.tab==="debug"&&(await sa(e),e.eventLog=Sv()),e.tab==="logs"&&(e.logsAtBottom=!0,await ho(e,{reset:!0}),Ec(e,!0))}function fu(){if(typeof window>"u")return"";const e=window.__OPENCLAW_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?Zs(e):lm(window.location.pathname)}function gu(e){e.theme=e.settings.theme??"system",ns(e,So(e.theme))}function ns(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t==="dark"?"dark":"light",t==="lifetrack"?du():uu()}function mu(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"&&ns(e,n.matches?"dark":"lifetrack")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function vu(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 yu(e,t){if(typeof window>"u")return;const n=dd(window.location.pathname,e.basePath)??"chat";To(e,n),xo(e,n,t)}function bu(e){if(typeof window>"u")return;const t=dd(window.location.pathname,e.basePath);if(!t)return;const s=new URL(window.location.href).searchParams.get("session")?.trim();if(s){e.sessionKey=s;const a=e.settings.openTabs.includes(s)?e.settings.openTabs:[...e.settings.openTabs,s];Je(e,{...e.settings,sessionKey:s,lastActiveSessionKey:s,openTabs:a})}To(e,t)}function To(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?fo(e):go(e),t==="logs"?mo(e):vo(e),t==="debug"?yo(e):bo(e),t==="mission-control"?eu(e):tu(e),e.connected&&ts(e)}function xo(e,t,n){if(typeof window>"u")return;const s=Vn(to(t,e.basePath)),a=Vn(window.location.pathname),i=new URL(window.location.href);t==="chat"&&e.sessionKey?i.searchParams.set("session",e.sessionKey):i.searchParams.delete("session"),a!==s&&(i.pathname=s),n?window.history.replaceState({},"",i.toString()):window.history.pushState({},"",i.toString())}function ve(e,t,n){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.set("session",t),n?window.history.replaceState({},"",s.toString()):window.history.pushState({},"",s.toString())}async function Co(e){await Promise.all([Me(e,!1),$o(e),X(e),Zn(e),sa(e)])}async function wu(e){await Promise.all([Me(e,!0),_c(e),Ye(e)])}async function ca(e){await Promise.all([Me(e,!1),Zn(e),aa(e)])}const hb=Object.freeze(Object.defineProperty({__proto__:null,applyResolvedTheme:ns,applySettings:Je,applySettingsFromUrl:pu,attachThemeListener:mu,detachThemeListener:vu,inferBasePath:fu,loadChannelsTab:wu,loadCron:ca,loadOverview:Co,onPopState:bu,refreshActiveTab:ts,setLastActiveSessionKey:Ao,setTab:_o,setTabFromRoute:To,setTheme:hu,syncTabWithLocation:yu,syncThemeWithSettings:gu,syncUrlWithSessionKey:ve,syncUrlWithTab:xo},Symbol.toStringTag,{value:"Module"}));function Ws(e){return e.chatSending||!!e.chatRunId}function $e(e,t){const n=t??e.sessionKey,s=e.chatMessage.trim();if(s)e.chatDrafts={...e.chatDrafts,[n]:s};else{const{[n]:a,...i}=e.chatDrafts;e.chatDrafts=i}}function Le(e,t){const n=t??e.sessionKey;e.chatMessage=e.chatDrafts[n]??""}function $u(e,t){const n=t??e.sessionKey,{[n]:s,...a}=e.chatDrafts;e.chatDrafts=a,n===e.sessionKey&&(e.chatMessage="")}function ku(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"}function fb(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/new"||n==="/reset"?!0:n.startsWith("/new ")||n.startsWith("/reset ")}async function Eo(e){e.connected&&(e.chatMessage="",await ao(e))}function gb(e,t,n){const s=t.trim(),a=!!(n&&n.length>0);if(!s&&!a)return;const i=Date.now();e.chatQueue=[...e.chatQueue,{id:ea(),text:s,createdAt:i,attachments:a?n?.map(l=>({...l})):void 0}];const o=[];if(s&&o.push({type:"text",text:s}),a&&n)for(const l of n)o.push({type:"image",source:{type:"base64",media_type:l.mimeType,data:l.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:o,timestamp:i}],rn(e,!0)}async function _i(e,t,n){Bi(e);const s=e;s.sessionKey&&s.workingSessions&&(s.workingSessions=new Set([...s.workingSessions,s.sessionKey])),n?.skipOptimisticUpdate||queueMicrotask(()=>{rn(e,!0)});const a=await so(e,t,n?.attachments,{skipOptimisticUpdate:n?.skipOptimisticUpdate});return!a&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!a&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),a&&(Ao(e,e.sessionKey),e.chatAttachments=[]),a&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),a&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),rn(e,!0),a&&!e.chatRunId&&Lo(e),a&&n?.refreshSessions&&(e.refreshSessionsAfterChat=!0),a}async function Lo(e){if(!e.connected||Ws(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await _i(e,t.text,{attachments:t.attachments,skipOptimisticUpdate:!0})||(e.chatQueue=[t,...e.chatQueue])}function Su(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function Au(e,t,n){if(!e.connected)return;const s=e.chatMessage,a=(t??e.chatMessage).trim(),i=e.chatAttachments??[],o=t==null?i:[],l=o.length>0;if(!a&&!l)return;if(ku(a)){await Eo(e);return}const c=fb(a);if(t==null&&(e.chatMessage="",$u(e)),n?.queue){gb(e,a,o),Ws(e)||await Lo(e);return}if(Ws(e)){await ao(e),await new Promise(u=>setTimeout(u,50)),await _i(e,a,{attachments:l?o:void 0,refreshSessions:c});return}await _i(e,a,{previousDraft:t==null?s:void 0,restoreDraft:!!(t&&n?.restoreDraft),attachments:l?o:void 0,previousAttachments:t==null?i:void 0,restoreAttachments:!!(t&&n?.restoreDraft),refreshSessions:c})}async function Ro(e){await Promise.all([ne(e),X(e,{activeMinutes:0}),qs(e)]),rn(e,!0)}const _u=Lo;function mb(e){const t=Cc(e.sessionKey);return t?.agentId?t.agentId:e.hello?.snapshot?.sessionDefaults?.defaultAgentId?.trim()||"main"}function vb(e,t){const n=Zs(e),s=encodeURIComponent(t);return n?`${n}/avatar/${s}?meta=1`:`/avatar/${s}?meta=1`}async function qs(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=mb(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=vb(e.basePath,t);try{const s=await fetch(n,{method:"GET"});if(!s.ok){e.chatAvatarUrl=null;return}const a=await s.json(),i=typeof a.avatarUrl=="string"?a.avatarUrl.trim():"";e.chatAvatarUrl=i||null}catch{e.chatAvatarUrl=null}}const ja=Object.freeze(Object.defineProperty({__proto__:null,clearDraft:$u,flushChatQueueForEvent:_u,handleAbortChat:Eo,handleSendChat:Au,isChatBusy:Ws,isChatStopCommand:ku,refreshChat:Ro,refreshChatAvatar:qs,removeQueuedMessage:Su,restoreDraft:Le,saveDraft:$e},Symbol.toStringTag,{value:"Module"})),yb={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},bb={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:""};const{I:wb}=Up,ul=e=>e,$b=e=>e.strings===void 0,pl=()=>document.createComment(""),Ln=(e,t,n)=>{const s=e._$AA.parentNode,a=t===void 0?e._$AB:t._$AA;if(n===void 0){const i=s.insertBefore(pl(),a),o=s.insertBefore(pl(),a);n=new wb(i,o,e,e.options)}else{const i=n._$AB.nextSibling,o=n._$AM,l=o!==e;if(l){let c;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==o._$AU&&n._$AP(c)}if(i!==a||l){let c=n._$AA;for(;c!==i;){const u=ul(c).nextSibling;ul(s).insertBefore(c,a),c=u}}}return n},vt=(e,t,n=e)=>(e._$AI(t,n),e),kb={},Sb=(e,t=kb)=>e._$AH=t,Ab=e=>e._$AH,Ha=e=>{e._$AR(),e._$AA.remove()};const hl=(e,t,n)=>{const s=new Map;for(let a=t;a<=n;a++)s.set(e[a],a);return s},da=zi(class extends Ki{constructor(e){if(super(e),e.type!==Ui.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,n){let s;n===void 0?n=t:t!==void 0&&(s=t);const a=[],i=[];let o=0;for(const l of e)a[o]=s?s(l,o):o,i[o]=n(l,o),o++;return{values:i,keys:a}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,s]){const a=Ab(e),{values:i,keys:o}=this.dt(t,n,s);if(!Array.isArray(a))return this.ut=o,i;const l=this.ut??=[],c=[];let u,p,f=0,m=a.length-1,g=0,$=i.length-1;for(;f<=m&&g<=$;)if(a[f]===null)f++;else if(a[m]===null)m--;else if(l[f]===o[g])c[g]=vt(a[f],i[g]),f++,g++;else if(l[m]===o[$])c[$]=vt(a[m],i[$]),m--,$--;else if(l[f]===o[$])c[$]=vt(a[f],i[$]),Ln(e,c[$+1],a[f]),f++,$--;else if(l[m]===o[g])c[g]=vt(a[m],i[g]),Ln(e,a[f],a[m]),m--,g++;else if(u===void 0&&(u=hl(o,g,$),p=hl(l,f,m)),u.has(l[f]))if(u.has(l[m])){const d=p.get(o[g]),v=d!==void 0?a[d]:null;if(v===null){const S=Ln(e,a[f]);vt(S,i[g]),c[g]=S}else c[g]=vt(v,i[g]),Ln(e,a[f],v),a[d]=null;g++}else Ha(a[m]),m--;else Ha(a[f]),f++;for(;g<=$;){const d=Ln(e,c[$+1]);vt(d,i[g]),c[g++]=d}for(;f<=m;){const d=a[f++];d!==null&&Ha(d)}return this.ut=o,Sb(e,c),dt}});function ua(e){$e(e);const n=`agent:main:webchat-${ea().slice(0,8)}`;e.applySettings({...e.settings,openTabs:[...e.settings.openTabs,n],sessionKey:n,lastActiveSessionKey:n,tabLastViewed:{...e.settings.tabLastViewed,[n]:Date.now()}}),e.sessionKey=n,e.chatMessage="",e.chatMessages=[],e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.loadAssistantIdentity(),ve(e,n,!0),ne(e)}function Tu(e,t){const n=to(t,e.basePath);return r`
721
721
  <a
722
722
  href=${n}
723
723
  class="nav-item ${e.tab===t?"active":""}"
724
724
  @click=${s=>{s.defaultPrevented||s.button!==0||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),e.setTab(t))}}
725
725
  title=${Gn(t)}
726
726
  >
727
- <span class="nav-item__emoji" aria-hidden="true">${dm(t)}</span>
727
+ <span class="nav-item__emoji" aria-hidden="true">${cm(t)}</span>
728
728
  <span class="nav-item__text">${Gn(t)}</span>
729
729
  </a>
730
- `}function Cu(e){const t=e.onboarding,n=e.onboarding,s=e.onboarding?!1:e.settings.chatShowThinking,a=e.onboarding?!0:e.settings.chatFocusMode,i=r`
730
+ `}function xu(e){const t=e.onboarding,n=e.onboarding,s=e.onboarding?!1:e.settings.chatShowThinking,a=e.onboarding?!0:e.settings.chatFocusMode,i=r`
731
731
  <svg
732
732
  width="18"
733
733
  height="18"
@@ -808,7 +808,7 @@ No details available.`,title:t.task,mimeType:"text/markdown"}}const Qt=Object.fr
808
808
  >
809
809
  ${H.folderOpen}
810
810
  </button>
811
- ${e.sessionPickerOpen?Eb(e):h}
811
+ ${e.sessionPickerOpen?xb(e):h}
812
812
  </div>
813
813
  <!-- Session search -->
814
814
  <div class="session-search-container">
@@ -821,7 +821,7 @@ No details available.`,title:t.task,mimeType:"text/markdown"}}const Qt=Object.fr
821
821
  >
822
822
  ${c}
823
823
  </button>
824
- ${e.sessionSearchOpen?Cb(e):h}
824
+ ${e.sessionSearchOpen?Tb(e):h}
825
825
  </div>
826
826
  <span class="chat-toolbar__separator"></span>
827
827
  <!-- Refresh button -->
@@ -886,7 +886,7 @@ No details available.`,title:t.task,mimeType:"text/markdown"}}const Qt=Object.fr
886
886
  ${H.minimize}
887
887
  </button>
888
888
  </div>
889
- `}function xb(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),s=new Date(n.getTime()-864e5);return{today:e.filter(a=>a.updatedAt&&new Date(a.updatedAt)>=n),yesterday:e.filter(a=>a.updatedAt&&new Date(a.updatedAt)>=s&&new Date(a.updatedAt)<n),older:e.filter(a=>!a.updatedAt||new Date(a.updatedAt)<s)}}let Va=null;function Cb(e){if(!e.client||!e.connected)return r`
889
+ `}function _b(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),s=new Date(n.getTime()-864e5);return{today:e.filter(a=>a.updatedAt&&new Date(a.updatedAt)>=n),yesterday:e.filter(a=>a.updatedAt&&new Date(a.updatedAt)>=s&&new Date(a.updatedAt)<n),older:e.filter(a=>!a.updatedAt||new Date(a.updatedAt)<s)}}let Va=null;function Tb(e){if(!e.client||!e.connected)return r`
890
890
  <div
891
891
  class="session-search-dropdown"
892
892
  style="top: ${e.sessionSearchPosition?.top??0}px; right: ${e.sessionSearchPosition?.right??0}px;"
@@ -937,7 +937,7 @@ No details available.`,title:t.task,mimeType:"text/markdown"}}const Qt=Object.fr
937
937
  `:e.sessionSearchResults.map(s)}
938
938
  </div>
939
939
  </div>
940
- `}function Eb(e){const t=(e.sessionPickerSearch??"").toLowerCase().trim();if(!e.client||!e.connected)return r`
940
+ `}function xb(e){const t=(e.sessionPickerSearch??"").toLowerCase().trim();if(!e.client||!e.connected)return r`
941
941
  <div
942
942
  class="session-picker-dropdown"
943
943
  style="top: ${e.sessionPickerPosition?.top??0}px; right: ${e.sessionPickerPosition?.right??0}px;"
@@ -955,7 +955,7 @@ No details available.`,title:t.task,mimeType:"text/markdown"}}const Qt=Object.fr
955
955
  <div class="session-picker-empty">Loading sessions...</div>
956
956
  </div>
957
957
  </div>
958
- `;let n=(e.sessionsResult?.sessions??[]).filter(m=>!e.settings.openTabs.includes(m.key));t&&(n=n.filter(m=>[m.label,m.displayName,m.key].filter(Boolean).some($=>$.toLowerCase().includes(t))));const s=50,a=n.length,i=n.slice(0,s),o=xb(i),l=m=>{e.sessionPickerOpen=!1,e.sessionPickerSearch="",$e(e),e.settings.openTabs.includes(m)?(e.sessionKey=m,e.applySettings({...e.settings,sessionKey:m,lastActiveSessionKey:m,tabLastViewed:{...e.settings.tabLastViewed,[m]:Date.now()}})):(e.applySettings({...e.settings,openTabs:[...e.settings.openTabs,m],sessionKey:m,lastActiveSessionKey:m,tabLastViewed:{...e.settings.tabLastViewed,[m]:Date.now()}}),e.sessionKey=m),Le(e,m),e.chatLoading=!0,e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.loadAssistantIdentity(),ve(e,m,!0),ne(e)},c=async(m,g)=>{if(m.stopPropagation(),!!window.confirm(`Delete session "${g}"?
958
+ `;let n=(e.sessionsResult?.sessions??[]).filter(m=>!e.settings.openTabs.includes(m.key));t&&(n=n.filter(m=>[m.label,m.displayName,m.key].filter(Boolean).some($=>$.toLowerCase().includes(t))));const s=50,a=n.length,i=n.slice(0,s),o=_b(i),l=m=>{e.sessionPickerOpen=!1,e.sessionPickerSearch="",$e(e),e.settings.openTabs.includes(m)?(e.sessionKey=m,e.applySettings({...e.settings,sessionKey:m,lastActiveSessionKey:m,tabLastViewed:{...e.settings.tabLastViewed,[m]:Date.now()}})):(e.applySettings({...e.settings,openTabs:[...e.settings.openTabs,m],sessionKey:m,lastActiveSessionKey:m,tabLastViewed:{...e.settings.tabLastViewed,[m]:Date.now()}}),e.sessionKey=m),Le(e,m),e.chatLoading=!0,e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.loadAssistantIdentity(),ve(e,m,!0),ne(e)},c=async(m,g)=>{if(m.stopPropagation(),!!window.confirm(`Delete session "${g}"?
959
959
 
960
960
  Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.sessions&&(e.sessionsResult={...e.sessionsResult,sessions:e.sessionsResult.sessions.filter(d=>d.key!==g)}),e.client&&e.connected))try{await e.client.request("sessions.delete",{key:g,deleteTranscript:!0}),X(e)}catch(d){console.error("Failed to delete session:",d),X(e)}},u=m=>r`
961
961
  <div class="session-picker-item" @click=${()=>l(m.key)}>
@@ -964,7 +964,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
964
964
  <div class="session-picker-item__name">${m.label??m.displayName??m.key}</div>
965
965
  </div>
966
966
  <div class="session-picker-item__actions">
967
- ${m.updatedAt?r`<span class="session-picker-item__time">${Sh(m.updatedAt)}</span>`:h}
967
+ ${m.updatedAt?r`<span class="session-picker-item__time">${kh(m.updatedAt)}</span>`:h}
968
968
  <button
969
969
  class="session-picker-item__close"
970
970
  @click=${g=>c(g,m.key)}
@@ -1011,7 +1011,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1011
1011
  `}
1012
1012
  </div>
1013
1013
  </div>
1014
- `}const Lb=["system","light","dark","lifetrack"];function Eu(e){const t=Math.max(0,Lb.indexOf(e.theme)),n=s=>a=>{const o={element:a.currentTarget};(a.clientX||a.clientY)&&(o.pointerClientX=a.clientX,o.pointerClientY=a.clientY),e.setTheme(s,o)};return r`
1014
+ `}const Cb=["system","light","dark","lifetrack"];function Cu(e){const t=Math.max(0,Cb.indexOf(e.theme)),n=s=>a=>{const o={element:a.currentTarget};(a.clientX||a.clientY)&&(o.pointerClientX=a.clientX,o.pointerClientY=a.clientY),e.setTheme(s,o)};return r`
1015
1015
  <div class="theme-toggle" style="--theme-index: ${t};">
1016
1016
  <div class="theme-toggle__track" role="group" aria-label="Theme">
1017
1017
  <span class="theme-toggle__indicator"></span>
@@ -1022,7 +1022,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1022
1022
  aria-label="System theme"
1023
1023
  title="System"
1024
1024
  >
1025
- ${Ib()}
1025
+ ${Rb()}
1026
1026
  </button>
1027
1027
  <button
1028
1028
  class="theme-toggle__button ${e.theme==="light"?"active":""}"
@@ -1031,7 +1031,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1031
1031
  aria-label="Light theme"
1032
1032
  title="Light"
1033
1033
  >
1034
- ${Rb()}
1034
+ ${Eb()}
1035
1035
  </button>
1036
1036
  <button
1037
1037
  class="theme-toggle__button ${e.theme==="dark"?"active":""}"
@@ -1040,7 +1040,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1040
1040
  aria-label="Dark theme"
1041
1041
  title="Dark"
1042
1042
  >
1043
- ${Pb()}
1043
+ ${Lb()}
1044
1044
  </button>
1045
1045
  <button
1046
1046
  class="theme-toggle__button ${e.theme==="lifetrack"?"active":""}"
@@ -1049,11 +1049,11 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1049
1049
  aria-label="Lifetrack theme"
1050
1050
  title="Lifetrack"
1051
1051
  >
1052
- ${Mb()}
1052
+ ${Pb()}
1053
1053
  </button>
1054
1054
  </div>
1055
1055
  </div>
1056
- `}function Rb(){return r`
1056
+ `}function Eb(){return r`
1057
1057
  <svg class="theme-icon" viewBox="0 0 24 24" aria-hidden="true">
1058
1058
  <circle cx="12" cy="12" r="4"></circle>
1059
1059
  <path d="M12 2v2"></path>
@@ -1065,24 +1065,24 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1065
1065
  <path d="m6.34 17.66-1.41 1.41"></path>
1066
1066
  <path d="m19.07 4.93-1.41 1.41"></path>
1067
1067
  </svg>
1068
- `}function Pb(){return r`
1068
+ `}function Lb(){return r`
1069
1069
  <svg class="theme-icon" viewBox="0 0 24 24" aria-hidden="true">
1070
1070
  <path
1071
1071
  d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"
1072
1072
  ></path>
1073
1073
  </svg>
1074
- `}function Ib(){return r`
1074
+ `}function Rb(){return r`
1075
1075
  <svg class="theme-icon" viewBox="0 0 24 24" aria-hidden="true">
1076
1076
  <rect width="20" height="14" x="2" y="3" rx="2"></rect>
1077
1077
  <line x1="8" x2="16" y1="21" y2="21"></line>
1078
1078
  <line x1="12" x2="12" y1="17" y2="21"></line>
1079
1079
  </svg>
1080
- `}function Mb(){return r`
1080
+ `}function Pb(){return r`
1081
1081
  <svg class="theme-icon" viewBox="0 0 24 24" aria-hidden="true">
1082
1082
  <path d="M12 3l1.5 5.5L19 10l-5.5 1.5L12 17l-1.5-5.5L5 10l5.5-1.5L12 3z"></path>
1083
1083
  <path d="M19 15l.67 2.33L22 18l-2.33.67L19 21l-.67-2.33L16 18l2.33-.67L19 15z"></path>
1084
1084
  </svg>
1085
- `}const at=Object.freeze(Object.defineProperty({__proto__:null,createNewSession:ua,renderChatControls:Cu,renderTab:xu,renderThemeToggle:Eu},Symbol.toStringTag,{value:"Module"})),Ga=new Set;function fl(e){if(!(!e.connected||!e.client||!e.settings.chatParallelView))for(const t of e.settings.parallelLanes){const n=t?.trim();if(!n)continue;const a=Ie(e.sessionsResult?.sessions,n)?.key??n;if(Ke.has(n)||Ke.has(a)||Ga.has(a))continue;Ga.add(a);const o=e.client;no(o,a).then(l=>{a!==n&&l.length>0&&Ke.set(n,l)}).finally(()=>{Ga.delete(a),e.applySettings({...e.settings})})}}function Db(e){e.basePath=gu(),e._urlSettingsApplied||(hu(e),e._urlSettingsApplied=!0),bu(e,!0),mu(e),vu(e),window.addEventListener("popstate",e.popStateHandler),e.keydownHandler=t=>{if(e.tab!=="chat")return;if((t.metaKey||t.ctrlKey)&&t.shiftKey&&t.key.toLowerCase()==="p"){t.preventDefault(),ua(e);return}if((t.metaKey||t.ctrlKey)&&t.shiftKey&&t.key.toLowerCase()==="h"){t.preventDefault(),e.handleConsciousnessFlush();return}if(!t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.key<"1"||t.key>"9")return;const n=parseInt(t.key,10)-1,s=e.settings.openTabs;if(n>=s.length)return;const a=s[n];a!==e.sessionKey&&(t.preventDefault(),$e(e),e.sessionKey=a,Le(e,a),e.chatLoading=!0,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:a,lastActiveSessionKey:a,tabLastViewed:{...e.settings.tabLastViewed,[a]:Date.now()}}),e.loadAssistantIdentity(),ve(e,a,!0),ne(e).then(()=>{Jd(e)}))},window.addEventListener("keydown",e.keydownHandler),po(e),e.tab==="nodes"&&fo(e),e.tab==="logs"&&mo(e),e.tab==="debug"&&yo(e)}function Ob(e){bh(e)}function Nb(e){window.removeEventListener("popstate",e.popStateHandler),window.removeEventListener("keydown",e.keydownHandler),e.sessionPickerClickOutsideHandler&&(document.removeEventListener("click",e.sessionPickerClickOutsideHandler,!0),e.sessionPickerClickOutsideHandler=null),e.sessionSearchClickOutsideHandler&&(document.removeEventListener("click",e.sessionSearchClickOutsideHandler,!0),e.sessionSearchClickOutsideHandler=null),go(e),vo(e),bo(e),yu(e),e.topbarObserver?.disconnect(),e.topbarObserver=null}function Ie(e,t){if(!e||!t)return;const n=e.find(o=>o.key===t);if(n)return n;const s=t.split(":"),a=s[s.length-1];if(a&&a.length>=4){const o=e.find(l=>l.key.includes(a));if(o)return o}const i=t.replace(/^webchat:/,"");if(i!==t){const o=e.find(l=>l.key.endsWith(i)||l.key.includes(i));if(o)return o}}function Fb(e,t){if(!t||t.length===0)return;const n=c=>{const u=c.toLowerCase();return u==="main"||u==="agent:main:main"||u.endsWith(":main")},s=(c,u)=>{const p=c?.sessionId?.trim();if(p)return`session:${p}`;if(c){const m=[c.kind,c.surface,c.subject,c.room,c.space,c.label,c.displayName].map(g=>String(g??"").trim().toLowerCase()).join("|");if(m.replace(/\|/g,"").length>0)return`meta:${m}`}return`key:${u}`};let a=!1;const i=new Map,o=[];for(const c of e.settings.openTabs){const u=c.trim();if(!u){a=!0;continue}if(n(u)){a=!0;continue}const p=Ie(t,u),f=p?.key??u;f!==c&&(a=!0);const m=s(p,f);if(i.has(m)){a=!0;continue}i.set(m,f),o.push(f)}const l=o.length!==e.settings.openTabs.length;if(a||l){const c={};for(const[g,$]of Object.entries(e.settings.tabLastViewed)){const d=g.trim();if(!d||typeof $!="number"||!Number.isFinite($))continue;const v=Ie(t,d),S=s(v,v?.key??d),_=i.get(S)??v?.key??d;c[_]=Math.max(c[_]??0,$)}const u=Ie(t,e.sessionKey),p=s(u,u?.key??e.sessionKey.trim()),f=i.get(p)??u?.key??(e.sessionKey.trim()||o[0]||"main"),m=o.includes(f)?f:o[0]||"main";e.applySettings({...e.settings,openTabs:o,sessionKey:m,lastActiveSessionKey:m,tabLastViewed:c}),e.sessionKey!==m&&(e.sessionKey=m)}}function Bb(e,t){if((t.has("sessionsResult")||t.has("settings"))&&e.sessionsResult?.sessions&&Fb(e,e.sessionsResult.sessions),t.has("connected")&&t.get("connected")===!1&&e.connected&&e.settings.chatParallelView&&fl(e),t.has("settings")&&e.connected&&e.settings.chatParallelView){const n=t.get("settings"),s=n?!n.chatParallelView:!0,a=!n||n.parallelLanes.some((i,o)=>i!==e.settings.parallelLanes[o]);(s||a)&&fl(e)}if(t.has("sessionPickerOpen")&&(e.sessionPickerOpen?setTimeout(()=>{e.sessionPickerOpen&&(e.sessionPickerClickOutsideHandler=n=>{const s=n.target,a=s.closest(".session-picker-container"),i=s.closest(".session-picker-dropdown");!a&&!i&&(e.sessionPickerOpen=!1)},document.addEventListener("click",e.sessionPickerClickOutsideHandler,!0))},0):e.sessionPickerClickOutsideHandler&&(document.removeEventListener("click",e.sessionPickerClickOutsideHandler,!0),e.sessionPickerClickOutsideHandler=null)),t.has("sessionSearchOpen")&&(e.sessionSearchOpen?setTimeout(()=>{e.sessionSearchOpen&&(e.sessionSearchClickOutsideHandler=n=>{const s=n.target,a=s.closest(".session-search-container"),i=s.closest(".session-search-dropdown");!a&&!i&&(e.sessionSearchOpen=!1)},document.addEventListener("click",e.sessionSearchClickOutsideHandler,!0))},0):e.sessionSearchClickOutsideHandler&&(document.removeEventListener("click",e.sessionSearchClickOutsideHandler,!0),e.sessionSearchClickOutsideHandler=null)),t.has("connected")&&t.get("connected")===!1&&e.connected&&e.tab==="chat"&&!e.chatLoading&&ne(e).then(()=>{Jd(e)}),t.has("connected")&&t.get("connected")===!1&&e.connected&&e.tab!=="chat"&&ts(e),e.tab==="chat"&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),s=t.has("chatLoading")&&t.get("chatLoading")===!0&&!e.chatLoading;let a=!1;if(t.has("chatMessages")){const i=e.chatMessages;i[i.length-1]?.role==="user"&&(a=!0)}t.has("chatStream")&&(a=!1),(n||s)&&Lc(e),rn(e,n||s||a||!e.chatHasAutoScrolled)}e.tab==="logs"&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&Ec(e,t.has("tab")||t.has("logsAutoFollow"))}async function gl(e,t){return!1}async function Ub(e,t){return null}function ml(e){return e.charAt(0).toUpperCase()||"A"}function vl(e){if(!e)return"";const t=new Date(e),n=t.getHours(),s=t.getMinutes().toString().padStart(2,"0"),a=n>=12?"PM":"AM";return`${n%12||12}:${s} ${a}`}function zb(e){e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`}function Lu(e,t=80){return e.scrollHeight-e.scrollTop-e.clientHeight<t}function Ru(e){const t=e.querySelector(".ally-panel__messages");t&&(t.scrollTop=t.scrollHeight)}const yl=new WeakMap;function Kb(e){requestAnimationFrame(()=>{const t=document.querySelector(".ally-panel, .ally-inline");if(!t)return;const n=t.querySelector(".ally-panel__messages");if(!n)return;const s=yl.get(n)??{lastMsgCount:0,lastStreamLen:0},a=e.messages.length,i=e.stream?.length??0,o=a!==s.lastMsgCount||i>s.lastStreamLen;yl.set(n,{lastMsgCount:a,lastStreamLen:i}),o&&Lu(n,120)&&Ru(t)})}function Wb(e){const t=e.currentTarget,n=t.querySelector(".ally-jump-bottom");n&&n.classList.toggle("ally-jump-bottom--visible",!Lu(t))}function Pu(e,t){return e.allyAvatar?r`<img class=${t==="bubble"?"ally-bubble__avatar":"ally-panel__header-avatar"} src=${e.allyAvatar} alt=${e.allyName} />`:t==="header"?r`<span class="ally-panel__header-initial">${ml(e.allyName)}</span>`:r`${ml(e.allyName)}`}function bl(e){if(e.role==="assistant"&&e.content){const t=ye(e.content);return r`<div class="ally-msg__content chat-text">${ke(t)}</div>`}return r`<span class="ally-msg__content">${e.content}</span>`}function qb(e){return!e.actions||e.actions.length===0?h:r`
1085
+ `}const at=Object.freeze(Object.defineProperty({__proto__:null,createNewSession:ua,renderChatControls:xu,renderTab:Tu,renderThemeToggle:Cu},Symbol.toStringTag,{value:"Module"})),Ga=new Set;function fl(e){if(!(!e.connected||!e.client||!e.settings.chatParallelView))for(const t of e.settings.parallelLanes){const n=t?.trim();if(!n)continue;const a=Ie(e.sessionsResult?.sessions,n)?.key??n;if(Ke.has(n)||Ke.has(a)||Ga.has(a))continue;Ga.add(a);const o=e.client;no(o,a).then(l=>{a!==n&&l.length>0&&Ke.set(n,l)}).finally(()=>{Ga.delete(a),e.applySettings({...e.settings})})}}function Ib(e){e.basePath=fu(),e._urlSettingsApplied||(pu(e),e._urlSettingsApplied=!0),yu(e,!0),gu(e),mu(e),window.addEventListener("popstate",e.popStateHandler),e.keydownHandler=t=>{if(e.tab!=="chat")return;if((t.metaKey||t.ctrlKey)&&t.shiftKey&&t.key.toLowerCase()==="p"){t.preventDefault(),ua(e);return}if((t.metaKey||t.ctrlKey)&&t.shiftKey&&t.key.toLowerCase()==="h"){t.preventDefault(),e.handleConsciousnessFlush();return}if(!t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.key<"1"||t.key>"9")return;const n=parseInt(t.key,10)-1,s=e.settings.openTabs;if(n>=s.length)return;const a=s[n];a!==e.sessionKey&&(t.preventDefault(),$e(e),e.sessionKey=a,Le(e,a),e.chatLoading=!0,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:a,lastActiveSessionKey:a,tabLastViewed:{...e.settings.tabLastViewed,[a]:Date.now()}}),e.loadAssistantIdentity(),ve(e,a,!0),ne(e).then(()=>{Jd(e)}))},window.addEventListener("keydown",e.keydownHandler),po(e),e.tab==="nodes"&&fo(e),e.tab==="logs"&&mo(e),e.tab==="debug"&&yo(e)}function Mb(e){yh(e)}function Db(e){window.removeEventListener("popstate",e.popStateHandler),window.removeEventListener("keydown",e.keydownHandler),e.sessionPickerClickOutsideHandler&&(document.removeEventListener("click",e.sessionPickerClickOutsideHandler,!0),e.sessionPickerClickOutsideHandler=null),e.sessionSearchClickOutsideHandler&&(document.removeEventListener("click",e.sessionSearchClickOutsideHandler,!0),e.sessionSearchClickOutsideHandler=null),go(e),vo(e),bo(e),vu(e),e.topbarObserver?.disconnect(),e.topbarObserver=null}function Ie(e,t){if(!e||!t)return;const n=e.find(o=>o.key===t);if(n)return n;const s=t.split(":"),a=s[s.length-1];if(a&&a.length>=4){const o=e.find(l=>l.key.includes(a));if(o)return o}const i=t.replace(/^webchat:/,"");if(i!==t){const o=e.find(l=>l.key.endsWith(i)||l.key.includes(i));if(o)return o}}function Ob(e,t){if(!t||t.length===0)return;const n=c=>{const u=c.toLowerCase();return u==="main"||u==="agent:main:main"||u.endsWith(":main")},s=(c,u)=>{const p=c?.sessionId?.trim();if(p)return`session:${p}`;if(c){const m=[c.kind,c.surface,c.subject,c.room,c.space,c.label,c.displayName].map(g=>String(g??"").trim().toLowerCase()).join("|");if(m.replace(/\|/g,"").length>0)return`meta:${m}`}return`key:${u}`};let a=!1;const i=new Map,o=[];for(const c of e.settings.openTabs){const u=c.trim();if(!u){a=!0;continue}if(n(u)){a=!0;continue}const p=Ie(t,u),f=p?.key??u;f!==c&&(a=!0);const m=s(p,f);if(i.has(m)){a=!0;continue}i.set(m,f),o.push(f)}const l=o.length!==e.settings.openTabs.length;if(a||l){const c={};for(const[g,$]of Object.entries(e.settings.tabLastViewed)){const d=g.trim();if(!d||typeof $!="number"||!Number.isFinite($))continue;const v=Ie(t,d),S=s(v,v?.key??d),_=i.get(S)??v?.key??d;c[_]=Math.max(c[_]??0,$)}const u=Ie(t,e.sessionKey),p=s(u,u?.key??e.sessionKey.trim()),f=i.get(p)??u?.key??(e.sessionKey.trim()||o[0]||"main"),m=o.includes(f)?f:o[0]||"main";e.applySettings({...e.settings,openTabs:o,sessionKey:m,lastActiveSessionKey:m,tabLastViewed:c}),e.sessionKey!==m&&(e.sessionKey=m)}}function Nb(e,t){if((t.has("sessionsResult")||t.has("settings"))&&e.sessionsResult?.sessions&&Ob(e,e.sessionsResult.sessions),t.has("connected")&&t.get("connected")===!1&&e.connected&&e.settings.chatParallelView&&fl(e),t.has("settings")&&e.connected&&e.settings.chatParallelView){const n=t.get("settings"),s=n?!n.chatParallelView:!0,a=!n||n.parallelLanes.some((i,o)=>i!==e.settings.parallelLanes[o]);(s||a)&&fl(e)}if(t.has("sessionPickerOpen")&&(e.sessionPickerOpen?setTimeout(()=>{e.sessionPickerOpen&&(e.sessionPickerClickOutsideHandler=n=>{const s=n.target,a=s.closest(".session-picker-container"),i=s.closest(".session-picker-dropdown");!a&&!i&&(e.sessionPickerOpen=!1)},document.addEventListener("click",e.sessionPickerClickOutsideHandler,!0))},0):e.sessionPickerClickOutsideHandler&&(document.removeEventListener("click",e.sessionPickerClickOutsideHandler,!0),e.sessionPickerClickOutsideHandler=null)),t.has("sessionSearchOpen")&&(e.sessionSearchOpen?setTimeout(()=>{e.sessionSearchOpen&&(e.sessionSearchClickOutsideHandler=n=>{const s=n.target,a=s.closest(".session-search-container"),i=s.closest(".session-search-dropdown");!a&&!i&&(e.sessionSearchOpen=!1)},document.addEventListener("click",e.sessionSearchClickOutsideHandler,!0))},0):e.sessionSearchClickOutsideHandler&&(document.removeEventListener("click",e.sessionSearchClickOutsideHandler,!0),e.sessionSearchClickOutsideHandler=null)),t.has("connected")&&t.get("connected")===!1&&e.connected&&e.tab==="chat"&&!e.chatLoading&&ne(e).then(()=>{Jd(e)}),t.has("connected")&&t.get("connected")===!1&&e.connected&&e.tab!=="chat"&&ts(e),e.tab==="chat"&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),s=t.has("chatLoading")&&t.get("chatLoading")===!0&&!e.chatLoading;let a=!1;if(t.has("chatMessages")){const i=e.chatMessages;i[i.length-1]?.role==="user"&&(a=!0)}t.has("chatStream")&&(a=!1),(n||s)&&Lc(e),rn(e,n||s||a||!e.chatHasAutoScrolled)}e.tab==="logs"&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&Ec(e,t.has("tab")||t.has("logsAutoFollow"))}async function gl(e,t){return!1}async function Fb(e,t){return null}function ml(e){return e.charAt(0).toUpperCase()||"A"}function vl(e){if(!e)return"";const t=new Date(e),n=t.getHours(),s=t.getMinutes().toString().padStart(2,"0"),a=n>=12?"PM":"AM";return`${n%12||12}:${s} ${a}`}function Bb(e){e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`}function Eu(e,t=80){return e.scrollHeight-e.scrollTop-e.clientHeight<t}function Lu(e){const t=e.querySelector(".ally-panel__messages");t&&(t.scrollTop=t.scrollHeight)}const yl=new WeakMap;function Ub(e){requestAnimationFrame(()=>{const t=document.querySelector(".ally-panel, .ally-inline");if(!t)return;const n=t.querySelector(".ally-panel__messages");if(!n)return;const s=yl.get(n)??{lastMsgCount:0,lastStreamLen:0},a=e.messages.length,i=e.stream?.length??0,o=a!==s.lastMsgCount||i>s.lastStreamLen;yl.set(n,{lastMsgCount:a,lastStreamLen:i}),o&&Eu(n,120)&&Lu(t)})}function zb(e){const t=e.currentTarget,n=t.querySelector(".ally-jump-bottom");n&&n.classList.toggle("ally-jump-bottom--visible",!Eu(t))}function Ru(e,t){return e.allyAvatar?r`<img class=${t==="bubble"?"ally-bubble__avatar":"ally-panel__header-avatar"} src=${e.allyAvatar} alt=${e.allyName} />`:t==="header"?r`<span class="ally-panel__header-initial">${ml(e.allyName)}</span>`:r`${ml(e.allyName)}`}function bl(e){if(e.role==="assistant"&&e.content){const t=ye(e.content);return r`<div class="ally-msg__content chat-text">${ke(t)}</div>`}return r`<span class="ally-msg__content">${e.content}</span>`}function Kb(e){return!e.actions||e.actions.length===0?h:r`
1086
1086
  <div class="ally-msg__actions">
1087
1087
  ${e.actions.map(t=>r`
1088
1088
  <button
@@ -1096,10 +1096,10 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1096
1096
  </button>
1097
1097
  `)}
1098
1098
  </div>
1099
- `}function jb(e,t){if(e.isNotification)return r`
1099
+ `}function Wb(e,t){if(e.isNotification)return r`
1100
1100
  <div class="ally-msg ally-msg--notification" data-idx=${t}>
1101
1101
  ${bl(e)}
1102
- ${qb(e)}
1102
+ ${Kb(e)}
1103
1103
  ${e.timestamp?r`<div class="ally-msg__time">${vl(e.timestamp)}</div>`:h}
1104
1104
  </div>
1105
1105
  `;const n=e.role==="user"?"ally-msg--user":"ally-msg--assistant";return r`
@@ -1107,11 +1107,11 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1107
1107
  ${bl(e)}
1108
1108
  ${e.timestamp?r`<div class="ally-msg__time">${vl(e.timestamp)}</div>`:h}
1109
1109
  </div>
1110
- `}function Hb(e){if(!e)return h;const t=Qc(e);return r`
1110
+ `}function qb(e){if(!e)return h;const t=Qc(e);return r`
1111
1111
  <div class="ally-msg ally-msg--streaming">
1112
1112
  <div class="ally-msg__content chat-text">${ke(t)}</div>
1113
1113
  </div>
1114
- `}function Vb(e){return e.connected?(e.isWorking||e.sending)&&!e.stream?r`<div class="ally-panel__status ally-panel__status--working">Working...</div>`:h:r`<div class="ally-panel__status ally-panel__status--disconnected">Disconnected</div>`}function Gb(e,t){const n=e.clipboardData?.items;if(!n)return;const s=[];for(const a of Array.from(n)){if(!a.type.startsWith("image/"))continue;const i=a.getAsFile();if(!i)continue;e.preventDefault();const o=new FileReader,l=`paste-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;o.onload=()=>{const c=o.result;t.onAttachmentsChange([...t.attachments,{id:l,dataUrl:c,mimeType:i.type,fileName:i.name||"screenshot.png",status:"ready"}])},o.readAsDataURL(i),s.push({id:l,dataUrl:"",mimeType:i.type,fileName:i.name,status:"reading"})}s.length>0&&t.onAttachmentsChange([...t.attachments,...s])}function Qb(e){return e.attachments.length===0?h:r`
1114
+ `}function jb(e){return e.connected?(e.isWorking||e.sending)&&!e.stream?r`<div class="ally-panel__status ally-panel__status--working">Working...</div>`:h:r`<div class="ally-panel__status ally-panel__status--disconnected">Disconnected</div>`}function Hb(e,t){const n=e.clipboardData?.items;if(!n)return;const s=[];for(const a of Array.from(n)){if(!a.type.startsWith("image/"))continue;const i=a.getAsFile();if(!i)continue;e.preventDefault();const o=new FileReader,l=`paste-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;o.onload=()=>{const c=o.result;t.onAttachmentsChange([...t.attachments,{id:l,dataUrl:c,mimeType:i.type,fileName:i.name||"screenshot.png",status:"ready"}])},o.readAsDataURL(i),s.push({id:l,dataUrl:"",mimeType:i.type,fileName:i.name,status:"reading"})}s.length>0&&t.onAttachmentsChange([...t.attachments,...s])}function Vb(e){return e.attachments.length===0?h:r`
1115
1115
  <div class="ally-panel__attachments">
1116
1116
  ${e.attachments.map(t=>r`
1117
1117
  <div class="ally-panel__attachment">
@@ -1125,8 +1125,8 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1125
1125
  </div>
1126
1126
  `)}
1127
1127
  </div>
1128
- `}function Yb(e){const t=e.connected?`Message ${e.allyName}...`:"Reconnecting...",n=e.draft.trim()||e.attachments.length>0;return r`
1129
- ${Qb(e)}
1128
+ `}function Gb(e){const t=e.connected?`Message ${e.allyName}...`:"Reconnecting...",n=e.draft.trim()||e.attachments.length>0;return r`
1129
+ ${Vb(e)}
1130
1130
  <div class="ally-panel__input">
1131
1131
  <textarea
1132
1132
  class="ally-panel__textarea"
@@ -1134,8 +1134,8 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1134
1134
  ?disabled=${!e.connected||e.sending}
1135
1135
  placeholder=${t}
1136
1136
  rows="1"
1137
- @input=${s=>{const a=s.target;zb(a),e.onDraftChange(a.value)}}
1138
- @paste=${s=>Gb(s,e)}
1137
+ @input=${s=>{const a=s.target;Bb(a),e.onDraftChange(a.value)}}
1138
+ @paste=${s=>Hb(s,e)}
1139
1139
  @keydown=${s=>{s.key==="Enter"&&(s.isComposing||s.keyCode===229||s.shiftKey||e.connected&&(s.preventDefault(),e.onSend()))}}
1140
1140
  ></textarea>
1141
1141
  <button
@@ -1148,7 +1148,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1148
1148
  ${H.arrowUp}
1149
1149
  </button>
1150
1150
  </div>
1151
- `}function Jb(e){return r`
1151
+ `}function Qb(e){return r`
1152
1152
  <div class="ally-bubble">
1153
1153
  <button
1154
1154
  type="button"
@@ -1157,15 +1157,15 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1157
1157
  aria-label="Open ${e.allyName} chat"
1158
1158
  @click=${()=>e.onToggle()}
1159
1159
  >
1160
- ${Pu(e,"bubble")}
1160
+ ${Ru(e,"bubble")}
1161
1161
  ${e.isWorking?r`<span class="ally-bubble__working"></span>`:h}
1162
1162
  </button>
1163
1163
  ${e.unreadCount>0?r`<span class="ally-bubble__badge">${e.unreadCount>99?"99+":e.unreadCount}</span>`:h}
1164
1164
  </div>
1165
- `}function Iu(e){return Kb(e),r`
1165
+ `}function Pu(e){return Ub(e),r`
1166
1166
  <div class="ally-panel__header">
1167
1167
  <div class="ally-panel__header-left">
1168
- ${Pu(e,"header")}
1168
+ ${Ru(e,"header")}
1169
1169
  <span class="ally-panel__header-name">${e.allyName}</span>
1170
1170
  </div>
1171
1171
  <div class="ally-panel__header-actions">
@@ -1189,32 +1189,32 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1189
1189
  </div>
1190
1190
  </div>
1191
1191
 
1192
- ${Vb(e)}
1192
+ ${jb(e)}
1193
1193
 
1194
- <div class="ally-panel__messages" @scroll=${Wb}>
1194
+ <div class="ally-panel__messages" @scroll=${zb}>
1195
1195
  ${e.messages.length===0&&!e.stream?r`<div class="ally-panel__empty">
1196
1196
  Start a conversation with ${e.allyName}
1197
1197
  </div>`:h}
1198
- ${e.messages.map((t,n)=>jb(t,n))}
1199
- ${e.stream?Hb(e.stream):h}
1198
+ ${e.messages.map((t,n)=>Wb(t,n))}
1199
+ ${e.stream?qb(e.stream):h}
1200
1200
  <button
1201
1201
  type="button"
1202
1202
  class="ally-jump-bottom"
1203
1203
  title="Jump to latest"
1204
- @click=${t=>{const n=t.currentTarget.closest(".ally-panel, .ally-inline");n&&Ru(n)}}
1204
+ @click=${t=>{const n=t.currentTarget.closest(".ally-panel, .ally-inline");n&&Lu(n)}}
1205
1205
  >${H.chevronDown}</button>
1206
1206
  </div>
1207
1207
 
1208
- ${Yb(e)}
1209
- `}function Xb(e){return e.open?r`
1208
+ ${Gb(e)}
1209
+ `}function Yb(e){return e.open?r`
1210
1210
  <div class="ally-panel">
1211
- ${Iu(e)}
1211
+ ${Pu(e)}
1212
1212
  </div>
1213
- `:Jb(e)}function Zb(e){return e.open?r`
1213
+ `:Qb(e)}function Jb(e){return e.open?r`
1214
1214
  <div class="ally-inline">
1215
- ${Iu(e)}
1215
+ ${Pu(e)}
1216
1216
  </div>
1217
- `:h}function We(e){if(e)return Array.isArray(e.type)?e.type.filter(n=>n!=="null")[0]??e.type[0]:e.type}function Mu(e){if(!e)return"";if(e.default!==void 0)return e.default;switch(We(e)){case"object":return{};case"array":return[];case"boolean":return!1;case"number":case"integer":return 0;case"string":return"";default:return""}}function pa(e){return e.filter(t=>typeof t=="string").join(".")}function xe(e,t){const n=pa(e),s=t[n];if(s)return s;const a=n.split(".");for(const[i,o]of Object.entries(t)){if(!i.includes("*"))continue;const l=i.split(".");if(l.length!==a.length)continue;let c=!0;for(let u=0;u<a.length;u+=1)if(l[u]!=="*"&&l[u]!==a[u]){c=!1;break}if(c)return o}}function et(e){return e.replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function ew(e){const t=pa(e).toLowerCase();return t.includes("token")||t.includes("password")||t.includes("secret")||t.includes("apikey")||t.endsWith("key")}function sn(e){return typeof e=="string"?e:e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}const tw=new Set(["title","description","default","nullable"]);function nw(e){return Object.keys(e??{}).filter(n=>!tw.has(n)).length===0}function sw(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const Yn={chevronDown:r`
1217
+ `:h}function We(e){if(e)return Array.isArray(e.type)?e.type.filter(n=>n!=="null")[0]??e.type[0]:e.type}function Iu(e){if(!e)return"";if(e.default!==void 0)return e.default;switch(We(e)){case"object":return{};case"array":return[];case"boolean":return!1;case"number":case"integer":return 0;case"string":return"";default:return""}}function pa(e){return e.filter(t=>typeof t=="string").join(".")}function xe(e,t){const n=pa(e),s=t[n];if(s)return s;const a=n.split(".");for(const[i,o]of Object.entries(t)){if(!i.includes("*"))continue;const l=i.split(".");if(l.length!==a.length)continue;let c=!0;for(let u=0;u<a.length;u+=1)if(l[u]!=="*"&&l[u]!==a[u]){c=!1;break}if(c)return o}}function et(e){return e.replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function Xb(e){const t=pa(e).toLowerCase();return t.includes("token")||t.includes("password")||t.includes("secret")||t.includes("apikey")||t.endsWith("key")}function sn(e){return typeof e=="string"?e:e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}const Zb=new Set(["title","description","default","nullable"]);function ew(e){return Object.keys(e??{}).filter(n=>!Zb.has(n)).length===0}function tw(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const Yn={chevronDown:r`
1218
1218
  <svg
1219
1219
  viewBox="0 0 24 24"
1220
1220
  fill="none"
@@ -1309,7 +1309,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1309
1309
  `)}
1310
1310
  </div>
1311
1311
  </div>
1312
- `}return $l({...e,options:$,value:n??t.default})}if(u==="object")return iw(e);if(u==="array")return ow(e);if(u==="boolean"){const $=typeof n=="boolean"?n:typeof t.default=="boolean"?t.default:!1;return r`
1312
+ `}return $l({...e,options:$,value:n??t.default})}if(u==="object")return sw(e);if(u==="array")return aw(e);if(u==="boolean"){const $=typeof n=="boolean"?n:typeof t.default=="boolean"?t.default:!1;return r`
1313
1313
  <label class="cfg-toggle-row ${o?"disabled":""}">
1314
1314
  <div class="cfg-toggle-row__content">
1315
1315
  <span class="cfg-toggle-row__label">${f}</span>
@@ -1325,12 +1325,12 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1325
1325
  <span class="cfg-toggle__track"></span>
1326
1326
  </div>
1327
1327
  </label>
1328
- `}return u==="number"||u==="integer"?aw(e):u==="string"?wl({...e,inputType:"text"}):r`
1328
+ `}return u==="number"||u==="integer"?nw(e):u==="string"?wl({...e,inputType:"text"}):r`
1329
1329
  <div class="cfg-field cfg-field--error">
1330
1330
  <div class="cfg-field__label">${f}</div>
1331
1331
  <div class="cfg-field__error">Unsupported type: ${u}. Use Raw mode.</div>
1332
1332
  </div>
1333
- `}function wl(e){const{schema:t,value:n,path:s,hints:a,disabled:i,onPatch:o,inputType:l}=e,c=e.showLabel??!0,u=xe(s,a),p=u?.label??t.title??et(String(s.at(-1))),f=u?.help??t.description,m=u?.sensitive??ew(s),g=u?.placeholder??(m?"••••":t.default!==void 0?`Default: ${sn(t.default)}`:""),$=n??"";return r`
1333
+ `}function wl(e){const{schema:t,value:n,path:s,hints:a,disabled:i,onPatch:o,inputType:l}=e,c=e.showLabel??!0,u=xe(s,a),p=u?.label??t.title??et(String(s.at(-1))),f=u?.help??t.description,m=u?.sensitive??Xb(s),g=u?.placeholder??(m?"••••":t.default!==void 0?`Default: ${sn(t.default)}`:""),$=n??"";return r`
1334
1334
  <div class="cfg-field">
1335
1335
  ${c?r`<label class="cfg-field__label">${p}</label>`:h}
1336
1336
  ${f?r`<div class="cfg-field__help">${f}</div>`:h}
@@ -1355,7 +1355,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1355
1355
  `:h}
1356
1356
  </div>
1357
1357
  </div>
1358
- `}function aw(e){const{schema:t,value:n,path:s,hints:a,disabled:i,onPatch:o}=e,l=e.showLabel??!0,c=xe(s,a),u=c?.label??t.title??et(String(s.at(-1))),p=c?.help??t.description,f=n??t.default??"",m=typeof f=="number"?f:0;return r`
1358
+ `}function nw(e){const{schema:t,value:n,path:s,hints:a,disabled:i,onPatch:o}=e,l=e.showLabel??!0,c=xe(s,a),u=c?.label??t.title??et(String(s.at(-1))),p=c?.help??t.description,f=n??t.default??"",m=typeof f=="number"?f:0;return r`
1359
1359
  <div class="cfg-field">
1360
1360
  ${l?r`<label class="cfg-field__label">${u}</label>`:h}
1361
1361
  ${p?r`<div class="cfg-field__help">${p}</div>`:h}
@@ -1397,7 +1397,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1397
1397
  `)}
1398
1398
  </select>
1399
1399
  </div>
1400
- `}function iw(e){const{schema:t,value:n,path:s,hints:a,unsupported:i,disabled:o,onPatch:l}=e;e.showLabel;const c=xe(s,a),u=c?.label??t.title??et(String(s.at(-1))),p=c?.help??t.description,f=n??t.default,m=f&&typeof f=="object"&&!Array.isArray(f)?f:{},g=t.properties??{},d=Object.entries(g).toSorted((T,A)=>{const C=xe([...s,T[0]],a)?.order??0,L=xe([...s,A[0]],a)?.order??0;return C!==L?C-L:T[0].localeCompare(A[0])}),v=new Set(Object.keys(g)),S=t.additionalProperties,_=!!S&&typeof S=="object";return s.length===1?r`
1400
+ `}function sw(e){const{schema:t,value:n,path:s,hints:a,unsupported:i,disabled:o,onPatch:l}=e;e.showLabel;const c=xe(s,a),u=c?.label??t.title??et(String(s.at(-1))),p=c?.help??t.description,f=n??t.default,m=f&&typeof f=="object"&&!Array.isArray(f)?f:{},g=t.properties??{},d=Object.entries(g).toSorted((T,A)=>{const C=xe([...s,T[0]],a)?.order??0,L=xe([...s,A[0]],a)?.order??0;return C!==L?C-L:T[0].localeCompare(A[0])}),v=new Set(Object.keys(g)),S=t.additionalProperties,_=!!S&&typeof S=="object";return s.length===1?r`
1401
1401
  <div class="cfg-fields">
1402
1402
  ${d.map(([T,A])=>Xe({schema:A,value:m[T],path:[...s,T],hints:a,unsupported:i,disabled:o,onPatch:l}))}
1403
1403
  ${_?kl({schema:S,value:m,path:s,hints:a,unsupported:i,disabled:o,reservedKeys:v,onPatch:l}):h}
@@ -1414,7 +1414,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1414
1414
  ${_?kl({schema:S,value:m,path:s,hints:a,unsupported:i,disabled:o,reservedKeys:v,onPatch:l}):h}
1415
1415
  </div>
1416
1416
  </details>
1417
- `}function ow(e){const{schema:t,value:n,path:s,hints:a,unsupported:i,disabled:o,onPatch:l}=e,c=e.showLabel??!0,u=xe(s,a),p=u?.label??t.title??et(String(s.at(-1))),f=u?.help??t.description,m=Array.isArray(t.items)?t.items[0]:t.items;if(!m)return r`
1417
+ `}function aw(e){const{schema:t,value:n,path:s,hints:a,unsupported:i,disabled:o,onPatch:l}=e,c=e.showLabel??!0,u=xe(s,a),p=u?.label??t.title??et(String(s.at(-1))),f=u?.help??t.description,m=Array.isArray(t.items)?t.items[0]:t.items;if(!m)return r`
1418
1418
  <div class="cfg-field cfg-field--error">
1419
1419
  <div class="cfg-field__label">${p}</div>
1420
1420
  <div class="cfg-field__error">Unsupported array schema. Use Raw mode.</div>
@@ -1428,7 +1428,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1428
1428
  type="button"
1429
1429
  class="cfg-array__add"
1430
1430
  ?disabled=${o}
1431
- @click=${()=>{const $=[...g,Mu(m)];l(s,$)}}
1431
+ @click=${()=>{const $=[...g,Iu(m)];l(s,$)}}
1432
1432
  >
1433
1433
  <span class="cfg-array__add-icon">${Yn.plus}</span>
1434
1434
  Add
@@ -1462,7 +1462,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1462
1462
  </div>
1463
1463
  `}
1464
1464
  </div>
1465
- `}function kl(e){const{schema:t,value:n,path:s,hints:a,unsupported:i,disabled:o,reservedKeys:l,onPatch:c}=e,u=nw(t),p=Object.entries(n??{}).filter(([f])=>!l.has(f));return r`
1465
+ `}function kl(e){const{schema:t,value:n,path:s,hints:a,unsupported:i,disabled:o,reservedKeys:l,onPatch:c}=e,u=ew(t),p=Object.entries(n??{}).filter(([f])=>!l.has(f));return r`
1466
1466
  <div class="cfg-map">
1467
1467
  <div class="cfg-map__header">
1468
1468
  <span class="cfg-map__label">Custom entries</span>
@@ -1470,7 +1470,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1470
1470
  type="button"
1471
1471
  class="cfg-map__add"
1472
1472
  ?disabled=${o}
1473
- @click=${()=>{const f={...n};let m=1,g=`custom-${m}`;for(;g in f;)m+=1,g=`custom-${m}`;f[g]=u?{}:Mu(t),c(s,f)}}
1473
+ @click=${()=>{const f={...n};let m=1,g=`custom-${m}`;for(;g in f;)m+=1,g=`custom-${m}`;f[g]=u?{}:Iu(t),c(s,f)}}
1474
1474
  >
1475
1475
  <span class="cfg-map__add-icon">${Yn.plus}</span>
1476
1476
  Add Entry
@@ -1481,7 +1481,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1481
1481
  <div class="cfg-map__empty">No custom entries.</div>
1482
1482
  `:r`
1483
1483
  <div class="cfg-map__items">
1484
- ${p.map(([f,m])=>{const g=[...s,f],$=sw(m);return r`
1484
+ ${p.map(([f,m])=>{const g=[...s,f],$=tw(m);return r`
1485
1485
  <div class="cfg-map__item">
1486
1486
  <div class="cfg-map__item-key">
1487
1487
  <input
@@ -1706,11 +1706,11 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1706
1706
  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
1707
1707
  <polyline points="14 2 14 8 20 8"></polyline>
1708
1708
  </svg>
1709
- `},Po={env:{label:"Environment Variables",description:"Environment variables passed to the gateway process"},update:{label:"Updates",description:"Auto-update settings and release channel"},agents:{label:"Agents",description:"Agent configurations, models, and identities"},auth:{label:"Authentication",description:"API keys and authentication profiles"},channels:{label:"Channels",description:"Messaging channels (Telegram, Discord, Slack, etc.)"},messages:{label:"Messages",description:"Message handling and routing settings"},commands:{label:"Commands",description:"Custom slash commands"},hooks:{label:"Hooks",description:"Webhooks and event hooks"},skills:{label:"Skills",description:"Skill packs and capabilities"},tools:{label:"Tools",description:"Tool configurations (browser, search, etc.)"},gateway:{label:"Gateway",description:"Gateway server settings (port, auth, binding)"},wizard:{label:"Setup Wizard",description:"Setup wizard state and history"},meta:{label:"Metadata",description:"Gateway metadata and version information"},logging:{label:"Logging",description:"Log levels and output configuration"},browser:{label:"Browser",description:"Browser automation settings"},ui:{label:"UI",description:"User interface preferences"},models:{label:"Models",description:"AI model configurations and providers"},bindings:{label:"Bindings",description:"Key bindings and shortcuts"},broadcast:{label:"Broadcast",description:"Broadcast and notification settings"},audio:{label:"Audio",description:"Audio input/output settings"},session:{label:"Session",description:"Session management and persistence"},cron:{label:"Cron",description:"Scheduled tasks and automation"},web:{label:"Web",description:"Web server and API settings"},discovery:{label:"Discovery",description:"Service discovery and networking"},canvasHost:{label:"Canvas Host",description:"Canvas rendering and display"},talk:{label:"Talk",description:"Voice and speech settings"},plugins:{label:"Plugins",description:"Plugin management and extensions"},user:{label:"User Profile",description:"Your display name and avatar"}};function Al(e){return Sl[e]??Sl.default}function rw(e,t,n){if(!n)return!0;const s=n.toLowerCase(),a=Po[e];return e.toLowerCase().includes(s)||a&&(a.label.toLowerCase().includes(s)||a.description.toLowerCase().includes(s))?!0:Mn(t,s)}function Mn(e,t){if(e.title?.toLowerCase().includes(t)||e.description?.toLowerCase().includes(t)||e.enum?.some(s=>String(s).toLowerCase().includes(t)))return!0;if(e.properties){for(const[s,a]of Object.entries(e.properties))if(s.toLowerCase().includes(t)||Mn(a,t))return!0}if(e.items){const s=Array.isArray(e.items)?e.items:[e.items];for(const a of s)if(a&&Mn(a,t))return!0}if(e.additionalProperties&&typeof e.additionalProperties=="object"&&Mn(e.additionalProperties,t))return!0;const n=e.anyOf??e.oneOf??e.allOf;if(n){for(const s of n)if(s&&Mn(s,t))return!0}return!1}function lw(e){if(!e.schema)return r`
1709
+ `},Po={env:{label:"Environment Variables",description:"Environment variables passed to the gateway process"},update:{label:"Updates",description:"Auto-update settings and release channel"},agents:{label:"Agents",description:"Agent configurations, models, and identities"},auth:{label:"Authentication",description:"API keys and authentication profiles"},channels:{label:"Channels",description:"Messaging channels (Telegram, Discord, Slack, etc.)"},messages:{label:"Messages",description:"Message handling and routing settings"},commands:{label:"Commands",description:"Custom slash commands"},hooks:{label:"Hooks",description:"Webhooks and event hooks"},skills:{label:"Skills",description:"Skill packs and capabilities"},tools:{label:"Tools",description:"Tool configurations (browser, search, etc.)"},gateway:{label:"Gateway",description:"Gateway server settings (port, auth, binding)"},wizard:{label:"Setup Wizard",description:"Setup wizard state and history"},meta:{label:"Metadata",description:"Gateway metadata and version information"},logging:{label:"Logging",description:"Log levels and output configuration"},browser:{label:"Browser",description:"Browser automation settings"},ui:{label:"UI",description:"User interface preferences"},models:{label:"Models",description:"AI model configurations and providers"},bindings:{label:"Bindings",description:"Key bindings and shortcuts"},broadcast:{label:"Broadcast",description:"Broadcast and notification settings"},audio:{label:"Audio",description:"Audio input/output settings"},session:{label:"Session",description:"Session management and persistence"},cron:{label:"Cron",description:"Scheduled tasks and automation"},web:{label:"Web",description:"Web server and API settings"},discovery:{label:"Discovery",description:"Service discovery and networking"},canvasHost:{label:"Canvas Host",description:"Canvas rendering and display"},talk:{label:"Talk",description:"Voice and speech settings"},plugins:{label:"Plugins",description:"Plugin management and extensions"},user:{label:"User Profile",description:"Your display name and avatar"}};function Al(e){return Sl[e]??Sl.default}function iw(e,t,n){if(!n)return!0;const s=n.toLowerCase(),a=Po[e];return e.toLowerCase().includes(s)||a&&(a.label.toLowerCase().includes(s)||a.description.toLowerCase().includes(s))?!0:Mn(t,s)}function Mn(e,t){if(e.title?.toLowerCase().includes(t)||e.description?.toLowerCase().includes(t)||e.enum?.some(s=>String(s).toLowerCase().includes(t)))return!0;if(e.properties){for(const[s,a]of Object.entries(e.properties))if(s.toLowerCase().includes(t)||Mn(a,t))return!0}if(e.items){const s=Array.isArray(e.items)?e.items:[e.items];for(const a of s)if(a&&Mn(a,t))return!0}if(e.additionalProperties&&typeof e.additionalProperties=="object"&&Mn(e.additionalProperties,t))return!0;const n=e.anyOf??e.oneOf??e.allOf;if(n){for(const s of n)if(s&&Mn(s,t))return!0}return!1}function ow(e){if(!e.schema)return r`
1710
1710
  <div class="muted">Schema unavailable.</div>
1711
1711
  `;const t=e.schema,n=e.value??{};if(We(t)!=="object"||!t.properties)return r`
1712
1712
  <div class="callout danger">Unsupported schema. Use Raw.</div>
1713
- `;const s=new Set(e.unsupportedPaths??[]),a=t.properties,i=e.searchQuery??"",o=e.activeSection,l=e.activeSubsection??null,u=Object.entries(a).toSorted((f,m)=>{const g=xe([f[0]],e.uiHints)?.order??50,$=xe([m[0]],e.uiHints)?.order??50;return g!==$?g-$:f[0].localeCompare(m[0])}).filter(([f,m])=>!(o&&f!==o||i&&!rw(f,m,i)));let p=null;if(o&&l&&u.length===1){const f=u[0]?.[1];f&&We(f)==="object"&&f.properties&&f.properties[l]&&(p={sectionKey:o,subsectionKey:l,schema:f.properties[l]})}return u.length===0?r`
1713
+ `;const s=new Set(e.unsupportedPaths??[]),a=t.properties,i=e.searchQuery??"",o=e.activeSection,l=e.activeSubsection??null,u=Object.entries(a).toSorted((f,m)=>{const g=xe([f[0]],e.uiHints)?.order??50,$=xe([m[0]],e.uiHints)?.order??50;return g!==$?g-$:f[0].localeCompare(m[0])}).filter(([f,m])=>!(o&&f!==o||i&&!iw(f,m,i)));let p=null;if(o&&l&&u.length===1){const f=u[0]?.[1];f&&We(f)==="object"&&f.properties&&f.properties[l]&&(p={sectionKey:o,subsectionKey:l,schema:f.properties[l]})}return u.length===0?r`
1714
1714
  <div class="config-empty">
1715
1715
  <div class="config-empty__icon">${H.search}</div>
1716
1716
  <div class="config-empty__text">
@@ -1747,11 +1747,11 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1747
1747
  </section>
1748
1748
  `})}
1749
1749
  </div>
1750
- `}const cw=new Set(["title","description","default","nullable"]);function dw(e){return Object.keys(e??{}).filter(n=>!cw.has(n)).length===0}function Du(e){const t=e.filter(a=>a!=null),n=t.length!==e.length,s=[];for(const a of t)s.some(i=>Object.is(i,a))||s.push(a);return{enumValues:s,nullable:n}}function Ou(e){return!e||typeof e!="object"?{schema:null,unsupportedPaths:["<root>"]}:Fn(e,[])}function Fn(e,t){const n=new Set,s={...e},a=pa(t)||"<root>";if(e.anyOf||e.oneOf||e.allOf){const l=uw(e,t);return l||{schema:e,unsupportedPaths:[a]}}const i=Array.isArray(e.type)&&e.type.includes("null"),o=We(e)??(e.properties||e.additionalProperties?"object":void 0);if(s.type=o??e.type,s.nullable=i||e.nullable,s.enum){const{enumValues:l,nullable:c}=Du(s.enum);s.enum=l,c&&(s.nullable=!0),l.length===0&&n.add(a)}if(o==="object"){const l=e.properties??{},c={};for(const[u,p]of Object.entries(l)){const f=Fn(p,[...t,u]);f.schema&&(c[u]=f.schema);for(const m of f.unsupportedPaths)n.add(m)}if(s.properties=c,e.additionalProperties===!0)n.add(a);else if(e.additionalProperties===!1)s.additionalProperties=!1;else if(e.additionalProperties&&typeof e.additionalProperties=="object"&&!dw(e.additionalProperties)){const u=Fn(e.additionalProperties,[...t,"*"]);s.additionalProperties=u.schema??e.additionalProperties,u.unsupportedPaths.length>0&&n.add(a)}}else if(o==="array"){const l=Array.isArray(e.items)?e.items[0]:e.items;if(!l)n.add(a);else{const c=Fn(l,[...t,"*"]);s.items=c.schema??l,c.unsupportedPaths.length>0&&n.add(a)}}else o!=="string"&&o!=="number"&&o!=="integer"&&o!=="boolean"&&!s.enum&&n.add(a);return{schema:s,unsupportedPaths:Array.from(n)}}function uw(e,t){if(e.allOf)return null;const n=e.anyOf??e.oneOf;if(!n)return null;const s=[],a=[];let i=!1;for(const l of n){if(!l||typeof l!="object")return null;if(Array.isArray(l.enum)){const{enumValues:c,nullable:u}=Du(l.enum);s.push(...c),u&&(i=!0);continue}if("const"in l){if(l.const==null){i=!0;continue}s.push(l.const);continue}if(We(l)==="null"){i=!0;continue}a.push(l)}if(s.length>0&&a.length===0){const l=[];for(const c of s)l.some(u=>Object.is(u,c))||l.push(c);return{schema:{...e,enum:l,nullable:i,anyOf:void 0,oneOf:void 0,allOf:void 0},unsupportedPaths:[]}}if(a.length===1){const l=Fn(a[0],t);return l.schema&&(l.schema.nullable=i||l.schema.nullable),l}const o=new Set(["string","number","integer","boolean"]);return a.length>0&&s.length===0&&a.every(l=>l.type&&o.has(String(l.type)))?{schema:{...e,nullable:i},unsupportedPaths:[]}:null}function pw(e,t){let n=e;for(const s of t){if(!n)return null;const a=We(n);if(a==="object"){const i=n.properties??{};if(typeof s=="string"&&i[s]){n=i[s];continue}const o=n.additionalProperties;if(typeof s=="string"&&o&&typeof o=="object"){n=o;continue}return null}if(a==="array"){if(typeof s!="number")return null;n=(Array.isArray(n.items)?n.items[0]:n.items)??null;continue}return null}return n}function hw(e,t){const s=(e.channels??{})[t],a=e[t];return(s&&typeof s=="object"?s:null)??(a&&typeof a=="object"?a:null)??{}}function fw(e){const t=Ou(e.schema),n=t.schema;if(!n)return r`
1750
+ `}const rw=new Set(["title","description","default","nullable"]);function lw(e){return Object.keys(e??{}).filter(n=>!rw.has(n)).length===0}function Mu(e){const t=e.filter(a=>a!=null),n=t.length!==e.length,s=[];for(const a of t)s.some(i=>Object.is(i,a))||s.push(a);return{enumValues:s,nullable:n}}function Du(e){return!e||typeof e!="object"?{schema:null,unsupportedPaths:["<root>"]}:Fn(e,[])}function Fn(e,t){const n=new Set,s={...e},a=pa(t)||"<root>";if(e.anyOf||e.oneOf||e.allOf){const l=cw(e,t);return l||{schema:e,unsupportedPaths:[a]}}const i=Array.isArray(e.type)&&e.type.includes("null"),o=We(e)??(e.properties||e.additionalProperties?"object":void 0);if(s.type=o??e.type,s.nullable=i||e.nullable,s.enum){const{enumValues:l,nullable:c}=Mu(s.enum);s.enum=l,c&&(s.nullable=!0),l.length===0&&n.add(a)}if(o==="object"){const l=e.properties??{},c={};for(const[u,p]of Object.entries(l)){const f=Fn(p,[...t,u]);f.schema&&(c[u]=f.schema);for(const m of f.unsupportedPaths)n.add(m)}if(s.properties=c,e.additionalProperties===!0)n.add(a);else if(e.additionalProperties===!1)s.additionalProperties=!1;else if(e.additionalProperties&&typeof e.additionalProperties=="object"&&!lw(e.additionalProperties)){const u=Fn(e.additionalProperties,[...t,"*"]);s.additionalProperties=u.schema??e.additionalProperties,u.unsupportedPaths.length>0&&n.add(a)}}else if(o==="array"){const l=Array.isArray(e.items)?e.items[0]:e.items;if(!l)n.add(a);else{const c=Fn(l,[...t,"*"]);s.items=c.schema??l,c.unsupportedPaths.length>0&&n.add(a)}}else o!=="string"&&o!=="number"&&o!=="integer"&&o!=="boolean"&&!s.enum&&n.add(a);return{schema:s,unsupportedPaths:Array.from(n)}}function cw(e,t){if(e.allOf)return null;const n=e.anyOf??e.oneOf;if(!n)return null;const s=[],a=[];let i=!1;for(const l of n){if(!l||typeof l!="object")return null;if(Array.isArray(l.enum)){const{enumValues:c,nullable:u}=Mu(l.enum);s.push(...c),u&&(i=!0);continue}if("const"in l){if(l.const==null){i=!0;continue}s.push(l.const);continue}if(We(l)==="null"){i=!0;continue}a.push(l)}if(s.length>0&&a.length===0){const l=[];for(const c of s)l.some(u=>Object.is(u,c))||l.push(c);return{schema:{...e,enum:l,nullable:i,anyOf:void 0,oneOf:void 0,allOf:void 0},unsupportedPaths:[]}}if(a.length===1){const l=Fn(a[0],t);return l.schema&&(l.schema.nullable=i||l.schema.nullable),l}const o=new Set(["string","number","integer","boolean"]);return a.length>0&&s.length===0&&a.every(l=>l.type&&o.has(String(l.type)))?{schema:{...e,nullable:i},unsupportedPaths:[]}:null}function dw(e,t){let n=e;for(const s of t){if(!n)return null;const a=We(n);if(a==="object"){const i=n.properties??{};if(typeof s=="string"&&i[s]){n=i[s];continue}const o=n.additionalProperties;if(typeof s=="string"&&o&&typeof o=="object"){n=o;continue}return null}if(a==="array"){if(typeof s!="number")return null;n=(Array.isArray(n.items)?n.items[0]:n.items)??null;continue}return null}return n}function uw(e,t){const s=(e.channels??{})[t],a=e[t];return(s&&typeof s=="object"?s:null)??(a&&typeof a=="object"?a:null)??{}}function pw(e){const t=Du(e.schema),n=t.schema;if(!n)return r`
1751
1751
  <div class="callout danger">Schema unavailable. Use Raw.</div>
1752
- `;const s=pw(n,["channels",e.channelId]);if(!s)return r`
1752
+ `;const s=dw(n,["channels",e.channelId]);if(!s)return r`
1753
1753
  <div class="callout danger">Channel config schema unavailable.</div>
1754
- `;const a=e.configValue??{},i=hw(a,e.channelId);return r`
1754
+ `;const a=e.configValue??{},i=uw(a,e.channelId);return r`
1755
1755
  <div class="config-form">
1756
1756
  ${Xe({schema:s,value:i,path:["channels",e.channelId],hints:e.uiHints,unsupported:new Set(t.unsupportedPaths),disabled:e.disabled,showLabel:!1,onPatch:e.onPatch})}
1757
1757
  </div>
@@ -1759,7 +1759,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1759
1759
  <div style="margin-top: 16px;">
1760
1760
  ${n.configSchemaLoading?r`
1761
1761
  <div class="muted">Loading config schema…</div>
1762
- `:fw({channelId:t,configValue:n.configForm,schema:n.configSchema,uiHints:n.configUiHints,disabled:s,onPatch:n.onConfigPatch})}
1762
+ `:pw({channelId:t,configValue:n.configForm,schema:n.configSchema,uiHints:n.configUiHints,disabled:s,onPatch:n.onConfigPatch})}
1763
1763
  <div class="row" style="margin-top: 12px;">
1764
1764
  <button
1765
1765
  class="btn primary"
@@ -1777,7 +1777,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1777
1777
  </button>
1778
1778
  </div>
1779
1779
  </div>
1780
- `}function gw(e){const{props:t,discord:n,accountCountLabel:s}=e;return r`
1780
+ `}function hw(e){const{props:t,discord:n,accountCountLabel:s}=e;return r`
1781
1781
  <div class="card">
1782
1782
  <div class="card-title">Discord</div>
1783
1783
  <div class="card-sub">Bot status and channel configuration.</div>
@@ -1819,7 +1819,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1819
1819
  </button>
1820
1820
  </div>
1821
1821
  </div>
1822
- `}function mw(e){const{props:t,googleChat:n,accountCountLabel:s}=e;return r`
1822
+ `}function fw(e){const{props:t,googleChat:n,accountCountLabel:s}=e;return r`
1823
1823
  <div class="card">
1824
1824
  <div class="card-title">Google Chat</div>
1825
1825
  <div class="card-sub">Chat API webhook status and channel configuration.</div>
@@ -1871,7 +1871,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1871
1871
  </button>
1872
1872
  </div>
1873
1873
  </div>
1874
- `}function vw(e){const{props:t,imessage:n,accountCountLabel:s}=e;return r`
1874
+ `}function gw(e){const{props:t,imessage:n,accountCountLabel:s}=e;return r`
1875
1875
  <div class="card">
1876
1876
  <div class="card-title">iMessage</div>
1877
1877
  <div class="card-sub">macOS bridge status and channel configuration.</div>
@@ -1913,7 +1913,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1913
1913
  </button>
1914
1914
  </div>
1915
1915
  </div>
1916
- `}function _l(e){return e?e.length<=20?e:`${e.slice(0,8)}...${e.slice(-8)}`:"n/a"}function yw(e){const{props:t,nostr:n,nostrAccounts:s,accountCountLabel:a,profileFormState:i,profileFormCallbacks:o,onEditProfile:l}=e,c=s[0],u=n?.configured??c?.configured??!1,p=n?.running??c?.running??!1,f=n?.publicKey??c?.publicKey,m=n?.lastStartAt??c?.lastStartAt??null,g=n?.lastError??c?.lastError??null,$=s.length>1,d=i!=null,v=_=>{const T=_.publicKey,A=_.profile,C=A?.displayName??A?.name??_.name??_.accountId;return r`
1916
+ `}function _l(e){return e?e.length<=20?e:`${e.slice(0,8)}...${e.slice(-8)}`:"n/a"}function mw(e){const{props:t,nostr:n,nostrAccounts:s,accountCountLabel:a,profileFormState:i,profileFormCallbacks:o,onEditProfile:l}=e,c=s[0],u=n?.configured??c?.configured??!1,p=n?.running??c?.running??!1,f=n?.publicKey??c?.publicKey,m=n?.lastStartAt??c?.lastStartAt??null,g=n?.lastError??c?.lastError??null,$=s.length>1,d=i!=null,v=_=>{const T=_.publicKey,A=_.profile,C=A?.displayName??A?.name??_.name??_.accountId;return r`
1917
1917
  <div class="account-card">
1918
1918
  <div class="account-card-header">
1919
1919
  <div class="account-card-title">${C}</div>
@@ -1941,7 +1941,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1941
1941
  `:h}
1942
1942
  </div>
1943
1943
  </div>
1944
- `},S=()=>{if(d&&o)return th({state:i,callbacks:o,accountId:s[0]?.accountId??"default"});const _=c?.profile??n?.profile,{name:T,displayName:A,about:C,picture:L,nip05:P}=_??{},te=T||A||C||L||P;return r`
1944
+ `},S=()=>{if(d&&o)return eh({state:i,callbacks:o,accountId:s[0]?.accountId??"default"});const _=c?.profile??n?.profile,{name:T,displayName:A,about:C,picture:L,nip05:P}=_??{},te=T||A||C||L||P;return r`
1945
1945
  <div style="margin-top: 16px; padding: 12px; background: var(--bg-secondary); border-radius: 8px;">
1946
1946
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
1947
1947
  <div style="font-weight: 500;">Profile</div>
@@ -2021,7 +2021,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
2021
2021
  <button class="btn" @click=${()=>t.onRefresh(!1)}>Refresh</button>
2022
2022
  </div>
2023
2023
  </div>
2024
- `}function bw(e){if(!e&&e!==0)return"n/a";const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);return n<60?`${n}m`:`${Math.round(n/60)}h`}function ww(e,t){const n=t.snapshot,s=n?.channels;if(!n||!s)return!1;const a=s[e],i=typeof a?.configured=="boolean"&&a.configured,o=typeof a?.running=="boolean"&&a.running,l=typeof a?.connected=="boolean"&&a.connected,u=(n.channelAccounts?.[e]??[]).some(p=>p.configured||p.running||p.connected);return i||o||l||u}function $w(e,t){return t?.[e]?.length??0}function Nu(e,t){const n=$w(e,t);return n<2?h:r`<div class="account-count">Accounts (${n})</div>`}function kw(e){const{props:t,signal:n,accountCountLabel:s}=e;return r`
2024
+ `}function vw(e){if(!e&&e!==0)return"n/a";const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);return n<60?`${n}m`:`${Math.round(n/60)}h`}function yw(e,t){const n=t.snapshot,s=n?.channels;if(!n||!s)return!1;const a=s[e],i=typeof a?.configured=="boolean"&&a.configured,o=typeof a?.running=="boolean"&&a.running,l=typeof a?.connected=="boolean"&&a.connected,u=(n.channelAccounts?.[e]??[]).some(p=>p.configured||p.running||p.connected);return i||o||l||u}function bw(e,t){return t?.[e]?.length??0}function Ou(e,t){const n=bw(e,t);return n<2?h:r`<div class="account-count">Accounts (${n})</div>`}function ww(e){const{props:t,signal:n,accountCountLabel:s}=e;return r`
2025
2025
  <div class="card">
2026
2026
  <div class="card-title">Signal</div>
2027
2027
  <div class="card-sub">signal-cli status and channel configuration.</div>
@@ -2067,7 +2067,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
2067
2067
  </button>
2068
2068
  </div>
2069
2069
  </div>
2070
- `}function Sw(e){const{props:t,slack:n,accountCountLabel:s}=e;return r`
2070
+ `}function $w(e){const{props:t,slack:n,accountCountLabel:s}=e;return r`
2071
2071
  <div class="card">
2072
2072
  <div class="card-title">Slack</div>
2073
2073
  <div class="card-sub">Socket mode status and channel configuration.</div>
@@ -2109,7 +2109,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
2109
2109
  </button>
2110
2110
  </div>
2111
2111
  </div>
2112
- `}function Aw(e){const{props:t,telegram:n,telegramAccounts:s,accountCountLabel:a}=e,i=s.length>1,o=l=>{const u=l.probe?.bot?.username,p=l.name||l.accountId;return r`
2112
+ `}function kw(e){const{props:t,telegram:n,telegramAccounts:s,accountCountLabel:a}=e,i=s.length>1,o=l=>{const u=l.probe?.bot?.username,p=l.name||l.accountId;return r`
2113
2113
  <div class="account-card">
2114
2114
  <div class="account-card-header">
2115
2115
  <div class="account-card-title">
@@ -2189,7 +2189,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
2189
2189
  </button>
2190
2190
  </div>
2191
2191
  </div>
2192
- `}function _w(e){const{props:t,whatsapp:n,accountCountLabel:s}=e;return r`
2192
+ `}function Sw(e){const{props:t,whatsapp:n,accountCountLabel:s}=e;return r`
2193
2193
  <div class="card">
2194
2194
  <div class="card-title">WhatsApp</div>
2195
2195
  <div class="card-sub">Link WhatsApp Web and monitor connection health.</div>
@@ -2227,7 +2227,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
2227
2227
  <div>
2228
2228
  <span class="label">Auth age</span>
2229
2229
  <span>
2230
- ${n?.authAgeMs!=null?bw(n.authAgeMs):"n/a"}
2230
+ ${n?.authAgeMs!=null?vw(n.authAgeMs):"n/a"}
2231
2231
  </span>
2232
2232
  </div>
2233
2233
  </div>
@@ -2280,9 +2280,9 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
2280
2280
 
2281
2281
  ${tt({channelId:"whatsapp",props:t})}
2282
2282
  </div>
2283
- `}function Tw(e){const t=e.snapshot?.channels,n=t?.whatsapp??void 0,s=t?.telegram??void 0,a=t?.discord??null;t?.googlechat;const i=t?.slack??null,o=t?.signal??null,l=t?.imessage??null,c=t?.nostr??null,p=xw(e.snapshot).map((f,m)=>({key:f,enabled:ww(f,e),order:m})).toSorted((f,m)=>f.enabled!==m.enabled?f.enabled?-1:1:f.order-m.order);return r`
2283
+ `}function Aw(e){const t=e.snapshot?.channels,n=t?.whatsapp??void 0,s=t?.telegram??void 0,a=t?.discord??null;t?.googlechat;const i=t?.slack??null,o=t?.signal??null,l=t?.imessage??null,c=t?.nostr??null,p=_w(e.snapshot).map((f,m)=>({key:f,enabled:yw(f,e),order:m})).toSorted((f,m)=>f.enabled!==m.enabled?f.enabled?-1:1:f.order-m.order);return r`
2284
2284
  <section class="grid grid-cols-2">
2285
- ${p.map(f=>Cw(f.key,e,{whatsapp:n,telegram:s,discord:a,slack:i,signal:o,imessage:l,nostr:c,channelAccounts:e.snapshot?.channelAccounts??null}))}
2285
+ ${p.map(f=>Tw(f.key,e,{whatsapp:n,telegram:s,discord:a,slack:i,signal:o,imessage:l,nostr:c,channelAccounts:e.snapshot?.channelAccounts??null}))}
2286
2286
  </section>
2287
2287
 
2288
2288
  <section class="card" style="margin-top: 18px;">
@@ -2300,7 +2300,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
2300
2300
  ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2301
2301
  </pre>
2302
2302
  </section>
2303
- `}function xw(e){return e?.channelMeta?.length?e.channelMeta.map(t=>t.id):e?.channelOrder?.length?e.channelOrder:["whatsapp","telegram","discord","googlechat","slack","signal","imessage","nostr"]}function Cw(e,t,n){const s=Nu(e,n.channelAccounts);switch(e){case"whatsapp":return _w({props:t,whatsapp:n.whatsapp,accountCountLabel:s});case"telegram":return Aw({props:t,telegram:n.telegram,telegramAccounts:n.channelAccounts?.telegram??[],accountCountLabel:s});case"discord":return gw({props:t,discord:n.discord,accountCountLabel:s});case"googlechat":return mw({props:t,accountCountLabel:s});case"slack":return Sw({props:t,slack:n.slack,accountCountLabel:s});case"signal":return kw({props:t,signal:n.signal,accountCountLabel:s});case"imessage":return vw({props:t,imessage:n.imessage,accountCountLabel:s});case"nostr":{const a=n.channelAccounts?.nostr??[],i=a[0],o=i?.accountId??"default",l=i?.profile??null,c=t.nostrProfileAccountId===o?t.nostrProfileFormState:null,u=c?{onFieldChange:t.onNostrProfileFieldChange,onSave:t.onNostrProfileSave,onImport:t.onNostrProfileImport,onCancel:t.onNostrProfileCancel,onToggleAdvanced:t.onNostrProfileToggleAdvanced}:null;return yw({props:t,nostr:n.nostr,nostrAccounts:a,accountCountLabel:s,profileFormState:c,profileFormCallbacks:u,onEditProfile:()=>t.onNostrProfileEdit(o,l)})}default:return Ew(e,t,n.channelAccounts??{})}}function Ew(e,t,n){const s=Rw(t.snapshot,e),a=t.snapshot?.channels?.[e],i=typeof a?.configured=="boolean"?a.configured:void 0,o=typeof a?.running=="boolean"?a.running:void 0,l=typeof a?.connected=="boolean"?a.connected:void 0,c=typeof a?.lastError=="string"?a.lastError:void 0,u=n[e]??[],p=Nu(e,n);return r`
2303
+ `}function _w(e){return e?.channelMeta?.length?e.channelMeta.map(t=>t.id):e?.channelOrder?.length?e.channelOrder:["whatsapp","telegram","discord","googlechat","slack","signal","imessage","nostr"]}function Tw(e,t,n){const s=Ou(e,n.channelAccounts);switch(e){case"whatsapp":return Sw({props:t,whatsapp:n.whatsapp,accountCountLabel:s});case"telegram":return kw({props:t,telegram:n.telegram,telegramAccounts:n.channelAccounts?.telegram??[],accountCountLabel:s});case"discord":return hw({props:t,discord:n.discord,accountCountLabel:s});case"googlechat":return fw({props:t,accountCountLabel:s});case"slack":return $w({props:t,slack:n.slack,accountCountLabel:s});case"signal":return ww({props:t,signal:n.signal,accountCountLabel:s});case"imessage":return gw({props:t,imessage:n.imessage,accountCountLabel:s});case"nostr":{const a=n.channelAccounts?.nostr??[],i=a[0],o=i?.accountId??"default",l=i?.profile??null,c=t.nostrProfileAccountId===o?t.nostrProfileFormState:null,u=c?{onFieldChange:t.onNostrProfileFieldChange,onSave:t.onNostrProfileSave,onImport:t.onNostrProfileImport,onCancel:t.onNostrProfileCancel,onToggleAdvanced:t.onNostrProfileToggleAdvanced}:null;return mw({props:t,nostr:n.nostr,nostrAccounts:a,accountCountLabel:s,profileFormState:c,profileFormCallbacks:u,onEditProfile:()=>t.onNostrProfileEdit(o,l)})}default:return xw(e,t,n.channelAccounts??{})}}function xw(e,t,n){const s=Ew(t.snapshot,e),a=t.snapshot?.channels?.[e],i=typeof a?.configured=="boolean"?a.configured:void 0,o=typeof a?.running=="boolean"?a.running:void 0,l=typeof a?.connected=="boolean"?a.connected:void 0,c=typeof a?.lastError=="string"?a.lastError:void 0,u=n[e]??[],p=Ou(e,n);return r`
2304
2304
  <div class="card">
2305
2305
  <div class="card-title">${s}</div>
2306
2306
  <div class="card-sub">Channel status and configuration.</div>
@@ -2308,7 +2308,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2308
2308
 
2309
2309
  ${u.length>0?r`
2310
2310
  <div class="account-card-list">
2311
- ${u.map(f=>Dw(f))}
2311
+ ${u.map(f=>Iw(f))}
2312
2312
  </div>
2313
2313
  `:r`
2314
2314
  <div class="status-list" style="margin-top: 16px;">
@@ -2333,7 +2333,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2333
2333
 
2334
2334
  ${tt({channelId:e,props:t})}
2335
2335
  </div>
2336
- `}function Lw(e){return e?.channelMeta?.length?Object.fromEntries(e.channelMeta.map(t=>[t.id,t])):{}}function Rw(e,t){return Lw(e)[t]?.label??e?.channelLabels?.[t]??t}const Pw=600*1e3;function Fu(e){return e.lastInboundAt?Date.now()-e.lastInboundAt<Pw:!1}function Iw(e){return e.running?"Yes":Fu(e)?"Active":"No"}function Mw(e){return e.connected===!0?"Yes":e.connected===!1?"No":Fu(e)?"Active":"n/a"}function Dw(e){const t=Iw(e),n=Mw(e);return r`
2336
+ `}function Cw(e){return e?.channelMeta?.length?Object.fromEntries(e.channelMeta.map(t=>[t.id,t])):{}}function Ew(e,t){return Cw(e)[t]?.label??e?.channelLabels?.[t]??t}const Lw=600*1e3;function Nu(e){return e.lastInboundAt?Date.now()-e.lastInboundAt<Lw:!1}function Rw(e){return e.running?"Yes":Nu(e)?"Active":"No"}function Pw(e){return e.connected===!0?"Yes":e.connected===!1?"No":Nu(e)?"Active":"n/a"}function Iw(e){const t=Rw(e),n=Pw(e);return r`
2337
2337
  <div class="account-card">
2338
2338
  <div class="account-card-header">
2339
2339
  <div class="account-card-title">${e.name||e.accountId}</div>
@@ -2363,20 +2363,20 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2363
2363
  `:h}
2364
2364
  </div>
2365
2365
  </div>
2366
- `}const Bn=(e,t)=>{const n=e._$AN;if(n===void 0)return!1;for(const s of n)s._$AO?.(t,!1),Bn(s,t);return!0},js=e=>{let t,n;do{if((t=e._$AM)===void 0)break;n=t._$AN,n.delete(e),e=t}while(n?.size===0)},Bu=e=>{for(let t;t=e._$AM;e=t){let n=t._$AN;if(n===void 0)t._$AN=n=new Set;else if(n.has(e))break;n.add(e),Fw(t)}};function Ow(e){this._$AN!==void 0?(js(this),this._$AM=e,Bu(this)):this._$AM=e}function Nw(e,t=!1,n=0){const s=this._$AH,a=this._$AN;if(a!==void 0&&a.size!==0)if(t)if(Array.isArray(s))for(let i=n;i<s.length;i++)Bn(s[i],!1),js(s[i]);else s!=null&&(Bn(s,!1),js(s));else Bn(this,e)}const Fw=e=>{e.type==Ui.CHILD&&(e._$AP??=Nw,e._$AQ??=Ow)};class Bw extends Ki{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,n,s){super._$AT(t,n,s),Bu(this),this.isConnected=t._$AU}_$AO(t,n=!0){t!==this.isConnected&&(this.isConnected=t,t?this.reconnected?.():this.disconnected?.()),n&&(Bn(this,t),js(this))}setValue(t){if(Sb(this._$Ct))this._$Ct._$AI(t,this);else{const n=[...this._$Ct._$AH];n[this._$Ci]=t,this._$Ct._$AI(n,this,0)}}disconnected(){}reconnected(){}}const Qa=new WeakMap,Uw=zi(class extends Bw{render(e){return h}update(e,[t]){const n=t!==this.G;return n&&this.G!==void 0&&this.rt(void 0),(n||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),h}rt(e){if(this.isConnected||(e=void 0),typeof this.G=="function"){const t=this.ht??globalThis;let n=Qa.get(t);n===void 0&&(n=new WeakMap,Qa.set(t,n)),n.get(this.G)!==void 0&&this.G.call(this.ht,void 0),n.set(this.G,e),e!==void 0&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return typeof this.G=="function"?Qa.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function zw(e){return typeof e.content=="string"?e.content:typeof e.text=="string"?e.text:Array.isArray(e.content)?e.content.map(t=>typeof t.text=="string"?t.text:"").join(`
2367
- `):""}const Kw=["persistence protocol","core principles:","core behaviors","your role as prosper","be diligent first time","exhaust reasonable options","assume capability exists","elite executive assistant","consciousness context","working context","enforcement:","internal system context injected by godmode"];function Ww(e){const t=typeof e.role=="string"?e.role.toLowerCase():"";if(t!=="user"&&t!=="system")return!1;const n=zw(e).trim();if(!n)return!1;if(n.startsWith("Read HEARTBEAT.md")||n.startsWith("Read CONSCIOUSNESS.md")||/^System:\s*\[\d{4}-\d{2}-\d{2}/.test(n)||n==="NO_REPLY"||n.startsWith(`NO_REPLY
2366
+ `}const Bn=(e,t)=>{const n=e._$AN;if(n===void 0)return!1;for(const s of n)s._$AO?.(t,!1),Bn(s,t);return!0},js=e=>{let t,n;do{if((t=e._$AM)===void 0)break;n=t._$AN,n.delete(e),e=t}while(n?.size===0)},Fu=e=>{for(let t;t=e._$AM;e=t){let n=t._$AN;if(n===void 0)t._$AN=n=new Set;else if(n.has(e))break;n.add(e),Ow(t)}};function Mw(e){this._$AN!==void 0?(js(this),this._$AM=e,Fu(this)):this._$AM=e}function Dw(e,t=!1,n=0){const s=this._$AH,a=this._$AN;if(a!==void 0&&a.size!==0)if(t)if(Array.isArray(s))for(let i=n;i<s.length;i++)Bn(s[i],!1),js(s[i]);else s!=null&&(Bn(s,!1),js(s));else Bn(this,e)}const Ow=e=>{e.type==Ui.CHILD&&(e._$AP??=Dw,e._$AQ??=Mw)};class Nw extends Ki{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,n,s){super._$AT(t,n,s),Fu(this),this.isConnected=t._$AU}_$AO(t,n=!0){t!==this.isConnected&&(this.isConnected=t,t?this.reconnected?.():this.disconnected?.()),n&&(Bn(this,t),js(this))}setValue(t){if($b(this._$Ct))this._$Ct._$AI(t,this);else{const n=[...this._$Ct._$AH];n[this._$Ci]=t,this._$Ct._$AI(n,this,0)}}disconnected(){}reconnected(){}}const Qa=new WeakMap,Fw=zi(class extends Nw{render(e){return h}update(e,[t]){const n=t!==this.G;return n&&this.G!==void 0&&this.rt(void 0),(n||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),h}rt(e){if(this.isConnected||(e=void 0),typeof this.G=="function"){const t=this.ht??globalThis;let n=Qa.get(t);n===void 0&&(n=new WeakMap,Qa.set(t,n)),n.get(this.G)!==void 0&&this.G.call(this.ht,void 0),n.set(this.G,e),e!==void 0&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return typeof this.G=="function"?Qa.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function Bw(e){return typeof e.content=="string"?e.content:typeof e.text=="string"?e.text:Array.isArray(e.content)?e.content.map(t=>typeof t.text=="string"?t.text:"").join(`
2367
+ `):""}const Uw=["persistence protocol","core principles:","core behaviors","your role as prosper","be diligent first time","exhaust reasonable options","assume capability exists","elite executive assistant","consciousness context","working context","enforcement:","internal system context injected by godmode"];function zw(e){const t=typeof e.role=="string"?e.role.toLowerCase():"";if(t!=="user"&&t!=="system")return!1;const n=Bw(e).trim();if(!n)return!1;if(n.startsWith("Read HEARTBEAT.md")||n.startsWith("Read CONSCIOUSNESS.md")||/^System:\s*\[\d{4}-\d{2}-\d{2}/.test(n)||n==="NO_REPLY"||n.startsWith(`NO_REPLY
2368
2368
  `)||/^#\s*(?:🧠|Atlas Consciousness)/i.test(n)||n.startsWith("# WORKING.md")||n.startsWith("# MISTAKES.md")||/(?:VERIFIED|FIXED|NEW):\s/.test(n)&&/✅|🟡|☑/.test(n)&&n.length>300||/^###\s*(?:Onboarding Philosophy|Self-Surgery Problem|Open Architecture)/i.test(n)||/^\[GodMode Context:[^\]]*\]\s*$/.test(n)||/^You are resourceful and thorough\.\s*Your job is to GET THE JOB DONE/i.test(n)||/^##?\s*Persistence Protocol/i.test(n)||/^##?\s*Core (?:Behaviors|Principles)/i.test(n)||/^##?\s*Your Role as Prosper/i.test(n)||/^##\s*Your Team\s*\(Agent Roster\)/i.test(n)&&n.indexOf(`
2369
2369
 
2370
- ## `)===-1||/^\w+\s+\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(n)&&n.length>200||/^(?:ID\s+START\s+END\s+SUMMARY)/i.test(n))return!0;const s=n.toLowerCase();return Kw.filter(a=>s.includes(a)).length>=2}const Tl=25*1024*1024,xl=50*1024*1024,Cl=20;function Ya(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Io(e,t=0){const n=[],s=[];let a=t;const i=Array.from(e);for(const o of i){if(n.length>=Cl){s.push(`Maximum ${Cl} files allowed per upload`);break}if(o.size>Tl){s.push(`"${o.name}" is too large (${Ya(o.size)}). Max ${Ya(Tl)}. For larger files, mention the file path instead.`);continue}if(a+o.size>xl){s.push(`Total upload size exceeds ${Ya(xl)} limit`);break}a+=o.size,n.push(o)}return{validFiles:n,errors:s}}const qw=new Set(["md","markdown","mdx"]),jw=new Set(["htm","html"]),Hw=new Set(["avif","bmp","gif","heic","heif","jpeg","jpg","png","svg","svgz","webp"]);function Vw(e){const t=e.replaceAll("\\","/").trim();if(!t)return e;const n=t.split("/");return n[n.length-1]||t}function Gw(e){if(!e)return null;const n=e.trim().toLowerCase().split(".").pop()??"";return n?qw.has(n)?"text/markdown":jw.has(n)?"text/html":Hw.has(n)?n==="svg"||n==="svgz"?"image/svg+xml":n==="jpg"?"image/jpeg":`image/${n}`:n==="pdf"?"application/pdf":n==="json"||n==="json5"?"application/json":n==="txt"||n==="text"||n==="log"?"text/plain":null:null}function Uu(e){const t=e.mimeType?.split(";")[0]?.trim().toLowerCase()??"";if(t)return t;const n=e.content?.trim()??"";if(n.startsWith("data:image/")){const s=/^data:(image\/[^;]+);/i.exec(n);return s?.[1]?s[1].toLowerCase():"image/*"}return Gw(e.filePath??null)??"text/markdown"}function Qw(e){if(!e.startsWith("file://"))return null;let t=e.slice(7);return t.startsWith("/~/")&&(t="~"+t.slice(2)),decodeURIComponent(t)}function Yw(e,t){if(!t)return;const s=e.target.closest("a");if(!s)return;const a=s.getAttribute("href");if(!a)return;const i=Qw(a);i&&(e.preventDefault(),e.stopPropagation(),t(i))}function Jw(e){if(e.error)return r`
2370
+ ## `)===-1||/^\w+\s+\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(n)&&n.length>200||/^(?:ID\s+START\s+END\s+SUMMARY)/i.test(n))return!0;const s=n.toLowerCase();return Uw.filter(a=>s.includes(a)).length>=2}const Tl=25*1024*1024,xl=50*1024*1024,Cl=20;function Ya(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Io(e,t=0){const n=[],s=[];let a=t;const i=Array.from(e);for(const o of i){if(n.length>=Cl){s.push(`Maximum ${Cl} files allowed per upload`);break}if(o.size>Tl){s.push(`"${o.name}" is too large (${Ya(o.size)}). Max ${Ya(Tl)}. For larger files, mention the file path instead.`);continue}if(a+o.size>xl){s.push(`Total upload size exceeds ${Ya(xl)} limit`);break}a+=o.size,n.push(o)}return{validFiles:n,errors:s}}const Kw=new Set(["md","markdown","mdx"]),Ww=new Set(["htm","html"]),qw=new Set(["avif","bmp","gif","heic","heif","jpeg","jpg","png","svg","svgz","webp"]);function jw(e){const t=e.replaceAll("\\","/").trim();if(!t)return e;const n=t.split("/");return n[n.length-1]||t}function Hw(e){if(!e)return null;const n=e.trim().toLowerCase().split(".").pop()??"";return n?Kw.has(n)?"text/markdown":Ww.has(n)?"text/html":qw.has(n)?n==="svg"||n==="svgz"?"image/svg+xml":n==="jpg"?"image/jpeg":`image/${n}`:n==="pdf"?"application/pdf":n==="json"||n==="json5"?"application/json":n==="txt"||n==="text"||n==="log"?"text/plain":null:null}function Bu(e){const t=e.mimeType?.split(";")[0]?.trim().toLowerCase()??"";if(t)return t;const n=e.content?.trim()??"";if(n.startsWith("data:image/")){const s=/^data:(image\/[^;]+);/i.exec(n);return s?.[1]?s[1].toLowerCase():"image/*"}return Hw(e.filePath??null)??"text/markdown"}function Vw(e){if(!e.startsWith("file://"))return null;let t=e.slice(7);return t.startsWith("/~/")&&(t="~"+t.slice(2)),decodeURIComponent(t)}function Gw(e,t){if(!t)return;const s=e.target.closest("a");if(!s)return;const a=s.getAttribute("href");if(!a)return;const i=Vw(a);i&&(e.preventDefault(),e.stopPropagation(),t(i))}function Qw(e){if(e.error)return r`
2371
2371
  <div class="callout danger">${e.error}</div>
2372
2372
  <button @click=${e.onViewRawText} class="btn" style="margin-top: 12px;">
2373
2373
  View Raw Text
2374
2374
  </button>
2375
2375
  `;if(!e.content)return r`
2376
2376
  <div class="muted">No content available</div>
2377
- `;const t=Uu(e),n=e.content,s=n.trim();if(t.startsWith("image/"))return s.startsWith("data:image/")?r`
2377
+ `;const t=Bu(e),n=e.content,s=n.trim();if(t.startsWith("image/"))return s.startsWith("data:image/")?r`
2378
2378
  <div class="sidebar-image">
2379
- <img src=${s} alt=${Vw(e.filePath??"Image preview")} />
2379
+ <img src=${s} alt=${jw(e.filePath??"Image preview")} />
2380
2380
  </div>
2381
2381
  `:r`
2382
2382
  <div class="callout">
@@ -2398,10 +2398,10 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2398
2398
  src=${i}
2399
2399
  sandbox="allow-same-origin"
2400
2400
  @load=${o=>{URL.revokeObjectURL(i);const l=o.target;try{const c=l.contentDocument?.documentElement?.scrollHeight;c&&(l.style.height=`${c}px`)}catch{}}}
2401
- ></iframe>`}if(t==="text/markdown"||t==="text/x-markdown"){const a=Vf(n);return r`<div
2401
+ ></iframe>`}if(t==="text/markdown"||t==="text/x-markdown"){const a=Hf(n);return r`<div
2402
2402
  class="sidebar-markdown"
2403
- @click=${i=>Yw(i,e.onOpenFile)}
2404
- >${ke(ye(a))}</div>`}return r`<pre class="sidebar-plain">${n}</pre>`}function Xw(e){const t=Uu(e);return t==="text/html"||t==="application/xhtml+xml"}function Zw(e){const t=new Blob([e],{type:"text/html"}),n=URL.createObjectURL(t);window.open(n,"_blank","noopener,noreferrer")}function Ti(e){const t=e.title?.trim()||"Tool Output",n=Xw(e)&&e.content;return r`
2403
+ @click=${i=>Gw(i,e.onOpenFile)}
2404
+ >${ke(ye(a))}</div>`}return r`<pre class="sidebar-plain">${n}</pre>`}function Yw(e){const t=Bu(e);return t==="text/html"||t==="application/xhtml+xml"}function Jw(e){const t=new Blob([e],{type:"text/html"}),n=URL.createObjectURL(t);window.open(n,"_blank","noopener,noreferrer")}function Ti(e){const t=e.title?.trim()||"Tool Output",n=Yw(e)&&e.content;return r`
2405
2405
  <div class="sidebar-panel">
2406
2406
  <div class="sidebar-header">
2407
2407
  <div class="sidebar-title-wrap">
@@ -2432,16 +2432,16 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2432
2432
  ${n?r`<button
2433
2433
  class="btn sidebar-open-browser-btn"
2434
2434
  title="Open in browser tab"
2435
- @click=${()=>Zw(e.content)}
2435
+ @click=${()=>Jw(e.content)}
2436
2436
  >Open in Browser</button>`:h}
2437
2437
  <button @click=${e.onClose} class="btn" title="Close sidebar">
2438
2438
  ${H.x}
2439
2439
  </button>
2440
2440
  </div>
2441
2441
  </div>
2442
- <div class="sidebar-content">${Jw(e)}</div>
2442
+ <div class="sidebar-content">${Qw(e)}</div>
2443
2443
  </div>
2444
- `}var e$=Object.defineProperty,t$=Object.getOwnPropertyDescriptor,ss=(e,t,n,s)=>{for(var a=s>1?void 0:s?t$(t,n):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=(s?o(t,n,a):o(a))||a);return s&&a&&e$(t,n,a),a};let Ot=class extends nn{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.direction="horizontal",this.isDragging=!1,this.startPos=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startPos=this.direction==="vertical"?e.clientY: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=this.direction==="vertical",s=n?t.getBoundingClientRect().height:t.getBoundingClientRect().width,o=((n?e.clientY:e.clientX)-this.startPos)/s;let l=this.startRatio+o;l=Math.max(this.minRatio,Math.min(this.maxRatio,l)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:l},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 r``}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)}};Ot.styles=kp`
2444
+ `}var Xw=Object.defineProperty,Zw=Object.getOwnPropertyDescriptor,ss=(e,t,n,s)=>{for(var a=s>1?void 0:s?Zw(t,n):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=(s?o(t,n,a):o(a))||a);return s&&a&&Xw(t,n,a),a};let Dt=class extends nn{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.direction="horizontal",this.isDragging=!1,this.startPos=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startPos=this.direction==="vertical"?e.clientY: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=this.direction==="vertical",s=n?t.getBoundingClientRect().height:t.getBoundingClientRect().width,o=((n?e.clientY:e.clientX)-this.startPos)/s;let l=this.startRatio+o;l=Math.max(this.minRatio,Math.min(this.maxRatio,l)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:l},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 r``}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)}};Dt.styles=$p`
2445
2445
  :host {
2446
2446
  flex-shrink: 0;
2447
2447
  position: relative;
@@ -2487,7 +2487,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2487
2487
  :host(.dragging) {
2488
2488
  background: var(--accent, #007bff);
2489
2489
  }
2490
- `;ss([Jn({type:Number})],Ot.prototype,"splitRatio",2);ss([Jn({type:Number})],Ot.prototype,"minRatio",2);ss([Jn({type:Number})],Ot.prototype,"maxRatio",2);ss([Jn({type:String})],Ot.prototype,"direction",2);Ot=ss([kc("resizable-divider")],Ot);const n$=5e3;function s$(e){const t=(e??"").trim();if(!t||t==="/")return"/consciousness-icon.webp";const n=t.startsWith("/")?t:`/${t}`;return`${n.endsWith("/")?n.slice(0,-1):n}/consciousness-icon.webp`}function El(e){e.style.height="auto",e.style.height=`${e.scrollHeight}px`}function a$(e){const t=e.sessions?.sessions?.find(a=>a.key===e.sessionKey);if(!t)return null;const n=t.totalTokens??0,s=t.contextTokens??e.sessions?.defaults?.contextTokens??2e5;return s<=0?null:n/s}function i$(e){const t=a$(e);if(t===null)return h;const n=Math.round(t*100),s=n>=90?"danger":n>=70?"warn":"ok",a=e.sessions?.sessions?.find(l=>l.key===e.sessionKey),i=a?.totalTokens??0,o=a?.contextTokens??e.sessions?.defaults?.contextTokens??2e5;return r`
2490
+ `;ss([Jn({type:Number})],Dt.prototype,"splitRatio",2);ss([Jn({type:Number})],Dt.prototype,"minRatio",2);ss([Jn({type:Number})],Dt.prototype,"maxRatio",2);ss([Jn({type:String})],Dt.prototype,"direction",2);Dt=ss([kc("resizable-divider")],Dt);const e$=5e3;function t$(e){const t=(e??"").trim();if(!t||t==="/")return"/consciousness-icon.webp";const n=t.startsWith("/")?t:`/${t}`;return`${n.endsWith("/")?n.slice(0,-1):n}/consciousness-icon.webp`}function El(e){e.style.height="auto",e.style.height=`${e.scrollHeight}px`}function n$(e){const t=e.sessions?.sessions?.find(a=>a.key===e.sessionKey);if(!t)return null;const n=t.totalTokens??0,s=t.contextTokens??e.sessions?.defaults?.contextTokens??2e5;return s<=0?null:n/s}function s$(e){const t=n$(e);if(t===null)return h;const n=Math.round(t*100),s=n>=90?"danger":n>=70?"warn":"ok",a=e.sessions?.sessions?.find(l=>l.key===e.sessionKey),i=a?.totalTokens??0,o=a?.contextTokens??e.sessions?.defaults?.contextTokens??2e5;return r`
2491
2491
  <button
2492
2492
  type="button"
2493
2493
  class="chat-context-badge chat-context-badge--${s}"
@@ -2502,17 +2502,17 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2502
2502
  Click to compact
2503
2503
  </span>
2504
2504
  </button>
2505
- `}function o$(e){return e?e.active?r`
2505
+ `}function a$(e){return e?e.active?r`
2506
2506
  <div class="compaction-bar compaction-bar--active">
2507
2507
  <span class="compaction-bar__icon">${H.loader}</span>
2508
2508
  <span class="compaction-bar__text">Optimizing context...</span>
2509
2509
  </div>
2510
- `:e.completedAt&&Date.now()-e.completedAt<n$?r`
2510
+ `:e.completedAt&&Date.now()-e.completedAt<e$?r`
2511
2511
  <div class="compaction-bar compaction-bar--complete">
2512
2512
  <span class="compaction-bar__icon">${H.check}</span>
2513
2513
  <span class="compaction-bar__text">Context optimized</span>
2514
2514
  </div>
2515
- `:h:h}function Mo(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function r$(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}function l$(e,t){e.preventDefault(),e.stopPropagation(),t.classList.add("chat--drag-over")}function c$(e,t){e.preventDefault(),e.stopPropagation();const n=t.getBoundingClientRect();(e.clientX<=n.left||e.clientX>=n.right||e.clientY<=n.top||e.clientY>=n.bottom)&&t.classList.remove("chat--drag-over")}function d$(e,t){e.preventDefault(),e.stopPropagation(),e.currentTarget.classList.remove("chat--drag-over");const s=e.dataTransfer?.files;if(!s||s.length===0||!t.onAttachmentsChange)return;const a=t.attachments??[],i=a.reduce((p,f)=>p+(f.dataUrl?.length??0)*.75,0),{validFiles:o,errors:l}=Io(s,i);for(const p of l)t.showToast?.(p,"error");if(o.length===0)return;const c=[];let u=o.length;for(const p of o){const f=new FileReader;f.addEventListener("load",()=>{const m=f.result;c.push({id:Mo(),dataUrl:m,mimeType:p.type||"application/octet-stream",fileName:p.name}),u--,u===0&&t.onAttachmentsChange?.([...a,...c])}),f.addEventListener("error",()=>{t.showToast?.(`Failed to read "${p.name}"`,"error"),u--,u===0&&c.length>0&&t.onAttachmentsChange?.([...a,...c])}),f.readAsDataURL(p)}}function u$(e,t){const n=e.clipboardData?.items;if(!n||!t.onAttachmentsChange)return;const s=[];for(let p=0;p<n.length;p++){const f=n[p];if(f.type.startsWith("image/")){const m=f.getAsFile();m&&s.push(m)}}if(s.length===0)return;e.preventDefault();const a=t.attachments??[],i=a.reduce((p,f)=>p+(f.dataUrl?.length??0)*.75,0),{validFiles:o,errors:l}=Io(s,i);for(const p of l)t.showToast?.(p,"error");if(o.length===0)return;const c=[];let u=o.length;for(const p of o){const f=new FileReader;f.addEventListener("load",()=>{const m=f.result;c.push({id:Mo(),dataUrl:m,mimeType:p.type,fileName:p.name||"pasted-image"}),u--,u===0&&t.onAttachmentsChange?.([...a,...c])}),f.addEventListener("error",()=>{t.showToast?.("Failed to read pasted image","error"),u--,u===0&&c.length>0&&t.onAttachmentsChange?.([...a,...c])}),f.readAsDataURL(p)}}function p$(e,t){const n=e.target,s=n.files;if(!s||!t.onAttachmentsChange)return;const a=t.attachments??[],i=a.reduce((p,f)=>p+(f.dataUrl?.length??0)*.75,0),{validFiles:o,errors:l}=Io(s,i);for(const p of l)t.showToast?.(p,"error");if(o.length===0){n.value="";return}const c=[];let u=o.length;for(const p of o){const f=new FileReader;f.addEventListener("load",()=>{const m=f.result;c.push({id:Mo(),dataUrl:m,mimeType:p.type||"application/octet-stream",fileName:p.name}),u--,u===0&&t.onAttachmentsChange?.([...a,...c])}),f.addEventListener("error",()=>{t.showToast?.(`Failed to read "${p.name}"`,"error"),u--,u===0&&c.length>0&&t.onAttachmentsChange?.([...a,...c])}),f.readAsDataURL(p)}n.value=""}function h$(e){const t=e.attachments??[];return t.length===0?h:r`
2515
+ `:h:h}function Mo(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function i$(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}function o$(e,t){e.preventDefault(),e.stopPropagation(),t.classList.add("chat--drag-over")}function r$(e,t){e.preventDefault(),e.stopPropagation();const n=t.getBoundingClientRect();(e.clientX<=n.left||e.clientX>=n.right||e.clientY<=n.top||e.clientY>=n.bottom)&&t.classList.remove("chat--drag-over")}function l$(e,t){e.preventDefault(),e.stopPropagation(),e.currentTarget.classList.remove("chat--drag-over");const s=e.dataTransfer?.files;if(!s||s.length===0||!t.onAttachmentsChange)return;const a=t.attachments??[],i=a.reduce((p,f)=>p+(f.dataUrl?.length??0)*.75,0),{validFiles:o,errors:l}=Io(s,i);for(const p of l)t.showToast?.(p,"error");if(o.length===0)return;const c=[];let u=o.length;for(const p of o){const f=new FileReader;f.addEventListener("load",()=>{const m=f.result;c.push({id:Mo(),dataUrl:m,mimeType:p.type||"application/octet-stream",fileName:p.name}),u--,u===0&&t.onAttachmentsChange?.([...a,...c])}),f.addEventListener("error",()=>{t.showToast?.(`Failed to read "${p.name}"`,"error"),u--,u===0&&c.length>0&&t.onAttachmentsChange?.([...a,...c])}),f.readAsDataURL(p)}}function c$(e,t){const n=e.clipboardData?.items;if(!n||!t.onAttachmentsChange)return;const s=[];for(let p=0;p<n.length;p++){const f=n[p];if(f.type.startsWith("image/")){const m=f.getAsFile();m&&s.push(m)}}if(s.length===0)return;e.preventDefault();const a=t.attachments??[],i=a.reduce((p,f)=>p+(f.dataUrl?.length??0)*.75,0),{validFiles:o,errors:l}=Io(s,i);for(const p of l)t.showToast?.(p,"error");if(o.length===0)return;const c=[];let u=o.length;for(const p of o){const f=new FileReader;f.addEventListener("load",()=>{const m=f.result;c.push({id:Mo(),dataUrl:m,mimeType:p.type,fileName:p.name||"pasted-image"}),u--,u===0&&t.onAttachmentsChange?.([...a,...c])}),f.addEventListener("error",()=>{t.showToast?.("Failed to read pasted image","error"),u--,u===0&&c.length>0&&t.onAttachmentsChange?.([...a,...c])}),f.readAsDataURL(p)}}function d$(e,t){const n=e.target,s=n.files;if(!s||!t.onAttachmentsChange)return;const a=t.attachments??[],i=a.reduce((p,f)=>p+(f.dataUrl?.length??0)*.75,0),{validFiles:o,errors:l}=Io(s,i);for(const p of l)t.showToast?.(p,"error");if(o.length===0){n.value="";return}const c=[];let u=o.length;for(const p of o){const f=new FileReader;f.addEventListener("load",()=>{const m=f.result;c.push({id:Mo(),dataUrl:m,mimeType:p.type||"application/octet-stream",fileName:p.name}),u--,u===0&&t.onAttachmentsChange?.([...a,...c])}),f.addEventListener("error",()=>{t.showToast?.(`Failed to read "${p.name}"`,"error"),u--,u===0&&c.length>0&&t.onAttachmentsChange?.([...a,...c])}),f.readAsDataURL(p)}n.value=""}function u$(e){const t=e.attachments??[];return t.length===0?h:r`
2516
2516
  <div class="chat-attachments">
2517
2517
  ${t.map(n=>{const s=n.mimeType.startsWith("image/"),a=n.fileName||"file",i=a.length>40?a.slice(0,37)+"...":a;return r`
2518
2518
  <div class="chat-attachment ${s?"":"chat-attachment--file"}">
@@ -2531,33 +2531,33 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2531
2531
  </div>
2532
2532
  `})}
2533
2533
  </div>
2534
- `}function f$(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}function g$(e){const t=e.href;if(t){if(e.target==="_blank"){window.open(t,"_blank","noopener,noreferrer");return}window.location.assign(t)}}function m$(e){const t=e.trim();return!t||t.includes(`
2535
- `)?null:t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-z]:[\\/]/i.test(t)||/^[^:\s]+\/[^\s]+$/.test(t)&&/\.[a-z0-9]{1,12}$/i.test(t)||/^[^\s/\\:*?"<>|]+\.[a-z0-9]{1,12}$/i.test(t)&&t.length<=100?t:null}async function v$(e,t){const n=e.target,s=n instanceof Element?n:n instanceof Node?n.parentElement:null;if(!s||!t.onMessageLinkClick||!f$(e))return;const a=s.closest("a");if(a instanceof HTMLAnchorElement){if(a.hasAttribute("download"))return;const c=a.getAttribute("href");if(!c)return;try{const p=new URL(c,window.location.href);if(/^https?:$/.test(p.protocol)&&p.origin!==window.location.origin){e.preventDefault(),window.open(p.href,"_blank","noopener,noreferrer");return}}catch{}e.preventDefault(),await t.onMessageLinkClick(c)||g$(a);return}const i=s.closest("code");if(!(i instanceof HTMLElement))return;const o=(i.textContent??"").trim();if(/^https?:\/\/\S+$/i.test(o)){e.preventDefault(),window.open(o,"_blank","noopener,noreferrer");return}const l=m$(o);l&&(e.preventDefault(),await t.onMessageLinkClick(l))}function y$(e){const t=e.connected,n=e.sending||e.stream!==null;e.canAbort&&e.onAbort;const a=e.sessions?.sessions?.find(g=>g.key===e.sessionKey)?.reasoningLevel??"off",i=e.showThinking&&a!=="off",o={name:e.assistantName,avatar:e.assistantAvatar??e.assistantAvatarUrl??null},l=(e.attachments?.length??0)>0,c=e.connected?l?"Add a message or paste more images...":"Message (↩ to send, ⌘↩ to queue, Shift+↩ for line breaks)":"Connect to the gateway to start chatting…",u=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),f=s$(e.basePath),m=r`
2534
+ `}function p$(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}function h$(e){const t=e.href;if(t){if(e.target==="_blank"){window.open(t,"_blank","noopener,noreferrer");return}window.location.assign(t)}}function f$(e){const t=e.trim();return!t||t.includes(`
2535
+ `)?null:t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-z]:[\\/]/i.test(t)||/^[^:\s]+\/[^\s]+$/.test(t)&&/\.[a-z0-9]{1,12}$/i.test(t)||/^[^\s/\\:*?"<>|]+\.[a-z0-9]{1,12}$/i.test(t)&&t.length<=100?t:null}async function g$(e,t){const n=e.target,s=n instanceof Element?n:n instanceof Node?n.parentElement:null;if(!s||!t.onMessageLinkClick||!p$(e))return;const a=s.closest("a");if(a instanceof HTMLAnchorElement){if(a.hasAttribute("download"))return;const c=a.getAttribute("href");if(!c)return;try{const p=new URL(c,window.location.href);if(/^https?:$/.test(p.protocol)&&p.origin!==window.location.origin){e.preventDefault(),window.open(p.href,"_blank","noopener,noreferrer");return}}catch{}e.preventDefault(),await t.onMessageLinkClick(c)||h$(a);return}const i=s.closest("code");if(!(i instanceof HTMLElement))return;const o=(i.textContent??"").trim();if(/^https?:\/\/\S+$/i.test(o)){e.preventDefault(),window.open(o,"_blank","noopener,noreferrer");return}const l=f$(o);l&&(e.preventDefault(),await t.onMessageLinkClick(l))}function m$(e){const t=e.connected,n=e.sending||e.stream!==null;e.canAbort&&e.onAbort;const a=e.sessions?.sessions?.find(g=>g.key===e.sessionKey)?.reasoningLevel??"off",i=e.showThinking&&a!=="off",o={name:e.assistantName,avatar:e.assistantAvatar??e.assistantAvatarUrl??null},l=(e.attachments?.length??0)>0,c=e.connected?l?"Add a message or paste more images...":"Message (↩ to send, ⌘↩ to queue, Shift+↩ for line breaks)":"Connect to the gateway to start chatting…",u=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),f=t$(e.basePath),m=r`
2536
2536
  <div
2537
2537
  class="chat-thread"
2538
2538
  role="log"
2539
2539
  aria-live="polite"
2540
2540
  @scroll=${e.onChatScroll}
2541
- @click=${g=>{v$(g,e)}}
2541
+ @click=${g=>{g$(g,e)}}
2542
2542
  >
2543
2543
  ${e.loading?r`
2544
2544
  <div class="muted">Loading chat…</div>
2545
2545
  `:h}
2546
- ${da($$(e),g=>g.key,g=>{try{if(g.kind==="reading-indicator")return tm(o,e.currentToolInfo);if(g.kind==="stream")return nm(g.text,g.startedAt,e.onOpenSidebar,o,e.currentToolInfo);if(g.kind==="compaction-summary")return om(g.message);if(g.kind==="group"){const $=e.resolveImageUrl?(d,v)=>e.resolveImageUrl(d,v):void 0;return sm(g,{onOpenSidebar:e.onOpenSidebar,onOpenFile:e.onOpenFile,onPushToDrive:e.onPushToDrive,onImageClick:e.onImageClick,resolveImageUrl:$,showReasoning:i,assistantName:e.assistantName,assistantAvatar:o.avatar,userName:e.userName,userAvatar:e.userAvatar})}return h}catch($){return console.error("[chat] item render error:",$,g.key),h}})}
2546
+ ${da(b$(e),g=>g.key,g=>{try{if(g.kind==="reading-indicator")return em(o,e.currentToolInfo);if(g.kind==="stream")return tm(g.text,g.startedAt,e.onOpenSidebar,o,e.currentToolInfo);if(g.kind==="compaction-summary")return im(g.message);if(g.kind==="group"){const $=e.resolveImageUrl?(d,v)=>e.resolveImageUrl(d,v):void 0;return nm(g,{onOpenSidebar:e.onOpenSidebar,onOpenFile:e.onOpenFile,onPushToDrive:e.onPushToDrive,onImageClick:e.onImageClick,resolveImageUrl:$,showReasoning:i,assistantName:e.assistantName,assistantAvatar:o.avatar,userName:e.userName,userAvatar:e.userAvatar})}return h}catch($){return console.error("[chat] item render error:",$,g.key),h}})}
2547
2547
  </div>
2548
2548
  `;return r`
2549
2549
  <section
2550
2550
  class="card chat"
2551
- @dragover=${r$}
2552
- @dragenter=${g=>l$(g,g.currentTarget)}
2553
- @dragleave=${g=>c$(g,g.currentTarget)}
2554
- @drop=${g=>d$(g,e)}
2551
+ @dragover=${i$}
2552
+ @dragenter=${g=>o$(g,g.currentTarget)}
2553
+ @dragleave=${g=>r$(g,g.currentTarget)}
2554
+ @drop=${g=>l$(g,e)}
2555
2555
  >
2556
2556
  ${e.disabledReason?r`<div class="callout">${e.disabledReason}</div>`:h}
2557
2557
 
2558
2558
  ${e.error?r`<div class="callout danger">${e.error}</div>`:h}
2559
2559
 
2560
- ${o$(e.compactionStatus)}
2560
+ ${a$(e.compactionStatus)}
2561
2561
 
2562
2562
  ${e.pendingRetry&&e.onRetry?r`
2563
2563
  <div class="callout info chat-retry-banner">
@@ -2639,7 +2639,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2639
2639
  .maxRatio=${.8}
2640
2640
  ></resizable-divider>
2641
2641
  <div class="chat-sidebar-bottom">
2642
- ${Zb(e.allyProps)}
2642
+ ${Jb(e.allyProps)}
2643
2643
  </div>
2644
2644
  </div>
2645
2645
  `:r`
@@ -2680,24 +2680,24 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2680
2680
  id="chat-file-input"
2681
2681
  multiple
2682
2682
  style="display: none"
2683
- @change=${g=>p$(g,e)}
2683
+ @change=${g=>d$(g,e)}
2684
2684
  />
2685
- ${h$(e)}
2685
+ ${u$(e)}
2686
2686
 
2687
2687
  <div class="chat-compose__input-area">
2688
2688
  <textarea
2689
2689
  class="chat-compose__textarea"
2690
- ${Uw(g=>g&&El(g))}
2690
+ ${Fw(g=>g&&El(g))}
2691
2691
  .value=${e.draft}
2692
2692
  ?disabled=${!e.connected}
2693
2693
  @keydown=${g=>{if(g.key!=="Enter"||g.isComposing||g.keyCode===229||g.shiftKey||!e.connected)return;g.preventDefault();const $=g.ctrlKey||g.metaKey;t&&e.onSend($)}}
2694
2694
  @input=${g=>{const $=g.target;El($),e.onDraftChange($.value)}}
2695
- @paste=${g=>u$(g,e)}
2695
+ @paste=${g=>c$(g,e)}
2696
2696
  placeholder=${c}
2697
2697
  ></textarea>
2698
2698
 
2699
2699
  <div class="chat-compose__actions">
2700
- ${i$(e)}
2700
+ ${s$(e)}
2701
2701
 
2702
2702
  <button
2703
2703
  class="chat-compose__toolbar-btn"
@@ -2735,7 +2735,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2735
2735
  </div>
2736
2736
  </div>
2737
2737
  </section>
2738
- `}const Ll=200;function b$(e){const t=[];let n=null;for(const s of e){if(s.kind!=="message"){n&&(t.push(n),n=null),t.push(s);continue}const a=td(s.message),i=Zi(a.role),o=a.timestamp||Date.now();!n||n.role!==i?(n&&t.push(n),n={kind:"group",key:`group:${i}:${s.key}`,role:i,messages:[{message:s.message,key:s.key}],timestamp:o,isStreaming:!1}):n.messages.push({message:s.message,key:s.key})}return n&&t.push(n),t}function w$(e){const n=e.content;if(!Array.isArray(n))return!1;for(const s of n){if(typeof s!="object"||s===null)continue;const a=s;if(a.type==="image")return!0;if(Array.isArray(a.content)){for(const i of a.content)if(!(typeof i!="object"||i===null)&&i.type==="image")return!0}}return!1}function $$(e){const t=[],n=Array.isArray(e.messages)?e.messages:[],s=Array.isArray(e.toolMessages)?e.toolMessages:[],a=Math.max(0,n.length-Ll);a>0&&t.push({kind:"message",key:"chat:history:notice",message:{role:"system",content:`Showing last ${Ll} messages (${a} hidden).`,timestamp:Date.now()}});for(let i=a;i<n.length;i++){const o=n[i];if(o._chatIdx=i,rm(o)){t.push({kind:"compaction-summary",key:`compaction:${i}`,message:o});continue}if(Ww(o))continue;const l=td(o);!e.showThinking&&l.role.toLowerCase()==="toolresult"&&!w$(o)||t.push({kind:"message",key:Rl(o,i),message:o})}if(e.showThinking)for(let i=0;i<s.length;i++)t.push({kind:"message",key:Rl(s[i],i+n.length),message:s[i]});if(e.stream!==null){const i=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:i,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:i})}else if(e.isWorking){const i=`working:${e.sessionKey}`;t.push({kind:"reading-indicator",key:i})}else if(e.sending||e.canAbort){const i=`sending:${e.sessionKey}`;t.push({kind:"reading-indicator",key:i})}return b$(t)}function Rl(e,t){const n=e,s=typeof n.toolCallId=="string"?n.toolCallId:"";if(s)return`tool:${s}`;const a=typeof n.id=="string"?n.id:"";if(a)return`msg:${a}`;const i=typeof n.messageId=="string"?n.messageId:"";if(i)return`msg:${i}`;const o=typeof n.timestamp=="number"?n.timestamp:null,l=typeof n.role=="string"?n.role:"unknown";return o!=null?`msg:${l}:${o}:${t}`:`msg:${l}:${t}`}function k$(e,t=128){return new Promise((n,s)=>{const a=new Image;a.addEventListener("load",()=>{const i=document.createElement("canvas");i.width=t,i.height=t;const o=i.getContext("2d");if(!o){s(new Error("Could not get canvas context"));return}const l=Math.min(a.width,a.height),c=(a.width-l)/2,u=(a.height-l)/2;o.drawImage(a,c,u,l,l,0,0,t,t),n(i.toDataURL("image/png"))}),a.addEventListener("error",()=>s(new Error("Failed to load image"))),a.src=URL.createObjectURL(e)})}let Xt="",Dn=null,At=null,Pl=!1,it=!1;function S$(e){Pl||(Xt=e.userName||"",Dn=e.userAvatar||null,At=e.userAvatar||null,Pl=!0,it=!1)}function A$(e){S$(e);const t=c=>{Xt=c.target.value,it=!0},n=async c=>{const p=c.target.files?.[0];if(p){if(!p.type.startsWith("image/")){alert("Please select an image file");return}if(p.size>5*1024*1024){alert("Image must be less than 5MB");return}try{const f=await k$(p,128);Dn=f,At=f,it=!0,document.dispatchEvent(new CustomEvent("user-settings-updated"))}catch(f){console.error("Failed to process image:",f),alert("Failed to process image")}}},s=()=>{Dn=null,At=null,it=!0;const c=document.getElementById("user-avatar-input");c&&(c.value=""),document.dispatchEvent(new CustomEvent("user-settings-updated"))},a=()=>{e.onUpdate(Xt,Dn||""),it=!1;const c=document.querySelector(".user-settings__save");c&&(c.textContent="Saved!",setTimeout(()=>{c.textContent="Save"},1500))},i=()=>{Xt=e.userName||"",Dn=e.userAvatar||null,At=e.userAvatar||null,it=!1,document.dispatchEvent(new CustomEvent("user-settings-updated"))},o=Xt||"You",l=At?r`<img src="${At}" alt="${o}" class="user-settings__avatar-img" />`:r`<span class="user-settings__avatar-initial">${o.charAt(0).toUpperCase()}</span>`;return r`
2738
+ `}const Ll=200;function v$(e){const t=[];let n=null;for(const s of e){if(s.kind!=="message"){n&&(t.push(n),n=null),t.push(s);continue}const a=td(s.message),i=Zi(a.role),o=a.timestamp||Date.now();!n||n.role!==i?(n&&t.push(n),n={kind:"group",key:`group:${i}:${s.key}`,role:i,messages:[{message:s.message,key:s.key}],timestamp:o,isStreaming:!1}):n.messages.push({message:s.message,key:s.key})}return n&&t.push(n),t}function y$(e){const n=e.content;if(!Array.isArray(n))return!1;for(const s of n){if(typeof s!="object"||s===null)continue;const a=s;if(a.type==="image")return!0;if(Array.isArray(a.content)){for(const i of a.content)if(!(typeof i!="object"||i===null)&&i.type==="image")return!0}}return!1}function b$(e){const t=[],n=Array.isArray(e.messages)?e.messages:[],s=Array.isArray(e.toolMessages)?e.toolMessages:[],a=Math.max(0,n.length-Ll);a>0&&t.push({kind:"message",key:"chat:history:notice",message:{role:"system",content:`Showing last ${Ll} messages (${a} hidden).`,timestamp:Date.now()}});for(let i=a;i<n.length;i++){const o=n[i];if(o._chatIdx=i,om(o)){t.push({kind:"compaction-summary",key:`compaction:${i}`,message:o});continue}if(zw(o))continue;const l=td(o);!e.showThinking&&l.role.toLowerCase()==="toolresult"&&!y$(o)||t.push({kind:"message",key:Rl(o,i),message:o})}if(e.showThinking)for(let i=0;i<s.length;i++)t.push({kind:"message",key:Rl(s[i],i+n.length),message:s[i]});if(e.stream!==null){const i=`stream:${e.sessionKey}:${e.streamStartedAt??"live"}`;e.stream.trim().length>0?t.push({kind:"stream",key:i,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:i})}else if(e.isWorking){const i=`working:${e.sessionKey}`;t.push({kind:"reading-indicator",key:i})}else if(e.sending||e.canAbort){const i=`sending:${e.sessionKey}`;t.push({kind:"reading-indicator",key:i})}return v$(t)}function Rl(e,t){const n=e,s=typeof n.toolCallId=="string"?n.toolCallId:"";if(s)return`tool:${s}`;const a=typeof n.id=="string"?n.id:"";if(a)return`msg:${a}`;const i=typeof n.messageId=="string"?n.messageId:"";if(i)return`msg:${i}`;const o=typeof n.timestamp=="number"?n.timestamp:null,l=typeof n.role=="string"?n.role:"unknown";return o!=null?`msg:${l}:${o}:${t}`:`msg:${l}:${t}`}function w$(e,t=128){return new Promise((n,s)=>{const a=new Image;a.addEventListener("load",()=>{const i=document.createElement("canvas");i.width=t,i.height=t;const o=i.getContext("2d");if(!o){s(new Error("Could not get canvas context"));return}const l=Math.min(a.width,a.height),c=(a.width-l)/2,u=(a.height-l)/2;o.drawImage(a,c,u,l,l,0,0,t,t),n(i.toDataURL("image/png"))}),a.addEventListener("error",()=>s(new Error("Failed to load image"))),a.src=URL.createObjectURL(e)})}let Xt="",Dn=null,St=null,Pl=!1,it=!1;function $$(e){Pl||(Xt=e.userName||"",Dn=e.userAvatar||null,St=e.userAvatar||null,Pl=!0,it=!1)}function k$(e){$$(e);const t=c=>{Xt=c.target.value,it=!0},n=async c=>{const p=c.target.files?.[0];if(p){if(!p.type.startsWith("image/")){alert("Please select an image file");return}if(p.size>5*1024*1024){alert("Image must be less than 5MB");return}try{const f=await w$(p,128);Dn=f,St=f,it=!0,document.dispatchEvent(new CustomEvent("user-settings-updated"))}catch(f){console.error("Failed to process image:",f),alert("Failed to process image")}}},s=()=>{Dn=null,St=null,it=!0;const c=document.getElementById("user-avatar-input");c&&(c.value=""),document.dispatchEvent(new CustomEvent("user-settings-updated"))},a=()=>{e.onUpdate(Xt,Dn||""),it=!1;const c=document.querySelector(".user-settings__save");c&&(c.textContent="Saved!",setTimeout(()=>{c.textContent="Save"},1500))},i=()=>{Xt=e.userName||"",Dn=e.userAvatar||null,St=e.userAvatar||null,it=!1,document.dispatchEvent(new CustomEvent("user-settings-updated"))},o=Xt||"You",l=St?r`<img src="${St}" alt="${o}" class="user-settings__avatar-img" />`:r`<span class="user-settings__avatar-initial">${o.charAt(0).toUpperCase()}</span>`;return r`
2739
2739
  <div class="user-settings">
2740
2740
  <section class="config-section-card">
2741
2741
  <div class="config-section-card__header">
@@ -2774,7 +2774,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
2774
2774
  >
2775
2775
  Choose Image
2776
2776
  </button>
2777
- ${At?r`
2777
+ ${St?r`
2778
2778
  <button
2779
2779
  type="button"
2780
2780
  class="user-settings__btn user-settings__btn--clear"
@@ -3026,7 +3026,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3026
3026
  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
3027
3027
  <polyline points="14 2 14 8 20 8"></polyline>
3028
3028
  </svg>
3029
- `},Ja=[{key:"model",label:"AI Model"},{key:"env",label:"Environment"},{key:"update",label:"Updates"},{key:"agents",label:"Agents"},{key:"auth",label:"Authentication"},{key:"channels",label:"Channels"},{key:"messages",label:"Messages"},{key:"commands",label:"Commands"},{key:"hooks",label:"Hooks"},{key:"skills",label:"Skills"},{key:"tools",label:"Tools"},{key:"gateway",label:"Gateway"},{key:"wizard",label:"Setup Wizard"},{key:"user",label:"User"}],Il=new Set(["user","model"]),Ml="__all__";function Dl(e){return xi[e]??xi.default}function _$(e,t){const n=Po[e];return n||{label:t?.title??et(e),description:t?.description??""}}function T$(e){const{key:t,schema:n,uiHints:s}=e;if(!n||We(n)!=="object"||!n.properties)return[];const a=Object.entries(n.properties).map(([i,o])=>{const l=xe([t,i],s),c=l?.label??o.title??et(i),u=l?.help??o.description??"",p=l?.order??50;return{key:i,label:c,description:u,order:p}});return a.sort((i,o)=>i.order!==o.order?i.order-o.order:i.key.localeCompare(o.key)),a}function x$(e,t){if(!e||!t)return[];const n=[];function s(a,i,o){if(a===i)return;if(typeof a!=typeof i){n.push({path:o,from:a,to:i});return}if(typeof a!="object"||a===null||i===null){a!==i&&n.push({path:o,from:a,to:i});return}if(Array.isArray(a)&&Array.isArray(i)){JSON.stringify(a)!==JSON.stringify(i)&&n.push({path:o,from:a,to:i});return}const l=a,c=i,u=new Set([...Object.keys(l),...Object.keys(c)]);for(const p of u)s(l[p],c[p],o?`${o}.${p}`:p)}return s(e,t,""),n}function Ol(e,t=40){let n;try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}return n.length<=t?n:n.slice(0,t-3)+"..."}const Nl={anthropic:"#d97706",openai:"#10b981","openai-codex":"#10b981",xai:"#6366f1"};function C$(e){const t=[],n=e.models,s=e.agents,a=n?.providers;if(a&&typeof a=="object")for(const[o,l]of Object.entries(a)){const c=l;for(const u of c.models??[])t.push({id:`${o}/${u.id}`,name:u.name??u.id,provider:o,providerLabel:o.charAt(0).toUpperCase()+o.slice(1),reasoning:u.reasoning??!1,contextWindow:u.contextWindow??0})}const i=s?.defaults?.models;if(i&&typeof i=="object")for(const o of Object.keys(i)){if(t.some(c=>c.id===o))continue;const l=o.split("/");t.push({id:o,name:l.slice(1).join("/"),provider:l[0]??"unknown",providerLabel:(l[0]??"unknown").replace(/-/g," ").replace(/\b\w/g,c=>c.toUpperCase()),reasoning:!1,contextWindow:0})}return t}function E$(e){return e.startsWith("anthropic/")?["openai-codex/gpt-5.3-codex"]:["anthropic/claude-sonnet-4-6"]}function L$(e){const t=e.formValue;if(!t)return r`<div class="config-loading"><span>Loading config...</span></div>`;const n=t.agents,s=n?.defaults?.model?.primary??"",a=n?.defaults?.model?.fallbacks??[],i=C$(t),o=new Map;for(const c of i){const u=o.get(c.provider)??[];u.push(c),o.set(c.provider,u)}const l=e.saving||e.applying;return r`
3029
+ `},Ja=[{key:"model",label:"AI Model"},{key:"env",label:"Environment"},{key:"update",label:"Updates"},{key:"agents",label:"Agents"},{key:"auth",label:"Authentication"},{key:"channels",label:"Channels"},{key:"messages",label:"Messages"},{key:"commands",label:"Commands"},{key:"hooks",label:"Hooks"},{key:"skills",label:"Skills"},{key:"tools",label:"Tools"},{key:"gateway",label:"Gateway"},{key:"wizard",label:"Setup Wizard"},{key:"user",label:"User"}],Il=new Set(["user","model"]),Ml="__all__";function Dl(e){return xi[e]??xi.default}function S$(e,t){const n=Po[e];return n||{label:t?.title??et(e),description:t?.description??""}}function A$(e){const{key:t,schema:n,uiHints:s}=e;if(!n||We(n)!=="object"||!n.properties)return[];const a=Object.entries(n.properties).map(([i,o])=>{const l=xe([t,i],s),c=l?.label??o.title??et(i),u=l?.help??o.description??"",p=l?.order??50;return{key:i,label:c,description:u,order:p}});return a.sort((i,o)=>i.order!==o.order?i.order-o.order:i.key.localeCompare(o.key)),a}function _$(e,t){if(!e||!t)return[];const n=[];function s(a,i,o){if(a===i)return;if(typeof a!=typeof i){n.push({path:o,from:a,to:i});return}if(typeof a!="object"||a===null||i===null){a!==i&&n.push({path:o,from:a,to:i});return}if(Array.isArray(a)&&Array.isArray(i)){JSON.stringify(a)!==JSON.stringify(i)&&n.push({path:o,from:a,to:i});return}const l=a,c=i,u=new Set([...Object.keys(l),...Object.keys(c)]);for(const p of u)s(l[p],c[p],o?`${o}.${p}`:p)}return s(e,t,""),n}function Ol(e,t=40){let n;try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}return n.length<=t?n:n.slice(0,t-3)+"..."}const Nl={anthropic:"#d97706",openai:"#10b981","openai-codex":"#10b981",xai:"#6366f1"};function T$(e){const t=[],n=e.models,s=e.agents,a=n?.providers;if(a&&typeof a=="object")for(const[o,l]of Object.entries(a)){const c=l;for(const u of c.models??[])t.push({id:`${o}/${u.id}`,name:u.name??u.id,provider:o,providerLabel:o.charAt(0).toUpperCase()+o.slice(1),reasoning:u.reasoning??!1,contextWindow:u.contextWindow??0})}const i=s?.defaults?.models;if(i&&typeof i=="object")for(const o of Object.keys(i)){if(t.some(c=>c.id===o))continue;const l=o.split("/");t.push({id:o,name:l.slice(1).join("/"),provider:l[0]??"unknown",providerLabel:(l[0]??"unknown").replace(/-/g," ").replace(/\b\w/g,c=>c.toUpperCase()),reasoning:!1,contextWindow:0})}return t}function x$(e){return e.startsWith("anthropic/")?["openai-codex/gpt-5.3-codex"]:["anthropic/claude-sonnet-4-6"]}function C$(e){const t=e.formValue;if(!t)return r`<div class="config-loading"><span>Loading config...</span></div>`;const n=t.agents,s=n?.defaults?.model?.primary??"",a=n?.defaults?.model?.fallbacks??[],i=T$(t),o=new Map;for(const c of i){const u=o.get(c.provider)??[];u.push(c),o.set(c.provider,u)}const l=e.saving||e.applying;return r`
3030
3030
  <div class="model-picker">
3031
3031
  <div class="model-picker__current">
3032
3032
  <div class="model-picker__current-label">Active Model</div>
@@ -3048,7 +3048,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3048
3048
  class="model-card ${f?"model-card--active":""}"
3049
3049
  style="--model-accent: ${m}"
3050
3050
  ?disabled=${l}
3051
- @click=${()=>{f||!e.onModelSwitch||e.onModelSwitch(p.id,E$(p.id))}}
3051
+ @click=${()=>{f||!e.onModelSwitch||e.onModelSwitch(p.id,x$(p.id))}}
3052
3052
  >
3053
3053
  <div class="model-card__body">
3054
3054
  <div class="model-card__name">${p.name||p.id}</div>
@@ -3062,7 +3062,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3062
3062
  </div>
3063
3063
  `)}
3064
3064
  </div>
3065
- `}function R$(e){const t=e.valid==null?"unknown":e.valid?"valid":"invalid",n=Ou(e.schema),s=n.schema?n.unsupportedPaths.length>0:!1,a=n.schema?.properties??{},i=Ja.filter(P=>P.key in a&&!Il.has(P.key)),o=new Set(Ja.map(P=>P.key)),l=Object.keys(a).filter(P=>!o.has(P)).map(P=>({key:P,label:P.charAt(0).toUpperCase()+P.slice(1)})),c=Ja.filter(P=>Il.has(P.key)),u=[...i,...l,...c],p=e.activeSection&&n.schema&&We(n.schema)==="object"?n.schema.properties?.[e.activeSection]:void 0,f=e.activeSection?_$(e.activeSection,p):null,m=e.activeSection?T$({key:e.activeSection,schema:p,uiHints:e.uiHints}):[],g=e.formMode==="form"&&!!e.activeSection&&m.length>0,$=e.activeSubsection===Ml,d=e.searchQuery||$?null:e.activeSubsection??m[0]?.key??null,v=e.formMode==="form"?x$(e.originalValue,e.formValue):[],S=e.formMode==="raw"&&e.raw!==e.originalRaw,_=e.formMode==="form"?v.length>0:S,T=!!e.formValue&&!e.loading&&!!n.schema,A=e.connected&&!e.saving&&_&&(e.formMode==="raw"?!0:T),C=e.connected&&!e.applying&&!e.updating&&_&&(e.formMode==="raw"?!0:T),L=e.connected&&!e.applying&&!e.updating;return r`
3065
+ `}function E$(e){const t=e.valid==null?"unknown":e.valid?"valid":"invalid",n=Du(e.schema),s=n.schema?n.unsupportedPaths.length>0:!1,a=n.schema?.properties??{},i=Ja.filter(P=>P.key in a&&!Il.has(P.key)),o=new Set(Ja.map(P=>P.key)),l=Object.keys(a).filter(P=>!o.has(P)).map(P=>({key:P,label:P.charAt(0).toUpperCase()+P.slice(1)})),c=Ja.filter(P=>Il.has(P.key)),u=[...i,...l,...c],p=e.activeSection&&n.schema&&We(n.schema)==="object"?n.schema.properties?.[e.activeSection]:void 0,f=e.activeSection?S$(e.activeSection,p):null,m=e.activeSection?A$({key:e.activeSection,schema:p,uiHints:e.uiHints}):[],g=e.formMode==="form"&&!!e.activeSection&&m.length>0,$=e.activeSubsection===Ml,d=e.searchQuery||$?null:e.activeSubsection??m[0]?.key??null,v=e.formMode==="form"?_$(e.originalValue,e.formValue):[],S=e.formMode==="raw"&&e.raw!==e.originalRaw,_=e.formMode==="form"?v.length>0:S,T=!!e.formValue&&!e.loading&&!!n.schema,A=e.connected&&!e.saving&&_&&(e.formMode==="raw"?!0:T),C=e.connected&&!e.applying&&!e.updating&&_&&(e.formMode==="raw"?!0:T),L=e.connected&&!e.applying&&!e.updating;return r`
3066
3066
  <div class="config-layout">
3067
3067
  <!-- Sidebar -->
3068
3068
  <aside class="config-sidebar">
@@ -3227,13 +3227,13 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3227
3227
 
3228
3228
  <!-- Form content -->
3229
3229
  <div class="config-content">
3230
- ${e.activeSection==="model"?L$(e):e.activeSection==="user"?A$({userName:e.userName,userAvatar:e.userAvatar,onUpdate:e.onUserProfileUpdate}):e.formMode==="form"?r`
3230
+ ${e.activeSection==="model"?C$(e):e.activeSection==="user"?k$({userName:e.userName,userAvatar:e.userAvatar,onUpdate:e.onUserProfileUpdate}):e.formMode==="form"?r`
3231
3231
  ${e.schemaLoading?r`
3232
3232
  <div class="config-loading">
3233
3233
  <div class="config-loading__spinner"></div>
3234
3234
  <span>Loading schema…</span>
3235
3235
  </div>
3236
- `:lw({schema:n.schema,uiHints:e.uiHints,value:e.formValue,disabled:e.loading||!e.formValue,unsupportedPaths:n.unsupportedPaths,onPatch:e.onFormPatch,searchQuery:e.searchQuery,activeSection:e.activeSection,activeSubsection:d})}
3236
+ `:ow({schema:n.schema,uiHints:e.uiHints,value:e.formValue,disabled:e.loading||!e.formValue,unsupportedPaths:n.unsupportedPaths,onPatch:e.onFormPatch,searchQuery:e.searchQuery,activeSection:e.activeSection,activeSubsection:d})}
3237
3237
  ${s?r`
3238
3238
  <div class="callout danger" style="margin-top: 12px">
3239
3239
  Form view can't safely edit some fields. Use Raw to avoid losing config entries.
@@ -3255,7 +3255,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3255
3255
  </div>`:h}
3256
3256
  </main>
3257
3257
  </div>
3258
- `}function P$(e){const t=e.host??"unknown",n=e.ip?`(${e.ip})`:"",s=e.mode??"",a=e.version??"";return`${t} ${n} ${s} ${a}`.trim()}function I$(e){const t=e.ts??null;return t?z(t):"n/a"}function zu(e){return e?`${qn(e)} (${z(e)})`:"n/a"}function M$(e){if(e.totalTokens==null)return"n/a";const t=e.totalTokens??0,n=e.contextTokens??0;return n?`${t} / ${n}`:String(t)}function D$(e){if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function O$(e){const t=e.state??{},n=t.nextRunAtMs?qn(t.nextRunAtMs):"n/a",s=t.lastRunAtMs?qn(t.lastRunAtMs):"n/a";return`${t.lastStatus??"n/a"} · next ${n} · last ${s}`}function N$(e){const t=e.schedule;return t.kind==="at"?`At ${qn(t.atMs)}`:t.kind==="every"?`Every ${Fi(t.everyMs)}`:`Cron ${t.expr}${t.tz?` (${t.tz})`:""}`}function F$(e){const t=e.payload;return t.kind==="systemEvent"?`System: ${t.text}`:`Agent: ${t.message}`}function B$(e){const t=["last",...e.channels.filter(Boolean)],n=e.form.channel?.trim();n&&!t.includes(n)&&t.push(n);const s=new Set;return t.filter(a=>s.has(a)?!1:(s.add(a),!0))}function U$(e,t){if(t==="last")return"last";const n=e.channelMeta?.find(s=>s.id===t);return n?.label?n.label:e.channelLabels?.[t]??t}function z$(e){const t=B$(e);return r`
3258
+ `}function L$(e){const t=e.host??"unknown",n=e.ip?`(${e.ip})`:"",s=e.mode??"",a=e.version??"";return`${t} ${n} ${s} ${a}`.trim()}function R$(e){const t=e.ts??null;return t?z(t):"n/a"}function Uu(e){return e?`${qn(e)} (${z(e)})`:"n/a"}function P$(e){if(e.totalTokens==null)return"n/a";const t=e.totalTokens??0,n=e.contextTokens??0;return n?`${t} / ${n}`:String(t)}function I$(e){if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function M$(e){const t=e.state??{},n=t.nextRunAtMs?qn(t.nextRunAtMs):"n/a",s=t.lastRunAtMs?qn(t.lastRunAtMs):"n/a";return`${t.lastStatus??"n/a"} · next ${n} · last ${s}`}function D$(e){const t=e.schedule;return t.kind==="at"?`At ${qn(t.atMs)}`:t.kind==="every"?`Every ${Fi(t.everyMs)}`:`Cron ${t.expr}${t.tz?` (${t.tz})`:""}`}function O$(e){const t=e.payload;return t.kind==="systemEvent"?`System: ${t.text}`:`Agent: ${t.message}`}function N$(e){const t=["last",...e.channels.filter(Boolean)],n=e.form.channel?.trim();n&&!t.includes(n)&&t.push(n);const s=new Set;return t.filter(a=>s.has(a)?!1:(s.add(a),!0))}function F$(e,t){if(t==="last")return"last";const n=e.channelMeta?.find(s=>s.id===t);return n?.label?n.label:e.channelLabels?.[t]??t}function B$(e){const t=N$(e);return r`
3259
3259
  <section class="grid grid-cols-2">
3260
3260
  <div class="card">
3261
3261
  <div class="card-title">Scheduler</div>
@@ -3273,7 +3273,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3273
3273
  </div>
3274
3274
  <div class="stat">
3275
3275
  <div class="stat-label">Next wake</div>
3276
- <div class="stat-value">${zu(e.status?.nextWakeAtMs??null)}</div>
3276
+ <div class="stat-value">${Uu(e.status?.nextWakeAtMs??null)}</div>
3277
3277
  </div>
3278
3278
  </div>
3279
3279
  <div class="row" style="margin-top: 12px;">
@@ -3330,7 +3330,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3330
3330
  </select>
3331
3331
  </label>
3332
3332
  </div>
3333
- ${K$(e)}
3333
+ ${U$(e)}
3334
3334
  <div class="form-grid" style="margin-top: 12px;">
3335
3335
  <label class="field">
3336
3336
  <span>Session</span>
@@ -3388,7 +3388,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3388
3388
  @change=${n=>e.onFormChange({channel:n.target.value})}
3389
3389
  >
3390
3390
  ${t.map(n=>r`<option value=${n}>
3391
- ${U$(e,n)}
3391
+ ${F$(e,n)}
3392
3392
  </option>`)}
3393
3393
  </select>
3394
3394
  </label>
@@ -3433,7 +3433,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3433
3433
  <div class="muted" style="margin-top: 12px">No jobs yet.</div>
3434
3434
  `:r`
3435
3435
  <div class="list" style="margin-top: 12px;">
3436
- ${e.jobs.map(n=>W$(n,e))}
3436
+ ${e.jobs.map(n=>z$(n,e))}
3437
3437
  </div>
3438
3438
  `}
3439
3439
  </section>
@@ -3447,11 +3447,11 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3447
3447
  <div class="muted" style="margin-top: 12px">No runs yet.</div>
3448
3448
  `:r`
3449
3449
  <div class="list" style="margin-top: 12px;">
3450
- ${e.runs.map(n=>q$(n))}
3450
+ ${e.runs.map(n=>K$(n))}
3451
3451
  </div>
3452
3452
  `}
3453
3453
  </section>
3454
- `}function K$(e){const t=e.form;return t.scheduleKind==="at"?r`
3454
+ `}function U$(e){const t=e.form;return t.scheduleKind==="at"?r`
3455
3455
  <label class="field" style="margin-top: 12px;">
3456
3456
  <span>Run at</span>
3457
3457
  <input
@@ -3498,12 +3498,12 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3498
3498
  />
3499
3499
  </label>
3500
3500
  </div>
3501
- `}function W$(e,t){const s=`list-item list-item-clickable${t.runsJobId===e.id?" list-item-selected":""}`;return r`
3501
+ `}function z$(e,t){const s=`list-item list-item-clickable${t.runsJobId===e.id?" list-item-selected":""}`;return r`
3502
3502
  <div class=${s} @click=${()=>t.onLoadRuns(e.id)}>
3503
3503
  <div class="list-main">
3504
3504
  <div class="list-title">${e.name}</div>
3505
- <div class="list-sub">${N$(e)}</div>
3506
- <div class="muted">${F$(e)}</div>
3505
+ <div class="list-sub">${D$(e)}</div>
3506
+ <div class="muted">${O$(e)}</div>
3507
3507
  ${e.agentId?r`<div class="muted">Agent: ${e.agentId}</div>`:h}
3508
3508
  <div class="chip-row" style="margin-top: 6px;">
3509
3509
  <span class="chip">${e.enabled?"enabled":"disabled"}</span>
@@ -3512,7 +3512,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3512
3512
  </div>
3513
3513
  </div>
3514
3514
  <div class="list-meta">
3515
- <div>${O$(e)}</div>
3515
+ <div>${M$(e)}</div>
3516
3516
  <div class="row" style="justify-content: flex-end; margin-top: 8px;">
3517
3517
  <button
3518
3518
  class="btn"
@@ -3545,7 +3545,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3545
3545
  </div>
3546
3546
  </div>
3547
3547
  </div>
3548
- `}function q$(e){return r`
3548
+ `}function K$(e){return r`
3549
3549
  <div class="list-item">
3550
3550
  <div class="list-main">
3551
3551
  <div class="list-title">${e.status}</div>
@@ -3557,7 +3557,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3557
3557
  ${e.error?r`<div class="muted">${e.error}</div>`:h}
3558
3558
  </div>
3559
3559
  </div>
3560
- `}function j$(e){const n=(e.status&&typeof e.status=="object"?e.status.securityAudit:null)?.summary??null,s=n?.critical??0,a=n?.warn??0,i=n?.info??0,o=s>0?"danger":a>0?"warn":"success",l=s>0?`${s} critical`:a>0?`${a} warnings`:"No critical issues";return r`
3560
+ `}function W$(e){const n=(e.status&&typeof e.status=="object"?e.status.securityAudit:null)?.summary??null,s=n?.critical??0,a=n?.warn??0,i=n?.info??0,o=s>0?"danger":a>0?"warn":"success",l=s>0?`${s} critical`:a>0?`${a} warnings`:"No critical issues";return r`
3561
3561
  <section class="grid grid-cols-2">
3562
3562
  <div class="card">
3563
3563
  <div class="row" style="justify-content: space-between;">
@@ -3640,14 +3640,14 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3640
3640
  <div class="list-sub">${new Date(c.ts).toLocaleTimeString()}</div>
3641
3641
  </div>
3642
3642
  <div class="list-meta">
3643
- <pre class="code-block">${D$(c.payload)}</pre>
3643
+ <pre class="code-block">${I$(c.payload)}</pre>
3644
3644
  </div>
3645
3645
  </div>
3646
3646
  `)}
3647
3647
  </div>
3648
3648
  `}
3649
3649
  </section>
3650
- `}function H$(e){const t=Math.max(0,e),n=Math.floor(t/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60);return s<60?`${s}m`:`${Math.floor(s/60)}h`}function yt(e,t){return t?r`<div class="exec-approval-meta-row"><span>${e}</span><span>${t}</span></div>`:h}function V$(e){const t=e.execApprovalQueue[0];if(!t)return h;const n=t.request,s=t.expiresAtMs-Date.now(),a=s>0?`expires in ${H$(s)}`:"expired",i=e.execApprovalQueue.length;return r`
3650
+ `}function q$(e){const t=Math.max(0,e),n=Math.floor(t/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60);return s<60?`${s}m`:`${Math.floor(s/60)}h`}function yt(e,t){return t?r`<div class="exec-approval-meta-row"><span>${e}</span><span>${t}</span></div>`:h}function j$(e){const t=e.execApprovalQueue[0];if(!t)return h;const n=t.request,s=t.expiresAtMs-Date.now(),a=s>0?`expires in ${q$(s)}`:"expired",i=e.execApprovalQueue.length;return r`
3651
3651
  <div class="exec-approval-overlay" role="dialog" aria-live="polite">
3652
3652
  <div class="exec-approval-card">
3653
3653
  <div class="exec-approval-header">
@@ -3693,7 +3693,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3693
3693
  </div>
3694
3694
  </div>
3695
3695
  </div>
3696
- `}function G$(e){const{pendingGatewayUrl:t}=e;return t?r`
3696
+ `}function H$(e){const{pendingGatewayUrl:t}=e;return t?r`
3697
3697
  <div class="exec-approval-overlay" role="dialog" aria-modal="true" aria-live="polite">
3698
3698
  <div class="exec-approval-card">
3699
3699
  <div class="exec-approval-header">
@@ -3722,7 +3722,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3722
3722
  </div>
3723
3723
  </div>
3724
3724
  </div>
3725
- `:h}function Q$(e){return r`
3725
+ `:h}function V$(e){return r`
3726
3726
  <section class="card">
3727
3727
  <div class="row" style="justify-content: space-between;">
3728
3728
  <div>
@@ -3742,14 +3742,14 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3742
3742
  <div class="list" style="margin-top: 16px;">
3743
3743
  ${e.entries.length===0?r`
3744
3744
  <div class="muted">No instances reported yet.</div>
3745
- `:e.entries.map(t=>Y$(t))}
3745
+ `:e.entries.map(t=>G$(t))}
3746
3746
  </div>
3747
3747
  </section>
3748
- `}function Y$(e){const t=e.lastInputSeconds!=null?`${e.lastInputSeconds}s ago`:"n/a",n=e.mode??"unknown",s=Array.isArray(e.roles)?e.roles.filter(Boolean):[],a=Array.isArray(e.scopes)?e.scopes.filter(Boolean):[],i=a.length>0?a.length>3?`${a.length} scopes`:`scopes: ${a.join(", ")}`:null;return r`
3748
+ `}function G$(e){const t=e.lastInputSeconds!=null?`${e.lastInputSeconds}s ago`:"n/a",n=e.mode??"unknown",s=Array.isArray(e.roles)?e.roles.filter(Boolean):[],a=Array.isArray(e.scopes)?e.scopes.filter(Boolean):[],i=a.length>0?a.length>3?`${a.length} scopes`:`scopes: ${a.join(", ")}`:null;return r`
3749
3749
  <div class="list-item">
3750
3750
  <div class="list-main">
3751
3751
  <div class="list-title">${e.host??"unknown host"}</div>
3752
- <div class="list-sub">${P$(e)}</div>
3752
+ <div class="list-sub">${L$(e)}</div>
3753
3753
  <div class="chip-row">
3754
3754
  <span class="chip">${n}</span>
3755
3755
  ${s.map(o=>r`<span class="chip">${o}</span>`)}
@@ -3761,12 +3761,12 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3761
3761
  </div>
3762
3762
  </div>
3763
3763
  <div class="list-meta">
3764
- <div>${I$(e)}</div>
3764
+ <div>${R$(e)}</div>
3765
3765
  <div class="muted">Last input ${t}</div>
3766
3766
  <div class="muted">Reason ${e.reason??""}</div>
3767
3767
  </div>
3768
3768
  </div>
3769
- `}const Fl=["trace","debug","info","warn","error","fatal"];function J$(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function X$(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function Z$(e){const t=e.filterText.trim().toLowerCase(),n=Fl.some(i=>!e.levelFilters[i]),s=e.entries.filter(i=>i.level&&!e.levelFilters[i.level]?!1:X$(i,t)),a=t||n?"filtered":"visible";return r`
3769
+ `}const Fl=["trace","debug","info","warn","error","fatal"];function Q$(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function Y$(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function J$(e){const t=e.filterText.trim().toLowerCase(),n=Fl.some(i=>!e.levelFilters[i]),s=e.entries.filter(i=>i.level&&!e.levelFilters[i.level]?!1:Y$(i,t)),a=t||n?"filtered":"visible";return r`
3770
3770
  <section class="card">
3771
3771
  <div class="row" style="justify-content: space-between;">
3772
3772
  <div>
@@ -3830,7 +3830,7 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3830
3830
  <div class="muted" style="padding: 12px">No log entries.</div>
3831
3831
  `:s.map(i=>r`
3832
3832
  <div class="log-row">
3833
- <div class="log-time mono">${J$(i.time)}</div>
3833
+ <div class="log-time mono">${Q$(i.time)}</div>
3834
3834
  <div class="log-level ${i.level??""}">${i.level??""}</div>
3835
3835
  <div class="log-subsystem mono">${i.subsystem??""}</div>
3836
3836
  <div class="log-message mono">${i.message??i.raw}</div>
@@ -3838,8 +3838,8 @@ ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
3838
3838
  `)}
3839
3839
  </div>
3840
3840
  </section>
3841
- `}const ek=/(^~\/|^\/|^\.\.?\/|[\\/])/;function Bl(e){const t=e.trim();if(!t)return null;const n=t.replace(/^["']|["']$/g,"").trim();return!n||/^[a-z][a-z0-9+.-]*:\/\//i.test(n)||/[*?<>|]/.test(n)||n.includes("\0")||n.includes(`
3842
- `)||n.includes("\r")||!ek.test(n)&&!/\.[a-z0-9]{1,12}$/i.test(n)?null:n}function Ku(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null;if(!t)return null;const n=t.closest("a");if(n){const a=n.getAttribute("href")??"";let i=a;if(a.includes("%"))try{i=decodeURIComponent(a)}catch{i=a}return Bl(i)}const s=t.closest("code");return!s||s.closest("pre")?null:Bl(s.textContent??"")}function tk(e){const n=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html").body.firstElementChild;if(!n)return"";const a=ze(n,{listDepth:0,orderedIndex:[]});return sk(a)}function Ci(e,t){if(e.nodeType===Node.TEXT_NODE)return e.textContent??"";if(e.nodeType!==Node.ELEMENT_NODE)return"";const n=e;switch(n.tagName.toLowerCase()){case"h1":return`# ${Qe(n,t)}
3841
+ `}const X$=/(^~\/|^\/|^\.\.?\/|[\\/])/;function Bl(e){const t=e.trim();if(!t)return null;const n=t.replace(/^["']|["']$/g,"").trim();return!n||/^[a-z][a-z0-9+.-]*:\/\//i.test(n)||/[*?<>|]/.test(n)||n.includes("\0")||n.includes(`
3842
+ `)||n.includes("\r")||!X$.test(n)&&!/\.[a-z0-9]{1,12}$/i.test(n)?null:n}function zu(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null;if(!t)return null;const n=t.closest("a");if(n){const a=n.getAttribute("href")??"";let i=a;if(a.includes("%"))try{i=decodeURIComponent(a)}catch{i=a}return Bl(i)}const s=t.closest("code");return!s||s.closest("pre")?null:Bl(s.textContent??"")}function Z$(e){const n=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html").body.firstElementChild;if(!n)return"";const a=ze(n,{listDepth:0,orderedIndex:[]});return tk(a)}function Ci(e,t){if(e.nodeType===Node.TEXT_NODE)return e.textContent??"";if(e.nodeType!==Node.ELEMENT_NODE)return"";const n=e;switch(n.tagName.toLowerCase()){case"h1":return`# ${Qe(n,t)}
3843
3843
 
3844
3844
  `;case"h2":return`## ${Qe(n,t)}
3845
3845
 
@@ -3864,21 +3864,21 @@ ${i}
3864
3864
  `).map(o=>`> ${o}`).join(`
3865
3865
  `)+`
3866
3866
 
3867
- `;case"ul":return Ul(n,t,!1);case"ol":return Ul(n,t,!0);case"li":return Wu(n,t);case"input":return n.getAttribute("type")==="checkbox"?n.checked?"[x]":"[ ]":"";case"table":return nk(n,t);case"div":case"span":case"section":case"article":case"main":case"header":case"footer":case"nav":case"aside":case"figure":case"figcaption":case"details":case"summary":return ze(n,t);default:return ze(n,t)}}function ze(e,t){let n="";for(const s of Array.from(e.childNodes))n+=Ci(s,t);return n}function Qe(e,t){return ze(e,t).replace(/\n+/g," ").trim()}function Ul(e,t,n){const s=Array.from(e.children).filter(o=>o.tagName.toLowerCase()==="li"),a=" ".repeat(t.listDepth);let i="";for(let o=0;o<s.length;o++){const l=s[o],c={listDepth:t.listDepth+1,orderedIndex:[...t.orderedIndex,o+1]},u=n?`${o+1}. `:"- ",p=Wu(l,c);i+=`${a}${u}${p}
3867
+ `;case"ul":return Ul(n,t,!1);case"ol":return Ul(n,t,!0);case"li":return Ku(n,t);case"input":return n.getAttribute("type")==="checkbox"?n.checked?"[x]":"[ ]":"";case"table":return ek(n,t);case"div":case"span":case"section":case"article":case"main":case"header":case"footer":case"nav":case"aside":case"figure":case"figcaption":case"details":case"summary":return ze(n,t);default:return ze(n,t)}}function ze(e,t){let n="";for(const s of Array.from(e.childNodes))n+=Ci(s,t);return n}function Qe(e,t){return ze(e,t).replace(/\n+/g," ").trim()}function Ul(e,t,n){const s=Array.from(e.children).filter(o=>o.tagName.toLowerCase()==="li"),a=" ".repeat(t.listDepth);let i="";for(let o=0;o<s.length;o++){const l=s[o],c={listDepth:t.listDepth+1,orderedIndex:[...t.orderedIndex,o+1]},u=n?`${o+1}. `:"- ",p=Ku(l,c);i+=`${a}${u}${p}
3868
3868
  `}return t.listDepth===0&&(i+=`
3869
- `),i}function Wu(e,t){let n="";for(const s of Array.from(e.childNodes)){const a=s.tagName?.toLowerCase();a==="ul"||a==="ol"?n+=`
3870
- `+Ci(s,t):n+=Ci(s,t)}return n.trim()}function nk(e,t){const n=[],s=e.querySelector("thead tr"),a=e.querySelectorAll("tbody tr");if(s){const u=Array.from(s.querySelectorAll("th, td")).map(p=>Qe(p,t));n.push(u)}for(const u of Array.from(a)){const p=Array.from(u.querySelectorAll("td, th")).map(f=>Qe(f,t));n.push(p)}if(n.length===0){const u=e.querySelectorAll("tr");for(const p of Array.from(u)){const f=Array.from(p.querySelectorAll("td, th")).map(m=>Qe(m,t));n.push(f)}}if(n.length===0)return"";const i=Math.max(...n.map(u=>u.length)),o=[];for(let u=0;u<i;u++)o[u]=Math.max(3,...n.map(p=>(p[u]??"").length));let l="";const c=u=>`| ${o.map((f,m)=>(u[m]??"").padEnd(f)).join(" | ")} |`;l+=c(n[0])+`
3869
+ `),i}function Ku(e,t){let n="";for(const s of Array.from(e.childNodes)){const a=s.tagName?.toLowerCase();a==="ul"||a==="ol"?n+=`
3870
+ `+Ci(s,t):n+=Ci(s,t)}return n.trim()}function ek(e,t){const n=[],s=e.querySelector("thead tr"),a=e.querySelectorAll("tbody tr");if(s){const u=Array.from(s.querySelectorAll("th, td")).map(p=>Qe(p,t));n.push(u)}for(const u of Array.from(a)){const p=Array.from(u.querySelectorAll("td, th")).map(f=>Qe(f,t));n.push(p)}if(n.length===0){const u=e.querySelectorAll("tr");for(const p of Array.from(u)){const f=Array.from(p.querySelectorAll("td, th")).map(m=>Qe(m,t));n.push(f)}}if(n.length===0)return"";const i=Math.max(...n.map(u=>u.length)),o=[];for(let u=0;u<i;u++)o[u]=Math.max(3,...n.map(p=>(p[u]??"").length));let l="";const c=u=>`| ${o.map((f,m)=>(u[m]??"").padEnd(f)).join(" | ")} |`;l+=c(n[0])+`
3871
3871
  `,l+=`| ${o.map(u=>"-".repeat(u)).join(" | ")} |
3872
3872
  `;for(let u=1;u<n.length;u++)l+=c(n[u])+`
3873
3873
  `;return l+`
3874
- `}function sk(e){let t=e;return t=t.replace(/\u00a0/g," "),t=t.replace(/\n{3,}/g,`
3874
+ `}function tk(e){let t=e;return t=t.replace(/\u00a0/g," "),t=t.replace(/\n{3,}/g,`
3875
3875
 
3876
3876
  `),t=t.trim(),t&&!t.endsWith(`
3877
3877
  `)&&(t+=`
3878
- `),t}function ak(e){return e.includes(`
3878
+ `),t}function nk(e){return e.includes(`
3879
3879
  `)&&e.indexOf(`
3880
3880
  `)<e.length-1?e:e.replace(/\\n/g,`
3881
- `)}function ik(e){const t=new Date(e),s=new Date().getTime()-t.getTime(),a=Math.floor(s/(1e3*60));if(a<1)return"Just now";if(a<60)return`${a}m ago`;const i=Math.floor(a/60);return i<24?`${i}h ago`:t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}function ok(e){const t="VAULT",n=encodeURIComponent(`01-Daily/${e}`);return`obsidian://open?vault=${t}&file=${n}`}let Un=null,un=null;function zl(e,t,n=1500){Un&&clearTimeout(Un),Un=setTimeout(()=>{e!==un&&(un=e,t(e))},n)}function rk(e,t){Un&&clearTimeout(Un),e!==un&&(un=e,t(e))}function Xa(e){for(const t of e.querySelectorAll('input[type="checkbox"]')){const n=t;n.checked?n.setAttribute("checked",""):n.removeAttribute("checked")}return tk(e.innerHTML)}function lk(e){const{data:t,loading:n,error:s,onRefresh:a,onOpenInObsidian:i,onSaveBrief:o,onToggleCheckbox:l,onOpenFile:c}=e;if(n)return r`
3881
+ `)}function sk(e){const t=new Date(e),s=new Date().getTime()-t.getTime(),a=Math.floor(s/(1e3*60));if(a<1)return"Just now";if(a<60)return`${a}m ago`;const i=Math.floor(a/60);return i<24?`${i}h ago`:t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}function ak(e){const t="VAULT",n=encodeURIComponent(`01-Daily/${e}`);return`obsidian://open?vault=${t}&file=${n}`}let Un=null,un=null;function zl(e,t,n=1500){Un&&clearTimeout(Un),Un=setTimeout(()=>{e!==un&&(un=e,t(e))},n)}function ik(e,t){Un&&clearTimeout(Un),e!==un&&(un=e,t(e))}function Xa(e){for(const t of e.querySelectorAll('input[type="checkbox"]')){const n=t;n.checked?n.setAttribute("checked",""):n.removeAttribute("checked")}return Z$(e.innerHTML)}function ok(e){const{data:t,loading:n,error:s,onRefresh:a,onOpenInObsidian:i,onSaveBrief:o,onToggleCheckbox:l,onOpenFile:c}=e;if(n)return r`
3882
3882
  <div class="my-day-card brief-section">
3883
3883
  <div class="my-day-card-header">
3884
3884
  <div class="my-day-card-title">
@@ -3925,7 +3925,7 @@ ${i}
3925
3925
  </div>
3926
3926
  </div>
3927
3927
  </div>
3928
- `;un===null&&(un=t.content);const u=g=>{const $=g.currentTarget;if(o){const d=Xa($);zl(d,o)}},p=g=>{if((g.ctrlKey||g.metaKey)&&g.key==="s"){g.preventDefault();const $=g.currentTarget;if(o){const d=Xa($);rk(d,o)}}if((g.ctrlKey||g.metaKey)&&g.key==="l"){g.preventDefault();const $=window.getSelection();if(!$||$.rangeCount===0)return;const d=$.focusNode,v=d instanceof HTMLElement?d.closest("li"):d?.parentElement?.closest("li");if(v){const S=v.querySelector('input[type="checkbox"]');if(S)S.nextSibling?.nodeType===Node.TEXT_NODE&&S.nextSibling.textContent===" "&&S.nextSibling.remove(),S.remove();else{const T=document.createElement("input");T.type="checkbox",v.insertBefore(document.createTextNode(" "),v.firstChild),v.insertBefore(T,v.firstChild)}const _=g.currentTarget;if(o){const T=Xa(_);zl(T,o)}}}if(g.key==="Enter"&&!g.shiftKey){const $=window.getSelection();if(!$||$.rangeCount===0)return;const d=$.focusNode,v=d instanceof HTMLElement?d.closest("li"):d?.parentElement?.closest("li");v&&v.querySelector('input[type="checkbox"]')&&setTimeout(()=>{const S=window.getSelection();if(!S||S.rangeCount===0)return;const _=S.focusNode,T=_ instanceof HTMLElement?_.closest("li"):_?.parentElement?.closest("li");if(T&&T!==v&&!T.querySelector('input[type="checkbox"]')){const A=document.createElement("input");A.type="checkbox",T.insertBefore(A,T.firstChild),T.insertBefore(document.createTextNode(" "),A.nextSibling);const C=document.createRange();C.setStartAfter(A.nextSibling),C.collapse(!0),S.removeAllRanges(),S.addRange(C)}},0)}},f=g=>{const $=g.target;if($.tagName==="INPUT"&&$.getAttribute("type")==="checkbox"){const v=$,S=g.currentTarget;if(l&&S){const T=Array.from(S.querySelectorAll('input[type="checkbox"]')).indexOf(v);T>=0&&l(T,v.checked)}return}const d=Ku(g.target);d&&c&&(g.preventDefault(),c(d))},m=Xf(ak(t.content));return r`
3928
+ `;un===null&&(un=t.content);const u=g=>{const $=g.currentTarget;if(o){const d=Xa($);zl(d,o)}},p=g=>{if((g.ctrlKey||g.metaKey)&&g.key==="s"){g.preventDefault();const $=g.currentTarget;if(o){const d=Xa($);ik(d,o)}}if((g.ctrlKey||g.metaKey)&&g.key==="l"){g.preventDefault();const $=window.getSelection();if(!$||$.rangeCount===0)return;const d=$.focusNode,v=d instanceof HTMLElement?d.closest("li"):d?.parentElement?.closest("li");if(v){const S=v.querySelector('input[type="checkbox"]');if(S)S.nextSibling?.nodeType===Node.TEXT_NODE&&S.nextSibling.textContent===" "&&S.nextSibling.remove(),S.remove();else{const T=document.createElement("input");T.type="checkbox",v.insertBefore(document.createTextNode(" "),v.firstChild),v.insertBefore(T,v.firstChild)}const _=g.currentTarget;if(o){const T=Xa(_);zl(T,o)}}}if(g.key==="Enter"&&!g.shiftKey){const $=window.getSelection();if(!$||$.rangeCount===0)return;const d=$.focusNode,v=d instanceof HTMLElement?d.closest("li"):d?.parentElement?.closest("li");v&&v.querySelector('input[type="checkbox"]')&&setTimeout(()=>{const S=window.getSelection();if(!S||S.rangeCount===0)return;const _=S.focusNode,T=_ instanceof HTMLElement?_.closest("li"):_?.parentElement?.closest("li");if(T&&T!==v&&!T.querySelector('input[type="checkbox"]')){const A=document.createElement("input");A.type="checkbox",T.insertBefore(A,T.firstChild),T.insertBefore(document.createTextNode(" "),A.nextSibling);const C=document.createRange();C.setStartAfter(A.nextSibling),C.collapse(!0),S.removeAllRanges(),S.addRange(C)}},0)}},f=g=>{const $=g.target;if($.tagName==="INPUT"&&$.getAttribute("type")==="checkbox"){const v=$,S=g.currentTarget;if(l&&S){const T=Array.from(S.querySelectorAll('input[type="checkbox"]')).indexOf(v);T>=0&&l(T,v.checked)}return}const d=zu(g.target);d&&c&&(g.preventDefault(),c(d))},m=Jf(nk(t.content));return r`
3929
3929
  <div class="my-day-card brief-section brief-editor">
3930
3930
  <div class="my-day-card-header">
3931
3931
  <div class="my-day-card-title">
@@ -3933,10 +3933,10 @@ ${i}
3933
3933
  <span>DAILY BRIEF</span>
3934
3934
  </div>
3935
3935
  <div class="brief-header-actions">
3936
- <span class="brief-updated">${ik(t.updatedAt)}</span>
3936
+ <span class="brief-updated">${sk(t.updatedAt)}</span>
3937
3937
  ${i?r`
3938
3938
  <a
3939
- href="${ok(t.date)}"
3939
+ href="${ak(t.date)}"
3940
3940
  class="brief-obsidian-link"
3941
3941
  title="Open in Obsidian"
3942
3942
  @click=${g=>{g.preventDefault(),i()}}
@@ -3965,7 +3965,7 @@ ${i}
3965
3965
  </div>
3966
3966
  </div>
3967
3967
  </div>
3968
- `}function qu(e){return!Number.isFinite(e)||e<=0?"0 B":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Do(e){switch(e){case"markdown":return"📄";case"html":return"🌐";case"image":return"🖼️";case"json":return"🧩";case"folder":return"📁";default:return"📄"}}function Kl(e){return e==="running"?"ws-session-dot ws-session-dot--running":e==="blocked"?"ws-session-dot ws-session-dot--blocked":"ws-session-dot ws-session-dot--complete"}function ju(e){return`ws-task-priority ws-task-priority--${e}`}function Hu(e){return e==="high"?"High":e==="low"?"Low":"Med"}function Vu(e){if(!e)return"";const t=re();return e===t?"Today":e<t?`Overdue (${e})`:e}function Gu(e){if(!e)return"ws-task-due";const t=re();return e<t?"ws-task-due ws-task-due--overdue":e===t?"ws-task-due ws-task-due--today":"ws-task-due"}function Hs(e,t="due"){const n={high:0,medium:1,low:2};return[...e].sort((s,a)=>{if(t==="priority"){const i=n[s.priority]-n[a.priority];return i!==0?i:s.dueDate&&a.dueDate?s.dueDate.localeCompare(a.dueDate):s.dueDate&&!a.dueDate?-1:!s.dueDate&&a.dueDate?1:0}if(t==="newest")return(a.createdAt||"").localeCompare(s.createdAt||"");if(s.dueDate&&a.dueDate){const i=s.dueDate.localeCompare(a.dueDate);if(i!==0)return i}else{if(s.dueDate&&!a.dueDate)return-1;if(!s.dueDate&&a.dueDate)return 1}return n[s.priority]-n[a.priority]})}function Wl(e,t,n,s,a,i){const o=e.status==="complete";return s===e.id?r`
3968
+ `}function Wu(e){return!Number.isFinite(e)||e<=0?"0 B":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Do(e){switch(e){case"markdown":return"📄";case"html":return"🌐";case"image":return"🖼️";case"json":return"🧩";case"folder":return"📁";default:return"📄"}}function Kl(e){return e==="running"?"ws-session-dot ws-session-dot--running":e==="blocked"?"ws-session-dot ws-session-dot--blocked":"ws-session-dot ws-session-dot--complete"}function qu(e){return`ws-task-priority ws-task-priority--${e}`}function ju(e){return e==="high"?"High":e==="low"?"Low":"Med"}function Hu(e){if(!e)return"";const t=re();return e===t?"Today":e<t?`Overdue (${e})`:e}function Vu(e){if(!e)return"ws-task-due";const t=re();return e<t?"ws-task-due ws-task-due--overdue":e===t?"ws-task-due ws-task-due--today":"ws-task-due"}function Hs(e,t="due"){const n={high:0,medium:1,low:2};return[...e].sort((s,a)=>{if(t==="priority"){const i=n[s.priority]-n[a.priority];return i!==0?i:s.dueDate&&a.dueDate?s.dueDate.localeCompare(a.dueDate):s.dueDate&&!a.dueDate?-1:!s.dueDate&&a.dueDate?1:0}if(t==="newest")return(a.createdAt||"").localeCompare(s.createdAt||"");if(s.dueDate&&a.dueDate){const i=s.dueDate.localeCompare(a.dueDate);if(i!==0)return i}else{if(s.dueDate&&!a.dueDate)return-1;if(!s.dueDate&&a.dueDate)return 1}return n[s.priority]-n[a.priority]})}function Wl(e,t,n,s,a,i){const o=e.status==="complete";return s===e.id?r`
3969
3969
  <form
3970
3970
  class="ws-list-row ws-task-row ws-task-edit-row"
3971
3971
  @submit=${c=>{c.preventDefault();const u=c.currentTarget,p=u.querySelector(".ws-task-edit-input"),f=u.querySelector(".ws-task-date-input"),m=p.value.trim();m&&(i?.(e.id,{title:m,dueDate:f.value||null}),a?.(null))}}
@@ -4003,8 +4003,8 @@ ${i}
4003
4003
  title="Click to edit"
4004
4004
  >${e.title}</span>
4005
4005
  ${e.briefSection?r`<span class="ws-task-section">${e.briefSection}</span>`:h}
4006
- <span class=${ju(e.priority)}>${Hu(e.priority)}</span>
4007
- ${e.dueDate?r`<span class=${Gu(e.dueDate)}>${Vu(e.dueDate)}</span>`:h}
4006
+ <span class=${qu(e.priority)}>${ju(e.priority)}</span>
4007
+ ${e.dueDate?r`<span class=${Vu(e.dueDate)}>${Hu(e.dueDate)}</span>`:h}
4008
4008
  ${!o&&e.queueStatus?.status==="processing"?r`<span class="ws-task-agent-status ws-task-agent-status--processing">
4009
4009
  <span class="ws-task-agent-dot"></span>
4010
4010
  ${e.queueStatus.roleName} working...
@@ -4057,8 +4057,8 @@ ${i}
4057
4057
  >${e.title}</span>
4058
4058
  ${e.project?r`<span class="ws-task-project">${e.project}</span>`:h}
4059
4059
  ${e.briefSection?r`<span class="ws-task-section">${e.briefSection}</span>`:h}
4060
- <span class=${ju(e.priority)}>${Hu(e.priority)}</span>
4061
- ${e.dueDate?r`<span class=${Gu(e.dueDate)}>${Vu(e.dueDate)}</span>`:h}
4060
+ <span class=${qu(e.priority)}>${ju(e.priority)}</span>
4061
+ ${e.dueDate?r`<span class=${Vu(e.dueDate)}>${Hu(e.dueDate)}</span>`:h}
4062
4062
  ${!o&&e.queueStatus?.status==="processing"?r`<span class="ws-task-agent-status ws-task-agent-status--processing">
4063
4063
  <span class="ws-task-agent-dot"></span>
4064
4064
  ${e.queueStatus.roleName} working...
@@ -4072,7 +4072,7 @@ ${i}
4072
4072
  title="Start working on this task"
4073
4073
  >Start</button>`:h}
4074
4074
  </div>
4075
- `}function ck(e,t){return e.trim()?t.toLowerCase().includes(e.trim().toLowerCase()):!0}function ql(e,t){if(!e.trim())return t;const n=e.trim().toLowerCase();return t.filter(s=>s.name.toLowerCase().includes(n)||s.path.toLowerCase().includes(n)||s.type.toLowerCase().includes(n)||(s.searchText??"").toLowerCase().includes(n))}function jl(e,t){if(!e.trim())return t;const n=e.trim().toLowerCase();return t.filter(s=>s.title.toLowerCase().includes(n)||s.key.toLowerCase().includes(n))}function Qu(e,t){if(!e.trim())return t;const n=e.trim().toLowerCase();return t.reduce((s,a)=>{if(a.type==="file")(a.name.toLowerCase().includes(n)||a.path.toLowerCase().includes(n))&&s.push(a);else{const i=Qu(e,a.children??[]);i.length>0&&s.push({...a,children:i})}return s},[])}function Yu(e){let t=0;for(const n of e)n.type==="file"?t++:n.children&&(t+=Yu(n.children));return t}const dk=10;function uk(e){if(!e.searchText)return null;const t=e.searchText.trim();if(!t)return null;const n=t.match(/#+ (.+?)(?:\s#|$)/);return n?n[1].trim().slice(0,120):(t.startsWith("---")?t.replace(/^---.*?---\s*/s,""):t).slice(0,120)||null}function pk(e,t=dk){return[...e].sort((n,s)=>s.modified.getTime()-n.modified.getTime()).slice(0,t)}function Ju(e,t,n){if(e.type==="file"){const o=n.pinnedPaths.has(e.path);return r`
4075
+ `}function rk(e,t){return e.trim()?t.toLowerCase().includes(e.trim().toLowerCase()):!0}function ql(e,t){if(!e.trim())return t;const n=e.trim().toLowerCase();return t.filter(s=>s.name.toLowerCase().includes(n)||s.path.toLowerCase().includes(n)||s.type.toLowerCase().includes(n)||(s.searchText??"").toLowerCase().includes(n))}function jl(e,t){if(!e.trim())return t;const n=e.trim().toLowerCase();return t.filter(s=>s.title.toLowerCase().includes(n)||s.key.toLowerCase().includes(n))}function Gu(e,t){if(!e.trim())return t;const n=e.trim().toLowerCase();return t.reduce((s,a)=>{if(a.type==="file")(a.name.toLowerCase().includes(n)||a.path.toLowerCase().includes(n))&&s.push(a);else{const i=Gu(e,a.children??[]);i.length>0&&s.push({...a,children:i})}return s},[])}function Qu(e){let t=0;for(const n of e)n.type==="file"?t++:n.children&&(t+=Qu(n.children));return t}const lk=10;function ck(e){if(!e.searchText)return null;const t=e.searchText.trim();if(!t)return null;const n=t.match(/#+ (.+?)(?:\s#|$)/);return n?n[1].trim().slice(0,120):(t.startsWith("---")?t.replace(/^---.*?---\s*/s,""):t).slice(0,120)||null}function dk(e,t=lk){return[...e].sort((n,s)=>s.modified.getTime()-n.modified.getTime()).slice(0,t)}function Yu(e,t,n){if(e.type==="file"){const o=n.pinnedPaths.has(e.path);return r`
4076
4076
  <div class="ws-folder-file-row" style="padding-left: ${12+t*16}px">
4077
4077
  <button
4078
4078
  class="ws-folder-file"
@@ -4080,7 +4080,7 @@ ${i}
4080
4080
  >
4081
4081
  <span class="ws-list-icon">${Do(e.fileType??"text")}</span>
4082
4082
  <span class="ws-list-title">${e.name}</span>
4083
- ${e.size!=null?r`<span class="ws-list-meta">${qu(e.size)}</span>`:h}
4083
+ ${e.size!=null?r`<span class="ws-list-meta">${Wu(e.size)}</span>`:h}
4084
4084
  ${e.modified?r`<span class="ws-list-meta">${z(e.modified.getTime())}</span>`:h}
4085
4085
  </button>
4086
4086
  <button
@@ -4091,7 +4091,7 @@ ${i}
4091
4091
  ${o?"Unpin":"Pin"}
4092
4092
  </button>
4093
4093
  </div>
4094
- `}const s=n.expandedFolders.has(e.path),a=e.children??[],i=Yu(a);return r`
4094
+ `}const s=n.expandedFolders.has(e.path),a=e.children??[],i=Qu(a);return r`
4095
4095
  <div class="ws-folder-node">
4096
4096
  <button
4097
4097
  class="ws-folder-header"
@@ -4105,11 +4105,11 @@ ${i}
4105
4105
  </button>
4106
4106
  ${s?r`
4107
4107
  <div class="ws-folder-children">
4108
- ${a.map(o=>Ju(o,t+1,n))}
4108
+ ${a.map(o=>Yu(o,t+1,n))}
4109
4109
  </div>
4110
4110
  `:h}
4111
4111
  </div>
4112
- `}function hk(e,t,n){return r`
4112
+ `}function uk(e,t,n){return r`
4113
4113
  <div class="workspace-card-wrapper">
4114
4114
  <button
4115
4115
  class="workspace-card"
@@ -4139,7 +4139,7 @@ ${i}
4139
4139
  <button class="ws-list-main" @click=${()=>a?.(n)}>
4140
4140
  <span class="ws-list-icon">${Do(n.type)}</span>
4141
4141
  <span class="ws-list-title">${n.name}</span>
4142
- <span class="ws-list-meta">${qu(n.size)}</span>
4142
+ <span class="ws-list-meta">${Wu(n.size)}</span>
4143
4143
  <span class="ws-list-meta">${z(n.modified.getTime())}</span>
4144
4144
  </button>
4145
4145
  <button
@@ -4150,7 +4150,7 @@ ${i}
4150
4150
  ${s?"Unpin":"Pin"}
4151
4151
  </button>
4152
4152
  </div>
4153
- `}function fk(e){const{workspaceId:t,entry:n,pinned:s,onOpen:a,onPinToggle:i}=e,o=uk(n);return r`
4153
+ `}function pk(e){const{workspaceId:t,entry:n,pinned:s,onOpen:a,onPinToggle:i}=e,o=ck(n);return r`
4154
4154
  <div class="ws-list-row">
4155
4155
  <button class="ws-list-main" @click=${()=>a?.(n)}>
4156
4156
  <span class="ws-list-icon">${Do(n.type)}</span>
@@ -4166,7 +4166,7 @@ ${i}
4166
4166
  ${s?"Unpin":"Pin"}
4167
4167
  </button>
4168
4168
  </div>
4169
- `}function gk(e,t){return r`
4169
+ `}function hk(e,t){return r`
4170
4170
  <div class="workspace-breadcrumbs">
4171
4171
  ${e.map((n,s)=>r`
4172
4172
  ${s>0?r`<span class="breadcrumb-sep">/</span>`:h}
@@ -4176,13 +4176,13 @@ ${i}
4176
4176
  >${n.name}</button>
4177
4177
  `)}
4178
4178
  </div>
4179
- `}function mk(e){const{browseEntries:t,breadcrumbs:n,browseSearchQuery:s,browseSearchResults:a,onBrowseFolder:i,onBrowseSearch:o,onBrowseBack:l,onCreateFolder:c,onItemClick:u}=e,p=a??t??[];return r`
4179
+ `}function fk(e){const{browseEntries:t,breadcrumbs:n,browseSearchQuery:s,browseSearchResults:a,onBrowseFolder:i,onBrowseSearch:o,onBrowseBack:l,onCreateFolder:c,onItemClick:u}=e,p=a??t??[];return r`
4180
4180
  <div class="workspace-browser">
4181
4181
  <div class="workspace-browser-toolbar">
4182
4182
  <button class="workspace-browse-back" @click=${()=>l?.()}>
4183
4183
  &larr; Back
4184
4184
  </button>
4185
- ${n?gk(n,f=>i?.(f)):h}
4185
+ ${n?hk(n,f=>i?.(f)):h}
4186
4186
  <input
4187
4187
  type="text"
4188
4188
  class="workspace-browse-search"
@@ -4209,7 +4209,7 @@ ${i}
4209
4209
  `)}
4210
4210
  </div>
4211
4211
  </div>
4212
- `}function vk(e){const{workspace:t,itemSearchQuery:n,expandedFolders:s=new Set,showCompletedTasks:a=!1,onItemSearch:i,onBack:o,onItemClick:l,onSessionClick:c,onPinToggle:u,onPinSessionToggle:p,onToggleFolder:f,onToggleTaskComplete:m,onCreateTask:g,onToggleCompletedTasks:$,onStartTask:d,editingTaskId:v,onEditTask:S,onUpdateTask:_,onBatchPushToDrive:T}=e,A=ql(n,t.pinned).toSorted((D,De)=>De.modified.getTime()-D.modified.getTime()),C=jl(n,t.pinnedSessions),L=ql(n,t.outputs).filter(D=>!t.pinned.some(De=>De.path===D.path)),P=(t.folderTree?.length??0)>0,te=P?Qu(n,t.folderTree):[],Q=jl(n,t.sessions),de=new Set(t.pinnedSessions.map(D=>D.key)),R=new Set(t.pinned.map(D=>D.path)),N=n.trim().length>0,B=A.length>0||C.length>0,W=Q.length>0||t.sessions.length===0||N,F=pk(t.outputs),we=F.length>0&&!N,Se={expandedFolders:s,pinnedPaths:R,workspaceId:t.id,onToggleFolder:f,onItemClick:l,onPinToggle:u};return r`
4212
+ `}function gk(e){const{workspace:t,itemSearchQuery:n,expandedFolders:s=new Set,showCompletedTasks:a=!1,onItemSearch:i,onBack:o,onItemClick:l,onSessionClick:c,onPinToggle:u,onPinSessionToggle:p,onToggleFolder:f,onToggleTaskComplete:m,onCreateTask:g,onToggleCompletedTasks:$,onStartTask:d,editingTaskId:v,onEditTask:S,onUpdateTask:_,onBatchPushToDrive:T}=e,A=ql(n,t.pinned).toSorted((D,De)=>De.modified.getTime()-D.modified.getTime()),C=jl(n,t.pinnedSessions),L=ql(n,t.outputs).filter(D=>!t.pinned.some(De=>De.path===D.path)),P=(t.folderTree?.length??0)>0,te=P?Gu(n,t.folderTree):[],Q=jl(n,t.sessions),de=new Set(t.pinnedSessions.map(D=>D.key)),R=new Set(t.pinned.map(D=>D.path)),N=n.trim().length>0,B=A.length>0||C.length>0,W=Q.length>0||t.sessions.length===0||N,F=dk(t.outputs),we=F.length>0&&!N,Se={expandedFolders:s,pinnedPaths:R,workspaceId:t.id,onToggleFolder:f,onItemClick:l,onPinToggle:u};return r`
4213
4213
  <div class="workspaces-container">
4214
4214
  <div class="workspaces-header">
4215
4215
  <div class="workspaces-title">
@@ -4236,7 +4236,7 @@ ${i}
4236
4236
  </div>
4237
4237
 
4238
4238
  <div class="workspace-content">
4239
- ${e.browsePath!=null?mk(e):h}
4239
+ ${e.browsePath!=null?fk(e):h}
4240
4240
 
4241
4241
  ${B?r`
4242
4242
  <section class="ws-section">
@@ -4266,7 +4266,7 @@ ${i}
4266
4266
  </section>
4267
4267
  `:h}
4268
4268
 
4269
- ${yk({tasks:t.tasks??[],workspaceName:t.name,showCompleted:a,onToggleTaskComplete:m,onCreateTask:g,onToggleCompletedTasks:$,onStartTask:d,editingTaskId:v,onEditTask:S,onUpdateTask:_})}
4269
+ ${mk({tasks:t.tasks??[],workspaceName:t.name,showCompleted:a,onToggleTaskComplete:m,onCreateTask:g,onToggleCompletedTasks:$,onStartTask:d,editingTaskId:v,onEditTask:S,onUpdateTask:_})}
4270
4270
 
4271
4271
  ${we?r`
4272
4272
  <section class="ws-section">
@@ -4275,7 +4275,7 @@ ${i}
4275
4275
  <span>${F.length}</span>
4276
4276
  </div>
4277
4277
  <div class="ws-list">
4278
- ${F.map(D=>fk({workspaceId:t.id,entry:D,pinned:R.has(D.path),onOpen:l,onPinToggle:u}))}
4278
+ ${F.map(D=>pk({workspaceId:t.id,entry:D,pinned:R.has(D.path),onOpen:l,onPinToggle:u}))}
4279
4279
  </div>
4280
4280
  </section>
4281
4281
  `:h}
@@ -4287,7 +4287,7 @@ ${i}
4287
4287
  ${T&&L.length>0?r`<button class="ws-export-drive-btn" @click=${()=>{const D=L.map(De=>De.path);T(D)}}>Export to Drive</button>`:h}
4288
4288
  </div>
4289
4289
  <div class="ws-list ws-list--scroll">
4290
- ${P?te.length===0?r`<div class="ws-empty">No artifacts</div>`:te.map(D=>Ju(D,0,Se)):L.length===0?r`<div class="ws-empty">No artifacts</div>`:L.map(D=>Za({workspaceId:t.id,entry:D,pinned:!1,onOpen:l,onPinToggle:u}))}
4290
+ ${P?te.length===0?r`<div class="ws-empty">No artifacts</div>`:te.map(D=>Yu(D,0,Se)):L.length===0?r`<div class="ws-empty">No artifacts</div>`:L.map(D=>Za({workspaceId:t.id,entry:D,pinned:!1,onOpen:l,onPinToggle:u}))}
4291
4291
  </div>
4292
4292
  </section>
4293
4293
 
@@ -4333,7 +4333,7 @@ ${i}
4333
4333
  `:h}
4334
4334
  </div>
4335
4335
  </div>
4336
- `}function yk(e){const{tasks:t,workspaceName:n,showCompleted:s,onToggleTaskComplete:a,onCreateTask:i,onToggleCompletedTasks:o,onStartTask:l,editingTaskId:c,onEditTask:u,onUpdateTask:p}=e,f=Hs(t.filter(g=>g.status==="pending")),m=Hs(t.filter(g=>g.status==="complete"));return r`
4336
+ `}function mk(e){const{tasks:t,workspaceName:n,showCompleted:s,onToggleTaskComplete:a,onCreateTask:i,onToggleCompletedTasks:o,onStartTask:l,editingTaskId:c,onEditTask:u,onUpdateTask:p}=e,f=Hs(t.filter(g=>g.status==="pending")),m=Hs(t.filter(g=>g.status==="complete"));return r`
4337
4337
  <section class="ws-section">
4338
4338
  <div class="ws-section__header">
4339
4339
  <h3>Tasks</h3>
@@ -4363,12 +4363,12 @@ ${i}
4363
4363
  </form>
4364
4364
  `:h}
4365
4365
  </section>
4366
- `}function bk(e){const{connected:t,workspaces:n,selectedWorkspace:s,searchQuery:a,itemSearchQuery:i,expandedFolders:o,loading:l,createLoading:c,error:u,allTasks:p=[],taskFilter:f="outstanding",taskSort:m="due",showCompletedTasks:g=!1,editingTaskId:$,workspaceNames:d=[],onSearch:v,onItemSearch:S,onSelectWorkspace:_,onBack:T,onItemClick:A,onSessionClick:C,onPinToggle:L,onPinSessionToggle:P,onCreateWorkspace:te,onDeleteWorkspace:Q,onToggleFolder:de,onTeamSetup:R,onToggleTaskComplete:N,onCreateTask:B,onSetTaskFilter:W,onSetTaskSort:F,onToggleCompletedTasks:we,onStartTask:Se,onEditTask:D,onUpdateTask:De}=e,Ut=n.filter(j=>ck(a,`${j.name} ${j.path} ${j.type}`));return s?vk({workspace:s,itemSearchQuery:i??"",expandedFolders:o,showCompletedTasks:g,onItemSearch:S,onBack:T,onItemClick:A,onSessionClick:C,onPinToggle:L,onPinSessionToggle:P,onToggleFolder:de,onToggleTaskComplete:N,onCreateTask:B,onToggleCompletedTasks:we,onStartTask:Se,editingTaskId:$,onEditTask:D,onUpdateTask:De,browsePath:e.browsePath,browseEntries:e.browseEntries,breadcrumbs:e.breadcrumbs,browseSearchQuery:e.browseSearchQuery,browseSearchResults:e.browseSearchResults,onBrowseFolder:e.onBrowseFolder,onBrowseSearch:e.onBrowseSearch,onBrowseBack:e.onBrowseBack,onCreateFolder:e.onCreateFolder,onBatchPushToDrive:e.onBatchPushToDrive}):r`
4366
+ `}function vk(e){const{connected:t,workspaces:n,selectedWorkspace:s,searchQuery:a,itemSearchQuery:i,expandedFolders:o,loading:l,createLoading:c,error:u,allTasks:p=[],taskFilter:f="outstanding",taskSort:m="due",showCompletedTasks:g=!1,editingTaskId:$,workspaceNames:d=[],onSearch:v,onItemSearch:S,onSelectWorkspace:_,onBack:T,onItemClick:A,onSessionClick:C,onPinToggle:L,onPinSessionToggle:P,onCreateWorkspace:te,onDeleteWorkspace:Q,onToggleFolder:de,onTeamSetup:R,onToggleTaskComplete:N,onCreateTask:B,onSetTaskFilter:W,onSetTaskSort:F,onToggleCompletedTasks:we,onStartTask:Se,onEditTask:D,onUpdateTask:De}=e,Bt=n.filter(j=>rk(a,`${j.name} ${j.path} ${j.type}`));return s?gk({workspace:s,itemSearchQuery:i??"",expandedFolders:o,showCompletedTasks:g,onItemSearch:S,onBack:T,onItemClick:A,onSessionClick:C,onPinToggle:L,onPinSessionToggle:P,onToggleFolder:de,onToggleTaskComplete:N,onCreateTask:B,onToggleCompletedTasks:we,onStartTask:Se,editingTaskId:$,onEditTask:D,onUpdateTask:De,browsePath:e.browsePath,browseEntries:e.browseEntries,breadcrumbs:e.breadcrumbs,browseSearchQuery:e.browseSearchQuery,browseSearchResults:e.browseSearchResults,onBrowseFolder:e.onBrowseFolder,onBrowseSearch:e.onBrowseSearch,onBrowseBack:e.onBrowseBack,onCreateFolder:e.onCreateFolder,onBatchPushToDrive:e.onBatchPushToDrive}):r`
4367
4367
  <div class="workspaces-container">
4368
4368
  <div class="workspaces-toolbar">
4369
4369
  <form
4370
4370
  class="workspaces-create-form"
4371
- @submit=${async j=>{if(j.preventDefault(),c||!te)return;const gn=j.currentTarget,Y=new FormData(gn),mn=Y.get("name"),V=(typeof mn=="string"?mn:"").trim();if(!V)return;const nt=Y.get("type"),ht=(typeof nt=="string"?nt:"project").trim().toLowerCase(),st=ht==="team"||ht==="personal"?ht:"project",vn=Y.get("path"),zt=(typeof vn=="string"?vn:"").trim();await te({name:V,type:st,...zt?{path:zt}:{}})!==!1&&gn.reset()}}
4371
+ @submit=${async j=>{if(j.preventDefault(),c||!te)return;const gn=j.currentTarget,Y=new FormData(gn),mn=Y.get("name"),V=(typeof mn=="string"?mn:"").trim();if(!V)return;const nt=Y.get("type"),ht=(typeof nt=="string"?nt:"project").trim().toLowerCase(),st=ht==="team"||ht==="personal"?ht:"project",vn=Y.get("path"),Ut=(typeof vn=="string"?vn:"").trim();await te({name:V,type:st,...Ut?{path:Ut}:{}})!==!1&&gn.reset()}}
4372
4372
  >
4373
4373
  <input
4374
4374
  type="text"
@@ -4403,7 +4403,7 @@ ${i}
4403
4403
  .value=${a}
4404
4404
  @input=${j=>v?.(j.target.value)}
4405
4405
  />
4406
- <span class="workspaces-count">${Ut.length} workspaces</span>
4406
+ <span class="workspaces-count">${Bt.length} workspaces</span>
4407
4407
  <span class="workspaces-status ${t?"online":"offline"}">
4408
4408
  ${t?"Online":"Offline"}
4409
4409
  </span>
@@ -4420,19 +4420,19 @@ ${i}
4420
4420
  `:r`
4421
4421
  <div class="workspaces-body">
4422
4422
  <div class="workspace-grid">
4423
- ${Ut.length===0?r`
4423
+ ${Bt.length===0?r`
4424
4424
  <div class="workspaces-empty">
4425
4425
  <span class="workspaces-empty-icon">${t?"📭":"🔌"}</span>
4426
4426
  <span>${t?"No workspaces found":"Connect to gateway to see workspaces"}</span>
4427
4427
  </div>
4428
- `:Ut.map(j=>hk(j,_,Q))}
4428
+ `:Bt.map(j=>uk(j,_,Q))}
4429
4429
  </div>
4430
4430
 
4431
- ${wk({tasks:p,taskFilter:f,taskSort:m,onToggleTaskComplete:N,onSetTaskFilter:W,onSetTaskSort:F,onCreateTask:B,workspaceNames:d,onStartTask:Se,editingTaskId:$,onEditTask:D,onUpdateTask:De})}
4431
+ ${yk({tasks:p,taskFilter:f,taskSort:m,onToggleTaskComplete:N,onSetTaskFilter:W,onSetTaskSort:F,onCreateTask:B,workspaceNames:d,onStartTask:Se,editingTaskId:$,onEditTask:D,onUpdateTask:De})}
4432
4432
  </div>
4433
4433
  `}
4434
4434
  </div>
4435
- `}function wk(e){const{tasks:t,taskFilter:n,taskSort:s="due",onToggleTaskComplete:a,onSetTaskFilter:i,onSetTaskSort:o,onCreateTask:l,workspaceNames:c=[],onStartTask:u,editingTaskId:p,onEditTask:f,onUpdateTask:m}=e;if(t.length===0&&!l)return r``;let g;if(n==="outstanding")g=t.filter(d=>d.status==="pending");else if(n==="today"){const d=re();g=t.filter(v=>v.status==="pending"&&v.dueDate!=null&&v.dueDate<=d)}else n==="complete"?g=t.filter(d=>d.status==="complete"):g=t;const $=Hs(g,s);return r`
4435
+ `}function yk(e){const{tasks:t,taskFilter:n,taskSort:s="due",onToggleTaskComplete:a,onSetTaskFilter:i,onSetTaskSort:o,onCreateTask:l,workspaceNames:c=[],onStartTask:u,editingTaskId:p,onEditTask:f,onUpdateTask:m}=e;if(t.length===0&&!l)return r``;let g;if(n==="outstanding")g=t.filter(d=>d.status==="pending");else if(n==="today"){const d=re();g=t.filter(v=>v.status==="pending"&&v.dueDate!=null&&v.dueDate<=d)}else n==="complete"?g=t.filter(d=>d.status==="complete"):g=t;const $=Hs(g,s);return r`
4436
4436
  <div class="ws-all-tasks-section">
4437
4437
  <section class="ws-section">
4438
4438
  <div class="ws-section__header">
@@ -4490,7 +4490,7 @@ ${i}
4490
4490
  </div>
4491
4491
  </section>
4492
4492
  </div>
4493
- `}function $k(e){return e===re()}function Xu(e){const t=new Date(e+"T12:00:00");return kk(t)}function kk(e){const t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],n=["January","February","March","April","May","June","July","August","September","October","November","December"],s=t[e.getDay()],a=n[e.getMonth()],i=e.getDate();return`${s}, ${a} ${i}`}function Sk(e){if(!e)return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const s=new Date().getTime()-t.getTime(),a=Math.floor(s/(1e3*60));if(a<1)return"Just now";if(a<60)return`${a}m ago`;const i=Math.floor(a/60);return i<24?`${i}h ago`:t.toLocaleString()}function Ak(e){if(!e)return"";const t=e.split("/");return t[t.length-1]||e}function _k(e,t,n){const s=a=>{if(!e.onOpenFile)return;const i=Ku(a.target);i&&(a.preventDefault(),e.onOpenFile(i))};return r`
4493
+ `}function bk(e){return e===re()}function Ju(e){const t=new Date(e+"T12:00:00");return wk(t)}function wk(e){const t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],n=["January","February","March","April","May","June","July","August","September","October","November","December"],s=t[e.getDay()],a=n[e.getMonth()],i=e.getDate();return`${s}, ${a} ${i}`}function $k(e){if(!e)return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const s=new Date().getTime()-t.getTime(),a=Math.floor(s/(1e3*60));if(a<1)return"Just now";if(a<60)return`${a}m ago`;const i=Math.floor(a/60);return i<24?`${i}h ago`:t.toLocaleString()}function kk(e){if(!e)return"";const t=e.split("/");return t[t.length-1]||e}function Sk(e,t,n){const s=a=>{if(!e.onOpenFile)return;const i=zu(a.target);i&&(a.preventDefault(),e.onOpenFile(i))};return r`
4494
4494
  <div class="my-day-card agent-log-section brief-editor">
4495
4495
  <div class="my-day-card-header">
4496
4496
  <div class="my-day-card-title">
@@ -4498,9 +4498,9 @@ ${i}
4498
4498
  <span>AGENT LOG</span>
4499
4499
  </div>
4500
4500
  <div class="agent-log-header-actions">
4501
- ${t?.updatedAt?r`<span class="brief-updated">${Sk(t.updatedAt)}</span>`:h}
4501
+ ${t?.updatedAt?r`<span class="brief-updated">${$k(t.updatedAt)}</span>`:h}
4502
4502
  ${t?.sourcePath?r`<span class="agent-log-file" title=${t.sourcePath}>
4503
- ${Ak(t.sourcePath)}
4503
+ ${kk(t.sourcePath)}
4504
4504
  </span>`:h}
4505
4505
  ${e.onAgentLogRefresh?r`<button class="brief-refresh-btn agent-log-refresh-btn"
4506
4506
  @click=${e.onAgentLogRefresh} title="Refresh agent log">&#x21BB;</button>`:h}
@@ -4512,12 +4512,12 @@ ${i}
4512
4512
  </div>`:r`<div class="my-day-empty">No agent day entry found for ${n}. Create/update <code>AGENT-DAY.md</code> and refresh.</div>`}
4513
4513
  </div>
4514
4514
  </div>
4515
- `}function Tk(e){return r`
4515
+ `}function Ak(e){return r`
4516
4516
  <form class="ws-task-create-form" @submit=${t=>{t.preventDefault();const s=t.currentTarget.querySelector("input"),a=s.value.trim();a&&(e(a),s.value="")}}>
4517
4517
  <input type="text" class="ws-task-create-input" placeholder="Add a task for today..." />
4518
4518
  <button type="submit" class="ws-task-create-btn">Add</button>
4519
4519
  </form>
4520
- `}function xk(e){const t=Hs(e.todayTasks??[],"due"),n=t.filter(a=>a.status==="pending"),s=t.filter(a=>a.status==="complete");return r`
4520
+ `}function _k(e){const t=Hs(e.todayTasks??[],"due"),n=t.filter(a=>a.status==="pending"),s=t.filter(a=>a.status==="complete");return r`
4521
4521
  <div class="my-day-card today-tasks-panel">
4522
4522
  <div class="my-day-card-header">
4523
4523
  <div class="my-day-card-title">
@@ -4530,7 +4530,7 @@ ${i}
4530
4530
  </div>
4531
4531
  <div class="my-day-card-content">
4532
4532
  ${e.todayTasksLoading?r`<div class="brief-loading"><div class="spinner"></div><span>Loading tasks...</span></div>`:r`
4533
- ${e.onCreateTask?Tk(e.onCreateTask):h}
4533
+ ${e.onCreateTask?Ak(e.onCreateTask):h}
4534
4534
  <div class="today-tasks-list">
4535
4535
  ${n.length===0&&s.length===0?r`<div class="today-tasks-empty">No tasks for today. Add one above or drop tasks in your daily brief.</div>`:n.map(a=>Ei(a,e.onToggleTaskComplete,e.onStartTask,e.editingTaskId,e.onEditTask,e.onUpdateTask))}
4536
4536
  </div>
@@ -4545,7 +4545,7 @@ ${i}
4545
4545
  `}
4546
4546
  </div>
4547
4547
  </div>
4548
- `}function Ck(e,t){const n=e.status==="review";return r`
4548
+ `}function Tk(e,t){const n=e.status==="review";return r`
4549
4549
  <div class="decision-card">
4550
4550
  <span class="decision-card-status ${n?"decision-card-status--review":"decision-card-status--done"}">${n?"Needs Review":"Complete"}</span>
4551
4551
  <h4 class="decision-card-title">${e.title}</h4>
@@ -4567,17 +4567,17 @@ ${i}
4567
4567
  ${e.prUrl?r`<a class="decision-card-btn decision-card-btn--view" href="${e.prUrl}" target="_blank" rel="noopener">View PR</a>`:h}
4568
4568
  </div>
4569
4569
  </div>
4570
- `}function Ek(e){if(!e.items.length)return h;const t=e.items.length>3;return r`
4570
+ `}function xk(e){if(!e.items.length)return h;const t=e.items.length>3;return r`
4571
4571
  <div class="decision-cards">
4572
4572
  <div class="decision-cards-header">
4573
4573
  <h3>Agent Results</h3>
4574
4574
  <span class="count-badge">${e.items.length}</span>
4575
4575
  </div>
4576
4576
  <div class="decision-cards-list ${t?"decision-cards-list--scroll":""}">
4577
- ${e.items.map(n=>Ck(n,e))}
4577
+ ${e.items.map(n=>Tk(n,e))}
4578
4578
  </div>
4579
4579
  </div>
4580
- `}function Lk(e){const t=re(),n=e.selectedDate??t,s=$k(n),a=Xu(n),i=e.viewMode??"brief";return r`
4580
+ `}function Ck(e){const t=re(),n=e.selectedDate??t,s=bk(n),a=Ju(n),i=e.viewMode??"brief";return r`
4581
4581
  <div class="my-day-toolbar">
4582
4582
  <div class="today-date-nav">
4583
4583
  ${e.onDatePrev?r`<button class="today-date-btn" @click=${e.onDatePrev} title="Previous day">&#x2039;</button>`:h}
@@ -4597,14 +4597,14 @@ ${i}
4597
4597
  title="Start your morning focus ritual">\u2600\uFE0F Start Morning Set</button>`:h}
4598
4598
  ${e.onRefresh?r`<button class="my-day-refresh-btn" @click=${e.onRefresh} title="Refresh">&#x21BB;</button>`:null}
4599
4599
  </div>
4600
- `}function Rk(e){return r`
4600
+ `}function Ek(e){return r`
4601
4601
  <div class="command-center">
4602
- ${e.decisionCards&&e.decisionCards.items.length>0?Ek(e.decisionCards):h}
4602
+ ${e.decisionCards&&e.decisionCards.items.length>0?xk(e.decisionCards):h}
4603
4603
  <div class="command-center-tasks">
4604
- ${xk(e)}
4604
+ ${_k(e)}
4605
4605
  </div>
4606
4606
  </div>
4607
- `}function Pk(e){const t=re(),n=e.selectedDate??t,s=e.viewMode??"brief",a=e.agentLog??null;if(e.loading)return r`
4607
+ `}function Lk(e){const t=re(),n=e.selectedDate??t,s=e.viewMode??"brief",a=e.agentLog??null;if(e.loading)return r`
4608
4608
  <div class="my-day-container">
4609
4609
  <div class="my-day-loading">
4610
4610
  <div class="spinner"></div>
@@ -4621,12 +4621,12 @@ ${i}
4621
4621
  </div>
4622
4622
  `;const i={connected:e.connected,data:e.dailyBrief??null,loading:e.dailyBriefLoading,error:e.dailyBriefError,onRefresh:e.onBriefRefresh,onOpenInObsidian:e.onBriefOpenInObsidian,onSaveBrief:e.onBriefSave,onToggleCheckbox:e.onBriefToggleCheckbox,onOpenFile:e.onOpenFile};return r`
4623
4623
  <div class="my-day-container">
4624
- ${s==="brief"?r`<div class="my-day-brief-full">${lk(i)}</div>`:s==="command-center"?Rk(e):r`<div class="my-day-brief-full">${_k(e,a,Xu(n))}</div>`}
4624
+ ${s==="brief"?r`<div class="my-day-brief-full">${ok(i)}</div>`:s==="command-center"?Ek(e):r`<div class="my-day-brief-full">${Sk(e,a,Ju(n))}</div>`}
4625
4625
  </div>
4626
- `}function Ik(e){const t=Bk(e),n=jk(e);return r`
4627
- ${Vk(n)}
4628
- ${Hk(t)}
4629
- ${Mk(e)}
4626
+ `}function Rk(e){const t=Nk(e),n=Wk(e);return r`
4627
+ ${jk(n)}
4628
+ ${qk(t)}
4629
+ ${Pk(e)}
4630
4630
  <section class="card">
4631
4631
  <div class="row" style="justify-content: space-between;">
4632
4632
  <div>
@@ -4640,10 +4640,10 @@ ${i}
4640
4640
  <div class="list" style="margin-top: 16px;">
4641
4641
  ${e.nodes.length===0?r`
4642
4642
  <div class="muted">No nodes found.</div>
4643
- `:e.nodes.map(s=>s0(s))}
4643
+ `:e.nodes.map(s=>t0(s))}
4644
4644
  </div>
4645
4645
  </section>
4646
- `}function Mk(e){const t=e.devicesList??{pending:[],paired:[]},n=Array.isArray(t.pending)?t.pending:[],s=Array.isArray(t.paired)?t.paired:[];return r`
4646
+ `}function Pk(e){const t=e.devicesList??{pending:[],paired:[]},n=Array.isArray(t.pending)?t.pending:[],s=Array.isArray(t.paired)?t.paired:[];return r`
4647
4647
  <section class="card">
4648
4648
  <div class="row" style="justify-content: space-between;">
4649
4649
  <div>
@@ -4658,18 +4658,18 @@ ${i}
4658
4658
  <div class="list" style="margin-top: 16px;">
4659
4659
  ${n.length>0?r`
4660
4660
  <div class="muted" style="margin-bottom: 8px;">Pending</div>
4661
- ${n.map(a=>Dk(a,e))}
4661
+ ${n.map(a=>Ik(a,e))}
4662
4662
  `:h}
4663
4663
  ${s.length>0?r`
4664
4664
  <div class="muted" style="margin-top: 12px; margin-bottom: 8px;">Paired</div>
4665
- ${s.map(a=>Ok(a,e))}
4665
+ ${s.map(a=>Mk(a,e))}
4666
4666
  `:h}
4667
4667
  ${n.length===0&&s.length===0?r`
4668
4668
  <div class="muted">No paired devices.</div>
4669
4669
  `:h}
4670
4670
  </div>
4671
4671
  </section>
4672
- `}function Dk(e,t){const n=e.displayName?.trim()||e.deviceId,s=typeof e.ts=="number"?z(e.ts):"n/a",a=e.role?.trim()?`role: ${e.role}`:"role: -",i=e.isRepair?" · repair":"",o=e.remoteIp?` · ${e.remoteIp}`:"";return r`
4672
+ `}function Ik(e,t){const n=e.displayName?.trim()||e.deviceId,s=typeof e.ts=="number"?z(e.ts):"n/a",a=e.role?.trim()?`role: ${e.role}`:"role: -",i=e.isRepair?" · repair":"",o=e.remoteIp?` · ${e.remoteIp}`:"";return r`
4673
4673
  <div class="list-item">
4674
4674
  <div class="list-main">
4675
4675
  <div class="list-title">${n}</div>
@@ -4689,7 +4689,7 @@ ${i}
4689
4689
  </div>
4690
4690
  </div>
4691
4691
  </div>
4692
- `}function Ok(e,t){const n=e.displayName?.trim()||e.deviceId,s=e.remoteIp?` · ${e.remoteIp}`:"",a=`roles: ${ai(e.roles)}`,i=`scopes: ${ai(e.scopes)}`,o=Array.isArray(e.tokens)?e.tokens:[];return r`
4692
+ `}function Mk(e,t){const n=e.displayName?.trim()||e.deviceId,s=e.remoteIp?` · ${e.remoteIp}`:"",a=`roles: ${ai(e.roles)}`,i=`scopes: ${ai(e.scopes)}`,o=Array.isArray(e.tokens)?e.tokens:[];return r`
4693
4693
  <div class="list-item">
4694
4694
  <div class="list-main">
4695
4695
  <div class="list-title">${n}</div>
@@ -4700,12 +4700,12 @@ ${i}
4700
4700
  `:r`
4701
4701
  <div class="muted" style="margin-top: 10px;">Tokens</div>
4702
4702
  <div style="display: flex; flex-direction: column; gap: 8px; margin-top: 6px;">
4703
- ${o.map(l=>Nk(e.deviceId,l,t))}
4703
+ ${o.map(l=>Dk(e.deviceId,l,t))}
4704
4704
  </div>
4705
4705
  `}
4706
4706
  </div>
4707
4707
  </div>
4708
- `}function Nk(e,t,n){const s=t.revokedAtMs?"revoked":"active",a=`scopes: ${ai(t.scopes)}`,i=z(t.rotatedAtMs??t.createdAtMs??t.lastUsedAtMs??null);return r`
4708
+ `}function Dk(e,t,n){const s=t.revokedAtMs?"revoked":"active",a=`scopes: ${ai(t.scopes)}`,i=z(t.rotatedAtMs??t.createdAtMs??t.lastUsedAtMs??null);return r`
4709
4709
  <div class="row" style="justify-content: space-between; gap: 8px;">
4710
4710
  <div class="list-sub">${t.role} · ${s} · ${a} · ${i}</div>
4711
4711
  <div class="row" style="justify-content: flex-end; gap: 6px; flex-wrap: wrap;">
@@ -4725,7 +4725,7 @@ ${i}
4725
4725
  `}
4726
4726
  </div>
4727
4727
  </div>
4728
- `}const ct="__defaults__",Hl=[{value:"deny",label:"Deny"},{value:"allowlist",label:"Allowlist"},{value:"full",label:"Full"}],Fk=[{value:"off",label:"Off"},{value:"on-miss",label:"On miss"},{value:"always",label:"Always"}];function Bk(e){const t=e.configForm,n=e0(e.nodes),{defaultBinding:s,agents:a}=n0(t),i=!!t,o=e.configSaving||e.configFormMode==="raw";return{ready:i,disabled:o,configDirty:e.configDirty,configLoading:e.configLoading,configSaving:e.configSaving,defaultBinding:s,agents:a,nodes:n,onBindDefault:e.onBindDefault,onBindAgent:e.onBindAgent,onSave:e.onSaveBindings,onLoadConfig:e.onLoadConfig,formMode:e.configFormMode}}function Vl(e){return e==="allowlist"||e==="full"||e==="deny"?e:"deny"}function Uk(e){return e==="always"||e==="off"||e==="on-miss"?e:"on-miss"}function zk(e){const t=e?.defaults??{};return{security:Vl(t.security),ask:Uk(t.ask),askFallback:Vl(t.askFallback??"deny"),autoAllowSkills:!!(t.autoAllowSkills??!1)}}function Kk(e){const t=e?.agents??{},n=Array.isArray(t.list)?t.list:[],s=[];return n.forEach(a=>{if(!a||typeof a!="object")return;const i=a,o=typeof i.id=="string"?i.id.trim():"";if(!o)return;const l=typeof i.name=="string"?i.name.trim():void 0,c=i.default===!0;s.push({id:o,name:l||void 0,isDefault:c})}),s}function Wk(e,t){const n=Kk(e),s=Object.keys(t?.agents??{}),a=new Map;n.forEach(o=>a.set(o.id,o)),s.forEach(o=>{a.has(o)||a.set(o,{id:o})});const i=Array.from(a.values());return i.length===0&&i.push({id:"main",isDefault:!0}),i.sort((o,l)=>{if(o.isDefault&&!l.isDefault)return-1;if(!o.isDefault&&l.isDefault)return 1;const c=o.name?.trim()?o.name:o.id,u=l.name?.trim()?l.name:l.id;return c.localeCompare(u)}),i}function qk(e,t){return e===ct?ct:e&&t.some(n=>n.id===e)?e:ct}function jk(e){const t=e.execApprovalsForm??e.execApprovalsSnapshot?.file??null,n=!!t,s=zk(t),a=Wk(e.configForm,t),i=t0(e.nodes),o=e.execApprovalsTarget;let l=o==="node"&&e.execApprovalsTargetNodeId?e.execApprovalsTargetNodeId:null;o==="node"&&l&&!i.some(f=>f.id===l)&&(l=null);const c=qk(e.execApprovalsSelectedAgent,a),u=c!==ct?(t?.agents??{})[c]??null:null,p=Array.isArray(u?.allowlist)?u.allowlist??[]:[];return{ready:n,disabled:e.execApprovalsSaving||e.execApprovalsLoading,dirty:e.execApprovalsDirty,loading:e.execApprovalsLoading,saving:e.execApprovalsSaving,form:t,defaults:s,selectedScope:c,selectedAgent:u,agents:a,allowlist:p,target:o,targetNodeId:l,targetNodes:i,onSelectScope:e.onExecApprovalsSelectAgent,onSelectTarget:e.onExecApprovalsTargetChange,onPatch:e.onExecApprovalsPatch,onRemove:e.onExecApprovalsRemove,onLoad:e.onLoadExecApprovals,onSave:e.onSaveExecApprovals}}function Hk(e){const t=e.nodes.length>0,n=e.defaultBinding??"";return r`
4728
+ `}const ct="__defaults__",Hl=[{value:"deny",label:"Deny"},{value:"allowlist",label:"Allowlist"},{value:"full",label:"Full"}],Ok=[{value:"off",label:"Off"},{value:"on-miss",label:"On miss"},{value:"always",label:"Always"}];function Nk(e){const t=e.configForm,n=Xk(e.nodes),{defaultBinding:s,agents:a}=e0(t),i=!!t,o=e.configSaving||e.configFormMode==="raw";return{ready:i,disabled:o,configDirty:e.configDirty,configLoading:e.configLoading,configSaving:e.configSaving,defaultBinding:s,agents:a,nodes:n,onBindDefault:e.onBindDefault,onBindAgent:e.onBindAgent,onSave:e.onSaveBindings,onLoadConfig:e.onLoadConfig,formMode:e.configFormMode}}function Vl(e){return e==="allowlist"||e==="full"||e==="deny"?e:"deny"}function Fk(e){return e==="always"||e==="off"||e==="on-miss"?e:"on-miss"}function Bk(e){const t=e?.defaults??{};return{security:Vl(t.security),ask:Fk(t.ask),askFallback:Vl(t.askFallback??"deny"),autoAllowSkills:!!(t.autoAllowSkills??!1)}}function Uk(e){const t=e?.agents??{},n=Array.isArray(t.list)?t.list:[],s=[];return n.forEach(a=>{if(!a||typeof a!="object")return;const i=a,o=typeof i.id=="string"?i.id.trim():"";if(!o)return;const l=typeof i.name=="string"?i.name.trim():void 0,c=i.default===!0;s.push({id:o,name:l||void 0,isDefault:c})}),s}function zk(e,t){const n=Uk(e),s=Object.keys(t?.agents??{}),a=new Map;n.forEach(o=>a.set(o.id,o)),s.forEach(o=>{a.has(o)||a.set(o,{id:o})});const i=Array.from(a.values());return i.length===0&&i.push({id:"main",isDefault:!0}),i.sort((o,l)=>{if(o.isDefault&&!l.isDefault)return-1;if(!o.isDefault&&l.isDefault)return 1;const c=o.name?.trim()?o.name:o.id,u=l.name?.trim()?l.name:l.id;return c.localeCompare(u)}),i}function Kk(e,t){return e===ct?ct:e&&t.some(n=>n.id===e)?e:ct}function Wk(e){const t=e.execApprovalsForm??e.execApprovalsSnapshot?.file??null,n=!!t,s=Bk(t),a=zk(e.configForm,t),i=Zk(e.nodes),o=e.execApprovalsTarget;let l=o==="node"&&e.execApprovalsTargetNodeId?e.execApprovalsTargetNodeId:null;o==="node"&&l&&!i.some(f=>f.id===l)&&(l=null);const c=Kk(e.execApprovalsSelectedAgent,a),u=c!==ct?(t?.agents??{})[c]??null:null,p=Array.isArray(u?.allowlist)?u.allowlist??[]:[];return{ready:n,disabled:e.execApprovalsSaving||e.execApprovalsLoading,dirty:e.execApprovalsDirty,loading:e.execApprovalsLoading,saving:e.execApprovalsSaving,form:t,defaults:s,selectedScope:c,selectedAgent:u,agents:a,allowlist:p,target:o,targetNodeId:l,targetNodes:i,onSelectScope:e.onExecApprovalsSelectAgent,onSelectTarget:e.onExecApprovalsTargetChange,onPatch:e.onExecApprovalsPatch,onRemove:e.onExecApprovalsRemove,onLoad:e.onLoadExecApprovals,onSave:e.onSaveExecApprovals}}function qk(e){const t=e.nodes.length>0,n=e.defaultBinding??"";return r`
4729
4729
  <section class="card">
4730
4730
  <div class="row" style="justify-content: space-between; align-items: center;">
4731
4731
  <div>
@@ -4780,7 +4780,7 @@ ${i}
4780
4780
 
4781
4781
  ${e.agents.length===0?r`
4782
4782
  <div class="muted">No agents found.</div>
4783
- `:e.agents.map(s=>Zk(s,e))}
4783
+ `:e.agents.map(s=>Jk(s,e))}
4784
4784
  </div>
4785
4785
  `:r`<div class="row" style="margin-top: 12px; gap: 12px;">
4786
4786
  <div class="muted">Load config to edit bindings.</div>
@@ -4789,7 +4789,7 @@ ${i}
4789
4789
  </button>
4790
4790
  </div>`}
4791
4791
  </section>
4792
- `}function Vk(e){const t=e.ready,n=e.target!=="node"||!!e.targetNodeId;return r`
4792
+ `}function jk(e){const t=e.ready,n=e.target!=="node"||!!e.targetNodeId;return r`
4793
4793
  <section class="card">
4794
4794
  <div class="row" style="justify-content: space-between; align-items: center;">
4795
4795
  <div>
@@ -4807,12 +4807,12 @@ ${i}
4807
4807
  </button>
4808
4808
  </div>
4809
4809
 
4810
- ${Gk(e)}
4810
+ ${Hk(e)}
4811
4811
 
4812
4812
  ${t?r`
4813
- ${Qk(e)}
4814
- ${Yk(e)}
4815
- ${e.selectedScope===ct?h:Jk(e)}
4813
+ ${Vk(e)}
4814
+ ${Gk(e)}
4815
+ ${e.selectedScope===ct?h:Qk(e)}
4816
4816
  `:r`<div class="row" style="margin-top: 12px; gap: 12px;">
4817
4817
  <div class="muted">Load exec approvals to edit allowlists.</div>
4818
4818
  <button class="btn" ?disabled=${e.loading||!n} @click=${e.onLoad}>
@@ -4820,7 +4820,7 @@ ${i}
4820
4820
  </button>
4821
4821
  </div>`}
4822
4822
  </section>
4823
- `}function Gk(e){const t=e.targetNodes.length>0,n=e.targetNodeId??"";return r`
4823
+ `}function Hk(e){const t=e.targetNodes.length>0,n=e.targetNodeId??"";return r`
4824
4824
  <div class="list" style="margin-top: 12px;">
4825
4825
  <div class="list-item">
4826
4826
  <div class="list-main">
@@ -4863,7 +4863,7 @@ ${i}
4863
4863
  <div class="muted">No nodes advertise exec approvals yet.</div>
4864
4864
  `:h}
4865
4865
  </div>
4866
- `}function Qk(e){return r`
4866
+ `}function Vk(e){return r`
4867
4867
  <div class="row" style="margin-top: 12px; gap: 8px; flex-wrap: wrap;">
4868
4868
  <span class="label">Scope</span>
4869
4869
  <div class="row" style="gap: 8px; flex-wrap: wrap;">
@@ -4883,7 +4883,7 @@ ${i}
4883
4883
  `})}
4884
4884
  </div>
4885
4885
  </div>
4886
- `}function Yk(e){const t=e.selectedScope===ct,n=e.defaults,s=e.selectedAgent??{},a=t?["defaults"]:["agents",e.selectedScope],i=typeof s.security=="string"?s.security:void 0,o=typeof s.ask=="string"?s.ask:void 0,l=typeof s.askFallback=="string"?s.askFallback:void 0,c=t?n.security:i??"__default__",u=t?n.ask:o??"__default__",p=t?n.askFallback:l??"__default__",f=typeof s.autoAllowSkills=="boolean"?s.autoAllowSkills:void 0,m=f??n.autoAllowSkills,g=f==null;return r`
4886
+ `}function Gk(e){const t=e.selectedScope===ct,n=e.defaults,s=e.selectedAgent??{},a=t?["defaults"]:["agents",e.selectedScope],i=typeof s.security=="string"?s.security:void 0,o=typeof s.ask=="string"?s.ask:void 0,l=typeof s.askFallback=="string"?s.askFallback:void 0,c=t?n.security:i??"__default__",u=t?n.ask:o??"__default__",p=t?n.askFallback:l??"__default__",f=typeof s.autoAllowSkills=="boolean"?s.autoAllowSkills:void 0,m=f??n.autoAllowSkills,g=f==null;return r`
4887
4887
  <div class="list" style="margin-top: 16px;">
4888
4888
  <div class="list-item">
4889
4889
  <div class="list-main">
@@ -4930,7 +4930,7 @@ ${i}
4930
4930
  ${t?h:r`<option value="__default__" ?selected=${u==="__default__"}>
4931
4931
  Use default (${n.ask})
4932
4932
  </option>`}
4933
- ${Fk.map($=>r`<option
4933
+ ${Ok.map($=>r`<option
4934
4934
  value=${$.value}
4935
4935
  ?selected=${u===$.value}
4936
4936
  >
@@ -4996,7 +4996,7 @@ ${i}
4996
4996
  </div>
4997
4997
  </div>
4998
4998
  </div>
4999
- `}function Jk(e){const t=["agents",e.selectedScope,"allowlist"],n=e.allowlist;return r`
4999
+ `}function Qk(e){const t=["agents",e.selectedScope,"allowlist"],n=e.allowlist;return r`
5000
5000
  <div class="row" style="margin-top: 18px; justify-content: space-between;">
5001
5001
  <div>
5002
5002
  <div class="card-title">Allowlist</div>
@@ -5013,9 +5013,9 @@ ${i}
5013
5013
  <div class="list" style="margin-top: 12px;">
5014
5014
  ${n.length===0?r`
5015
5015
  <div class="muted">No allowlist entries yet.</div>
5016
- `:n.map((s,a)=>Xk(e,s,a))}
5016
+ `:n.map((s,a)=>Yk(e,s,a))}
5017
5017
  </div>
5018
- `}function Xk(e,t,n){const s=t.lastUsedAt?z(t.lastUsedAt):"never",a=t.lastUsedCommand?ii(t.lastUsedCommand,120):null,i=t.lastResolvedPath?ii(t.lastResolvedPath,120):null;return r`
5018
+ `}function Yk(e,t,n){const s=t.lastUsedAt?z(t.lastUsedAt):"never",a=t.lastUsedCommand?ii(t.lastUsedCommand,120):null,i=t.lastResolvedPath?ii(t.lastResolvedPath,120):null;return r`
5019
5019
  <div class="list-item">
5020
5020
  <div class="list-main">
5021
5021
  <div class="list-title">${t.pattern?.trim()?t.pattern:"New pattern"}</div>
@@ -5042,7 +5042,7 @@ ${i}
5042
5042
  </button>
5043
5043
  </div>
5044
5044
  </div>
5045
- `}function Zk(e,t){const n=e.binding??"__default__",s=e.name?.trim()?`${e.name} (${e.id})`:e.id,a=t.nodes.length>0;return r`
5045
+ `}function Jk(e,t){const n=e.binding??"__default__",s=e.name?.trim()?`${e.name} (${e.id})`:e.id,a=t.nodes.length>0;return r`
5046
5046
  <div class="list-item">
5047
5047
  <div class="list-main">
5048
5048
  <div class="list-title">${s}</div>
@@ -5071,7 +5071,7 @@ ${i}
5071
5071
  </label>
5072
5072
  </div>
5073
5073
  </div>
5074
- `}function e0(e){const t=[];for(const n of e){if(!(Array.isArray(n.commands)?n.commands:[]).some(l=>String(l)==="system.run"))continue;const i=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!i)continue;const o=typeof n.displayName=="string"&&n.displayName.trim()?n.displayName.trim():i;t.push({id:i,label:o===i?i:`${o} · ${i}`})}return t.sort((n,s)=>n.label.localeCompare(s.label)),t}function t0(e){const t=[];for(const n of e){if(!(Array.isArray(n.commands)?n.commands:[]).some(l=>String(l)==="system.execApprovals.get"||String(l)==="system.execApprovals.set"))continue;const i=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!i)continue;const o=typeof n.displayName=="string"&&n.displayName.trim()?n.displayName.trim():i;t.push({id:i,label:o===i?i:`${o} · ${i}`})}return t.sort((n,s)=>n.label.localeCompare(s.label)),t}function n0(e){const t={id:"main",name:void 0,index:0,isDefault:!0,binding:null};if(!e||typeof e!="object")return{defaultBinding:null,agents:[t]};const s=(e.tools??{}).exec??{},a=typeof s.node=="string"&&s.node.trim()?s.node.trim():null,i=e.agents??{},o=Array.isArray(i.list)?i.list:[];if(o.length===0)return{defaultBinding:a,agents:[t]};const l=[];return o.forEach((c,u)=>{if(!c||typeof c!="object")return;const p=c,f=typeof p.id=="string"?p.id.trim():"";if(!f)return;const m=typeof p.name=="string"?p.name.trim():void 0,g=p.default===!0,d=(p.tools??{}).exec??{},v=typeof d.node=="string"&&d.node.trim()?d.node.trim():null;l.push({id:f,name:m||void 0,index:u,isDefault:g,binding:v})}),l.length===0&&l.push(t),{defaultBinding:a,agents:l}}function s0(e){const t=!!e.connected,n=!!e.paired,s=typeof e.displayName=="string"&&e.displayName.trim()||(typeof e.nodeId=="string"?e.nodeId:"unknown"),a=Array.isArray(e.caps)?e.caps:[],i=Array.isArray(e.commands)?e.commands:[];return r`
5074
+ `}function Xk(e){const t=[];for(const n of e){if(!(Array.isArray(n.commands)?n.commands:[]).some(l=>String(l)==="system.run"))continue;const i=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!i)continue;const o=typeof n.displayName=="string"&&n.displayName.trim()?n.displayName.trim():i;t.push({id:i,label:o===i?i:`${o} · ${i}`})}return t.sort((n,s)=>n.label.localeCompare(s.label)),t}function Zk(e){const t=[];for(const n of e){if(!(Array.isArray(n.commands)?n.commands:[]).some(l=>String(l)==="system.execApprovals.get"||String(l)==="system.execApprovals.set"))continue;const i=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!i)continue;const o=typeof n.displayName=="string"&&n.displayName.trim()?n.displayName.trim():i;t.push({id:i,label:o===i?i:`${o} · ${i}`})}return t.sort((n,s)=>n.label.localeCompare(s.label)),t}function e0(e){const t={id:"main",name:void 0,index:0,isDefault:!0,binding:null};if(!e||typeof e!="object")return{defaultBinding:null,agents:[t]};const s=(e.tools??{}).exec??{},a=typeof s.node=="string"&&s.node.trim()?s.node.trim():null,i=e.agents??{},o=Array.isArray(i.list)?i.list:[];if(o.length===0)return{defaultBinding:a,agents:[t]};const l=[];return o.forEach((c,u)=>{if(!c||typeof c!="object")return;const p=c,f=typeof p.id=="string"?p.id.trim():"";if(!f)return;const m=typeof p.name=="string"?p.name.trim():void 0,g=p.default===!0,d=(p.tools??{}).exec??{},v=typeof d.node=="string"&&d.node.trim()?d.node.trim():null;l.push({id:f,name:m||void 0,index:u,isDefault:g,binding:v})}),l.length===0&&l.push(t),{defaultBinding:a,agents:l}}function t0(e){const t=!!e.connected,n=!!e.paired,s=typeof e.displayName=="string"&&e.displayName.trim()||(typeof e.nodeId=="string"?e.nodeId:"unknown"),a=Array.isArray(e.caps)?e.caps:[],i=Array.isArray(e.commands)?e.commands:[];return r`
5075
5075
  <div class="list-item">
5076
5076
  <div class="list-main">
5077
5077
  <div class="list-title">${s}</div>
@@ -5090,7 +5090,7 @@ ${i}
5090
5090
  </div>
5091
5091
  </div>
5092
5092
  </div>
5093
- `}function a0(e){const t=e.hello?.snapshot,n=t?.uptimeMs?Fi(t.uptimeMs):"n/a",s=t?.policy?.tickIntervalMs?`${t.policy.tickIntervalMs}ms`:"n/a",a=(()=>{if(e.connected||!e.lastError)return null;const o=e.lastError.toLowerCase();if(!(o.includes("unauthorized")||o.includes("connect failed")))return null;const c=!!e.settings.token.trim(),u=!!e.password.trim();return!c&&!u?r`
5093
+ `}function n0(e){const t=e.hello?.snapshot,n=t?.uptimeMs?Fi(t.uptimeMs):"n/a",s=t?.policy?.tickIntervalMs?`${t.policy.tickIntervalMs}ms`:"n/a",a=(()=>{if(e.connected||!e.lastError)return null;const o=e.lastError.toLowerCase();if(!(o.includes("unauthorized")||o.includes("connect failed")))return null;const c=!!e.settings.token.trim(),u=!!e.password.trim();return!c&&!u?r`
5094
5094
  <div class="muted" style="margin-top: 8px">
5095
5095
  This gateway requires auth. Add a token or password, then click Connect.
5096
5096
  <div style="margin-top: 6px">
@@ -5250,7 +5250,7 @@ ${i}
5250
5250
  <div class="stat-value">
5251
5251
  ${e.cronEnabled==null?"n/a":e.cronEnabled?"Enabled":"Disabled"}
5252
5252
  </div>
5253
- <div class="muted">Next wake ${zu(e.cronNext)}</div>
5253
+ <div class="muted">Next wake ${Uu(e.cronNext)}</div>
5254
5254
  </div>
5255
5255
  </section>
5256
5256
 
@@ -5348,20 +5348,20 @@ ${i}
5348
5348
  </div>
5349
5349
  </div>
5350
5350
  </section>
5351
- `}const i0=["","off","minimal","low","medium","high"],o0=["","off","on"],r0=[{value:"",label:"inherit"},{value:"off",label:"off (explicit)"},{value:"on",label:"on"}],l0=["","off","on","stream"];function c0(e){if(!e)return"";const t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t}function Zu(e){return c0(e)==="zai"}function d0(e){return Zu(e)?o0:i0}function u0(e,t){return!t||!e||e==="off"?e:"on"}function p0(e,t){return e?t&&e==="on"?"low":e:null}function h0(e){switch(e){case"idle-7d":return"Idle > 7 days";case"task-complete":return"Task completed";case"manual":return"Manual";default:return e}}function f0(){return r`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
5351
+ `}const s0=["","off","minimal","low","medium","high"],a0=["","off","on"],i0=[{value:"",label:"inherit"},{value:"off",label:"off (explicit)"},{value:"on",label:"on"}],o0=["","off","on","stream"];function r0(e){if(!e)return"";const t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t}function Xu(e){return r0(e)==="zai"}function l0(e){return Xu(e)?a0:s0}function c0(e,t){return!t||!e||e==="off"?e:"on"}function d0(e,t){return e?t&&e==="on"?"low":e:null}function u0(e){switch(e){case"idle-7d":return"Idle > 7 days";case"task-complete":return"Task completed";case"manual":return"Manual";default:return e}}function p0(){return r`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
5352
5352
  <rect x="2" y="3" width="20" height="5" rx="1"/>
5353
5353
  <path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/>
5354
5354
  <path d="M10 12h4"/>
5355
- </svg>`}function g0(){return r`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
5355
+ </svg>`}function h0(){return r`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
5356
5356
  <polyline points="9 14 4 9 9 4"/>
5357
5357
  <path d="M20 20v-7a4 4 0 0 0-4-4H4"/>
5358
- </svg>`}function m0(e){return r`<svg
5358
+ </svg>`}function f0(e){return r`<svg
5359
5359
  width="12" height="12" viewBox="0 0 24 24" fill="none"
5360
5360
  stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
5361
5361
  style="transition: transform 150ms ease; transform: rotate(${e?"90deg":"0deg"});"
5362
5362
  >
5363
5363
  <polyline points="9 18 15 12 9 6"/>
5364
- </svg>`}function v0(e){const t=e.result?.sessions??[],n=new Set(e.archivedSessions.map(i=>i.sessionKey)),s=t.filter(i=>!n.has(i.key)),a=e.archivedSessions.length;return r`
5364
+ </svg>`}function g0(e){const t=e.result?.sessions??[],n=new Set(e.archivedSessions.map(i=>i.sessionKey)),s=t.filter(i=>!n.has(i.key)),a=e.archivedSessions.length;return r`
5365
5365
  <section class="card">
5366
5366
  <div class="row" style="justify-content: space-between;">
5367
5367
  <div>
@@ -5436,19 +5436,19 @@ ${i}
5436
5436
  </div>
5437
5437
  ${s.length===0?r`
5438
5438
  <div class="muted">No active sessions found.</div>
5439
- `:s.map(i=>b0(i,e.basePath,e.onPatch,e.onDelete,e.onArchive,e.loading))}
5439
+ `:s.map(i=>v0(i,e.basePath,e.onPatch,e.onDelete,e.onArchive,e.loading))}
5440
5440
  </div>
5441
5441
  </section>
5442
5442
 
5443
- ${y0(e,a)}
5444
- `}function y0(e,t){return t===0&&!e.archivedSessionsLoading?h:r`
5443
+ ${m0(e,a)}
5444
+ `}function m0(e,t){return t===0&&!e.archivedSessionsLoading?h:r`
5445
5445
  <section class="card archived-section">
5446
5446
  <div
5447
5447
  class="archived-section__header"
5448
5448
  @click=${e.onToggleArchived}
5449
5449
  >
5450
5450
  <div class="row" style="gap: 8px; align-items: center;">
5451
- ${m0(e.archivedSessionsExpanded)}
5451
+ ${f0(e.archivedSessionsExpanded)}
5452
5452
  <span class="archived-section__title">Archived</span>
5453
5453
  ${t>0?r`<span class="archived-badge">${t}</span>`:h}
5454
5454
  </div>
@@ -5466,11 +5466,11 @@ ${i}
5466
5466
  <div>Linked Task</div>
5467
5467
  <div>Actions</div>
5468
5468
  </div>
5469
- ${e.archivedSessionsLoading?r`<div class="muted" style="padding: 12px;">Loading...</div>`:e.archivedSessions.length===0?r`<div class="muted" style="padding: 12px;">No archived sessions.</div>`:e.archivedSessions.map(n=>w0(n,e.onUnarchive,e.loading))}
5469
+ ${e.archivedSessionsLoading?r`<div class="muted" style="padding: 12px;">Loading...</div>`:e.archivedSessions.length===0?r`<div class="muted" style="padding: 12px;">No archived sessions.</div>`:e.archivedSessions.map(n=>y0(n,e.onUnarchive,e.loading))}
5470
5470
  </div>
5471
5471
  `:h}
5472
5472
  </section>
5473
- `}function b0(e,t,n,s,a,i){const o=e.updatedAt?z(e.updatedAt):"n/a",l=e.thinkingLevel??"",c=Zu(e.modelProvider),u=u0(l,c),p=d0(e.modelProvider),f=e.verboseLevel??"",m=e.reasoningLevel??"",g=e.displayName??e.key,$=e.kind!=="global",d=$?`${to("chat",t)}?session=${encodeURIComponent(e.key)}`:null;return r`
5473
+ `}function v0(e,t,n,s,a,i){const o=e.updatedAt?z(e.updatedAt):"n/a",l=e.thinkingLevel??"",c=Xu(e.modelProvider),u=c0(l,c),p=l0(e.modelProvider),f=e.verboseLevel??"",m=e.reasoningLevel??"",g=e.displayName??e.key,$=e.kind!=="global",d=$?`${to("chat",t)}?session=${encodeURIComponent(e.key)}`:null;return r`
5474
5474
  <div class="table-row">
5475
5475
  <div class="mono">${$?r`<a href=${d} class="session-link">${g}</a>`:g}</div>
5476
5476
  <div>
@@ -5483,12 +5483,12 @@ ${i}
5483
5483
  </div>
5484
5484
  <div>${e.kind}</div>
5485
5485
  <div>${o}</div>
5486
- <div>${M$(e)}</div>
5486
+ <div>${P$(e)}</div>
5487
5487
  <div>
5488
5488
  <select
5489
5489
  .value=${u}
5490
5490
  ?disabled=${i}
5491
- @change=${v=>{const S=v.target.value;n(e.key,{thinkingLevel:p0(S,c)})}}
5491
+ @change=${v=>{const S=v.target.value;n(e.key,{thinkingLevel:d0(S,c)})}}
5492
5492
  >
5493
5493
  ${p.map(v=>r`<option value=${v}>${v||"inherit"}</option>`)}
5494
5494
  </select>
@@ -5499,7 +5499,7 @@ ${i}
5499
5499
  ?disabled=${i}
5500
5500
  @change=${v=>{const S=v.target.value;n(e.key,{verboseLevel:S||null})}}
5501
5501
  >
5502
- ${r0.map(v=>r`<option value=${v.value}>${v.label}</option>`)}
5502
+ ${i0.map(v=>r`<option value=${v.value}>${v.label}</option>`)}
5503
5503
  </select>
5504
5504
  </div>
5505
5505
  <div>
@@ -5508,7 +5508,7 @@ ${i}
5508
5508
  ?disabled=${i}
5509
5509
  @change=${v=>{const S=v.target.value;n(e.key,{reasoningLevel:S||null})}}
5510
5510
  >
5511
- ${l0.map(v=>r`<option value=${v}>${v||"inherit"}</option>`)}
5511
+ ${o0.map(v=>r`<option value=${v}>${v||"inherit"}</option>`)}
5512
5512
  </select>
5513
5513
  </div>
5514
5514
  <div class="row" style="gap: 4px;">
@@ -5518,18 +5518,18 @@ ${i}
5518
5518
  @click=${()=>a(e.key)}
5519
5519
  title="Archive this session"
5520
5520
  >
5521
- ${f0()}
5521
+ ${p0()}
5522
5522
  </button>
5523
5523
  <button class="btn danger btn--sm" ?disabled=${i} @click=${()=>s(e.key)}>
5524
5524
  Delete
5525
5525
  </button>
5526
5526
  </div>
5527
5527
  </div>
5528
- `}function w0(e,t,n){const s=z(Date.parse(e.archivedAt));return r`
5528
+ `}function y0(e,t,n){const s=z(Date.parse(e.archivedAt));return r`
5529
5529
  <div class="archived-table__row">
5530
5530
  <div class="mono" style="opacity: 0.7;">${e.sessionKey}</div>
5531
5531
  <div>${s}</div>
5532
- <div>${h0(e.reason)}</div>
5532
+ <div>${u0(e.reason)}</div>
5533
5533
  <div class="mono" style="font-size: 11px; opacity: 0.6;">
5534
5534
  ${e.linkedTaskId?e.linkedTaskId.slice(0,8):"--"}
5535
5535
  </div>
@@ -5540,11 +5540,11 @@ ${i}
5540
5540
  @click=${()=>t(e.sessionKey)}
5541
5541
  title="Restore this session"
5542
5542
  >
5543
- ${g0()}
5543
+ ${h0()}
5544
5544
  </button>
5545
5545
  </div>
5546
5546
  </div>
5547
- `}function $0(e){return r`<div class="muted" style="padding: 16px;">ClawHub has been retired.</div>`}function k0(e){return r`
5547
+ `}function b0(e){return r`<div class="muted" style="padding: 16px;">ClawHub has been retired.</div>`}function w0(e){return r`
5548
5548
  <section class="card">
5549
5549
  <div class="row" style="justify-content: space-between; align-items: center;">
5550
5550
  <div class="chip-row" style="gap: 0;">
@@ -5570,10 +5570,10 @@ ${i}
5570
5570
  </button>`:h}
5571
5571
  </div>
5572
5572
 
5573
- ${e.subTab==="my-skills"?S0(e):h}
5574
- ${e.subTab==="clawhub"?r`<div style="margin-top: 16px;">${$0(e.clawhub)}</div>`:h}
5573
+ ${e.subTab==="my-skills"?$0(e):h}
5574
+ ${e.subTab==="clawhub"?r`<div style="margin-top: 16px;">${b0(e.clawhub)}</div>`:h}
5575
5575
  </section>
5576
- `}function S0(e){const t=e.report?.skills??[],n=e.filter.trim().toLowerCase(),s=n?t.filter(a=>[a.name,a.description,a.source].join(" ").toLowerCase().includes(n)):t;return r`
5576
+ `}function $0(e){const t=e.report?.skills??[],n=e.filter.trim().toLowerCase(),s=n?t.filter(a=>[a.name,a.description,a.source].join(" ").toLowerCase().includes(n)):t;return r`
5577
5577
  <div class="filters" style="margin-top: 14px;">
5578
5578
  <label class="field" style="flex: 1;">
5579
5579
  <span>Filter</span>
@@ -5589,9 +5589,9 @@ ${i}
5589
5589
  ${e.error?r`<div class="callout danger" style="margin-top: 12px;">${e.error}</div>`:h}
5590
5590
 
5591
5591
  ${s.length===0?r`<div class="muted" style="margin-top: 16px">No skills found.</div>`:r`<div class="list" style="margin-top: 16px;">
5592
- ${s.map(a=>A0(a,e))}
5592
+ ${s.map(a=>k0(a,e))}
5593
5593
  </div>`}
5594
- `}function A0(e,t){const n=t.busyKey===e.skillKey,s=t.edits[e.skillKey]??"",a=t.messages[e.skillKey]??null,i=e.install.length>0&&e.missing.bins.length>0,o=[...e.missing.bins.map(c=>`bin:${c}`),...e.missing.env.map(c=>`env:${c}`),...e.missing.config.map(c=>`config:${c}`),...e.missing.os.map(c=>`os:${c}`)],l=[];return e.disabled&&l.push("disabled"),e.blockedByAllowlist&&l.push("blocked by allowlist"),r`
5594
+ `}function k0(e,t){const n=t.busyKey===e.skillKey,s=t.edits[e.skillKey]??"",a=t.messages[e.skillKey]??null,i=e.install.length>0&&e.missing.bins.length>0,o=[...e.missing.bins.map(c=>`bin:${c}`),...e.missing.env.map(c=>`env:${c}`),...e.missing.config.map(c=>`config:${c}`),...e.missing.os.map(c=>`os:${c}`)],l=[];return e.disabled&&l.push("disabled"),e.blockedByAllowlist&&l.push("blocked by allowlist"),r`
5595
5595
  <div class="list-item">
5596
5596
  <div class="list-main">
5597
5597
  <div class="list-title">
@@ -5661,7 +5661,7 @@ ${i}
5661
5661
  `:h}
5662
5662
  </div>
5663
5663
  </div>
5664
- `}function ep(){return{open:!1,images:[],currentIndex:0}}function _0(e,t,n){return{open:!0,images:t,currentIndex:n}}function T0(){return ep()}function x0(e,t){const n=e.currentIndex+t;return n<0||n>=e.images.length?e:{...e,currentIndex:n}}const C0=r`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`,E0=r`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>`,L0=r`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 6 15 12 9 18"/></svg>`;function R0(e,t){if(!e.open||e.images.length===0)return h;const n=e.images[e.currentIndex];if(!n)return h;const s=e.images.length>1,a=e.currentIndex>0,i=e.currentIndex<e.images.length-1;return r`
5664
+ `}function Zu(){return{open:!1,images:[],currentIndex:0}}function S0(e,t,n){return{open:!0,images:t,currentIndex:n}}function A0(){return Zu()}function _0(e,t){const n=e.currentIndex+t;return n<0||n>=e.images.length?e:{...e,currentIndex:n}}const T0=r`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`,x0=r`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>`,C0=r`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 6 15 12 9 18"/></svg>`;function E0(e,t){if(!e.open||e.images.length===0)return h;const n=e.images[e.currentIndex];if(!n)return h;const s=e.images.length>1,a=e.currentIndex>0,i=e.currentIndex<e.images.length-1;return r`
5665
5665
  <div
5666
5666
  class="lightbox-overlay"
5667
5667
  @click=${o=>{o.target.classList.contains("lightbox-overlay")&&t.onClose()}}
@@ -5669,10 +5669,10 @@ ${i}
5669
5669
  tabindex="0"
5670
5670
  >
5671
5671
  <button class="lightbox-close" @click=${t.onClose} aria-label="Close image viewer">
5672
- ${C0}
5672
+ ${T0}
5673
5673
  </button>
5674
5674
 
5675
- ${s&&a?r`<button class="lightbox-nav lightbox-nav--prev" @click=${()=>t.onNav(-1)} aria-label="Previous image">${E0}</button>`:h}
5675
+ ${s&&a?r`<button class="lightbox-nav lightbox-nav--prev" @click=${()=>t.onNav(-1)} aria-label="Previous image">${x0}</button>`:h}
5676
5676
 
5677
5677
  <img
5678
5678
  class="lightbox-image"
@@ -5682,11 +5682,11 @@ ${i}
5682
5682
  @error=${o=>{o.target.classList.add("lightbox-image--broken")}}
5683
5683
  />
5684
5684
 
5685
- ${s&&i?r`<button class="lightbox-nav lightbox-nav--next" @click=${()=>t.onNav(1)} aria-label="Next image">${L0}</button>`:h}
5685
+ ${s&&i?r`<button class="lightbox-nav lightbox-nav--next" @click=${()=>t.onNav(1)} aria-label="Next image">${C0}</button>`:h}
5686
5686
 
5687
5687
  ${s?r`<div class="lightbox-counter">${e.currentIndex+1} / ${e.images.length}</div>`:h}
5688
5688
  </div>
5689
- `}const P0=e=>{switch(e){case"success":return r`
5689
+ `}const L0=e=>{switch(e){case"success":return r`
5690
5690
  <svg
5691
5691
  width="16"
5692
5692
  height="16"
@@ -5742,11 +5742,11 @@ ${i}
5742
5742
  <circle cx="8" cy="8" r="7" />
5743
5743
  <path d="M8 11V8M8 5h.01" />
5744
5744
  </svg>
5745
- `}};function I0({toasts:e,onDismiss:t}){return e.length===0?null:r`
5745
+ `}};function R0({toasts:e,onDismiss:t}){return e.length===0?null:r`
5746
5746
  <div class="toast-container">
5747
5747
  ${da(e,n=>n.id,n=>r`
5748
5748
  <div class="toast toast--${n.type}">
5749
- <div class="toast__icon">${P0(n.type)}</div>
5749
+ <div class="toast__icon">${L0(n.type)}</div>
5750
5750
  <div class="toast__body">
5751
5751
  <div class="toast__message">${n.message}</div>
5752
5752
  ${n.action?r`${n.action.url?r`<a
@@ -5771,7 +5771,7 @@ ${i}
5771
5771
  </div>
5772
5772
  `)}
5773
5773
  </div>
5774
- `}const Gl=[{key:"focusPulse.enabled",icon:"☀️",name:"Focus Pulse",description:"Morning priority ritual + persistent focus widget in the topbar. Silent 30-min pulse checks compare your activity against your plan.",default:!0}];function M0(e,t){return r`
5774
+ `}const Gl=[{key:"focusPulse.enabled",icon:"☀️",name:"Focus Pulse",description:"Morning priority ritual + persistent focus widget in the topbar. Silent 30-min pulse checks compare your activity against your plan.",default:!0}];function P0(e,t){return r`
5775
5775
  <button
5776
5776
  class="options-toggle ${e?"options-toggle--on":""}"
5777
5777
  role="switch"
@@ -5782,25 +5782,25 @@ ${i}
5782
5782
  <span class="options-toggle-thumb"></span>
5783
5783
  </span>
5784
5784
  </button>
5785
- `}function D0(e,t,n){const a=!!(t?.[e.key]??e.default);return r`
5785
+ `}function I0(e,t,n){const a=!!(t?.[e.key]??e.default);return r`
5786
5786
  <div class="options-card card">
5787
5787
  <div class="options-card-header">
5788
5788
  <div class="options-card-info">
5789
5789
  <span class="options-card-icon">${e.icon}</span>
5790
5790
  <span class="options-card-name">${e.name}</span>
5791
5791
  </div>
5792
- ${M0(a,()=>n(e.key,!a))}
5792
+ ${P0(a,()=>n(e.key,!a))}
5793
5793
  </div>
5794
5794
  <div class="options-card-description">${e.description}</div>
5795
5795
  </div>
5796
- `}function O0(e){const{connected:t,loading:n,options:s,onToggle:a,onOpenWizard:i}=e;return t?n&&!s?r`
5796
+ `}function M0(e){const{connected:t,loading:n,options:s,onToggle:a,onOpenWizard:i}=e;return t?n&&!s?r`
5797
5797
  <section class="tab-body options-section">
5798
5798
  <div class="options-loading">Loading options...</div>
5799
5799
  </section>
5800
5800
  `:r`
5801
5801
  <section class="tab-body options-section">
5802
5802
  <div class="options-grid">
5803
- ${Gl.map(o=>D0(o,s,a))}
5803
+ ${Gl.map(o=>I0(o,s,a))}
5804
5804
  </div>
5805
5805
  ${Gl.length===0?r`<div class="options-empty">
5806
5806
  No configurable features yet.
@@ -5830,7 +5830,7 @@ ${i}
5830
5830
  <section class="tab-body options-section">
5831
5831
  <div class="options-empty">Not connected to gateway.</div>
5832
5832
  </section>
5833
- `}const Ql=["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Kolkata","Australia/Sydney","Pacific/Auckland"],N0=["Direct and concise -- no fluff, just answers","Detailed explanations -- walk me through the reasoning","Casual and conversational -- like talking to a friend","Structured with bullet points -- organized and scannable","Technical and precise -- specifics matter"],F0=[{value:"sonnet",label:"Sonnet (fast, balanced)"},{value:"opus",label:"Opus (deep reasoning)"},{value:"haiku",label:"Haiku (quick, lightweight)"}],ei=["Never send emails without explicit approval","Never delete or overwrite files without backup","Always search memory before guessing","Never share private information externally"],Yl=[{label:"Name",question:"What should I call you?"},{label:"Timezone",question:"What timezone are you in?"},{label:"Focus",question:"What are you building or focused on?"},{label:"Projects",question:"What are your top projects? (1-3)"},{label:"Style",question:"How do you like to communicate?"},{label:"Rules",question:"What rules must the AI always follow?"},{label:"People",question:"Who are the key people in your work/life?"},{label:"Model",question:"What AI model do you prefer?"}];function Jl(e){const n=Math.min(Number(e),8);return r`
5833
+ `}const Ql=["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Kolkata","Australia/Sydney","Pacific/Auckland"],D0=["Direct and concise -- no fluff, just answers","Detailed explanations -- walk me through the reasoning","Casual and conversational -- like talking to a friend","Structured with bullet points -- organized and scannable","Technical and precise -- specifics matter"],O0=[{value:"sonnet",label:"Sonnet (fast, balanced)"},{value:"opus",label:"Opus (deep reasoning)"},{value:"haiku",label:"Haiku (quick, lightweight)"}],ei=["Never send emails without explicit approval","Never delete or overwrite files without backup","Always search memory before guessing","Never share private information externally"],Yl=[{label:"Name",question:"What should I call you?"},{label:"Timezone",question:"What timezone are you in?"},{label:"Focus",question:"What are you building or focused on?"},{label:"Projects",question:"What are your top projects? (1-3)"},{label:"Style",question:"How do you like to communicate?"},{label:"Rules",question:"What rules must the AI always follow?"},{label:"People",question:"Who are the key people in your work/life?"},{label:"Model",question:"What AI model do you prefer?"}];function Jl(e){const n=Math.min(Number(e),8);return r`
5834
5834
  <div class="wizard-progress">
5835
5835
  <div class="wizard-progress-dots">
5836
5836
  ${Array.from({length:8},(s,a)=>r`
@@ -5841,11 +5841,11 @@ ${i}
5841
5841
  ${n<8?`Step ${n+1} of 8`:"Review"}
5842
5842
  </div>
5843
5843
  </div>
5844
- `}function B0(e){if(e>=Yl.length)return r`${h}`;const t=Yl[e];return r`
5844
+ `}function N0(e){if(e>=Yl.length)return r`${h}`;const t=Yl[e];return r`
5845
5845
  <div class="wizard-step-header">
5846
5846
  <h2 class="wizard-question">${t.question}</h2>
5847
5847
  </div>
5848
- `}function U0(e,t,n,s){return r`
5848
+ `}function F0(e,t,n,s){return r`
5849
5849
  <div class="wizard-nav">
5850
5850
  ${e>0?r`
5851
5851
  <button
@@ -5859,7 +5859,7 @@ ${i}
5859
5859
  @click=${()=>{s?(t.onStepChange(8),t.onPreview()):t.onStepChange(e+1)}}
5860
5860
  >${s?"Review":"Continue"}</button>
5861
5861
  </div>
5862
- `}function tp(){return r`<p class="wizard-skip-hint">Press Enter to use the default and continue</p>`}function z0(e,t){function n(a){const i=a.target.value;t.onAnswerChange("name",i)}function s(a){a.key==="Enter"&&(a.preventDefault(),t.onStepChange(1))}return r`
5862
+ `}function ep(){return r`<p class="wizard-skip-hint">Press Enter to use the default and continue</p>`}function B0(e,t){function n(a){const i=a.target.value;t.onAnswerChange("name",i)}function s(a){a.key==="Enter"&&(a.preventDefault(),t.onStepChange(1))}return r`
5863
5863
  <div class="wizard-field">
5864
5864
  <input
5865
5865
  type="text"
@@ -5871,7 +5871,7 @@ ${i}
5871
5871
  autofocus
5872
5872
  />
5873
5873
  </div>
5874
- `}function K0(e,t){const n=Intl.DateTimeFormat().resolvedOptions().timeZone;return r`
5874
+ `}function U0(e,t){const n=Intl.DateTimeFormat().resolvedOptions().timeZone;return r`
5875
5875
  <div class="wizard-field">
5876
5876
  <div class="wizard-detected">
5877
5877
  Detected: <strong>${n}</strong>
@@ -5888,9 +5888,9 @@ ${i}
5888
5888
  </option>
5889
5889
  `)}
5890
5890
  </select>
5891
- ${tp()}
5891
+ ${ep()}
5892
5892
  </div>
5893
- `}function W0(e,t){function n(a){t.onAnswerChange("focus",a.target.value)}function s(a){a.key==="Enter"&&(a.preventDefault(),t.onStepChange(3))}return r`
5893
+ `}function z0(e,t){function n(a){t.onAnswerChange("focus",a.target.value)}function s(a){a.key==="Enter"&&(a.preventDefault(),t.onStepChange(3))}return r`
5894
5894
  <div class="wizard-field">
5895
5895
  <input
5896
5896
  type="text"
@@ -5902,7 +5902,7 @@ ${i}
5902
5902
  autofocus
5903
5903
  />
5904
5904
  </div>
5905
- `}function q0(e,t){function n(){const i=document.querySelector(".wizard-project-input");if(!i)return;const o=i.value.trim();o&&e.projects.length<5&&(t.onAnswerChange("projects",[...e.projects,o]),i.value="",i.focus())}function s(i){const o=e.projects.filter((l,c)=>c!==i);t.onAnswerChange("projects",o)}function a(i){i.key==="Enter"&&(i.preventDefault(),i.target.value.trim()?n():e.projects.length>0&&t.onStepChange(4))}return r`
5905
+ `}function K0(e,t){function n(){const i=document.querySelector(".wizard-project-input");if(!i)return;const o=i.value.trim();o&&e.projects.length<5&&(t.onAnswerChange("projects",[...e.projects,o]),i.value="",i.focus())}function s(i){const o=e.projects.filter((l,c)=>c!==i);t.onAnswerChange("projects",o)}function a(i){i.key==="Enter"&&(i.preventDefault(),i.target.value.trim()?n():e.projects.length>0&&t.onStepChange(4))}return r`
5906
5906
  <div class="wizard-field">
5907
5907
  <div class="wizard-tag-list">
5908
5908
  ${e.projects.map((i,o)=>r`
@@ -5924,10 +5924,10 @@ ${i}
5924
5924
  </div>
5925
5925
  ${e.projects.length===0?r`<p class="wizard-hint">Add 1-3 projects, or skip to continue</p>`:h}
5926
5926
  </div>
5927
- `}function j0(e,t){return r`
5927
+ `}function W0(e,t){return r`
5928
5928
  <div class="wizard-field">
5929
5929
  <div class="wizard-radio-list">
5930
- ${N0.map(n=>r`
5930
+ ${D0.map(n=>r`
5931
5931
  <label class="wizard-radio ${e.commStyle===n?"wizard-radio--selected":""}">
5932
5932
  <input
5933
5933
  type="radio"
@@ -5950,7 +5950,7 @@ ${i}
5950
5950
  />
5951
5951
  </div>
5952
5952
  </div>
5953
- `}function H0(e,t){const n=e.hardRules.length>0?e.hardRules:[];function s(o){n.includes(o)?t.onAnswerChange("hardRules",n.filter(l=>l!==o)):t.onAnswerChange("hardRules",[...n,o])}function a(){const o=document.querySelector(".wizard-rule-input");if(!o)return;const l=o.value.trim();l&&(t.onAnswerChange("hardRules",[...n,l]),o.value="",o.focus())}function i(o){o.key==="Enter"&&(o.preventDefault(),o.target.value.trim()&&a())}return r`
5953
+ `}function q0(e,t){const n=e.hardRules.length>0?e.hardRules:[];function s(o){n.includes(o)?t.onAnswerChange("hardRules",n.filter(l=>l!==o)):t.onAnswerChange("hardRules",[...n,o])}function a(){const o=document.querySelector(".wizard-rule-input");if(!o)return;const l=o.value.trim();l&&(t.onAnswerChange("hardRules",[...n,l]),o.value="",o.focus())}function i(o){o.key==="Enter"&&(o.preventDefault(),o.target.value.trim()&&a())}return r`
5954
5954
  <div class="wizard-field">
5955
5955
  <p class="wizard-hint">Select common rules or add your own:</p>
5956
5956
  <div class="wizard-checkbox-list">
@@ -5985,7 +5985,7 @@ ${i}
5985
5985
  </div>
5986
5986
  `:h}
5987
5987
  </div>
5988
- `}function V0(e,t){function n(){const i=document.querySelector(".wizard-person-input");if(!i)return;const o=i.value.trim();o&&e.keyPeople.length<10&&(t.onAnswerChange("keyPeople",[...e.keyPeople,o]),i.value="",i.focus())}function s(i){t.onAnswerChange("keyPeople",e.keyPeople.filter((o,l)=>l!==i))}function a(i){i.key==="Enter"&&(i.preventDefault(),i.target.value.trim()?n():e.keyPeople.length>0&&t.onStepChange(7))}return r`
5988
+ `}function j0(e,t){function n(){const i=document.querySelector(".wizard-person-input");if(!i)return;const o=i.value.trim();o&&e.keyPeople.length<10&&(t.onAnswerChange("keyPeople",[...e.keyPeople,o]),i.value="",i.focus())}function s(i){t.onAnswerChange("keyPeople",e.keyPeople.filter((o,l)=>l!==i))}function a(i){i.key==="Enter"&&(i.preventDefault(),i.target.value.trim()?n():e.keyPeople.length>0&&t.onStepChange(7))}return r`
5989
5989
  <div class="wizard-field">
5990
5990
  <div class="wizard-tag-list">
5991
5991
  ${e.keyPeople.map((i,o)=>r`
@@ -6007,10 +6007,10 @@ ${i}
6007
6007
  </div>
6008
6008
  <p class="wizard-hint">Co-founders, family, key collaborators. You can add more later.</p>
6009
6009
  </div>
6010
- `}function G0(e,t){return r`
6010
+ `}function H0(e,t){return r`
6011
6011
  <div class="wizard-field">
6012
6012
  <div class="wizard-radio-list">
6013
- ${F0.map(n=>r`
6013
+ ${O0.map(n=>r`
6014
6014
  <label class="wizard-radio ${e.defaultModel===n.value?"wizard-radio--selected":""}">
6015
6015
  <input
6016
6016
  type="radio"
@@ -6023,9 +6023,9 @@ ${i}
6023
6023
  </label>
6024
6024
  `)}
6025
6025
  </div>
6026
- ${tp()}
6026
+ ${ep()}
6027
6027
  </div>
6028
- `}function Q0(e,t){const{answers:n,preview:s,generating:a}=e;return r`
6028
+ `}function V0(e,t){const{answers:n,preview:s,generating:a}=e;return r`
6029
6029
  <div class="wizard-review">
6030
6030
  <h2 class="wizard-review-title">Ready to generate your workspace</h2>
6031
6031
 
@@ -6092,7 +6092,7 @@ ${i}
6092
6092
 
6093
6093
  ${e.error?r`<div class="wizard-error">${e.error}</div>`:h}
6094
6094
  </div>
6095
- `}function Y0(e,t){const n=e.result;return n?r`
6095
+ `}function G0(e,t){const n=e.result;return n?r`
6096
6096
  <div class="wizard-success">
6097
6097
  <div class="wizard-success-icon">
6098
6098
  <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="var(--ok, #22c55e)" stroke-width="2">
@@ -6117,35 +6117,62 @@ ${i}
6117
6117
  </div>
6118
6118
  <p class="wizard-success-path">Workspace: <code>${n.workspacePath}</code></p>
6119
6119
  <p class="wizard-success-hint">
6120
- Start a new chat session and the agent will automatically read your memory files.
6121
- The system gets smarter with every conversation.
6120
+ Your memory system is set up. Now let's meet the team that will work for you.
6122
6121
  </p>
6123
- <button class="wizard-btn wizard-btn--next" @click=${()=>t.onClose()}>
6124
- Start Using GodMode
6122
+ <button class="wizard-btn wizard-btn--next" @click=${()=>t.onStepChange(10)}>
6123
+ Meet Your Team
6125
6124
  </button>
6126
6125
  </div>
6127
- `:r`${h}`}function np(){return{name:"",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,focus:"",projects:[],commStyle:"Direct and concise -- no fluff, just answers",hardRules:[],keyPeople:[],defaultModel:"sonnet"}}function J0(){return{step:0,answers:np(),preview:null,generating:!1,result:null,error:null}}function sp(e,t){const{step:n,answers:s}=e;if(n===9)return r`
6126
+ `:r`${h}`}const Q0={researcher:"🔍",writer:"✍️",analyst:"📊","task-runner":"⚡","creative-director":"🎨",growth:"📈"};function Y0(e,t){const n=e.roster??[];return r`
6127
+ <div class="wizard-team">
6128
+ <h2 class="wizard-team-title">Your AI team is ready</h2>
6129
+ <p class="wizard-team-subtitle">
6130
+ Your ally manages them — you just say what you need.
6131
+ </p>
6132
+ <p class="wizard-team-hint">
6133
+ Each specialist handles a different kind of work. As you use GodMode, they learn your preferences and get better.
6134
+ </p>
6135
+
6136
+ <div class="wizard-team-grid">
6137
+ ${n.map((s,a)=>r`
6138
+ <div class="wizard-team-card" style="animation-delay: ${a*120}ms">
6139
+ <span class="wizard-team-icon">${Q0[s.slug]??"🤖"}</span>
6140
+ <h3 class="wizard-team-name">${s.name}</h3>
6141
+ <p class="wizard-team-mission">${s.mission??s.taskTypes.join(", ")}</p>
6142
+ </div>
6143
+ `)}
6144
+ </div>
6145
+
6146
+ <button class="wizard-btn wizard-btn--next wizard-team-cta" @click=${()=>t.onClose()}>
6147
+ Let's Go
6148
+ </button>
6149
+ </div>
6150
+ `}function tp(){return{name:"",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,focus:"",projects:[],commStyle:"Direct and concise -- no fluff, just answers",hardRules:[],keyPeople:[],defaultModel:"sonnet"}}function J0(){return{step:0,answers:tp(),preview:null,generating:!1,result:null,roster:null,error:null}}function np(e,t){const{step:n,answers:s}=e;if(n===10)return r`
6128
6151
  <div class="wizard-fullscreen">
6129
6152
  ${Y0(e,t)}
6130
6153
  </div>
6154
+ `;if(n===9)return r`
6155
+ <div class="wizard-fullscreen">
6156
+ ${G0(e,t)}
6157
+ </div>
6131
6158
  `;if(n===8)return r`
6132
6159
  <div class="wizard-fullscreen">
6133
6160
  <div class="wizard-container">
6134
6161
  ${Jl(n)}
6135
- ${Q0(e,t)}
6162
+ ${V0(e,t)}
6136
6163
  </div>
6137
6164
  </div>
6138
- `;const a=(()=>{switch(n){case 0:return s.name.trim().length>0;case 1:return!0;case 2:return!0;case 3:return!0;case 4:return s.commStyle.trim().length>0;case 5:return!0;case 6:return!0;case 7:return!0;default:return!1}})(),i=n===7,o=(()=>{switch(n){case 0:return z0(s,t);case 1:return K0(s,t);case 2:return W0(s,t);case 3:return q0(s,t);case 4:return j0(s,t);case 5:return H0(s,t);case 6:return V0(s,t);case 7:return G0(s,t);default:return r`${h}`}})();return r`
6165
+ `;const a=(()=>{switch(n){case 0:return s.name.trim().length>0;case 1:return!0;case 2:return!0;case 3:return!0;case 4:return s.commStyle.trim().length>0;case 5:return!0;case 6:return!0;case 7:return!0;default:return!1}})(),i=n===7,o=(()=>{switch(n){case 0:return B0(s,t);case 1:return U0(s,t);case 2:return z0(s,t);case 3:return K0(s,t);case 4:return W0(s,t);case 5:return q0(s,t);case 6:return j0(s,t);case 7:return H0(s,t);default:return r`${h}`}})();return r`
6139
6166
  <div class="wizard-fullscreen">
6140
6167
  <div class="wizard-container">
6141
6168
  <div class="wizard-glow"></div>
6142
6169
  ${Jl(n)}
6143
- ${B0(n)}
6170
+ ${N0(n)}
6144
6171
  ${o}
6145
- ${U0(n,t,a,i)}
6172
+ ${F0(n,t,a,i)}
6146
6173
  </div>
6147
6174
  </div>
6148
- `}const X0=Object.freeze(Object.defineProperty({__proto__:null,emptyWizardAnswers:np,emptyWizardState:J0,renderOnboardingWizard:sp},Symbol.toStringTag,{value:"Module"}));function fn(e){return e===null?"none":e>=8?"high":e>=5?"medium":"low"}function as(e){return{high:"trust-score--high",medium:"trust-score--medium",low:"trust-score--low",none:"trust-score--none"}[e]}function Z0(e){return{improving:"Improving",declining:"Declining",stable:"Stable",new:"New"}[e]??"New"}function eS(e){return{improving:"trust-trend--up",declining:"trust-trend--down",stable:"trust-trend--stable",new:"trust-trend--new"}[e]??"trust-trend--new"}function tS(e){return{improving:"↑",declining:"↓",stable:"→",new:"•"}[e]??"•"}function nS(e){const t=Date.now()-Date.parse(e),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);if(s<24)return`${s}h ago`;const a=Math.floor(s/24);return a<7?`${a}d ago`:new Date(e).toLocaleDateString()}function sS(e){const t=e.overallScore,n=fn(t);return r`
6175
+ `}const X0=Object.freeze(Object.defineProperty({__proto__:null,emptyWizardAnswers:tp,emptyWizardState:J0,renderOnboardingWizard:np},Symbol.toStringTag,{value:"Module"}));function fn(e){return e===null?"none":e>=8?"high":e>=5?"medium":"low"}function as(e){return{high:"trust-score--high",medium:"trust-score--medium",low:"trust-score--low",none:"trust-score--none"}[e]}function Z0(e){return{improving:"Improving",declining:"Declining",stable:"Stable",new:"New"}[e]??"New"}function eS(e){return{improving:"trust-trend--up",declining:"trust-trend--down",stable:"trust-trend--stable",new:"trust-trend--new"}[e]??"trust-trend--new"}function tS(e){return{improving:"↑",declining:"↓",stable:"→",new:"•"}[e]??"•"}function nS(e){const t=Date.now()-Date.parse(e),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);if(s<24)return`${s}h ago`;const a=Math.floor(s/24);return a<7?`${a}d ago`:new Date(e).toLocaleDateString()}function sS(e){const t=e.overallScore,n=fn(t);return r`
6149
6176
  <div class="trust-overall">
6150
6177
  <div class="trust-overall-score ${as(n)}">
6151
6178
  <span class="trust-overall-number">${t!==null?t.toFixed(1):"--"}</span>
@@ -6406,7 +6433,7 @@ ${i}
6406
6433
  </div>
6407
6434
  `:h}
6408
6435
  </section>
6409
- `}function wS(e){const t=Date.now()-Date.parse(e),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);if(s<24)return`${s}h ago`;const a=Math.floor(s/24);return a<7?`${a}d ago`:new Date(e).toLocaleDateString()}function $S(e){return{fired:"guardrails-badge--fired",blocked:"guardrails-badge--blocked",cleaned:"guardrails-badge--cleaned"}[e]??""}function ap(e,t){return r`
6436
+ `}function wS(e){const t=Date.now()-Date.parse(e),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);if(s<24)return`${s}h ago`;const a=Math.floor(s/24);return a<7?`${a}d ago`:new Date(e).toLocaleDateString()}function $S(e){return{fired:"guardrails-badge--fired",blocked:"guardrails-badge--blocked",cleaned:"guardrails-badge--cleaned"}[e]??""}function sp(e,t){return r`
6410
6437
  <button
6411
6438
  class="options-toggle ${e?"options-toggle--on":""}"
6412
6439
  role="switch"
@@ -6437,7 +6464,7 @@ ${i}
6437
6464
  <span class="guardrails-card-name">${e.name}</span>
6438
6465
  <span class="guardrails-card-hook">${e.hook}</span>
6439
6466
  </div>
6440
- ${ap(e.enabled,()=>t(e.id,!e.enabled))}
6467
+ ${sp(e.enabled,()=>t(e.id,!e.enabled))}
6441
6468
  </div>
6442
6469
  <div class="guardrails-card-description">${e.description}</div>
6443
6470
  ${s.length>0?r`
@@ -6455,7 +6482,7 @@ ${i}
6455
6482
  <span class="guardrails-card-hook guardrails-action-tag guardrails-action-tag--${a}">${a}</span>
6456
6483
  </div>
6457
6484
  <div class="guardrails-custom-actions">
6458
- ${ap(e.enabled,()=>t(e.id,!e.enabled))}
6485
+ ${sp(e.enabled,()=>t(e.id,!e.enabled))}
6459
6486
  <button class="guardrails-delete-btn" title="Delete rule" @click=${()=>n(e.id)}>&times;</button>
6460
6487
  </div>
6461
6488
  </div>
@@ -6562,7 +6589,7 @@ ${i}
6562
6589
  </span>
6563
6590
  `})}
6564
6591
  </div>
6565
- `:h}const ti=new Set;function ip(e,t,n=!1){const s=e.startedAt?Zd(e.startedAt,e.endedAt??void 0):null,a=e.childSessionKey&&t.onOpenSession?r`<button class="mc-open-session-btn" @click=${i=>{i.stopPropagation(),t.onOpenSession(e.childSessionKey)}}>Open</button>`:e.sourceTaskId&&t.onOpenTaskSession?r`<button class="mc-open-session-btn" @click=${i=>{i.stopPropagation(),t.onOpenTaskSession(e.sourceTaskId)}}>Open Task</button>`:h;return n&&!ti.has(e.id)?r`
6592
+ `:h}const ti=new Set;function ap(e,t,n=!1){const s=e.startedAt?Zd(e.startedAt,e.endedAt??void 0):null,a=e.childSessionKey&&t.onOpenSession?r`<button class="mc-open-session-btn" @click=${i=>{i.stopPropagation(),t.onOpenSession(e.childSessionKey)}}>Open</button>`:e.sourceTaskId&&t.onOpenTaskSession?r`<button class="mc-open-session-btn" @click=${i=>{i.stopPropagation(),t.onOpenTaskSession(e.sourceTaskId)}}>Open Task</button>`:h;return n&&!ti.has(e.id)?r`
6566
6593
  <div class="${ec(e.status)} mc-agent-card--compact"
6567
6594
  @click=${()=>{ti.add(e.id)}}>
6568
6595
  <div class="mc-agent-card-header">
@@ -6608,7 +6635,7 @@ ${i}
6608
6635
  </div>
6609
6636
  `:r`
6610
6637
  <div class="mc-agents-grid">
6611
- ${s.map(a=>ip(a,t,n))}
6638
+ ${s.map(a=>ap(a,t,n))}
6612
6639
  </div>
6613
6640
  `}function IS(e,t,n,s,a){const i=e.filter(o=>o.isReview===!0);return i.length===0?h:r`
6614
6641
  <div style="margin-bottom: 1.5rem">
@@ -6715,7 +6742,7 @@ ${i}
6715
6742
  <div style="margin-bottom: 1.5rem">
6716
6743
  <h3 class="mc-section-title">Recent Completed</h3>
6717
6744
  <div class="mc-agents-grid">
6718
- ${a.map(i=>ip(i,t))}
6745
+ ${a.map(i=>ap(i,t))}
6719
6746
  </div>
6720
6747
  </div>
6721
6748
  `}function US(e){if(!e.connected)return r`<div class="mc-section"><div class="mc-empty">Not connected to gateway.</div></div>`;if(e.loading&&!e.data)return r`<div class="mc-section"><div class="mc-loading">Loading agent data...</div></div>`;if(e.error&&!e.data)return r`
@@ -6865,7 +6892,7 @@ ${i}
6865
6892
  >
6866
6893
  ${t.map((n,s)=>n?jS(s,n,e):qS(s))}
6867
6894
  </div>
6868
- `}const VS=20;function op(e){switch(e.split(".").pop()?.toLowerCase()){case"md":return"📝";case"html":return"🌐";case"json":case"yaml":case"yml":case"toml":return"⚙️";case"ts":case"js":case"py":case"sh":case"rs":case"go":return"💻";case"css":return"🎨";default:return"📄"}}function rp(e,t=VS){const n=[];function s(a){for(const i of a){if(n.length>=t)return;const o=i;o.type==="file"?n.push(o):o.type==="directory"&&o.children&&s(o.children)}}return s(e),n}const GS=8;function QS(e){return rp(e,500).filter(n=>n.modifiedAt!=null).sort((n,s)=>(s.modifiedAt??0)-(n.modifiedAt??0)).slice(0,GS)}function YS(e){const n=Date.now()-e,s=Math.floor(n/6e4);if(s<1)return"just now";if(s<60)return`${s}m ago`;const a=Math.floor(s/60);if(a<24)return`${a}h ago`;const i=Math.floor(a/24);return i<30?`${i}d ago`:`${Math.floor(i/30)}mo ago`}function JS(e,t){if(!e||e.length===0)return h;const n=QS(e);return n.length===0?h:r`
6895
+ `}const VS=20;function ip(e){switch(e.split(".").pop()?.toLowerCase()){case"md":return"📝";case"html":return"🌐";case"json":case"yaml":case"yml":case"toml":return"⚙️";case"ts":case"js":case"py":case"sh":case"rs":case"go":return"💻";case"css":return"🎨";default:return"📄"}}function op(e,t=VS){const n=[];function s(a){for(const i of a){if(n.length>=t)return;const o=i;o.type==="file"?n.push(o):o.type==="directory"&&o.children&&s(o.children)}}return s(e),n}const GS=8;function QS(e){return op(e,500).filter(n=>n.modifiedAt!=null).sort((n,s)=>(s.modifiedAt??0)-(n.modifiedAt??0)).slice(0,GS)}function YS(e){const n=Date.now()-e,s=Math.floor(n/6e4);if(s<1)return"just now";if(s<60)return`${s}m ago`;const a=Math.floor(s/60);if(a<24)return`${a}h ago`;const i=Math.floor(a/24);return i<30?`${i}d ago`:`${Math.floor(i/30)}mo ago`}function JS(e,t){if(!e||e.length===0)return h;const n=QS(e);return n.length===0?h:r`
6869
6896
  <div class="work-section">
6870
6897
  <div class="work-section-label">Recent</div>
6871
6898
  <div class="work-file-list">
@@ -6874,21 +6901,21 @@ ${i}
6874
6901
  class="work-file-item"
6875
6902
  @click=${a=>{a.stopPropagation(),s.path&&t&&t(s.path)}}
6876
6903
  >
6877
- <span class="work-file-icon">${op(s.name)}</span>
6904
+ <span class="work-file-icon">${ip(s.name)}</span>
6878
6905
  <span class="work-file-name">${s.name}</span>
6879
6906
  <span class="work-file-meta">${s.modifiedAt?YS(s.modifiedAt):""}</span>
6880
6907
  </button>
6881
6908
  `)}
6882
6909
  </div>
6883
6910
  </div>
6884
- `}function XS(e,t){if(!e||e.length===0)return h;const n=rp(e);return n.length===0?h:r`
6911
+ `}function XS(e,t){if(!e||e.length===0)return h;const n=op(e);return n.length===0?h:r`
6885
6912
  <div class="work-file-list">
6886
6913
  ${n.map(s=>r`
6887
6914
  <button
6888
6915
  class="work-file-item"
6889
6916
  @click=${a=>{a.stopPropagation(),s.path&&t&&t(s.path)}}
6890
6917
  >
6891
- <span class="work-file-icon">${op(s.name)}</span>
6918
+ <span class="work-file-icon">${ip(s.name)}</span>
6892
6919
  <span class="work-file-name">${s.name}</span>
6893
6920
  ${s.size!=null?r`<span class="work-file-meta">${(s.size/1024).toFixed(1)}KB</span>`:h}
6894
6921
  </button>
@@ -7345,7 +7372,7 @@ ${i}
7345
7372
  />
7346
7373
  </div>
7347
7374
 
7348
- ${e.fileSearchResults?c1(e):e.fileTreeLoading?r`<div class="sb-files-loading">Loading file tree...</div>`:e.fileTree?lp(e.fileTree,e):r`<div class="sb-files-empty">No files found</div>`}
7375
+ ${e.fileSearchResults?c1(e):e.fileTreeLoading?r`<div class="sb-files-loading">Loading file tree...</div>`:e.fileTree?rp(e.fileTree,e):r`<div class="sb-files-empty">No files found</div>`}
7349
7376
  </div>
7350
7377
  `}function c1(e){const t=e.fileSearchResults??[];return t.length===0?r`<div class="sb-files-empty">No results found</div>`:r`
7351
7378
  <div class="sb-files-results">
@@ -7363,7 +7390,7 @@ ${i}
7363
7390
  </button>
7364
7391
  `)}
7365
7392
  </div>
7366
- `}function lp(e,t,n=0){return r`
7393
+ `}function rp(e,t,n=0){return r`
7367
7394
  <div class="sb-file-tree" style="padding-left: ${n*16}px">
7368
7395
  ${e.map(s=>s.type==="folder"?r`
7369
7396
  <details class="sb-tree-folder">
@@ -7372,7 +7399,7 @@ ${i}
7372
7399
  <span>${s.name}</span>
7373
7400
  ${s.childCount!=null?r`<span class="sb-tree-count">${s.childCount}</span>`:h}
7374
7401
  </summary>
7375
- ${s.children?lp(s.children,t,n+1):h}
7402
+ ${s.children?rp(s.children,t,n+1):h}
7376
7403
  </details>
7377
7404
  `:r`
7378
7405
  <button
@@ -7603,7 +7630,7 @@ ${i}
7603
7630
  </div>
7604
7631
  <div class="dashboards-content">
7605
7632
  <div class="dashboard-render">
7606
- ${ke(tg(t))}
7633
+ ${ke(eg(t))}
7607
7634
  </div>
7608
7635
  </div>
7609
7636
  </section>
@@ -8168,7 +8195,7 @@ ${i}
8168
8195
  </div>
8169
8196
  <div class="dynamic-slot__content">${ke(Gc(n))}</div>
8170
8197
  </div>
8171
- `:h}function dc(e){return e.trim().toLowerCase().replace(/[^a-z0-9+\s]/g," ").replace(/\s+/g," ")}function Li(e){const t=e.trim();if(!t)return t;const n=t.split(/\s+/);if(n.length>=2&&n.length%2===0){const l=n.length/2,c=n.slice(0,l).join(" "),u=n.slice(l).join(" ");if(c.toLowerCase()===u.toLowerCase())return c}const s=t.replace(/\s+/g," ").toLowerCase(),a=Math.floor(s.length/2),i=s.slice(0,a).trim(),o=s.slice(a).trim();return i&&i===o?t.slice(0,Math.ceil(t.length/2)).trim():t}function Ri(e,t){const n=t?.sessionId?.trim();if(n)return`session:${n}`;const s=t?.label??t?.displayName??Te.get(t?.key??e)??Te.get(e)??"",a=dc(Li(s));if(a){const i=String(t?.surface??"").trim().toLowerCase(),o=dc(String(t?.subject??"")).slice(0,20),l=a.split(" ").filter(Boolean).slice(0,3).join(" ");return`name:${i}|${o}|${l||a.slice(0,24)}`}return`key:${e.trim().toLowerCase()}`}function uc(e){if(e===ee)return!0;const t=e.toLowerCase();return!!(t==="agent:main:main"||t.endsWith(":main"))}function z1(e){const t=e.sessionsResult?.sessions,n=[...new Set(e.settings.openTabs.map(l=>l.trim()).filter(Boolean))].filter(l=>!uc(l)),s=Ie(t,e.sessionKey),a=Ri(e.sessionKey,s),i=new Map;for(const l of n){const c=Ie(t,l),u=Ri(l,c);if(!i.has(u)){i.set(u,l);continue}l===e.sessionKey&&i.set(u,l)}const o=[...i.values()];if(o.length===0){const l=e.sessionKey.trim()||"main";uc(l)||o.push(l)}return{tabKeys:o,activeIdentity:a}}function K1(e){const t=e.onboardingActive&&e.onboarding,n=e.onboardingPhase??0,s=e.onboardingData;if(t&&n===0)return x1(()=>{e.handleOnboardingStart?.()},s?.assessment);if(t&&n===1)return C1(d=>{e.handleOnboardingIdentitySubmit?.(d)});if(t&&n===6)return L1(s?.summary??null,s?.identity??null,()=>{e.handleOnboardingComplete?.()});if(e.wizardActive&&e.wizardState)return sp(e.wizardState,{onStepChange:d=>{e.handleWizardStepChange?.(d)},onAnswerChange:(d,v)=>{e.handleWizardAnswerChange?.(d,v)},onPreview:()=>{e.handleWizardPreview?.()},onGenerate:()=>{e.handleWizardGenerate?.()},onClose:()=>{e.handleWizardClose?.()}});const a=e.presenceEntries.length,i=e.sessionsResult?.count??null,o=e.cronStatus?.nextWakeAtMs??null,l=e.connected?null:"Disconnected from gateway.",c=e.tab==="chat",u=c&&(e.settings.chatFocusMode||e.onboarding||t&&n>=2),p=e.onboarding?!1:e.settings.chatShowThinking,f=U1(e),m=e.chatAvatarUrl??f??null,{tabKeys:g,activeIdentity:$}=z1(e);return r`
8198
+ `:h}function dc(e){return e.trim().toLowerCase().replace(/[^a-z0-9+\s]/g," ").replace(/\s+/g," ")}function Li(e){const t=e.trim();if(!t)return t;const n=t.split(/\s+/);if(n.length>=2&&n.length%2===0){const l=n.length/2,c=n.slice(0,l).join(" "),u=n.slice(l).join(" ");if(c.toLowerCase()===u.toLowerCase())return c}const s=t.replace(/\s+/g," ").toLowerCase(),a=Math.floor(s.length/2),i=s.slice(0,a).trim(),o=s.slice(a).trim();return i&&i===o?t.slice(0,Math.ceil(t.length/2)).trim():t}function Ri(e,t){const n=t?.sessionId?.trim();if(n)return`session:${n}`;const s=t?.label??t?.displayName??Te.get(t?.key??e)??Te.get(e)??"",a=dc(Li(s));if(a){const i=String(t?.surface??"").trim().toLowerCase(),o=dc(String(t?.subject??"")).slice(0,20),l=a.split(" ").filter(Boolean).slice(0,3).join(" ");return`name:${i}|${o}|${l||a.slice(0,24)}`}return`key:${e.trim().toLowerCase()}`}function uc(e){if(e===ee)return!0;const t=e.toLowerCase();return!!(t==="agent:main:main"||t.endsWith(":main"))}function z1(e){const t=e.sessionsResult?.sessions,n=[...new Set(e.settings.openTabs.map(l=>l.trim()).filter(Boolean))].filter(l=>!uc(l)),s=Ie(t,e.sessionKey),a=Ri(e.sessionKey,s),i=new Map;for(const l of n){const c=Ie(t,l),u=Ri(l,c);if(!i.has(u)){i.set(u,l);continue}l===e.sessionKey&&i.set(u,l)}const o=[...i.values()];if(o.length===0){const l=e.sessionKey.trim()||"main";uc(l)||o.push(l)}return{tabKeys:o,activeIdentity:a}}function K1(e){const t=e.onboardingActive&&e.onboarding,n=e.onboardingPhase??0,s=e.onboardingData;if(t&&n===0)return x1(()=>{e.handleOnboardingStart?.()},s?.assessment);if(t&&n===1)return C1(d=>{e.handleOnboardingIdentitySubmit?.(d)});if(t&&n===6)return L1(s?.summary??null,s?.identity??null,()=>{e.handleOnboardingComplete?.()});if(e.wizardActive&&e.wizardState)return np(e.wizardState,{onStepChange:d=>{e.handleWizardStepChange?.(d)},onAnswerChange:(d,v)=>{e.handleWizardAnswerChange?.(d,v)},onPreview:()=>{e.handleWizardPreview?.()},onGenerate:()=>{e.handleWizardGenerate?.()},onClose:()=>{e.handleWizardClose?.()}});const a=e.presenceEntries.length,i=e.sessionsResult?.count??null,o=e.cronStatus?.nextWakeAtMs??null,l=e.connected?null:"Disconnected from gateway.",c=e.tab==="chat",u=c&&(e.settings.chatFocusMode||e.onboarding||t&&n>=2),p=e.onboarding?!1:e.settings.chatShowThinking,f=U1(e),m=e.chatAvatarUrl??f??null,{tabKeys:g,activeIdentity:$}=z1(e);return r`
8172
8199
  <div class="shell ${c?"shell--chat":""} ${u?"shell--chat-focus":""} ${e.settings.navCollapsed?"shell--nav-collapsed":""} ${e.onboarding?"shell--onboarding":""}">
8173
8200
  <header class="topbar">
8174
8201
  <div class="topbar-left">
@@ -8216,11 +8243,11 @@ ${i}
8216
8243
  <span>Gateway</span>
8217
8244
  <span class="mono">${e.reconnecting?`Reconnecting${e.reconnectAttempt>1?` (${e.reconnectAttempt})`:""}...`:e.connected?"Connected":"Offline"}</span>
8218
8245
  </div>
8219
- ${Eu(e)}
8246
+ ${Cu(e)}
8220
8247
  </div>
8221
8248
  </header>
8222
8249
  <aside class="nav ${e.settings.navCollapsed?"nav--collapsed":""}">
8223
- ${lm.map(d=>{const v=e.settings.navGroupsCollapsed[d.label]??!1,S=d.tabs.some(T=>T===e.tab),_=!d.label||d.tabs.length===1&&Gn(d.tabs[0])===d.label;return r`
8250
+ ${rm.map(d=>{const v=e.settings.navGroupsCollapsed[d.label]??!1,S=d.tabs.some(T=>T===e.tab),_=!d.label||d.tabs.length===1&&Gn(d.tabs[0])===d.label;return r`
8224
8251
  <div class="nav-group ${v&&!S?"nav-group--collapsed":""} ${_?"nav-group--no-header":""}">
8225
8252
  ${_?h:r`
8226
8253
  <button
@@ -8245,7 +8272,7 @@ ${i}
8245
8272
  ${e.onboardingProgress!=null?r`<span class="nav-item__badge">${e.onboardingProgress}%</span>`:e.setupChecklist&&e.setupChecklist.percentComplete!=null?r`<span class="nav-item__badge">${e.setupChecklist.percentComplete}%</span>`:h}
8246
8273
  </a>
8247
8274
  `:h}
8248
- ${d.tabs.map(T=>xu(e,T))}
8275
+ ${d.tabs.map(T=>Tu(e,T))}
8249
8276
  </div>
8250
8277
  </div>
8251
8278
  `})}
@@ -8272,7 +8299,7 @@ ${i}
8272
8299
  <div>
8273
8300
  ${e.tab!=="chat"&&e.tab!=="setup"?r`
8274
8301
  <div class="page-title">${Gn(e.tab)}</div>
8275
- <div class="page-sub">${um(e.tab)}</div>
8302
+ <div class="page-sub">${dm(e.tab)}</div>
8276
8303
  `:e.tab==="chat"?r`
8277
8304
  <div class="session-tabs">
8278
8305
  <div class="session-tab session-tab--pinned ${e.sessionKey===ee?"session-tab--active":""}"
@@ -8340,8 +8367,8 @@ ${i}
8340
8367
  <span class="reconnect-spinner"></span>
8341
8368
  Reconnecting${e.reconnectAttempt>1?` (attempt ${e.reconnectAttempt})`:""}...
8342
8369
  </div>`:e.lastError?r`<div class="pill ${e.lastError.startsWith("✓")?"success":"danger"}">${e.lastError}</div>`:h}
8343
- ${c?Cu(e):h}
8344
- ${(e.tab==="today"||e.tab==="my-day")&&!e.dynamicSlots.today?Lk({connected:e.connected,onRefresh:()=>e.handleMyDayRefresh(),selectedDate:e.todaySelectedDate,onDatePrev:()=>e.handleDatePrev(),onDateNext:()=>e.handleDateNext(),onDateToday:()=>e.handleDateToday(),viewMode:e.todayViewMode??"brief",onViewModeChange:d=>e.handleTodayViewModeChange(d),focusPulseActive:!1,decisionCards:(e.todayQueueResults??[]).length>0?{items:e.todayQueueResults,onApprove:()=>{},onReject:()=>{},onViewOutput:()=>{},onOpenChat:()=>{}}:void 0}):h}
8370
+ ${c?xu(e):h}
8371
+ ${(e.tab==="today"||e.tab==="my-day")&&!e.dynamicSlots.today?Ck({connected:e.connected,onRefresh:()=>e.handleMyDayRefresh(),selectedDate:e.todaySelectedDate,onDatePrev:()=>e.handleDatePrev(),onDateNext:()=>e.handleDateNext(),onDateToday:()=>e.handleDateToday(),viewMode:e.todayViewMode??"brief",onViewModeChange:d=>e.handleTodayViewModeChange(d),focusPulseActive:!1,decisionCards:(e.todayQueueResults??[]).length>0?{items:e.todayQueueResults,onApprove:()=>{},onReject:()=>{},onViewOutput:()=>{},onOpenChat:()=>{}}:void 0}):h}
8345
8372
  </div>
8346
8373
  </section>
8347
8374
 
@@ -8365,25 +8392,25 @@ ${i}
8365
8392
 
8366
8393
  ${e.tab==="onboarding"?oc({connected:e.connected,integrations:e.onboardingIntegrations??null,coreProgress:e.onboardingCoreProgress??null,expandedCard:e.onboardingExpandedCard??null,loadingGuide:e.onboardingLoadingGuide??null,activeGuide:e.onboardingActiveGuide??null,testingId:e.onboardingTestingId??null,testResult:e.onboardingTestResult??null,configValues:e.onboardingConfigValues??{},onLoadIntegrations:()=>e.handleLoadIntegrations(),onExpandCard:d=>e.handleExpandCard(d),onLoadGuide:d=>e.handleLoadGuide(d),onTestIntegration:d=>e.handleTestIntegration(d),onConfigureIntegration:(d,v)=>e.handleConfigureIntegration(d,v),onUpdateConfigValue:(d,v)=>e.handleUpdateConfigValue(d,v),onSkipIntegration:d=>e.handleSkipIntegration(d),onNavigate:d=>e.setTab(d),onMarkComplete:()=>e.handleMarkOnboardingComplete?.(),onOpenSupportChat:()=>e.handleOpenSupportChat()}):h}
8367
8394
 
8368
- ${e.tab==="overview"?a0({connected:e.connected,hello:e.hello,settings:e.settings,password:e.password,lastError:e.lastError,presenceCount:a,sessionsCount:i,cronEnabled:e.cronStatus?.enabled??null,cronNext:o,lastChannelsRefresh:e.channelsLastSuccess,updateStatus:e.updateStatus,updateLoading:e.updateLoading,updateError:e.updateError,updateLastChecked:e.updateLastChecked,updateRunning:e.updateRunning,onSettingsChange:d=>e.applySettings(d),onPasswordChange:d=>e.password=d,onSessionKeyChange:d=>{$e(e),e.sessionKey=d,Le(e,d),e.resetToolStream(),e.applySettings({...e.settings,sessionKey:d,lastActiveSessionKey:d}),e.loadAssistantIdentity()},onConnect:()=>e.connect(),onRefresh:()=>e.loadOverview(),onCheckUpdates:()=>sv(e),onUpdateNow:()=>{hr(e)}}):h}
8395
+ ${e.tab==="overview"?n0({connected:e.connected,hello:e.hello,settings:e.settings,password:e.password,lastError:e.lastError,presenceCount:a,sessionsCount:i,cronEnabled:e.cronStatus?.enabled??null,cronNext:o,lastChannelsRefresh:e.channelsLastSuccess,updateStatus:e.updateStatus,updateLoading:e.updateLoading,updateError:e.updateError,updateLastChecked:e.updateLastChecked,updateRunning:e.updateRunning,onSettingsChange:d=>e.applySettings(d),onPasswordChange:d=>e.password=d,onSessionKeyChange:d=>{$e(e),e.sessionKey=d,Le(e,d),e.resetToolStream(),e.applySettings({...e.settings,sessionKey:d,lastActiveSessionKey:d}),e.loadAssistantIdentity()},onConnect:()=>e.connect(),onRefresh:()=>e.loadOverview(),onCheckUpdates:()=>nv(e),onUpdateNow:()=>{hr(e)}}):h}
8369
8396
 
8370
- ${e.tab==="workspaces"?bk({connected:e.connected,workspaces:e.workspaces??[],selectedWorkspace:e.selectedWorkspace??null,searchQuery:e.workspacesSearchQuery??"",itemSearchQuery:e.workspaceItemSearchQuery??"",expandedFolders:e.workspaceExpandedFolders??new Set,loading:e.workspacesLoading??!1,createLoading:e.workspacesCreateLoading??!1,error:e.workspacesError??null,onSearch:d=>e.workspacesSearchQuery=d,onItemSearch:d=>e.workspaceItemSearchQuery=d,onCreateWorkspace:async d=>{e.workspacesCreateLoading=!0;try{const{createWorkspace:v,selectWorkspace:S}=await E(async()=>{const{createWorkspace:T,selectWorkspace:A}=await Promise.resolve().then(()=>pe);return{createWorkspace:T,selectWorkspace:A}},void 0,import.meta.url),_=await v(e,d);return _?(e.workspaceItemSearchQuery="",await S(e,_),e.showToast(`Created workspace: ${_.name}`,"success"),!0):(e.showToast("Failed to create workspace","error"),!1)}finally{e.workspacesCreateLoading=!1}},onDeleteWorkspace:async d=>{const{deleteWorkspace:v,loadAllTasksWithQueueStatus:S}=await E(async()=>{const{deleteWorkspace:T,loadAllTasksWithQueueStatus:A}=await Promise.resolve().then(()=>pe);return{deleteWorkspace:T,loadAllTasksWithQueueStatus:A}},void 0,import.meta.url);if(!await v(e,d.id)){e.showToast(`Failed to delete ${d.name}`,"error");return}e.showToast(`Deleted workspace: ${d.name}`,"success"),e.allTasks=await S(e)},onSelectWorkspace:async d=>{e.workspaceItemSearchQuery="";const{selectWorkspace:v}=await E(async()=>{const{selectWorkspace:S}=await Promise.resolve().then(()=>pe);return{selectWorkspace:S}},void 0,import.meta.url);await v(e,d)},onBack:()=>{e.selectedWorkspace=null,e.workspaceItemSearchQuery=""},onItemClick:async d=>{const{readWorkspaceFile:v}=await E(async()=>{const{readWorkspaceFile:T}=await Promise.resolve().then(()=>pe);return{readWorkspaceFile:T}},void 0,import.meta.url),S=e.selectedWorkspace?.id,_=await v(e,d.path,S);if(!_){e.showToast(`Failed to open ${d.name}`,"error");return}e.handleOpenSidebar(_.content,{mimeType:_.mime,filePath:d.path,title:d.name})},onSessionClick:async d=>{if(!d.key)return;const v=d.key;$e(e),e.sessionKey=v,Le(e,v),e.chatLoading=!0,e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll();const S=e.settings.openTabs.includes(v)?e.settings.openTabs:[...e.settings.openTabs,v];e.applySettings({...e.settings,openTabs:S,sessionKey:v,lastActiveSessionKey:v,tabLastViewed:{...e.settings.tabLastViewed,[v]:Date.now()}}),e.setTab("chat"),e.loadAssistantIdentity(),ve(e,v,!0),ne(e)},onPinToggle:async(d,v,S)=>{const{toggleWorkspacePin:_}=await E(async()=>{const{toggleWorkspacePin:A}=await Promise.resolve().then(()=>pe);return{toggleWorkspacePin:A}},void 0,import.meta.url);await _(e,d,v,S)||e.showToast("Failed to update pin","error")},onPinSessionToggle:async(d,v,S)=>{const{toggleWorkspaceSessionPin:_}=await E(async()=>{const{toggleWorkspaceSessionPin:A}=await Promise.resolve().then(()=>pe);return{toggleWorkspaceSessionPin:A}},void 0,import.meta.url);await _(e,d,v,S)||e.showToast("Failed to update session pin","error")},onToggleFolder:d=>{E(async()=>{const{toggleWorkspaceFolder:v}=await Promise.resolve().then(()=>pe);return{toggleWorkspaceFolder:v}},void 0,import.meta.url).then(({toggleWorkspaceFolder:v})=>{e.workspaceExpandedFolders=v(e.workspaceExpandedFolders??new Set,d),e.requestUpdate()})},onTeamSetup:async()=>{let d="I want to set up a Team Workspace so my team can collaborate. Please walk me through it step by step, keeping it simple.";try{const v=await e.client?.request("workspaces.teamSetupPrompt",{});v?.prompt&&(d=v.prompt)}catch{}e.handleStartChatWithPrompt(d)},allTasks:e.allTasks??[],taskFilter:e.taskFilter??"outstanding",taskSort:e.taskSort??"due",showCompletedTasks:e.showCompletedTasks??!1,onToggleTaskComplete:async(d,v)=>{const{toggleTaskComplete:S,loadAllTasksWithQueueStatus:_,getWorkspace:T}=await E(async()=>{const{toggleTaskComplete:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}=await Promise.resolve().then(()=>pe);return{toggleTaskComplete:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}},void 0,import.meta.url);if(!await S(e,d,v)){e.showToast("Failed to update task","error");return}if(e.allTasks=await _(e),e.selectedWorkspace){const C=await T(e,e.selectedWorkspace.id);C&&(e.selectedWorkspace=C)}},onCreateTask:async(d,v)=>{const{createTask:S,loadAllTasksWithQueueStatus:_,getWorkspace:T}=await E(async()=>{const{createTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}=await Promise.resolve().then(()=>pe);return{createTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}},void 0,import.meta.url),A=await S(e,d,v);if(!A){e.showToast("Failed to create task","error");return}if(e.showToast(`Task created: ${A.title}`,"success"),e.allTasks=await _(e),e.selectedWorkspace){const C=await T(e,e.selectedWorkspace.id);C&&(e.selectedWorkspace=C)}},onSetTaskFilter:d=>{e.taskFilter=d},onSetTaskSort:d=>{e.taskSort=d},onToggleCompletedTasks:()=>{e.showCompletedTasks=!(e.showCompletedTasks??!1)},editingTaskId:e.editingTaskId??null,workspaceNames:(e.workspaces??[]).map(d=>d.name),onStartTask:async d=>{const{startTask:v,loadAllTasksWithQueueStatus:S}=await E(async()=>{const{startTask:C,loadAllTasksWithQueueStatus:L}=await Promise.resolve().then(()=>pe);return{startTask:C,loadAllTasksWithQueueStatus:L}},void 0,import.meta.url),_=await v(e,d);if(!_?.sessionId){e.showToast("Failed to open session for task","error");return}$e(e);const T=_.sessionId;_.task?.title&&Te.set(T,_.task.title);const A=e.settings.openTabs.includes(T)?e.settings.openTabs:[...e.settings.openTabs,T];if(e.applySettings({...e.settings,openTabs:A,sessionKey:T,lastActiveSessionKey:T,tabLastViewed:{...e.settings.tabLastViewed,[T]:Date.now()}}),e.sessionKey=T,e.setTab("chat"),_.created&&!_.queueOutput){const C=e.allTasks??[],L=e.selectedWorkspace?.tasks??[],P=[...C,...L].find(Q=>Q.id===d),te=P?.project?` (project: ${P.project})`:"";e.chatMessage=`Let's work on: ${P?.title??"this task"}${te}`}else e.chatMessage="";e.chatMessages=[],e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.loadAssistantIdentity(),ve(e,T,!0),await ne(e),_.queueOutput&&e.chatMessages.length===0&&e.seedSessionWithAgentOutput(_.task?.title??"this task",_.queueOutput,_.agentPrompt??void 0),e.allTasks=await S(e),e.requestUpdate()},onEditTask:d=>{e.editingTaskId=d},onUpdateTask:async(d,v)=>{const{updateTask:S,loadAllTasksWithQueueStatus:_,getWorkspace:T}=await E(async()=>{const{updateTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}=await Promise.resolve().then(()=>pe);return{updateTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}},void 0,import.meta.url);if(!await S(e,d,v)){e.showToast("Failed to update task","error");return}if(e.editingTaskId=null,e.allTasks=await _(e),e.selectedWorkspace){const C=await T(e,e.selectedWorkspace.id);C&&(e.selectedWorkspace=C)}},browsePath:e.workspaceBrowsePath??null,browseEntries:e.workspaceBrowseEntries??null,breadcrumbs:e.workspaceBreadcrumbs??null,browseSearchQuery:e.workspaceBrowseSearchQuery??"",browseSearchResults:e.workspaceBrowseSearchResults??null,onBrowseFolder:d=>e.handleWorkspaceBrowse(d),onBrowseSearch:d=>e.handleWorkspaceBrowseSearch(d),onBrowseBack:()=>e.handleWorkspaceBrowseBack(),onCreateFolder:d=>e.handleWorkspaceCreateFolder(d),onBatchPushToDrive:d=>e.handleBatchPushToDrive(d)}):h}
8397
+ ${e.tab==="workspaces"?vk({connected:e.connected,workspaces:e.workspaces??[],selectedWorkspace:e.selectedWorkspace??null,searchQuery:e.workspacesSearchQuery??"",itemSearchQuery:e.workspaceItemSearchQuery??"",expandedFolders:e.workspaceExpandedFolders??new Set,loading:e.workspacesLoading??!1,createLoading:e.workspacesCreateLoading??!1,error:e.workspacesError??null,onSearch:d=>e.workspacesSearchQuery=d,onItemSearch:d=>e.workspaceItemSearchQuery=d,onCreateWorkspace:async d=>{e.workspacesCreateLoading=!0;try{const{createWorkspace:v,selectWorkspace:S}=await E(async()=>{const{createWorkspace:T,selectWorkspace:A}=await Promise.resolve().then(()=>pe);return{createWorkspace:T,selectWorkspace:A}},void 0,import.meta.url),_=await v(e,d);return _?(e.workspaceItemSearchQuery="",await S(e,_),e.showToast(`Created workspace: ${_.name}`,"success"),!0):(e.showToast("Failed to create workspace","error"),!1)}finally{e.workspacesCreateLoading=!1}},onDeleteWorkspace:async d=>{const{deleteWorkspace:v,loadAllTasksWithQueueStatus:S}=await E(async()=>{const{deleteWorkspace:T,loadAllTasksWithQueueStatus:A}=await Promise.resolve().then(()=>pe);return{deleteWorkspace:T,loadAllTasksWithQueueStatus:A}},void 0,import.meta.url);if(!await v(e,d.id)){e.showToast(`Failed to delete ${d.name}`,"error");return}e.showToast(`Deleted workspace: ${d.name}`,"success"),e.allTasks=await S(e)},onSelectWorkspace:async d=>{e.workspaceItemSearchQuery="";const{selectWorkspace:v}=await E(async()=>{const{selectWorkspace:S}=await Promise.resolve().then(()=>pe);return{selectWorkspace:S}},void 0,import.meta.url);await v(e,d)},onBack:()=>{e.selectedWorkspace=null,e.workspaceItemSearchQuery=""},onItemClick:async d=>{const{readWorkspaceFile:v}=await E(async()=>{const{readWorkspaceFile:T}=await Promise.resolve().then(()=>pe);return{readWorkspaceFile:T}},void 0,import.meta.url),S=e.selectedWorkspace?.id,_=await v(e,d.path,S);if(!_){e.showToast(`Failed to open ${d.name}`,"error");return}e.handleOpenSidebar(_.content,{mimeType:_.mime,filePath:d.path,title:d.name})},onSessionClick:async d=>{if(!d.key)return;const v=d.key;$e(e),e.sessionKey=v,Le(e,v),e.chatLoading=!0,e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll();const S=e.settings.openTabs.includes(v)?e.settings.openTabs:[...e.settings.openTabs,v];e.applySettings({...e.settings,openTabs:S,sessionKey:v,lastActiveSessionKey:v,tabLastViewed:{...e.settings.tabLastViewed,[v]:Date.now()}}),e.setTab("chat"),e.loadAssistantIdentity(),ve(e,v,!0),ne(e)},onPinToggle:async(d,v,S)=>{const{toggleWorkspacePin:_}=await E(async()=>{const{toggleWorkspacePin:A}=await Promise.resolve().then(()=>pe);return{toggleWorkspacePin:A}},void 0,import.meta.url);await _(e,d,v,S)||e.showToast("Failed to update pin","error")},onPinSessionToggle:async(d,v,S)=>{const{toggleWorkspaceSessionPin:_}=await E(async()=>{const{toggleWorkspaceSessionPin:A}=await Promise.resolve().then(()=>pe);return{toggleWorkspaceSessionPin:A}},void 0,import.meta.url);await _(e,d,v,S)||e.showToast("Failed to update session pin","error")},onToggleFolder:d=>{E(async()=>{const{toggleWorkspaceFolder:v}=await Promise.resolve().then(()=>pe);return{toggleWorkspaceFolder:v}},void 0,import.meta.url).then(({toggleWorkspaceFolder:v})=>{e.workspaceExpandedFolders=v(e.workspaceExpandedFolders??new Set,d),e.requestUpdate()})},onTeamSetup:async()=>{let d="I want to set up a Team Workspace so my team can collaborate. Please walk me through it step by step, keeping it simple.";try{const v=await e.client?.request("workspaces.teamSetupPrompt",{});v?.prompt&&(d=v.prompt)}catch{}e.handleStartChatWithPrompt(d)},allTasks:e.allTasks??[],taskFilter:e.taskFilter??"outstanding",taskSort:e.taskSort??"due",showCompletedTasks:e.showCompletedTasks??!1,onToggleTaskComplete:async(d,v)=>{const{toggleTaskComplete:S,loadAllTasksWithQueueStatus:_,getWorkspace:T}=await E(async()=>{const{toggleTaskComplete:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}=await Promise.resolve().then(()=>pe);return{toggleTaskComplete:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}},void 0,import.meta.url);if(!await S(e,d,v)){e.showToast("Failed to update task","error");return}if(e.allTasks=await _(e),e.selectedWorkspace){const C=await T(e,e.selectedWorkspace.id);C&&(e.selectedWorkspace=C)}},onCreateTask:async(d,v)=>{const{createTask:S,loadAllTasksWithQueueStatus:_,getWorkspace:T}=await E(async()=>{const{createTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}=await Promise.resolve().then(()=>pe);return{createTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}},void 0,import.meta.url),A=await S(e,d,v);if(!A){e.showToast("Failed to create task","error");return}if(e.showToast(`Task created: ${A.title}`,"success"),e.allTasks=await _(e),e.selectedWorkspace){const C=await T(e,e.selectedWorkspace.id);C&&(e.selectedWorkspace=C)}},onSetTaskFilter:d=>{e.taskFilter=d},onSetTaskSort:d=>{e.taskSort=d},onToggleCompletedTasks:()=>{e.showCompletedTasks=!(e.showCompletedTasks??!1)},editingTaskId:e.editingTaskId??null,workspaceNames:(e.workspaces??[]).map(d=>d.name),onStartTask:async d=>{const{startTask:v,loadAllTasksWithQueueStatus:S}=await E(async()=>{const{startTask:C,loadAllTasksWithQueueStatus:L}=await Promise.resolve().then(()=>pe);return{startTask:C,loadAllTasksWithQueueStatus:L}},void 0,import.meta.url),_=await v(e,d);if(!_?.sessionId){e.showToast("Failed to open session for task","error");return}$e(e);const T=_.sessionId;_.task?.title&&Te.set(T,_.task.title);const A=e.settings.openTabs.includes(T)?e.settings.openTabs:[...e.settings.openTabs,T];if(e.applySettings({...e.settings,openTabs:A,sessionKey:T,lastActiveSessionKey:T,tabLastViewed:{...e.settings.tabLastViewed,[T]:Date.now()}}),e.sessionKey=T,e.setTab("chat"),_.created&&!_.queueOutput){const C=e.allTasks??[],L=e.selectedWorkspace?.tasks??[],P=[...C,...L].find(Q=>Q.id===d),te=P?.project?` (project: ${P.project})`:"";e.chatMessage=`Let's work on: ${P?.title??"this task"}${te}`}else e.chatMessage="";e.chatMessages=[],e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.resetChatScroll(),e.loadAssistantIdentity(),ve(e,T,!0),await ne(e),_.queueOutput&&e.chatMessages.length===0&&e.seedSessionWithAgentOutput(_.task?.title??"this task",_.queueOutput,_.agentPrompt??void 0),e.allTasks=await S(e),e.requestUpdate()},onEditTask:d=>{e.editingTaskId=d},onUpdateTask:async(d,v)=>{const{updateTask:S,loadAllTasksWithQueueStatus:_,getWorkspace:T}=await E(async()=>{const{updateTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}=await Promise.resolve().then(()=>pe);return{updateTask:C,loadAllTasksWithQueueStatus:L,getWorkspace:P}},void 0,import.meta.url);if(!await S(e,d,v)){e.showToast("Failed to update task","error");return}if(e.editingTaskId=null,e.allTasks=await _(e),e.selectedWorkspace){const C=await T(e,e.selectedWorkspace.id);C&&(e.selectedWorkspace=C)}},browsePath:e.workspaceBrowsePath??null,browseEntries:e.workspaceBrowseEntries??null,breadcrumbs:e.workspaceBreadcrumbs??null,browseSearchQuery:e.workspaceBrowseSearchQuery??"",browseSearchResults:e.workspaceBrowseSearchResults??null,onBrowseFolder:d=>e.handleWorkspaceBrowse(d),onBrowseSearch:d=>e.handleWorkspaceBrowseSearch(d),onBrowseBack:()=>e.handleWorkspaceBrowseBack(),onCreateFolder:d=>e.handleWorkspaceCreateFolder(d),onBatchPushToDrive:d=>e.handleBatchPushToDrive(d)}):h}
8371
8398
 
8372
- ${e.tab==="today"||e.tab==="my-day"?e.dynamicSlots.today?cc(e,"today"):Pk({connected:e.connected,loading:e.myDayLoading??!1,error:e.myDayError??null,onRefresh:()=>e.handleMyDayRefresh(),dailyBrief:e.dailyBrief??null,dailyBriefLoading:e.dailyBriefLoading??!1,dailyBriefError:e.dailyBriefError??null,onBriefRefresh:()=>e.handleDailyBriefRefresh(),onBriefOpenInObsidian:()=>e.handleDailyBriefOpenInObsidian(),onBriefSave:d=>e.handleBriefSave(d),onBriefToggleCheckbox:(d,v)=>e.handleBriefToggleCheckbox(d,v),onOpenFile:d=>{e.handleOpenFile(d)},selectedDate:e.todaySelectedDate,onDatePrev:()=>e.handleDatePrev(),onDateNext:()=>e.handleDateNext(),onDateToday:()=>e.handleDateToday(),viewMode:e.todayViewMode??"brief",onViewModeChange:d=>e.handleTodayViewModeChange(d),agentLog:e.agentLog??null,agentLogLoading:e.agentLogLoading??!1,agentLogError:e.agentLogError??null,onAgentLogRefresh:()=>e.handleMyDayRefresh(),focusPulseActive:!1,todayTasks:e.todayTasks??[],todayTasksLoading:e.todayTasksLoading??!1,onToggleTaskComplete:(d,v)=>e.handleMyDayTaskStatusChange(d,v==="complete"?"pending":"complete"),onStartTask:d=>e.handleTodayStartTask(d),onCreateTask:d=>e.handleTodayCreateTask(d),onEditTask:d=>e.handleTodayEditTask(d),onUpdateTask:(d,v)=>e.handleTodayUpdateTask(d,v),editingTaskId:e.todayEditingTaskId,showCompletedTasks:e.todayShowCompleted,onToggleCompletedTasks:()=>e.handleTodayToggleCompleted(),decisionCards:(e.todayQueueResults??[]).length>0?{items:e.todayQueueResults,onApprove:d=>e.handleDecisionApprove(d),onReject:d=>e.handleDecisionReject(d),onViewOutput:(d,v)=>e.handleDecisionViewOutput(d,v),onOpenChat:d=>e.handleDecisionOpenChat(d)}:void 0}):h}
8399
+ ${e.tab==="today"||e.tab==="my-day"?e.dynamicSlots.today?cc(e,"today"):Lk({connected:e.connected,loading:e.myDayLoading??!1,error:e.myDayError??null,onRefresh:()=>e.handleMyDayRefresh(),dailyBrief:e.dailyBrief??null,dailyBriefLoading:e.dailyBriefLoading??!1,dailyBriefError:e.dailyBriefError??null,onBriefRefresh:()=>e.handleDailyBriefRefresh(),onBriefOpenInObsidian:()=>e.handleDailyBriefOpenInObsidian(),onBriefSave:d=>e.handleBriefSave(d),onBriefToggleCheckbox:(d,v)=>e.handleBriefToggleCheckbox(d,v),onOpenFile:d=>{e.handleOpenFile(d)},selectedDate:e.todaySelectedDate,onDatePrev:()=>e.handleDatePrev(),onDateNext:()=>e.handleDateNext(),onDateToday:()=>e.handleDateToday(),viewMode:e.todayViewMode??"brief",onViewModeChange:d=>e.handleTodayViewModeChange(d),agentLog:e.agentLog??null,agentLogLoading:e.agentLogLoading??!1,agentLogError:e.agentLogError??null,onAgentLogRefresh:()=>e.handleMyDayRefresh(),focusPulseActive:!1,todayTasks:e.todayTasks??[],todayTasksLoading:e.todayTasksLoading??!1,onToggleTaskComplete:(d,v)=>e.handleMyDayTaskStatusChange(d,v==="complete"?"pending":"complete"),onStartTask:d=>e.handleTodayStartTask(d),onCreateTask:d=>e.handleTodayCreateTask(d),onEditTask:d=>e.handleTodayEditTask(d),onUpdateTask:(d,v)=>e.handleTodayUpdateTask(d,v),editingTaskId:e.todayEditingTaskId,showCompletedTasks:e.todayShowCompleted,onToggleCompletedTasks:()=>e.handleTodayToggleCompleted(),decisionCards:(e.todayQueueResults??[]).length>0?{items:e.todayQueueResults,onApprove:d=>e.handleDecisionApprove(d),onReject:d=>e.handleDecisionReject(d),onViewOutput:(d,v)=>e.handleDecisionViewOutput(d,v),onOpenChat:d=>e.handleDecisionOpenChat(d)}:void 0}):h}
8373
8400
 
8374
8401
  ${e.tab==="work"?e.dynamicSlots.work?cc(e,"work"):t1({connected:e.connected,projects:e.workProjects??[],loading:e.workLoading??!1,error:e.workError??null,expandedProjects:e.workExpandedProjects,projectFiles:e.workProjectFiles??{},detailLoading:e.workDetailLoading??new Set,onRefresh:()=>e.handleWorkRefresh(),onToggleProject:d=>e.handleWorkToggleProject(d),onPersonClick:d=>e.handleWorkPersonClick(d),onFileClick:d=>e.handleWorkFileClick(d),onSkillClick:(d,v)=>e.handleWorkSkillClick(d,v)}):h}
8375
8402
 
8376
- ${e.tab==="channels"?Tw({connected:e.connected,loading:e.channelsLoading,snapshot:e.channelsSnapshot,lastError:e.channelsError,lastSuccessAt:e.channelsLastSuccess,whatsappMessage:e.whatsappLoginMessage,whatsappQrDataUrl:e.whatsappLoginQrDataUrl,whatsappConnected:e.whatsappLoginConnected,whatsappBusy:e.whatsappBusy,configSchema:e.configSchema,configSchemaLoading:e.configSchemaLoading,configForm:e.configForm,configUiHints:e.configUiHints,configSaving:e.configSaving,configFormDirty:e.configFormDirty,nostrProfileFormState:e.nostrProfileFormState,nostrProfileAccountId:e.nostrProfileAccountId,onRefresh:d=>Me(e,d),onWhatsAppStart:d=>e.handleWhatsAppStart(d),onWhatsAppWait:()=>e.handleWhatsAppWait(),onWhatsAppLogout:()=>e.handleWhatsAppLogout(),onConfigPatch:(d,v)=>Zt(e,d,v),onConfigSave:()=>e.handleChannelConfigSave(),onConfigReload:()=>e.handleChannelConfigReload(),onNostrProfileEdit:(d,v)=>e.handleNostrProfileEdit(d,v),onNostrProfileCancel:()=>e.handleNostrProfileCancel(),onNostrProfileFieldChange:(d,v)=>e.handleNostrProfileFieldChange(d,v),onNostrProfileSave:()=>e.handleNostrProfileSave(),onNostrProfileImport:()=>e.handleNostrProfileImport(),onNostrProfileToggleAdvanced:()=>e.handleNostrProfileToggleAdvanced()}):h}
8403
+ ${e.tab==="channels"?Aw({connected:e.connected,loading:e.channelsLoading,snapshot:e.channelsSnapshot,lastError:e.channelsError,lastSuccessAt:e.channelsLastSuccess,whatsappMessage:e.whatsappLoginMessage,whatsappQrDataUrl:e.whatsappLoginQrDataUrl,whatsappConnected:e.whatsappLoginConnected,whatsappBusy:e.whatsappBusy,configSchema:e.configSchema,configSchemaLoading:e.configSchemaLoading,configForm:e.configForm,configUiHints:e.configUiHints,configSaving:e.configSaving,configFormDirty:e.configFormDirty,nostrProfileFormState:e.nostrProfileFormState,nostrProfileAccountId:e.nostrProfileAccountId,onRefresh:d=>Me(e,d),onWhatsAppStart:d=>e.handleWhatsAppStart(d),onWhatsAppWait:()=>e.handleWhatsAppWait(),onWhatsAppLogout:()=>e.handleWhatsAppLogout(),onConfigPatch:(d,v)=>Zt(e,d,v),onConfigSave:()=>e.handleChannelConfigSave(),onConfigReload:()=>e.handleChannelConfigReload(),onNostrProfileEdit:(d,v)=>e.handleNostrProfileEdit(d,v),onNostrProfileCancel:()=>e.handleNostrProfileCancel(),onNostrProfileFieldChange:(d,v)=>e.handleNostrProfileFieldChange(d,v),onNostrProfileSave:()=>e.handleNostrProfileSave(),onNostrProfileImport:()=>e.handleNostrProfileImport(),onNostrProfileToggleAdvanced:()=>e.handleNostrProfileToggleAdvanced()}):h}
8377
8404
 
8378
- ${e.tab==="instances"?Q$({loading:e.presenceLoading,entries:e.presenceEntries,lastError:e.presenceError,statusMessage:e.presenceStatus,onRefresh:()=>$o(e)}):h}
8405
+ ${e.tab==="instances"?V$({loading:e.presenceLoading,entries:e.presenceEntries,lastError:e.presenceError,statusMessage:e.presenceStatus,onRefresh:()=>$o(e)}):h}
8379
8406
 
8380
- ${e.tab==="sessions"?v0({loading:e.sessionsLoading,result:e.sessionsResult,error:e.sessionsError,activeMinutes:e.sessionsFilterActive,limit:e.sessionsFilterLimit,includeGlobal:e.sessionsIncludeGlobal,includeUnknown:e.sessionsIncludeUnknown,basePath:e.basePath,archivedSessions:e.archivedSessions,archivedSessionsLoading:e.archivedSessionsLoading,archivedSessionsExpanded:e.archivedSessionsExpanded,onFiltersChange:d=>{e.sessionsFilterActive=d.activeMinutes,e.sessionsFilterLimit=d.limit,e.sessionsIncludeGlobal=d.includeGlobal,e.sessionsIncludeUnknown=d.includeUnknown},onRefresh:()=>{X(e),Mt(e)},onPatch:async(d,v)=>{const S=await Ts(e,d,v);if(S.ok&&S.canonicalKey!==d&&e.settings.openTabs.includes(d)){const _=e.settings.openTabs.map(A=>A===d?S.canonicalKey:A),T=d===e.sessionKey;e.applySettings({...e.settings,openTabs:_,tabLastViewed:{...e.settings.tabLastViewed,[S.canonicalKey]:e.settings.tabLastViewed[d]??Date.now()},...T?{sessionKey:S.canonicalKey,lastActiveSessionKey:S.canonicalKey}:{}}),T&&(e.sessionKey=S.canonicalKey,ve(e,S.canonicalKey,!0))}},onDelete:d=>Nd(e,d),onArchive:d=>Fd(e,d),onUnarchive:d=>Bd(e,d),onToggleArchived:()=>{e.archivedSessionsExpanded=!e.archivedSessionsExpanded,e.archivedSessionsExpanded&&e.archivedSessions.length===0&&Mt(e)},onAutoArchive:()=>Ud(e)}):h}
8407
+ ${e.tab==="sessions"?g0({loading:e.sessionsLoading,result:e.sessionsResult,error:e.sessionsError,activeMinutes:e.sessionsFilterActive,limit:e.sessionsFilterLimit,includeGlobal:e.sessionsIncludeGlobal,includeUnknown:e.sessionsIncludeUnknown,basePath:e.basePath,archivedSessions:e.archivedSessions,archivedSessionsLoading:e.archivedSessionsLoading,archivedSessionsExpanded:e.archivedSessionsExpanded,onFiltersChange:d=>{e.sessionsFilterActive=d.activeMinutes,e.sessionsFilterLimit=d.limit,e.sessionsIncludeGlobal=d.includeGlobal,e.sessionsIncludeUnknown=d.includeUnknown},onRefresh:()=>{X(e),It(e)},onPatch:async(d,v)=>{const S=await Ts(e,d,v);if(S.ok&&S.canonicalKey!==d&&e.settings.openTabs.includes(d)){const _=e.settings.openTabs.map(A=>A===d?S.canonicalKey:A),T=d===e.sessionKey;e.applySettings({...e.settings,openTabs:_,tabLastViewed:{...e.settings.tabLastViewed,[S.canonicalKey]:e.settings.tabLastViewed[d]??Date.now()},...T?{sessionKey:S.canonicalKey,lastActiveSessionKey:S.canonicalKey}:{}}),T&&(e.sessionKey=S.canonicalKey,ve(e,S.canonicalKey,!0))}},onDelete:d=>Nd(e,d),onArchive:d=>Fd(e,d),onUnarchive:d=>Bd(e,d),onToggleArchived:()=>{e.archivedSessionsExpanded=!e.archivedSessionsExpanded,e.archivedSessionsExpanded&&e.archivedSessions.length===0&&It(e)},onAutoArchive:()=>Ud(e)}):h}
8381
8408
 
8382
- ${e.tab==="cron"?z$({loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:e.channelsSnapshot?.channelMeta?.length?e.channelsSnapshot.channelMeta.map(d=>d.id):e.channelsSnapshot?.channelOrder??[],channelLabels:e.channelsSnapshot?.channelLabels??{},channelMeta:e.channelsSnapshot?.channelMeta??[],runsJobId:e.cronRunsJobId,runs:e.cronRuns,onFormChange:d=>e.cronForm={...e.cronForm,...d},onRefresh:()=>e.loadCron(),onAdd:()=>oy(e),onToggle:(d,v)=>ry(e,d,v),onRun:d=>ly(e,d),onRemove:d=>cy(e,d),onLoadRuns:d=>nu(e,d)}):h}
8409
+ ${e.tab==="cron"?B$({loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:e.channelsSnapshot?.channelMeta?.length?e.channelsSnapshot.channelMeta.map(d=>d.id):e.channelsSnapshot?.channelOrder??[],channelLabels:e.channelsSnapshot?.channelLabels??{},channelMeta:e.channelsSnapshot?.channelMeta??[],runsJobId:e.cronRunsJobId,runs:e.cronRuns,onFormChange:d=>e.cronForm={...e.cronForm,...d},onRefresh:()=>e.loadCron(),onAdd:()=>iy(e),onToggle:(d,v)=>oy(e,d,v),onRun:d=>ry(e,d),onRemove:d=>ly(e,d),onLoadRuns:d=>nu(e,d)}):h}
8383
8410
 
8384
- ${e.tab==="skills"?k0({loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,subTab:e.skillsSubTab,onFilterChange:d=>e.skillsFilter=d,onRefresh:()=>es(e,{clearMessages:!0}),onToggle:(d,v)=>Ly(e,d,v),onEdit:(d,v)=>Ey(e,d,v),onSaveKey:d=>Ry(e,d),onInstall:(d,v,S)=>Py(e,d,v,S),onSubTabChange:d=>{e.skillsSubTab=d,d==="clawhub"&&e.clawhubExploreItems},clawhub:{loading:e.clawhubLoading,error:e.clawhubError,query:e.clawhubQuery,results:e.clawhubResults,exploreItems:e.clawhubExploreItems,exploreSort:e.clawhubExploreSort,detailSlug:e.clawhubDetailSlug,detail:e.clawhubDetail,importing:e.clawhubImporting,message:e.clawhubMessage,onSearch:d=>{e.clawhubQuery=d},onExplore:d=>void 0,onDetail:d=>void 0,onCloseDetail:()=>void 0,onImport:d=>gl(),onImportAndPersonalize:async d=>{if(!await gl())return;const S=await Ub();S&&(_o(e,"chat"),ua(e),e.chatMessage=S)}}}):h}
8411
+ ${e.tab==="skills"?w0({loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,subTab:e.skillsSubTab,onFilterChange:d=>e.skillsFilter=d,onRefresh:()=>es(e,{clearMessages:!0}),onToggle:(d,v)=>Cy(e,d,v),onEdit:(d,v)=>xy(e,d,v),onSaveKey:d=>Ey(e,d),onInstall:(d,v,S)=>Ly(e,d,v,S),onSubTabChange:d=>{e.skillsSubTab=d,d==="clawhub"&&e.clawhubExploreItems},clawhub:{loading:e.clawhubLoading,error:e.clawhubError,query:e.clawhubQuery,results:e.clawhubResults,exploreItems:e.clawhubExploreItems,exploreSort:e.clawhubExploreSort,detailSlug:e.clawhubDetailSlug,detail:e.clawhubDetail,importing:e.clawhubImporting,message:e.clawhubMessage,onSearch:d=>{e.clawhubQuery=d},onExplore:d=>void 0,onDetail:d=>void 0,onCloseDetail:()=>void 0,onImport:d=>gl(),onImportAndPersonalize:async d=>{if(!await gl())return;const S=await Fb();S&&(_o(e,"chat"),ua(e),e.chatMessage=S)}}}):h}
8385
8412
 
8386
- ${e.tab==="nodes"?Ik({loading:e.nodesLoading,nodes:e.nodes,devicesLoading:e.devicesLoading,devicesError:e.devicesError,devicesList:e.devicesList,configForm:e.configForm??e.configSnapshot?.config,configLoading:e.configLoading,configSaving:e.configSaving,configDirty:e.configFormDirty,configFormMode:e.configFormMode,execApprovalsLoading:e.execApprovalsLoading,execApprovalsSaving:e.execApprovalsSaving,execApprovalsDirty:e.execApprovalsDirty,execApprovalsSnapshot:e.execApprovalsSnapshot,execApprovalsForm:e.execApprovalsForm,execApprovalsSelectedAgent:e.execApprovalsSelectedAgent,execApprovalsTarget:e.execApprovalsTarget,execApprovalsTargetNodeId:e.execApprovalsTargetNodeId,onRefresh:()=>na(e),onDevicesRefresh:()=>pt(e),onDeviceApprove:d=>Qm(e,d),onDeviceReject:d=>Ym(e,d),onDeviceRotate:(d,v,S)=>Jm(e,{deviceId:d,role:v,scopes:S}),onDeviceRevoke:(d,v)=>Xm(e,{deviceId:d,role:v}),onLoadConfig:()=>Ye(e),onLoadExecApprovals:()=>{const d=e.execApprovalsTarget==="node"&&e.execApprovalsTargetNodeId?{kind:"node",nodeId:e.execApprovalsTargetNodeId}:{kind:"gateway"};return wo(e,d)},onBindDefault:d=>{d?Zt(e,["tools","exec","node"],d):fr(e,["tools","exec","node"])},onBindAgent:(d,v)=>{const S=["agents","list",d,"tools","exec","node"];v?Zt(e,S,v):fr(e,S)},onSaveBindings:()=>Ps(e),onExecApprovalsTargetChange:(d,v)=>{e.execApprovalsTarget=d,e.execApprovalsTargetNodeId=v,e.execApprovalsSnapshot=null,e.execApprovalsForm=null,e.execApprovalsDirty=!1,e.execApprovalsSelectedAgent=null},onExecApprovalsSelectAgent:d=>{e.execApprovalsSelectedAgent=d},onExecApprovalsPatch:(d,v)=>by(e,d,v),onExecApprovalsRemove:d=>wy(e,d),onSaveExecApprovals:()=>{const d=e.execApprovalsTarget==="node"&&e.execApprovalsTargetNodeId?{kind:"node",nodeId:e.execApprovalsTargetNodeId}:{kind:"gateway"};return yy(e,d)}}):h}
8413
+ ${e.tab==="nodes"?Rk({loading:e.nodesLoading,nodes:e.nodes,devicesLoading:e.devicesLoading,devicesError:e.devicesError,devicesList:e.devicesList,configForm:e.configForm??e.configSnapshot?.config,configLoading:e.configLoading,configSaving:e.configSaving,configDirty:e.configFormDirty,configFormMode:e.configFormMode,execApprovalsLoading:e.execApprovalsLoading,execApprovalsSaving:e.execApprovalsSaving,execApprovalsDirty:e.execApprovalsDirty,execApprovalsSnapshot:e.execApprovalsSnapshot,execApprovalsForm:e.execApprovalsForm,execApprovalsSelectedAgent:e.execApprovalsSelectedAgent,execApprovalsTarget:e.execApprovalsTarget,execApprovalsTargetNodeId:e.execApprovalsTargetNodeId,onRefresh:()=>na(e),onDevicesRefresh:()=>pt(e),onDeviceApprove:d=>Gm(e,d),onDeviceReject:d=>Qm(e,d),onDeviceRotate:(d,v,S)=>Ym(e,{deviceId:d,role:v,scopes:S}),onDeviceRevoke:(d,v)=>Jm(e,{deviceId:d,role:v}),onLoadConfig:()=>Ye(e),onLoadExecApprovals:()=>{const d=e.execApprovalsTarget==="node"&&e.execApprovalsTargetNodeId?{kind:"node",nodeId:e.execApprovalsTargetNodeId}:{kind:"gateway"};return wo(e,d)},onBindDefault:d=>{d?Zt(e,["tools","exec","node"],d):fr(e,["tools","exec","node"])},onBindAgent:(d,v)=>{const S=["agents","list",d,"tools","exec","node"];v?Zt(e,S,v):fr(e,S)},onSaveBindings:()=>Ps(e),onExecApprovalsTargetChange:(d,v)=>{e.execApprovalsTarget=d,e.execApprovalsTargetNodeId=v,e.execApprovalsSnapshot=null,e.execApprovalsForm=null,e.execApprovalsDirty=!1,e.execApprovalsSelectedAgent=null},onExecApprovalsSelectAgent:d=>{e.execApprovalsSelectedAgent=d},onExecApprovalsPatch:(d,v)=>yy(e,d,v),onExecApprovalsRemove:d=>by(e,d),onSaveExecApprovals:()=>{const d=e.execApprovalsTarget==="node"&&e.execApprovalsTargetNodeId?{kind:"node",nodeId:e.execApprovalsTargetNodeId}:{kind:"gateway"};return vy(e,d)}}):h}
8387
8414
 
8388
8415
  ${t&&n>=2&&n<=5&&e.tab==="chat"?E1({phase:n,identity:s?.identity??null,tools:s?.tools??[],auditFindings:s?.audit?.findings??[],summary:s?.summary??null,onSkipPhase:()=>e.handleOnboardingSkipPhase?.()}):e.tab==="chat"&&e.workspaceNeedsSetup&&!e.chatMessages?.length&&!t?r`
8389
8416
  <div class="workspace-welcome-banner">
@@ -8411,9 +8438,9 @@ ${i}
8411
8438
 
8412
8439
  ${e.tab==="chat"&&e.settings.chatParallelView?HS({state:e,onAssignLane:(d,v)=>{const S=v?Ie(e.sessionsResult?.sessions,v)?.key??v:null,_=[...e.settings.parallelLanes];_[d]=S,e.applySettings({...e.settings,parallelLanes:_}),S&&e.client&&no(e.client,S).then(()=>{e.applySettings({...e.settings})})},onReorderLanes:(d,v)=>{if(d===v||d<0||v<0||d>=e.settings.parallelLanes.length||v>=e.settings.parallelLanes.length)return;const S=[...e.settings.parallelLanes],[_]=S.splice(d,1);S.splice(v,0,_),e.applySettings({...e.settings,parallelLanes:S})},onLaneViewed:d=>{const v=Ie(e.sessionsResult?.sessions,d)?.key??d,S=Date.now(),T=Ie(e.sessionsResult?.sessions,v)?.updatedAt??0,A=Math.max(e.settings.tabLastViewed[d]??0,e.settings.tabLastViewed[v]??0);T>0&&A>=T||e.applySettings({...e.settings,tabLastViewed:{...e.settings.tabLastViewed,[d]:S,[v]:S}})},onSendInLane:(d,v)=>{d!==e.sessionKey?($e(e),e.sessionKey=d,Le(e,d),e.chatLoading=!0,e.chatMessages=[],e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.resetToolStream(),e.applySettings({...e.settings,sessionKey:d,lastActiveSessionKey:d}),e.loadAssistantIdentity(),ve(e,d,!0),ne(e).then(()=>{e.chatMessage=v,e.handleSendChat(v)})):(e.chatMessage=v,e.handleSendChat(v))}}):h}
8413
8440
 
8414
- ${e.tab==="chat"&&!e.settings.chatParallelView?y$({basePath:e.basePath,sessionKey:e.sessionKey,onSessionKeyChange:d=>{$e(e),e.sessionKey=d,Le(e,d),e.chatLoading=!0,e.chatMessages=[],e.chatAttachments=[],e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:d,lastActiveSessionKey:d}),e.loadAssistantIdentity(),ne(e),qs(e)},thinkingLevel:e.chatThinkingLevel,showThinking:p,loading:e.chatLoading,sending:e.chatSending,sendingSessionKey:e.chatSendingSessionKey,compactionStatus:e.compactionStatus,assistantAvatarUrl:m,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,draft:e.chatMessage,queue:e.chatQueue,connected:e.connected,canSend:e.connected,disabledReason:l,error:e.lastError,sessions:e.sessionsResult,focusMode:u,onRefresh:()=>(e.resetToolStream(),Promise.all([ne(e),qs(e)])),onToggleFocusMode:()=>{e.onboarding||e.applySettings({...e.settings,chatFocusMode:!e.settings.chatFocusMode})},onChatScroll:d=>e.handleChatScroll(d),onDraftChange:d=>e.chatMessage=d,attachments:e.chatAttachments,onAttachmentsChange:d=>e.chatAttachments=d,showToast:(d,v)=>e.showToast(d,v),onSend:d=>e.handleSendChat(void 0,{queue:d}),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onCompact:()=>{e.handleCompactChat()},pendingRetry:e.pendingRetry,onRetry:()=>{e.handleRetryMessage()},onClearRetry:()=>e.handleClearRetry(),onQueueRemove:d=>e.removeQueuedMessage(d),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),onConsciousnessFlush:()=>{e.handleConsciousnessFlush()},consciousnessStatus:e.consciousnessStatus,sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,sidebarMimeType:e.sidebarMimeType,sidebarFilePath:e.sidebarFilePath,sidebarTitle:e.sidebarTitle,splitRatio:e.splitRatio,onOpenSidebar:(d,v)=>e.handleOpenSidebar(d,v),onMessageLinkClick:d=>e.handleOpenMessageFileLink(d),onCloseSidebar:()=>e.handleCloseSidebar(),onOpenFile:d=>e.handleOpenFile(d),onSplitRatioChange:d=>e.handleSplitRatioChange(d),onPushToDrive:(d,v)=>e.handlePushToDrive(d,v),driveAccounts:e.driveAccounts,showDrivePicker:e.showDrivePicker,driveUploading:e.driveUploading,onToggleDrivePicker:()=>e.handleToggleDrivePicker(),onImageClick:(d,v,S)=>e.handleImageClick(d,v,S),resolveImageUrl:(d,v)=>Sv(e.sessionKey,d,v),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,userName:e.userName,userAvatar:e.userAvatar,currentToolName:e.currentToolName,currentToolInfo:e.currentToolInfo,isWorking:e.workingSessions.has(e.sessionKey),showScrollButton:!e.chatUserNearBottom,showNewMessages:e.chatNewMessagesBelow,onScrollToBottom:()=>{const d=document.querySelector(".chat-thread");d&&(d.scrollTo({top:d.scrollHeight,behavior:"smooth"}),e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1)},allyPanelOpen:e.allyPanelOpen??!1,allyProps:e.allyPanelOpen?{allyName:e.assistantName,allyAvatar:e.assistantAvatar??null,open:!0,messages:e.allyMessages??[],stream:e.allyStream??null,draft:e.allyDraft??"",sending:e.allySending??!1,isWorking:e.allyWorking??!1,unreadCount:0,connected:e.connected,compact:!0,attachments:e.allyAttachments??[],onToggle:()=>e.handleAllyToggle(),onDraftChange:d=>e.handleAllyDraftChange(d),onSend:()=>e.handleAllySend(),onOpenFullChat:()=>e.handleAllyOpenFull(),onAttachmentsChange:d=>e.handleAllyAttachmentsChange(d)}:null}):h}
8441
+ ${e.tab==="chat"&&!e.settings.chatParallelView?m$({basePath:e.basePath,sessionKey:e.sessionKey,onSessionKeyChange:d=>{$e(e),e.sessionKey=d,Le(e,d),e.chatLoading=!0,e.chatMessages=[],e.chatAttachments=[],e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:d,lastActiveSessionKey:d}),e.loadAssistantIdentity(),ne(e),qs(e)},thinkingLevel:e.chatThinkingLevel,showThinking:p,loading:e.chatLoading,sending:e.chatSending,sendingSessionKey:e.chatSendingSessionKey,compactionStatus:e.compactionStatus,assistantAvatarUrl:m,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,draft:e.chatMessage,queue:e.chatQueue,connected:e.connected,canSend:e.connected,disabledReason:l,error:e.lastError,sessions:e.sessionsResult,focusMode:u,onRefresh:()=>(e.resetToolStream(),Promise.all([ne(e),qs(e)])),onToggleFocusMode:()=>{e.onboarding||e.applySettings({...e.settings,chatFocusMode:!e.settings.chatFocusMode})},onChatScroll:d=>e.handleChatScroll(d),onDraftChange:d=>e.chatMessage=d,attachments:e.chatAttachments,onAttachmentsChange:d=>e.chatAttachments=d,showToast:(d,v)=>e.showToast(d,v),onSend:d=>e.handleSendChat(void 0,{queue:d}),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onCompact:()=>{e.handleCompactChat()},pendingRetry:e.pendingRetry,onRetry:()=>{e.handleRetryMessage()},onClearRetry:()=>e.handleClearRetry(),onQueueRemove:d=>e.removeQueuedMessage(d),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),onConsciousnessFlush:()=>{e.handleConsciousnessFlush()},consciousnessStatus:e.consciousnessStatus,sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,sidebarMimeType:e.sidebarMimeType,sidebarFilePath:e.sidebarFilePath,sidebarTitle:e.sidebarTitle,splitRatio:e.splitRatio,onOpenSidebar:(d,v)=>e.handleOpenSidebar(d,v),onMessageLinkClick:d=>e.handleOpenMessageFileLink(d),onCloseSidebar:()=>e.handleCloseSidebar(),onOpenFile:d=>e.handleOpenFile(d),onSplitRatioChange:d=>e.handleSplitRatioChange(d),onPushToDrive:(d,v)=>e.handlePushToDrive(d,v),driveAccounts:e.driveAccounts,showDrivePicker:e.showDrivePicker,driveUploading:e.driveUploading,onToggleDrivePicker:()=>e.handleToggleDrivePicker(),onImageClick:(d,v,S)=>e.handleImageClick(d,v,S),resolveImageUrl:(d,v)=>kv(e.sessionKey,d,v),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,userName:e.userName,userAvatar:e.userAvatar,currentToolName:e.currentToolName,currentToolInfo:e.currentToolInfo,isWorking:e.workingSessions.has(e.sessionKey),showScrollButton:!e.chatUserNearBottom,showNewMessages:e.chatNewMessagesBelow,onScrollToBottom:()=>{const d=document.querySelector(".chat-thread");d&&(d.scrollTo({top:d.scrollHeight,behavior:"smooth"}),e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1)},allyPanelOpen:e.allyPanelOpen??!1,allyProps:e.allyPanelOpen?{allyName:e.assistantName,allyAvatar:e.assistantAvatar??null,open:!0,messages:e.allyMessages??[],stream:e.allyStream??null,draft:e.allyDraft??"",sending:e.allySending??!1,isWorking:e.allyWorking??!1,unreadCount:0,connected:e.connected,compact:!0,attachments:e.allyAttachments??[],onToggle:()=>e.handleAllyToggle(),onDraftChange:d=>e.handleAllyDraftChange(d),onSend:()=>e.handleAllySend(),onOpenFullChat:()=>e.handleAllyOpenFull(),onAttachmentsChange:d=>e.handleAllyAttachmentsChange(d)}:null}):h}
8415
8442
 
8416
- ${e.tab==="options"?O0({connected:e.connected,loading:e.godmodeOptionsLoading,options:e.godmodeOptions,onToggle:(d,v)=>e.handleOptionToggle(d,v),onOpenWizard:e.handleWizardOpen?()=>e.handleWizardOpen?.():void 0}):h}
8443
+ ${e.tab==="options"?M0({connected:e.connected,loading:e.godmodeOptionsLoading,options:e.godmodeOptions,onToggle:(d,v)=>e.handleOptionToggle(d,v),onOpenWizard:e.handleWizardOpen?()=>e.handleWizardOpen?.():void 0}):h}
8417
8444
 
8418
8445
  ${e.tab==="guardrails"?TS({connected:e.connected,loading:e.guardrailsLoading,data:e.guardrailsData,showAddForm:e.guardrailsShowAddForm,onToggle:(d,v)=>e.handleGuardrailToggle(d,v),onThresholdChange:(d,v,S)=>e.handleGuardrailThresholdChange(d,v,S),onCustomToggle:(d,v)=>e.handleCustomGuardrailToggle(d,v),onCustomDelete:d=>e.handleCustomGuardrailDelete(d),onToggleAddForm:()=>e.handleToggleGuardrailAddForm(),onOpenAllyChat:d=>{e.handleAllyToggle(),d&&e.handleAllyDraftChange(d)}}):h}
8419
8446
 
@@ -8425,15 +8452,15 @@ ${i}
8425
8452
 
8426
8453
  ${e.tab==="dashboards"?e.dynamicSlots.dashboards?r`<div class="dynamic-slot">${ke(Gc(e.dynamicSlots.dashboards))}</div>`:b1({connected:e.connected,loading:e.dashboardsLoading??!1,error:e.dashboardsError??null,dashboards:e.dashboardsList,activeDashboardId:e.activeDashboardId??null,activeDashboardHtml:e.activeDashboardHtml??null,activeDashboardManifest:e.activeDashboardManifest??null,isWorking:e.activeDashboardManifest?.sessionId?e.workingSessions.has(e.activeDashboardManifest.sessionId):!1,onSelectDashboard:d=>e.handleDashboardSelect(d),onDeleteDashboard:d=>e.handleDashboardDelete(d),onCreateViaChat:()=>e.handleDashboardCreateViaChat(),onBack:()=>e.handleDashboardBack(),onRefresh:()=>e.handleDashboardsRefresh(),onOpenSession:d=>e.handleDashboardOpenSession(d)}):h}
8427
8454
 
8428
- ${e.tab==="config"?R$({raw:e.configRaw,originalRaw:e.configRawOriginal,valid:e.configValid,issues:e.configIssues,loading:e.configLoading,saving:e.configSaving,applying:e.configApplying,updating:e.updateRunning,connected:e.connected,schema:e.configSchema,schemaLoading:e.configSchemaLoading,uiHints:e.configUiHints,formMode:e.configFormMode,formValue:e.configForm,originalValue:e.configFormOriginal,searchQuery:e.configSearchQuery,activeSection:e.configActiveSection,activeSubsection:e.configActiveSubsection,onRawChange:d=>{e.configRaw=d},onFormModeChange:d=>e.configFormMode=d,onFormPatch:(d,v)=>Zt(e,d,v),onSearchChange:d=>e.configSearchQuery=d,onSectionChange:d=>{e.configActiveSection=d,e.configActiveSubsection=null},onSubsectionChange:d=>e.configActiveSubsection=d,onReload:()=>Ye(e),onSave:()=>Ps(e),onApply:()=>Xp(e),onUpdate:()=>hr(e),userName:e.userName||"",userAvatar:e.userAvatar,onUserProfileUpdate:(d,v)=>e.handleUpdateUserProfile(d,v),onModelSwitch:(d,v)=>Zp(e,d,v)}):h}
8455
+ ${e.tab==="config"?E$({raw:e.configRaw,originalRaw:e.configRawOriginal,valid:e.configValid,issues:e.configIssues,loading:e.configLoading,saving:e.configSaving,applying:e.configApplying,updating:e.updateRunning,connected:e.connected,schema:e.configSchema,schemaLoading:e.configSchemaLoading,uiHints:e.configUiHints,formMode:e.configFormMode,formValue:e.configForm,originalValue:e.configFormOriginal,searchQuery:e.configSearchQuery,activeSection:e.configActiveSection,activeSubsection:e.configActiveSubsection,onRawChange:d=>{e.configRaw=d},onFormModeChange:d=>e.configFormMode=d,onFormPatch:(d,v)=>Zt(e,d,v),onSearchChange:d=>e.configSearchQuery=d,onSectionChange:d=>{e.configActiveSection=d,e.configActiveSubsection=null},onSubsectionChange:d=>e.configActiveSubsection=d,onReload:()=>Ye(e),onSave:()=>Ps(e),onApply:()=>Jp(e),onUpdate:()=>hr(e),userName:e.userName||"",userAvatar:e.userAvatar,onUserProfileUpdate:(d,v)=>e.handleUpdateUserProfile(d,v),onModelSwitch:(d,v)=>Xp(e,d,v)}):h}
8429
8456
 
8430
- ${e.tab==="debug"?j$({loading:e.debugLoading,status:e.debugStatus,health:e.debugHealth,models:e.debugModels,heartbeat:e.debugHeartbeat,eventLog:e.eventLog,callMethod:e.debugCallMethod,callParams:e.debugCallParams,callResult:e.debugCallResult,callError:e.debugCallError,onCallMethodChange:d=>e.debugCallMethod=d,onCallParamsChange:d=>e.debugCallParams=d,onRefresh:()=>sa(e),onCall:()=>Kv(e)}):h}
8457
+ ${e.tab==="debug"?W$({loading:e.debugLoading,status:e.debugStatus,health:e.debugHealth,models:e.debugModels,heartbeat:e.debugHeartbeat,eventLog:e.eventLog,callMethod:e.debugCallMethod,callParams:e.debugCallParams,callResult:e.debugCallResult,callError:e.debugCallError,onCallMethodChange:d=>e.debugCallMethod=d,onCallParamsChange:d=>e.debugCallParams=d,onRefresh:()=>sa(e),onCall:()=>zv(e)}):h}
8431
8458
 
8432
- ${e.tab==="logs"?Z$({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:d=>e.logsFilterText=d,onLevelToggle:(d,v)=>{e.logsLevelFilters={...e.logsLevelFilters,[d]:v}},onToggleAutoFollow:d=>e.logsAutoFollow=d,onRefresh:()=>ho(e,{reset:!0}),onExport:(d,v)=>e.exportLogs(d,v),onScroll:d=>e.handleLogsScroll(d)}):h}
8459
+ ${e.tab==="logs"?J$({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:d=>e.logsFilterText=d,onLevelToggle:(d,v)=>{e.logsLevelFilters={...e.logsLevelFilters,[d]:v}},onToggleAutoFollow:d=>e.logsAutoFollow=d,onRefresh:()=>ho(e,{reset:!0}),onExport:(d,v)=>e.exportLogs(d,v),onScroll:d=>e.handleLogsScroll(d)}):h}
8433
8460
  </main>
8434
- ${e.tab!=="chat"?Xb({allyName:e.assistantName,allyAvatar:e.assistantAvatar??null,open:e.allyPanelOpen??!1,messages:e.allyMessages??[],stream:e.allyStream??null,draft:e.allyDraft??"",sending:e.allySending??!1,isWorking:e.allyWorking??!1,unreadCount:e.allyUnread??0,connected:e.connected,compact:!1,attachments:e.allyAttachments??[],onToggle:()=>e.handleAllyToggle(),onDraftChange:d=>e.handleAllyDraftChange(d),onSend:()=>e.handleAllySend(),onOpenFullChat:()=>e.handleAllyOpenFull(),onAttachmentsChange:d=>e.handleAllyAttachmentsChange(d)}):h}
8435
- ${V$(e)}
8436
- ${G$(e)}
8461
+ ${e.tab!=="chat"?Yb({allyName:e.assistantName,allyAvatar:e.assistantAvatar??null,open:e.allyPanelOpen??!1,messages:e.allyMessages??[],stream:e.allyStream??null,draft:e.allyDraft??"",sending:e.allySending??!1,isWorking:e.allyWorking??!1,unreadCount:e.allyUnread??0,connected:e.connected,compact:!1,attachments:e.allyAttachments??[],onToggle:()=>e.handleAllyToggle(),onDraftChange:d=>e.handleAllyDraftChange(d),onSend:()=>e.handleAllySend(),onOpenFullChat:()=>e.handleAllyOpenFull(),onAttachmentsChange:d=>e.handleAllyAttachmentsChange(d)}):h}
8462
+ ${j$(e)}
8463
+ ${H$(e)}
8437
8464
  ${e.sidebarOpen&&e.tab!=="chat"?r`
8438
8465
  <div class="global-document-viewer">
8439
8466
  <div class="global-document-viewer__overlay" @click=${()=>e.handleCloseSidebar()}></div>
@@ -8442,27 +8469,27 @@ ${i}
8442
8469
  </div>
8443
8470
  </div>
8444
8471
  `:h}
8445
- ${I0({toasts:e.toasts,onDismiss:d=>e.dismissToast(d)})}
8446
- ${R0(e.lightbox,{onClose:()=>e.handleLightboxClose(),onNav:d=>e.handleLightboxNav(d)})}
8472
+ ${R0({toasts:e.toasts,onDismiss:d=>e.dismissToast(d)})}
8473
+ ${E0(e.lightbox,{onClose:()=>e.handleLightboxClose(),onNav:d=>e.handleLightboxNav(d)})}
8447
8474
  </div>
8448
- `}async function W1(e){}async function q1(e){}async function j1(e,t){}async function H1(e){}async function V1(e){}async function G1(e){}async function Oo(e){if(!(!e.client||!e.connected)){e.trustTrackerLoading=!0;try{const[t,n]=await Promise.all([e.client.request("trust.dashboard",{}),e.client.request("trust.history",{limit:50})]);e.trustTrackerData={workflows:t.workflows,summaries:t.summaries,ratings:n.ratings,total:n.total,overallScore:t.overallScore,totalRatings:t.totalRatings,totalUses:t.totalUses,todayRating:t.todayRating??null,dailyAverage:t.dailyAverage??null,dailyStreak:t.dailyStreak??0,recentDaily:t.recentDaily??[]}}catch{e.trustTrackerData=null}finally{e.trustTrackerLoading=!1}}}async function cp(e,t){if(!(!e.client||!e.connected))try{await e.client.request("trust.workflows.set",{workflows:t}),e.showToast("Workflows updated","success",2e3),await Oo(e)}catch(n){e.showToast("Failed to update workflows","error"),console.error("[TrustTracker] setWorkflows error:",n)}}async function Q1(e,t){const n=e.trustTrackerData?.workflows??[];if(n.length>=5){e.showToast("Maximum 5 workflows allowed","error");return}if(n.includes(t.trim())){e.showToast("Workflow already tracked","error");return}await cp(e,[...n,t.trim()])}async function Y1(e,t){const n=e.trustTrackerData?.workflows??[];await cp(e,n.filter(s=>s!==t))}async function J1(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("trust.dailyRate",{rating:t,...n?{note:n}:{}}),e.showToast(`Rated ${t}/10 today`,"success",2e3),await Oo(e)}catch(s){e.showToast("Failed to submit daily rating","error"),console.error("[TrustTracker] dailyRate error:",s)}}const X1=6e4,pc=15,hc=new Set;let Es=null;async function fc(e){if(!(!e.client||!e.connected))try{const t=new Date,n=new Date(t.getTime()+pc*6e4+6e4),s=await e.client.request("calendar.events.range",{startDate:t.toISOString(),endDate:n.toISOString()});for(const a of s.events??[]){if(hc.has(a.id))continue;const i=new Date(a.startTime),o=Math.round((i.getTime()-t.getTime())/6e4);if(o>0&&o<=pc){hc.add(a.id);const l=i.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),c=a.location?` @ ${a.location}`:"",u=`${a.title} starts in ${o} min (${l})${c}`;e.showToast(u,"warning",0)}}}catch(t){console.warn("[MeetingNotify] Poll error:",t)}}function Z1(e){dp(),fc(e),Es=setInterval(()=>{fc(e)},X1)}function dp(){Es&&(clearInterval(Es),Es=null)}let e2=0;function t2(e,t="info",n=3e3,s){return{id:`toast-${Date.now()}-${e2++}`,message:e,type:t,duration:n,createdAt:Date.now(),action:s}}function n2(e,t){return e.filter(n=>n.id!==t)}function s2(e,t){return[...e,t]}var a2=Object.defineProperty,i2=Object.getOwnPropertyDescriptor,b=(e,t,n,s)=>{for(var a=s>1?void 0:s?i2(t,n):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=(s?o(t,n,a):o(a))||a);return s&&a&&a2(t,n,a),a};function si(){return gm()}function ws(){return vm()}function o2(){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 r2(e,t){let n=e.trim();if(!n)return null;if(n.startsWith("Read HEARTBEAT.md")||n.startsWith("Read CONSCIOUSNESS.md")||/^System:\s*\[\d{4}-\d{2}-\d{2}/.test(n)||n==="NO_REPLY"||n.startsWith(`NO_REPLY
8475
+ `}async function W1(e){}async function q1(e){}async function j1(e,t){}async function H1(e){}async function V1(e){}async function G1(e){}async function Oo(e){if(!(!e.client||!e.connected)){e.trustTrackerLoading=!0;try{const[t,n]=await Promise.all([e.client.request("trust.dashboard",{}),e.client.request("trust.history",{limit:50})]);e.trustTrackerData={workflows:t.workflows,summaries:t.summaries,ratings:n.ratings,total:n.total,overallScore:t.overallScore,totalRatings:t.totalRatings,totalUses:t.totalUses,todayRating:t.todayRating??null,dailyAverage:t.dailyAverage??null,dailyStreak:t.dailyStreak??0,recentDaily:t.recentDaily??[]}}catch{e.trustTrackerData=null}finally{e.trustTrackerLoading=!1}}}async function lp(e,t){if(!(!e.client||!e.connected))try{await e.client.request("trust.workflows.set",{workflows:t}),e.showToast("Workflows updated","success",2e3),await Oo(e)}catch(n){e.showToast("Failed to update workflows","error"),console.error("[TrustTracker] setWorkflows error:",n)}}async function Q1(e,t){const n=e.trustTrackerData?.workflows??[];if(n.length>=5){e.showToast("Maximum 5 workflows allowed","error");return}if(n.includes(t.trim())){e.showToast("Workflow already tracked","error");return}await lp(e,[...n,t.trim()])}async function Y1(e,t){const n=e.trustTrackerData?.workflows??[];await lp(e,n.filter(s=>s!==t))}async function J1(e,t,n){if(!(!e.client||!e.connected))try{await e.client.request("trust.dailyRate",{rating:t,...n?{note:n}:{}}),e.showToast(`Rated ${t}/10 today`,"success",2e3),await Oo(e)}catch(s){e.showToast("Failed to submit daily rating","error"),console.error("[TrustTracker] dailyRate error:",s)}}const X1=6e4,pc=15,hc=new Set;let Es=null;async function fc(e){if(!(!e.client||!e.connected))try{const t=new Date,n=new Date(t.getTime()+pc*6e4+6e4),s=await e.client.request("calendar.events.range",{startDate:t.toISOString(),endDate:n.toISOString()});for(const a of s.events??[]){if(hc.has(a.id))continue;const i=new Date(a.startTime),o=Math.round((i.getTime()-t.getTime())/6e4);if(o>0&&o<=pc){hc.add(a.id);const l=i.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),c=a.location?` @ ${a.location}`:"",u=`${a.title} starts in ${o} min (${l})${c}`;e.showToast(u,"warning",0)}}}catch(t){console.warn("[MeetingNotify] Poll error:",t)}}function Z1(e){cp(),fc(e),Es=setInterval(()=>{fc(e)},X1)}function cp(){Es&&(clearInterval(Es),Es=null)}let e2=0;function t2(e,t="info",n=3e3,s){return{id:`toast-${Date.now()}-${e2++}`,message:e,type:t,duration:n,createdAt:Date.now(),action:s}}function n2(e,t){return e.filter(n=>n.id!==t)}function s2(e,t){return[...e,t]}var a2=Object.defineProperty,i2=Object.getOwnPropertyDescriptor,b=(e,t,n,s)=>{for(var a=s>1?void 0:s?i2(t,n):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=(s?o(t,n,a):o(a))||a);return s&&a&&a2(t,n,a),a};function si(){return fm()}function ws(){return mm()}function o2(){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 r2(e,t){let n=e.trim();if(!n)return null;if(n.startsWith("Read HEARTBEAT.md")||n.startsWith("Read CONSCIOUSNESS.md")||/^System:\s*\[\d{4}-\d{2}-\d{2}/.test(n)||n==="NO_REPLY"||n.startsWith(`NO_REPLY
8449
8476
  `)||/^#\s*(?:🧠|Atlas Consciousness)/i.test(n)||n.startsWith("# WORKING.md")||n.startsWith("# MISTAKES.md"))return console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null;if(/(?:VERIFIED|FIXED|NEW):\s/.test(n)&&/✅|🟡|☑/.test(n)&&n.length>300)return console.debug("[Ally] Filtered message (verification dump):",t,n.substring(0,100)),null;if(/^###\s*(?:Onboarding Philosophy|Self-Surgery Problem|Open Architecture)/i.test(n))return console.debug("[Ally] Filtered message (system block):",t,n.substring(0,100)),null;if(/^\[GodMode Context:[^\]]*\]\s*$/.test(n))return console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null;if(n=n.replace(/^(?:HEARTBEAT_OK|CONSCIOUSNESS_OK)\s*/i,"").trim(),n=n.replace(/^Deep work window is yours\.\s*/i,"").trim(),!n)return null;if(/^\w+\s+\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(n)&&n.length>200||/^##\s*Your Team\s*\(Agent Roster\)/i.test(n)&&n.indexOf(`
8450
8477
 
8451
- ## `)===-1)return console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null;if(/^##?\s*Persistence Protocol/i.test(n)||/^You are resourceful and thorough\.\s*Your job is to GET THE JOB DONE/i.test(n)||/^##?\s*Core (?:Behaviors|Principles)/i.test(n)||/^##?\s*Your Role as Prosper/i.test(n))return console.debug("[Ally] Filtered message (persona leak):",t,n.substring(0,100)),null;const s=n.toLowerCase();return["persistence protocol","core principles:","core behaviors","your role as prosper","be diligent first time","exhaust reasonable options","assume capability exists","elite executive assistant","consciousness context","working context","enforcement:","internal system context injected by godmode"].filter(i=>s.includes(i)).length>=2?(console.debug("[Ally] Filtered message (multi-signal system leak):",t,n.substring(0,100)),null):/^(?:ID\s+START\s+END\s+SUMMARY)/i.test(n)?(console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null):n}const gc=new Set(["chat","today","workspaces","work","data","overview","channels","instances","sessions","cron","skills","nodes","config","debug","logs","my-day"]),l2=["path","filePath","file","workspacePath"];let y=class extends nn{constructor(){super(...arguments),this.settings=ib(),this.password="",this.tab="chat",this.onboarding=o2(),this.connected=!1,this.reconnecting=!1,this.reconnectAttempt=0,this.theme=this.settings.theme??"system",this.themeResolved="dark",this.hello=null,this.lastError=null,this.eventLog=[],this.toolStreamSyncTimer=null,this.sidebarCloseTimer=null,this.sessionPickerClickOutsideHandler=null,this.sessionSearchClickOutsideHandler=null,this.assistantName=si().name,this.assistantAvatar=si().avatar,this.assistantAgentId=si().agentId??null,this.userName=ws().name,this.userAvatar=ws().avatar,this.sessionKey=this.settings.sessionKey,this.sessionPickerOpen=!1,this.sessionPickerPosition=null,this.sessionPickerSearch="",this.sessionSearchOpen=!1,this.sessionSearchPosition=null,this.sessionSearchQuery="",this.sessionSearchResults=[],this.sessionSearchLoading=!1,this.profilePopoverOpen=!1,this.profileEditName="",this.profileEditAvatar="",this.editingTabKey=null,this.chatLoading=!1,this.chatSending=!1,this.chatSendingSessionKey=null,this.chatMessage="",this.chatDrafts={},this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.currentToolName=null,this.currentToolInfo=null,this.workingSessions=new Set,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatThinkingLevel=null,this.chatQueue=[],this.chatAttachments=[],this.pendingRetry=null,this.autoRetryAfterCompact=!1,this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.sidebarMimeType=null,this.sidebarFilePath=null,this.sidebarTitle=null,this.splitRatio=this.settings.splitRatio,this.lightbox=ep(),this.driveAccounts=[],this.showDrivePicker=!1,this.driveUploading=!1,this.updateStatus=null,this.updateLoading=!1,this.updateError=null,this.updateLastChecked=null,this.updatePollInterval=null,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.pendingGatewayUrl=null,this.configLoading=!1,this.configRaw=`{
8478
+ ## `)===-1)return console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null;if(/^##?\s*Persistence Protocol/i.test(n)||/^You are resourceful and thorough\.\s*Your job is to GET THE JOB DONE/i.test(n)||/^##?\s*Core (?:Behaviors|Principles)/i.test(n)||/^##?\s*Your Role as Prosper/i.test(n))return console.debug("[Ally] Filtered message (persona leak):",t,n.substring(0,100)),null;const s=n.toLowerCase();return["persistence protocol","core principles:","core behaviors","your role as prosper","be diligent first time","exhaust reasonable options","assume capability exists","elite executive assistant","consciousness context","working context","enforcement:","internal system context injected by godmode"].filter(i=>s.includes(i)).length>=2?(console.debug("[Ally] Filtered message (multi-signal system leak):",t,n.substring(0,100)),null):/^(?:ID\s+START\s+END\s+SUMMARY)/i.test(n)?(console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null):n}const gc=new Set(["chat","today","workspaces","work","data","overview","channels","instances","sessions","cron","skills","nodes","config","debug","logs","my-day"]),l2=["path","filePath","file","workspacePath"];let y=class extends nn{constructor(){super(...arguments),this.settings=sb(),this.password="",this.tab="chat",this.onboarding=o2(),this.connected=!1,this.reconnecting=!1,this.reconnectAttempt=0,this.theme=this.settings.theme??"system",this.themeResolved="dark",this.hello=null,this.lastError=null,this.eventLog=[],this.toolStreamSyncTimer=null,this.sidebarCloseTimer=null,this.sessionPickerClickOutsideHandler=null,this.sessionSearchClickOutsideHandler=null,this.assistantName=si().name,this.assistantAvatar=si().avatar,this.assistantAgentId=si().agentId??null,this.userName=ws().name,this.userAvatar=ws().avatar,this.sessionKey=this.settings.sessionKey,this.sessionPickerOpen=!1,this.sessionPickerPosition=null,this.sessionPickerSearch="",this.sessionSearchOpen=!1,this.sessionSearchPosition=null,this.sessionSearchQuery="",this.sessionSearchResults=[],this.sessionSearchLoading=!1,this.profilePopoverOpen=!1,this.profileEditName="",this.profileEditAvatar="",this.editingTabKey=null,this.chatLoading=!1,this.chatSending=!1,this.chatSendingSessionKey=null,this.chatMessage="",this.chatDrafts={},this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.currentToolName=null,this.currentToolInfo=null,this.workingSessions=new Set,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatThinkingLevel=null,this.chatQueue=[],this.chatAttachments=[],this.pendingRetry=null,this.autoRetryAfterCompact=!1,this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.sidebarMimeType=null,this.sidebarFilePath=null,this.sidebarTitle=null,this.splitRatio=this.settings.splitRatio,this.lightbox=Zu(),this.driveAccounts=[],this.showDrivePicker=!1,this.driveUploading=!1,this.updateStatus=null,this.updateLoading=!1,this.updateError=null,this.updateLastChecked=null,this.updatePollInterval=null,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.pendingGatewayUrl=null,this.configLoading=!1,this.configRaw=`{
8452
8479
  }
8453
- `,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.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.sessionsFilterActive="",this.sessionsFilterLimit="120",this.sessionsIncludeGlobal=!0,this.sessionsIncludeUnknown=!1,this.archivedSessions=[],this.archivedSessionsLoading=!1,this.archivedSessionsExpanded=!1,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...$b},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.workspaceNeedsSetup=!1,this.onboardingPhase=0,this.onboardingData=null,this.onboardingActive=!1,this.wizardActive=!1,this.wizardState=null,this.showSetupTab=!1,this.setupChecklist=null,this.setupChecklistLoading=!1,this.setupQuickDone=!1,this.onboardingIntegrations=null,this.onboardingCoreProgress=null,this.onboardingExpandedCard=null,this.onboardingLoadingGuide=null,this.onboardingActiveGuide=null,this.onboardingTestingId=null,this.onboardingTestResult=null,this.onboardingConfigValues={},this.onboardingProgress=null,this.selectedWorkspace=null,this.workspacesSearchQuery="",this.workspaceItemSearchQuery="",this.workspacesLoading=!1,this.workspacesCreateLoading=!1,this.workspacesError=null,this.workspaceExpandedFolders=new Set,this.editingTaskId=null,this.workspaceBrowsePath=null,this.workspaceBrowseEntries=null,this.workspaceBreadcrumbs=null,this.workspaceBrowseSearchQuery="",this.workspaceBrowseSearchResults=null,this.myDayLoading=!1,this.myDayError=null,this.todaySelectedDate=re(),this.todayViewMode="brief",this.dailyBriefLoading=!1,this.dailyBriefError=null,this.agentLogLoading=!1,this.agentLogError=null,this.briefNotes={},this.todayTasks=[],this.todayTasksLoading=!1,this.todayEditingTaskId=null,this.todayShowCompleted=!1,this.allyPanelOpen=!1,this.allyMessages=[],this.allyStream=null,this.allyDraft="",this.allyUnread=0,this.allySending=!1,this.allyWorking=!1,this.allyAttachments=[],this.todayQueueResults=[],this.chatPrivateMode=!1,this.privateSessions=new Map,this._privateSessionTimer=null,this.goalsLoading=!1,this.goalsError=null,this.dataLoading=!1,this.dataError=null,this.dataSubtab="dashboard",this.dynamicSlots={},this.workLoading=!1,this.workError=null,this.workExpandedProjects=new Set,this.workProjectFiles={},this.workDetailLoading=new Set,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},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={...wb},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.toasts=[],this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.chatUserNearBottom=!0,this.chatIsAutoScrolling=!1,this.chatNewMessagesBelow=!1,this.consciousnessStatus="idle",this.focusPulseData=null,this.trustTrackerData=null,this.trustTrackerLoading=!1,this.guardrailsData=null,this.guardrailsLoading=!1,this.guardrailsShowAddForm=!1,this.missionControlData=null,this.missionControlLoading=!1,this.missionControlError=null,this.missionControlFullControl=(()=>{try{return localStorage.getItem("godmode.mc.fullControl")==="1"}catch{return!0}})(),this.missionControlPollInterval=null,this.godmodeOptions=null,this.godmodeOptionsLoading=!1,this.dashboardsLoading=!1,this.dashboardsError=null,this.activeDashboardId=null,this.activeDashboardHtml=null,this.activeDashboardManifest=null,this.dashboardPreviousSessionKey=null,this.dashboardChatOpen=!1,this.secondBrainSubtab="identity",this.secondBrainLoading=!1,this.secondBrainError=null,this.secondBrainIdentity=null,this.secondBrainMemoryBank=null,this.secondBrainAiPacket=null,this.secondBrainSourcesData=null,this.secondBrainResearchData=null,this.secondBrainResearchAddFormOpen=!1,this.secondBrainResearchAddForm={title:"",url:"",category:"",tags:"",notes:""},this.secondBrainResearchCategories=[],this.secondBrainSelectedEntry=null,this.secondBrainSearchQuery="",this.secondBrainSyncing=!1,this.secondBrainBrowsingFolder=null,this.secondBrainFolderEntries=null,this.secondBrainFolderName=null,this.secondBrainFileTree=null,this.secondBrainFileTreeLoading=!1,this.secondBrainFileSearchQuery="",this.secondBrainFileSearchResults=null,this.nodesPollInterval=null,this.logsPollInterval=null,this.debugPollInterval=null,this.agentLogPollInterval=null,this.agentLogUnsub=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.refreshSessionsAfterChat=!1,this.basePath="",this.popStateHandler=()=>wu(this),this.keydownHandler=()=>{},this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null}createRenderRoot(){return this}connectedCallback(){if(super.connectedCallback(),this.settings.userName)this.userName=this.settings.userName;else{const t=ws();this.userName=t.name}if(this.settings.userAvatar)this.userAvatar=this.settings.userAvatar;else{const t=ws();this.userAvatar=t.avatar}Db(this);const e=re();this.todaySelectedDate!==e&&(this.todaySelectedDate=e),this.agentLogPollInterval==null&&(this.agentLogPollInterval=window.setInterval(()=>{!this.connected||!(this.tab==="today"||this.tab==="my-day")||this.todayViewMode!=="agent-log"||St(this)},6e4)),!this.agentLogUnsub&&this.client&&(this.agentLogUnsub=ru(this.client,()=>{this.todayViewMode==="agent-log"&&St(this)})),Z1(this),this._restorePrivateSessions()}firstUpdated(){Ob(this)}disconnectedCallback(){dp(),this._stopPrivateSessionTimer(),this.agentLogPollInterval!=null&&(clearInterval(this.agentLogPollInterval),this.agentLogPollInterval=null),this.agentLogUnsub&&(this.agentLogUnsub(),this.agentLogUnsub=null),Nb(this),super.disconnectedCallback()}updated(e){Bb(this,e)}connect(){po(this)}handleChatScroll(e){mh(this,e)}handleLogsScroll(e){vh(this,e)}exportLogs(e,t){yh(e,t)}resetToolStream(){Bi(this)}resetChatScroll(){Lc(this)}async loadAssistantIdentity(){await hd(this)}applySettings(e){Je(this,e)}setTab(e){_o(this,e)}setTheme(e,t){fu(this,e,t)}async loadOverview(){await Co(this)}async loadCron(){await ca(this)}async handleAbortChat(){await Eo(this)}async handleConsciousnessFlush(){if(!(!this.client||this.consciousnessStatus==="loading")){this.consciousnessStatus="loading";try{await this.client.request("godmode.consciousness.flush",{}),this.consciousnessStatus="ok"}catch{this.consciousnessStatus="error"}setTimeout(()=>{this.consciousnessStatus!=="loading"&&(this.consciousnessStatus="idle")},3e3)}}async loadFocusPulse(){await W1()}async handleFocusPulseStartMorning(){await q1(),this.setTab("chat");const e="Let's do my morning set. Check my daily note for today's Win The Day items, then help me review priorities and pick my #1 focus to lock in.",{createNewSession:t}=await E(async()=>{const{createNewSession:n}=await Promise.resolve().then(()=>at);return{createNewSession:n}},void 0,import.meta.url);t(this),this.handleSendChat(e)}async handleFocusPulseSetFocus(e){await j1()}async handleFocusPulseComplete(){await H1()}async handleFocusPulsePulseCheck(){await V1()}async handleFocusPulseEndDay(){await G1()}async handleTrustLoad(){await Oo(this)}async handleTrustAddWorkflow(e){await Q1(this,e)}async handleTrustRemoveWorkflow(e){await Y1(this,e)}async handleDailyRate(e,t){await J1(this,e,t)}async handleGuardrailsLoad(){const{loadGuardrails:e}=await E(async()=>{const{loadGuardrails:t}=await Promise.resolve().then(()=>Yt);return{loadGuardrails:t}},void 0,import.meta.url);await e(this)}async handleGuardrailToggle(e,t){const{toggleGuardrail:n}=await E(async()=>{const{toggleGuardrail:s}=await Promise.resolve().then(()=>Yt);return{toggleGuardrail:s}},void 0,import.meta.url);await n(this,e,t)}async handleGuardrailThresholdChange(e,t,n){const{updateGuardrailThreshold:s}=await E(async()=>{const{updateGuardrailThreshold:a}=await Promise.resolve().then(()=>Yt);return{updateGuardrailThreshold:a}},void 0,import.meta.url);await s(this,e,t,n)}async handleCustomGuardrailToggle(e,t){const{toggleCustomGuardrail:n}=await E(async()=>{const{toggleCustomGuardrail:s}=await Promise.resolve().then(()=>Yt);return{toggleCustomGuardrail:s}},void 0,import.meta.url);await n(this,e,t)}async handleCustomGuardrailDelete(e){const{deleteCustomGuardrail:t}=await E(async()=>{const{deleteCustomGuardrail:n}=await Promise.resolve().then(()=>Yt);return{deleteCustomGuardrail:n}},void 0,import.meta.url);await t(this,e)}async handleCustomGuardrailAdd(e){const{addCustomGuardrailFromUI:t}=await E(async()=>{const{addCustomGuardrailFromUI:n}=await Promise.resolve().then(()=>Yt);return{addCustomGuardrailFromUI:n}},void 0,import.meta.url);await t(this,e),this.guardrailsShowAddForm=!1}handleToggleGuardrailAddForm(){this.guardrailsShowAddForm=!this.guardrailsShowAddForm}handleMissionControlToggleFullControl(){this.missionControlFullControl=!this.missionControlFullControl;try{localStorage.setItem("godmode.mc.fullControl",this.missionControlFullControl?"1":"0")}catch{}}async handleMissionControlRefresh(){const{loadMissionControl:e}=await E(async()=>{const{loadMissionControl:t}=await Promise.resolve().then(()=>Qt);return{loadMissionControl:t}},void 0,import.meta.url);await e(this)}async handleMissionControlCancelTask(e){const{cancelCodingTask:t}=await E(async()=>{const{cancelCodingTask:n}=await Promise.resolve().then(()=>Qt);return{cancelCodingTask:n}},void 0,import.meta.url);await t(this,e)}async handleMissionControlApproveItem(e){const{approveCodingTask:t,approveQueueItem:n}=await E(async()=>{const{approveCodingTask:a,approveQueueItem:i}=await Promise.resolve().then(()=>Qt);return{approveCodingTask:a,approveQueueItem:i}},void 0,import.meta.url);await t(this,e)||await n(this,e)}async handleMissionControlRetryItem(e){const{retryQueueItem:t}=await E(async()=>{const{retryQueueItem:n}=await Promise.resolve().then(()=>Qt);return{retryQueueItem:n}},void 0,import.meta.url);await t(this,e)}async handleMissionControlViewDetail(e){const{loadAgentDetail:t}=await E(async()=>{const{loadAgentDetail:s}=await Promise.resolve().then(()=>Qt);return{loadAgentDetail:s}},void 0,import.meta.url),n=await t(this,e);this.handleOpenSidebar(n.content,{mimeType:n.mimeType,title:n.title})}async handleMissionControlOpenSession(e){const t=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:t,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity();const{loadChatHistory:n}=await E(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:s}},void 0,import.meta.url);await n(this)}async handleMissionControlOpenTaskSession(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("tasks.openSession",{taskId:e});if(t?.sessionId){if(t.task?.title){const{autoTitleCache:n}=await E(async()=>{const{autoTitleCache:s}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:s}},void 0,import.meta.url);n.set(t.sessionId,t.task.title)}await this.handleMissionControlOpenSession(t.sessionId),t.queueOutput&&this.chatMessages.length===0&&await this.seedSessionWithAgentOutput(t.task?.title??"task",t.queueOutput,t.agentPrompt??void 0)}}catch(t){console.error("[MissionControl] Failed to open task session:",t),this.showToast("Failed to open session","error")}}async handleMissionControlStartQueueItem(e){await this.handleMissionControlOpenTaskSession(e)}async handleMissionControlViewTaskFiles(e){try{const n=(await this.client?.request("queue.taskFiles",{itemId:e}))?.files??[];if(n.length===0){this.showToast("No files found for this task","info");return}const a=`## Task Files
8480
+ `,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.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.sessionsFilterActive="",this.sessionsFilterLimit="120",this.sessionsIncludeGlobal=!0,this.sessionsIncludeUnknown=!1,this.archivedSessions=[],this.archivedSessionsLoading=!1,this.archivedSessionsExpanded=!1,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...bb},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.workspaceNeedsSetup=!1,this.onboardingPhase=0,this.onboardingData=null,this.onboardingActive=!1,this.wizardActive=!1,this.wizardState=null,this.showSetupTab=!1,this.setupChecklist=null,this.setupChecklistLoading=!1,this.setupQuickDone=!1,this.onboardingIntegrations=null,this.onboardingCoreProgress=null,this.onboardingExpandedCard=null,this.onboardingLoadingGuide=null,this.onboardingActiveGuide=null,this.onboardingTestingId=null,this.onboardingTestResult=null,this.onboardingConfigValues={},this.onboardingProgress=null,this.selectedWorkspace=null,this.workspacesSearchQuery="",this.workspaceItemSearchQuery="",this.workspacesLoading=!1,this.workspacesCreateLoading=!1,this.workspacesError=null,this.workspaceExpandedFolders=new Set,this.editingTaskId=null,this.workspaceBrowsePath=null,this.workspaceBrowseEntries=null,this.workspaceBreadcrumbs=null,this.workspaceBrowseSearchQuery="",this.workspaceBrowseSearchResults=null,this.myDayLoading=!1,this.myDayError=null,this.todaySelectedDate=re(),this.todayViewMode="brief",this.dailyBriefLoading=!1,this.dailyBriefError=null,this.agentLogLoading=!1,this.agentLogError=null,this.briefNotes={},this.todayTasks=[],this.todayTasksLoading=!1,this.todayEditingTaskId=null,this.todayShowCompleted=!1,this.allyPanelOpen=!1,this.allyMessages=[],this.allyStream=null,this.allyDraft="",this.allyUnread=0,this.allySending=!1,this.allyWorking=!1,this.allyAttachments=[],this.todayQueueResults=[],this.chatPrivateMode=!1,this.privateSessions=new Map,this._privateSessionTimer=null,this.goalsLoading=!1,this.goalsError=null,this.dataLoading=!1,this.dataError=null,this.dataSubtab="dashboard",this.dynamicSlots={},this.workLoading=!1,this.workError=null,this.workExpandedProjects=new Set,this.workProjectFiles={},this.workDetailLoading=new Set,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},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={...yb},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.toasts=[],this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.chatUserNearBottom=!0,this.chatIsAutoScrolling=!1,this.chatNewMessagesBelow=!1,this.consciousnessStatus="idle",this.focusPulseData=null,this.trustTrackerData=null,this.trustTrackerLoading=!1,this.guardrailsData=null,this.guardrailsLoading=!1,this.guardrailsShowAddForm=!1,this.missionControlData=null,this.missionControlLoading=!1,this.missionControlError=null,this.missionControlFullControl=(()=>{try{return localStorage.getItem("godmode.mc.fullControl")==="1"}catch{return!0}})(),this.missionControlPollInterval=null,this.godmodeOptions=null,this.godmodeOptionsLoading=!1,this.dashboardsLoading=!1,this.dashboardsError=null,this.activeDashboardId=null,this.activeDashboardHtml=null,this.activeDashboardManifest=null,this.dashboardPreviousSessionKey=null,this.dashboardChatOpen=!1,this.secondBrainSubtab="identity",this.secondBrainLoading=!1,this.secondBrainError=null,this.secondBrainIdentity=null,this.secondBrainMemoryBank=null,this.secondBrainAiPacket=null,this.secondBrainSourcesData=null,this.secondBrainResearchData=null,this.secondBrainResearchAddFormOpen=!1,this.secondBrainResearchAddForm={title:"",url:"",category:"",tags:"",notes:""},this.secondBrainResearchCategories=[],this.secondBrainSelectedEntry=null,this.secondBrainSearchQuery="",this.secondBrainSyncing=!1,this.secondBrainBrowsingFolder=null,this.secondBrainFolderEntries=null,this.secondBrainFolderName=null,this.secondBrainFileTree=null,this.secondBrainFileTreeLoading=!1,this.secondBrainFileSearchQuery="",this.secondBrainFileSearchResults=null,this.nodesPollInterval=null,this.logsPollInterval=null,this.debugPollInterval=null,this.agentLogPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.refreshSessionsAfterChat=!1,this.basePath="",this.popStateHandler=()=>bu(this),this.keydownHandler=()=>{},this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null}createRenderRoot(){return this}connectedCallback(){if(super.connectedCallback(),this.settings.userName)this.userName=this.settings.userName;else{const t=ws();this.userName=t.name}if(this.settings.userAvatar)this.userAvatar=this.settings.userAvatar;else{const t=ws();this.userAvatar=t.avatar}Ib(this);const e=re();this.todaySelectedDate!==e&&(this.todaySelectedDate=e),this.agentLogPollInterval==null&&(this.agentLogPollInterval=window.setInterval(()=>{!this.connected||!(this.tab==="today"||this.tab==="my-day")||this.todayViewMode!=="agent-log"||Jt(this)},6e4)),Z1(this),this._restorePrivateSessions()}firstUpdated(){Mb(this)}disconnectedCallback(){cp(),this._stopPrivateSessionTimer(),this.agentLogPollInterval!=null&&(clearInterval(this.agentLogPollInterval),this.agentLogPollInterval=null),Db(this),super.disconnectedCallback()}updated(e){Nb(this,e)}connect(){po(this)}handleChatScroll(e){gh(this,e)}handleLogsScroll(e){mh(this,e)}exportLogs(e,t){vh(e,t)}resetToolStream(){Bi(this)}resetChatScroll(){Lc(this)}async loadAssistantIdentity(){await hd(this)}applySettings(e){Je(this,e)}setTab(e){_o(this,e)}setTheme(e,t){hu(this,e,t)}async loadOverview(){await Co(this)}async loadCron(){await ca(this)}async handleAbortChat(){await Eo(this)}async handleConsciousnessFlush(){if(!(!this.client||this.consciousnessStatus==="loading")){this.consciousnessStatus="loading";try{await this.client.request("godmode.consciousness.flush",{}),this.consciousnessStatus="ok"}catch{this.consciousnessStatus="error"}setTimeout(()=>{this.consciousnessStatus!=="loading"&&(this.consciousnessStatus="idle")},3e3)}}async loadFocusPulse(){await W1()}async handleFocusPulseStartMorning(){await q1(),this.setTab("chat");const e="Let's do my morning set. Check my daily note for today's Win The Day items, then help me review priorities and pick my #1 focus to lock in.",{createNewSession:t}=await E(async()=>{const{createNewSession:n}=await Promise.resolve().then(()=>at);return{createNewSession:n}},void 0,import.meta.url);t(this),this.handleSendChat(e)}async handleFocusPulseSetFocus(e){await j1()}async handleFocusPulseComplete(){await H1()}async handleFocusPulsePulseCheck(){await V1()}async handleFocusPulseEndDay(){await G1()}async handleTrustLoad(){await Oo(this)}async handleTrustAddWorkflow(e){await Q1(this,e)}async handleTrustRemoveWorkflow(e){await Y1(this,e)}async handleDailyRate(e,t){await J1(this,e,t)}async handleGuardrailsLoad(){const{loadGuardrails:e}=await E(async()=>{const{loadGuardrails:t}=await Promise.resolve().then(()=>Qt);return{loadGuardrails:t}},void 0,import.meta.url);await e(this)}async handleGuardrailToggle(e,t){const{toggleGuardrail:n}=await E(async()=>{const{toggleGuardrail:s}=await Promise.resolve().then(()=>Qt);return{toggleGuardrail:s}},void 0,import.meta.url);await n(this,e,t)}async handleGuardrailThresholdChange(e,t,n){const{updateGuardrailThreshold:s}=await E(async()=>{const{updateGuardrailThreshold:a}=await Promise.resolve().then(()=>Qt);return{updateGuardrailThreshold:a}},void 0,import.meta.url);await s(this,e,t,n)}async handleCustomGuardrailToggle(e,t){const{toggleCustomGuardrail:n}=await E(async()=>{const{toggleCustomGuardrail:s}=await Promise.resolve().then(()=>Qt);return{toggleCustomGuardrail:s}},void 0,import.meta.url);await n(this,e,t)}async handleCustomGuardrailDelete(e){const{deleteCustomGuardrail:t}=await E(async()=>{const{deleteCustomGuardrail:n}=await Promise.resolve().then(()=>Qt);return{deleteCustomGuardrail:n}},void 0,import.meta.url);await t(this,e)}async handleCustomGuardrailAdd(e){const{addCustomGuardrailFromUI:t}=await E(async()=>{const{addCustomGuardrailFromUI:n}=await Promise.resolve().then(()=>Qt);return{addCustomGuardrailFromUI:n}},void 0,import.meta.url);await t(this,e),this.guardrailsShowAddForm=!1}handleToggleGuardrailAddForm(){this.guardrailsShowAddForm=!this.guardrailsShowAddForm}handleMissionControlToggleFullControl(){this.missionControlFullControl=!this.missionControlFullControl;try{localStorage.setItem("godmode.mc.fullControl",this.missionControlFullControl?"1":"0")}catch{}}async handleMissionControlRefresh(){const{loadMissionControl:e}=await E(async()=>{const{loadMissionControl:t}=await Promise.resolve().then(()=>Gt);return{loadMissionControl:t}},void 0,import.meta.url);await e(this)}async handleMissionControlCancelTask(e){const{cancelCodingTask:t}=await E(async()=>{const{cancelCodingTask:n}=await Promise.resolve().then(()=>Gt);return{cancelCodingTask:n}},void 0,import.meta.url);await t(this,e)}async handleMissionControlApproveItem(e){const{approveCodingTask:t,approveQueueItem:n}=await E(async()=>{const{approveCodingTask:a,approveQueueItem:i}=await Promise.resolve().then(()=>Gt);return{approveCodingTask:a,approveQueueItem:i}},void 0,import.meta.url);await t(this,e)||await n(this,e)}async handleMissionControlRetryItem(e){const{retryQueueItem:t}=await E(async()=>{const{retryQueueItem:n}=await Promise.resolve().then(()=>Gt);return{retryQueueItem:n}},void 0,import.meta.url);await t(this,e)}async handleMissionControlViewDetail(e){const{loadAgentDetail:t}=await E(async()=>{const{loadAgentDetail:s}=await Promise.resolve().then(()=>Gt);return{loadAgentDetail:s}},void 0,import.meta.url),n=await t(this,e);this.handleOpenSidebar(n.content,{mimeType:n.mimeType,title:n.title})}async handleMissionControlOpenSession(e){const t=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:t,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity();const{loadChatHistory:n}=await E(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:s}},void 0,import.meta.url);await n(this)}async handleMissionControlOpenTaskSession(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("tasks.openSession",{taskId:e});if(t?.sessionId){if(t.task?.title){const{autoTitleCache:n}=await E(async()=>{const{autoTitleCache:s}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:s}},void 0,import.meta.url);n.set(t.sessionId,t.task.title)}await this.handleMissionControlOpenSession(t.sessionId),t.queueOutput&&this.chatMessages.length===0&&await this.seedSessionWithAgentOutput(t.task?.title??"task",t.queueOutput,t.agentPrompt??void 0)}}catch(t){console.error("[MissionControl] Failed to open task session:",t),this.showToast("Failed to open session","error")}}async handleMissionControlStartQueueItem(e){await this.handleMissionControlOpenTaskSession(e)}async handleMissionControlViewTaskFiles(e){try{const n=(await this.client?.request("queue.taskFiles",{itemId:e}))?.files??[];if(n.length===0){this.showToast("No files found for this task","info");return}const a=`## Task Files
8454
8481
 
8455
8482
  ${n.map(i=>`- **${i.name}** (${i.type}, ${(i.size/1024).toFixed(1)} KB)
8456
8483
  \`${i.path}\``).join(`
8457
8484
 
8458
- `)}`;this.handleOpenSidebar(a,{title:"Task Files"})}catch(t){console.error("Failed to load task files:",t),this.showToast("Failed to load task files","error")}}handleAllyToggle(){this.allyPanelOpen=!this.allyPanelOpen,this.allyPanelOpen&&(this.allyUnread=0,this._loadAllyHistory().then(()=>this._scrollAllyToBottom()))}handleAllyDraftChange(e){this.allyDraft=e}handleAllyAttachmentsChange(e){this.allyAttachments=e}async handleAllySend(){const e=this.allyDraft.trim(),t=this.allyAttachments;if(!e&&t.length===0||this.allySending)return;const n=pm(this);let s=e?`${n}
8485
+ `)}`;this.handleOpenSidebar(a,{title:"Task Files"})}catch(t){console.error("Failed to load task files:",t),this.showToast("Failed to load task files","error")}}handleAllyToggle(){this.allyPanelOpen=!this.allyPanelOpen,this.allyPanelOpen&&(this.allyUnread=0,this._loadAllyHistory().then(()=>this._scrollAllyToBottom()))}handleAllyDraftChange(e){this.allyDraft=e}handleAllyAttachmentsChange(e){this.allyAttachments=e}async handleAllySend(){const e=this.allyDraft.trim(),t=this.allyAttachments;if(!e&&t.length===0||this.allySending)return;const n=um(this);let s=e?`${n}
8459
8486
 
8460
- ${e}`:n;this.allyDraft="",this.allyAttachments=[],this.allySending=!0,this.allyMessages=[...this.allyMessages,{role:"user",content:e||"(image)",timestamp:Date.now()}];try{let a;if(t.length>0){const o=[];for(const l of t){if(!l.dataUrl)continue;const c=l.dataUrl.match(/^data:([^;]+);base64,(.+)$/);if(!c)continue;const[,u,p]=c;u.startsWith("image/")&&o.push({type:"image",mimeType:u,content:p,fileName:l.fileName})}if(o.length>0){a=o;try{await this.client?.request("images.cache",{images:o.map(l=>({data:l.content,mimeType:l.mimeType,fileName:l.fileName})),sessionKey:ee})}catch{}}}const i=`ally-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.client?.request("chat.send",{sessionKey:ee,message:s,deliver:!1,idempotencyKey:i,attachments:a}),this.allyWorking=!0,setTimeout(()=>{this.allyWorking&&!this.allyStream&&(this.allyMessages=[...this.allyMessages,{role:"assistant",content:"*Session is busy — your message is queued and will be answered shortly.*",timestamp:Date.now()}],this.allyWorking=!1)},45e3)}catch(a){const i=a instanceof Error?a.message:String(a);console.error("[Ally] Failed to send ally message:",i),this.allyMessages=[...this.allyMessages,{role:"assistant",content:`*Send failed: ${i}*`,timestamp:Date.now()}]}finally{this.allySending=!1}}handleAllyOpenFull(){this.allyPanelOpen=!1,this.setTab("chat"),this.applySettings({...this.settings,sessionKey:ee,lastActiveSessionKey:ee,tabLastViewed:{...this.settings.tabLastViewed,[ee]:Date.now()}}),this.sessionKey=ee,this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity(),E(async()=>{const{loadChatHistory:e}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:e}},void 0,import.meta.url).then(({loadChatHistory:e})=>e(this))}_scrollAllyToBottom(){this.updateComplete.then(()=>{requestAnimationFrame(()=>{const e=this.renderRoot?.querySelector?.(".ally-panel, .ally-inline")??document.querySelector(".ally-panel, .ally-inline");if(!e)return;const t=e.querySelector(".ally-panel__messages");t&&(t.scrollTop=t.scrollHeight)})})}async _loadAllyHistory(){try{const e=await this.client?.request("chat.history",{sessionKey:ee,limit:100});if(e?.messages){const{extractText:t,formatApiError:n}=await E(async()=>{const{extractText:s,formatApiError:a}=await Promise.resolve().then(()=>kg);return{extractText:s,formatApiError:a}},void 0,import.meta.url);this.allyMessages=e.messages.map(s=>{let a=t(s);if(!a)return null;const i=n(a);if(i&&(a=i),a=a.replace(/^\[GodMode Context:[^\]]*\]\s*/i,"").trim(),!a)return null;const o=s.role??"assistant",l=r2(a,o);return l?{role:o,content:l,timestamp:s.timestamp}:null}).filter(s=>s!==null)}}catch{}}async handleDecisionApprove(e){if(!(!this.client||!this.connected))try{await this.client.request("queue.approve",{id:e}),this.todayQueueResults=this.todayQueueResults.filter(t=>t.id!==e)}catch(t){console.error("[DecisionCard] Approve failed:",t),this.showToast("Failed to approve","error")}}async handleDecisionReject(e){if(!(!this.client||!this.connected))try{await this.client.request("queue.reject",{id:e}),this.todayQueueResults=this.todayQueueResults.filter(t=>t.id!==e)}catch(t){console.error("[DecisionCard] Reject failed:",t),this.showToast("Failed to reject","error")}}async handleDecisionViewOutput(e,t){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const n=await this.client.request("queue.readOutput",{path:t}),s=t.split("/").pop()??"Agent Output";this.handleOpenSidebar(n.content,{mimeType:"text/markdown",filePath:t,title:s})}catch(n){console.error("[DecisionCard] View output failed:",n),this.handleOpenFile(t)}}async handleDecisionOpenChat(e){const t=this.todayQueueResults?.find(a=>a.id===e);if(!t)return;if(t.sourceTaskId){await this.handleMissionControlOpenTaskSession(t.sourceTaskId);return}const{createNewSession:n}=await E(async()=>{const{createNewSession:a}=await Promise.resolve().then(()=>at);return{createNewSession:a}},void 0,import.meta.url);n(this),this.setTab("chat");const{autoTitleCache:s}=await E(async()=>{const{autoTitleCache:a}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:a}},void 0,import.meta.url);if(s.set(this.sessionKey,t.title),t.outputPath&&this.client&&this.connected)try{const a=await this.client.request("queue.readOutput",{path:t.outputPath});a?.content&&await this.seedSessionWithAgentOutput(t.title,a.content)}catch{await this.seedSessionWithAgentOutput(t.title,t.summary)}else t.summary&&await this.seedSessionWithAgentOutput(t.title,t.summary)}async handleTodayOpenChatToEdit(e){try{const t=this.todayQueueResults?.find(s=>s.id===e),n=t?.outputPath;if(n&&this.client&&this.connected)try{const s=await this.client.request("queue.readOutput",{path:n});this.handleOpenSidebar(s.content,{mimeType:"text/markdown",filePath:n,title:t?.title??n.split("/").pop()??"Agent Output"})}catch{await this.handleOpenFile(n)}this.allyPanelOpen=!0,this.allyUnread=0,this.tab!=="chat"&&this.setTab("chat")}catch(t){console.error("Open chat to edit failed:",t)}}async seedSessionWithAgentOutput(e,t,n){if(!this.client||!this.connected)return;this.handleOpenSidebar(t,{title:`Agent Output: ${e}`,filePath:null,mimeType:null});const s=t.match(/## Summary\n([\s\S]*?)(?=\n## |$)/),a=s?s[1].trim().split(`
8487
+ ${e}`:n;this.allyDraft="",this.allyAttachments=[],this.allySending=!0,this.allyMessages=[...this.allyMessages,{role:"user",content:e||"(image)",timestamp:Date.now()}];try{let a;if(t.length>0){const o=[];for(const l of t){if(!l.dataUrl)continue;const c=l.dataUrl.match(/^data:([^;]+);base64,(.+)$/);if(!c)continue;const[,u,p]=c;u.startsWith("image/")&&o.push({type:"image",mimeType:u,content:p,fileName:l.fileName})}if(o.length>0){a=o;try{await this.client?.request("images.cache",{images:o.map(l=>({data:l.content,mimeType:l.mimeType,fileName:l.fileName})),sessionKey:ee})}catch{}}}const i=`ally-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.client?.request("chat.send",{sessionKey:ee,message:s,deliver:!1,idempotencyKey:i,attachments:a}),this.allyWorking=!0,setTimeout(()=>{this.allyWorking&&!this.allyStream&&(this.allyMessages=[...this.allyMessages,{role:"assistant",content:"*Session is busy — your message is queued and will be answered shortly.*",timestamp:Date.now()}],this.allyWorking=!1)},45e3)}catch(a){const i=a instanceof Error?a.message:String(a);console.error("[Ally] Failed to send ally message:",i),this.allyMessages=[...this.allyMessages,{role:"assistant",content:`*Send failed: ${i}*`,timestamp:Date.now()}]}finally{this.allySending=!1}}handleAllyOpenFull(){this.allyPanelOpen=!1,this.setTab("chat"),this.applySettings({...this.settings,sessionKey:ee,lastActiveSessionKey:ee,tabLastViewed:{...this.settings.tabLastViewed,[ee]:Date.now()}}),this.sessionKey=ee,this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity(),E(async()=>{const{loadChatHistory:e}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:e}},void 0,import.meta.url).then(({loadChatHistory:e})=>e(this))}_scrollAllyToBottom(){this.updateComplete.then(()=>{requestAnimationFrame(()=>{const e=this.renderRoot?.querySelector?.(".ally-panel, .ally-inline")??document.querySelector(".ally-panel, .ally-inline");if(!e)return;const t=e.querySelector(".ally-panel__messages");t&&(t.scrollTop=t.scrollHeight)})})}async _loadAllyHistory(){try{const e=await this.client?.request("chat.history",{sessionKey:ee,limit:100});if(e?.messages){const{extractText:t,formatApiError:n}=await E(async()=>{const{extractText:s,formatApiError:a}=await Promise.resolve().then(()=>$g);return{extractText:s,formatApiError:a}},void 0,import.meta.url);this.allyMessages=e.messages.map(s=>{let a=t(s);if(!a)return null;const i=n(a);if(i&&(a=i),a=a.replace(/^\[GodMode Context:[^\]]*\]\s*/i,"").trim(),!a)return null;const o=s.role??"assistant",l=r2(a,o);return l?{role:o,content:l,timestamp:s.timestamp}:null}).filter(s=>s!==null)}}catch{}}async handleDecisionApprove(e){if(!(!this.client||!this.connected))try{await this.client.request("queue.approve",{id:e}),this.todayQueueResults=this.todayQueueResults.filter(t=>t.id!==e)}catch(t){console.error("[DecisionCard] Approve failed:",t),this.showToast("Failed to approve","error")}}async handleDecisionReject(e){if(!(!this.client||!this.connected))try{await this.client.request("queue.reject",{id:e}),this.todayQueueResults=this.todayQueueResults.filter(t=>t.id!==e)}catch(t){console.error("[DecisionCard] Reject failed:",t),this.showToast("Failed to reject","error")}}async handleDecisionViewOutput(e,t){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const n=await this.client.request("queue.readOutput",{path:t}),s=t.split("/").pop()??"Agent Output";this.handleOpenSidebar(n.content,{mimeType:"text/markdown",filePath:t,title:s})}catch(n){console.error("[DecisionCard] View output failed:",n),this.handleOpenFile(t)}}async handleDecisionOpenChat(e){const t=this.todayQueueResults?.find(a=>a.id===e);if(!t)return;if(t.sourceTaskId){await this.handleMissionControlOpenTaskSession(t.sourceTaskId);return}const{createNewSession:n}=await E(async()=>{const{createNewSession:a}=await Promise.resolve().then(()=>at);return{createNewSession:a}},void 0,import.meta.url);n(this),this.setTab("chat");const{autoTitleCache:s}=await E(async()=>{const{autoTitleCache:a}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:a}},void 0,import.meta.url);if(s.set(this.sessionKey,t.title),t.outputPath&&this.client&&this.connected)try{const a=await this.client.request("queue.readOutput",{path:t.outputPath});a?.content&&await this.seedSessionWithAgentOutput(t.title,a.content)}catch{await this.seedSessionWithAgentOutput(t.title,t.summary)}else t.summary&&await this.seedSessionWithAgentOutput(t.title,t.summary)}async handleTodayOpenChatToEdit(e){try{const t=this.todayQueueResults?.find(s=>s.id===e),n=t?.outputPath;if(n&&this.client&&this.connected)try{const s=await this.client.request("queue.readOutput",{path:n});this.handleOpenSidebar(s.content,{mimeType:"text/markdown",filePath:n,title:t?.title??n.split("/").pop()??"Agent Output"})}catch{await this.handleOpenFile(n)}this.allyPanelOpen=!0,this.allyUnread=0,this.tab!=="chat"&&this.setTab("chat")}catch(t){console.error("Open chat to edit failed:",t)}}async seedSessionWithAgentOutput(e,t,n){if(!this.client||!this.connected)return;this.handleOpenSidebar(t,{title:`Agent Output: ${e}`,filePath:null,mimeType:null});const s=t.match(/## Summary\n([\s\S]*?)(?=\n## |$)/),a=s?s[1].trim().split(`
8461
8488
  `).slice(0,3).join(`
8462
8489
  `):"Output available in sidebar.",i=[`Agent completed **${e}**.`,"",a,"","Full output is in the sidebar. What would you like to do?"].join(`
8463
- `);try{const{sendChatMessage:o}=await E(async()=>{const{sendChatMessage:l}=await Promise.resolve().then(()=>Ge);return{sendChatMessage:l}},void 0,import.meta.url);await o(this,i)}catch(o){console.error("[Session] Failed to seed session with agent output:",o)}}async handleMissionControlAddToQueue(e,t){if(!(!this.client||!this.connected))try{await this.client.request("queue.add",{type:e,title:t,priority:"normal"}),this.showToast("Added to queue","success",2e3);const{loadMissionControl:n}=await E(async()=>{const{loadMissionControl:s}=await Promise.resolve().then(()=>Qt);return{loadMissionControl:s}},void 0,import.meta.url);await n(this)}catch{this.showToast("Failed to add to queue","error")}}async handleDashboardsRefresh(){const{loadDashboards:e}=await E(async()=>{const{loadDashboards:t}=await import("./dashboards-BWn_hwxU.js");return{loadDashboards:t}},[],import.meta.url);await e(this)}async handleDashboardSelect(e){const{loadDashboard:t}=await E(async()=>{const{loadDashboard:n}=await import("./dashboards-BWn_hwxU.js");return{loadDashboard:n}},[],import.meta.url);if(await t(this,e),this.client&&this.connected)try{const n=await this.client.request("dashboards.openSession",{dashboardId:e});if(n?.sessionId){this.dashboardPreviousSessionKey=this.sessionKey;const s=n.sessionId,{autoTitleCache:a}=await E(async()=>{const{autoTitleCache:l}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:l}},void 0,import.meta.url);a.set(s,n.manifest.title),this.activeDashboardManifest&&(this.activeDashboardManifest={...this.activeDashboardManifest,sessionId:s});const{saveDraft:i}=await E(async()=>{const{saveDraft:l}=await Promise.resolve().then(()=>ja);return{saveDraft:l}},void 0,import.meta.url);i(this),this.sessionKey=s,this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream();const{loadChatHistory:o}=await E(async()=>{const{loadChatHistory:l}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:l}},void 0,import.meta.url);await o(this),this.dashboardChatOpen=!0}}catch(n){console.error("[Dashboards] Failed to init session on select:",n)}}async handleDashboardDelete(e){const{deleteDashboard:t}=await E(async()=>{const{deleteDashboard:n}=await import("./dashboards-BWn_hwxU.js");return{deleteDashboard:n}},[],import.meta.url);await t(this,e)}async handleDashboardCreateViaChat(){this.setTab("chat");const{createNewSession:e}=await E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url);e(this),this.handleSendChat("I want to create a custom dashboard. Ask me what data I want to see and design it for me. You can use any of GodMode's data — tasks, calendar, focus pulse, goals, trust scores, agent activity, queue status, coding tasks, workspace stats, and more.")}handleDashboardBack(){if(this.activeDashboardId=null,this.activeDashboardHtml=null,this.activeDashboardManifest=null,this.dashboardChatOpen=!1,this.dashboardPreviousSessionKey){const e=this.dashboardPreviousSessionKey;this.dashboardPreviousSessionKey=null,E(async()=>{const{saveDraft:t}=await Promise.resolve().then(()=>ja);return{saveDraft:t}},void 0,import.meta.url).then(({saveDraft:t})=>{t(this),this.sessionKey=e,E(async()=>{const{loadChatHistory:n}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:n}},void 0,import.meta.url).then(({loadChatHistory:n})=>{n(this)})})}}async handleDashboardOpenSession(e){const t=this.activeDashboardManifest?.sessionId;if(!t){this.showToast("No session for this dashboard","error");return}this.dashboardPreviousSessionKey=null,this.activeDashboardId=null,this.activeDashboardHtml=null,this.activeDashboardManifest=null,this.dashboardChatOpen=!1;const n=this.settings.openTabs.includes(t)?this.settings.openTabs:[...this.settings.openTabs,t];this.applySettings({...this.settings,openTabs:n,sessionKey:t,lastActiveSessionKey:t,tabLastViewed:{...this.settings.tabLastViewed,[t]:Date.now()}}),this.setTab("chat");const{syncUrlWithSessionKey:s}=await E(async()=>{const{syncUrlWithSessionKey:a}=await Promise.resolve().then(()=>gb);return{syncUrlWithSessionKey:a}},void 0,import.meta.url);s(this,t,!0)}async handleOptionsLoad(){const{loadOptions:e}=await E(async()=>{const{loadOptions:t}=await import("./options-QuHclvvX.js");return{loadOptions:t}},[],import.meta.url);await e(this)}async handleOptionToggle(e,t){const{saveOption:n}=await E(async()=>{const{saveOption:s}=await import("./options-QuHclvvX.js");return{saveOption:s}},[],import.meta.url);await n(this,e,t)}async handleSecondBrainRefresh(){const{loadSecondBrain:e}=await E(async()=>{const{loadSecondBrain:t}=await import("./second-brain-nWUdvmOD.js");return{loadSecondBrain:t}},[],import.meta.url);await e(this)}handleSecondBrainSubtabChange(e){this.secondBrainSubtab=e,this.secondBrainLoading=!1,this.secondBrainSelectedEntry=null,this.secondBrainSearchQuery="",this.secondBrainError=null,this.secondBrainBrowsingFolder=null,this.secondBrainFolderEntries=null,this.secondBrainFolderName=null,e==="intel"?this.handleIntelLoad().catch(t=>{console.error("[Intel] Load after subtab change failed:",t),this.intelError=t instanceof Error?t.message:"Failed to load intel data"}):e==="files"?this.handleSecondBrainFileTreeRefresh().catch(t=>{console.error("[SecondBrain] File tree load after subtab change failed:",t)}):this.handleSecondBrainRefresh().catch(t=>{console.error("[SecondBrain] Refresh after subtab change failed:",t),this.secondBrainError=t instanceof Error?t.message:"Failed to load data",this.secondBrainLoading=!1})}async handleSecondBrainSelectEntry(e){if(e.endsWith(".html")||e.endsWith(".htm")){try{const s=await this.client.request("secondBrain.memoryBankEntry",{path:e});s?.content&&this.handleOpenSidebar(s.content,{mimeType:"text/html",filePath:e,title:s.name||e.split("/").pop()||"File"})}catch(s){console.error("[SecondBrain] Failed to open HTML file:",s)}return}const{loadSecondBrainEntry:n}=await E(async()=>{const{loadSecondBrainEntry:s}=await import("./second-brain-nWUdvmOD.js");return{loadSecondBrainEntry:s}},[],import.meta.url);await n(this,e)}async handleSecondBrainOpenInBrowser(e){try{const t=await this.client.request("secondBrain.memoryBankEntry",{path:e});if(t?.content){const n=new Blob([t.content],{type:"text/html"}),s=URL.createObjectURL(n);window.open(s,"_blank","noopener,noreferrer")}}catch(t){console.error("[SecondBrain] Failed to open in browser:",t)}}async handleSecondBrainBrowseFolder(e){const{browseFolder:t}=await E(async()=>{const{browseFolder:n}=await import("./second-brain-nWUdvmOD.js");return{browseFolder:n}},[],import.meta.url);await t(this,e)}handleSecondBrainBack(){this.secondBrainSelectedEntry?this.secondBrainSelectedEntry=null:this.secondBrainBrowsingFolder&&(this.secondBrainBrowsingFolder=null,this.secondBrainFolderEntries=null,this.secondBrainFolderName=null)}handleSecondBrainSearch(e){this.secondBrainSearchQuery=e}async handleSecondBrainSync(){const{syncSecondBrain:e}=await E(async()=>{const{syncSecondBrain:t}=await import("./second-brain-nWUdvmOD.js");return{syncSecondBrain:t}},[],import.meta.url);await e(this)}async handleSecondBrainFileTreeRefresh(){if(!(!this.client||!this.connected)){this.secondBrainFileTreeLoading=!0;try{const e=await this.client.request("secondBrain.fileTree",{depth:4});this.secondBrainFileTree=e.tree??[]}catch(e){console.error("[SecondBrain] fileTree failed:",e)}finally{this.secondBrainFileTreeLoading=!1}}}handleSecondBrainFileSearch(e){if(this.secondBrainFileSearchQuery=e,!e.trim()){this.secondBrainFileSearchResults=null;return}this._doSecondBrainFileSearch(e)}async _doSecondBrainFileSearch(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("secondBrain.search",{query:e,limit:50});this.secondBrainFileSearchQuery===e&&(this.secondBrainFileSearchResults=t.results??[])}catch(t){console.error("[SecondBrain] search failed:",t)}}async handleSecondBrainFileSelect(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("secondBrain.memoryBankEntry",{path:e});if(t?.content){const n=e.endsWith(".html")||e.endsWith(".htm");this.handleOpenSidebar(t.content,{mimeType:n?"text/html":"text/markdown",filePath:e,title:t.name||e.split("/").pop()||"File"})}}catch(t){console.error("[SecondBrain] Failed to open file:",t),this.showToast("Failed to open file","error")}}handleResearchAddFormToggle(){this.secondBrainResearchAddFormOpen=!this.secondBrainResearchAddFormOpen,this.secondBrainResearchAddFormOpen&&(this.secondBrainResearchAddForm={title:"",url:"",category:"",tags:"",notes:""})}handleResearchAddFormChange(e,t){this.secondBrainResearchAddForm={...this.secondBrainResearchAddForm,[e]:t}}async handleResearchAddSubmit(){const{addResearch:e}=await E(async()=>{const{addResearch:t}=await import("./second-brain-nWUdvmOD.js");return{addResearch:t}},[],import.meta.url);await e(this)}async handleResearchSaveViaChat(){this.setTab("chat");const{createNewSession:e}=await E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url);e(this),this.handleSendChat("I want to save some research. I'll paste links, bookmarks, or notes — please organize them into ~/godmode/memory/research/ with proper frontmatter (title, url, category, tags, date). Ask me what I'd like to save.")}async handleAddSource(){this.setTab("chat");const{createNewSession:e}=await E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url);e(this),this.handleSendChat("I want to add a new data source to my Second Brain. Help me figure out what I need — whether it's an API integration, a local file sync, or a new skill. Ask me what source I'd like to connect.")}async handleCommunityResourceAdd(){const{addCommunityResource:e}=await E(async()=>{const{addCommunityResource:t}=await import("./second-brain-nWUdvmOD.js");return{addCommunityResource:t}},[],import.meta.url);await e(this)}async handleCommunityResourceRemove(e){const{removeCommunityResource:t}=await E(async()=>{const{removeCommunityResource:n}=await import("./second-brain-nWUdvmOD.js");return{removeCommunityResource:n}},[],import.meta.url);await t(this,e)}handleCommunityResourceAddFormToggle(){this.secondBrainCommunityResourceAddFormOpen=!this.secondBrainCommunityResourceAddFormOpen,this.secondBrainCommunityResourceAddFormOpen&&(this.secondBrainCommunityResourceAddForm={url:"",label:"",description:"",tags:""})}handleCommunityResourceAddFormChange(e,t){this.secondBrainCommunityResourceAddForm={...this.secondBrainCommunityResourceAddForm,[e]:t}}removeQueuedMessage(e){Au(this,e)}async handleSendChat(e,t){const n=this.sessionsResult?.sessions?.find(s=>s.key===this.sessionKey);if(n){const s=n.totalTokens??0,a=n.contextTokens??this.sessionsResult?.defaults?.contextTokens??2e5;if((a>0?s/a:0)>=.9&&!this.compactionStatus?.active){const o=(e??this.chatMessage).trim(),l=e==null?[...this.chatAttachments??[]]:[];if(o||l.length>0){this.pendingRetry={message:o,attachments:l,timestamp:Date.now()},this.autoRetryAfterCompact=!0,this.chatMessages=[...this.chatMessages,{role:"user",content:[{type:"text",text:o}],timestamp:Date.now()}],e==null&&(this.chatMessage="",this.chatAttachments=[]),this.showToast("Context near limit — auto-compacting...","info",3e3),this.handleCompactChat();return}}}await _u(this,e,t)}handleToggleSessionPicker(){this.sessionPickerOpen=!this.sessionPickerOpen}handleToggleSessionSearch(e){if(!this.sessionSearchOpen&&e){const n=e.currentTarget.getBoundingClientRect();this.sessionSearchPosition={top:n.bottom+8,right:window.innerWidth-n.right}}this.sessionSearchOpen=!this.sessionSearchOpen,this.sessionSearchOpen||(this.sessionSearchQuery="",this.sessionSearchResults=[])}async handleSessionSearchQuery(e){if(this.sessionSearchQuery=e,!e.trim()){this.sessionSearchResults=[];return}if(this.client){this.sessionSearchLoading=!0;try{const t=await this.client.request("sessions.searchContent",{query:e.trim(),limit:20});this.sessionSearchResults=t.results}catch(t){console.error("Session search failed:",t),this.sessionSearchResults=[]}finally{this.sessionSearchLoading=!1}}}handleSelectSession(e){this.sessionPickerOpen=!1,this.sessionSearchOpen=!1,this.sessionSearchQuery="",this.sessionSearchResults=[]}async handleWhatsAppStart(e){await sh(this,e)}async handleWhatsAppWait(){await ah(this)}async handleWhatsAppLogout(){await ih(this)}async handleChannelConfigSave(){await oh(this)}async handleChannelConfigReload(){await rh(this)}async handleCompactChat(){if(!this.connected){this.showToast("Cannot compact: not connected","error");return}if(!this.sessionKey){this.showToast("Cannot compact: no active session","error");return}this.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null};try{await this.handleSendChat("/compact")}catch(e){this.compactionStatus=null,console.error("Compaction failed:",e),this.showToast("Compaction failed","error")}}injectCompactionSummary(e,t){const n={role:"system",content:e,timestamp:Date.now(),isCompactionSummary:!0,keptMessages:t};this.chatMessages=[n,...this.chatMessages]}async handleRetryMessage(){const e={client:this.client,connected:this.connected,sessionKey:this.sessionKey,chatLoading:this.chatLoading,chatMessages:this.chatMessages,chatThinkingLevel:this.chatThinkingLevel,chatSending:this.chatSending,chatSendingSessionKey:this.chatSendingSessionKey,chatMessage:this.chatMessage,chatAttachments:this.chatAttachments,chatRunId:this.chatRunId,chatStream:this.chatStream,chatStreamStartedAt:this.chatStreamStartedAt,lastError:this.lastError,pendingRetry:this.pendingRetry},t=await md(e);this.chatSending=e.chatSending,this.chatSendingSessionKey=e.chatSendingSessionKey,this.chatRunId=e.chatRunId,this.chatStream=e.chatStream,this.chatStreamStartedAt=e.chatStreamStartedAt,this.lastError=e.lastError,this.pendingRetry=e.pendingRetry??null,this.chatMessages=e.chatMessages,t&&this.showToast("Message resent","success",2e3)}handleClearRetry(){this.pendingRetry=null}handleNostrProfileEdit(e,t){ch(this,e,t)}handleNostrProfileCancel(){dh(this)}handleNostrProfileFieldChange(e,t){uh(this,e,t)}async handleNostrProfileSave(){await hh(this)}async handleNostrProfileImport(){await fh(this)}handleNostrProfileToggleAdvanced(){ph(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}}}handleGatewayUrlConfirm(){const e=this.pendingGatewayUrl;e&&(this.pendingGatewayUrl=null,Je(this,{...this.settings,gatewayUrl:e}),this.connect())}handleGatewayUrlCancel(){this.pendingGatewayUrl=null}handleOpenSidebar(e,t={}){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarMimeType=t.mimeType?.trim()||null,this.sidebarFilePath=t.filePath?.trim()||null,this.sidebarTitle=t.title?.trim()||null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.showDrivePicker=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarMimeType=null,this.sidebarFilePath=null,this.sidebarTitle=null,this.sidebarCloseTimer=null)},200)}async handleOpenFile(e){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const t=await this.client.request("files.read",{path:e}),n=e.split(".").pop()?.toLowerCase()??"",s=t.contentType??t.mime??(n==="md"?"text/markdown":null),a=e.split("/").pop()??e;this.handleOpenSidebar(t.content,{mimeType:s,filePath:e,title:a}),t.truncated&&this.showToast(`Opened truncated file: ${e}`,"warning")}catch(t){console.error("[Chat] Failed to open file:",t),this.showToast(`Failed to open file: ${e}`,"error")}}async handleToggleDrivePicker(){if(this.showDrivePicker){this.showDrivePicker=!1;return}if(this.driveAccounts.length===0)try{const e=await this.client?.request("files.listDriveAccounts",{});this.driveAccounts=e?.accounts??[]}catch{this.driveAccounts=[]}this.showDrivePicker=!0}async handlePushToDrive(e,t){if(!this.driveUploading){if(this.showDrivePicker=!1,this._pendingBatchPaths&&this._pendingBatchPaths.length>0){const n=this._pendingBatchPaths;this._pendingBatchPaths=void 0,await this._executeBatchDrive(n,t);return}this.driveUploading=!0;try{const n={filePath:e};t&&(n.account=t);const s=await this.client?.request("files.pushToDrive",n),a=t?` to ${t.split("@")[0]}`:"",i=s?.message??`Uploaded${a} to Google Drive`,o=s?.driveUrl;this.showToast(i,"success",o?8e3:5e3,o?{label:"View in Drive",url:o}:void 0)}catch(n){console.error("Push to Drive failed:",n);const s=n instanceof Error?n.message:typeof n=="object"&&n!==null&&"message"in n?String(n.message):"Unknown error";s.includes("GOG_NOT_FOUND")||s.includes("gog CLI not found")?this.showToast("Google Drive not configured. Install gog CLI: npm install -g gog-cli, then run: gog auth add <email> --services drive","warning",1e4):s.includes("GOG_AUTH")||s.includes("auth")&&s.includes("expired")?this.showToast("Google Drive auth expired. Re-authenticate: gog auth add <email> --services drive","warning",8e3):this.showToast(`Drive upload failed: ${s}`,"error",8e3)}finally{this.driveUploading=!1}}}async handleBatchPushToDrive(e){if(this.driveUploading||e.length===0)return;if(!this.driveAccounts||this.driveAccounts.length===0)try{const n=await this.client?.request("files.listDriveAccounts");this.driveAccounts=n?.accounts??[]}catch{}if(this.driveAccounts&&this.driveAccounts.length>1){this._pendingBatchPaths=e,this.showDrivePicker=!0;return}const t=this.driveAccounts?.[0]?.email;await this._executeBatchDrive(e,t)}async _executeBatchDrive(e,t){this.driveUploading=!0,this.showToast(`Uploading ${e.length} files to Drive...`,"info",0);try{const n={filePaths:e};t&&(n.account=t);const s=await this.client?.request("files.batchPushToDrive",n);this.dismissAllToasts();const a=s?.results?.filter(o=>o.success).length??0,i=s?.results?.length??e.length;a===i?this.showToast(`Uploaded ${a} files to Google Drive`,"success",5e3):this.showToast(`Uploaded ${a}/${i} files (${i-a} failed)`,"warning",8e3)}catch(n){this.dismissAllToasts();const s=n instanceof Error?n.message:"Unknown error";this.showToast(`Batch Drive upload failed: ${s}`,"error",8e3)}finally{this.driveUploading=!1,this._pendingBatchPaths=void 0}}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}handleImageClick(e,t,n){this.lightbox=_0(e,t,n)}handleLightboxClose(){this.lightbox=T0()}handleLightboxNav(e){this.lightbox=x0(this.lightbox,e)}normalizeWorkspacePathCandidate(e,t={}){let n=e.trim();if(!n||n.startsWith("#"))return null;for(;n.startsWith("./");)n=n.slice(2);if(n=n.replaceAll("\\","/"),!t.allowAbsolute)for(;n.startsWith("/");)n=n.slice(1);return!n||n.includes("\0")?null:n}isAbsoluteFilesystemPath(e){return e.startsWith("/")||e.startsWith("~/")||/^[a-z]:[\\/]/i.test(e)}inferMimeTypeFromPath(e){if(!e)return null;const t=e.trim().toLowerCase();if(!t)return null;const n=t.split(".").pop()??"";return n?n==="md"||n==="markdown"||n==="mdx"?"text/markdown":n==="html"||n==="htm"?"text/html":n==="json"||n==="json5"?"application/json":n==="txt"||n==="text"||n==="log"?"text/plain":n==="svg"||n==="svgz"?"image/svg+xml":n==="avif"||n==="bmp"||n==="gif"||n==="heic"||n==="heif"||n==="jpeg"||n==="jpg"||n==="png"||n==="webp"?`image/${n==="jpg"?"jpeg":n}`:null:null}sidebarTitleForPath(e){const t=e.replaceAll("\\","/").trim();if(!t)return"Document";const n=t.split("/");return n[n.length-1]||t}async listWorkspaceIdsForPathResolution(){const e=[],t=new Set,n=s=>{if(typeof s!="string")return;const a=s.trim();!a||t.has(a)||(t.add(a),e.push(a))};n(this.selectedWorkspace?.id);for(const s of this.workspaces??[])n(s.id);if(e.length>0||!this.client||!this.connected)return e;try{const s=await this.client.request("workspaces.list",{});for(const a of s.workspaces??[])n(a.id)}catch{}return e}async openWorkspaceRelativeFileInViewer(e){if(!this.client||!this.connected)return!1;const t=await this.listWorkspaceIdsForPathResolution();for(const n of t)try{const s=await this.client.request("workspaces.readFile",{workspaceId:n,filePath:e});if(typeof s.content!="string")continue;return this.handleOpenSidebar(s.content,{mimeType:s.contentType??s.mime??this.inferMimeTypeFromPath(e),filePath:s.path??e,title:this.sidebarTitleForPath(e)}),!0}catch{}return!1}extractWorkspacePathCandidatesFromHref(e){const t=e.trim();if(!t)return[];const n=[],s=t.toLowerCase();if(s.startsWith("mailto:")||s.startsWith("tel:")||s.startsWith("javascript:")||s.startsWith("data:"))return[];if(t.startsWith("file://")){let u=t.slice(7);u.startsWith("/~/")&&(u="~"+u.slice(2));try{u=decodeURIComponent(u)}catch{}n.push(u);const p=[],f=new Set;for(const m of n){const g=this.normalizeWorkspacePathCandidate(m,{allowAbsolute:!0});!g||f.has(g)||(f.add(g),p.push(g))}return p}const a=/^[a-z][a-z0-9+.-]*:/i.test(t),i=/^[a-z]:[\\/]/i.test(t);(!a||i)&&n.push(t);let o=null;try{o=new URL(t,window.location.href)}catch{o=null}if(o&&/^https?:$/.test(o.protocol)&&o.origin===window.location.origin){for(const $ of l2){const d=o.searchParams.get($);d&&n.push(d)}const p=(t.split("#")[0]??"").split("?")[0]??"";p.length>0&&!p.startsWith("/")&&!p.includes("://")&&n.push(p);let m=o.pathname;this.basePath&&m.startsWith(`${this.basePath}/`)?m=m.slice(this.basePath.length):this.basePath&&m===this.basePath&&(m="");const g=m.startsWith("/")?m.slice(1):m;if(g){n.push(g);const $=g.indexOf("/");if($>0){const d=g.slice(0,$).toLowerCase();gc.has(d)&&n.push(g.slice($+1))}}if(m.startsWith("/")&&g){const $=g.split("/")[0]?.toLowerCase()??"";gc.has($)||n.push(m)}}const l=[],c=new Set;for(const u of n){let p=u;try{p=decodeURIComponent(u)}catch{}const f=this.normalizeWorkspacePathCandidate(p,{allowAbsolute:!0});!f||c.has(f)||(c.add(f),l.push(f))}return l}async openWorkspaceFileInViewer(e){if(!this.client||!this.connected)return!1;const t=this.isAbsoluteFilesystemPath(e);if(!t&&await this.openWorkspaceRelativeFileInViewer(e))return!0;try{const n=await this.client.request("workspaces.readFile",{path:e});if(typeof n.content=="string")return this.handleOpenSidebar(n.content,{mimeType:n.contentType??n.mime??this.inferMimeTypeFromPath(e),filePath:n.path??e,title:this.sidebarTitleForPath(e)}),!0}catch{}if(!t)return!1;try{const n=await this.client.request("files.read",{path:e,maxSize:1e6});return typeof n.content!="string"?!1:(this.handleOpenSidebar(n.content,{mimeType:this.inferMimeTypeFromPath(e),filePath:e,title:this.sidebarTitleForPath(e)}),!0)}catch{return!1}}async handleOpenMessageFileLink(e){const t=this.extractWorkspacePathCandidatesFromHref(e);if(t.length===0)return!1;for(const n of t)if(await this.openWorkspaceFileInViewer(n))return!0;return!1}showToast(e,t="info",n=5e3,s){const a=t2(e,t,n,s);this.toasts=s2(this.toasts,a),n>0&&window.setTimeout(()=>{this.dismissToast(a.id)},n)}dismissToast(e){this.toasts=n2(this.toasts,e)}dismissAllToasts(){this.toasts=[]}async handleMyDayRefresh(){if(this.todayViewMode==="agent-log"){await St(this,{refresh:!0});return}await Ks(this),this._loadDecisionCards()}_loadDecisionCards(){E(()=>Promise.resolve().then(()=>In),void 0,import.meta.url).then(async e=>{this.todayQueueResults=await e.loadTodayQueueResults(this)}).catch(()=>{})}async handleMyDayTaskStatusChange(e,t){if(!(!this.client||!this.connected))try{await this.client.request("tasks.update",{id:e,status:t,completedAt:t==="complete"?new Date().toISOString():null});const{loadTodayTasksWithQueueStatus:n}=await E(async()=>{const{loadTodayTasksWithQueueStatus:s}=await Promise.resolve().then(()=>In);return{loadTodayTasksWithQueueStatus:s}},void 0,import.meta.url);await n(this)}catch(n){console.error("[MyDay] Failed to update task status:",n)}}async handleTodayCreateTask(e){if(!(!this.client||!this.connected))try{await this.client.request("tasks.create",{title:e,dueDate:re(),priority:"medium",source:"chat"});const{loadTodayTasksWithQueueStatus:t}=await E(async()=>{const{loadTodayTasksWithQueueStatus:n}=await Promise.resolve().then(()=>In);return{loadTodayTasksWithQueueStatus:n}},void 0,import.meta.url);await t(this)}catch(t){console.error("[MyDay] Failed to create task:",t),this.showToast("Failed to create task","error")}}handleTodayEditTask(e){this.todayEditingTaskId=e}async handleTodayUpdateTask(e,t){if(!(!this.client||!this.connected))try{await this.client.request("tasks.update",{id:e,...t}),this.todayEditingTaskId=null;const{loadTodayTasksWithQueueStatus:n}=await E(async()=>{const{loadTodayTasksWithQueueStatus:s}=await Promise.resolve().then(()=>In);return{loadTodayTasksWithQueueStatus:s}},void 0,import.meta.url);await n(this)}catch(n){console.error("[MyDay] Failed to update task:",n),this.showToast("Failed to update task","error")}}handleTodayToggleCompleted(){this.todayShowCompleted=!this.todayShowCompleted}async handleTodayStartTask(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("tasks.openSession",{taskId:e}),n=t?.sessionId??t?.sessionKey;if(n){if(t.task?.title){const{autoTitleCache:i}=await E(async()=>{const{autoTitleCache:o}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:o}},void 0,import.meta.url);i.set(n,t.task.title)}this.setTab("chat"),this.sessionKey=n;const s=this.settings.openTabs.includes(n)?this.settings.openTabs:[...this.settings.openTabs,n];this.applySettings({...this.settings,sessionKey:n,lastActiveSessionKey:n,openTabs:s}),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity();const{loadChatHistory:a}=await E(async()=>{const{loadChatHistory:i}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:i}},void 0,import.meta.url);await a(this),t.queueOutput&&this.chatMessages.length===0&&this.seedSessionWithAgentOutput(t.task?.title??"this task",t.queueOutput,t.agentPrompt??void 0),this.requestUpdate()}}catch(t){console.error("[MyDay] Failed to open session for task:",t),this.showToast("Failed to open session for task","error")}}handleDatePrev(){const e=new Date(this.todaySelectedDate+"T12:00:00");if(e.setDate(e.getDate()-1),this.todaySelectedDate=re(e),this.todayViewMode==="agent-log"){St(this);return}xs(this)}handleDateNext(){const e=new Date(this.todaySelectedDate+"T12:00:00");e.setDate(e.getDate()+1);const t=re(),n=re(e);if(!(n>t)){if(this.todaySelectedDate=n,this.todayViewMode==="agent-log"){St(this);return}xs(this)}}handleDateToday(){this.todaySelectedDate=re(),Ks(this)}async handleDailyBriefRefresh(){await xs(this)}handleDailyBriefOpenInObsidian(){const e=this.dailyBrief?.date;ou(e)}async loadBriefNotes(){if(!this.client||!this.connected)return;const e=this.todaySelectedDate;try{const t=await this.client.request("briefNotes.get",{date:e});this.briefNotes=t.notes??{}}catch(t){console.error("[BriefNotes] Load error:",t),this.briefNotes={}}}async handleBriefNoteSave(e,t){if(!this.client||!this.connected)return;const n=this.todaySelectedDate;try{const s=await this.client.request("briefNotes.update",{date:n,section:e,text:t});this.briefNotes=s.notes??{}}catch(s){console.error("[BriefNotes] Save error:",s),this.showToast("Failed to save note","error")}}handleTodayViewModeChange(e){this.todayViewMode=e,e==="agent-log"&&!this.agentLog&&St(this)}handlePrivateModeToggle(){if(this.chatPrivateMode){const e=this.sessionKey;this.chatPrivateMode=!1,this._destroyPrivateSession(e),this.showToast("Private session destroyed","info",2e3);return}this.chatPrivateMode=!0,this.setTab("chat"),E(async()=>{const{createNewSession:e}=await Promise.resolve().then(()=>at);return{createNewSession:e}},void 0,import.meta.url).then(({createNewSession:e})=>{e(this);const t=Date.now()+1440*60*1e3;this.privateSessions=new Map(this.privateSessions).set(this.sessionKey,t),this._persistPrivateSessions(),this._startPrivateSessionTimer(),this.chatMessages=[{role:"assistant",content:`This is a **private session**. Nothing will be saved to memory or logs.
8490
+ `);try{const{sendChatMessage:o}=await E(async()=>{const{sendChatMessage:l}=await Promise.resolve().then(()=>Ge);return{sendChatMessage:l}},void 0,import.meta.url);await o(this,i)}catch(o){console.error("[Session] Failed to seed session with agent output:",o)}}async handleMissionControlAddToQueue(e,t){if(!(!this.client||!this.connected))try{await this.client.request("queue.add",{type:e,title:t,priority:"normal"}),this.showToast("Added to queue","success",2e3);const{loadMissionControl:n}=await E(async()=>{const{loadMissionControl:s}=await Promise.resolve().then(()=>Gt);return{loadMissionControl:s}},void 0,import.meta.url);await n(this)}catch{this.showToast("Failed to add to queue","error")}}async handleDashboardsRefresh(){const{loadDashboards:e}=await E(async()=>{const{loadDashboards:t}=await import("./dashboards-BWn_hwxU.js");return{loadDashboards:t}},[],import.meta.url);await e(this)}async handleDashboardSelect(e){const{loadDashboard:t}=await E(async()=>{const{loadDashboard:n}=await import("./dashboards-BWn_hwxU.js");return{loadDashboard:n}},[],import.meta.url);if(await t(this,e),this.client&&this.connected)try{const n=await this.client.request("dashboards.openSession",{dashboardId:e});if(n?.sessionId){this.dashboardPreviousSessionKey=this.sessionKey;const s=n.sessionId,{autoTitleCache:a}=await E(async()=>{const{autoTitleCache:l}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:l}},void 0,import.meta.url);a.set(s,n.manifest.title),this.activeDashboardManifest&&(this.activeDashboardManifest={...this.activeDashboardManifest,sessionId:s});const{saveDraft:i}=await E(async()=>{const{saveDraft:l}=await Promise.resolve().then(()=>ja);return{saveDraft:l}},void 0,import.meta.url);i(this),this.sessionKey=s,this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream();const{loadChatHistory:o}=await E(async()=>{const{loadChatHistory:l}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:l}},void 0,import.meta.url);await o(this),this.dashboardChatOpen=!0}}catch(n){console.error("[Dashboards] Failed to init session on select:",n)}}async handleDashboardDelete(e){const{deleteDashboard:t}=await E(async()=>{const{deleteDashboard:n}=await import("./dashboards-BWn_hwxU.js");return{deleteDashboard:n}},[],import.meta.url);await t(this,e)}async handleDashboardCreateViaChat(){this.setTab("chat");const{createNewSession:e}=await E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url);e(this),this.handleSendChat("I want to create a custom dashboard. Ask me what data I want to see and design it for me. You can use any of GodMode's data — tasks, calendar, focus pulse, goals, trust scores, agent activity, queue status, coding tasks, workspace stats, and more.")}handleDashboardBack(){if(this.activeDashboardId=null,this.activeDashboardHtml=null,this.activeDashboardManifest=null,this.dashboardChatOpen=!1,this.dashboardPreviousSessionKey){const e=this.dashboardPreviousSessionKey;this.dashboardPreviousSessionKey=null,E(async()=>{const{saveDraft:t}=await Promise.resolve().then(()=>ja);return{saveDraft:t}},void 0,import.meta.url).then(({saveDraft:t})=>{t(this),this.sessionKey=e,E(async()=>{const{loadChatHistory:n}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:n}},void 0,import.meta.url).then(({loadChatHistory:n})=>{n(this)})})}}async handleDashboardOpenSession(e){const t=this.activeDashboardManifest?.sessionId;if(!t){this.showToast("No session for this dashboard","error");return}this.dashboardPreviousSessionKey=null,this.activeDashboardId=null,this.activeDashboardHtml=null,this.activeDashboardManifest=null,this.dashboardChatOpen=!1;const n=this.settings.openTabs.includes(t)?this.settings.openTabs:[...this.settings.openTabs,t];this.applySettings({...this.settings,openTabs:n,sessionKey:t,lastActiveSessionKey:t,tabLastViewed:{...this.settings.tabLastViewed,[t]:Date.now()}}),this.setTab("chat");const{syncUrlWithSessionKey:s}=await E(async()=>{const{syncUrlWithSessionKey:a}=await Promise.resolve().then(()=>hb);return{syncUrlWithSessionKey:a}},void 0,import.meta.url);s(this,t,!0)}async handleOptionsLoad(){const{loadOptions:e}=await E(async()=>{const{loadOptions:t}=await import("./options-QuHclvvX.js");return{loadOptions:t}},[],import.meta.url);await e(this)}async handleOptionToggle(e,t){const{saveOption:n}=await E(async()=>{const{saveOption:s}=await import("./options-QuHclvvX.js");return{saveOption:s}},[],import.meta.url);await n(this,e,t)}async handleSecondBrainRefresh(){const{loadSecondBrain:e}=await E(async()=>{const{loadSecondBrain:t}=await import("./second-brain-nWUdvmOD.js");return{loadSecondBrain:t}},[],import.meta.url);await e(this)}handleSecondBrainSubtabChange(e){this.secondBrainSubtab=e,this.secondBrainLoading=!1,this.secondBrainSelectedEntry=null,this.secondBrainSearchQuery="",this.secondBrainError=null,this.secondBrainBrowsingFolder=null,this.secondBrainFolderEntries=null,this.secondBrainFolderName=null,e==="intel"?this.handleIntelLoad().catch(t=>{console.error("[Intel] Load after subtab change failed:",t),this.intelError=t instanceof Error?t.message:"Failed to load intel data"}):e==="files"?this.handleSecondBrainFileTreeRefresh().catch(t=>{console.error("[SecondBrain] File tree load after subtab change failed:",t)}):this.handleSecondBrainRefresh().catch(t=>{console.error("[SecondBrain] Refresh after subtab change failed:",t),this.secondBrainError=t instanceof Error?t.message:"Failed to load data",this.secondBrainLoading=!1})}async handleSecondBrainSelectEntry(e){if(e.endsWith(".html")||e.endsWith(".htm")){try{const s=await this.client.request("secondBrain.memoryBankEntry",{path:e});s?.content&&this.handleOpenSidebar(s.content,{mimeType:"text/html",filePath:e,title:s.name||e.split("/").pop()||"File"})}catch(s){console.error("[SecondBrain] Failed to open HTML file:",s)}return}const{loadSecondBrainEntry:n}=await E(async()=>{const{loadSecondBrainEntry:s}=await import("./second-brain-nWUdvmOD.js");return{loadSecondBrainEntry:s}},[],import.meta.url);await n(this,e)}async handleSecondBrainOpenInBrowser(e){try{const t=await this.client.request("secondBrain.memoryBankEntry",{path:e});if(t?.content){const n=new Blob([t.content],{type:"text/html"}),s=URL.createObjectURL(n);window.open(s,"_blank","noopener,noreferrer")}}catch(t){console.error("[SecondBrain] Failed to open in browser:",t)}}async handleSecondBrainBrowseFolder(e){const{browseFolder:t}=await E(async()=>{const{browseFolder:n}=await import("./second-brain-nWUdvmOD.js");return{browseFolder:n}},[],import.meta.url);await t(this,e)}handleSecondBrainBack(){this.secondBrainSelectedEntry?this.secondBrainSelectedEntry=null:this.secondBrainBrowsingFolder&&(this.secondBrainBrowsingFolder=null,this.secondBrainFolderEntries=null,this.secondBrainFolderName=null)}handleSecondBrainSearch(e){this.secondBrainSearchQuery=e}async handleSecondBrainSync(){const{syncSecondBrain:e}=await E(async()=>{const{syncSecondBrain:t}=await import("./second-brain-nWUdvmOD.js");return{syncSecondBrain:t}},[],import.meta.url);await e(this)}async handleSecondBrainFileTreeRefresh(){if(!(!this.client||!this.connected)){this.secondBrainFileTreeLoading=!0;try{const e=await this.client.request("secondBrain.fileTree",{depth:4});this.secondBrainFileTree=e.tree??[]}catch(e){console.error("[SecondBrain] fileTree failed:",e)}finally{this.secondBrainFileTreeLoading=!1}}}handleSecondBrainFileSearch(e){if(this.secondBrainFileSearchQuery=e,!e.trim()){this.secondBrainFileSearchResults=null;return}this._doSecondBrainFileSearch(e)}async _doSecondBrainFileSearch(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("secondBrain.search",{query:e,limit:50});this.secondBrainFileSearchQuery===e&&(this.secondBrainFileSearchResults=t.results??[])}catch(t){console.error("[SecondBrain] search failed:",t)}}async handleSecondBrainFileSelect(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("secondBrain.memoryBankEntry",{path:e});if(t?.content){const n=e.endsWith(".html")||e.endsWith(".htm");this.handleOpenSidebar(t.content,{mimeType:n?"text/html":"text/markdown",filePath:e,title:t.name||e.split("/").pop()||"File"})}}catch(t){console.error("[SecondBrain] Failed to open file:",t),this.showToast("Failed to open file","error")}}handleResearchAddFormToggle(){this.secondBrainResearchAddFormOpen=!this.secondBrainResearchAddFormOpen,this.secondBrainResearchAddFormOpen&&(this.secondBrainResearchAddForm={title:"",url:"",category:"",tags:"",notes:""})}handleResearchAddFormChange(e,t){this.secondBrainResearchAddForm={...this.secondBrainResearchAddForm,[e]:t}}async handleResearchAddSubmit(){const{addResearch:e}=await E(async()=>{const{addResearch:t}=await import("./second-brain-nWUdvmOD.js");return{addResearch:t}},[],import.meta.url);await e(this)}async handleResearchSaveViaChat(){this.setTab("chat");const{createNewSession:e}=await E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url);e(this),this.handleSendChat("I want to save some research. I'll paste links, bookmarks, or notes — please organize them into ~/godmode/memory/research/ with proper frontmatter (title, url, category, tags, date). Ask me what I'd like to save.")}async handleAddSource(){this.setTab("chat");const{createNewSession:e}=await E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url);e(this),this.handleSendChat("I want to add a new data source to my Second Brain. Help me figure out what I need — whether it's an API integration, a local file sync, or a new skill. Ask me what source I'd like to connect.")}async handleCommunityResourceAdd(){const{addCommunityResource:e}=await E(async()=>{const{addCommunityResource:t}=await import("./second-brain-nWUdvmOD.js");return{addCommunityResource:t}},[],import.meta.url);await e(this)}async handleCommunityResourceRemove(e){const{removeCommunityResource:t}=await E(async()=>{const{removeCommunityResource:n}=await import("./second-brain-nWUdvmOD.js");return{removeCommunityResource:n}},[],import.meta.url);await t(this,e)}handleCommunityResourceAddFormToggle(){this.secondBrainCommunityResourceAddFormOpen=!this.secondBrainCommunityResourceAddFormOpen,this.secondBrainCommunityResourceAddFormOpen&&(this.secondBrainCommunityResourceAddForm={url:"",label:"",description:"",tags:""})}handleCommunityResourceAddFormChange(e,t){this.secondBrainCommunityResourceAddForm={...this.secondBrainCommunityResourceAddForm,[e]:t}}removeQueuedMessage(e){Su(this,e)}async handleSendChat(e,t){const n=this.sessionsResult?.sessions?.find(s=>s.key===this.sessionKey);if(n){const s=n.totalTokens??0,a=n.contextTokens??this.sessionsResult?.defaults?.contextTokens??2e5;if((a>0?s/a:0)>=.9&&!this.compactionStatus?.active){const o=(e??this.chatMessage).trim(),l=e==null?[...this.chatAttachments??[]]:[];if(o||l.length>0){this.pendingRetry={message:o,attachments:l,timestamp:Date.now()},this.autoRetryAfterCompact=!0,this.chatMessages=[...this.chatMessages,{role:"user",content:[{type:"text",text:o}],timestamp:Date.now()}],e==null&&(this.chatMessage="",this.chatAttachments=[]),this.showToast("Context near limit — auto-compacting...","info",3e3),this.handleCompactChat();return}}}await Au(this,e,t)}handleToggleSessionPicker(){this.sessionPickerOpen=!this.sessionPickerOpen}handleToggleSessionSearch(e){if(!this.sessionSearchOpen&&e){const n=e.currentTarget.getBoundingClientRect();this.sessionSearchPosition={top:n.bottom+8,right:window.innerWidth-n.right}}this.sessionSearchOpen=!this.sessionSearchOpen,this.sessionSearchOpen||(this.sessionSearchQuery="",this.sessionSearchResults=[])}async handleSessionSearchQuery(e){if(this.sessionSearchQuery=e,!e.trim()){this.sessionSearchResults=[];return}if(this.client){this.sessionSearchLoading=!0;try{const t=await this.client.request("sessions.searchContent",{query:e.trim(),limit:20});this.sessionSearchResults=t.results}catch(t){console.error("Session search failed:",t),this.sessionSearchResults=[]}finally{this.sessionSearchLoading=!1}}}handleSelectSession(e){this.sessionPickerOpen=!1,this.sessionSearchOpen=!1,this.sessionSearchQuery="",this.sessionSearchResults=[]}async handleWhatsAppStart(e){await nh(this,e)}async handleWhatsAppWait(){await sh(this)}async handleWhatsAppLogout(){await ah(this)}async handleChannelConfigSave(){await ih(this)}async handleChannelConfigReload(){await oh(this)}async handleCompactChat(){if(!this.connected){this.showToast("Cannot compact: not connected","error");return}if(!this.sessionKey){this.showToast("Cannot compact: no active session","error");return}this.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null};try{await this.handleSendChat("/compact")}catch(e){this.compactionStatus=null,console.error("Compaction failed:",e),this.showToast("Compaction failed","error")}}injectCompactionSummary(e,t){const n={role:"system",content:e,timestamp:Date.now(),isCompactionSummary:!0,keptMessages:t};this.chatMessages=[n,...this.chatMessages]}async handleRetryMessage(){const e={client:this.client,connected:this.connected,sessionKey:this.sessionKey,chatLoading:this.chatLoading,chatMessages:this.chatMessages,chatThinkingLevel:this.chatThinkingLevel,chatSending:this.chatSending,chatSendingSessionKey:this.chatSendingSessionKey,chatMessage:this.chatMessage,chatAttachments:this.chatAttachments,chatRunId:this.chatRunId,chatStream:this.chatStream,chatStreamStartedAt:this.chatStreamStartedAt,lastError:this.lastError,pendingRetry:this.pendingRetry},t=await md(e);this.chatSending=e.chatSending,this.chatSendingSessionKey=e.chatSendingSessionKey,this.chatRunId=e.chatRunId,this.chatStream=e.chatStream,this.chatStreamStartedAt=e.chatStreamStartedAt,this.lastError=e.lastError,this.pendingRetry=e.pendingRetry??null,this.chatMessages=e.chatMessages,t&&this.showToast("Message resent","success",2e3)}handleClearRetry(){this.pendingRetry=null}handleNostrProfileEdit(e,t){lh(this,e,t)}handleNostrProfileCancel(){ch(this)}handleNostrProfileFieldChange(e,t){dh(this,e,t)}async handleNostrProfileSave(){await ph(this)}async handleNostrProfileImport(){await hh(this)}handleNostrProfileToggleAdvanced(){uh(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}}}handleGatewayUrlConfirm(){const e=this.pendingGatewayUrl;e&&(this.pendingGatewayUrl=null,Je(this,{...this.settings,gatewayUrl:e}),this.connect())}handleGatewayUrlCancel(){this.pendingGatewayUrl=null}handleOpenSidebar(e,t={}){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarMimeType=t.mimeType?.trim()||null,this.sidebarFilePath=t.filePath?.trim()||null,this.sidebarTitle=t.title?.trim()||null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.showDrivePicker=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarMimeType=null,this.sidebarFilePath=null,this.sidebarTitle=null,this.sidebarCloseTimer=null)},200)}async handleOpenFile(e){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const t=await this.client.request("files.read",{path:e}),n=e.split(".").pop()?.toLowerCase()??"",s=t.contentType??t.mime??(n==="md"?"text/markdown":null),a=e.split("/").pop()??e;this.handleOpenSidebar(t.content,{mimeType:s,filePath:e,title:a}),t.truncated&&this.showToast(`Opened truncated file: ${e}`,"warning")}catch(t){console.error("[Chat] Failed to open file:",t),this.showToast(`Failed to open file: ${e}`,"error")}}async handleToggleDrivePicker(){if(this.showDrivePicker){this.showDrivePicker=!1;return}if(this.driveAccounts.length===0)try{const e=await this.client?.request("files.listDriveAccounts",{});this.driveAccounts=e?.accounts??[]}catch{this.driveAccounts=[]}this.showDrivePicker=!0}async handlePushToDrive(e,t){if(!this.driveUploading){if(this.showDrivePicker=!1,this._pendingBatchPaths&&this._pendingBatchPaths.length>0){const n=this._pendingBatchPaths;this._pendingBatchPaths=void 0,await this._executeBatchDrive(n,t);return}this.driveUploading=!0;try{const n={filePath:e};t&&(n.account=t);const s=await this.client?.request("files.pushToDrive",n),a=t?` to ${t.split("@")[0]}`:"",i=s?.message??`Uploaded${a} to Google Drive`,o=s?.driveUrl;this.showToast(i,"success",o?8e3:5e3,o?{label:"View in Drive",url:o}:void 0)}catch(n){console.error("Push to Drive failed:",n);const s=n instanceof Error?n.message:typeof n=="object"&&n!==null&&"message"in n?String(n.message):"Unknown error";s.includes("GOG_NOT_FOUND")||s.includes("gog CLI not found")?this.showToast("Google Drive not configured. Install gog CLI: npm install -g gog-cli, then run: gog auth add <email> --services drive","warning",1e4):s.includes("GOG_AUTH")||s.includes("auth")&&s.includes("expired")?this.showToast("Google Drive auth expired. Re-authenticate: gog auth add <email> --services drive","warning",8e3):this.showToast(`Drive upload failed: ${s}`,"error",8e3)}finally{this.driveUploading=!1}}}async handleBatchPushToDrive(e){if(this.driveUploading||e.length===0)return;if(!this.driveAccounts||this.driveAccounts.length===0)try{const n=await this.client?.request("files.listDriveAccounts");this.driveAccounts=n?.accounts??[]}catch{}if(this.driveAccounts&&this.driveAccounts.length>1){this._pendingBatchPaths=e,this.showDrivePicker=!0;return}const t=this.driveAccounts?.[0]?.email;await this._executeBatchDrive(e,t)}async _executeBatchDrive(e,t){this.driveUploading=!0,this.showToast(`Uploading ${e.length} files to Drive...`,"info",0);try{const n={filePaths:e};t&&(n.account=t);const s=await this.client?.request("files.batchPushToDrive",n);this.dismissAllToasts();const a=s?.results?.filter(o=>o.success).length??0,i=s?.results?.length??e.length;a===i?this.showToast(`Uploaded ${a} files to Google Drive`,"success",5e3):this.showToast(`Uploaded ${a}/${i} files (${i-a} failed)`,"warning",8e3)}catch(n){this.dismissAllToasts();const s=n instanceof Error?n.message:"Unknown error";this.showToast(`Batch Drive upload failed: ${s}`,"error",8e3)}finally{this.driveUploading=!1,this._pendingBatchPaths=void 0}}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}handleImageClick(e,t,n){this.lightbox=S0(e,t,n)}handleLightboxClose(){this.lightbox=A0()}handleLightboxNav(e){this.lightbox=_0(this.lightbox,e)}normalizeWorkspacePathCandidate(e,t={}){let n=e.trim();if(!n||n.startsWith("#"))return null;for(;n.startsWith("./");)n=n.slice(2);if(n=n.replaceAll("\\","/"),!t.allowAbsolute)for(;n.startsWith("/");)n=n.slice(1);return!n||n.includes("\0")?null:n}isAbsoluteFilesystemPath(e){return e.startsWith("/")||e.startsWith("~/")||/^[a-z]:[\\/]/i.test(e)}inferMimeTypeFromPath(e){if(!e)return null;const t=e.trim().toLowerCase();if(!t)return null;const n=t.split(".").pop()??"";return n?n==="md"||n==="markdown"||n==="mdx"?"text/markdown":n==="html"||n==="htm"?"text/html":n==="json"||n==="json5"?"application/json":n==="txt"||n==="text"||n==="log"?"text/plain":n==="svg"||n==="svgz"?"image/svg+xml":n==="avif"||n==="bmp"||n==="gif"||n==="heic"||n==="heif"||n==="jpeg"||n==="jpg"||n==="png"||n==="webp"?`image/${n==="jpg"?"jpeg":n}`:null:null}sidebarTitleForPath(e){const t=e.replaceAll("\\","/").trim();if(!t)return"Document";const n=t.split("/");return n[n.length-1]||t}async listWorkspaceIdsForPathResolution(){const e=[],t=new Set,n=s=>{if(typeof s!="string")return;const a=s.trim();!a||t.has(a)||(t.add(a),e.push(a))};n(this.selectedWorkspace?.id);for(const s of this.workspaces??[])n(s.id);if(e.length>0||!this.client||!this.connected)return e;try{const s=await this.client.request("workspaces.list",{});for(const a of s.workspaces??[])n(a.id)}catch{}return e}async openWorkspaceRelativeFileInViewer(e){if(!this.client||!this.connected)return!1;const t=await this.listWorkspaceIdsForPathResolution();for(const n of t)try{const s=await this.client.request("workspaces.readFile",{workspaceId:n,filePath:e});if(typeof s.content!="string")continue;return this.handleOpenSidebar(s.content,{mimeType:s.contentType??s.mime??this.inferMimeTypeFromPath(e),filePath:s.path??e,title:this.sidebarTitleForPath(e)}),!0}catch{}return!1}extractWorkspacePathCandidatesFromHref(e){const t=e.trim();if(!t)return[];const n=[],s=t.toLowerCase();if(s.startsWith("mailto:")||s.startsWith("tel:")||s.startsWith("javascript:")||s.startsWith("data:"))return[];if(t.startsWith("file://")){let u=t.slice(7);u.startsWith("/~/")&&(u="~"+u.slice(2));try{u=decodeURIComponent(u)}catch{}n.push(u);const p=[],f=new Set;for(const m of n){const g=this.normalizeWorkspacePathCandidate(m,{allowAbsolute:!0});!g||f.has(g)||(f.add(g),p.push(g))}return p}const a=/^[a-z][a-z0-9+.-]*:/i.test(t),i=/^[a-z]:[\\/]/i.test(t);(!a||i)&&n.push(t);let o=null;try{o=new URL(t,window.location.href)}catch{o=null}if(o&&/^https?:$/.test(o.protocol)&&o.origin===window.location.origin){for(const $ of l2){const d=o.searchParams.get($);d&&n.push(d)}const p=(t.split("#")[0]??"").split("?")[0]??"";p.length>0&&!p.startsWith("/")&&!p.includes("://")&&n.push(p);let m=o.pathname;this.basePath&&m.startsWith(`${this.basePath}/`)?m=m.slice(this.basePath.length):this.basePath&&m===this.basePath&&(m="");const g=m.startsWith("/")?m.slice(1):m;if(g){n.push(g);const $=g.indexOf("/");if($>0){const d=g.slice(0,$).toLowerCase();gc.has(d)&&n.push(g.slice($+1))}}if(m.startsWith("/")&&g){const $=g.split("/")[0]?.toLowerCase()??"";gc.has($)||n.push(m)}}const l=[],c=new Set;for(const u of n){let p=u;try{p=decodeURIComponent(u)}catch{}const f=this.normalizeWorkspacePathCandidate(p,{allowAbsolute:!0});!f||c.has(f)||(c.add(f),l.push(f))}return l}async openWorkspaceFileInViewer(e){if(!this.client||!this.connected)return!1;const t=this.isAbsoluteFilesystemPath(e);if(!t&&await this.openWorkspaceRelativeFileInViewer(e))return!0;try{const n=await this.client.request("workspaces.readFile",{path:e});if(typeof n.content=="string")return this.handleOpenSidebar(n.content,{mimeType:n.contentType??n.mime??this.inferMimeTypeFromPath(e),filePath:n.path??e,title:this.sidebarTitleForPath(e)}),!0}catch{}if(!t)return!1;try{const n=await this.client.request("files.read",{path:e,maxSize:1e6});return typeof n.content!="string"?!1:(this.handleOpenSidebar(n.content,{mimeType:this.inferMimeTypeFromPath(e),filePath:e,title:this.sidebarTitleForPath(e)}),!0)}catch{return!1}}async handleOpenMessageFileLink(e){const t=this.extractWorkspacePathCandidatesFromHref(e);if(t.length===0)return!1;for(const n of t)if(await this.openWorkspaceFileInViewer(n))return!0;return!1}showToast(e,t="info",n=5e3,s){const a=t2(e,t,n,s);this.toasts=s2(this.toasts,a),n>0&&window.setTimeout(()=>{this.dismissToast(a.id)},n)}dismissToast(e){this.toasts=n2(this.toasts,e)}dismissAllToasts(){this.toasts=[]}async handleMyDayRefresh(){if(this.todayViewMode==="agent-log"){await Jt(this,{refresh:!0});return}await Ks(this),this._loadDecisionCards()}_loadDecisionCards(){E(()=>Promise.resolve().then(()=>In),void 0,import.meta.url).then(async e=>{this.todayQueueResults=await e.loadTodayQueueResults(this)}).catch(()=>{})}async handleMyDayTaskStatusChange(e,t){if(!(!this.client||!this.connected))try{await this.client.request("tasks.update",{id:e,status:t,completedAt:t==="complete"?new Date().toISOString():null});const{loadTodayTasksWithQueueStatus:n}=await E(async()=>{const{loadTodayTasksWithQueueStatus:s}=await Promise.resolve().then(()=>In);return{loadTodayTasksWithQueueStatus:s}},void 0,import.meta.url);await n(this)}catch(n){console.error("[MyDay] Failed to update task status:",n)}}async handleTodayCreateTask(e){if(!(!this.client||!this.connected))try{await this.client.request("tasks.create",{title:e,dueDate:re(),priority:"medium",source:"chat"});const{loadTodayTasksWithQueueStatus:t}=await E(async()=>{const{loadTodayTasksWithQueueStatus:n}=await Promise.resolve().then(()=>In);return{loadTodayTasksWithQueueStatus:n}},void 0,import.meta.url);await t(this)}catch(t){console.error("[MyDay] Failed to create task:",t),this.showToast("Failed to create task","error")}}handleTodayEditTask(e){this.todayEditingTaskId=e}async handleTodayUpdateTask(e,t){if(!(!this.client||!this.connected))try{await this.client.request("tasks.update",{id:e,...t}),this.todayEditingTaskId=null;const{loadTodayTasksWithQueueStatus:n}=await E(async()=>{const{loadTodayTasksWithQueueStatus:s}=await Promise.resolve().then(()=>In);return{loadTodayTasksWithQueueStatus:s}},void 0,import.meta.url);await n(this)}catch(n){console.error("[MyDay] Failed to update task:",n),this.showToast("Failed to update task","error")}}handleTodayToggleCompleted(){this.todayShowCompleted=!this.todayShowCompleted}async handleTodayStartTask(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("tasks.openSession",{taskId:e}),n=t?.sessionId??t?.sessionKey;if(n){if(t.task?.title){const{autoTitleCache:i}=await E(async()=>{const{autoTitleCache:o}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:o}},void 0,import.meta.url);i.set(n,t.task.title)}this.setTab("chat"),this.sessionKey=n;const s=this.settings.openTabs.includes(n)?this.settings.openTabs:[...this.settings.openTabs,n];this.applySettings({...this.settings,sessionKey:n,lastActiveSessionKey:n,openTabs:s}),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity();const{loadChatHistory:a}=await E(async()=>{const{loadChatHistory:i}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:i}},void 0,import.meta.url);await a(this),t.queueOutput&&this.chatMessages.length===0&&this.seedSessionWithAgentOutput(t.task?.title??"this task",t.queueOutput,t.agentPrompt??void 0),this.requestUpdate()}}catch(t){console.error("[MyDay] Failed to open session for task:",t),this.showToast("Failed to open session for task","error")}}handleDatePrev(){const e=new Date(this.todaySelectedDate+"T12:00:00");if(e.setDate(e.getDate()-1),this.todaySelectedDate=re(e),this.todayViewMode==="agent-log"){Jt(this);return}xs(this)}handleDateNext(){const e=new Date(this.todaySelectedDate+"T12:00:00");e.setDate(e.getDate()+1);const t=re(),n=re(e);if(!(n>t)){if(this.todaySelectedDate=n,this.todayViewMode==="agent-log"){Jt(this);return}xs(this)}}handleDateToday(){this.todaySelectedDate=re(),Ks(this)}async handleDailyBriefRefresh(){await xs(this)}handleDailyBriefOpenInObsidian(){const e=this.dailyBrief?.date;ou(e)}async loadBriefNotes(){if(!this.client||!this.connected)return;const e=this.todaySelectedDate;try{const t=await this.client.request("briefNotes.get",{date:e});this.briefNotes=t.notes??{}}catch(t){console.error("[BriefNotes] Load error:",t),this.briefNotes={}}}async handleBriefNoteSave(e,t){if(!this.client||!this.connected)return;const n=this.todaySelectedDate;try{const s=await this.client.request("briefNotes.update",{date:n,section:e,text:t});this.briefNotes=s.notes??{}}catch(s){console.error("[BriefNotes] Save error:",s),this.showToast("Failed to save note","error")}}handleTodayViewModeChange(e){this.todayViewMode=e,e==="agent-log"&&!this.agentLog&&Jt(this)}handlePrivateModeToggle(){if(this.chatPrivateMode){const e=this.sessionKey;this.chatPrivateMode=!1,this._destroyPrivateSession(e),this.showToast("Private session destroyed","info",2e3);return}this.chatPrivateMode=!0,this.setTab("chat"),E(async()=>{const{createNewSession:e}=await Promise.resolve().then(()=>at);return{createNewSession:e}},void 0,import.meta.url).then(({createNewSession:e})=>{e(this);const t=Date.now()+1440*60*1e3;this.privateSessions=new Map(this.privateSessions).set(this.sessionKey,t),this._persistPrivateSessions(),this._startPrivateSessionTimer(),this.chatMessages=[{role:"assistant",content:`This is a **private session**. Nothing will be saved to memory or logs.
8464
8491
 
8465
- This session self-destructs when you close it or in **24 hours** — whichever comes first.`,timestamp:Date.now()}],this.requestUpdate()}),this.showToast("Private session created — 24h countdown started","info",3e3)}async _destroyPrivateSession(e){const t=new Map(this.privateSessions);if(t.delete(e),this.privateSessions=t,this._persistPrivateSessions(),this.sessionKey===e){this.chatPrivateMode=!1;const n=this.settings.openTabs.filter(a=>a!==e),s=n[0]||ee;this.applySettings({...this.settings,openTabs:n,sessionKey:s,lastActiveSessionKey:s}),this.sessionKey=s,(await E(async()=>{const{loadChatHistory:a}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:a}},void 0,import.meta.url)).loadChatHistory(this)}else this.applySettings({...this.settings,openTabs:this.settings.openTabs.filter(n=>n!==e)});this.client&&this.connected&&this.client.request("sessions.delete",{key:e,deleteTranscript:!0}).catch(()=>{}),this.privateSessions.size===0&&this._stopPrivateSessionTimer()}_persistPrivateSessions(){const e=Array.from(this.privateSessions.entries());e.length===0?localStorage.removeItem("godmode.privateSessions"):localStorage.setItem("godmode.privateSessions",JSON.stringify(e))}_restorePrivateSessions(){try{const e=localStorage.getItem("godmode.privateSessions");if(!e)return;const t=JSON.parse(e),n=Date.now(),s=t.filter(([,a])=>a>n);if(this.privateSessions=new Map(s),s.length!==t.length){const a=t.filter(([,i])=>i<=n);for(const[i]of a)this._destroyPrivateSession(i)}this.privateSessions.size>0&&(this.privateSessions.has(this.sessionKey)&&(this.chatPrivateMode=!0),this._startPrivateSessionTimer()),this._persistPrivateSessions()}catch{localStorage.removeItem("godmode.privateSessions")}}_startPrivateSessionTimer(){this._privateSessionTimer||(this._privateSessionTimer=setInterval(()=>{const e=Date.now();for(const[t,n]of this.privateSessions)n<=e&&(this._destroyPrivateSession(t),this.showToast("Private session expired and was destroyed","info",3e3));this.privateSessions.size>0&&this.requestUpdate()},3e4))}_stopPrivateSessionTimer(){this._privateSessionTimer&&(clearInterval(this._privateSessionTimer),this._privateSessionTimer=null)}async handleBriefSave(e){if(!this.client||!this.connected)return;const t=this.dailyBrief?.date||this.todaySelectedDate;try{await this.client.request("dailyBrief.update",{date:t,content:e}),this.dailyBrief&&(this.dailyBrief={...this.dailyBrief,updatedAt:new Date().toISOString()})}catch(n){console.error("[DailyBrief] Save error:",n),this.showToast("Failed to save brief","error")}}async handleBriefToggleCheckbox(e,t){if(!this.client||!this.connected)return;const n=this.dailyBrief?.date||this.todaySelectedDate;try{await this.client.request("dailyBrief.toggleCheckbox",{date:n,index:e,checked:t}),this.dailyBrief&&(this.dailyBrief={...this.dailyBrief,updatedAt:new Date().toISOString()})}catch(s){console.error("[DailyBrief] Checkbox toggle error:",s),this.showToast("Failed to toggle checkbox","error")}}async handleWorkRefresh(){await lu(this)}handleWorkToggleProject(e){const t=new Set(this.workExpandedProjects);t.has(e)?t.delete(e):(t.add(e),this.workProjectFiles[e]||Iy(this,e)),this.workExpandedProjects=t}async handleWorkFileClick(e){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const t=await this.client.request("workspaces.readFile",{path:e});if(!t.content){this.showToast(t.error??"Failed to read file","error");return}this.handleOpenSidebar(t.content,{mimeType:t.contentType??t.mime??this.inferMimeTypeFromPath(e),filePath:t.path??e,title:this.sidebarTitleForPath(e)})}catch(t){console.error("[Work] Failed to read file:",t),this.showToast(`Failed to open: ${e}`,"error")}}handleWorkSkillClick(e,t){this.handleStartChatWithPrompt(`Tell me about the "${e}" skill and how it's used in the ${t} project.`)}handlePeopleImport(e){const t=e==="apple"?"Import my contacts from Apple Contacts and organize them into categories.":"Import my contacts from Google Contacts and organize them into categories.";this.handleStartChatWithPrompt(t)}async handleWorkspacesRefresh(){await ra(this)}async handleWorkspaceBrowse(e){if(!this.selectedWorkspace)return;const{browseWorkspaceFolder:t}=await E(async()=>{const{browseWorkspaceFolder:s}=await Promise.resolve().then(()=>pe);return{browseWorkspaceFolder:s}},void 0,import.meta.url),n=await t(this,this.selectedWorkspace.id,e);n&&(this.workspaceBrowsePath=e,this.workspaceBrowseEntries=n.entries,this.workspaceBreadcrumbs=n.breadcrumbs)}async handleWorkspaceBrowseSearch(e){if(this.workspaceBrowseSearchQuery=e,!e.trim()||!this.selectedWorkspace){this.workspaceBrowseSearchResults=null;return}const{searchWorkspaceFiles:t}=await E(async()=>{const{searchWorkspaceFiles:n}=await Promise.resolve().then(()=>pe);return{searchWorkspaceFiles:n}},void 0,import.meta.url);this.workspaceBrowseSearchResults=await t(this,this.selectedWorkspace.id,e)}handleWorkspaceBrowseBack(){this.workspaceBrowsePath=null,this.workspaceBrowseEntries=null,this.workspaceBreadcrumbs=null,this.workspaceBrowseSearchQuery="",this.workspaceBrowseSearchResults=null}async handleWorkspaceCreateFolder(e){if(!this.selectedWorkspace)return;const{createWorkspaceFolder:t}=await E(async()=>{const{createWorkspaceFolder:s}=await Promise.resolve().then(()=>pe);return{createWorkspaceFolder:s}},void 0,import.meta.url),n=await t(this,this.selectedWorkspace.id,e);n&&this.workspaceBrowsePath&&await this.handleWorkspaceBrowse(this.workspaceBrowsePath),n&&this.showToast("Folder created","success",2e3)}async handleGoalsRefresh(){if(!(!this.client||!this.connected)){this.goalsLoading=!0,this.goalsError=null;try{const e=await this.client.request("goals.get",{});this.goals=e.goals??[]}catch(e){this.goalsError=e instanceof Error?e.message:"Failed to load goals",console.error("[Goals] Load error:",e)}finally{this.goalsLoading=!1}}}handleOnboardingStart(){this.onboardingPhase=1,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:1}),this.client?.request("onboarding.update",{phase:1,completePhase:0})}async handleOnboardingIdentitySubmit(e){if(this.client)try{await this.client.request("onboarding.update",{phase:2,completePhase:1,identity:e}),this.onboardingPhase=2,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:2,identity:e}),this.userName=e.name,this.userAvatar=e.emoji,this.applySettings({...this.settings,userName:e.name,userAvatar:e.emoji}),this.setTab("chat"),E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this);const n=`I just set up my GodMode identity. My name is ${e.name}${e.mission?` and my mission is: ${e.mission}`:""}. Let's set up my workspace.`;this.chatMessage=n,this.handleSendChat(n)})}catch(t){console.error("[Onboarding] Identity submit failed:",t),this.showToast("Failed to save identity","error")}}handleOnboardingSkipPhase(){if(!this.client)return;const e=Math.min(this.onboardingPhase+1,6);this.onboardingPhase=e,this.client.request("onboarding.update",{phase:e,completePhase:this.onboardingPhase})}handleOnboardingComplete(){this.onboardingActive=!1,this.onboardingPhase=6,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:6,completedAt:new Date().toISOString()}),this.client?.request("onboarding.complete",{summary:this.onboardingData?.summary??null}),this.showToast("Welcome to GodMode!","success",4e3)}handleStartChatWithPrompt(e){this.setTab("chat"),E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this),this.chatMessage=e,this.requestUpdate()})}handleOpenSupportChat(){const e="agent:main:support";if(this.sessionKey===e){this.setTab("chat");return}E(async()=>{const{saveDraft:s}=await Promise.resolve().then(()=>ja);return{saveDraft:s}},void 0,import.meta.url).then(({saveDraft:s})=>s(this));const n=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:n,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity(),E(async()=>{const{autoTitleCache:s}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:s}},void 0,import.meta.url).then(({autoTitleCache:s})=>{s.set(e,"Support")}),E(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:s}},void 0,import.meta.url).then(({loadChatHistory:s})=>{s(this).then(()=>{this.chatMessages.length===0&&this.sessionKey===e&&(this.chatMessages=[{role:"assistant",content:`**Welcome to GodMode Support**
8492
+ This session self-destructs when you close it or in **24 hours** — whichever comes first.`,timestamp:Date.now()}],this.requestUpdate()}),this.showToast("Private session created — 24h countdown started","info",3e3)}async _destroyPrivateSession(e){const t=new Map(this.privateSessions);if(t.delete(e),this.privateSessions=t,this._persistPrivateSessions(),this.sessionKey===e){this.chatPrivateMode=!1;const n=this.settings.openTabs.filter(a=>a!==e),s=n[0]||ee;this.applySettings({...this.settings,openTabs:n,sessionKey:s,lastActiveSessionKey:s}),this.sessionKey=s,(await E(async()=>{const{loadChatHistory:a}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:a}},void 0,import.meta.url)).loadChatHistory(this)}else this.applySettings({...this.settings,openTabs:this.settings.openTabs.filter(n=>n!==e)});this.client&&this.connected&&this.client.request("sessions.delete",{key:e,deleteTranscript:!0}).catch(()=>{}),this.privateSessions.size===0&&this._stopPrivateSessionTimer()}_persistPrivateSessions(){const e=Array.from(this.privateSessions.entries());e.length===0?localStorage.removeItem("godmode.privateSessions"):localStorage.setItem("godmode.privateSessions",JSON.stringify(e))}_restorePrivateSessions(){try{const e=localStorage.getItem("godmode.privateSessions");if(!e)return;const t=JSON.parse(e),n=Date.now(),s=t.filter(([,a])=>a>n);if(this.privateSessions=new Map(s),s.length!==t.length){const a=t.filter(([,i])=>i<=n);for(const[i]of a)this._destroyPrivateSession(i)}this.privateSessions.size>0&&(this.privateSessions.has(this.sessionKey)&&(this.chatPrivateMode=!0),this._startPrivateSessionTimer()),this._persistPrivateSessions()}catch{localStorage.removeItem("godmode.privateSessions")}}_startPrivateSessionTimer(){this._privateSessionTimer||(this._privateSessionTimer=setInterval(()=>{const e=Date.now();for(const[t,n]of this.privateSessions)n<=e&&(this._destroyPrivateSession(t),this.showToast("Private session expired and was destroyed","info",3e3));this.privateSessions.size>0&&this.requestUpdate()},3e4))}_stopPrivateSessionTimer(){this._privateSessionTimer&&(clearInterval(this._privateSessionTimer),this._privateSessionTimer=null)}async handleBriefSave(e){if(!this.client||!this.connected)return;const t=this.dailyBrief?.date||this.todaySelectedDate;try{await this.client.request("dailyBrief.update",{date:t,content:e}),this.dailyBrief&&(this.dailyBrief={...this.dailyBrief,updatedAt:new Date().toISOString()})}catch(n){console.error("[DailyBrief] Save error:",n),this.showToast("Failed to save brief","error")}}async handleBriefToggleCheckbox(e,t){if(!this.client||!this.connected)return;const n=this.dailyBrief?.date||this.todaySelectedDate;try{await this.client.request("dailyBrief.toggleCheckbox",{date:n,index:e,checked:t}),this.dailyBrief&&(this.dailyBrief={...this.dailyBrief,updatedAt:new Date().toISOString()})}catch(s){console.error("[DailyBrief] Checkbox toggle error:",s),this.showToast("Failed to toggle checkbox","error")}}async handleWorkRefresh(){await ru(this)}handleWorkToggleProject(e){const t=new Set(this.workExpandedProjects);t.has(e)?t.delete(e):(t.add(e),this.workProjectFiles[e]||Ry(this,e)),this.workExpandedProjects=t}async handleWorkFileClick(e){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const t=await this.client.request("workspaces.readFile",{path:e});if(!t.content){this.showToast(t.error??"Failed to read file","error");return}this.handleOpenSidebar(t.content,{mimeType:t.contentType??t.mime??this.inferMimeTypeFromPath(e),filePath:t.path??e,title:this.sidebarTitleForPath(e)})}catch(t){console.error("[Work] Failed to read file:",t),this.showToast(`Failed to open: ${e}`,"error")}}handleWorkSkillClick(e,t){this.handleStartChatWithPrompt(`Tell me about the "${e}" skill and how it's used in the ${t} project.`)}handlePeopleImport(e){const t=e==="apple"?"Import my contacts from Apple Contacts and organize them into categories.":"Import my contacts from Google Contacts and organize them into categories.";this.handleStartChatWithPrompt(t)}async handleWorkspacesRefresh(){await ra(this)}async handleWorkspaceBrowse(e){if(!this.selectedWorkspace)return;const{browseWorkspaceFolder:t}=await E(async()=>{const{browseWorkspaceFolder:s}=await Promise.resolve().then(()=>pe);return{browseWorkspaceFolder:s}},void 0,import.meta.url),n=await t(this,this.selectedWorkspace.id,e);n&&(this.workspaceBrowsePath=e,this.workspaceBrowseEntries=n.entries,this.workspaceBreadcrumbs=n.breadcrumbs)}async handleWorkspaceBrowseSearch(e){if(this.workspaceBrowseSearchQuery=e,!e.trim()||!this.selectedWorkspace){this.workspaceBrowseSearchResults=null;return}const{searchWorkspaceFiles:t}=await E(async()=>{const{searchWorkspaceFiles:n}=await Promise.resolve().then(()=>pe);return{searchWorkspaceFiles:n}},void 0,import.meta.url);this.workspaceBrowseSearchResults=await t(this,this.selectedWorkspace.id,e)}handleWorkspaceBrowseBack(){this.workspaceBrowsePath=null,this.workspaceBrowseEntries=null,this.workspaceBreadcrumbs=null,this.workspaceBrowseSearchQuery="",this.workspaceBrowseSearchResults=null}async handleWorkspaceCreateFolder(e){if(!this.selectedWorkspace)return;const{createWorkspaceFolder:t}=await E(async()=>{const{createWorkspaceFolder:s}=await Promise.resolve().then(()=>pe);return{createWorkspaceFolder:s}},void 0,import.meta.url),n=await t(this,this.selectedWorkspace.id,e);n&&this.workspaceBrowsePath&&await this.handleWorkspaceBrowse(this.workspaceBrowsePath),n&&this.showToast("Folder created","success",2e3)}async handleGoalsRefresh(){if(!(!this.client||!this.connected)){this.goalsLoading=!0,this.goalsError=null;try{const e=await this.client.request("goals.get",{});this.goals=e.goals??[]}catch(e){this.goalsError=e instanceof Error?e.message:"Failed to load goals",console.error("[Goals] Load error:",e)}finally{this.goalsLoading=!1}}}handleOnboardingStart(){this.onboardingPhase=1,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:1}),this.client?.request("onboarding.update",{phase:1,completePhase:0})}async handleOnboardingIdentitySubmit(e){if(this.client)try{await this.client.request("onboarding.update",{phase:2,completePhase:1,identity:e}),this.onboardingPhase=2,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:2,identity:e}),this.userName=e.name,this.userAvatar=e.emoji,this.applySettings({...this.settings,userName:e.name,userAvatar:e.emoji}),this.setTab("chat"),E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this);const n=`I just set up my GodMode identity. My name is ${e.name}${e.mission?` and my mission is: ${e.mission}`:""}. Let's set up my workspace.`;this.chatMessage=n,this.handleSendChat(n)})}catch(t){console.error("[Onboarding] Identity submit failed:",t),this.showToast("Failed to save identity","error")}}handleOnboardingSkipPhase(){if(!this.client)return;const e=Math.min(this.onboardingPhase+1,6);this.onboardingPhase=e,this.client.request("onboarding.update",{phase:e,completePhase:this.onboardingPhase})}handleOnboardingComplete(){this.onboardingActive=!1,this.onboardingPhase=6,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:6,completedAt:new Date().toISOString()}),this.client?.request("onboarding.complete",{summary:this.onboardingData?.summary??null}),this.showToast("Welcome to GodMode!","success",4e3)}handleStartChatWithPrompt(e){this.setTab("chat"),E(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>at);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this),this.chatMessage=e,this.requestUpdate()})}handleOpenSupportChat(){const e="agent:main:support";if(this.sessionKey===e){this.setTab("chat");return}E(async()=>{const{saveDraft:s}=await Promise.resolve().then(()=>ja);return{saveDraft:s}},void 0,import.meta.url).then(({saveDraft:s})=>s(this));const n=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:n,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity(),E(async()=>{const{autoTitleCache:s}=await Promise.resolve().then(()=>Cn);return{autoTitleCache:s}},void 0,import.meta.url).then(({autoTitleCache:s})=>{s.set(e,"Support")}),E(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>Ge);return{loadChatHistory:s}},void 0,import.meta.url).then(({loadChatHistory:s})=>{s(this).then(()=>{this.chatMessages.length===0&&this.sessionKey===e&&(this.chatMessages=[{role:"assistant",content:`**Welcome to GodMode Support**
8466
8493
 
8467
8494
  I have full access to your system diagnostics and GodMode knowledge base. I can help with:
8468
8495
 
@@ -8471,4 +8498,4 @@ I have full access to your system diagnostics and GodMode knowledge base. I can
8471
8498
  - Setup guidance
8472
8499
  - Escalation to the team if needed
8473
8500
 
8474
- What can I help you with?`,timestamp:Date.now()}],this.requestUpdate())}).catch(a=>{console.error("[Support] Failed to load chat history:",a)})})}handleWizardOpen(){E(async()=>{const{emptyWizardState:e}=await Promise.resolve().then(()=>X0);return{emptyWizardState:e}},void 0,import.meta.url).then(({emptyWizardState:e})=>{this.wizardState=e(),this.wizardActive=!0,this.requestUpdate()})}handleWizardClose(){this.wizardActive=!1,this.wizardState=null,this.requestUpdate()}handleWizardStepChange(e){this.wizardState&&(this.wizardState={...this.wizardState,step:e},this.requestUpdate())}handleWizardAnswerChange(e,t){this.wizardState&&(this.wizardState={...this.wizardState,answers:{...this.wizardState.answers,[e]:t}},this.requestUpdate())}async handleWizardPreview(){if(!(!this.client||!this.wizardState))try{const e=await this.client.request("onboarding.wizard.preview",this.wizardState.answers);this.wizardState={...this.wizardState,preview:e.files??[]},this.requestUpdate()}catch(e){console.error("[Wizard] Preview failed:",e)}}async handleWizardGenerate(){if(!(!this.client||!this.wizardState)){this.wizardState={...this.wizardState,generating:!0,error:null},this.requestUpdate();try{const e=await this.client.request("onboarding.wizard.generate",this.wizardState.answers);this.wizardState={...this.wizardState,generating:!1,step:9,result:{filesCreated:e.filesCreated,filesSkipped:e.filesSkipped,configPatched:e.configPatched,workspacePath:e.workspacePath}},this.requestUpdate(),this.showToast("Memory system generated!","success",4e3)}catch(e){const t=e instanceof Error?e.message:"Failed to generate workspace";this.wizardState={...this.wizardState,generating:!1,error:t},this.requestUpdate(),this.showToast(t,"error")}}}async handleQuickSetup(e,t,n){E(()=>import("./setup-DDvbMoK2.js"),[],import.meta.url).then(async({quickSetup:s})=>{await s(this,e,t,n)&&(this.setTab("chat"),E(async()=>{const{loadChecklist:i}=await import("./setup-DDvbMoK2.js");return{loadChecklist:i}},[],import.meta.url).then(({loadChecklist:i})=>i(this)))})}handleLoadSetupChecklist(){E(async()=>{const{loadChecklist:e}=await import("./setup-DDvbMoK2.js");return{loadChecklist:e}},[],import.meta.url).then(({loadChecklist:e})=>e(this))}handleHideSetup(){E(async()=>{const{hideSetup:e}=await import("./setup-DDvbMoK2.js");return{hideSetup:e}},[],import.meta.url).then(({hideSetup:e})=>e(this))}handleRunAssessment(){this.client&&this.client.request("onboarding.assess",{}).then(()=>{this.handleLoadSetupChecklist()})}async handleDataRefresh(){if(!(!this.client||!this.connected)){this.dataLoading=!0,this.dataError=null;try{const e=await this.client.request("dataSources.list",{});this.dataSources=e.sources??[]}catch(e){this.dataError=e instanceof Error?e.message:"Failed to load data sources",console.error("[Data] Load error:",e)}finally{this.dataLoading=!1}}}handleDataSubtabChange(e){this.dataSubtab=e}handleDataConnectSource(e){const n=this.dataSources?.find(s=>s.id===e)?.name??e;this.handleStartChatWithPrompt(`Help me connect and configure the ${n} integration.`)}handleDataQuerySubmit(e){this.handleStartChatWithPrompt(`Query my connected data: ${e}`)}handleUpdateUserProfile(e,t){const n=e.trim().slice(0,50),s=t.trim();this.userName=n||"You",this.userAvatar=s||null,this.applySettings({...this.settings,userName:n,userAvatar:s})}async handleLoadIntegrations(){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadIntegrations(this)}handleExpandCard(e){E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.expandCard(this,e))}async handleLoadGuide(e){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadGuide(this,e)}async handleTestIntegration(e){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).testIntegration(this,e)}async handleConfigureIntegration(e,t){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).configureIntegration(this,e,t)}handleUpdateConfigValue(e,t){this.onboardingConfigValues={...this.onboardingConfigValues,[e]:t}}handleSkipIntegration(e){E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.skipIntegration(this,e))}async handleMarkOnboardingComplete(){if(!(!this.client||!this.connected))try{await this.client.request("onboarding.complete",{}),this.godmodeOptions&&(this.godmodeOptions={...this.godmodeOptions,"onboarding.complete":!0}),this.showSetupTab=!1,this.setTab("chat")}catch(e){console.error("[onboarding] Failed to mark complete:",e)}}render(){return K1(this)}};b([w()],y.prototype,"settings",2);b([w()],y.prototype,"password",2);b([w()],y.prototype,"tab",2);b([w()],y.prototype,"onboarding",2);b([w()],y.prototype,"connected",2);b([w()],y.prototype,"reconnecting",2);b([w()],y.prototype,"reconnectAttempt",2);b([w()],y.prototype,"theme",2);b([w()],y.prototype,"themeResolved",2);b([w()],y.prototype,"hello",2);b([w()],y.prototype,"lastError",2);b([w()],y.prototype,"eventLog",2);b([w()],y.prototype,"assistantName",2);b([w()],y.prototype,"assistantAvatar",2);b([w()],y.prototype,"assistantAgentId",2);b([w()],y.prototype,"userName",2);b([w()],y.prototype,"userAvatar",2);b([w()],y.prototype,"sessionKey",2);b([w()],y.prototype,"sessionPickerOpen",2);b([w()],y.prototype,"sessionPickerPosition",2);b([w()],y.prototype,"sessionPickerSearch",2);b([w()],y.prototype,"sessionSearchOpen",2);b([w()],y.prototype,"sessionSearchPosition",2);b([w()],y.prototype,"sessionSearchQuery",2);b([w()],y.prototype,"sessionSearchResults",2);b([w()],y.prototype,"sessionSearchLoading",2);b([w()],y.prototype,"profilePopoverOpen",2);b([w()],y.prototype,"profileEditName",2);b([w()],y.prototype,"profileEditAvatar",2);b([w()],y.prototype,"editingTabKey",2);b([w()],y.prototype,"chatLoading",2);b([w()],y.prototype,"chatSending",2);b([w()],y.prototype,"chatSendingSessionKey",2);b([w()],y.prototype,"chatMessage",2);b([w()],y.prototype,"chatDrafts",2);b([w()],y.prototype,"chatMessages",2);b([w()],y.prototype,"chatToolMessages",2);b([w()],y.prototype,"chatStream",2);b([w()],y.prototype,"chatStreamStartedAt",2);b([w()],y.prototype,"chatRunId",2);b([w()],y.prototype,"currentToolName",2);b([w()],y.prototype,"currentToolInfo",2);b([w()],y.prototype,"workingSessions",2);b([w()],y.prototype,"compactionStatus",2);b([w()],y.prototype,"chatAvatarUrl",2);b([w()],y.prototype,"chatThinkingLevel",2);b([w()],y.prototype,"chatQueue",2);b([w()],y.prototype,"chatAttachments",2);b([w()],y.prototype,"pendingRetry",2);b([w()],y.prototype,"autoRetryAfterCompact",2);b([w()],y.prototype,"sidebarOpen",2);b([w()],y.prototype,"sidebarContent",2);b([w()],y.prototype,"sidebarError",2);b([w()],y.prototype,"sidebarMimeType",2);b([w()],y.prototype,"sidebarFilePath",2);b([w()],y.prototype,"sidebarTitle",2);b([w()],y.prototype,"splitRatio",2);b([w()],y.prototype,"lightbox",2);b([w()],y.prototype,"driveAccounts",2);b([w()],y.prototype,"showDrivePicker",2);b([w()],y.prototype,"driveUploading",2);b([w()],y.prototype,"updateStatus",2);b([w()],y.prototype,"updateLoading",2);b([w()],y.prototype,"updateError",2);b([w()],y.prototype,"updateLastChecked",2);b([w()],y.prototype,"nodesLoading",2);b([w()],y.prototype,"nodes",2);b([w()],y.prototype,"devicesLoading",2);b([w()],y.prototype,"devicesError",2);b([w()],y.prototype,"devicesList",2);b([w()],y.prototype,"execApprovalsLoading",2);b([w()],y.prototype,"execApprovalsSaving",2);b([w()],y.prototype,"execApprovalsDirty",2);b([w()],y.prototype,"execApprovalsSnapshot",2);b([w()],y.prototype,"execApprovalsForm",2);b([w()],y.prototype,"execApprovalsSelectedAgent",2);b([w()],y.prototype,"execApprovalsTarget",2);b([w()],y.prototype,"execApprovalsTargetNodeId",2);b([w()],y.prototype,"execApprovalQueue",2);b([w()],y.prototype,"execApprovalBusy",2);b([w()],y.prototype,"execApprovalError",2);b([w()],y.prototype,"pendingGatewayUrl",2);b([w()],y.prototype,"configLoading",2);b([w()],y.prototype,"configRaw",2);b([w()],y.prototype,"configRawOriginal",2);b([w()],y.prototype,"configValid",2);b([w()],y.prototype,"configIssues",2);b([w()],y.prototype,"configSaving",2);b([w()],y.prototype,"configApplying",2);b([w()],y.prototype,"updateRunning",2);b([w()],y.prototype,"applySessionKey",2);b([w()],y.prototype,"configSnapshot",2);b([w()],y.prototype,"configSchema",2);b([w()],y.prototype,"configSchemaVersion",2);b([w()],y.prototype,"configSchemaLoading",2);b([w()],y.prototype,"configUiHints",2);b([w()],y.prototype,"configForm",2);b([w()],y.prototype,"configFormOriginal",2);b([w()],y.prototype,"configFormDirty",2);b([w()],y.prototype,"configFormMode",2);b([w()],y.prototype,"configSearchQuery",2);b([w()],y.prototype,"configActiveSection",2);b([w()],y.prototype,"configActiveSubsection",2);b([w()],y.prototype,"channelsLoading",2);b([w()],y.prototype,"channelsSnapshot",2);b([w()],y.prototype,"channelsError",2);b([w()],y.prototype,"channelsLastSuccess",2);b([w()],y.prototype,"whatsappLoginMessage",2);b([w()],y.prototype,"whatsappLoginQrDataUrl",2);b([w()],y.prototype,"whatsappLoginConnected",2);b([w()],y.prototype,"whatsappBusy",2);b([w()],y.prototype,"nostrProfileFormState",2);b([w()],y.prototype,"nostrProfileAccountId",2);b([w()],y.prototype,"presenceLoading",2);b([w()],y.prototype,"presenceEntries",2);b([w()],y.prototype,"presenceError",2);b([w()],y.prototype,"presenceStatus",2);b([w()],y.prototype,"agentsLoading",2);b([w()],y.prototype,"agentsList",2);b([w()],y.prototype,"agentsError",2);b([w()],y.prototype,"sessionsLoading",2);b([w()],y.prototype,"sessionsResult",2);b([w()],y.prototype,"sessionsError",2);b([w()],y.prototype,"sessionsFilterActive",2);b([w()],y.prototype,"sessionsFilterLimit",2);b([w()],y.prototype,"sessionsIncludeGlobal",2);b([w()],y.prototype,"sessionsIncludeUnknown",2);b([w()],y.prototype,"archivedSessions",2);b([w()],y.prototype,"archivedSessionsLoading",2);b([w()],y.prototype,"archivedSessionsExpanded",2);b([w()],y.prototype,"cronLoading",2);b([w()],y.prototype,"cronJobs",2);b([w()],y.prototype,"cronStatus",2);b([w()],y.prototype,"cronError",2);b([w()],y.prototype,"cronForm",2);b([w()],y.prototype,"cronRunsJobId",2);b([w()],y.prototype,"cronRuns",2);b([w()],y.prototype,"cronBusy",2);b([w()],y.prototype,"workspaceNeedsSetup",2);b([w()],y.prototype,"onboardingPhase",2);b([w()],y.prototype,"onboardingData",2);b([w()],y.prototype,"onboardingActive",2);b([w()],y.prototype,"wizardActive",2);b([w()],y.prototype,"wizardState",2);b([w()],y.prototype,"showSetupTab",2);b([w()],y.prototype,"setupChecklist",2);b([w()],y.prototype,"setupChecklistLoading",2);b([w()],y.prototype,"setupQuickDone",2);b([w()],y.prototype,"onboardingIntegrations",2);b([w()],y.prototype,"onboardingCoreProgress",2);b([w()],y.prototype,"onboardingExpandedCard",2);b([w()],y.prototype,"onboardingLoadingGuide",2);b([w()],y.prototype,"onboardingActiveGuide",2);b([w()],y.prototype,"onboardingTestingId",2);b([w()],y.prototype,"onboardingTestResult",2);b([w()],y.prototype,"onboardingConfigValues",2);b([w()],y.prototype,"onboardingProgress",2);b([w()],y.prototype,"workspaces",2);b([w()],y.prototype,"selectedWorkspace",2);b([w()],y.prototype,"workspacesSearchQuery",2);b([w()],y.prototype,"workspaceItemSearchQuery",2);b([w()],y.prototype,"workspacesLoading",2);b([w()],y.prototype,"workspacesCreateLoading",2);b([w()],y.prototype,"workspacesError",2);b([w()],y.prototype,"workspaceExpandedFolders",2);b([w()],y.prototype,"allTasks",2);b([w()],y.prototype,"taskFilter",2);b([w()],y.prototype,"taskSort",2);b([w()],y.prototype,"showCompletedTasks",2);b([w()],y.prototype,"editingTaskId",2);b([w()],y.prototype,"workspaceBrowsePath",2);b([w()],y.prototype,"workspaceBrowseEntries",2);b([w()],y.prototype,"workspaceBreadcrumbs",2);b([w()],y.prototype,"workspaceBrowseSearchQuery",2);b([w()],y.prototype,"workspaceBrowseSearchResults",2);b([w()],y.prototype,"myDayLoading",2);b([w()],y.prototype,"myDayError",2);b([w()],y.prototype,"todaySelectedDate",2);b([w()],y.prototype,"todayViewMode",2);b([w()],y.prototype,"dailyBrief",2);b([w()],y.prototype,"dailyBriefLoading",2);b([w()],y.prototype,"dailyBriefError",2);b([w()],y.prototype,"agentLog",2);b([w()],y.prototype,"agentLogLoading",2);b([w()],y.prototype,"agentLogError",2);b([w()],y.prototype,"briefNotes",2);b([w()],y.prototype,"todayTasks",2);b([w()],y.prototype,"todayTasksLoading",2);b([w()],y.prototype,"todayEditingTaskId",2);b([w()],y.prototype,"todayShowCompleted",2);b([w()],y.prototype,"allyPanelOpen",2);b([w()],y.prototype,"allyMessages",2);b([w()],y.prototype,"allyStream",2);b([w()],y.prototype,"allyDraft",2);b([w()],y.prototype,"allyUnread",2);b([w()],y.prototype,"allySending",2);b([w()],y.prototype,"allyWorking",2);b([w()],y.prototype,"allyAttachments",2);b([w()],y.prototype,"todayQueueResults",2);b([w()],y.prototype,"chatPrivateMode",2);b([w()],y.prototype,"privateSessions",2);b([w()],y.prototype,"goals",2);b([w()],y.prototype,"goalsLoading",2);b([w()],y.prototype,"goalsError",2);b([w()],y.prototype,"dataSources",2);b([w()],y.prototype,"dataLoading",2);b([w()],y.prototype,"dataError",2);b([w()],y.prototype,"dataSubtab",2);b([w()],y.prototype,"dynamicSlots",2);b([w()],y.prototype,"workProjects",2);b([w()],y.prototype,"workLoading",2);b([w()],y.prototype,"workError",2);b([w()],y.prototype,"workExpandedProjects",2);b([w()],y.prototype,"workProjectFiles",2);b([w()],y.prototype,"workDetailLoading",2);b([w()],y.prototype,"skillsLoading",2);b([w()],y.prototype,"skillsReport",2);b([w()],y.prototype,"skillsError",2);b([w()],y.prototype,"skillsFilter",2);b([w()],y.prototype,"skillEdits",2);b([w()],y.prototype,"skillsBusyKey",2);b([w()],y.prototype,"skillMessages",2);b([w()],y.prototype,"debugLoading",2);b([w()],y.prototype,"debugStatus",2);b([w()],y.prototype,"debugHealth",2);b([w()],y.prototype,"debugModels",2);b([w()],y.prototype,"debugHeartbeat",2);b([w()],y.prototype,"debugCallMethod",2);b([w()],y.prototype,"debugCallParams",2);b([w()],y.prototype,"debugCallResult",2);b([w()],y.prototype,"debugCallError",2);b([w()],y.prototype,"logsLoading",2);b([w()],y.prototype,"logsError",2);b([w()],y.prototype,"logsFile",2);b([w()],y.prototype,"logsEntries",2);b([w()],y.prototype,"logsFilterText",2);b([w()],y.prototype,"logsLevelFilters",2);b([w()],y.prototype,"logsAutoFollow",2);b([w()],y.prototype,"logsTruncated",2);b([w()],y.prototype,"logsCursor",2);b([w()],y.prototype,"logsLastFetchAt",2);b([w()],y.prototype,"logsLimit",2);b([w()],y.prototype,"logsMaxBytes",2);b([w()],y.prototype,"logsAtBottom",2);b([w()],y.prototype,"toasts",2);b([w()],y.prototype,"chatUserNearBottom",2);b([w()],y.prototype,"chatNewMessagesBelow",2);b([w()],y.prototype,"consciousnessStatus",2);b([w()],y.prototype,"focusPulseData",2);b([w()],y.prototype,"trustTrackerData",2);b([w()],y.prototype,"trustTrackerLoading",2);b([w()],y.prototype,"guardrailsData",2);b([w()],y.prototype,"guardrailsLoading",2);b([w()],y.prototype,"guardrailsShowAddForm",2);b([w()],y.prototype,"missionControlData",2);b([w()],y.prototype,"missionControlLoading",2);b([w()],y.prototype,"missionControlError",2);b([w()],y.prototype,"missionControlFullControl",2);b([w()],y.prototype,"godmodeOptions",2);b([w()],y.prototype,"godmodeOptionsLoading",2);b([w()],y.prototype,"dashboardsList",2);b([w()],y.prototype,"dashboardsLoading",2);b([w()],y.prototype,"dashboardsError",2);b([w()],y.prototype,"activeDashboardId",2);b([w()],y.prototype,"activeDashboardHtml",2);b([w()],y.prototype,"activeDashboardManifest",2);b([w()],y.prototype,"dashboardChatOpen",2);b([w()],y.prototype,"secondBrainSubtab",2);b([w()],y.prototype,"secondBrainLoading",2);b([w()],y.prototype,"secondBrainError",2);b([w()],y.prototype,"secondBrainIdentity",2);b([w()],y.prototype,"secondBrainMemoryBank",2);b([w()],y.prototype,"secondBrainAiPacket",2);b([w()],y.prototype,"secondBrainSourcesData",2);b([w()],y.prototype,"secondBrainResearchData",2);b([w()],y.prototype,"secondBrainResearchAddFormOpen",2);b([w()],y.prototype,"secondBrainResearchAddForm",2);b([w()],y.prototype,"secondBrainResearchCategories",2);b([w()],y.prototype,"secondBrainSelectedEntry",2);b([w()],y.prototype,"secondBrainSearchQuery",2);b([w()],y.prototype,"secondBrainSyncing",2);b([w()],y.prototype,"secondBrainBrowsingFolder",2);b([w()],y.prototype,"secondBrainFolderEntries",2);b([w()],y.prototype,"secondBrainFolderName",2);b([w()],y.prototype,"secondBrainFileTree",2);b([w()],y.prototype,"secondBrainFileTreeLoading",2);b([w()],y.prototype,"secondBrainFileSearchQuery",2);b([w()],y.prototype,"secondBrainFileSearchResults",2);y=b([kc("godmode-app")],y);
8501
+ What can I help you with?`,timestamp:Date.now()}],this.requestUpdate())}).catch(a=>{console.error("[Support] Failed to load chat history:",a)})})}handleWizardOpen(){E(async()=>{const{emptyWizardState:e}=await Promise.resolve().then(()=>X0);return{emptyWizardState:e}},void 0,import.meta.url).then(({emptyWizardState:e})=>{this.wizardState=e(),this.wizardActive=!0,this.requestUpdate()})}handleWizardClose(){this.wizardActive=!1,this.wizardState=null,this.requestUpdate()}handleWizardStepChange(e){this.wizardState&&(this.wizardState={...this.wizardState,step:e},this.requestUpdate(),e===10&&this.client&&this.client.request("onboarding.seedRoster",{}).then(t=>{this.wizardState&&(this.wizardState={...this.wizardState,roster:t.roster},this.requestUpdate())}).catch(t=>{console.error("[Wizard] seedRoster failed:",t)}))}handleWizardAnswerChange(e,t){this.wizardState&&(this.wizardState={...this.wizardState,answers:{...this.wizardState.answers,[e]:t}},this.requestUpdate())}async handleWizardPreview(){if(!(!this.client||!this.wizardState))try{const e=await this.client.request("onboarding.wizard.preview",this.wizardState.answers);this.wizardState={...this.wizardState,preview:e.files??[]},this.requestUpdate()}catch(e){console.error("[Wizard] Preview failed:",e)}}async handleWizardGenerate(){if(!(!this.client||!this.wizardState)){this.wizardState={...this.wizardState,generating:!0,error:null},this.requestUpdate();try{const e=await this.client.request("onboarding.wizard.generate",this.wizardState.answers);this.wizardState={...this.wizardState,generating:!1,step:9,result:{filesCreated:e.filesCreated,filesSkipped:e.filesSkipped,configPatched:e.configPatched,workspacePath:e.workspacePath}},this.requestUpdate(),this.showToast("Memory system generated!","success",4e3)}catch(e){const t=e instanceof Error?e.message:"Failed to generate workspace";this.wizardState={...this.wizardState,generating:!1,error:t},this.requestUpdate(),this.showToast(t,"error")}}}async handleQuickSetup(e,t,n){E(()=>import("./setup-DDvbMoK2.js"),[],import.meta.url).then(async({quickSetup:s})=>{await s(this,e,t,n)&&(this.setTab("chat"),E(async()=>{const{loadChecklist:i}=await import("./setup-DDvbMoK2.js");return{loadChecklist:i}},[],import.meta.url).then(({loadChecklist:i})=>i(this)))})}handleLoadSetupChecklist(){E(async()=>{const{loadChecklist:e}=await import("./setup-DDvbMoK2.js");return{loadChecklist:e}},[],import.meta.url).then(({loadChecklist:e})=>e(this))}handleHideSetup(){E(async()=>{const{hideSetup:e}=await import("./setup-DDvbMoK2.js");return{hideSetup:e}},[],import.meta.url).then(({hideSetup:e})=>e(this))}handleRunAssessment(){this.client&&this.client.request("onboarding.assess",{}).then(()=>{this.handleLoadSetupChecklist()})}async handleDataRefresh(){if(!(!this.client||!this.connected)){this.dataLoading=!0,this.dataError=null;try{const e=await this.client.request("dataSources.list",{});this.dataSources=e.sources??[]}catch(e){this.dataError=e instanceof Error?e.message:"Failed to load data sources",console.error("[Data] Load error:",e)}finally{this.dataLoading=!1}}}handleDataSubtabChange(e){this.dataSubtab=e}handleDataConnectSource(e){const n=this.dataSources?.find(s=>s.id===e)?.name??e;this.handleStartChatWithPrompt(`Help me connect and configure the ${n} integration.`)}handleDataQuerySubmit(e){this.handleStartChatWithPrompt(`Query my connected data: ${e}`)}handleUpdateUserProfile(e,t){const n=e.trim().slice(0,50),s=t.trim();this.userName=n||"You",this.userAvatar=s||null,this.applySettings({...this.settings,userName:n,userAvatar:s})}async handleLoadIntegrations(){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadIntegrations(this)}handleExpandCard(e){E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.expandCard(this,e))}async handleLoadGuide(e){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadGuide(this,e)}async handleTestIntegration(e){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).testIntegration(this,e)}async handleConfigureIntegration(e,t){await(await E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).configureIntegration(this,e,t)}handleUpdateConfigValue(e,t){this.onboardingConfigValues={...this.onboardingConfigValues,[e]:t}}handleSkipIntegration(e){E(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.skipIntegration(this,e))}async handleMarkOnboardingComplete(){if(!(!this.client||!this.connected))try{await this.client.request("onboarding.complete",{}),this.godmodeOptions&&(this.godmodeOptions={...this.godmodeOptions,"onboarding.complete":!0}),this.showSetupTab=!1,this.setTab("chat")}catch(e){console.error("[onboarding] Failed to mark complete:",e)}}render(){return K1(this)}};b([w()],y.prototype,"settings",2);b([w()],y.prototype,"password",2);b([w()],y.prototype,"tab",2);b([w()],y.prototype,"onboarding",2);b([w()],y.prototype,"connected",2);b([w()],y.prototype,"reconnecting",2);b([w()],y.prototype,"reconnectAttempt",2);b([w()],y.prototype,"theme",2);b([w()],y.prototype,"themeResolved",2);b([w()],y.prototype,"hello",2);b([w()],y.prototype,"lastError",2);b([w()],y.prototype,"eventLog",2);b([w()],y.prototype,"assistantName",2);b([w()],y.prototype,"assistantAvatar",2);b([w()],y.prototype,"assistantAgentId",2);b([w()],y.prototype,"userName",2);b([w()],y.prototype,"userAvatar",2);b([w()],y.prototype,"sessionKey",2);b([w()],y.prototype,"sessionPickerOpen",2);b([w()],y.prototype,"sessionPickerPosition",2);b([w()],y.prototype,"sessionPickerSearch",2);b([w()],y.prototype,"sessionSearchOpen",2);b([w()],y.prototype,"sessionSearchPosition",2);b([w()],y.prototype,"sessionSearchQuery",2);b([w()],y.prototype,"sessionSearchResults",2);b([w()],y.prototype,"sessionSearchLoading",2);b([w()],y.prototype,"profilePopoverOpen",2);b([w()],y.prototype,"profileEditName",2);b([w()],y.prototype,"profileEditAvatar",2);b([w()],y.prototype,"editingTabKey",2);b([w()],y.prototype,"chatLoading",2);b([w()],y.prototype,"chatSending",2);b([w()],y.prototype,"chatSendingSessionKey",2);b([w()],y.prototype,"chatMessage",2);b([w()],y.prototype,"chatDrafts",2);b([w()],y.prototype,"chatMessages",2);b([w()],y.prototype,"chatToolMessages",2);b([w()],y.prototype,"chatStream",2);b([w()],y.prototype,"chatStreamStartedAt",2);b([w()],y.prototype,"chatRunId",2);b([w()],y.prototype,"currentToolName",2);b([w()],y.prototype,"currentToolInfo",2);b([w()],y.prototype,"workingSessions",2);b([w()],y.prototype,"compactionStatus",2);b([w()],y.prototype,"chatAvatarUrl",2);b([w()],y.prototype,"chatThinkingLevel",2);b([w()],y.prototype,"chatQueue",2);b([w()],y.prototype,"chatAttachments",2);b([w()],y.prototype,"pendingRetry",2);b([w()],y.prototype,"autoRetryAfterCompact",2);b([w()],y.prototype,"sidebarOpen",2);b([w()],y.prototype,"sidebarContent",2);b([w()],y.prototype,"sidebarError",2);b([w()],y.prototype,"sidebarMimeType",2);b([w()],y.prototype,"sidebarFilePath",2);b([w()],y.prototype,"sidebarTitle",2);b([w()],y.prototype,"splitRatio",2);b([w()],y.prototype,"lightbox",2);b([w()],y.prototype,"driveAccounts",2);b([w()],y.prototype,"showDrivePicker",2);b([w()],y.prototype,"driveUploading",2);b([w()],y.prototype,"updateStatus",2);b([w()],y.prototype,"updateLoading",2);b([w()],y.prototype,"updateError",2);b([w()],y.prototype,"updateLastChecked",2);b([w()],y.prototype,"nodesLoading",2);b([w()],y.prototype,"nodes",2);b([w()],y.prototype,"devicesLoading",2);b([w()],y.prototype,"devicesError",2);b([w()],y.prototype,"devicesList",2);b([w()],y.prototype,"execApprovalsLoading",2);b([w()],y.prototype,"execApprovalsSaving",2);b([w()],y.prototype,"execApprovalsDirty",2);b([w()],y.prototype,"execApprovalsSnapshot",2);b([w()],y.prototype,"execApprovalsForm",2);b([w()],y.prototype,"execApprovalsSelectedAgent",2);b([w()],y.prototype,"execApprovalsTarget",2);b([w()],y.prototype,"execApprovalsTargetNodeId",2);b([w()],y.prototype,"execApprovalQueue",2);b([w()],y.prototype,"execApprovalBusy",2);b([w()],y.prototype,"execApprovalError",2);b([w()],y.prototype,"pendingGatewayUrl",2);b([w()],y.prototype,"configLoading",2);b([w()],y.prototype,"configRaw",2);b([w()],y.prototype,"configRawOriginal",2);b([w()],y.prototype,"configValid",2);b([w()],y.prototype,"configIssues",2);b([w()],y.prototype,"configSaving",2);b([w()],y.prototype,"configApplying",2);b([w()],y.prototype,"updateRunning",2);b([w()],y.prototype,"applySessionKey",2);b([w()],y.prototype,"configSnapshot",2);b([w()],y.prototype,"configSchema",2);b([w()],y.prototype,"configSchemaVersion",2);b([w()],y.prototype,"configSchemaLoading",2);b([w()],y.prototype,"configUiHints",2);b([w()],y.prototype,"configForm",2);b([w()],y.prototype,"configFormOriginal",2);b([w()],y.prototype,"configFormDirty",2);b([w()],y.prototype,"configFormMode",2);b([w()],y.prototype,"configSearchQuery",2);b([w()],y.prototype,"configActiveSection",2);b([w()],y.prototype,"configActiveSubsection",2);b([w()],y.prototype,"channelsLoading",2);b([w()],y.prototype,"channelsSnapshot",2);b([w()],y.prototype,"channelsError",2);b([w()],y.prototype,"channelsLastSuccess",2);b([w()],y.prototype,"whatsappLoginMessage",2);b([w()],y.prototype,"whatsappLoginQrDataUrl",2);b([w()],y.prototype,"whatsappLoginConnected",2);b([w()],y.prototype,"whatsappBusy",2);b([w()],y.prototype,"nostrProfileFormState",2);b([w()],y.prototype,"nostrProfileAccountId",2);b([w()],y.prototype,"presenceLoading",2);b([w()],y.prototype,"presenceEntries",2);b([w()],y.prototype,"presenceError",2);b([w()],y.prototype,"presenceStatus",2);b([w()],y.prototype,"agentsLoading",2);b([w()],y.prototype,"agentsList",2);b([w()],y.prototype,"agentsError",2);b([w()],y.prototype,"sessionsLoading",2);b([w()],y.prototype,"sessionsResult",2);b([w()],y.prototype,"sessionsError",2);b([w()],y.prototype,"sessionsFilterActive",2);b([w()],y.prototype,"sessionsFilterLimit",2);b([w()],y.prototype,"sessionsIncludeGlobal",2);b([w()],y.prototype,"sessionsIncludeUnknown",2);b([w()],y.prototype,"archivedSessions",2);b([w()],y.prototype,"archivedSessionsLoading",2);b([w()],y.prototype,"archivedSessionsExpanded",2);b([w()],y.prototype,"cronLoading",2);b([w()],y.prototype,"cronJobs",2);b([w()],y.prototype,"cronStatus",2);b([w()],y.prototype,"cronError",2);b([w()],y.prototype,"cronForm",2);b([w()],y.prototype,"cronRunsJobId",2);b([w()],y.prototype,"cronRuns",2);b([w()],y.prototype,"cronBusy",2);b([w()],y.prototype,"workspaceNeedsSetup",2);b([w()],y.prototype,"onboardingPhase",2);b([w()],y.prototype,"onboardingData",2);b([w()],y.prototype,"onboardingActive",2);b([w()],y.prototype,"wizardActive",2);b([w()],y.prototype,"wizardState",2);b([w()],y.prototype,"showSetupTab",2);b([w()],y.prototype,"setupChecklist",2);b([w()],y.prototype,"setupChecklistLoading",2);b([w()],y.prototype,"setupQuickDone",2);b([w()],y.prototype,"onboardingIntegrations",2);b([w()],y.prototype,"onboardingCoreProgress",2);b([w()],y.prototype,"onboardingExpandedCard",2);b([w()],y.prototype,"onboardingLoadingGuide",2);b([w()],y.prototype,"onboardingActiveGuide",2);b([w()],y.prototype,"onboardingTestingId",2);b([w()],y.prototype,"onboardingTestResult",2);b([w()],y.prototype,"onboardingConfigValues",2);b([w()],y.prototype,"onboardingProgress",2);b([w()],y.prototype,"workspaces",2);b([w()],y.prototype,"selectedWorkspace",2);b([w()],y.prototype,"workspacesSearchQuery",2);b([w()],y.prototype,"workspaceItemSearchQuery",2);b([w()],y.prototype,"workspacesLoading",2);b([w()],y.prototype,"workspacesCreateLoading",2);b([w()],y.prototype,"workspacesError",2);b([w()],y.prototype,"workspaceExpandedFolders",2);b([w()],y.prototype,"allTasks",2);b([w()],y.prototype,"taskFilter",2);b([w()],y.prototype,"taskSort",2);b([w()],y.prototype,"showCompletedTasks",2);b([w()],y.prototype,"editingTaskId",2);b([w()],y.prototype,"workspaceBrowsePath",2);b([w()],y.prototype,"workspaceBrowseEntries",2);b([w()],y.prototype,"workspaceBreadcrumbs",2);b([w()],y.prototype,"workspaceBrowseSearchQuery",2);b([w()],y.prototype,"workspaceBrowseSearchResults",2);b([w()],y.prototype,"myDayLoading",2);b([w()],y.prototype,"myDayError",2);b([w()],y.prototype,"todaySelectedDate",2);b([w()],y.prototype,"todayViewMode",2);b([w()],y.prototype,"dailyBrief",2);b([w()],y.prototype,"dailyBriefLoading",2);b([w()],y.prototype,"dailyBriefError",2);b([w()],y.prototype,"agentLog",2);b([w()],y.prototype,"agentLogLoading",2);b([w()],y.prototype,"agentLogError",2);b([w()],y.prototype,"briefNotes",2);b([w()],y.prototype,"todayTasks",2);b([w()],y.prototype,"todayTasksLoading",2);b([w()],y.prototype,"todayEditingTaskId",2);b([w()],y.prototype,"todayShowCompleted",2);b([w()],y.prototype,"allyPanelOpen",2);b([w()],y.prototype,"allyMessages",2);b([w()],y.prototype,"allyStream",2);b([w()],y.prototype,"allyDraft",2);b([w()],y.prototype,"allyUnread",2);b([w()],y.prototype,"allySending",2);b([w()],y.prototype,"allyWorking",2);b([w()],y.prototype,"allyAttachments",2);b([w()],y.prototype,"todayQueueResults",2);b([w()],y.prototype,"chatPrivateMode",2);b([w()],y.prototype,"privateSessions",2);b([w()],y.prototype,"goals",2);b([w()],y.prototype,"goalsLoading",2);b([w()],y.prototype,"goalsError",2);b([w()],y.prototype,"dataSources",2);b([w()],y.prototype,"dataLoading",2);b([w()],y.prototype,"dataError",2);b([w()],y.prototype,"dataSubtab",2);b([w()],y.prototype,"dynamicSlots",2);b([w()],y.prototype,"workProjects",2);b([w()],y.prototype,"workLoading",2);b([w()],y.prototype,"workError",2);b([w()],y.prototype,"workExpandedProjects",2);b([w()],y.prototype,"workProjectFiles",2);b([w()],y.prototype,"workDetailLoading",2);b([w()],y.prototype,"skillsLoading",2);b([w()],y.prototype,"skillsReport",2);b([w()],y.prototype,"skillsError",2);b([w()],y.prototype,"skillsFilter",2);b([w()],y.prototype,"skillEdits",2);b([w()],y.prototype,"skillsBusyKey",2);b([w()],y.prototype,"skillMessages",2);b([w()],y.prototype,"debugLoading",2);b([w()],y.prototype,"debugStatus",2);b([w()],y.prototype,"debugHealth",2);b([w()],y.prototype,"debugModels",2);b([w()],y.prototype,"debugHeartbeat",2);b([w()],y.prototype,"debugCallMethod",2);b([w()],y.prototype,"debugCallParams",2);b([w()],y.prototype,"debugCallResult",2);b([w()],y.prototype,"debugCallError",2);b([w()],y.prototype,"logsLoading",2);b([w()],y.prototype,"logsError",2);b([w()],y.prototype,"logsFile",2);b([w()],y.prototype,"logsEntries",2);b([w()],y.prototype,"logsFilterText",2);b([w()],y.prototype,"logsLevelFilters",2);b([w()],y.prototype,"logsAutoFollow",2);b([w()],y.prototype,"logsTruncated",2);b([w()],y.prototype,"logsCursor",2);b([w()],y.prototype,"logsLastFetchAt",2);b([w()],y.prototype,"logsLimit",2);b([w()],y.prototype,"logsMaxBytes",2);b([w()],y.prototype,"logsAtBottom",2);b([w()],y.prototype,"toasts",2);b([w()],y.prototype,"chatUserNearBottom",2);b([w()],y.prototype,"chatNewMessagesBelow",2);b([w()],y.prototype,"consciousnessStatus",2);b([w()],y.prototype,"focusPulseData",2);b([w()],y.prototype,"trustTrackerData",2);b([w()],y.prototype,"trustTrackerLoading",2);b([w()],y.prototype,"guardrailsData",2);b([w()],y.prototype,"guardrailsLoading",2);b([w()],y.prototype,"guardrailsShowAddForm",2);b([w()],y.prototype,"missionControlData",2);b([w()],y.prototype,"missionControlLoading",2);b([w()],y.prototype,"missionControlError",2);b([w()],y.prototype,"missionControlFullControl",2);b([w()],y.prototype,"godmodeOptions",2);b([w()],y.prototype,"godmodeOptionsLoading",2);b([w()],y.prototype,"dashboardsList",2);b([w()],y.prototype,"dashboardsLoading",2);b([w()],y.prototype,"dashboardsError",2);b([w()],y.prototype,"activeDashboardId",2);b([w()],y.prototype,"activeDashboardHtml",2);b([w()],y.prototype,"activeDashboardManifest",2);b([w()],y.prototype,"dashboardChatOpen",2);b([w()],y.prototype,"secondBrainSubtab",2);b([w()],y.prototype,"secondBrainLoading",2);b([w()],y.prototype,"secondBrainError",2);b([w()],y.prototype,"secondBrainIdentity",2);b([w()],y.prototype,"secondBrainMemoryBank",2);b([w()],y.prototype,"secondBrainAiPacket",2);b([w()],y.prototype,"secondBrainSourcesData",2);b([w()],y.prototype,"secondBrainResearchData",2);b([w()],y.prototype,"secondBrainResearchAddFormOpen",2);b([w()],y.prototype,"secondBrainResearchAddForm",2);b([w()],y.prototype,"secondBrainResearchCategories",2);b([w()],y.prototype,"secondBrainSelectedEntry",2);b([w()],y.prototype,"secondBrainSearchQuery",2);b([w()],y.prototype,"secondBrainSyncing",2);b([w()],y.prototype,"secondBrainBrowsingFolder",2);b([w()],y.prototype,"secondBrainFolderEntries",2);b([w()],y.prototype,"secondBrainFolderName",2);b([w()],y.prototype,"secondBrainFileTree",2);b([w()],y.prototype,"secondBrainFileTreeLoading",2);b([w()],y.prototype,"secondBrainFileSearchQuery",2);b([w()],y.prototype,"secondBrainFileSearchResults",2);y=b([kc("godmode-app")],y);