(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function s(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();const Et=globalThis,Pn=Et.ShadowRoot&&(Et.ShadyCSS===void 0||Et.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Fn=Symbol(),As=new WeakMap;let fi=class{constructor(t,n,s){if(this._$cssResult$=!0,s!==Fn)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(Pn&&t===void 0){const s=n!==void 0&&n.length===1;s&&(t=As.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&As.set(n,t))}return t}toString(){return this.cssText}};const ma=e=>new fi(typeof e=="string"?e:e+"",void 0,Fn),ba=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((s,i,a)=>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.")})(i)+e[a+1],e[0]);return new fi(n,e,Fn)},va=(e,t)=>{if(Pn)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const s=document.createElement("style"),i=Et.litNonce;i!==void 0&&s.setAttribute("nonce",i),s.textContent=n.cssText,e.appendChild(s)}},Ts=Pn?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const s of t.cssRules)n+=s.cssText;return ma(n)})(e):e;const{is:ya,defineProperty:ka,getOwnPropertyDescriptor:$a,getOwnPropertyNames:wa,getOwnPropertySymbols:Sa,getPrototypeOf:xa}=Object,Ot=globalThis,Cs=Ot.trustedTypes,Aa=Cs?Cs.emptyScript:"",Ta=Ot.reactiveElementPolyfillSupport,nt=(e,t)=>e,Lt={toAttribute(e,t){switch(t){case Boolean:e=e?Aa: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}},Nn=(e,t)=>!ya(e,t),Es={attribute:!0,type:String,converter:Lt,reflect:!1,useDefault:!1,hasChanged:Nn};Symbol.metadata??=Symbol("metadata"),Ot.litPropertyMetadata??=new WeakMap;let Pe=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=Es){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(),i=this.getPropertyDescriptor(t,s,n);i!==void 0&&ka(this.prototype,t,i)}}static getPropertyDescriptor(t,n,s){const{get:i,set:a}=$a(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:i,set(o){const l=i?.call(this);a?.call(this,o),this.requestUpdate(t,l,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Es}static _$Ei(){if(this.hasOwnProperty(nt("elementProperties")))return;const t=xa(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(nt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(nt("properties"))){const n=this.properties,s=[...wa(n),...Sa(n)];for(const i of s)this.createProperty(i,n[i])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[s,i]of n)this.elementProperties.set(s,i)}this._$Eh=new Map;for(const[n,s]of this.elementProperties){const i=this._$Eu(n,s);i!==void 0&&this._$Eh.set(i,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 i of s)n.unshift(Ts(i))}else t!==void 0&&n.push(Ts(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 va(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),i=this.constructor._$Eu(t,s);if(i!==void 0&&s.reflect===!0){const a=(s.converter?.toAttribute!==void 0?s.converter:Lt).toAttribute(n,s.type);this._$Em=t,a==null?this.removeAttribute(i):this.setAttribute(i,a),this._$Em=null}}_$AK(t,n){const s=this.constructor,i=s._$Eh.get(t);if(i!==void 0&&this._$Em!==i){const a=s.getPropertyOptions(i),o=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:Lt;this._$Em=i;const l=o.fromAttribute(n,a.type);this[i]=l??this._$Ej?.get(i)??l,this._$Em=null}}requestUpdate(t,n,s,i=!1,a){if(t!==void 0){const o=this.constructor;if(i===!1&&(a=this[t]),s??=o.getPropertyOptions(t),!((s.hasChanged??Nn)(a,n)||s.useDefault&&s.reflect&&a===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:i,wrapped:a},o){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??n??this[t]),a!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(n=void 0),this._$AL.set(t,n)),i===!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[i,a]of this._$Ep)this[i]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[i,a]of s){const{wrapped:o}=a,l=this[i];o!==!0||this._$AL.has(i)||l===void 0||this.C(i,void 0,a,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){}};Pe.elementStyles=[],Pe.shadowRootOptions={mode:"open"},Pe[nt("elementProperties")]=new Map,Pe[nt("finalized")]=new Map,Ta?.({ReactiveElement:Pe}),(Ot.reactiveElementVersions??=[]).push("2.1.2");const On=globalThis,_s=e=>e,Rt=On.trustedTypes,Ms=Rt?Rt.createPolicy("lit-html",{createHTML:e=>e}):void 0,mi="$lit$",fe=`lit$${Math.random().toFixed(9).slice(2)}$`,bi="?"+fe,Ca=`<${bi}>`,Se=document,lt=()=>Se.createComment(""),rt=e=>e===null||typeof e!="object"&&typeof e!="function",Dn=Array.isArray,Ea=e=>Dn(e)||typeof e?.[Symbol.iterator]=="function",dn=`[ \f\r]`,We=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ls=/-->/g,Rs=/>/g,ke=RegExp(`>|${dn}(?:([^\\s"'>=/]+)(${dn}*=${dn}*(?:[^ \f\r"'\`<>=]|("|')|))|$)`,"g"),Is=/'/g,Ps=/"/g,vi=/^(?:script|style|textarea|title)$/i,_a=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),h=_a(1),me=Symbol.for("lit-noChange"),g=Symbol.for("lit-nothing"),Fs=new WeakMap,we=Se.createTreeWalker(Se,129);function yi(e,t){if(!Dn(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ms!==void 0?Ms.createHTML(t):t}const Ma=(e,t)=>{const n=e.length-1,s=[];let i,a=t===2?"":t===3?"":"",o=We;for(let l=0;l"?(o=i??We,p=-1):c[1]===void 0?p=-2:(p=o.lastIndex-c[2].length,d=c[1],o=c[3]===void 0?ke:c[3]==='"'?Ps:Is):o===Ps||o===Is?o=ke:o===Ls||o===Rs?o=We:(o=ke,i=void 0);const w=o===ke&&e[l+1].startsWith("/>")?" ":"";a+=o===We?r+Ca:p>=0?(s.push(d),r.slice(0,p)+mi+r.slice(p)+fe+w):r+fe+(p===-2?l:w)}return[yi(e,a+(e[n]||"")+(t===2?"":t===3?"":"")),s]};let kn=class ki{constructor({strings:t,_$litType$:n},s){let i;this.parts=[];let a=0,o=0;const l=t.length-1,r=this.parts,[d,c]=Ma(t,n);if(this.el=ki.createElement(d,s),we.currentNode=this.el.content,n===2||n===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(i=we.nextNode())!==null&&r.length0){i.textContent=Rt?Rt.emptyScript:"";for(let w=0;w2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=g}_$AI(t,n=this,s,i){const a=this.strings;let o=!1;if(a===void 0)t=Oe(this,t,n,0),o=!rt(t)||t!==this._$AH&&t!==me,o&&(this._$AH=t);else{const l=t;let r,d;for(t=a[0],r=0;r{const s=n?.renderBefore??t;let i=s._$litPart$;if(i===void 0){const a=n?.renderBefore??null;s._$litPart$=i=new Dt(t.insertBefore(lt(),a),a,void 0,n??{})}return i._$AI(e),i};const Un=globalThis;let Fe=class extends Pe{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=Da(n,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return me}};Fe._$litElement$=!0,Fe.finalized=!0,Un.litElementHydrateSupport?.({LitElement:Fe});const Ua=Un.litElementPolyfillSupport;Ua?.({LitElement:Fe});(Un.litElementVersions??=[]).push("4.2.2");const wi=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Ba={attribute:!0,type:String,converter:Lt,reflect:!1,hasChanged:Nn},Ka=(e=Ba,t,n)=>{const{kind:s,metadata:i}=n;let a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),s==="accessor"){const{name:o}=n;return{set(l){const r=t.get.call(this);t.set.call(this,l),this.requestUpdate(o,r,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 r=this[o];t.call(this,l),this.requestUpdate(o,r,e,!0,l)}}throw Error("Unsupported decorator location: "+s)};function Bt(e){return(t,n)=>typeof n=="object"?Ka(e,t,n):((s,i,a)=>{const o=i.hasOwnProperty(a);return i.constructor.createProperty(a,s),o?Object.getOwnPropertyDescriptor(i,a):void 0})(e,t,n)}function b(e){return Bt({...e,state:!0,attribute:!1})}function Ns(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n>>8&255,e[2]^=t>>>16&255,e[3]^=t>>>24&255,e}function Bn(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),Ns(t)}return Ns(Ha())}class ja{constructor(t){this.opts=t,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=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.onopen=()=>this.sendConnect(),this.ws.onmessage=t=>this.handleMessage(String(t.data??"")),this.ws.onclose=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.onerror=()=>{})}scheduleReconnect(){if(this.closed)return;const t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),t)}flushPending(t){for(const[,n]of this.pending)n.reject(t);this.pending.clear()}sendConnect(){const t=this.opts.token||this.opts.password?{token:this.opts.token,password:this.opts.password}:void 0,n={minProtocol:2,maxProtocol:2,client:{name:this.opts.clientName??"clawdbot-control-ui",version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??"webchat",instanceId:this.opts.instanceId},caps:[],auth:t,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",n).then(s=>{this.backoffMs=800,this.opts.onHello?.(s)}).catch(()=>{this.ws?.close(1008,"connect failed")})}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;if(s.type==="event"){const i=n,a=typeof i.seq=="number"?i.seq:null;a!==null&&(this.lastSeq!==null&&a>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:a}),this.lastSeq=a),this.opts.onEvent?.(i);return}if(s.type==="res"){const i=n,a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),i.ok?a.resolve(i.payload):a.reject(new Error(i.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=Bn(),i={type:"req",id:s,method:t,params:n},a=new Promise((o,l)=>{this.pending.set(s,{resolve:r=>o(r),reject:l})});return this.ws.send(JSON.stringify(i)),a}}const Si="clawdbot.control.settings.v1";function za(){const t={gatewayUrl:`${location.protocol==="https:"?"wss":"ws"}://${location.host}`,token:"",sessionKey:"main",lastActiveSessionKey:"main",theme:"system",chatFocusMode:!1,splitRatio:.6,useNewChatLayout:!0,navCollapsed:!1,navGroupsCollapsed:{}};try{const n=localStorage.getItem(Si);if(!n)return t;const s=JSON.parse(n);return{gatewayUrl:typeof s.gatewayUrl=="string"&&s.gatewayUrl.trim()?s.gatewayUrl.trim():t.gatewayUrl,token:typeof s.token=="string"?s.token:t.token,sessionKey:typeof s.sessionKey=="string"&&s.sessionKey.trim()?s.sessionKey.trim():t.sessionKey,lastActiveSessionKey:typeof s.lastActiveSessionKey=="string"&&s.lastActiveSessionKey.trim()?s.lastActiveSessionKey.trim():typeof s.sessionKey=="string"&&s.sessionKey.trim()||t.lastActiveSessionKey,theme:s.theme==="light"||s.theme==="dark"||s.theme==="system"?s.theme:t.theme,chatFocusMode:typeof s.chatFocusMode=="boolean"?s.chatFocusMode:t.chatFocusMode,splitRatio:typeof s.splitRatio=="number"&&s.splitRatio>=.4&&s.splitRatio<=.7?s.splitRatio:t.splitRatio,useNewChatLayout:typeof s.useNewChatLayout=="boolean"?s.useNewChatLayout:t.useNewChatLayout,navCollapsed:typeof s.navCollapsed=="boolean"?s.navCollapsed:t.navCollapsed,navGroupsCollapsed:typeof s.navGroupsCollapsed=="object"&&s.navGroupsCollapsed!==null?s.navGroupsCollapsed:t.navGroupsCollapsed}}catch{return t}}function qa(e){localStorage.setItem(Si,JSON.stringify(e))}const Wa=[{label:"Chat",tabs:["chat"]},{label:"Control",tabs:["overview","connections","instances","sessions","cron"]},{label:"Agent",tabs:["skills","nodes"]},{label:"Settings",tabs:["config","debug","logs"]}],xi={overview:"/overview",connections:"/connections",instances:"/instances",sessions:"/sessions",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",config:"/config",debug:"/debug",logs:"/logs"},Ai=new Map(Object.entries(xi).map(([e,t])=>[t,e]));function Kn(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function ct(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 Hn(e,t=""){const n=Kn(t),s=xi[e];return n?`${n}${s}`:s}function Os(e,t=""){const n=Kn(t);let s=e||"/";n&&(s===n?s="/":s.startsWith(`${n}/`)&&(s=s.slice(n.length)));let i=ct(s).toLowerCase();return i.endsWith("/index.html")&&(i="/"),i==="/"?"chat":Ai.get(i)??null}function Ga(e){let t=ct(e);if(t.endsWith("/index.html")&&(t=ct(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let s=0;s(...t)=>({_$litDirective$:e,values:t});let Ei=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)}};const{I:Ja}=Na,Ds=e=>e,Us=()=>document.createComment(""),Ge=(e,t,n)=>{const s=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0){const a=s.insertBefore(Us(),i),o=s.insertBefore(Us(),i);n=new Ja(a,o,e,e.options)}else{const a=n._$AB.nextSibling,o=n._$AM,l=o!==e;if(l){let r;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(r=e._$AU)!==o._$AU&&n._$AP(r)}if(a!==i||l){let r=n._$AA;for(;r!==a;){const d=Ds(r).nextSibling;Ds(s).insertBefore(r,i),r=d}}}return n},$e=(e,t,n=e)=>(e._$AI(t,n),e),Qa={},Xa=(e,t=Qa)=>e._$AH=t,Za=e=>e._$AH,un=e=>{e._$AR(),e._$AA.remove()};const Bs=(e,t,n)=>{const s=new Map;for(let i=t;i<=n;i++)s.set(e[i],i);return s},eo=Ci(class extends Ei{constructor(e){if(super(e),e.type!==Ti.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 i=[],a=[];let o=0;for(const l of e)i[o]=s?s(l,o):o,a[o]=n(l,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,s]){const i=Za(e),{values:a,keys:o}=this.dt(t,n,s);if(!Array.isArray(i))return this.ut=o,a;const l=this.ut??=[],r=[];let d,c,p=0,v=i.length-1,w=0,y=a.length-1;for(;p<=v&&w<=y;)if(i[p]===null)p++;else if(i[v]===null)v--;else if(l[p]===o[w])r[w]=$e(i[p],a[w]),p++,w++;else if(l[v]===o[y])r[y]=$e(i[v],a[y]),v--,y--;else if(l[p]===o[y])r[y]=$e(i[p],a[y]),Ge(e,r[y+1],i[p]),p++,y--;else if(l[v]===o[w])r[w]=$e(i[v],a[w]),Ge(e,i[p],i[v]),v--,w++;else if(d===void 0&&(d=Bs(o,w,y),c=Bs(l,p,v)),d.has(l[p]))if(d.has(l[v])){const $=c.get(o[w]),T=$!==void 0?i[$]:null;if(T===null){const S=Ge(e,i[p]);$e(S,a[w]),r[w]=S}else r[w]=$e(T,a[w]),Ge(e,i[p],T),i[$]=null;w++}else un(i[v]),v--;else un(i[p]),p++;for(;w<=y;){const $=Ge(e,r[y+1]);$e($,a[w]),r[w++]=$}for(;p<=v;){const $=i[p++];$!==null&&un($)}return this.ut=o,Xa(e,r),me}});function to(e){const t=e;let n=typeof t.role=="string"?t.role:"unknown";(typeof t.toolCallId=="string"||typeof t.tool_call_id=="string")&&(n="toolResult");let s=[];typeof t.content=="string"?s=[{type:"text",text:t.content}]:Array.isArray(t.content)?s=t.content.map(o=>({type:o.type||"text",text:o.text,name:o.name,args:o.args||o.arguments})):typeof t.text=="string"&&(s=[{type:"text",text:t.text}]);const i=typeof t.timestamp=="number"?t.timestamp:Date.now(),a=typeof t.id=="string"?t.id:void 0;return{role:n,content:s,timestamp:i,id:a}}function Kt(e){const t=e.toLowerCase();return t==="toolresult"||t==="tool_result"||t==="tool"||t==="function"?"assistant":e}function jn(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}function dt(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString()}function W(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 i=Math.round(s/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function _i(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 no(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}โ€ฆ`}function Mi(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 It(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function pe(e){return e.split(/[,\n]/).map(t=>t.trim()).filter(t=>t.length>0)}const hn=/<\s*\/?\s*think(?:ing)?\s*>/gi,Ks=/<\s*think(?:ing)?\s*>/i,Hs=/<\s*\/\s*think(?:ing)?\s*>/i;function Ne(e){if(!e)return e;const t=Ks.test(e),n=Hs.test(e);if(!t&&!n)return e;if(t!==n)return t?e.replace(Ks,"").trimStart():e.replace(Hs,"").trimStart();if(!hn.test(e))return e;hn.lastIndex=0;let s="",i=0,a=!1;for(const o of e.matchAll(hn)){const l=o.index??0;a||(s+=e.slice(i,l)),a=!o[0].toLowerCase().includes("/"),i=l+o[0].length}return a||(s+=e.slice(i)),s.trimStart()}function Ht(e){const t=e,n=typeof t.role=="string"?t.role:"",s=t.content;if(typeof s=="string")return n==="assistant"?Ne(s):s;if(Array.isArray(s)){const i=s.map(a=>{const o=a;return o.type==="text"&&typeof o.text=="string"?o.text:null}).filter(a=>typeof a=="string");if(i.length>0){const a=i.join(` `);return n==="assistant"?Ne(a):a}}return typeof t.text=="string"?n==="assistant"?Ne(t.text):t.text:null}function Li(e){const n=e.content,s=[];if(Array.isArray(n))for(const l of n){const r=l;if(r.type==="thinking"&&typeof r.thinking=="string"){const d=r.thinking.trim();d&&s.push(d)}}if(s.length>0)return s.join(` `);const i=so(e);if(!i)return null;const o=[...i.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(` `):null}function so(e){const t=e,n=t.content;if(typeof n=="string")return n;if(Array.isArray(n)){const s=n.map(i=>{const a=i;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(i=>typeof i=="string");if(s.length>0)return s.join(` `)}return typeof t.text=="string"?t.text:null}function Ri(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(` `):""}class wn extends Ei{constructor(t){if(super(t),this.it=g,t.type!==Ti.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===g||t==null)return this._t=void 0,this.it=t;if(t===me)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:[]}}}wn.directiveName="unsafeHTML",wn.resultType=1;const jt=Ci(wn);const{entries:Ii,setPrototypeOf:js,isFrozen:io,getPrototypeOf:ao,getOwnPropertyDescriptor:oo}=Object;let{freeze:Q,seal:ee,create:Sn}=Object,{apply:xn,construct:An}=typeof Reflect<"u"&&Reflect;Q||(Q=function(t){return t});ee||(ee=function(t){return t});xn||(xn=function(t,n){for(var s=arguments.length,i=new Array(s>2?s-2:0),a=2;a1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:_t;js&&js(e,null);let s=t.length;for(;s--;){let i=t[s];if(typeof i=="string"){const a=n(i);a!==i&&(io(t)||(t[s]=a),i=a)}e[i]=!0}return e}function po(e){for(let t=0;t/gm),vo=ee(/\$\{[\w\W]*/gm),yo=ee(/^data-[\-\w.\u00B7-\uFFFF]+$/),ko=ee(/^aria-[\-\w]+$/),Pi=ee(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),$o=ee(/^(?:\w+script|data):/i),wo=ee(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Fi=ee(/^html$/i),So=ee(/^[a-z][.\w]*(-[.\w]+)+$/i);var Vs=Object.freeze({__proto__:null,ARIA_ATTR:ko,ATTR_WHITESPACE:wo,CUSTOM_ELEMENT:So,DATA_ATTR:yo,DOCTYPE_NAME:Fi,ERB_EXPR:bo,IS_ALLOWED_URI:Pi,IS_SCRIPT_OR_DATA:$o,MUSTACHE_EXPR:mo,TMPLIT_EXPR:vo});const Xe={element:1,text:3,progressingInstruction:7,comment:8,document:9},xo=function(){return typeof window>"u"?null:window},Ao=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(s=n.getAttribute(i));const a="dompurify"+(s?"#"+s:"");try{return t.createPolicy(a,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Js=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ni(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xo();const t=A=>Ni(A);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==Xe.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const s=n,i=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:l,Element:r,NodeFilter:d,NamedNodeMap:c=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:v,trustedTypes:w}=e,y=r.prototype,$=Qe(y,"cloneNode"),T=Qe(y,"remove"),S=Qe(y,"nextSibling"),E=Qe(y,"childNodes"),N=Qe(y,"parentNode");if(typeof o=="function"){const A=n.createElement("template");A.content&&A.content.ownerDocument&&(n=A.content.ownerDocument)}let R,C="";const{implementation:I,createNodeIterator:Y,createDocumentFragment:H,getElementsByTagName:F}=n,{importNode:M}=s;let D=Js();t.isSupported=typeof Ii=="function"&&typeof N=="function"&&I&&I.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Ke,ERB_EXPR:He,TMPLIT_EXPR:be,DATA_ATTR:Te,ARIA_ATTR:aa,IS_SCRIPT_OR_DATA:oa,ATTR_WHITESPACE:ts,CUSTOM_ELEMENT:la}=Vs;let{IS_ALLOWED_URI:ns}=Vs,j=null;const ss=_({},[...qs,...fn,...mn,...bn,...Ws]);let z=null;const is=_({},[...Gs,...vn,...Ys,...xt]);let U=Object.seal(Sn(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}})),je=null,Qt=null;const Ce=Object.seal(Sn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let as=!0,Xt=!0,os=!1,ls=!0,Ee=!1,mt=!0,ve=!1,Zt=!1,en=!1,_e=!1,bt=!1,vt=!1,rs=!0,cs=!1;const ra="user-content-";let tn=!0,ze=!1,Me={},ae=null;const nn=_({},["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 ds=null;const us=_({},["audio","video","img","source","image","track"]);let sn=null;const hs=_({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),yt="http://www.w3.org/1998/Math/MathML",kt="http://www.w3.org/2000/svg",ce="http://www.w3.org/1999/xhtml";let Le=ce,an=!1,on=null;const ca=_({},[yt,kt,ce],pn);let $t=_({},["mi","mo","mn","ms","mtext"]),wt=_({},["annotation-xml"]);const da=_({},["title","style","font","a","script"]);let qe=null;const ua=["application/xhtml+xml","text/html"],ha="text/html";let K=null,Re=null;const pa=n.createElement("form"),ps=function(u){return u instanceof RegExp||u instanceof Function},ln=function(){let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Re&&Re===u)){if((!u||typeof u!="object")&&(u={}),u=le(u),qe=ua.indexOf(u.PARSER_MEDIA_TYPE)===-1?ha:u.PARSER_MEDIA_TYPE,K=qe==="application/xhtml+xml"?pn:_t,j=ne(u,"ALLOWED_TAGS")?_({},u.ALLOWED_TAGS,K):ss,z=ne(u,"ALLOWED_ATTR")?_({},u.ALLOWED_ATTR,K):is,on=ne(u,"ALLOWED_NAMESPACES")?_({},u.ALLOWED_NAMESPACES,pn):ca,sn=ne(u,"ADD_URI_SAFE_ATTR")?_(le(hs),u.ADD_URI_SAFE_ATTR,K):hs,ds=ne(u,"ADD_DATA_URI_TAGS")?_(le(us),u.ADD_DATA_URI_TAGS,K):us,ae=ne(u,"FORBID_CONTENTS")?_({},u.FORBID_CONTENTS,K):nn,je=ne(u,"FORBID_TAGS")?_({},u.FORBID_TAGS,K):le({}),Qt=ne(u,"FORBID_ATTR")?_({},u.FORBID_ATTR,K):le({}),Me=ne(u,"USE_PROFILES")?u.USE_PROFILES:!1,as=u.ALLOW_ARIA_ATTR!==!1,Xt=u.ALLOW_DATA_ATTR!==!1,os=u.ALLOW_UNKNOWN_PROTOCOLS||!1,ls=u.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ee=u.SAFE_FOR_TEMPLATES||!1,mt=u.SAFE_FOR_XML!==!1,ve=u.WHOLE_DOCUMENT||!1,_e=u.RETURN_DOM||!1,bt=u.RETURN_DOM_FRAGMENT||!1,vt=u.RETURN_TRUSTED_TYPE||!1,en=u.FORCE_BODY||!1,rs=u.SANITIZE_DOM!==!1,cs=u.SANITIZE_NAMED_PROPS||!1,tn=u.KEEP_CONTENT!==!1,ze=u.IN_PLACE||!1,ns=u.ALLOWED_URI_REGEXP||Pi,Le=u.NAMESPACE||ce,$t=u.MATHML_TEXT_INTEGRATION_POINTS||$t,wt=u.HTML_INTEGRATION_POINTS||wt,U=u.CUSTOM_ELEMENT_HANDLING||{},u.CUSTOM_ELEMENT_HANDLING&&ps(u.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(U.tagNameCheck=u.CUSTOM_ELEMENT_HANDLING.tagNameCheck),u.CUSTOM_ELEMENT_HANDLING&&ps(u.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(U.attributeNameCheck=u.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),u.CUSTOM_ELEMENT_HANDLING&&typeof u.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(U.allowCustomizedBuiltInElements=u.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ee&&(Xt=!1),bt&&(_e=!0),Me&&(j=_({},Ws),z=[],Me.html===!0&&(_(j,qs),_(z,Gs)),Me.svg===!0&&(_(j,fn),_(z,vn),_(z,xt)),Me.svgFilters===!0&&(_(j,mn),_(z,vn),_(z,xt)),Me.mathMl===!0&&(_(j,bn),_(z,Ys),_(z,xt))),u.ADD_TAGS&&(typeof u.ADD_TAGS=="function"?Ce.tagCheck=u.ADD_TAGS:(j===ss&&(j=le(j)),_(j,u.ADD_TAGS,K))),u.ADD_ATTR&&(typeof u.ADD_ATTR=="function"?Ce.attributeCheck=u.ADD_ATTR:(z===is&&(z=le(z)),_(z,u.ADD_ATTR,K))),u.ADD_URI_SAFE_ATTR&&_(sn,u.ADD_URI_SAFE_ATTR,K),u.FORBID_CONTENTS&&(ae===nn&&(ae=le(ae)),_(ae,u.FORBID_CONTENTS,K)),u.ADD_FORBID_CONTENTS&&(ae===nn&&(ae=le(ae)),_(ae,u.ADD_FORBID_CONTENTS,K)),tn&&(j["#text"]=!0),ve&&_(j,["html","head","body"]),j.table&&(_(j,["tbody"]),delete je.tbody),u.TRUSTED_TYPES_POLICY){if(typeof u.TRUSTED_TYPES_POLICY.createHTML!="function")throw Je('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof u.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Je('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');R=u.TRUSTED_TYPES_POLICY,C=R.createHTML("")}else R===void 0&&(R=Ao(w,i)),R!==null&&typeof C=="string"&&(C=R.createHTML(""));Q&&Q(u),Re=u}},gs=_({},[...fn,...mn,...go]),fs=_({},[...bn,...fo]),ga=function(u){let k=N(u);(!k||!k.tagName)&&(k={namespaceURI:Le,tagName:"template"});const x=_t(u.tagName),O=_t(k.tagName);return on[u.namespaceURI]?u.namespaceURI===kt?k.namespaceURI===ce?x==="svg":k.namespaceURI===yt?x==="svg"&&(O==="annotation-xml"||$t[O]):!!gs[x]:u.namespaceURI===yt?k.namespaceURI===ce?x==="math":k.namespaceURI===kt?x==="math"&&wt[O]:!!fs[x]:u.namespaceURI===ce?k.namespaceURI===kt&&!wt[O]||k.namespaceURI===yt&&!$t[O]?!1:!fs[x]&&(da[x]||!gs[x]):!!(qe==="application/xhtml+xml"&&on[u.namespaceURI]):!1},oe=function(u){Ye(t.removed,{element:u});try{N(u).removeChild(u)}catch{T(u)}},ye=function(u,k){try{Ye(t.removed,{attribute:k.getAttributeNode(u),from:k})}catch{Ye(t.removed,{attribute:null,from:k})}if(k.removeAttribute(u),u==="is")if(_e||bt)try{oe(k)}catch{}else try{k.setAttribute(u,"")}catch{}},ms=function(u){let k=null,x=null;if(en)u=""+u;else{const B=gn(u,/^[\r\n\t ]+/);x=B&&B[0]}qe==="application/xhtml+xml"&&Le===ce&&(u=''+u+"");const O=R?R.createHTML(u):u;if(Le===ce)try{k=new v().parseFromString(O,qe)}catch{}if(!k||!k.documentElement){k=I.createDocument(Le,"template",null);try{k.documentElement.innerHTML=an?C:O}catch{}}const G=k.body||k.documentElement;return u&&x&&G.insertBefore(n.createTextNode(x),G.childNodes[0]||null),Le===ce?F.call(k,ve?"html":"body")[0]:ve?k.documentElement:G},bs=function(u){return Y.call(u.ownerDocument||u,u,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},rn=function(u){return u instanceof p&&(typeof u.nodeName!="string"||typeof u.textContent!="string"||typeof u.removeChild!="function"||!(u.attributes instanceof c)||typeof u.removeAttribute!="function"||typeof u.setAttribute!="function"||typeof u.namespaceURI!="string"||typeof u.insertBefore!="function"||typeof u.hasChildNodes!="function")},vs=function(u){return typeof l=="function"&&u instanceof l};function de(A,u,k){St(A,x=>{x.call(t,u,k,Re)})}const ys=function(u){let k=null;if(de(D.beforeSanitizeElements,u,null),rn(u))return oe(u),!0;const x=K(u.nodeName);if(de(D.uponSanitizeElement,u,{tagName:x,allowedTags:j}),mt&&u.hasChildNodes()&&!vs(u.firstElementChild)&&V(/<[/\w!]/g,u.innerHTML)&&V(/<[/\w!]/g,u.textContent)||u.nodeType===Xe.progressingInstruction||mt&&u.nodeType===Xe.comment&&V(/<[/\w]/g,u.data))return oe(u),!0;if(!(Ce.tagCheck instanceof Function&&Ce.tagCheck(x))&&(!j[x]||je[x])){if(!je[x]&&$s(x)&&(U.tagNameCheck instanceof RegExp&&V(U.tagNameCheck,x)||U.tagNameCheck instanceof Function&&U.tagNameCheck(x)))return!1;if(tn&&!ae[x]){const O=N(u)||u.parentNode,G=E(u)||u.childNodes;if(G&&O){const B=G.length;for(let Z=B-1;Z>=0;--Z){const ue=$(G[Z],!0);ue.__removalCount=(u.__removalCount||0)+1,O.insertBefore(ue,S(u))}}}return oe(u),!0}return u instanceof r&&!ga(u)||(x==="noscript"||x==="noembed"||x==="noframes")&&V(/<\/no(script|embed|frames)/i,u.innerHTML)?(oe(u),!0):(Ee&&u.nodeType===Xe.text&&(k=u.textContent,St([Ke,He,be],O=>{k=Ve(k,O," ")}),u.textContent!==k&&(Ye(t.removed,{element:u.cloneNode()}),u.textContent=k)),de(D.afterSanitizeElements,u,null),!1)},ks=function(u,k,x){if(rs&&(k==="id"||k==="name")&&(x in n||x in pa))return!1;if(!(Xt&&!Qt[k]&&V(Te,k))){if(!(as&&V(aa,k))){if(!(Ce.attributeCheck instanceof Function&&Ce.attributeCheck(k,u))){if(!z[k]||Qt[k]){if(!($s(u)&&(U.tagNameCheck instanceof RegExp&&V(U.tagNameCheck,u)||U.tagNameCheck instanceof Function&&U.tagNameCheck(u))&&(U.attributeNameCheck instanceof RegExp&&V(U.attributeNameCheck,k)||U.attributeNameCheck instanceof Function&&U.attributeNameCheck(k,u))||k==="is"&&U.allowCustomizedBuiltInElements&&(U.tagNameCheck instanceof RegExp&&V(U.tagNameCheck,x)||U.tagNameCheck instanceof Function&&U.tagNameCheck(x))))return!1}else if(!sn[k]){if(!V(ns,Ve(x,ts,""))){if(!((k==="src"||k==="xlink:href"||k==="href")&&u!=="script"&&co(x,"data:")===0&&ds[u])){if(!(os&&!V(oa,Ve(x,ts,"")))){if(x)return!1}}}}}}}return!0},$s=function(u){return u!=="annotation-xml"&&gn(u,la)},ws=function(u){de(D.beforeSanitizeAttributes,u,null);const{attributes:k}=u;if(!k||rn(u))return;const x={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:z,forceKeepAttr:void 0};let O=k.length;for(;O--;){const G=k[O],{name:B,namespaceURI:Z,value:ue}=G,Ie=K(B),cn=ue;let q=B==="value"?cn:uo(cn);if(x.attrName=Ie,x.attrValue=q,x.keepAttr=!0,x.forceKeepAttr=void 0,de(D.uponSanitizeAttribute,u,x),q=x.attrValue,cs&&(Ie==="id"||Ie==="name")&&(ye(B,u),q=ra+q),mt&&V(/((--!?|])>)|<\/(style|title|textarea)/i,q)){ye(B,u);continue}if(Ie==="attributename"&&gn(q,"href")){ye(B,u);continue}if(x.forceKeepAttr)continue;if(!x.keepAttr){ye(B,u);continue}if(!ls&&V(/\/>/i,q)){ye(B,u);continue}Ee&&St([Ke,He,be],xs=>{q=Ve(q,xs," ")});const Ss=K(u.nodeName);if(!ks(Ss,Ie,q)){ye(B,u);continue}if(R&&typeof w=="object"&&typeof w.getAttributeType=="function"&&!Z)switch(w.getAttributeType(Ss,Ie)){case"TrustedHTML":{q=R.createHTML(q);break}case"TrustedScriptURL":{q=R.createScriptURL(q);break}}if(q!==cn)try{Z?u.setAttributeNS(Z,B,q):u.setAttribute(B,q),rn(u)?oe(u):zs(t.removed)}catch{ye(B,u)}}de(D.afterSanitizeAttributes,u,null)},fa=function A(u){let k=null;const x=bs(u);for(de(D.beforeSanitizeShadowDOM,u,null);k=x.nextNode();)de(D.uponSanitizeShadowNode,k,null),ys(k),ws(k),k.content instanceof a&&A(k.content);de(D.afterSanitizeShadowDOM,u,null)};return t.sanitize=function(A){let u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=null,x=null,O=null,G=null;if(an=!A,an&&(A=""),typeof A!="string"&&!vs(A))if(typeof A.toString=="function"){if(A=A.toString(),typeof A!="string")throw Je("dirty is not a string, aborting")}else throw Je("toString is not a function");if(!t.isSupported)return A;if(Zt||ln(u),t.removed=[],typeof A=="string"&&(ze=!1),ze){if(A.nodeName){const ue=K(A.nodeName);if(!j[ue]||je[ue])throw Je("root node is forbidden and cannot be sanitized in-place")}}else if(A instanceof l)k=ms(""),x=k.ownerDocument.importNode(A,!0),x.nodeType===Xe.element&&x.nodeName==="BODY"||x.nodeName==="HTML"?k=x:k.appendChild(x);else{if(!_e&&!Ee&&!ve&&A.indexOf("<")===-1)return R&&vt?R.createHTML(A):A;if(k=ms(A),!k)return _e?null:vt?C:""}k&&en&&oe(k.firstChild);const B=bs(ze?A:k);for(;O=B.nextNode();)ys(O),ws(O),O.content instanceof a&&fa(O.content);if(ze)return A;if(_e){if(bt)for(G=H.call(k.ownerDocument);k.firstChild;)G.appendChild(k.firstChild);else G=k;return(z.shadowroot||z.shadowrootmode)&&(G=M.call(s,G,!0)),G}let Z=ve?k.outerHTML:k.innerHTML;return ve&&j["!doctype"]&&k.ownerDocument&&k.ownerDocument.doctype&&k.ownerDocument.doctype.name&&V(Fi,k.ownerDocument.doctype.name)&&(Z=" `+Z),Ee&&St([Ke,He,be],ue=>{Z=Ve(Z,ue," ")}),R&&vt?R.createHTML(Z):Z},t.setConfig=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ln(A),Zt=!0},t.clearConfig=function(){Re=null,Zt=!1},t.isValidAttribute=function(A,u,k){Re||ln({});const x=K(A),O=K(u);return ks(x,O,k)},t.addHook=function(A,u){typeof u=="function"&&Ye(D[A],u)},t.removeHook=function(A,u){if(u!==void 0){const k=lo(D[A],u);return k===-1?void 0:ro(D[A],k,1)[0]}return zs(D[A])},t.removeHooks=function(A){D[A]=[]},t.removeAllHooks=function(){D=Js()},t}var Tn=Ni();function zn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ae=zn();function Oi(e){Ae=e}var st={exec:()=>null};function L(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(i,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(J.caret,"$1"),n=n.replace(i,o),s},getRegex:()=>new RegExp(n,t)};return s}var To=(()=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,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")},Co=/^(?:[ \t]*(?:\n|$))+/,Eo=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,_o=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,pt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Mo=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,qn=/(?:[*+-]|\d{1,9}[.)])/,Di=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ui=L(Di).replace(/bull/g,qn).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(),Lo=L(Di).replace(/bull/g,qn).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(),Wn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ro=/^[^\n]+/,Gn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Io=L(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Gn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Po=L(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,qn).getRegex(),zt="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",Yn=/|$))/,Fo=L("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Yn).replace("tag",zt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Bi=L(Wn).replace("hr",pt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",zt).getRegex(),No=L(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Bi).getRegex(),Vn={blockquote:No,code:Eo,def:Io,fences:_o,heading:Mo,hr:pt,html:Fo,lheading:Ui,list:Po,newline:Co,paragraph:Bi,table:st,text:Ro},Qs=L("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",pt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",zt).getRegex(),Oo={...Vn,lheading:Lo,table:Qs,paragraph:L(Wn).replace("hr",pt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Qs).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",zt).getRegex()},Do={...Vn,html:L(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Yn).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:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:st,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:L(Wn).replace("hr",pt).replace("heading",` *#{1,6} *[^ ]`).replace("lheading",Ui).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Uo=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Bo=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ki=/^( {2,}|\\)\n(?!\s*$)/,Ko=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",To?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),zi=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Wo=L(zi,"u").replace(/punct/g,qt).getRegex(),Go=L(zi,"u").replace(/punct/g,ji).getRegex(),qi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Yo=L(qi,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,Jn).replace(/punct/g,qt).getRegex(),Vo=L(qi,"gu").replace(/notPunctSpace/g,zo).replace(/punctSpace/g,jo).replace(/punct/g,ji).getRegex(),Jo=L("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,Jn).replace(/punct/g,qt).getRegex(),Qo=L(/\\(punct)/,"gu").replace(/punct/g,qt).getRegex(),Xo=L(/^<(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(),Zo=L(Yn).replace("(?:-->|$)","-->").getRegex(),el=L("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Zo).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Pt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,tl=L(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Pt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Wi=L(/^!?\[(label)\]\[(ref)\]/).replace("label",Pt).replace("ref",Gn).getRegex(),Gi=L(/^!?\[(ref)\](?:\[\])?/).replace("ref",Gn).getRegex(),nl=L("reflink|nolink(?!\\()","g").replace("reflink",Wi).replace("nolink",Gi).getRegex(),Xs=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Qn={_backpedal:st,anyPunctuation:Qo,autolink:Xo,blockSkip:qo,br:Ki,code:Bo,del:st,emStrongLDelim:Wo,emStrongRDelimAst:Yo,emStrongRDelimUnd:Jo,escape:Uo,link:tl,nolink:Gi,punctuation:Ho,reflink:Wi,reflinkSearch:nl,tag:el,text:Ko,url:st},sl={...Qn,link:L(/^!?\[(label)\]\((.*?)\)/).replace("label",Pt).getRegex(),reflink:L(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Pt).getRegex()},Cn={...Qn,emStrongRDelimAst:Vo,emStrongLDelim:Go,url:L(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Xs).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:L(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Zs=e=>al[e];function he(e,t){if(t){if(J.escapeTest.test(e))return e.replace(J.escapeReplace,Zs)}else if(J.escapeTestNoEncode.test(e))return e.replace(J.escapeReplaceNoEncode,Zs);return e}function ei(e){try{e=encodeURI(e).replace(J.percentDecode,"%")}catch{return null}return e}function ti(e,t){let n=e.replace(J.findPipe,(a,o,l)=>{let r=!1,d=o;for(;--d>=0&&l[d]==="\\";)r=!r;return r?"|":" |"}),s=n.split(J.splitPipe),i=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.length0?-2:-1}function ni(e,t,n,s,i){let a=t.href,o=t.title||null,l=e[1].replace(i.other.outputLinkReplace,"$1");s.state.inLink=!0;let r={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:a,title:o,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,r}function ll(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(s===null)return t;let i=s[1];return t.split(` `).map(a=>{let o=a.match(n.other.beginningSpace);if(o===null)return a;let[l]=o;return l.length>=i.length?a.slice(i.length):a}).join(` `)}var Ft=class{options;rules;lexer;constructor(e){this.options=e||Ae}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:et(n,` `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=ll(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=et(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:et(t[0],` `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=et(t[0],` `).split(` `),s="",i="",a=[];for(;n.length>0;){let o=!1,l=[],r;for(r=0;r1,i={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 a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let r=!1,d="",c="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let p=t[2].split(` `,1)[0].replace(this.rules.other.listReplaceTabs,$=>" ".repeat(3*$.length)),v=e.split(` `,1)[0],w=!p.trim(),y=0;if(this.options.pedantic?(y=2,c=p.trimStart()):w?y=t[1].length+1:(y=t[2].search(this.rules.other.nonSpaceChar),y=y>4?1:y,c=p.slice(y),y+=t[1].length),w&&this.rules.other.blankLine.test(v)&&(d+=v+` `,e=e.substring(v.length+1),r=!0),!r){let $=this.rules.other.nextBulletRegex(y),T=this.rules.other.hrRegex(y),S=this.rules.other.fencesBeginRegex(y),E=this.rules.other.headingBeginRegex(y),N=this.rules.other.htmlBeginRegex(y);for(;e;){let R=e.split(` `,1)[0],C;if(v=R,this.options.pedantic?(v=v.replace(this.rules.other.listReplaceNesting," "),C=v):C=v.replace(this.rules.other.tabCharGlobal," "),S.test(v)||E.test(v)||N.test(v)||$.test(v)||T.test(v))break;if(C.search(this.rules.other.nonSpaceChar)>=y||!v.trim())c+=` `+C.slice(y);else{if(w||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(p)||E.test(p)||T.test(p))break;c+=` `+v}!w&&!v.trim()&&(w=!0),d+=R+` `,e=e.substring(R.length+1),p=C.slice(y)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(o=!0)),i.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),i.raw+=d}let l=i.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let r of i.items){if(this.lexer.state.top=!1,r.tokens=this.lexer.blockTokens(r.text,[]),r.task){if(r.text=r.text.replace(this.rules.other.listReplaceTask,""),r.tokens[0]?.type==="text"||r.tokens[0]?.type==="paragraph"){r.tokens[0].raw=r.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),r.tokens[0].text=r.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let c=this.lexer.inlineQueue.length-1;c>=0;c--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)){this.lexer.inlineQueue[c].src=this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask,"");break}}let d=this.rules.other.listTaskCheckbox.exec(r.raw);if(d){let c={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};r.checked=c.checked,i.loose?r.tokens[0]&&["paragraph","text"].includes(r.tokens[0].type)&&"tokens"in r.tokens[0]&&r.tokens[0].tokens?(r.tokens[0].raw=c.raw+r.tokens[0].raw,r.tokens[0].text=c.raw+r.tokens[0].text,r.tokens[0].tokens.unshift(c)):r.tokens.unshift({type:"paragraph",raw:c.raw,text:c.raw,tokens:[c]}):r.tokens.unshift(c)}}if(!i.loose){let d=r.tokens.filter(p=>p.type==="space"),c=d.length>0&&d.some(p=>this.rules.other.anyLine.test(p.raw));i.loose=c}}if(i.loose)for(let r of i.items){r.loose=!0;for(let d of r.tokens)d.type==="text"&&(d.type="paragraph")}return i}}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"):"",i=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:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ti(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` `):[],a={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o({text:l,tokens:this.lexer.inline(l),header:!1,align:a.align[r]})));return a}}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)===` `?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 a=et(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=ol(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],i="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(s);a&&(s=a[1],i=a[3])}else i=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)),ni(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.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," "),i=t[s.toLowerCase()];if(!i){let a=n[0].charAt(0);return{type:"text",raw:a,text:a}}return ni(n,i,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 i=[...s[0]].length-1,a,o,l=i,r=0,d=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(s=d.exec(t))!=null;){if(a=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!a)continue;if(o=[...a].length,s[3]||s[4]){l+=o;continue}else if((s[5]||s[6])&&i%3&&!((i+o)%3)){r+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+r);let c=[...s[0]][0].length,p=e.slice(0,i+s.index+c+o);if(Math.min(i,o)%2){let w=p.slice(1,-1);return{type:"em",raw:p,text:w,tokens:this.lexer.inlineTokens(w)}}let v=p.slice(2,-2);return{type:"strong",raw:p,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,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 i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==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}}}},se=class En{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ae,this.options.tokenizer=this.options.tokenizer||new Ft,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:J,block:At.normal,inline:Ze.normal};this.options.pedantic?(n.block=At.pedantic,n.inline=Ze.pedantic):this.options.gfm&&(n.block=At.gfm,this.options.breaks?n.inline=Ze.breaks:n.inline=Ze.gfm),this.tokenizer.rules=n}static get rules(){return{block:At,inline:Ze}}static lex(t,n){return new En(n).lex(t)}static lexInline(t,n){return new En(n).inlineTokens(t)}lex(t){t=t.replace(J.carriageReturn,` `),this.blockTokens(t,this.tokens);for(let n=0;n(i=o.call({lexer:this},t,n))?(t=t.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(t)){t=t.substring(i.raw.length);let o=n.at(-1);i.raw.length===1&&o!==void 0?o.raw+=` `:n.push(i);continue}if(i=this.tokenizer.code(t)){t=t.substring(i.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` `)?"":` `)+i.raw,o.text+=` `+i.text,this.inlineQueue.at(-1).src=o.text):n.push(i);continue}if(i=this.tokenizer.fences(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.heading(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.hr(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.blockquote(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.list(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.html(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.def(t)){t=t.substring(i.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` `)?"":` `)+i.raw,o.text+=` `+i.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},n.push(i));continue}if(i=this.tokenizer.table(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.lheading(t)){t=t.substring(i.raw.length),n.push(i);continue}let a=t;if(this.options.extensions?.startBlock){let o=1/0,l=t.slice(1),r;this.options.extensions.startBlock.forEach(d=>{r=d.call({lexer:this},l),typeof r=="number"&&r>=0&&(o=Math.min(o,r))}),o<1/0&&o>=0&&(a=t.substring(0,o+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let o=n.at(-1);s&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(` `)?"":` `)+i.raw,o.text+=` `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(i),s=a.length!==t.length,t=t.substring(i.raw.length);continue}if(i=this.tokenizer.text(t)){t=t.substring(i.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(` `)?"":` `)+i.raw,o.text+=` `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(i);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,i=null;if(this.tokens.links){let r=Object.keys(this.tokens.links);if(r.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)r.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let a;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)a=i[2]?i[2].length:0,s=s.slice(0,i.index+a)+"["+"a".repeat(i[0].length-a-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 r;if(this.options.extensions?.inline?.some(c=>(r=c.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))continue;if(r=this.tokenizer.escape(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.tag(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.link(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(r.raw.length);let c=n.at(-1);r.type==="text"&&c?.type==="text"?(c.raw+=r.raw,c.text+=r.text):n.push(r);continue}if(r=this.tokenizer.emStrong(t,s,l)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.codespan(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.br(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.del(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.autolink(t)){t=t.substring(r.raw.length),n.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(t))){t=t.substring(r.raw.length),n.push(r);continue}let d=t;if(this.options.extensions?.startInline){let c=1/0,p=t.slice(1),v;this.options.extensions.startInline.forEach(w=>{v=w.call({lexer:this},p),typeof v=="number"&&v>=0&&(c=Math.min(c,v))}),c<1/0&&c>=0&&(d=t.substring(0,c+1))}if(r=this.tokenizer.inlineText(d)){t=t.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(l=r.raw.slice(-1)),o=!0;let c=n.at(-1);c?.type==="text"?(c.raw+=r.raw,c.text+=r.text):n.push(r);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return n}},Nt=class{options;parser;constructor(e){this.options=e||Ae}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(J.notSpaceStart)?.[0],i=e.replace(J.endingNewline,"")+` `;return s?'
'+(n?i:he(i,!0))+`
`:"
"+(n?i:he(i,!0))+`
`}blockquote({tokens:e}){return`
${this.parser.parse(e)}
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} `}hr(e){return`
`}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o `+s+" `}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • `}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    `}table(e){let t="",n="";for(let i=0;i${s}`),` `+t+` `+s+`
    `}tablerow({text:e}){return` ${e} `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` `}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${he(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),i=ei(e);if(i===null)return s;e=i;let a='
    ",a}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=ei(e);if(i===null)return he(n);e=i;let a=`${n}{let o=i[a].flat(1/0);n=n.concat(this.walkTokens(o,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.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(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let a=t.renderers[i.name];a?t.renderers[i.name]=function(...o){let l=i.renderer.apply(this,o);return l===!1&&(l=a.apply(this,o)),l}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[i.level];a?a.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),s.extensions=t),n.renderer){let i=this.defaults.renderer||new Nt(this.defaults);for(let a in n.renderer){if(!(a in i))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,l=n.renderer[o],r=i[o];i[o]=(...d)=>{let c=l.apply(i,d);return c===!1&&(c=r.apply(i,d)),c||""}}s.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new Ft(this.defaults);for(let a in n.tokenizer){if(!(a in i))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,l=n.tokenizer[o],r=i[o];i[o]=(...d)=>{let c=l.apply(i,d);return c===!1&&(c=r.apply(i,d)),c}}s.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new tt;for(let a in n.hooks){if(!(a in i))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,l=n.hooks[o],r=i[o];tt.passThroughHooks.has(a)?i[o]=d=>{if(this.defaults.async&&tt.passThroughHooksRespectAsync.has(a))return(async()=>{let p=await l.call(i,d);return r.call(i,p)})();let c=l.call(i,d);return r.call(i,c)}:i[o]=(...d)=>{if(this.defaults.async)return(async()=>{let p=await l.apply(i,d);return p===!1&&(p=await r.apply(i,d)),p})();let c=l.apply(i,d);return c===!1&&(c=r.apply(i,d)),c}}s.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,a=n.walkTokens;s.walkTokens=function(o){let l=[];return l.push(a.call(this,o)),i&&(l=l.concat(i.call(this,o))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return se.lex(e,t??this.defaults)}parser(e,t){return ie.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},i={...this.defaults,...s},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&s.async===!1)return a(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 a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(t):t,l=await(i.hooks?await i.hooks.provideLexer():e?se.lex:se.lexInline)(o,i),r=i.hooks?await i.hooks.processAllTokens(l):l;i.walkTokens&&await Promise.all(this.walkTokens(r,i.walkTokens));let d=await(i.hooks?await i.hooks.provideParser():e?ie.parse:ie.parseInline)(r,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let o=(i.hooks?i.hooks.provideLexer():e?se.lex:se.lexInline)(t,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let l=(i.hooks?i.hooks.provideParser():e?ie.parse:ie.parseInline)(o,i);return i.hooks&&(l=i.hooks.postprocess(l)),l}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=` Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+he(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},xe=new rl;function P(e,t){return xe.parse(e,t)}P.options=P.setOptions=function(e){return xe.setOptions(e),P.defaults=xe.defaults,Oi(P.defaults),P};P.getDefaults=zn;P.defaults=Ae;P.use=function(...e){return xe.use(...e),P.defaults=xe.defaults,Oi(P.defaults),P};P.walkTokens=function(e,t){return xe.walkTokens(e,t)};P.parseInline=xe.parseInline;P.Parser=ie;P.parser=ie.parse;P.Renderer=Nt;P.TextRenderer=Xn;P.Lexer=se;P.lexer=se.lex;P.Tokenizer=Ft;P.Hooks=tt;P.parse=P;P.options;P.setOptions;P.use;P.walkTokens;P.parseInline;ie.parse;se.lex;P.setOptions({gfm:!0,breaks:!0,headerIds:!1,mangle:!1});const si=["a","b","blockquote","br","code","del","em","h1","h2","h3","h4","hr","i","li","ol","p","pre","strong","table","tbody","td","th","thead","tr","ul"],ii=["class","href","rel","target","title"];let ai=!1;const cl=14e4,dl=4e4;function ul(){ai||(ai=!0,Tn.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function Wt(e){const t=e.trim();if(!t)return"";ul();const n=Mi(t,cl),s=n.truncated?` โ€ฆ truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>dl){const o=`
    ${hl(`${n.text}${s}`)}
    `;return Tn.sanitize(o,{ALLOWED_TAGS:si,ALLOWED_ATTR:ii})}const i=P.parse(`${n.text}${s}`);return Tn.sanitize(i,{ALLOWED_TAGS:si,ALLOWED_ATTR:ii})}function hl(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const pl={emoji:"๐Ÿงฉ",detailKeys:["command","path","url","targetUrl","targetId","ref","element","node","nodeId","id","requestId","to","channelId","guildId","userId","name","query","pattern","messageId"]},gl={bash:{emoji:"๐Ÿ› ๏ธ",title:"Bash",detailKeys:["command"]},process:{emoji:"๐Ÿงฐ",title:"Process",detailKeys:["sessionId"]},read:{emoji:"๐Ÿ“–",title:"Read",detailKeys:["path"]},write:{emoji:"โœ๏ธ",title:"Write",detailKeys:["path"]},edit:{emoji:"๐Ÿ“",title:"Edit",detailKeys:["path"]},attach:{emoji:"๐Ÿ“Ž",title:"Attach",detailKeys:["path","url","fileName"]},browser:{emoji:"๐ŸŒ",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:{emoji:"๐Ÿ–ผ๏ธ",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:{emoji:"๐Ÿ“ฑ",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:{emoji:"โฐ",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:{emoji:"๐Ÿ”Œ",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:{emoji:"๐ŸŸข",title:"WhatsApp Login",actions:{start:{label:"start"},wait:{label:"wait"}}},discord:{emoji:"๐Ÿ’ฌ",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:{emoji:"๐Ÿ’ฌ",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"}}}},fl={fallback:pl,tools:gl},Yi=fl,oi=Yi.fallback??{emoji:"๐Ÿงฉ"},ml=Yi.tools??{};function bl(e){return(e??"tool").trim()}function vl(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 yl(e){const t=e?.trim();if(t)return t.replace(/_/g," ")}function Vi(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=>Vi(s)).filter(s=>!!s);if(t.length===0)return;const n=t.slice(0,3).join(", ");return t.length>3?`${n}โ€ฆ`:n}}}function kl(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 $l(e,t){for(const n of t){const s=kl(e,n),i=Vi(s);if(i)return i}}function wl(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,i=typeof t.limit=="number"?t.limit:void 0;return s!==void 0&&i!==void 0?`${n}:${s}-${s+i}`:n}function Sl(e){if(!e||typeof e!="object")return;const t=e;return typeof t.path=="string"?t.path:void 0}function xl(e,t){if(!(!e||!t))return e.actions?.[t]??void 0}function Ji(e){const t=bl(e.name),n=t.toLowerCase(),s=ml[n],i=s?.emoji??oi.emoji??"๐Ÿงฉ",a=s?.title??vl(t),o=s?.label??t,l=e.args&&typeof e.args=="object"?e.args.action:void 0,r=typeof l=="string"?l.trim():void 0,d=xl(s,r),c=yl(d?.label??r);let p;n==="read"&&(p=wl(e.args)),!p&&(n==="write"||n==="edit"||n==="attach")&&(p=Sl(e.args));const v=d?.detailKeys??s?.detailKeys??oi.detailKeys??[];return!p&&v.length>0&&(p=$l(e.args,v)),!p&&e.meta&&(p=e.meta),p&&(p=Al(p)),{name:t,emoji:i,title:a,label:o,verb:c,detail:p}}function Qi(e){const t=[];if(e.verb&&t.push(e.verb),e.detail&&t.push(e.detail),t.length!==0)return t.join(" ยท ")}function Al(e){return e&&e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~")}const Tl=80,Cl=2,li=100;function El(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 _l(e){const t=e.split(` `),n=t.slice(0,Cl),s=n.join(` `);return s.length>li?s.slice(0,li)+"โ€ฆ":n.lengthi.kind==="result")){const i=typeof t.toolName=="string"&&t.toolName||typeof t.tool_name=="string"&&t.tool_name||"tool",a=Ht(e)??void 0;s.push({kind:"result",name:i,text:a})}return s}function Ml(e,t){const n=Ji({name:e.name,args:e.args}),s=Qi(n),i=typeof e.text=="string"&&e.text.length>0,a=t?.expanded??!1,o=t?.id??`${e.name}-${Math.random()}`;return h`
    ${n.emoji} ${n.label}
    ${i?g:h`โœ“`}
    ${s?h`
    ${s}
    `:g} ${i?h`
    {if(!t?.onToggle)return;const r=l.currentTarget;t.onToggle(o,r.open)}} > ${a?"Hide output":"Show output"} (${e.text?.length??0} chars) ${a?h`
    ${jt(Wt(e.text??""))}
    `:g}
    `:g}
    `}function ri(e,t){const n=Ji({name:e.name,args:e.args}),s=Qi(n),i=!!e.text?.trim(),a=!!t,o=a?()=>{if(i){t(El(e.text));return}const p=`## ${n.label} ${s?`**Command:** \`${s}\` `:""}*No output โ€” tool completed successfully.*`;t(p)}:void 0,l=i&&(e.text?.length??0)<=Tl,r=i&&!l,d=i&&l,c=!i;return h`
    {p.key!=="Enter"&&p.key!==" "||(p.preventDefault(),o?.())}:g} >
    ${n.emoji} ${n.label}
    ${a?h`${i?"View โ€บ":"โ€บ"}`:g} ${c&&!a?h`โœ“`:g}
    ${s?h`
    ${s}
    `:g} ${c?h`
    Completed
    `:g} ${r?h`
    ${_l(e.text)}
    `:g} ${d?h`
    ${e.text}
    `:g}
    `}function Ll(e){return Array.isArray(e)?e.filter(Boolean):[]}function Rl(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 Il(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}function Pl(){return h`
    `}function ci(e,t,n){const s=e,i=typeof s.role=="string"?s.role:"unknown",a=Xi(e),o=a.length>0,l=jn(e)||typeof s.toolCallId=="string"||typeof s.tool_call_id=="string",r=Ht(e),d=n?.showReasoning&&i==="assistant"?Li(e):null,c=typeof s.content=="string"?s.content:null,p=o?null:JSON.stringify(e,null,2),v=!l&&r?.trim()?{kind:"text",value:r}:!l&&c?.trim()?{kind:"text",value:c}:!l&&p?{kind:"json",value:p}:null,w=v?.kind==="json"?["```json",v.value,"```"].join(` `):v?.value??null,y=d?[Ri(d),w].filter(Boolean).join(` `):w,$=typeof s.timestamp=="number"?new Date(s.timestamp).toLocaleTimeString():"",T=Kt(i),S=T==="assistant"?"assistant":T==="user"?"user":"other",E=T==="assistant"?"Assistant":T==="user"?"You":T,R=(typeof s.toolCallId=="string"?s.toolCallId:"")||(typeof s.id=="string"?s.id:"")||(typeof s.messageId=="string"?s.messageId:"")||(typeof s.timestamp=="number"?String(s.timestamp):"tool-card");return h`
    ${y?h`
    ${jt(Wt(y))}
    `:g} ${a.map((C,I)=>Ml(C,{id:`${R}:${I}`,expanded:t?.isToolOutputExpanded?t.isToolOutputExpanded(`${R}:${I}`):!1,onToggle:t?.onToolOutputToggle}))}
    ${E}${$?h` ยท ${$}`:g}
    `}function Fl(){return h`
    ${Zn("assistant")}
    `}function Nl(e,t,n){const s=new Date(t).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return h`
    ${Zn("assistant")}
    ${Zi({role:"assistant",content:[{type:"text",text:e}]},{isStreaming:!0,showReasoning:!1},n)}
    `}function Ol(e,t){const n=Kt(e.role),s=n==="user"?"You":n==="assistant"?"Assistant":n,i=n==="user"?"user":n==="assistant"?"assistant":"other",a=new Date(e.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return h`
    ${Zn(e.role)}
    ${e.messages.map((o,l)=>Zi(o.message,{isStreaming:e.isStreaming&&l===e.messages.length-1,showReasoning:t.showReasoning},t.onOpenSidebar))}
    `}function Zn(e){const t=Kt(e);return h`
    ${t==="user"?"U":t==="assistant"?"A":"?"}
    `}function Zi(e,t,n){const s=e,i=typeof s.role=="string"?s.role:"unknown",a=jn(e)||i.toLowerCase()==="toolresult"||i.toLowerCase()==="tool_result"||typeof s.toolCallId=="string"||typeof s.tool_call_id=="string",o=Xi(e),l=o.length>0,r=Ht(e),d=t.showReasoning&&i==="assistant"?Li(e):null,c=r?.trim()?r:null,p=d?[Ri(d),c].filter(Boolean).join(` `):c,v=["chat-bubble",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!p&&l&&a?h`${o.map(w=>ri(w,n))}`:!p&&!l?g:h`
    ${p?h`
    ${jt(Wt(p))}
    `:g} ${o.map(w=>ri(w,n))}
    `}function Dl(e){return h` `}var Ul=Object.defineProperty,Bl=Object.getOwnPropertyDescriptor,Gt=(e,t,n,s)=>{for(var i=s>1?void 0:s?Bl(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(s?o(t,n,i):o(i))||i);return s&&i&&Ul(t,n,i),i};let De=class extends Fe{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,i=(e.clientX-this.startX)/n;let a=this.startRatio+i;a=Math.max(this.minRatio,Math.min(this.maxRatio,a)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:a},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 h``}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)}};De.styles=ba` :host { width: 4px; cursor: col-resize; background: var(--border, #333); transition: background 150ms ease-out; flex-shrink: 0; position: relative; } :host::before { content: ""; position: absolute; top: 0; left: -4px; right: -4px; bottom: 0; } :host(:hover) { background: var(--accent, #007bff); } :host(.dragging) { background: var(--accent, #007bff); } `;Gt([Bt({type:Number})],De.prototype,"splitRatio",2);Gt([Bt({type:Number})],De.prototype,"minRatio",2);Gt([Bt({type:Number})],De.prototype,"maxRatio",2);De=Gt([wi("resizable-divider")],De);function Kl(e){const t=e.connected,n=e.sending||e.stream!==null,a=(e.sessions?.sessions?.find(c=>c.key===e.sessionKey)?.reasoningLevel??"off")!=="off",o=e.connected?"Message (โ†ฉ to send, Shift+โ†ฉ for line breaks)":"Connect to the gateway to start chattingโ€ฆ",l=e.splitRatio??.6,r=!!(e.sidebarOpen&&e.onCloseSidebar),d=e.useNewChatLayout??!1;return h`
    ${e.disabledReason?h`
    ${e.disabledReason}
    `:g} ${e.error?h`
    ${e.error}
    `:g} ${e.focusMode?h` `:g}
    ${e.loading?h`
    Loading chatโ€ฆ
    `:g} ${eo(jl(e),c=>c.key,c=>c.kind==="reading-indicator"?d?Fl():Pl():c.kind==="stream"?d?Nl(c.text,c.startedAt,e.onOpenSidebar):ci({role:"assistant",content:[{type:"text",text:c.text}],timestamp:c.startedAt},e,{streaming:!0,showReasoning:a}):c.kind==="group"?Ol(c,{onOpenSidebar:e.onOpenSidebar,showReasoning:a}):ci(c.message,e,{showReasoning:a}))}
    ${d&&r?h` e.onSplitRatioChange?.(c.detail.splitRatio)} >
    ${Dl({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\` ${e.sidebarContent} \`\`\``)}})}
    `:g}
    ${e.queue.length?h`
    Queued (${e.queue.length})
    ${e.queue.map(c=>h`
    ${c.text}
    `)}
    `:g}
    ${e.onAbort?h` `:g}
    `}const di=200;function Hl(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 i=to(s.message),a=Kt(i.role),o=i.timestamp||Date.now();!n||n.role!==a?(n&&t.push(n),n={kind:"group",key:`group:${a}:${s.key}`,role:a,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 jl(e){const t=[],n=Array.isArray(e.messages)?e.messages:[],s=Array.isArray(e.toolMessages)?e.toolMessages:[],i=Math.max(0,n.length-di);i>0&&t.push({kind:"message",key:"chat:history:notice",message:{role:"system",content:`Showing last ${di} messages (${i} hidden).`,timestamp:Date.now()}});for(let a=i;a0?t.push({kind:"stream",key:a,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:a})}return e.useNewChatLayout?Hl(t):t}function ui(e,t){const n=e,s=typeof n.toolCallId=="string"?n.toolCallId:"";if(s)return`tool:${s}`;const i=typeof n.id=="string"?n.id:"";if(i)return`msg:${i}`;const a=typeof n.messageId=="string"?n.messageId:"";if(a)return`msg:${a}`;const o=typeof n.timestamp=="number"?n.timestamp:null,l=typeof n.role=="string"?n.role:"unknown",d=Ht(e)??(typeof n.content=="string"?n.content:null)??zl(e)??String(t),c=ql(d);return o?`msg:${l}:${o}:${c}`:`msg:${l}:${c}`}function zl(e){try{return JSON.stringify(e)}catch{return null}}function ql(e){let t=2166136261;for(let n=0;n>>0).toString(36)}function Wl(e){if(!e.schema)return h`
    Schema unavailable.
    `;const t=e.schema,n=e.value??{};if(gt(t)!=="object"||!t.properties)return h`
    Unsupported schema. Use Raw.
    `;const s=new Set(e.unsupportedPaths??[]),a=Object.entries(t.properties).sort((o,l)=>{const r=Mn([o[0]],e.uiHints)?.order??0,d=Mn([l[0]],e.uiHints)?.order??0;return r!==d?r-d:o[0].localeCompare(l[0])});return h`
    ${a.map(([o,l])=>it({schema:l,value:n[o],path:[o],hints:e.uiHints,unsupported:s,disabled:e.disabled??!1,onPatch:e.onPatch}))}
    `}function it(e){const{schema:t,value:n,path:s,hints:i,unsupported:a,disabled:o,onPatch:l}=e,r=e.showLabel??!0,d=gt(t),c=Mn(s,i),p=c?.label??t.title??Gl(String(s.at(-1))),v=c?.help??t.description,w=Yt(s);if(a.has(w))return h`
    ${p}: unsupported schema node. Use Raw.
    `;if(t.anyOf||t.oneOf){const $=(t.anyOf??t.oneOf??[]).filter(C=>!(C.type==="null"||Array.isArray(C.type)&&C.type.includes("null")));if($.length===1)return it({...e,schema:$[0]});const T=C=>{if(C.const!==void 0)return C.const;if(C.enum&&C.enum.length===1)return C.enum[0]},S=$.map(T);if(S.every(C=>C!==void 0)&&S.length>0){const C=S.findIndex(I=>I===n||String(I)===String(n));return h` `}const N=["string","number","integer","boolean"];if($.every(C=>C.type&&N.includes(String(C.type)))){const C=$.map(F=>F.type).join(" | "),I=$.some(F=>F.type==="boolean"),Y=$.some(F=>F.type==="number"||F.type==="integer"),H=$.every(F=>F.type!=="number");return h` `}return h`
    ${p}: unsupported schema node. Use Raw.
    `}if(t.allOf)return h`
    ${p}: unsupported schema node. Use Raw.
    `;if(d==="object"){const y=t.properties??{},$=Object.entries(y),T=t.additionalProperties&&typeof t.additionalProperties=="object";if($.length===0&&!T)return g;const S=new Set($.map(([E])=>E));return h`
    ${p} ${v?h`
    ${v}
    `:g} ${$.map(([E,N])=>it({schema:N,value:n&&typeof n=="object"?n[E]:void 0,path:[...s,E],hints:i,unsupported:a,onPatch:l,disabled:o}))} ${T?Vl({schema:t.additionalProperties,value:n&&typeof n=="object"?n:{},path:s,hints:i,unsupported:a,disabled:o,reservedKeys:S,onPatch:l}):g}
    `}if(d==="array"){const y=Array.isArray(t.items)?t.items[0]:t.items,$=Array.isArray(n)?n:[];return h`
    ${r?h`${p}`:g}
    ${v?h`
    ${v}
    `:g} ${$.map((T,S)=>h`
    ${y?it({schema:y,value:T,path:[...s,S],hints:i,unsupported:a,disabled:o,onPatch:l}):g}
    `)}
    `}if(t.enum){const y=t.enum,$=y.findIndex(S=>S===n||String(S)===String(n)),T="__unset__";return h` `}if(d==="boolean")return h` `;if(d==="number"||d==="integer")return h` `;if(d==="string"){const y=c?.sensitive??Yl(s),$=c?.placeholder??(y?"โ€ขโ€ขโ€ขโ€ข":"");return h` `}return h`
    ${r?h`${p}`:g}
    Unsupported type. Use Raw.
    `}function gt(e){if(e)return Array.isArray(e.type)?e.type.filter(n=>n!=="null")[0]??e.type[0]:e.type}function ea(e){if(!e)return"";if(e.default!==void 0)return e.default;switch(gt(e)){case"object":return{};case"array":return[];case"boolean":return!1;case"number":case"integer":return 0;case"string":return"";default:return""}}function Mn(e,t){const n=Yt(e);return t[n]}function Yt(e){return e.filter(t=>typeof t=="string").join(".")}function Gl(e){return e.replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function Yl(e){const t=Yt(e).toLowerCase();return t.includes("token")||t.includes("password")||t.includes("secret")||t.includes("apikey")||t.endsWith("key")}function Vl(e){const{schema:t,value:n,path:s,hints:i,unsupported:a,disabled:o,reservedKeys:l,onPatch:r}=e,d=Object.entries(n??{}).filter(([c])=>!l.has(c));return h`
    Extra entries
    ${d.length===0?h`
    No entries yet.
    `:d.map(([c,p])=>{const v=[...s,c];return h`
    {const y=w.target.value.trim();if(!y||y===c)return;const $={...n??{}};y in $||($[y]=$[c],delete $[c],r(s,$))}} />
    ${it({schema:t,value:p,path:v,hints:i,unsupported:a,disabled:o,showLabel:!1,onPatch:r})}
    `})}
    `}function Jl(e){return!e||typeof e!="object"?{schema:null,unsupportedPaths:[""]}:at(e,[])}function at(e,t){const n=[],s={...e},i=Yt(t)||"";if(e.anyOf||e.oneOf||e.allOf){const l=Ql(e,t);return l||(n.push(i),{schema:e,unsupportedPaths:n})}const a=Array.isArray(e.type)&&e.type.includes("null"),o=gt(e)??(e.properties||e.additionalProperties?"object":void 0);if(s.type=o??e.type,s.nullable=a||e.nullable,s.enum){const{enumValues:l,nullable:r}=ta(s.enum);s.enum=l,r&&(s.nullable=!0),l.length===0&&n.push(i)}if(o==="object"){const l=e.properties??{},r={};for(const[d,c]of Object.entries(l)){const p=at(c,[...t,d]);p.schema&&(r[d]=p.schema),n.push(...p.unsupportedPaths)}if(s.properties=r,e.additionalProperties===!0)n.push(i);else if(e.additionalProperties===!1)s.additionalProperties=!1;else if(e.additionalProperties){const d=at(e.additionalProperties,[...t,"*"]);s.additionalProperties=d.schema??e.additionalProperties,d.unsupportedPaths.length>0&&n.push(i)}}else if(o==="array"){const l=Array.isArray(e.items)?e.items[0]:e.items;if(!l)n.push(i);else{const r=at(l,[...t,"*"]);s.items=r.schema??l,r.unsupportedPaths.length>0&&n.push(i)}}else o==="string"||o==="number"||o==="integer"||o==="boolean"||s.enum||n.push(i);return{schema:s,unsupportedPaths:Array.from(new Set(n))}}function Ql(e,t){if(e.allOf)return null;const n=e.anyOf??e.oneOf;if(!n)return null;const s=[],i=[];let a=!1;for(const r of n){if(!r||typeof r!="object")return null;if(Array.isArray(r.enum)){const{enumValues:d,nullable:c}=ta(r.enum);s.push(...d),c&&(a=!0);continue}if("const"in r){if(r.const===null||r.const===void 0){a=!0;continue}s.push(r.const);continue}if(gt(r)==="null"){a=!0;continue}i.push(r)}if(s.length>0&&i.length===0){const r=[];for(const d of s)r.some(c=>Object.is(c,d))||r.push(d);return{schema:{...e,enum:r,nullable:a,anyOf:void 0,oneOf:void 0,allOf:void 0},unsupportedPaths:[]}}if(i.length===1){const r=at(i[0],t);return r.schema&&(r.schema.nullable=a||r.schema.nullable),r}const o=["string","number","integer","boolean"];return i.every(r=>r.type&&o.includes(String(r.type)))&&i.length>0&&s.length===0?{schema:{...e,nullable:a},unsupportedPaths:[]}:null}function ta(e){const t=e.filter(i=>i!=null),n=t.length!==e.length,s=[];for(const i of t)s.some(a=>Object.is(a,i))||s.push(i);return{enumValues:s,nullable:n}}function Xl(e){const t=e.valid==null?"unknown":e.valid?"valid":"invalid",n=Jl(e.schema),s=n.schema?n.unsupportedPaths.length>0:!1,i=!!e.formValue&&!e.loading&&!s,a=e.connected&&!e.saving&&(e.formMode==="raw"?!0:i),o=e.connected&&!e.applying&&!e.updating&&(e.formMode==="raw"?!0:i),l=e.connected&&!e.applying&&!e.updating;return h`
    Config
    ${t}
    Writes to ~/.clawdbot/clawdbot.json. Apply & Update restart the gateway and will ping the last active session when it comes back.
    ${e.formMode==="form"?h`
    ${e.schemaLoading?h`
    Loading schemaโ€ฆ
    `:Wl({schema:n.schema,uiHints:e.uiHints,value:e.formValue,disabled:e.loading||!e.formValue,unsupportedPaths:n.unsupportedPaths,onPatch:e.onFormPatch})} ${s?h`
    Form view canโ€™t safely edit some fields. Use Raw to avoid losing config entries.
    `:g}
    `:h``} ${e.issues.length>0?h`
    ${JSON.stringify(e.issues,null,2)}
    `:g}
    `}const Zl=[{key:"reactions",label:"Reactions"},{key:"stickers",label:"Stickers"},{key:"polls",label:"Polls"},{key:"permissions",label:"Permissions"},{key:"messages",label:"Messages"},{key:"threads",label:"Threads"},{key:"pins",label:"Pins"},{key:"search",label:"Search"},{key:"memberInfo",label:"Member info"},{key:"roleInfo",label:"Role info"},{key:"channelInfo",label:"Channel info"},{key:"voiceStatus",label:"Voice status"},{key:"events",label:"Events"},{key:"roles",label:"Role changes"},{key:"moderation",label:"Moderation"}],er=[{key:"reactions",label:"Reactions"},{key:"messages",label:"Messages"},{key:"pins",label:"Pins"},{key:"memberInfo",label:"Member info"},{key:"emojiList",label:"Emoji list"}];function tr(e){const t=e.snapshot?.whatsapp,n=e.snapshot?.telegram,s=e.snapshot?.discord??null,i=e.snapshot?.slack??null,a=e.snapshot?.signal??null,o=e.snapshot?.imessage??null,r=["whatsapp","telegram","discord","slack","signal","imessage"].map((d,c)=>({key:d,enabled:sr(d,e),order:c})).sort((d,c)=>d.enabled!==c.enabled?d.enabled?-1:1:d.order-c.order);return h`
    ${r.map(d=>ir(d.key,e,{whatsapp:t,telegram:n,discord:s,slack:i,signal:a,imessage:o}))}
    Connection health
    Provider status snapshots from the gateway.
    ${e.lastSuccessAt?W(e.lastSuccessAt):"n/a"}
    ${e.lastError?h`
    ${e.lastError}
    `:g}
    ${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
          
    `}function nr(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 sr(e,t){const n=t.snapshot;if(!n)return!1;switch(e){case"whatsapp":return n.whatsapp.configured||n.whatsapp.linked||n.whatsapp.running;case"telegram":return n.telegram.configured||n.telegram.running;case"discord":return!!(n.discord?.configured||n.discord?.running);case"slack":return!!(n.slack?.configured||n.slack?.running);case"signal":return!!(n.signal?.configured||n.signal?.running);case"imessage":return!!(n.imessage?.configured||n.imessage?.running);default:return!1}}function ir(e,t,n){switch(e){case"whatsapp":{const s=n.whatsapp;return h`
    WhatsApp
    Link WhatsApp Web and monitor connection health.
    Configured ${s?.configured?"Yes":"No"}
    Linked ${s?.linked?"Yes":"No"}
    Running ${s?.running?"Yes":"No"}
    Connected ${s?.connected?"Yes":"No"}
    Last connect ${s?.lastConnectedAt?W(s.lastConnectedAt):"n/a"}
    Last message ${s?.lastMessageAt?W(s.lastMessageAt):"n/a"}
    Auth age ${s?.authAgeMs!=null?nr(s.authAgeMs):"n/a"}
    ${s?.lastError?h`
    ${s.lastError}
    `:g} ${t.whatsappMessage?h`
    ${t.whatsappMessage}
    `:g} ${t.whatsappQrDataUrl?h`
    WhatsApp QR
    `:g}
    `}case"telegram":{const s=n.telegram;return h`
    Telegram
    Bot token and delivery options.
    Configured ${s?.configured?"Yes":"No"}
    Running ${s?.running?"Yes":"No"}
    Mode ${s?.mode??"n/a"}
    Last start ${s?.lastStartAt?W(s.lastStartAt):"n/a"}
    Last probe ${s?.lastProbeAt?W(s.lastProbeAt):"n/a"}
    ${s?.lastError?h`
    ${s.lastError}
    `:g} ${s?.probe?h`
    Probe ${s.probe.ok?"ok":"failed"} ยท ${s.probe.status??""} ${s.probe.error??""}
    `:g}
    Allow from supports numeric user IDs (recommended) or @usernames. DM the bot to get your ID, or run /whoami.
    ${t.telegramTokenLocked?h`
    TELEGRAM_BOT_TOKEN is set in the environment. Config edits will not override it.
    `:g} ${t.telegramForm.groupsWildcardEnabled?h`
    This writes telegram.groups["*"] and allows all groups. Remove it if you only want specific groups.
    `:g} ${t.telegramStatus?h`
    ${t.telegramStatus}
    `:g}
    `}case"discord":{const s=n.discord,i=s?.probe?.bot?.username;return h`
    Discord
    Bot connection and probe status.
    Configured ${s?.configured?"Yes":"No"}
    Running ${s?.running?"Yes":"No"}
    Bot ${i?`@${i}`:"n/a"}
    Last start ${s?.lastStartAt?W(s.lastStartAt):"n/a"}
    Last probe ${s?.lastProbeAt?W(s.lastProbeAt):"n/a"}
    ${s?.lastError?h`
    ${s.lastError}
    `:g} ${s?.probe?h`
    Probe ${s.probe.ok?"ok":"failed"} ยท ${s.probe.status??""} ${s.probe.error??""}
    `:g}
    Guilds
    Add each guild (id or slug) and optional channel rules. Empty channel entries still allow that channel.
    ${t.discordForm.guilds.map((a,o)=>h`
    ${a.channels.length?h`
    ${a.channels.map((l,r)=>h` `)}
    `:g}
    Channels
    `)}
    Tool actions
    ${Zl.map(a=>h``)}
    ${t.discordTokenLocked?h`
    DISCORD_BOT_TOKEN is set in the environment. Config edits will not override it.
    `:g} ${t.discordStatus?h`
    ${t.discordStatus}
    `:g}
    `}case"slack":{const s=n.slack,i=s?.probe?.bot?.name,a=s?.probe?.team?.name;return h`
    Slack
    Socket mode status and bot details.
    Configured ${s?.configured?"Yes":"No"}
    Running ${s?.running?"Yes":"No"}
    Bot ${i||"n/a"}
    Team ${a||"n/a"}
    Last start ${s?.lastStartAt?W(s.lastStartAt):"n/a"}
    Last probe ${s?.lastProbeAt?W(s.lastProbeAt):"n/a"}
    ${s?.lastError?h`
    ${s.lastError}
    `:g} ${s?.probe?h`
    Probe ${s.probe.ok?"ok":"failed"} ยท ${s.probe.status??""} ${s.probe.error??""}
    `:g}
    Slash command
    Channels
    Add channel ids or #names and optionally require mentions.
    ${t.slackForm.channels.map((o,l)=>h`
    `)}
    Tool actions
    ${er.map(o=>h``)}
    ${t.slackTokenLocked||t.slackAppTokenLocked?h`
    ${t.slackTokenLocked?"SLACK_BOT_TOKEN ":""} ${t.slackAppTokenLocked?"SLACK_APP_TOKEN ":""} is set in the environment. Config edits will not override it.
    `:g} ${t.slackStatus?h`
    ${t.slackStatus}
    `:g}
    `}case"signal":{const s=n.signal;return h`
    Signal
    REST daemon status and probe details.
    Configured ${s?.configured?"Yes":"No"}
    Running ${s?.running?"Yes":"No"}
    Base URL ${s?.baseUrl??"n/a"}
    Last start ${s?.lastStartAt?W(s.lastStartAt):"n/a"}
    Last probe ${s?.lastProbeAt?W(s.lastProbeAt):"n/a"}
    ${s?.lastError?h`
    ${s.lastError}
    `:g} ${s?.probe?h`
    Probe ${s.probe.ok?"ok":"failed"} ยท ${s.probe.status??""} ${s.probe.error??""}
    `:g}
    ${t.signalStatus?h`
    ${t.signalStatus}
    `:g}
    `}case"imessage":{const s=n.imessage;return h`
    iMessage
    imsg CLI and database availability.
    Configured ${s?.configured?"Yes":"No"}
    Running ${s?.running?"Yes":"No"}
    CLI ${s?.cliPath??"n/a"}
    DB ${s?.dbPath??"n/a"}
    Last start ${s?.lastStartAt?W(s.lastStartAt):"n/a"}
    Last probe ${s?.lastProbeAt?W(s.lastProbeAt):"n/a"}
    ${s?.lastError?h`
    ${s.lastError}
    `:g} ${s?.probe&&!s.probe.ok?h`
    Probe failed ยท ${s.probe.error??"unknown error"}
    `:g}
    ${t.imessageStatus?h`
    ${t.imessageStatus}
    `:g}
    `}default:return g}}function ar(e){const t=e.host??"unknown",n=e.ip?`(${e.ip})`:"",s=e.mode??"",i=e.version??"";return`${t} ${n} ${s} ${i}`.trim()}function or(e){const t=e.ts??null;return t?W(t):"n/a"}function na(e){return e?`${dt(e)} (${W(e)})`:"n/a"}function lr(e){if(e.totalTokens==null)return"n/a";const t=e.totalTokens??0,n=e.contextTokens??0;return n?`${t} / ${n}`:String(t)}function rr(e){if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cr(e){const t=e.state??{},n=t.nextRunAtMs?dt(t.nextRunAtMs):"n/a",s=t.lastRunAtMs?dt(t.lastRunAtMs):"n/a";return`${t.lastStatus??"n/a"} ยท next ${n} ยท last ${s}`}function dr(e){const t=e.schedule;return t.kind==="at"?`At ${dt(t.atMs)}`:t.kind==="every"?`Every ${_i(t.everyMs)}`:`Cron ${t.expr}${t.tz?` (${t.tz})`:""}`}function ur(e){const t=e.payload;return t.kind==="systemEvent"?`System: ${t.text}`:`Agent: ${t.message}`}function hr(e){return h`
    Scheduler
    Gateway-owned cron scheduler status.
    Enabled
    ${e.status?e.status.enabled?"Yes":"No":"n/a"}
    Jobs
    ${e.status?.jobs??"n/a"}
    Next wake
    ${na(e.status?.nextWakeAtMs??null)}
    ${e.error?h`${e.error}`:g}
    New Job
    Create a scheduled wakeup or agent run.
    ${pr(e)}
    ${e.form.payloadKind==="agentTurn"?h`
    ${e.form.sessionTarget==="isolated"?h` `:g}
    `:g}
    Jobs
    All scheduled jobs stored in the gateway.
    ${e.jobs.length===0?h`
    No jobs yet.
    `:h`
    ${e.jobs.map(t=>gr(t,e))}
    `}
    Run history
    Latest runs for ${e.runsJobId??"(select a job)"}.
    ${e.runs.length===0?h`
    No runs yet.
    `:h`
    ${e.runs.map(t=>fr(t))}
    `}
    `}function pr(e){const t=e.form;return t.scheduleKind==="at"?h` `:t.scheduleKind==="every"?h`
    `:h`
    `}function gr(e,t){return h`
    ${e.name}
    ${dr(e)}
    ${ur(e)}
    ${e.enabled?"enabled":"disabled"} ${e.sessionTarget} ${e.wakeMode}
    ${cr(e)}
    `}function fr(e){return h`
    ${e.status}
    ${e.summary??""}
    ${dt(e.ts)}
    ${e.durationMs??0}ms
    ${e.error?h`
    ${e.error}
    `:g}
    `}function mr(e){return h`
    Snapshots
    Status, health, and heartbeat data.
    Status
    ${JSON.stringify(e.status??{},null,2)}
    Health
    ${JSON.stringify(e.health??{},null,2)}
    Last heartbeat
    ${JSON.stringify(e.heartbeat??{},null,2)}
    Manual RPC
    Send a raw gateway method with JSON params.
    ${e.callError?h`
    ${e.callError}
    `:g} ${e.callResult?h`
    ${e.callResult}
    `:g}
    Models
    Catalog from models.list.
    ${JSON.stringify(e.models??[],null,2)}
    Event Log
    Latest gateway events.
    ${e.eventLog.length===0?h`
    No events yet.
    `:h`
    ${e.eventLog.map(t=>h`
    ${t.event}
    ${new Date(t.ts).toLocaleTimeString()}
    ${rr(t.payload)}
    `)}
    `}
    `}function br(e){return h`
    Connected Instances
    Presence beacons from the gateway and clients.
    ${e.lastError?h`
    ${e.lastError}
    `:g} ${e.statusMessage?h`
    ${e.statusMessage}
    `:g}
    ${e.entries.length===0?h`
    No instances reported yet.
    `:e.entries.map(t=>vr(t))}
    `}function vr(e){const t=e.lastInputSeconds!=null?`${e.lastInputSeconds}s ago`:"n/a",n=e.mode??"unknown";return h`
    ${e.host??"unknown host"}
    ${ar(e)}
    ${n} ${e.platform?h`${e.platform}`:g} ${e.deviceFamily?h`${e.deviceFamily}`:g} ${e.modelIdentifier?h`${e.modelIdentifier}`:g} ${e.version?h`${e.version}`:g}
    ${or(e)}
    Last input ${t}
    Reason ${e.reason??""}
    `}const hi=["trace","debug","info","warn","error","fatal"];function yr(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function kr(e,t){return t?[e.message,e.subsystem,e.raw].filter(Boolean).join(" ").toLowerCase().includes(t):!0}function $r(e){const t=e.filterText.trim().toLowerCase(),n=hi.some(a=>!e.levelFilters[a]),s=e.entries.filter(a=>a.level&&!e.levelFilters[a.level]?!1:kr(a,t)),i=t||n?"filtered":"visible";return h`
    Logs
    Gateway file logs (JSONL).
    ${hi.map(a=>h` `)}
    ${e.file?h`
    File: ${e.file}
    `:g} ${e.truncated?h`
    Log output truncated; showing latest chunk.
    `:g} ${e.error?h`
    ${e.error}
    `:g}
    ${s.length===0?h`
    No log entries.
    `:s.map(a=>h`
    ${yr(a.time)}
    ${a.level??""}
    ${a.subsystem??""}
    ${a.message??a.raw}
    `)}
    `}function wr(e){return h`
    Nodes
    Paired devices and live connections.
    ${e.nodes.length===0?h`
    No nodes found.
    `:e.nodes.map(t=>Sr(t))}
    `}function Sr(e){const t=!!e.connected,n=!!e.paired,s=typeof e.displayName=="string"&&e.displayName.trim()||(typeof e.nodeId=="string"?e.nodeId:"unknown"),i=Array.isArray(e.caps)?e.caps:[],a=Array.isArray(e.commands)?e.commands:[];return h`
    ${s}
    ${typeof e.nodeId=="string"?e.nodeId:""} ${typeof e.remoteIp=="string"?` ยท ${e.remoteIp}`:""} ${typeof e.version=="string"?` ยท ${e.version}`:""}
    ${n?"paired":"unpaired"} ${t?"connected":"offline"} ${i.slice(0,12).map(o=>h`${String(o)}`)} ${a.slice(0,8).map(o=>h`${String(o)}`)}
    `}function xr(e){const t=e.hello?.snapshot,n=t?.uptimeMs?_i(t.uptimeMs):"n/a",s=t?.policy?.tickIntervalMs?`${t.policy.tickIntervalMs}ms`:"n/a";return h`
    Gateway Access
    Where the dashboard connects and how it authenticates.
    Click Connect to apply connection changes.
    Snapshot
    Latest gateway handshake information.
    Status
    ${e.connected?"Connected":"Disconnected"}
    Uptime
    ${n}
    Tick Interval
    ${s}
    Last Providers Refresh
    ${e.lastProvidersRefresh?W(e.lastProvidersRefresh):"n/a"}
    ${e.lastError?h`
    ${e.lastError}
    `:h`
    Use Connections to link WhatsApp, Telegram, Discord, Signal, or iMessage.
    `}
    Instances
    ${e.presenceCount}
    Presence beacons in the last 5 minutes.
    Sessions
    ${e.sessionsCount??"n/a"}
    Recent session keys tracked by the gateway.
    Cron
    ${e.cronEnabled==null?"n/a":e.cronEnabled?"Enabled":"Disabled"}
    Next wake ${na(e.cronNext)}
    Notes
    Quick reminders for remote control setups.
    Tailscale serve
    Prefer serve mode to keep the gateway on loopback with tailnet auth.
    Session hygiene
    Use /new or sessions.patch to reset context.
    Cron reminders
    Use isolated sessions for recurring runs.
    `}const Ar=["","off","minimal","low","medium","high"],Tr=[{value:"",label:"inherit"},{value:"off",label:"off (explicit)"},{value:"on",label:"on"}],Cr=["","off","on","stream"];function Er(e){const t=e.result?.sessions??[];return h`
    Sessions
    Active session keys and per-session overrides.
    ${e.error?h`
    ${e.error}
    `:g}
    ${e.result?`Store: ${e.result.path}`:""}
    Key
    Label
    Kind
    Updated
    Tokens
    Thinking
    Verbose
    Reasoning
    ${t.length===0?h`
    No sessions found.
    `:t.map(n=>_r(n,e.basePath,e.onPatch))}
    `}function _r(e,t,n){const s=e.updatedAt?W(e.updatedAt):"n/a",i=e.thinkingLevel??"",a=e.verboseLevel??"",o=e.reasoningLevel??"",l=e.displayName??e.key,r=e.kind!=="global",d=r?`${Hn("chat",t)}?session=${encodeURIComponent(e.key)}`:null;return h`
    ${e.label??""}
    ${e.kind}
    ${s}
    ${lr(e)}
    `}function Mr(e){const t=e.report?.skills??[],n=e.filter.trim().toLowerCase(),s=n?t.filter(i=>[i.name,i.description,i.source].join(" ").toLowerCase().includes(n)):t;return h`
    Skills
    Bundled, managed, and workspace skills.
    ${s.length} shown
    ${e.error?h`
    ${e.error}
    `:g} ${s.length===0?h`
    No skills found.
    `:h`
    ${s.map(i=>Lr(i,e))}
    `}
    `}function Lr(e,t){const n=t.busyKey===e.skillKey,s=t.edits[e.skillKey]??"",i=t.messages[e.skillKey]??null,a=e.install.length>0&&e.missing.bins.length>0,o=[...e.missing.bins.map(r=>`bin:${r}`),...e.missing.env.map(r=>`env:${r}`),...e.missing.config.map(r=>`config:${r}`),...e.missing.os.map(r=>`os:${r}`)],l=[];return e.disabled&&l.push("disabled"),e.blockedByAllowlist&&l.push("blocked by allowlist"),h`
    ${e.emoji?`${e.emoji} `:""}${e.name}
    ${no(e.description,140)}
    ${e.source} ${e.eligible?"eligible":"blocked"} ${e.disabled?h`disabled`:g}
    ${o.length>0?h`
    Missing: ${o.join(", ")}
    `:g} ${l.length>0?h`
    Reason: ${l.join(", ")}
    `:g}
    ${a?h``:g}
    ${i?h`
    ${i.message}
    `:g} ${e.primaryEnv?h`
    API key t.onEdit(e.skillKey,r.target.value)} />
    `:g}
    `}const es={reactions:!0,stickers:!0,polls:!0,permissions:!0,messages:!0,threads:!0,pins:!0,search:!0,memberInfo:!0,roleInfo:!0,channelInfo:!0,voiceStatus:!0,events:!0,roles:!1,moderation:!1},ge={reactions:!0,messages:!0,pins:!0,memberInfo:!0,emojiList:!0};async function te(e,t){if(!(!e.client||!e.connected)&&!e.providersLoading){e.providersLoading=!0,e.providersError=null;try{const n=await e.client.request("providers.status",{probe:t,timeoutMs:8e3});e.providersSnapshot=n,e.providersLastSuccess=Date.now(),e.telegramTokenLocked=n.telegram.tokenSource==="env",e.discordTokenLocked=n.discord?.tokenSource==="env",e.slackTokenLocked=n.slack?.botTokenSource==="env",e.slackAppTokenLocked=n.slack?.appTokenSource==="env"}catch(n){e.providersError=String(n)}finally{e.providersLoading=!1}}}async function Rr(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 Ir(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 Pr(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{await e.client.request("web.logout",{}),e.whatsappLoginMessage="Logged out.",e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}catch(t){e.whatsappLoginMessage=String(t)}finally{e.whatsappBusy=!1}}}function Fr(e,t){e.telegramForm={...e.telegramForm,...t}}function Nr(e,t){if(t.actions){e.discordForm={...e.discordForm,...t,actions:{...e.discordForm.actions,...t.actions}};return}e.discordForm={...e.discordForm,...t}}function Or(e,t){if(t.actions){e.slackForm={...e.slackForm,...t,actions:{...e.slackForm.actions,...t.actions}};return}e.slackForm={...e.slackForm,...t}}function Dr(e,t){e.signalForm={...e.signalForm,...t}}function Ur(e,t){e.imessageForm={...e.imessageForm,...t}}async function Br(e){if(!(!e.client||!e.connected)&&!e.telegramSaving){e.telegramSaving=!0,e.telegramConfigStatus=null;try{if(e.telegramForm.groupsWildcardEnabled&&!window.confirm('Telegram groups wildcard "*" allows all groups. Continue?')){e.telegramConfigStatus="Save cancelled.";return}const n={...e.configSnapshot?.config??{}},s={...n.telegram??{}};if(!e.telegramTokenLocked){const p=e.telegramForm.token.trim();p?s.botToken=p:delete s.botToken}const i=s.groups&&typeof s.groups=="object"?{...s.groups}:{};if(e.telegramForm.groupsWildcardEnabled){const p=i["*"]&&typeof i["*"]=="object"?{...i["*"]}:{};p.requireMention=e.telegramForm.requireMention,i["*"]=p,s.groups=i}else i["*"]&&(delete i["*"],Object.keys(i).length>0?s.groups=i:delete s.groups);delete s.requireMention;const a=pe(e.telegramForm.allowFrom);a.length>0?s.allowFrom=a:delete s.allowFrom;const o=e.telegramForm.proxy.trim();o?s.proxy=o:delete s.proxy;const l=e.telegramForm.webhookUrl.trim();l?s.webhookUrl=l:delete s.webhookUrl;const r=e.telegramForm.webhookSecret.trim();r?s.webhookSecret=r:delete s.webhookSecret;const d=e.telegramForm.webhookPath.trim();d?s.webhookPath=d:delete s.webhookPath,n.telegram=s;const c=`${JSON.stringify(n,null,2).trimEnd()} `;await e.client.request("config.set",{raw:c}),e.telegramConfigStatus="Saved. Restart gateway if needed."}catch(t){e.telegramConfigStatus=String(t)}finally{e.telegramSaving=!1}}}async function Kr(e){if(!(!e.client||!e.connected)&&!e.discordSaving){e.discordSaving=!0,e.discordConfigStatus=null;try{const n={...e.configSnapshot?.config??{}},s={...n.discord??{}},i=e.discordForm;if(i.enabled?delete s.enabled:s.enabled=!1,!e.discordTokenLocked){const S=i.token.trim();S?s.token=S:delete s.token}const a=pe(i.allowFrom),o=pe(i.groupChannels),l={...s.dm??{}};i.dmEnabled?delete l.enabled:l.enabled=!1,a.length>0?l.allowFrom=a:delete l.allowFrom,i.groupEnabled?l.groupEnabled=!0:delete l.groupEnabled,o.length>0?l.groupChannels=o:delete l.groupChannels,Object.keys(l).length>0?s.dm=l:delete s.dm;const r=Number(i.mediaMaxMb);Number.isFinite(r)&&r>0?s.mediaMaxMb=r:delete s.mediaMaxMb;const d=i.historyLimit.trim();if(d.length===0)delete s.historyLimit;else{const S=Number(d);Number.isFinite(S)&&S>=0?s.historyLimit=S:delete s.historyLimit}const c=i.textChunkLimit.trim();if(c.length===0)delete s.textChunkLimit;else{const S=Number(c);Number.isFinite(S)&&S>0?s.textChunkLimit=S:delete s.textChunkLimit}i.replyToMode==="off"?delete s.replyToMode:s.replyToMode=i.replyToMode;const p=Array.isArray(i.guilds)?i.guilds:[],v={};p.forEach(S=>{const E=String(S.key??"").trim();if(!E)return;const N={},R=String(S.slug??"").trim();R&&(N.slug=R),S.requireMention&&(N.requireMention=!0),(S.reactionNotifications==="off"||S.reactionNotifications==="all"||S.reactionNotifications==="own"||S.reactionNotifications==="allowlist")&&(N.reactionNotifications=S.reactionNotifications);const C=pe(S.users);C.length>0&&(N.users=C);const I={};(Array.isArray(S.channels)?S.channels:[]).forEach(H=>{const F=String(H.key??"").trim();if(!F)return;const M={};H.allow===!1&&(M.allow=!1),H.requireMention&&(M.requireMention=!0),I[F]=M}),Object.keys(I).length>0&&(N.channels=I),v[E]=N}),Object.keys(v).length>0?s.guilds=v:delete s.guilds;const w={},y=S=>{const E=i.actions[S];E!==es[S]&&(w[S]=E)};y("reactions"),y("stickers"),y("polls"),y("permissions"),y("messages"),y("threads"),y("pins"),y("search"),y("memberInfo"),y("roleInfo"),y("channelInfo"),y("voiceStatus"),y("events"),y("roles"),y("moderation"),Object.keys(w).length>0?s.actions=w:delete s.actions;const $={...s.slashCommand??{}};i.slashEnabled?$.enabled=!0:delete $.enabled,i.slashName.trim()?$.name=i.slashName.trim():delete $.name,i.slashSessionPrefix.trim()?$.sessionPrefix=i.slashSessionPrefix.trim():delete $.sessionPrefix,i.slashEphemeral?delete $.ephemeral:$.ephemeral=!1,Object.keys($).length>0?s.slashCommand=$:delete s.slashCommand,Object.keys(s).length>0?n.discord=s:delete n.discord;const T=`${JSON.stringify(n,null,2).trimEnd()} `;await e.client.request("config.set",{raw:T}),e.discordConfigStatus="Saved. Restart gateway if needed."}catch(t){e.discordConfigStatus=String(t)}finally{e.discordSaving=!1}}}async function Hr(e){if(!(!e.client||!e.connected)&&!e.slackSaving){e.slackSaving=!0,e.slackConfigStatus=null;try{const n={...e.configSnapshot?.config??{}},s={...n.slack??{}},i=e.slackForm;if(i.enabled?delete s.enabled:s.enabled=!1,!e.slackTokenLocked){const T=i.botToken.trim();T?s.botToken=T:delete s.botToken}if(!e.slackAppTokenLocked){const T=i.appToken.trim();T?s.appToken=T:delete s.appToken}const a={...s.dm??{}};a.enabled=i.dmEnabled;const o=pe(i.allowFrom);o.length>0?a.allowFrom=o:delete a.allowFrom,i.groupEnabled?a.groupEnabled=!0:delete a.groupEnabled;const l=pe(i.groupChannels);l.length>0?a.groupChannels=l:delete a.groupChannels,Object.keys(a).length>0?s.dm=a:delete s.dm;const r=Number.parseFloat(i.mediaMaxMb);Number.isFinite(r)&&r>0?s.mediaMaxMb=r:delete s.mediaMaxMb;const d=Number.parseInt(i.textChunkLimit,10);Number.isFinite(d)&&d>0?s.textChunkLimit=d:delete s.textChunkLimit,i.reactionNotifications==="own"?delete s.reactionNotifications:s.reactionNotifications=i.reactionNotifications;const c=pe(i.reactionAllowlist);c.length>0?s.reactionAllowlist=c:delete s.reactionAllowlist;const p={...s.slashCommand??{}};i.slashEnabled?p.enabled=!0:delete p.enabled,i.slashName.trim()?p.name=i.slashName.trim():delete p.name,i.slashSessionPrefix.trim()?p.sessionPrefix=i.slashSessionPrefix.trim():delete p.sessionPrefix,i.slashEphemeral?delete p.ephemeral:p.ephemeral=!1,Object.keys(p).length>0?s.slashCommand=p:delete s.slashCommand;const v={},w=T=>{const S=i.actions[T];S!==ge[T]&&(v[T]=S)};w("reactions"),w("messages"),w("pins"),w("memberInfo"),w("emojiList"),Object.keys(v).length>0?s.actions=v:delete s.actions;const y=i.channels.map(T=>{const S=T.key.trim();if(!S)return null;const E={allow:T.allow,requireMention:T.requireMention};return[S,E]}).filter(T=>!!T);y.length>0?s.channels=Object.fromEntries(y):delete s.channels,Object.keys(s).length>0?n.slack=s:delete n.slack;const $=`${JSON.stringify(n,null,2).trimEnd()} `;await e.client.request("config.set",{raw:$}),e.slackConfigStatus="Saved. Restart gateway if needed."}catch(t){e.slackConfigStatus=String(t)}finally{e.slackSaving=!1}}}async function jr(e){if(!(!e.client||!e.connected)&&!e.signalSaving){e.signalSaving=!0,e.signalConfigStatus=null;try{const n={...e.configSnapshot?.config??{}},s={...n.signal??{}},i=e.signalForm;i.enabled?delete s.enabled:s.enabled=!1;const a=i.account.trim();a?s.account=a:delete s.account;const o=i.httpUrl.trim();o?s.httpUrl=o:delete s.httpUrl;const l=i.httpHost.trim();l?s.httpHost=l:delete s.httpHost;const r=Number(i.httpPort);Number.isFinite(r)&&r>0?s.httpPort=r:delete s.httpPort;const d=i.cliPath.trim();d?s.cliPath=d:delete s.cliPath,i.autoStart?delete s.autoStart:s.autoStart=!1,i.receiveMode==="on-start"||i.receiveMode==="manual"?s.receiveMode=i.receiveMode:delete s.receiveMode,i.ignoreAttachments?s.ignoreAttachments=!0:delete s.ignoreAttachments,i.ignoreStories?s.ignoreStories=!0:delete s.ignoreStories,i.sendReadReceipts?s.sendReadReceipts=!0:delete s.sendReadReceipts;const c=pe(i.allowFrom);c.length>0?s.allowFrom=c:delete s.allowFrom;const p=Number(i.mediaMaxMb);Number.isFinite(p)&&p>0?s.mediaMaxMb=p:delete s.mediaMaxMb,Object.keys(s).length>0?n.signal=s:delete n.signal;const v=`${JSON.stringify(n,null,2).trimEnd()} `;await e.client.request("config.set",{raw:v}),e.signalConfigStatus="Saved. Restart gateway if needed."}catch(t){e.signalConfigStatus=String(t)}finally{e.signalSaving=!1}}}async function zr(e){if(!(!e.client||!e.connected)&&!e.imessageSaving){e.imessageSaving=!0,e.imessageConfigStatus=null;try{const n={...e.configSnapshot?.config??{}},s={...n.imessage??{}},i=e.imessageForm;i.enabled?delete s.enabled:s.enabled=!1;const a=i.cliPath.trim();a?s.cliPath=a:delete s.cliPath;const o=i.dbPath.trim();o?s.dbPath=o:delete s.dbPath,i.service==="auto"?delete s.service:s.service=i.service;const l=i.region.trim();l?s.region=l:delete s.region;const r=pe(i.allowFrom);r.length>0?s.allowFrom=r:delete s.allowFrom,i.includeAttachments?s.includeAttachments=!0:delete s.includeAttachments;const d=Number(i.mediaMaxMb);Number.isFinite(d)&&d>0?s.mediaMaxMb=d:delete s.mediaMaxMb,Object.keys(s).length>0?n.imessage=s:delete n.imessage;const c=`${JSON.stringify(n,null,2).trimEnd()} `;await e.client.request("config.set",{raw:c}),e.imessageConfigStatus="Saved. Restart gateway if needed."}catch(t){e.imessageConfigStatus=String(t)}finally{e.imessageSaving=!1}}}async function Ln(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}}}async function ot(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:e.sessionsIncludeGlobal,includeUnknown:e.sessionsIncludeUnknown},n=It(e.sessionsFilterActive,0),s=It(e.sessionsFilterLimit,0);n>0&&(t.activeMinutes=n),s>0&&(t.limit=s);const i=await e.client.request("sessions.list",t);i&&(e.sessionsResult=i)}catch(t){e.sessionsError=String(t)}finally{e.sessionsLoading=!1}}}async function qr(e,t,n){if(!e.client||!e.connected)return;const s={key:t};"thinkingLevel"in n&&(s.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(s.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(s.reasoningLevel=n.reasoningLevel);try{await e.client.request("sessions.patch",s),await ot(e)}catch(i){e.sessionsError=String(i)}}function Ue(e,t,n){if(!t.trim())return;const s={...e.skillMessages};n?s[t]=n:delete s[t],e.skillMessages=s}function Vt(e){return e instanceof Error?e.message:String(e)}async function ft(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=Vt(n)}finally{e.skillsLoading=!1}}}function Wr(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Gr(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 ft(e),Ue(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(s){const i=Vt(s);e.skillsError=i,Ue(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Yr(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 ft(e),Ue(e,t,{kind:"success",message:"API key saved"})}catch(n){const s=Vt(n);e.skillsError=s,Ue(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Vr(e,t,n,s){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const i=await e.client.request("skills.install",{name:n,installId:s,timeoutMs:12e4});await ft(e),Ue(e,t,{kind:"success",message:i?.message??"Installed"})}catch(i){const a=Vt(i);e.skillsError=a,Ue(e,t,{kind:"error",message:a})}finally{e.skillsBusyKey=null}}}async function Mt(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",{});e.nodes=Array.isArray(n.nodes)?n.nodes:[]}catch(n){t?.quiet||(e.lastError=String(n))}finally{e.nodesLoading=!1}}}async function Be(e){if(!(!e.client||!e.connected)){e.chatLoading=!0,e.lastError=null;try{const t=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:200});e.chatMessages=Array.isArray(t.messages)?t.messages:[],e.chatThinkingLevel=t.thinkingLevel??null}catch(t){e.lastError=String(t)}finally{e.chatLoading=!1}}}async function Jr(e,t){if(!e.client||!e.connected)return!1;const n=t.trim();if(!n)return!1;const s=Date.now();e.chatMessages=[...e.chatMessages,{role:"user",content:[{type:"text",text:n}],timestamp:s}],e.chatSending=!0,e.lastError=null;const i=Bn();e.chatRunId=i,e.chatStream="",e.chatStreamStartedAt=s;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:n,deliver:!1,idempotencyKey:i}),!0}catch(a){const o=String(a);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=o,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+o}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function Qr(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 Xr(e,t){if(!t||t.sessionKey!==e.sessionKey||t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return null;if(t.state==="delta"){const n=Zr(t.message);if(typeof n=="string"){const s=e.chatStream??"";(!s||n.length>=s.length)&&(e.chatStream=n)}}else t.state==="final"||t.state==="aborted"?(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null):t.state==="error"&&(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.lastError=t.errorMessage??"chat error");return t.state}function Zr(e){const t=e,n=typeof t.role=="string"?t.role:"",s=t.content;if(typeof s=="string")return n==="assistant"?Ne(s):s;if(Array.isArray(s)){const i=s.map(a=>{const o=a;return o.type==="text"&&typeof o.text=="string"?o.text:null}).filter(a=>typeof a=="string");if(i.length>0){const a=i.join(` `);return n==="assistant"?Ne(a):a}}return typeof t.text=="string"?n==="assistant"?Ne(t.text):t.text:null}async function re(e){if(!(!e.client||!e.connected)){e.configLoading=!0,e.lastError=null;try{const t=await e.client.request("config.get",{});nc(e,t)}catch(t){e.lastError=String(t)}finally{e.configLoading=!1}}}async function ec(e){if(!(!e.client||!e.connected)&&!e.configSchemaLoading){e.configSchemaLoading=!0;try{const t=await e.client.request("config.schema",{});tc(e,t)}catch(t){e.lastError=String(t)}finally{e.configSchemaLoading=!1}}}function tc(e,t){e.configSchema=t.schema??null,e.configUiHints=t.uiHints??{},e.configSchemaVersion=t.version??null}function nc(e,t){e.configSnapshot=t;const n=typeof t.raw=="string"?t.raw:t.config&&typeof t.config=="object"?ut(t.config):e.configRaw;!e.configFormDirty||e.configFormMode==="raw"?e.configRaw=n:e.configForm?e.configRaw=ut(e.configForm):e.configRaw=n,e.configValid=typeof t.valid=="boolean"?t.valid:null,e.configIssues=Array.isArray(t.issues)?t.issues:[];const s=t.config??{},i=s.telegram??{},a=s.discord??{},o=s.slack??{},l=s.signal??{},r=s.imessage??{},d=H=>Array.isArray(H)?H.map(F=>String(F??"").trim()).filter(F=>F.length>0).join(", "):"",c=i.groups&&typeof i.groups=="object"?i.groups:{},p=c["*"]&&typeof c["*"]=="object"?c["*"]:{},v=!!c["*"],w=Array.isArray(i.allowFrom)?d(i.allowFrom):typeof i.allowFrom=="string"?i.allowFrom:"";e.telegramForm={token:typeof i.botToken=="string"?i.botToken:"",requireMention:typeof p.requireMention=="boolean"?p.requireMention:!0,groupsWildcardEnabled:v,allowFrom:w,proxy:typeof i.proxy=="string"?i.proxy:"",webhookUrl:typeof i.webhookUrl=="string"?i.webhookUrl:"",webhookSecret:typeof i.webhookSecret=="string"?i.webhookSecret:"",webhookPath:typeof i.webhookPath=="string"?i.webhookPath:""};const y=a.dm??{},$=a.slashCommand??{},T=a.actions??{},S=a.guilds,E=H=>typeof T[H]=="boolean"?T[H]:es[H];e.discordForm={enabled:typeof a.enabled=="boolean"?a.enabled:!0,token:typeof a.token=="string"?a.token:"",dmEnabled:typeof y.enabled=="boolean"?y.enabled:!0,allowFrom:d(y.allowFrom),groupEnabled:typeof y.groupEnabled=="boolean"?y.groupEnabled:!1,groupChannels:d(y.groupChannels),mediaMaxMb:typeof a.mediaMaxMb=="number"?String(a.mediaMaxMb):"",historyLimit:typeof a.historyLimit=="number"?String(a.historyLimit):"",textChunkLimit:typeof a.textChunkLimit=="number"?String(a.textChunkLimit):"",replyToMode:a.replyToMode==="first"||a.replyToMode==="all"?a.replyToMode:"off",guilds:Array.isArray(S)?[]:typeof S=="object"&&S?Object.entries(S).map(([H,F])=>{const M=F&&typeof F=="object"?F:{},D=M.channels&&typeof M.channels=="object"?M.channels:{},Ke=Object.entries(D).map(([He,be])=>{const Te=be&&typeof be=="object"?be:{};return{key:He,allow:typeof Te.allow=="boolean"?Te.allow:!0,requireMention:typeof Te.requireMention=="boolean"?Te.requireMention:!1}});return{key:H,slug:typeof M.slug=="string"?M.slug:"",requireMention:typeof M.requireMention=="boolean"?M.requireMention:!1,reactionNotifications:M.reactionNotifications==="off"||M.reactionNotifications==="all"||M.reactionNotifications==="own"||M.reactionNotifications==="allowlist"?M.reactionNotifications:"own",users:d(M.users),channels:Ke}}):[],actions:{reactions:E("reactions"),stickers:E("stickers"),polls:E("polls"),permissions:E("permissions"),messages:E("messages"),threads:E("threads"),pins:E("pins"),search:E("search"),memberInfo:E("memberInfo"),roleInfo:E("roleInfo"),channelInfo:E("channelInfo"),voiceStatus:E("voiceStatus"),events:E("events"),roles:E("roles"),moderation:E("moderation")},slashEnabled:typeof $.enabled=="boolean"?$.enabled:!1,slashName:typeof $.name=="string"?$.name:"",slashSessionPrefix:typeof $.sessionPrefix=="string"?$.sessionPrefix:"",slashEphemeral:typeof $.ephemeral=="boolean"?$.ephemeral:!0};const N=o.dm??{},R=o.channels,C=o.slashCommand??{},I=o.actions??{};e.slackForm={enabled:typeof o.enabled=="boolean"?o.enabled:!0,botToken:typeof o.botToken=="string"?o.botToken:"",appToken:typeof o.appToken=="string"?o.appToken:"",dmEnabled:typeof N.enabled=="boolean"?N.enabled:!0,allowFrom:d(N.allowFrom),groupEnabled:typeof N.groupEnabled=="boolean"?N.groupEnabled:!1,groupChannels:d(N.groupChannels),mediaMaxMb:typeof o.mediaMaxMb=="number"?String(o.mediaMaxMb):"",textChunkLimit:typeof o.textChunkLimit=="number"?String(o.textChunkLimit):"",reactionNotifications:o.reactionNotifications==="off"||o.reactionNotifications==="all"||o.reactionNotifications==="allowlist"?o.reactionNotifications:"own",reactionAllowlist:d(o.reactionAllowlist),slashEnabled:typeof C.enabled=="boolean"?C.enabled:!1,slashName:typeof C.name=="string"?C.name:"",slashSessionPrefix:typeof C.sessionPrefix=="string"?C.sessionPrefix:"",slashEphemeral:typeof C.ephemeral=="boolean"?C.ephemeral:!0,actions:{...ge,reactions:typeof I.reactions=="boolean"?I.reactions:ge.reactions,messages:typeof I.messages=="boolean"?I.messages:ge.messages,pins:typeof I.pins=="boolean"?I.pins:ge.pins,memberInfo:typeof I.memberInfo=="boolean"?I.memberInfo:ge.memberInfo,emojiList:typeof I.emojiList=="boolean"?I.emojiList:ge.emojiList},channels:Array.isArray(R)?[]:typeof R=="object"&&R?Object.entries(R).map(([H,F])=>{const M=F&&typeof F=="object"?F:{};return{key:H,allow:typeof M.allow=="boolean"?M.allow:!0,requireMention:typeof M.requireMention=="boolean"?M.requireMention:!1}}):[]},e.signalForm={enabled:typeof l.enabled=="boolean"?l.enabled:!0,account:typeof l.account=="string"?l.account:"",httpUrl:typeof l.httpUrl=="string"?l.httpUrl:"",httpHost:typeof l.httpHost=="string"?l.httpHost:"",httpPort:typeof l.httpPort=="number"?String(l.httpPort):"",cliPath:typeof l.cliPath=="string"?l.cliPath:"",autoStart:typeof l.autoStart=="boolean"?l.autoStart:!0,receiveMode:l.receiveMode==="on-start"||l.receiveMode==="manual"?l.receiveMode:"",ignoreAttachments:typeof l.ignoreAttachments=="boolean"?l.ignoreAttachments:!1,ignoreStories:typeof l.ignoreStories=="boolean"?l.ignoreStories:!1,sendReadReceipts:typeof l.sendReadReceipts=="boolean"?l.sendReadReceipts:!1,allowFrom:d(l.allowFrom),mediaMaxMb:typeof l.mediaMaxMb=="number"?String(l.mediaMaxMb):""},e.imessageForm={enabled:typeof r.enabled=="boolean"?r.enabled:!0,cliPath:typeof r.cliPath=="string"?r.cliPath:"",dbPath:typeof r.dbPath=="string"?r.dbPath:"",service:r.service==="imessage"||r.service==="sms"||r.service==="auto"?r.service:"auto",region:typeof r.region=="string"?r.region:"",allowFrom:d(r.allowFrom),includeAttachments:typeof r.includeAttachments=="boolean"?r.includeAttachments:!1,mediaMaxMb:typeof r.mediaMaxMb=="number"?String(r.mediaMaxMb):""};const Y=t.valid===!1?"Config invalid.":null;e.telegramConfigStatus=Y,e.discordConfigStatus=Y,e.slackConfigStatus=Y,e.signalConfigStatus=Y,e.imessageConfigStatus=Y,e.configFormDirty||(e.configForm=sa(t.config??{}))}async function sc(e){if(!(!e.client||!e.connected)){e.configSaving=!0,e.lastError=null;try{const t=e.configFormMode==="form"&&e.configForm?ut(e.configForm):e.configRaw;await e.client.request("config.set",{raw:t}),e.configFormDirty=!1,await re(e)}catch(t){e.lastError=String(t)}finally{e.configSaving=!1}}}async function ic(e){if(!(!e.client||!e.connected)){e.configApplying=!0,e.lastError=null;try{const t=e.configFormMode==="form"&&e.configForm?ut(e.configForm):e.configRaw;await e.client.request("config.apply",{raw:t,sessionKey:e.applySessionKey}),e.configFormDirty=!1,await re(e)}catch(t){e.lastError=String(t)}finally{e.configApplying=!1}}}async function ac(e){if(!(!e.client||!e.connected)){e.updateRunning=!0,e.lastError=null;try{await e.client.request("update.run",{sessionKey:e.applySessionKey})}catch(t){e.lastError=String(t)}finally{e.updateRunning=!1}}}function oc(e,t,n){const s=sa(e.configForm??e.configSnapshot?.config??{});lc(s,t,n),e.configForm=s,e.configFormDirty=!0,e.configFormMode==="form"&&(e.configRaw=ut(s))}function sa(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function ut(e){return`${JSON.stringify(e,null,2).trimEnd()} `}function lc(e,t,n){if(t.length===0)return;let s=e;for(let a=0;a0&&(n.timeoutSeconds=s),n}async function dc(e){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const t=rc(e.cronForm),n=cc(e.cronForm),s={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||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(!s.name)throw new Error("Name required.");await e.client.request("cron.add",s),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await Jt(e),await ht(e)}catch(t){e.cronError=String(t)}finally{e.cronBusy=!1}}}async function uc(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 Jt(e),await ht(e)}catch(s){e.cronError=String(s)}finally{e.cronBusy=!1}}}async function hc(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 ia(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function pc(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 Jt(e),await ht(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function ia(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 Rn(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,s,i]=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 a=s;e.debugModels=Array.isArray(a?.models)?a?.models:[],e.debugHeartbeat=i}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}async function gc(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 fc=2e3,mc=new Set(["trace","debug","info","warn","error","fatal"]);function bc(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 vc(e){if(typeof e!="string")return null;const t=e.toLowerCase();return mc.has(t)?t:null}function yc(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,i=vc(n?.logLevelName??n?.level),a=typeof t[0]=="string"?t[0]:typeof n?.name=="string"?n?.name:null,o=bc(a);let l=null;o&&(typeof o.subsystem=="string"?l=o.subsystem:typeof o.module=="string"&&(l=o.module)),!l&&a&&a.length<120&&(l=a);let r=null;return typeof t[1]=="string"?r=t[1]:!o&&typeof t[0]=="string"?r=t[0]:typeof t.message=="string"&&(r=t.message),{raw:e,time:s,level:i,subsystem:l,message:r??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function In(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}),a=(Array.isArray(s.lines)?s.lines.filter(l=>typeof l=="string"):[]).map(yc),o=!!(t?.reset||s.reset||e.logsCursor==null);e.logsEntries=o?a:[...e.logsEntries,...a].slice(-fc),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)}}}function kc(e){const t=e.presenceEntries.length,n=e.sessionsResult?.count??null,s=e.cronStatus?.nextWakeAtMs??null,i=e.connected?null:"Disconnected from gateway.",a=e.tab==="chat",o=a&&e.settings.chatFocusMode;return h`
    CLAWDBOT
    Gateway Dashboard
    Health ${e.connected?"OK":"Offline"}
    ${Ac(e)}
    ${$n(e.tab)}
    ${Va(e.tab)}
    ${e.lastError?h`
    ${e.lastError}
    `:g} ${a?wc(e):g}
    ${e.tab==="overview"?xr({connected:e.connected,hello:e.hello,settings:e.settings,password:e.password,lastError:e.lastError,presenceCount:t,sessionsCount:n,cronEnabled:e.cronStatus?.enabled??null,cronNext:s,lastProvidersRefresh:e.providersLastSuccess,onSettingsChange:l=>e.applySettings(l),onPasswordChange:l=>e.password=l,onSessionKeyChange:l=>{e.sessionKey=l,e.chatMessage="",e.resetToolStream(),e.applySettings({...e.settings,sessionKey:l,lastActiveSessionKey:l})},onConnect:()=>e.connect(),onRefresh:()=>e.loadOverview()}):g} ${e.tab==="connections"?tr({connected:e.connected,loading:e.providersLoading,snapshot:e.providersSnapshot,lastError:e.providersError,lastSuccessAt:e.providersLastSuccess,whatsappMessage:e.whatsappLoginMessage,whatsappQrDataUrl:e.whatsappLoginQrDataUrl,whatsappConnected:e.whatsappLoginConnected,whatsappBusy:e.whatsappBusy,telegramForm:e.telegramForm,telegramTokenLocked:e.telegramTokenLocked,telegramSaving:e.telegramSaving,telegramStatus:e.telegramConfigStatus,discordForm:e.discordForm,discordTokenLocked:e.discordTokenLocked,discordSaving:e.discordSaving,discordStatus:e.discordConfigStatus,slackForm:e.slackForm,slackTokenLocked:e.slackTokenLocked,slackAppTokenLocked:e.slackAppTokenLocked,slackSaving:e.slackSaving,slackStatus:e.slackConfigStatus,signalForm:e.signalForm,signalSaving:e.signalSaving,signalStatus:e.signalConfigStatus,imessageForm:e.imessageForm,imessageSaving:e.imessageSaving,imessageStatus:e.imessageConfigStatus,onRefresh:l=>te(e,l),onWhatsAppStart:l=>e.handleWhatsAppStart(l),onWhatsAppWait:()=>e.handleWhatsAppWait(),onWhatsAppLogout:()=>e.handleWhatsAppLogout(),onTelegramChange:l=>Fr(e,l),onTelegramSave:()=>e.handleTelegramSave(),onDiscordChange:l=>Nr(e,l),onDiscordSave:()=>e.handleDiscordSave(),onSlackChange:l=>Or(e,l),onSlackSave:()=>e.handleSlackSave(),onSignalChange:l=>Dr(e,l),onSignalSave:()=>e.handleSignalSave(),onIMessageChange:l=>Ur(e,l),onIMessageSave:()=>e.handleIMessageSave()}):g} ${e.tab==="instances"?br({loading:e.presenceLoading,entries:e.presenceEntries,lastError:e.presenceError,statusMessage:e.presenceStatus,onRefresh:()=>Ln(e)}):g} ${e.tab==="sessions"?Er({loading:e.sessionsLoading,result:e.sessionsResult,error:e.sessionsError,activeMinutes:e.sessionsFilterActive,limit:e.sessionsFilterLimit,includeGlobal:e.sessionsIncludeGlobal,includeUnknown:e.sessionsIncludeUnknown,basePath:e.basePath,onFiltersChange:l=>{e.sessionsFilterActive=l.activeMinutes,e.sessionsFilterLimit=l.limit,e.sessionsIncludeGlobal=l.includeGlobal,e.sessionsIncludeUnknown=l.includeUnknown},onRefresh:()=>ot(e),onPatch:(l,r)=>qr(e,l,r)}):g} ${e.tab==="cron"?hr({loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,runsJobId:e.cronRunsJobId,runs:e.cronRuns,onFormChange:l=>e.cronForm={...e.cronForm,...l},onRefresh:()=>e.loadCron(),onAdd:()=>dc(e),onToggle:(l,r)=>uc(e,l,r),onRun:l=>hc(e,l),onRemove:l=>pc(e,l),onLoadRuns:l=>ia(e,l)}):g} ${e.tab==="skills"?Mr({loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,onFilterChange:l=>e.skillsFilter=l,onRefresh:()=>ft(e,{clearMessages:!0}),onToggle:(l,r)=>Gr(e,l,r),onEdit:(l,r)=>Wr(e,l,r),onSaveKey:l=>Yr(e,l),onInstall:(l,r,d)=>Vr(e,l,r,d)}):g} ${e.tab==="nodes"?wr({loading:e.nodesLoading,nodes:e.nodes,onRefresh:()=>Mt(e)}):g} ${e.tab==="chat"?Kl({sessionKey:e.sessionKey,onSessionKeyChange:l=>{e.sessionKey=l,e.chatMessage="",e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:l,lastActiveSessionKey:l}),Be(e)},thinkingLevel:e.chatThinkingLevel,loading:e.chatLoading,sending:e.chatSending,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:i,error:e.lastError,sessions:e.sessionsResult,isToolOutputExpanded:l=>e.toolOutputExpanded.has(l),onToolOutputToggle:(l,r)=>e.toggleToolOutput(l,r),focusMode:e.settings.chatFocusMode,useNewChatLayout:e.settings.useNewChatLayout,onRefresh:()=>(e.resetToolStream(),Be(e)),onToggleFocusMode:()=>e.applySettings({...e.settings,chatFocusMode:!e.settings.chatFocusMode}),onToggleLayout:()=>e.applySettings({...e.settings,useNewChatLayout:!e.settings.useNewChatLayout}),onDraftChange:l=>e.chatMessage=l,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:l=>e.removeQueuedMessage(l),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:l=>e.handleOpenSidebar(l),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:l=>e.handleSplitRatioChange(l)}):g} ${e.tab==="config"?Xl({raw:e.configRaw,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,onRawChange:l=>e.configRaw=l,onFormModeChange:l=>e.configFormMode=l,onFormPatch:(l,r)=>oc(e,l,r),onReload:()=>re(e),onSave:()=>sc(e),onApply:()=>ic(e),onUpdate:()=>ac(e)}):g} ${e.tab==="debug"?mr({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:l=>e.debugCallMethod=l,onCallParamsChange:l=>e.debugCallParams=l,onRefresh:()=>Rn(e),onCall:()=>gc(e)}):g} ${e.tab==="logs"?$r({loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,truncated:e.logsTruncated,onFilterTextChange:l=>e.logsFilterText=l,onLevelToggle:(l,r)=>{e.logsLevelFilters={...e.logsLevelFilters,[l]:r}},onToggleAutoFollow:l=>e.logsAutoFollow=l,onRefresh:()=>In(e,{reset:!0}),onExport:(l,r)=>e.exportLogs(l,r),onScroll:l=>e.handleLogsScroll(l)}):g}
    Docs
    `}function $c(e,t){const n=Hn(t,e.basePath);return h` {s.defaultPrevented||s.button!==0||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),e.setTab(t))}} title=${$n(t)} > ${$n(t)} `}function wc(e){const t=Sc(e.sessionKey,e.sessionsResult),n=h``,s=h``,i=h``,a=h``;return h`
    |
    `}function Sc(e,t){const n=new Set,s=[];if(n.add(e),s.push({key:e}),t?.sessions)for(const i of t.sessions)n.has(i.key)||(n.add(i.key),s.push({key:i.key,displayName:i.displayName}));return s}const xc=["system","light","dark"];function Ac(e){const t=Math.max(0,xc.indexOf(e.theme)),n=s=>i=>{const o={element:i.currentTarget};(i.clientX||i.clientY)&&(o.pointerClientX=i.clientX,o.pointerClientY=i.clientY),e.setTheme(s,o)};return h`
    `}function Tc(){return h` `}function Cc(){return h` `}function Ec(){return h` `}function _c(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function yn(e){return e==="system"?_c():e}const Tt=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,Mc=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,Ct=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},Lc=({nextTheme:e,applyTheme:t,context:n,currentTheme:s})=>{if(s===e)return;const i=globalThis.document??null;if(!i){t();return}const a=i.documentElement,o=i,l=Mc();if(!!o.startViewTransition&&!l){let d=.5,c=.5;if(n?.pointerClientX!==void 0&&n?.pointerClientY!==void 0&&typeof window<"u")d=Tt(n.pointerClientX/window.innerWidth),c=Tt(n.pointerClientY/window.innerHeight);else if(n?.element){const p=n.element.getBoundingClientRect();p.width>0&&p.height>0&&typeof window<"u"&&(d=Tt((p.left+p.width/2)/window.innerWidth),c=Tt((p.top+p.height/2)/window.innerHeight))}a.style.setProperty("--theme-switch-x",`${d*100}%`),a.style.setProperty("--theme-switch-y",`${c*100}%`),a.classList.add("theme-transition");try{const p=o.startViewTransition?.(()=>{t()});p?.finished?p.finished.finally(()=>Ct(a)):Ct(a)}catch{Ct(a),t()}return}t(),Ct(a)};var Rc=Object.defineProperty,Ic=Object.getOwnPropertyDescriptor,m=(e,t,n,s)=>{for(var i=s>1?void 0:s?Ic(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(s?o(t,n,i):o(i))||i);return s&&i&&Rc(t,n,i),i};const pi=50,Pc=80,Fc=12e4,Nc={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0};function Oc(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(i=>{if(!i||typeof i!="object")return null;const a=i;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(i=>!!i);return s.length===0?null:s.join(` `)}function gi(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=Oc(e);let n;if(typeof e=="string")n=e;else if(t)n=t;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}const s=Mi(n,Fc);return s.truncated?`${s.text} โ€ฆ truncated (${s.total} chars, showing first ${s.text.length}).`:s.text}const Dc={name:"",description:"",enabled:!0,scheduleKind:"every",scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"0 7 * * *",cronTz:"",sessionTarget:"main",wakeMode:"next-heartbeat",payloadKind:"systemEvent",payloadText:"",deliver:!1,provider:"last",to:"",timeoutSeconds:"",postToMainPrefix:""};let f=class extends Fe{constructor(){super(...arguments),this.settings=za(),this.password="",this.tab="chat",this.connected=!1,this.theme=this.settings.theme??"system",this.themeResolved="dark",this.hello=null,this.lastError=null,this.eventLog=[],this.eventLogBuffer=[],this.toolStreamSyncTimer=null,this.sidebarCloseTimer=null,this.sessionKey=this.settings.sessionKey,this.chatLoading=!1,this.chatSending=!1,this.chatMessage="",this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.chatThinkingLevel=null,this.chatQueue=[],this.toolOutputExpanded=new Set,this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.splitRatio=this.settings.splitRatio,this.nodesLoading=!1,this.nodes=[],this.configLoading=!1,this.configRaw=`{ } `,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.configFormDirty=!1,this.configFormMode="form",this.providersLoading=!1,this.providersSnapshot=null,this.providersError=null,this.providersLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.telegramForm={token:"",requireMention:!0,groupsWildcardEnabled:!1,allowFrom:"",proxy:"",webhookUrl:"",webhookSecret:"",webhookPath:""},this.telegramSaving=!1,this.telegramTokenLocked=!1,this.telegramConfigStatus=null,this.discordForm={enabled:!0,token:"",dmEnabled:!0,allowFrom:"",groupEnabled:!1,groupChannels:"",mediaMaxMb:"",historyLimit:"",textChunkLimit:"",guilds:[],actions:{...es},slashEnabled:!1,slashName:"",slashSessionPrefix:"",slashEphemeral:!0},this.discordSaving=!1,this.discordTokenLocked=!1,this.discordConfigStatus=null,this.slackForm={enabled:!0,botToken:"",appToken:"",dmEnabled:!0,allowFrom:"",groupEnabled:!1,groupChannels:"",mediaMaxMb:"",textChunkLimit:"",reactionNotifications:"own",reactionAllowlist:"",slashEnabled:!1,slashName:"",slashSessionPrefix:"",slashEphemeral:!0,actions:{...ge},channels:[]},this.slackSaving=!1,this.slackTokenLocked=!1,this.slackAppTokenLocked=!1,this.slackConfigStatus=null,this.signalForm={enabled:!0,account:"",httpUrl:"",httpHost:"",httpPort:"",cliPath:"",autoStart:!0,receiveMode:"",ignoreAttachments:!1,ignoreStories:!1,sendReadReceipts:!1,allowFrom:"",mediaMaxMb:""},this.signalSaving=!1,this.signalConfigStatus=null,this.imessageForm={enabled:!0,cliPath:"",dbPath:"",service:"auto",region:"",allowFrom:"",includeAttachments:!1,mediaMaxMb:""},this.imessageSaving=!1,this.imessageConfigStatus=null,this.presenceLoading=!1,this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.sessionsLoading=!1,this.sessionsResult=null,this.sessionsError=null,this.sessionsFilterActive="",this.sessionsFilterLimit="120",this.sessionsIncludeGlobal=!0,this.sessionsIncludeUnknown=!1,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...Dc},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,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={...Nc},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.nodesPollInterval=null,this.logsPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.basePath="",this.popStateHandler=()=>this.onPopState(),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.basePath=this.inferBasePath(),this.syncTabWithLocation(!0),this.syncThemeWithSettings(),this.attachThemeListener(),window.addEventListener("popstate",this.popStateHandler),this.applySettingsFromUrl(),this.connect(),this.startNodesPolling(),this.tab==="logs"&&this.startLogsPolling()}firstUpdated(){this.observeTopbar()}disconnectedCallback(){window.removeEventListener("popstate",this.popStateHandler),this.stopNodesPolling(),this.stopLogsPolling(),this.detachThemeListener(),this.topbarObserver?.disconnect(),this.topbarObserver=null,super.disconnectedCallback()}updated(e){if(this.tab==="chat"&&(e.has("chatMessages")||e.has("chatToolMessages")||e.has("chatStream")||e.has("chatLoading")||e.has("tab"))){const t=e.has("tab"),n=e.has("chatLoading")&&e.get("chatLoading")===!0&&this.chatLoading===!1;this.scheduleChatScroll(t||n||!this.chatHasAutoScrolled)}this.tab==="logs"&&(e.has("logsEntries")||e.has("logsAutoFollow")||e.has("tab"))&&this.logsAutoFollow&&this.logsAtBottom&&this.scheduleLogsScroll(e.has("tab")||e.has("logsAutoFollow"))}connect(){this.lastError=null,this.hello=null,this.connected=!1,this.client?.stop(),this.client=new ja({url:this.settings.gatewayUrl,token:this.settings.token.trim()?this.settings.token:void 0,password:this.password.trim()?this.password:void 0,clientName:"clawdbot-control-ui",mode:"webchat",onHello:e=>{this.connected=!0,this.hello=e,this.applySnapshot(e),Mt(this,{quiet:!0}),this.refreshActiveTab()},onClose:({code:e,reason:t})=>{this.connected=!1,this.lastError=`disconnected (${e}): ${t||"no reason"}`},onEvent:e=>this.onEvent(e),onGap:({expected:e,received:t})=>{this.lastError=`event gap detected (expected seq ${e}, got ${t}); refresh recommended`}}),this.client.start()}scheduleChatScroll(e=!1){this.chatScrollFrame&&cancelAnimationFrame(this.chatScrollFrame),this.chatScrollTimeout!=null&&(clearTimeout(this.chatScrollTimeout),this.chatScrollTimeout=null);const t=()=>{const n=this.querySelector(".chat-thread");if(n){const s=getComputedStyle(n).overflowY;if(s==="auto"||s==="scroll"||n.scrollHeight-n.clientHeight>1)return n}return document.scrollingElement??document.documentElement};this.updateComplete.then(()=>{this.chatScrollFrame=requestAnimationFrame(()=>{this.chatScrollFrame=null;const n=t();if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;if(!(e||s<200))return;e&&(this.chatHasAutoScrolled=!0),n.scrollTop=n.scrollHeight;const a=e?150:120;this.chatScrollTimeout=window.setTimeout(()=>{this.chatScrollTimeout=null;const o=t();if(!o)return;const l=o.scrollHeight-o.scrollTop-o.clientHeight;!e&&l>=250||(o.scrollTop=o.scrollHeight)},a)})})}observeTopbar(){if(typeof ResizeObserver>"u")return;const e=this.querySelector(".topbar");if(!e)return;const t=()=>{const{height:n}=e.getBoundingClientRect();this.style.setProperty("--topbar-height",`${n}px`)};t(),this.topbarObserver=new ResizeObserver(()=>t()),this.topbarObserver.observe(e)}startNodesPolling(){this.nodesPollInterval==null&&(this.nodesPollInterval=window.setInterval(()=>{Mt(this,{quiet:!0})},5e3))}stopNodesPolling(){this.nodesPollInterval!=null&&(clearInterval(this.nodesPollInterval),this.nodesPollInterval=null)}startLogsPolling(){this.logsPollInterval==null&&(this.logsPollInterval=window.setInterval(()=>{this.tab==="logs"&&In(this,{quiet:!0})},2e3))}stopLogsPolling(){this.logsPollInterval!=null&&(clearInterval(this.logsPollInterval),this.logsPollInterval=null)}scheduleLogsScroll(e=!1){this.logsScrollFrame&&cancelAnimationFrame(this.logsScrollFrame),this.updateComplete.then(()=>{this.logsScrollFrame=requestAnimationFrame(()=>{this.logsScrollFrame=null;const t=this.querySelector(".log-stream");if(!t)return;const n=t.scrollHeight-t.scrollTop-t.clientHeight;(e||n<80)&&(t.scrollTop=t.scrollHeight)})})}handleLogsScroll(e){const t=e.currentTarget;if(!t)return;const n=t.scrollHeight-t.scrollTop-t.clientHeight;this.logsAtBottom=n<80}exportLogs(e,t){if(e.length===0)return;const n=new Blob([`${e.join(` `)} `],{type:"text/plain"}),s=URL.createObjectURL(n),i=document.createElement("a"),a=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");i.href=s,i.download=`clawdbot-logs-${t}-${a}.log`,i.click(),URL.revokeObjectURL(s)}resetToolStream(){this.toolStreamById.clear(),this.toolStreamOrder=[],this.chatToolMessages=[],this.toolOutputExpanded=new Set,this.flushToolStreamSync()}resetChatScroll(){this.chatHasAutoScrolled=!1}toggleToolOutput(e,t){const n=new Set(this.toolOutputExpanded);t?n.add(e):n.delete(e),this.toolOutputExpanded=n}trimToolStream(){if(this.toolStreamOrder.length<=pi)return;const e=this.toolStreamOrder.length-pi,t=this.toolStreamOrder.splice(0,e);for(const n of t)this.toolStreamById.delete(n)}syncToolStreamMessages(){this.chatToolMessages=this.toolStreamOrder.map(e=>this.toolStreamById.get(e)?.message).filter(e=>!!e)}scheduleToolStreamSync(e=!1){if(e){this.flushToolStreamSync();return}this.toolStreamSyncTimer==null&&(this.toolStreamSyncTimer=window.setTimeout(()=>this.flushToolStreamSync(),Pc))}flushToolStreamSync(){this.toolStreamSyncTimer!=null&&(clearTimeout(this.toolStreamSyncTimer),this.toolStreamSyncTimer=null),this.syncToolStreamMessages()}buildToolStreamMessage(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}}handleAgentEvent(e){if(!e||e.stream!=="tool")return;const t=typeof e.sessionKey=="string"?e.sessionKey:void 0;if(t&&t!==this.sessionKey||!t&&this.chatRunId&&e.runId!==this.chatRunId||this.chatRunId&&e.runId!==this.chatRunId||!this.chatRunId)return;const n=e.data??{},s=typeof n.toolCallId=="string"?n.toolCallId:"";if(!s)return;const i=typeof n.name=="string"?n.name:"tool",a=typeof n.phase=="string"?n.phase:"",o=a==="start"?n.args:void 0,l=a==="update"?gi(n.partialResult):a==="result"?gi(n.result):void 0,r=Date.now();let d=this.toolStreamById.get(s);d?(d.name=i,o!==void 0&&(d.args=o),l!==void 0&&(d.output=l),d.updatedAt=r):(d={toolCallId:s,runId:e.runId,sessionKey:t,name:i,args:o,output:l,startedAt:typeof e.ts=="number"?e.ts:r,updatedAt:r,message:{}},this.toolStreamById.set(s,d),this.toolStreamOrder.push(s)),d.message=this.buildToolStreamMessage(d),this.trimToolStream(),this.scheduleToolStreamSync(a==="result")}onEvent(e){if(this.eventLogBuffer=[{ts:Date.now(),event:e.event,payload:e.payload},...this.eventLogBuffer].slice(0,250),this.tab==="debug"&&(this.eventLog=this.eventLogBuffer),e.event==="agent"){this.handleAgentEvent(e.payload);return}if(e.event==="chat"){const t=e.payload;t?.sessionKey&&this.setLastActiveSessionKey(t.sessionKey);const n=Xr(this,t);(n==="final"||n==="error"||n==="aborted")&&(this.resetToolStream(),this.flushChatQueue()),n==="final"&&Be(this);return}if(e.event==="presence"){const t=e.payload;t?.presence&&Array.isArray(t.presence)&&(this.presenceEntries=t.presence,this.presenceError=null,this.presenceStatus=null);return}e.event==="cron"&&this.tab==="cron"&&this.loadCron()}applySnapshot(e){const t=e.snapshot;t?.presence&&Array.isArray(t.presence)&&(this.presenceEntries=t.presence),t?.health&&(this.debugHealth=t.health)}applySettings(e){const t={...e,lastActiveSessionKey:e.lastActiveSessionKey?.trim()||e.sessionKey.trim()||"main"};this.settings=t,qa(t),e.theme!==this.theme&&(this.theme=e.theme,this.applyResolvedTheme(yn(e.theme))),this.applySessionKey=this.settings.lastActiveSessionKey}setLastActiveSessionKey(e){const t=e.trim();t&&this.settings.lastActiveSessionKey!==t&&this.applySettings({...this.settings,lastActiveSessionKey:t})}applySettingsFromUrl(){if(!window.location.search)return;const e=new URLSearchParams(window.location.search),t=e.get("token"),n=e.get("password"),s=e.get("session");let i=!1;if(t!=null){const o=t.trim();o&&!this.settings.token&&this.applySettings({...this.settings,token:o}),e.delete("token"),i=!0}if(n!=null){const o=n.trim();o&&(this.password=o),e.delete("password"),i=!0}if(s!=null){const o=s.trim();o&&(this.sessionKey=o),e.delete("session"),i=!0}if(!i)return;const a=new URL(window.location.href);a.search=e.toString(),window.history.replaceState({},"",a.toString())}setTab(e){this.tab!==e&&(this.tab=e),e==="chat"&&(this.chatHasAutoScrolled=!1),e==="logs"?this.startLogsPolling():this.stopLogsPolling(),this.refreshActiveTab(),this.syncUrlWithTab(e,!1)}setTheme(e,t){Lc({nextTheme:e,applyTheme:()=>{this.theme=e,this.applySettings({...this.settings,theme:e}),this.applyResolvedTheme(yn(e))},context:t,currentTheme:this.theme})}async refreshActiveTab(){this.tab==="overview"&&await this.loadOverview(),this.tab==="connections"&&await this.loadConnections(),this.tab==="instances"&&await Ln(this),this.tab==="sessions"&&await ot(this),this.tab==="cron"&&await this.loadCron(),this.tab==="skills"&&await ft(this),this.tab==="nodes"&&await Mt(this),this.tab==="chat"&&(await Promise.all([Be(this),ot(this)]),this.scheduleChatScroll(!this.chatHasAutoScrolled)),this.tab==="config"&&(await ec(this),await re(this)),this.tab==="debug"&&(await Rn(this),this.eventLog=this.eventLogBuffer),this.tab==="logs"&&(this.logsAtBottom=!0,await In(this,{reset:!0}),this.scheduleLogsScroll(!0))}inferBasePath(){if(typeof window>"u")return"";const e=window.__CLAWDBOT_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?Kn(e):Ga(window.location.pathname)}syncThemeWithSettings(){this.theme=this.settings.theme??"system",this.applyResolvedTheme(yn(this.theme))}applyResolvedTheme(e){if(this.themeResolved=e,typeof document>"u")return;const t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e}attachThemeListener(){if(typeof window>"u"||typeof window.matchMedia!="function")return;if(this.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),this.themeMediaHandler=t=>{this.theme==="system"&&this.applyResolvedTheme(t.matches?"dark":"light")},typeof this.themeMedia.addEventListener=="function"){this.themeMedia.addEventListener("change",this.themeMediaHandler);return}this.themeMedia.addListener(this.themeMediaHandler)}detachThemeListener(){if(!this.themeMedia||!this.themeMediaHandler)return;if(typeof this.themeMedia.removeEventListener=="function"){this.themeMedia.removeEventListener("change",this.themeMediaHandler);return}this.themeMedia.removeListener(this.themeMediaHandler),this.themeMedia=null,this.themeMediaHandler=null}syncTabWithLocation(e){if(typeof window>"u")return;const t=Os(window.location.pathname,this.basePath)??"chat";this.setTabFromRoute(t),this.syncUrlWithTab(t,e)}onPopState(){if(typeof window>"u")return;const e=Os(window.location.pathname,this.basePath);e&&this.setTabFromRoute(e)}setTabFromRoute(e){this.tab!==e&&(this.tab=e),e==="chat"&&(this.chatHasAutoScrolled=!1),e==="logs"?this.startLogsPolling():this.stopLogsPolling(),this.connected&&this.refreshActiveTab()}syncUrlWithTab(e,t){if(typeof window>"u")return;const n=ct(Hn(e,this.basePath));if(ct(window.location.pathname)===n)return;const i=new URL(window.location.href);i.pathname=n,t?window.history.replaceState({},"",i.toString()):window.history.pushState({},"",i.toString())}async loadOverview(){await Promise.all([te(this,!1),Ln(this),ot(this),ht(this),Rn(this)])}async loadConnections(){await Promise.all([te(this,!0),re(this)])}async loadCron(){await Promise.all([ht(this),Jt(this)])}isChatBusy(){return this.chatSending||!!this.chatRunId}isChatStopCommand(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/stop"?!0:n==="stop"||n==="esc"||n==="abort"||n==="wait"||n==="exit"}async handleAbortChat(){this.connected&&(this.chatMessage="",await Qr(this))}enqueueChatMessage(e){const t=e.trim();t&&(this.chatQueue=[...this.chatQueue,{id:Bn(),text:t,createdAt:Date.now()}])}async sendChatMessageNow(e,t){this.resetToolStream();const n=await Jr(this,e);return!n&&t?.previousDraft!=null&&(this.chatMessage=t.previousDraft),n&&this.setLastActiveSessionKey(this.sessionKey),n&&t?.restoreDraft&&t.previousDraft?.trim()&&(this.chatMessage=t.previousDraft),this.scheduleChatScroll(),n&&!this.chatRunId&&this.flushChatQueue(),n}async flushChatQueue(){if(!this.connected||this.isChatBusy())return;const[e,...t]=this.chatQueue;if(!e)return;this.chatQueue=t,await this.sendChatMessageNow(e.text)||(this.chatQueue=[e,...this.chatQueue])}removeQueuedMessage(e){this.chatQueue=this.chatQueue.filter(t=>t.id!==e)}async handleSendChat(e,t){if(!this.connected)return;const n=this.chatMessage,s=(e??this.chatMessage).trim();if(s){if(this.isChatStopCommand(s)){await this.handleAbortChat();return}if(e==null&&(this.chatMessage=""),this.isChatBusy()){this.enqueueChatMessage(s);return}await this.sendChatMessageNow(s,{previousDraft:e==null?n:void 0,restoreDraft:!!(e&&t?.restoreDraft)})}}async handleWhatsAppStart(e){await Rr(this,e),await te(this,!0)}async handleWhatsAppWait(){await Ir(this),await te(this,!0)}async handleWhatsAppLogout(){await Pr(this),await te(this,!0)}async handleTelegramSave(){await Br(this),await re(this),await te(this,!0)}async handleDiscordSave(){await Kr(this),await re(this),await te(this,!0)}async handleSlackSave(){await Hr(this),await re(this),await te(this,!0)}async handleSignalSave(){await jr(this),await re(this),await te(this,!0)}async handleIMessageSave(){await zr(this),await re(this),await te(this,!0)}handleOpenSidebar(e){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarCloseTimer=null)},200)}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}render(){return kc(this)}};m([b()],f.prototype,"settings",2);m([b()],f.prototype,"password",2);m([b()],f.prototype,"tab",2);m([b()],f.prototype,"connected",2);m([b()],f.prototype,"theme",2);m([b()],f.prototype,"themeResolved",2);m([b()],f.prototype,"hello",2);m([b()],f.prototype,"lastError",2);m([b()],f.prototype,"eventLog",2);m([b()],f.prototype,"sessionKey",2);m([b()],f.prototype,"chatLoading",2);m([b()],f.prototype,"chatSending",2);m([b()],f.prototype,"chatMessage",2);m([b()],f.prototype,"chatMessages",2);m([b()],f.prototype,"chatToolMessages",2);m([b()],f.prototype,"chatStream",2);m([b()],f.prototype,"chatStreamStartedAt",2);m([b()],f.prototype,"chatRunId",2);m([b()],f.prototype,"chatThinkingLevel",2);m([b()],f.prototype,"chatQueue",2);m([b()],f.prototype,"toolOutputExpanded",2);m([b()],f.prototype,"sidebarOpen",2);m([b()],f.prototype,"sidebarContent",2);m([b()],f.prototype,"sidebarError",2);m([b()],f.prototype,"splitRatio",2);m([b()],f.prototype,"nodesLoading",2);m([b()],f.prototype,"nodes",2);m([b()],f.prototype,"configLoading",2);m([b()],f.prototype,"configRaw",2);m([b()],f.prototype,"configValid",2);m([b()],f.prototype,"configIssues",2);m([b()],f.prototype,"configSaving",2);m([b()],f.prototype,"configApplying",2);m([b()],f.prototype,"updateRunning",2);m([b()],f.prototype,"applySessionKey",2);m([b()],f.prototype,"configSnapshot",2);m([b()],f.prototype,"configSchema",2);m([b()],f.prototype,"configSchemaVersion",2);m([b()],f.prototype,"configSchemaLoading",2);m([b()],f.prototype,"configUiHints",2);m([b()],f.prototype,"configForm",2);m([b()],f.prototype,"configFormDirty",2);m([b()],f.prototype,"configFormMode",2);m([b()],f.prototype,"providersLoading",2);m([b()],f.prototype,"providersSnapshot",2);m([b()],f.prototype,"providersError",2);m([b()],f.prototype,"providersLastSuccess",2);m([b()],f.prototype,"whatsappLoginMessage",2);m([b()],f.prototype,"whatsappLoginQrDataUrl",2);m([b()],f.prototype,"whatsappLoginConnected",2);m([b()],f.prototype,"whatsappBusy",2);m([b()],f.prototype,"telegramForm",2);m([b()],f.prototype,"telegramSaving",2);m([b()],f.prototype,"telegramTokenLocked",2);m([b()],f.prototype,"telegramConfigStatus",2);m([b()],f.prototype,"discordForm",2);m([b()],f.prototype,"discordSaving",2);m([b()],f.prototype,"discordTokenLocked",2);m([b()],f.prototype,"discordConfigStatus",2);m([b()],f.prototype,"slackForm",2);m([b()],f.prototype,"slackSaving",2);m([b()],f.prototype,"slackTokenLocked",2);m([b()],f.prototype,"slackAppTokenLocked",2);m([b()],f.prototype,"slackConfigStatus",2);m([b()],f.prototype,"signalForm",2);m([b()],f.prototype,"signalSaving",2);m([b()],f.prototype,"signalConfigStatus",2);m([b()],f.prototype,"imessageForm",2);m([b()],f.prototype,"imessageSaving",2);m([b()],f.prototype,"imessageConfigStatus",2);m([b()],f.prototype,"presenceLoading",2);m([b()],f.prototype,"presenceEntries",2);m([b()],f.prototype,"presenceError",2);m([b()],f.prototype,"presenceStatus",2);m([b()],f.prototype,"sessionsLoading",2);m([b()],f.prototype,"sessionsResult",2);m([b()],f.prototype,"sessionsError",2);m([b()],f.prototype,"sessionsFilterActive",2);m([b()],f.prototype,"sessionsFilterLimit",2);m([b()],f.prototype,"sessionsIncludeGlobal",2);m([b()],f.prototype,"sessionsIncludeUnknown",2);m([b()],f.prototype,"cronLoading",2);m([b()],f.prototype,"cronJobs",2);m([b()],f.prototype,"cronStatus",2);m([b()],f.prototype,"cronError",2);m([b()],f.prototype,"cronForm",2);m([b()],f.prototype,"cronRunsJobId",2);m([b()],f.prototype,"cronRuns",2);m([b()],f.prototype,"cronBusy",2);m([b()],f.prototype,"skillsLoading",2);m([b()],f.prototype,"skillsReport",2);m([b()],f.prototype,"skillsError",2);m([b()],f.prototype,"skillsFilter",2);m([b()],f.prototype,"skillEdits",2);m([b()],f.prototype,"skillsBusyKey",2);m([b()],f.prototype,"skillMessages",2);m([b()],f.prototype,"debugLoading",2);m([b()],f.prototype,"debugStatus",2);m([b()],f.prototype,"debugHealth",2);m([b()],f.prototype,"debugModels",2);m([b()],f.prototype,"debugHeartbeat",2);m([b()],f.prototype,"debugCallMethod",2);m([b()],f.prototype,"debugCallParams",2);m([b()],f.prototype,"debugCallResult",2);m([b()],f.prototype,"debugCallError",2);m([b()],f.prototype,"logsLoading",2);m([b()],f.prototype,"logsError",2);m([b()],f.prototype,"logsFile",2);m([b()],f.prototype,"logsEntries",2);m([b()],f.prototype,"logsFilterText",2);m([b()],f.prototype,"logsLevelFilters",2);m([b()],f.prototype,"logsAutoFollow",2);m([b()],f.prototype,"logsTruncated",2);m([b()],f.prototype,"logsCursor",2);m([b()],f.prototype,"logsLastFetchAt",2);m([b()],f.prototype,"logsLimit",2);m([b()],f.prototype,"logsMaxBytes",2);m([b()],f.prototype,"logsAtBottom",2);f=m([wi("clawdbot-app")],f); //# sourceMappingURL=index-R0hOuO5Q.js.map