(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=n(s);fetch(s.href,a)}})();const dn=globalThis,Ji=dn.ShadowRoot&&(dn.ShadyCSS===void 0||dn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Zi=Symbol(),la=new WeakMap;let Eo=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==Zi)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(Ji&&t===void 0){const i=n!==void 0&&n.length===1;i&&(t=la.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&la.set(n,t))}return t}toString(){return this.cssText}};const kr=e=>new Eo(typeof e=="string"?e:e+"",void 0,Zi),Ar=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((i,s,a)=>i+(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.")})(s)+e[a+1],e[0]);return new Eo(n,e,Zi)},xr=(e,t)=>{if(Ji)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const i=document.createElement("style"),s=dn.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=n.cssText,e.appendChild(i)}},ra=Ji?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const i of t.cssRules)n+=i.cssText;return kr(n)})(e):e;const{is:Sr,defineProperty:_r,getOwnPropertyDescriptor:Cr,getOwnPropertyNames:Er,getOwnPropertySymbols:Tr,getPrototypeOf:Lr}=Object,Sn=globalThis,ca=Sn.trustedTypes,Ir=ca?ca.emptyScript:"",Rr=Sn.reactiveElementPolyfillSupport,Ct=(e,t)=>e,hn={toAttribute(e,t){switch(t){case Boolean:e=e?Ir: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}},Xi=(e,t)=>!Sr(e,t),da={attribute:!0,type:String,converter:hn,reflect:!1,useDefault:!1,hasChanged:Xi};Symbol.metadata??=Symbol("metadata"),Sn.litPropertyMetadata??=new WeakMap;let ot=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=da){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,n);s!==void 0&&_r(this.prototype,t,s)}}static getPropertyDescriptor(t,n,i){const{get:s,set:a}=Cr(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:s,set(o){const r=s?.call(this);a?.call(this,o),this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??da}static _$Ei(){if(this.hasOwnProperty(Ct("elementProperties")))return;const t=Lr(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Ct("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ct("properties"))){const n=this.properties,i=[...Er(n),...Tr(n)];for(const s of i)this.createProperty(s,n[s])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[i,s]of n)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[n,i]of this.elementProperties){const s=this._$Eu(n,i);s!==void 0&&this._$Eh.set(s,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const n=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)n.unshift(ra(s))}else t!==void 0&&n.push(ra(t));return n}static _$Eu(t,n){const i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){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 i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return xr(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,i){this._$AK(t,i)}_$ET(t,n){const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const a=(i.converter?.toAttribute!==void 0?i.converter:hn).toAttribute(n,i.type);this._$Em=t,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(t,n){const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),o=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:hn;this._$Em=s;const r=o.fromAttribute(n,a.type);this[s]=r??this._$Ej?.get(s)??r,this._$Em=null}}requestUpdate(t,n,i,s=!1,a){if(t!==void 0){const o=this.constructor;if(s===!1&&(a=this[t]),i??=o.getPropertyOptions(t),!((i.hasChanged??Xi)(a,n)||i.useDefault&&i.reflect&&a===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,i))))return;this.C(t,n,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,n,{useDefault:i,reflect:s,wrapped:a},o){i&&!(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||i||(n=void 0),this._$AL.set(t,n)),s===!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[s,a]of this._$Ep)this[s]=a;this._$Ep=void 0}const i=this.constructor.elementProperties;if(i.size>0)for(const[s,a]of i){const{wrapped:o}=a,r=this[s];o!==!0||this._$AL.has(s)||r===void 0||this.C(s,void 0,a,r)}}let t=!1;const n=this._$AL;try{t=this.shouldUpdate(n),t?(this.willUpdate(n),this._$EO?.forEach(i=>i.hostUpdate?.()),this.update(n)):this._$EM()}catch(i){throw t=!1,this._$EM(),i}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){}};ot.elementStyles=[],ot.shadowRootOptions={mode:"open"},ot[Ct("elementProperties")]=new Map,ot[Ct("finalized")]=new Map,Rr?.({ReactiveElement:ot}),(Sn.reactiveElementVersions??=[]).push("2.1.2");const es=globalThis,ua=e=>e,vn=es.trustedTypes,fa=vn?vn.createPolicy("lit-html",{createHTML:e=>e}):void 0,To="$lit$",Ie=`lit$${Math.random().toFixed(9).slice(2)}$`,Lo="?"+Ie,Mr=`<${Lo}>`,We=document,Mt=()=>We.createComment(""),Pt=e=>e===null||typeof e!="object"&&typeof e!="function",ts=Array.isArray,Pr=e=>ts(e)||typeof e?.[Symbol.iterator]=="function",ti=`[ \f\r]`,vt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ga=/-->/g,pa=/>/g,Ue=RegExp(`>|${ti}(?:([^\\s"'>=/]+)(${ti}*=${ti}*(?:[^ \f\r"'\`<>=]|("|')|))|$)`,"g"),ha=/'/g,va=/"/g,Io=/^(?:script|style|textarea|title)$/i,Fr=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),l=Fr(1),Me=Symbol.for("lit-noChange"),p=Symbol.for("lit-nothing"),ma=new WeakMap,je=We.createTreeWalker(We,129);function Ro(e,t){if(!ts(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return fa!==void 0?fa.createHTML(t):t}const Nr=(e,t)=>{const n=e.length-1,i=[];let s,a=t===2?"":t===3?"":"",o=vt;for(let r=0;r"?(o=s??vt,g=-1):f[1]===void 0?g=-2:(g=o.lastIndex-f[2].length,u=f[1],o=f[3]===void 0?Ue:f[3]==='"'?va:ha):o===va||o===ha?o=Ue:o===ga||o===pa?o=vt:(o=Ue,s=void 0);const v=o===Ue&&e[r+1].startsWith("/>")?" ":"";a+=o===vt?c+Mr:g>=0?(i.push(u),c.slice(0,g)+To+c.slice(g)+Ie+v):c+Ie+(g===-2?r:v)}return[Ro(e,a+(e[n]||"")+(t===2?"":t===3?"":"")),i]};let Ai=class Mo{constructor({strings:t,_$litType$:n},i){let s;this.parts=[];let a=0,o=0;const r=t.length-1,c=this.parts,[u,f]=Nr(t,n);if(this.el=Mo.createElement(u,i),je.currentNode=this.el.content,n===2||n===3){const g=this.el.content.firstChild;g.replaceWith(...g.childNodes)}for(;(s=je.nextNode())!==null&&c.length0){s.textContent=vn?vn.emptyScript:"";for(let v=0;v2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=p}_$AI(t,n=this,i,s){const a=this.strings;let o=!1;if(a===void 0)t=ct(this,t,n,0),o=!Pt(t)||t!==this._$AH&&t!==Me,o&&(this._$AH=t);else{const r=t;let c,u;for(t=a[0],c=0;c{const i=n?.renderBefore??t;let s=i._$litPart$;if(s===void 0){const a=n?.renderBefore??null;i._$litPart$=s=new _n(t.insertBefore(Mt(),a),a,void 0,n??{})}return s._$AI(e),s};const ns=globalThis;let rt=class extends ot{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=jr(n,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Me}};rt._$litElement$=!0,rt.finalized=!0,ns.litElementHydrateSupport?.({LitElement:rt});const Gr=ns.litElementPolyfillSupport;Gr?.({LitElement:rt});(ns.litElementVersions??=[]).push("4.2.2");const Fo=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Wr={attribute:!0,type:String,converter:hn,reflect:!1,hasChanged:Xi},qr=(e=Wr,t,n)=>{const{kind:i,metadata:s}=n;let a=globalThis.litPropertyMetadata.get(s);if(a===void 0&&globalThis.litPropertyMetadata.set(s,a=new Map),i==="setter"&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),i==="accessor"){const{name:o}=n;return{set(r){const c=t.get.call(this);t.set.call(this,r),this.requestUpdate(o,c,e,!0,r)},init(r){return r!==void 0&&this.C(o,void 0,e,r),r}}}if(i==="setter"){const{name:o}=n;return function(r){const c=this[o];t.call(this,r),this.requestUpdate(o,c,e,!0,r)}}throw Error("Unsupported decorator location: "+i)};function En(e){return(t,n)=>typeof n=="object"?qr(e,t,n):((i,s,a)=>{const o=s.hasOwnProperty(a);return s.constructor.createProperty(a,i),o?Object.getOwnPropertyDescriptor(s,a):void 0})(e,t,n)}function k(e){return En({...e,state:!0,attribute:!1})}async function se(e,t){if(!(!e.client||!e.connected)&&!e.channelsLoading){e.channelsLoading=!0,e.channelsError=null;try{const n=await e.client.request("channels.status",{probe:t,timeoutMs:8e3});e.channelsSnapshot=n,e.channelsLastSuccess=Date.now()}catch(n){e.channelsError=String(n)}finally{e.channelsLoading=!1}}}async function Vr(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 Yr(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 Qr(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{await e.client.request("channels.logout",{channel:"whatsapp"}),e.whatsappLoginMessage="Logged out.",e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}catch(t){e.whatsappLoginMessage=String(t)}finally{e.whatsappBusy=!1}}}function qe(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function dt(e){return`${JSON.stringify(e,null,2).trimEnd()} `}function No(e,t,n){if(t.length===0)return;let i=e;for(let a=0;a{const{type:f="text",placeholder:g,maxLength:m,help:v}=u,b=t.values[r]??"",d=t.fieldErrors[r],y=`nostr-profile-${r}`;return f==="textarea"?l`
${v?l`
${v}
`:p} ${d?l`
${d}
`:p}
`:l`
{const S=A.target;n.onFieldChange(r,S.value)}} ?disabled=${t.saving} /> ${v?l`
${v}
`:p} ${d?l`
${d}
`:p}
`},o=()=>{const r=t.values.picture;return r?l`
Profile picture preview{const u=c.target;u.style.display="none"}} @load=${c=>{const u=c.target;u.style.display="block"}} />
`:p};return l`
Edit Profile
Account: ${i}
${t.error?l`
${t.error}
`:p} ${t.success?l`
${t.success}
`:p} ${o()} ${a("name","Username",{placeholder:"satoshi",maxLength:256,help:"Short username (e.g., satoshi)"})} ${a("displayName","Display Name",{placeholder:"Satoshi Nakamoto",maxLength:256,help:"Your full display name"})} ${a("about","Bio",{type:"textarea",placeholder:"Tell people about yourself...",maxLength:2e3,help:"A brief bio or description"})} ${a("picture","Avatar URL",{type:"url",placeholder:"https://example.com/avatar.jpg",help:"HTTPS URL to your profile picture"})} ${t.showAdvanced?l`
Advanced
${a("banner","Banner URL",{type:"url",placeholder:"https://example.com/banner.jpg",help:"HTTPS URL to a banner image"})} ${a("website","Website",{type:"url",placeholder:"https://example.com",help:"Your personal website"})} ${a("nip05","NIP-05 Identifier",{placeholder:"you@example.com",help:"Verifiable identifier (e.g., you@domain.com)"})} ${a("lud16","Lightning Address",{placeholder:"you@getalby.com",help:"Lightning address for tips (LUD-16)"})}
`:p}
${s?l`
You have unsaved changes
`:p}
`}function ic(e){const t={name:e?.name??"",displayName:e?.displayName??"",about:e?.about??"",picture:e?.picture??"",banner:e?.banner??"",website:e?.website??"",nip05:e?.nip05??"",lud16:e?.lud16??""};return{values:t,original:{...t},saving:!1,importing:!1,error:null,success:null,fieldErrors:{},showAdvanced:!!(e?.banner||e?.website||e?.nip05||e?.lud16)}}async function sc(e,t){await Vr(e,t),await se(e,!0)}async function ac(e){await Yr(e),await se(e,!0)}async function oc(e){await Qr(e),await se(e,!0)}async function lc(e){await un(e),await pe(e),await se(e,!0)}async function rc(e){await pe(e),await se(e,!0)}function cc(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[i,...s]=n.split(":");if(!i||s.length===0)continue;const a=i.trim(),o=s.join(":").trim();a&&o&&(t[a]=o)}return t}function Bo(e){return(e.channelsSnapshot?.channelAccounts?.nostr??[])[0]?.accountId??e.nostrProfileAccountId??"default"}function Uo(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function dc(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=ic(n??void 0)}function uc(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function fc(e,t,n){const i=e.nostrProfileFormState;i&&(e.nostrProfileFormState={...i,values:{...i.values,[t]:n},fieldErrors:{...i.fieldErrors,[t]:""}})}function gc(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function pc(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=Bo(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const i=await fetch(Uo(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),s=await i.json().catch(()=>null);if(!i.ok||s?.ok===!1||!s){const a=s?.error??`Profile update failed (${i.status})`;e.nostrProfileFormState={...t,saving:!1,error:a,success:null,fieldErrors:cc(s?.details)};return}if(!s.persisted){e.nostrProfileFormState={...t,saving:!1,error:"Profile publish failed on all relays.",success:null};return}e.nostrProfileFormState={...t,saving:!1,error:null,success:"Profile published to relays.",fieldErrors:{},original:{...t.values}},await se(e,!0)}catch(i){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(i)}`,success:null}}}async function hc(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=Bo(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const i=await fetch(Uo(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),s=await i.json().catch(()=>null);if(!i.ok||s?.ok===!1||!s){const c=s?.error??`Profile import failed (${i.status})`;e.nostrProfileFormState={...t,importing:!1,error:c,success:null};return}const a=s.merged??s.imported??null,o=a?{...t.values,...a}:t.values,r=!!(o.banner||o.website||o.nip05||o.lud16);e.nostrProfileFormState={...t,importing:!1,values:o,error:null,success:s.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:r},s.saved&&await se(e,!0)}catch(i){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(i)}`,success:null}}}function Ko(e){const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const i=n[1]?.trim(),s=n.slice(2).join(":");return!i||!s?null:{agentId:i,rest:s}}const xi=450;function Ut(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=()=>{const i=e.querySelector(".chat-thread");if(i){const s=getComputedStyle(i).overflowY;if(s==="auto"||s==="scroll"||i.scrollHeight-i.clientHeight>1)return i}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{e.chatScrollFrame=requestAnimationFrame(()=>{e.chatScrollFrame=null;const i=n();if(!i)return;const s=i.scrollHeight-i.scrollTop-i.clientHeight,a=t&&!e.chatHasAutoScrolled;if(!(a||e.chatUserNearBottom||s{e.chatScrollTimeout=null;const c=n();if(!c)return;const u=c.scrollHeight-c.scrollTop-c.clientHeight;(a||e.chatUserNearBottom||u{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");if(!n)return;const i=n.scrollHeight-n.scrollTop-n.clientHeight;(t||i<80)&&(n.scrollTop=n.scrollHeight)})})}function vc(e,t){const n=t.currentTarget;if(!n)return;const i=n.scrollHeight-n.scrollTop-n.clientHeight;e.chatUserNearBottom=i"u")return;const t=e.querySelector(".topbar");if(!t)return;const n=()=>{const{height:i}=t.getBoundingClientRect();e.style.setProperty("--topbar-height",`${i}px`)};n(),e.topbarObserver=new ResizeObserver(()=>n()),e.topbarObserver.observe(t)}async function Tn(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,i,s]=await Promise.all([e.client.request("status",{}),e.client.request("health",{}),e.client.request("models.list",{}),e.client.request("last-heartbeat",{})]);e.debugStatus=t,e.debugHealth=n;const a=i;e.debugModels=Array.isArray(a?.models)?a?.models:[],e.debugHeartbeat=s}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}async function wc(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 $c=2e3,kc=new Set(["trace","debug","info","warn","error","fatal"]);function Ac(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 xc(e){if(typeof e!="string")return null;const t=e.toLowerCase();return kc.has(t)?t:null}function Sc(e){if(!e.trim())return{raw:e,message:e};try{const t=JSON.parse(e),n=t&&typeof t._meta=="object"&&t._meta!==null?t._meta:null,i=typeof t.time=="string"?t.time:typeof n?.date=="string"?n?.date:null,s=xc(n?.logLevelName??n?.level),a=typeof t[0]=="string"?t[0]:typeof n?.name=="string"?n?.name:null,o=Ac(a);let r=null;o&&(typeof o.subsystem=="string"?r=o.subsystem:typeof o.module=="string"&&(r=o.module)),!r&&a&&a.length<120&&(r=a);let c=null;return typeof t[1]=="string"?c=t[1]:!o&&typeof t[0]=="string"?c=t[0]:typeof t.message=="string"&&(c=t.message),{raw:e,time:i,level:s,subsystem:r,message:c??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function is(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!t?.quiet)){t?.quiet||(e.logsLoading=!0),e.logsError=null;try{const i=await e.client.request("logs.tail",{cursor:t?.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),a=(Array.isArray(i.lines)?i.lines.filter(r=>typeof r=="string"):[]).map(Sc),o=!!(t?.reset||i.reset||e.logsCursor==null);e.logsEntries=o?a:[...e.logsEntries,...a].slice(-$c),typeof i.cursor=="number"&&(e.logsCursor=i.cursor),typeof i.file=="string"&&(e.logsFile=i.file),e.logsTruncated=!!i.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t?.quiet||(e.logsLoading=!1)}}}async function Ln(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}}}function _c(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{Ln(e,{quiet:!0})},5e3))}function Cc(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function ss(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&is(e,{quiet:!0})},2e3))}function as(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function os(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&Tn(e)},3e3))}function ls(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}async function Ho(e,t){if(!(!e.client||!e.connected||e.agentIdentityLoading)&&!e.agentIdentityById[t]){e.agentIdentityLoading=!0,e.agentIdentityError=null;try{const n=await e.client.request("agent.identity.get",{agentId:t});n&&(e.agentIdentityById={...e.agentIdentityById,[t]:n})}catch(n){e.agentIdentityError=String(n)}finally{e.agentIdentityLoading=!1}}}async function jo(e,t){if(!e.client||!e.connected||e.agentIdentityLoading)return;const n=t.filter(i=>!e.agentIdentityById[i]);if(n.length!==0){e.agentIdentityLoading=!0,e.agentIdentityError=null;try{for(const i of n){const s=await e.client.request("agent.identity.get",{agentId:i});s&&(e.agentIdentityById={...e.agentIdentityById,[i]:s})}}catch(i){e.agentIdentityError=String(i)}finally{e.agentIdentityLoading=!1}}}async function fn(e,t){if(!(!e.client||!e.connected)&&!e.agentSkillsLoading){e.agentSkillsLoading=!0,e.agentSkillsError=null;try{const n=await e.client.request("skills.status",{agentId:t});n&&(e.agentSkillsReport=n,e.agentSkillsAgentId=t)}catch(n){e.agentSkillsError=String(n)}finally{e.agentSkillsLoading=!1}}}async function rs(e){if(!(!e.client||!e.connected)&&!e.agentsLoading){e.agentsLoading=!0,e.agentsError=null;try{const t=await e.client.request("agents.list",{});if(t){e.agentsList=t;const n=e.agentsSelectedId,i=t.agents.some(s=>s.id===n);(!n||!i)&&(e.agentsSelectedId=t.defaultId??t.agents[0]?.id??null)}}catch(t){e.agentsError=String(t)}finally{e.agentsLoading=!1}}}const Ec=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,Xt=/<\s*\/?\s*final\b[^<>]*>/gi,ba=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^<>]*>/gi;function wa(e){const t=[],n=/(^|\n)(```|~~~)[^\n]*\n[\s\S]*?(?:\n\2(?:\n|$)|$)/g;for(const s of e.matchAll(n)){const a=(s.index??0)+s[1].length;t.push({start:a,end:a+s[0].length-s[1].length})}const i=/`+[^`]+`+/g;for(const s of e.matchAll(i)){const a=s.index??0,o=a+s[0].length;t.some(c=>a>=c.start&&o<=c.end)||t.push({start:a,end:o})}return t.sort((s,a)=>s.start-a.start),t}function $a(e,t){return t.some(n=>e>=n.start&&e=0;u--){const f=r[u];f.inCode||(n=n.slice(0,f.start)+n.slice(f.start+f.length))}}else Xt.lastIndex=0;const i=wa(n);ba.lastIndex=0;let s="",a=0,o=!1;for(const r of n.matchAll(ba)){const c=r.index??0,u=r[1]==="/";$a(c,i)||(o?u&&(o=!1):(s+=n.slice(a,c),u||(o=!0)),a=c+r[0].length)}return s+=n.slice(a),Tc(s)}function Ft(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString()}function O(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e,n=Math.abs(t),i=t<0?"from now":"ago",s=Math.round(n/1e3);if(s<60)return t<0?"just now":`${s}s ago`;const a=Math.round(s/60);if(a<60)return`${a}m ${i}`;const o=Math.round(a/60);return o<48?`${o}h ${i}`:`${Math.round(o/24)}d ${i}`}function Go(e){if(!e&&e!==0)return"n/a";if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);if(n<60)return`${n}m`;const i=Math.round(n/60);return i<48?`${i}h`:`${Math.round(i/24)}d`}function Si(e){return!e||e.length===0?"none":e.filter(t=>!!(t&&t.trim())).join(", ")}function _i(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Wo(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 mn(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function ni(e){return Lc(e)}async function Kt(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("cron.status",{});e.cronStatus=t}catch(t){e.cronError=String(t)}}async function In(e){if(!(!e.client||!e.connected)&&!e.cronLoading){e.cronLoading=!0,e.cronError=null;try{const t=await e.client.request("cron.list",{includeDisabled:!0});e.cronJobs=Array.isArray(t.jobs)?t.jobs:[]}catch(t){e.cronError=String(t)}finally{e.cronLoading=!1}}}function Ic(e){if(e.scheduleKind==="at"){const n=Date.parse(e.scheduleAt);if(!Number.isFinite(n))throw new Error("Invalid run time.");return{kind:"at",at:new Date(n).toISOString()}}if(e.scheduleKind==="every"){const n=mn(e.everyAmount,0);if(n<=0)throw new Error("Invalid interval amount.");const i=e.everyUnit;return{kind:"every",everyMs:n*(i==="minutes"?6e4:i==="hours"?36e5:864e5)}}const t=e.cronExpr.trim();if(!t)throw new Error("Cron expression required.");return{kind:"cron",expr:t,tz:e.cronTz.trim()||void 0}}function Rc(e){if(e.payloadKind==="systemEvent"){const s=e.payloadText.trim();if(!s)throw new Error("System event text required.");return{kind:"systemEvent",text:s}}const t=e.payloadText.trim();if(!t)throw new Error("Agent message required.");const n={kind:"agentTurn",message:t},i=mn(e.timeoutSeconds,0);return i>0&&(n.timeoutSeconds=i),n}async function Mc(e){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const t=Ic(e.cronForm),n=Rc(e.cronForm),i=e.cronForm.sessionTarget==="isolated"&&e.cronForm.payloadKind==="agentTurn"&&e.cronForm.deliveryMode?{mode:e.cronForm.deliveryMode==="announce"?"announce":"none",channel:e.cronForm.deliveryChannel.trim()||"last",to:e.cronForm.deliveryTo.trim()||void 0}:void 0,s=e.cronForm.agentId.trim(),a={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,enabled:e.cronForm.enabled,schedule:t,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:n,delivery:i};if(!a.name)throw new Error("Name required.");await e.client.request("cron.add",a),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await In(e),await Kt(e)}catch(t){e.cronError=String(t)}finally{e.cronBusy=!1}}}async function Pc(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 In(e),await Kt(e)}catch(i){e.cronError=String(i)}finally{e.cronBusy=!1}}}async function Fc(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 qo(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function Nc(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 In(e),await Kt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function qo(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)}}const Vo="openclaw.device.auth.v1";function cs(e){return e.trim()}function Dc(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const i=n.trim();i&&t.add(i)}return[...t].toSorted()}function ds(){try{const e=window.localStorage.getItem(Vo);if(!e)return null;const t=JSON.parse(e);return!t||t.version!==1||!t.deviceId||typeof t.deviceId!="string"||!t.tokens||typeof t.tokens!="object"?null:t}catch{return null}}function Yo(e){try{window.localStorage.setItem(Vo,JSON.stringify(e))}catch{}}function Oc(e){const t=ds();if(!t||t.deviceId!==e.deviceId)return null;const n=cs(e.role),i=t.tokens[n];return!i||typeof i.token!="string"?null:i}function Qo(e){const t=cs(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},i=ds();i&&i.deviceId===e.deviceId&&(n.tokens={...i.tokens});const s={token:e.token,role:t,scopes:Dc(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=s,Yo(n),s}function Jo(e){const t=ds();if(!t||t.deviceId!==e.deviceId)return;const n=cs(e.role);if(!t.tokens[n])return;const i={...t,tokens:{...t.tokens}};delete i.tokens[n],Yo(i)}const Zo={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:Z,n:gn,Gx:ka,Gy:Aa,a:ii,d:si,h:Bc}=Zo,Ve=32,us=64,Uc=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},W=(e="")=>{const t=new Error(e);throw Uc(t,W),t},Kc=e=>typeof e=="bigint",zc=e=>typeof e=="string",Hc=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",Fe=(e,t,n="")=>{const i=Hc(e),s=e?.length,a=t!==void 0;if(!i||a&&s!==t){const o=n&&`"${n}" `,r=a?` of length ${t}`:"",c=i?`length=${s}`:`type=${typeof e}`;W(o+"expected Uint8Array"+r+", got "+c)}return e},Rn=e=>new Uint8Array(e),Xo=e=>Uint8Array.from(e),el=(e,t)=>e.toString(16).padStart(t,"0"),tl=e=>Array.from(Fe(e)).map(t=>el(t,2)).join(""),Se={_0:48,_9:57,A:65,F:70,a:97,f:102},xa=e=>{if(e>=Se._0&&e<=Se._9)return e-Se._0;if(e>=Se.A&&e<=Se.F)return e-(Se.A-10);if(e>=Se.a&&e<=Se.f)return e-(Se.a-10)},nl=e=>{const t="hex invalid";if(!zc(e))return W(t);const n=e.length,i=n/2;if(n%2)return W(t);const s=Rn(i);for(let a=0,o=0;aglobalThis?.crypto,jc=()=>il()?.subtle??W("crypto.subtle must be defined, consider polyfill"),Nt=(...e)=>{const t=Rn(e.reduce((i,s)=>i+Fe(s).length,0));let n=0;return e.forEach(i=>{t.set(i,n),n+=i.length}),t},Gc=(e=Ve)=>il().getRandomValues(Rn(e)),yn=BigInt,He=(e,t,n,i="bad number: out of range")=>Kc(e)&&t<=e&&e{const n=e%t;return n>=0n?n:t+n},sl=e=>L(e,gn),Wc=(e,t)=>{(e===0n||t<=0n)&&W("no inverse n="+e+" mod="+t);let n=L(e,t),i=t,s=0n,a=1n;for(;n!==0n;){const o=i/n,r=i%n,c=s-a*o;i=n,n=r,s=a,a=c}return i===1n?L(s,t):W("no inverse")},qc=e=>{const t=rl[e];return typeof t!="function"&&W("hashes."+e+" not set"),t},ai=e=>e instanceof oe?e:W("Point expected"),Ci=2n**256n;class oe{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,i,s){const a=Ci;this.X=He(t,0n,a),this.Y=He(n,0n,a),this.Z=He(i,1n,a),this.T=He(s,0n,a),Object.freeze(this)}static CURVE(){return Zo}static fromAffine(t){return new oe(t.x,t.y,1n,L(t.x*t.y))}static fromBytes(t,n=!1){const i=si,s=Xo(Fe(t,Ve)),a=t[31];s[31]=a&-129;const o=ol(s);He(o,0n,n?Ci:Z);const c=L(o*o),u=L(c-1n),f=L(i*c+1n);let{isValid:g,value:m}=Yc(u,f);g||W("bad point: y not sqrt");const v=(m&1n)===1n,b=(a&128)!==0;return!n&&m===0n&&b&&W("bad point: x==0, isLastByteOdd"),b!==v&&(m=L(-m)),new oe(m,o,1n,L(m*o))}static fromHex(t,n){return oe.fromBytes(nl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=ii,n=si,i=this;if(i.is0())return W("bad point: ZERO");const{X:s,Y:a,Z:o,T:r}=i,c=L(s*s),u=L(a*a),f=L(o*o),g=L(f*f),m=L(c*t),v=L(f*L(m+u)),b=L(g+L(n*L(c*u)));if(v!==b)return W("bad point: equation left != right (1)");const d=L(s*a),y=L(o*r);return d!==y?W("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:i,Z:s}=this,{X:a,Y:o,Z:r}=ai(t),c=L(n*r),u=L(a*s),f=L(i*r),g=L(o*s);return c===u&&f===g}is0(){return this.equals(lt)}negate(){return new oe(L(-this.X),this.Y,this.Z,L(-this.T))}double(){const{X:t,Y:n,Z:i}=this,s=ii,a=L(t*t),o=L(n*n),r=L(2n*L(i*i)),c=L(s*a),u=t+n,f=L(L(u*u)-a-o),g=c+o,m=g-r,v=c-o,b=L(f*m),d=L(g*v),y=L(f*v),A=L(m*g);return new oe(b,d,A,y)}add(t){const{X:n,Y:i,Z:s,T:a}=this,{X:o,Y:r,Z:c,T:u}=ai(t),f=ii,g=si,m=L(n*o),v=L(i*r),b=L(a*g*u),d=L(s*c),y=L((n+i)*(o+r)-m-v),A=L(d-b),S=L(d+b),T=L(v-f*m),x=L(y*A),C=L(S*T),E=L(y*T),P=L(A*S);return new oe(x,C,P,E)}subtract(t){return this.add(ai(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return lt;if(He(t,1n,gn),t===1n)return this;if(this.equals(Ye))return od(t).p;let i=lt,s=Ye;for(let a=this;t>0n;a=a.double(),t>>=1n)t&1n?i=i.add(a):n&&(s=s.add(a));return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:i}=this;if(this.equals(lt))return{x:0n,y:1n};const s=Wc(i,Z);L(i*s)!==1n&&W("invalid inverse");const a=L(t*s),o=L(n*s);return{x:a,y:o}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),i=al(n);return i[31]|=t&1n?128:0,i}toHex(){return tl(this.toBytes())}clearCofactor(){return this.multiply(yn(Bc),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(gn/2n,!1).double();return gn%2n&&(t=t.add(this)),t.is0()}}const Ye=new oe(ka,Aa,1n,L(ka*Aa)),lt=new oe(0n,1n,1n,0n);oe.BASE=Ye;oe.ZERO=lt;const al=e=>nl(el(He(e,0n,Ci),us)).reverse(),ol=e=>yn("0x"+tl(Xo(Fe(e)).reverse())),ye=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=Z;return n},Vc=e=>{const n=e*e%Z*e%Z,i=ye(n,2n)*n%Z,s=ye(i,1n)*e%Z,a=ye(s,5n)*s%Z,o=ye(a,10n)*a%Z,r=ye(o,20n)*o%Z,c=ye(r,40n)*r%Z,u=ye(c,80n)*c%Z,f=ye(u,80n)*c%Z,g=ye(f,10n)*a%Z;return{pow_p_5_8:ye(g,2n)*e%Z,b2:n}},Sa=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Yc=(e,t)=>{const n=L(t*t*t),i=L(n*n*t),s=Vc(e*i).pow_p_5_8;let a=L(e*n*s);const o=L(t*a*a),r=a,c=L(a*Sa),u=o===e,f=o===L(-e),g=o===L(-e*Sa);return u&&(a=r),(f||g)&&(a=c),(L(a)&1n)===1n&&(a=L(-a)),{isValid:u||f,value:a}},Ei=e=>sl(ol(e)),fs=(...e)=>rl.sha512Async(Nt(...e)),Qc=(...e)=>qc("sha512")(Nt(...e)),ll=e=>{const t=e.slice(0,Ve);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Ve,us),i=Ei(t),s=Ye.multiply(i),a=s.toBytes();return{head:t,prefix:n,scalar:i,point:s,pointBytes:a}},gs=e=>fs(Fe(e,Ve)).then(ll),Jc=e=>ll(Qc(Fe(e,Ve))),Zc=e=>gs(e).then(t=>t.pointBytes),Xc=e=>fs(e.hashable).then(e.finish),ed=(e,t,n)=>{const{pointBytes:i,scalar:s}=e,a=Ei(t),o=Ye.multiply(a).toBytes();return{hashable:Nt(o,i,n),finish:u=>{const f=sl(a+Ei(u)*s);return Fe(Nt(o,al(f)),us)}}},td=async(e,t)=>{const n=Fe(e),i=await gs(t),s=await fs(i.prefix,n);return Xc(ed(i,s,n))},rl={sha512Async:async e=>{const t=jc(),n=Nt(e);return Rn(await t.digest("SHA-512",n.buffer))},sha512:void 0},nd=(e=Gc(Ve))=>e,id={getExtendedPublicKeyAsync:gs,getExtendedPublicKey:Jc,randomSecretKey:nd},bn=8,sd=256,cl=Math.ceil(sd/bn)+1,Ti=2**(bn-1),ad=()=>{const e=[];let t=Ye,n=t;for(let i=0;i{const n=t.negate();return e?n:t},od=e=>{const t=_a||(_a=ad());let n=lt,i=Ye;const s=2**bn,a=s,o=yn(s-1),r=yn(bn);for(let c=0;c>=r,u>Ti&&(u-=a,e+=1n);const f=c*Ti,g=f,m=f+Math.abs(u)-1,v=c%2!==0,b=u<0;u===0?i=i.add(Ca(v,t[g])):n=n.add(Ca(b,t[m]))}return e!==0n&&W("invalid wnaf"),{p:n,f:i}},oi="openclaw-device-identity-v1";function Li(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/g,"")}function dl(e){const t=e.replaceAll("-","+").replaceAll("_","/"),n=t+"=".repeat((4-t.length%4)%4),i=atob(n),s=new Uint8Array(i.length);for(let a=0;at.toString(16).padStart(2,"0")).join("")}async function ul(e){const t=await crypto.subtle.digest("SHA-256",e.slice().buffer);return ld(new Uint8Array(t))}async function rd(){const e=id.randomSecretKey(),t=await Zc(e);return{deviceId:await ul(t),publicKey:Li(t),privateKey:Li(e)}}async function ps(){try{const n=localStorage.getItem(oi);if(n){const i=JSON.parse(n);if(i?.version===1&&typeof i.deviceId=="string"&&typeof i.publicKey=="string"&&typeof i.privateKey=="string"){const s=await ul(dl(i.publicKey));if(s!==i.deviceId){const a={...i,deviceId:s};return localStorage.setItem(oi,JSON.stringify(a)),{deviceId:s,publicKey:i.publicKey,privateKey:i.privateKey}}return{deviceId:i.deviceId,publicKey:i.publicKey,privateKey:i.privateKey}}}}catch{}const e=await rd(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(oi,JSON.stringify(t)),e}async function cd(e,t){const n=dl(e),i=new TextEncoder().encode(t),s=await td(i,n);return Li(s)}async function Ne(e,t){if(!(!e.client||!e.connected)&&!e.devicesLoading){e.devicesLoading=!0,t?.quiet||(e.devicesError=null);try{const n=await e.client.request("device.pair.list",{});e.devicesList={pending:Array.isArray(n?.pending)?n.pending:[],paired:Array.isArray(n?.paired)?n.paired:[]}}catch(n){t?.quiet||(e.devicesError=String(n))}finally{e.devicesLoading=!1}}}async function dd(e,t){if(!(!e.client||!e.connected))try{await e.client.request("device.pair.approve",{requestId:t}),await Ne(e)}catch(n){e.devicesError=String(n)}}async function ud(e,t){if(!(!e.client||!e.connected||!window.confirm("Reject this device pairing request?")))try{await e.client.request("device.pair.reject",{requestId:t}),await Ne(e)}catch(i){e.devicesError=String(i)}}async function fd(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("device.token.rotate",t);if(n?.token){const i=await ps(),s=n.role??t.role;(n.deviceId===i.deviceId||t.deviceId===i.deviceId)&&Qo({deviceId:i.deviceId,role:s,token:n.token,scopes:n.scopes??t.scopes??[]}),window.prompt("New device token (copy and store securely):",n.token)}await Ne(e)}catch(n){e.devicesError=String(n)}}async function gd(e,t){if(!(!e.client||!e.connected||!window.confirm(`Revoke token for ${t.deviceId} (${t.role})?`)))try{await e.client.request("device.token.revoke",t);const i=await ps();t.deviceId===i.deviceId&&Jo({deviceId:i.deviceId,role:t.role}),await Ne(e)}catch(i){e.devicesError=String(i)}}function pd(e){if(!e||e.kind==="gateway")return{method:"exec.approvals.get",params:{}};const t=e.nodeId.trim();return t?{method:"exec.approvals.node.get",params:{nodeId:t}}:null}function hd(e,t){if(!e||e.kind==="gateway")return{method:"exec.approvals.set",params:t};const n=e.nodeId.trim();return n?{method:"exec.approvals.node.set",params:{...t,nodeId:n}}:null}async function hs(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=pd(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const i=await e.client.request(n.method,n.params);vd(e,i)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function vd(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=qe(t.file??{}))}async function md(e,t){if(!(!e.client||!e.connected)){e.execApprovalsSaving=!0,e.lastError=null;try{const n=e.execApprovalsSnapshot?.hash;if(!n){e.lastError="Exec approvals hash missing; reload and retry.";return}const i=e.execApprovalsForm??e.execApprovalsSnapshot?.file??{},s=hd(t,{file:i,baseHash:n});if(!s){e.lastError="Select a node before saving exec approvals.";return}await e.client.request(s.method,s.params),e.execApprovalsDirty=!1,await hs(e,t)}catch(n){e.lastError=String(n)}finally{e.execApprovalsSaving=!1}}}function yd(e,t,n){const i=qe(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});No(i,t,n),e.execApprovalsForm=i,e.execApprovalsDirty=!0}function bd(e,t){const n=qe(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});Do(n,t),e.execApprovalsForm=n,e.execApprovalsDirty=!0}async function vs(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 Je(e,t){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const n=t?.includeGlobal??e.sessionsIncludeGlobal,i=t?.includeUnknown??e.sessionsIncludeUnknown,s=t?.activeMinutes??mn(e.sessionsFilterActive,0),a=t?.limit??mn(e.sessionsFilterLimit,0),o={includeGlobal:n,includeUnknown:i};s>0&&(o.activeMinutes=s),a>0&&(o.limit=a);const r=await e.client.request("sessions.list",o);r&&(e.sessionsResult=r)}catch(n){e.sessionsError=String(n)}finally{e.sessionsLoading=!1}}}async function wd(e,t,n){if(!e.client||!e.connected)return;const i={key:t};"label"in n&&(i.label=n.label),"thinkingLevel"in n&&(i.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(i.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(i.reasoningLevel=n.reasoningLevel);try{await e.client.request("sessions.patch",i),await Je(e)}catch(s){e.sessionsError=String(s)}}async function $d(e,t){if(!(!e.client||!e.connected||e.sessionsLoading||!window.confirm(`Delete session "${t}"? Deletes the session entry and archives its transcript.`))){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.delete",{key:t,deleteTranscript:!0}),await Je(e)}catch(i){e.sessionsError=String(i)}finally{e.sessionsLoading=!1}}}function ut(e,t,n){if(!t.trim())return;const i={...e.skillMessages};n?i[t]=n:delete i[t],e.skillMessages=i}function Mn(e){return e instanceof Error?e.message:String(e)}async function zt(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=Mn(n)}finally{e.skillsLoading=!1}}}function kd(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Ad(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 zt(e),ut(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(i){const s=Mn(i);e.skillsError=s,ut(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function xd(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 zt(e),ut(e,t,{kind:"success",message:"API key saved"})}catch(n){const i=Mn(n);e.skillsError=i,ut(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Sd(e,t,n,i){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const s=await e.client.request("skills.install",{name:n,installId:i,timeoutMs:12e4});await zt(e),ut(e,t,{kind:"success",message:s?.message??"Installed"})}catch(s){const a=Mn(s);e.skillsError=a,ut(e,t,{kind:"error",message:a})}finally{e.skillsBusyKey=null}}}const _d=[{label:"Chat",tabs:["chat"]},{label:"Control",tabs:["overview","channels","instances","sessions","cron"]},{label:"Agent",tabs:["agents","skills","nodes"]},{label:"Settings",tabs:["config","debug","logs"]}],fl={agents:"/agents",overview:"/overview",channels:"/channels",instances:"/instances",sessions:"/sessions",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",config:"/config",debug:"/debug",logs:"/logs"},gl=new Map(Object.entries(fl).map(([e,t])=>[t,e]));function Ht(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function Dt(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 ms(e,t=""){const n=Ht(t),i=fl[e];return n?`${n}${i}`:i}function pl(e,t=""){const n=Ht(t);let i=e||"/";n&&(i===n?i="/":i.startsWith(`${n}/`)&&(i=i.slice(n.length)));let s=Dt(i).toLowerCase();return s.endsWith("/index.html")&&(s="/"),s==="/"?"chat":gl.get(s)??null}function Cd(e){let t=Dt(e);if(t.endsWith("/index.html")&&(t=Dt(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let i=0;i=.4&&i.splitRatio<=.7?i.splitRatio:t.splitRatio,navCollapsed:typeof i.navCollapsed=="boolean"?i.navCollapsed:t.navCollapsed,navGroupsCollapsed:typeof i.navGroupsCollapsed=="object"&&i.navGroupsCollapsed!==null?i.navGroupsCollapsed:t.navGroupsCollapsed}}catch{return t}}function Id(e){localStorage.setItem(hl,JSON.stringify(e))}const en=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,Rd=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,tn=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},Md=({nextTheme:e,applyTheme:t,context:n,currentTheme:i})=>{if(i===e)return;const s=globalThis.document??null;if(!s){t();return}const a=s.documentElement,o=s,r=Rd();if(!!o.startViewTransition&&!r){let u=.5,f=.5;if(n?.pointerClientX!==void 0&&n?.pointerClientY!==void 0&&typeof window<"u")u=en(n.pointerClientX/window.innerWidth),f=en(n.pointerClientY/window.innerHeight);else if(n?.element){const g=n.element.getBoundingClientRect();g.width>0&&g.height>0&&typeof window<"u"&&(u=en((g.left+g.width/2)/window.innerWidth),f=en((g.top+g.height/2)/window.innerHeight))}a.style.setProperty("--theme-switch-x",`${u*100}%`),a.style.setProperty("--theme-switch-y",`${f*100}%`),a.classList.add("theme-transition");try{const g=o.startViewTransition?.(()=>{t()});g?.finished?g.finished.finally(()=>tn(a)):tn(a)}catch{tn(a),t()}return}t(),tn(a)};function Pd(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ys(e){return e==="system"?Pd():e}function Fd(){try{return window.top===window.self}catch{return!1}}function Nd(e){const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"?null:t}catch{return null}}function Pe(e,t){const n={...t,lastActiveSessionKey:t.lastActiveSessionKey?.trim()||t.sessionKey.trim()||"main"};e.settings=n,Id(n),t.theme!==e.theme&&(e.theme=t.theme,Pn(e,ys(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function vl(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&Pe(e,{...e.settings,lastActiveSessionKey:n})}function Dd(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),i=t.get("password"),s=t.get("session"),a=t.get("gatewayUrl");let o=!1;if(n!=null){const c=n.trim();c&&c!==e.settings.token&&Pe(e,{...e.settings,token:c}),t.delete("token"),o=!0}if(i!=null){const c=i.trim();c&&(e.password=c),t.delete("password"),o=!0}if(s!=null){const c=s.trim();c&&(e.sessionKey=c,Pe(e,{...e.settings,sessionKey:c,lastActiveSessionKey:c}))}if(a!=null){const c=Nd(a);c&&c!==e.settings.gatewayUrl&&Fd()&&(e.pendingGatewayUrl=c),t.delete("gatewayUrl"),o=!0}if(!o)return;const r=new URL(window.location.href);r.search=t.toString(),window.history.replaceState({},"",r.toString())}function Od(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?ss(e):as(e),t==="debug"?os(e):ls(e),bs(e),yl(e,t,!1)}function Bd(e,t,n){Md({nextTheme:t,applyTheme:()=>{e.theme=t,Pe(e,{...e.settings,theme:t}),Pn(e,ys(t))},context:n,currentTheme:e.theme})}async function bs(e){if(e.tab==="overview"&&await bl(e),e.tab==="channels"&&await qd(e),e.tab==="instances"&&await vs(e),e.tab==="sessions"&&await Je(e),e.tab==="cron"&&await wn(e),e.tab==="skills"&&await zt(e),e.tab==="agents"){const t=e;await rs(t),await pe(t);const n=t.agentsList?.agents?.map(s=>s.id)??[];n.length>0&&jo(t,n);const i=t.agentsSelectedId??t.agentsList?.defaultId??t.agentsList?.agents?.[0]?.id;i&&(Ho(t,i),t.agentsPanel==="skills"&&fn(t,i),t.agentsPanel==="channels"&&se(t,!1),t.agentsPanel==="cron"&&wn(e))}e.tab==="nodes"&&(await Ln(e),await Ne(e),await pe(e),await hs(e)),e.tab==="chat"&&(await _l(e),Ut(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await Oo(e),await pe(e)),e.tab==="debug"&&(await Tn(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"&&(e.logsAtBottom=!0,await is(e,{reset:!0}),zo(e,!0))}function Ud(){if(typeof window>"u")return"";const e=window.__OPENCLAW_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?Ht(e):Cd(window.location.pathname)}function Kd(e){e.theme=e.settings.theme??"system",Pn(e,ys(e.theme))}function Pn(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function zd(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;if(e.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),e.themeMediaHandler=n=>{e.theme==="system"&&Pn(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Hd(e){if(!e.themeMedia||!e.themeMediaHandler)return;if(typeof e.themeMedia.removeEventListener=="function"){e.themeMedia.removeEventListener("change",e.themeMediaHandler);return}e.themeMedia.removeListener(e.themeMediaHandler),e.themeMedia=null,e.themeMediaHandler=null}function jd(e,t){if(typeof window>"u")return;const n=pl(window.location.pathname,e.basePath)??"chat";ml(e,n),yl(e,n,t)}function Gd(e){if(typeof window>"u")return;const t=pl(window.location.pathname,e.basePath);if(!t)return;const i=new URL(window.location.href).searchParams.get("session")?.trim();i&&(e.sessionKey=i,Pe(e,{...e.settings,sessionKey:i,lastActiveSessionKey:i})),ml(e,t)}function ml(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?ss(e):as(e),t==="debug"?os(e):ls(e),e.connected&&bs(e)}function yl(e,t,n){if(typeof window>"u")return;const i=Dt(ms(t,e.basePath)),s=Dt(window.location.pathname),a=new URL(window.location.href);t==="chat"&&e.sessionKey?a.searchParams.set("session",e.sessionKey):a.searchParams.delete("session"),s!==i&&(a.pathname=i),n?window.history.replaceState({},"",a.toString()):window.history.pushState({},"",a.toString())}function Wd(e,t){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.set("session",e),window.history.replaceState({},"",n.toString())}async function bl(e){await Promise.all([se(e,!1),vs(e),Je(e),Kt(e),Tn(e)])}async function qd(e){await Promise.all([se(e,!0),Oo(e),pe(e)])}async function wn(e){await Promise.all([se(e,!1),Kt(e),In(e)])}const Ea=50,Vd=80,Yd=12e4;function Qd(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.text=="string")return t.text;const n=t.content;if(!Array.isArray(n))return null;const i=n.map(s=>{if(!s||typeof s!="object")return null;const a=s;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(s=>!!s);return i.length===0?null:i.join(` `)}function Ta(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=Qd(e);let n;if(typeof e=="string")n=e;else if(t)n=t;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}const i=Wo(n,Yd);return i.truncated?`${i.text} … truncated (${i.total} chars, showing first ${i.text.length}).`:i.text}function Jd(e){const t=[];return t.push({type:"toolcall",name:e.name,arguments:e.args??{}}),e.output&&t.push({type:"toolresult",name:e.name,text:e.output}),{role:"assistant",toolCallId:e.toolCallId,runId:e.runId,content:t,timestamp:e.startedAt}}function Zd(e){if(e.toolStreamOrder.length<=Ea)return;const t=e.toolStreamOrder.length-Ea,n=e.toolStreamOrder.splice(0,t);for(const i of n)e.toolStreamById.delete(i)}function Xd(e){e.chatToolMessages=e.toolStreamOrder.map(t=>e.toolStreamById.get(t)?.message).filter(t=>!!t)}function Ri(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Xd(e)}function eu(e,t=!1){if(t){Ri(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>Ri(e),Vd))}function Fn(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],Ri(e)}const tu=5e3;function nu(e,t){const n=t.data??{},i=typeof n.phase=="string"?n.phase:"";e.compactionClearTimer!=null&&(window.clearTimeout(e.compactionClearTimer),e.compactionClearTimer=null),i==="start"?e.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null}:i==="end"&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus?.startedAt??null,completedAt:Date.now()},e.compactionClearTimer=window.setTimeout(()=>{e.compactionStatus=null,e.compactionClearTimer=null},tu))}function iu(e,t){if(!t)return;if(t.stream==="compaction"){nu(e,t);return}if(t.stream!=="tool")return;const n=typeof t.sessionKey=="string"?t.sessionKey:void 0;if(n&&n!==e.sessionKey||!n&&e.chatRunId&&t.runId!==e.chatRunId||e.chatRunId&&t.runId!==e.chatRunId||!e.chatRunId)return;const i=t.data??{},s=typeof i.toolCallId=="string"?i.toolCallId:"";if(!s)return;const a=typeof i.name=="string"?i.name:"tool",o=typeof i.phase=="string"?i.phase:"",r=o==="start"?i.args:void 0,c=o==="update"?Ta(i.partialResult):o==="result"?Ta(i.result):void 0,u=Date.now();let f=e.toolStreamById.get(s);f?(f.name=a,r!==void 0&&(f.args=r),c!==void 0&&(f.output=c||void 0),f.updatedAt=u):(f={toolCallId:s,runId:t.runId,sessionKey:n,name:a,args:r,output:c||void 0,startedAt:typeof t.ts=="number"?t.ts:u,updatedAt:u,message:{}},e.toolStreamById.set(s,f),e.toolStreamOrder.push(s)),f.message=Jd(f),Zd(e),eu(e,o==="result")}const su=/^\[([^\]]+)\]\s*/,au=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],li=new WeakMap,ri=new WeakMap;function ou(e){return/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z\b/.test(e)||/\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b/.test(e)?!0:au.some(t=>e.startsWith(`${t} `))}function ci(e){const t=e.match(su);if(!t)return e;const n=t[1]??"";return ou(n)?e.slice(t[0].length):e}function Mi(e){const t=e,n=typeof t.role=="string"?t.role:"",i=t.content;if(typeof i=="string")return n==="assistant"?ni(i):ci(i);if(Array.isArray(i)){const s=i.map(a=>{const o=a;return o.type==="text"&&typeof o.text=="string"?o.text:null}).filter(a=>typeof a=="string");if(s.length>0){const a=s.join(` `);return n==="assistant"?ni(a):ci(a)}}return typeof t.text=="string"?n==="assistant"?ni(t.text):ci(t.text):null}function wl(e){if(!e||typeof e!="object")return Mi(e);const t=e;if(li.has(t))return li.get(t)??null;const n=Mi(e);return li.set(t,n),n}function La(e){const n=e.content,i=[];if(Array.isArray(n))for(const r of n){const c=r;if(c.type==="thinking"&&typeof c.thinking=="string"){const u=c.thinking.trim();u&&i.push(u)}}if(i.length>0)return i.join(` `);const s=ru(e);if(!s)return null;const o=[...s.matchAll(/<\s*think(?:ing)?\s*>([\s\S]*?)<\s*\/\s*think(?:ing)?\s*>/gi)].map(r=>(r[1]??"").trim()).filter(Boolean);return o.length>0?o.join(` `):null}function lu(e){if(!e||typeof e!="object")return La(e);const t=e;if(ri.has(t))return ri.get(t)??null;const n=La(e);return ri.set(t,n),n}function ru(e){const t=e,n=t.content;if(typeof n=="string")return n;if(Array.isArray(n)){const i=n.map(s=>{const a=s;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(s=>typeof s=="string");if(i.length>0)return i.join(` `)}return typeof t.text=="string"?t.text:null}function cu(e){const t=e.trim();if(!t)return"";const n=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).map(i=>`_${i}_`);return n.length?["_Reasoning:_",...n].join(` `):""}let Ia=!1;function Ra(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 uu(){Ia||(Ia=!0,console.warn("[uuid] crypto API missing; falling back to weak randomness"))}function ws(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),Ra(t)}return uu(),Ra(du())}async function Ot(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}}}function fu(e){const t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}async function gu(e,t,n){if(!e.client||!e.connected)return null;const i=t.trim(),s=n&&n.length>0;if(!i&&!s)return null;const a=Date.now(),o=[];if(i&&o.push({type:"text",text:i}),s)for(const u of n)o.push({type:"image",source:{type:"base64",media_type:u.mimeType,data:u.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:o,timestamp:a}],e.chatSending=!0,e.lastError=null;const r=ws();e.chatRunId=r,e.chatStream="",e.chatStreamStartedAt=a;const c=s?n.map(u=>{const f=fu(u.dataUrl);return f?{type:"image",mimeType:f.mimeType,content:f.content}:null}).filter(u=>u!==null):void 0;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:r,attachments:c}),r}catch(u){const f=String(u);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=f,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+f}],timestamp:Date.now()}],null}finally{e.chatSending=!1}}async function pu(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 hu(e,t){if(!t||t.sessionKey!==e.sessionKey)return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return t.state==="final"?"final":null;if(t.state==="delta"){const n=Mi(t.message);if(typeof n=="string"){const i=e.chatStream??"";(!i||n.length>=i.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}const $l=120;function kl(e){return e.chatSending||!!e.chatRunId}function vu(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/stop"?!0:n==="stop"||n==="esc"||n==="abort"||n==="wait"||n==="exit"}function mu(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/new"||n==="/reset"?!0:n.startsWith("/new ")||n.startsWith("/reset ")}async function Al(e){e.connected&&(e.chatMessage="",await pu(e))}function yu(e,t,n,i){const s=t.trim(),a=!!(n&&n.length>0);!s&&!a||(e.chatQueue=[...e.chatQueue,{id:ws(),text:s,createdAt:Date.now(),attachments:a?n?.map(o=>({...o})):void 0,refreshSessions:i}])}async function xl(e,t,n){Fn(e);const i=await gu(e,t,n?.attachments),s=!!i;return!s&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!s&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),s&&vl(e,e.sessionKey),s&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),s&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),Ut(e),s&&!e.chatRunId&&Sl(e),s&&n?.refreshSessions&&i&&e.refreshSessionsAfterChat.add(i),s}async function Sl(e){if(!e.connected||kl(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await xl(e,t.text,{attachments:t.attachments,refreshSessions:t.refreshSessions})||(e.chatQueue=[t,...e.chatQueue])}function bu(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function wu(e,t,n){if(!e.connected)return;const i=e.chatMessage,s=(t??e.chatMessage).trim(),a=e.chatAttachments??[],o=t==null?a:[],r=o.length>0;if(!s&&!r)return;if(vu(s)){await Al(e);return}const c=mu(s);if(t==null&&(e.chatMessage="",e.chatAttachments=[]),kl(e)){yu(e,s,o,c);return}await xl(e,s,{previousDraft:t==null?i:void 0,restoreDraft:!!(t&&n?.restoreDraft),attachments:r?o:void 0,previousAttachments:t==null?a:void 0,restoreAttachments:!!(t&&n?.restoreDraft),refreshSessions:c})}async function _l(e){await Promise.all([Ot(e),Je(e,{activeMinutes:$l}),Pi(e)]),Ut(e)}const $u=Sl;function ku(e){const t=Ko(e.sessionKey);return t?.agentId?t.agentId:e.hello?.snapshot?.sessionDefaults?.defaultAgentId?.trim()||"main"}function Au(e,t){const n=Ht(e),i=encodeURIComponent(t);return n?`${n}/avatar/${i}?meta=1`:`/avatar/${i}?meta=1`}async function Pi(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=ku(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=Au(e.basePath,t);try{const i=await fetch(n,{method:"GET"});if(!i.ok){e.chatAvatarUrl=null;return}const s=await i.json(),a=typeof s.avatarUrl=="string"?s.avatarUrl.trim():"";e.chatAvatarUrl=a||null}catch{e.chatAvatarUrl=null}}const xu={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},Su={name:"",description:"",agentId:"",enabled:!0,scheduleKind:"every",scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"0 7 * * *",cronTz:"",sessionTarget:"isolated",wakeMode:"next-heartbeat",payloadKind:"agentTurn",payloadText:"",deliveryMode:"announce",deliveryChannel:"last",deliveryTo:"",timeoutSeconds:""},_u=50,Cu=200,Eu="Assistant";function Ma(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function Fi(e){const t=Ma(e?.name,_u)??Eu,n=Ma(e?.avatar??void 0,Cu)??null;return{agentId:typeof e?.agentId=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function Tu(){return Fi(typeof window>"u"?{}:{name:window.__OPENCLAW_ASSISTANT_NAME__,avatar:window.__OPENCLAW_ASSISTANT_AVATAR__})}async function Cl(e,t){if(!e.client||!e.connected)return;const n=e.sessionKey.trim(),i=n?{sessionKey:n}:{};try{const s=await e.client.request("agent.identity.get",i);if(!s)return;const a=Fi(s);e.assistantName=a.name,e.assistantAvatar=a.avatar,e.assistantAgentId=a.agentId??null}catch{}}function Ni(e){return typeof e=="object"&&e!==null}function Lu(e){if(!Ni(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!Ni(n))return null;const i=typeof n.command=="string"?n.command.trim():"";if(!i)return null;const s=typeof e.createdAtMs=="number"?e.createdAtMs:0,a=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!s||!a?null:{id:t,request:{command:i,cwd:typeof n.cwd=="string"?n.cwd:null,host:typeof n.host=="string"?n.host:null,security:typeof n.security=="string"?n.security:null,ask:typeof n.ask=="string"?n.ask:null,agentId:typeof n.agentId=="string"?n.agentId:null,resolvedPath:typeof n.resolvedPath=="string"?n.resolvedPath:null,sessionKey:typeof n.sessionKey=="string"?n.sessionKey:null},createdAtMs:s,expiresAtMs:a}}function Iu(e){if(!Ni(e))return null;const t=typeof e.id=="string"?e.id.trim():"";return t?{id:t,decision:typeof e.decision=="string"?e.decision:null,resolvedBy:typeof e.resolvedBy=="string"?e.resolvedBy:null,ts:typeof e.ts=="number"?e.ts:null}:null}function El(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Ru(e,t){const n=El(e).filter(i=>i.id!==t.id);return n.push(t),n}function Pa(e,t){return El(e).filter(n=>n.id!==t)}function Mu(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),i=e.token??"",s=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),i];return t==="v2"&&s.push(e.nonce??""),s.join("|")}const Tl={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",IOS_APP:"openclaw-ios",ANDROID_APP:"openclaw-android",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},Fa=Tl,Di={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Tl));new Set(Object.values(Di));const Pu=4008;class Fu{constructor(t){this.opts=t,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=null,this.connectNonce=null,this.connectSent=!1,this.connectTimer=null,this.backoffMs=800}start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.ws?.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){return this.ws?.readyState===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.addEventListener("open",()=>this.queueConnect()),this.ws.addEventListener("message",t=>this.handleMessage(String(t.data??""))),this.ws.addEventListener("close",t=>{const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),this.opts.onClose?.({code:t.code,reason:n}),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{}))}scheduleReconnect(){if(this.closed)return;const t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),t)}flushPending(t){for(const[,n]of this.pending)n.reject(t);this.pending.clear()}async sendConnect(){if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=typeof crypto<"u"&&!!crypto.subtle,n=["operator.admin","operator.approvals","operator.pairing"],i="operator";let s=null,a=!1,o=this.opts.token;if(t){s=await ps();const f=Oc({deviceId:s.deviceId,role:i})?.token;o=f??this.opts.token,a=!!(f&&this.opts.token)}const r=o||this.opts.password?{token:o,password:this.opts.password}:void 0;let c;if(t&&s){const f=Date.now(),g=this.connectNonce??void 0,m=Mu({deviceId:s.deviceId,clientId:this.opts.clientName??Fa.CONTROL_UI,clientMode:this.opts.mode??Di.WEBCHAT,role:i,scopes:n,signedAtMs:f,token:o??null,nonce:g}),v=await cd(s.privateKey,m);c={id:s.deviceId,publicKey:s.publicKey,signature:v,signedAt:f,nonce:g}}const u={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Fa.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Di.WEBCHAT,instanceId:this.opts.instanceId},role:i,scopes:n,device:c,caps:[],auth:r,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",u).then(f=>{f?.auth?.deviceToken&&s&&Qo({deviceId:s.deviceId,role:f.auth.role??i,token:f.auth.deviceToken,scopes:f.auth.scopes??[]}),this.backoffMs=800,this.opts.onHello?.(f)}).catch(()=>{a&&s&&Jo({deviceId:s.deviceId,role:i}),this.ws?.close(Pu,"connect failed")})}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}const i=n;if(i.type==="event"){const s=n;if(s.event==="connect.challenge"){const o=s.payload,r=o&&typeof o.nonce=="string"?o.nonce:null;r&&(this.connectNonce=r,this.sendConnect());return}const a=typeof s.seq=="number"?s.seq:null;a!==null&&(this.lastSeq!==null&&a>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:a}),this.lastSeq=a);try{this.opts.onEvent?.(s)}catch(o){console.error("[gateway] event handler error:",o)}return}if(i.type==="res"){const s=n,a=this.pending.get(s.id);if(!a)return;this.pending.delete(s.id),s.ok?a.resolve(s.payload):a.reject(new Error(s.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 i=ws(),s={type:"req",id:i,method:t,params:n},a=new Promise((o,r)=>{this.pending.set(i,{resolve:c=>o(c),reject:r})});return this.ws.send(JSON.stringify(s)),a}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}function di(e,t){const n=(e??"").trim(),i=t.mainSessionKey?.trim();if(!i)return n;if(!n)return i;const s=t.mainKey?.trim()||"main",a=t.defaultAgentId?.trim();return n==="main"||n===s||a&&(n===`agent:${a}:main`||n===`agent:${a}:${s}`)?i:n}function Nu(e,t){if(!t?.mainSessionKey)return;const n=di(e.sessionKey,t),i=di(e.settings.sessionKey,t),s=di(e.settings.lastActiveSessionKey,t),a=n||i||e.sessionKey,o={...e.settings,sessionKey:i||a,lastActiveSessionKey:s||a},r=o.sessionKey!==e.settings.sessionKey||o.lastActiveSessionKey!==e.settings.lastActiveSessionKey;a!==e.sessionKey&&(e.sessionKey=a),r&&Pe(e,o)}function Ll(e){e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null,e.client?.stop(),e.client=new Fu({url:e.settings.gatewayUrl,token:e.settings.token.trim()?e.settings.token:void 0,password:e.password.trim()?e.password:void 0,clientName:"openclaw-control-ui",mode:"webchat",onHello:t=>{e.connected=!0,e.lastError=null,e.hello=t,Bu(e,t),e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,Fn(e),Cl(e),rs(e),Ln(e,{quiet:!0}),Ne(e,{quiet:!0}),bs(e)},onClose:({code:t,reason:n})=>{e.connected=!1,t!==1012&&(e.lastError=`disconnected (${t}): ${n||"no reason"}`)},onEvent:t=>Du(e,t),onGap:({expected:t,received:n})=>{e.lastError=`event gap detected (expected seq ${t}, got ${n}); refresh recommended`}}),e.client.start()}function Du(e,t){try{Ou(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function Ou(e,t){if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),e.tab==="debug"&&(e.eventLog=e.eventLogBuffer),t.event==="agent"){if(e.onboarding)return;iu(e,t.payload);return}if(t.event==="chat"){const n=t.payload;n?.sessionKey&&vl(e,n.sessionKey);const i=hu(e,n);if(i==="final"||i==="error"||i==="aborted"){Fn(e),$u(e);const s=n?.runId;s&&e.refreshSessionsAfterChat.has(s)&&(e.refreshSessionsAfterChat.delete(s),i==="final"&&Je(e,{activeMinutes:$l}))}i==="final"&&Ot(e);return}if(t.event==="presence"){const n=t.payload;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"&&e.tab==="cron"&&wn(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&Ne(e,{quiet:!0}),t.event==="exec.approval.requested"){const n=Lu(t.payload);if(n){e.execApprovalQueue=Ru(e.execApprovalQueue,n),e.execApprovalError=null;const i=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Pa(e.execApprovalQueue,n.id)},i)}return}if(t.event==="exec.approval.resolved"){const n=Iu(t.payload);n&&(e.execApprovalQueue=Pa(e.execApprovalQueue,n.id))}}function Bu(e,t){const n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health),n?.sessionDefaults&&Nu(e,n.sessionDefaults)}function Uu(e){e.basePath=Ud(),Dd(e),jd(e,!0),Kd(e),zd(e),window.addEventListener("popstate",e.popStateHandler),Ll(e),_c(e),e.tab==="logs"&&ss(e),e.tab==="debug"&&os(e)}function Ku(e){bc(e)}function zu(e){window.removeEventListener("popstate",e.popStateHandler),Cc(e),as(e),ls(e),Hd(e),e.topbarObserver?.disconnect(),e.topbarObserver=null}function Hu(e,t){if(e.tab==="chat"&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),i=t.has("chatLoading")&&t.get("chatLoading")===!0&&!e.chatLoading;Ut(e,n||i||!e.chatHasAutoScrolled)}e.tab==="logs"&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&zo(e,t.has("tab")||t.has("logsAutoFollow"))}const $s={CHILD:2},ks=e=>(...t)=>({_$litDirective$:e,values:t});let As=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,n,i){this._$Ct=t,this._$AM=n,this._$Ci=i}_$AS(t,n){return this.update(t,n)}update(t,n){return this.render(...n)}};const{I:ju}=zr,Na=e=>e,Gu=e=>e.strings===void 0,Da=()=>document.createComment(""),mt=(e,t,n)=>{const i=e._$AA.parentNode,s=t===void 0?e._$AB:t._$AA;if(n===void 0){const a=i.insertBefore(Da(),s),o=i.insertBefore(Da(),s);n=new ju(a,o,e,e.options)}else{const a=n._$AB.nextSibling,o=n._$AM,r=o!==e;if(r){let c;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(c=e._$AU)!==o._$AU&&n._$AP(c)}if(a!==s||r){let c=n._$AA;for(;c!==a;){const u=Na(c).nextSibling;Na(i).insertBefore(c,s),c=u}}}return n},Ke=(e,t,n=e)=>(e._$AI(t,n),e),Wu={},qu=(e,t=Wu)=>e._$AH=t,Vu=e=>e._$AH,ui=e=>{e._$AR(),e._$AA.remove()};const Oa=(e,t,n)=>{const i=new Map;for(let s=t;s<=n;s++)i.set(e[s],s);return i},Il=ks(class extends As{constructor(e){if(super(e),e.type!==$s.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,n){let i;n===void 0?n=t:t!==void 0&&(i=t);const s=[],a=[];let o=0;for(const r of e)s[o]=i?i(r,o):o,a[o]=n(r,o),o++;return{values:a,keys:s}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,i]){const s=Vu(e),{values:a,keys:o}=this.dt(t,n,i);if(!Array.isArray(s))return this.ut=o,a;const r=this.ut??=[],c=[];let u,f,g=0,m=s.length-1,v=0,b=a.length-1;for(;g<=m&&v<=b;)if(s[g]===null)g++;else if(s[m]===null)m--;else if(r[g]===o[v])c[v]=Ke(s[g],a[v]),g++,v++;else if(r[m]===o[b])c[b]=Ke(s[m],a[b]),m--,b--;else if(r[g]===o[b])c[b]=Ke(s[g],a[b]),mt(e,c[b+1],s[g]),g++,b--;else if(r[m]===o[v])c[v]=Ke(s[m],a[v]),mt(e,s[g],s[m]),m--,v++;else if(u===void 0&&(u=Oa(o,v,b),f=Oa(r,g,m)),u.has(r[g]))if(u.has(r[m])){const d=f.get(o[v]),y=d!==void 0?s[d]:null;if(y===null){const A=mt(e,s[g]);Ke(A,a[v]),c[v]=A}else c[v]=Ke(y,a[v]),mt(e,s[g],y),s[d]=null;v++}else ui(s[m]),m--;else ui(s[g]),g++;for(;v<=b;){const d=mt(e,c[b+1]);Ke(d,a[v]),c[v++]=d}for(;g<=m;){const d=s[g++];d!==null&&ui(d)}return this.ut=o,qu(e,c),Me}}),Y={messageSquare:l` `,barChart:l` `,link:l` `,radio:l` `,fileText:l` `,zap:l` `,monitor:l` `,settings:l` `,bug:l` `,scrollText:l` `,folder:l` `,menu:l` `,x:l` `,check:l` `,arrowDown:l` `,copy:l` `,search:l` `,brain:l` `,book:l` `,loader:l` `,wrench:l` `,fileCode:l` `,edit:l` `,penLine:l` `,paperclip:l` `,globe:l` `,image:l` `,smartphone:l` `,plug:l` `,circle:l` `,puzzle:l` `};function Yu(e,t){const n=ms(t,e.basePath);return l` {i.defaultPrevented||i.button!==0||i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||(i.preventDefault(),e.setTab(t))}} title=${Ii(t)} > ${Ii(t)} `}function Qu(e){const t=Ju(e.hello,e.sessionsResult),n=Zu(e.sessionKey,e.sessionsResult,t),i=e.onboarding,s=e.onboarding,a=e.onboarding?!1:e.settings.chatShowThinking,o=e.onboarding?!0:e.settings.chatFocusMode,r=l` `,c=l` `;return l`
|
`}function Ju(e,t){const n=e?.snapshot,i=n?.sessionDefaults?.mainSessionKey?.trim();if(i)return i;const s=n?.sessionDefaults?.mainKey?.trim();return s||(t?.sessions?.some(a=>a.key==="main")?"main":null)}function fi(e,t){const n=t?.label?.trim();if(n)return`${n} (${e})`;const i=t?.displayName?.trim();return i||e}function Zu(e,t,n){const i=new Set,s=[],a=n&&t?.sessions?.find(r=>r.key===n),o=t?.sessions?.find(r=>r.key===e);if(n&&(i.add(n),s.push({key:n,displayName:fi(n,a||void 0)})),i.has(e)||(i.add(e),s.push({key:e,displayName:fi(e,o)})),t?.sessions)for(const r of t.sessions)i.has(r.key)||(i.add(r.key),s.push({key:r.key,displayName:fi(r.key,r)}));return s}const Xu=["system","light","dark"];function ef(e){const t=Math.max(0,Xu.indexOf(e.theme)),n=i=>s=>{const o={element:s.currentTarget};(s.clientX||s.clientY)&&(o.pointerClientX=s.clientX,o.pointerClientY=s.clientY),e.setTheme(i,o)};return l`
`}function tf(){return l` `}function nf(){return l` `}function sf(){return l` `}function Rl(e,t){if(!e)return e;const i=e.files.some(s=>s.name===t.name)?e.files.map(s=>s.name===t.name?t:s):[...e.files,t];return{...e,files:i}}async function gi(e,t){if(!(!e.client||!e.connected||e.agentFilesLoading)){e.agentFilesLoading=!0,e.agentFilesError=null;try{const n=await e.client.request("agents.files.list",{agentId:t});n&&(e.agentFilesList=n,e.agentFileActive&&!n.files.some(i=>i.name===e.agentFileActive)&&(e.agentFileActive=null))}catch(n){e.agentFilesError=String(n)}finally{e.agentFilesLoading=!1}}}async function Ba(e,t,n,i){if(!(!e.client||!e.connected||e.agentFilesLoading)&&!(!i?.force&&Object.hasOwn(e.agentFileContents,n))){e.agentFilesLoading=!0,e.agentFilesError=null;try{const s=await e.client.request("agents.files.get",{agentId:t,name:n});if(s?.file){const a=s.file.content??"",o=e.agentFileContents[n]??"",r=e.agentFileDrafts[n],c=i?.preserveDraft??!0;e.agentFilesList=Rl(e.agentFilesList,s.file),e.agentFileContents={...e.agentFileContents,[n]:a},(!c||!Object.hasOwn(e.agentFileDrafts,n)||r===o)&&(e.agentFileDrafts={...e.agentFileDrafts,[n]:a})}}catch(s){e.agentFilesError=String(s)}finally{e.agentFilesLoading=!1}}}async function af(e,t,n,i){if(!(!e.client||!e.connected||e.agentFileSaving)){e.agentFileSaving=!0,e.agentFilesError=null;try{const s=await e.client.request("agents.files.set",{agentId:t,name:n,content:i});s?.file&&(e.agentFilesList=Rl(e.agentFilesList,s.file),e.agentFileContents={...e.agentFileContents,[n]:i},e.agentFileDrafts={...e.agentFileDrafts,[n]:i})}catch(s){e.agentFilesError=String(s)}finally{e.agentFileSaving=!1}}}const of={bash:"exec","apply-patch":"apply_patch"},lf={"group:memory":["memory_search","memory_get"],"group:web":["web_search","web_fetch"],"group:fs":["read","write","edit","apply_patch"],"group:runtime":["exec","process"],"group:sessions":["sessions_list","sessions_history","sessions_send","sessions_spawn","session_status"],"group:ui":["browser","canvas"],"group:automation":["cron","gateway"],"group:messaging":["message"],"group:nodes":["nodes"],"group:openclaw":["browser","canvas","nodes","cron","message","gateway","agents_list","sessions_list","sessions_history","sessions_send","sessions_spawn","session_status","memory_search","memory_get","web_search","web_fetch","image"]},rf={minimal:{allow:["session_status"]},coding:{allow:["group:fs","group:runtime","group:sessions","group:memory","image"]},messaging:{allow:["group:messaging","sessions_list","sessions_history","sessions_send","session_status"]},full:{}};function we(e){const t=e.trim().toLowerCase();return of[t]??t}function cf(e){return e?e.map(we).filter(Boolean):[]}function df(e){const t=cf(e),n=[];for(const i of t){const s=lf[i];if(s){n.push(...s);continue}n.push(i)}return Array.from(new Set(n))}function uf(e){if(!e)return;const t=rf[e];if(t&&!(!t.allow&&!t.deny))return{allow:t.allow?[...t.allow]:void 0,deny:t.deny?[...t.deny]:void 0}}function ff(e){const t=e.host??"unknown",n=e.ip?`(${e.ip})`:"",i=e.mode??"",s=e.version??"";return`${t} ${n} ${i} ${s}`.trim()}function gf(e){const t=e.ts??null;return t?O(t):"n/a"}function xs(e){return e?`${Ft(e)} (${O(e)})`:"n/a"}function pf(e){if(e.totalTokens==null)return"n/a";const t=e.totalTokens??0,n=e.contextTokens??0;return n?`${t} / ${n}`:String(t)}function hf(e){if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ml(e){const t=e.state??{},n=t.nextRunAtMs?Ft(t.nextRunAtMs):"n/a",i=t.lastRunAtMs?Ft(t.lastRunAtMs):"n/a";return`${t.lastStatus??"n/a"} · next ${n} · last ${i}`}function Pl(e){const t=e.schedule;if(t.kind==="at"){const n=Date.parse(t.at);return Number.isFinite(n)?`At ${Ft(n)}`:`At ${t.at}`}return t.kind==="every"?`Every ${Go(t.everyMs)}`:`Cron ${t.expr}${t.tz?` (${t.tz})`:""}`}function Fl(e){const t=e.payload;if(t.kind==="systemEvent")return`System: ${t.text}`;const n=`Agent: ${t.message}`,i=e.delivery;if(i&&i.mode!=="none"){const s=i.channel||i.to?` (${i.channel??"last"}${i.to?` -> ${i.to}`:""})`:"";return`${n} · ${i.mode}${s}`}return n}const Ua=[{id:"fs",label:"Files",tools:[{id:"read",label:"read",description:"Read file contents"},{id:"write",label:"write",description:"Create or overwrite files"},{id:"edit",label:"edit",description:"Make precise edits"},{id:"apply_patch",label:"apply_patch",description:"Patch files (OpenAI)"}]},{id:"runtime",label:"Runtime",tools:[{id:"exec",label:"exec",description:"Run shell commands"},{id:"process",label:"process",description:"Manage background processes"}]},{id:"web",label:"Web",tools:[{id:"web_search",label:"web_search",description:"Search the web"},{id:"web_fetch",label:"web_fetch",description:"Fetch web content"}]},{id:"memory",label:"Memory",tools:[{id:"memory_search",label:"memory_search",description:"Semantic search"},{id:"memory_get",label:"memory_get",description:"Read memory files"}]},{id:"sessions",label:"Sessions",tools:[{id:"sessions_list",label:"sessions_list",description:"List sessions"},{id:"sessions_history",label:"sessions_history",description:"Session history"},{id:"sessions_send",label:"sessions_send",description:"Send to session"},{id:"sessions_spawn",label:"sessions_spawn",description:"Spawn sub-agent"},{id:"session_status",label:"session_status",description:"Session status"}]},{id:"ui",label:"UI",tools:[{id:"browser",label:"browser",description:"Control web browser"},{id:"canvas",label:"canvas",description:"Control canvases"}]},{id:"messaging",label:"Messaging",tools:[{id:"message",label:"message",description:"Send messages"}]},{id:"automation",label:"Automation",tools:[{id:"cron",label:"cron",description:"Schedule tasks"},{id:"gateway",label:"gateway",description:"Gateway control"}]},{id:"nodes",label:"Nodes",tools:[{id:"nodes",label:"nodes",description:"Nodes + devices"}]},{id:"agents",label:"Agents",tools:[{id:"agents_list",label:"agents_list",description:"List agents"}]},{id:"media",label:"Media",tools:[{id:"image",label:"image",description:"Image understanding"}]}],vf=[{id:"minimal",label:"Minimal"},{id:"coding",label:"Coding"},{id:"messaging",label:"Messaging"},{id:"full",label:"Full"}];function Oi(e){return e.name?.trim()||e.identity?.name?.trim()||e.id}function nn(e){const t=e.trim();if(!t||t.length>16)return!1;let n=!1;for(let i=0;i127){n=!0;break}return!(!n||t.includes("://")||t.includes("/")||t.includes("."))}function Nn(e,t){const n=t?.emoji?.trim();if(n&&nn(n))return n;const i=e.identity?.emoji?.trim();if(i&&nn(i))return i;const s=t?.avatar?.trim();if(s&&nn(s))return s;const a=e.identity?.avatar?.trim();return a&&nn(a)?a:""}function Nl(e,t){return t&&e===t?"default":null}function mf(e){if(e==null||!Number.isFinite(e))return"-";if(e<1024)return`${e} B`;const t=["KB","MB","GB","TB"];let n=e/1024,i=0;for(;n>=1024&&ia?.id===t),defaults:n?.agents?.defaults,globalTools:n?.tools}}function Dl(e,t,n,i,s){const a=Dn(t,e.id),r=(n&&n.agentId===e.id?n.workspace:null)||a.entry?.workspace||a.defaults?.workspace||"default",c=a.entry?.model?Et(a.entry?.model):Et(a.defaults?.model),u=s?.name?.trim()||e.identity?.name?.trim()||e.name?.trim()||a.entry?.name||e.id,f=Nn(e,s)||"-",g=Array.isArray(a.entry?.skills)?a.entry?.skills:null,m=g?.length??null;return{workspace:r,model:c,identityName:u,identityEmoji:f,skillsLabel:g?`${m} selected`:"all skills",isDefault:!!(i&&e.id===i)}}function Et(e){if(!e)return"-";if(typeof e=="string")return e.trim()||"-";if(typeof e=="object"&&e){const t=e,n=t.primary?.trim();if(n){const i=Array.isArray(t.fallbacks)?t.fallbacks.length:0;return i>0?`${n} (+${i} fallback)`:n}}return"-"}function Ka(e){const t=e.match(/^(.+) \(\+\d+ fallback\)$/);return t?t[1]:e}function za(e){if(!e)return null;if(typeof e=="string")return e.trim()||null;if(typeof e=="object"&&e){const t=e;return(typeof t.primary=="string"?t.primary:typeof t.model=="string"?t.model:typeof t.id=="string"?t.id:typeof t.value=="string"?t.value:null)?.trim()||null}return null}function yf(e){if(!e||typeof e=="string")return null;if(typeof e=="object"&&e){const t=e,n=Array.isArray(t.fallbacks)?t.fallbacks:Array.isArray(t.fallback)?t.fallback:null;return n?n.filter(i=>typeof i=="string"):null}return null}function bf(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function wf(e){const n=e?.agents?.defaults?.models;if(!n||typeof n!="object")return[];const i=[];for(const[s,a]of Object.entries(n)){const o=s.trim();if(!o)continue;const r=a&&typeof a=="object"&&"alias"in a&&typeof a.alias=="string"?a.alias?.trim():void 0,c=r&&r!==o?`${r} (${o})`:o;i.push({value:o,label:c})}return i}function $f(e,t){const n=wf(e),i=t?n.some(s=>s.value===t):!1;return t&&!i&&n.unshift({value:t,label:`Current (${t})`}),n.length===0?l` `:n.map(s=>l``)}function kf(e){const t=we(e);if(!t)return{kind:"exact",value:""};if(t==="*")return{kind:"all"};if(!t.includes("*"))return{kind:"exact",value:t};const n=t.replace(/[.*+?^${}()|[\\]\\]/g,"\\$&");return{kind:"regex",value:new RegExp(`^${n.replaceAll("\\*",".*")}$`)}}function Bi(e){return Array.isArray(e)?df(e).map(kf).filter(t=>t.kind!=="exact"||t.value.length>0):[]}function Tt(e,t){for(const n of t)if(n.kind==="all"||n.kind==="exact"&&e===n.value||n.kind==="regex"&&n.value.test(e))return!0;return!1}function Af(e,t){if(!t)return!0;const n=we(e),i=Bi(t.deny);if(Tt(n,i))return!1;const s=Bi(t.allow);return!!(s.length===0||Tt(n,s)||n==="apply_patch"&&Tt("exec",s))}function Ha(e,t){if(!Array.isArray(t)||t.length===0)return!1;const n=we(e),i=Bi(t);return!!(Tt(n,i)||n==="apply_patch"&&Tt("exec",i))}function xf(e){const t=e.agentsList?.agents??[],n=e.agentsList?.defaultId??null,i=e.selectedAgentId??n??t[0]?.id??null,s=i?t.find(a=>a.id===i)??null:null;return l`
Agents
${t.length} configured.
${e.error?l`
${e.error}
`:p}
${t.length===0?l`
No agents found.
`:t.map(a=>{const o=Nl(a.id,n),r=Nn(a,e.agentIdentityById[a.id]??null);return l` `})}
${s?l` ${Sf(s,n,e.agentIdentityById[s.id]??null)} ${_f(e.activePanel,a=>e.onSelectPanel(a))} ${e.activePanel==="overview"?Cf({agent:s,defaultId:n,configForm:e.configForm,agentFilesList:e.agentFilesList,agentIdentity:e.agentIdentityById[s.id]??null,agentIdentityError:e.agentIdentityError,agentIdentityLoading:e.agentIdentityLoading,configLoading:e.configLoading,configSaving:e.configSaving,configDirty:e.configDirty,onConfigReload:e.onConfigReload,onConfigSave:e.onConfigSave,onModelChange:e.onModelChange,onModelFallbacksChange:e.onModelFallbacksChange}):p} ${e.activePanel==="files"?Df({agentId:s.id,agentFilesList:e.agentFilesList,agentFilesLoading:e.agentFilesLoading,agentFilesError:e.agentFilesError,agentFileActive:e.agentFileActive,agentFileContents:e.agentFileContents,agentFileDrafts:e.agentFileDrafts,agentFileSaving:e.agentFileSaving,onLoadFiles:e.onLoadFiles,onSelectFile:e.onSelectFile,onFileDraftChange:e.onFileDraftChange,onFileReset:e.onFileReset,onFileSave:e.onFileSave}):p} ${e.activePanel==="tools"?Bf({agentId:s.id,configForm:e.configForm,configLoading:e.configLoading,configSaving:e.configSaving,configDirty:e.configDirty,onProfileChange:e.onToolsProfileChange,onOverridesChange:e.onToolsOverridesChange,onConfigReload:e.onConfigReload,onConfigSave:e.onConfigSave}):p} ${e.activePanel==="skills"?Kf({agentId:s.id,report:e.agentSkillsReport,loading:e.agentSkillsLoading,error:e.agentSkillsError,activeAgentId:e.agentSkillsAgentId,configForm:e.configForm,configLoading:e.configLoading,configSaving:e.configSaving,configDirty:e.configDirty,filter:e.skillsFilter,onFilterChange:e.onSkillsFilterChange,onRefresh:e.onSkillsRefresh,onToggle:e.onAgentSkillToggle,onClear:e.onAgentSkillsClear,onDisableAll:e.onAgentSkillsDisableAll,onConfigReload:e.onConfigReload,onConfigSave:e.onConfigSave}):p} ${e.activePanel==="channels"?Ff({agent:s,defaultId:n,configForm:e.configForm,agentFilesList:e.agentFilesList,agentIdentity:e.agentIdentityById[s.id]??null,snapshot:e.channelsSnapshot,loading:e.channelsLoading,error:e.channelsError,lastSuccess:e.channelsLastSuccess,onRefresh:e.onChannelsRefresh}):p} ${e.activePanel==="cron"?Nf({agent:s,defaultId:n,configForm:e.configForm,agentFilesList:e.agentFilesList,agentIdentity:e.agentIdentityById[s.id]??null,jobs:e.cronJobs,status:e.cronStatus,loading:e.cronLoading,error:e.cronError,onRefresh:e.onCronRefresh}):p} `:l`
Select an agent
Pick an agent to inspect its workspace and tools.
`}
`}function Sf(e,t,n){const i=Nl(e.id,t),s=Oi(e),a=e.identity?.theme?.trim()||"Agent workspace and routing.",o=Nn(e,n);return l`
${o||s.slice(0,1)}
${s}
${a}
${e.id}
${i?l`${i}`:p}
`}function _f(e,t){return l`
${[{id:"overview",label:"Overview"},{id:"files",label:"Files"},{id:"tools",label:"Tools"},{id:"skills",label:"Skills"},{id:"channels",label:"Channels"},{id:"cron",label:"Cron Jobs"}].map(i=>l` `)}
`}function Cf(e){const{agent:t,configForm:n,agentFilesList:i,agentIdentity:s,agentIdentityLoading:a,agentIdentityError:o,configLoading:r,configSaving:c,configDirty:u,onConfigReload:f,onConfigSave:g,onModelChange:m,onModelFallbacksChange:v}=e,b=Dn(n,t.id),y=(i&&i.agentId===t.id?i.workspace:null)||b.entry?.workspace||b.defaults?.workspace||"default",A=b.entry?.model?Et(b.entry?.model):Et(b.defaults?.model),S=Et(b.defaults?.model),T=za(b.entry?.model)||(A!=="-"?Ka(A):null),x=za(b.defaults?.model)||(S!=="-"?Ka(S):null),C=T??x??null,E=yf(b.entry?.model),P=E?E.join(", "):"",ce=s?.name?.trim()||t.identity?.name?.trim()||t.name?.trim()||b.entry?.name||"-",Q=Nn(t,s)||"-",D=Array.isArray(b.entry?.skills)?b.entry?.skills:null,De=D?.length??null,ae=a?"Loading…":o?"Unavailable":"",Le=!!(e.defaultId&&t.id===e.defaultId);return l`
Overview
Workspace paths and identity metadata.
Workspace
${y}
Primary Model
${A}
Identity Name
${ce}
${ae?l`
${ae}
`:p}
Default
${Le?"yes":"no"}
Identity Emoji
${Q}
Skills Filter
${D?`${De} selected`:"all skills"}
Model Selection
`}function Ol(e,t){return l`
Agent Context
${t}
Workspace
${e.workspace}
Primary Model
${e.model}
Identity Name
${e.identityName}
Identity Emoji
${e.identityEmoji}
Skills Filter
${e.skillsLabel}
Default
${e.isDefault?"yes":"no"}
`}function Ef(e,t){const n=e.channelMeta?.find(i=>i.id===t);return n?.label?n.label:e.channelLabels?.[t]??t}function Tf(e){if(!e)return[];const t=new Set;for(const s of e.channelOrder??[])t.add(s);for(const s of e.channelMeta??[])t.add(s.id);for(const s of Object.keys(e.channelAccounts??{}))t.add(s);const n=[],i=e.channelOrder?.length?e.channelOrder:Array.from(t);for(const s of i)t.has(s)&&(n.push(s),t.delete(s));for(const s of t)n.push(s);return n.map(s=>({id:s,label:Ef(e,s),accounts:e.channelAccounts?.[s]??[]}))}const Lf=["groupPolicy","streamMode","dmPolicy"];function If(e,t){if(!e)return null;const i=(e.channels??{})[t];if(i&&typeof i=="object")return i;const s=e[t];return s&&typeof s=="object"?s:null}function Rf(e){if(e==null)return"n/a";if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return"n/a"}}function Mf(e,t){const n=If(e,t);return n?Lf.flatMap(i=>i in n?[{label:i,value:Rf(n[i])}]:[]):[]}function Pf(e){let t=0,n=0,i=0;for(const s of e){const a=s.probe&&typeof s.probe=="object"&&"ok"in s.probe?!!s.probe.ok:!1;(s.connected===!0||s.running===!0||a)&&(t+=1),s.configured&&(n+=1),s.enabled&&(i+=1)}return{total:e.length,connected:t,configured:n,enabled:i}}function Ff(e){const t=Dl(e.agent,e.configForm,e.agentFilesList,e.defaultId,e.agentIdentity),n=Tf(e.snapshot),i=e.lastSuccess?O(e.lastSuccess):"never";return l`
${Ol(t,"Workspace, identity, and model configuration.")}
Channels
Gateway-wide channel status snapshot.
Last refresh: ${i}
${e.error?l`
${e.error}
`:p} ${e.snapshot?p:l`
Load channels to see live status.
`} ${n.length===0?l`
No channels found.
`:l`
${n.map(s=>{const a=Pf(s.accounts),o=a.total?`${a.connected}/${a.total} connected`:"no accounts",r=a.configured?`${a.configured} configured`:"not configured",c=a.total?`${a.enabled} enabled`:"disabled",u=Mf(e.configForm,s.id);return l`
${s.label}
${s.id}
${o}
${r}
${c}
${u.length>0?u.map(f=>l`
${f.label}: ${f.value}
`):p}
`})}
`}
`}function Nf(e){const t=Dl(e.agent,e.configForm,e.agentFilesList,e.defaultId,e.agentIdentity),n=e.jobs.filter(i=>i.agentId===e.agent.id);return l`
${Ol(t,"Workspace and scheduling targets.")}
Scheduler
Gateway cron status.
Enabled
${e.status?e.status.enabled?"Yes":"No":"n/a"}
Jobs
${e.status?.jobs??"n/a"}
Next wake
${xs(e.status?.nextWakeAtMs??null)}
${e.error?l`
${e.error}
`:p}
Agent Cron Jobs
Scheduled jobs targeting this agent.
${n.length===0?l`
No jobs assigned.
`:l`
${n.map(i=>l`
${i.name}
${i.description?l`
${i.description}
`:p}
${Pl(i)} ${i.enabled?"enabled":"disabled"} ${i.sessionTarget}
${Ml(i)}
${Fl(i)}
`)}
`}
`}function Df(e){const t=e.agentFilesList?.agentId===e.agentId?e.agentFilesList:null,n=t?.files??[],i=e.agentFileActive??null,s=i?n.find(c=>c.name===i)??null:null,a=i?e.agentFileContents[i]??"":"",o=i?e.agentFileDrafts[i]??a:"",r=i?o!==a:!1;return l`
Core Files
Bootstrap persona, identity, and tool guidance.
${t?l`
Workspace: ${t.workspace}
`:p} ${e.agentFilesError?l`
${e.agentFilesError}
`:p} ${t?l`
${n.length===0?l`
No files found.
`:n.map(c=>Of(c,i,()=>e.onSelectFile(c.name)))}
${s?l`
${s.name}
${s.path}
${s.missing?l`
This file is missing. Saving will create it in the agent workspace.
`:p} `:l`
Select a file to edit.
`}
`:l`
Load the agent workspace files to edit core instructions.
`}
`}function Of(e,t,n){const i=e.missing?"Missing":`${mf(e.size)} · ${O(e.updatedAtMs??null)}`;return l` `}function Bf(e){const t=Dn(e.configForm,e.agentId),n=t.entry?.tools??{},i=t.globalTools??{},s=n.profile??i.profile??"full",a=n.profile?"agent override":i.profile?"global default":"default",o=Array.isArray(n.allow)&&n.allow.length>0,r=Array.isArray(i.allow)&&i.allow.length>0,c=!!e.configForm&&!e.configLoading&&!e.configSaving&&!o,u=o?[]:Array.isArray(n.alsoAllow)?n.alsoAllow:[],f=o?[]:Array.isArray(n.deny)?n.deny:[],g=o?{allow:n.allow??[],deny:n.deny??[]}:uf(s)??void 0,m=Ua.flatMap(A=>A.tools.map(S=>S.id)),v=A=>{const S=Af(A,g),T=Ha(A,u),x=Ha(A,f);return{allowed:(S||T)&&!x,baseAllowed:S,denied:x}},b=m.filter(A=>v(A).allowed).length,d=(A,S)=>{const T=new Set(u.map(P=>we(P)).filter(P=>P.length>0)),x=new Set(f.map(P=>we(P)).filter(P=>P.length>0)),C=v(A).baseAllowed,E=we(A);S?(x.delete(E),C||T.add(E)):(T.delete(E),x.add(E)),e.onOverridesChange(e.agentId,[...T],[...x])},y=A=>{const S=new Set(u.map(x=>we(x)).filter(x=>x.length>0)),T=new Set(f.map(x=>we(x)).filter(x=>x.length>0));for(const x of m){const C=v(x).baseAllowed,E=we(x);A?(T.delete(E),C||S.add(E)):(S.delete(E),T.add(E))}e.onOverridesChange(e.agentId,[...S],[...T])};return l`
Tool Access
Profile + per-tool overrides for this agent. ${b}/${m.length} enabled.
${e.configForm?p:l`
Load the gateway config to adjust tool profiles.
`} ${o?l`
This agent is using an explicit allowlist in config. Tool overrides are managed in the Config tab.
`:p} ${r?l`
Global tools.allow is set. Agent overrides cannot enable tools that are globally blocked.
`:p}
Profile
${s}
Source
${a}
${e.configDirty?l`
Status
unsaved
`:p}
Quick Presets
${vf.map(A=>l` `)}
${Ua.map(A=>l`
${A.label}
${A.tools.map(S=>{const{allowed:T}=v(S.id);return l`
${S.label}
${S.description}
`})}
`)}
`}const sn=[{id:"workspace",label:"Workspace Skills",sources:["openclaw-workspace"]},{id:"built-in",label:"Built-in Skills",sources:["openclaw-bundled"]},{id:"installed",label:"Installed Skills",sources:["openclaw-managed"]},{id:"extra",label:"Extra Skills",sources:["openclaw-extra"]}];function Uf(e){const t=new Map;for(const a of sn)t.set(a.id,{id:a.id,label:a.label,skills:[]});const n=sn.find(a=>a.id==="built-in"),i={id:"other",label:"Other Skills",skills:[]};for(const a of e){const o=a.bundled?n:sn.find(r=>r.sources.includes(a.source));o?t.get(o.id)?.skills.push(a):i.skills.push(a)}const s=sn.map(a=>t.get(a.id)).filter(a=>!!(a&&a.skills.length>0));return i.skills.length>0&&s.push(i),s}function Kf(e){const t=!!e.configForm&&!e.configLoading&&!e.configSaving,n=Dn(e.configForm,e.agentId),i=Array.isArray(n.entry?.skills)?n.entry?.skills:void 0,s=new Set((i??[]).map(v=>v.trim()).filter(Boolean)),a=i!==void 0,o=!!(e.report&&e.activeAgentId===e.agentId),r=o?e.report?.skills??[]:[],c=e.filter.trim().toLowerCase(),u=c?r.filter(v=>[v.name,v.description,v.source].join(" ").toLowerCase().includes(c)):r,f=Uf(u),g=a?r.filter(v=>s.has(v.name)).length:r.length,m=r.length;return l`
Skills
Per-agent skill allowlist and workspace skills. ${m>0?l`${g}/${m}`:p}
${e.configForm?p:l`
Load the gateway config to set per-agent skills.
`} ${a?l`
This agent uses a custom skill allowlist.
`:l`
All skills are enabled. Disabling any skill will create a per-agent allowlist.
`} ${!o&&!e.loading?l`
Load skills for this agent to view workspace-specific entries.
`:p} ${e.error?l`
${e.error}
`:p}
${u.length} shown
${u.length===0?l`
No skills found.
`:l`
${f.map(v=>zf(v,{agentId:e.agentId,allowSet:s,usingAllowlist:a,editable:t,onToggle:e.onToggle}))}
`}
`}function zf(e,t){const n=e.id==="workspace"||e.id==="built-in";return l`
${e.label} ${e.skills.length}
${e.skills.map(i=>Hf(i,{agentId:t.agentId,allowSet:t.allowSet,usingAllowlist:t.usingAllowlist,editable:t.editable,onToggle:t.onToggle}))}
`}function Hf(e,t){const n=t.usingAllowlist?t.allowSet.has(e.name):!0,i=[...e.missing.bins.map(a=>`bin:${a}`),...e.missing.env.map(a=>`env:${a}`),...e.missing.config.map(a=>`config:${a}`),...e.missing.os.map(a=>`os:${a}`)],s=[];return e.disabled&&s.push("disabled"),e.blockedByAllowlist&&s.push("blocked by allowlist"),l`
${e.emoji?`${e.emoji} `:""}${e.name}
${e.description}
${e.source} ${e.eligible?"eligible":"blocked"} ${e.disabled?l` disabled `:p}
${i.length>0?l`
Missing: ${i.join(", ")}
`:p} ${s.length>0?l`
Reason: ${s.join(", ")}
`:p}
`}function $e(e){if(e)return Array.isArray(e.type)?e.type.filter(n=>n!=="null")[0]??e.type[0]:e.type}function Bl(e){if(!e)return"";if(e.default!==void 0)return e.default;switch($e(e)){case"object":return{};case"array":return[];case"boolean":return!1;case"number":case"integer":return 0;case"string":return"";default:return""}}function On(e){return e.filter(t=>typeof t=="string").join(".")}function le(e,t){const n=On(e),i=t[n];if(i)return i;const s=n.split(".");for(const[a,o]of Object.entries(t)){if(!a.includes("*"))continue;const r=a.split(".");if(r.length!==s.length)continue;let c=!0;for(let u=0;ut.toUpperCase())}function jf(e){const t=On(e).toLowerCase();return t.includes("token")||t.includes("password")||t.includes("secret")||t.includes("apikey")||t.endsWith("key")}const Gf=new Set(["title","description","default","nullable"]);function Wf(e){return Object.keys(e??{}).filter(n=>!Gf.has(n)).length===0}function qf(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const Bt={chevronDown:l` `,plus:l` `,minus:l` `,trash:l` `,edit:l` `};function Ce(e){const{schema:t,value:n,path:i,hints:s,unsupported:a,disabled:o,onPatch:r}=e,c=e.showLabel??!0,u=$e(t),f=le(i,s),g=f?.label??t.title??Ee(String(i.at(-1))),m=f?.help??t.description,v=On(i);if(a.has(v))return l`
${g}
Unsupported schema node. Use Raw mode.
`;if(t.anyOf||t.oneOf){const d=(t.anyOf??t.oneOf??[]).filter(C=>!(C.type==="null"||Array.isArray(C.type)&&C.type.includes("null")));if(d.length===1)return Ce({...e,schema:d[0]});const y=C=>{if(C.const!==void 0)return C.const;if(C.enum&&C.enum.length===1)return C.enum[0]},A=d.map(y),S=A.every(C=>C!==void 0);if(S&&A.length>0&&A.length<=5){const C=n??t.default;return l`
${c?l``:p} ${m?l`
${m}
`:p}
${A.map(E=>l` `)}
`}if(S&&A.length>5)return Ga({...e,options:A,value:n??t.default});const T=new Set(d.map(C=>$e(C)).filter(Boolean)),x=new Set([...T].map(C=>C==="integer"?"number":C));if([...x].every(C=>["string","number","boolean"].includes(C))){const C=x.has("string"),E=x.has("number");if(x.has("boolean")&&x.size===1)return Ce({...e,schema:{...t,type:"boolean",anyOf:void 0,oneOf:void 0}});if(C||E)return ja({...e,inputType:E&&!C?"number":"text"})}}if(t.enum){const b=t.enum;if(b.length<=5){const d=n??t.default;return l`
${c?l``:p} ${m?l`
${m}
`:p}
${b.map(y=>l` `)}
`}return Ga({...e,options:b,value:n??t.default})}if(u==="object")return Yf(e);if(u==="array")return Qf(e);if(u==="boolean"){const b=typeof n=="boolean"?n:typeof t.default=="boolean"?t.default:!1;return l` `}return u==="number"||u==="integer"?Vf(e):u==="string"?ja({...e,inputType:"text"}):l`
${g}
Unsupported type: ${u}. Use Raw mode.
`}function ja(e){const{schema:t,value:n,path:i,hints:s,disabled:a,onPatch:o,inputType:r}=e,c=e.showLabel??!0,u=le(i,s),f=u?.label??t.title??Ee(String(i.at(-1))),g=u?.help??t.description,m=u?.sensitive??jf(i),v=u?.placeholder??(m?"••••":t.default!==void 0?`Default: ${String(t.default)}`:""),b=n??"";return l`
${c?l``:p} ${g?l`
${g}
`:p}
{const y=d.target.value;if(r==="number"){if(y.trim()===""){o(i,void 0);return}const A=Number(y);o(i,Number.isNaN(A)?y:A);return}o(i,y)}} @change=${d=>{if(r==="number")return;const y=d.target.value;o(i,y.trim())}} /> ${t.default!==void 0?l` `:p}
`}function Vf(e){const{schema:t,value:n,path:i,hints:s,disabled:a,onPatch:o}=e,r=e.showLabel??!0,c=le(i,s),u=c?.label??t.title??Ee(String(i.at(-1))),f=c?.help??t.description,g=n??t.default??"",m=typeof g=="number"?g:0;return l`
${r?l``:p} ${f?l`
${f}
`:p}
{const b=v.target.value,d=b===""?void 0:Number(b);o(i,d)}} />
`}function Ga(e){const{schema:t,value:n,path:i,hints:s,disabled:a,options:o,onPatch:r}=e,c=e.showLabel??!0,u=le(i,s),f=u?.label??t.title??Ee(String(i.at(-1))),g=u?.help??t.description,m=n??t.default,v=o.findIndex(d=>d===m||String(d)===String(m)),b="__unset__";return l`
${c?l``:p} ${g?l`
${g}
`:p}
`}function Yf(e){const{schema:t,value:n,path:i,hints:s,unsupported:a,disabled:o,onPatch:r}=e,c=le(i,s),u=c?.label??t.title??Ee(String(i.at(-1))),f=c?.help??t.description,g=n??t.default,m=g&&typeof g=="object"&&!Array.isArray(g)?g:{},v=t.properties??{},d=Object.entries(v).toSorted((T,x)=>{const C=le([...i,T[0]],s)?.order??0,E=le([...i,x[0]],s)?.order??0;return C!==E?C-E:T[0].localeCompare(x[0])}),y=new Set(Object.keys(v)),A=t.additionalProperties,S=!!A&&typeof A=="object";return i.length===1?l`
${d.map(([T,x])=>Ce({schema:x,value:m[T],path:[...i,T],hints:s,unsupported:a,disabled:o,onPatch:r}))} ${S?Wa({schema:A,value:m,path:i,hints:s,unsupported:a,disabled:o,reservedKeys:y,onPatch:r}):p}
`:l`
${u} ${Bt.chevronDown} ${f?l`
${f}
`:p}
${d.map(([T,x])=>Ce({schema:x,value:m[T],path:[...i,T],hints:s,unsupported:a,disabled:o,onPatch:r}))} ${S?Wa({schema:A,value:m,path:i,hints:s,unsupported:a,disabled:o,reservedKeys:y,onPatch:r}):p}
`}function Qf(e){const{schema:t,value:n,path:i,hints:s,unsupported:a,disabled:o,onPatch:r}=e,c=e.showLabel??!0,u=le(i,s),f=u?.label??t.title??Ee(String(i.at(-1))),g=u?.help??t.description,m=Array.isArray(t.items)?t.items[0]:t.items;if(!m)return l`
${f}
Unsupported array schema. Use Raw mode.
`;const v=Array.isArray(n)?n:Array.isArray(t.default)?t.default:[];return l`
${c?l`${f}`:p} ${v.length} item${v.length!==1?"s":""}
${g?l`
${g}
`:p} ${v.length===0?l`
No items yet. Click "Add" to create one.
`:l`
${v.map((b,d)=>l`
#${d+1}
${Ce({schema:m,value:b,path:[...i,d],hints:s,unsupported:a,disabled:o,showLabel:!1,onPatch:r})}
`)}
`}
`}function Wa(e){const{schema:t,value:n,path:i,hints:s,unsupported:a,disabled:o,reservedKeys:r,onPatch:c}=e,u=Wf(t),f=Object.entries(n??{}).filter(([g])=>!r.has(g));return l`
Custom entries
${f.length===0?l`
No custom entries.
`:l`
${f.map(([g,m])=>{const v=[...i,g],b=qf(m);return l`
{const y=d.target.value.trim();if(!y||y===g)return;const A={...n};y in A||(A[y]=A[g],delete A[g],c(i,A))}} />
${u?l` `:Ce({schema:t,value:m,path:v,hints:s,unsupported:a,disabled:o,showLabel:!1,onPatch:c})}
`})}
`}
`}const qa={env:l` `,update:l` `,agents:l` `,auth:l` `,channels:l` `,messages:l` `,commands:l` `,hooks:l` `,skills:l` `,tools:l` `,gateway:l` `,wizard:l` `,meta:l` `,logging:l` `,browser:l` `,ui:l` `,models:l` `,bindings:l` `,broadcast:l` `,audio:l` `,session:l` `,cron:l` `,web:l` `,discovery:l` `,canvasHost:l` `,talk:l` `,plugins:l` `,default:l` `},Ss={env:{label:"Environment Variables",description:"Environment variables passed to the gateway process"},update:{label:"Updates",description:"Auto-update settings and release channel"},agents:{label:"Agents",description:"Agent configurations, models, and identities"},auth:{label:"Authentication",description:"API keys and authentication profiles"},channels:{label:"Channels",description:"Messaging channels (Telegram, Discord, Slack, etc.)"},messages:{label:"Messages",description:"Message handling and routing settings"},commands:{label:"Commands",description:"Custom slash commands"},hooks:{label:"Hooks",description:"Webhooks and event hooks"},skills:{label:"Skills",description:"Skill packs and capabilities"},tools:{label:"Tools",description:"Tool configurations (browser, search, etc.)"},gateway:{label:"Gateway",description:"Gateway server settings (port, auth, binding)"},wizard:{label:"Setup Wizard",description:"Setup wizard state and history"},meta:{label:"Metadata",description:"Gateway metadata and version information"},logging:{label:"Logging",description:"Log levels and output configuration"},browser:{label:"Browser",description:"Browser automation settings"},ui:{label:"UI",description:"User interface preferences"},models:{label:"Models",description:"AI model configurations and providers"},bindings:{label:"Bindings",description:"Key bindings and shortcuts"},broadcast:{label:"Broadcast",description:"Broadcast and notification settings"},audio:{label:"Audio",description:"Audio input/output settings"},session:{label:"Session",description:"Session management and persistence"},cron:{label:"Cron",description:"Scheduled tasks and automation"},web:{label:"Web",description:"Web server and API settings"},discovery:{label:"Discovery",description:"Service discovery and networking"},canvasHost:{label:"Canvas Host",description:"Canvas rendering and display"},talk:{label:"Talk",description:"Voice and speech settings"},plugins:{label:"Plugins",description:"Plugin management and extensions"}};function Va(e){return qa[e]??qa.default}function Jf(e,t,n){if(!n)return!0;const i=n.toLowerCase(),s=Ss[e];return e.toLowerCase().includes(i)||s&&(s.label.toLowerCase().includes(i)||s.description.toLowerCase().includes(i))?!0:St(t,i)}function St(e,t){if(e.title?.toLowerCase().includes(t)||e.description?.toLowerCase().includes(t)||e.enum?.some(i=>String(i).toLowerCase().includes(t)))return!0;if(e.properties){for(const[i,s]of Object.entries(e.properties))if(i.toLowerCase().includes(t)||St(s,t))return!0}if(e.items){const i=Array.isArray(e.items)?e.items:[e.items];for(const s of i)if(s&&St(s,t))return!0}if(e.additionalProperties&&typeof e.additionalProperties=="object"&&St(e.additionalProperties,t))return!0;const n=e.anyOf??e.oneOf??e.allOf;if(n){for(const i of n)if(i&&St(i,t))return!0}return!1}function Zf(e){if(!e.schema)return l`
Schema unavailable.
`;const t=e.schema,n=e.value??{};if($e(t)!=="object"||!t.properties)return l`
Unsupported schema. Use Raw.
`;const i=new Set(e.unsupportedPaths??[]),s=t.properties,a=e.searchQuery??"",o=e.activeSection,r=e.activeSubsection??null,u=Object.entries(s).toSorted((g,m)=>{const v=le([g[0]],e.uiHints)?.order??50,b=le([m[0]],e.uiHints)?.order??50;return v!==b?v-b:g[0].localeCompare(m[0])}).filter(([g,m])=>!(o&&g!==o||a&&!Jf(g,m,a)));let f=null;if(o&&r&&u.length===1){const g=u[0]?.[1];g&&$e(g)==="object"&&g.properties&&g.properties[r]&&(f={sectionKey:o,subsectionKey:r,schema:g.properties[r]})}return u.length===0?l`
${Y.search}
${a?`No settings match "${a}"`:"No settings in this section"}
`:l`
${f?(()=>{const{sectionKey:g,subsectionKey:m,schema:v}=f,b=le([g,m],e.uiHints),d=b?.label??v.title??Ee(m),y=b?.help??v.description??"",A=n[g],S=A&&typeof A=="object"?A[m]:void 0,T=`config-section-${g}-${m}`;return l`
${Va(g)}

${d}

${y?l`

${y}

`:p}
${Ce({schema:v,value:S,path:[g,m],hints:e.uiHints,unsupported:i,disabled:e.disabled??!1,showLabel:!1,onPatch:e.onPatch})}
`})():u.map(([g,m])=>{const v=Ss[g]??{label:g.charAt(0).toUpperCase()+g.slice(1),description:m.description??""};return l`
${Va(g)}

${v.label}

${v.description?l`

${v.description}

`:p}
${Ce({schema:m,value:n[g],path:[g],hints:e.uiHints,unsupported:i,disabled:e.disabled??!1,showLabel:!1,onPatch:e.onPatch})}
`})}
`}const Xf=new Set(["title","description","default","nullable"]);function eg(e){return Object.keys(e??{}).filter(n=>!Xf.has(n)).length===0}function Ul(e){const t=e.filter(s=>s!=null),n=t.length!==e.length,i=[];for(const s of t)i.some(a=>Object.is(a,s))||i.push(s);return{enumValues:i,nullable:n}}function Kl(e){return!e||typeof e!="object"?{schema:null,unsupportedPaths:[""]}:Lt(e,[])}function Lt(e,t){const n=new Set,i={...e},s=On(t)||"";if(e.anyOf||e.oneOf||e.allOf){const r=tg(e,t);return r||{schema:e,unsupportedPaths:[s]}}const a=Array.isArray(e.type)&&e.type.includes("null"),o=$e(e)??(e.properties||e.additionalProperties?"object":void 0);if(i.type=o??e.type,i.nullable=a||e.nullable,i.enum){const{enumValues:r,nullable:c}=Ul(i.enum);i.enum=r,c&&(i.nullable=!0),r.length===0&&n.add(s)}if(o==="object"){const r=e.properties??{},c={};for(const[u,f]of Object.entries(r)){const g=Lt(f,[...t,u]);g.schema&&(c[u]=g.schema);for(const m of g.unsupportedPaths)n.add(m)}if(i.properties=c,e.additionalProperties===!0)n.add(s);else if(e.additionalProperties===!1)i.additionalProperties=!1;else if(e.additionalProperties&&typeof e.additionalProperties=="object"&&!eg(e.additionalProperties)){const u=Lt(e.additionalProperties,[...t,"*"]);i.additionalProperties=u.schema??e.additionalProperties,u.unsupportedPaths.length>0&&n.add(s)}}else if(o==="array"){const r=Array.isArray(e.items)?e.items[0]:e.items;if(!r)n.add(s);else{const c=Lt(r,[...t,"*"]);i.items=c.schema??r,c.unsupportedPaths.length>0&&n.add(s)}}else o!=="string"&&o!=="number"&&o!=="integer"&&o!=="boolean"&&!i.enum&&n.add(s);return{schema:i,unsupportedPaths:Array.from(n)}}function tg(e,t){if(e.allOf)return null;const n=e.anyOf??e.oneOf;if(!n)return null;const i=[],s=[];let a=!1;for(const r of n){if(!r||typeof r!="object")return null;if(Array.isArray(r.enum)){const{enumValues:c,nullable:u}=Ul(r.enum);i.push(...c),u&&(a=!0);continue}if("const"in r){if(r.const==null){a=!0;continue}i.push(r.const);continue}if($e(r)==="null"){a=!0;continue}s.push(r)}if(i.length>0&&s.length===0){const r=[];for(const c of i)r.some(u=>Object.is(u,c))||r.push(c);return{schema:{...e,enum:r,nullable:a,anyOf:void 0,oneOf:void 0,allOf:void 0},unsupportedPaths:[]}}if(s.length===1){const r=Lt(s[0],t);return r.schema&&(r.schema.nullable=a||r.schema.nullable),r}const o=new Set(["string","number","integer","boolean"]);return s.length>0&&i.length===0&&s.every(r=>r.type&&o.has(String(r.type)))?{schema:{...e,nullable:a},unsupportedPaths:[]}:null}function ng(e,t){let n=e;for(const i of t){if(!n)return null;const s=$e(n);if(s==="object"){const a=n.properties??{};if(typeof i=="string"&&a[i]){n=a[i];continue}const o=n.additionalProperties;if(typeof i=="string"&&o&&typeof o=="object"){n=o;continue}return null}if(s==="array"){if(typeof i!="number")return null;n=(Array.isArray(n.items)?n.items[0]:n.items)??null;continue}return null}return n}function ig(e,t){const i=(e.channels??{})[t],s=e[t];return(i&&typeof i=="object"?i:null)??(s&&typeof s=="object"?s:null)??{}}const sg=["groupPolicy","streamMode","dmPolicy"];function ag(e){if(e==null)return"n/a";if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return"n/a"}}function og(e){const t=sg.flatMap(n=>n in e?[[n,e[n]]]:[]);return t.length===0?null:l`
${t.map(([n,i])=>l`
${n} ${ag(i)}
`)}
`}function lg(e){const t=Kl(e.schema),n=t.schema;if(!n)return l`
Schema unavailable. Use Raw.
`;const i=ng(n,["channels",e.channelId]);if(!i)return l`
Channel config schema unavailable.
`;const s=e.configValue??{},a=ig(s,e.channelId);return l`
${Ce({schema:i,value:a,path:["channels",e.channelId],hints:e.uiHints,unsupported:new Set(t.unsupportedPaths),disabled:e.disabled,showLabel:!1,onPatch:e.onPatch})}
${og(a)} `}function Te(e){const{channelId:t,props:n}=e,i=n.configSaving||n.configSchemaLoading;return l`
${n.configSchemaLoading?l`
Loading config schema…
`:lg({channelId:t,configValue:n.configForm,schema:n.configSchema,uiHints:n.configUiHints,disabled:i,onPatch:n.onConfigPatch})}
`}function rg(e){const{props:t,discord:n,accountCountLabel:i}=e;return l`
Discord
Bot status and channel configuration.
${i}
Configured ${n?.configured?"Yes":"No"}
Running ${n?.running?"Yes":"No"}
Last start ${n?.lastStartAt?O(n.lastStartAt):"n/a"}
Last probe ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"}
${n?.lastError?l`
${n.lastError}
`:p} ${n?.probe?l`
Probe ${n.probe.ok?"ok":"failed"} · ${n.probe.status??""} ${n.probe.error??""}
`:p} ${Te({channelId:"discord",props:t})}
`}function cg(e){const{props:t,googleChat:n,accountCountLabel:i}=e;return l`
Google Chat
Chat API webhook status and channel configuration.
${i}
Configured ${n?n.configured?"Yes":"No":"n/a"}
Running ${n?n.running?"Yes":"No":"n/a"}
Credential ${n?.credentialSource??"n/a"}
Audience ${n?.audienceType?`${n.audienceType}${n.audience?` · ${n.audience}`:""}`:"n/a"}
Last start ${n?.lastStartAt?O(n.lastStartAt):"n/a"}
Last probe ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"}
${n?.lastError?l`
${n.lastError}
`:p} ${n?.probe?l`
Probe ${n.probe.ok?"ok":"failed"} · ${n.probe.status??""} ${n.probe.error??""}
`:p} ${Te({channelId:"googlechat",props:t})}
`}function dg(e){const{props:t,imessage:n,accountCountLabel:i}=e;return l`
iMessage
macOS bridge status and channel configuration.
${i}
Configured ${n?.configured?"Yes":"No"}
Running ${n?.running?"Yes":"No"}
Last start ${n?.lastStartAt?O(n.lastStartAt):"n/a"}
Last probe ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"}
${n?.lastError?l`
${n.lastError}
`:p} ${n?.probe?l`
Probe ${n.probe.ok?"ok":"failed"} · ${n.probe.error??""}
`:p} ${Te({channelId:"imessage",props:t})}
`}function Ya(e){return e?e.length<=20?e:`${e.slice(0,8)}...${e.slice(-8)}`:"n/a"}function ug(e){const{props:t,nostr:n,nostrAccounts:i,accountCountLabel:s,profileFormState:a,profileFormCallbacks:o,onEditProfile:r}=e,c=i[0],u=n?.configured??c?.configured??!1,f=n?.running??c?.running??!1,g=n?.publicKey??c?.publicKey,m=n?.lastStartAt??c?.lastStartAt??null,v=n?.lastError??c?.lastError??null,b=i.length>1,d=a!=null,y=S=>{const T=S.publicKey,x=S.profile,C=x?.displayName??x?.name??S.name??S.accountId;return l` `},A=()=>{if(d&&o)return nc({state:a,callbacks:o,accountId:i[0]?.accountId??"default"});const S=c?.profile??n?.profile,{name:T,displayName:x,about:C,picture:E,nip05:P}=S??{},ce=T||x||C||E||P;return l`
Profile
${u?l` `:p}
${ce?l`
${E?l`
Profile picture{H.target.style.display="none"}} />
`:p} ${T?l`
Name${T}
`:p} ${x?l`
Display Name${x}
`:p} ${C?l`
About${C}
`:p} ${P?l`
NIP-05${P}
`:p}
`:l`
No profile set. Click "Edit Profile" to add your name, bio, and avatar.
`}
`};return l`
Nostr
Decentralized DMs via Nostr relays (NIP-04).
${s} ${b?l` `:l`
Configured ${u?"Yes":"No"}
Running ${f?"Yes":"No"}
Public Key ${Ya(g)}
Last start ${m?O(m):"n/a"}
`} ${v?l`
${v}
`:p} ${A()} ${Te({channelId:"nostr",props:t})}
`}function fg(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 gg(e,t){const n=t.snapshot,i=n?.channels;if(!n||!i)return!1;const s=i[e],a=typeof s?.configured=="boolean"&&s.configured,o=typeof s?.running=="boolean"&&s.running,r=typeof s?.connected=="boolean"&&s.connected,u=(n.channelAccounts?.[e]??[]).some(f=>f.configured||f.running||f.connected);return a||o||r||u}function pg(e,t){return t?.[e]?.length??0}function zl(e,t){const n=pg(e,t);return n<2?p:l``}function hg(e){const{props:t,signal:n,accountCountLabel:i}=e;return l`
Signal
signal-cli status and channel configuration.
${i}
Configured ${n?.configured?"Yes":"No"}
Running ${n?.running?"Yes":"No"}
Base URL ${n?.baseUrl??"n/a"}
Last start ${n?.lastStartAt?O(n.lastStartAt):"n/a"}
Last probe ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"}
${n?.lastError?l`
${n.lastError}
`:p} ${n?.probe?l`
Probe ${n.probe.ok?"ok":"failed"} · ${n.probe.status??""} ${n.probe.error??""}
`:p} ${Te({channelId:"signal",props:t})}
`}function vg(e){const{props:t,slack:n,accountCountLabel:i}=e;return l`
Slack
Socket mode status and channel configuration.
${i}
Configured ${n?.configured?"Yes":"No"}
Running ${n?.running?"Yes":"No"}
Last start ${n?.lastStartAt?O(n.lastStartAt):"n/a"}
Last probe ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"}
${n?.lastError?l`
${n.lastError}
`:p} ${n?.probe?l`
Probe ${n.probe.ok?"ok":"failed"} · ${n.probe.status??""} ${n.probe.error??""}
`:p} ${Te({channelId:"slack",props:t})}
`}function mg(e){const{props:t,telegram:n,telegramAccounts:i,accountCountLabel:s}=e,a=i.length>1,o=r=>{const u=r.probe?.bot?.username,f=r.name||r.accountId;return l` `};return l`
Telegram
Bot status and channel configuration.
${s} ${a?l` `:l`
Configured ${n?.configured?"Yes":"No"}
Running ${n?.running?"Yes":"No"}
Mode ${n?.mode??"n/a"}
Last start ${n?.lastStartAt?O(n.lastStartAt):"n/a"}
Last probe ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"}
`} ${n?.lastError?l`
${n.lastError}
`:p} ${n?.probe?l`
Probe ${n.probe.ok?"ok":"failed"} · ${n.probe.status??""} ${n.probe.error??""}
`:p} ${Te({channelId:"telegram",props:t})}
`}function yg(e){const{props:t,whatsapp:n,accountCountLabel:i}=e;return l`
WhatsApp
Link WhatsApp Web and monitor connection health.
${i}
Configured ${n?.configured?"Yes":"No"}
Linked ${n?.linked?"Yes":"No"}
Running ${n?.running?"Yes":"No"}
Connected ${n?.connected?"Yes":"No"}
Last connect ${n?.lastConnectedAt?O(n.lastConnectedAt):"n/a"}
Last message ${n?.lastMessageAt?O(n.lastMessageAt):"n/a"}
Auth age ${n?.authAgeMs!=null?fg(n.authAgeMs):"n/a"}
${n?.lastError?l`
${n.lastError}
`:p} ${t.whatsappMessage?l`
${t.whatsappMessage}
`:p} ${t.whatsappQrDataUrl?l`
WhatsApp QR
`:p}
${Te({channelId:"whatsapp",props:t})}
`}function bg(e){const t=e.snapshot?.channels,n=t?.whatsapp??void 0,i=t?.telegram??void 0,s=t?.discord??null,a=t?.googlechat??null,o=t?.slack??null,r=t?.signal??null,c=t?.imessage??null,u=t?.nostr??null,g=wg(e.snapshot).map((m,v)=>({key:m,enabled:gg(m,e),order:v})).toSorted((m,v)=>m.enabled!==v.enabled?m.enabled?-1:1:m.order-v.order);return l`
${g.map(m=>$g(m.key,e,{whatsapp:n,telegram:i,discord:s,googlechat:a,slack:o,signal:r,imessage:c,nostr:u,channelAccounts:e.snapshot?.channelAccounts??null}))}
Channel health
Channel status snapshots from the gateway.
${e.lastSuccessAt?O(e.lastSuccessAt):"n/a"}
${e.lastError?l`
${e.lastError}
`:p}
${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
      
`}function wg(e){return e?.channelMeta?.length?e.channelMeta.map(t=>t.id):e?.channelOrder?.length?e.channelOrder:["whatsapp","telegram","discord","googlechat","slack","signal","imessage","nostr"]}function $g(e,t,n){const i=zl(e,n.channelAccounts);switch(e){case"whatsapp":return yg({props:t,whatsapp:n.whatsapp,accountCountLabel:i});case"telegram":return mg({props:t,telegram:n.telegram,telegramAccounts:n.channelAccounts?.telegram??[],accountCountLabel:i});case"discord":return rg({props:t,discord:n.discord,accountCountLabel:i});case"googlechat":return cg({props:t,googleChat:n.googlechat,accountCountLabel:i});case"slack":return vg({props:t,slack:n.slack,accountCountLabel:i});case"signal":return hg({props:t,signal:n.signal,accountCountLabel:i});case"imessage":return dg({props:t,imessage:n.imessage,accountCountLabel:i});case"nostr":{const s=n.channelAccounts?.nostr??[],a=s[0],o=a?.accountId??"default",r=a?.profile??null,c=t.nostrProfileAccountId===o?t.nostrProfileFormState:null,u=c?{onFieldChange:t.onNostrProfileFieldChange,onSave:t.onNostrProfileSave,onImport:t.onNostrProfileImport,onCancel:t.onNostrProfileCancel,onToggleAdvanced:t.onNostrProfileToggleAdvanced}:null;return ug({props:t,nostr:n.nostr,nostrAccounts:s,accountCountLabel:i,profileFormState:c,profileFormCallbacks:u,onEditProfile:()=>t.onNostrProfileEdit(o,r)})}default:return kg(e,t,n.channelAccounts??{})}}function kg(e,t,n){const i=xg(t.snapshot,e),s=t.snapshot?.channels?.[e],a=typeof s?.configured=="boolean"?s.configured:void 0,o=typeof s?.running=="boolean"?s.running:void 0,r=typeof s?.connected=="boolean"?s.connected:void 0,c=typeof s?.lastError=="string"?s.lastError:void 0,u=n[e]??[],f=zl(e,n);return l`
${i}
Channel status and configuration.
${f} ${u.length>0?l` `:l`
Configured ${a==null?"n/a":a?"Yes":"No"}
Running ${o==null?"n/a":o?"Yes":"No"}
Connected ${r==null?"n/a":r?"Yes":"No"}
`} ${c?l`
${c}
`:p} ${Te({channelId:e,props:t})}
`}function Ag(e){return e?.channelMeta?.length?Object.fromEntries(e.channelMeta.map(t=>[t.id,t])):{}}function xg(e,t){return Ag(e)[t]?.label??e?.channelLabels?.[t]??t}const Sg=600*1e3;function Hl(e){return e.lastInboundAt?Date.now()-e.lastInboundAt